@jrpool/kilotest 58.2.0 → 59.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/api/listIssues.test.ts +32 -0
  2. package/api/listIssues.ts +38 -8
  3. package/api/listPages.test.ts +92 -0
  4. package/api/listPages.ts +93 -0
  5. package/api/orderNewTest.test.ts +1 -1
  6. package/api/orderNewTest.ts +4 -4
  7. package/api/requestNewTest.ts +6 -6
  8. package/api/requestRetest.ts +2 -2
  9. package/api/routes.test.ts +1 -1
  10. package/api/routes.ts +5 -5
  11. package/api/schemas.ts +24 -7
  12. package/api/util.ts +26 -45
  13. package/apiIntegration.test.ts +5 -5
  14. package/docs/SERVICE.md +16 -5
  15. package/index.html +1 -1
  16. package/index.test.ts +30 -18
  17. package/index.ts +22 -11
  18. package/lhm.plugin.json +1433 -141
  19. package/linkValidation.test.ts +2 -2
  20. package/llms-full.txt +9 -9
  21. package/llms.txt +4 -4
  22. package/mcp.test.ts +8 -8
  23. package/mcp.ts +14 -14
  24. package/openapi.yaml +84 -30
  25. package/package.json +1 -1
  26. package/routing.test.ts +5 -5
  27. package/server.json +1 -1
  28. package/sitemap.xml +1 -1
  29. package/smokeTest.ts +2 -2
  30. package/style.css +8 -8
  31. package/test/fixtures/buildFixtures.ts +1 -1
  32. package/util.test.ts +71 -12
  33. package/util.ts +61 -12
  34. package/web/enqueueForm/index.html +1 -1
  35. package/web/hideReportForm/hideReportForm.test.ts +5 -0
  36. package/web/hideReportForm/index.ts +9 -6
  37. package/web/listIssues/index.html +2 -1
  38. package/web/listIssues/index.ts +45 -3
  39. package/web/listIssues/listIssues.test.ts +76 -0
  40. package/web/{listReports → listPages}/index.html +1 -2
  41. package/web/listPages/index.ts +99 -0
  42. package/web/listPages/listPages.test.ts +196 -0
  43. package/web/metrics/metrics.test.ts +2 -2
  44. package/web/requestRetestForm/index.ts +4 -2
  45. package/web/requestRetestForm/requestRetestForm.test.ts +11 -0
  46. package/web/unhideReportForm/index.ts +9 -6
  47. package/web/unhideReportForm/unhideReportForm.test.ts +8 -5
  48. package/web/util.test.ts +85 -11
  49. package/web/util.ts +26 -28
  50. package/api/listReports.test.ts +0 -109
  51. package/api/listReports.ts +0 -87
  52. package/web/listReports/index.ts +0 -182
  53. package/web/listReports/listReports.test.ts +0 -300
