【问题标题】:node.js async child processes testingnode.js 异步子进程测试
【发布时间】:2013-12-11 05:04:49
【问题描述】:

我在 node.js 中迈出了第一步,想测试我的代码,但我卡住了。我使用node-qunit 库作为测试工具。

这是我的代码:

var spawn = require('child_process').spawn;
var ok = require('assert').ok;

function _call_gpg(stdin_pass, passphrase, decrypt, callback) {
    ok(stdin_pass);
    ok(passphrase);

    var buffers = []; 
    var gpg = spawn('gpg', ['--passphrase', passphrase, decrypt ? '-d' : '-c', '--no-use-agent']);

    gpg.stdout.on('data', function(data) {
        buffers.push(data);
    }); 

    gpg.on('exit', function(return_code) {
        callback(return_code === 0 ? Buffer.concat(buffers) : undefined);
    }); 

    gpg.stdin.write(stdin_pass);
    gpg.stdin.end();
}

function encrypt(string, passphrase, callback) {
    ok(typeof callback === 'function');

    _call_gpg(string, passphrase, false, function(buf) {
        callback(buf && buf.toString('base64'));
    }); 
}

function decrypt(encoded_string, passphrase, callback) {
    ok(typeof callback === 'function');

    raw_encoded_string = new Buffer(encoded_string, 'base64');
    _call_gpg(raw_encoded_string, passphrase, true, function(buf) {
        callback(buf && buf.toString('utf8'));
    }); 
}

exports.encrypt = encrypt;
exports.decrypt = decrypt;

当我从交互式控制台调用此函数时,它们按预期工作。但是当我尝试使用下面的代码对它们进行异步测试时,第二个 strictEqual 有时可以工作,有时会失败。

asyncTest('encrypting and decrypting', function() {

    encrypt('foo', 'pass', function(encoded_string) {
        decrypt(encoded_string, 'pass', function(decoded_string) {
            strictEqual('foo', decoded_string, 'encryption and decryption work');
        });
    });

    decrypt('jA0EAwMCNiwPDFiMxvFgyRmB4axFyanuy2DZmB0ZIUfpXcASCKT8pwFm', 'pass', function(decoded_string) {
        strictEqual('foo', decoded_string, 'only decryption works');
    });

    setTimeout(function() { start(); }, 10000);
});

看起来问题出在异步上,因为当我单独测试这个函数时,它们都可以工作。

感谢您的帮助。

【问题讨论】:

    标签: unit-testing node.js qunit gnupg


    【解决方案1】:

    使用惰性求值代替setTimeout

    asyncTest('encrypting and decrypting', function() {
    
    encrypt('foo', 'pass', function(encoded_string) 
       {
       decrypt(encoded_string, 'pass', function(decoded_string) 
         {
         /* Call start() as part of the output */
         strictEqual('foo', decoded_string, 'encryption and decryption work' && start() );
         });
       });
    
    decrypt('jA0EAwMCNiwPDFiMxvFgyRmB4axFyanuy2DZmB0ZIUfpXcASCKT8pwFm', 'pass', function(decoded_string) 
        {
        /* Do not call start() */
        strictEqual('foo', decoded_string, 'only decryption works');
        });
    
    });
    

    【讨论】:

      猜你喜欢
      • 2016-12-23
      • 1970-01-01
      • 2010-10-12
      • 2013-08-19
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      相关资源
      最近更新 更多