Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Type check and restructure tests #119

Merged
merged 10 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ node_modules
dist
.mf
.env
.dev.vars
.dev.vars
.wrangler
26 changes: 14 additions & 12 deletions test/fixtures/worker-fixture.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,41 +6,39 @@ import { runWranglerDev } from '../helpers/run-wrangler.js'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

/**
* The wrangler environment to use for the test worker.
* @type {string}
*/
const wranglerEnv = process.env.WRANGLER_ENV || 'integration'

/**
* Worker information object
* @typedef {Object} WorkerInfo
* @property {string | undefined} ip - The IP address of the test worker.
* @property {number | undefined} port - The port of the test worker.
* @property {() => Promise<void> | undefined} stop - Function to stop the test worker.
* @property {() => string | undefined} getOutput - Function to get the output of the test worker.
* @property {string} wranglerEnv - The wrangler environment to use for the test worker.
*/

/**
* Worker information object
* @type {WorkerInfo}
* @type {WorkerInfo | undefined}
*/
const workerInfo = {
ip: undefined,
port: undefined,
stop: undefined,
getOutput: undefined,
wranglerEnv: process.env.WRANGLER_ENV || 'integration'
}
let workerInfo;

/**
* Sets up the test worker.
* @returns {Promise<void>}
*/
export const mochaGlobalSetup = async () => {
try {
const result = await runWranglerDev(
workerInfo = await runWranglerDev(
resolve(__dirname, '../../'), // The directory of the worker with the wrangler.toml
['--local'],
process.env,
workerInfo.wranglerEnv
wranglerEnv
)
Object.assign(workerInfo, result)
console.log(`Output: ${await workerInfo.getOutput()}`)
console.log('WorkerInfo:', workerInfo)
console.log('Test worker started!')
Expand All @@ -55,6 +53,9 @@ export const mochaGlobalSetup = async () => {
* @returns {Promise<void>}
*/
export const mochaGlobalTeardown = async () => {
// If the worker is not running, nothing to do.
if (!workerInfo) return;

try {
const { stop } = workerInfo
await stop?.()
Expand All @@ -71,5 +72,6 @@ export const mochaGlobalTeardown = async () => {
* @returns {WorkerInfo}
*/
export function getWorkerInfo () {
if (!workerInfo) throw new Error('Worker not running.');
return workerInfo
}
112 changes: 50 additions & 62 deletions test/helpers/run-wrangler.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,70 +62,58 @@ async function runLongLivedWrangler (
cwd,
env
) {
let settledReadyPromise = false
/** @type {(value: { ip: string port: number }) => void} */
let resolveReadyPromise
/** @type {(reason: unknown) => void} */
let rejectReadyPromise

const ready = new Promise((resolve, reject) => {
resolveReadyPromise = resolve
rejectReadyPromise = reject
})

const wranglerProcess = fork(wranglerEntryPath, command, {
stdio: ['ignore', /* stdout */ 'pipe', /* stderr */ 'pipe', 'ipc'],
cwd,
env: { ...process.env, ...env, PWD: cwd }
}).on('message', (message) => {
if (settledReadyPromise) return
settledReadyPromise = true
clearTimeout(timeoutHandle)
resolveReadyPromise(JSON.parse(message.toString()))
})
return new Promise((resolve, reject) => {
const wranglerProcess = fork(wranglerEntryPath, command, {
stdio: ['ignore', /* stdout */ 'pipe', /* stderr */ 'pipe', 'ipc'],
cwd,
env: { ...process.env, ...env, PWD: cwd }
}).on('message', (messageJSON) => {
clearTimeout(timeoutHandle)
/** @type {{ ip: string, port: number }} */
const message = JSON.parse(messageJSON.toString())
resolve({...message, stop, getOutput, clearOutput})
})

const chunks = []
wranglerProcess.stdout?.on('data', (chunk) => {
chunks.push(chunk)
})
wranglerProcess.stderr?.on('data', (chunk) => {
chunks.push(chunk)
})
const getOutput = () => Buffer.concat(chunks).toString()
const clearOutput = () => (chunks.length = 0)
/** @type {Buffer[]} */
const chunks = []
wranglerProcess.stdout?.on('data', (chunk) => {
chunks.push(chunk)
})
wranglerProcess.stderr?.on('data', (chunk) => {
chunks.push(chunk)
})
const getOutput = () => Buffer.concat(chunks).toString()
const clearOutput = () => (chunks.length = 0)

const timeoutHandle = setTimeout(() => {
if (settledReadyPromise) return
settledReadyPromise = true
const separator = '='.repeat(80)
const message = [
'Timed out starting long-lived Wrangler:',
separator,
getOutput(),
separator
].join('\n')
rejectReadyPromise(new Error(message))
}, 50_000)
const timeoutHandle = setTimeout(() => {
const separator = '='.repeat(80)
const message = [
'Timed out starting long-lived Wrangler:',
separator,
getOutput(),
separator
].join('\n')
reject(new Error(message))
}, 50_000)

async function stop () {
return new Promise((resolve) => {
assert(
wranglerProcess.pid,
`Command "${command.join(' ')}" had no process id`
)
treeKill(wranglerProcess.pid, (e) => {
if (e) {
console.error(
'Failed to kill command: ' + command.join(' '),
wranglerProcess.pid,
e
)
}
resolve()
/** @type {WranglerProcessInfo['stop']} */
async function stop () {
return new Promise((resolve) => {
assert(
wranglerProcess.pid,
`Command "${command.join(' ')}" had no process id`
)
treeKill(wranglerProcess.pid, (e) => {
Peeja marked this conversation as resolved.
Show resolved Hide resolved
if (e) {
console.error(
'Failed to kill command: ' + command.join(' '),
wranglerProcess.pid,
e
)
}
resolve()
})
})
})
}

const { ip, port } = await ready
return { ip, port, stop, getOutput, clearOutput }
}
})
}
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

{
"include": ["src"],
"include": ["src", "test"],
"compilerOptions": {
"declaration": true,
"declarationMap": true,
Expand Down
Loading