Skip to content

Commit

Permalink
feat: add environment variable interpolation to YAML script parser
Browse files Browse the repository at this point in the history
  • Loading branch information
georgeleiLM committed Dec 31, 2024
1 parent 8042bcc commit e4a4836
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
13 changes: 12 additions & 1 deletion packages/web-integration/src/yaml/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,22 @@ import type {
MidsceneYamlFlowItemSleep,
} from '@midscene/core';

function interpolateEnvVars(content: string): string {
return content.replace(/\{\{([^}]+)\}\}/g, (_, envVar) => {
const value = process.env[envVar.trim()];
if (value === undefined) {
throw new Error(`Environment variable "${envVar.trim()}" is not defined`);
}
return value;
});
}

export function parseYamlScript(
content: string,
filePath?: string,
): MidsceneYamlScript {
const obj = yaml.load(content) as MidsceneYamlScript;
const interpolatedContent = interpolateEnvVars(content);
const obj = yaml.load(interpolatedContent) as MidsceneYamlScript;
const pathTip = filePath ? `, failed to load ${filePath}` : '';
assert(obj.target, `property "target" is required in yaml script${pathTip}`);
assert(
Expand Down
32 changes: 31 additions & 1 deletion packages/web-integration/tests/unit-test/yaml/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { buildYaml, flowItemBrief } from '@/yaml';
import { buildYaml, flowItemBrief, parseYamlScript } from '@/yaml';
import { describe, expect, test } from 'vitest';

describe('utils', () => {
Expand All @@ -14,4 +14,34 @@ describe('utils', () => {
flowItemBrief({ aiWaitFor: 'wait for something' }),
).toMatchSnapshot();
});

describe('parseYamlScript', () => {
test('interpolates environment variables', () => {
process.env.TEST_URL = 'https://example.com';
process.env.TEST_PATH = '/test/path';

const yamlContent = `
target:
url: "{{TEST_URL}}{{TEST_PATH}}"
tasks:
- sleep: 1000
`;

const result = parseYamlScript(yamlContent);
expect(result.target.url).toBe('https://example.com/test/path');
});

test('throws error for undefined environment variables', () => {
const yamlContent = `
target:
url: "{{UNDEFINED_ENV_VAR}}"
tasks:
- sleep: 1000
`;

expect(() => parseYamlScript(yamlContent)).toThrow(
'Environment variable "UNDEFINED_ENV_VAR" is not defined',
);
});
});
});

0 comments on commit e4a4836

Please sign in to comment.