diff --git a/scripts/patch-tfvars.test.mjs b/scripts/patch-tfvars.test.mjs new file mode 100644 index 0000000..eb3fb18 --- /dev/null +++ b/scripts/patch-tfvars.test.mjs @@ -0,0 +1,52 @@ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' + +const script = join(import.meta.dirname, 'patch-tfvars.mjs') + +let dirs = [] +afterEach(() => { + for (const dir of dirs) rmSync(dir, { recursive: true, force: true }) + dirs = [] +}) + +function tfvarsFile(initial) { + const dir = mkdtempSync(join(tmpdir(), 'patch-tfvars-')) + dirs.push(dir) + const file = join(dir, 'terraform.tfvars.json') + if (initial !== undefined) writeFileSync(file, initial) + return file +} + +function patch(file, key, value) { + execFileSync(process.execPath, [script, file, key, value]) + return JSON.parse(readFileSync(file, 'utf8')) +} + +describe('patch-tfvars.mjs', () => { + it('creates the file when missing', () => { + const file = tfvarsFile() + expect(patch(file, 'release_sha', 'abc123def456')).toEqual({ release_sha: 'abc123def456' }) + }) + + it('replaces an existing value', () => { + const file = tfvarsFile('{"release_sha": "abc123def456"}\n') + expect(patch(file, 'release_sha', 'def456abc123')).toEqual({ release_sha: 'def456abc123' }) + }) + + it('preserves other variables', () => { + const file = tfvarsFile('{"other_var": true, "release_sha": "abc123def456"}\n') + expect(patch(file, 'release_sha', 'def456abc123')).toEqual({ + other_var: true, + release_sha: 'def456abc123', + }) + }) + + it('fails rather than clobbering a file it cannot parse', () => { + const file = tfvarsFile('not json') + expect(() => patch(file, 'release_sha', 'abc123def456')).toThrow() + expect(readFileSync(file, 'utf8')).toBe('not json') + }) +})