我是摩卡咖啡和Node的新手。
我正在尝试使用Mocha编写一些测试,这些测试检查SSL证书的各种属性。我有一个函数getCert
,它将打开一个tls套接字。
但是,我找不到一种方法来调用该函数并在getCert
的回调上执行多个mocha测试。
是否可以这样做?这是我的代码...
var assert = require('chai').assert;
var tls = require('tls');
const moment = require('moment');
var hostToTest = 'www.google.com';
//this is based a little on https://www.npmjs.com/package/certificate-monitor
function getCert(host, port, callback) {
let socketOptions = {
host: host,
port: port,
rejectUnauthorized: false,
requestCert: true,
agent: false,
authorized: null,
cert: null,
error: null,
daysRemaining: null
};
const socket = tls.connect(socketOptions, function() {
socketOptions.authorized = socket.authorized;
socketOptions.cert = socket.getPeerCertificate(true);
var expireDate = new Date(socketOptions.cert.valid_to).toJSON();
socketOptions.daysRemaining = moment(expireDate, moment.ISO_8601).diff(moment(), 'days');
socket.end();
callback(socketOptions);
});
socket.on('error', function (err){
socketOptions.error = err;
callback(socketOptions);
});
}
//This works, but I have to call getCert multiple times
describe('TLS Certificate Checks 1', function() {
it('Certificate should be trusted', function(done) {
getCert(hostToTest, 443, function(certResponse){
assert.isTrue(certResponse.authorized);
done();
});
});
it('Certificate should not be close to expirey', function(done) {
getCert(hostToTest, 443, function(certResponse){
assert.isAbove(certResponse.daysRemaining, 30);
done();
});
});
});
//this does nothing... is it possible to call getcert just once?
describe('TLS Certificate Checks 2', function() {
getCert(hostToTest, 443, function(certResponse){
it('Certificate should be trusted', function(done) {
assert.isTrue(certResponse.authorized);
done();
});
it('Certificate should not be close to expirey', function(done) {
assert.isBelow(certResponse.daysRemaining, 30);
done();
});
});
});
这是上面代码的输出:
$mocha testssl.js
TLS Certificate Checks 1
✓ Certificate should be trusted (56ms)
✓ Certificate should not be close to expirey
2 passing (100ms)
答案 0 :(得分:1)
在摩卡咖啡中有一种叫做“挂钩”的东西。您可以在每次测试运行之前调用getCert方法。
describe('TLS Certificate Checks 2', function() {
var certResponse = null;
// THIS IS A HOOK
beforeEach(function(done) {
certResponse = null;
// runs before each test in this block
getCert(hostToTest, 443, function(result){
certResponse = result;
done();
});
});
// PUT TEST CASES HERE
it('Certificate should be trusted', function(done) {
assert.isTrue(certResponse.authorized);
done();
});
it('Certificate should not be close to expirey', function(done) {
assert.isBelow(certResponse.daysRemaining, 30);
done();
});
});
beforeEach将在每次测试之前运行。