60 lines
1.8 KiB
TypeScript
60 lines
1.8 KiB
TypeScript
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
import { tmpdir } from 'node:os'
|
|
import { join } from 'node:path'
|
|
import { afterEach, describe, expect, it } from 'vitest'
|
|
import { loadEnvironmentFile } from '../src/server/environment.js'
|
|
|
|
const testVariable = 'PRODUCT_ISSUE_ENV_FILE_TEST'
|
|
const originalValue = process.env[testVariable]
|
|
const temporaryDirectories: string[] = []
|
|
|
|
afterEach(() => {
|
|
if (originalValue === undefined) {
|
|
delete process.env[testVariable]
|
|
} else {
|
|
process.env[testVariable] = originalValue
|
|
}
|
|
for (const directory of temporaryDirectories.splice(0)) {
|
|
rmSync(directory, { recursive: true, force: true })
|
|
}
|
|
})
|
|
|
|
function environmentFile(value: string): string {
|
|
const directory = mkdtempSync(join(tmpdir(), 'product-issue-env-'))
|
|
temporaryDirectories.push(directory)
|
|
const filePath = join(directory, '.env')
|
|
writeFileSync(filePath, `${testVariable}=${value}\n`, {
|
|
encoding: 'utf8',
|
|
mode: 0o600
|
|
})
|
|
return filePath
|
|
}
|
|
|
|
describe('loadEnvironmentFile', () => {
|
|
it('loads values from an explicit environment file', () => {
|
|
delete process.env[testVariable]
|
|
|
|
const filePath = environmentFile('from-file')
|
|
|
|
expect(loadEnvironmentFile(filePath)).toBe(filePath)
|
|
expect(process.env[testVariable]).toBe('from-file')
|
|
})
|
|
|
|
it('does not override values already provided by the process', () => {
|
|
process.env[testVariable] = 'from-process'
|
|
|
|
loadEnvironmentFile(environmentFile('from-file'))
|
|
|
|
expect(process.env[testVariable]).toBe('from-process')
|
|
})
|
|
|
|
it('fails when an explicitly configured file does not exist', () => {
|
|
const directory = mkdtempSync(join(tmpdir(), 'product-issue-env-'))
|
|
temporaryDirectories.push(directory)
|
|
|
|
expect(() => loadEnvironmentFile(join(directory, '.env'))).toThrow(
|
|
'Environment file does not exist'
|
|
)
|
|
})
|
|
})
|