Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add environment variable interpolation to YAML script parser #226

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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',
);
});
});
});
Loading