Skip to content

Commit

Permalink
✨ feat(core): Add createTempContextDir function (#945)
Browse files Browse the repository at this point in the history
  • Loading branch information
duckception authored Oct 23, 2023
1 parent 06a913a commit 0584183
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
14 changes: 14 additions & 0 deletions packages/core/src/utils/createTempContextDir.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import os from 'node:os'
import path from 'node:path'
import fs from 'fs-extra'

/**
* Creates a temporary context directory.
* This directory should be 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/server/browserType.ts#L161
*/
export async function createTempContextDir(browserName: string, testId: string) {
return await fs.mkdtemp(path.join(os.tmpdir(), `synpress_${browserName}_${testId}_`))
}
70 changes: 70 additions & 0 deletions packages/core/test/utils/createTempContextDir.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import os from 'node:os'
import path from 'node:path'
import { fs, vol } from 'memfs'
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createTempContextDir } from '../../src/utils/createTempContextDir'

const BROWSER_NAME = 'chromium'
const TEST_ID = 'test-id'
const SUFFIX = '123456'

const ROOT_DIR = '/tmp'
const TEMP_DIR_PATH = path.join(ROOT_DIR, `synpress_${BROWSER_NAME}_${TEST_ID}_${SUFFIX}`)

vi.mock('fs-extra', async () => {
return {
default: {
...fs,
mkdtemp: async (prefix: string) => {
const dirName = prefix + SUFFIX
await fs.promises.mkdir(dirName)
return dirName
}
}
}
})

vi.mock('node:os', async () => {
return {
default: {
tmpdir: () => ROOT_DIR
}
}
})

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

beforeEach(() => {
vol.mkdirSync(ROOT_DIR)
})

afterEach(() => {
vol.reset() // Clear the in-memory file system after each test
vi.clearAllMocks()
})

it('calls os.tmpdir', async () => {
const osTmpDirSpy = vi.spyOn(os, 'tmpdir')

await createTempContextDir(BROWSER_NAME, TEST_ID)

expect(osTmpDirSpy).toHaveBeenCalledOnce()
})

it('returns path to the directory', async () => {
const tempDirPath = await createTempContextDir(BROWSER_NAME, TEST_ID)
expect(tempDirPath).toEqual(TEMP_DIR_PATH)
})

it('creates a directory with the correct name', async () => {
expect(fs.readdirSync(ROOT_DIR)).toHaveLength(0)

const tempDirPath = await createTempContextDir(BROWSER_NAME, TEST_ID)

expect(fs.readdirSync(ROOT_DIR)).toHaveLength(1)
expect(fs.existsSync(tempDirPath)).toBeTruthy()
})
})

0 comments on commit 0584183

Please sign in to comment.