简体   繁体   中英

node.js async child processes testing

I make my first steps in node.js and want to test my code, but I'm stuck. I use node-qunit library as a testing tool.

Here is my code:

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;

When I call this functions from interactive console, they work as expected. But when I try to test them asynchronously using code below, second strictEqual sometimes works, and sometimes fails.

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);
});

Looks like problems are with asynchrony, because when I test this functions separately, they both work.

Thanks for you help.

Use lazy evaluation instead of 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');
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM