-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.ts
255 lines (224 loc) · 7.86 KB
/
test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
'use strict';
import * as core from '@actions/core';
import * as YAML from 'yaml';
import { PathLike, readFileSync } from 'fs';
import * as util from 'util';
import * as path from 'path';
import * as child_process from 'child_process';
import { promises as fs } from 'fs';
import { Testcase, Problem as _TestConfig } from './problem';
const execw = util.promisify(child_process.exec);
const execr = async function (args) {
return (await execw(args)).stdout.trim();
};
export enum TestResult {
// fail-fast results
ACCEPTED = 0,
UNACCEPTED = -1,
COMPILATION_ERROR = -2,
// detailed results
CPU_TIME_LIMIT_EXCEEDED = 1,
TIME_LIMIT_EXCEEDED = 2,
SPACE_LIMIT_EXCEEDED = 3,
RUNTIME_ERROR = 4,
SYSTEM_ERROR = 5,
WRONG_ANSWER = 6,
}
interface TestReport {
result: TestResult;
used_time?: number;
used_space?: number;
message?: string;
children?: TestReport[];
}
interface TestConfig extends _TestConfig {
filepath: string;
}
function tmpName() : string {
return `/tmp/tmp-et-${(Math.random() * (36**6-36**5) + 36**5).toString(36)}`;
}
class Test {
private config: TestConfig;
private executable: string;
constructor(configPath: PathLike) {
const cfg = YAML.parse(readFileSync(configPath).toString());
this.config = cfg;
this.config.filepath = configPath.toString();
this.config.spaceLimit ??= 128;
this.config.timeLimit ??= 2048;
this.config.testcases ??= [];
if (typeof this.config.solution !== 'string') {
const v = this.config.solution['cpp'];
this.config.solution = typeof v === 'string' ? v : undefined;
}
delete this.config.description;
}
private _defFail(message: string) : TestReport {
if (this.config.target?.includes('test')) {
core.error(`${this.shortPath()}: ${message}`);
return {
result: TestResult.SYSTEM_ERROR,
message,
};
} else {
return {
result: TestResult.ACCEPTED,
message: 'test skipped.'
};
}
}
async test(): Promise<TestReport> {
return await core.group(this.shortPath(), async () => {
core.info('\x1b[1;34m- parse infomation');
console.log(this.config);
if (this.config.target?.includes('!test')) {
return {
result: TestResult.ACCEPTED,
message: 'test skipped.'
};
}
try {
if (this.config.solution) {
this.executable = await this.compile();
} else {
return this._defFail('no solution file provided');
}
} catch (e) {
core.error(`${this.shortPath()}: ${e}`);
return {
result: TestResult.COMPILATION_ERROR,
};
}
let reports;
try {
reports = await this.testAllCases();
} catch (e) {
core.error(`${this.shortPath()}: ${e}`);
return {
result: TestResult.SYSTEM_ERROR,
};
}
let totalTime = 0;
let maxSpace = 0;
let failed = 0;
for (const i of reports) {
if (i.result != TestResult.ACCEPTED) failed++;
totalTime += i.used_time ?? 0;
maxSpace = Math.max(maxSpace, i.used_space ?? 0);
}
const logFn = failed ? core.error : core.info;
const color = failed ? '' : '\x1b[1;32m';
logFn.call(core, `${color}${this.shortPath()}:\n` +
`\t${color}${reports.length - failed} of ${reports.length} tests passed.`);
return {
result: failed ? TestResult.UNACCEPTED : TestResult.ACCEPTED,
used_time: totalTime,
used_space: maxSpace,
children: reports,
} as TestReport;
});
}
private shortPath() : string {
const dir = process.cwd();
return this.config.filepath.replace(`${dir}/`, '');
}
private async compile() : Promise<string> {
core.info('\x1b[1;34m- compile solution file');
const solPath = path.resolve(this.config.solution as string);
const tmpFile = tmpName();
const out = await execr(`g++ ${this.config.config?.compileArgs ?? ''} -o ${tmpFile} ${solPath}`);
console.log(out);
return tmpFile;
}
private async testAllCases(): Promise<TestReport[]> {
core.info('\x1b[1;34m- run tests begin');
if (this.config.testcases.length === 0) {
console.log('no test cases provided.');
return [];
}
const reports: TestReport[] = [];
for (const i in this.config.testcases) {
const kase = this.config.testcases[i];
let report : TestReport;
try {
core.info(`\x1b[1;34m\t- run test #${i}`);
const result = await this.testCase(kase);
report = result;
} catch (e) {
report = {
result: TestResult.SYSTEM_ERROR,
used_time: 0,
used_space: 0,
message: e,
};
}
if (report.result !== TestResult.ACCEPTED) {
core.error(
`${this.shortPath()}: test #${i}: ${TestResult[report.result]}\n` +
JSON.stringify(report, null, 2));
}
reports.push(report);
}
core.info('\x1b[1;34m- run tests end');
return reports;
}
private async testCase(t: Testcase): Promise<TestReport> {
const inf = path.resolve(t.input);
const anf = path.resolve(t.answer);
const ouf = tmpName();
const args = [
`--exe_path=${this.executable}`,
`--input_path=${inf}`,
`--output_path=${ouf}`,
`--error_path=${ouf}`,
`--max_output_size=${134217728}`,
`--max_real_time=${this.config.timeLimit}`,
`--max_memory=${this.config.spaceLimit * 1048576}`
];
let report: TestReport;
try {
const cmd = `sudo ${__dirname}/libjudger.so ${args.join(' ')}`;
const result = JSON.parse(await execr(cmd));
report = {
result: result.result,
message: result,
used_time: result.real_time,
used_space: result.memory,
};
} catch (e) {
return {
result: TestResult.SYSTEM_ERROR,
message: e,
} as TestReport;
}
if (report.result === TestResult.ACCEPTED) {
const ansc = (await fs.readFile(anf)).toString();
const outc = (await fs.readFile(ouf)).toString();
const diff = this.diff(ansc, outc);
if (diff) {
report.result = TestResult.WRONG_ANSWER;
report.message = diff;
}
}
return report;
}
private diff(istr: string, astr: string): string | null {
[istr, astr] = [istr.trim(), astr.trim()];
let ln = 1, col = 1;
for (let i = 0; i < istr.length; i++) {
if (i >= astr.length) {
return 'Unexpected EOF while reading answer.';
}
if (istr[i] !== astr[i]) {
return `Expected ${escape(astr[i])} but found ${escape(istr[i])} at ${ln}:${col}`;
}
if (istr[i] === '\n') [ln, col] = [ln + 1, 1];
else col++;
}
if (istr.length !== astr.length) {
return 'Unexpected EOF while reading output.';
}
return null;
}
}
export default Test;