Skip to content
Merged
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
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

238 changes: 231 additions & 7 deletions packages/sdk-generator/__tests__/backends/python.test.ts

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/sdk-generator/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@archastro/sdk-generator",
"version": "0.3.2",
"version": "0.4.0",
"description": "Generate typed TypeScript and Python SDKs (plus contract tests) from an OpenAPI spec.",
"keywords": [
"openapi",
Expand Down
116 changes: 106 additions & 10 deletions packages/sdk-generator/src/backends/contract-tests/python-emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ function emitResourceTestFile(
}
cb.line();
cb.line("import pytest");
cb.line("from archastro.platform import PlatformClient");
cb.line("from archastro.platform import AsyncPlatformClient, PlatformClient");
cb.line("from archastro.platform.runtime.http_client import ApiError");
cb.line();
cb.line();
Expand All @@ -95,10 +95,28 @@ function emitResourceTestFile(
cb.line(' access_token="test-token",');
cb.line(" )");
cb.line();
cb.line();
cb.line("def _async_client() -> AsyncPlatformClient:");
cb.line(" return AsyncPlatformClient(");
cb.line(" base_url=PRISM_URL,");
cb.line(' default_headers={"x-archastro-api-key": "pk_test-key"},');
cb.line(' access_token="test-token",');
cb.line(" )");
cb.line();
cb.line();
cb.line("def _async_error_client(code: int) -> AsyncPlatformClient:");
cb.line(" return AsyncPlatformClient(");
cb.line(" base_url=PRISM_URL,");
cb.line(' default_headers={"x-archastro-api-key": "pk_test-key", "Prefer": f"code={code}"},');
cb.line(' access_token="test-token",');
cb.line(" )");
cb.line();

for (const call of calls) {
emitHappyPathTest(cb, call);
emitErrorTests(cb, call);
emitAsyncHappyPathTest(cb, call);
emitAsyncErrorTests(cb, call);
}

return cb.toString();
Expand Down Expand Up @@ -170,24 +188,29 @@ function emitHappyPathTest(cb: CodeBuilder, call: MethodCallInfo): void {
const returnsNoContent = call.operation.returnType.kind === "void";

cb.line();
cb.line(`async def ${testName}():`);
cb.line(`def ${testName}():`);
cb.indent();
cb.line("client = _client()");
cb.pyBlock("try", () => {
if (returnsNoContent) {
cb.line(`result = await ${methodCall}`);
cb.line(`result = ${methodCall}`);
cb.line("assert result is None");
} else if (call.operation.rawResponse) {
cb.line(`result = await ${methodCall}`);
cb.line(`result = ${methodCall}`);
cb.line('assert result["content"] is not None');
cb.line('assert result["mime_type"]')
} else {
cb.line(`result = await ${methodCall}`);
cb.line(`result = ${methodCall}`);
cb.line("assert result is not None");
if (hasDataArray) {
cb.line('assert "data" in result');
cb.line('assert isinstance(result["data"], list)');
}
}
});
cb.pyBlock("finally", () => {
cb.line("client.close()");
});
cb.dedent();
}

Expand All @@ -209,14 +232,83 @@ function emitErrorTests(cb: CodeBuilder, call: MethodCallInfo): void {
const methodCall = `ec.${chainPy}.${pythonParameterName(call.methodName)}(${argStr})`;

cb.line();
cb.line(`async def ${testName}():`);
cb.line(`def ${testName}():`);
cb.indent();
cb.line(`ec = _error_client(${code})`);
cb.line("with pytest.raises(ApiError) as exc_info:");
cb.indent();
cb.line(`await ${methodCall}`);
cb.pyBlock("try", () => {
cb.line("with pytest.raises(ApiError) as exc_info:");
cb.indent();
cb.line(methodCall);
cb.dedent();
cb.line(`assert exc_info.value.status == ${code}`);
});
cb.pyBlock("finally", () => {
cb.line("ec.close()");
});
cb.dedent();
cb.line(`assert exc_info.value.status == ${code}`);
}
}

function emitAsyncHappyPathTest(cb: CodeBuilder, call: MethodCallInfo): void {
const testName = buildAsyncTestName(call, "success");
const argStr = buildPythonArgs(call);
const chainPy = call.accessorChain.replace("client.", "");
const methodCall = `client.${chainPy}.${pythonParameterName(call.methodName)}(${argStr})`;
const hasDataArray = returnTypeHasDataArray(call.operation.returnType);
const returnsNoContent = call.operation.returnType.kind === "void";

cb.line();
cb.line("@pytest.mark.asyncio");
cb.line(`async def ${testName}():`);
cb.indent();
cb.line("client = _async_client()");
cb.pyBlock("try", () => {
if (returnsNoContent) {
cb.line(`result = await ${methodCall}`);
cb.line("assert result is None");
} else if (call.operation.rawResponse) {
cb.line(`result = await ${methodCall}`);
cb.line('assert result["content"] is not None');
cb.line('assert result["mime_type"]');
} else {
cb.line(`result = await ${methodCall}`);
cb.line("assert result is not None");
if (hasDataArray) {
cb.line('assert "data" in result');
cb.line('assert isinstance(result["data"], list)');
}
}
});
cb.pyBlock("finally", () => {
cb.line("await client.close()");
});
cb.dedent();
}

function emitAsyncErrorTests(cb: CodeBuilder, call: MethodCallInfo): void {
for (const code of call.errorCodes) {
if (code < 400) continue;

const testName = buildAsyncTestName(call, `error_${code}`);
const argStr = buildPythonArgs(call);
const chainPy = call.accessorChain.replace("client.", "");
const methodCall = `ec.${chainPy}.${pythonParameterName(call.methodName)}(${argStr})`;

cb.line();
cb.line("@pytest.mark.asyncio");
cb.line(`async def ${testName}():`);
cb.indent();
cb.line(`ec = _async_error_client(${code})`);
cb.pyBlock("try", () => {
cb.line("with pytest.raises(ApiError) as exc_info:");
cb.indent();
cb.line(`await ${methodCall}`);
cb.dedent();
cb.line(`assert exc_info.value.status == ${code}`);
});
cb.pyBlock("finally", () => {
cb.line("await ec.close()");
});
cb.dedent();
}
}
Expand All @@ -229,6 +321,10 @@ function buildTestName(call: MethodCallInfo, suffix: string): string {
return `test_${parts.join("_")}_${snakeCase(call.methodName)}_${suffix}`;
}

function buildAsyncTestName(call: MethodCallInfo, suffix: string): string {
return buildTestName(call, suffix).replace(/^test_/, "test_async_");
}

function emitConftest(opts: {
includePrism: boolean;
includeHarness: boolean;
Expand Down
84 changes: 81 additions & 3 deletions packages/sdk-generator/src/backends/python/auth-emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function emitPythonAuthFile(spec: SdkSpec): string {
cb.line();
cb.line("from dataclasses import dataclass");
cb.line();
cb.line("from .runtime.http_client import HttpClient");
cb.line("from .runtime.http_client import HttpClient, SyncHttpClient");
cb.line();
cb.line();

Expand All @@ -43,8 +43,7 @@ export function emitPythonAuthFile(spec: SdkSpec): string {
cb.line();
}

// AuthClient
cb.pyBlock("class AuthClient", () => {
cb.pyBlock("class AsyncAuthClient", () => {
cb.pyBlock("def __init__(self, http: HttpClient)", () => {
cb.line("self._http = http");
});
Expand All @@ -54,6 +53,19 @@ export function emitPythonAuthFile(spec: SdkSpec): string {
emitAuthMethod(cb, op, tokenFields, spec.schemas);
}
});
cb.line();
cb.line();

cb.pyBlock("class AuthClient", () => {
cb.pyBlock("def __init__(self, http: SyncHttpClient)", () => {
cb.line("self._http = http");
});

for (const op of authOps) {
cb.line();
emitSyncAuthMethod(cb, op, tokenFields, spec.schemas);
}
});

return cb.toString();
}
Expand Down Expand Up @@ -193,6 +205,72 @@ function emitAuthMethod(
});
}

function emitSyncAuthMethod(
cb: CodeBuilder,
op: OperationDef,
tokenFields: TokenFieldInfo[],
schemas: SchemaDef[]
): void {
const methodName = pyAuthMethodName(op);
const params = extractPythonAuthInputParams(op);
const responseFields = getResponseFields(op.returnType, schemas);
const hasTokenReturn = responseFields.some((field) => Boolean(field.sdkRole));
const returnType = hasTokenReturn ? "AuthTokens" : "dict";
const requiredParams = params.filter((p) => p.required);
const optionalParams = params.filter((p) => !p.required);
const sortedParams = [...requiredParams, ...optionalParams];
const sig = sortedParams
.map((p) => {
if (p.required) return `${p.name}: str`;
return `${p.name}: str | None = None`;
})
.join(", ");
const methodParams = sig ? `self, ${sig}` : "self";

cb.pyBlock(`def ${methodName}(${methodParams}) -> ${returnType}`, () => {
if (sortedParams.length > 0) {
cb.line("body: dict[str, object] = {}");
for (const p of sortedParams) {
if (p.required) {
cb.line(`body["${p.originalName}"] = ${p.name}`);
} else {
cb.pyBlock(`if ${p.name} is not None`, () => {
cb.line(`body["${p.originalName}"] = ${p.name}`);
});
}
}
cb.line();
}

cb.line("data = self._http.request(");
cb.indent();
cb.line(`"${op.path}",`);
cb.line(`method="${op.method}",`);
if (sortedParams.length > 0) {
cb.line("body=body,");
}
cb.dedent();
cb.line(")");

if (hasTokenReturn) {
cb.line("return AuthTokens(");
cb.indent();
for (const tf of tokenFields) {
const field = responseFields.find((f) => f.sdkRole === tf.role);
if (field) {
cb.line(`${pythonParameterName(tf.role)}=data.get("${field.name}"),`);
} else {
cb.line(`${pythonParameterName(tf.role)}=None,`);
}
}
cb.dedent();
cb.line(")");
} else {
cb.line("return data");
}
});
}

export function extractPythonAuthInputParams(op: OperationDef): AuthParam[] {
const entries: Array<Omit<AuthParam, "name">> = [];

Expand Down
Loading
Loading