1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2025-05-18 12:02:53 +02:00

feat: usage of ESM modules imports (instead of CommonJS) (#14)

This commit is contained in:
Divlo
2022-04-23 18:41:14 +02:00
committed by GitHub
parent c502c17e7c
commit 104c61935a
44 changed files with 6623 additions and 5171 deletions

View File

@ -1,3 +0,0 @@
import { Docker } from '../services/Docker.js'
jest.setTimeout(Docker.MAXIMUM_TIMEOUT_MILLISECONDS)

View File

@ -2,9 +2,11 @@ import { PassThrough } from 'node:stream'
import path from 'node:path'
import fs from 'node:fs'
import tap from 'tap'
import sinon from 'sinon'
import fsMock from 'mock-fs'
import chalk from 'chalk'
import getStream from 'get-stream'
import fsMock from 'mock-fs'
import date from 'date-and-time'
import { cli } from '../../../cli.js'
@ -16,8 +18,8 @@ const challenge = 'aaaa-test-jest'
const inputChallenge = `--challenge=${challenge}`
const inputGitHubUser = `--github-user=${githubUser}`
describe('programming-challenges generate challenge', () => {
beforeEach(() => {
await tap.test('programming-challenges generate challenge', async (t) => {
t.beforeEach(() => {
fsMock(
{
[process.cwd()]: fsMock.load(process.cwd(), { recursive: true })
@ -26,13 +28,14 @@ describe('programming-challenges generate challenge', () => {
)
})
afterEach(() => {
t.afterEach(() => {
fsMock.restore()
jest.clearAllMocks()
sinon.restore()
})
it('succeeds and generate the new challenge', async () => {
console.log = jest.fn()
await t.test('succeeds and generate the new challenge', async (t) => {
sinon.stub(console, 'log').value(() => {})
const consoleLogSpy = sinon.spy(console, 'log')
const dateString = date.format(new Date(), 'D MMMM Y', true)
const stream = new PassThrough()
const exitCode = await cli.run(
@ -44,14 +47,20 @@ describe('programming-challenges generate challenge', () => {
}
)
stream.end()
expect(exitCode).toEqual(0)
t.equal(exitCode, 0)
const challengePath = path.join(process.cwd(), 'challenges', challenge)
const readmePath = path.join(challengePath, 'README.md')
const readmeContent = await fs.promises.readFile(readmePath, { encoding: 'utf-8' })
const successMessage = `${chalk.bold.green('Success:')} created the new challenge at ${challengePath}.`
expect(console.log).toHaveBeenCalledWith(successMessage)
expect(await isExistingPath(challengePath)).toBeTruthy()
expect(readmeContent).toMatch(`# ${challenge}
const readmeContent = await fs.promises.readFile(readmePath, {
encoding: 'utf-8'
})
const successMessage = `${chalk.bold.green(
'Success:'
)} created the new challenge at ${challengePath}.`
t.equal(consoleLogSpy.calledWith(successMessage), true)
t.equal(await isExistingPath(challengePath), true)
t.equal(
readmeContent,
`# ${challenge}
Created by [@${githubUser}](https://github.com/${githubUser}) on ${dateString}.
@ -62,10 +71,11 @@ Description of the challenge...
## Examples
See the \`test\` folder for examples of input/output.
`)
`
)
})
it('fails without options', async () => {
await t.test('fails without options', async (t) => {
const stream = new PassThrough()
const promise = getStream(stream)
const exitCode = await cli.run(input, {
@ -74,13 +84,14 @@ See the \`test\` folder for examples of input/output.
stderr: stream
})
stream.end()
expect(exitCode).toEqual(1)
t.equal(exitCode, 1)
const output = await promise
expect(output).toContain('Unknown Syntax Error')
t.match(output, 'Unknown Syntax Error')
})
it('fails with already existing challenge', async () => {
console.error = jest.fn()
await t.test('fails with already existing challenge', async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const exitCode = await cli.run(
[...input, '--challenge=hello-world', inputGitHubUser],
@ -90,15 +101,19 @@ See the \`test\` folder for examples of input/output.
stderr: stream
}
)
expect(console.error).toHaveBeenCalledWith(
`${chalk.bold.red('Error:')} The challenge already exists: hello-world.`
)
stream.end()
expect(exitCode).toEqual(1)
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
`${chalk.bold.red('Error:')} The challenge already exists: hello-world.`
),
true
)
})
it('fails with invalid challenge name', async () => {
console.error = jest.fn()
await t.test('fails with invalid challenge name', async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const exitCode = await cli.run(
[...input, '--challenge=hEllO-world', inputGitHubUser],
@ -109,9 +124,12 @@ See the \`test\` folder for examples of input/output.
}
)
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
`${chalk.bold.red('Error:')} Invalid challenge name.`
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
`${chalk.bold.red('Error:')} Invalid challenge name.`
),
true
)
})
})

View File

@ -2,9 +2,11 @@ import { PassThrough } from 'node:stream'
import path from 'node:path'
import fs from 'node:fs'
import tap from 'tap'
import sinon from 'sinon'
import fsMock from 'mock-fs'
import chalk from 'chalk'
import getStream from 'get-stream'
import fsMock from 'mock-fs'
import date from 'date-and-time'
import { cli } from '../../../cli.js'
@ -20,8 +22,8 @@ const inputGitHubUser = `--github-user=${githubUser}`
const inputLanguage = `--language=${language}`
const inputSolution = `--solution=${solution}`
describe('programming-challenges generate solution', () => {
beforeEach(() => {
await tap.test('programming-challenges generate solution', async (t) => {
t.beforeEach(() => {
fsMock(
{
[process.cwd()]: fsMock.load(process.cwd(), { recursive: true })
@ -30,13 +32,14 @@ describe('programming-challenges generate solution', () => {
)
})
afterEach(() => {
t.afterEach(() => {
fsMock.restore()
jest.clearAllMocks()
sinon.restore()
})
it('succeeds and generate the new solution', async () => {
console.log = jest.fn()
await t.test('succeeds and generate the new solution', async (t) => {
sinon.stub(console, 'log').value(() => {})
const consoleLogSpy = sinon.spy(console, 'log')
const dateString = date.format(new Date(), 'D MMMM Y', true)
const stream = new PassThrough()
const exitCode = await cli.run(
@ -48,26 +51,47 @@ describe('programming-challenges generate solution', () => {
}
)
stream.end()
expect(exitCode).toEqual(0)
const solutionPath = path.join(process.cwd(), 'challenges', challenge, 'solutions', language, solution)
t.equal(exitCode, 0)
const solutionPath = path.join(
process.cwd(),
'challenges',
challenge,
'solutions',
language,
solution
)
const readmePath = path.join(solutionPath, 'README.md')
const readmeContent = await fs.promises.readFile(readmePath, { encoding: 'utf-8' })
const successMessage = `${chalk.bold.green('Success:')} created the new solution at ${solutionPath}.`
expect(console.log).toHaveBeenCalledWith(successMessage)
expect(await isExistingPath(solutionPath)).toBeTruthy()
expect(readmeContent).toMatch(`# ${challenge}/${language}/${solution}
const readmeContent = await fs.promises.readFile(readmePath, {
encoding: 'utf-8'
})
const successMessage = `${chalk.bold.green(
'Success:'
)} created the new solution at ${solutionPath}.`
t.equal(consoleLogSpy.calledWith(successMessage), true)
t.equal(await isExistingPath(solutionPath), true)
t.equal(
readmeContent,
`# ${challenge}/${language}/${solution}
Created by [@${githubUser}](https://github.com/${githubUser}) on ${dateString}.
`)
`
)
})
it("fails with challenges that doesn't exist", async () => {
console.error = jest.fn()
await t.test("fails with challenges that doesn't exist", async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const invalidChallenge = 'aaa-jest-challenge'
const inputInvalidChallenge = `--challenge=${invalidChallenge}`
const exitCode = await cli.run(
[...input, inputInvalidChallenge, inputGitHubUser, inputLanguage, inputSolution],
[
...input,
inputInvalidChallenge,
inputGitHubUser,
inputLanguage,
inputSolution
],
{
stdin: process.stdin,
stdout: stream,
@ -75,19 +99,30 @@ Created by [@${githubUser}](https://github.com/${githubUser}) on ${dateString}.
}
)
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
chalk.bold.red('Error:') + ` The challenge doesn't exist yet: ${invalidChallenge}.`
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
chalk.bold.red('Error:') +
` The challenge doesn't exist yet: ${invalidChallenge}.`
),
true
)
})
it('fails with solution that already exist', async () => {
console.error = jest.fn()
await t.test('fails with solution that already exist', async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const invalidSolution = 'function'
const inputInvalidSolution = `--solution=${invalidSolution}`
const exitCode = await cli.run(
[...input, inputChallenge, inputGitHubUser, inputLanguage, inputInvalidSolution],
[
...input,
inputChallenge,
inputGitHubUser,
inputLanguage,
inputInvalidSolution
],
{
stdin: process.stdin,
stdout: stream,
@ -95,19 +130,30 @@ Created by [@${githubUser}](https://github.com/${githubUser}) on ${dateString}.
}
)
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
chalk.bold.red('Error:') + ` The solution already exists: ${invalidSolution}.`
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
chalk.bold.red('Error:') +
` The solution already exists: ${invalidSolution}.`
),
true
)
})
it('fails with invalid language', async () => {
console.error = jest.fn()
await t.test('fails with invalid language', async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const invalidLanguage = 'invalid'
const inputInvalidLanguage = `--language=${invalidLanguage}`
const exitCode = await cli.run(
[...input, inputChallenge, inputGitHubUser, inputSolution, inputInvalidLanguage],
[
...input,
inputChallenge,
inputGitHubUser,
inputSolution,
inputInvalidLanguage
],
{
stdin: process.stdin,
stdout: stream,
@ -115,13 +161,17 @@ Created by [@${githubUser}](https://github.com/${githubUser}) on ${dateString}.
}
)
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
chalk.bold.red('Error:') + ' This programming language is not supported yet.'
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
chalk.bold.red('Error:') +
' This programming language is not supported yet.'
),
true
)
})
it('fails without options', async () => {
await t.test('fails without options', async () => {
const stream = new PassThrough()
const promise = getStream(stream)
const exitCode = await cli.run(input, {
@ -130,8 +180,8 @@ Created by [@${githubUser}](https://github.com/${githubUser}) on ${dateString}.
stderr: stream
})
stream.end()
expect(exitCode).toEqual(1)
t.equal(exitCode, 1)
const output = await promise
expect(output).toContain('Unknown Syntax Error')
t.match(output, 'Unknown Syntax Error')
})
})

View File

@ -1,5 +1,7 @@
import { PassThrough } from 'node:stream'
import tap from 'tap'
import sinon from 'sinon'
import chalk from 'chalk'
import { cli } from '../../../cli.js'
@ -13,13 +15,14 @@ const inputChallenge = `--challenge=${challenge}`
const inputLanguage = `--language=${language}`
const inputSolution = `--solution=${solution}`
describe('programming-challenges run test', () => {
afterEach(() => {
jest.clearAllMocks()
await tap.test('programming-challenges run test', async (t) => {
t.afterEach(() => {
sinon.restore()
})
it('succeeds', async () => {
console.log = jest.fn()
await t.test('succeeds', async (t) => {
sinon.stub(console, 'log').value(() => {})
const consoleLogSpy = sinon.spy(console, 'log')
const stream = new PassThrough()
const exitCode = await cli.run(
[...input, inputChallenge, inputSolution, inputLanguage],
@ -30,14 +33,25 @@ describe('programming-challenges run test', () => {
}
)
stream.end()
expect(exitCode).toEqual(0)
expect(console.log).toHaveBeenNthCalledWith(2, `${chalk.bold('Name:')} ${challenge}/${language}/${solution}\n`)
expect(console.log).toHaveBeenNthCalledWith(4, `${chalk.bold('Tests:')} ${chalk.bold.green('3 passed')}, 3 total`)
expect(console.log).toHaveBeenNthCalledWith(6, Test.SUCCESS_MESSAGE)
t.equal(exitCode, 0)
t.equal(
consoleLogSpy.calledWith(
`${chalk.bold('Name:')} ${challenge}/${language}/${solution}\n`
),
true
)
t.equal(
consoleLogSpy.calledWith(
`${chalk.bold('Tests:')} ${chalk.bold.green('3 passed')}, 3 total`
),
true
)
t.equal(consoleLogSpy.calledWith(Test.SUCCESS_MESSAGE), true)
})
it("fails with solution that doesn't exist", async () => {
console.error = jest.fn()
await t.test("fails with solution that doesn't exist", async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const invalidSolution = 'invalid'
const inputInvalidSolution = `--solution=${invalidSolution}`
@ -50,14 +64,18 @@ describe('programming-challenges run test', () => {
}
)
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
chalk.bold.red('Error:') + ' The solution was not found.'
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
chalk.bold.red('Error:') + ' The solution was not found.'
),
true
)
})
it('fails with invalid language', async () => {
console.error = jest.fn()
await t.test('fails with invalid language', async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const invalidLanguage = 'invalid'
const inputInvalidLanguage = `--language=${invalidLanguage}`
@ -70,14 +88,19 @@ describe('programming-challenges run test', () => {
}
)
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
chalk.bold.red('Error:') + ' This programming language is not supported yet.'
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
chalk.bold.red('Error:') +
' This programming language is not supported yet.'
),
true
)
})
it('fails without options', async () => {
console.error = jest.fn()
await t.test('fails without options', async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const exitCode = await cli.run(input, {
stdin: process.stdin,
@ -85,9 +108,14 @@ describe('programming-challenges run test', () => {
stderr: stream
})
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
`${chalk.bold.red('Error:')} You must specify all the options (\`--challenge\`, \`--solution\`, \`--language\`).`
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
`${chalk.bold.red(
'Error:'
)} You must specify all the options (\`--challenge\`, \`--solution\`, \`--language\`).`
),
true
)
})
})

View File

@ -5,7 +5,4 @@ import { cli } from './cli.js'
const [, , ...arguments_] = process.argv
cli.runExit(arguments_, Cli.defaultContext).catch(() => {
console.error('Error occurred...')
process.exit(1)
})
await cli.runExit(arguments_, Cli.defaultContext)

View File

@ -1,5 +1,5 @@
import path from 'node:path'
import fs from 'node:fs'
import { fileURLToPath } from 'node:url'
import validateProjectName from 'validate-npm-package-name'
@ -21,7 +21,7 @@ export class Challenge implements ChallengeOptions {
constructor (options: ChallengeOptions) {
const { name } = options
this.name = name
this.path = path.join(__dirname, '..', '..', 'challenges', name)
this.path = fileURLToPath(new URL(`../../challenges/${name}`, import.meta.url))
}
static async generate (options: GenerateChallengeOptions): Promise<Challenge> {

View File

@ -1,4 +1,4 @@
import execa from 'execa'
import { execaCommand } from 'execa'
import ora from 'ora'
import ms from 'ms'
@ -11,7 +11,7 @@ export class Docker {
public async build (): Promise<void> {
const loader = ora('Building the Docker image').start()
try {
await execa.command(`docker build --tag=${Docker.CONTAINER_TAG} ./`)
await execaCommand(`docker build --tag=${Docker.CONTAINER_TAG} ./`)
loader.stop()
} catch (error) {
loader.fail()
@ -20,7 +20,7 @@ export class Docker {
}
public async run (input: string): Promise<string> {
const subprocess = execa.command(
const subprocess = execaCommand(
`docker run --interactive --rm ${Docker.CONTAINER_TAG}`,
{
input

View File

@ -1,4 +1,4 @@
import execa from 'execa'
import { execaCommand } from 'execa'
import { Challenge } from './Challenge.js'
import { Solution } from './Solution.js'
@ -35,7 +35,7 @@ export class GitAffected implements GitAffectedOptions {
head: string
): Promise<string[]> {
try {
const { stdout } = await execa.command(
const { stdout } = await execaCommand(
`git diff --name-only --relative ${base} ${head}`
)
return this.parseGitOutput(stdout)
@ -50,7 +50,7 @@ export class GitAffected implements GitAffectedOptions {
public async getLatestPushedCommit (): Promise<string> {
const latestCommit = this.isContinuousIntegration ? '~1' : ''
const { stdout } = await execa.command(`git rev-parse origin/master${latestCommit}`)
const { stdout } = await execaCommand(`git rev-parse origin/master${latestCommit}`)
return stdout
}

View File

@ -1,3 +1,4 @@
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import fs from 'node:fs'
@ -122,12 +123,7 @@ export class Solution implements SolutionOptions {
static async getManyByProgrammingLanguages (programmingLanguages?: string[]): Promise<Solution[]> {
const languages = programmingLanguages ?? await template.getProgrammingLanguages()
const challengesPath = path.join(
__dirname,
'..',
'..',
'challenges'
)
const challengesPath = fileURLToPath(new URL('../../challenges', import.meta.url))
const challenges = await fs.promises.readdir(challengesPath)
const paths: string[] = []
for (const challenge of challenges) {

View File

@ -1,12 +1,15 @@
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import fs from 'node:fs'
import { replaceInFile } from 'replace-in-file'
import replaceInFileDefault from 'replace-in-file'
import date from 'date-and-time'
import { copyDirectory } from '../utils/copyDirectory.js'
const TEMPLATE_PATH = path.join(__dirname, '..', '..', 'templates')
const { replaceInFile } = replaceInFileDefault
const TEMPLATE_PATH = fileURLToPath(new URL('../../templates', import.meta.url))
const TEMPLATE_DOCKER_PATH = path.join(TEMPLATE_PATH, 'docker')
const TEMPLATE_CHALLENGE_PATH = path.join(TEMPLATE_PATH, 'challenge')
const TEMPLATE_SOLUTION_PATH = path.join(TEMPLATE_PATH, 'solution')
@ -38,7 +41,7 @@ export interface ReplaceInDestinationOptions {
}
class Template {
private getDescription (githubUser?: string): string {
private getDescription(githubUser?: string): string {
const dateString = date.format(new Date(), 'D MMMM Y', true)
let description = 'Created'
if (githubUser != null) {
@ -48,7 +51,9 @@ class Template {
return description
}
private async replaceInDestination (options: ReplaceInDestinationOptions): Promise<void> {
private async replaceInDestination(
options: ReplaceInDestinationOptions
): Promise<void> {
const { name, description, destination } = options
const readmePath = path.join(destination, 'README.md')
await replaceInFile({
@ -63,15 +68,24 @@ class Template {
})
}
public async docker (options: TemplateDockerOptions): Promise<void> {
public async docker(options: TemplateDockerOptions): Promise<void> {
const { programmingLanguage, destination } = options
const sourcePath = path.join(TEMPLATE_DOCKER_PATH, programmingLanguage)
await copyDirectory(sourcePath, destination)
}
public async solution (options: TemplateSolutionOptions): Promise<void> {
const { destination, githubUser, name, challengeName, programmingLanguageName } = options
const templateLanguagePath = path.join(TEMPLATE_SOLUTION_PATH, programmingLanguageName)
public async solution(options: TemplateSolutionOptions): Promise<void> {
const {
destination,
githubUser,
name,
challengeName,
programmingLanguageName
} = options
const templateLanguagePath = path.join(
TEMPLATE_SOLUTION_PATH,
programmingLanguageName
)
await this.verifySupportedProgrammingLanguage(programmingLanguageName)
await fs.promises.mkdir(destination, { recursive: true })
await copyDirectory(templateLanguagePath, destination)
@ -83,7 +97,7 @@ class Template {
})
}
public async challenge (options: TemplateChallengeOptions): Promise<void> {
public async challenge(options: TemplateChallengeOptions): Promise<void> {
const { destination, githubUser, name } = options
await copyDirectory(TEMPLATE_CHALLENGE_PATH, destination)
await this.replaceInDestination({
@ -93,12 +107,14 @@ class Template {
})
}
public async getProgrammingLanguages (): Promise<string[]> {
public async getProgrammingLanguages(): Promise<string[]> {
const languages = await fs.promises.readdir(TEMPLATE_SOLUTION_PATH)
return languages.filter(language => language !== 'base')
return languages.filter((language) => language !== 'base')
}
public async verifySupportedProgrammingLanguage (language: string): Promise<void> {
public async verifySupportedProgrammingLanguage(
language: string
): Promise<void> {
const languages = await this.getProgrammingLanguages()
if (!languages.includes(language)) {
throw new Error('This programming language is not supported yet.')

View File

@ -1,104 +1,125 @@
import tap from 'tap'
import { Challenge } from '../Challenge.js'
import { GitAffected } from '../GitAffected.js'
import { Solution } from '../Solution.js'
const gitAffected = new GitAffected({ isContinuousIntegration: false })
describe('services/GitAffected - parseGitOutput', () => {
it('returns the right output array', () => {
expect(gitAffected.parseGitOutput('1.txt\n 2.txt ')).toEqual(['1.txt', '2.txt'])
})
})
describe('services/GitAffected - getAffectedSolutionsFromFiles', () => {
it('returns the affected solutions', async () => {
const files = [
'challenges/hello-world/solutions/javascript/function/solution.js',
'challenges/is-palindrome/solutions/c/function/input.c'
]
const solutions = await gitAffected.getAffectedSolutionsFromFiles(files)
expect(solutions).toEqual([
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'javascript'
}),
new Solution({
challenge: new Challenge({ name: 'is-palindrome' }),
name: 'function',
programmingLanguageName: 'c'
})
])
await tap.test('services/GitAffected', async (t) => {
await t.test('parseGitOutput', async (t) => {
await t.test('returns the right output array', async (t) => {
t.same(gitAffected.parseGitOutput('1.txt\n 2.txt '), ['1.txt', '2.txt'])
})
})
it('returns the affected solutions from Dockerfile changes', async () => {
const files = ['templates/docker/javascript/Dockerfile']
const solutions = await gitAffected.getAffectedSolutionsFromFiles(files)
expect(solutions[0]).toEqual(
new Solution({
challenge: new Challenge({ name: 'camel-case' }),
name: 'function',
programmingLanguageName: 'javascript'
})
)
expect(solutions[1]).toEqual(
new Solution({
challenge: new Challenge({ name: 'first-non-repeating-character' }),
name: 'function',
programmingLanguageName: 'javascript'
})
)
})
await t.test('getAffectedSolutionsFromFiles', async (t) => {
await t.test('returns the affected solutions', async (t) => {
const files = [
'challenges/hello-world/solutions/javascript/function/solution.js',
'challenges/is-palindrome/solutions/c/function/input.c'
]
const solutions = await gitAffected.getAffectedSolutionsFromFiles(files)
t.same(solutions, [
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'javascript'
}),
new Solution({
challenge: new Challenge({ name: 'is-palindrome' }),
name: 'function',
programmingLanguageName: 'c'
})
])
})
it('returns the affected solutions from Docker template changes', async () => {
const files = ['templates/docker/javascript/package.json']
const solutions = await gitAffected.getAffectedSolutionsFromFiles(files)
expect(solutions[0]).toEqual(
new Solution({
challenge: new Challenge({ name: 'camel-case' }),
name: 'function',
programmingLanguageName: 'javascript'
})
await t.test(
'returns the affected solutions from Dockerfile changes',
async (t) => {
const files = ['templates/docker/javascript/Dockerfile']
const solutions = await gitAffected.getAffectedSolutionsFromFiles(files)
t.same(
solutions[0],
new Solution({
challenge: new Challenge({ name: 'camel-case' }),
name: 'function',
programmingLanguageName: 'javascript'
})
)
t.same(
solutions[1],
new Solution({
challenge: new Challenge({ name: 'first-non-repeating-character' }),
name: 'function',
programmingLanguageName: 'javascript'
})
)
}
)
expect(solutions[1]).toEqual(
new Solution({
challenge: new Challenge({ name: 'first-non-repeating-character' }),
name: 'function',
programmingLanguageName: 'javascript'
})
)
})
it('returns the affected solutions from input/output files', async () => {
const files = ['challenges/hello-world/test/1/input.txt']
const solutions = await gitAffected.getAffectedSolutionsFromFiles(files)
expect(solutions[0]).toEqual(
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'c'
})
await t.test(
'returns the affected solutions from Docker template changes',
async (t) => {
const files = ['templates/docker/javascript/package.json']
const solutions = await gitAffected.getAffectedSolutionsFromFiles(files)
t.same(
solutions[0],
new Solution({
challenge: new Challenge({ name: 'camel-case' }),
name: 'function',
programmingLanguageName: 'javascript'
})
)
t.same(
solutions[1],
new Solution({
challenge: new Challenge({ name: 'first-non-repeating-character' }),
name: 'function',
programmingLanguageName: 'javascript'
})
)
}
)
expect(solutions[1]).toEqual(
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'cpp'
})
)
expect(solutions[2]).toEqual(
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'cs'
})
)
expect(solutions[3]).toEqual(
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'dart'
})
await t.test(
'returns the affected solutions from input/output files',
async (t) => {
const files = ['challenges/hello-world/test/1/input.txt']
const solutions = await gitAffected.getAffectedSolutionsFromFiles(files)
t.same(
solutions[0],
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'c'
})
)
t.same(
solutions[1],
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'cpp'
})
)
t.same(
solutions[2],
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'cs'
})
)
t.same(
solutions[3],
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'dart'
})
)
}
)
})
})

View File

@ -1,43 +1,39 @@
import fs from 'node:fs'
import tap from 'tap'
import fsMock from 'mock-fs'
import { copyDirectory } from '../copyDirectory.js'
describe('utils/copyDirectory', () => {
afterEach(() => {
await tap.test('utils/copyDirectory', async (t) => {
t.afterEach(() => {
fsMock.restore()
})
it('copy the files', async () => {
await t.test('copy the files', async (t) => {
fsMock({
'/source': {
'default.png': '',
'index.ts': '',
'.npmignore': ''
'index.ts': ''
},
'/destination': {}
}, { createCwd: false })
})
let destinationDirectoryContent = await fs.promises.readdir('/destination')
let sourceDirectoryContent = await fs.promises.readdir('/source')
expect(destinationDirectoryContent.length).toEqual(0)
expect(sourceDirectoryContent.length).toEqual(3)
t.equal(destinationDirectoryContent.length, 0)
t.equal(sourceDirectoryContent.length, 2)
await copyDirectory('/source', '/destination')
destinationDirectoryContent = await fs.promises.readdir('/destination')
sourceDirectoryContent = await fs.promises.readdir('/source')
expect(destinationDirectoryContent.length).toEqual(3)
expect(sourceDirectoryContent.length).toEqual(3)
expect(destinationDirectoryContent).toEqual(
expect.arrayContaining(['default.png', 'index.ts', '.npmignore'])
)
expect(sourceDirectoryContent).toEqual(
expect.arrayContaining(['default.png', 'index.ts', '.npmignore'])
)
t.equal(destinationDirectoryContent.length, 2)
t.equal(sourceDirectoryContent.length, 2)
t.strictSame(destinationDirectoryContent, ['default.png', 'index.ts'])
t.strictSame(sourceDirectoryContent, ['default.png', 'index.ts'])
})
it('copy the files and folders recursively', async () => {
await t.test('copy the files and folders recursively', async (t) => {
fsMock({
'/source': {
'random-folder': {
@ -46,11 +42,10 @@ describe('utils/copyDirectory', () => {
'mycode.ts': ''
}
},
'index.ts': '',
'.npmignore': ''
'index.ts': ''
},
'/destination': {}
}, { createCwd: false })
})
let destinationDirectoryContent = await fs.promises.readdir('/destination')
let sourceDirectoryContent = await fs.promises.readdir('/source')
@ -58,33 +53,27 @@ describe('utils/copyDirectory', () => {
let secondRandomFolderContent = await fs.promises.readdir(
'/source/random-folder/second-random-folder'
)
expect(randomFolderContent.length).toEqual(2)
expect(secondRandomFolderContent.length).toEqual(1)
expect(destinationDirectoryContent.length).toEqual(0)
expect(sourceDirectoryContent.length).toEqual(3)
t.equal(randomFolderContent.length, 2)
t.equal(secondRandomFolderContent.length, 1)
t.equal(destinationDirectoryContent.length, 0)
t.equal(sourceDirectoryContent.length, 2)
await copyDirectory('/source', '/destination')
destinationDirectoryContent = await fs.promises.readdir('/destination')
sourceDirectoryContent = await fs.promises.readdir('/source')
randomFolderContent = await fs.promises.readdir('/destination/random-folder')
randomFolderContent = await fs.promises.readdir(
'/destination/random-folder'
)
secondRandomFolderContent = await fs.promises.readdir(
'/destination/random-folder/second-random-folder'
)
expect(destinationDirectoryContent.length).toEqual(3)
expect(sourceDirectoryContent.length).toEqual(3)
expect(destinationDirectoryContent).toEqual(
expect.arrayContaining(['random-folder', 'index.ts', '.npmignore'])
)
expect(sourceDirectoryContent).toEqual(
expect.arrayContaining(['random-folder', 'index.ts', '.npmignore'])
)
expect(randomFolderContent.length).toEqual(2)
expect(secondRandomFolderContent.length).toEqual(1)
expect(randomFolderContent).toEqual(
expect.arrayContaining(['default.png', 'second-random-folder'])
)
expect(secondRandomFolderContent).toEqual(
expect.arrayContaining(['mycode.ts'])
)
t.equal(destinationDirectoryContent.length, 2)
t.equal(sourceDirectoryContent.length, 2)
t.strictSame(destinationDirectoryContent, ['index.ts', 'random-folder'])
t.strictSame(sourceDirectoryContent, ['index.ts', 'random-folder'])
t.equal(randomFolderContent.length, 2)
t.equal(secondRandomFolderContent.length, 1)
t.strictSame(randomFolderContent, ['default.png', 'second-random-folder'])
t.strictSame(secondRandomFolderContent, ['mycode.ts'])
})
})

View File

@ -1,6 +1,7 @@
import fs from 'node:fs'
import fsMock from 'mock-fs'
import tap from 'tap'
import {
TEMPORARY_PATH,
@ -8,20 +9,30 @@ import {
} from '../createTemporaryEmptyFolder.js'
import { isExistingPath } from '../isExistingPath.js'
describe('utils/createTemporaryEmptyFolder', () => {
afterEach(() => {
await tap.test('utils/createTemporaryEmptyFolder', async (t) => {
t.afterEach(() => {
fsMock.restore()
})
it('should remove and create again the temporary folder', async () => {
fsMock({
[TEMPORARY_PATH]: {
'file.txt': ''
}
}, { createCwd: false })
expect(await isExistingPath(TEMPORARY_PATH)).toBeTruthy()
expect((await fs.promises.readdir(TEMPORARY_PATH)).length).toEqual(1)
await t.test('should create the temporary folder', async (t) => {
fsMock({})
t.equal(await isExistingPath(TEMPORARY_PATH), false)
await createTemporaryEmptyFolder()
expect((await fs.promises.readdir(TEMPORARY_PATH)).length).toEqual(0)
t.equal(await isExistingPath(TEMPORARY_PATH), true)
})
await t.test(
'should remove and create again the temporary folder',
async (t) => {
fsMock({
[TEMPORARY_PATH]: {
'file.txt': ''
}
})
t.equal(await isExistingPath(TEMPORARY_PATH), true)
t.equal((await fs.promises.readdir(TEMPORARY_PATH)).length, 1)
await createTemporaryEmptyFolder()
t.equal((await fs.promises.readdir(TEMPORARY_PATH)).length, 0)
}
)
})

View File

@ -1,23 +1,24 @@
import fsMock from 'mock-fs'
import tap from 'tap'
import { isExistingPath } from '../isExistingPath.js'
describe('utils/isExistingFile', () => {
afterEach(() => {
await tap.test('utils/isExistingPath', async (t) => {
t.afterEach(() => {
fsMock.restore()
})
it('should return true if the file exists', async () => {
await t.test('should return true if the file exists', async () => {
fsMock({
'/file.txt': ''
}, { createCwd: false })
expect(await isExistingPath('/file.txt')).toBeTruthy()
})
t.equal(await isExistingPath('/file.txt'), true)
})
it("should return false if the file doesn't exists", async () => {
await t.test("should return false if the file doesn't exists", async () => {
fsMock({
'/file.txt': ''
}, { createCwd: false })
expect(await isExistingPath('/randomfile.txt')).toBeFalsy()
})
t.equal(await isExistingPath('/randomfile.txt'), false)
})
})

View File

@ -1,7 +1,7 @@
import fs from 'node:fs'
import path from 'node:path'
export async function copyDirectory (
export async function copyDirectory(
source: string,
destination: string
): Promise<void> {

View File

@ -1,13 +1,14 @@
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import fs from 'node:fs'
import { isExistingPath } from '../utils/isExistingPath.js'
export const TEMPORARY_PATH = path.join(__dirname, '..', '..', 'temp')
export const TEMPORARY_URL = new URL('../../temp', import.meta.url)
export const TEMPORARY_PATH = fileURLToPath(TEMPORARY_URL)
export const createTemporaryEmptyFolder = async (): Promise<void> => {
if (await isExistingPath(TEMPORARY_PATH)) {
await fs.promises.rm(TEMPORARY_PATH, { recursive: true, force: true })
await fs.promises.rm(TEMPORARY_URL, { recursive: true, force: true })
}
await fs.promises.mkdir(TEMPORARY_PATH)
await fs.promises.mkdir(TEMPORARY_URL)
}