mercredi 6 avril 2016

Testing a user script

I have a userscript (hopefully cross-browser compatible, though at the moment I'm running it on Tampermonkey) and I'm trying to set up a test suite. Or rather, trying to see if the approach I took in creating a test suite was reasonable and if I should/could do it differently.

The userscript is pretty straightforward: define a bunch of functions, then call one of them to do its work. To check it in node I want to define the functions but avoid running the initial function (since there isn't a browser present to handle the DOM properties). So I run this ugly shell script (hopefully fairly compatible; I'm running it on dash):

grep -ev '^\s*stuff\s*\(\s*\)\s*;?\s*($|//)' oeis-tools.user.js > test-cat.js
./getFunctions.sh >> test-cat.js
cat test.js >> test-cat.js
nodejs test-cat.js
rm test-cat.js

So basically I drop the line where the function is invoked, cat it with a test script, then pass it to node. Within the test script I have an assert-like function

function shouldBe(func, args, desiredResults) {
    totalTests++;
    tested.push(func.name);
    var actualResult = func.apply(null, args);
    if (isIn(actualResult, desiredResults)) return;
    console.log('Called ' + func.name + '(' + args.map(disp).join(', ') + ')');
    if (desiredResults.length === 1) {
        console.log('\tExpected ' + disp(desiredResults[0]));
    } else {
        console.log('\tExpected ' + desiredResults.map(disp).join(' or '));
    }
    console.log('\tGot      ' + disp(actualResult));
    failedTests++;
}

which lets me call tests in the form shouldBe(functionToTest, [firstInput, secondInput, etc], [correctOutput, otherCorrectOutput]). (I've left out the definitions of various helper functions but their precise definitions shouldn't matter here.)

On the plus side, this lets me write tests quickly and leaves the userscript untouched (no testing baggage). But it seems pretty hacky. Is there a better approach?

Aucun commentaire:

Enregistrer un commentaire