Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions __fixtures__/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export const summary = {
addHeading: jest.fn<typeof core.summary.addHeading>(),
addRaw: jest.fn<typeof core.summary.addRaw>(),
addBreak: jest.fn<typeof core.summary.addBreak>(),
addList: jest.fn<typeof core.summary.addList>(),
addTable: jest.fn<typeof core.summary.addTable>(),
stringify: jest.fn<typeof core.summary.stringify>(),
write: jest.fn<typeof core.summary.write>(),
};
13 changes: 13 additions & 0 deletions __fixtures__/svrl/report.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<svrl:schematron-output xmlns:svrl="http://purl.oclc.org/dsdl/svrl"
xmlns:tei="http://www.tei-c.org/ns/1.0">
<svrl:active-pattern name="dracor-checks" documents="file:{{DOCUMENT_PATH}}"/>
<svrl:fired-rule context="tei:teiHeader" role="warning"/>
<svrl:failed-assert location="/Q{http://www.tei-c.org/ns/1.0}TEI/Q{http://www.tei-c.org/ns/1.0}teiHeader">
<svrl:text>Attribute @xml:id missing on element &lt;teiHeader&gt;.</svrl:text>
</svrl:failed-assert>
<svrl:fired-rule context="tei:title"/>
<svrl:successful-report location="/Q{http://www.tei-c.org/ns/1.0}TEI/Q{http://www.tei-c.org/ns/1.0}teiHeader/Q{http://www.tei-c.org/ns/1.0}fileDesc/Q{http://www.tei-c.org/ns/1.0}titleStmt/Q{http://www.tei-c.org/ns/1.0}title">
<svrl:text>Second issue on same document exercises the doc cache.</svrl:text>
</svrl:successful-report>
</svrl:schematron-output>
25 changes: 25 additions & 0 deletions __fixtures__/svrl/sample.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<TEI xmlns="http://www.tei-c.org/ns/1.0">
<teiHeader>
<fileDesc>
<titleStmt>
<title>Sample</title>
</titleStmt>
<publicationStmt>
<p>Fixture</p>
</publicationStmt>
<sourceDesc>
<p>Fixture</p>
</sourceDesc>
</fileDesc>
</teiHeader>
<text>
<body>
<div type="act" n="1">
<sp who="#char1">
<p>Hello.</p>
</sp>
</div>
</body>
</text>
</TEI>
108 changes: 99 additions & 9 deletions __tests__/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ import { jest } from '@jest/globals';
import * as core from '../__fixtures__/core.js';
import * as exec from '../__fixtures__/exec.js';

const validate = jest.fn(async () => [] as unknown[]);

// Mocks should be declared before the module being tested is imported.
jest.unstable_mockModule('@actions/core', () => core);
jest.unstable_mockModule('@actions/exec', () => exec);
jest.unstable_mockModule('../src/schematron.js', () => ({ validate }));

// The module being tested should be imported dynamically. This ensures that the
// mocks are used in place of any actual dependencies.
Expand All @@ -21,22 +24,28 @@ const twoErrorOutput = `/invalid.xml:10:36: error: attribute "foo" not allowed
/invalid.xml:456:78: error: element "bar" not allowed`;

