Skip to content

Commit

Permalink
Tests: Added --insert and --update parameters to language test (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
RunDevelopment committed Apr 3, 2021
1 parent ea82478 commit 4c8b855
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 46 deletions.
51 changes: 38 additions & 13 deletions test-suite.html
Expand Up @@ -85,22 +85,20 @@ <h2 id="writing-tests-creating-your-test-case-file">Creating your test case file


<h2 id="writing-tests-writing-your-test">Writing your test</h2>
<p>The structure of a test case file is as follows:</p>
<pre><code>
... language snippet...
----
... the simplified token stream you expect ...</code></pre>

<p>Your file is built up of two or three sections, separated by ten or more dashes <code>-</code>, starting at the begin of the line:</p>
<p>A test case file is built up of two or three sections separated by ten or more dashes <code>-</code> starting at the begin of the line. The sections are the following:</p>

<ol>
<li>Your language snippet. The code you want to tokenize using Prism. (<strong>required</strong>)</li>
<li>
The simplified token stream you expect. Needs to be valid JSON. (<em>optional</em>) <br>
If there no token stream defined, the test case will fail unless the <code>--accept</code> flag is present when running the test command (e.g. <code>npm run test:languages -- --accept</code>). If the flag is present and there is no expected token stream, the runner will insert the actual token stream into the test case file, changing it.
Instead of manually inserting the expected token stream yourself, prefer using the <code class="language-bash">npm run test:languages -- --insert</code> command. You can read more about this and related commands <a href="#writing-tests-insert-and-update">here</a>. <br>
If there no token stream defined, the test case will fail unless the <code>--insert</code> or <code>--update</code> flag is present when running the test command.
</li>
<li>A comment explaining the test case. (<em>optional</em>)</li>
<li>A brief comment explaining the test case. (<em>optional</em>)</li>
</ol>
<p>The easiest way would be to look at an existing test file:</p>

<p>Here is an example:</p>
<pre><code>var a = 5;

----------------------------------------------------
Expand All @@ -117,21 +115,48 @@ <h2 id="writing-tests-writing-your-test">Writing your test</h2>

This is a comment explaining this test case.</code></pre>

<h2 id="writing-tests-the-easy-way">The easy way</h2>
<h2 id="writing-tests-the-easy-way">The easy way to write tests</h2>
<p>The easy way to create one or multiple new test case(s) is this:</p>

<ol>
<li>Create a new file for a new test case in <code>tests/languages/${language}</code>.</li>
<li>Create a new test case file <code class="language-none">tests/languages/{language}/{test-case}.test</code>.</li>
<li>Insert the code you want to test (and nothing more).</li>
<li>Repeat the first two steps for as many test cases as you want.</li>
<li>Run <code>npm run test:languages -- --accept</code>.</li>
<li>Run <code class="language-bash">npm run test:languages -- --insert</code>.</li>
<li>Done.</li>
</ol>

<p>Updating existing test case files is easy too!</p>

<ol>
<li>Run <code class="language-bash">npm run test:languages -- --update</code>.</li>
<li>Done.</li>
</ol>

<p>This works by making the test runner insert the actual token stream of you test code as the expected token stream. <strong>Carefully check that the inserted token stream is actually what you expect or else the test is meaningless!</strong></p>

<p>Optionally, you can then also add comments to test cases.</p>
<p>More details about the command can be found <a href="#writing-tests-insert-and-update">here</a>.</p>

<h2 id="writing-tests-insert-and-update">Insert and update expected token streams</h2>

<p>When creating and changing languages, their test files have to be updated to properly test the language. The rather tedious task of updating test files can be automated using the following commands:</p>

<ul>
<li>
<pre><code class="language-bash">npm run test:languages -- --insert</code></pre>

<p>This will insert the current actual token stream into all test files without an expected token stream. Test files that have an expected token stream are not affected.</p>

<p>This command is intended to be used when you want to create new test files while not updating existing ones.</p>
</li>
<li>
<pre><code class="language-bash">npm run test:languages -- --update</code></pre>

<p>Updates (overwrites) the expected token stream of all failing test files and all test files that do not have an expected token stream. The language tests are guaranteed to pass after running this command.</p>
</li>
</ul>

<p><em>Keep in mind:</em> Both commands make it easy to create/update test files but this doesn't mean that the tests will be correct. <strong>Always carefully check the inserted/updated token streams!</strong></p>

<h2 id="writing-tests-explaining-the-simplified-token-stream">Explaining the simplified token stream</h2>

Expand Down
55 changes: 32 additions & 23 deletions tests/helper/test-case.js
Expand Up @@ -53,9 +53,9 @@ module.exports = {
*
* @param {string} languageIdentifier
* @param {string} filePath
* @param {boolean} acceptEmpty
* @param {"none" | "insert" | "update"} updateMode
*/
runTestCase(languageIdentifier, filePath, acceptEmpty) {
runTestCase(languageIdentifier, filePath, updateMode) {
const testCase = this.parseTestCaseFile(filePath);
const usedLanguages = this.parseLanguageNames(languageIdentifier);

Expand All @@ -64,30 +64,31 @@ module.exports = {
// the first language is the main language to highlight
const tokenStream = this.tokenize(Prism, testCase.code, usedLanguages.mainLanguage);

if (testCase.expectedTokenStream === null) {
// the test case doesn't have an expected value
if (!acceptEmpty) {
throw new Error('This test case doesn\'t have an expected toke n stream.'
+ ' Either add the JSON of a token stream or run \`npm run test:languages -- --accept\`'
+ ' to automatically add the current token stream.');
}

function updateFile() {
// change the file
const lineEnd = (/\r\n/.test(testCase.code) || !/\n/.test(testCase.code)) ? '\r\n' : '\n';
const separator = "\n\n----------------------------------------------------\n\n";
const pretty = TokenStreamTransformer.prettyprint(tokenStream)
.replace(/^( +)/gm, m => {
return "\t".repeat(m.length / 4);
});
const separator = '\n\n----------------------------------------------------\n\n';
const pretty = TokenStreamTransformer.prettyprint(tokenStream, '\t');

let content = testCase.code + separator + pretty;
if (testCase.comment) {
content += separator + testCase.comment;
if (testCase.comment.trim()) {
content += separator + testCase.comment.trim();
}
//content += '\n'
content += '\n'
content = content.replace(/\r?\n/g, lineEnd);

fs.writeFileSync(filePath, content, "utf-8");
fs.writeFileSync(filePath, content, 'utf-8');
}

if (testCase.expectedTokenStream === null) {
// the test case doesn't have an expected value
if (updateMode === 'none') {
throw new Error('This test case doesn\'t have an expected token stream.'
+ ' Either add the JSON of a token stream or run \`npm run test:languages -- --insert\`'
+ ' to automatically add the current token stream.');
}

updateFile();
} else {
// there is an expected value
const simplifiedTokenStream = TokenStreamTransformer.simplify(tokenStream);
Expand All @@ -100,6 +101,11 @@ module.exports = {
return;
}

if (updateMode === 'update') {
updateFile();
return;
}

// The index of the first difference between the expected token stream and the actual token stream.
// The index is in the raw expected token stream JSON of the test case.
const diffIndex = translateIndexIgnoreSpaces(testCase.expectedJson, expected, firstDiff(expected, actual));
Expand All @@ -108,11 +114,14 @@ module.exports = {
const lineNumber = testCase.expectedLineOffset + expectedJsonLines.length;

const tokenStreamStr = TokenStreamTransformer.prettyprint(tokenStream);
const message = "\n\nActual Token Stream:" +
"\n-----------------------------------------\n" +
const message = `\nThe expected token stream differs from the actual token stream.` +
` Either change the ${usedLanguages.mainLanguage} language or update the expected token stream.` +
` Run \`npm run test:languages -- --update\` to update all missing or incorrect expected token streams.` +
`\n\n\nActual Token Stream:` +
`\n-----------------------------------------\n` +
tokenStreamStr +
"\n-----------------------------------------\n" +
"File: " + filePath + ":" + lineNumber + ":" + columnNumber + "\n\n";
`\n-----------------------------------------\n` +
`File: ${filePath}:${lineNumber}:${columnNumber}\n\n`;

assert.deepEqual(simplifiedTokenStream, testCase.expectedTokenStream, testCase.comment + message);
}
Expand Down
16 changes: 8 additions & 8 deletions tests/helper/token-stream-transformer.js
Expand Up @@ -50,10 +50,11 @@ module.exports = {

/**
* @param {TokenStream} tokenStream
* @param {string} [indentation]
* @returns {string}
*/
prettyprint(tokenStream) {
return printPrettyTokenStream(toPrettyTokenStream(tokenStream));
prettyprint(tokenStream, indentation) {
return printPrettyTokenStream(toPrettyTokenStream(tokenStream), undefined, indentation);
}
};

Expand Down Expand Up @@ -219,13 +220,12 @@ function prettyFormat(prettyStream) {
/**
* @param {PrettyTokenStream} prettyStream
* @param {number} [indentationLevel]
* @param {string} [indentationChar]
* @returns {string}
*/
function printPrettyTokenStream(prettyStream, indentationLevel = 1) {
const indentChar = ' ';

function printPrettyTokenStream(prettyStream, indentationLevel = 1, indentationChar = ' ') {
// can't use tabs because the console will convert one tab to four spaces
const indentation = new Array(indentationLevel + 1).join(indentChar);
const indentation = new Array(indentationLevel + 1).join(indentationChar);

let out = '';
out += '[\n';
Expand Down Expand Up @@ -265,7 +265,7 @@ function printPrettyTokenStream(prettyStream, indentationLevel = 1) {
out += JSON.stringify(content);
} else {
// token stream
out += printPrettyTokenStream(content, indentationLevel + 1);
out += printPrettyTokenStream(content, indentationLevel + 1, indentationChar);
}

out += ']';
Expand All @@ -275,7 +275,7 @@ function printPrettyTokenStream(prettyStream, indentationLevel = 1) {
out += lineEnd;
}
})
out += indentation.substr(indentChar.length) + ']'
out += indentation.substr(indentationChar.length) + ']'
return out;
}

Expand Down
5 changes: 3 additions & 2 deletions tests/run.js
Expand Up @@ -12,7 +12,8 @@ const testSuite =
// load complete test suite
: TestDiscovery.loadAllTests(__dirname + "/languages");

const accept = !!argv.accept;
const insert = !!argv.accept || !!argv.insert;
const update = !!argv.update;

// define tests for all tests in all languages in the test suite
for (const language in testSuite) {
Expand All @@ -29,7 +30,7 @@ for (const language in testSuite) {

it("– should pass test case '" + fileName + "'", function () {
if (path.extname(filePath) === '.test') {
TestCase.runTestCase(language, filePath, accept);
TestCase.runTestCase(language, filePath, update ? "update" : insert ? "insert" : "none");
} else {
TestCase.runTestsWithHooks(language, require(filePath));
}
Expand Down

0 comments on commit 4c8b855

Please sign in to comment.