Skip to content

Commit

Permalink
✨ feat(core): Add removeTempContextDir function (#946)
Browse files Browse the repository at this point in the history
  • Loading branch information
duckception authored Oct 23, 2023
1 parent 0584183 commit a1b1480
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
23 changes: 23 additions & 0 deletions packages/core/src/utils/removeTempContextDir.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { type RimrafAsyncOptions, rimraf } from 'rimraf'

/**
* Sometimes the browser is still closing when we remove the context directory which results in an error/unwanted behaviour.
* We retry a few times to make sure it's removed.
*/
const opts: RimrafAsyncOptions = {
maxRetries: 10
}

/**
* Removes the temporary context directory created per-worker basis.
*
* This function mirrors the one found in the Playwright source code:
* https://github.com/microsoft/playwright/blob/d1d5fc67dc684a5d4b682749e59bba8cc0ad14de/packages/playwright-core/src/utils/processLauncher.ts#L142
*/
export async function removeTempContextDir(contextDirPath: string) {
return new Promise<null | Error>((resolve) => {
rimraf(contextDirPath, opts)
.then(() => resolve(null))
.catch((e: Error) => resolve(e))
})
}
32 changes: 32 additions & 0 deletions packages/core/test/utils/removeTempContextDir.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { afterAll, describe, expect, it, vi } from 'vitest'
import { removeTempContextDir } from '../../src/utils/removeTempContextDir'

const PATH = 'Happy Quack Path'
const MAX_RETRIES = 10

// This mock acts both as a mock and a spy.
// I couldn't make `vi.spyOn` or mocking a throw to work, so this is used instead.
vi.mock('rimraf', async () => {
return {
rimraf: vi.fn(async (path: string, options: { maxRetries: number }) => {
expect(path).toEqual(PATH)
expect(options.maxRetries).toEqual(MAX_RETRIES)
})
}
})

describe('removeTempContextDir', () => {
afterAll(() => {
vi.resetAllMocks()
})

it('returns null on success', async () => {
const result = await removeTempContextDir(PATH)
expect(result).toBeNull()
})

it('returns error if one occurred', async () => {
const result = await removeTempContextDir('A Ducking Wrong Path')
expect(result?.message).toMatch(/expected 'A Ducking Wrong Path' to deeply equal/)
})
})

0 comments on commit a1b1480

Please sign in to comment.