const mockJingExecSuccess = async () => 0;
const mockJingExecFailure = async (command, args, options) => {
const mockJingExecFailure = async (
_command: string,
_args: string[] | undefined,
options?: { listeners?: { stdout?: (data: Buffer) => void } }
) => {
if (options?.listeners?.stdout) {
options.listeners.stdout(Buffer.from(twoErrorOutput));
}
return 1;
};

function setInputs(inputs: Record<string, string>) {
core.getInput.mockImplementation((name: string) => inputs[name] ?? '');
}

describe('main.ts', () => {
beforeEach(() => {
// Set the action's inputs as return values from core.getInput().
core.getInput.mockImplementation((input) => {
return { schema: 'dracor', files: 'tei/valid.xml' }[input] || '';
});
setInputs({ schema: 'dracor', files: 'tei/valid.xml' });
core.summary.stringify.mockImplementation(() => '<summary>');

exec.exec.mockImplementation(mockJingExecSuccess);
validate.mockResolvedValue([]);
delete process.env.GITHUB_STEP_SUMMARY;
});

afterEach(() => {
Expand All @@ -45,12 +54,93 @@ describe('main.ts', () => {

it('runs with successful jing validation', async () => {
await run();
expect(exec.exec).toHaveBeenCalledTimes(2);
expect(exec.exec).toHaveBeenCalledTimes(1);
expect(validate).toHaveBeenCalledTimes(1);
expect(core.setFailed).not.toHaveBeenCalled();
});

it('runs with jing validation errors', async () => {
it('runs with jing validation errors and fails the action', async () => {
exec.exec.mockImplementation(mockJingExecFailure);
await run();
expect(exec.exec).toHaveBeenCalledTimes(2);
expect(core.summary.addTable).toHaveBeenCalled();
expect(core.setFailed).toHaveBeenCalledWith('Invalid documents');
});

it('uses the TEI schema when schema=tei and skips schematron', async () => {
setInputs({ schema: 'tei', version: '4.9.0', files: 'tei/valid.xml' });
await run();
const [, args] = exec.exec.mock.calls[0];
expect(args?.[0]).toMatch(/tei_all_4\.9\.0\.rng$/);
expect(validate).not.toHaveBeenCalled();
});

it('fails with a clear message on unknown schema', async () => {
setInputs({ schema: 'bogus', files: 'tei/valid.xml' });
await run();
expect(core.setFailed).toHaveBeenCalledWith('Unknown schema "bogus"');
expect(exec.exec).not.toHaveBeenCalled();
});

it('does not fail the action when warn-only is set', async () => {
setInputs({
schema: 'dracor',
files: 'tei/valid.xml',
'warn-only': 'yes',
});
exec.exec.mockImplementation(mockJingExecFailure);
await run();
expect(core.setFailed).not.toHaveBeenCalled();
});

it('reports no files found when the input resolves to nothing', async () => {
setInputs({ schema: 'dracor', files: '' });
await run();
expect(exec.exec).not.toHaveBeenCalled();
expect(core.summary.addRaw).toHaveBeenCalledWith(
expect.stringMatching(/No files found/)
);
});

it('writes the summary when GITHUB_STEP_SUMMARY is set', async () => {
process.env.GITHUB_STEP_SUMMARY = '/tmp/summary.md';
try {
await run();
expect(core.summary.write).toHaveBeenCalled();
} finally {
delete process.env.GITHUB_STEP_SUMMARY;
}
});

it('adds schematron warnings and errors to the summary table, skipping information', async () => {
validate.mockResolvedValue([
{
document: 'tei/valid.xml',
role: 'warning',
text: 'warn msg',
lineNumber: 3,
columnNumber: 4,
},
{
document: 'tei/valid.xml',
role: '',
text: 'error msg',
lineNumber: 5,
columnNumber: 6,
},
{
document: 'tei/valid.xml',
role: 'information',
text: 'info msg',
lineNumber: 7,
columnNumber: 8,
},
]);
await run();
expect(core.summary.addTable).toHaveBeenCalled();
const table = core.summary.addTable.mock.calls[0][0];
// header row + warning + error rows (info skipped)
expect(table).toHaveLength(3);
// errors present, so action fails
expect(core.setFailed).toHaveBeenCalledWith('Invalid documents');
});
});
110 changes: 110 additions & 0 deletions __tests__/schematron.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { jest } from '@jest/globals';
import { mkdtempSync, readFileSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join, resolve } from 'path';
import * as exec from '../__fixtures__/exec.js';

jest.unstable_mockModule('@actions/exec', () => exec);

const { validate, runSchxslt, parseSVRL } =
await import('../src/schematron.js');

const svrlTemplate = readFileSync('__fixtures__/svrl/report.xml', 'utf8');
const samplePath = resolve('__fixtures__/svrl/sample.xml');

function writeSvrlFixture(): string {
const dir = mkdtempSync(join(tmpdir(), 'svrl-test-'));
const file = join(dir, 'report.xml');
writeFileSync(file, svrlTemplate.replaceAll('{{DOCUMENT_PATH}}', samplePath));
return file;
}

describe('schematron.ts', () => {
afterEach(() => {
jest.resetAllMocks();
});

describe('parseSVRL', () => {
it('extracts asserts with location, role and pattern info', () => {
const results = parseSVRL(writeSvrlFixture());

expect(results).toHaveLength(2);

const [first, second] = results;
expect(first.role).toBe('warning');
expect(first.patternName).toBe('dracor-checks');
expect(first.context).toBe('tei:teiHeader');
expect(first.location).toBe('/tei:TEI/tei:teiHeader');
expect(first.document).toBe(samplePath);
expect(first.fileName).toBe('sample.xml');
expect(typeof first.lineNumber).toBe('number');
expect(typeof first.columnNumber).toBe('number');

expect(second.role).toBe('');
expect(second.location).toBe(
'/tei:TEI/tei:teiHeader/tei:fileDesc/tei:titleStmt/tei:title'
);
});

it('escapes < and wraps @attributes in code tags', () => {
const [first] = parseSVRL(writeSvrlFixture());
expect(first.text).toContain('&lt;teiHeader');
expect(first.text).not.toContain('<teiHeader');
expect(first.text).toContain('<code>@xml:id</code>');
});

it('caches parsed TEI documents across asserts', () => {
const results = parseSVRL(writeSvrlFixture());
expect(results).toHaveLength(2);
expect(results[0].document).toBe(results[1].document);
});
});

describe('runSchxslt', () => {
it('invokes java with expected arguments and returns a report path', async () => {
exec.exec.mockImplementation(async () => 0);
const reportFile = await runSchxslt('in.xml', 'schema.sch', 'my-jar.jar');

expect(exec.exec).toHaveBeenCalledTimes(1);
const [cmd, args] = exec.exec.mock.calls[0];
expect(cmd).toBe('java');
expect(args).toEqual([
'-jar',
'my-jar.jar',
'-d',
'in.xml',
'-s',
'schema.sch',
'-o',
reportFile,
]);
expect(reportFile).toMatch(/svrl\.xml$/);
});

it('swallows exec failures and still resolves with a report path', async () => {
exec.exec.mockImplementation(async () => {
throw new Error('boom');
});
const reportFile = await runSchxslt('in.xml', 'schema.sch');
expect(reportFile).toMatch(/svrl\.xml$/);
});
});

describe('validate', () => {
it('runs schxslt and returns parsed asserts', async () => {
exec.exec.mockImplementation(async (_cmd, args) => {
const outIdx = (args as string[]).indexOf('-o');
const outFile = (args as string[])[outIdx + 1];
writeFileSync(
outFile,
svrlTemplate.replaceAll('{{DOCUMENT_PATH}}', samplePath)
);
return 0;
});

const results = await validate('in.xml', 'schema.sch', 'jar.jar');
expect(results).toHaveLength(2);
expect(results[0].fileName).toBe('sample.xml');
});
});
});
Loading
Loading