Update Iot.js
[platform/upstream/iotjs.git] / tools / test / run_pass / test_http_get.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 var assert = require('assert');
18 var http = require('http');
19
20
21 var server = http.createServer(function (req, res) {
22
23   var body = '';
24   var url = req.url;
25
26   req.on('data', function (chunk) {
27     body += chunk;
28   });
29
30   var endHandler = function () {
31
32     res.writeHead(200, { 'Connection' : 'close',
33                          'Content-Length' : body.length
34                        });
35     res.write(body);
36     res.end(function(){
37       if(body == 'close server') server.close();
38     });
39   };
40
41   req.on('end', endHandler);
42
43 });
44
45 server.listen(3005,5);
46
47
48 // 1. GET req
49 options = {
50   method : 'GET',
51   port : 3005
52 };
53
54 var getResponseHandler = function (res) {
55   var res_body = '';
56
57   assert.equal(200, res.statusCode);
58
59   var endHandler = function(){
60     // GET msg, no received body
61     assert.equal('', res_body);
62   };
63   res.on('end', endHandler);
64
65   res.on('data', function(chunk){
66     res_body += chunk.toString();
67   });
68 };
69
70 http.get(options, getResponseHandler);
71
72
73 // 2. close server req
74 var finalMsg = 'close server';
75 var finalOptions = {
76   method : 'POST',
77   port : 3005,
78   headers : {'Content-Length': finalMsg.length}
79 };
80
81 var finalResponseHandler = function (res) {
82   var res_body = '';
83
84   assert.equal(200, res.statusCode);
85
86   var endHandler = function(){
87     assert.equal(finalMsg, res_body);
88   };
89   res.on('end', endHandler);
90
91   res.on('data', function(chunk){
92     res_body += chunk.toString();
93   });
94 };
95
96 var finalReq = http.request(finalOptions, finalResponseHandler);
97 finalReq.write(finalMsg);
98 finalReq.end();