Search code examples
perlunit-testingmocha.jstap

How can I use Perl's 'prove' with TAP producers in other languages?


I'm a Perl dev working with a multi-language project, including python, node.js and C. Thankfully all of these languages have TAP producer libraries. For example, I can use the mocha command to run Node.js scripts and get TAP output.

However, how do I integrate this with the prove tool? For perl, I generally put tests in t/ and prove -vlc t/ will run all .t files inside as perl scripts. The only thing I can think of is to exec a mocha command within a perl .t file.


Solution

  • The most direct way I can think of to use TAP as a common unit test reporting format in a multi-language project is to write a few scripts in your t/ directory that call TAP-producing unit test drivers.

    Mocha has a TAP reporting plugin called mocha-tap-reporter and invoking it from the command line is just

    mocha --reporter mocha-tap-reporter <directory>
    

    Here's an example of how might set things up in a simple project

    .
    ├── node_modules
        (contents of node_modules omitted)
    ├── package-lock.json
    ├── package.json
    ├── t
    │   └── mocha.t
    └── test
        └── multiply.js
    

    In this case, multiply.js uses the assert helper and just has one test:

    const assert = require('assert');
    
    describe('multiply', function () {
        it('1 * 0 = 0', function () {
            assert.equal(1 * 0, 0);
        });
    });
    

    mocha.t is just a shell wrapper around mocha --reporter mocha-tap-reporter test.

    #!/bin/bash
    # change directory to folder containing source file
    cd "$(dirname "${BASH_SOURCE[0]}")"
    # go to project root
    cd ..
    # invoke mocha test runner with tap reporter
    ./node_modules/.bin/mocha \
        --reporter mocha-tap-reporter \
        test
    

    And then if you run prove from the project root, you'll see this:

    % prove
    t/mocha.t .. ok
    All tests successful.
    Files=1, Tests=1,  0 wallclock secs ( 0.02 usr  0.01 sys +  0.23 cusr  0.08 csys =  0.34 CPU)
    Result: PASS
    

    That being said, the mocha-tap-reporter plugin hasn't been updated in three years or so and looks a little unmaintained. I think that's the general situation for TAP libraries outside of the Perl community, though (having used one in an OCaml project a while back).