我在测试HTTPS服务器时遇到了一个问题。
我使用jasmine编写了一个测试用例,我面临的问题是,当我在测试用例中评论一段代码时,测试用例失败,如果我启用该代码,测试用例就会通过。
以下是我为网络服务器编写的代码:
网络-server.js
var https = require('https');
var fs = require('fs');
var jsonFile = require('jsonfile');
var util = require("util");
const events = require('events');
var fileName = 'resource.json';
const contentType = "application/xml";
const port = 443;
var Options = {
key: fs.readFileSync('./key1'),
cert: fs.readFileSync('./Cert1')
};
var webServerIface = function (){
var server = https.createServer(Options, (request, response) => {
console.log('request ', request.url,request.method);
jsonFile.readFile(fileName, (err, jsonData) => {
if (err) throw err;
this.emit(jsonData[request.url][request.method],response);
});
})
server.listen(port, "0.0.0.0");
// Error handling
server.on('error',(err) => {
throw err;
});
this.on('processClassRequest', (response) => {
var xmlHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
var infoRootNode = "<infoUriType>";
var infoMacIdNode = "<macid>";
var infoMacIdClosingNode = "</macid>";
var infoRootClosingNode = "</infoUriType>";
var macAddress = "DEADBEEFFEED";
console.log("Got a processClassRequest request: ");
var xmlReturn = xmlHeader + infoRootNode + infoMacIdNode + macAddress
+ infoMacIdClosingNode +infoRootClosingNode;
response.writeHead(200, { 'Content-Type': contentType });
response.write(xmlReturn);
response.write("OK");
response.end();
});
webServerIface.prototype.shutDown = function () {
server.close(() => {
console.log('All connections are ended:server is finally closed');
});
}
}
util.inherits(webServerIface, events.EventEmitter);
module.exports = webServerIface;
resource.json
{
"/class/double/triple" : {
"GET" : "processClassRequest"
}
}
测试上述HTTPS服务器的代码:
WebServer_spec.js
const WebServer = require('../web-server.js');
var https = require('https');
var class_info = {
hostname: '172.18.1.45',
rejectUnauthorized: false,
port: 443,
path: '/class/double/triple',
method: 'GET'
};
describe("Web Server Test Suite", function() {
var WebServerHandle;
it("should start the secure web server", function() {
console.log("Starting Web Server");
this.webserverhandle = new WebServer();
WebServerHandle = this.webserverhandle;
});
it("should send http request to secure web-server", function(done) {
var req = https.request(class_info, function(res) {
res.setEncoding('utf8');
//If I uncomment below lines then test succeeds
/*res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});*/
res.on('end', chunk => {
expect(res.statusCode).toBe(200);
done();
});
});
req.end();
});
it("should stop the secure web server", function() {
WebServerHandle.shutDown();
});
});
输出:
> testscripts@1.0.0 test TestScripts
> jasmine
Randomized with seed 38516
Started
Starting Web Server
.request /class/double/triple GET
Got a processClassRequest request:
F.All connections are ended:server is finally closed
Failures:
1) Web Server Test Suite should send http request to secure web-server
Message:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
Stack:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
at <Jasmine>
at Timer.listOnTimeout (timers.js:92:15)
3 specs, 1 failure
Finished in 5.028 seconds
Randomized with seed 38516 (jasmine --random=true --seed=38516)
npm ERR! Test failed. See above for more details.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
Sometime I also get below Error:
> testscripts@1.0.0 test TestScripts
> jasmine
Randomized with seed 68125
Started
FFStarting Web Server
.
Failures:
1) Web Server Test Suite should send http request to secure web-server
Message:
Error: connect ECONNREFUSED 172.18.1.45:443
Stack:
error properties: Object({ code: 'ECONNREFUSED', errno: 'ECONNREFUSED', syscall: 'connect', address: '172.18.1.45', port: 443 })
Error: connect ECONNREFUSED 172.18.1.45:443
at Object.exports._errnoException (util.js:907:11)
at exports._exceptionWithHostPort (util.js:930:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1077:14)
Message:
Failed: connect ECONNREFUSED 172.18.1.45:443
Stack:
error properties: Object({ code: 'ECONNREFUSED', errno: 'ECONNREFUSED', syscall: 'connect', address: '172.18.1.45', port: 443 })
Error: connect ECONNREFUSED 172.18.1.45:443
at Object.exports._errnoException (util.js:907:11)
at exports._exceptionWithHostPort (util.js:930:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1077:14)
Message:
Error: socket hang up
Stack:
error properties: Object({ code: 'ECONNRESET' })
Error: socket hang up
at createHangUpError (_http_client.js:213:15)
at TLSSocket.socketCloseListener (_http_client.js:245:23)
at emitOne (events.js:82:20)
at TLSSocket.emit (events.js:169:7)
at TCP._onclose (net.js:486:12)
2) Web Server Test Suite should stop the secure web server
Message:
TypeError: Cannot read property 'shutDown' of undefined
Stack:
at <Jasmine>
at UserContext.<anonymous> (TestScripts/spec/WebServer_spec.js:38:24)
at <Jasmine>
at processImmediate [as _immediateCallback] (timers.js:383:17)
3 specs, 2 failures
Finished in 0.037 seconds
Randomized with seed 68125 (jasmine --random=true --seed=68125)
npm ERR! Test failed. See above for more details.
如果我取消注释res.on('data', function (chunk) { console.log('Response: ' + chunk); });
,测试成功。
我不知道如果我做错了什么。
答案 0 :(得分:0)
在搜索了一下并通过nodejs文档后,我发现HTTP / HTTPS服务器在从客户端获得新的连接请求时会创建可写和可读的流。
当有些数据需要写入steam时,服务器会发出data
事件,当且仅当流上消耗了所有数据时才会发出end
事件。
参考链接:Stream Event End