@skyramp/mcp 0.2.8 → 0.2.150-rc.local.de
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/commands/commandLibrary.d.ts +1 -0
- package/build/commands/commandLibrary.js +18 -17
- package/build/commands/localDevTestChangesCommand.d.ts +15 -0
- package/build/commands/localDevTestChangesCommand.js +175 -0
- package/build/index.js +74 -13
- package/build/prompts/enhance-assertions/sharedAssertionRules.js +1 -0
- package/build/prompts/initialize-workspace/initializeWorkspacePrompt.js +7 -6
- package/build/prompts/local-dev/local-dev-plan.d.ts +25 -0
- package/build/prompts/local-dev/local-dev-plan.js +414 -0
- package/build/prompts/local-dev/local-dev-prompts.d.ts +4 -0
- package/build/prompts/local-dev/local-dev-prompts.js +152 -0
- package/build/prompts/prompt-utils.d.ts +8 -0
- package/build/prompts/prompt-utils.js +33 -0
- package/build/prompts/sut-setup/modes/adaptWorkflowPrompt.js +3 -1
- package/build/prompts/sut-setup/modes/dockerComposePrompt.js +3 -1
- package/build/prompts/sut-setup/shared.d.ts +20 -0
- package/build/prompts/sut-setup/shared.js +69 -7
- package/build/prompts/test-recommendation/analysisOutputPrompt.js +21 -29
- package/build/prompts/test-recommendation/analysisOutputPrompt.test.js +79 -16
- package/build/prompts/test-recommendation/test-recommendation-prompt.js +41 -4
- package/build/prompts/test-recommendation/test-recommendation-prompt.test.js +34 -1
- package/build/prompts/testbot/testbot-prompts.d.ts +0 -5
- package/build/prompts/testbot/testbot-prompts.js +4 -34
- package/build/resources/testbotResource.js +2 -1
- package/build/services/TestExecutionService.d.ts +10 -2
- package/build/services/TestExecutionService.js +220 -28
- package/build/services/TestExecutionService.test.js +447 -16
- package/build/services/TestGenerationService.d.ts +2 -2
- package/build/tool-phases.js +4 -0
- package/build/tools/code-refactor/enhanceAssertionsTool.js +34 -2
- package/build/tools/enrichTestWithMocksTool.d.ts +15 -0
- package/build/tools/enrichTestWithMocksTool.js +414 -0
- package/build/tools/enrichTestWithMocksTool.test.d.ts +1 -0
- package/build/tools/enrichTestWithMocksTool.test.js +397 -0
- package/build/tools/executeSkyrampTestTool.d.ts +3 -0
- package/build/tools/executeSkyrampTestTool.js +73 -18
- package/build/tools/executeSkyrampTestTool.test.d.ts +1 -0
- package/build/tools/executeSkyrampTestTool.test.js +111 -0
- package/build/tools/generate-tests/batchMockGenerationTool.d.ts +72 -0
- package/build/tools/generate-tests/batchMockGenerationTool.js +382 -0
- package/build/tools/generate-tests/batchMockGenerationTool.test.d.ts +1 -0
- package/build/tools/generate-tests/batchMockGenerationTool.test.js +514 -0
- package/build/tools/generate-tests/generateContractRestTool.js +2 -2
- package/build/tools/generate-tests/generateMockRestTool.d.ts +56 -6
- package/build/tools/generate-tests/generateMockRestTool.js +193 -21
- package/build/tools/generate-tests/generateMockRestTool.test.d.ts +1 -0
- package/build/tools/generate-tests/generateMockRestTool.test.js +340 -0
- package/build/tools/generateEnrichedIntegrationTestTool.d.ts +24 -0
- package/build/tools/generateEnrichedIntegrationTestTool.js +209 -0
- package/build/tools/generateEnrichedIntegrationTestTool.test.d.ts +1 -0
- package/build/tools/generateEnrichedIntegrationTestTool.test.js +199 -0
- package/build/tools/one-click/oneClickTool.d.ts +10 -0
- package/build/tools/one-click/oneClickTool.js +182 -40
- package/build/tools/one-click/oneClickTool.test.d.ts +1 -0
- package/build/tools/one-click/oneClickTool.test.js +204 -0
- package/build/tools/preflightMockCheckTool.d.ts +2 -0
- package/build/tools/preflightMockCheckTool.js +91 -0
- package/build/tools/test-management/analyzeChangesTool.d.ts +2 -1
- package/build/tools/test-management/analyzeChangesTool.js +59 -38
- package/build/tools/workspace/initializeWorkspaceTool.js +2 -9
- package/build/tools/workspace/initializeWorkspaceTool.test.js +9 -4
- package/build/types/OneClickCommands.d.ts +1 -1
- package/build/types/RepositoryAnalysis.d.ts +117 -0
- package/build/types/RepositoryAnalysis.js +16 -2
- package/build/types/TestTypes.d.ts +11 -2
- package/build/types/TestTypes.js +11 -1
- package/build/utils/analyze-openapi.js +18 -1
- package/build/utils/analyze-openapi.test.d.ts +1 -0
- package/build/utils/analyze-openapi.test.js +19 -0
- package/build/utils/branchDiff.d.ts +17 -1
- package/build/utils/branchDiff.js +96 -14
- package/build/utils/branchDiff.test.d.ts +1 -0
- package/build/utils/branchDiff.test.js +107 -0
- package/build/utils/docker.test.js +1 -1
- package/build/utils/featureFlags.d.ts +15 -1
- package/build/utils/featureFlags.js +19 -2
- package/build/utils/featureFlags.test.js +57 -2
- package/build/utils/grpcMockValidation.d.ts +1 -0
- package/build/utils/grpcMockValidation.js +49 -0
- package/build/utils/grpcMockValidation.test.d.ts +1 -0
- package/build/utils/grpcMockValidation.test.js +41 -0
- package/build/utils/httpMethodValidation.d.ts +4 -0
- package/build/utils/httpMethodValidation.js +13 -0
- package/build/utils/mockCompatibility.d.ts +49 -0
- package/build/utils/mockCompatibility.js +80 -0
- package/build/utils/mockCompatibility.test.d.ts +1 -0
- package/build/utils/mockCompatibility.test.js +88 -0
- package/build/utils/versions.d.ts +3 -3
- package/build/utils/versions.js +1 -1
- package/build/workspace/workspace.d.ts +35 -21
- package/build/workspace/workspace.js +8 -4
- package/build/workspace/workspace.test.js +65 -6
- package/package.json +2 -2
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { ProgrammingLanguage } from "../types/TestTypes.js";
|
|
3
|
+
/**
|
|
4
|
+
* skyramp_enrich_test_with_mocks
|
|
5
|
+
*
|
|
6
|
+
* Injects mock imports and apply_mock() calls into a generated test file.
|
|
7
|
+
* The mock files are generated by skyramp_mock_generation — this tool wires
|
|
8
|
+
* them into the test so the mocks are applied before the test runs.
|
|
9
|
+
*
|
|
10
|
+
* No data duplication — the test imports from the generated mock files.
|
|
11
|
+
*/
|
|
12
|
+
export declare function registerEnrichTestWithMocksTool(server: McpServer): void;
|
|
13
|
+
declare function injectMockImports(original: string, testFile: string, scenarioName: string, mockFiles: string[], traceComments?: string[], language?: ProgrammingLanguage): string;
|
|
14
|
+
declare function buildMockImportBlock(testFile: string, scenarioName: string, mockFiles: string[], traceComments?: string[], language?: ProgrammingLanguage): string;
|
|
15
|
+
export { injectMockImports, buildMockImportBlock };
|
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { logger } from "../utils/logger.js";
|
|
3
|
+
import * as fs from "fs";
|
|
4
|
+
import * as path from "path";
|
|
5
|
+
import { ProgrammingLanguage, MockProtocol } from "../types/TestTypes.js";
|
|
6
|
+
const TOOL_NAME = "skyramp_enrich_test_with_mocks";
|
|
7
|
+
const enrichSchema = {
|
|
8
|
+
testFile: z
|
|
9
|
+
.string()
|
|
10
|
+
.describe("Absolute path to the generated test file to enrich (e.g., /repo/tests/skyramp/order_happy_path_integration_test.py)"),
|
|
11
|
+
scenarioName: z
|
|
12
|
+
.string()
|
|
13
|
+
.describe("Human-readable scenario name (e.g., order-happy-path, payment-timeout). Used as the SCENARIO_NAME constant."),
|
|
14
|
+
mockFiles: z
|
|
15
|
+
.array(z.string())
|
|
16
|
+
.describe("Absolute paths to the generated mock files (from skyramp_mock_generation) that this test needs. " +
|
|
17
|
+
"The tool will inject import statements and apply_mock() calls for each file. " +
|
|
18
|
+
'Example: ["/repo/tests/skyramp/mocks/validate_POST_mock.py", "/repo/tests/skyramp/mocks/payment_authorizations_POST_mock.py"]'),
|
|
19
|
+
language: z
|
|
20
|
+
.nativeEnum(ProgrammingLanguage)
|
|
21
|
+
.optional()
|
|
22
|
+
.describe("Programming language of the generated test. Optional for backward compatibility; inferred from testFile when omitted. Mock enrichment currently supports Python tests only."),
|
|
23
|
+
traceComments: z
|
|
24
|
+
.array(z.string())
|
|
25
|
+
.optional()
|
|
26
|
+
.describe("Optional trace comments showing how mock values flow to assertions (e.g., 'pricing-service returns discount=true → creator sets order.discount_applied=true → assert True')"),
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* skyramp_enrich_test_with_mocks
|
|
30
|
+
*
|
|
31
|
+
* Injects mock imports and apply_mock() calls into a generated test file.
|
|
32
|
+
* The mock files are generated by skyramp_mock_generation — this tool wires
|
|
33
|
+
* them into the test so the mocks are applied before the test runs.
|
|
34
|
+
*
|
|
35
|
+
* No data duplication — the test imports from the generated mock files.
|
|
36
|
+
*/
|
|
37
|
+
export function registerEnrichTestWithMocksTool(server) {
|
|
38
|
+
server.registerTool(TOOL_NAME, {
|
|
39
|
+
description: "Enrich a generated INTEGRATION test file by injecting imports from generated mock files. " +
|
|
40
|
+
"Call this after skyramp_mock_generation and skyramp_integration_test_generation. " +
|
|
41
|
+
"The tool adds import statements and apply_mock() calls so the test uses the " +
|
|
42
|
+
"generated mocks directly — no data duplication. " +
|
|
43
|
+
"NOTE: Do NOT call this for contract tests — consumer contract tests already have mocks wired inline by the generation tool.",
|
|
44
|
+
inputSchema: enrichSchema,
|
|
45
|
+
}, async (params) => {
|
|
46
|
+
try {
|
|
47
|
+
const { testFile, scenarioName, mockFiles, traceComments, language } = params;
|
|
48
|
+
if (!fs.existsSync(testFile)) {
|
|
49
|
+
return {
|
|
50
|
+
content: [
|
|
51
|
+
{
|
|
52
|
+
type: "text",
|
|
53
|
+
text: `**Error:** Test file not found: ${testFile}`,
|
|
54
|
+
},
|
|
55
|
+
],
|
|
56
|
+
isError: true,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
// Validate mock files exist
|
|
60
|
+
const missingFiles = mockFiles.filter((f) => !fs.existsSync(f));
|
|
61
|
+
if (missingFiles.length > 0) {
|
|
62
|
+
return {
|
|
63
|
+
content: [
|
|
64
|
+
{
|
|
65
|
+
type: "text",
|
|
66
|
+
text: `**Error:** Mock files not found:\n` +
|
|
67
|
+
missingFiles.map((f) => ` - ${f}`).join("\n") +
|
|
68
|
+
`\n\nGenerate them first with \`skyramp_mock_generation\`.`,
|
|
69
|
+
},
|
|
70
|
+
],
|
|
71
|
+
isError: true,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
const resolvedLanguage = resolveMockEnrichmentLanguage(testFile, language);
|
|
75
|
+
if (resolvedLanguage !== ProgrammingLanguage.PYTHON) {
|
|
76
|
+
return unsupportedLanguageResult(testFile, resolvedLanguage);
|
|
77
|
+
}
|
|
78
|
+
const original = fs.readFileSync(testFile, "utf-8");
|
|
79
|
+
const enriched = injectMockImports(original, testFile, scenarioName, mockFiles, traceComments, resolvedLanguage);
|
|
80
|
+
fs.writeFileSync(testFile, enriched);
|
|
81
|
+
logger.info(`Enriched test file with mock imports: ${testFile}`, {
|
|
82
|
+
scenarioName,
|
|
83
|
+
mockFileCount: mockFiles.length,
|
|
84
|
+
});
|
|
85
|
+
return {
|
|
86
|
+
content: [
|
|
87
|
+
{
|
|
88
|
+
type: "text",
|
|
89
|
+
text: [
|
|
90
|
+
`**Test enriched with mock imports for scenario "${scenarioName}".**\n`,
|
|
91
|
+
`**File:** ${testFile}`,
|
|
92
|
+
`**Mock files imported:** ${mockFiles.length}`,
|
|
93
|
+
...mockFiles.map((f) => ` • ${path.basename(f)}`),
|
|
94
|
+
`\nThe test now imports and applies mocks from the generated files.`,
|
|
95
|
+
`Before execution, stop real services selected for mocking, then execute with: \`skyramp_execute_test({testFile: "${testFile}", mockIsolationConfirmed: true, ...})\``,
|
|
96
|
+
].join("\n"),
|
|
97
|
+
},
|
|
98
|
+
],
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
logger.error(`Failed to enrich test: ${error.message}`);
|
|
103
|
+
return {
|
|
104
|
+
content: [
|
|
105
|
+
{
|
|
106
|
+
type: "text",
|
|
107
|
+
text: `**Failed to enrich test:** ${error.message}`,
|
|
108
|
+
},
|
|
109
|
+
],
|
|
110
|
+
isError: true,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
116
|
+
function injectMockImports(original, testFile, scenarioName, mockFiles, traceComments, language) {
|
|
117
|
+
const resolvedLanguage = resolveMockEnrichmentLanguage(testFile, language);
|
|
118
|
+
assertSupportedMockEnrichmentLanguage(testFile, resolvedLanguage);
|
|
119
|
+
const generatedBlock = buildMockImportBlock(testFile, scenarioName, mockFiles, traceComments, resolvedLanguage);
|
|
120
|
+
const existingBlockRange = findGeneratedMockBlockRange(original);
|
|
121
|
+
if (existingBlockRange) {
|
|
122
|
+
const suffix = original.slice(existingBlockRange.end);
|
|
123
|
+
const separator = suffix.length > 0 && !suffix.startsWith("\n") ? "\n" : "";
|
|
124
|
+
original =
|
|
125
|
+
original.slice(0, existingBlockRange.start) +
|
|
126
|
+
generatedBlock +
|
|
127
|
+
separator +
|
|
128
|
+
suffix;
|
|
129
|
+
}
|
|
130
|
+
// Find insertion point: after the last import line
|
|
131
|
+
const lines = original.split("\n");
|
|
132
|
+
let insertIdx = 0;
|
|
133
|
+
for (let i = 0; i < lines.length; i++) {
|
|
134
|
+
const line = lines[i].trim();
|
|
135
|
+
if (line.startsWith("import ") ||
|
|
136
|
+
line.startsWith("from ") ||
|
|
137
|
+
line.startsWith("# Import") ||
|
|
138
|
+
(line === "" &&
|
|
139
|
+
i > 0 &&
|
|
140
|
+
(lines[i - 1].trim().startsWith("import") ||
|
|
141
|
+
lines[i - 1].trim().startsWith("from")))) {
|
|
142
|
+
insertIdx = i + 1;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// If no imports found, insert after initial comments
|
|
146
|
+
if (insertIdx === 0) {
|
|
147
|
+
for (let i = 0; i < lines.length; i++) {
|
|
148
|
+
if (!lines[i].startsWith("#") && lines[i].trim() !== "") {
|
|
149
|
+
insertIdx = i;
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
// Insert the mock block once. If a previous generated block existed, it was
|
|
155
|
+
// replaced before splitting into lines so stale imports/mappings do not survive.
|
|
156
|
+
if (!existingBlockRange) {
|
|
157
|
+
lines.splice(insertIdx, 0, "", generatedBlock, "");
|
|
158
|
+
}
|
|
159
|
+
// Wire apply_all_mocks(client) after the generated Skyramp client exists.
|
|
160
|
+
for (let i = 0; i < lines.length; i++) {
|
|
161
|
+
const line = lines[i];
|
|
162
|
+
// Match Python test function definitions (def test_integration(): or def test_*():)
|
|
163
|
+
if (/^def test_\w+\(/.test(line.trim())) {
|
|
164
|
+
const functionEnd = findPythonFunctionEnd(lines, i + 1);
|
|
165
|
+
const applyCallIndex = lines.findIndex((l, idx) => idx >= i &&
|
|
166
|
+
idx < functionEnd &&
|
|
167
|
+
(l.trim() === "apply_all_mocks(client)" ||
|
|
168
|
+
l.trim() === "apply_all_mocks()"));
|
|
169
|
+
if (applyCallIndex !== -1) {
|
|
170
|
+
// Existing generated tests may already call apply_all_mocks(client).
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
const clientEnd = findSkyrampClientConstructionEnd(lines, i + 1, functionEnd);
|
|
174
|
+
if (clientEnd !== -1) {
|
|
175
|
+
lines.splice(clientEnd + 1, 0, " apply_all_mocks(client)", "");
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
break; // Only inject into the first test function
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return lines.join("\n");
|
|
182
|
+
}
|
|
183
|
+
function resolveMockEnrichmentLanguage(testFile, language) {
|
|
184
|
+
if (language)
|
|
185
|
+
return language;
|
|
186
|
+
const extension = path.extname(testFile).toLowerCase();
|
|
187
|
+
switch (extension) {
|
|
188
|
+
case ".py":
|
|
189
|
+
return ProgrammingLanguage.PYTHON;
|
|
190
|
+
case ".ts":
|
|
191
|
+
case ".tsx":
|
|
192
|
+
return ProgrammingLanguage.TYPESCRIPT;
|
|
193
|
+
case ".js":
|
|
194
|
+
case ".jsx":
|
|
195
|
+
return ProgrammingLanguage.JAVASCRIPT;
|
|
196
|
+
case ".java":
|
|
197
|
+
return ProgrammingLanguage.JAVA;
|
|
198
|
+
default:
|
|
199
|
+
throw new Error(`Cannot infer mock enrichment language from test file extension: ${testFile}`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
function assertSupportedMockEnrichmentLanguage(testFile, language) {
|
|
203
|
+
if (language === ProgrammingLanguage.PYTHON)
|
|
204
|
+
return;
|
|
205
|
+
throw new Error(unsupportedLanguageMessage(testFile, language));
|
|
206
|
+
}
|
|
207
|
+
function unsupportedLanguageMessage(testFile, language) {
|
|
208
|
+
return `Mock enrichment is currently supported only for Python tests; received language "${language}" for test file "${testFile}".`;
|
|
209
|
+
}
|
|
210
|
+
function unsupportedLanguageResult(testFile, language) {
|
|
211
|
+
return {
|
|
212
|
+
content: [
|
|
213
|
+
{
|
|
214
|
+
type: "text",
|
|
215
|
+
text: `**Error:** ${unsupportedLanguageMessage(testFile, language)}`,
|
|
216
|
+
},
|
|
217
|
+
],
|
|
218
|
+
isError: true,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
function findGeneratedMockBlockRange(source) {
|
|
222
|
+
const marker = "# ─── Mock Scenario:";
|
|
223
|
+
const start = source.indexOf(marker);
|
|
224
|
+
if (start === -1)
|
|
225
|
+
return null;
|
|
226
|
+
const segment = source.slice(start);
|
|
227
|
+
const lines = segment.split("\n");
|
|
228
|
+
const applyIdx = lines.findIndex((line) => line.trim() === "def apply_all_mocks(client):");
|
|
229
|
+
if (applyIdx === -1)
|
|
230
|
+
return null;
|
|
231
|
+
let endLine = lines.length;
|
|
232
|
+
for (let i = applyIdx + 1; i < lines.length; i++) {
|
|
233
|
+
const line = lines[i];
|
|
234
|
+
if (line.trim() === "" || /^\s/.test(line))
|
|
235
|
+
continue;
|
|
236
|
+
endLine = i;
|
|
237
|
+
break;
|
|
238
|
+
}
|
|
239
|
+
while (endLine < lines.length) {
|
|
240
|
+
const line = lines[endLine].trim();
|
|
241
|
+
if (line === "" || line.startsWith("# Mock trace:")) {
|
|
242
|
+
endLine += 1;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
const replacementText = lines.slice(0, endLine).join("\n");
|
|
248
|
+
return { start, end: start + replacementText.length };
|
|
249
|
+
}
|
|
250
|
+
function findPythonFunctionEnd(lines, bodyStart) {
|
|
251
|
+
for (let i = bodyStart; i < lines.length; i++) {
|
|
252
|
+
if (/^def\s+\w+\(/.test(lines[i]) || /^class\s+\w+/.test(lines[i])) {
|
|
253
|
+
return i;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return lines.length;
|
|
257
|
+
}
|
|
258
|
+
function findSkyrampClientConstructionEnd(lines, start, end) {
|
|
259
|
+
for (let i = start; i < end; i++) {
|
|
260
|
+
if (!/^\s*client\s*=\s*skyramp\.Client\s*\(/.test(lines[i])) {
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
let depth = 0;
|
|
264
|
+
for (let j = i; j < end; j++) {
|
|
265
|
+
depth += countChar(lines[j], "(") - countChar(lines[j], ")");
|
|
266
|
+
if (depth <= 0) {
|
|
267
|
+
return j;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return i;
|
|
271
|
+
}
|
|
272
|
+
return -1;
|
|
273
|
+
}
|
|
274
|
+
function countChar(value, char) {
|
|
275
|
+
return [...value].filter((current) => current === char).length;
|
|
276
|
+
}
|
|
277
|
+
function buildMockImportBlock(testFile, scenarioName, mockFiles, traceComments, language) {
|
|
278
|
+
const resolvedLanguage = resolveMockEnrichmentLanguage(testFile, language);
|
|
279
|
+
assertSupportedMockEnrichmentLanguage(testFile, resolvedLanguage);
|
|
280
|
+
const lines = [];
|
|
281
|
+
const testDir = path.dirname(testFile);
|
|
282
|
+
lines.push(`# ─── Mock Scenario: ${scenarioName} ──────────────────────────────────────`);
|
|
283
|
+
lines.push(`SCENARIO_NAME = "${scenarioName}"`);
|
|
284
|
+
lines.push(``);
|
|
285
|
+
// Generate path-based mock module loaders so dotted filenames still import correctly.
|
|
286
|
+
const mockEntries = [];
|
|
287
|
+
const usedModuleNames = new Set();
|
|
288
|
+
for (const mockFile of mockFiles) {
|
|
289
|
+
const relativePath = path.relative(testDir, mockFile).replace(/\\/g, "/");
|
|
290
|
+
const baseName = path.basename(mockFile, ".py");
|
|
291
|
+
const moduleName = uniquePythonIdentifier(baseName, usedModuleNames);
|
|
292
|
+
const serviceName = baseName.replace(/_mock$/, "").replace(/_/g, "-");
|
|
293
|
+
// Read each mock file once for both URL and protocol extraction.
|
|
294
|
+
const commandLine = extractMockCommandLine(mockFile);
|
|
295
|
+
const targetUrl = extractBaseUrlFromCommandLine(commandLine);
|
|
296
|
+
const protocol = extractProtocolFromCommandLine(commandLine, mockFile);
|
|
297
|
+
mockEntries.push({
|
|
298
|
+
serviceName,
|
|
299
|
+
moduleName,
|
|
300
|
+
relativePath,
|
|
301
|
+
targetUrl,
|
|
302
|
+
protocol,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
lines.push(`import importlib.util`);
|
|
306
|
+
lines.push(`import os`);
|
|
307
|
+
lines.push(`from pathlib import Path`);
|
|
308
|
+
lines.push(``);
|
|
309
|
+
lines.push(`def _load_mock_factory(relative_path, module_name):`);
|
|
310
|
+
lines.push(` mock_path = Path(__file__).parent / relative_path`);
|
|
311
|
+
lines.push(` spec = importlib.util.spec_from_file_location(module_name, mock_path)`);
|
|
312
|
+
lines.push(` if spec is None or spec.loader is None:`);
|
|
313
|
+
lines.push(` raise ImportError(f"Could not load mock module: {mock_path}")`);
|
|
314
|
+
lines.push(` module = importlib.util.module_from_spec(spec)`);
|
|
315
|
+
lines.push(` spec.loader.exec_module(module)`);
|
|
316
|
+
lines.push(` return module.get_all_mocks`);
|
|
317
|
+
// Generate MOCK_SERVICES dictionary
|
|
318
|
+
lines.push(``);
|
|
319
|
+
lines.push(`MOCK_SERVICES = {`);
|
|
320
|
+
for (const entry of mockEntries) {
|
|
321
|
+
lines.push(` "${entry.serviceName}": {"factory": _load_mock_factory("${entry.relativePath}", "${entry.moduleName}"), "protocol": "${entry.protocol}"},`);
|
|
322
|
+
}
|
|
323
|
+
lines.push(`}`);
|
|
324
|
+
// Always define MOCK_TARGET_URLS so apply_all_mocks can reference it unconditionally.
|
|
325
|
+
// REST targets normalize to URL origins, while gRPC/Kafka targets preserve host:port.
|
|
326
|
+
lines.push(``);
|
|
327
|
+
lines.push(`MOCK_TARGET_URLS = {`);
|
|
328
|
+
for (const entry of mockEntries) {
|
|
329
|
+
if (entry.targetUrl) {
|
|
330
|
+
lines.push(` "${entry.serviceName}": "${entry.targetUrl}",`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
lines.push(`}`);
|
|
334
|
+
// Generate apply_all_mocks() function.
|
|
335
|
+
lines.push(``);
|
|
336
|
+
lines.push(`def apply_all_mocks(client):`);
|
|
337
|
+
lines.push(` """Apply all generated mocks together after protocol-specific normalization."""`);
|
|
338
|
+
lines.push(` client.remove_all_mocks()`);
|
|
339
|
+
lines.push(``);
|
|
340
|
+
lines.push(` all_mocks = []`);
|
|
341
|
+
lines.push(` for service_name, mock_config in MOCK_SERVICES.items():`);
|
|
342
|
+
lines.push(` get_mocks_fn = mock_config["factory"]`);
|
|
343
|
+
lines.push(` mocks = get_mocks_fn()`);
|
|
344
|
+
lines.push(` target_url = MOCK_TARGET_URLS.get(service_name)`);
|
|
345
|
+
lines.push(` if target_url:`);
|
|
346
|
+
lines.push(` for mock in mocks:`);
|
|
347
|
+
lines.push(` mock.url = target_url`);
|
|
348
|
+
lines.push(` all_mocks.extend(mocks)`);
|
|
349
|
+
lines.push(``);
|
|
350
|
+
lines.push(` if all_mocks:`);
|
|
351
|
+
lines.push(` client.apply_mock(all_mocks)`);
|
|
352
|
+
if (traceComments?.length) {
|
|
353
|
+
lines.push(``);
|
|
354
|
+
for (const comment of traceComments) {
|
|
355
|
+
lines.push(`# Mock trace: ${comment}`);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return lines.join("\n");
|
|
359
|
+
}
|
|
360
|
+
function extractMockCommandLine(mockFile) {
|
|
361
|
+
if (!fs.existsSync(mockFile))
|
|
362
|
+
return undefined;
|
|
363
|
+
return fs
|
|
364
|
+
.readFileSync(mockFile, "utf-8")
|
|
365
|
+
.split("\n")
|
|
366
|
+
.map((line) => line.replace(/^\s*#\s?/, "").trim())
|
|
367
|
+
.find((line) => line.startsWith("Command: skyramp generate mock "));
|
|
368
|
+
}
|
|
369
|
+
function extractProtocolFromCommandLine(commandLine, mockFile) {
|
|
370
|
+
const protocolMatch = commandLine?.match(/skyramp generate mock (rest|grpc|kafka)\b/);
|
|
371
|
+
if (protocolMatch?.[1])
|
|
372
|
+
return protocolMatch[1];
|
|
373
|
+
const baseName = path.basename(mockFile).toLowerCase();
|
|
374
|
+
if (baseName.includes("kafka"))
|
|
375
|
+
return MockProtocol.Kafka;
|
|
376
|
+
if (baseName.includes("grpc"))
|
|
377
|
+
return MockProtocol.Grpc;
|
|
378
|
+
return MockProtocol.Rest;
|
|
379
|
+
}
|
|
380
|
+
function extractBaseUrlFromCommandLine(commandLine) {
|
|
381
|
+
if (!commandLine)
|
|
382
|
+
return undefined;
|
|
383
|
+
const commandMatch = commandLine.match(/skyramp generate mock (?:rest|grpc|kafka)\s+([^\s\\]+)/);
|
|
384
|
+
if (!commandMatch || commandMatch[1].startsWith("--"))
|
|
385
|
+
return undefined;
|
|
386
|
+
return normalizeMockCommandTarget(commandMatch[1]);
|
|
387
|
+
}
|
|
388
|
+
function uniquePythonIdentifier(raw, used) {
|
|
389
|
+
const base = raw.replace(/\W|^(?=\d)/g, "_");
|
|
390
|
+
let candidate = base;
|
|
391
|
+
let suffix = 2;
|
|
392
|
+
while (used.has(candidate)) {
|
|
393
|
+
candidate = `${base}_${suffix}`;
|
|
394
|
+
suffix += 1;
|
|
395
|
+
}
|
|
396
|
+
used.add(candidate);
|
|
397
|
+
return candidate;
|
|
398
|
+
}
|
|
399
|
+
function normalizeMockCommandTarget(target) {
|
|
400
|
+
if (!target)
|
|
401
|
+
return undefined;
|
|
402
|
+
try {
|
|
403
|
+
const endpointUrl = new URL(target);
|
|
404
|
+
if (endpointUrl.origin !== "null")
|
|
405
|
+
return endpointUrl.origin;
|
|
406
|
+
}
|
|
407
|
+
catch {
|
|
408
|
+
// Fall through to host:port handling below.
|
|
409
|
+
}
|
|
410
|
+
// gRPC and Kafka mock targets are usually service host:port values without a URL scheme.
|
|
411
|
+
return /^[A-Za-z0-9_.-]+:\d+$/.test(target) ? target : undefined;
|
|
412
|
+
}
|
|
413
|
+
// Exported for testing
|
|
414
|
+
export { injectMockImports, buildMockImportBlock };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|