Update Iot.js
[platform/upstream/iotjs.git] / test / run_pass / test_fs_open_close.js
1 /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16
17
18 var fs = require('fs');
19 var assert = require('assert');
20
21
22 var fileName = "../resources/greeting.txt";
23
24
25 // test sync open & close.
26
27 // test normal sequence.
28 try {
29   var fd = fs.openSync(fileName, 'r');
30   fs.closeSync(fd);
31 } catch (err) {
32   throw err;
33 }
34
35
36 // test trying to open not exist file - expecting exception.
37 try {
38   var fd = fs.openSync('not_exist_file', 'r');
39   assert.fail('none', 'exception');
40 } catch (err) {
41 }
42
43
44 // test trying to close with bad fd - expecting exception.
45 try {
46   fs.closeSync(-1);
47   assert.fail('none', 'exception');
48 } catch (err) {
49 }
50
51
52 // test async open & close.
53
54 // test normal sequence.
55 var fs_async_normal_ok = false;
56 fs.open(fileName, 'r', function(err, fd) {
57   if (err) {
58     throw err;
59   } else {
60     fs.close(fd, function(err) {
61       if (err) {
62         throw err;
63       } else {
64         fs_async_normal_ok = true;
65       }
66     });
67   }
68 });
69
70
71 // test not exist file - expecting exception.
72 var fs_async_open_not_exist_ok = false;
73 fs.open('not_exist_file', 'r', function(err, fd) {
74   if (err) {
75     fs_async_open_not_exist_ok = true;
76   } else {
77     assert.fail('none', 'exception');
78   }
79 });
80
81
82 // test trying to close with bad fd - expecting exception.
83 var fs_async_close_bad_fd_ok = false;
84 fs.close(-1, function(err) {
85   if (err) {
86     fs_async_close_bad_fd_ok = true;
87   } else {
88     assert.fail('none', 'exception');
89   }
90 });
91
92 var buffer = new Buffer(10);
93 // expect length out of bound
94 assert.throws(function () { fs.readSync(5, buffer, 0, 20); }, RangeError);
95 // expect offset out of bound
96 assert.throws(function () { fs.readSync(5, buffer, -1, 20); }, RangeError);
97
98 process.on('exit', function() {
99   assert.equal(fs_async_normal_ok, true);
100   assert.equal(fs_async_open_not_exist_ok, true);
101   assert.equal(fs_async_close_bad_fd_ok, true);
102 });