Skip to content

Commit 36f1c07

Browse files
authored
Improved checking for import, moved removeComments
Improved checking of imports and moved removeComments to separate function, clearly explaining that it's limited to javascript type of comments.
1 parent 84c56a4 commit 36f1c07

1 file changed

Lines changed: 19 additions & 9 deletions

File tree

js/tests/test.mjs

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -150,17 +150,27 @@ ${tests.trim()}`.trim()
150150
}
151151

152152
const loadAndSanitizeSolution = async () => {
153-
const path = `${solutionPath}/${name}.js`
154-
const rawCode = await read(path, "student solution")
155-
156-
// this is a very crude and basic removal of comments
157-
// since checking code is only use to prevent cheating
158-
// it's not that important if it doesn't work 100% of the time.
159-
const code = rawCode.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "").trim()
160-
if (code.includes("import")) fatal("import keyword not allowed")
161-
return { code, rawCode, path }
153+
try {
154+
const path = `${solutionPath}/${name}.js`
155+
const rawCode = await read(path, "student solution")
156+
const sanitizedCode = removeComments(rawCode)
157+
158+
if (sanitizedCode.includes("import ")) { // space is important as it prevents "imported" or "importance" or other words containing "import"
159+
throw new Error("The use of the 'import' keyword is not allowed.")
160+
}
161+
return { code: sanitizedCode, rawCode, path }
162+
} catch (error) {
163+
console.error(error)
164+
}
162165
}
163166

167+
const removeComments = (code) => {
168+
// removes JS single line and multi-line comments only. Not for bash files etc.
169+
// for use with multiple file-types, I suggest writing a removeComments function with language-type as input and then handling accordingly
170+
return code.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "").trim()
171+
}
172+
173+
164174
const runTests = async ({ url, path, code }) => {
165175
const { setup, tests } = await import(url).catch(err =>
166176
fatal(`Unable to execute ${name}, error:\n${stackFmt(err, url)}`),

0 commit comments

Comments
 (0)