Skip to content
Merged
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
10 changes: 9 additions & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,15 @@
"linter": {
"enabled": true,
"rules": {
"recommended": true
"recommended": true,
"suspicious": {
"noConsole": {
"level": "error",
"options": {
"allow": ["info","warn", "error"]
}
}
}
}
},
"javascript": {
Expand Down
3 changes: 1 addition & 2 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,5 @@
"semantic-release": "^24.2.3",
"ts-jest": "^29.3.1",
"typescript": "^5.8.3"
},
"packageManager": "yarn@4.5.0"
}
}
10 changes: 4 additions & 6 deletions packages/core/src/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ function normalizeArrayMatcher(
}

function normalizePath(request: FixtureRequestType) {
if (!request.options?.path?.allowRegex) {
request.path = decodeURI(request.path)
}

// extract query from path is needed and move it in query property
const indexQueryString = request.path.indexOf('?')

Expand All @@ -117,12 +121,6 @@ function normalizePath(request: FixtureRequestType) {
request.query = query
}
}

const pathOptions = request.options?.path

if (!pathOptions || (!pathOptions.allowRegex && !pathOptions.disableEncodeURI)) {
request.path = encodeURI(request.path)
}
}

function normalizeFixture(fixture: FixtureType, configuration: ConfigurationType): NormalizedFixtureType {
Expand Down
6 changes: 1 addition & 5 deletions packages/core/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,9 @@ export const FixtureRequestOptionsSchema = z
path: z
.object({
allowRegex: z.boolean(),
disableEncodeURI: z.boolean(),
})
.strict()
.partial()
.refine((value) => !(value.allowRegex === true && value.disableEncodeURI === true), {
message: 'Cannot use options.path.allowRegex and options.path.disableEncodeURI together',
}),
.partial(),
method: z
.object({
allowRegex: z.boolean(),
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export function matchServiceRequestAgainstFixtures(
coreRequest: CoreRequest,
end: (coreResponse: CoreResponse) => void,
): boolean {
if (coreRequest.method === 'OPTIONS' && service.configuration.cors === '*') {
if (coreRequest.method === 'OPTIONS' && hasServiceCors(service)) {
end({
status: 200,
headers: corsAllowAllHeaders,
Expand Down Expand Up @@ -199,7 +199,7 @@ export function matchServiceRequestAgainstFixtures(
filepath: response.filepath ?? '',
}

if (service.configuration.cors === '*') {
if (hasServiceCors(service)) {
Object.assign(coreResponse.headers, corsAllowAllHeaders)
}

Expand Down
6 changes: 2 additions & 4 deletions packages/dynamock/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"release": "semantic-release",
"test": "yarn test:ts",
"test:common": "NODE_OPTIONS='--enable-source-maps --experimental-vm-modules' jest",
"test:ts": "yarn test:common --config=./test/config/jest.config.js --coverage",
"test:ts": "yarn test:common --config=./test/config/jest.config.js --coverage --runInBand",
"coverage:permissions": "chmod -R 777 ./coverage"
},
"engines": {
Expand All @@ -46,9 +46,7 @@
"@types/supertest": "^6.0.3",
"jest": "^29.7.0",
"semantic-release": "^24.2.3",
"supertest": "^7.1.0",
"ts-jest": "^29.3.1",
"typescript": "^5.8.3"
},
"packageManager": "yarn@4.5.0"
}
}
4 changes: 2 additions & 2 deletions packages/dynamock/src/bin/dynamock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ if (!port) {
const server = createServer()

server.listen(Number(port), host, () => {
console.log(`dynamock is running on port ${port}...`)
console.info(`dynamock is running on port ${port}...`)
})

function shutDown() {
console.log('dynamock is shutting down gracefully')
console.info('dynamock is shutting down gracefully')
server.close(() => {
process.exit(0)
})
Expand Down
2 changes: 1 addition & 1 deletion packages/dynamock/src/mapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { Request } from 'express'
export function mapToCoreRequest(req: Request) {
const coreRequest: CoreRequest = {
origin: `${req.protocol}://${req.get('host')}`,
path: req.path,
path: decodeURI(req.path),
method: req.method,
headers: Object.entries(req.headers).reduce<{ [key in string]: string }>((acc, [headerKey, headerValue]) => {
if (headerValue) {
Expand Down
6 changes: 5 additions & 1 deletion packages/dynamock/test/bin.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { afterEach, beforeEach, describe, expect, test } from '@jest/globals'
import { afterEach, beforeAll, beforeEach, describe, expect, test } from '@jest/globals'
import { spawn, type ChildProcess } from 'node:child_process'
import { getTestFiles, wrapError } from '@dynamock/test-cases'
import { waitPortFree, waitPortUsed } from './config/utils.js'
Expand All @@ -10,6 +10,10 @@ describe('bin integration tests', () => {
const port = 3000
let process: ChildProcess

beforeAll(async () => {
await waitPortFree(port)
})

beforeEach(async () => {
process = spawn('dynamock', [String(port)] /*, {stdio: 'inherit'}*/)
await waitPortUsed(port)
Expand Down
54 changes: 28 additions & 26 deletions packages/dynamock/test/config/utils.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,43 @@
import { createServer } from 'node:net'
import { spawn } from 'node:child_process'

const isPortUsed = async (port: number): Promise<boolean> => {
return new Promise((resolve) => {
const server = createServer()
server.once('error', (err: Error) => {
server.close(() => {
resolve('code' in err && err.code === 'EADDRINUSE')
})
const lsof = spawn('lsof', ['-i', `:${port}`])

let output = ''
lsof.stdout.on('data', (data) => {
output += data.toString()
})

lsof.stderr.on('data', (data) => {
console.error(`isPortUsed error: ${data}`)
})
server.once('listening', () => {
server.close(() => {
resolve(false)
})

lsof.on('close', () => {
const inUse = output.trim().length > 0
resolve(inUse)
})
server.listen(port)
})
}

export function waitPortUsed(port: number, retry = 50, reverse = false) {
return new Promise((resolve) => {
const loop = async () => {
const isUsed = await isPortUsed(port)
export async function waitPortUsed(port: number, retry = 10, timeout = 2000, waitUsed = true) {
const startTime = Date.now()

// @ts-ignore
if (!(isUsed ^ !reverse)) {
return
}
while (true) {
const isUsed = await isPortUsed(port)

// @ts-ignore
await new Promise((resolve) => setTimeout(resolve, retry))
return loop()
if (isUsed === waitUsed) {
return
}

loop().then(resolve)
})
if (Date.now() - startTime > timeout) {
throw new Error(`Timeout waiting for port ${port} to be ${waitUsed ? 'used' : 'free'}`)
}

await new Promise((resolve) => setTimeout(resolve, retry))
}
}

export function waitPortFree(port: number, retry?: number) {
return waitPortUsed(port, retry, true)
export function waitPortFree(port: number, retry?: number, timeout?: number) {
return waitPortUsed(port, retry, timeout, false)
}
83 changes: 0 additions & 83 deletions packages/dynamock/test/integrations.spec.ts

This file was deleted.

5 changes: 2 additions & 3 deletions packages/puppeteer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"node": ">=20"
},
"dependencies": {
"dynamock": "workspace:*"
"@dynamock/core": "workspace:*"
},
"devDependencies": {
"@dynamock/test-cases": "workspace:*",
Expand All @@ -40,6 +40,5 @@
"semantic-release": "^24.2.3",
"ts-jest": "^29.3.1",
"typescript": "^5.8.3"
},
"packageManager": "yarn@4.5.0"
}
}
6 changes: 3 additions & 3 deletions packages/puppeteer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import {
matchServiceRequestAgainstFixtures,
resetService,
updateServiceConfiguration,
type ConfigurationType,
} from '@dynamock/core'
import { URLSearchParams } from 'node:url'
import type { ConfigurationType } from '@dynamock/core'
import { URL } from 'node:url'
import { readFileSync } from 'node:fs'

Expand Down Expand Up @@ -55,7 +55,7 @@ function mapToCoreRequest(request: HTTPRequest): CoreRequest {

return {
origin: parsedUrl.origin,
path: parsedUrl.pathname,
path: decodeURI(parsedUrl.pathname),
method: request.method(),
body,
headers: headersWithoutCookie,
Expand All @@ -72,7 +72,7 @@ function mapToFixtureType(fixture: FixturePuppeteerType): FixtureType {
try {
const parsedUrl = new URL(url)
origin = parsedUrl.origin
path = parsedUrl.toString().replace(parsedUrl.origin, '')
path = decodeURI(parsedUrl.toString()).replace(parsedUrl.origin, '')
} catch (error) {
if (url.endsWith('*')) {
const parsedUrl = new URL(url.slice(0, -1))
Expand Down
2 changes: 1 addition & 1 deletion packages/puppeteer/test/config/setupTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,4 @@ afterAll(async () => {
await browser.close()
})

export { page }
export { browser, page }
11 changes: 6 additions & 5 deletions packages/puppeteer/test/puppeteer.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { jest, afterEach, beforeEach, describe, expect, test } from '@jest/globals'
import { page } from './config/setupTests.js'
import { browser, page } from './config/setupTests.js'
import { ActionEnum, getTestFiles, wrapError } from '@dynamock/test-cases'
import { getPuppeteerTestCases } from './config/getTestCases.js'
import { writeFileSync } from 'node:fs'

describe('puppeteer integration tests', () => {
const allTests = getTestFiles() //.filter(([filePath]) => filePath.includes('create-and-delete-bulk.yml'))
const allTests = getTestFiles() /* .filter(([filePath]) => filePath.includes('matching-path-regexp.yml')) */

beforeEach(() => page.goto('http://127.0.0.1:3000/index.html'))

Expand All @@ -19,8 +19,7 @@ describe('puppeteer integration tests', () => {

for (let i = 0; i < testData.length; i++) {
const { action, expectation } = testData[i]
// @ts-ignore
// console.log(action.name, action.data, expectation)

switch (action.name) {
case ActionEnum.put_config:
case ActionEnum.delete_config:
Expand Down Expand Up @@ -56,7 +55,9 @@ describe('puppeteer integration tests', () => {
const safeQuery = query ?? {}

if (cookies) {
await page.setCookie(...Object.entries(cookies ?? {}).map(([name, value]) => ({ name, value })))
await browser.setCookie(
...Object.entries(cookies ?? {}).map(([name, value]) => ({ name, value, domain: '127.0.0.1' })),
)
}

const fetchOptions: {
Expand Down
1 change: 0 additions & 1 deletion packages/test-cases/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"private": true,
"type": "module",
"main": "./index.ts",
"packageManager": "yarn@4.5.0",
"dependencies": {
"js-yaml": "^4.1.0"
},
Expand Down
Loading