-
Notifications
You must be signed in to change notification settings - Fork 310
Expand file tree
/
Copy pathWireTestGenerator.ts
More file actions
819 lines (723 loc) · 33.5 KB
/
WireTestGenerator.ts
File metadata and controls
819 lines (723 loc) · 33.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
import { FernGeneratorExec } from "@fern-api/browser-compatible-base-generator";
import { FernIr as DynamicFernIr } from "@fern-api/dynamic-ir-sdk";
import { RelativeFilePath } from "@fern-api/fs-utils";
import { WireMockMapping } from "@fern-api/mock-utils";
import { python } from "@fern-api/python-ast";
import { WriteablePythonFile } from "@fern-api/python-base";
import { DynamicSnippetsGenerator } from "@fern-api/python-dynamic-snippets";
import { FernIr } from "@fern-fern/ir-sdk";
import { SdkGeneratorContext } from "../SdkGeneratorContext.js";
import { WireTestSetupGenerator } from "./WireTestSetupGenerator.js";
/**
* Local interface for wire test examples.
* Contains only the fields needed for wire test generation, avoiding coupling to FernIr.dynamic.EndpointExample.
*/
interface WireTestExample {
name?: string;
pathParameters: Record<string, unknown>;
queryParameters: Record<string, unknown>;
headers: Record<string, unknown>;
requestBody?: unknown;
}
/**
* Generates WireMock-based integration tests for Python SDK.
*
* This is a skeleton implementation that sets up the infrastructure for wire tests
* but does not implement the actual Python test code generation.
*/
export class WireTestGenerator {
private readonly context: SdkGeneratorContext;
private dynamicIr: FernIr.dynamic.DynamicIntermediateRepresentation;
private wireMockConfigContent: Record<string, WireMockMapping>;
private snippetGenerator: DynamicSnippetsGenerator;
constructor(context: SdkGeneratorContext, ir: FernIr.IntermediateRepresentation) {
this.context = context;
const dynamicIr = ir.dynamic;
if (!dynamicIr) {
throw new Error("Cannot generate wire tests without dynamic IR");
}
this.dynamicIr = dynamicIr;
this.wireMockConfigContent = this.getWireMockConfigContent();
// TODO(tjdbdc): Really need a migration framework for FernIr.dynamic IR
this.snippetGenerator = new DynamicSnippetsGenerator({
ir: this.dynamicIr,
config: {
organization: context.config.organization,
workspaceName: context.config.workspaceName,
customConfig: context.customConfig
} as FernGeneratorExec.GeneratorConfig
});
}
// =============================================================================
// PUBLIC API
// =============================================================================
public async generate(): Promise<void> {
const endpointsByService = this.groupEndpointsByService();
this.context.logger.debug(
`Wire tests: ${endpointsByService.size} services, ${Object.keys(this.dynamicIr.endpoints).length} dynamic endpoints`
);
let totalEndpointsWithExamples = 0;
for (const [serviceName, endpoints] of endpointsByService.entries()) {
// Filter to endpoints that have static IR examples
// We MUST use static IR examples to match WireMock mappings (which are generated from static IR)
const endpointsWithExamples = endpoints.filter((endpoint) => {
const staticExample = this.getStaticIrExample(endpoint);
return staticExample !== undefined;
});
totalEndpointsWithExamples += endpointsWithExamples.length;
if (endpointsWithExamples.length === 0) {
continue;
}
const serviceTestFile = await this.generateServiceTestFile(serviceName, endpointsWithExamples);
if (serviceTestFile) {
this.context.project.addSourceFiles(serviceTestFile);
}
}
this.context.logger.debug(`Wire tests: ${totalEndpointsWithExamples} endpoints with static IR examples`);
// Generate docker-compose.test.yml and wiremock-mappings.json for WireMock
new WireTestSetupGenerator(this.context, this.context.ir).generate();
}
/**
* Gets the first available example from the static IR for an endpoint.
* Prefers user-specified examples over autogenerated ones.
*/
private getStaticIrExample(endpoint: FernIr.HttpEndpoint): FernIr.ExampleEndpointCall | undefined {
// Prefer user-specified OK examples (WireMock mappings are generated from successful examples).
for (const userExample of endpoint.userSpecifiedExamples) {
if (userExample.example && userExample.example.response.type === "ok") {
return userExample.example;
}
}
// Then fall back to any user-specified example
for (const userExample of endpoint.userSpecifiedExamples) {
if (userExample.example) {
return userExample.example;
}
}
// Prefer autogenerated OK examples
for (const autoExample of endpoint.autogeneratedExamples) {
if (autoExample.example && autoExample.example.response.type === "ok") {
return autoExample.example;
}
}
// Then fall back to any autogenerated example
for (const autoExample of endpoint.autogeneratedExamples) {
if (autoExample.example) {
return autoExample.example;
}
}
return undefined;
}
/**
* Checks if an example has an error response (non-2xx status code).
*/
private isErrorResponse(example: FernIr.ExampleEndpointCall): boolean {
// WireMock mappings produced by @fern-api/mock-utils currently only include successful
// responses (e.g. 200/201). Until error stubs are generated as well, wire tests should
// not assert ApiError behavior.
void example;
return false;
}
/**
* Converts a static IR example to a wire test example format.
*/
private convertStaticExampleToWireTest(
endpoint: FernIr.HttpEndpoint,
staticExample: FernIr.ExampleEndpointCall
): WireTestExample {
// Extract path parameters
const pathParameters: Record<string, unknown> = {};
for (const param of [
...(staticExample.rootPathParameters ?? []),
...(staticExample.servicePathParameters ?? []),
...(staticExample.endpointPathParameters ?? [])
]) {
pathParameters[param.name.originalName] = param.value.jsonExample;
}
// Extract query parameters
const queryParameters: Record<string, unknown> = {};
for (const param of staticExample.queryParameters ?? []) {
queryParameters[param.name.wireValue] = param.value.jsonExample;
}
// Extract headers
const headers: Record<string, unknown> = {};
for (const header of [...(staticExample.serviceHeaders ?? []), ...(staticExample.endpointHeaders ?? [])]) {
headers[header.name.wireValue] = header.value.jsonExample;
}
// Extract request body
let requestBody: unknown = undefined;
if (staticExample.request) {
if ("jsonExample" in staticExample.request && staticExample.request.jsonExample !== undefined) {
requestBody = staticExample.request.jsonExample;
}
}
return {
name: staticExample.name?.originalName,
pathParameters,
queryParameters,
headers,
requestBody
};
}
// =============================================================================
// FILE GENERATION
// =============================================================================
private async generateServiceTestFile(
serviceName: string,
endpoints: FernIr.HttpEndpoint[]
): Promise<WriteablePythonFile | null> {
const endpointTestCases: Array<{
endpoint: FernIr.HttpEndpoint;
example: WireTestExample;
service: FernIr.HttpService;
exampleIndex: number;
isErrorResponse: boolean;
}> = [];
for (const endpoint of endpoints) {
// Find the service that owns this endpoint
const service = Object.values(this.context.ir.services).find((s) =>
s.endpoints.some((e) => e.id === endpoint.id)
);
if (!service) {
continue;
}
// Skip bytes request body endpoints — the IR example system has no
// ExampleRequestBody variant for bytes, so we can't produce a proper example.
if (endpoint.requestBody?.type === "bytes") {
continue;
}
// Always use static IR examples to match WireMock mappings
// WireMock mappings are generated from static IR examples, so we must use the same examples
const staticExample = this.getStaticIrExample(endpoint);
if (staticExample) {
const wireTestExample = this.convertStaticExampleToWireTest(endpoint, staticExample);
const isErrorResponse = this.isErrorResponse(staticExample);
endpointTestCases.push({
endpoint,
example: wireTestExample,
service,
exampleIndex: 0,
isErrorResponse
});
}
}
if (endpointTestCases.length === 0) {
return null;
}
this.context.logger.info(
`Generating test file for service ${serviceName} with ${endpointTestCases.length} test cases`
);
const pythonFile = this.buildTestFile(serviceName, endpointTestCases);
if (pythonFile === null) {
return null;
}
return new WriteablePythonFile({
filename: `test_${serviceName}`,
directory: RelativeFilePath.of("tests/wire"),
contents: pythonFile
});
}
// =============================================================================
// FILE BUILDING
// =============================================================================
private buildTestFile(
serviceName: string,
testCases: Array<{
endpoint: FernIr.HttpEndpoint;
example: WireTestExample;
service: FernIr.HttpService;
exampleIndex: number;
isErrorResponse: boolean;
}>
): python.PythonFile | null {
const statements: python.AstNode[] = [];
// Add raw imports for pytest (not supported by AST)
statements.push(python.codeBlock("import pytest"));
// Add an import registration statement (for "from X import Y" style imports)
statements.push(this.createImportRegistration());
// Add test functions for each endpoint
let testFunctionCount = 0;
for (const { endpoint, example, service, exampleIndex, isErrorResponse } of testCases) {
const testFunction = this.generateEndpointTestFunction(
serviceName,
endpoint,
example,
service,
exampleIndex,
isErrorResponse
);
if (testFunction) {
statements.push(testFunction);
testFunctionCount++;
}
}
if (testFunctionCount === 0) {
return null;
}
const pathSegments = `tests/wire/test_${serviceName}`.split("/");
return python.file({
path: pathSegments,
statements
});
}
/**
* Creates a special node that registers imports without rendering anything.
* This is a workaround for using codeBlock while still getting automatic "from X import Y" imports.
*/
private createImportRegistration(): python.AstNode {
// Create an empty code block
const node = python.codeBlock("");
// Import get_client and verify_request_count from .conftest (relative import within tests/wire package)
node.addReference(python.reference({ name: "get_client", modulePath: [".conftest"] }));
node.addReference(python.reference({ name: "verify_request_count", modulePath: [".conftest"] }));
// Import ApiError from the SDK's core module for error response tests
const modulePath = this.context.getModulePath();
node.addReference(python.reference({ name: "ApiError", modulePath: [modulePath, "core"] }));
return node;
}
// =============================================================================
// TEST FUNCTION GENERATION
// =============================================================================
private generateEndpointTestFunction(
serviceName: string,
endpoint: FernIr.HttpEndpoint,
example: WireTestExample,
service: FernIr.HttpService,
exampleIndex: number,
isErrorResponse: boolean
): python.Method | null {
try {
const testName = this.getTestFunctionName(serviceName, endpoint);
const basePath = this.buildBasePath(endpoint);
const queryParamsCode = this.buildQueryParamsCode(endpoint);
// Build deterministic test ID based on fully qualified path
const testId = this.buildDeterministicTestId(service, endpoint, exampleIndex);
const statements: python.AstNode[] = [];
// Use deterministic test ID for concurrency safety
statements.push(python.codeBlock(`test_id = "${testId}"`));
// Create client using the get_client helper from conftest.py
// This ensures all required auth parameters are supplied with fake values
statements.push(python.codeBlock(`client = get_client(test_id)`));
// Exclusions use definition-level identifiers in the form "<service_path>.<endpoint_name>"
// or "<service_path>.*" to exclude an entire service.
const servicePathParts = service.name.fernFilepath.allParts.map((part) => part.snakeCase.safeName);
const servicePath = servicePathParts.join(".");
const selector =
servicePath.length > 0
? `${servicePath}.${endpoint.name.snakeCase.safeName}`
: endpoint.name.snakeCase.safeName;
const excluded = this.context.customConfig.wire_tests?.exclusions ?? [];
if (
excluded.includes(selector) ||
excluded.some((pattern) => pattern.endsWith(".*") && selector.startsWith(pattern.slice(0, -2) + "."))
) {
return null;
}
// Generate the API call AST directly
const apiCallAst = this.generateApiCallAst(endpoint, example);
// For error responses, wrap in pytest.raises() to expect the exception
if (isErrorResponse) {
// For streaming endpoints, we need to consume the iterator inside pytest.raises
if (this.isStreamingEndpoint(endpoint)) {
const block = python.codeBlock(
`with pytest.raises(ApiError):\n for _ in ${apiCallAst.toString()}:\n pass`
);
// Preserve import references from the AST that are lost during toString()
for (const ref of apiCallAst.getReferences()) {
block.addReference(ref);
}
statements.push(block);
} else {
const block = python.codeBlock(`with pytest.raises(ApiError):\n ${apiCallAst.toString()}`);
for (const ref of apiCallAst.getReferences()) {
block.addReference(ref);
}
statements.push(block);
}
} else {
// For streaming endpoints, wrap the call in a for loop to consume the iterator
// This is necessary because streaming methods return lazy generators that don't
// execute the HTTP request until iterated
if (this.isStreamingEndpoint(endpoint)) {
const block = python.codeBlock(`for _ in ${apiCallAst.toString()}:`);
// Preserve import references from the AST that are lost during toString()
for (const ref of apiCallAst.getReferences()) {
block.addReference(ref);
}
statements.push(block);
statements.push(python.codeBlock(" pass"));
} else {
statements.push(apiCallAst);
}
}
// Verify request count using test ID for filtering
// When testing the auth token endpoint itself, expect 2 requests:
// 1. The automatic token fetch request (from OAuth/inferred auth)
// 2. The actual API call being tested
// For all other endpoints, expect 1 request (the auth token fetch goes to a different endpoint)
const expectedRequestCount =
this.isInferredAuthTokenEndpoint(endpoint) || this.isOAuthTokenEndpoint(endpoint) ? 2 : 1;
statements.push(
python.codeBlock(
`verify_request_count(test_id, "${endpoint.method}", "${basePath}", ${queryParamsCode}, ${expectedRequestCount})`
)
);
const method = python.method({
name: testName,
return_: python.Type.none(),
docstring: `Test ${endpoint.name.originalName} endpoint with WireMock`
});
statements.forEach((stmt) => method.addStatement(stmt));
return method;
} catch (error) {
this.context.logger.warn(`Failed to generate test function for endpoint ${endpoint.id}: ${error}`);
return null;
}
}
/**
* Checks if the IR has any inferred auth schemes.
* When inferred auth is present, the client will make an additional request to get a token.
*/
private hasInferredAuth(): boolean {
if (!this.context.ir.auth?.schemes) {
return false;
}
return this.context.ir.auth.schemes.some((scheme) => scheme.type === "inferred");
}
/**
* Checks if an endpoint is the inferred auth token endpoint.
* When testing the auth token endpoint with inferred auth, expect 2 requests:
* 1. The automatic token fetch request
* 2. The actual API call being tested
*/
private isInferredAuthTokenEndpoint(endpoint: FernIr.HttpEndpoint): boolean {
if (!this.context.ir.auth?.schemes) {
return false;
}
for (const scheme of this.context.ir.auth.schemes) {
if (scheme.type === "inferred") {
const tokenEndpointId = scheme.tokenEndpoint.endpoint.endpointId;
if (endpoint.id === tokenEndpointId) {
return true;
}
}
}
return false;
}
/**
* Checks if an endpoint is the OAuth token endpoint.
* When testing the token endpoint with OAuth client credentials, expect 2 requests:
* 1. The automatic token fetch request (from the OAuth token provider)
* 2. The actual API call being tested
*/
private isOAuthTokenEndpoint(endpoint: FernIr.HttpEndpoint): boolean {
if (!this.context.ir.auth?.schemes) {
return false;
}
for (const scheme of this.context.ir.auth.schemes) {
if (scheme.type === "oauth" && scheme.configuration?.type === "clientCredentials") {
const tokenEndpointId = scheme.configuration.tokenEndpoint.endpointReference.endpointId;
if (endpoint.id === tokenEndpointId) {
return true;
}
}
}
return false;
}
/**
* Checks if an endpoint returns a streaming response.
* Streaming endpoints return Iterator[bytes] or AsyncIterator[bytes] which are lazy generators.
* This includes:
* - streaming: SSE or other streaming responses
* - streamParameter: Responses controlled by a stream parameter
* - fileDownload: File download responses that return an iterator of bytes
*/
private isStreamingEndpoint(endpoint: FernIr.HttpEndpoint): boolean {
const responseBody = endpoint.response?.body;
if (!responseBody) {
return false;
}
return (
responseBody.type === "streaming" ||
responseBody.type === "streamParameter" ||
responseBody.type === "fileDownload"
);
}
/**
* Builds a deterministic test ID based on the fully qualified service path.
* Format: service.sub_service.endpoint_name.example_index
* This ensures test IDs are unique per test and deterministic across regenerations.
*/
private buildDeterministicTestId(
service: FernIr.HttpService,
endpoint: FernIr.HttpEndpoint,
exampleIndex: number
): string {
const servicePathParts = service.name.fernFilepath.allParts.map((part) => part.snakeCase.safeName);
const endpointName = endpoint.name.snakeCase.safeName;
const segments: string[] = [];
if (servicePathParts.length > 0) {
segments.push(servicePathParts.join("."));
}
segments.push(endpointName);
segments.push(String(exampleIndex));
// Example: "endpoints.primitive.get_and_return_string.0"
return segments.join(".");
}
// =============================================================================
// API CALL GENERATION
// =============================================================================
/**
* Builds the path template for an endpoint in the format expected by the snippet generator.
* Example: "/users/{userId}/posts/{postId}"
*/
private buildPathTemplate(endpoint: FernIr.HttpEndpoint): string {
let path = endpoint.fullPath.head;
for (const part of endpoint.fullPath.parts) {
path += `{${part.pathParameter}}${part.tail}`;
}
// Ensure the path starts with a leading slash to match FernIr.dynamic IR format
if (!path.startsWith("/")) {
path = "/" + path;
}
return path;
}
private generateApiCallAst(endpoint: FernIr.HttpEndpoint, example: WireTestExample): python.AstNode {
try {
// Build the snippet request
const snippetRequest: DynamicFernIr.dynamic.EndpointSnippetRequest = {
endpoint: {
method: endpoint.method,
path: this.buildPathTemplate(endpoint)
},
baseURL: "http://localhost:8080",
pathParameters: example.pathParameters,
queryParameters: example.queryParameters,
headers: example.headers,
requestBody: example.requestBody
};
// If this is a multipart/file-upload endpoint, static examples often omit file content.
// However, generated Python client methods can require these file parameters. To keep
// wire tests runnable and generic, synthesize placeholder file values for any required
// file fields that are missing from the example request body.
this.addPlaceholderFileUploadFields({ endpoint, snippetRequest });
// Generate just the method call AST using DynamicSnippetsGenerator
// Pass endpointId to avoid path collision issues when multiple
// namespaces have endpoints with the same HTTP method and path pattern
return this.snippetGenerator.generateMethodCallSnippetAst({
request: snippetRequest,
options: { endpointId: endpoint.id }
});
} catch (error) {
// Fallback: log error and generate a placeholder
this.context.logger.error(
`Failed to generate API call for endpoint ${endpoint.name.originalName}: ${error}`
);
throw error;
}
}
private addPlaceholderFileUploadFields({
endpoint,
snippetRequest
}: {
endpoint: FernIr.HttpEndpoint;
snippetRequest: DynamicFernIr.dynamic.EndpointSnippetRequest;
}): void {
const requestBody = endpoint.requestBody;
if (requestBody?.type !== "fileUpload" || !Array.isArray(requestBody.properties)) {
return;
}
const record =
typeof snippetRequest.requestBody === "object" && snippetRequest.requestBody != null
? (snippetRequest.requestBody as Record<string, unknown>)
: {};
for (const property of requestBody.properties) {
if (property.type !== "file") {
continue;
}
const fileValue = property.value;
const key = fileValue.key;
if (key.wireValue == null || fileValue.isOptional || record[key.wireValue] != null) {
continue;
}
const placeholder = `example_${key.wireValue}`;
record[key.wireValue] = fileValue.type === "fileArray" ? [placeholder] : placeholder;
}
snippetRequest.requestBody = record;
}
/**
* Escapes a string for use in Python code.
* Handles newlines, tabs, carriage returns, backslashes, and quotes.
*/
private escapeStringForPython(value: string): string {
return value
.replace(/\\/g, "\\\\") // Escape backslashes first
.replace(/\n/g, "\\n") // Escape newlines
.replace(/\r/g, "\\r") // Escape carriage returns
.replace(/\t/g, "\\t") // Escape tabs
.replace(/"/g, '\\"'); // Escape double quotes
}
// =============================================================================
// PATH AND QUERY PARAMETER HELPERS
// =============================================================================
/**
* Checks if a query parameter is typed as datetime (DATE_TIME) in the IR.
* Handles optional/nullable wrappers by unwrapping to the inner type.
* String-typed parameters that happen to contain datetime-looking values return false.
*/
private isDatetimeTypedQueryParam(endpoint: FernIr.HttpEndpoint, wireKey: string): boolean {
const queryParam = endpoint.queryParameters.find((qp) => qp.name.wireValue === wireKey);
if (!queryParam) {
return false;
}
return this.isDatetimeTypeReference(queryParam.valueType);
}
/**
* Recursively checks if a TypeReference resolves to a datetime primitive.
* Unwraps optional/nullable containers to check the inner type.
*/
private isDatetimeTypeReference(typeRef: FernIr.TypeReference): boolean {
if (typeRef.type === "primitive") {
return typeRef.primitive.v1 === "DATE_TIME";
}
if (typeRef.type === "container") {
if (typeRef.container.type === "optional") {
return this.isDatetimeTypeReference(typeRef.container.optional);
}
if (typeRef.container.type === "nullable") {
return this.isDatetimeTypeReference(typeRef.container.nullable);
}
}
return false;
}
/**
* Normalizes a query parameter value for datetime_milliseconds config.
* When datetime_milliseconds is true AND the parameter is datetime-typed, adds ".000" to
* datetime values that lack fractional seconds so the test verification matches the SDK's
* millisecond-precision output from serialize_datetime.
* String-typed parameters are never normalized because the SDK passes them through as-is.
*/
private normalizeDatetimeQueryParamValue(value: string, isDatetimeTyped: boolean): string {
if (this.context.customConfig.datetime_milliseconds && isDatetimeTyped) {
// Use replace with a capture group to insert ".000" before the timezone suffix.
// The regex matches the seconds portion followed by the timezone (Z or +/-offset).
return value.replace(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(Z|[+-]\d{2}:\d{2})$/, "$1.000$2");
}
return value;
}
private buildQueryParamsCode(endpoint: FernIr.HttpEndpoint): string {
const dynamicEndpoint = this.dynamicIr.endpoints[endpoint.id];
if (!dynamicEndpoint?.examples?.[0]?.queryParameters) {
return "None";
}
const queryParams = dynamicEndpoint.examples[0].queryParameters;
const entries: string[] = [];
for (const [key, value] of Object.entries(queryParams)) {
if (value != null) {
const isDatetimeTyped = this.isDatetimeTypedQueryParam(endpoint, key);
const normalized = this.normalizeDatetimeQueryParamValue(String(value), isDatetimeTyped);
entries.push(`"${this.escapeStringForPython(key)}": "${this.escapeStringForPython(normalized)}"`);
}
}
if (entries.length === 0) {
return "None";
}
return `{${entries.join(", ")}}`;
}
// =============================================================================
// UTILITY METHODS
// =============================================================================
private getTestFunctionName(serviceName: string, endpoint: FernIr.HttpEndpoint): string {
const endpointName = endpoint.name.snakeCase.safeName;
return `test_${serviceName}_${endpointName}`;
}
private getClientModulePath(): string[] {
// The client is imported from the root package module
// e.g., "from seed import SeedExhaustive" -> modulePath is ["seed"]
return [this.context.getModulePath()];
}
private getClientClassName(): string {
// The client class name follows the pattern: OrganizationWorkspace
// For seed_exhaustive, it would be SeedExhaustive
const orgName = this.context.config.organization;
const workspaceName = this.context.config.workspaceName;
// Convert to PascalCase
const toPascalCase = (str: string) => {
return str
.split(/[-_]/)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
.join("");
};
return toPascalCase(orgName) + toPascalCase(workspaceName);
}
// =============================================================================
// =============================================================================
private wiremockMappingKey({
requestMethod,
requestUrlPathTemplate
}: {
requestMethod: string;
requestUrlPathTemplate: string;
}): string {
return `${requestMethod} - ${requestUrlPathTemplate}`;
}
private getWireMockConfigContent(): Record<string, WireMockMapping> {
const out: Record<string, WireMockMapping> = {};
const wiremockStubMapping = WireTestSetupGenerator.getWiremockConfigContent(this.context.ir);
for (const mapping of wiremockStubMapping.mappings) {
const key = this.wiremockMappingKey({
requestMethod: mapping.request.method,
requestUrlPathTemplate: mapping.request.urlPathTemplate
});
out[key] = mapping;
}
return out;
}
// =============================================================================
// =============================================================================
private buildBasePath(endpoint: FernIr.HttpEndpoint): string {
let basePath = endpoint.fullPath.head;
for (const part of endpoint.fullPath.parts || []) {
basePath += `{${part.pathParameter}}${part.tail}`;
}
if (!basePath.startsWith("/")) {
basePath = "/" + basePath;
}
// Strip URL fragment - fragments are never sent to the server in HTTP requests
// e.g., "/oauth2/token#refresh" -> "/oauth2/token"
const fragmentIndex = basePath.indexOf("#");
if (fragmentIndex !== -1) {
basePath = basePath.substring(0, fragmentIndex);
}
// Substitute path parameters with actual values from WireMock mapping
// Use the path WITHOUT fragment to look up the mapping, since mock-utils strips fragments
const mappingKey = this.wiremockMappingKey({
requestMethod: endpoint.method,
requestUrlPathTemplate: basePath
});
const wiremockMapping = this.wireMockConfigContent[mappingKey];
if (wiremockMapping && wiremockMapping.request.pathParameters) {
Object.entries(wiremockMapping.request.pathParameters).forEach(([paramName, paramValue]) => {
const pathParam = paramValue as { equalTo: string };
basePath = basePath.replace(`{${paramName}}`, pathParam.equalTo);
});
}
return basePath;
}
// =============================================================================
// =============================================================================
private groupEndpointsByService(): Map<string, FernIr.HttpEndpoint[]> {
const endpointsByService = new Map<string, FernIr.HttpEndpoint[]>();
for (const service of Object.values(this.context.ir.services)) {
const serviceName = this.getFormattedServiceName(service);
const endpoints = service.endpoints;
if (endpoints.length > 0) {
endpointsByService.set(serviceName, endpoints);
}
}
return endpointsByService;
}
private getFormattedServiceName(service: FernIr.HttpService): string {
return service.name.fernFilepath.allParts.map((part) => part.camelCase.unsafeName).join("_");
}
}