@@ -1,109 +0,0 @@
1
- /*
2
- listReports.test.ts
3
- Tests for api/listReports.ts using the fixture corpus.
4
- */
5
-
6
- // IMPORTS
7
-
8
- import {test, before, after} from 'node:test';
9
- import assert from 'node:assert/strict';
10
- import {response} from './listReports.ts';
11
-
12
- // CONSTANTS
13
-
14
- // Fixture report identifiers in the reports/ directory (excluding the hidden one).
15
- const fixtureIds = [
16
- ['260101T0000', 'mix'],
17
- ['260101T0001', 'ct'],
18
- ['260101T0002', 'no'],
19
- ['260101T0005', 'emp'],
20
- ['260101T0006', 'prv'],
21
- ['260101T0008', 'mul'],
22
- ['260101T0009', 'brd'],
23
- ['260202T0000', 'new']
24
- ];
25
-
26
- // SETUP AND TEARDOWN
27
-
28
- const savedDBDir = process.env.DB_DIR;
29
-
30
- before(async () => {
31
- process.env.DB_DIR = (await import('../test/dbFixture.ts')).fixtureDBDir;
32
- });
33
-
34
- after(() => {
35
- if (savedDBDir !== undefined) {
36
- process.env.DB_DIR = savedDBDir;
37
- }
38
- else {
39
- delete process.env.DB_DIR;
40
- }
41
- });
42
-
43
- // TESTS
44
-
45
- test('listReports returns basics about all 8 non-hidden reports', async () => {
46
- const body = await response();
47
- const reportsBasics = body['response content']['basics about all available reports'];
48
- assert.equal(reportsBasics.length, 8);
49
- const ids = reportsBasics.map((b: any) => b.identifier).sort();
50
- const expectedIds = fixtureIds.map(([ts, jid]) => `${ts}-${jid}`).sort();
51
- assert.deepEqual(ids, expectedIds);
52
- });
53
-
54
- test('listReports does not include the hidden report', async () => {
55
- const body = await response();
56
- const reportsBasics = body['response content']['basics about all available reports'];
57
- const ids = reportsBasics.map((b: any) => b.identifier);
58
- assert.ok(!ids.includes('260101T0007-hid'), 'hidden report must not appear in listReports');
59
- });
60
-
61
- test('listReports sorts reports by page description and then by completion time', async () => {
62
- const body = await response();
63
- const reportsBasics = body['response content']['basics about all available reports'];
64
- const descriptions = reportsBasics.map((b: any) => b['tested web page'].description);
65
- // All CantTell Page, Empty Results Page, Mixed Outcomes Page, Mixed Outcomes Page, No Outcomes Page, Prevented Page.
66
- assert.deepEqual(
67
- descriptions,
68
- [
69
- 'All CantTell Page',
70
- 'Branch Coverage Page',
71
- 'Empty Results Page',
72
- 'Mixed Outcomes Page',
73
- 'Mixed Outcomes Page',
74
- 'Multi Violator Page',
75
- 'No Outcomes Page',
76
- 'Prevented Page'
77
- ]
78
- );
79
- // The two Mixed Outcomes Page reports should be sorted by completion time (older first).
80
- const mixedReports = reportsBasics.filter((b: any) => b['tested web page'].description === 'Mixed Outcomes Page');
81
- assert.equal(mixedReports[0]!.identifier, '260101T0000-mix');
82
- assert.equal(mixedReports[1]!.identifier, '260202T0000-new');
83
- });
84
-
85
- test('listReports marks the superseded report correctly', async () => {
86
- const body = await response();
87
- const reportsBasics = body['response content']['basics about all available reports'];
88
- const mix = reportsBasics.find((b: any) => b.identifier === '260101T0000-mix');
89
- const newer = reportsBasics.find((b: any) => b.identifier === '260202T0000-new');
90
- assert.ok(mix);
91
- assert.ok(newer);
92
- assert.equal(mix['whether a later report about the same page exists'], true);
93
- assert.equal(newer['whether a later report about the same page exists'], false);
94
- });
95
-
96
- test('listReports includes request-test instructions', async () => {
97
- const body = await response();
98
- const content = body['response content'];
99
- assert.ok(content['how to request that a page with no report be tested']);
100
- assert.ok(content['how a web user can request that the page be tested']);
101
- assert.equal(content['how to request that a page with no report be tested'].method, 'POST');
102
- });
103
-
104
- test('listReports includes tool name and metadata', async () => {
105
- const body = await response();
106
- assert.equal(body['tool name'], 'listReports');
107
- assert.ok(body['response metadata'].identifier);
108
- assert.ok(body['response metadata']['date and time']);
109
- });
@@ -1,87 +0,0 @@
1
- /*
2
- listReports.ts
3
- Returns basics about all the available reports.
4
- */
5
-
6
- // IMPORTS
7
-
8
- import {z} from 'zod';
9
- import {getReportBasics, getResponseMetadata, getThisHost, getToolsFacts} from './util.ts';
10
- import {getReportExtracts} from '../util.ts';
11
- import {listReportsResponseSchema} from './schemas.ts';
12
-
13
- // TYPES
14
-
15
- // The response content defined by the response schema.
16
- type ResponseContent = z.infer<typeof listReportsResponseSchema>['response content'];
17
-
18
- // FUNCTIONS
19
-
20
- // Returns the response body.
21
- export const response = async () => {
22
- const thisHost = getThisHost();
23
- // Initialize an array of basics about the reports.
24
- const reportsBasics: ResponseContent['basics about all available reports'] = [];
25
- // Get extracts of all available reports.
26
- const reportExtracts = await getReportExtracts();
27
- // For each report:
28
- for (const extract of reportExtracts) {
29
- const {jobID, timeStamp} = extract;
30
- // Get the basics about it.
31
- const reportBasics = await getReportBasics(timeStamp, jobID, extract);
32
- // Add the basics, with instructions for getting details, to the array.
33
- reportsBasics.push({
34
- ...reportBasics,
35
- 'how to get details about the report': {
36
- method: 'GET',
37
- URL: `${thisHost}/api/listIssues/${timeStamp}/${jobID}`
38
- },
39
- 'web users can get details about the report at': `${thisHost}/listIssues.html/${timeStamp}/${jobID}`
40
- });
41
- }
42
- // Sort the array by page description and secondarily by completion recency.
43
- reportsBasics.sort((a, b) => {
44
- if (a['tested web page'].description !== b['tested web page'].description) {
45
- return a['tested web page']
46
- .description
47
- .localeCompare(b['tested web page'].description, 'en', {sensitivity: 'base'});
48
- }
49
- return a['completion date and time'].localeCompare(b['completion date and time']);
50
- });
51
- // Create the response content.
52
- const responseContent: ResponseContent = {
53
- 'basics about all available reports': reportsBasics,
54
- 'how to request that a page with no report be tested': {
55
- method: 'POST',
56
- URL: `${thisHost}/api/requestNewTest`,
57
- 'request body': {
58
- description: '10- to 100-character description of the page conforming to the naming convention used in this list of reports',
59
- URL: '12- to 300-character URL of the page, including the https:// scheme and any query',
60
- reason: '20- to 100-character reason why the page should be tested'
61
- },
62
- 'how to check whether the request has been fulfilled': 'use this listReports tool to determine whether a report about the page has become available (typical wait time: 1 hour to 1 day)'
63
- },
64
- 'how a web user can request that the page be tested': {
65
- URL: `${thisHost}/requestNewTestForm.html`
66
- }
67
- };
68
- // Create a response body.
69
- const body = {
70
- 'tool collection': getToolsFacts(),
71
- 'tool name': 'listReports',
72
- 'this request': {
73
- description: 'Provide basics about all available reports.',
74
- method: 'GET',
75
- URL: `${thisHost}/api/listReports`,
76
- 'closest ancestor request': null
77
- },
78
- 'URLs of similar requests for web users': {
79
- 'this request': `${thisHost}/listReports.html`,
80
- 'closest ancestor request': null
81
- },
82
- 'response metadata': getResponseMetadata(),
83
- 'response content': responseContent
84
- };
85
- // Return it.
86
- return body;
87
- };
@@ -1,182 +0,0 @@
1
- /*
2
- index.ts
3
- Lists all available reports.
4
- */
5
-
6
- // IMPORTS
7
-
8
- import {
9
- getJobNames,
10
- getObject,
11
- getReport,
12
- getReportExtracts,
13
- getTestRequests,
14
- isReportError,
15
- jobsPath,
16
- objectSort,
17
- populateTemplate
18
- } from '../../util.ts';
19
- import {
20
- getMultiReportWhats,
21
- getPageDataStrings,
22
- getPageFactsLines,
23
- getReportData
24
- } from '../util.ts';
25
- import path from 'node:path';
26
-
27
- // FUNCTIONS
28
-
29
- // Adds parameters to a query for the answer page.
30
- const populateQuery = async (query: Record<string, any>) => {
31
- const margin = ' '.repeat(8);
32
- // Initialize the classes of lines.
33
- const lines: {requests: string[], queue: string[], claimed: string[], tested: string[]} = {
34
- requests: [],
35
- queue: [],
36
- claimed: [],
37
- tested: []
38
- };
39
- // Get the test requests.
40
- const testRequests = await getTestRequests();
41
- // For each requested URL:
42
- Object.keys(testRequests).forEach(url => {
43
- // For each of its requests:
44
- testRequests[url]!.forEach((req: any) => {
45
- const {description, reason} = req;
46
- // Add a line.
47
- lines.requests.push(`${margin}<li><code>${url}</code> (${description}): ${reason}</li>`);
48
- });
49
- });
50
- // Sort the lines in alphabetical order by URL and secondarily by proposed name.
51
- lines.requests.sort();
52
- // Add the lines to the query.
53
- query.requests = lines.requests.join('\n');
54
- // Add a no-requests message, if applicable, to the query.
55
- query.noRequests = lines.requests.length
56
- ? 'Kilotest managers can <a href="enqueueForm.html">approve or reject a request</a>.'
57
- : 'No requests await approval now.';
58
- // Get the file names of all queued and claimed jobs.
59
- const jobFileNames = await getJobNames();
60
- // Initialize sets of the page descriptions and URLs of jobs in both categories.
61
- const jobsData = {
62
- queue: {
63
- descriptions: new Set(),
64
- urls: new Set()
65
- },
66
- claimed: {
67
- descriptions: new Set(),
68
- urls: new Set()
69
- }
70
- };
71
- // For each job category:
72
- for (const category of ['queue', 'claimed'] as const) {
73
- // For each job in the category:
74
- for (const fileName of jobFileNames[category]) {
75
- // Get the job.
76
- const job = await getObject(path.join(jobsPath(), category, fileName)) as {target: {url: string, what: string}};
77
- // Get the description and URL of its page.
78
- const {target} = job;
79
- const {what, url} = target;
80
- // Ensure they are in the sets of properties of the category.
81
- jobsData[category].descriptions.add(what);
82
- jobsData[category].urls.add(url);
83
- // Add a line.
84
- lines[category].push(`${margin}<li><code>${job.target.url}</code> (${job.target.what})</li>`);
85
- }
86
- // Add the lines to the query.
87
- query[category] = lines[category].join('\n');
88
- }
89
- // Add a no-queued message, if applicable, to the query.
90
- query.noQueued = lines.queue.length ? '' : 'No pages are queued for testing.';
91
- // Add a no-claimed message, if applicable, to the query.
92
- query.noClaimed = lines.claimed.length ? '' : 'No pages are being tested now.';
93
- // Get extracts of all available reports.
94
- const reportExtracts = await getReportExtracts();
95
- const reportCount = reportExtracts.length;
96
- query.which = reportCount ? 'the following' : 'no';
97
- query.some = (reportCount || jobFileNames.queue.length || jobFileNames.claimed.length)
98
- ? 'another'
99
- : 'a';
100
- const multiReportWhats = await getMultiReportWhats();
101
- // Sort them primarily by page description and secondarily by completion time.
102
- let sortedExtracts = objectSort(reportExtracts, 'reportTime', 'alpha');
103
- sortedExtracts = objectSort(sortedExtracts, 'description', 'alpha');
104
- // For each report:
105
- for (const extract of sortedExtracts) {
106
- const {jobID, timeStamp, url, description, superseded} = extract;
107
- // Get the report.
108
- const report = await getReport(timeStamp, jobID);
109
- // If this failed:
110
- if (isReportError(report)) {
111
- console.error(report.error);
112
- // Populate the query with the reason.
113
- query.error = report.error;
114
- // Stop populating the query.
115
- return;
116
- }
117
- // Otherwise, i.e. if it succeeded, get data about the report.
118
- const reportData = getReportData(report);
119
- const pageDataStrings = getPageDataStrings(report);
120
- const {issueCount} = reportData;
121
- const {testInfo} = pageDataStrings;
122
- // Add lines about the report.
123
- lines.tested.push(`${margin}<details>`);
124
- const testText = multiReportWhats.includes(description) ? ` (${testInfo.toLowerCase()})` : '';
125
- lines.tested.push(`${margin} <summary>${description}${testText}</summary>`);
126
- // Add the page facts to the lines.
127
- lines.tested.push(...getPageFactsLines(pageDataStrings, reportData, `${margin} `));
128
- lines.tested.push(`${margin} <ul class="nav">`);
129
- // If any issues were reported:
130
- if (issueCount) {
131
- // Add a link to issue details to the lines.
132
- const href = `href="listIssues.html/${timeStamp}/${jobID}"`;
133
- const label = `aria-label="issue details for the ${description} page"`;
134
- const link = `<a ${href} ${label}>Issue details</a>`;
135
- lines.tested.push(`${margin} <li>${link}</li>`);
136
- }
137
- let retestString: string = '';
138
- // If a page with the same description or URL is being tested:
139
- if (jobsData.claimed.descriptions.has(description) || jobsData.claimed.urls.has(url)) {
140
- // Report this.
141
- retestString = 'Currently being retested';
142
- }
143
- // Otherwise, if such a page is queued:
144
- else if (jobsData.queue.descriptions.has(description) || jobsData.queue.urls.has(url)) {
145
- retestString = 'Currently in the queue for retesting';
146
- }
147
- // Otherwise, if no such page is being tested or queued and the report is not superseded:
148
- else if (!superseded) {
149
- // Make the page available for retesting.
150
- const href = `/requestRetestForm.html/${timeStamp}/${jobID}`;
151
- const retestContent = 'Should Kilotest retest the page?';
152
- retestString = `<a href="${href}">${retestContent}</a>`;
153
- }
154
- if (retestString) {
155
- lines.tested.push(`${margin} <li>${retestString}</li>`);
156
- }
157
- lines.tested.push(`${margin} </ul>`);
158
- lines.tested.push(`${margin}</details>`);
159
- }
160
- query.testedPages = lines.tested.join('\n');
161
- };
162
- // Returns a page answering the targets question.
163
- export const answer = async () => {
164
- const query: Record<string, any> = {};
165
- // Create a query to replace placeholders.
166
- await populateQuery(query);
167
- // If the query reports an error:
168
- if (query.error) {
169
- // Return it.
170
- return {
171
- status: 'error',
172
- message: query.error
173
- };
174
- }
175
- // Otherwise, i.e. if it does not report an error, get the template.
176
- const answerPage = await populateTemplate(import.meta.dirname, query);
177
- // Return the populated page.
178
- return {
179
- status: 'ok',
180
- answerPage
181
- };
182
- };
@@ -1,300 +0,0 @@
1
- /*
2
- listReports.test.ts
3
- UI tests for web/listReports/index.ts using the fixture corpus.
4
- */
5
-
6
- // IMPORTS
7
-
8
- import {test, before, after} from 'node:test';
9
- import assert from 'node:assert/strict';
10
- import path from 'node:path';
11
- import fs from 'node:fs/promises';
12
- import {parse} from 'node-html-parser';
13
- import {answer} from './index.ts';
14
-
15
- // SETUP AND TEARDOWN
16
-
17
- const savedDBDir = process.env.DB_DIR;
18
-
19
- before(async () => {
20
- process.env.DB_DIR = (await import('../../test/dbFixture.ts')).fixtureDBDir;
21
- // Ensure job subdirectories exist (they are empty and not tracked by Git).
22
- for (const sub of ['queue', 'claimed', 'failed']) {
23
- await fs.mkdir(path.join(process.env.DB_DIR, 'jobs', sub), {recursive: true});
24
- }
25
- });
26
-
27
- after(() => {
28
- if (savedDBDir !== undefined) {
29
- process.env.DB_DIR = savedDBDir;
30
- }
31
- else {
32
- delete process.env.DB_DIR;
33
- }
34
- });
35
-
36
- // TESTS
37
-
38
- test('listReports returns an ok status with valid HTML', async () => {
39
- const result: any = await answer();
40
- assert.equal(result.status, 'ok');
41
- assert.ok(result.answerPage);
42
- const html = parse(result.answerPage);
43
- assert.equal(html.querySelector('title')?.text, 'Pages tested | Kilotest');
44
- });
45
-
46
- test('listReports includes the 8 non-hidden fixture reports as details elements', async () => {
47
- const result: any = await answer();
48
- const html = parse(result.answerPage);
49
- const details = html.querySelectorAll('details');
50
- assert.equal(details.length, 8);
51
- });
52
-
53
- test('listReports includes the page descriptions in summary elements', async () => {
54
- const result: any = await answer();
55
- const html = parse(result.answerPage);
56
- const summaries = html.querySelectorAll('details > summary').map(s => s.text);
57
- assert.ok(summaries.some(s => s.startsWith('Mixed Outcomes Page')));
58
- assert.ok(summaries.some(s => s.startsWith('All CantTell Page')));
59
- assert.ok(summaries.some(s => s.startsWith('No Outcomes Page')));
60
- assert.ok(summaries.some(s => s.startsWith('Empty Results Page')));
61
- assert.ok(summaries.some(s => s.startsWith('Prevented Page')));
62
- });
63
-
64
- test('listReports does not include the hidden report', async () => {
65
- const result: any = await answer();
66
- assert.ok(!result.answerPage.includes('Hidden Page'));
67
- });
68
-
69
- test('listReports includes links to listIssues for reports with issues', async () => {
70
- const result: any = await answer();
71
- const html = parse(result.answerPage);
72
- const issueLinks = html.querySelectorAll('a[href*="listIssues.html"]');
73
- assert.ok(issueLinks.length > 0);
74
- const hrefs = issueLinks.map(a => a.getAttribute('href'));
75
- assert.ok(hrefs.some(href => href?.includes('260101T0000/mix')));
76
- });
77
-
78
- test('listReports includes the page URLs in the report details', async () => {
79
- const result: any = await answer();
80
- assert.ok(result.answerPage.includes('https://example.com/mixed'));
81
- assert.ok(result.answerPage.includes('https://example.com/canttell'));
82
- });
83
-
84
- test('listReports includes a link to request testing a new page', async () => {
85
- const result: any = await answer();
86
- const html = parse(result.answerPage);
87
- const testLink = html.querySelector('a[href="requestNewTestForm.html"]');
88
- assert.ok(testLink);
89
- });
90
-
91
- test('listReports shows requests when testRequests.json has entries', {timeout: 500}, async () => {
92
- const dbDir = (await import('../../test/dbFixture.ts')).fixtureDBDir;
93
- const testRequestsPath = path.join(dbDir, 'jobs', 'testRequests.json');
94
- const originalTestRequests = await fs.readFile(testRequestsPath, 'utf8');
95
- try {
96
- const testRequests = {
97
- 'https://example.com/mixed': [
98
- {description: 'Mixed Outcomes Page', reason: 'Needs retesting for accessibility'}
99
- ]
100
- };
101
- await fs.writeFile(testRequestsPath, JSON.stringify(testRequests, null, 2));
102
- const result: any = await answer();
103
- assert.equal(result.status, 'ok');
104
- assert.ok(result.answerPage.includes('https://example.com/mixed'));
105
- assert.ok(result.answerPage.includes('Needs retesting for accessibility'));
106
- }
107
- finally {
108
- await fs.writeFile(testRequestsPath, originalTestRequests);
109
- }
110
- });
111
-
112
- test('listReports shows queued and claimed jobs when they exist', async () => {
113
- const dbDir = (await import('../../test/dbFixture.ts')).fixtureDBDir;
114
- const queueDir = path.join(dbDir, 'jobs', 'queue');
115
- const claimedDir = path.join(dbDir, 'jobs', 'claimed');
116
- const queueFile = path.join(queueDir, 'queuedJob.json');
117
- const claimedFile = path.join(claimedDir, 'claimedJob.json');
118
- try {
119
- const queuedJob = {
120
- target: {url: 'https://example.com/queued', what: 'Queued Page'}
121
- };
122
- const claimedJob = {
123
- target: {url: 'https://example.com/claimed', what: 'Claimed Page'}
124
- };
125
- await fs.writeFile(queueFile, JSON.stringify(queuedJob, null, 2));
126
- await fs.writeFile(claimedFile, JSON.stringify(claimedJob, null, 2));
127
- const result: any = await answer();
128
- assert.equal(result.status, 'ok');
129
- assert.ok(result.answerPage.includes('https://example.com/queued'));
130
- assert.ok(result.answerPage.includes('Queued Page'));
131
- assert.ok(result.answerPage.includes('https://example.com/claimed'));
132
- assert.ok(result.answerPage.includes('Claimed Page'));
133
- }
134
- finally {
135
- await fs.unlink(queueFile).catch(() => {});
136
- await fs.unlink(claimedFile).catch(() => {});
137
- }
138
- });
139
-
140
- test('listReports shows claimed retest status for a report with a matching claimed job', async () => {
141
- const dbDir = (await import('../../test/dbFixture.ts')).fixtureDBDir;
142
- const claimedDir = path.join(dbDir, 'jobs', 'claimed');
143
- const claimedFile = path.join(claimedDir, 'claimedRetest.json');
144
- try {
145
- const claimedJob = {
146
- target: {url: 'https://example.com/mixed', what: 'Mixed Outcomes Page'}
147
- };
148
- await fs.writeFile(claimedFile, JSON.stringify(claimedJob, null, 2));
149
- const result: any = await answer();
150
- assert.equal(result.status, 'ok');
151
- assert.ok(result.answerPage.includes('Currently being retested'));
152
- }
153
- finally {
154
- await fs.unlink(claimedFile).catch(() => {});
155
- }
156
- });
157
-
158
- test('listReports shows queued retest status for a report with a matching queued job', async () => {
159
- const dbDir = (await import('../../test/dbFixture.ts')).fixtureDBDir;
160
- const queueDir = path.join(dbDir, 'jobs', 'queue');
161
- const queueFile = path.join(queueDir, 'queuedRetest.json');
162
- try {
163
- const queuedJob = {
164
- target: {url: 'https://example.com/mixed', what: 'Mixed Outcomes Page'}
165
- };
166
- await fs.writeFile(queueFile, JSON.stringify(queuedJob, null, 2));
167
- const result: any = await answer();
168
- assert.equal(result.status, 'ok');
169
- assert.ok(result.answerPage.includes('Currently in the queue for retesting'));
170
- }
171
- finally {
172
- await fs.unlink(queueFile).catch(() => {});
173
- }
174
- });
175
-
176
- test('listReports returns an error when a report file is invalid', {timeout: 500}, async () => {
177
- const dbDir = (await import('../../test/dbFixture.ts')).fixtureDBDir;
178
- const reportsDir = path.join(dbDir, 'reports');
179
- const invalidReportPath = path.join(reportsDir, '260101T9999-bad.json');
180
- try {
181
- // Valid for getReportExtract (has target and jobData.endTime) but not usable by isUsableReport (no acts or catalog).
182
- const invalidReport = {
183
- target: {what: 'Invalid Report', url: 'https://example.com/invalid'},
184
- jobData: {endTime: '26-01-01T00:10'}
185
- };
186
- await fs.writeFile(invalidReportPath, JSON.stringify(invalidReport, null, 2));
187
- const result: any = await answer();
188
- assert.equal(result.status, 'error');
189
- assert.ok(result.message);
190
- }
191
- finally {
192
- await fs.unlink(invalidReportPath).catch(() => {});
193
- }
194
- });
195
-
196
- test('listReports shows no-reports message when the database is empty', async () => {
197
- // Create a temp DB with empty reports and jobs directories.
198
- const os = await import('node:os');
199
- const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'listreports-empty-'));
200
- await fs.mkdir(path.join(tmpDir, 'reports'), {recursive: true});
201
- await fs.mkdir(path.join(tmpDir, 'jobs', 'queue'), {recursive: true});
202
- await fs.mkdir(path.join(tmpDir, 'jobs', 'claimed'), {recursive: true});
203
- await fs.mkdir(path.join(tmpDir, 'jobs', 'failed'), {recursive: true});
204
- await fs.writeFile(path.join(tmpDir, 'jobs', 'testRequests.json'), '{}\n');
205
- const savedDBDir = process.env.DB_DIR;
206
- process.env.DB_DIR = tmpDir;
207
- try {
208
- const {answer} = await import('./index.ts');
209
- const result: any = await answer();
210
- assert.equal(result.status, 'ok');
211
- assert.ok(result.answerPage.includes('no'));
212
- assert.ok(result.answerPage.includes(' a '));
213
- }
214
- finally {
215
- process.env.DB_DIR = savedDBDir;
216
- await fs.rm(tmpDir, {recursive: true}).catch(() => {});
217
- }
218
- });
219
-
220
- // Returns the details element of the report whose summary starts with a description and whose issue link, if required, contains a fragment.
221
- const getReportDetails = (html: any, description: string, hrefFragment?: string) => {
222
- const matches = html.querySelectorAll('details').filter((d: any) => {
223
- const summary = d.querySelector('summary')?.text ?? '';
224
- if (!summary.startsWith(description)) {
225
- return false;
226
- }
227
- return hrefFragment === undefined
228
- || d.querySelectorAll('a').some((a: any) => a.getAttribute('href')?.includes(hrefFragment));
229
- });
230
- assert.equal(matches.length, 1, `exactly one report matches ${description} ${hrefFragment ?? ''}`);
231
- return matches[0];
232
- };
233
-
234
- // Returns the 3 rule-engine amounts and the 3 summary amounts of a details element.
235
- const getResultFacts = (details: any) => {
236
- const items = details.querySelectorAll('li');
237
- const itemTexts: string[] = items.map((li: any) => li.text.trim());
238
- const getAmount = (label: string) => {
239
- const text = itemTexts.find(t => t.startsWith(`${label}: `));
240
- assert.ok(text, `${label} item exists`);
241
- return Number(text.slice(label.length + 2));
242
- };
243
- // The summary item is the parent of the rule-engine item and the 3 amount items.
244
- const summaryItem = items.find((li: any) => li.text.trim().startsWith('Summary of results:'));
245
- assert.ok(summaryItem, 'Summary of results item exists');
246
- const summaryList = summaryItem.querySelector('ul');
247
- const amountLabels = summaryList.childNodes
248
- .filter((node: any) => node.tagName === 'LI')
249
- .map((li: any) => li.text.trim().split(':')[0]);
250
- return {
251
- called: getAmount('Called'),
252
- tested: getAmount('Were able to test'),
253
- reporters: getAmount('Reported any rule violations'),
254
- amountLabels,
255
- violations: getAmount('Violations'),
256
- violators: getAmount('Violators'),
257
- issues: getAmount('Issues')
258
- };
259
- };
260
-
261
- // Expected facts, hand-computed from the fixtures.
262
- const expectedFacts: [string, string | undefined, number, number, number, number, number, number][] = [
263
- // Description, issue-link fragment, engines called, engines able to test, reporting engines, violations, violators, issues.
264
- ['Mixed Outcomes Page', '260101T0000/mix', 2, 2, 2, 3, 2, 2],
265
- ['Mixed Outcomes Page', '260202T0000/new', 1, 1, 1, 1, 1, 1],
266
- ['All CantTell Page', undefined, 1, 1, 0, 0, 0, 0],
267
- ['No Outcomes Page', undefined, 1, 1, 1, 1, 1, 1],
268
- ['Empty Results Page', undefined, 1, 1, 0, 0, 0, 0],
269
- ['Prevented Page', undefined, 2, 1, 1, 1, 1, 1],
270
- ['Multi Violator Page', undefined, 2, 2, 2, 4, 3, 1],
271
- ['Branch Coverage Page', undefined, 3, 3, 1, 4, 4, 1]
272
- ];
273
-
274
- for (const [description, fragment, called, tested, reporters, violations, violators, issues] of expectedFacts) {
275
- test(`listReports gives correct rule-engine and summary amounts for ${description}${fragment ? ` (${fragment})` : ''}`, async () => {
276
- const result: any = await answer();
277
- const html = parse(result.answerPage);
278
- const facts = getResultFacts(getReportDetails(html, description, fragment));
279
- assert.equal(facts.called, called);
280
- assert.equal(facts.tested, tested);
281
- assert.equal(facts.reporters, reporters);
282
- assert.deepEqual(facts.amountLabels, ['Rule engines', 'Violations', 'Violators', 'Issues']);
283
- assert.equal(facts.violations, violations);
284
- assert.equal(facts.violators, violators);
285
- assert.equal(facts.issues, issues);
286
- });
287
- }
288
-
289
- test('listReports counts a prevented rule engine as called but not able to test', async () => {
290
- const result: any = await answer();
291
- const html = parse(result.answerPage);
292
- const prevented = getResultFacts(getReportDetails(html, 'Prevented Page'));
293
- assert.equal(prevented.called - prevented.tested, 1);
294
- const others = html.querySelectorAll('details').filter((d: any) => !d.text.includes('Prevented Page'));
295
- assert.equal(others.length, 7);
296
- assert.ok(others.every((d: any) => {
297
- const facts = getResultFacts(d);
298
- return facts.called === facts.tested;
299
- }));
300
- });