From 352934c79dcc932e8c7ca2ecd6a7728447aa3747 Mon Sep 17 00:00:00 2001 From: Sarangan Rajamanickam Date: Thu, 10 Oct 2024 11:18:32 -0700 Subject: [PATCH] [cadl-ranch-*] Backport the server testing changes from typespec repository to cadl-ranch repository (#741) * Initial Commit * Format and Changeset addition --- .changeset/fifty-cherries-wave.md | 7 + packages/cadl-ranch-api/src/scenarios.ts | 32 +- packages/cadl-ranch-api/src/types.ts | 44 +- .../http/authentication/api-key/mockapi.ts | 51 +- .../authentication/http/custom/mockapi.ts | 51 +- .../http/authentication/oauth2/mockapi.ts | 48 +- .../http/authentication/union/mockapi.ts | 40 +- .../client-generator-core/access/mockapi.ts | 105 +- .../flatten-property/mockapi.ts | 38 +- .../client-generator-core/usage/mockapi.ts | 61 +- .../http/azure/core/basic/mockapi.ts | 183 +++- .../http/azure/core/lro/rpc/mockapi.ts | 85 +- .../http/azure/core/lro/standard/mockapi.ts | 260 ++++- .../http/azure/core/model/mockapi.ts | 43 +- .../http/azure/core/page/mockapi.ts | 84 +- .../http/azure/core/scalar/mockapi.ts | 82 +- .../http/azure/core/traits/mockapi.ts | 65 +- .../http/azure/example/basic/mockapi.ts | 41 +- .../common-types/managed-identity/mockapi.ts | 165 +-- .../models/resources/mockapi.ts | 963 +++++++++++------- .../client-request-id/mockapi.ts | 24 +- .../http/client/naming/mockapi.ts | 194 +++- .../client-operation-group/mockapi.ts | 28 +- .../http/client/structure/common/service.ts | 14 + .../http/client/structure/default/mockapi.ts | 40 +- .../client/structure/multi-client/mockapi.ts | 28 +- .../structure/renamed-operation/mockapi.ts | 28 +- .../structure/two-operation-group/mockapi.ts | 28 +- .../http/encode/bytes/mockapi.ts | 339 ++++-- .../http/encode/datetime/mockapi.ts | 330 ++++-- .../http/encode/duration/mockapi.ts | 223 +++- .../http/encode/numeric/mockapi.ts | 35 +- .../http/parameters/basic/mockapi.ts | 36 +- .../parameters/body-optionality/mockapi.ts | 81 +- .../parameters/collection-format/mockapi.ts | 106 +- .../http/parameters/spread/mockapi.ts | 214 +++- .../payload/content-negotiation/mockapi.ts | 221 +++- .../http/payload/json-merge-patch/mockapi.ts | 209 ++-- .../http/payload/media-type/mockapi.ts | 82 +- .../http/payload/multipart/mockapi.ts | 321 ++++-- .../http/payload/pageable/mockapi.ts | 93 +- .../http/payload/xml/mockapi.ts | 339 ++---- .../http/resiliency/srv-driven/mockapi.ts | 322 ++++-- .../cadl-ranch-specs/http/routes/mockapi.ts | 122 ++- .../encoded-name/json/mockapi.ts | 31 +- .../server/endpoint/not-defined/mockapi.ts | 17 +- .../http/server/path/multiple/mockapi.ts | 32 +- .../http/server/path/single/mockapi.ts | 17 +- .../server/versions/not-versioned/mockapi.ts | 69 +- .../http/server/versions/versioned/mockapi.ts | 84 +- .../conditional-request/mockapi.ts | 78 +- .../special-headers/repeatability/mockapi.ts | 25 +- .../http/special-words/mockapi.ts | 497 ++++++--- .../http/type/array/mockapi.ts | 166 +-- .../http/type/dictionary/mockapi.ts | 144 ++- .../http/type/enum/extensible/mockapi.ts | 70 +- .../http/type/enum/fixed/mockapi.ts | 60 +- .../http/type/model/empty/mockapi.ts | 53 +- .../inheritance/enum-discriminator/mockapi.ts | 125 ++- .../nested-discriminator/mockapi.ts | 111 +- .../inheritance/not-discriminated/mockapi.ts | 56 +- .../model/inheritance/recursive/mockapi.ts | 37 +- .../single-discriminator/mockapi.ts | 127 ++- .../http/type/model/usage/mockapi.ts | 57 +- .../http/type/model/visibility/mockapi.ts | 148 ++- .../property/additional-properties/mockapi.ts | 639 +++++++----- .../http/type/property/nullable/mockapi.ts | 251 +++-- .../http/type/property/optionality/mockapi.ts | 397 ++++---- .../http/type/property/value-types/mockapi.ts | 354 ++++--- .../http/type/scalar/mockapi.ts | 364 +++++-- .../http/type/union/mockapi.ts | 134 ++- .../http/versioning/added/mockapi.ts | 71 +- .../http/versioning/madeOptional/mockapi.ts | 22 +- .../http/versioning/removed/mockapi.ts | 24 +- .../http/versioning/renamedFrom/mockapi.ts | 49 +- .../returnTypeChangedFrom/mockapi.ts | 23 +- .../versioning/typeChangedFrom/mockapi.ts | 26 +- packages/cadl-ranch-specs/package.json | 4 + packages/cadl-ranch/package.json | 4 +- packages/cadl-ranch/src/actions/helper.ts | 104 ++ .../cadl-ranch/src/actions/server-test.ts | 172 ++++ packages/cadl-ranch/src/app/app.ts | 22 +- packages/cadl-ranch/src/cli/cli.ts | 33 + .../src/coverage/coverage-tracker.ts | 11 +- pnpm-lock.yaml | 84 ++ 85 files changed, 7406 insertions(+), 3291 deletions(-) create mode 100644 .changeset/fifty-cherries-wave.md create mode 100644 packages/cadl-ranch-specs/http/client/structure/common/service.ts create mode 100644 packages/cadl-ranch/src/actions/helper.ts create mode 100644 packages/cadl-ranch/src/actions/server-test.ts diff --git a/.changeset/fifty-cherries-wave.md b/.changeset/fifty-cherries-wave.md new file mode 100644 index 000000000..c450009cf --- /dev/null +++ b/.changeset/fifty-cherries-wave.md @@ -0,0 +1,7 @@ +--- +"@azure-tools/cadl-ranch-specs": patch +"@azure-tools/cadl-ranch-api": patch +"@azure-tools/cadl-ranch": patch +--- + +Backport the changes from typespec repository to migrate the scenarios to new model diff --git a/packages/cadl-ranch-api/src/scenarios.ts b/packages/cadl-ranch-api/src/scenarios.ts index acff4162b..872038b55 100644 --- a/packages/cadl-ranch-api/src/scenarios.ts +++ b/packages/cadl-ranch-api/src/scenarios.ts @@ -1,10 +1,22 @@ -import { KeyedMockApi, MockApi, PassByKeyScenario, PassOnCodeScenario, PassOnSuccessScenario } from "./types.js"; +import { + KeyedMockApi, + KeyedMockApiDefinition, + KeyedMockRequestHandler, + MockApi, + MockApiDefinition, + PassByKeyScenario, + PassByServiceKeyScenario, + PassOnCodeScenario, + PassOnSuccessScenario, +} from "./types.js"; /** * Specify that the scenario should be a `pass` if all the endpoints are called and the API response with 2xx exit code. * @param apis Endpoint or List of endpoints for this scenario */ -export function passOnSuccess(apis: MockApi | readonly MockApi[]): PassOnSuccessScenario { +export function passOnSuccess( + apis: MockApi | readonly MockApi[] | MockApiDefinition | readonly MockApiDefinition[], +): PassOnSuccessScenario { return { passCondition: "response-success", apis: Array.isArray(apis) ? apis : [apis], @@ -42,3 +54,19 @@ export function withKeys(keys: K[]): WithKeysScenarioExp }, }; } + +export interface WithServiceKeysScenarioExpect { + pass(api: KeyedMockApiDefinition | KeyedMockApiDefinition[]): PassByServiceKeyScenario; +} + +export function withServiceKeys(keys: K[]): WithServiceKeysScenarioExpect { + return { + pass: (api: KeyedMockApiDefinition | KeyedMockApiDefinition[]) => { + return { + passCondition: "by-key", + keys, + apis: Array.isArray(api) ? api : [api], + }; + }, + }; +} diff --git a/packages/cadl-ranch-api/src/types.ts b/packages/cadl-ranch-api/src/types.ts index c70c0db53..f195c440f 100644 --- a/packages/cadl-ranch-api/src/types.ts +++ b/packages/cadl-ranch-api/src/types.ts @@ -19,21 +19,28 @@ export type ScenarioPassCondition = "response-success" | "status-code"; export interface PassOnSuccessScenario { passCondition: "response-success"; - apis: MockApi[]; + apis: MockApi[] | MockApiDefinition[]; } export interface PassOnCodeScenario { passCondition: "status-code"; code: number; - apis: MockApi[]; + apis: MockApi[] | MockApiDefinition[]; } + export interface PassByKeyScenario { passCondition: "by-key"; keys: K[]; apis: KeyedMockApi[]; } -export type ScenarioMockApi = PassOnSuccessScenario | PassOnCodeScenario | PassByKeyScenario; +export interface PassByServiceKeyScenario { + passCondition: "by-key"; + keys: K[]; + apis: KeyedMockApiDefinition[]; +} + +export type ScenarioMockApi = PassOnSuccessScenario | PassOnCodeScenario | PassByKeyScenario | PassByServiceKeyScenario; export type MockRequestHandler = SimpleMockRequestHandler | KeyedMockRequestHandler; export type SimpleMockRequestHandler = (req: MockRequest) => MockResponse | Promise; export type KeyedMockRequestHandler = ( @@ -49,12 +56,43 @@ export interface MockApi { method: HttpMethod; uri: string; handler: MockRequestHandler; + kind: "MockApi"; +} + +export interface MockApiDefinition { + uri: string; + method: HttpMethod; + request: ServiceRequest; + response: MockResponse; + handler?: MockRequestHandler; + kind: "MockApiDefinition"; +} + +export interface ServiceRequest { + body?: any; + status?: number; + /** + * Query parameters to match to the request. + */ + params?: Record; + headers?: Record; + files?: ServiceRequestFile[]; +} + +export interface ServiceRequestFile { + fieldname: string; + originalname: string; + buffer: Buffer; + mimetype: string; } export const Fail = Symbol.for("Fail"); export interface KeyedMockApi extends MockApi { handler: KeyedMockRequestHandler; } +export interface KeyedMockApiDefinition extends MockApiDefinition { + handler: KeyedMockRequestHandler; +} export interface MockResponse { status: number; diff --git a/packages/cadl-ranch-specs/http/authentication/api-key/mockapi.ts b/packages/cadl-ranch-specs/http/authentication/api-key/mockapi.ts index 876bd3739..3d1a7fa24 100644 --- a/packages/cadl-ranch-specs/http/authentication/api-key/mockapi.ts +++ b/packages/cadl-ranch-specs/http/authentication/api-key/mockapi.ts @@ -1,17 +1,48 @@ -import { MockRequest } from "@azure-tools/cadl-ranch-api"; +import { json, MockRequest, passOnSuccess } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; -import { getValidAndInvalidScenarios } from "../commonapi.js"; export const Scenarios: Record = {}; -const validAndInvalidScenarios = getValidAndInvalidScenarios( - "api-key", - "invalid-api-key", - function addOptionalParamOldApiVersionNewClientValidate(req: MockRequest): void { +Scenarios.Authentication_ApiKey_valid = passOnSuccess({ + uri: `/authentication/api-key/valid`, + method: `get`, + request: { + headers: { + "x-ms-api-key": "valid-key", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("x-ms-api-key", "valid-key"); + return { status: 204 }; }, -); - -Scenarios.Authentication_ApiKey_valid = validAndInvalidScenarios.valid; + kind: "MockApiDefinition", +}); -Scenarios.Authentication_ApiKey_invalid = validAndInvalidScenarios.invalid; +Scenarios.Authentication_ApiKey_invalid = passOnSuccess({ + uri: `/authentication/api-key/invalid`, + method: `get`, + request: { + headers: { + "x-ms-api-key": "valid-key", + }, + status: 403, + }, + response: { + status: 403, + body: json({ + error: "invalid-api-key", + }), + }, + handler: (req: MockRequest) => { + return { + status: 403, + body: json({ + error: "invalid-api-key", + }), + }; + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/authentication/http/custom/mockapi.ts b/packages/cadl-ranch-specs/http/authentication/http/custom/mockapi.ts index ee6886a27..3e94f45e5 100644 --- a/packages/cadl-ranch-specs/http/authentication/http/custom/mockapi.ts +++ b/packages/cadl-ranch-specs/http/authentication/http/custom/mockapi.ts @@ -1,17 +1,48 @@ -import { MockRequest } from "@azure-tools/cadl-ranch-api"; +import { json, MockRequest, passOnSuccess } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; -import { getValidAndInvalidScenarios } from "../../commonapi.js"; export const Scenarios: Record = {}; -const validAndInvalidScenarios = getValidAndInvalidScenarios( - "http/custom", - "invalid-api-key", - function addOptionalParamOldApiVersionNewClientValidate(req: MockRequest): void { +Scenarios.Authentication_Http_Custom_valid = passOnSuccess({ + uri: `/authentication/http/custom/valid`, + method: "get", + request: { + headers: { + authorization: "SharedAccessKey valid-key", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("authorization", "SharedAccessKey valid-key"); + return { status: 204 }; }, -); - -Scenarios.Authentication_Http_Custom_valid = validAndInvalidScenarios.valid; + kind: "MockApiDefinition", +}); -Scenarios.Authentication_Http_Custom_invalid = validAndInvalidScenarios.invalid; +Scenarios.Authentication_Http_Custom_invalid = passOnSuccess({ + uri: `/authentication/http/custom/invalid`, + method: "get", + request: { + headers: { + authorization: "SharedAccessKey valid-key", + }, + status: 403, + }, + response: { + status: 403, + body: json({ + error: "invalid-api-key", + }), + }, + handler: (req: MockRequest) => { + return { + status: 403, + body: json({ + error: "invalid-api-key", + }), + }; + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/authentication/oauth2/mockapi.ts b/packages/cadl-ranch-specs/http/authentication/oauth2/mockapi.ts index bf1b123fa..18a4a5e56 100644 --- a/packages/cadl-ranch-specs/http/authentication/oauth2/mockapi.ts +++ b/packages/cadl-ranch-specs/http/authentication/oauth2/mockapi.ts @@ -1,17 +1,45 @@ -import { MockRequest } from "@azure-tools/cadl-ranch-api"; +import { json, MockRequest, passOnSuccess } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; -import { getValidAndInvalidScenarios } from "../commonapi.js"; export const Scenarios: Record = {}; -const validAndInvalidScenarios = getValidAndInvalidScenarios( - "oauth2", - "invalid-grant", - function addOptionalParamOldApiVersionNewClientValidate(req: MockRequest): void { +Scenarios.Authentication_OAuth2_valid = passOnSuccess({ + uri: `/authentication/oauth2/valid`, + method: "get", + request: { + headers: { + authorization: "Bearer https://security.microsoft.com/.default", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("authorization", "Bearer https://security.microsoft.com/.default"); + return { status: 204 }; }, -); - -Scenarios.Authentication_OAuth2_valid = validAndInvalidScenarios.valid; + kind: "MockApiDefinition", +}); -Scenarios.Authentication_OAuth2_invalid = validAndInvalidScenarios.invalid; +Scenarios.Authentication_OAuth2_invalid = passOnSuccess({ + uri: `/authentication/oauth2/invalid`, + method: "get", + request: { + status: 403, + }, + response: { + status: 403, + body: json({ + error: "invalid-grant", + }), + }, + handler: (req: MockRequest) => { + return { + status: 403, + body: json({ + error: "invalid-grant", + }), + }; + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/authentication/union/mockapi.ts b/packages/cadl-ranch-specs/http/authentication/union/mockapi.ts index 58135909d..48a62f661 100644 --- a/packages/cadl-ranch-specs/http/authentication/union/mockapi.ts +++ b/packages/cadl-ranch-specs/http/authentication/union/mockapi.ts @@ -1,18 +1,40 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Authentication_Union_validKey = passOnSuccess( - mockapi.get("/authentication/union/validkey", (req) => { +Scenarios.Authentication_Union_validKey = passOnSuccess({ + uri: `/authentication/union/validkey`, + method: "get", + request: { + headers: { + "x-ms-api-key": "valid-key", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("x-ms-api-key", "valid-key"); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Authentication_Union_validToken = passOnSuccess( - mockapi.get("/authentication/union/validtoken", (req) => { +Scenarios.Authentication_Union_validToken = passOnSuccess({ + uri: `/authentication/union/validtoken`, + method: "get", + request: { + headers: { + authorization: "Bearer https://security.microsoft.com/.default", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("authorization", "Bearer https://security.microsoft.com/.default"); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/azure/client-generator-core/access/mockapi.ts b/packages/cadl-ranch-specs/http/azure/client-generator-core/access/mockapi.ts index 079a3fa24..41feac784 100644 --- a/packages/cadl-ranch-specs/http/azure/client-generator-core/access/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/client-generator-core/access/mockapi.ts @@ -1,54 +1,95 @@ -import { passOnSuccess, mockapi, ValidationError, json, MockApi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ValidationError, json, MockApiDefinition, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -function createMockApis(route: string): MockApi { - const url = `/azure/client-generator-core/access/${route}`; - return mockapi.get(url, (req) => { - if (!("name" in req.query)) { - throw new ValidationError("Should submit name query", "any string", undefined); - } - return { +function createMockApiDefinitions(route: string): MockApiDefinition { + return { + uri: `/azure/client-generator-core/access/${route}`, + method: "get", + request: { + params: { + name: "sample", + }, + }, + response: { status: 200, - body: json({ name: req.query["name"] }), - }; - }); + body: json({ name: "sample" }), + }, + handler: (req: MockRequest) => { + if (!("name" in req.query)) { + throw new ValidationError("Should submit name query", "any string", undefined); + } + return { + status: 200, + body: json({ name: req.query["name"] }), + }; + }, + kind: "MockApiDefinition", + }; } Scenarios.Azure_ClientGenerator_Core_Access_PublicOperation = passOnSuccess([ - createMockApis("publicOperation/noDecoratorInPublic"), - createMockApis("publicOperation/publicDecoratorInPublic"), + createMockApiDefinitions("publicOperation/noDecoratorInPublic"), + createMockApiDefinitions("publicOperation/publicDecoratorInPublic"), ]); Scenarios.Azure_ClientGenerator_Core_Access_InternalOperation = passOnSuccess([ - createMockApis("internalOperation/noDecoratorInInternal"), - createMockApis("internalOperation/internalDecoratorInInternal"), - createMockApis("internalOperation/publicDecoratorInInternal"), + createMockApiDefinitions("internalOperation/noDecoratorInInternal"), + createMockApiDefinitions("internalOperation/internalDecoratorInInternal"), + createMockApiDefinitions("internalOperation/publicDecoratorInInternal"), ]); Scenarios.Azure_ClientGenerator_Core_Access_SharedModelInOperation = passOnSuccess([ - createMockApis("sharedModelInOperation/public"), - createMockApis("sharedModelInOperation/internal"), + createMockApiDefinitions("sharedModelInOperation/public"), + createMockApiDefinitions("sharedModelInOperation/internal"), ]); Scenarios.Azure_ClientGenerator_Core_Access_RelativeModelInOperation = passOnSuccess([ - mockapi.get("/azure/client-generator-core/access/relativeModelInOperation/operation", (req) => { - if (!("name" in req.query)) { - throw new ValidationError("Should submit name query", "any string", undefined); - } - return { + { + uri: "/azure/client-generator-core/access/relativeModelInOperation/operation", + method: "get", + request: { + params: { + name: "Madge", + }, + }, + response: { status: 200, body: json({ name: "Madge", inner: { name: "Madge" } }), - }; - }), - mockapi.get("/azure/client-generator-core/access/relativeModelInOperation/discriminator", (req) => { - if (!("kind" in req.query)) { - throw new ValidationError("Should submit name query", "any string", undefined); - } - return { + }, + handler: (req: MockRequest) => { + if (!("name" in req.query)) { + throw new ValidationError("Should submit name query", "any string", undefined); + } + return { + status: 200, + body: json({ name: "Madge", inner: { name: "Madge" } }), + }; + }, + kind: "MockApiDefinition", + }, + { + uri: "/azure/client-generator-core/access/relativeModelInOperation/discriminator", + method: "get", + request: { + params: { + kind: "real", + }, + }, + response: { status: 200, body: json({ name: "Madge", kind: "real" }), - }; - }), + }, + handler: (req: MockRequest) => { + if (!("kind" in req.query)) { + throw new ValidationError("Should submit name query", "any string", undefined); + } + return { + status: 200, + body: json({ name: "Madge", kind: "real" }), + }; + }, + kind: "MockApiDefinition", + }, ]); diff --git a/packages/cadl-ranch-specs/http/azure/client-generator-core/flatten-property/mockapi.ts b/packages/cadl-ranch-specs/http/azure/client-generator-core/flatten-property/mockapi.ts index bb269ffc2..6ee94dc50 100644 --- a/packages/cadl-ranch-specs/http/azure/client-generator-core/flatten-property/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/client-generator-core/flatten-property/mockapi.ts @@ -1,26 +1,32 @@ -import { passOnSuccess, mockapi, json, MockApi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockApiDefinition, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; +import { Mock } from "node:test"; export const Scenarios: Record = {}; -/** - * Return the put operation. - * @param route The route under /azure/client-generator-core/flatten-property for your function. - * @param request The request body you are expecting and will return. - * @param response The response body you are expecting and will return. - */ -function createMockApis(route: string, request: any, response: any): MockApi { - const url = `/azure/client-generator-core/flatten-property/${route}`; - return mockapi.put(url, (req) => { - req.expect.bodyEquals(request); - return { +function createMockApiDefinitions(route: string, request: any, response: any): MockApiDefinition { + return { + uri: `/azure/client-generator-core/flatten-property/${route}`, + method: "put", + request: { + body: request, + }, + response: { status: 200, body: json(response), - }; - }); + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals(request); + return { + status: 200, + body: json(response), + }; + }, + kind: "MockApiDefinition", + }; } Scenarios.Azure_ClientGenerator_Core_FlattenProperty_putFlattenModel = passOnSuccess( - createMockApis( + createMockApiDefinitions( "flattenModel", { name: "foo", @@ -40,7 +46,7 @@ Scenarios.Azure_ClientGenerator_Core_FlattenProperty_putFlattenModel = passOnSuc ); Scenarios.Azure_ClientGenerator_Core_FlattenProperty_putNestedFlattenModel = passOnSuccess( - createMockApis( + createMockApiDefinitions( "nestedFlattenModel", { name: "foo", diff --git a/packages/cadl-ranch-specs/http/azure/client-generator-core/usage/mockapi.ts b/packages/cadl-ranch-specs/http/azure/client-generator-core/usage/mockapi.ts index 12d2bf111..2c07c89f0 100644 --- a/packages/cadl-ranch-specs/http/azure/client-generator-core/usage/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/client-generator-core/usage/mockapi.ts @@ -1,24 +1,57 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; Scenarios.Azure_ClientGenerator_Core_Usage_ModelInOperation = passOnSuccess([ - mockapi.post("/azure/client-generator-core/usage/inputToInputOutput", (req) => { - const validBody = { name: "Madge" }; - req.expect.bodyEquals(validBody); - return { status: 204 }; - }), - mockapi.get("/azure/client-generator-core/usage/outputToInputOutput", (req) => { - return { + { + uri: "/azure/client-generator-core/usage/inputToInputOutput", + method: "post", + request: { + body: { + name: "Madge", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + const validBody = { name: "Madge" }; + req.expect.bodyEquals(validBody); + return { status: 204 }; + }, + kind: "MockApiDefinition", + }, + { + uri: "/azure/client-generator-core/usage/outputToInputOutput", + method: "get", + request: {}, + response: { status: 200, body: json({ name: "Madge" }), - }; - }), - mockapi.put("/azure/client-generator-core/usage/modelInReadOnlyProperty", (req) => { - return { + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: json({ name: "Madge" }), + }; + }, + kind: "MockApiDefinition", + }, + { + uri: "/azure/client-generator-core/usage/modelInReadOnlyProperty", + method: "put", + request: {}, + response: { status: 200, body: json({ result: { name: "Madge" } }), - }; - }), + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: json({ result: { name: "Madge" } }), + }; + }, + kind: "MockApiDefinition", + }, ]); diff --git a/packages/cadl-ranch-specs/http/azure/core/basic/mockapi.ts b/packages/cadl-ranch-specs/http/azure/core/basic/mockapi.ts index 9ccac7bb5..d2b35a806 100644 --- a/packages/cadl-ranch-specs/http/azure/core/basic/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/core/basic/mockapi.ts @@ -1,11 +1,24 @@ -import { passOnSuccess, mockapi, json, ValidationError } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, ValidationError, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; const validUser = { id: 1, name: "Madge", etag: "11bdc430-65e8-45ad-81d9-8ffa60d55b59" }; const validUser2 = { id: 2, name: "John", etag: "22bdc430-65e8-45ad-81d9-8ffa60d55b59" }; -Scenarios.Azure_Core_Basic_createOrUpdate = passOnSuccess( - mockapi.patch("/azure/core/basic/users/:id", (req) => { +Scenarios.Azure_Core_Basic_createOrUpdate = passOnSuccess({ + uri: "/azure/core/basic/users/:id", + method: "patch", + request: { + params: { + "id": "1", + "api-version": "2022-12-01-preview", + }, + headers: { + "Content-Type": "application/merge-patch+json", + }, + body: { name: "Madge" }, + }, + response: { status: 200, body: json(validUser) }, + handler: (req: MockRequest) => { if (req.params.id !== "1") { throw new ValidationError("Expected path param id=1", "1", req.params.id); } @@ -14,11 +27,22 @@ Scenarios.Azure_Core_Basic_createOrUpdate = passOnSuccess( const validBody = { name: "Madge" }; req.expect.bodyEquals(validBody); return { status: 200, body: json(validUser) }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_Core_Basic_createOrReplace = passOnSuccess( - mockapi.put("/azure/core/basic/users/:id", (req) => { +Scenarios.Azure_Core_Basic_createOrReplace = passOnSuccess({ + uri: "/azure/core/basic/users/:id", + method: "put", + request: { + params: { + "id": "1", + "api-version": "2022-12-01-preview", + }, + body: { name: "Madge" }, + }, + response: { status: 200, body: json(validUser) }, + handler: (req: MockRequest) => { if (req.params.id !== "1") { throw new ValidationError("Expected path param id=1", "1", req.params.id); } @@ -27,80 +51,141 @@ Scenarios.Azure_Core_Basic_createOrReplace = passOnSuccess( const validBody = { name: "Madge" }; req.expect.bodyEquals(validBody); return { status: 200, body: json(validUser) }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_Core_Basic_get = passOnSuccess( - mockapi.get("/azure/core/basic/users/:id", (req) => { +Scenarios.Azure_Core_Basic_get = passOnSuccess({ + uri: "/azure/core/basic/users/:id", + method: "get", + request: { + params: { + "id": "1", + "api-version": "2022-12-01-preview", + }, + }, + response: { status: 200, body: json(validUser) }, + handler: (req: MockRequest) => { if (req.params.id !== "1") { throw new ValidationError("Expected path param id=1", "1", req.params.id); } req.expect.containsQueryParam("api-version", "2022-12-01-preview"); return { status: 200, body: json(validUser) }; - }), -); - -Scenarios.Azure_Core_Basic_list = passOnSuccess( - mockapi.get("/azure/core/basic/users", (req) => { + }, + kind: "MockApiDefinition", +}); +const responseBody = { + value: [ + { + id: 1, + name: "Madge", + etag: "11bdc430-65e8-45ad-81d9-8ffa60d55b59", + orders: [{ id: 1, userId: 1, detail: "a recorder" }], + }, + { + id: 2, + name: "John", + etag: "11bdc430-65e8-45ad-81d9-8ffa60d55b5a", + orders: [{ id: 2, userId: 2, detail: "a TV" }], + }, + ], +}; +Scenarios.Azure_Core_Basic_list = passOnSuccess({ + uri: "/azure/core/basic/users", + method: "get", + request: { + params: { + "api-version": "2022-12-01-preview", + "top": 5, + "skip": 10, + "orderby": "id", + "filter": "id lt 10", + "select": ["id", "orders", "etag"], + "expand": "orders", + }, + }, + response: { status: 200, body: json(responseBody) }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("api-version", "2022-12-01-preview"); req.expect.containsQueryParam("top", "5"); req.expect.containsQueryParam("skip", "10"); req.expect.containsQueryParam("orderby", "id"); req.expect.containsQueryParam("filter", "id lt 10"); - if (!req.originalRequest.originalUrl.includes("select=id&select=orders&select=etag")) { + if (!req.originalRequest.originalUrl.includes("select[]=id&select[]=orders&select[]=etag")) { throw new ValidationError( - "Expected query param select=id&select=orders&select=etag ", - "select=id&select=orders&select=etag", + "Expected query param select[]=id&select[]=orders&select[]=etag ", + "select[]=id&select[]=orders&select[]=etag", req.originalRequest.originalUrl, ); } req.expect.containsQueryParam("expand", "orders"); - const responseBody = { - value: [ - { - id: 1, - name: "Madge", - etag: "11bdc430-65e8-45ad-81d9-8ffa60d55b59", - orders: [{ id: 1, userId: 1, detail: "a recorder" }], - }, - { - id: 2, - name: "John", - etag: "11bdc430-65e8-45ad-81d9-8ffa60d55b5a", - orders: [{ id: 2, userId: 2, detail: "a TV" }], - }, - ], - }; return { status: 200, body: json(responseBody) }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_Core_Basic_delete = passOnSuccess( - mockapi.delete("/azure/core/basic/users/:id", (req) => { +Scenarios.Azure_Core_Basic_delete = passOnSuccess({ + uri: "/azure/core/basic/users/:id", + method: "delete", + request: { + params: { + "id": "1", + "api-version": "2022-12-01-preview", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { if (req.params.id !== "1") { throw new ValidationError("Expected path param id=1", "1", req.params.id); } req.expect.containsQueryParam("api-version", "2022-12-01-preview"); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_Core_Basic_export = passOnSuccess( - mockapi.post("/azure/core/basic/users/:id[:]export", (req) => { +Scenarios.Azure_Core_Basic_export = passOnSuccess({ + uri: "/azure/core/basic/users/:id[:]export", + method: "post", + request: { + params: { + "id": "1", + "format": "json", + "api-version": "2022-12-01-preview", + }, + }, + response: { + status: 200, + body: json(validUser), + }, + handler: (req: MockRequest) => { if (req.params.id !== "1") { throw new ValidationError("Expected path param id=1", "1", req.params.id); } req.expect.containsQueryParam("api-version", "2022-12-01-preview"); req.expect.containsQueryParam("format", "json"); return { status: 200, body: json(validUser) }; - }), -); + }, + kind: "MockApiDefinition", +}); const expectBody = { users: [validUser, validUser2] }; -Scenarios.Azure_Core_Basic_exportAllUsers = passOnSuccess( - mockapi.post("/azure/core/basic/users:exportallusers", (req) => { +Scenarios.Azure_Core_Basic_exportAllUsers = passOnSuccess({ + uri: "/azure/core/basic/users:exportallusers", + method: "post", + request: { + params: { + "format": "json", + "api-version": "2022-12-01-preview", + }, + }, + response: { status: 200, body: json(expectBody) }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("api-version", "2022-12-01-preview"); req.expect.containsQueryParam("format", "json"); return { status: 200, body: json(expectBody) }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/azure/core/lro/rpc/mockapi.ts b/packages/cadl-ranch-specs/http/azure/core/lro/rpc/mockapi.ts index 1aa276da7..22edeef49 100644 --- a/packages/cadl-ranch-specs/http/azure/core/lro/rpc/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/core/lro/rpc/mockapi.ts @@ -1,4 +1,4 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; @@ -6,25 +6,74 @@ export const Scenarios: Record = {}; let generationPollCount = 0; Scenarios.Azure_Core_Lro_Rpc_longRunningRpc = passOnSuccess([ - mockapi.post("/azure/core/lro/rpc/generations:submit", (req) => { - req.expect.containsQueryParam("api-version", "2022-12-01-preview"); - req.expect.bodyEquals({ prompt: "text" }); - generationPollCount = 0; - return { + { + uri: "/azure/core/lro/rpc/generations:submit", + method: "post", + request: { + body: { prompt: "text" }, + params: { + "api-version": "2022-12-01-preview", + }, + }, + response: { status: 202, headers: { - "operation-location": `${req.baseUrl}/azure/core/lro/rpc/generations/operations/operation1`, + "operation-location": `/azure/core/lro/rpc/generations/operations/operation1`, + }, + body: json({ id: "operation1", status: "InProgress" }), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2022-12-01-preview"); + req.expect.bodyEquals({ prompt: "text" }); + generationPollCount = 0; + return { + status: 202, + headers: { + "operation-location": `${req.baseUrl}/azure/core/lro/rpc/generations/operations/operation1`, + }, + body: json({ id: "operation1", status: "InProgress" }), + }; + }, + kind: "MockApiDefinition", + }, + { + uri: "/azure/core/lro/rpc/generations/operations/operation1", + method: "get", + request: { + params: { + "api-version": "2022-12-01-preview", }, + }, + response: { + status: 200, body: json({ id: "operation1", status: "InProgress" }), - }; - }), - mockapi.get("/azure/core/lro/rpc/generations/operations/operation1", (req) => { - req.expect.containsQueryParam("api-version", "2022-12-01-preview"); - const response = - generationPollCount > 0 - ? { id: "operation1", status: "Succeeded", result: { data: "text data" } } - : { id: "operation1", status: "InProgress" }; - generationPollCount += 1; - return { status: 200, body: json(response) }; - }), + }, + handler: lroHandler, + kind: "MockApiDefinition", + }, + { + uri: "/azure/core/lro/rpc/generations/operations/operation1", + method: "get", + request: { + params: { + "api-version": "2022-12-01-preview", + }, + }, + response: { + status: 200, + body: json({ id: "operation1", status: "Succeeded", result: { data: "text data" } }), + }, + handler: lroHandler, + kind: "MockApiDefinition", + }, ]); + +function lroHandler(req: MockRequest) { + req.expect.containsQueryParam("api-version", "2022-12-01-preview"); + const response = + generationPollCount > 0 + ? { id: "operation1", status: "Succeeded", result: { data: "text data" } } + : { id: "operation1", status: "InProgress" }; + generationPollCount += 1; + return { status: 200, body: json(response) }; +} diff --git a/packages/cadl-ranch-specs/http/azure/core/lro/standard/mockapi.ts b/packages/cadl-ranch-specs/http/azure/core/lro/standard/mockapi.ts index ef2d6f255..a379b7820 100644 --- a/packages/cadl-ranch-specs/http/azure/core/lro/standard/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/core/lro/standard/mockapi.ts @@ -1,4 +1,4 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; @@ -8,74 +8,230 @@ let createOrReplacePollCount = 0; let deletePollCount = 0; let exportPollCount = 0; +function createOrReplaceLroHandler(req: MockRequest) { + req.expect.containsQueryParam("api-version", "2022-12-01-preview"); + const response = + createOrReplacePollCount > 0 + ? { id: "operation1", status: "Succeeded" } + : { id: "operation1", status: "InProgress" }; + createOrReplacePollCount += 1; + return { status: 200, body: json(response) }; +} + +function deleteLroHandler(req: MockRequest) { + req.expect.containsQueryParam("api-version", "2022-12-01-preview"); + const response = + deletePollCount > 0 ? { id: "operation2", status: "Succeeded" } : { id: "operation2", status: "InProgress" }; + deletePollCount += 1; + return { status: 200, body: json(response) }; +} + +function exportLroHandler(req: MockRequest) { + req.expect.containsQueryParam("api-version", "2022-12-01-preview"); + const response = + exportPollCount > 0 + ? { id: "operation3", status: "Succeeded", result: { name: "madge", resourceUri: "/users/madge" } } + : { id: "operation3", status: "InProgress" }; + exportPollCount += 1; + return { status: 200, body: json(response) }; +} + Scenarios.Azure_Core_Lro_Standard_createOrReplace = passOnSuccess([ - mockapi.put("/azure/core/lro/standard/users/madge", (req) => { - req.expect.containsQueryParam("api-version", "2022-12-01-preview"); - req.expect.bodyEquals({ role: "contributor" }); - createOrReplacePollCount = 0; - return { + { + uri: "/azure/core/lro/standard/users/madge", + method: "put", + request: { + body: { role: "contributor" }, + params: { + "api-version": "2022-12-01-preview", + }, + }, + response: { status: 201, headers: { - "operation-location": `${req.baseUrl}/azure/core/lro/standard/users/madge/operations/operation1`, + "operation-location": `/azure/core/lro/standard/users/madge/operations/operation1`, }, body: json(validUser), - }; - }), - mockapi.get("/azure/core/lro/standard/users/madge/operations/operation1", (req) => { - req.expect.containsQueryParam("api-version", "2022-12-01-preview"); - const response = - createOrReplacePollCount > 0 - ? { id: "operation1", status: "Succeeded" } - : { id: "operation1", status: "InProgress" }; - createOrReplacePollCount += 1; - return { status: 200, body: json(response) }; - }), - mockapi.get("/azure/core/lro/standard/users/madge", (req) => { - return { status: 200, body: json(validUser) }; - }), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2022-12-01-preview"); + req.expect.bodyEquals({ role: "contributor" }); + createOrReplacePollCount = 0; + return { + status: 201, + headers: { + "operation-location": `${req.baseUrl}/azure/core/lro/standard/users/madge/operations/operation1`, + }, + body: json(validUser), + }; + }, + kind: "MockApiDefinition", + }, + { + uri: "/azure/core/lro/standard/users/madge/operations/operation1", + method: "get", + request: { + params: { + "api-version": "2022-12-01-preview", + }, + }, + response: { + status: 200, + body: json({ id: "operation1", status: "InProgress" }), + }, + handler: createOrReplaceLroHandler, + kind: "MockApiDefinition", + }, + { + uri: "/azure/core/lro/standard/users/madge/operations/operation1", + method: "get", + request: { + params: { + "api-version": "2022-12-01-preview", + }, + }, + response: { + status: 200, + body: json({ id: "operation1", status: "Succeeded" }), + }, + handler: createOrReplaceLroHandler, + kind: "MockApiDefinition", + }, + { + uri: "/azure/core/lro/standard/users/madge", + method: "get", + request: {}, + response: { + status: 200, + body: json(validUser), + }, + handler: (req: MockRequest) => { + return { status: 200, body: json(validUser) }; + }, + kind: "MockApiDefinition", + }, ]); Scenarios.Azure_Core_Lro_Standard_delete = passOnSuccess([ - mockapi.delete("/azure/core/lro/standard/users/madge", (req) => { - req.expect.containsQueryParam("api-version", "2022-12-01-preview"); - deletePollCount = 0; - return { + { + uri: "/azure/core/lro/standard/users/madge", + method: "delete", + request: { + params: { + "api-version": "2022-12-01-preview", + }, + }, + response: { status: 202, headers: { - "operation-location": `${req.baseUrl}/azure/core/lro/standard/users/madge/operations/operation2`, + "operation-location": `/azure/core/lro/standard/users/madge/operations/operation2`, }, body: json({ id: "operation2", status: "InProgress" }), - }; - }), - mockapi.get("/azure/core/lro/standard/users/madge/operations/operation2", (req) => { - req.expect.containsQueryParam("api-version", "2022-12-01-preview"); - const response = - deletePollCount > 0 ? { id: "operation2", status: "Succeeded" } : { id: "operation2", status: "InProgress" }; - deletePollCount += 1; - return { status: 200, body: json(response) }; - }), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2022-12-01-preview"); + deletePollCount = 0; + return { + status: 202, + headers: { + "operation-location": `${req.baseUrl}/azure/core/lro/standard/users/madge/operations/operation2`, + }, + body: json({ id: "operation2", status: "InProgress" }), + }; + }, + kind: "MockApiDefinition", + }, + { + uri: "/azure/core/lro/standard/users/madge/operations/operation2", + method: "get", + request: { + params: { + "api-version": "2022-12-01-preview", + }, + }, + response: { + status: 200, + body: json({ id: "operation2", status: "InProgress" }), + }, + handler: deleteLroHandler, + kind: "MockApiDefinition", + }, + { + uri: "/azure/core/lro/standard/users/madge/operations/operation2", + method: "get", + request: { + params: { + "api-version": "2022-12-01-preview", + }, + }, + response: { + status: 200, + body: json({ id: "operation2", status: "Succeeded" }), + }, + handler: deleteLroHandler, + kind: "MockApiDefinition", + }, ]); Scenarios.Azure_Core_Lro_Standard_export = passOnSuccess([ - mockapi.post("/azure/core/lro/standard/users/madge:export", (req) => { - req.expect.containsQueryParam("api-version", "2022-12-01-preview"); - req.expect.containsQueryParam("format", "json"); - exportPollCount = 0; - return { + { + uri: "/azure/core/lro/standard/users/madge:export", + method: "post", + request: { + params: { + "api-version": "2022-12-01-preview", + "format": "json", + }, + }, + response: { status: 202, headers: { - "operation-location": `${req.baseUrl}/azure/core/lro/standard/users/madge/operations/operation3`, + "operation-location": `/azure/core/lro/standard/users/madge/operations/operation3`, }, body: json({ id: "operation3", status: "InProgress" }), - }; - }), - mockapi.get("/azure/core/lro/standard/users/madge/operations/operation3", (req) => { - req.expect.containsQueryParam("api-version", "2022-12-01-preview"); - const response = - exportPollCount > 0 - ? { id: "operation3", status: "Succeeded", result: { name: "madge", resourceUri: "/users/madge" } } - : { id: "operation3", status: "InProgress" }; - exportPollCount += 1; - return { status: 200, body: json(response) }; - }), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2022-12-01-preview"); + req.expect.containsQueryParam("format", "json"); + exportPollCount = 0; + return { + status: 202, + headers: { + "operation-location": `${req.baseUrl}/azure/core/lro/standard/users/madge/operations/operation3`, + }, + body: json({ id: "operation3", status: "InProgress" }), + }; + }, + kind: "MockApiDefinition", + }, + { + uri: "/azure/core/lro/standard/users/madge/operations/operation3", + method: "get", + request: { + params: { + "api-version": "2022-12-01-preview", + }, + }, + response: { + status: 200, + body: json({ id: "operation3", status: "InProgress" }), + }, + handler: exportLroHandler, + kind: "MockApiDefinition", + }, + { + uri: "/azure/core/lro/standard/users/madge/operations/operation3", + method: "get", + request: { + params: { + "api-version": "2022-12-01-preview", + }, + }, + response: { + status: 200, + body: json({ id: "operation3", status: "Succeeded", result: { name: "madge", resourceUri: "/users/madge" } }), + }, + handler: exportLroHandler, + kind: "MockApiDefinition", + }, ]); diff --git a/packages/cadl-ranch-specs/http/azure/core/model/mockapi.ts b/packages/cadl-ranch-specs/http/azure/core/model/mockapi.ts index c3f7538cd..47b121823 100644 --- a/packages/cadl-ranch-specs/http/azure/core/model/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/core/model/mockapi.ts @@ -1,28 +1,45 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Azure_Core_Model_AzureCoreEmbeddingVector_get = passOnSuccess( - mockapi.get("/azure/core/model/embeddingVector", (req) => { +Scenarios.Azure_Core_Model_AzureCoreEmbeddingVector_get = passOnSuccess({ + uri: "/azure/core/model/embeddingVector", + method: "get", + request: {}, + response: { status: 200, body: json([0, 1, 2, 3, 4]) }, + handler: (req) => { return { status: 200, body: json([0, 1, 2, 3, 4]) }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_Core_Model_AzureCoreEmbeddingVector_put = passOnSuccess( - mockapi.put("/azure/core/model/embeddingVector", (req) => { +Scenarios.Azure_Core_Model_AzureCoreEmbeddingVector_put = passOnSuccess({ + uri: "/azure/core/model/embeddingVector", + method: "put", + request: { + body: [0, 1, 2, 3, 4], + }, + response: { status: 204 }, + handler: (req) => { req.expect.bodyEquals([0, 1, 2, 3, 4]); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); const responseBody = { embedding: [5, 6, 7, 8, 9] }; -Scenarios.Azure_Core_Model_AzureCoreEmbeddingVector_post = passOnSuccess( - mockapi.post("/azure/core/model/embeddingVector", (req) => { +Scenarios.Azure_Core_Model_AzureCoreEmbeddingVector_post = passOnSuccess({ + uri: "/azure/core/model/embeddingVector", + method: "post", + request: { body: { embedding: [0, 1, 2, 3, 4] } }, + response: { status: 200, body: json(responseBody) }, + handler: (req) => { req.expect.bodyEquals({ embedding: [0, 1, 2, 3, 4] }); return { status: 200, body: json(responseBody), }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/azure/core/page/mockapi.ts b/packages/cadl-ranch-specs/http/azure/core/page/mockapi.ts index bf2e22d21..18883d2a9 100644 --- a/packages/cadl-ranch-specs/http/azure/core/page/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/core/page/mockapi.ts @@ -1,20 +1,34 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; const validUser = { id: 1, name: "Madge", etag: "11bdc430-65e8-45ad-81d9-8ffa60d55b59" }; -Scenarios.Azure_Core_Page_listWithPage = passOnSuccess( - mockapi.get("/azure/core/page/page", (req) => { +Scenarios.Azure_Core_Page_listWithPage = passOnSuccess({ + uri: "/azure/core/page/page", + method: "get", + request: {}, + response: { status: 200, body: json({ value: [validUser] }) }, + handler: (req: MockRequest) => { const responseBody = { value: [validUser], }; return { status: 200, body: json(responseBody) }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_Core_Page_listWithParameters = passOnSuccess( - mockapi.get("/azure/core/page/parameters", (req) => { +Scenarios.Azure_Core_Page_listWithParameters = passOnSuccess({ + uri: "/azure/core/page/parameters", + method: "get", + request: { + params: { + another: "Second", + }, + body: { inputName: "Madge" }, + }, + response: { status: 200, body: json({ value: [validUser] }) }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("another", "Second"); const validBody = { inputName: "Madge" }; @@ -24,29 +38,49 @@ Scenarios.Azure_Core_Page_listWithParameters = passOnSuccess( value: [validUser], }; return { status: 200, body: json(responseBody) }; - }), -); + }, + kind: "MockApiDefinition", +}); Scenarios.Azure_Core_Page_TwoModelsAsPageItem = passOnSuccess([ - mockapi.get("/azure/core/page/first-item", () => { - const responseBody = { - value: [{ id: 1 }], - }; - return { status: 200, body: json(responseBody) }; - }), - mockapi.get("/azure/core/page/second-item", () => { - const responseBody = { - value: [{ name: "Madge" }], - }; - return { status: 200, body: json(responseBody) }; - }), + { + uri: "/azure/core/page/first-item", + method: "get", + request: {}, + response: { status: 200, body: json({ value: [{ id: 1 }] }) }, + handler: (req: MockRequest) => { + const responseBody = { + value: [{ id: 1 }], + }; + return { status: 200, body: json(responseBody) }; + }, + kind: "MockApiDefinition", + }, + { + uri: "/azure/core/page/second-item", + method: "get", + request: {}, + response: { status: 200, body: json({ value: [{ name: "Madge" }] }) }, + handler: (req: MockRequest) => { + const responseBody = { + value: [{ name: "Madge" }], + }; + return { status: 200, body: json(responseBody) }; + }, + kind: "MockApiDefinition", + }, ]); -Scenarios.Azure_Core_Page_listWithCustomPageModel = passOnSuccess( - mockapi.get("/azure/core/page/custom-page", () => { +Scenarios.Azure_Core_Page_listWithCustomPageModel = passOnSuccess({ + uri: "/azure/core/page/custom-page", + method: "get", + request: {}, + response: { status: 200, body: json({ items: [validUser] }) }, + handler: (req: MockRequest) => { const responseBody = { items: [validUser], }; return { status: 200, body: json(responseBody) }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/azure/core/scalar/mockapi.ts b/packages/cadl-ranch-specs/http/azure/core/scalar/mockapi.ts index 667d389c4..a7a265cb7 100644 --- a/packages/cadl-ranch-specs/http/azure/core/scalar/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/core/scalar/mockapi.ts @@ -1,45 +1,81 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; // string value -Scenarios.Azure_Core_Scalar_AzureLocationScalar_get = passOnSuccess( - mockapi.get("/azure/core/scalar/azureLocation", (req) => { +Scenarios.Azure_Core_Scalar_AzureLocationScalar_get = passOnSuccess({ + uri: "/azure/core/scalar/azureLocation", + method: "get", + request: {}, + response: { status: 200, body: json("eastus") }, + handler: (req: MockRequest) => { return { status: 200, body: json("eastus") }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_Core_Scalar_AzureLocationScalar_put = passOnSuccess( - mockapi.put("/azure/core/scalar/azureLocation", (req) => { +Scenarios.Azure_Core_Scalar_AzureLocationScalar_put = passOnSuccess({ + uri: "/azure/core/scalar/azureLocation", + method: "put", + request: { + body: "eastus", + headers: { + "Content-Type": "text/plain", + }, + }, + response: { status: 204 }, + handler: (req: MockRequest) => { req.expect.bodyEquals("eastus"); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); const azureLocation = { location: "eastus" }; -Scenarios.Azure_Core_Scalar_AzureLocationScalar_post = passOnSuccess( - mockapi.post("/azure/core/scalar/azureLocation", (req) => { +Scenarios.Azure_Core_Scalar_AzureLocationScalar_post = passOnSuccess({ + uri: "/azure/core/scalar/azureLocation", + method: "post", + request: { body: azureLocation }, + response: { status: 200, body: json(azureLocation) }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ location: "eastus" }); return { status: 200, body: json(azureLocation), }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_Core_Scalar_AzureLocationScalar_header = passOnSuccess( - mockapi.post("/azure/core/scalar/azureLocation/header", (req) => { +Scenarios.Azure_Core_Scalar_AzureLocationScalar_header = passOnSuccess({ + uri: "/azure/core/scalar/azureLocation/header", + method: "post", + request: { + headers: { + region: "eastus", + }, + }, + response: { status: 204 }, + handler: (req: MockRequest) => { req.expect.containsHeader("region", "eastus"); - return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_Core_Scalar_AzureLocationScalar_query = passOnSuccess( - mockapi.post("/azure/core/scalar/azureLocation/query", (req) => { +Scenarios.Azure_Core_Scalar_AzureLocationScalar_query = passOnSuccess({ + uri: "/azure/core/scalar/azureLocation/query", + method: "post", + request: { + params: { + region: "eastus", + }, + }, + response: { status: 204 }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("region", "eastus"); - return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/azure/core/traits/mockapi.ts b/packages/cadl-ranch-specs/http/azure/core/traits/mockapi.ts index 02e6186df..acd888910 100644 --- a/packages/cadl-ranch-specs/http/azure/core/traits/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/core/traits/mockapi.ts @@ -1,4 +1,4 @@ -import { passOnSuccess, mockapi, json, ValidationError, validateValueFormat } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, ValidationError, validateValueFormat, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; @@ -8,8 +8,32 @@ const validUser = { name: "Madge", }; -Scenarios.Azure_Core_Traits_smokeTest = passOnSuccess( - mockapi.get("/azure/core/traits/user/:id", (req) => { +Scenarios.Azure_Core_Traits_smokeTest = passOnSuccess({ + uri: "/azure/core/traits/user/:id", + method: "get", + request: { + params: { + id: "1", + }, + headers: { + "foo": "123", + "If-Match": '"valid"', + "If-None-Match": '"invalid"', + "If-Modified-Since": "Thu, 26 Aug 2021 14:38:00 GMT", + "If-Unmodified-Since": "Fri, 26 Aug 2022 14:38:00 GMT", + "x-ms-client-request-id": "86aede1f-96fa-4e7f-b1e1-bf8a947cb804", + }, + }, + response: { + status: 200, + body: json(validUser), + headers: { + "bar": "456", + "etag": "11bdc430-65e8-45ad-81d9-8ffa60d55b59", + "x-ms-client-request-id": "86aede1f-96fa-4e7f-b1e1-bf8a947cb804", + }, + }, + handler: (req: MockRequest) => { if (!("x-ms-client-request-id" in req.headers)) { throw new ValidationError("Should submit header x-ms-client-request-id", "any uuid", undefined); } @@ -37,11 +61,33 @@ Scenarios.Azure_Core_Traits_smokeTest = passOnSuccess( "x-ms-client-request-id": req.headers["x-ms-client-request-id"], }, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_Core_Traits_repeatableAction = passOnSuccess( - mockapi.post("/azure/core/traits/user/:id:repeatableAction", (req) => { +Scenarios.Azure_Core_Traits_repeatableAction = passOnSuccess({ + uri: "/azure/core/traits/user/:id:repeatableAction", + method: "post", + request: { + body: { + userActionValue: "test", + }, + headers: { + "Repeatability-Request-ID": "86aede1f-96fa-4e7f-b1e1-bf8a947cb804", + "Repeatability-First-Sent": "Mon, 27 Nov 2023 11:58:00 GMT", + }, + params: { + id: "1", + }, + }, + response: { + status: 200, + body: json({ userActionResult: "test" }), + headers: { + "repeatability-result": "accepted", + }, + }, + handler: (req: MockRequest) => { if (req.params.id !== "1") { throw new ValidationError("Expected path param id=1", "1", req.params.id); } @@ -66,5 +112,6 @@ Scenarios.Azure_Core_Traits_repeatableAction = passOnSuccess( "repeatability-result": "accepted", }, }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/azure/example/basic/mockapi.ts b/packages/cadl-ranch-specs/http/azure/example/basic/mockapi.ts index afdccd189..9d0c965ca 100644 --- a/packages/cadl-ranch-specs/http/azure/example/basic/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/example/basic/mockapi.ts @@ -1,10 +1,40 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; +import { Mock } from "node:test"; export const Scenarios: Record = {}; -Scenarios.Client_AzureExampleClient_basicAction = passOnSuccess( - mockapi.post("/azure/example/basic/basic", (req) => { +Scenarios.Client_AzureExampleClient_basicAction = passOnSuccess({ + uri: "/azure/example/basic/basic", + method: "post", + request: { + params: { + "api-version": "2022-12-01-preview", + "query-param": "query", + }, + headers: { + "header-param": "header", + }, + body: { + stringProperty: "text", + modelProperty: { + int32Property: 1, + float32Property: 1.5, + enumProperty: "EnumValue1", + }, + arrayProperty: ["item"], + recordProperty: { + record: "value", + }, + }, + }, + response: { + status: 200, + body: json({ + stringProperty: "text", + }), + }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("api-version", "2022-12-01-preview"); req.expect.containsQueryParam("query-param", "query"); req.expect.containsHeader("header-param", "header"); @@ -27,5 +57,6 @@ Scenarios.Client_AzureExampleClient_basicAction = passOnSuccess( stringProperty: "text", }), }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/azure/resource-manager/models/common-types/managed-identity/mockapi.ts b/packages/cadl-ranch-specs/http/azure/resource-manager/models/common-types/managed-identity/mockapi.ts index 02d5976a8..773385a9d 100644 --- a/packages/cadl-ranch-specs/http/azure/resource-manager/models/common-types/managed-identity/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/resource-manager/models/common-types/managed-identity/mockapi.ts @@ -1,4 +1,4 @@ -import { passOnSuccess, mockapi, json, ValidationError } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, ValidationError, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; @@ -63,10 +63,64 @@ const updateExpectedIdentity = { }; // managed identity tracked resource -Scenarios.Azure_ResourceManager_Models_CommonTypes_ManagedIdentity_ManagedIdentityTrackedResources_get = passOnSuccess([ - mockapi.get( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/:managedIdentityResourceName", - (req) => { +Scenarios.Azure_ResourceManager_Models_CommonTypes_ManagedIdentity_ManagedIdentityTrackedResources_get = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/:managedIdentityResourceName", + method: "get", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "managedIdentityResourceName": "identity", + "api-version": "2023-12-01-preview", + }, + }, + response: { + status: 200, + body: json(validSystemAssignedManagedIdentityResource), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + if (req.params.managedIdentityResourceName.toLowerCase() !== "identity") { + throw new ValidationError( + "Unexpected managed identity resource name", + "identity", + req.params.managedIdentityResourceName, + ); + } + return { + status: 200, + body: json(validSystemAssignedManagedIdentityResource), + }; + }, + kind: "MockApiDefinition", +}); + +Scenarios.Azure_ResourceManager_Models_CommonTypes_ManagedIdentity_ManagedIdentityTrackedResources_createWithSystemAssigned = + passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/:managedIdentityResourceName", + method: "put", + request: { + body: { + identity: createExpectedIdentity, + }, + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "managedIdentityResourceName": "identity", + "api-version": "2023-12-01-preview", + }, + }, + response: { + status: 200, + body: json(validSystemAssignedManagedIdentityResource), + }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("api-version", "2023-12-01-preview"); if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); @@ -81,66 +135,57 @@ Scenarios.Azure_ResourceManager_Models_CommonTypes_ManagedIdentity_ManagedIdenti req.params.managedIdentityResourceName, ); } + req.expect.deepEqual(req.body["identity"], createExpectedIdentity); return { status: 200, body: json(validSystemAssignedManagedIdentityResource), }; }, - ), -]); - -Scenarios.Azure_ResourceManager_Models_CommonTypes_ManagedIdentity_ManagedIdentityTrackedResources_createWithSystemAssigned = - passOnSuccess([ - mockapi.put( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/:managedIdentityResourceName", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - if (req.params.managedIdentityResourceName.toLowerCase() !== "identity") { - throw new ValidationError( - "Unexpected managed identity resource name", - "identity", - req.params.managedIdentityResourceName, - ); - } - req.expect.deepEqual(req.body["identity"], createExpectedIdentity); - return { - status: 200, - body: json(validSystemAssignedManagedIdentityResource), - }; - }, - ), - ]); + kind: "MockApiDefinition", + }); Scenarios.Azure_ResourceManager_Models_CommonTypes_ManagedIdentity_ManagedIdentityTrackedResources_updateWithUserAssignedAndSystemAssigned = - passOnSuccess([ - mockapi.patch( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/:managedIdentityResourceName", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - if (req.params.managedIdentityResourceName.toLowerCase() !== "identity") { - throw new ValidationError( - "Unexpected managed identity resource name", - "identity", - req.params.managedIdentityResourceName, - ); - } - req.expect.deepEqual(req.body["identity"], updateExpectedIdentity); - return { - status: 200, - body: json(validUserAssignedAndSystemAssignedManagedIdentityResource), - }; + passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/:managedIdentityResourceName", + method: "patch", + request: { + body: { + identity: updateExpectedIdentity, + }, + headers: { + "Content-Type": "application/merge-patch+json", }, - ), - ]); + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "managedIdentityResourceName": "identity", + "api-version": "2023-12-01-preview", + }, + }, + response: { + status: 200, + body: json(validUserAssignedAndSystemAssignedManagedIdentityResource), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + if (req.params.managedIdentityResourceName.toLowerCase() !== "identity") { + throw new ValidationError( + "Unexpected managed identity resource name", + "identity", + req.params.managedIdentityResourceName, + ); + } + req.expect.deepEqual(req.body["identity"], updateExpectedIdentity); + return { + status: 200, + body: json(validUserAssignedAndSystemAssignedManagedIdentityResource), + }; + }, + kind: "MockApiDefinition", + }); diff --git a/packages/cadl-ranch-specs/http/azure/resource-manager/models/resources/mockapi.ts b/packages/cadl-ranch-specs/http/azure/resource-manager/models/resources/mockapi.ts index 011bd053a..8012e584f 100644 --- a/packages/cadl-ranch-specs/http/azure/resource-manager/models/resources/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/resource-manager/models/resources/mockapi.ts @@ -1,4 +1,4 @@ -import { passOnSuccess, mockapi, json, ValidationError } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, ValidationError, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; @@ -17,9 +17,9 @@ const validTopLevelResource = { systemData: { createdBy: "AzureSDK", createdByType: "User", - createdAt: new Date(), + createdAt: "2024-10-04T00:56:07.442Z", lastModifiedBy: "AzureSDK", - lastModifiedAt: new Date(), + lastModifiedAt: "2024-10-04T00:56:07.442Z", lastModifiedByType: "User", }, }; @@ -35,9 +35,9 @@ const validNestedResource = { systemData: { createdBy: "AzureSDK", createdByType: "User", - createdAt: new Date(), + createdAt: "2024-10-04T00:56:07.442Z", lastModifiedBy: "AzureSDK", - lastModifiedAt: new Date(), + lastModifiedAt: "2024-10-04T00:56:07.442Z", lastModifiedByType: "User", }, }; @@ -54,390 +54,649 @@ const validSingletonResource = { systemData: { createdBy: "AzureSDK", createdByType: "User", - createdAt: new Date(), + createdAt: "2024-10-04T00:56:07.442Z", lastModifiedBy: "AzureSDK", - lastModifiedAt: new Date(), + lastModifiedAt: "2024-10-04T00:56:07.442Z", lastModifiedByType: "User", }, }; // singleton tracked resource -Scenarios.Azure_ResourceManager_Models_Resources_SingletonTrackedResources_getByResourceGroup = passOnSuccess([ - mockapi.get( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/singletonTrackedResources/default", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - return { - status: 200, - body: json(validSingletonResource), - }; +Scenarios.Azure_ResourceManager_Models_Resources_SingletonTrackedResources_getByResourceGroup = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/singletonTrackedResources/default", + method: "get", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "api-version": "2023-12-01-preview", }, - ), -]); + }, + response: { + status: 200, + body: json(validSingletonResource), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + return { + status: 200, + body: json(validSingletonResource), + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_SingletonTrackedResources_createOrUpdate = passOnSuccess([ - mockapi.put( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/singletonTrackedResources/default", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - req.expect.bodyEquals({ - location: "eastus", - properties: { - description: "valid", - }, - }); - return { - status: 200, - body: json(validSingletonResource), - }; +Scenarios.Azure_ResourceManager_Models_Resources_SingletonTrackedResources_createOrUpdate = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/singletonTrackedResources/default", + method: "put", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "api-version": "2023-12-01-preview", }, - ), -]); + body: { + location: "eastus", + properties: { + description: "valid", + }, + }, + }, + response: { + status: 200, + body: json(validSingletonResource), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + req.expect.bodyEquals({ + location: "eastus", + properties: { + description: "valid", + }, + }); + return { + status: 200, + body: json(validSingletonResource), + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_SingletonTrackedResources_update = passOnSuccess([ - mockapi.patch( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/singletonTrackedResources/default", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - req.expect.bodyEquals({ - location: "eastus2", - properties: { - description: "valid2", - }, - }); - const resource = JSON.parse(JSON.stringify(validSingletonResource)); - resource.location = "eastus2"; - resource.properties.description = "valid2"; - return { - status: 200, - body: json(resource), - }; +Scenarios.Azure_ResourceManager_Models_Resources_SingletonTrackedResources_update = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/singletonTrackedResources/default", + method: "patch", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "api-version": "2023-12-01-preview", + }, + body: { + location: "eastus2", + properties: { + description: "valid2", + }, }, - ), -]); + headers: { + "Content-Type": "application/merge-patch+json", + }, + }, + response: { + status: 200, + body: json({ + ...validSingletonResource, + location: "eastus2", + properties: { + provisioningState: "Succeeded", + description: "valid2", + }, + }), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + req.expect.bodyEquals({ + location: "eastus2", + properties: { + description: "valid2", + }, + }); + const resource = JSON.parse(JSON.stringify(validSingletonResource)); + resource.location = "eastus2"; + resource.properties.description = "valid2"; + return { + status: 200, + body: json(resource), + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_SingletonTrackedResources_listByResourceGroup = passOnSuccess([ - mockapi.get( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/singletonTrackedResources", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - return { - status: 200, - body: json({ - value: [validSingletonResource], - }), - }; +Scenarios.Azure_ResourceManager_Models_Resources_SingletonTrackedResources_listByResourceGroup = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/singletonTrackedResources", + method: "get", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "api-version": "2023-12-01-preview", }, - ), -]); + }, + response: { + status: 200, + body: json({ + value: [validSingletonResource], + }), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + return { + status: 200, + body: json({ + value: [validSingletonResource], + }), + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_actionSync = passOnSuccess([ - mockapi.post( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName/actionSync", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - if (req.params.topLevelResourceName.toLowerCase() !== "top") { - throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); - } - req.expect.bodyEquals({ - message: "Resource action at top level.", - urgent: true, - }); - return { - status: 204, - }; +Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_actionSync = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName/actionSync", + method: "post", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "topLevelResourceName": "top", + "api-version": "2023-12-01-preview", + }, + body: { + message: "Resource action at top level.", + urgent: true, }, - ), -]); + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + if (req.params.topLevelResourceName.toLowerCase() !== "top") { + throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); + } + req.expect.bodyEquals({ + message: "Resource action at top level.", + urgent: true, + }); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", +}); // top level tracked resource -Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_get = passOnSuccess([ - mockapi.get( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - if (req.params.topLevelResourceName.toLowerCase() !== "top") { - throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); - } - return { - status: 200, - body: json(validTopLevelResource), - }; +Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_get = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName", + method: "get", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "topLevelResourceName": "top", + "api-version": "2023-12-01-preview", }, - ), -]); + }, + response: { + status: 200, + body: json(validTopLevelResource), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + if (req.params.topLevelResourceName.toLowerCase() !== "top") { + throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); + } + return { + status: 200, + body: json(validTopLevelResource), + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_createOrReplace = passOnSuccess([ - mockapi.put( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - if (req.params.topLevelResourceName.toLowerCase() !== "top") { - throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); - } - req.expect.bodyEquals({ - location: "eastus", - properties: { - description: "valid", - }, - }); - return { - status: 200, - body: json(validTopLevelResource), - }; +Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_createOrReplace = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName", + method: "put", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "topLevelResourceName": "top", + "api-version": "2023-12-01-preview", }, - ), -]); + body: { + location: "eastus", + properties: { + description: "valid", + }, + }, + }, + response: { + status: 200, + body: json(validTopLevelResource), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + if (req.params.topLevelResourceName.toLowerCase() !== "top") { + throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); + } + req.expect.bodyEquals({ + location: "eastus", + properties: { + description: "valid", + }, + }); + return { + status: 200, + body: json(validTopLevelResource), + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_update = passOnSuccess([ - mockapi.patch( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - if (req.params.topLevelResourceName.toLowerCase() !== "top") { - throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); - } - req.expect.deepEqual(req.body.properties, { +Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_update = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName", + method: "patch", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "topLevelResourceName": "top", + "api-version": "2023-12-01-preview", + }, + body: { + properties: { description: "valid2", - }); - const resource = JSON.parse(JSON.stringify(validTopLevelResource)); - resource.properties.description = "valid2"; - return { - status: 200, - body: json(resource), - }; + }, + }, + headers: { + "Content-Type": "application/merge-patch+json", }, - ), -]); + }, + response: { + status: 200, + body: json({ + ...validTopLevelResource, + properties: { + provisioningState: "Succeeded", + description: "valid2", + }, + }), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + if (req.params.topLevelResourceName.toLowerCase() !== "top") { + throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); + } + req.expect.deepEqual(req.body.properties, { + description: "valid2", + }); + const resource = JSON.parse(JSON.stringify(validTopLevelResource)); + resource.properties.description = "valid2"; + return { + status: 200, + body: json(resource), + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_delete = passOnSuccess([ - mockapi.delete( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - if (req.params.topLevelResourceName.toLowerCase() !== "top") { - throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); - } - return { - status: 204, - }; +Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_delete = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName", + method: "delete", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "topLevelResourceName": "top", + "api-version": "2023-12-01-preview", }, - ), -]); + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + if (req.params.topLevelResourceName.toLowerCase() !== "top") { + throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); + } + return { + status: 204, + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_listByResourceGroup = passOnSuccess([ - mockapi.get( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - return { - status: 200, - body: json({ - value: [validTopLevelResource], - }), - }; +Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_listByResourceGroup = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources", + method: "get", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "api-version": "2023-12-01-preview", }, - ), -]); + }, + response: { + status: 200, + body: json({ + value: [validTopLevelResource], + }), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + return { + status: 200, + body: json({ + value: [validTopLevelResource], + }), + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_listBySubscription = passOnSuccess([ - mockapi.get( - "/subscriptions/:subscriptionId/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - return { - status: 200, - body: json({ - value: [validTopLevelResource], - }), - }; +Scenarios.Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_listBySubscription = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources", + method: "get", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "api-version": "2023-12-01-preview", }, - ), -]); + }, + response: { + status: 200, + body: json({ + value: [validTopLevelResource], + }), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + return { + status: 200, + body: json({ + value: [validTopLevelResource], + }), + }; + }, + kind: "MockApiDefinition", +}); // nested proxy resource -Scenarios.Azure_ResourceManager_Models_Resources_NestedProxyResources_get = passOnSuccess([ - mockapi.get( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName/nestedProxyResources/:nestedResourceName", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - if (req.params.topLevelResourceName.toLowerCase() !== "top") { - throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); - } - if (req.params.nestedResourceName.toLowerCase() !== "nested") { - throw new ValidationError("Unexpected nested resource name", "nested", req.params.nestedResourceName); - } - return { - status: 200, - body: json(validNestedResource), - }; +Scenarios.Azure_ResourceManager_Models_Resources_NestedProxyResources_get = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName/nestedProxyResources/:nestedResourceName", + method: "get", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "topLevelResourceName": "top", + "nestedResourceName": "nested", + "api-version": "2023-12-01-preview", }, - ), -]); + }, + response: { + status: 200, + body: json(validNestedResource), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + if (req.params.topLevelResourceName.toLowerCase() !== "top") { + throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); + } + if (req.params.nestedResourceName.toLowerCase() !== "nested") { + throw new ValidationError("Unexpected nested resource name", "nested", req.params.nestedResourceName); + } + return { + status: 200, + body: json(validNestedResource), + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_NestedProxyResources_createOrReplace = passOnSuccess([ - mockapi.put( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName/nestedProxyResources/:nestedResourceName", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - if (req.params.topLevelResourceName.toLowerCase() !== "top") { - throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); - } - if (req.params.nestedResourceName.toLowerCase() !== "nested") { - throw new ValidationError("Unexpected nested resource name", "nested", req.params.nestedResourceName); - } - req.expect.bodyEquals({ - properties: { - description: "valid", - }, - }); - return { - status: 200, - body: json(validNestedResource), - }; +Scenarios.Azure_ResourceManager_Models_Resources_NestedProxyResources_createOrReplace = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName/nestedProxyResources/:nestedResourceName", + method: "put", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "topLevelResourceName": "top", + "nestedResourceName": "nested", + "api-version": "2023-12-01-preview", }, - ), -]); + body: { + properties: { + description: "valid", + }, + }, + }, + response: { + status: 200, + body: json(validNestedResource), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + if (req.params.topLevelResourceName.toLowerCase() !== "top") { + throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); + } + if (req.params.nestedResourceName.toLowerCase() !== "nested") { + throw new ValidationError("Unexpected nested resource name", "nested", req.params.nestedResourceName); + } + req.expect.bodyEquals({ + properties: { + description: "valid", + }, + }); + return { + status: 200, + body: json(validNestedResource), + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_NestedProxyResources_update = passOnSuccess([ - mockapi.patch( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName/nestedProxyResources/:nestedResourceName", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - if (req.params.topLevelResourceName.toLowerCase() !== "top") { - throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); - } - if (req.params.nestedResourceName.toLowerCase() !== "nested") { - throw new ValidationError("Unexpected nested resource name", "nested", req.params.nestedResourceName); - } - req.expect.bodyEquals({ - properties: { - description: "valid2", - }, - }); - const resource = JSON.parse(JSON.stringify(validNestedResource)); - resource.properties.description = "valid2"; - return { - status: 200, - body: json(resource), - }; +Scenarios.Azure_ResourceManager_Models_Resources_NestedProxyResources_update = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName/nestedProxyResources/:nestedResourceName", + method: "patch", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "topLevelResourceName": "top", + "nestedResourceName": "nested", + "api-version": "2023-12-01-preview", + }, + body: { + properties: { + description: "valid2", + }, }, - ), -]); + headers: { + "Content-Type": "application/merge-patch+json", + }, + }, + response: { + status: 200, + body: json({ + ...validNestedResource, + properties: { + provisioningState: "Succeeded", + description: "valid2", + }, + }), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + if (req.params.topLevelResourceName.toLowerCase() !== "top") { + throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); + } + if (req.params.nestedResourceName.toLowerCase() !== "nested") { + throw new ValidationError("Unexpected nested resource name", "nested", req.params.nestedResourceName); + } + req.expect.bodyEquals({ + properties: { + description: "valid2", + }, + }); + const resource = JSON.parse(JSON.stringify(validNestedResource)); + resource.properties.description = "valid2"; + return { + status: 200, + body: json(resource), + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_NestedProxyResources_delete = passOnSuccess([ - mockapi.delete( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName/nestedProxyResources/:nestedResourceName", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - return { - status: 204, - }; +Scenarios.Azure_ResourceManager_Models_Resources_NestedProxyResources_delete = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName/nestedProxyResources/:nestedResourceName", + method: "delete", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "topLevelResourceName": "top", + "nestedResourceName": "nested", + "api-version": "2023-12-01-preview", }, - ), -]); + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Azure_ResourceManager_Models_Resources_NestedProxyResources_listByTopLevelTrackedResource = passOnSuccess([ - mockapi.get( - "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName/nestedProxyResources", - (req) => { - req.expect.containsQueryParam("api-version", "2023-12-01-preview"); - if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { - throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); - } - if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { - throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); - } - if (req.params.topLevelResourceName.toLowerCase() !== "top") { - throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); - } - return { - status: 200, - body: json({ - value: [validNestedResource], - }), - }; +Scenarios.Azure_ResourceManager_Models_Resources_NestedProxyResources_listByTopLevelTrackedResource = passOnSuccess({ + uri: "/subscriptions/:subscriptionId/resourceGroups/:resourceGroup/providers/Azure.ResourceManager.Models.Resources/topLevelTrackedResources/:topLevelResourceName/nestedProxyResources", + method: "get", + request: { + params: { + "subscriptionId": SUBSCRIPTION_ID_EXPECTED, + "resourceGroup": RESOURCE_GROUP_EXPECTED, + "topLevelResourceName": "top", + "api-version": "2023-12-01-preview", }, - ), -]); + }, + response: { + status: 200, + body: json({ + value: [validNestedResource], + }), + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "2023-12-01-preview"); + if (req.params.subscriptionId !== SUBSCRIPTION_ID_EXPECTED) { + throw new ValidationError("Unexpected subscriptionId", SUBSCRIPTION_ID_EXPECTED, req.params.subscriptionId); + } + if (req.params.resourceGroup.toLowerCase() !== RESOURCE_GROUP_EXPECTED) { + throw new ValidationError("Unexpected resourceGroup", RESOURCE_GROUP_EXPECTED, req.params.resourceGroup); + } + if (req.params.topLevelResourceName.toLowerCase() !== "top") { + throw new ValidationError("Unexpected top level resource name", "top", req.params.topLevelResourceName); + } + return { + status: 200, + body: json({ + value: [validNestedResource], + }), + }; + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/azure/special-headers/client-request-id/mockapi.ts b/packages/cadl-ranch-specs/http/azure/special-headers/client-request-id/mockapi.ts index 9e5beb177..fc01aafe4 100644 --- a/packages/cadl-ranch-specs/http/azure/special-headers/client-request-id/mockapi.ts +++ b/packages/cadl-ranch-specs/http/azure/special-headers/client-request-id/mockapi.ts @@ -1,9 +1,22 @@ -import { passOnSuccess, ScenarioMockApi, mockapi, validateValueFormat } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ScenarioMockApi, validateValueFormat, MockRequest } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Azure_SpecialHeaders_XmsClientRequestId = passOnSuccess( - mockapi.get("/azure/special-headers/x-ms-client-request-id", (req) => { +Scenarios.Azure_SpecialHeaders_XmsClientRequestId = passOnSuccess({ + uri: "/azure/special-headers/x-ms-client-request-id", + method: "get", + request: { + headers: { + "x-ms-client-request-id": "123e4567-e89b-12d3-a456-426614174000", + }, + }, + response: { + status: 204, + headers: { + "x-ms-client-request-id": "123e4567-e89b-12d3-a456-426614174000", + }, + }, + handler: (req: MockRequest) => { validateValueFormat(req.headers["x-ms-client-request-id"], "uuid"); return { status: 204, @@ -11,5 +24,6 @@ Scenarios.Azure_SpecialHeaders_XmsClientRequestId = passOnSuccess( ["x-ms-client-request-id"]: req.headers["x-ms-client-request-id"], }, }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/client/naming/mockapi.ts b/packages/cadl-ranch-specs/http/client/naming/mockapi.ts index 352fd90a9..c4acd1f3f 100644 --- a/packages/cadl-ranch-specs/http/client/naming/mockapi.ts +++ b/packages/cadl-ranch-specs/http/client/naming/mockapi.ts @@ -1,104 +1,208 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Client_Naming_Property_client = passOnSuccess( - mockapi.post("/client/naming/property/client", (req) => { +Scenarios.Client_Naming_Property_client = passOnSuccess({ + uri: "/client/naming/property/client", + method: "post", + request: { + body: { defaultName: true }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ defaultName: true }); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Client_Naming_Property_language = passOnSuccess( - mockapi.post("/client/naming/property/language", (req) => { +Scenarios.Client_Naming_Property_language = passOnSuccess({ + uri: "/client/naming/property/language", + method: "post", + request: { + body: { defaultName: true }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ defaultName: true }); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Client_Naming_Property_compatibleWithEncodedName = passOnSuccess( - mockapi.post("/client/naming/property/compatible-with-encoded-name", (req) => { +Scenarios.Client_Naming_Property_compatibleWithEncodedName = passOnSuccess({ + uri: `/client/naming/property/compatible-with-encoded-name`, + method: "post", + request: { + body: { wireName: true }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ wireName: true }); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Client_Naming_operation = passOnSuccess( - mockapi.post("/client/naming/operation", (req) => { +Scenarios.Client_Naming_operation = passOnSuccess({ + uri: `/client/naming/operation`, + method: "post", + request: {}, + response: { + status: 204, + }, + handler: (req: MockRequest) => { return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Client_Naming_parameter = passOnSuccess( - mockapi.post("/client/naming/parameter", (req) => { +Scenarios.Client_Naming_parameter = passOnSuccess({ + uri: `/client/naming/parameter`, + method: "post", + request: { + params: { defaultName: "true" }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("defaultName", "true"); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Client_Naming_Header_request = passOnSuccess( - mockapi.post("/client/naming/header", (req) => { +Scenarios.Client_Naming_Header_request = passOnSuccess({ + uri: `/client/naming/header`, + method: "post", + request: { + headers: { "default-name": "true" }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("default-name", "true"); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Client_Naming_Header_response = passOnSuccess( - mockapi.get("/client/naming/header", (req) => { +Scenarios.Client_Naming_Header_response = passOnSuccess({ + uri: `/client/naming/header`, + method: "get", + request: {}, + response: { + status: 204, + headers: { + "default-name": "true", + }, + }, + handler: (req: MockRequest) => { return { status: 204, headers: { "default-name": "true", }, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Client_Naming_Model_client = passOnSuccess( - mockapi.post("/client/naming/model/client", (req) => { +Scenarios.Client_Naming_Model_client = passOnSuccess({ + uri: `/client/naming/model/client`, + method: "post", + request: { + body: { defaultName: true }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ defaultName: true }); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Client_Naming_Model_language = passOnSuccess( - mockapi.post("/client/naming/model/language", (req) => { +Scenarios.Client_Naming_Model_language = passOnSuccess({ + uri: `/client/naming/model/language`, + method: "post", + request: { + body: { defaultName: true }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ defaultName: true }); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Client_Naming_UnionEnum_unionEnumName = passOnSuccess( - mockapi.post("/client/naming/union-enum/union-enum-name", (req) => { +Scenarios.Client_Naming_UnionEnum_unionEnumName = passOnSuccess({ + uri: `/client/naming/union-enum/union-enum-name`, + method: "post", + request: { + body: "value1", + headers: { + "Content-Type": "text/plain", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals("value1"); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Client_Naming_UnionEnum_unionEnumMemberName = passOnSuccess( - mockapi.post("/client/naming/union-enum/union-enum-member-name", (req) => { +Scenarios.Client_Naming_UnionEnum_unionEnumMemberName = passOnSuccess({ + uri: `/client/naming/union-enum/union-enum-member-name`, + method: "post", + request: { + body: "value1", + headers: { + "Content-Type": "text/plain", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals("value1"); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/client/structure/client-operation-group/mockapi.ts b/packages/cadl-ranch-specs/http/client/structure/client-operation-group/mockapi.ts index 21b2e3ccb..14504ca95 100644 --- a/packages/cadl-ranch-specs/http/client/structure/client-operation-group/mockapi.ts +++ b/packages/cadl-ranch-specs/http/client/structure/client-operation-group/mockapi.ts @@ -1,27 +1,17 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; +import { createServerTests } from "../common/service.js"; export const Scenarios: Record = {}; + Scenarios.Client_Structure_ClientOperationGroup = passOnSuccess([ - mockapi.post("/client/structure/client-operation-group/one", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/client-operation-group/two", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/client-operation-group/three", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/client-operation-group/four", (req) => { - return { status: 204 }; - }), + createServerTests("/client/structure/client-operation-group/one"), + createServerTests("/client/structure/client-operation-group/two"), + createServerTests("/client/structure/client-operation-group/three"), + createServerTests("/client/structure/client-operation-group/four"), ]); Scenarios.Client_Structure_AnotherClientOperationGroup = passOnSuccess([ - mockapi.post("/client/structure/client-operation-group/five", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/client-operation-group/six", (req) => { - return { status: 204 }; - }), + createServerTests("/client/structure/client-operation-group/five"), + createServerTests("/client/structure/client-operation-group/six"), ]); diff --git a/packages/cadl-ranch-specs/http/client/structure/common/service.ts b/packages/cadl-ranch-specs/http/client/structure/common/service.ts new file mode 100644 index 000000000..9d98eb0d1 --- /dev/null +++ b/packages/cadl-ranch-specs/http/client/structure/common/service.ts @@ -0,0 +1,14 @@ +import { MockApiDefinition, MockRequest } from "@azure-tools/cadl-ranch-api"; + +export function createServerTests(uri: string): MockApiDefinition { + return { + uri: uri, + method: "post", + request: {}, + response: { status: 204 }, + handler: (req: MockRequest) => { + return { status: 204 }; + }, + kind: "MockApiDefinition", + }; +} diff --git a/packages/cadl-ranch-specs/http/client/structure/default/mockapi.ts b/packages/cadl-ranch-specs/http/client/structure/default/mockapi.ts index f92ef55ca..ee7a142d6 100644 --- a/packages/cadl-ranch-specs/http/client/structure/default/mockapi.ts +++ b/packages/cadl-ranch-specs/http/client/structure/default/mockapi.ts @@ -1,33 +1,17 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; +import { createServerTests } from "../common/service.js"; export const Scenarios: Record = {}; + Scenarios.Client_Structure_Service = passOnSuccess([ - mockapi.post("/client/structure/default/one", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/default/two", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/default/three", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/default/four", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/default/five", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/default/six", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/default/seven", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/default/eight", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/default/nine", (req) => { - return { status: 204 }; - }), + createServerTests("/client/structure/default/one"), + createServerTests("/client/structure/default/two"), + createServerTests("/client/structure/default/three"), + createServerTests("/client/structure/default/four"), + createServerTests("/client/structure/default/five"), + createServerTests("/client/structure/default/six"), + createServerTests("/client/structure/default/seven"), + createServerTests("/client/structure/default/eight"), + createServerTests("/client/structure/default/nine"), ]); diff --git a/packages/cadl-ranch-specs/http/client/structure/multi-client/mockapi.ts b/packages/cadl-ranch-specs/http/client/structure/multi-client/mockapi.ts index 8f1dedad8..41ea5517b 100644 --- a/packages/cadl-ranch-specs/http/client/structure/multi-client/mockapi.ts +++ b/packages/cadl-ranch-specs/http/client/structure/multi-client/mockapi.ts @@ -1,24 +1,14 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; +import { createServerTests } from "../common/service.js"; export const Scenarios: Record = {}; + Scenarios.Client_Structure_MultiClient = passOnSuccess([ - mockapi.post("/client/structure/multi-client/one", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/multi-client/two", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/multi-client/three", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/multi-client/four", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/multi-client/five", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/multi-client/six", (req) => { - return { status: 204 }; - }), + createServerTests("/client/structure/multi-client/one"), + createServerTests("/client/structure/multi-client/two"), + createServerTests("/client/structure/multi-client/three"), + createServerTests("/client/structure/multi-client/four"), + createServerTests("/client/structure/multi-client/five"), + createServerTests("/client/structure/multi-client/six"), ]); diff --git a/packages/cadl-ranch-specs/http/client/structure/renamed-operation/mockapi.ts b/packages/cadl-ranch-specs/http/client/structure/renamed-operation/mockapi.ts index a236556cf..14149236d 100644 --- a/packages/cadl-ranch-specs/http/client/structure/renamed-operation/mockapi.ts +++ b/packages/cadl-ranch-specs/http/client/structure/renamed-operation/mockapi.ts @@ -1,24 +1,14 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; +import { createServerTests } from "../common/service.js"; export const Scenarios: Record = {}; + Scenarios.Client_Structure_RenamedOperation = passOnSuccess([ - mockapi.post("/client/structure/renamed-operation/one", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/renamed-operation/two", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/renamed-operation/three", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/renamed-operation/four", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/renamed-operation/five", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/renamed-operation/six", (req) => { - return { status: 204 }; - }), + createServerTests("/client/structure/renamed-operation/one"), + createServerTests("/client/structure/renamed-operation/two"), + createServerTests("/client/structure/renamed-operation/three"), + createServerTests("/client/structure/renamed-operation/four"), + createServerTests("/client/structure/renamed-operation/five"), + createServerTests("/client/structure/renamed-operation/six"), ]); diff --git a/packages/cadl-ranch-specs/http/client/structure/two-operation-group/mockapi.ts b/packages/cadl-ranch-specs/http/client/structure/two-operation-group/mockapi.ts index 651b902ff..d58d522ca 100644 --- a/packages/cadl-ranch-specs/http/client/structure/two-operation-group/mockapi.ts +++ b/packages/cadl-ranch-specs/http/client/structure/two-operation-group/mockapi.ts @@ -1,24 +1,14 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; +import { createServerTests } from "../common/service.js"; export const Scenarios: Record = {}; + Scenarios.Client_Structure_TwoOperationGroup = passOnSuccess([ - mockapi.post("/client/structure/two-operation-group/one", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/two-operation-group/two", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/two-operation-group/three", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/two-operation-group/four", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/two-operation-group/five", (req) => { - return { status: 204 }; - }), - mockapi.post("/client/structure/two-operation-group/six", (req) => { - return { status: 204 }; - }), + createServerTests("/client/structure/two-operation-group/one"), + createServerTests("/client/structure/two-operation-group/two"), + createServerTests("/client/structure/two-operation-group/three"), + createServerTests("/client/structure/two-operation-group/four"), + createServerTests("/client/structure/two-operation-group/five"), + createServerTests("/client/structure/two-operation-group/six"), ]); diff --git a/packages/cadl-ranch-specs/http/encode/bytes/mockapi.ts b/packages/cadl-ranch-specs/http/encode/bytes/mockapi.ts index 71cb04391..cb135d999 100644 --- a/packages/cadl-ranch-specs/http/encode/bytes/mockapi.ts +++ b/packages/cadl-ranch-specs/http/encode/bytes/mockapi.ts @@ -1,4 +1,4 @@ -import { passOnSuccess, mockapi, json, CollectionFormat, MockApi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, CollectionFormat, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; import { resolvePath } from "@typespec/compiler"; import { readFileSync } from "fs"; @@ -10,98 +10,291 @@ const pngFile = readFileSync(resolvePath(root, "assets/image.png")); export const Scenarios: Record = {}; -function createQueryMockApis(route: string, value: any, collectionFormat?: CollectionFormat): MockApi { - const url = `/encode/bytes/query/${route}`; - return mockapi.get(url, (req) => { - req.expect.containsQueryParam("value", value, collectionFormat); - return { +function createQueryServerTests(uri: string, data: any, value: any, collectionFormat?: CollectionFormat) { + return passOnSuccess({ + uri, + method: "get", + request: { + params: data, + }, + response: { status: 204, - }; + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("value", value, collectionFormat); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", }); } - -function createPropertyMockApis(route: string, value: any): MockApi { - const url = `/encode/bytes/property/${route}`; - return mockapi.post(url, (req) => { - req.expect.coercedBodyEquals({ value: value }); - return { +Scenarios.Encode_Bytes_Query_default = createQueryServerTests( + "/encode/bytes/query/default", + { + value: "dGVzdA==", + }, + "dGVzdA==", +); +Scenarios.Encode_Bytes_Query_base64 = createQueryServerTests( + "/encode/bytes/query/base64", + { + value: "dGVzdA==", + }, + "dGVzdA==", +); +Scenarios.Encode_Bytes_Query_base64url = createQueryServerTests( + "/encode/bytes/query/base64url", + { + value: "dGVzdA", + }, + "dGVzdA", +); +Scenarios.Encode_Bytes_Query_base64urlArray = createQueryServerTests( + "/encode/bytes/query/base64url-array", + { + value: ["dGVzdA", "dGVzdA"].join(","), + }, + ["dGVzdA", "dGVzdA"], + "csv", +); +function createPropertyServerTests(uri: string, data: any, value: any) { + return passOnSuccess({ + uri, + method: "post", + request: { + body: data, + }, + response: { status: 200, - body: json({ value: value }), - }; + }, + handler: (req: MockRequest) => { + req.expect.coercedBodyEquals({ value: value }); + return { + status: 200, + body: json({ value: value }), + }; + }, + kind: "MockApiDefinition", }); } - -function createHeaderMockApis(route: string, value: any): MockApi { - const url = `/encode/bytes/header/${route}`; - return mockapi.get(url, (req) => { - req.expect.containsHeader("value", value); - return { +Scenarios.Encode_Bytes_Property_default = createPropertyServerTests( + "/encode/bytes/property/default", + { + value: "dGVzdA==", + }, + "dGVzdA==", +); +Scenarios.Encode_Bytes_Property_base64 = createPropertyServerTests( + "/encode/bytes/property/base64", + { + value: "dGVzdA==", + }, + "dGVzdA==", +); +Scenarios.Encode_Bytes_Property_base64url = createPropertyServerTests( + "/encode/bytes/property/base64url", + { + value: "dGVzdA", + }, + "dGVzdA", +); +Scenarios.Encode_Bytes_Property_base64urlArray = createPropertyServerTests( + "/encode/bytes/property/base64url-array", + { + value: ["dGVzdA", "dGVzdA"], + }, + ["dGVzdA", "dGVzdA"], +); +function createHeaderServerTests(uri: string, data: any, value: any) { + return passOnSuccess({ + uri, + method: "get", + request: { + headers: data, + }, + response: { status: 204, - }; + }, + handler: (req: MockRequest) => { + req.expect.containsHeader("value", value); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", }); } - -function createRequestBodyMockApis(route: string, value: any, contentType: string = "application/json"): MockApi { - const url = `/encode/bytes/body/request/${route}`; - return mockapi.post(url, (req) => { - req.expect.containsHeader("content-type", contentType); - req.expect.rawBodyEquals(value); - return { +Scenarios.Encode_Bytes_Header_default = createHeaderServerTests( + "/encode/bytes/header/default", + { + value: "dGVzdA==", + }, + "dGVzdA==", +); +Scenarios.Encode_Bytes_Header_base64 = createHeaderServerTests( + "/encode/bytes/header/base64", + { + value: "dGVzdA==", + }, + "dGVzdA==", +); +Scenarios.Encode_Bytes_Header_base64url = createHeaderServerTests( + "/encode/bytes/header/base64url", + { + value: "dGVzdA", + }, + "dGVzdA", +); +Scenarios.Encode_Bytes_Header_base64urlArray = createHeaderServerTests( + "/encode/bytes/header/base64url-array", + { + value: ["dGVzdA", "dGVzdA"].join(","), + }, + ["dGVzdA", "dGVzdA"].join(","), +); +function createRequestBodyServerTests( + uri: string, + data: any, + headersData: any, + value: any, + contentType: string = "application/json", +) { + return passOnSuccess({ + uri, + method: "post", + request: { + body: data, + headers: headersData, + }, + response: { status: 204, - }; + }, + handler(req: MockRequest) { + req.expect.containsHeader("content-type", contentType); + req.expect.rawBodyEquals(value); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", }); } - -function createResponseBodyMockApis(route: string, value: any, contentType: string = "application/json"): MockApi { - const url = `/encode/bytes/body/response/${route}`; - return mockapi.get(url, (req) => { - return { +// Request body +Scenarios.Encode_Bytes_RequestBody_default = createRequestBodyServerTests( + "/encode/bytes/body/request/default", + '"dGVzdA=="', + { + "Content-Type": "application/json", + }, + '"dGVzdA=="', +); +Scenarios.Encode_Bytes_RequestBody_octetStream = createRequestBodyServerTests( + "/encode/bytes/body/request/octet-stream", + pngFile, + { + "Content-Type": "application/octet-stream", + }, + pngFile, + "application/octet-stream", +); +Scenarios.Encode_Bytes_RequestBody_customContentType = createRequestBodyServerTests( + "/encode/bytes/body/request/custom-content-type", + pngFile, + { + "Content-Type": "image/png", + }, + pngFile, + "image/png", +); +Scenarios.Encode_Bytes_RequestBody_base64 = createRequestBodyServerTests( + "/encode/bytes/body/request/base64", + '"dGVzdA=="', + { + "Content-Type": "application/json", + }, + '"dGVzdA=="', +); +Scenarios.Encode_Bytes_RequestBody_base64url = createRequestBodyServerTests( + "/encode/bytes/body/request/base64url", + '"dGVzdA=="', + { + "Content-Type": "application/json", + }, + '"dGVzdA=="', +); +function createResponseBodyServerTests( + uri: string, + data: any, + headerData: any, + value: any, + contentType: string = "application/json", +) { + return passOnSuccess({ + uri, + method: "get", + request: { + headers: headerData, + }, + response: { status: 200, body: { contentType: contentType, - rawContent: value, + rawContent: data, }, - }; + }, + handler(req: MockRequest) { + return { + status: 200, + body: { + contentType: contentType, + rawContent: value, + }, + }; + }, + kind: "MockApiDefinition", }); } - -Scenarios.Encode_Bytes_Query_default = passOnSuccess(createQueryMockApis("default", "dGVzdA==")); -Scenarios.Encode_Bytes_Query_base64 = passOnSuccess(createQueryMockApis("base64", "dGVzdA==")); -Scenarios.Encode_Bytes_Query_base64url = passOnSuccess(createQueryMockApis("base64url", "dGVzdA")); -Scenarios.Encode_Bytes_Query_base64urlArray = passOnSuccess( - createQueryMockApis("base64url-array", ["dGVzdA", "dGVzdA"], "csv"), -); - -Scenarios.Encode_Bytes_Property_default = passOnSuccess(createPropertyMockApis("default", "dGVzdA==")); -Scenarios.Encode_Bytes_Property_base64 = passOnSuccess(createPropertyMockApis("base64", "dGVzdA==")); -Scenarios.Encode_Bytes_Property_base64url = passOnSuccess(createPropertyMockApis("base64url", "dGVzdA")); -Scenarios.Encode_Bytes_Property_base64urlArray = passOnSuccess( - createPropertyMockApis("base64url-array", ["dGVzdA", "dGVzdA"]), +// Response body +Scenarios.Encode_Bytes_ResponseBody_default = createResponseBodyServerTests( + "/encode/bytes/body/response/default", + JSON.stringify("dGVzdA=="), + { + "Content-Type": "application/json", + }, + JSON.stringify("dGVzdA=="), ); - -Scenarios.Encode_Bytes_Header_default = passOnSuccess(createHeaderMockApis("default", "dGVzdA==")); -Scenarios.Encode_Bytes_Header_base64 = passOnSuccess(createHeaderMockApis("base64", "dGVzdA==")); -Scenarios.Encode_Bytes_Header_base64url = passOnSuccess(createHeaderMockApis("base64url", "dGVzdA")); -Scenarios.Encode_Bytes_Header_base64urlArray = passOnSuccess(createHeaderMockApis("base64url-array", "dGVzdA,dGVzdA")); - -// Request body -Scenarios.Encode_Bytes_RequestBody_default = passOnSuccess(createRequestBodyMockApis("default", '"dGVzdA=="')); -Scenarios.Encode_Bytes_RequestBody_octetStream = passOnSuccess( - createRequestBodyMockApis("octet-stream", pngFile, "application/octet-stream"), +Scenarios.Encode_Bytes_ResponseBody_octetStream = createResponseBodyServerTests( + "/encode/bytes/body/response/octet-stream", + pngFile, + { + "Content-Type": "application/octet-stream", + }, + pngFile, + "application/octet-stream", ); -Scenarios.Encode_Bytes_RequestBody_customContentType = passOnSuccess( - createRequestBodyMockApis("custom-content-type", pngFile, "image/png"), +Scenarios.Encode_Bytes_ResponseBody_customContentType = createResponseBodyServerTests( + "/encode/bytes/body/response/custom-content-type", + pngFile, + { + "Content-Type": "image/png", + }, + pngFile, + "image/png", ); -Scenarios.Encode_Bytes_RequestBody_base64 = passOnSuccess(createRequestBodyMockApis("base64", '"dGVzdA=="')); -Scenarios.Encode_Bytes_RequestBody_base64url = passOnSuccess(createRequestBodyMockApis("base64url", '"dGVzdA"')); - -// Response body -Scenarios.Encode_Bytes_ResponseBody_default = passOnSuccess(createResponseBodyMockApis("default", '"dGVzdA=="')); -Scenarios.Encode_Bytes_ResponseBody_octetStream = passOnSuccess( - createResponseBodyMockApis("octet-stream", pngFile, "application/octet-stream"), +Scenarios.Encode_Bytes_ResponseBody_base64 = createResponseBodyServerTests( + "/encode/bytes/body/response/base64", + JSON.stringify("dGVzdA=="), + { + "Content-Type": "application/json", + }, + JSON.stringify("dGVzdA=="), ); -Scenarios.Encode_Bytes_ResponseBody_customContentType = passOnSuccess( - createResponseBodyMockApis("custom-content-type", pngFile, "image/png"), +Scenarios.Encode_Bytes_ResponseBody_base64url = createResponseBodyServerTests( + "/encode/bytes/body/response/base64url", + JSON.stringify("dGVzdA"), + { + "Content-Type": "application/json", + }, + JSON.stringify("dGVzdA"), ); -Scenarios.Encode_Bytes_ResponseBody_base64 = passOnSuccess(createResponseBodyMockApis("base64", '"dGVzdA=="')); -Scenarios.Encode_Bytes_ResponseBody_base64url = passOnSuccess(createResponseBodyMockApis("base64url", '"dGVzdA"')); diff --git a/packages/cadl-ranch-specs/http/encode/datetime/mockapi.ts b/packages/cadl-ranch-specs/http/encode/datetime/mockapi.ts index e91f000f6..aee0a373b 100644 --- a/packages/cadl-ranch-specs/http/encode/datetime/mockapi.ts +++ b/packages/cadl-ranch-specs/http/encode/datetime/mockapi.ts @@ -1,140 +1,264 @@ import { passOnSuccess, - mockapi, json, CollectionFormat, - MockApi, validateValueFormat, ValidationError, + MockRequest, } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -function createQueryMockApis( - route: string, +function createQueryServerTests( + uri: string, + paramData: any, format: "rfc7231" | "rfc3339" | undefined, value: any, collectionFormat?: CollectionFormat, -): MockApi { - const url = `/encode/datetime/query/${route}`; - return mockapi.get(url, (req) => { - if (format) { - validateValueFormat(req.query["value"] as string, format); - if (Date.parse(req.query["value"] as string) !== Date.parse(value)) { - throw new ValidationError(`Wrong value`, value, req.query["value"]); - } - } else { - req.expect.containsQueryParam("value", value, collectionFormat); - } - return { +) { + return passOnSuccess({ + uri, + method: "get", + request: { + params: paramData, + }, + response: { status: 204, - }; - }); -} - -function createPropertyMockApis(route: string, format: "rfc7231" | "rfc3339" | undefined, value: any): MockApi { - const url = `/encode/datetime/property/${route}`; - return mockapi.post(url, (req) => { - if (format) { - validateValueFormat(req.body["value"], format); - if (Date.parse(req.body["value"]) !== Date.parse(value)) { - throw new ValidationError(`Wrong value`, value, req.body["value"]); + }, + handler(req: MockRequest) { + if (format) { + validateValueFormat(req.query["value"] as string, format); + if (Date.parse(req.query["value"] as string) !== Date.parse(value)) { + throw new ValidationError(`Wrong value`, value, req.query["value"]); + } + } else { + req.expect.containsQueryParam("value", value, collectionFormat); } - } else { - req.expect.coercedBodyEquals({ value: value }); - } - return { - status: 200, - body: json({ value: value }), - }; + return { + status: 204, + }; + }, + kind: "MockApiDefinition", }); } - -function createHeaderMockApis(route: string, format: "rfc7231" | "rfc3339" | undefined, value: any): MockApi { - const url = `/encode/datetime/header/${route}`; - return mockapi.get(url, (req) => { - if (format) { - validateValueFormat(req.headers["value"], format); - if (Date.parse(req.headers["value"]) !== Date.parse(value)) { - throw new ValidationError(`Wrong value`, value, req.headers["value"]); - } - } else { - req.expect.containsHeader("value", value); - } - return { - status: 204, - }; - }); -} - -function createResponseHeaderMockApis(route: string, value: any): MockApi { - const url = `/encode/datetime/responseheader/${route}`; - return mockapi.get(url, () => { - return { - status: 204, - headers: { value: value }, - }; - }); -} - -Scenarios.Encode_Datetime_Query_default = passOnSuccess( - createQueryMockApis("default", "rfc3339", "2022-08-26T18:38:00.000Z"), +Scenarios.Encode_Datetime_Query_default = createQueryServerTests( + "/encode/datetime/query/default", + { + value: "2022-08-26T18:38:00.000Z", + }, + "rfc3339", + "2022-08-26T18:38:00.000Z", ); -Scenarios.Encode_Datetime_Query_rfc3339 = passOnSuccess( - createQueryMockApis("rfc3339", "rfc3339", "2022-08-26T18:38:00.000Z"), +Scenarios.Encode_Datetime_Query_rfc3339 = createQueryServerTests( + "/encode/datetime/query/rfc3339", + { + value: "2022-08-26T18:38:00.000Z", + }, + "rfc3339", + "2022-08-26T18:38:00.000Z", ); -Scenarios.Encode_Datetime_Query_rfc7231 = passOnSuccess( - createQueryMockApis("rfc7231", "rfc7231", "Fri, 26 Aug 2022 14:38:00 GMT"), +Scenarios.Encode_Datetime_Query_rfc7231 = createQueryServerTests( + "/encode/datetime/query/rfc7231", + { + value: "Fri, 26 Aug 2022 14:38:00 GMT", + }, + "rfc7231", + "Fri, 26 Aug 2022 14:38:00 GMT", ); -Scenarios.Encode_Datetime_Query_unixTimestamp = passOnSuccess( - createQueryMockApis("unix-timestamp", undefined, "1686566864"), +Scenarios.Encode_Datetime_Query_unixTimestamp = createQueryServerTests( + "/encode/datetime/query/unix-timestamp", + { + value: 1686566864, + }, + undefined, + "1686566864", ); -Scenarios.Encode_Datetime_Query_unixTimestampArray = passOnSuccess( - createQueryMockApis("unix-timestamp-array", undefined, ["1686566864", "1686734256"], "csv"), +Scenarios.Encode_Datetime_Query_unixTimestampArray = createQueryServerTests( + "/encode/datetime/query/unix-timestamp-array", + { + value: [1686566864, 1686734256].join(","), + }, + undefined, + ["1686566864", "1686734256"], + "csv", ); - -Scenarios.Encode_Datetime_Property_default = passOnSuccess( - createPropertyMockApis("default", "rfc3339", "2022-08-26T18:38:00.000Z"), +function createPropertyServerTests(uri: string, data: any, format: "rfc7231" | "rfc3339" | undefined, value: any) { + return passOnSuccess({ + uri, + method: "post", + request: { + body: data, + }, + response: { + status: 200, + }, + handler: (req: MockRequest) => { + if (format) { + validateValueFormat(req.body["value"], format); + if (Date.parse(req.body["value"]) !== Date.parse(value)) { + throw new ValidationError(`Wrong value`, value, req.body["value"]); + } + } else { + req.expect.coercedBodyEquals({ value: value }); + } + return { + status: 200, + body: json({ value: value }), + }; + }, + kind: "MockApiDefinition", + }); +} +Scenarios.Encode_Datetime_Property_default = createPropertyServerTests( + "/encode/datetime/property/default", + { + value: "2022-08-26T18:38:00.000Z", + }, + "rfc3339", + "2022-08-26T18:38:00.000Z", ); -Scenarios.Encode_Datetime_Property_rfc3339 = passOnSuccess( - createPropertyMockApis("rfc3339", "rfc3339", "2022-08-26T18:38:00.000Z"), +Scenarios.Encode_Datetime_Property_rfc3339 = createPropertyServerTests( + "/encode/datetime/property/rfc3339", + { + value: "2022-08-26T18:38:00.000Z", + }, + "rfc3339", + "2022-08-26T18:38:00.000Z", ); -Scenarios.Encode_Datetime_Property_rfc7231 = passOnSuccess( - createPropertyMockApis("rfc7231", "rfc7231", "Fri, 26 Aug 2022 14:38:00 GMT"), +Scenarios.Encode_Datetime_Property_rfc7231 = createPropertyServerTests( + "/encode/datetime/property/rfc7231", + { + value: "Fri, 26 Aug 2022 14:38:00 GMT", + }, + "rfc7231", + "Fri, 26 Aug 2022 14:38:00 GMT", ); -Scenarios.Encode_Datetime_Property_unixTimestamp = passOnSuccess( - createPropertyMockApis("unix-timestamp", undefined, 1686566864), +Scenarios.Encode_Datetime_Property_unixTimestamp = createPropertyServerTests( + "/encode/datetime/property/unix-timestamp", + { + value: 1686566864, + }, + undefined, + 1686566864, ); -Scenarios.Encode_Datetime_Property_unixTimestampArray = passOnSuccess( - createPropertyMockApis("unix-timestamp-array", undefined, [1686566864, 1686734256]), +Scenarios.Encode_Datetime_Property_unixTimestampArray = createPropertyServerTests( + "/encode/datetime/property/unix-timestamp-array", + { + value: [1686566864, 1686734256], + }, + undefined, + [1686566864, 1686734256], ); - -Scenarios.Encode_Datetime_Header_default = passOnSuccess( - createHeaderMockApis("default", "rfc7231", "Fri, 26 Aug 2022 14:38:00 GMT"), +function createHeaderServerTests(uri: string, data: any, format: "rfc7231" | "rfc3339" | undefined, value: any) { + return passOnSuccess({ + uri, + method: "get", + request: { + headers: data, + }, + response: { + status: 204, + }, + handler(req: MockRequest) { + if (format) { + validateValueFormat(req.headers["value"], format); + if (Date.parse(req.headers["value"]) !== Date.parse(value)) { + throw new ValidationError(`Wrong value`, value, req.headers["value"]); + } + } else { + req.expect.containsHeader("value", value); + } + return { + status: 204, + }; + }, + kind: "MockApiDefinition", + }); +} +Scenarios.Encode_Datetime_Header_default = createHeaderServerTests( + "/encode/datetime/header/default", + { + value: "Fri, 26 Aug 2022 14:38:00 GMT", + }, + "rfc7231", + "Fri, 26 Aug 2022 14:38:00 GMT", ); -Scenarios.Encode_Datetime_Header_rfc3339 = passOnSuccess( - createHeaderMockApis("rfc3339", "rfc3339", "2022-08-26T18:38:00.000Z"), +Scenarios.Encode_Datetime_Header_rfc3339 = createHeaderServerTests( + "/encode/datetime/header/rfc3339", + { + value: "2022-08-26T18:38:00.000Z", + }, + "rfc3339", + "2022-08-26T18:38:00.000Z", ); -Scenarios.Encode_Datetime_Header_rfc7231 = passOnSuccess( - createHeaderMockApis("rfc7231", "rfc7231", "Fri, 26 Aug 2022 14:38:00 GMT"), +Scenarios.Encode_Datetime_Header_rfc7231 = createHeaderServerTests( + "/encode/datetime/header/rfc7231", + { + value: "Fri, 26 Aug 2022 14:38:00 GMT", + }, + "rfc7231", + "Fri, 26 Aug 2022 14:38:00 GMT", ); -Scenarios.Encode_Datetime_Header_unixTimestamp = passOnSuccess( - createHeaderMockApis("unix-timestamp", undefined, "1686566864"), +Scenarios.Encode_Datetime_Header_unixTimestamp = createHeaderServerTests( + "/encode/datetime/header/unix-timestamp", + { + value: 1686566864, + }, + undefined, + "1686566864", ); -Scenarios.Encode_Datetime_Header_unixTimestampArray = passOnSuccess( - createHeaderMockApis("unix-timestamp-array", undefined, "1686566864,1686734256"), +Scenarios.Encode_Datetime_Header_unixTimestampArray = createHeaderServerTests( + "/encode/datetime/header/unix-timestamp-array", + { + value: [1686566864, 1686734256].join(","), + }, + undefined, + "1686566864,1686734256", ); - -Scenarios.Encode_Datetime_ResponseHeader_default = passOnSuccess( - createResponseHeaderMockApis("default", "Fri, 26 Aug 2022 14:38:00 GMT"), +function createResponseHeaderServerTests(uri: string, data: any, value: any) { + return passOnSuccess({ + uri, + method: "get", + request: {}, + response: { + status: 204, + headers: data, + }, + handler: (req: MockRequest) => { + return { + status: 204, + headers: { value: value }, + }; + }, + kind: "MockApiDefinition", + }); +} +Scenarios.Encode_Datetime_ResponseHeader_default = createResponseHeaderServerTests( + "/encode/datetime/responseheader/default", + { + value: "Fri, 26 Aug 2022 14:38:00 GMT", + }, + "Fri, 26 Aug 2022 14:38:00 GMT", ); -Scenarios.Encode_Datetime_ResponseHeader_rfc3339 = passOnSuccess( - createResponseHeaderMockApis("rfc3339", "2022-08-26T18:38:00.000Z"), +Scenarios.Encode_Datetime_ResponseHeader_rfc3339 = createResponseHeaderServerTests( + "/encode/datetime/responseheader/rfc3339", + { + value: "2022-08-26T18:38:00.000Z", + }, + "2022-08-26T18:38:00.000Z", ); -Scenarios.Encode_Datetime_ResponseHeader_rfc7231 = passOnSuccess( - createResponseHeaderMockApis("rfc7231", "Fri, 26 Aug 2022 14:38:00 GMT"), +Scenarios.Encode_Datetime_ResponseHeader_rfc7231 = createResponseHeaderServerTests( + "/encode/datetime/responseheader/rfc7231", + { + value: "Fri, 26 Aug 2022 14:38:00 GMT", + }, + "Fri, 26 Aug 2022 14:38:00 GMT", ); -Scenarios.Encode_Datetime_ResponseHeader_unixTimestamp = passOnSuccess( - createResponseHeaderMockApis("unix-timestamp", 1686566864), +Scenarios.Encode_Datetime_ResponseHeader_unixTimestamp = createResponseHeaderServerTests( + "/encode/datetime/responseheader/unix-timestamp", + { + value: "1686566864", + }, + 1686566864, ); diff --git a/packages/cadl-ranch-specs/http/encode/duration/mockapi.ts b/packages/cadl-ranch-specs/http/encode/duration/mockapi.ts index f2d8265bf..f3090e1d9 100644 --- a/packages/cadl-ranch-specs/http/encode/duration/mockapi.ts +++ b/packages/cadl-ranch-specs/http/encode/duration/mockapi.ts @@ -1,60 +1,191 @@ -import { passOnSuccess, mockapi, json, MockApi, CollectionFormat } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, CollectionFormat, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -function createQueryMockApis(route: string, value: any, collectionFormat?: CollectionFormat): MockApi { - const url = `/encode/duration/query/${route}`; - return mockapi.get(url, (req) => { - req.expect.containsQueryParam("input", value, collectionFormat); - return { +function createQueryServerTests(uri: string, paramData: any, value: any, collectionFormat?: CollectionFormat) { + return passOnSuccess({ + uri, + method: "get", + request: { + params: paramData, + }, + response: { status: 204, - }; + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("input", value, collectionFormat); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", }); } - -function createPropertyMockApis(route: string, value: any): MockApi { - const url = `/encode/duration/property/${route}`; - return mockapi.post(url, (req) => { - req.expect.coercedBodyEquals({ value: value }); - return { +Scenarios.Encode_Duration_Query_default = createQueryServerTests( + "/encode/duration/query/default", + { + input: "P40D", + }, + "P40D", +); +Scenarios.Encode_Duration_Query_iso8601 = createQueryServerTests( + "/encode/duration/query/iso8601", + { + input: "P40D", + }, + "P40D", +); +Scenarios.Encode_Duration_Query_int32Seconds = createQueryServerTests( + "/encode/duration/query/int32-seconds", + { + input: 36, + }, + "36", +); +Scenarios.Encode_Duration_Query_int32SecondsArray = createQueryServerTests( + "/encode/duration/query/int32-seconds-array", + { + input: [36, 47].join(","), + }, + ["36", "47"], + "csv", +); +Scenarios.Encode_Duration_Query_floatSeconds = createQueryServerTests( + "/encode/duration/query/float-seconds", + { + input: 35.625, + }, + "35.625", +); +Scenarios.Encode_Duration_Query_float64Seconds = createQueryServerTests( + "/encode/duration/query/float64-seconds", + { + input: 35.625, + }, + "35.625", +); +function createBodyServerTests(uri: string, data: any, value: any) { + return passOnSuccess({ + uri, + method: "post", + request: { + body: data, + }, + response: { status: 200, - body: json({ value: value }), - }; + body: json(data), + }, + handler: (req: MockRequest) => { + req.expect.coercedBodyEquals({ value: value }); + return { + status: 200, + body: json({ value: value }), + }; + }, + kind: "MockApiDefinition", }); } - -function createHeaderMockApis(route: string, value: any): MockApi { - const url = `/encode/duration/header/${route}`; - return mockapi.get(url, (req) => { - req.expect.containsHeader("duration", value); - return { +Scenarios.Encode_Duration_Property_default = createBodyServerTests( + "/encode/duration/property/default", + { + value: "P40D", + }, + "P40D", +); +Scenarios.Encode_Duration_Property_iso8601 = createBodyServerTests( + "/encode/duration/property/iso8601", + { + value: "P40D", + }, + "P40D", +); +Scenarios.Encode_Duration_Property_int32Seconds = createBodyServerTests( + "/encode/duration/property/int32-seconds", + { + value: 36, + }, + 36, +); +Scenarios.Encode_Duration_Property_floatSeconds = createBodyServerTests( + "/encode/duration/property/float-seconds", + { + value: 35.625, + }, + 35.625, +); +Scenarios.Encode_Duration_Property_float64Seconds = createBodyServerTests( + "/encode/duration/property/float64-seconds", + { + value: 35.625, + }, + 35.625, +); +Scenarios.Encode_Duration_Property_floatSecondsArray = createBodyServerTests( + "/encode/duration/property/float-seconds-array", + { + value: [35.625, 46.75], + }, + [35.625, 46.75], +); +function createHeaderServerTests(uri: string, headersData: any, value: any) { + return passOnSuccess({ + uri, + method: "get", + request: { + headers: headersData, + }, + response: { status: 204, - }; + }, + handler: (req: MockRequest) => { + req.expect.containsHeader("duration", value); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", }); } - -Scenarios.Encode_Duration_Query_default = passOnSuccess(createQueryMockApis("default", "P40D")); -Scenarios.Encode_Duration_Query_iso8601 = passOnSuccess(createQueryMockApis("iso8601", "P40D")); -Scenarios.Encode_Duration_Query_int32Seconds = passOnSuccess(createQueryMockApis("int32-seconds", "36")); -Scenarios.Encode_Duration_Query_int32SecondsArray = passOnSuccess( - createQueryMockApis("int32-seconds-array", ["36", "47"], "csv"), -); -Scenarios.Encode_Duration_Query_floatSeconds = passOnSuccess(createQueryMockApis("float-seconds", "35.625")); -Scenarios.Encode_Duration_Query_float64Seconds = passOnSuccess(createQueryMockApis("float64-seconds", "35.625")); - -Scenarios.Encode_Duration_Property_default = passOnSuccess(createPropertyMockApis("default", "P40D")); -Scenarios.Encode_Duration_Property_iso8601 = passOnSuccess(createPropertyMockApis("iso8601", "P40D")); -Scenarios.Encode_Duration_Property_int32Seconds = passOnSuccess(createPropertyMockApis("int32-seconds", 36)); -Scenarios.Encode_Duration_Property_floatSeconds = passOnSuccess(createPropertyMockApis("float-seconds", 35.625)); -Scenarios.Encode_Duration_Property_float64Seconds = passOnSuccess(createPropertyMockApis("float64-seconds", 35.625)); -Scenarios.Encode_Duration_Property_floatSecondsArray = passOnSuccess( - createPropertyMockApis("float-seconds-array", [35.625, 46.75]), +Scenarios.Encode_Duration_Header_default = createHeaderServerTests( + "/encode/duration/header/default", + { + duration: "P40D", + }, + "P40D", +); +Scenarios.Encode_Duration_Header_iso8601 = createHeaderServerTests( + "/encode/duration/header/iso8601", + { + duration: "P40D", + }, + "P40D", +); +Scenarios.Encode_Duration_Header_iso8601Array = createHeaderServerTests( + "/encode/duration/header/iso8601-array", + { + duration: ["P40D", "P50D"].join(","), + }, + "P40D,P50D", +); +Scenarios.Encode_Duration_Header_int32Seconds = createHeaderServerTests( + "/encode/duration/header/int32-seconds", + { + duration: 36, + }, + "36", +); +Scenarios.Encode_Duration_Header_floatSeconds = createHeaderServerTests( + "/encode/duration/header/float-seconds", + { + duration: 35.625, + }, + "35.625", +); +Scenarios.Encode_Duration_Header_float64Seconds = createHeaderServerTests( + "/encode/duration/header/float64-seconds", + { + duration: 35.625, + }, + "35.625", ); - -Scenarios.Encode_Duration_Header_default = passOnSuccess(createHeaderMockApis("default", "P40D")); -Scenarios.Encode_Duration_Header_iso8601 = passOnSuccess(createHeaderMockApis("iso8601", "P40D")); -Scenarios.Encode_Duration_Header_iso8601Array = passOnSuccess(createHeaderMockApis("iso8601-array", "P40D,P50D")); -Scenarios.Encode_Duration_Header_int32Seconds = passOnSuccess(createHeaderMockApis("int32-seconds", "36")); -Scenarios.Encode_Duration_Header_floatSeconds = passOnSuccess(createHeaderMockApis("float-seconds", "35.625")); -Scenarios.Encode_Duration_Header_float64Seconds = passOnSuccess(createHeaderMockApis("float64-seconds", "35.625")); diff --git a/packages/cadl-ranch-specs/http/encode/numeric/mockapi.ts b/packages/cadl-ranch-specs/http/encode/numeric/mockapi.ts index 7f6632963..ea588c265 100644 --- a/packages/cadl-ranch-specs/http/encode/numeric/mockapi.ts +++ b/packages/cadl-ranch-specs/http/encode/numeric/mockapi.ts @@ -1,21 +1,34 @@ -import { passOnSuccess, mockapi, json, MockApi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -function createPropertyMockApis(route: string, value: string): MockApi { - const url = `/encode/numeric/property/${route}`; - return mockapi.post(url, (req) => { - req.expect.coercedBodyEquals({ value: value }); - return { +function createTests(uri: string, value: any) { + return passOnSuccess({ + uri, + method: "post", + request: { + body: { + value, + }, + }, + response: { status: 200, - body: json({ value: value }), - }; + body: json({ value }), + }, + handler: (req: MockRequest) => { + req.expect.coercedBodyEquals({ value }); + return { + status: 200, + body: json({ value }), + }; + }, + kind: "MockApiDefinition", }); } -Scenarios.Encode_Numeric_Property_safeintAsString = passOnSuccess(createPropertyMockApis("safeint", "10000000000")); +Scenarios.Encode_Numeric_Property_safeintAsString = createTests("/encode/numeric/property/safeint", "10000000000"); -Scenarios.Encode_Numeric_Property_uint32AsStringOptional = passOnSuccess(createPropertyMockApis("uint32", "1")); +Scenarios.Encode_Numeric_Property_uint32AsStringOptional = createTests("/encode/numeric/property/uint32", "1"); -Scenarios.Encode_Numeric_Property_uint8AsString = passOnSuccess(createPropertyMockApis("uint8", "255")); +Scenarios.Encode_Numeric_Property_uint8AsString = createTests("/encode/numeric/property/uint8", "255"); diff --git a/packages/cadl-ranch-specs/http/parameters/basic/mockapi.ts b/packages/cadl-ranch-specs/http/parameters/basic/mockapi.ts index b3515974f..9f3f4d32f 100644 --- a/packages/cadl-ranch-specs/http/parameters/basic/mockapi.ts +++ b/packages/cadl-ranch-specs/http/parameters/basic/mockapi.ts @@ -1,18 +1,28 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Parameters_Basic_ExplicitBody_simple = passOnSuccess( - mockapi.put("/parameters/basic/explicit-body/simple", (req) => { - req.expect.bodyEquals({ name: "foo" }); - return { status: 204 }; - }), -); +function createServerTests(uri: string) { + return passOnSuccess({ + uri, + method: "put", + request: { + body: { + name: "foo", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals({ name: "foo" }); + return { status: 204 }; + }, + kind: "MockApiDefinition", + }); +} -Scenarios.Parameters_Basic_ImplicitBody_simple = passOnSuccess( - mockapi.put("/parameters/basic/implicit-body/simple", (req) => { - req.expect.bodyEquals({ name: "foo" }); - return { status: 204 }; - }), -); +Scenarios.Parameters_Basic_ExplicitBody_simple = createServerTests("/parameters/basic/explicit-body/simple"); + +Scenarios.Parameters_Basic_ImplicitBody_simple = createServerTests("/parameters/basic/implicit-body/simple"); diff --git a/packages/cadl-ranch-specs/http/parameters/body-optionality/mockapi.ts b/packages/cadl-ranch-specs/http/parameters/body-optionality/mockapi.ts index 3918943cb..f81e9a930 100644 --- a/packages/cadl-ranch-specs/http/parameters/body-optionality/mockapi.ts +++ b/packages/cadl-ranch-specs/http/parameters/body-optionality/mockapi.ts @@ -1,29 +1,72 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; +function createServerTests(uri: string, data: any) { + return passOnSuccess({ + uri, + method: "post", + request: { + body: data, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals({ name: "foo" }); + return { status: 204 }; + }, + kind: "MockApiDefinition", + }); +} -Scenarios.Parameters_BodyOptionality_requiredExplicit = passOnSuccess( - mockapi.post("/parameters/body-optionality/required-explicit", (req) => { - req.expect.bodyEquals({ name: "foo" }); - return { status: 204 }; - }), +Scenarios.Parameters_BodyOptionality_requiredExplicit = createServerTests( + "/parameters/body-optionality/required-explicit", + { + name: "foo", + }, ); Scenarios.Parameters_BodyOptionality_OptionalExplicit = passOnSuccess([ - mockapi.post("/parameters/body-optionality/optional-explicit/set", (req) => { - req.expect.bodyEquals({ name: "foo" }); - return { status: 204 }; - }), - mockapi.post("/parameters/body-optionality/optional-explicit/omit", (req) => { - req.expect.rawBodyEquals(undefined); - return { status: 204 }; - }), + { + uri: "/parameters/body-optionality/optional-explicit/set", + method: "post", + request: { + body: { + name: "foo", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals({ name: "foo" }); + return { status: 204 }; + }, + kind: "MockApiDefinition", + }, + { + uri: "/parameters/body-optionality/optional-explicit/omit", + method: "post", + request: { + body: { + name: "foo", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals({ name: "foo" }); + return { status: 204 }; + }, + kind: "MockApiDefinition", + }, ]); -Scenarios.Parameters_BodyOptionality_requiredImplicit = passOnSuccess( - mockapi.post("/parameters/body-optionality/required-implicit", (req) => { - req.expect.bodyEquals({ name: "foo" }); - return { status: 204 }; - }), +Scenarios.Parameters_BodyOptionality_requiredImplicit = createServerTests( + "/parameters/body-optionality/required-implicit", + { + name: "foo", + }, ); diff --git a/packages/cadl-ranch-specs/http/parameters/collection-format/mockapi.ts b/packages/cadl-ranch-specs/http/parameters/collection-format/mockapi.ts index 37212a6fd..888d86e15 100644 --- a/packages/cadl-ranch-specs/http/parameters/collection-format/mockapi.ts +++ b/packages/cadl-ranch-specs/http/parameters/collection-format/mockapi.ts @@ -1,58 +1,114 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { MockRequest, passOnSuccess } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Parameters_CollectionFormat_Query_multi = passOnSuccess( - mockapi.get("/parameters/collection-format/query/multi", (req) => { +const colors = ["blue", "red", "green"]; + +Scenarios.Parameters_CollectionFormat_Query_multi = passOnSuccess({ + uri: `/parameters/collection-format/query/multi`, + method: "get", + request: { + params: { colors: ["blue", "red", "green"] }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("colors", ["blue", "red", "green"], "multi"); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_CollectionFormat_Query_csv = passOnSuccess( - mockapi.get("/parameters/collection-format/query/csv", (req) => { +Scenarios.Parameters_CollectionFormat_Query_csv = passOnSuccess({ + uri: `/parameters/collection-format/query/csv`, + method: "get", + request: { + params: { colors: colors.join(",") }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("colors", ["blue", "red", "green"], "csv"); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_CollectionFormat_Query_ssv = passOnSuccess( - mockapi.get("/parameters/collection-format/query/ssv", (req) => { +Scenarios.Parameters_CollectionFormat_Query_ssv = passOnSuccess({ + uri: `/parameters/collection-format/query/ssv`, + method: "get", + request: { + params: { colors: colors.join(" ") }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("colors", ["blue", "red", "green"], "ssv"); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_CollectionFormat_Query_tsv = passOnSuccess( - mockapi.get("/parameters/collection-format/query/tsv", (req) => { +Scenarios.Parameters_CollectionFormat_Query_tsv = passOnSuccess({ + uri: `/parameters/collection-format/query/tsv`, + method: "get", + request: { + params: { colors: colors.join("\t") }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("colors", ["blue", "red", "green"], "tsv"); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_CollectionFormat_Query_pipes = passOnSuccess( - mockapi.get("/parameters/collection-format/query/pipes", (req) => { +Scenarios.Parameters_CollectionFormat_Query_pipes = passOnSuccess({ + uri: `/parameters/collection-format/query/pipes`, + method: "get", + request: { + params: { colors: colors.join("|") }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("colors", ["blue", "red", "green"], "pipes"); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_CollectionFormat_Header_csv = passOnSuccess( - mockapi.get("/parameters/collection-format/header/csv", (req) => { +Scenarios.Parameters_CollectionFormat_Header_csv = passOnSuccess({ + uri: `/parameters/collection-format/header/csv`, + method: "get", + request: { + headers: { colors: colors.join(",") }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("colors", "blue,red,green"); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/parameters/spread/mockapi.ts b/packages/cadl-ranch-specs/http/parameters/spread/mockapi.ts index e3f64a4c6..23851adaf 100644 --- a/packages/cadl-ranch-specs/http/parameters/spread/mockapi.ts +++ b/packages/cadl-ranch-specs/http/parameters/spread/mockapi.ts @@ -1,62 +1,164 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Parameters_Spread_Model_spreadAsRequestBody = passOnSuccess( - mockapi.put("/parameters/spread/model/request-body", (req) => { +Scenarios.Parameters_Spread_Model_spreadAsRequestBody = passOnSuccess({ + uri: `/parameters/spread/model/request-body`, + method: "put", + request: { + body: { + name: "foo", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ name: "foo" }); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_Spread_Model_spreadCompositeRequestOnlyWithBody = passOnSuccess( - mockapi.put("/parameters/spread/model/composite-request-only-with-body", (req) => { +Scenarios.Parameters_Spread_Model_spreadCompositeRequestOnlyWithBody = passOnSuccess({ + uri: `/parameters/spread/model/composite-request-only-with-body`, + method: "put", + request: { + body: { + name: "foo", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ name: "foo" }); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_Spread_Model_spreadCompositeRequestWithoutBody = passOnSuccess( - mockapi.put("/parameters/spread/model/composite-request-without-body/foo", (req) => { +Scenarios.Parameters_Spread_Model_spreadCompositeRequestWithoutBody = passOnSuccess({ + uri: `/parameters/spread/model/composite-request-without-body/foo`, + method: "put", + request: { + headers: { + "test-header": "bar", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("test-header", "bar"); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_Spread_Model_spreadCompositeRequest = passOnSuccess( - mockapi.put("/parameters/spread/model/composite-request/foo", (req) => { +Scenarios.Parameters_Spread_Model_spreadCompositeRequest = passOnSuccess({ + uri: `/parameters/spread/model/composite-request/foo`, + method: "put", + request: { + body: { + name: "foo", + }, + headers: { + "test-header": "bar", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("test-header", "bar"); req.expect.bodyEquals({ name: "foo" }); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_Spread_Model_spreadCompositeRequestMix = passOnSuccess( - mockapi.put("/parameters/spread/model/composite-request-mix/foo", (req) => { +Scenarios.Parameters_Spread_Model_spreadCompositeRequestMix = passOnSuccess({ + uri: `/parameters/spread/model/composite-request-mix/foo`, + method: "put", + request: { + body: { + prop: "foo", + }, + headers: { + "test-header": "bar", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("test-header", "bar"); req.expect.bodyEquals({ prop: "foo" }); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_Spread_Alias_spreadAsRequestBody = passOnSuccess( - mockapi.put("/parameters/spread/alias/request-body", (req) => { +Scenarios.Parameters_Spread_Alias_spreadAsRequestBody = passOnSuccess({ + uri: `/parameters/spread/alias/request-body`, + method: "put", + request: { + body: { + name: "foo", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ name: "foo" }); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_Spread_Alias_spreadAsRequestParameter = passOnSuccess( - mockapi.put("/parameters/spread/alias/request-parameter/1", (req) => { +Scenarios.Parameters_Spread_Alias_spreadAsRequestParameter = passOnSuccess({ + uri: `/parameters/spread/alias/request-parameter/1`, + method: "put", + request: { + body: { + name: "foo", + }, + headers: { + "x-ms-test-header": "bar", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("x-ms-test-header", "bar"); req.expect.bodyEquals({ name: "foo" }); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_Spread_Alias_spreadWithMultipleParameters = passOnSuccess( - mockapi.put("/parameters/spread/alias/multiple-parameters/1", (req) => { +Scenarios.Parameters_Spread_Alias_spreadWithMultipleParameters = passOnSuccess({ + uri: `/parameters/spread/alias/multiple-parameters/1`, + method: "put", + request: { + body: { + requiredString: "foo", + optionalInt: 1, + requiredIntList: [1, 2], + optionalStringList: ["foo", "bar"], + }, + headers: { + "x-ms-test-header": "bar", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("x-ms-test-header", "bar"); req.expect.bodyEquals({ requiredString: "foo", @@ -65,21 +167,51 @@ Scenarios.Parameters_Spread_Alias_spreadWithMultipleParameters = passOnSuccess( optionalStringList: ["foo", "bar"], }); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_Spread_Alias_spreadParameterWithInnerModel = passOnSuccess( - mockapi.post("/parameters/spread/alias/inner-model-parameter/1", (req) => { +Scenarios.Parameters_Spread_Alias_spreadParameterWithInnerModel = passOnSuccess({ + uri: `/parameters/spread/alias/inner-model-parameter/1`, + method: "post", + request: { + body: { + name: "foo", + }, + headers: { + "x-ms-test-header": "bar", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("x-ms-test-header", "bar"); req.expect.bodyEquals({ name: "foo" }); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Parameters_Spread_Alias_spreadParameterWithInnerAlias = passOnSuccess( - mockapi.post("/parameters/spread/alias/inner-alias-parameter/1", (req) => { +Scenarios.Parameters_Spread_Alias_spreadParameterWithInnerAlias = passOnSuccess({ + uri: `/parameters/spread/alias/inner-alias-parameter/1`, + method: "post", + request: { + body: { + name: "foo", + age: 1, + }, + headers: { + "x-ms-test-header": "bar", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("x-ms-test-header", "bar"); req.expect.bodyEquals({ name: "foo", age: 1 }); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/payload/content-negotiation/mockapi.ts b/packages/cadl-ranch-specs/http/payload/content-negotiation/mockapi.ts index 4e039c032..eb07595cd 100644 --- a/packages/cadl-ranch-specs/http/payload/content-negotiation/mockapi.ts +++ b/packages/cadl-ranch-specs/http/payload/content-negotiation/mockapi.ts @@ -1,63 +1,172 @@ -import { mockapi, ValidationError, json, withKeys } from "@azure-tools/cadl-ranch-api"; +import { ValidationError, json, withServiceKeys, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; import { pngFile, jpgFile } from "../../helper.js"; export const Scenarios: Record = {}; -Scenarios.Payload_ContentNegotiation_SameBody = withKeys(["image/png", "image/jpeg"]).pass( - mockapi.get("/content-negotiation/same-body", (req) => { - switch (req.headers["accept"]) { - case "image/png": - return { - pass: "image/png", - status: 200, - body: { - contentType: "image/png", - rawContent: pngFile, - }, - } as const; - case "image/jpeg": - return { - pass: "image/jpeg", +function sameBodyHandler(req: MockRequest) { + switch (req.headers["accept"]) { + case "image/png": + return { + pass: "image/png", + status: 200, + body: { + contentType: "image/png", + rawContent: pngFile, + }, + } as const; + case "image/jpeg": + return { + pass: "image/jpeg", - status: 200, - body: { - contentType: "image/jpeg", - rawContent: jpgFile, - }, - } as const; - default: - throw new ValidationError("Unsupported Accept header", `"image/png" | "image/jpeg"`, req.headers["accept"]); - } - }), -); + status: 200, + body: { + contentType: "image/jpeg", + rawContent: jpgFile, + }, + } as const; + default: + throw new ValidationError("Unsupported Accept header", `"image/png" | "image/jpeg"`, req.headers["accept"]); + } +} -Scenarios.Payload_ContentNegotiation_DifferentBody = withKeys(["image/png", "application/json"]).pass( - mockapi.get("/content-negotiation/different-body", (req) => { - switch (req.headers["accept"]) { - case "image/png": - return { - pass: "image/png", - status: 200, - body: { - contentType: "image/png", - rawContent: pngFile, - }, - } as const; - case "application/json": - return { - pass: "application/json", - status: 200, - body: json({ - content: pngFile.toString("base64"), - }), - } as const; - default: - throw new ValidationError( - "Unsupported Accept header", - `"image/png" | "application/json"`, - req.headers["accept"], - ); - } - }), -); +function differentBodyHandler(req: MockRequest) { + switch (req.headers["accept"]) { + case "image/png": + return { + pass: "image/png", + status: 200, + body: { + contentType: "image/png", + rawContent: pngFile, + }, + } as const; + case "application/json": + return { + pass: "application/json", + status: 200, + body: json({ + content: pngFile.toString("base64"), + }), + } as const; + default: + throw new ValidationError("Unsupported Accept header", `"image/png" | "application/json"`, req.headers["accept"]); + } +} + +Scenarios.Payload_ContentNegotiation_SameBody = withServiceKeys(["image/png", "image/jpeg"]).pass([ + { + uri: "/content-negotiation/same-body", + method: "get", + request: { + headers: { + accept: "image/png", + }, + }, + response: { + body: { + contentType: "image/png", + rawContent: pngFile, + }, + status: 200, + }, + handler: (req) => sameBodyHandler(req), + kind: "MockApiDefinition", + }, + { + uri: "/content-negotiation/same-body", + method: "get", + request: { + headers: { + accept: "image/jpeg", + }, + }, + response: { + body: { + contentType: "image/jpeg", + rawContent: jpgFile, + }, + status: 200, + }, + handler: (req) => sameBodyHandler(req), + kind: "MockApiDefinition", + }, + { + uri: "/content-negotiation/same-body", + method: "get", + request: { + status: 400, + headers: { + accept: "wrongAccept", + }, + }, + response: { + status: 400, + body: json({ + message: "Unsupported Accept header", + expected: `"image/png" | "image/jpeg"`, + actual: "wrongAccept", + }), + }, + handler: sameBodyHandler, + kind: "MockApiDefinition", + }, +]); + +Scenarios.Payload_ContentNegotiation_DifferentBody = withServiceKeys(["image/png", "application/json"]).pass([ + { + uri: "/content-negotiation/different-body", + method: "get", + request: { + headers: { + accept: "image/png", + }, + }, + response: { + status: 200, + body: { + contentType: "image/png", + rawContent: pngFile, + }, + }, + handler: differentBodyHandler, + kind: "MockApiDefinition", + }, + { + uri: "/content-negotiation/different-body", + method: "get", + request: { + headers: { + accept: "application/json", + }, + }, + response: { + status: 200, + body: json({ + content: pngFile.toString("base64"), + }), + }, + handler: differentBodyHandler, + kind: "MockApiDefinition", + }, + { + uri: "/content-negotiation/different-body", + method: "get", + request: { + status: 400, + headers: { + accept: "wrongAccept", + }, + }, + response: { + status: 400, + body: json({ + message: "Unsupported Accept header", + expected: `"image/png" | "application/json"`, + actual: "wrongAccept", + }), + }, + handler: differentBodyHandler, + kind: "MockApiDefinition", + }, +]); diff --git a/packages/cadl-ranch-specs/http/payload/json-merge-patch/mockapi.ts b/packages/cadl-ranch-specs/http/payload/json-merge-patch/mockapi.ts index 849baa9a1..00d233b12 100644 --- a/packages/cadl-ranch-specs/http/payload/json-merge-patch/mockapi.ts +++ b/packages/cadl-ranch-specs/http/payload/json-merge-patch/mockapi.ts @@ -1,83 +1,144 @@ -import { passOnSuccess, ScenarioMockApi, mockapi, json, MockApi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ScenarioMockApi, json, MockRequest } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -function createMockApis(route: string, isUpdateRequest: boolean): MockApi { - const url = `/json-merge-patch/${route}`; - const expectedCreateBody = { - name: "Madge", - description: "desc", - map: { - key: { - name: "InnerMadge", - description: "innerDesc", - }, +export const expectedCreateBody = { + name: "Madge", + description: "desc", + map: { + key: { + name: "InnerMadge", + description: "innerDesc", }, - array: [ - { - name: "InnerMadge", - description: "innerDesc", - }, - ], - intValue: 1, - floatValue: 1.1, - innerModel: { + }, + array: [ + { name: "InnerMadge", description: "innerDesc", }, - intArray: [1, 2, 3], - }; - const expectedUpdateBody = { - name: "Madge", - description: null, - map: { - key: { - name: "InnerMadge", - description: null, - }, - key2: null, + ], + intValue: 1, + floatValue: 1.1, + innerModel: { + name: "InnerMadge", + description: "innerDesc", + }, + intArray: [1, 2, 3], +}; + +export const expectedUpdateBody = { + name: "Madge", + description: null, + map: { + key: { + name: "InnerMadge", + description: null, }, - array: null, - intValue: null, - floatValue: null, - innerModel: null, - intArray: null, - }; - if (isUpdateRequest) { - return mockapi.patch(url, (req) => { - req.expect.deepEqual(req.body.description, expectedUpdateBody.description); - req.expect.deepEqual(req.body.map.key.description, expectedUpdateBody.map.key.description); - req.expect.deepEqual(req.body.map.key2, expectedUpdateBody.map.key2); - req.expect.deepEqual(req.body.array, expectedUpdateBody.array); - req.expect.deepEqual(req.body.intValue, expectedUpdateBody.intValue); - req.expect.deepEqual(req.body.floatValue, expectedUpdateBody.floatValue); - req.expect.deepEqual(req.body.innerModel, expectedUpdateBody.innerModel); - req.expect.deepEqual(req.body.intArray, expectedUpdateBody.intArray); - return { - status: 200, - body: json({ - name: "Madge", - map: { - key: { - name: "InnerMadge", - }, - }, - }), - }; - }); - } else { - return mockapi.put(url, (req) => { - req.expect.coercedBodyEquals(expectedCreateBody); - return { - status: 200, - body: json(expectedCreateBody), - }; - }); - } -} + key2: null, + }, + array: null, + intValue: null, + floatValue: null, + innerModel: null, + intArray: null, +}; -Scenarios.Payload_JsonMergePatch_createResource = passOnSuccess(createMockApis("create/resource", false)); -Scenarios.Payload_JsonMergePatch_updateResource = passOnSuccess(createMockApis("update/resource", true)); -Scenarios.Payload_JsonMergePatch_updateOptionalResource = passOnSuccess( - createMockApis("update/resource/optional", true), -); +Scenarios.Payload_JsonMergePatch_createResource = passOnSuccess({ + uri: "/json-merge-patch/create/resource", + method: "put", + request: { + body: expectedCreateBody, + }, + response: { + status: 200, + body: json(expectedCreateBody), + }, + handler: (req: MockRequest) => { + req.expect.coercedBodyEquals(expectedCreateBody); + return { + status: 200, + body: json(expectedCreateBody), + }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Payload_JsonMergePatch_updateResource = passOnSuccess({ + uri: "/json-merge-patch/update/resource", + method: "patch", + request: { + body: expectedUpdateBody, + }, + response: { + status: 200, + body: json({ + name: "Madge", + map: { + key: { + name: "InnerMadge", + }, + }, + }), + }, + handler: (req: MockRequest) => { + req.expect.deepEqual(req.body.description, expectedUpdateBody.description); + req.expect.deepEqual(req.body.map.key.description, expectedUpdateBody.map.key.description); + req.expect.deepEqual(req.body.map.key2, expectedUpdateBody.map.key2); + req.expect.deepEqual(req.body.array, expectedUpdateBody.array); + req.expect.deepEqual(req.body.intValue, expectedUpdateBody.intValue); + req.expect.deepEqual(req.body.floatValue, expectedUpdateBody.floatValue); + req.expect.deepEqual(req.body.innerModel, expectedUpdateBody.innerModel); + req.expect.deepEqual(req.body.intArray, expectedUpdateBody.intArray); + return { + status: 200, + body: json({ + name: "Madge", + map: { + key: { + name: "InnerMadge", + }, + }, + }), + }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Payload_JsonMergePatch_updateOptionalResource = passOnSuccess({ + uri: "/json-merge-patch/update/resource/optional", + method: "patch", + request: { + body: expectedUpdateBody, + }, + response: { + status: 200, + body: json({ + name: "Madge", + map: { + key: { + name: "InnerMadge", + }, + }, + }), + }, + handler: (req: MockRequest) => { + req.expect.deepEqual(req.body.description, expectedUpdateBody.description); + req.expect.deepEqual(req.body.map.key.description, expectedUpdateBody.map.key.description); + req.expect.deepEqual(req.body.map.key2, expectedUpdateBody.map.key2); + req.expect.deepEqual(req.body.array, expectedUpdateBody.array); + req.expect.deepEqual(req.body.intValue, expectedUpdateBody.intValue); + req.expect.deepEqual(req.body.floatValue, expectedUpdateBody.floatValue); + req.expect.deepEqual(req.body.innerModel, expectedUpdateBody.innerModel); + req.expect.deepEqual(req.body.intArray, expectedUpdateBody.intArray); + return { + status: 200, + body: json({ + name: "Madge", + map: { + key: { + name: "InnerMadge", + }, + }, + }), + }; + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/payload/media-type/mockapi.ts b/packages/cadl-ranch-specs/http/payload/media-type/mockapi.ts index a6ae064b5..43decd951 100644 --- a/packages/cadl-ranch-specs/http/payload/media-type/mockapi.ts +++ b/packages/cadl-ranch-specs/http/payload/media-type/mockapi.ts @@ -1,41 +1,89 @@ -import { json, mockapi, passOnSuccess } from "@azure-tools/cadl-ranch-api"; +import { json, MockRequest, passOnSuccess } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Payload_MediaType_StringBody_sendAsText = passOnSuccess( - mockapi.post("/payload/media-type/string-body/sendAsText", (req) => { +Scenarios.Payload_MediaType_StringBody_sendAsText = passOnSuccess({ + uri: "/payload/media-type/string-body/sendAsText", + method: "post", + request: { + body: "{cat}", + headers: { + "Content-Type": "text/plain", + }, + }, + response: { + status: 200, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("content-type", "text/plain"); req.expect.bodyEquals("{cat}"); return { status: 200 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Payload_MediaType_StringBody_getAsText = passOnSuccess( - mockapi.get("/payload/media-type/string-body/getAsText", (req) => { +Scenarios.Payload_MediaType_StringBody_getAsText = passOnSuccess({ + uri: "/payload/media-type/string-body/getAsText", + method: "get", + request: { + headers: { + accept: "text/plain", + }, + }, + response: { + status: 200, + body: { rawContent: "{cat}", contentType: "text/plain" }, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("accept", "text/plain"); return { status: 200, body: { rawContent: "{cat}", contentType: "text/plain" }, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Payload_MediaType_StringBody_sendAsJson = passOnSuccess( - mockapi.post("/payload/media-type/string-body/sendAsJson", (req) => { +Scenarios.Payload_MediaType_StringBody_sendAsJson = passOnSuccess({ + uri: "/payload/media-type/string-body/sendAsJson", + method: "post", + request: { + body: "foo", + headers: { + "Content-Type": "application/json", + }, + }, + response: { + status: 200, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("content-type", "application/json"); req.expect.bodyEquals("foo"); return { status: 200 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Payload_MediaType_StringBody_getAsJson = passOnSuccess( - mockapi.get("/payload/media-type/string-body/getAsJson", (req) => { +Scenarios.Payload_MediaType_StringBody_getAsJson = passOnSuccess({ + uri: "/payload/media-type/string-body/getAsJson", + method: "get", + request: { + headers: { + accept: "application/json", + }, + }, + response: { + status: 200, + body: json("foo"), + }, + handler: (req: MockRequest) => { req.expect.containsHeader("accept", "application/json"); return { status: 200, body: json("foo"), contentType: "application/json", }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/payload/multipart/mockapi.ts b/packages/cadl-ranch-specs/http/payload/multipart/mockapi.ts index 82af82fd1..e4bd3e46e 100644 --- a/packages/cadl-ranch-specs/http/payload/multipart/mockapi.ts +++ b/packages/cadl-ranch-specs/http/payload/multipart/mockapi.ts @@ -1,11 +1,9 @@ import { passOnSuccess, ScenarioMockApi, - mockapi, ValidationError, MockRequest, - MockApi, - withKeys, + withServiceKeys, } from "@azure-tools/cadl-ranch-api"; import { jpgFile, pngFile } from "../../helper.js"; @@ -108,87 +106,242 @@ function checkPictures(req: MockRequest) { function checkFloat(req: MockRequest) { req.expect.deepEqual(parseFloat(req.body.temperature), 0.5); } -function createMockApis(route: string, checkList: ((param: MockRequest) => void)[]): MockApi { - const url = `/multipart/form-data/${route}`; - return mockapi.post(url, (req) => { - for (const callback of checkList) { - callback(req); - } - return { status: 204 }; - }); -} -Scenarios.Payload_MultiPart_FormData_basic = passOnSuccess(createMockApis("mixed-parts", [checkId, checkProfileImage])); - -Scenarios.Payload_MultiPart_FormData_fileArrayAndBasic = passOnSuccess( - createMockApis("complex-parts", [checkId, checkAddress, checkAllFiles]), -); - -Scenarios.Payload_MultiPart_FormData_jsonPart = passOnSuccess( - createMockApis("json-part", [checkAddress, checkProfileImage]), -); - -Scenarios.Payload_MultiPart_FormData_binaryArrayParts = passOnSuccess( - createMockApis("binary-array-parts", [checkId, checkPictures]), -); - -Scenarios.Payload_MultiPart_FormData_multiBinaryParts = withKeys(["profileImage", "profileImage,picture"]).pass( - mockapi.post("/multipart/form-data/multi-binary-parts", (req) => { - if (req.files instanceof Array) { - switch (req.files.length) { - case 1: - checkJpgFile(req, req.files[0]); - return { pass: "profileImage", status: 204 } as const; - case 2: - let profileImage = false; - let picture = false; - for (const file of req.files) { - if (file.fieldname === "profileImage") { - checkJpgFile(req, file); - profileImage = true; - } else if (file.fieldname === "picture") { - checkPngFile(req, file, "picture"); - picture = true; - } else { - throw new ValidationError("unexpected fieldname", "profileImage or picture", file.fieldname); - } - } - if (!profileImage) { - throw new ValidationError("No profileImage found", "jpg file is expected", req.body); - } else if (!picture) { - throw new ValidationError("No picture found", "png file are expected", req.body); +const files = [ + { + fieldname: "profileImage", + originalname: "image.jpg", + buffer: jpgFile, + mimetype: "application/octet-stream", + }, + { + fieldname: "pictures", + originalname: "image.png", + buffer: pngFile, + mimetype: "application/octet-stream", + }, +]; +function createHandler(req: MockRequest, checkList: ((req: MockRequest) => void)[]) { + for (const callback of checkList) { + callback(req); + } + return { status: 204 }; +} +function createMultiBinaryPartsHandler(req: MockRequest) { + if (req.files instanceof Array) { + switch (req.files.length) { + case 1: + checkJpgFile(req, req.files[0]); + return { pass: "profileImage", status: 204 } as const; + case 2: + let profileImage = false; + let picture = false; + for (const file of req.files) { + if (file.fieldname === "profileImage") { + checkJpgFile(req, file); + profileImage = true; + } else if (file.fieldname === "picture") { + checkPngFile(req, file, "picture"); + picture = true; + } else { + throw new ValidationError("unexpected fieldname", "profileImage or picture", file.fieldname); } - return { pass: "profileImage,picture", status: 204 } as const; - default: - throw new ValidationError("number of files is incorrect", "1 or 2 files are expected", req.body); - } - } else { - throw new ValidationError("Can't parse files from request", "jpg/png files are expected", req.body); + } + if (!profileImage) { + throw new ValidationError("No profileImage found", "jpg file is expected", req.body); + } else if (!picture) { + throw new ValidationError("No picture found", "png file are expected", req.body); + } + return { pass: "profileImage,picture", status: 204 } as const; + default: + throw new ValidationError("number of files is incorrect", "1 or 2 files are expected", req.body); } - }), -); - -Scenarios.Payload_MultiPart_FormData_checkFileNameAndContentType = passOnSuccess( - createMockApis("check-filename-and-content-type", [checkId, checkFileNameAndContentType]), -); - -Scenarios.Payload_MultiPart_FormData_anonymousModel = passOnSuccess( - createMockApis("anonymous-model", [checkProfileImage]), -); - -Scenarios.Payload_MultiPart_FormData_HttpParts_ContentType_imageJpegContentType = passOnSuccess( - createMockApis("check-filename-and-specific-content-type-with-httppart", [checkFileNameAndContentType]), -); - -Scenarios.Payload_MultiPart_FormData_HttpParts_ContentType_requiredContentType = passOnSuccess( - createMockApis("check-filename-and-required-content-type-with-httppart", [checkProfileImage]), -); -Scenarios.Payload_MultiPart_FormData_HttpParts_ContentType_optionalContentType = passOnSuccess( - createMockApis("file-with-http-part-optional-content-type", [checkOptionalContentType]), -); -Scenarios.Payload_MultiPart_FormData_HttpParts_jsonArrayAndFileArray = passOnSuccess( - createMockApis("complex-parts-with-httppart", [checkId, checkAddress, checkPreviousAddresses, checkAllFiles]), -); -Scenarios.Payload_MultiPart_FormData_HttpParts_NonString_float = passOnSuccess( - createMockApis("non-string-float", [checkFloat]), -); + } else { + throw new ValidationError("Can't parse files from request", "jpg/png files are expected", req.body); + } +} +Scenarios.Payload_MultiPart_FormData_basic = passOnSuccess({ + uri: "/multipart/form-data/mixed-parts", + method: "post", + request: { + headers: { + "Content-Type": "multipart/form-data", + }, + body: { id: 123 }, + files: [files[0]], + }, + response: { status: 204 }, + handler: (req: MockRequest) => createHandler(req, [checkId, checkProfileImage]), + kind: "MockApiDefinition", +}); + +Scenarios.Payload_MultiPart_FormData_fileArrayAndBasic = passOnSuccess({ + uri: "/multipart/form-data/complex-parts", + method: "post", + request: { + headers: { + "Content-Type": "multipart/form-data", + }, + body: { id: 123, address: { city: "X" } }, + files: [files[0], files[1], files[1]], + }, + response: { status: 204 }, + handler: (req: MockRequest) => createHandler(req, [checkId, checkAddress, checkAllFiles]), + kind: "MockApiDefinition", +}); + +Scenarios.Payload_MultiPart_FormData_jsonPart = passOnSuccess({ + uri: "/multipart/form-data/json-part", + method: "post", + request: { + headers: { + "Content-Type": "multipart/form-data", + }, + body: { address: { city: "X" } }, + files: [files[0]], + }, + response: { status: 204 }, + handler: (req: MockRequest) => createHandler(req, [checkAddress, checkProfileImage]), + kind: "MockApiDefinition", +}); + +Scenarios.Payload_MultiPart_FormData_binaryArrayParts = passOnSuccess({ + uri: "/multipart/form-data/binary-array-parts", + method: "post", + request: { + headers: { + "Content-Type": "multipart/form-data", + }, + body: { id: 123 }, + files: [files[1], files[1]], + }, + response: { status: 204 }, + handler: (req: MockRequest) => createHandler(req, [checkId, checkPictures]), + kind: "MockApiDefinition", +}); + +Scenarios.Payload_MultiPart_FormData_multiBinaryParts = withServiceKeys(["profileImage", "profileImage,picture"]).pass([ + { + uri: "/multipart/form-data/multi-binary-parts", + method: "post", + request: { + headers: { + "Content-Type": "multipart/form-data", + }, + files: [files[0]], + }, + response: { status: 204 }, + handler: createMultiBinaryPartsHandler, + kind: "MockApiDefinition", + }, + { + uri: "/multipart/form-data/multi-binary-parts", + method: "post", + request: { + headers: { + "Content-Type": "multipart/form-data", + }, + files: [files[0], { ...files[1], fieldname: "picture" }], + }, + response: { status: 204 }, + handler: createMultiBinaryPartsHandler, + kind: "MockApiDefinition", + }, +]); + +Scenarios.Payload_MultiPart_FormData_checkFileNameAndContentType = passOnSuccess({ + uri: "/multipart/form-data/check-filename-and-content-type", + method: "post", + request: { + headers: { + "Content-Type": "multipart/form-data", + }, + body: { id: 123 }, + files: [{ ...files[0], mimetype: "image/jpg", originalname: "hello.jpg" }], + }, + response: { status: 204 }, + handler: (req: MockRequest) => createHandler(req, [checkId, checkFileNameAndContentType]), + kind: "MockApiDefinition", +}); + +Scenarios.Payload_MultiPart_FormData_anonymousModel = passOnSuccess({ + uri: "/multipart/form-data/anonymous-model", + method: "post", + request: { + headers: { + "Content-Type": "multipart/form-data", + }, + files: [files[0]], + }, + response: { status: 204 }, + handler: (req: MockRequest) => createHandler(req, [checkProfileImage]), + kind: "MockApiDefinition", +}); + +Scenarios.Payload_MultiPart_FormData_HttpParts_ContentType_imageJpegContentType = passOnSuccess({ + uri: "/multipart/form-data/check-filename-and-specific-content-type-with-httppart", + method: "post", + request: { + headers: { + "Content-Type": "multipart/form-data", + }, + files: [{ ...files[0], mimetype: "image/jpg", originalname: "hello.jpg" }], + }, + response: { status: 204 }, + handler: (req: MockRequest) => createHandler(req, [checkFileNameAndContentType]), + kind: "MockApiDefinition", +}); + +Scenarios.Payload_MultiPart_FormData_HttpParts_ContentType_requiredContentType = passOnSuccess({ + uri: "/multipart/form-data/check-filename-and-required-content-type-with-httppart", + method: "post", + request: { + headers: { + "Content-Type": "multipart/form-data", + }, + files: [files[0]], + }, + response: { status: 204 }, + handler: (req: MockRequest) => createHandler(req, [checkProfileImage]), + kind: "MockApiDefinition", +}); +Scenarios.Payload_MultiPart_FormData_HttpParts_ContentType_optionalContentType = passOnSuccess({ + uri: "/multipart/form-data/file-with-http-part-optional-content-type", + method: "post", + request: { + headers: { + "Content-Type": "multipart/form-data", + }, + files: [files[0]], + }, + response: { status: 204 }, + handler: (req: MockRequest) => createHandler(req, [checkOptionalContentType]), + kind: "MockApiDefinition", +}); +Scenarios.Payload_MultiPart_FormData_HttpParts_jsonArrayAndFileArray = passOnSuccess({ + uri: "/multipart/form-data/complex-parts-with-httppart", + method: "post", + request: { + headers: { + "Content-Type": "multipart/form-data", + }, + body: { id: 123, address: { city: "X" }, previousAddresses: [{ city: "Y" }, { city: "Z" }] }, + files: [files[0], files[1], files[1]], + }, + response: { status: 204 }, + handler: (req: MockRequest) => createHandler(req, [checkId, checkAddress, checkPreviousAddresses, checkAllFiles]), + kind: "MockApiDefinition", +}); +Scenarios.Payload_MultiPart_FormData_HttpParts_NonString_float = passOnSuccess({ + uri: "/multipart/form-data/non-string-float", + method: "post", + request: { + body: { temperature: 0.5 }, + headers: { + "Content-Type": "multipart/form-data", + }, + }, + response: { status: 204 }, + handler: (req: MockRequest) => createHandler(req, [checkFloat]), + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/payload/pageable/mockapi.ts b/packages/cadl-ranch-specs/http/payload/pageable/mockapi.ts index 1f6bcd4bc..de8260466 100644 --- a/packages/cadl-ranch-specs/http/payload/pageable/mockapi.ts +++ b/packages/cadl-ranch-specs/http/payload/pageable/mockapi.ts @@ -1,35 +1,68 @@ -import { mockapi, json, withKeys, ValidationError } from "@azure-tools/cadl-ranch-api"; +import { json, ValidationError, withServiceKeys, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Payload_Pageable_list = withKeys(["firstPage", "secondPage"]).pass( - mockapi.get("/payload/pageable", (req) => { - req.expect.containsQueryParam("maxpagesize", "3"); - const skipToken = req.query["skipToken"]; - if (skipToken === undefined) { - return { - pass: "firstPage", +function pageableHandler(req: MockRequest) { + req.expect.containsQueryParam("maxpagesize", "3"); + const skipToken = req.query["skipToken"]; + if (skipToken === undefined) { + return { + pass: "firstPage", + status: 200, + body: json({ + value: [{ name: "user5" }, { name: "user6" }, { name: "user7" }], + nextLink: `${req.baseUrl}/payload/pageable?skipToken=name-user7&maxpagesize=3`, + }), + } as const; + } else if (skipToken === "name-user7") { + return { + pass: "secondPage", + status: 200, + body: json({ value: [{ name: "user8" }] }), + } as const; + } else { + throw new ValidationError( + "Unsupported skipToken query parameter", + `Not provided for first page, "name-user7" for second page`, + req.query["skipToken"], + ); + } +} - status: 200, - body: json({ - value: [{ name: "user5" }, { name: "user6" }, { name: "user7" }], - nextLink: `${req.baseUrl}/payload/pageable?skipToken=name-user7&maxpagesize=3`, - }), - } as const; - } else if (skipToken === "name-user7") { - return { - pass: "secondPage", - - status: 200, - body: json({ value: [{ name: "user8" }] }), - } as const; - } else { - throw new ValidationError( - "Unsupported skipToken query parameter", - `Not provided for first page, "name-user7" for second page`, - req.query["skipToken"], - ); - } - }), -); +Scenarios.Payload_Pageable_list = withServiceKeys(["firstPage", "secondPage"]).pass([ + { + uri: "/payload/pageable", + method: "get", + request: { + params: { + maxpagesize: "3", + }, + }, + response: { + status: 200, + body: json({ + value: [{ name: "user5" }, { name: "user6" }, { name: "user7" }], + nextLink: `/payload/pageable?skipToken=name-user7&maxpagesize=3`, + }), + }, + handler: pageableHandler, + kind: "MockApiDefinition", + }, + { + uri: "/payload/pageable", + method: "get", + request: { + params: { + maxpagesize: "3", + skipToken: "name-user7", + }, + }, + response: { + status: 200, + body: json({ value: [{ name: "user8" }] }), + }, + handler: pageableHandler, + kind: "MockApiDefinition", + }, +]); diff --git a/packages/cadl-ranch-specs/http/payload/xml/mockapi.ts b/packages/cadl-ranch-specs/http/payload/xml/mockapi.ts index 8adfe0182..fb0cadaca 100644 --- a/packages/cadl-ranch-specs/http/payload/xml/mockapi.ts +++ b/packages/cadl-ranch-specs/http/payload/xml/mockapi.ts @@ -1,4 +1,4 @@ -import { passOnSuccess, mockapi, xml } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, xml, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; @@ -124,230 +124,113 @@ const modelWithEncodedNames = ` `; -Scenarios.Payload_Xml_SimpleModelValue_get = passOnSuccess( - mockapi.get("/payload/xml/simpleModel", (req) => { - return { - status: 200, - body: xml(simpleModel), - }; - }), -); - -Scenarios.Payload_Xml_SimpleModelValue_put = passOnSuccess( - mockapi.put("/payload/xml/simpleModel", (req) => { - req.expect.containsHeader("content-type", "application/xml"); - req.expect.xmlBodyEquals(simpleModel); - return { - status: 204, - }; - }), -); - -Scenarios.Payload_Xml_ModelWithSimpleArraysValue_get = passOnSuccess( - mockapi.get("/payload/xml/modelWithSimpleArrays", (req) => { - return { - status: 200, - body: xml(modelWithSimpleArrays), - }; - }), -); - -Scenarios.Payload_Xml_ModelWithSimpleArraysValue_put = passOnSuccess( - mockapi.put("/payload/xml/modelWithSimpleArrays", (req) => { - req.expect.containsHeader("content-type", "application/xml"); - req.expect.xmlBodyEquals(modelWithSimpleArrays); - return { - status: 204, - }; - }), -); - -Scenarios.Payload_Xml_ModelWithArrayOfModelValue_get = passOnSuccess( - mockapi.get("/payload/xml/modelWithArrayOfModel", (req) => { - return { - status: 200, - body: xml(modelWithArrayOfModel), - }; - }), -); - -Scenarios.Payload_Xml_ModelWithArrayOfModelValue_put = passOnSuccess( - mockapi.put("/payload/xml/modelWithArrayOfModel", (req) => { - req.expect.containsHeader("content-type", "application/xml"); - req.expect.xmlBodyEquals(modelWithArrayOfModel); - return { - status: 204, - }; - }), -); - -Scenarios.Payload_Xml_ModelWithOptionalFieldValue_get = passOnSuccess( - mockapi.get("/payload/xml/modelWithOptionalField", (req) => { - return { - status: 200, - body: xml(modelWithOptionalField), - }; - }), -); - -Scenarios.Payload_Xml_ModelWithOptionalFieldValue_put = passOnSuccess( - mockapi.put("/payload/xml/modelWithOptionalField", (req) => { - req.expect.containsHeader("content-type", "application/xml"); - req.expect.xmlBodyEquals(modelWithOptionalField); - return { - status: 204, - }; - }), -); - -Scenarios.Payload_Xml_ModelWithAttributesValue_get = passOnSuccess( - mockapi.get("/payload/xml/modelWithAttributes", (req) => { - return { - status: 200, - body: xml(modelWithAttributes), - }; - }), -); - -Scenarios.Payload_Xml_ModelWithAttributesValue_put = passOnSuccess( - mockapi.put("/payload/xml/modelWithAttributes", (req) => { - req.expect.containsHeader("content-type", "application/xml"); - req.expect.xmlBodyEquals(modelWithAttributes); - return { - status: 204, - }; - }), -); - -Scenarios.Payload_Xml_ModelWithUnwrappedArrayValue_get = passOnSuccess( - mockapi.get("/payload/xml/modelWithUnwrappedArray", (req) => { - return { - status: 200, - body: xml(modelWithUnwrappedArray), - }; - }), -); - -Scenarios.Payload_Xml_ModelWithUnwrappedArrayValue_put = passOnSuccess( - mockapi.put("/payload/xml/modelWithUnwrappedArray", (req) => { - req.expect.containsHeader("content-type", "application/xml"); - req.expect.xmlBodyEquals(modelWithUnwrappedArray); - return { - status: 204, - }; - }), -); - -Scenarios.Payload_Xml_ModelWithRenamedArraysValue_get = passOnSuccess( - mockapi.get("/payload/xml/modelWithRenamedArrays", (req) => { - return { - status: 200, - body: xml(modelWithRenamedArrays), - }; - }), -); - -Scenarios.Payload_Xml_ModelWithRenamedArraysValue_put = passOnSuccess( - mockapi.put("/payload/xml/modelWithRenamedArrays", (req) => { - req.expect.containsHeader("content-type", "application/xml"); - req.expect.xmlBodyEquals(modelWithRenamedArrays); - return { - status: 204, - }; - }), -); - -Scenarios.Payload_Xml_ModelWithRenamedFieldsValue_get = passOnSuccess( - mockapi.get("/payload/xml/modelWithRenamedFields", (req) => { - return { - status: 200, - body: xml(modelWithRenamedFields), - }; - }), -); - -Scenarios.Payload_Xml_ModelWithRenamedFieldsValue_put = passOnSuccess( - mockapi.put("/payload/xml/modelWithRenamedFields", (req) => { - req.expect.containsHeader("content-type", "application/xml"); - req.expect.xmlBodyEquals(modelWithRenamedFields); - return { - status: 204, - }; - }), -); - -Scenarios.Payload_Xml_ModelWithEmptyArrayValue_get = passOnSuccess( - mockapi.get("/payload/xml/modelWithEmptyArray", (req) => { - return { - status: 200, - body: xml(modelWithEmptyArray), - }; - }), -); - -Scenarios.Payload_Xml_ModelWithEmptyArrayValue_put = passOnSuccess( - mockapi.put("/payload/xml/modelWithEmptyArray", (req) => { - req.expect.containsHeader("content-type", "application/xml"); - req.expect.xmlBodyEquals(modelWithEmptyArray); - return { - status: 204, - }; - }), -); - -Scenarios.Payload_Xml_ModelWithTextValue_get = passOnSuccess( - mockapi.get("/payload/xml/modelWithText", (req) => { - return { - status: 200, - body: xml(modelWithText), - }; - }), -); - -Scenarios.Payload_Xml_ModelWithTextValue_put = passOnSuccess( - mockapi.put("/payload/xml/modelWithText", (req) => { - req.expect.containsHeader("content-type", "application/xml"); - req.expect.xmlBodyEquals(modelWithText); - return { - status: 204, - }; - }), -); - -Scenarios.Payload_Xml_ModelWithDictionaryValue_get = passOnSuccess( - mockapi.get("/payload/xml/modelWithDictionary", (req) => { - return { - status: 200, - body: xml(modelWithDictionary), - }; - }), -); - -Scenarios.Payload_Xml_ModelWithDictionaryValue_put = passOnSuccess( - mockapi.put("/payload/xml/modelWithDictionary", (req) => { - req.expect.containsHeader("content-type", "application/xml"); - req.expect.xmlBodyEquals(modelWithDictionary); - return { - status: 204, - }; - }), -); - -Scenarios.Payload_Xml_ModelWithEncodedNamesValue_get = passOnSuccess( - mockapi.get("/payload/xml/modelWithEncodedNames", (req) => { - return { - status: 200, - body: xml(modelWithEncodedNames), - }; - }), -); - -Scenarios.Payload_Xml_ModelWithEncodedNamesValue_put = passOnSuccess( - mockapi.put("/payload/xml/modelWithEncodedNames", (req) => { - req.expect.containsHeader("content-type", "application/xml"); - req.expect.xmlBodyEquals(modelWithEncodedNames); - return { - status: 204, - }; - }), -); +function createServerTests(uri: string, data?: any) { + return { + get: passOnSuccess({ + uri, + method: "get", + request: {}, + response: { + status: 200, + body: xml(data), + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: xml(data), + }; + }, + kind: "MockApiDefinition", + }), + put: passOnSuccess({ + uri, + method: "put", + request: { + body: data, + headers: { + "content-type": "application/xml", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsHeader("content-type", "application/xml"); + req.expect.xmlBodyEquals(data); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", + }), + }; +} + +const Payload_Xml_SimpleModel = createServerTests("/payload/xml/simpleModel", simpleModel); +Scenarios.Payload_Xml_SimpleModelValue_get = Payload_Xml_SimpleModel.get; +Scenarios.Payload_Xml_SimpleModelValue_put = Payload_Xml_SimpleModel.put; + +const Payload_Xml_ModelWithSimpleArrays = createServerTests( + "/payload/xml/modelWithSimpleArrays", + modelWithSimpleArrays, +); +Scenarios.Payload_Xml_ModelWithSimpleArraysValue_get = Payload_Xml_ModelWithSimpleArrays.get; +Scenarios.Payload_Xml_ModelWithSimpleArraysValue_put = Payload_Xml_ModelWithSimpleArrays.put; + +const Payload_Xml_ModelWithArrayOfModel = createServerTests( + "/payload/xml/modelWithArrayOfModel", + modelWithArrayOfModel, +); +Scenarios.Payload_Xml_ModelWithArrayOfModelValue_get = Payload_Xml_ModelWithArrayOfModel.get; +Scenarios.Payload_Xml_ModelWithArrayOfModelValue_put = Payload_Xml_ModelWithArrayOfModel.put; + +const Payload_Xml_ModelWithOptionalField = createServerTests( + "/payload/xml/modelWithOptionalField", + modelWithOptionalField, +); +Scenarios.Payload_Xml_ModelWithOptionalFieldValue_get = Payload_Xml_ModelWithOptionalField.get; +Scenarios.Payload_Xml_ModelWithOptionalFieldValue_put = Payload_Xml_ModelWithOptionalField.put; + +const Payload_Xml_ModelWithAttributes = createServerTests("/payload/xml/modelWithAttributes", modelWithAttributes); +Scenarios.Payload_Xml_ModelWithAttributesValue_get = Payload_Xml_ModelWithAttributes.get; +Scenarios.Payload_Xml_ModelWithAttributesValue_put = Payload_Xml_ModelWithAttributes.put; + +const Payload_Xml_ModelWithUnwrappedArray = createServerTests( + "/payload/xml/modelWithUnwrappedArray", + modelWithUnwrappedArray, +); +Scenarios.Payload_Xml_ModelWithUnwrappedArrayValue_get = Payload_Xml_ModelWithUnwrappedArray.get; +Scenarios.Payload_Xml_ModelWithUnwrappedArrayValue_put = Payload_Xml_ModelWithUnwrappedArray.put; + +const Payload_Xml_ModelWithRenamedArrays = createServerTests( + "/payload/xml/modelWithRenamedArrays", + modelWithRenamedArrays, +); +Scenarios.Payload_Xml_ModelWithRenamedArraysValue_get = Payload_Xml_ModelWithRenamedArrays.get; +Scenarios.Payload_Xml_ModelWithRenamedArraysValue_put = Payload_Xml_ModelWithRenamedArrays.put; + +const Payload_Xml_ModelWithRenamedFields = createServerTests( + "/payload/xml/modelWithRenamedFields", + modelWithRenamedFields, +); +Scenarios.Payload_Xml_ModelWithRenamedFieldsValue_get = Payload_Xml_ModelWithRenamedFields.get; +Scenarios.Payload_Xml_ModelWithRenamedFieldsValue_put = Payload_Xml_ModelWithRenamedFields.put; + +const Payload_Xml_ModelWithEmptyArray = createServerTests("/payload/xml/modelWithEmptyArray", modelWithEmptyArray); +Scenarios.Payload_Xml_ModelWithEmptyArrayValue_get = Payload_Xml_ModelWithEmptyArray.get; +Scenarios.Payload_Xml_ModelWithEmptyArrayValue_put = Payload_Xml_ModelWithEmptyArray.put; + +const Payload_Xml_ModelWithText = createServerTests("/payload/xml/modelWithText", modelWithText); +Scenarios.Payload_Xml_ModelWithTextValue_get = Payload_Xml_ModelWithText.get; +Scenarios.Payload_Xml_ModelWithTextValue_put = Payload_Xml_ModelWithText.put; + +const Payload_Xml_ModelWithDictionary = createServerTests("/payload/xml/modelWithDictionary", modelWithDictionary); +Scenarios.Payload_Xml_ModelWithDictionaryValue_get = Payload_Xml_ModelWithDictionary.get; +Scenarios.Payload_Xml_ModelWithDictionaryValue_put = Payload_Xml_ModelWithDictionary.put; + +const Payload_Xml_ModelWithEncodedNames = createServerTests( + "/payload/xml/modelWithEncodedNames", + modelWithEncodedNames, +); +Scenarios.Payload_Xml_ModelWithEncodedNamesValue_get = Payload_Xml_ModelWithEncodedNames.get; +Scenarios.Payload_Xml_ModelWithEncodedNamesValue_put = Payload_Xml_ModelWithEncodedNames.put; diff --git a/packages/cadl-ranch-specs/http/resiliency/srv-driven/mockapi.ts b/packages/cadl-ranch-specs/http/resiliency/srv-driven/mockapi.ts index 9e584afcd..df132f047 100644 --- a/packages/cadl-ranch-specs/http/resiliency/srv-driven/mockapi.ts +++ b/packages/cadl-ranch-specs/http/resiliency/srv-driven/mockapi.ts @@ -1,112 +1,270 @@ -import { - mockapi, - ValidationError, - MockApi, - MockRequest, - ScenarioMockApi, - passOnSuccess, -} from "@azure-tools/cadl-ranch-api"; -import { HttpVerb } from "@typespec/http"; +import { ValidationError, MockRequest, ScenarioMockApi, passOnSuccess } from "@azure-tools/cadl-ranch-api"; export const commonBase = "/resiliency/service-driven"; -type PassResiliencyOptions = { - path: string; - verb: HttpVerb; - commonValidate: (req: MockRequest) => void; - oldApiVersionNewClientValidate: (req: MockRequest) => void; - newApiVersionNewClientValidate: (req: MockRequest) => void; -}; +export const Scenarios: Record = {}; -function createResilientMockApi(options: PassResiliencyOptions): MockApi[] { - return [ - mockapi.request(options.verb, `${commonBase}/client[:]v1/service[:]v1/api-version[:]v1${options.path}`, (req) => { - options.commonValidate(req); +Scenarios.Resiliency_ServiceDriven_AddOptionalParam_fromNone = passOnSuccess([ + { + uri: `${commonBase}/client[:]v1/service[:]v1/api-version[:]v1/add-optional-param/from-none`, + method: "head", + request: {}, + response: { + status: 204, + }, + handler: (req: MockRequest) => { return { status: 204, }; - }), - mockapi.request(options.verb, `${commonBase}/client[:]v1/service[:]v2/api-version[:]v1${options.path}`, (req) => { - options.commonValidate(req); + }, + kind: "MockApiDefinition", + }, + { + uri: `${commonBase}/client[:]v1/service[:]v2/api-version[:]v1/add-optional-param/from-none`, + method: "head", + request: {}, + response: { + status: 204, + }, + handler: (req: MockRequest) => { return { status: 204, }; - }), - mockapi.request(options.verb, `${commonBase}/client[:]v2/service[:]v2/api-version[:]v1${options.path}`, (req) => { - options.commonValidate(req); - options.oldApiVersionNewClientValidate(req); + }, + kind: "MockApiDefinition", + }, + { + uri: `${commonBase}/client[:]v2/service[:]v2/api-version[:]v1/add-optional-param/from-none`, + method: "head", + request: {}, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + if (req.params["new-parameter"] !== undefined) { + throw new ValidationError("Did not expect 'new-parameter'", undefined, req.params["new-parameter"]); + } return { status: 204, }; - }), - mockapi.request(options.verb, `${commonBase}/client[:]v2/service[:]v2/api-version[:]v2${options.path}`, (req) => { - options.commonValidate(req); - options.newApiVersionNewClientValidate(req); + }, + kind: "MockApiDefinition", + }, + { + uri: `${commonBase}/client[:]v2/service[:]v2/api-version[:]v2/add-optional-param/from-none`, + method: "head", + request: { + params: { + "new-parameter": "new", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("new-parameter", "new"); return { status: 204, }; - }), - ]; -} - -function addOptionalParamOldApiVersionNewClientValidate(req: MockRequest): void { - if (req.params["new-parameter"] !== undefined) { - throw new ValidationError("Did not expect 'new-parameter'", undefined, req.params["new-parameter"]); - } -} - -function addOptionalParamNewApiVersionNewClientValidate(req: MockRequest): void { - req.expect.containsQueryParam("new-parameter", "new"); -} - -export const Scenarios: Record = {}; - -Scenarios.Resiliency_ServiceDriven_AddOptionalParam_fromNone = passOnSuccess( - createResilientMockApi({ - path: "/add-optional-param/from-none", - verb: "head", - commonValidate: function validate(req: MockRequest): void {}, - oldApiVersionNewClientValidate: addOptionalParamOldApiVersionNewClientValidate, - newApiVersionNewClientValidate: addOptionalParamNewApiVersionNewClientValidate, - }), -); + }, + kind: "MockApiDefinition", + }, +]); -Scenarios.Resiliency_ServiceDriven_AddOptionalParam_fromOneRequired = passOnSuccess( - createResilientMockApi({ - path: "/add-optional-param/from-one-required", - verb: "get", - commonValidate: function validate(req: MockRequest): void { +Scenarios.Resiliency_ServiceDriven_AddOptionalParam_fromOneRequired = passOnSuccess([ + { + uri: `${commonBase}/client[:]v1/service[:]v1/api-version[:]v1/add-optional-param/from-one-required`, + method: "get", + request: { + params: { + parameter: "required", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("parameter", "required"); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", + }, + { + uri: `${commonBase}/client[:]v1/service[:]v2/api-version[:]v1/add-optional-param/from-one-required`, + method: "get", + request: { + params: { + parameter: "required", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("parameter", "required"); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", + }, + { + uri: `${commonBase}/client[:]v2/service[:]v2/api-version[:]v1/add-optional-param/from-one-required`, + method: "get", + request: { + params: { + parameter: "required", + }, + }, + response: { + status: 204, }, - oldApiVersionNewClientValidate: addOptionalParamOldApiVersionNewClientValidate, - newApiVersionNewClientValidate: addOptionalParamNewApiVersionNewClientValidate, - }), -); + handler: (req: MockRequest) => { + req.expect.containsQueryParam("parameter", "required"); + if (req.params["new-parameter"] !== undefined) { + throw new ValidationError("Did not expect 'new-parameter'", undefined, req.params["new-parameter"]); + } + return { + status: 204, + }; + }, + kind: "MockApiDefinition", + }, + { + uri: `${commonBase}/client[:]v2/service[:]v2/api-version[:]v2/add-optional-param/from-one-required`, + method: "get", + request: { + params: { + "parameter": "required", + "new-parameter": "new", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("parameter", "required"); + req.expect.containsQueryParam("new-parameter", "new"); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", + }, +]); -Scenarios.Resiliency_ServiceDriven_AddOptionalParam_fromOneOptional = passOnSuccess( - createResilientMockApi({ - path: "/add-optional-param/from-one-optional", - verb: "get", - commonValidate: function validate(req: MockRequest): void { +Scenarios.Resiliency_ServiceDriven_AddOptionalParam_fromOneOptional = passOnSuccess([ + { + uri: `${commonBase}/client[:]v1/service[:]v1/api-version[:]v1/add-optional-param/from-one-optional`, + method: "get", + request: { + params: { + parameter: "optional", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("parameter", "optional"); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", + }, + { + uri: `${commonBase}/client[:]v1/service[:]v2/api-version[:]v1/add-optional-param/from-one-optional`, + method: "get", + request: { + params: { + parameter: "optional", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsQueryParam("parameter", "optional"); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", + }, + { + uri: `${commonBase}/client[:]v2/service[:]v2/api-version[:]v1/add-optional-param/from-one-optional`, + method: "get", + request: { + params: { + parameter: "optional", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("parameter", "optional"); + if (req.params["new-parameter"] !== undefined) { + throw new ValidationError("Did not expect 'new-parameter'", undefined, req.params["new-parameter"]); + } + return { + status: 204, + }; + }, + kind: "MockApiDefinition", + }, + { + uri: `${commonBase}/client[:]v2/service[:]v2/api-version[:]v2/add-optional-param/from-one-optional`, + method: "get", + request: { + params: { + "parameter": "optional", + "new-parameter": "new", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("parameter", "optional"); + req.expect.containsQueryParam("new-parameter", "new"); + return { + status: 204, + }; }, - oldApiVersionNewClientValidate: addOptionalParamOldApiVersionNewClientValidate, - newApiVersionNewClientValidate: addOptionalParamNewApiVersionNewClientValidate, - }), -); + kind: "MockApiDefinition", + }, +]); -Scenarios.Resiliency_ServiceDriven_breakTheGlass = passOnSuccess( - mockapi.delete(`${commonBase}/client[:]v1/service[:]v2/api-version[:]v2/add-operation`, (req) => { +Scenarios.Resiliency_ServiceDriven_breakTheGlass = passOnSuccess({ + uri: `${commonBase}/client[:]v1/service[:]v2/api-version[:]v2/add-operation`, + method: "delete", + request: {}, + response: { + status: 204, + }, + handler: (req: MockRequest) => { return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Resiliency_ServiceDriven_addOperation = passOnSuccess( - mockapi.delete(`${commonBase}/client[:]v2/service[:]v2/api-version[:]v2/add-operation`, (req) => { +Scenarios.Resiliency_ServiceDriven_addOperation = passOnSuccess({ + uri: `${commonBase}/client[:]v2/service[:]v2/api-version[:]v2/add-operation`, + method: "delete", + request: {}, + response: { + status: 204, + }, + handler: (req: MockRequest) => { return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/routes/mockapi.ts b/packages/cadl-ranch-specs/http/routes/mockapi.ts index ab09373eb..994bb5720 100644 --- a/packages/cadl-ranch-specs/http/routes/mockapi.ts +++ b/packages/cadl-ranch-specs/http/routes/mockapi.ts @@ -1,12 +1,25 @@ -import { passOnSuccess, mockapi, ValidationError } from "@azure-tools/cadl-ranch-api"; +import { MockRequest, passOnSuccess, ValidationError } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -function defineUri(uri: string) { +function createTests(uri: string) { const url = new URL("http://example.com" + uri); - return passOnSuccess( - mockapi.get(url.pathname, (req) => { + const searchParams = url.searchParams; + const params: Record = {}; + for (const [key, value] of searchParams) { + params[key] = value; + } + return passOnSuccess({ + uri: url.pathname, + method: "get", + request: { + params, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { const queryMap = new Map(); for (const [key, value] of url.searchParams.entries()) { if (queryMap.has(key)) { @@ -33,90 +46,91 @@ function defineUri(uri: string) { } } return { status: 204 }; - }), - ); + }, + kind: "MockApiDefinition", + }); } -Scenarios.Routes_InInterface = defineUri("/routes/fixed"); -Scenarios.Routes_fixed = defineUri("/routes/in-interface/fixed"); +Scenarios.Routes_InInterface = createTests("/routes/fixed"); +Scenarios.Routes_fixed = createTests("/routes/in-interface/fixed"); -Scenarios.Routes_PathParameters_templateOnly = defineUri("/routes/path/template-only/a"); -Scenarios.Routes_PathParameters_explicit = defineUri("/routes/path/explicit/a"); -Scenarios.Routes_PathParameters_annotationOnly = defineUri("/routes/path/annotation-only/a"); +Scenarios.Routes_PathParameters_templateOnly = createTests("/routes/path/template-only/a"); +Scenarios.Routes_PathParameters_explicit = createTests("/routes/path/explicit/a"); +Scenarios.Routes_PathParameters_annotationOnly = createTests("/routes/path/annotation-only/a"); -Scenarios.Routes_PathParameters_ReservedExpansion_template = defineUri( +Scenarios.Routes_PathParameters_ReservedExpansion_template = createTests( "/routes/path/reserved-expansion/template/foo/bar%20baz", ); -Scenarios.Routes_PathParameters_ReservedExpansion_annotation = defineUri( +Scenarios.Routes_PathParameters_ReservedExpansion_annotation = createTests( "/routes/path/reserved-expansion/annotation/foo/bar%20baz", ); -Scenarios.Routes_PathParameters_SimpleExpansion_Standard_primitive = defineUri("/routes/simple/standard/primitivea"); -Scenarios.Routes_PathParameters_SimpleExpansion_Standard_array = defineUri("/routes/simple/standard/arraya,b"); -Scenarios.Routes_PathParameters_SimpleExpansion_Standard_record = defineUri("/routes/simple/standard/recorda,1,b,2"); -Scenarios.Routes_PathParameters_SimpleExpansion_Explode_primitive = defineUri("/routes/simple/standard/primitivea"); -Scenarios.Routes_PathParameters_SimpleExpansion_Explode_array = defineUri("/routes/simple/standard/arraya,b"); -Scenarios.Routes_PathParameters_SimpleExpansion_Explode_record = defineUri("/routes/simple/standard/recorda=1,b=2"); +Scenarios.Routes_PathParameters_SimpleExpansion_Standard_primitive = createTests("/routes/simple/standard/primitivea"); +Scenarios.Routes_PathParameters_SimpleExpansion_Standard_array = createTests("/routes/simple/standard/arraya,b"); +Scenarios.Routes_PathParameters_SimpleExpansion_Standard_record = createTests("/routes/simple/standard/recorda,1,b,2"); +Scenarios.Routes_PathParameters_SimpleExpansion_Explode_primitive = createTests("/routes/simple/standard/primitivea"); +Scenarios.Routes_PathParameters_SimpleExpansion_Explode_array = createTests("/routes/simple/standard/arraya,b"); +Scenarios.Routes_PathParameters_SimpleExpansion_Explode_record = createTests("/routes/simple/standard/recorda=1,b=2"); -Scenarios.Routes_PathParameters_PathExpansion_Standard_primitive = defineUri("/routes/path/standard/primitive/a"); -Scenarios.Routes_PathParameters_PathExpansion_Standard_array = defineUri("/routes/path/standard/array/a,b"); -Scenarios.Routes_PathParameters_PathExpansion_Standard_record = defineUri("/routes/path/standard/record/a,1,b,2"); -Scenarios.Routes_PathParameters_PathExpansion_Explode_primitive = defineUri("/routes/path/standard/primitive/a"); -Scenarios.Routes_PathParameters_PathExpansion_Explode_array = defineUri("/routes/path/standard/array/a/b"); -Scenarios.Routes_PathParameters_PathExpansion_Explode_record = defineUri("/routes/path/standard/record/a=1/b=2"); +Scenarios.Routes_PathParameters_PathExpansion_Standard_primitive = createTests("/routes/path/standard/primitive/a"); +Scenarios.Routes_PathParameters_PathExpansion_Standard_array = createTests("/routes/path/standard/array/a,b"); +Scenarios.Routes_PathParameters_PathExpansion_Standard_record = createTests("/routes/path/standard/record/a,1,b,2"); +Scenarios.Routes_PathParameters_PathExpansion_Explode_primitive = createTests("/routes/path/standard/primitive/a"); +Scenarios.Routes_PathParameters_PathExpansion_Explode_array = createTests("/routes/path/standard/array/a/b"); +Scenarios.Routes_PathParameters_PathExpansion_Explode_record = createTests("/routes/path/standard/record/a=1/b=2"); -Scenarios.Routes_PathParameters_LabelExpansion_Standard_primitive = defineUri("/routes/label/standard/primitive.a"); -Scenarios.Routes_PathParameters_LabelExpansion_Standard_array = defineUri("/routes/label/standard/array.a,b"); -Scenarios.Routes_PathParameters_LabelExpansion_Standard_record = defineUri("/routes/label/standard/record.a,1,b,2"); -Scenarios.Routes_PathParameters_LabelExpansion_Explode_primitive = defineUri("/routes/label/standard/primitive.a"); -Scenarios.Routes_PathParameters_LabelExpansion_Explode_array = defineUri("/routes/label/standard/array.a.b"); -Scenarios.Routes_PathParameters_LabelExpansion_Explode_record = defineUri("/routes/label/standard/record.a=1.b=2"); +Scenarios.Routes_PathParameters_LabelExpansion_Standard_primitive = createTests("/routes/label/standard/primitive.a"); +Scenarios.Routes_PathParameters_LabelExpansion_Standard_array = createTests("/routes/label/standard/array.a,b"); +Scenarios.Routes_PathParameters_LabelExpansion_Standard_record = createTests("/routes/label/standard/record.a,1,b,2"); +Scenarios.Routes_PathParameters_LabelExpansion_Explode_primitive = createTests("/routes/label/standard/primitive.a"); +Scenarios.Routes_PathParameters_LabelExpansion_Explode_array = createTests("/routes/label/standard/array.a.b"); +Scenarios.Routes_PathParameters_LabelExpansion_Explode_record = createTests("/routes/label/standard/record.a=1.b=2"); -Scenarios.Routes_PathParameters_MatrixExpansion_Standard_primitive = defineUri("/routes/matrix/standard/primitive;a"); -Scenarios.Routes_PathParameters_MatrixExpansion_Standard_array = defineUri("/routes/matrix/standard/array;a,b"); -Scenarios.Routes_PathParameters_MatrixExpansion_Standard_record = defineUri("/routes/matrix/standard/record;a,1,b,2"); -Scenarios.Routes_PathParameters_MatrixExpansion_Explode_primitive = defineUri("/routes/matrix/standard/primitive;a"); -Scenarios.Routes_PathParameters_MatrixExpansion_Explode_array = defineUri("/routes/matrix/standard/array;a;b"); -Scenarios.Routes_PathParameters_MatrixExpansion_Explode_record = defineUri("/routes/matrix/standard/record;a=1;b=2"); +Scenarios.Routes_PathParameters_MatrixExpansion_Standard_primitive = createTests("/routes/matrix/standard/primitive;a"); +Scenarios.Routes_PathParameters_MatrixExpansion_Standard_array = createTests("/routes/matrix/standard/array;a,b"); +Scenarios.Routes_PathParameters_MatrixExpansion_Standard_record = createTests("/routes/matrix/standard/record;a,1,b,2"); +Scenarios.Routes_PathParameters_MatrixExpansion_Explode_primitive = createTests("/routes/matrix/standard/primitive;a"); +Scenarios.Routes_PathParameters_MatrixExpansion_Explode_array = createTests("/routes/matrix/standard/array;a;b"); +Scenarios.Routes_PathParameters_MatrixExpansion_Explode_record = createTests("/routes/matrix/standard/record;a=1;b=2"); -Scenarios.Routes_QueryParameters_templateOnly = defineUri("/routes/query/template-only?param=a"); -Scenarios.Routes_QueryParameters_explicit = defineUri("/routes/query/explicit?param=a"); -Scenarios.Routes_QueryParameters_annotationOnly = defineUri("/routes/query/annotation-only?param=a"); +Scenarios.Routes_QueryParameters_templateOnly = createTests("/routes/query/template-only?param=a"); +Scenarios.Routes_QueryParameters_explicit = createTests("/routes/query/explicit?param=a"); +Scenarios.Routes_QueryParameters_annotationOnly = createTests("/routes/query/annotation-only?param=a"); -Scenarios.Routes_QueryParameters_QueryExpansion_Standard_primitive = defineUri( +Scenarios.Routes_QueryParameters_QueryExpansion_Standard_primitive = createTests( "/routes/query/query-expansion/standard/primitive?param=a", ); -Scenarios.Routes_QueryParameters_QueryExpansion_Standard_array = defineUri( +Scenarios.Routes_QueryParameters_QueryExpansion_Standard_array = createTests( "/routes/query/query-expansion/standard/array?param=a,b", ); -Scenarios.Routes_QueryParameters_QueryExpansion_Standard_record = defineUri( +Scenarios.Routes_QueryParameters_QueryExpansion_Standard_record = createTests( "/routes/query/query-expansion/standard/record?param=a,1,b,2", ); -Scenarios.Routes_QueryParameters_QueryExpansion_Explode_primitive = defineUri( +Scenarios.Routes_QueryParameters_QueryExpansion_Explode_primitive = createTests( "/routes/query/query-expansion/explode/primitive?param=a", ); -Scenarios.Routes_QueryParameters_QueryExpansion_Explode_array = defineUri( - "/routes/query/query-expansion/explode/array?param=a¶m=b", +Scenarios.Routes_QueryParameters_QueryExpansion_Explode_array = createTests( + "/routes/query/query-expansion/explode/array?param=a,b", ); -Scenarios.Routes_QueryParameters_QueryExpansion_Explode_record = defineUri( +Scenarios.Routes_QueryParameters_QueryExpansion_Explode_record = createTests( "/routes/query/query-expansion/explode/record?a=1&b=2", ); -Scenarios.Routes_QueryParameters_QueryContinuation_Standard_primitive = defineUri( +Scenarios.Routes_QueryParameters_QueryContinuation_Standard_primitive = createTests( "/routes/query/query-continuation/standard/primitive?fixed=true¶m=a", ); -Scenarios.Routes_QueryParameters_QueryContinuation_Standard_array = defineUri( +Scenarios.Routes_QueryParameters_QueryContinuation_Standard_array = createTests( "/routes/query/query-continuation/standard/array?fixed=true¶m=a,b", ); -Scenarios.Routes_QueryParameters_QueryContinuation_Standard_record = defineUri( +Scenarios.Routes_QueryParameters_QueryContinuation_Standard_record = createTests( "/routes/query/query-continuation/standard/record?fixed=true¶m=a,1,b,2", ); -Scenarios.Routes_QueryParameters_QueryContinuation_Explode_primitive = defineUri( +Scenarios.Routes_QueryParameters_QueryContinuation_Explode_primitive = createTests( "/routes/query/query-continuation/explode/primitive?fixed=true¶m=a", ); -Scenarios.Routes_QueryParameters_QueryContinuation_Explode_array = defineUri( - "/routes/query/query-continuation/explode/array?fixed=true¶m=a¶m=b", +Scenarios.Routes_QueryParameters_QueryContinuation_Explode_array = createTests( + "/routes/query/query-continuation/explode/array?fixed=true¶m=a,b", ); -Scenarios.Routes_QueryParameters_QueryContinuation_Explode_record = defineUri( +Scenarios.Routes_QueryParameters_QueryContinuation_Explode_record = createTests( "/routes/query/query-continuation/explode/record?fixed=true&a=1&b=2", ); diff --git a/packages/cadl-ranch-specs/http/serialization/encoded-name/json/mockapi.ts b/packages/cadl-ranch-specs/http/serialization/encoded-name/json/mockapi.ts index 669d26e75..61dbe6050 100644 --- a/packages/cadl-ranch-specs/http/serialization/encoded-name/json/mockapi.ts +++ b/packages/cadl-ranch-specs/http/serialization/encoded-name/json/mockapi.ts @@ -1,21 +1,34 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Serialization_EncodedName_Json_Property_send = passOnSuccess( - mockapi.post("/serialization/encoded-name/json/property", (req) => { +Scenarios.Serialization_EncodedName_Json_Property_send = passOnSuccess({ + uri: "/serialization/encoded-name/json/property", + method: "post", + request: { body: { wireName: true } }, + response: { status: 204 }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ wireName: true }); return { status: 204, }; - }), -); -Scenarios.Serialization_EncodedName_Json_Property_get = passOnSuccess( - mockapi.get("/serialization/encoded-name/json/property", (req) => { + }, + kind: "MockApiDefinition", +}); +Scenarios.Serialization_EncodedName_Json_Property_get = passOnSuccess({ + uri: "/serialization/encoded-name/json/property", + method: "get", + request: {}, + response: { + status: 200, + body: json({ wireName: true }), + }, + handler: (req: MockRequest) => { return { status: 200, body: json({ wireName: true }), }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/server/endpoint/not-defined/mockapi.ts b/packages/cadl-ranch-specs/http/server/endpoint/not-defined/mockapi.ts index 65a8a1339..8a4d25102 100644 --- a/packages/cadl-ranch-specs/http/server/endpoint/not-defined/mockapi.ts +++ b/packages/cadl-ranch-specs/http/server/endpoint/not-defined/mockapi.ts @@ -1,10 +1,17 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Server_Endpoint_NotDefined_valid = passOnSuccess( - mockapi.head("/server/endpoint/not-defined/valid", (req) => { +Scenarios.Server_Endpoint_NotDefined_valid = passOnSuccess({ + uri: "/server/endpoint/not-defined/valid", + method: "head", + request: {}, + response: { + status: 200, + }, + handler: (req: MockRequest) => { return { status: 200 }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/server/path/multiple/mockapi.ts b/packages/cadl-ranch-specs/http/server/path/multiple/mockapi.ts index 02bac178d..53b9207e2 100644 --- a/packages/cadl-ranch-specs/http/server/path/multiple/mockapi.ts +++ b/packages/cadl-ranch-specs/http/server/path/multiple/mockapi.ts @@ -1,15 +1,29 @@ -import { passOnSuccess, ScenarioMockApi, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ScenarioMockApi, MockRequest } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Server_Path_Multiple_noOperationParams = passOnSuccess( - mockapi.get("/server/path/multiple/v1.0", (req) => { +Scenarios.Server_Path_Multiple_noOperationParams = passOnSuccess({ + uri: "/server/path/multiple/v1.0", + method: "get", + request: {}, + response: { + status: 204, + }, + handler: (req: MockRequest) => { return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Server_Path_Multiple_withOperationPathParam = passOnSuccess( - mockapi.get("/server/path/multiple/v1.0/test", (req) => { +Scenarios.Server_Path_Multiple_withOperationPathParam = passOnSuccess({ + uri: "/server/path/multiple/v1.0/test", + method: "get", + request: {}, + response: { + status: 204, + }, + handler: (req: MockRequest) => { return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/server/path/single/mockapi.ts b/packages/cadl-ranch-specs/http/server/path/single/mockapi.ts index 252f80d9b..f7082a929 100644 --- a/packages/cadl-ranch-specs/http/server/path/single/mockapi.ts +++ b/packages/cadl-ranch-specs/http/server/path/single/mockapi.ts @@ -1,10 +1,17 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Server_Path_Single_myOp = passOnSuccess( - mockapi.head("/server/path/single/myOp", (req) => { +Scenarios.Server_Path_Single_myOp = passOnSuccess({ + uri: "/server/path/single/myOp", + method: "head", + request: {}, + response: { + status: 200, + }, + handler: (req: MockRequest) => { return { status: 200 }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/server/versions/not-versioned/mockapi.ts b/packages/cadl-ranch-specs/http/server/versions/not-versioned/mockapi.ts index 4fef1a040..06e9fa3b0 100644 --- a/packages/cadl-ranch-specs/http/server/versions/not-versioned/mockapi.ts +++ b/packages/cadl-ranch-specs/http/server/versions/not-versioned/mockapi.ts @@ -1,29 +1,58 @@ -import { passOnSuccess, mockapi, ValidationError } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ValidationError, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Server_Versions_NotVersioned_withoutApiVersion = passOnSuccess( - mockapi.head("/server/versions/not-versioned/without-api-version", (req) => { - if (Object.keys(req.query).length > 0) { - throw new ValidationError("Expected no query parameters including api-version", "No query parameters", req.query); - } - return { status: 200 }; - }), +function createServerTests(uri: string, requestData?: any) { + let requestObject: any; + if (requestData) { + requestObject = requestData; + } else { + requestObject = {}; + } + return passOnSuccess({ + uri, + method: "head", + request: requestObject, + response: { + status: 200, + }, + handler: (req: MockRequest) => { + if (Object.keys(req.query).length > 0) { + throw new ValidationError( + "Expected no query parameters including api-version", + "No query parameters", + req.query, + ); + } + return { status: 200 }; + }, + kind: "MockApiDefinition", + }); +} + +Scenarios.Server_Versions_NotVersioned_withoutApiVersion = createServerTests( + "/server/versions/not-versioned/without-api-version", ); -Scenarios.Server_Versions_NotVersioned_withQueryApiVersion = passOnSuccess( - mockapi.head("/server/versions/not-versioned/with-query-api-version", (req) => { - req.expect.containsQueryParam("api-version", "v1.0"); - return { status: 200 }; - }), +Scenarios.Server_Versions_NotVersioned_withPathApiVersion = createServerTests( + "/server/versions/not-versioned/with-path-api-version/v1.0", ); -Scenarios.Server_Versions_NotVersioned_withPathApiVersion = passOnSuccess( - mockapi.head("/server/versions/not-versioned/with-path-api-version/v1.0", (req) => { - if (Object.keys(req.query).length > 0) { - throw new ValidationError("Expected no query parameters including api-version", "No query parameters", req.query); - } +Scenarios.Server_Versions_NotVersioned_withQueryApiVersion = passOnSuccess({ + uri: "/server/versions/not-versioned/with-query-api-version", + method: "head", + request: { + params: { + "api-version": "v1.0", + }, + }, + response: { + status: 200, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", "v1.0"); return { status: 200 }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/server/versions/versioned/mockapi.ts b/packages/cadl-ranch-specs/http/server/versions/versioned/mockapi.ts index 1580da077..be37b7772 100644 --- a/packages/cadl-ranch-specs/http/server/versions/versioned/mockapi.ts +++ b/packages/cadl-ranch-specs/http/server/versions/versioned/mockapi.ts @@ -1,36 +1,70 @@ -import { passOnSuccess, mockapi, ValidationError } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ValidationError, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Server_Versions_Versioned_withoutApiVersion = passOnSuccess( - mockapi.head("/server/versions/versioned/without-api-version", (req) => { - if (Object.keys(req.query).length > 0) { - throw new ValidationError("Expected no query parameters including api-version", "No query parameters", req.query); - } - return { status: 200 }; - }), +function createServerTests(uri: string) { + return passOnSuccess({ + uri, + method: "head", + request: {}, + response: { + status: 200, + }, + handler: (req: MockRequest) => { + if (Object.keys(req.query).length > 0) { + throw new ValidationError( + "Expected no query parameters including api-version", + "No query parameters", + req.query, + ); + } + return { status: 200 }; + }, + kind: "MockApiDefinition", + }); +} + +function createAPIVersionTests(uri: string, requestData: any, serverData: string) { + return passOnSuccess({ + uri, + method: "head", + request: requestData, + response: { + status: 200, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("api-version", serverData); + return { status: 200 }; + }, + kind: "MockApiDefinition", + }); +} + +Scenarios.Server_Versions_Versioned_withoutApiVersion = createServerTests( + "/server/versions/versioned/without-api-version", ); -Scenarios.Server_Versions_Versioned_withQueryApiVersion = passOnSuccess( - mockapi.head("/server/versions/versioned/with-query-api-version", (req) => { - req.expect.containsQueryParam("api-version", "2022-12-01-preview"); - return { status: 200 }; - }), +Scenarios.Server_Versions_Versioned_withQueryApiVersion = createAPIVersionTests( + "/server/versions/versioned/with-query-api-version", + { + params: { + "api-version": "2022-12-01-preview", + }, + }, + "2022-12-01-preview", ); -Scenarios.Server_Versions_Versioned_withPathApiVersion = passOnSuccess( - mockapi.head("/server/versions/versioned/with-path-api-version/2022-12-01-preview", (req) => { - if (Object.keys(req.query).length > 0) { - throw new ValidationError("Expected no query parameters including api-version", "No query parameters", req.query); - } - return { status: 200 }; - }), +Scenarios.Server_Versions_Versioned_withPathApiVersion = createServerTests( + "/server/versions/versioned/with-path-api-version/2022-12-01-preview", ); -Scenarios.Server_Versions_Versioned_withQueryOldApiVersion = passOnSuccess( - mockapi.head("/server/versions/versioned/with-query-old-api-version", (req) => { - req.expect.containsQueryParam("api-version", "2021-01-01-preview"); - return { status: 200 }; - }), +Scenarios.Server_Versions_Versioned_withQueryOldApiVersion = createAPIVersionTests( + "/server/versions/versioned/with-query-old-api-version", + { + params: { + "api-version": "2021-01-01-preview", + }, + }, + "2021-01-01-preview", ); diff --git a/packages/cadl-ranch-specs/http/special-headers/conditional-request/mockapi.ts b/packages/cadl-ranch-specs/http/special-headers/conditional-request/mockapi.ts index 38501164a..865243d96 100644 --- a/packages/cadl-ranch-specs/http/special-headers/conditional-request/mockapi.ts +++ b/packages/cadl-ranch-specs/http/special-headers/conditional-request/mockapi.ts @@ -1,40 +1,84 @@ -import { passOnSuccess, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.SpecialHeaders_ConditionalRequest_postIfMatch = passOnSuccess( - mockapi.post("/special-headers/conditional-request/if-match", (req) => { +Scenarios.SpecialHeaders_ConditionalRequest_postIfMatch = passOnSuccess({ + uri: "/special-headers/conditional-request/if-match", + method: "post", + request: { + headers: { + "if-match": '"valid"', + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("if-match", '"valid"'); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.SpecialHeaders_ConditionalRequest_postIfNoneMatch = passOnSuccess( - mockapi.post("/special-headers/conditional-request/if-none-match", (req) => { +Scenarios.SpecialHeaders_ConditionalRequest_postIfNoneMatch = passOnSuccess({ + uri: "/special-headers/conditional-request/if-none-match", + method: "post", + request: { + headers: { + "if-none-match": '"invalid"', + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("if-none-match", '"invalid"'); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.SpecialHeaders_ConditionalRequest_headIfModifiedSince = passOnSuccess( - mockapi.head("/special-headers/conditional-request/if-modified-since", (req) => { +Scenarios.SpecialHeaders_ConditionalRequest_headIfModifiedSince = passOnSuccess({ + uri: "/special-headers/conditional-request/if-modified-since", + method: "head", + request: { + headers: { + "if-modified-since": "Fri, 26 Aug 2022 14:38:00 GMT", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("if-modified-since", "Fri, 26 Aug 2022 14:38:00 GMT"); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.SpecialHeaders_ConditionalRequest_postIfUnmodifiedSince = passOnSuccess( - mockapi.post("/special-headers/conditional-request/if-unmodified-since", (req) => { +Scenarios.SpecialHeaders_ConditionalRequest_postIfUnmodifiedSince = passOnSuccess({ + uri: "/special-headers/conditional-request/if-unmodified-since", + method: "post", + request: { + headers: { + "if-unmodified-since": "Fri, 26 Aug 2022 14:38:00 GMT", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.containsHeader("if-unmodified-since", "Fri, 26 Aug 2022 14:38:00 GMT"); return { status: 204, }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/special-headers/repeatability/mockapi.ts b/packages/cadl-ranch-specs/http/special-headers/repeatability/mockapi.ts index e3a0c7a75..cabf54b0b 100644 --- a/packages/cadl-ranch-specs/http/special-headers/repeatability/mockapi.ts +++ b/packages/cadl-ranch-specs/http/special-headers/repeatability/mockapi.ts @@ -1,15 +1,29 @@ import { passOnSuccess, ScenarioMockApi, - mockapi, ValidationError, validateValueFormat, + MockRequest, } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.SpecialHeaders_Repeatability_immediateSuccess = passOnSuccess( - mockapi.post("/special-headers/repeatability/immediateSuccess", (req) => { +Scenarios.SpecialHeaders_Repeatability_immediateSuccess = passOnSuccess({ + uri: "/special-headers/repeatability/immediateSuccess", + method: "post", + request: { + headers: { + "Repeatability-First-Sent": "Tue, 15 Nov 2022 12:45:26 GMT", + "Repeatability-Request-ID": "2378d9bc-1726-11ee-be56-0242ac120002", // fake uuid + }, + }, + response: { + status: 204, + headers: { + "repeatability-result": "accepted", + }, + }, + handler: (req: MockRequest) => { if (!("repeatability-request-id" in req.headers)) { throw new ValidationError("Repeatability-Request-ID is missing", "A UUID string", undefined); } @@ -24,5 +38,6 @@ Scenarios.SpecialHeaders_Repeatability_immediateSuccess = passOnSuccess( "repeatability-result": "accepted", }, }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/special-words/mockapi.ts b/packages/cadl-ranch-specs/http/special-words/mockapi.ts index 35a57e57e..1c7ccf58a 100644 --- a/packages/cadl-ranch-specs/http/special-words/mockapi.ts +++ b/packages/cadl-ranch-specs/http/special-words/mockapi.ts @@ -1,164 +1,401 @@ -import { passOnSuccess, ScenarioMockApi, mockapi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ScenarioMockApi, MockRequest } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; // ------------------------------------------------------------------------ // Operation name scenarios // ------------------------------------------------------------------------ -function opNameScenario(name: string) { - return passOnSuccess( - mockapi.get(`/special-words/operations/${name}`, (req) => { +function createOperationsTests(uri: string) { + return passOnSuccess({ + uri, + method: "get", + request: {}, + response: { + status: 204, + }, + handler: (req: MockRequest) => { return { status: 204, }; - }), - ); + }, + kind: "MockApiDefinition", + }); } -Scenarios.SpecialWords_Operations_and = opNameScenario("and"); -Scenarios.SpecialWords_Operations_as = opNameScenario("as"); -Scenarios.SpecialWords_Operations_assert = opNameScenario("assert"); -Scenarios.SpecialWords_Operations_async = opNameScenario("async"); -Scenarios.SpecialWords_Operations_await = opNameScenario("await"); -Scenarios.SpecialWords_Operations_break = opNameScenario("break"); -Scenarios.SpecialWords_Operations_class = opNameScenario("class"); -Scenarios.SpecialWords_Operations_constructor = opNameScenario("constructor"); -Scenarios.SpecialWords_Operations_continue = opNameScenario("continue"); -Scenarios.SpecialWords_Operations_def = opNameScenario("def"); -Scenarios.SpecialWords_Operations_del = opNameScenario("del"); -Scenarios.SpecialWords_Operations_elif = opNameScenario("elif"); -Scenarios.SpecialWords_Operations_else = opNameScenario("else"); -Scenarios.SpecialWords_Operations_except = opNameScenario("except"); -Scenarios.SpecialWords_Operations_exec = opNameScenario("exec"); -Scenarios.SpecialWords_Operations_finally = opNameScenario("finally"); -Scenarios.SpecialWords_Operations_for = opNameScenario("for"); -Scenarios.SpecialWords_Operations_from = opNameScenario("from"); -Scenarios.SpecialWords_Operations_global = opNameScenario("global"); -Scenarios.SpecialWords_Operations_if = opNameScenario("if"); -Scenarios.SpecialWords_Operations_import = opNameScenario("import"); -Scenarios.SpecialWords_Operations_in = opNameScenario("in"); -Scenarios.SpecialWords_Operations_is = opNameScenario("is"); -Scenarios.SpecialWords_Operations_lambda = opNameScenario("lambda"); -Scenarios.SpecialWords_Operations_not = opNameScenario("not"); -Scenarios.SpecialWords_Operations_or = opNameScenario("or"); -Scenarios.SpecialWords_Operations_pass = opNameScenario("pass"); -Scenarios.SpecialWords_Operations_raise = opNameScenario("raise"); -Scenarios.SpecialWords_Operations_return = opNameScenario("return"); -Scenarios.SpecialWords_Operations_try = opNameScenario("try"); -Scenarios.SpecialWords_Operations_while = opNameScenario("while"); -Scenarios.SpecialWords_Operations_with = opNameScenario("with"); -Scenarios.SpecialWords_Operations_yield = opNameScenario("yield"); +Scenarios.SpecialWords_Operations_and = createOperationsTests(`/special-words/operations/and`); +Scenarios.SpecialWords_Operations_as = createOperationsTests(`/special-words/operations/as`); +Scenarios.SpecialWords_Operations_assert = createOperationsTests(`/special-words/operations/assert`); +Scenarios.SpecialWords_Operations_async = createOperationsTests(`/special-words/operations/async`); +Scenarios.SpecialWords_Operations_await = createOperationsTests(`/special-words/operations/await`); +Scenarios.SpecialWords_Operations_break = createOperationsTests(`/special-words/operations/break`); +Scenarios.SpecialWords_Operations_class = createOperationsTests(`/special-words/operations/class`); +Scenarios.SpecialWords_Operations_constructor = createOperationsTests(`/special-words/operations/constructor`); +Scenarios.SpecialWords_Operations_continue = createOperationsTests(`/special-words/operations/continue`); +Scenarios.SpecialWords_Operations_def = createOperationsTests(`/special-words/operations/def`); +Scenarios.SpecialWords_Operations_del = createOperationsTests(`/special-words/operations/del`); +Scenarios.SpecialWords_Operations_elif = createOperationsTests(`/special-words/operations/elif`); +Scenarios.SpecialWords_Operations_else = createOperationsTests(`/special-words/operations/else`); +Scenarios.SpecialWords_Operations_except = createOperationsTests(`/special-words/operations/except`); +Scenarios.SpecialWords_Operations_exec = createOperationsTests(`/special-words/operations/exec`); +Scenarios.SpecialWords_Operations_finally = createOperationsTests(`/special-words/operations/finally`); +Scenarios.SpecialWords_Operations_for = createOperationsTests(`/special-words/operations/for`); +Scenarios.SpecialWords_Operations_from = createOperationsTests(`/special-words/operations/from`); +Scenarios.SpecialWords_Operations_global = createOperationsTests(`/special-words/operations/global`); +Scenarios.SpecialWords_Operations_if = createOperationsTests(`/special-words/operations/if`); +Scenarios.SpecialWords_Operations_import = createOperationsTests(`/special-words/operations/import`); +Scenarios.SpecialWords_Operations_in = createOperationsTests(`/special-words/operations/in`); +Scenarios.SpecialWords_Operations_is = createOperationsTests(`/special-words/operations/is`); +Scenarios.SpecialWords_Operations_lambda = createOperationsTests(`/special-words/operations/lambda`); +Scenarios.SpecialWords_Operations_not = createOperationsTests(`/special-words/operations/not`); +Scenarios.SpecialWords_Operations_or = createOperationsTests(`/special-words/operations/or`); +Scenarios.SpecialWords_Operations_pass = createOperationsTests(`/special-words/operations/pass`); +Scenarios.SpecialWords_Operations_raise = createOperationsTests(`/special-words/operations/raise`); +Scenarios.SpecialWords_Operations_return = createOperationsTests(`/special-words/operations/return`); +Scenarios.SpecialWords_Operations_try = createOperationsTests(`/special-words/operations/try`); +Scenarios.SpecialWords_Operations_while = createOperationsTests(`/special-words/operations/while`); +Scenarios.SpecialWords_Operations_with = createOperationsTests(`/special-words/operations/with`); +Scenarios.SpecialWords_Operations_yield = createOperationsTests(`/special-words/operations/yield`); // ------------------------------------------------------------------------ // Parameter name scenarios // ------------------------------------------------------------------------ -function paramNameScenario(name: string) { - return passOnSuccess( - mockapi.get(`/special-words/parameters/${name}`, (req) => { - req.expect.containsQueryParam(name, "ok"); +function createParametersTests(uri: string, data: any, paramName: string) { + return passOnSuccess({ + uri, + method: "get", + request: { + params: data, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam(paramName, "ok"); return { status: 204, }; - }), - ); + }, + kind: "MockApiDefinition", + }); } -Scenarios.SpecialWords_Parameters_and = paramNameScenario("and"); -Scenarios.SpecialWords_Parameters_as = paramNameScenario("as"); -Scenarios.SpecialWords_Parameters_assert = paramNameScenario("assert"); -Scenarios.SpecialWords_Parameters_async = paramNameScenario("async"); -Scenarios.SpecialWords_Parameters_await = paramNameScenario("await"); -Scenarios.SpecialWords_Parameters_break = paramNameScenario("break"); -Scenarios.SpecialWords_Parameters_class = paramNameScenario("class"); -Scenarios.SpecialWords_Parameters_constructor = paramNameScenario("constructor"); -Scenarios.SpecialWords_Parameters_continue = paramNameScenario("continue"); -Scenarios.SpecialWords_Parameters_def = paramNameScenario("def"); -Scenarios.SpecialWords_Parameters_del = paramNameScenario("del"); -Scenarios.SpecialWords_Parameters_elif = paramNameScenario("elif"); -Scenarios.SpecialWords_Parameters_else = paramNameScenario("else"); -Scenarios.SpecialWords_Parameters_except = paramNameScenario("except"); -Scenarios.SpecialWords_Parameters_exec = paramNameScenario("exec"); -Scenarios.SpecialWords_Parameters_finally = paramNameScenario("finally"); -Scenarios.SpecialWords_Parameters_for = paramNameScenario("for"); -Scenarios.SpecialWords_Parameters_from = paramNameScenario("from"); -Scenarios.SpecialWords_Parameters_global = paramNameScenario("global"); -Scenarios.SpecialWords_Parameters_if = paramNameScenario("if"); -Scenarios.SpecialWords_Parameters_import = paramNameScenario("import"); -Scenarios.SpecialWords_Parameters_in = paramNameScenario("in"); -Scenarios.SpecialWords_Parameters_is = paramNameScenario("is"); -Scenarios.SpecialWords_Parameters_lambda = paramNameScenario("lambda"); -Scenarios.SpecialWords_Parameters_not = paramNameScenario("not"); -Scenarios.SpecialWords_Parameters_or = paramNameScenario("or"); -Scenarios.SpecialWords_Parameters_pass = paramNameScenario("pass"); -Scenarios.SpecialWords_Parameters_raise = paramNameScenario("raise"); -Scenarios.SpecialWords_Parameters_return = paramNameScenario("return"); -Scenarios.SpecialWords_Parameters_try = paramNameScenario("try"); -Scenarios.SpecialWords_Parameters_while = paramNameScenario("while"); -Scenarios.SpecialWords_Parameters_with = paramNameScenario("with"); -Scenarios.SpecialWords_Parameters_yield = paramNameScenario("yield"); +Scenarios.SpecialWords_Parameters_and = createParametersTests( + `/special-words/parameters/and`, + { + and: "ok", + }, + "and", +); +Scenarios.SpecialWords_Parameters_as = createParametersTests( + `/special-words/parameters/as`, + { + as: "ok", + }, + "as", +); +Scenarios.SpecialWords_Parameters_assert = createParametersTests( + `/special-words/parameters/assert`, + { + assert: "ok", + }, + "assert", +); +Scenarios.SpecialWords_Parameters_async = createParametersTests( + `/special-words/parameters/async`, + { + async: "ok", + }, + "async", +); +Scenarios.SpecialWords_Parameters_await = createParametersTests( + `/special-words/parameters/await`, + { + await: "ok", + }, + "await", +); +Scenarios.SpecialWords_Parameters_break = createParametersTests( + `/special-words/parameters/break`, + { + break: "ok", + }, + "break", +); +Scenarios.SpecialWords_Parameters_class = createParametersTests( + `/special-words/parameters/class`, + { + class: "ok", + }, + "class", +); +Scenarios.SpecialWords_Parameters_constructor = createParametersTests( + `/special-words/parameters/constructor`, + { + constructor: "ok", + }, + "constructor", +); +Scenarios.SpecialWords_Parameters_continue = createParametersTests( + `/special-words/parameters/continue`, + { + continue: "ok", + }, + "continue", +); +Scenarios.SpecialWords_Parameters_def = createParametersTests( + `/special-words/parameters/def`, + { + def: "ok", + }, + "def", +); +Scenarios.SpecialWords_Parameters_del = createParametersTests( + `/special-words/parameters/del`, + { + del: "ok", + }, + "del", +); +Scenarios.SpecialWords_Parameters_elif = createParametersTests( + `/special-words/parameters/elif`, + { + elif: "ok", + }, + "elif", +); +Scenarios.SpecialWords_Parameters_else = createParametersTests( + `/special-words/parameters/else`, + { + else: "ok", + }, + "else", +); +Scenarios.SpecialWords_Parameters_except = createParametersTests( + `/special-words/parameters/except`, + { + except: "ok", + }, + "except", +); +Scenarios.SpecialWords_Parameters_exec = createParametersTests( + `/special-words/parameters/exec`, + { + exec: "ok", + }, + "exec", +); +Scenarios.SpecialWords_Parameters_finally = createParametersTests( + `/special-words/parameters/finally`, + { + finally: "ok", + }, + "finally", +); -Scenarios.SpecialWords_Parameters_cancellationToken = paramNameScenario("cancellationToken"); +Scenarios.SpecialWords_Parameters_for = createParametersTests( + `/special-words/parameters/for`, + { + for: "ok", + }, + "for", +); +Scenarios.SpecialWords_Parameters_from = createParametersTests( + `/special-words/parameters/from`, + { + from: "ok", + }, + "from", +); +Scenarios.SpecialWords_Parameters_global = createParametersTests( + `/special-words/parameters/global`, + { + global: "ok", + }, + "global", +); +Scenarios.SpecialWords_Parameters_if = createParametersTests( + `/special-words/parameters/if`, + { + if: "ok", + }, + "if", +); +Scenarios.SpecialWords_Parameters_import = createParametersTests( + `/special-words/parameters/import`, + { + import: "ok", + }, + "import", +); +Scenarios.SpecialWords_Parameters_in = createParametersTests( + `/special-words/parameters/in`, + { + in: "ok", + }, + "in", +); +Scenarios.SpecialWords_Parameters_is = createParametersTests( + `/special-words/parameters/is`, + { + is: "ok", + }, + "is", +); +Scenarios.SpecialWords_Parameters_lambda = createParametersTests( + `/special-words/parameters/lambda`, + { + lambda: "ok", + }, + "lambda", +); +Scenarios.SpecialWords_Parameters_not = createParametersTests( + `/special-words/parameters/not`, + { + not: "ok", + }, + "not", +); +Scenarios.SpecialWords_Parameters_or = createParametersTests( + `/special-words/parameters/or`, + { + or: "ok", + }, + "or", +); +Scenarios.SpecialWords_Parameters_pass = createParametersTests( + `/special-words/parameters/pass`, + { + pass: "ok", + }, + "pass", +); +Scenarios.SpecialWords_Parameters_raise = createParametersTests( + `/special-words/parameters/raise`, + { + raise: "ok", + }, + "raise", +); +Scenarios.SpecialWords_Parameters_return = createParametersTests( + `/special-words/parameters/return`, + { + return: "ok", + }, + "return", +); +Scenarios.SpecialWords_Parameters_try = createParametersTests( + `/special-words/parameters/try`, + { + try: "ok", + }, + "try", +); +Scenarios.SpecialWords_Parameters_while = createParametersTests( + `/special-words/parameters/while`, + { + while: "ok", + }, + "while", +); +Scenarios.SpecialWords_Parameters_with = createParametersTests( + `/special-words/parameters/with`, + { + with: "ok", + }, + "with", +); +Scenarios.SpecialWords_Parameters_yield = createParametersTests( + `/special-words/parameters/yield`, + { + yield: "ok", + }, + "yield", +); +Scenarios.SpecialWords_Parameters_cancellationToken = createParametersTests( + `/special-words/parameters/cancellationToken`, + { + cancellationToken: "ok", + }, + "cancellationToken", +); // ------------------------------------------------------------------------ // Model name scenarios // ------------------------------------------------------------------------ -function modelNameScenario(name: string) { - return passOnSuccess( - mockapi.post(`/special-words/models/${name}`, (req) => { +function createModelsTests(uri: string) { + return passOnSuccess({ + uri, + method: "post", + request: { + body: { + name: "ok", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ name: "ok" }); return { status: 204, }; - }), - ); + }, + kind: "MockApiDefinition", + }); } - -Scenarios.SpecialWords_Models_and = modelNameScenario("and"); -Scenarios.SpecialWords_Models_as = modelNameScenario("as"); -Scenarios.SpecialWords_Models_assert = modelNameScenario("assert"); -Scenarios.SpecialWords_Models_async = modelNameScenario("async"); -Scenarios.SpecialWords_Models_await = modelNameScenario("await"); -Scenarios.SpecialWords_Models_break = modelNameScenario("break"); -Scenarios.SpecialWords_Models_class = modelNameScenario("class"); -Scenarios.SpecialWords_Models_constructor = modelNameScenario("constructor"); -Scenarios.SpecialWords_Models_continue = modelNameScenario("continue"); -Scenarios.SpecialWords_Models_def = modelNameScenario("def"); -Scenarios.SpecialWords_Models_del = modelNameScenario("del"); -Scenarios.SpecialWords_Models_elif = modelNameScenario("elif"); -Scenarios.SpecialWords_Models_else = modelNameScenario("else"); -Scenarios.SpecialWords_Models_except = modelNameScenario("except"); -Scenarios.SpecialWords_Models_exec = modelNameScenario("exec"); -Scenarios.SpecialWords_Models_finally = modelNameScenario("finally"); -Scenarios.SpecialWords_Models_for = modelNameScenario("for"); -Scenarios.SpecialWords_Models_from = modelNameScenario("from"); -Scenarios.SpecialWords_Models_global = modelNameScenario("global"); -Scenarios.SpecialWords_Models_if = modelNameScenario("if"); -Scenarios.SpecialWords_Models_import = modelNameScenario("import"); -Scenarios.SpecialWords_Models_in = modelNameScenario("in"); -Scenarios.SpecialWords_Models_is = modelNameScenario("is"); -Scenarios.SpecialWords_Models_lambda = modelNameScenario("lambda"); -Scenarios.SpecialWords_Models_not = modelNameScenario("not"); -Scenarios.SpecialWords_Models_or = modelNameScenario("or"); -Scenarios.SpecialWords_Models_pass = modelNameScenario("pass"); -Scenarios.SpecialWords_Models_raise = modelNameScenario("raise"); -Scenarios.SpecialWords_Models_return = modelNameScenario("return"); -Scenarios.SpecialWords_Models_try = modelNameScenario("try"); -Scenarios.SpecialWords_Models_while = modelNameScenario("while"); -Scenarios.SpecialWords_Models_with = modelNameScenario("with"); -Scenarios.SpecialWords_Models_yield = modelNameScenario("yield"); +Scenarios.SpecialWords_Models_and = createModelsTests(`/special-words/models/and`); +Scenarios.SpecialWords_Models_as = createModelsTests(`/special-words/models/as`); +Scenarios.SpecialWords_Models_assert = createModelsTests(`/special-words/models/assert`); +Scenarios.SpecialWords_Models_async = createModelsTests(`/special-words/models/async`); +Scenarios.SpecialWords_Models_await = createModelsTests(`/special-words/models/await`); +Scenarios.SpecialWords_Models_break = createModelsTests(`/special-words/models/break`); +Scenarios.SpecialWords_Models_class = createModelsTests(`/special-words/models/class`); +Scenarios.SpecialWords_Models_constructor = createModelsTests(`/special-words/models/constructor`); +Scenarios.SpecialWords_Models_continue = createModelsTests(`/special-words/models/continue`); +Scenarios.SpecialWords_Models_def = createModelsTests(`/special-words/models/def`); +Scenarios.SpecialWords_Models_del = createModelsTests(`/special-words/models/del`); +Scenarios.SpecialWords_Models_elif = createModelsTests(`/special-words/models/elif`); +Scenarios.SpecialWords_Models_else = createModelsTests(`/special-words/models/else`); +Scenarios.SpecialWords_Models_except = createModelsTests(`/special-words/models/except`); +Scenarios.SpecialWords_Models_exec = createModelsTests(`/special-words/models/exec`); +Scenarios.SpecialWords_Models_finally = createModelsTests(`/special-words/models/finally`); +Scenarios.SpecialWords_Models_for = createModelsTests(`/special-words/models/for`); +Scenarios.SpecialWords_Models_from = createModelsTests(`/special-words/models/from`); +Scenarios.SpecialWords_Models_global = createModelsTests(`/special-words/models/global`); +Scenarios.SpecialWords_Models_if = createModelsTests(`/special-words/models/if`); +Scenarios.SpecialWords_Models_import = createModelsTests(`/special-words/models/import`); +Scenarios.SpecialWords_Models_in = createModelsTests(`/special-words/models/in`); +Scenarios.SpecialWords_Models_is = createModelsTests(`/special-words/models/is`); +Scenarios.SpecialWords_Models_lambda = createModelsTests(`/special-words/models/lambda`); +Scenarios.SpecialWords_Models_not = createModelsTests(`/special-words/models/not`); +Scenarios.SpecialWords_Models_or = createModelsTests(`/special-words/models/or`); +Scenarios.SpecialWords_Models_pass = createModelsTests(`/special-words/models/pass`); +Scenarios.SpecialWords_Models_raise = createModelsTests(`/special-words/models/raise`); +Scenarios.SpecialWords_Models_return = createModelsTests(`/special-words/models/return`); +Scenarios.SpecialWords_Models_try = createModelsTests(`/special-words/models/try`); +Scenarios.SpecialWords_Models_while = createModelsTests(`/special-words/models/while`); +Scenarios.SpecialWords_Models_with = createModelsTests(`/special-words/models/with`); +Scenarios.SpecialWords_Models_yield = createModelsTests(`/special-words/models/yield`); // ------------------------------------------------------------------------ // Property name scenarios // ------------------------------------------------------------------------ -function propertyNameScenario(route: string, name: string) { - return passOnSuccess( - mockapi.post(`/special-words/model-properties/${route}`, (req) => { - req.expect.bodyEquals({ [name]: "ok" }); - return { - status: 204, - }; - }), - ); -} - -Scenarios.SpecialWords_ModelProperties_sameAsModel = propertyNameScenario("same-as-model", "SameAsModel"); +Scenarios.SpecialWords_ModelProperties_sameAsModel = passOnSuccess({ + uri: "/special-words/model-properties/same-as-model", + method: "post", + request: { + body: { + SameAsModel: "ok", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals({ ["SameAsModel"]: "ok" }); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/type/array/mockapi.ts b/packages/cadl-ranch-specs/http/type/array/mockapi.ts index 775f0180e..959e6d5f8 100644 --- a/packages/cadl-ranch-specs/http/type/array/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/array/mockapi.ts @@ -1,87 +1,101 @@ -import { passOnSuccess, ScenarioMockApi, mockapi, json, MockApi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ScenarioMockApi, json, MockRequest } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -interface MockApiGetPut { - get: MockApi; - put: MockApi; -} - -/** - * Return the get and put operations - * @param route The route within /dictionary for your function. - * @param value The value you are expecting and will return. - */ -function createModelMockApis(route: string, value: any[]): MockApiGetPut { - const url = `/type/array/${route}`; +function createServerTests(uri: string, data: any) { return { - get: mockapi.get(url, (req) => { - return { + get: passOnSuccess({ + uri, + method: "get", + request: {}, + response: { status: 200, - body: json(value), - }; + body: json(data), + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: json(data), + }; + }, + kind: "MockApiDefinition", }), - put: mockapi.put(url, (req) => { - req.expect.coercedBodyEquals(value); - return { + put: passOnSuccess({ + uri, + method: "put", + request: { + body: data, + }, + response: { status: 204, - }; + }, + handler: (req: MockRequest) => { + req.expect.coercedBodyEquals(data); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", }), }; } -const Int32ValueMock = createModelMockApis("int32", [1, 2]); -Scenarios.Type_Array_Int32Value_get = passOnSuccess(Int32ValueMock.get); -Scenarios.Type_Array_Int32Value_put = passOnSuccess(Int32ValueMock.put); - -const Int64ValueMock = createModelMockApis("int64", [Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER]); -Scenarios.Type_Array_Int64Value_get = passOnSuccess(Int64ValueMock.get); -Scenarios.Type_Array_Int64Value_put = passOnSuccess(Int64ValueMock.put); - -const BooleanValueMock = createModelMockApis("boolean", [true, false]); -Scenarios.Type_Array_BooleanValue_get = passOnSuccess(BooleanValueMock.get); -Scenarios.Type_Array_BooleanValue_put = passOnSuccess(BooleanValueMock.put); - -const StringValueMock = createModelMockApis("string", ["hello", ""]); -Scenarios.Type_Array_StringValue_get = passOnSuccess(StringValueMock.get); -Scenarios.Type_Array_StringValue_put = passOnSuccess(StringValueMock.put); - -const Float32ValueMock = createModelMockApis("float32", [43.125]); -Scenarios.Type_Array_Float32Value_get = passOnSuccess(Float32ValueMock.get); -Scenarios.Type_Array_Float32Value_put = passOnSuccess(Float32ValueMock.put); - -const DatetimeValueMock = createModelMockApis("datetime", ["2022-08-26T18:38:00Z"]); -Scenarios.Type_Array_DatetimeValue_get = passOnSuccess(DatetimeValueMock.get); -Scenarios.Type_Array_DatetimeValue_put = passOnSuccess(DatetimeValueMock.put); - -const DurationValueMock = createModelMockApis("duration", ["P123DT22H14M12.011S"]); -Scenarios.Type_Array_DurationValue_get = passOnSuccess(DurationValueMock.get); -Scenarios.Type_Array_DurationValue_put = passOnSuccess(DurationValueMock.put); - -const UnknownValueMock = createModelMockApis("unknown", [1, "hello", null]); -Scenarios.Type_Array_UnknownValue_get = passOnSuccess(UnknownValueMock.get); -Scenarios.Type_Array_UnknownValue_put = passOnSuccess(UnknownValueMock.put); - -const ModelValueMock = createModelMockApis("model", [{ property: "hello" }, { property: "world" }]); -Scenarios.Type_Array_ModelValue_get = passOnSuccess(ModelValueMock.get); -Scenarios.Type_Array_ModelValue_put = passOnSuccess(ModelValueMock.put); - -const NullableFloatMock = createModelMockApis("nullable-float", [1.25, null, 3.0]); -Scenarios.Type_Array_NullableFloatValue_get = passOnSuccess(NullableFloatMock.get); -Scenarios.Type_Array_NullableFloatValue_put = passOnSuccess(NullableFloatMock.put); - -const NullableInt32Mock = createModelMockApis("nullable-int32", [1, null, 3]); -Scenarios.Type_Array_NullableInt32Value_get = passOnSuccess(NullableInt32Mock.get); -Scenarios.Type_Array_NullableInt32Value_put = passOnSuccess(NullableInt32Mock.put); - -const NullableStringMock = createModelMockApis("nullable-string", ["hello", null, "world"]); -Scenarios.Type_Array_NullableStringValue_get = passOnSuccess(NullableStringMock.get); -Scenarios.Type_Array_NullableStringValue_put = passOnSuccess(NullableStringMock.put); - -const NullableBooleanMock = createModelMockApis("nullable-boolean", [true, null, false]); -Scenarios.Type_Array_NullableBooleanValue_get = passOnSuccess(NullableBooleanMock.get); -Scenarios.Type_Array_NullableBooleanValue_put = passOnSuccess(NullableBooleanMock.put); - -const NullableModelMock = createModelMockApis("nullable-model", [{ property: "hello" }, null, { property: "world" }]); -Scenarios.Type_Array_NullableModelValue_get = passOnSuccess(NullableModelMock.get); -Scenarios.Type_Array_NullableModelValue_put = passOnSuccess(NullableModelMock.put); +const Type_Array_Int32 = createServerTests(`/type/array/int32`, [1, 2]); +Scenarios.Type_Array_Int32Value_get = Type_Array_Int32.get; +Scenarios.Type_Array_Int32Value_put = Type_Array_Int32.put; + +const Type_Array_Int64 = createServerTests(`/type/array/int64`, [Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER]); +Scenarios.Type_Array_Int64Value_get = Type_Array_Int64.get; +Scenarios.Type_Array_Int64Value_put = Type_Array_Int64.put; + +const Type_Array_Boolean = createServerTests(`/type/array/boolean`, [true, false]); +Scenarios.Type_Array_BooleanValue_get = Type_Array_Boolean.get; +Scenarios.Type_Array_BooleanValue_put = Type_Array_Boolean.put; + +const Type_Array_String = createServerTests(`/type/array/string`, ["hello", ""]); +Scenarios.Type_Array_StringValue_get = Type_Array_String.get; +Scenarios.Type_Array_StringValue_put = Type_Array_String.put; + +const Type_Array_Float32 = createServerTests(`/type/array/float32`, [43.125]); +Scenarios.Type_Array_Float32Value_get = Type_Array_Float32.get; +Scenarios.Type_Array_Float32Value_put = Type_Array_Float32.put; + +const Type_Array_Datetime = createServerTests(`/type/array/datetime`, ["2022-08-26T18:38:00Z"]); +Scenarios.Type_Array_DatetimeValue_get = Type_Array_Datetime.get; +Scenarios.Type_Array_DatetimeValue_put = Type_Array_Datetime.put; + +const Type_Array_Duration = createServerTests(`/type/array/duration`, ["P123DT22H14M12.011S"]); +Scenarios.Type_Array_DurationValue_get = Type_Array_Duration.get; +Scenarios.Type_Array_DurationValue_put = Type_Array_Duration.put; + +const Type_Array_Unknown = createServerTests(`/type/array/unknown`, [1, "hello", null]); +Scenarios.Type_Array_UnknownValue_get = Type_Array_Unknown.get; +Scenarios.Type_Array_UnknownValue_put = Type_Array_Unknown.put; + +const Type_Array_Model = createServerTests(`/type/array/model`, [{ property: "hello" }, { property: "world" }]); +Scenarios.Type_Array_ModelValue_get = Type_Array_Model.get; +Scenarios.Type_Array_ModelValue_put = Type_Array_Model.put; + +const Type_Array_Nullable_Float = createServerTests(`/type/array/nullable-float`, [1.25, null, 3.0]); +Scenarios.Type_Array_NullableFloatValue_get = Type_Array_Nullable_Float.get; +Scenarios.Type_Array_NullableFloatValue_put = Type_Array_Nullable_Float.put; + +const Type_Array_Nullable_Int32 = createServerTests(`/type/array/nullable-int32`, [1, null, 3]); +Scenarios.Type_Array_NullableInt32Value_get = Type_Array_Nullable_Int32.get; +Scenarios.Type_Array_NullableInt32Value_put = Type_Array_Nullable_Int32.put; + +const Type_Array_Nullable_String = createServerTests(`/type/array/nullable-string`, ["hello", null, "world"]); +Scenarios.Type_Array_NullableStringValue_get = Type_Array_Nullable_String.get; +Scenarios.Type_Array_NullableStringValue_put = Type_Array_Nullable_String.put; + +const Type_Array_Nullable_Boolean = createServerTests(`/type/array/nullable-boolean`, [true, null, false]); +Scenarios.Type_Array_NullableBooleanValue_get = Type_Array_Nullable_Boolean.get; +Scenarios.Type_Array_NullableBooleanValue_put = Type_Array_Nullable_Boolean.put; + +const Type_Array_Nullable_Model = createServerTests(`/type/array/nullable-model`, [ + { property: "hello" }, + null, + { property: "world" }, +]); +Scenarios.Type_Array_NullableModelValue_get = Type_Array_Nullable_Model.get; +Scenarios.Type_Array_NullableModelValue_put = Type_Array_Nullable_Model.put; diff --git a/packages/cadl-ranch-specs/http/type/dictionary/mockapi.ts b/packages/cadl-ranch-specs/http/type/dictionary/mockapi.ts index 4de3d05be..3be5009ee 100644 --- a/packages/cadl-ranch-specs/http/type/dictionary/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/dictionary/mockapi.ts @@ -1,81 +1,115 @@ -import { passOnSuccess, ScenarioMockApi, mockapi, json, MockApi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ScenarioMockApi, json, MockRequest } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -interface MockApiGetPut { - get: MockApi; - put: MockApi; -} - -/** - * Return the get and put operations - * @param route The route within /dictionary for your function. - * @param value The value you are expecting and will return. - */ -function createModelMockApis(route: string, value: any): MockApiGetPut { - const url = `/type/dictionary/${route}`; +function createServerTests(uri: string, data: any) { return { - get: mockapi.get(url, (req) => { - return { + get: passOnSuccess({ + uri, + method: "get", + request: {}, + response: { status: 200, - body: json(value), - }; + body: json(data), + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: json(data), + }; + }, + kind: "MockApiDefinition", }), - put: mockapi.put(url, (req) => { - req.expect.coercedBodyEquals(value); - return { + put: passOnSuccess({ + uri, + method: "put", + request: { + body: data, + }, + response: { status: 204, - }; + }, + handler: (req: MockRequest) => { + req.expect.coercedBodyEquals(data); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", }), }; } -const Int32ValueMock = createModelMockApis("int32", { k1: 1, k2: 2 }); -Scenarios.Type_Dictionary_Int32Value_get = passOnSuccess(Int32ValueMock.get); -Scenarios.Type_Dictionary_Int32Value_put = passOnSuccess(Int32ValueMock.put); +const Type_Dictionary_Int32 = createServerTests(`/type/dictionary/int32`, { k1: 1, k2: 2 }); +Scenarios.Type_Dictionary_Int32Value_get = Type_Dictionary_Int32.get; +Scenarios.Type_Dictionary_Int32Value_put = Type_Dictionary_Int32.put; -const Int64ValueMock = createModelMockApis("int64", { k1: Number.MAX_SAFE_INTEGER, k2: Number.MIN_SAFE_INTEGER }); -Scenarios.Type_Dictionary_Int64Value_get = passOnSuccess(Int64ValueMock.get); -Scenarios.Type_Dictionary_Int64Value_put = passOnSuccess(Int64ValueMock.put); +const Type_Dictionary_Int64 = createServerTests(`/type/dictionary/int64`, { + k1: Number.MAX_SAFE_INTEGER, + k2: Number.MIN_SAFE_INTEGER, +}); +Scenarios.Type_Dictionary_Int64Value_get = Type_Dictionary_Int64.get; +Scenarios.Type_Dictionary_Int64Value_put = Type_Dictionary_Int64.put; -const BooleanValueMock = createModelMockApis("boolean", { k1: true, k2: false }); -Scenarios.Type_Dictionary_BooleanValue_get = passOnSuccess(BooleanValueMock.get); -Scenarios.Type_Dictionary_BooleanValue_put = passOnSuccess(BooleanValueMock.put); +const Type_Dictionary_Boolean = createServerTests(`/type/dictionary/boolean`, { + k1: true, + k2: false, +}); +Scenarios.Type_Dictionary_BooleanValue_get = Type_Dictionary_Boolean.get; +Scenarios.Type_Dictionary_BooleanValue_put = Type_Dictionary_Boolean.put; -const StringValueMock = createModelMockApis("string", { k1: "hello", k2: "" }); -Scenarios.Type_Dictionary_StringValue_get = passOnSuccess(StringValueMock.get); -Scenarios.Type_Dictionary_StringValue_put = passOnSuccess(StringValueMock.put); +const Type_Dictionary_String = createServerTests(`/type/dictionary/string`, { + k1: "hello", + k2: "", +}); +Scenarios.Type_Dictionary_StringValue_get = Type_Dictionary_String.get; +Scenarios.Type_Dictionary_StringValue_put = Type_Dictionary_String.put; -const Float32ValueMock = createModelMockApis("float32", { k1: 43.125 }); -Scenarios.Type_Dictionary_Float32Value_get = passOnSuccess(Float32ValueMock.get); -Scenarios.Type_Dictionary_Float32Value_put = passOnSuccess(Float32ValueMock.put); +const Type_Dictionary_Float32 = createServerTests(`/type/dictionary/float32`, { k1: 43.125 }); +Scenarios.Type_Dictionary_Float32Value_get = Type_Dictionary_Float32.get; +Scenarios.Type_Dictionary_Float32Value_put = Type_Dictionary_Float32.put; -const DatetimeValueMock = createModelMockApis("datetime", { k1: "2022-08-26T18:38:00Z" }); -Scenarios.Type_Dictionary_DatetimeValue_get = passOnSuccess(DatetimeValueMock.get); -Scenarios.Type_Dictionary_DatetimeValue_put = passOnSuccess(DatetimeValueMock.put); +const Type_Dictionary_Datetime = createServerTests(`/type/dictionary/datetime`, { + k1: "2022-08-26T18:38:00Z", +}); +Scenarios.Type_Dictionary_DatetimeValue_get = Type_Dictionary_Datetime.get; +Scenarios.Type_Dictionary_DatetimeValue_put = Type_Dictionary_Datetime.put; -const DurationValueMock = createModelMockApis("duration", { k1: "P123DT22H14M12.011S" }); -Scenarios.Type_Dictionary_DurationValue_get = passOnSuccess(DurationValueMock.get); -Scenarios.Type_Dictionary_DurationValue_put = passOnSuccess(DurationValueMock.put); +const Type_Dictionary_Duration = createServerTests(`/type/dictionary/duration`, { + k1: "P123DT22H14M12.011S", +}); +Scenarios.Type_Dictionary_DurationValue_get = Type_Dictionary_Duration.get; +Scenarios.Type_Dictionary_DurationValue_put = Type_Dictionary_Duration.put; -const UnknownValueMock = createModelMockApis("unknown", { k1: 1, k2: "hello", k3: null }); -Scenarios.Type_Dictionary_UnknownValue_get = passOnSuccess(UnknownValueMock.get); -Scenarios.Type_Dictionary_UnknownValue_put = passOnSuccess(UnknownValueMock.put); +const Type_Dictionary_Unknown = createServerTests(`/type/dictionary/unknown`, { + k1: 1, + k2: "hello", + k3: null, +}); +Scenarios.Type_Dictionary_UnknownValue_get = Type_Dictionary_Unknown.get; +Scenarios.Type_Dictionary_UnknownValue_put = Type_Dictionary_Unknown.put; -const ModelValueMock = createModelMockApis("model", { +const Type_Dictionary_Model = createServerTests(`/type/dictionary/model`, { k1: { property: "hello" }, k2: { property: "world" }, }); -Scenarios.Type_Dictionary_ModelValue_get = passOnSuccess(ModelValueMock.get); -Scenarios.Type_Dictionary_ModelValue_put = passOnSuccess(ModelValueMock.put); +Scenarios.Type_Dictionary_ModelValue_get = Type_Dictionary_Model.get; +Scenarios.Type_Dictionary_ModelValue_put = Type_Dictionary_Model.put; -const RecursiveValueMock = createModelMockApis("model/recursive", { +const Type_Dictionary_Model_Recursive = createServerTests(`/type/dictionary/model/recursive`, { k1: { property: "hello", children: {} }, - k2: { property: "world", children: { "k2.1": { property: "inner world" } } }, + k2: { + property: "world", + children: { "k2.1": { property: "inner world" } }, + }, }); -Scenarios.Type_Dictionary_RecursiveModelValue_get = passOnSuccess(RecursiveValueMock.get); -Scenarios.Type_Dictionary_RecursiveModelValue_put = passOnSuccess(RecursiveValueMock.put); +Scenarios.Type_Dictionary_RecursiveModelValue_get = Type_Dictionary_Model_Recursive.get; +Scenarios.Type_Dictionary_RecursiveModelValue_put = Type_Dictionary_Model_Recursive.put; -const NullableFloatValueMock = createModelMockApis("nullable-float", { k1: 1.25, k2: 0.5, k3: null }); -Scenarios.Type_Dictionary_NullableFloatValue_get = passOnSuccess(NullableFloatValueMock.get); -Scenarios.Type_Dictionary_NullableFloatValue_put = passOnSuccess(NullableFloatValueMock.put); +const Type_Dictionary_Nullable_Float = createServerTests(`/type/dictionary/nullable-float`, { + k1: 1.25, + k2: 0.5, + k3: null, +}); +Scenarios.Type_Dictionary_NullableFloatValue_get = Type_Dictionary_Nullable_Float.get; +Scenarios.Type_Dictionary_NullableFloatValue_put = Type_Dictionary_Nullable_Float.put; diff --git a/packages/cadl-ranch-specs/http/type/enum/extensible/mockapi.ts b/packages/cadl-ranch-specs/http/type/enum/extensible/mockapi.ts index 7ee1dcab5..59aa28c78 100644 --- a/packages/cadl-ranch-specs/http/type/enum/extensible/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/enum/extensible/mockapi.ts @@ -1,32 +1,56 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -// Known Values -Scenarios.Type_Enum_Extensible_String_getKnownValue = passOnSuccess( - mockapi.get("/type/enum/extensible/string/known-value", (req) => { - return { status: 200, body: json("Monday") }; - }), -); +function createMockServerTests(uri: string, data: any) { + return { + get: passOnSuccess({ + uri, + method: "get", + request: {}, + response: { + status: 200, + body: json(data), + }, + handler: (req: MockRequest) => { + return { status: 200, body: json(data) }; + }, + kind: "MockApiDefinition", + }), + put: passOnSuccess({ + uri, + method: "put", + request: { + body: data, + headers: { + "Content-Type": "text/plain", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals(data); + return { status: 204 }; + }, + kind: "MockApiDefinition", + }), + }; +} -Scenarios.Type_Enum_Extensible_String_putKnownValue = passOnSuccess( - mockapi.put("/type/enum/extensible/string/known-value", (req) => { - req.expect.bodyEquals("Monday"); - return { status: 204 }; - }), +// Known Values +const Type_Enum_Extensible_String_Known_Value = createMockServerTests( + `/type/enum/extensible/string/known-value`, + "Monday", ); +Scenarios.Type_Enum_Extensible_String_getKnownValue = Type_Enum_Extensible_String_Known_Value.get; +Scenarios.Type_Enum_Extensible_String_putKnownValue = Type_Enum_Extensible_String_Known_Value.put; // Unknown values -Scenarios.Type_Enum_Extensible_String_getUnknownValue = passOnSuccess( - mockapi.get("/type/enum/extensible/string/unknown-value", (req) => { - return { status: 200, body: json("Weekend") }; - }), -); - -Scenarios.Type_Enum_Extensible_String_putUnknownValue = passOnSuccess( - mockapi.put("/type/enum/extensible/string/unknown-value", (req) => { - req.expect.bodyEquals("Weekend"); - return { status: 204 }; - }), +const Type_Enum_Extensible_String_UnKnown_Value = createMockServerTests( + `/type/enum/extensible/string/unknown-value`, + "Weekend", ); +Scenarios.Type_Enum_Extensible_String_getUnknownValue = Type_Enum_Extensible_String_UnKnown_Value.get; +Scenarios.Type_Enum_Extensible_String_putUnknownValue = Type_Enum_Extensible_String_UnKnown_Value.put; diff --git a/packages/cadl-ranch-specs/http/type/enum/fixed/mockapi.ts b/packages/cadl-ranch-specs/http/type/enum/fixed/mockapi.ts index c2fd799ed..16c385916 100644 --- a/packages/cadl-ranch-specs/http/type/enum/fixed/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/enum/fixed/mockapi.ts @@ -1,27 +1,59 @@ -import { passOnSuccess, mockapi, json, passOnCode } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; // Known Values -Scenarios.Type_Enum_Fixed_String_getKnownValue = passOnSuccess( - mockapi.get("/type/enum/fixed/string/known-value", (req) => { +Scenarios.Type_Enum_Fixed_String_getKnownValue = passOnSuccess({ + uri: "/type/enum/fixed/string/known-value", + method: "get", + request: {}, + response: { + status: 200, + body: json("Monday"), + }, + handler: (req: MockRequest) => { return { status: 200, body: json("Monday") }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Type_Enum_Fixed_String_putKnownValue = passOnSuccess( - mockapi.put("/type/enum/fixed/string/known-value", (req) => { +Scenarios.Type_Enum_Fixed_String_putKnownValue = passOnSuccess({ + uri: "/type/enum/fixed/string/known-value", + method: "put", + request: { + body: "Monday", + headers: { + "Content-Type": "application/json", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals("Monday"); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); // Unknown values -Scenarios.Type_Enum_Fixed_String_putUnknownValue = passOnCode( - 500, - mockapi.put("/type/enum/fixed/string/unknown-value", (req) => { +Scenarios.Type_Enum_Fixed_String_putUnknownValue = passOnSuccess({ + uri: "/type/enum/fixed/string/unknown-value", + method: "put", + request: { + body: "Weekend", + headers: { + "Content-Type": "application/json", + }, + status: 500, + }, + response: { + status: 500, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals("Weekend"); return { status: 500 }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/type/model/empty/mockapi.ts b/packages/cadl-ranch-specs/http/type/model/empty/mockapi.ts index 186aa4958..2a70a5aee 100644 --- a/packages/cadl-ranch-specs/http/type/model/empty/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/model/empty/mockapi.ts @@ -1,26 +1,53 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; const body = {}; -Scenarios.Type_Model_Empty_putEmpty = passOnSuccess( - mockapi.put("/type/model/empty/alone", (req) => { +Scenarios.Type_Model_Empty_putEmpty = passOnSuccess({ + uri: "/type/model/empty/alone", + method: "put", + request: { + body: body, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(body); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Type_Model_Empty_getEmpty = passOnSuccess( - mockapi.get("/type/model/empty/alone", (req) => { +Scenarios.Type_Model_Empty_getEmpty = passOnSuccess({ + uri: "/type/model/empty/alone", + method: "get", + request: {}, + response: { + status: 200, + body: json(body), + }, + handler: (req: MockRequest) => { return { status: 200, body: json(body) }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Type_Model_Empty_postRoundTripEmpty = passOnSuccess( - mockapi.post("/type/model/empty/round-trip", (req) => { +Scenarios.Type_Model_Empty_postRoundTripEmpty = passOnSuccess({ + uri: "/type/model/empty/round-trip", + method: "post", + request: { + body: body, + }, + response: { + status: 200, + body: json(body), + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(body); return { status: 200, body: json(body) }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/type/model/inheritance/enum-discriminator/mockapi.ts b/packages/cadl-ranch-specs/http/type/model/inheritance/enum-discriminator/mockapi.ts index 54189f5af..2c57a7a28 100644 --- a/packages/cadl-ranch-specs/http/type/model/inheritance/enum-discriminator/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/model/inheritance/enum-discriminator/mockapi.ts @@ -1,4 +1,4 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; @@ -7,56 +7,93 @@ const validExtensibleEnumBody = { weight: 10, kind: "golden", }; -Scenarios.Type_Model_Inheritance_EnumDiscriminator_getExtensibleModel = passOnSuccess( - mockapi.get("/type/model/inheritance/enum-discriminator/extensible-enum", (req) => { - return { status: 200, body: json(validExtensibleEnumBody) }; - }), -); - -Scenarios.Type_Model_Inheritance_EnumDiscriminator_putExtensibleModel = passOnSuccess( - mockapi.put("/type/model/inheritance/enum-discriminator/extensible-enum", (req) => { - req.expect.bodyEquals(validExtensibleEnumBody); - return { status: 204 }; - }), -); - -Scenarios.Type_Model_Inheritance_EnumDiscriminator_getExtensibleModelMissingDiscriminator = passOnSuccess( - mockapi.get("/type/model/inheritance/enum-discriminator/extensible-enum/missingdiscriminator", (req) => { - return { status: 200, body: json({ weight: 10 }) }; - }), -); - -Scenarios.Type_Model_Inheritance_EnumDiscriminator_getExtensibleModelWrongDiscriminator = passOnSuccess( - mockapi.get("/type/model/inheritance/enum-discriminator/extensible-enum/wrongdiscriminator", (req) => { - return { status: 200, body: json({ weight: 8, kind: "wrongKind" }) }; - }), -); - const validFixedEnumBody = { length: 10, kind: "cobra", }; -Scenarios.Type_Model_Inheritance_EnumDiscriminator_getFixedModel = passOnSuccess( - mockapi.get("/type/model/inheritance/enum-discriminator/fixed-enum", (req) => { - return { status: 200, body: json(validFixedEnumBody) }; - }), -); +function createGetServerTests(uri: string, data: any) { + return passOnSuccess({ + uri: uri, + method: "get", + request: {}, + response: { + status: 200, + body: json(data), + }, + handler: (req: MockRequest) => { + return { status: 200, body: json(data) }; + }, + kind: "MockApiDefinition", + }); +} + +function createGetPutServerTests(uri: string, data: any) { + return { + get: passOnSuccess({ + uri: uri, + method: "get", + request: {}, + response: { + status: 200, + body: json(data), + }, + handler: (req: MockRequest) => { + return { status: 200, body: json(data) }; + }, + kind: "MockApiDefinition", + }), + put: passOnSuccess({ + uri: uri, + method: "put", + request: { + body: data, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals(data); + return { status: 204 }; + }, + kind: "MockApiDefinition", + }), + }; +} -Scenarios.Type_Model_Inheritance_EnumDiscriminator_putFixedModel = passOnSuccess( - mockapi.put("/type/model/inheritance/enum-discriminator/fixed-enum", (req) => { - req.expect.bodyEquals(validFixedEnumBody); - return { status: 204 }; - }), +const Type_Model_Inheritance_Enum_Discriminator_Extensible_Enum = createGetPutServerTests( + "/type/model/inheritance/enum-discriminator/extensible-enum", + validExtensibleEnumBody, ); +Scenarios.Type_Model_Inheritance_EnumDiscriminator_getExtensibleModel = + Type_Model_Inheritance_Enum_Discriminator_Extensible_Enum.get; +Scenarios.Type_Model_Inheritance_EnumDiscriminator_putExtensibleModel = + Type_Model_Inheritance_Enum_Discriminator_Extensible_Enum.put; -Scenarios.Type_Model_Inheritance_EnumDiscriminator_getFixedModelMissingDiscriminator = passOnSuccess( - mockapi.get("/type/model/inheritance/enum-discriminator/fixed-enum/missingdiscriminator", (req) => { - return { status: 200, body: json({ length: 10 }) }; - }), +const Type_Model_Inheritance_Enum_Discriminator_Fixed_Enum = createGetPutServerTests( + "/type/model/inheritance/enum-discriminator/fixed-enum", + validFixedEnumBody, ); +Scenarios.Type_Model_Inheritance_EnumDiscriminator_getFixedModel = + Type_Model_Inheritance_Enum_Discriminator_Fixed_Enum.get; +Scenarios.Type_Model_Inheritance_EnumDiscriminator_putFixedModel = + Type_Model_Inheritance_Enum_Discriminator_Fixed_Enum.put; -Scenarios.Type_Model_Inheritance_EnumDiscriminator_getFixedModelWrongDiscriminator = passOnSuccess( - mockapi.get("/type/model/inheritance/enum-discriminator/fixed-enum/wrongdiscriminator", (req) => { - return { status: 200, body: json({ length: 8, kind: "wrongKind" }) }; - }), +Scenarios.Type_Model_Inheritance_EnumDiscriminator_getExtensibleModelMissingDiscriminator = createGetServerTests( + "/type/model/inheritance/enum-discriminator/extensible-enum/missingdiscriminator", + { weight: 10 }, +); +Scenarios.Type_Model_Inheritance_EnumDiscriminator_getExtensibleModelWrongDiscriminator = createGetServerTests( + "/type/model/inheritance/enum-discriminator/extensible-enum/wrongdiscriminator", + { weight: 8, kind: "wrongKind" }, +); +Scenarios.Type_Model_Inheritance_EnumDiscriminator_getFixedModelMissingDiscriminator = createGetServerTests( + "/type/model/inheritance/enum-discriminator/fixed-enum/missingdiscriminator", + { length: 10 }, +); +Scenarios.Type_Model_Inheritance_EnumDiscriminator_getFixedModelWrongDiscriminator = createGetServerTests( + "/type/model/inheritance/enum-discriminator/fixed-enum/wrongdiscriminator", + { + length: 8, + kind: "wrongKind", + }, ); diff --git a/packages/cadl-ranch-specs/http/type/model/inheritance/nested-discriminator/mockapi.ts b/packages/cadl-ranch-specs/http/type/model/inheritance/nested-discriminator/mockapi.ts index 5e2efd303..69f6bc35f 100644 --- a/packages/cadl-ranch-specs/http/type/model/inheritance/nested-discriminator/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/model/inheritance/nested-discriminator/mockapi.ts @@ -1,4 +1,4 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; @@ -8,19 +8,6 @@ const validPolymorphicBody = { kind: "shark", sharktype: "goblin", }; -Scenarios.Type_Model_Inheritance_NestedDiscriminator_getModel = passOnSuccess( - mockapi.get("/type/model/inheritance/nested-discriminator/model", (req) => { - return { status: 200, body: json(validPolymorphicBody) }; - }), -); - -Scenarios.Type_Model_Inheritance_NestedDiscriminator_putModel = passOnSuccess( - mockapi.put("/type/model/inheritance/nested-discriminator/model", (req) => { - req.expect.bodyEquals(validPolymorphicBody); - return { status: 204 }; - }), -); - const validRecursiveBody = { age: 1, kind: "salmon", @@ -78,27 +65,87 @@ const validRecursiveBody = { }, }, }; -Scenarios.Type_Model_Inheritance_NestedDiscriminator_getRecursiveModel = passOnSuccess( - mockapi.get("/type/model/inheritance/nested-discriminator/recursivemodel", (req) => { - return { status: 200, body: json(validRecursiveBody) }; - }), -); +Scenarios.Type_Model_Inheritance_NestedDiscriminator_getModel = passOnSuccess({ + uri: "/type/model/inheritance/nested-discriminator/model", + method: "get", + request: {}, + response: { + status: 200, + body: json(validPolymorphicBody), + }, + handler: (req: MockRequest) => { + return { status: 200, body: json(validPolymorphicBody) }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Inheritance_NestedDiscriminator_putModel = passOnSuccess({ + uri: "/type/model/inheritance/nested-discriminator/model", + method: "put", + request: { + body: validPolymorphicBody, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals(validPolymorphicBody); + return { status: 204 }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Type_Model_Inheritance_NestedDiscriminator_putRecursiveModel = passOnSuccess( - mockapi.put("/type/model/inheritance/nested-discriminator/recursivemodel", (req) => { +Scenarios.Type_Model_Inheritance_NestedDiscriminator_getRecursiveModel = passOnSuccess({ + uri: "/type/model/inheritance/nested-discriminator/recursivemodel", + method: "get", + request: {}, + response: { + status: 200, + body: json(validRecursiveBody), + }, + handler: (req: MockRequest) => { + return { status: 200, body: json(validRecursiveBody) }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Inheritance_NestedDiscriminator_putRecursiveModel = passOnSuccess({ + uri: "/type/model/inheritance/nested-discriminator/recursivemodel", + method: "put", + request: { + body: validRecursiveBody, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(validRecursiveBody); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Type_Model_Inheritance_NestedDiscriminator_getMissingDiscriminator = passOnSuccess( - mockapi.get("/type/model/inheritance/nested-discriminator/missingdiscriminator", (req) => { +Scenarios.Type_Model_Inheritance_NestedDiscriminator_getMissingDiscriminator = passOnSuccess({ + uri: "/type/model/inheritance/nested-discriminator/missingdiscriminator", + method: "get", + request: {}, + response: { + status: 200, + body: json({ age: 1 }), + }, + handler: (req: MockRequest) => { return { status: 200, body: json({ age: 1 }) }; - }), -); - -Scenarios.Type_Model_Inheritance_NestedDiscriminator_getWrongDiscriminator = passOnSuccess( - mockapi.get("/type/model/inheritance/nested-discriminator/wrongdiscriminator", (req) => { + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Inheritance_NestedDiscriminator_getWrongDiscriminator = passOnSuccess({ + uri: "/type/model/inheritance/nested-discriminator/wrongdiscriminator", + method: "get", + request: {}, + response: { + status: 200, + body: json({ age: 1, kind: "wrongKind" }), + }, + handler: (req: MockRequest) => { return { status: 200, body: json({ age: 1, kind: "wrongKind" }) }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/type/model/inheritance/not-discriminated/mockapi.ts b/packages/cadl-ranch-specs/http/type/model/inheritance/not-discriminated/mockapi.ts index cfbe81cdb..ec992949b 100644 --- a/packages/cadl-ranch-specs/http/type/model/inheritance/not-discriminated/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/model/inheritance/not-discriminated/mockapi.ts @@ -1,24 +1,50 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; const inheritanceValidBody = { name: "abc", age: 32, smart: true }; -Scenarios.Type_Model_Inheritance_NotDiscriminated_postValid = passOnSuccess( - mockapi.post("/type/model/inheritance/not-discriminated/valid", (req) => { + +Scenarios.Type_Model_Inheritance_NotDiscriminated_postValid = passOnSuccess({ + uri: "/type/model/inheritance/not-discriminated/valid", + method: "post", + request: { + body: inheritanceValidBody, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(inheritanceValidBody); return { status: 204 }; - }), -); - -Scenarios.Type_Model_Inheritance_NotDiscriminated_getValid = passOnSuccess( - mockapi.get("/type/model/inheritance/not-discriminated/valid", (req) => { + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Inheritance_NotDiscriminated_getValid = passOnSuccess({ + uri: "/type/model/inheritance/not-discriminated/valid", + method: "get", + request: {}, + response: { + status: 200, + body: json(inheritanceValidBody), + }, + handler: (req: MockRequest) => { return { status: 200, body: json(inheritanceValidBody) }; - }), -); - -Scenarios.Type_Model_Inheritance_NotDiscriminated_putValid = passOnSuccess( - mockapi.put("/type/model/inheritance/not-discriminated/valid", (req) => { + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Inheritance_NotDiscriminated_putValid = passOnSuccess({ + uri: "/type/model/inheritance/not-discriminated/valid", + method: "put", + request: { + body: inheritanceValidBody, + }, + response: { + status: 200, + body: json(inheritanceValidBody), + }, + handler: (req: MockRequest) => { return { status: 200, body: json(req.body) }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/type/model/inheritance/recursive/mockapi.ts b/packages/cadl-ranch-specs/http/type/model/inheritance/recursive/mockapi.ts index b9200c8df..4d95475f9 100644 --- a/packages/cadl-ranch-specs/http/type/model/inheritance/recursive/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/model/inheritance/recursive/mockapi.ts @@ -1,4 +1,4 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; @@ -19,16 +19,31 @@ const body = { }, ], }; - -Scenarios.Type_Model_Inheritance_Recursive_put = passOnSuccess( - mockapi.put("/type/model/inheritance/recursive", (req) => { +Scenarios.Type_Model_Inheritance_Recursive_put = passOnSuccess({ + uri: "/type/model/inheritance/recursive", + method: "put", + request: { + body: body, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(body); return { status: 204 }; - }), -); - -Scenarios.Type_Model_Inheritance_Recursive_get = passOnSuccess( - mockapi.get("/type/model/inheritance/recursive", (req) => { + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Inheritance_Recursive_get = passOnSuccess({ + uri: "/type/model/inheritance/recursive", + method: "get", + request: {}, + response: { + status: 200, + body: json(body), + }, + handler: (req: MockRequest) => { return { status: 200, body: json(body) }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/type/model/inheritance/single-discriminator/mockapi.ts b/packages/cadl-ranch-specs/http/type/model/inheritance/single-discriminator/mockapi.ts index 8a35c6df4..2a45afca5 100644 --- a/packages/cadl-ranch-specs/http/type/model/inheritance/single-discriminator/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/model/inheritance/single-discriminator/mockapi.ts @@ -1,4 +1,4 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; @@ -7,19 +7,6 @@ const validPolymorphicBody = { wingspan: 1, kind: "sparrow", }; -Scenarios.Type_Model_Inheritance_SingleDiscriminator_getModel = passOnSuccess( - mockapi.get("/type/model/inheritance/single-discriminator/model", (req) => { - return { status: 200, body: json(validPolymorphicBody) }; - }), -); - -Scenarios.Type_Model_Inheritance_SingleDiscriminator_putModel = passOnSuccess( - mockapi.put("/type/model/inheritance/single-discriminator/model", (req) => { - req.expect.bodyEquals(validPolymorphicBody); - return { status: 204 }; - }), -); - const validRecursiveBody = { wingspan: 5, kind: "eagle", @@ -40,33 +27,101 @@ const validRecursiveBody = { }, }, }; -Scenarios.Type_Model_Inheritance_SingleDiscriminator_getRecursiveModel = passOnSuccess( - mockapi.get("/type/model/inheritance/single-discriminator/recursivemodel", (req) => { - return { status: 200, body: json(validRecursiveBody) }; - }), -); +Scenarios.Type_Model_Inheritance_SingleDiscriminator_getModel = passOnSuccess({ + uri: "/type/model/inheritance/single-discriminator/model", + method: "get", + request: {}, + response: { + status: 200, + body: json(validPolymorphicBody), + }, + handler: (req: MockRequest) => { + return { status: 200, body: json(validPolymorphicBody) }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Inheritance_SingleDiscriminator_putModel = passOnSuccess({ + uri: "/type/model/inheritance/single-discriminator/model", + method: "put", + request: { + body: validPolymorphicBody, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals(validPolymorphicBody); + return { status: 204 }; + }, + kind: "MockApiDefinition", +}); -Scenarios.Type_Model_Inheritance_SingleDiscriminator_putRecursiveModel = passOnSuccess( - mockapi.put("/type/model/inheritance/single-discriminator/recursivemodel", (req) => { +Scenarios.Type_Model_Inheritance_SingleDiscriminator_getRecursiveModel = passOnSuccess({ + uri: "/type/model/inheritance/single-discriminator/recursivemodel", + method: "get", + request: {}, + response: { + status: 200, + body: json(validRecursiveBody), + }, + handler: (req: MockRequest) => { + return { status: 200, body: json(validRecursiveBody) }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Inheritance_SingleDiscriminator_putRecursiveModel = passOnSuccess({ + uri: "/type/model/inheritance/single-discriminator/recursivemodel", + method: "put", + request: { + body: validRecursiveBody, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(validRecursiveBody); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Type_Model_Inheritance_SingleDiscriminator_getMissingDiscriminator = passOnSuccess( - mockapi.get("/type/model/inheritance/single-discriminator/missingdiscriminator", (req) => { +Scenarios.Type_Model_Inheritance_SingleDiscriminator_getMissingDiscriminator = passOnSuccess({ + uri: "/type/model/inheritance/single-discriminator/missingdiscriminator", + method: "get", + request: {}, + response: { + status: 200, + body: json({ wingspan: 1 }), + }, + handler: (req: MockRequest) => { return { status: 200, body: json({ wingspan: 1 }) }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Type_Model_Inheritance_SingleDiscriminator_getWrongDiscriminator = passOnSuccess( - mockapi.get("/type/model/inheritance/single-discriminator/wrongdiscriminator", (req) => { +Scenarios.Type_Model_Inheritance_SingleDiscriminator_getWrongDiscriminator = passOnSuccess({ + uri: "/type/model/inheritance/single-discriminator/wrongdiscriminator", + method: "get", + request: {}, + response: { + status: 200, + body: json({ wingspan: 1, kind: "wrongKind" }), + }, + handler: (req: MockRequest) => { return { status: 200, body: json({ wingspan: 1, kind: "wrongKind" }) }; - }), -); - -Scenarios.Type_Model_Inheritance_SingleDiscriminator_getLegacyModel = passOnSuccess( - mockapi.get("/type/model/inheritance/single-discriminator/legacy-model", (req) => { + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Inheritance_SingleDiscriminator_getLegacyModel = passOnSuccess({ + uri: "/type/model/inheritance/single-discriminator/legacy-model", + method: "get", + request: {}, + response: { + status: 200, + body: json({ size: 20, kind: "t-rex" }), + }, + handler: (req: MockRequest) => { return { status: 200, body: json({ size: 20, kind: "t-rex" }) }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/type/model/usage/mockapi.ts b/packages/cadl-ranch-specs/http/type/model/usage/mockapi.ts index e37687640..76f4f7488 100644 --- a/packages/cadl-ranch-specs/http/type/model/usage/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/model/usage/mockapi.ts @@ -1,26 +1,57 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; const body = { requiredProp: "example-value" }; -Scenarios.Type_Model_Usage_input = passOnSuccess( - mockapi.post("/type/model/usage/input", (req) => { +Scenarios.Type_Model_Usage_input = passOnSuccess({ + uri: "/type/model/usage/input", + method: "post", + request: { + body: { + requiredProp: "example-value", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(body); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Type_Model_Usage_output = passOnSuccess( - mockapi.get("/type/model/usage/output", (req) => { +Scenarios.Type_Model_Usage_output = passOnSuccess({ + uri: "/type/model/usage/output", + method: "get", + request: {}, + response: { + status: 200, + body: json(body), + }, + handler: (req: MockRequest) => { return { status: 200, body: json(body) }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Type_Model_Usage_inputAndOutput = passOnSuccess( - mockapi.post("/type/model/usage/input-output", (req) => { +Scenarios.Type_Model_Usage_inputAndOutput = passOnSuccess({ + uri: "/type/model/usage/input-output", + method: "post", + request: { + body: { + requiredProp: "example-value", + }, + }, + response: { + status: 200, + body: json(body), + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(body); return { status: 200, body: json(body) }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/type/model/visibility/mockapi.ts b/packages/cadl-ranch-specs/http/type/model/visibility/mockapi.ts index 60315453f..2016975fc 100644 --- a/packages/cadl-ranch-specs/http/type/model/visibility/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/model/visibility/mockapi.ts @@ -1,4 +1,4 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; @@ -19,60 +19,122 @@ function genData(keys: string[]): Record { } return ret; } - -Scenarios.Type_Model_Visibility_headModel = passOnSuccess( - mockapi.head("/type/model/visibility", (req) => { +const expectBody = { + optionalNullableIntList: [1, 2, 3], + optionalStringRecord: { k1: "value1", k2: "value2" }, +}; +Scenarios.Type_Model_Visibility_putReadOnlyModel = passOnSuccess({ + uri: "/type/model/visibility/readonlyroundtrip", + method: "put", + request: {}, + response: { + status: 200, + body: json(expectBody), + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals({}); + return { status: 200, body: json(expectBody) }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Visibility_headModel = passOnSuccess({ + uri: "/type/model/visibility", + method: "head", + request: { + body: { queryProp: 123 }, + }, + response: { + status: 200, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(genData(["queryProp"])); return { status: 200 }; - }), -); - -Scenarios.Type_Model_Visibility_getModel = passOnSuccess( - mockapi.get("/type/model/visibility", (req) => { + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Visibility_getModel = passOnSuccess({ + uri: "/type/model/visibility", + method: "get", + request: { + body: { queryProp: 123 }, + }, + response: { + status: 200, + body: json(genData(["readProp"])), + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(genData(["queryProp"])); return { status: 200, body: json(genData(["readProp"])), }; - }), -); - -Scenarios.Type_Model_Visibility_putModel = passOnSuccess( - mockapi.put("/type/model/visibility", (req) => { + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Visibility_putModel = passOnSuccess({ + uri: "/type/model/visibility", + method: "put", + request: { + body: { + createProp: ["foo", "bar"], + updateProp: [1, 2], + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(genData(["createProp", "updateProp"])); return { status: 204 }; - }), -); - -Scenarios.Type_Model_Visibility_patchModel = passOnSuccess( - mockapi.patch("/type/model/visibility", (req) => { + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Visibility_patchModel = passOnSuccess({ + uri: "/type/model/visibility", + method: "patch", + request: { + body: { + updateProp: [1, 2], + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(genData(["updateProp"])); return { status: 204 }; - }), -); - -Scenarios.Type_Model_Visibility_postModel = passOnSuccess( - mockapi.post("/type/model/visibility", (req) => { + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Visibility_postModel = passOnSuccess({ + uri: "/type/model/visibility", + method: "post", + request: { + body: { + createProp: ["foo", "bar"], + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(genData(["createProp"])); return { status: 204 }; - }), -); - -Scenarios.Type_Model_Visibility_deleteModel = passOnSuccess( - mockapi.delete("/type/model/visibility", (req) => { + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Model_Visibility_deleteModel = passOnSuccess({ + uri: "/type/model/visibility", + method: "delete", + request: { + body: { deleteProp: true }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(genData(["deleteProp"])); return { status: 204 }; - }), -); - -const expectBody = { - optionalNullableIntList: [1, 2, 3], - optionalStringRecord: { k1: "value1", k2: "value2" }, -}; - -Scenarios.Type_Model_Visibility_putReadOnlyModel = passOnSuccess( - mockapi.put("/type/model/visibility/readonlyroundtrip", (req) => { - req.expect.bodyEquals({}); - return { status: 200, body: json(expectBody) }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/type/property/additional-properties/mockapi.ts b/packages/cadl-ranch-specs/http/type/property/additional-properties/mockapi.ts index 68f939961..1f7a730f0 100644 --- a/packages/cadl-ranch-specs/http/type/property/additional-properties/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/property/additional-properties/mockapi.ts @@ -1,296 +1,61 @@ -import { passOnSuccess, ScenarioMockApi, mockapi, json, MockApi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ScenarioMockApi, json, MockRequest } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -interface MockApiGetPut { - get: MockApi; - put: MockApi; -} - -/** - * Return the get and put operations - * @param route The route within /models/properties for your function. - * @param value The value you are expecting and will return. - */ -function createMockApis(route: string, value: any): MockApiGetPut { - const url = `/type/property/additionalProperties/${route}`; - const body = value; - return { - get: mockapi.get(url, (req) => { - return { - status: 200, - body: json(body), - }; - }), - put: mockapi.put(url, (req) => { - const expectedBody = JSON.parse(JSON.stringify(body)); - req.expect.coercedBodyEquals(expectedBody); - return { - status: 204, - }; - }), - }; -} -// **************************************************** Record **************************************************** -const extendsUnknown = createMockApis("extendsRecordUnknown", { - name: "ExtendsUnknownAdditionalProperties", - prop1: 32, - prop2: true, - prop3: "abc", -}); -Scenarios.Type_Property_AdditionalProperties_ExtendsUnknown_get = passOnSuccess(extendsUnknown.get); -Scenarios.Type_Property_AdditionalProperties_ExtendsUnknown_put = passOnSuccess(extendsUnknown.put); - -const extendsUnknownDerived = createMockApis("extendsRecordUnknownDerived", { - name: "ExtendsUnknownAdditionalProperties", - index: 314, - age: 2.71875, - prop1: 32, - prop2: true, - prop3: "abc", -}); -Scenarios.Type_Property_AdditionalProperties_ExtendsUnknownDerived_get = passOnSuccess(extendsUnknownDerived.get); -Scenarios.Type_Property_AdditionalProperties_ExtendsUnknownDerived_put = passOnSuccess(extendsUnknownDerived.put); - -const extendsUnknownDiscriminated = createMockApis("extendsUnknownDiscriminated", { - kind: "derived", - name: "Derived", - index: 314, - age: 2.71875, - prop1: 32, - prop2: true, - prop3: "abc", -}); -Scenarios.Type_Property_AdditionalProperties_ExtendsUnknownDiscriminated_get = passOnSuccess( - extendsUnknownDiscriminated.get, -); -Scenarios.Type_Property_AdditionalProperties_ExtendsUnknownDiscriminated_put = passOnSuccess( - extendsUnknownDiscriminated.put, -); - -const isUnknown = createMockApis("isRecordUnknown", { - name: "IsUnknownAdditionalProperties", - prop1: 32, - prop2: true, - prop3: "abc", -}); -Scenarios.Type_Property_AdditionalProperties_IsUnknown_get = passOnSuccess(isUnknown.get); -Scenarios.Type_Property_AdditionalProperties_IsUnknown_put = passOnSuccess(isUnknown.put); - -const isUnknownDerived = createMockApis("isRecordUnknownDerived", { - name: "IsUnknownAdditionalProperties", - index: 314, - age: 2.71875, - prop1: 32, - prop2: true, - prop3: "abc", -}); -Scenarios.Type_Property_AdditionalProperties_IsUnknownDerived_get = passOnSuccess(isUnknownDerived.get); -Scenarios.Type_Property_AdditionalProperties_IsUnknownDerived_put = passOnSuccess(isUnknownDerived.put); - -const isUnknownDiscriminated = createMockApis("isUnknownDiscriminated", { - kind: "derived", - name: "Derived", - index: 314, - age: 2.71875, - prop1: 32, - prop2: true, - prop3: "abc", -}); -Scenarios.Type_Property_AdditionalProperties_IsUnknownDiscriminated_get = passOnSuccess(isUnknownDiscriminated.get); -Scenarios.Type_Property_AdditionalProperties_IsUnknownDiscriminated_put = passOnSuccess(isUnknownDiscriminated.put); - -// **************************************************** Record **************************************************** -const extendsString = createMockApis("extendsRecordString", { - name: "ExtendsStringAdditionalProperties", - prop: "abc", -}); -Scenarios.Type_Property_AdditionalProperties_ExtendsString_get = passOnSuccess(extendsString.get); -Scenarios.Type_Property_AdditionalProperties_ExtendsString_put = passOnSuccess(extendsString.put); - -const isString = createMockApis("isRecordString", { - name: "IsStringAdditionalProperties", - prop: "abc", -}); -Scenarios.Type_Property_AdditionalProperties_IsString_get = passOnSuccess(isString.get); -Scenarios.Type_Property_AdditionalProperties_IsString_put = passOnSuccess(isString.put); - -const spreadString = createMockApis("spreadRecordString", { - name: "SpreadSpringRecord", - prop: "abc", -}); -Scenarios.Type_Property_AdditionalProperties_SpreadString_get = passOnSuccess(spreadString.get); -Scenarios.Type_Property_AdditionalProperties_SpreadString_put = passOnSuccess(spreadString.put); - -// **************************************************** Record **************************************************** const recordFloatBody = { id: 43.125, prop: 43.125, }; -const extendsFloat = createMockApis("extendsRecordFloat", recordFloatBody); -Scenarios.Type_Property_AdditionalProperties_ExtendsFloat_get = passOnSuccess(extendsFloat.get); -Scenarios.Type_Property_AdditionalProperties_ExtendsFloat_put = passOnSuccess(extendsFloat.put); - -const isFloat = createMockApis("isRecordFloat", recordFloatBody); -Scenarios.Type_Property_AdditionalProperties_IsFloat_get = passOnSuccess(isFloat.get); -Scenarios.Type_Property_AdditionalProperties_IsFloat_put = passOnSuccess(isFloat.put); - -const spreadFloat = createMockApis("spreadRecordFloat", recordFloatBody); -Scenarios.Type_Property_AdditionalProperties_SpreadFloat_get = passOnSuccess(spreadFloat.get); -Scenarios.Type_Property_AdditionalProperties_SpreadFloat_put = passOnSuccess(spreadFloat.put); - -// **************************************************** Record **************************************************** const recordModelBody = { knownProp: { state: "ok" }, prop: { state: "ok" }, }; -const extendsModel = createMockApis("extendsRecordModel", recordModelBody); -Scenarios.Type_Property_AdditionalProperties_ExtendsModel_get = passOnSuccess(extendsModel.get); -Scenarios.Type_Property_AdditionalProperties_ExtendsModel_put = passOnSuccess(extendsModel.put); - -const isModel = createMockApis("isRecordModel", recordModelBody); -Scenarios.Type_Property_AdditionalProperties_IsModel_get = passOnSuccess(isModel.get); -Scenarios.Type_Property_AdditionalProperties_IsModel_put = passOnSuccess(isModel.put); - -const spreadModel = createMockApis("spreadRecordModel", recordModelBody); -Scenarios.Type_Property_AdditionalProperties_SpreadModel_get = passOnSuccess(spreadModel.get); -Scenarios.Type_Property_AdditionalProperties_SpreadModel_put = passOnSuccess(spreadModel.put); - -// **************************************************** Record **************************************************** const recordModelArrayBody = { knownProp: [{ state: "ok" }, { state: "ok" }], prop: [{ state: "ok" }, { state: "ok" }], }; -const extendsModelArray = createMockApis("extendsRecordModelArray", recordModelArrayBody); -Scenarios.Type_Property_AdditionalProperties_ExtendsModelArray_get = passOnSuccess(extendsModelArray.get); -Scenarios.Type_Property_AdditionalProperties_ExtendsModelArray_put = passOnSuccess(extendsModelArray.put); - -const isModelArray = createMockApis("isRecordModelArray", recordModelArrayBody); -Scenarios.Type_Property_AdditionalProperties_IsModelArray_get = passOnSuccess(isModelArray.get); -Scenarios.Type_Property_AdditionalProperties_IsModelArray_put = passOnSuccess(isModelArray.put); - -const spreadModelArray = createMockApis("spreadRecordModelArray", recordModelArrayBody); -Scenarios.Type_Property_AdditionalProperties_SpreadModelArray_get = passOnSuccess(spreadModelArray.get); -Scenarios.Type_Property_AdditionalProperties_SpreadModelArray_put = passOnSuccess(spreadModelArray.put); - -// **************************************************** Spread different Record type **************************************************** const differentRecordStringBody = { id: 43.125, prop: "abc", }; -const spreadDifferentRecordString = createMockApis("spreadDifferentRecordString", differentRecordStringBody); -Scenarios.Type_Property_AdditionalProperties_SpreadDifferentString_get = passOnSuccess(spreadDifferentRecordString.get); -Scenarios.Type_Property_AdditionalProperties_SpreadDifferentString_put = passOnSuccess(spreadDifferentRecordString.put); - const differentRecordFloatBody = { name: "abc", prop: 43.125, }; -const spreadDifferentRecordFloat = createMockApis("spreadDifferentRecordFloat", differentRecordFloatBody); -Scenarios.Type_Property_AdditionalProperties_SpreadDifferentFloat_get = passOnSuccess(spreadDifferentRecordFloat.get); -Scenarios.Type_Property_AdditionalProperties_SpreadDifferentFloat_put = passOnSuccess(spreadDifferentRecordFloat.put); - const differentRecordModelBody = { knownProp: "abc", prop: { state: "ok" }, }; - -const spreadDifferentRecordModel = createMockApis("spreadDifferentRecordModel", differentRecordModelBody); -Scenarios.Type_Property_AdditionalProperties_SpreadDifferentModel_get = passOnSuccess(spreadDifferentRecordModel.get); -Scenarios.Type_Property_AdditionalProperties_SpreadDifferentModel_put = passOnSuccess(spreadDifferentRecordModel.put); - const differentRecordModelArrayBody = { knownProp: "abc", prop: [{ state: "ok" }, { state: "ok" }], }; -const spreadDifferentRecordModelArray = createMockApis( - "spreadDifferentRecordModelArray", - differentRecordModelArrayBody, -); -Scenarios.Type_Property_AdditionalProperties_SpreadDifferentModelArray_get = passOnSuccess( - spreadDifferentRecordModelArray.get, -); -Scenarios.Type_Property_AdditionalProperties_SpreadDifferentModelArray_put = passOnSuccess( - spreadDifferentRecordModelArray.put, -); - -// **************************************************** extends from a model has spread Record **************************************************** const extendsModelSpreadStringBody = { id: 43.125, prop: "abc", derivedProp: "abc", }; - -const extendsModelSpreadString = createMockApis("extendsDifferentSpreadString", extendsModelSpreadStringBody); -Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadString_get = passOnSuccess( - extendsModelSpreadString.get, -); -Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadString_put = passOnSuccess( - extendsModelSpreadString.put, -); - -// **************************************************** extends from a model has spread Record **************************************************** const extendsModelSpreadFloatBody = { name: "abc", prop: 43.125, derivedProp: 43.125, }; -const extendsModelSpreadFloat = createMockApis("extendsDifferentSpreadFloat", extendsModelSpreadFloatBody); -Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadFloat_get = passOnSuccess( - extendsModelSpreadFloat.get, -); -Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadFloat_put = passOnSuccess( - extendsModelSpreadFloat.put, -); - -// **************************************************** extends from a model has spread Record **************************************************** const extendsModelSpreadModelBody = { knownProp: "abc", prop: { state: "ok" }, derivedProp: { state: "ok" }, }; -const extendsModelSpreadModel = createMockApis("extendsDifferentSpreadModel", extendsModelSpreadModelBody); -Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadModel_get = passOnSuccess( - extendsModelSpreadModel.get, -); -Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadModel_put = passOnSuccess( - extendsModelSpreadModel.put, -); - -// **************************************************** extends from a model has spread Record **************************************************** const extendsModelSpreadModelArrayBody = { knownProp: "abc", prop: [{ state: "ok" }, { state: "ok" }], derivedProp: [{ state: "ok" }, { state: "ok" }], }; -const extendsModelSpreadModelArray = createMockApis( - "extendsDifferentSpreadModelArray", - extendsModelSpreadModelArrayBody, -); -Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadModelArray_get = passOnSuccess( - extendsModelSpreadModelArray.get, -); -Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadModelArray_put = passOnSuccess( - extendsModelSpreadModelArray.put, -); - -// **************************************************** Multiple spread of Records **************************************************** const multipleSpreadBody = { flag: true, prop1: "abc", prop2: 43.125, }; -const multipleSpreadRecord = createMockApis("multipleSpreadRecord", multipleSpreadBody); -Scenarios.Type_Property_AdditionalProperties_MultipleSpread_get = passOnSuccess(multipleSpreadRecord.get); -Scenarios.Type_Property_AdditionalProperties_MultipleSpread_put = passOnSuccess(multipleSpreadRecord.put); - -// **************************************************** Record of union **************************************************** const recordUnionBody = multipleSpreadBody; -const recordUnion = createMockApis("spreadRecordUnion", recordUnionBody); -Scenarios.Type_Property_AdditionalProperties_SpreadRecordUnion_get = passOnSuccess(recordUnion.get); -Scenarios.Type_Property_AdditionalProperties_SpreadRecordUnion_put = passOnSuccess(recordUnion.put); - -// **************************************************** Record of discriminated union **************************************************** const recordDiscriminatedUnionBody = { name: "abc", prop1: { @@ -303,25 +68,6 @@ const recordDiscriminatedUnionBody = { end: "2021-01-02T00:00:00Z", }, }; - -const recordDiscriminatedUnion = createMockApis("spreadRecordDiscriminatedUnion", recordDiscriminatedUnionBody); -Scenarios.Type_Property_AdditionalProperties_SpreadRecordDiscriminatedUnion_get = passOnSuccess( - recordDiscriminatedUnion.get, -); -Scenarios.Type_Property_AdditionalProperties_SpreadRecordDiscriminatedUnion_put = passOnSuccess( - recordDiscriminatedUnion.put, -); - -// **************************************************** Record of non discriminated union **************************************************** -const recordNonDiscriminatedUnion = createMockApis("spreadRecordNonDiscriminatedUnion", recordDiscriminatedUnionBody); -Scenarios.Type_Property_AdditionalProperties_SpreadRecordNonDiscriminatedUnion_get = passOnSuccess( - recordNonDiscriminatedUnion.get, -); -Scenarios.Type_Property_AdditionalProperties_SpreadRecordNonDiscriminatedUnion_put = passOnSuccess( - recordNonDiscriminatedUnion.put, -); - -// **************************************************** Record of non discriminated union 2 **************************************************** const recordNonDiscriminatedUnion2Body = { name: "abc", prop1: { @@ -334,18 +80,6 @@ const recordNonDiscriminatedUnion2Body = { end: "2021-01-02T00:00:00Z", }, }; -const recordNonDiscriminatedUnion2 = createMockApis( - "spreadRecordNonDiscriminatedUnion2", - recordNonDiscriminatedUnion2Body, -); -Scenarios.Type_Property_AdditionalProperties_SpreadRecordNonDiscriminatedUnion2_get = passOnSuccess( - recordNonDiscriminatedUnion2.get, -); -Scenarios.Type_Property_AdditionalProperties_SpreadRecordNonDiscriminatedUnion2_put = passOnSuccess( - recordNonDiscriminatedUnion2.put, -); - -// **************************************************** Record of non discriminated union 3 **************************************************** const recordNonDiscriminatedUnion3Body = { name: "abc", prop1: [ @@ -364,13 +98,370 @@ const recordNonDiscriminatedUnion3Body = { end: "2021-01-02T00:00:00Z", }, }; -const recordNonDiscriminatedUnion3 = createMockApis( - "spreadRecordNonDiscriminatedUnion3", - recordNonDiscriminatedUnion3Body, +function createServerTests(url: string, value: any) { + return { + get: passOnSuccess({ + uri: url, + method: `get`, + request: {}, + response: { + status: 200, + body: json(value), + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: json(value), + }; + }, + kind: "MockApiDefinition", + }), + put: passOnSuccess({ + uri: url, + method: `put`, + request: { + body: value, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + const expectedBody = JSON.parse(JSON.stringify(value)); + req.expect.coercedBodyEquals(expectedBody); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", + }), + }; +} + +const Type_Property_Additional_Properties_Extends_Record_Unknown = createServerTests( + `/type/property/additionalProperties/extendsRecordUnknown`, + { + name: "ExtendsUnknownAdditionalProperties", + prop1: 32, + prop2: true, + prop3: "abc", + }, +); +Scenarios.Type_Property_AdditionalProperties_ExtendsUnknown_get = + Type_Property_Additional_Properties_Extends_Record_Unknown.get; +Scenarios.Type_Property_AdditionalProperties_ExtendsUnknown_put = + Type_Property_Additional_Properties_Extends_Record_Unknown.put; + +const Type_Property_Additional_Properties_Extends_Record_Unknown_Derived = createServerTests( + `/type/property/additionalProperties/extendsRecordUnknownDerived`, + { + name: "ExtendsUnknownAdditionalProperties", + index: 314, + age: 2.71875, + prop1: 32, + prop2: true, + prop3: "abc", + }, +); +Scenarios.Type_Property_AdditionalProperties_ExtendsUnknownDerived_get = + Type_Property_Additional_Properties_Extends_Record_Unknown_Derived.get; +Scenarios.Type_Property_AdditionalProperties_ExtendsUnknownDerived_put = + Type_Property_Additional_Properties_Extends_Record_Unknown_Derived.put; + +const Type_Property_Additional_Properties_Extends_Unknown_Discriminated = createServerTests( + `/type/property/additionalProperties/extendsUnknownDiscriminated`, + { + kind: "derived", + name: "Derived", + index: 314, + age: 2.71875, + prop1: 32, + prop2: true, + prop3: "abc", + }, +); +Scenarios.Type_Property_AdditionalProperties_ExtendsUnknownDiscriminated_get = + Type_Property_Additional_Properties_Extends_Unknown_Discriminated.get; +Scenarios.Type_Property_AdditionalProperties_ExtendsUnknownDiscriminated_put = + Type_Property_Additional_Properties_Extends_Unknown_Discriminated.put; + +const Type_Property_Additional_Properties_Is_Record_Unknown = createServerTests( + `/type/property/additionalProperties/isRecordUnknown`, + { + name: "IsUnknownAdditionalProperties", + prop1: 32, + prop2: true, + prop3: "abc", + }, +); +Scenarios.Type_Property_AdditionalProperties_IsUnknown_get = Type_Property_Additional_Properties_Is_Record_Unknown.get; +Scenarios.Type_Property_AdditionalProperties_IsUnknown_put = Type_Property_Additional_Properties_Is_Record_Unknown.put; + +const Type_Property_Additional_Properties_Is_Record_Unknown_Derived = createServerTests( + `/type/property/additionalProperties/isRecordUnknownDerived`, + { + name: "IsUnknownAdditionalProperties", + index: 314, + age: 2.71875, + prop1: 32, + prop2: true, + prop3: "abc", + }, +); +Scenarios.Type_Property_AdditionalProperties_IsUnknownDerived_get = + Type_Property_Additional_Properties_Is_Record_Unknown_Derived.get; +Scenarios.Type_Property_AdditionalProperties_IsUnknownDerived_put = + Type_Property_Additional_Properties_Is_Record_Unknown_Derived.put; + +const Type_Property_Additional_Properties_Is_Unknown_Discriminated = createServerTests( + `/type/property/additionalProperties/isUnknownDiscriminated`, + { + kind: "derived", + name: "Derived", + index: 314, + age: 2.71875, + prop1: 32, + prop2: true, + prop3: "abc", + }, +); +Scenarios.Type_Property_AdditionalProperties_IsUnknownDiscriminated_get = + Type_Property_Additional_Properties_Is_Unknown_Discriminated.get; +Scenarios.Type_Property_AdditionalProperties_IsUnknownDiscriminated_put = + Type_Property_Additional_Properties_Is_Unknown_Discriminated.put; + +const Type_Property_Additional_Properties_Extends_Record_String = createServerTests( + `/type/property/additionalProperties/extendsRecordString`, + { + name: "ExtendsStringAdditionalProperties", + prop: "abc", + }, +); +Scenarios.Type_Property_AdditionalProperties_ExtendsString_get = + Type_Property_Additional_Properties_Extends_Record_String.get; +Scenarios.Type_Property_AdditionalProperties_ExtendsString_put = + Type_Property_Additional_Properties_Extends_Record_String.put; + +const Type_Property_Additional_Properties_Is_Record_String = createServerTests( + `/type/property/additionalProperties/isRecordstring`, + { + name: "IsStringAdditionalProperties", + prop: "abc", + }, +); +Scenarios.Type_Property_AdditionalProperties_IsString_get = Type_Property_Additional_Properties_Is_Record_String.get; +Scenarios.Type_Property_AdditionalProperties_IsString_put = Type_Property_Additional_Properties_Is_Record_String.put; + +const Type_Property_Additional_Properties_Extends_Record_Float = createServerTests( + `/type/property/additionalProperties/extendsRecordFloat`, + recordFloatBody, +); +Scenarios.Type_Property_AdditionalProperties_ExtendsFloat_get = + Type_Property_Additional_Properties_Extends_Record_Float.get; +Scenarios.Type_Property_AdditionalProperties_ExtendsFloat_put = + Type_Property_Additional_Properties_Extends_Record_Float.put; + +const Type_Property_Additional_Properties_Is_Record_Float = createServerTests( + `/type/property/additionalProperties/isRecordFloat`, + recordFloatBody, +); +Scenarios.Type_Property_AdditionalProperties_IsFloat_get = Type_Property_Additional_Properties_Is_Record_Float.get; +Scenarios.Type_Property_AdditionalProperties_IsFloat_put = Type_Property_Additional_Properties_Is_Record_Float.put; + +const Type_Property_Additional_Properties_Extends_Record_Model = createServerTests( + `/type/property/additionalProperties/extendsRecordModel`, + recordModelBody, +); +Scenarios.Type_Property_AdditionalProperties_ExtendsModel_get = + Type_Property_Additional_Properties_Extends_Record_Model.get; +Scenarios.Type_Property_AdditionalProperties_ExtendsModel_put = + Type_Property_Additional_Properties_Extends_Record_Model.put; + +const Type_Property_Additional_Properties_Is_Record_Model = createServerTests( + `/type/property/additionalProperties/isRecordModel`, + recordModelBody, +); +Scenarios.Type_Property_AdditionalProperties_IsModel_get = Type_Property_Additional_Properties_Is_Record_Model.get; +Scenarios.Type_Property_AdditionalProperties_IsModel_put = Type_Property_Additional_Properties_Is_Record_Model.put; + +const Type_Property_Additional_Properties_Extends_Record_Model_Array = createServerTests( + `/type/property/additionalProperties/extendsRecordModelArray`, + recordModelArrayBody, +); +Scenarios.Type_Property_AdditionalProperties_ExtendsModelArray_get = + Type_Property_Additional_Properties_Extends_Record_Model_Array.get; +Scenarios.Type_Property_AdditionalProperties_ExtendsModelArray_put = + Type_Property_Additional_Properties_Extends_Record_Model_Array.put; + +const Type_Property_Additional_Properties_Is_Record_Model_Array = createServerTests( + `/type/property/additionalProperties/isRecordModelArray`, + recordModelArrayBody, +); +Scenarios.Type_Property_AdditionalProperties_IsModelArray_get = + Type_Property_Additional_Properties_Is_Record_Model_Array.get; +Scenarios.Type_Property_AdditionalProperties_IsModelArray_put = + Type_Property_Additional_Properties_Is_Record_Model_Array.put; + +const Type_Property_Additional_Properties_Spread_Record_String = createServerTests( + `/type/property/additionalProperties/spreadRecordString`, + { + name: "SpreadSpringRecord", + prop: "abc", + }, +); +Scenarios.Type_Property_AdditionalProperties_SpreadString_get = + Type_Property_Additional_Properties_Spread_Record_String.get; +Scenarios.Type_Property_AdditionalProperties_SpreadString_put = + Type_Property_Additional_Properties_Spread_Record_String.put; + +const Type_Property_Additional_Properties_Spread_Record_Float = createServerTests( + `/type/property/additionalProperties/spreadRecordFloat`, + recordFloatBody, +); +Scenarios.Type_Property_AdditionalProperties_SpreadFloat_get = + Type_Property_Additional_Properties_Spread_Record_Float.get; +Scenarios.Type_Property_AdditionalProperties_SpreadFloat_put = + Type_Property_Additional_Properties_Spread_Record_Float.put; + +const Type_Property_Additional_Properties_Spread_Record_Model = createServerTests( + `/type/property/additionalProperties/spreadRecordModel`, + recordModelBody, +); +Scenarios.Type_Property_AdditionalProperties_SpreadModel_get = + Type_Property_Additional_Properties_Spread_Record_Model.get; +Scenarios.Type_Property_AdditionalProperties_SpreadModel_put = + Type_Property_Additional_Properties_Spread_Record_Model.put; + +const Type_Property_Additional_Properties_Spread_Record_Model_Array = createServerTests( + `/type/property/additionalProperties/spreadRecordModelArray`, + recordModelArrayBody, +); +Scenarios.Type_Property_AdditionalProperties_SpreadModelArray_get = + Type_Property_Additional_Properties_Spread_Record_Model_Array.get; +Scenarios.Type_Property_AdditionalProperties_SpreadModelArray_put = + Type_Property_Additional_Properties_Spread_Record_Model_Array.put; + +const Type_Property_Additional_Properties_Spread_Different_Record_String = createServerTests( + `/type/property/additionalProperties/spreadDifferentRecordString`, + differentRecordStringBody, +); +Scenarios.Type_Property_AdditionalProperties_SpreadDifferentString_get = + Type_Property_Additional_Properties_Spread_Different_Record_String.get; +Scenarios.Type_Property_AdditionalProperties_SpreadDifferentString_put = + Type_Property_Additional_Properties_Spread_Different_Record_String.put; + +const Type_Property_Additional_Properties_Spread_Different_Record_Float = createServerTests( + `/type/property/additionalProperties/spreadDifferentRecordFloat`, + differentRecordFloatBody, +); +Scenarios.Type_Property_AdditionalProperties_SpreadDifferentFloat_get = + Type_Property_Additional_Properties_Spread_Different_Record_Float.get; +Scenarios.Type_Property_AdditionalProperties_SpreadDifferentFloat_put = + Type_Property_Additional_Properties_Spread_Different_Record_Float.put; + +const Type_Property_Additional_Properties_Spread_Different_Record_Model = createServerTests( + `/type/property/additionalProperties/spreadDifferentRecordModel`, + differentRecordModelBody, +); +Scenarios.Type_Property_AdditionalProperties_SpreadDifferentModel_get = + Type_Property_Additional_Properties_Spread_Different_Record_Model.get; +Scenarios.Type_Property_AdditionalProperties_SpreadDifferentModel_put = + Type_Property_Additional_Properties_Spread_Different_Record_Model.put; + +const Type_Property_Additional_Properties_Spread_Different_Record_Model_Array = createServerTests( + `/type/property/additionalProperties/spreadDifferentRecordModelArray`, + differentRecordModelArrayBody, +); +Scenarios.Type_Property_AdditionalProperties_SpreadDifferentModelArray_get = + Type_Property_Additional_Properties_Spread_Different_Record_Model_Array.get; +Scenarios.Type_Property_AdditionalProperties_SpreadDifferentModelArray_put = + Type_Property_Additional_Properties_Spread_Different_Record_Model_Array.put; + +const Type_Property_Additional_Properties_Extends_Different_Spread_String = createServerTests( + `/type/property/additionalProperties/extendsDifferentSpreadString`, + extendsModelSpreadStringBody, +); +Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadString_get = + Type_Property_Additional_Properties_Extends_Different_Spread_String.get; +Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadString_put = + Type_Property_Additional_Properties_Extends_Different_Spread_String.put; + +const Type_Property_Additional_Properties_Extends_Different_Spread_Float = createServerTests( + `/type/property/additionalProperties/extendsDifferentSpreadFloat`, + extendsModelSpreadFloatBody, +); +Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadFloat_get = + Type_Property_Additional_Properties_Extends_Different_Spread_Float.get; +Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadFloat_put = + Type_Property_Additional_Properties_Extends_Different_Spread_Float.put; + +const Type_Property_Additional_Properties_Extends_Different_Spread_Model = createServerTests( + `/type/property/additionalProperties/extendsDifferentSpreadModel`, + extendsModelSpreadModelBody, +); +Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadModel_get = + Type_Property_Additional_Properties_Extends_Different_Spread_Model.get; +Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadModel_put = + Type_Property_Additional_Properties_Extends_Different_Spread_Model.put; + +const Type_Property_Additional_Properties_Extends_Different_Spread_Model_Array = createServerTests( + `/type/property/additionalProperties/extendsDifferentSpreadModelArray`, + extendsModelSpreadModelArrayBody, +); +Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadModelArray_get = + Type_Property_Additional_Properties_Extends_Different_Spread_Model_Array.get; +Scenarios.Type_Property_AdditionalProperties_ExtendsDifferentSpreadModelArray_put = + Type_Property_Additional_Properties_Extends_Different_Spread_Model_Array.put; + +const Type_Property_Additional_Properties_Multiple_Spread_Record = createServerTests( + `/type/property/additionalProperties/multipleSpreadRecord`, + multipleSpreadBody, ); -Scenarios.Type_Property_AdditionalProperties_SpreadRecordNonDiscriminatedUnion3_get = passOnSuccess( - recordNonDiscriminatedUnion3.get, +Scenarios.Type_Property_AdditionalProperties_MultipleSpread_get = + Type_Property_Additional_Properties_Multiple_Spread_Record.get; +Scenarios.Type_Property_AdditionalProperties_MultipleSpread_put = + Type_Property_Additional_Properties_Multiple_Spread_Record.put; + +const Type_Property_Additional_Properties_Spread_Record_Union = createServerTests( + `/type/property/additionalProperties/spreadRecordUnion`, + recordUnionBody, ); -Scenarios.Type_Property_AdditionalProperties_SpreadRecordNonDiscriminatedUnion3_put = passOnSuccess( - recordNonDiscriminatedUnion3.put, +Scenarios.Type_Property_AdditionalProperties_SpreadRecordUnion_get = + Type_Property_Additional_Properties_Spread_Record_Union.get; +Scenarios.Type_Property_AdditionalProperties_SpreadRecordUnion_put = + Type_Property_Additional_Properties_Spread_Record_Union.put; + +const Type_Property_Additional_Properties_Spread_Record_Discriminated_Union = createServerTests( + `/type/property/additionalProperties/spreadRecordDiscriminatedUnion`, + recordDiscriminatedUnionBody, +); +Scenarios.Type_Property_AdditionalProperties_SpreadRecordDiscriminatedUnion_get = + Type_Property_Additional_Properties_Spread_Record_Discriminated_Union.get; +Scenarios.Type_Property_AdditionalProperties_SpreadRecordDiscriminatedUnion_put = + Type_Property_Additional_Properties_Spread_Record_Discriminated_Union.put; + +const Type_Property_Additional_Properties_Spread_Record_Non_Discriminated_Union = createServerTests( + `/type/property/additionalProperties/spreadRecordNonDiscriminatedUnion`, + recordDiscriminatedUnionBody, +); +Scenarios.Type_Property_AdditionalProperties_SpreadRecordNonDiscriminatedUnion_get = + Type_Property_Additional_Properties_Spread_Record_Non_Discriminated_Union.get; +Scenarios.Type_Property_AdditionalProperties_SpreadRecordNonDiscriminatedUnion_put = + Type_Property_Additional_Properties_Spread_Record_Non_Discriminated_Union.put; + +const Type_Property_Additional_Properties_Spread_Record_Non_Discriminated_Union2 = createServerTests( + `/type/property/additionalProperties/spreadRecordNonDiscriminatedUnion2`, + recordNonDiscriminatedUnion2Body, +); +Scenarios.Type_Property_AdditionalProperties_SpreadRecordNonDiscriminatedUnion2_get = + Type_Property_Additional_Properties_Spread_Record_Non_Discriminated_Union2.get; +Scenarios.Type_Property_AdditionalProperties_SpreadRecordNonDiscriminatedUnion2_put = + Type_Property_Additional_Properties_Spread_Record_Non_Discriminated_Union2.put; + +const Type_Property_Additional_Properties_Spread_Record_Non_Discriminated_Union3 = createServerTests( + `/type/property/additionalProperties/spreadRecordNonDiscriminatedUnion3`, + recordNonDiscriminatedUnion3Body, ); +Scenarios.Type_Property_AdditionalProperties_SpreadRecordNonDiscriminatedUnion3_get = + Type_Property_Additional_Properties_Spread_Record_Non_Discriminated_Union3.get; +Scenarios.Type_Property_AdditionalProperties_SpreadRecordNonDiscriminatedUnion3_put = + Type_Property_Additional_Properties_Spread_Record_Non_Discriminated_Union3.put; diff --git a/packages/cadl-ranch-specs/http/type/property/nullable/mockapi.ts b/packages/cadl-ranch-specs/http/type/property/nullable/mockapi.ts index c08528c8d..cc3377484 100644 --- a/packages/cadl-ranch-specs/http/type/property/nullable/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/property/nullable/mockapi.ts @@ -1,96 +1,181 @@ -import { passOnSuccess, ScenarioMockApi, mockapi, json, MockApi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ScenarioMockApi, json, MockRequest } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -interface MockApiGetPut { - getNonNull: MockApi; - getNull: MockApi; - patchNonNull: MockApi; - patchNull: MockApi; -} - -/** - * Return the get and put operations - * @param route The route within /type/property/nullable for your function. - * @param value The value you are expecting and will return - */ -function createMockApis(route: string, value: any): MockApiGetPut { - const url = `/type/property/nullable/${route}`; - const nonNullUrl = `${url}/non-null`; - const nullUrl = `${url}/null`; - const nonNullBody = { requiredProperty: "foo", nullableProperty: value }; - const nullBody = { requiredProperty: "foo", nullableProperty: null }; - const getNonNull = mockapi.get(nonNullUrl, (req) => { - return { - status: 200, - body: json(nonNullBody), - }; - }); - const getNull = mockapi.get(nullUrl, (req) => { - return { - status: 200, - body: json(nullBody), - }; - }); - const patchNonNull = mockapi.patch(nonNullUrl, (req) => { - const expectedBody = JSON.parse(JSON.stringify(nonNullBody)); // deep clone - req.expect.coercedBodyEquals(expectedBody); - return { - status: 204, - }; - }); - const patchNull = mockapi.patch(nullUrl, (req) => { - req.expect.bodyEquals(nullBody); - return { - status: 204, - }; - }); +function createServerTests(url: string, value: unknown, patchNullableProperty?: any) { return { - getNonNull: getNonNull, - getNull: getNull, - patchNonNull: patchNonNull, - patchNull: patchNull, + get: passOnSuccess({ + uri: url, + method: `get`, + request: {}, + response: { + status: 200, + body: json(value), + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: json(value), + }; + }, + kind: "MockApiDefinition", + }), + patch: passOnSuccess({ + uri: url, + method: `patch`, + request: { + body: { + requiredProperty: "foo", + nullableProperty: patchNullableProperty || null, + }, + headers: { + "Content-Type": "application/merge-patch+json", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals({ + requiredProperty: "foo", + nullableProperty: patchNullableProperty || null, + }); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", + }), }; } -const stringMock = createMockApis("string", "hello"); -Scenarios.Type_Property_Nullable_String_getNonNull = passOnSuccess(stringMock.getNonNull); -Scenarios.Type_Property_Nullable_String_getNull = passOnSuccess(stringMock.getNull); -Scenarios.Type_Property_Nullable_String_patchNonNull = passOnSuccess(stringMock.patchNonNull); -Scenarios.Type_Property_Nullable_String_patchNull = passOnSuccess(stringMock.patchNull); +const Type_Property_Nullable_String_Null = createServerTests(`/type/property/nullable/string/null`, { + requiredProperty: "foo", + nullableProperty: null, +}); +const Type_Property_Nullable_String_Non_Null = createServerTests( + `/type/property/nullable/string/non-null`, + { + requiredProperty: "foo", + nullableProperty: "hello", + }, + "hello", +); + +Scenarios.Type_Property_Nullable_String_getNonNull = Type_Property_Nullable_String_Non_Null.get; +Scenarios.Type_Property_Nullable_String_getNull = Type_Property_Nullable_String_Null.get; +Scenarios.Type_Property_Nullable_String_patchNonNull = Type_Property_Nullable_String_Non_Null.patch; +Scenarios.Type_Property_Nullable_String_patchNull = Type_Property_Nullable_String_Null.patch; -const bytesMock = createMockApis("bytes", "aGVsbG8sIHdvcmxkIQ=="); -Scenarios.Type_Property_Nullable_Bytes_getNonNull = passOnSuccess(bytesMock.getNonNull); -Scenarios.Type_Property_Nullable_Bytes_getNull = passOnSuccess(bytesMock.getNull); -Scenarios.Type_Property_Nullable_Bytes_patchNonNull = passOnSuccess(bytesMock.patchNonNull); -Scenarios.Type_Property_Nullable_Bytes_patchNull = passOnSuccess(bytesMock.patchNull); +const Type_Property_Nullable_Bytes_Null = createServerTests(`/type/property/nullable/bytes/null`, { + requiredProperty: "foo", + nullableProperty: null, +}); +const Type_Property_Nullable_Bytes_Non_Null = createServerTests( + `/type/property/nullable/bytes/non-null`, + { + requiredProperty: "foo", + nullableProperty: "aGVsbG8sIHdvcmxkIQ==", + }, + "aGVsbG8sIHdvcmxkIQ==", +); +Scenarios.Type_Property_Nullable_Bytes_getNonNull = Type_Property_Nullable_Bytes_Non_Null.get; +Scenarios.Type_Property_Nullable_Bytes_getNull = Type_Property_Nullable_Bytes_Null.get; +Scenarios.Type_Property_Nullable_Bytes_patchNonNull = Type_Property_Nullable_Bytes_Non_Null.patch; +Scenarios.Type_Property_Nullable_Bytes_patchNull = Type_Property_Nullable_Bytes_Null.patch; -const datetimeMock = createMockApis("datetime", "2022-08-26T18:38:00Z"); -Scenarios.Type_Property_Nullable_Datetime_getNonNull = passOnSuccess(datetimeMock.getNonNull); -Scenarios.Type_Property_Nullable_Datetime_getNull = passOnSuccess(datetimeMock.getNull); -Scenarios.Type_Property_Nullable_Datetime_patchNonNull = passOnSuccess(datetimeMock.patchNonNull); -Scenarios.Type_Property_Nullable_Datetime_patchNull = passOnSuccess(datetimeMock.patchNull); +const Type_Property_Nullable_DateTime_Null = createServerTests(`/type/property/nullable/datetime/null`, { + requiredProperty: "foo", + nullableProperty: null, +}); +const Type_Property_Nullable_DateTime_Non_Null = createServerTests( + `/type/property/nullable/datetime/non-null`, + { + requiredProperty: "foo", + nullableProperty: "2022-08-26T18:38:00Z", + }, + "2022-08-26T18:38:00Z", +); +Scenarios.Type_Property_Nullable_Datetime_getNonNull = Type_Property_Nullable_DateTime_Non_Null.get; +Scenarios.Type_Property_Nullable_Datetime_getNull = Type_Property_Nullable_DateTime_Null.get; +Scenarios.Type_Property_Nullable_Datetime_patchNonNull = Type_Property_Nullable_DateTime_Non_Null.patch; +Scenarios.Type_Property_Nullable_Datetime_patchNull = Type_Property_Nullable_DateTime_Null.patch; -const durationMock = createMockApis("duration", "P123DT22H14M12.011S"); -Scenarios.Type_Property_Nullable_Duration_getNonNull = passOnSuccess(durationMock.getNonNull); -Scenarios.Type_Property_Nullable_Duration_getNull = passOnSuccess(durationMock.getNull); -Scenarios.Type_Property_Nullable_Duration_patchNonNull = passOnSuccess(durationMock.patchNonNull); -Scenarios.Type_Property_Nullable_Duration_patchNull = passOnSuccess(durationMock.patchNull); +const Type_Property_Nullable_Duration_Null = createServerTests(`/type/property/nullable/duration/null`, { + requiredProperty: "foo", + nullableProperty: null, +}); +const Type_Property_Nullable_Duration_Non_Null = createServerTests( + `/type/property/nullable/duration/non-null`, + { + requiredProperty: "foo", + nullableProperty: "P123DT22H14M12.011S", + }, + "P123DT22H14M12.011S", +); +Scenarios.Type_Property_Nullable_Duration_getNonNull = Type_Property_Nullable_Duration_Non_Null.get; +Scenarios.Type_Property_Nullable_Duration_getNull = Type_Property_Nullable_Duration_Null.get; +Scenarios.Type_Property_Nullable_Duration_patchNonNull = Type_Property_Nullable_Duration_Non_Null.patch; +Scenarios.Type_Property_Nullable_Duration_patchNull = Type_Property_Nullable_Duration_Null.patch; -const collectionsBytesMock = createMockApis("collections/bytes", ["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="]); -Scenarios.Type_Property_Nullable_CollectionsByte_getNonNull = passOnSuccess(collectionsBytesMock.getNonNull); -Scenarios.Type_Property_Nullable_CollectionsByte_getNull = passOnSuccess(collectionsBytesMock.getNull); -Scenarios.Type_Property_Nullable_CollectionsByte_patchNonNull = passOnSuccess(collectionsBytesMock.patchNonNull); -Scenarios.Type_Property_Nullable_CollectionsByte_patchNull = passOnSuccess(collectionsBytesMock.patchNull); +const Type_Property_Nullable_Collections_Bytes_Null = createServerTests( + `/type/property/nullable/collections/bytes/null`, + { + requiredProperty: "foo", + nullableProperty: null, + }, +); +const Type_Property_Nullable_Collections_Bytes_Non_Null = createServerTests( + `/type/property/nullable/collections/bytes/non-null`, + { + requiredProperty: "foo", + nullableProperty: ["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="], + }, + ["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="], +); +Scenarios.Type_Property_Nullable_CollectionsByte_getNonNull = Type_Property_Nullable_Collections_Bytes_Non_Null.get; +Scenarios.Type_Property_Nullable_CollectionsByte_getNull = Type_Property_Nullable_Collections_Bytes_Null.get; +Scenarios.Type_Property_Nullable_CollectionsByte_patchNonNull = Type_Property_Nullable_Collections_Bytes_Non_Null.patch; +Scenarios.Type_Property_Nullable_CollectionsByte_patchNull = Type_Property_Nullable_Collections_Bytes_Null.patch; -const collectionsModelMock = createMockApis("collections/model", [{ property: "hello" }, { property: "world" }]); -Scenarios.Type_Property_Nullable_CollectionsModel_getNonNull = passOnSuccess(collectionsModelMock.getNonNull); -Scenarios.Type_Property_Nullable_CollectionsModel_getNull = passOnSuccess(collectionsModelMock.getNull); -Scenarios.Type_Property_Nullable_CollectionsModel_patchNonNull = passOnSuccess(collectionsModelMock.patchNonNull); -Scenarios.Type_Property_Nullable_CollectionsModel_patchNull = passOnSuccess(collectionsModelMock.patchNull); +const Type_Property_Nullable_Collections_Model_Null = createServerTests( + `/type/property/nullable/collections/model/null`, + { + requiredProperty: "foo", + nullableProperty: null, + }, +); +const Type_Property_Nullable_Collections_Model_Non_Null = createServerTests( + `/type/property/nullable/collections/model/non-null`, + { + requiredProperty: "foo", + nullableProperty: [{ property: "hello" }, { property: "world" }], + }, + [{ property: "hello" }, { property: "world" }], +); +Scenarios.Type_Property_Nullable_CollectionsModel_getNonNull = Type_Property_Nullable_Collections_Model_Non_Null.get; +Scenarios.Type_Property_Nullable_CollectionsModel_getNull = Type_Property_Nullable_Collections_Model_Null.get; +Scenarios.Type_Property_Nullable_CollectionsModel_patchNonNull = + Type_Property_Nullable_Collections_Model_Non_Null.patch; +Scenarios.Type_Property_Nullable_CollectionsModel_patchNull = Type_Property_Nullable_Collections_Model_Null.patch; -const collectionsStringMock = createMockApis("collections/string", ["hello", "world"]); -Scenarios.Type_Property_Nullable_CollectionsString_getNonNull = passOnSuccess(collectionsStringMock.getNonNull); -Scenarios.Type_Property_Nullable_CollectionsString_getNull = passOnSuccess(collectionsStringMock.getNull); -Scenarios.Type_Property_Nullable_CollectionsString_patchNonNull = passOnSuccess(collectionsStringMock.patchNonNull); -Scenarios.Type_Property_Nullable_CollectionsString_patchNull = passOnSuccess(collectionsStringMock.patchNull); +const Type_Property_Nullable_Collections_String_Null = createServerTests( + `/type/property/nullable/collections/string/null`, + { + requiredProperty: "foo", + nullableProperty: null, + }, +); +const Type_Property_Nullable_Collections_String_Non_Null = createServerTests( + `/type/property/nullable/collections/string/non-null`, + { + requiredProperty: "foo", + nullableProperty: ["hello", "world"], + }, + ["hello", "world"], +); +Scenarios.Type_Property_Nullable_CollectionsString_getNonNull = Type_Property_Nullable_Collections_String_Non_Null.get; +Scenarios.Type_Property_Nullable_CollectionsString_getNull = Type_Property_Nullable_Collections_String_Null.get; +Scenarios.Type_Property_Nullable_CollectionsString_patchNonNull = + Type_Property_Nullable_Collections_String_Non_Null.patch; +Scenarios.Type_Property_Nullable_CollectionsString_patchNull = Type_Property_Nullable_Collections_String_Null.patch; diff --git a/packages/cadl-ranch-specs/http/type/property/optionality/mockapi.ts b/packages/cadl-ranch-specs/http/type/property/optionality/mockapi.ts index fa8997ae3..ba4b77390 100644 --- a/packages/cadl-ranch-specs/http/type/property/optionality/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/property/optionality/mockapi.ts @@ -1,190 +1,229 @@ -import { passOnSuccess, ScenarioMockApi, mockapi, json, MockApi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ScenarioMockApi, json, MockRequest } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -interface MockApiGetPut { - getAll: MockApi; - getDefault: MockApi; - putAll: MockApi; - putDefault: MockApi; -} - -/** - * Return the get and put operations - * @param route The route within /models/properties/optional/all/ for your function. - * @param value The value you are expecting and will return - */ -function createMockApis(route: string, value: any): MockApiGetPut { - const url = `/type/property/optional/${route}`; - const allUrl = `${url}/all`; - const defaultUrl = `${url}/default`; - const allBody = { property: value }; - const defaultBody = {}; - const getAll = mockapi.get(allUrl, (req) => { - return { - status: 200, - body: json(allBody), - }; - }); - const getDefault = mockapi.get(defaultUrl, (req) => { - return { - status: 200, - body: json(defaultBody), - }; - }); - const putAll = mockapi.put(allUrl, (req) => { - const expectedBody = JSON.parse(JSON.stringify(allBody)); // deep clone - req.expect.coercedBodyEquals(expectedBody); - return { - status: 204, - }; - }); - const putDefault = mockapi.put(defaultUrl, (req) => { - req.expect.bodyEquals(defaultBody); - return { - status: 204, - }; - }); +function createServerTests(url: string, value: unknown) { return { - getAll: getAll, - getDefault: getDefault, - putAll: putAll, - putDefault: putDefault, + get: passOnSuccess({ + uri: url, + method: `get`, + request: {}, + response: { + status: 200, + body: json(value), + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: json(value), + }; + }, + kind: "MockApiDefinition", + }), + put: passOnSuccess({ + uri: url, + method: `put`, + request: { + body: value, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals(value); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", + }), }; } -const stringMock = createMockApis("string", "hello"); -Scenarios.Type_Property_Optional_String_getAll = passOnSuccess(stringMock.getAll); -Scenarios.Type_Property_Optional_String_getDefault = passOnSuccess(stringMock.getDefault); -Scenarios.Type_Property_Optional_String_putAll = passOnSuccess(stringMock.putAll); -Scenarios.Type_Property_Optional_String_putDefault = passOnSuccess(stringMock.putDefault); - -const bytesMock = createMockApis("bytes", "aGVsbG8sIHdvcmxkIQ=="); -Scenarios.Type_Property_Optional_Bytes_getAll = passOnSuccess(bytesMock.getAll); -Scenarios.Type_Property_Optional_Bytes_getDefault = passOnSuccess(bytesMock.getDefault); -Scenarios.Type_Property_Optional_Bytes_putAll = passOnSuccess(bytesMock.putAll); -Scenarios.Type_Property_Optional_Bytes_putDefault = passOnSuccess(bytesMock.putDefault); - -const datetimeMock = createMockApis("datetime", "2022-08-26T18:38:00Z"); -Scenarios.Type_Property_Optional_Datetime_getAll = passOnSuccess(datetimeMock.getAll); -Scenarios.Type_Property_Optional_Datetime_getDefault = passOnSuccess(datetimeMock.getDefault); -Scenarios.Type_Property_Optional_Datetime_putAll = passOnSuccess(datetimeMock.putAll); -Scenarios.Type_Property_Optional_Datetime_putDefault = passOnSuccess(datetimeMock.putDefault); - -const durationMock = createMockApis("duration", "P123DT22H14M12.011S"); -Scenarios.Type_Property_Optional_Duration_getAll = passOnSuccess(durationMock.getAll); -Scenarios.Type_Property_Optional_Duration_getDefault = passOnSuccess(durationMock.getDefault); -Scenarios.Type_Property_Optional_Duration_putAll = passOnSuccess(durationMock.putAll); -Scenarios.Type_Property_Optional_Duration_putDefault = passOnSuccess(durationMock.putDefault); - -const plainDateMock = createMockApis("plainDate", "2022-12-12"); -Scenarios.Type_Property_Optional_PlainDate_getAll = passOnSuccess(plainDateMock.getAll); -Scenarios.Type_Property_Optional_PlainDate_getDefault = passOnSuccess(plainDateMock.getDefault); -Scenarios.Type_Property_Optional_PlainDate_putAll = passOnSuccess(plainDateMock.putAll); -Scenarios.Type_Property_Optional_PlainDate_putDefault = passOnSuccess(plainDateMock.putDefault); - -const plainTimeMock = createMockApis("plainTime", "13:06:12"); -Scenarios.Type_Property_Optional_PlainTime_getAll = passOnSuccess(plainTimeMock.getAll); -Scenarios.Type_Property_Optional_PlainTime_getDefault = passOnSuccess(plainTimeMock.getDefault); -Scenarios.Type_Property_Optional_PlainTime_putAll = passOnSuccess(plainTimeMock.putAll); -Scenarios.Type_Property_Optional_PlainTime_putDefault = passOnSuccess(plainTimeMock.putDefault); - -const collectionsBytesMock = createMockApis("collections/bytes", ["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="]); -Scenarios.Type_Property_Optional_CollectionsByte_getAll = passOnSuccess(collectionsBytesMock.getAll); -Scenarios.Type_Property_Optional_CollectionsByte_getDefault = passOnSuccess(collectionsBytesMock.getDefault); -Scenarios.Type_Property_Optional_CollectionsByte_putAll = passOnSuccess(collectionsBytesMock.putAll); -Scenarios.Type_Property_Optional_CollectionsByte_putDefault = passOnSuccess(collectionsBytesMock.putDefault); - -const collectionsModelMock = createMockApis("collections/model", [{ property: "hello" }, { property: "world" }]); -Scenarios.Type_Property_Optional_CollectionsModel_getAll = passOnSuccess(collectionsModelMock.getAll); -Scenarios.Type_Property_Optional_CollectionsModel_getDefault = passOnSuccess(collectionsModelMock.getDefault); -Scenarios.Type_Property_Optional_CollectionsModel_putAll = passOnSuccess(collectionsModelMock.putAll); -Scenarios.Type_Property_Optional_CollectionsModel_putDefault = passOnSuccess(collectionsModelMock.putDefault); - -const stringLiteralMock = createMockApis("string/literal", "hello"); -Scenarios.Type_Property_Optional_StringLiteral_getAll = passOnSuccess(stringLiteralMock.getAll); -Scenarios.Type_Property_Optional_StringLiteral_getDefault = passOnSuccess(stringLiteralMock.getDefault); -Scenarios.Type_Property_Optional_StringLiteral_putAll = passOnSuccess(stringLiteralMock.putAll); -Scenarios.Type_Property_Optional_StringLiteral_putDefault = passOnSuccess(stringLiteralMock.putDefault); - -const intLiteralMock = createMockApis("int/literal", 1); -Scenarios.Type_Property_Optional_IntLiteral_getAll = passOnSuccess(intLiteralMock.getAll); -Scenarios.Type_Property_Optional_IntLiteral_getDefault = passOnSuccess(intLiteralMock.getDefault); -Scenarios.Type_Property_Optional_IntLiteral_putAll = passOnSuccess(intLiteralMock.putAll); -Scenarios.Type_Property_Optional_IntLiteral_putDefault = passOnSuccess(intLiteralMock.putDefault); - -const floatLiteralMock = createMockApis("float/literal", 1.25); -Scenarios.Type_Property_Optional_FloatLiteral_getAll = passOnSuccess(floatLiteralMock.getAll); -Scenarios.Type_Property_Optional_FloatLiteral_getDefault = passOnSuccess(floatLiteralMock.getDefault); -Scenarios.Type_Property_Optional_FloatLiteral_putAll = passOnSuccess(floatLiteralMock.putAll); -Scenarios.Type_Property_Optional_FloatLiteral_putDefault = passOnSuccess(floatLiteralMock.putDefault); - -const booleanLiteralMock = createMockApis("boolean/literal", true); -Scenarios.Type_Property_Optional_BooleanLiteral_getAll = passOnSuccess(booleanLiteralMock.getAll); -Scenarios.Type_Property_Optional_BooleanLiteral_getDefault = passOnSuccess(booleanLiteralMock.getDefault); -Scenarios.Type_Property_Optional_BooleanLiteral_putAll = passOnSuccess(booleanLiteralMock.putAll); -Scenarios.Type_Property_Optional_BooleanLiteral_putDefault = passOnSuccess(booleanLiteralMock.putDefault); - -const unionStringLiteralMock = createMockApis("union/string/literal", "world"); -Scenarios.Type_Property_Optional_UnionStringLiteral_getAll = passOnSuccess(unionStringLiteralMock.getAll); -Scenarios.Type_Property_Optional_UnionStringLiteral_getDefault = passOnSuccess(unionStringLiteralMock.getDefault); -Scenarios.Type_Property_Optional_UnionStringLiteral_putAll = passOnSuccess(unionStringLiteralMock.putAll); -Scenarios.Type_Property_Optional_UnionStringLiteral_putDefault = passOnSuccess(unionStringLiteralMock.putDefault); - -const unionIntLiteralMock = createMockApis("union/int/literal", 2); -Scenarios.Type_Property_Optional_UnionIntLiteral_getAll = passOnSuccess(unionIntLiteralMock.getAll); -Scenarios.Type_Property_Optional_UnionIntLiteral_getDefault = passOnSuccess(unionIntLiteralMock.getDefault); -Scenarios.Type_Property_Optional_UnionIntLiteral_putAll = passOnSuccess(unionIntLiteralMock.putAll); -Scenarios.Type_Property_Optional_UnionIntLiteral_putDefault = passOnSuccess(unionIntLiteralMock.putDefault); - -const unionFloatLiteralMock = createMockApis("union/float/literal", 2.375); -Scenarios.Type_Property_Optional_UnionFloatLiteral_getAll = passOnSuccess(unionFloatLiteralMock.getAll); -Scenarios.Type_Property_Optional_UnionFloatLiteral_getDefault = passOnSuccess(unionFloatLiteralMock.getDefault); -Scenarios.Type_Property_Optional_UnionFloatLiteral_putAll = passOnSuccess(unionFloatLiteralMock.putAll); -Scenarios.Type_Property_Optional_UnionFloatLiteral_putDefault = passOnSuccess(unionFloatLiteralMock.putDefault); - -// TEST REQUIRED AND OPTIONAL PROPERTIES - -const requiredAndOptionalBaseUrl = `/type/property/optional/requiredAndOptional`; -Scenarios.Type_Property_Optional_RequiredAndOptional_getAll = passOnSuccess( - mockapi.get(`${requiredAndOptionalBaseUrl}/all`, (req) => { - return { - status: 200, - body: json({ - optionalProperty: "hello", - requiredProperty: 42, - }), - }; - }), +const Type_Property_Optional_String_Default = createServerTests(`/type/property/optional/string/default`, {}); +const Type_Property_Optional_String_All = createServerTests(`/type/property/optional/string/all`, { + property: "hello", +}); +Scenarios.Type_Property_Optional_String_getDefault = Type_Property_Optional_String_Default.get; +Scenarios.Type_Property_Optional_String_putDefault = Type_Property_Optional_String_Default.put; +Scenarios.Type_Property_Optional_String_getAll = Type_Property_Optional_String_All.get; +Scenarios.Type_Property_Optional_String_putAll = Type_Property_Optional_String_All.put; + +const Type_Property_Optional_Bytes_Default = createServerTests(`/type/property/optional/bytes/default`, {}); +const Type_Property_Optional_Bytes_All = createServerTests(`/type/property/optional/bytes/all`, { + property: "aGVsbG8sIHdvcmxkIQ==", +}); +Scenarios.Type_Property_Optional_Bytes_getDefault = Type_Property_Optional_Bytes_Default.get; +Scenarios.Type_Property_Optional_Bytes_putDefault = Type_Property_Optional_Bytes_Default.put; +Scenarios.Type_Property_Optional_Bytes_getAll = Type_Property_Optional_Bytes_All.get; +Scenarios.Type_Property_Optional_Bytes_putAll = Type_Property_Optional_Bytes_All.put; + +const Type_Property_Optional_DateTime_Default = createServerTests(`/type/property/optional/datetime/default`, {}); +const Type_Property_Optional_DateTime_All = createServerTests(`/type/property/optional/datetime/all`, { + property: "2022-08-26T18:38:00Z", +}); +Scenarios.Type_Property_Optional_Datetime_getDefault = Type_Property_Optional_DateTime_Default.get; +Scenarios.Type_Property_Optional_Datetime_putDefault = Type_Property_Optional_DateTime_Default.put; +Scenarios.Type_Property_Optional_Datetime_getAll = Type_Property_Optional_DateTime_All.get; +Scenarios.Type_Property_Optional_Datetime_putAll = Type_Property_Optional_DateTime_All.put; + +const Type_Property_Optional_Duration_Default = createServerTests(`/type/property/optional/duration/default`, {}); +const Type_Property_Optional_Duration_All = createServerTests(`/type/property/optional/duration/all`, { + property: "P123DT22H14M12.011S", +}); + +Scenarios.Type_Property_Optional_Duration_getDefault = Type_Property_Optional_Duration_Default.get; +Scenarios.Type_Property_Optional_Duration_putDefault = Type_Property_Optional_Duration_Default.put; +Scenarios.Type_Property_Optional_Duration_getAll = Type_Property_Optional_Duration_All.get; +Scenarios.Type_Property_Optional_Duration_putAll = Type_Property_Optional_Duration_All.put; + +const Type_Property_Optional_PlainDate_Default = createServerTests(`/type/property/optional/plainDate/default`, {}); +const Type_Property_Optional_PlainDate_All = createServerTests(`/type/property/optional/plainDate/all`, { + property: "2022-12-12", +}); + +Scenarios.Type_Property_Optional_PlainDate_getDefault = Type_Property_Optional_PlainDate_Default.get; +Scenarios.Type_Property_Optional_PlainDate_putDefault = Type_Property_Optional_PlainDate_Default.put; +Scenarios.Type_Property_Optional_PlainDate_getAll = Type_Property_Optional_PlainDate_All.get; +Scenarios.Type_Property_Optional_PlainDate_putAll = Type_Property_Optional_PlainDate_All.put; + +const Type_Property_Optional_PlainTime_Default = createServerTests(`/type/property/optional/plainTime/default`, {}); +const Type_Property_Optional_PlainTime_All = createServerTests(`/type/property/optional/plainTime/all`, { + property: "13:06:12", +}); +Scenarios.Type_Property_Optional_PlainTime_getDefault = Type_Property_Optional_PlainTime_Default.get; +Scenarios.Type_Property_Optional_PlainTime_putDefault = Type_Property_Optional_PlainTime_Default.put; +Scenarios.Type_Property_Optional_PlainTime_getAll = Type_Property_Optional_PlainTime_All.get; +Scenarios.Type_Property_Optional_PlainTime_putAll = Type_Property_Optional_PlainTime_All.put; + +const Type_Property_Optional_Collections_Bytes_Default = createServerTests( + `/type/property/optional/collections/bytes/default`, + {}, +); +const Type_Property_Optional_Collections_Bytes_All = createServerTests( + `/type/property/optional/collections/bytes/all`, + { property: ["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="] }, +); + +Scenarios.Type_Property_Optional_CollectionsByte_getDefault = Type_Property_Optional_Collections_Bytes_Default.get; +Scenarios.Type_Property_Optional_CollectionsByte_putDefault = Type_Property_Optional_Collections_Bytes_Default.put; +Scenarios.Type_Property_Optional_CollectionsByte_getAll = Type_Property_Optional_Collections_Bytes_All.get; +Scenarios.Type_Property_Optional_CollectionsByte_putAll = Type_Property_Optional_Collections_Bytes_All.put; + +const Type_Property_Optional_Collections_Model_Default = createServerTests( + `/type/property/optional/collections/model/default`, + {}, +); +const Type_Property_Optional_Collections_Model_All = createServerTests( + `/type/property/optional/collections/model/all`, + { property: [{ property: "hello" }, { property: "world" }] }, +); +Scenarios.Type_Property_Optional_CollectionsModel_getDefault = Type_Property_Optional_Collections_Model_Default.get; +Scenarios.Type_Property_Optional_CollectionsModel_putDefault = Type_Property_Optional_Collections_Model_Default.put; +Scenarios.Type_Property_Optional_CollectionsModel_getAll = Type_Property_Optional_Collections_Model_All.get; +Scenarios.Type_Property_Optional_CollectionsModel_putAll = Type_Property_Optional_Collections_Model_All.put; + +const Type_Property_Optional_String_Literal_Default = createServerTests( + `/type/property/optional/string/literal/default`, + {}, +); +const Type_Property_Optional_String_Literal_All = createServerTests(`/type/property/optional/string/literal/all`, { + property: "hello", +}); +Scenarios.Type_Property_Optional_StringLiteral_getDefault = Type_Property_Optional_String_Literal_Default.get; +Scenarios.Type_Property_Optional_StringLiteral_putDefault = Type_Property_Optional_String_Literal_Default.put; +Scenarios.Type_Property_Optional_StringLiteral_getAll = Type_Property_Optional_String_Literal_All.get; +Scenarios.Type_Property_Optional_StringLiteral_putAll = Type_Property_Optional_String_Literal_All.put; + +const Type_Property_Optional_Int_Literal_Default = createServerTests(`/type/property/optional/int/literal/default`, {}); +const Type_Property_Optional_Int_Literal_All = createServerTests(`/type/property/optional/int/literal/all`, { + property: 1, +}); +Scenarios.Type_Property_Optional_IntLiteral_getDefault = Type_Property_Optional_Int_Literal_Default.get; +Scenarios.Type_Property_Optional_IntLiteral_putDefault = Type_Property_Optional_Int_Literal_Default.put; +Scenarios.Type_Property_Optional_IntLiteral_getAll = Type_Property_Optional_Int_Literal_All.get; +Scenarios.Type_Property_Optional_IntLiteral_putAll = Type_Property_Optional_Int_Literal_All.put; + +const Type_Property_Optional_Float_Literal_Default = createServerTests( + `/type/property/optional/float/literal/default`, + {}, +); +const Type_Property_Optional_Float_Literal_All = createServerTests(`/type/property/optional/float/literal/all`, { + property: 1.25, +}); +Scenarios.Type_Property_Optional_FloatLiteral_getDefault = Type_Property_Optional_Float_Literal_Default.get; +Scenarios.Type_Property_Optional_FloatLiteral_putDefault = Type_Property_Optional_Float_Literal_Default.put; +Scenarios.Type_Property_Optional_FloatLiteral_getAll = Type_Property_Optional_Float_Literal_All.get; +Scenarios.Type_Property_Optional_FloatLiteral_putAll = Type_Property_Optional_Float_Literal_All.put; + +const Type_Property_Optional_Boolean_Literal_Default = createServerTests( + `/type/property/optional/boolean/literal/default`, + {}, +); +const Type_Property_Optional_Boolean_Literal_All = createServerTests(`/type/property/optional/boolean/literal/all`, { + property: true, +}); +Scenarios.Type_Property_Optional_BooleanLiteral_getDefault = Type_Property_Optional_Boolean_Literal_Default.get; +Scenarios.Type_Property_Optional_BooleanLiteral_putDefault = Type_Property_Optional_Boolean_Literal_Default.put; +Scenarios.Type_Property_Optional_BooleanLiteral_getAll = Type_Property_Optional_Boolean_Literal_All.get; +Scenarios.Type_Property_Optional_BooleanLiteral_putAll = Type_Property_Optional_Boolean_Literal_All.put; + +const Type_Property_Optional_Union_String_Literal_Default = createServerTests( + `/type/property/optional/union/string/literal/default`, + {}, +); +const Type_Property_Optional_Union_String_Literal_All = createServerTests( + `/type/property/optional/union/string/literal/all`, + { property: "world" }, +); +Scenarios.Type_Property_Optional_UnionStringLiteral_getDefault = + Type_Property_Optional_Union_String_Literal_Default.get; +Scenarios.Type_Property_Optional_UnionStringLiteral_putDefault = + Type_Property_Optional_Union_String_Literal_Default.put; +Scenarios.Type_Property_Optional_UnionStringLiteral_getAll = Type_Property_Optional_Union_String_Literal_All.get; +Scenarios.Type_Property_Optional_UnionStringLiteral_putAll = Type_Property_Optional_Union_String_Literal_All.put; + +const Type_Property_Optional_Union_Int_Literal_Default = createServerTests( + `/type/property/optional/union/int/literal/default`, + {}, +); +const Type_Property_Optional_Union_Int_Literal_All = createServerTests( + `/type/property/optional/union/int/literal/all`, + { property: 2 }, +); +Scenarios.Type_Property_Optional_UnionIntLiteral_getDefault = Type_Property_Optional_Union_Int_Literal_Default.get; +Scenarios.Type_Property_Optional_UnionIntLiteral_putDefault = Type_Property_Optional_Union_Int_Literal_Default.put; +Scenarios.Type_Property_Optional_UnionIntLiteral_getAll = Type_Property_Optional_Union_Int_Literal_All.get; +Scenarios.Type_Property_Optional_UnionIntLiteral_putAll = Type_Property_Optional_Union_Int_Literal_All.put; + +const Type_Property_Optional_Union_Float_Literal_Default = createServerTests( + `/type/property/optional/union/float/literal/default`, + {}, ); -Scenarios.Type_Property_Optional_RequiredAndOptional_getRequiredOnly = passOnSuccess( - mockapi.get(`${requiredAndOptionalBaseUrl}/requiredOnly`, (req) => { - return { - status: 200, - body: json({ - requiredProperty: 42, - }), - }; - }), +const Type_Property_Optional_Union_Float_Literal_All = createServerTests( + `/type/property/optional/union/float/literal/all`, + { property: 2.375 }, ); -Scenarios.Type_Property_Optional_RequiredAndOptional_putAll = passOnSuccess( - mockapi.put(`${requiredAndOptionalBaseUrl}/all`, (req) => { - req.expect.bodyEquals({ - optionalProperty: "hello", - requiredProperty: 42, - }); - return { - status: 204, - }; - }), +Scenarios.Type_Property_Optional_UnionFloatLiteral_getDefault = Type_Property_Optional_Union_Float_Literal_Default.get; +Scenarios.Type_Property_Optional_UnionFloatLiteral_putDefault = Type_Property_Optional_Union_Float_Literal_Default.put; +Scenarios.Type_Property_Optional_UnionFloatLiteral_getAll = Type_Property_Optional_Union_Float_Literal_All.get; +Scenarios.Type_Property_Optional_UnionFloatLiteral_putAll = Type_Property_Optional_Union_Float_Literal_All.put; + +const Type_Property_Optional_Required_And_Optional_RequiredOnly = createServerTests( + `/type/property/optional/requiredAndOptional/requiredOnly`, + { requiredProperty: 42 }, ); -Scenarios.Type_Property_Optional_RequiredAndOptional_putRequiredOnly = passOnSuccess( - mockapi.put(`${requiredAndOptionalBaseUrl}/requiredOnly`, (req) => { - req.expect.bodyEquals({ - requiredProperty: 42, - }); - return { - status: 204, - }; - }), +Scenarios.Type_Property_Optional_RequiredAndOptional_getRequiredOnly = + Type_Property_Optional_Required_And_Optional_RequiredOnly.get; +Scenarios.Type_Property_Optional_RequiredAndOptional_putRequiredOnly = + Type_Property_Optional_Required_And_Optional_RequiredOnly.put; + +const Type_Property_Optional_Required_And_Optional_All = createServerTests( + `/type/property/optional/requiredAndOptional/all`, + { + optionalProperty: "hello", + requiredProperty: 42, + }, ); +Scenarios.Type_Property_Optional_RequiredAndOptional_getAll = Type_Property_Optional_Required_And_Optional_All.get; +Scenarios.Type_Property_Optional_RequiredAndOptional_putAll = Type_Property_Optional_Required_And_Optional_All.put; diff --git a/packages/cadl-ranch-specs/http/type/property/value-types/mockapi.ts b/packages/cadl-ranch-specs/http/type/property/value-types/mockapi.ts index 6a215e8e7..595edfdf9 100644 --- a/packages/cadl-ranch-specs/http/type/property/value-types/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/property/value-types/mockapi.ts @@ -1,149 +1,229 @@ -import { passOnSuccess, ScenarioMockApi, mockapi, json, MockApi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, ScenarioMockApi, json, MockRequest } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -interface MockApiGetPut { - get: MockApi; - put: MockApi; -} +function createServerTests(url: string, data: unknown, convertedToFn?: (_: any) => any) { + let property; + if (convertedToFn) { + property = convertedToFn(data); + } else { + property = data; + } -/** - * Return the get and put operations - * @param route The route within /models/properties for your function. - * @param value The value you are expecting and will return. - */ -function createMockApis(route: string, value: any): MockApiGetPut { - const url = `/type/property/value-types/${route}`; - const body = { property: value }; return { - get: mockapi.get(url, (req) => { - return { + get: passOnSuccess({ + uri: url, + method: `get`, + request: {}, + response: { status: 200, - body: json(body), - }; + body: json(data), + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: json(data), + }; + }, + kind: "MockApiDefinition", }), - put: mockapi.put(url, (req) => { - const expectedBody = JSON.parse(JSON.stringify(body)); - req.expect.coercedBodyEquals(expectedBody); - return { + put: passOnSuccess({ + uri: url, + method: `put`, + request: { + body: property, + }, + response: { status: 204, - }; + }, + handler: (req: MockRequest) => { + const expectedBody = JSON.parse(JSON.stringify(property)); + req.expect.coercedBodyEquals(expectedBody); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", }), }; } -const booleanMock = createMockApis("boolean", true); -Scenarios.Type_Property_ValueTypes_Boolean_get = passOnSuccess(booleanMock.get); -Scenarios.Type_Property_ValueTypes_Boolean_put = passOnSuccess(booleanMock.put); - -const stringMock = createMockApis("string", "hello"); -Scenarios.Type_Property_ValueTypes_String_get = passOnSuccess(stringMock.get); -Scenarios.Type_Property_ValueTypes_String_put = passOnSuccess(stringMock.put); - -const bytesMock = createMockApis("bytes", "aGVsbG8sIHdvcmxkIQ=="); -Scenarios.Type_Property_ValueTypes_Bytes_get = passOnSuccess(bytesMock.get); -Scenarios.Type_Property_ValueTypes_Bytes_put = passOnSuccess(bytesMock.put); - -const intMock = createMockApis("int", 42); -Scenarios.Type_Property_ValueTypes_Int_get = passOnSuccess(intMock.get); -Scenarios.Type_Property_ValueTypes_Int_put = passOnSuccess(intMock.put); - -const floatMock = createMockApis("float", 43.125); -Scenarios.Type_Property_ValueTypes_Float_get = passOnSuccess(floatMock.get); -Scenarios.Type_Property_ValueTypes_Float_put = passOnSuccess(floatMock.put); - -const decimalMock = createMockApis("decimal", 0.33333); -Scenarios.Type_Property_ValueTypes_Decimal_get = passOnSuccess(decimalMock.get); -Scenarios.Type_Property_ValueTypes_Decimal_put = passOnSuccess(decimalMock.put); - -const decimal128Mock = createMockApis("decimal128", 0.33333); -Scenarios.Type_Property_ValueTypes_Decimal128_get = passOnSuccess(decimal128Mock.get); -Scenarios.Type_Property_ValueTypes_Decimal128_put = passOnSuccess(decimal128Mock.put); - -const datetimeMock = createMockApis("datetime", "2022-08-26T18:38:00Z"); -Scenarios.Type_Property_ValueTypes_Datetime_get = passOnSuccess(datetimeMock.get); -Scenarios.Type_Property_ValueTypes_Datetime_put = passOnSuccess(datetimeMock.put); - -const durationMock = createMockApis("duration", "P123DT22H14M12.011S"); -Scenarios.Type_Property_ValueTypes_Duration_get = passOnSuccess(durationMock.get); -Scenarios.Type_Property_ValueTypes_Duration_put = passOnSuccess(durationMock.put); - -const enumMock = createMockApis("enum", "ValueOne"); -Scenarios.Type_Property_ValueTypes_Enum_get = passOnSuccess(enumMock.get); -Scenarios.Type_Property_ValueTypes_Enum_put = passOnSuccess(enumMock.put); - -const extensibleEnumMock = createMockApis("extensible-enum", "UnknownValue"); -Scenarios.Type_Property_ValueTypes_ExtensibleEnum_get = passOnSuccess(extensibleEnumMock.get); -Scenarios.Type_Property_ValueTypes_ExtensibleEnum_put = passOnSuccess(extensibleEnumMock.put); - -const modelMock = createMockApis("model", { property: "hello" }); -Scenarios.Type_Property_ValueTypes_Model_get = passOnSuccess(modelMock.get); -Scenarios.Type_Property_ValueTypes_Model_put = passOnSuccess(modelMock.put); - -const collectionsStringMock = createMockApis("collections/string", ["hello", "world"]); -Scenarios.Type_Property_ValueTypes_CollectionsString_get = passOnSuccess(collectionsStringMock.get); -Scenarios.Type_Property_ValueTypes_CollectionsString_put = passOnSuccess(collectionsStringMock.put); - -const collectionsIntMock = createMockApis("collections/int", [1, 2]); -Scenarios.Type_Property_ValueTypes_CollectionsInt_get = passOnSuccess(collectionsIntMock.get); -Scenarios.Type_Property_ValueTypes_CollectionsInt_put = passOnSuccess(collectionsIntMock.put); - -const collectionsModelMock = createMockApis("collections/model", [{ property: "hello" }, { property: "world" }]); -Scenarios.Type_Property_ValueTypes_CollectionsModel_get = passOnSuccess(collectionsModelMock.get); -Scenarios.Type_Property_ValueTypes_CollectionsModel_put = passOnSuccess(collectionsModelMock.put); - -const dictionaryStringMock = createMockApis("dictionary/string", { k1: "hello", k2: "world" }); -Scenarios.Type_Property_ValueTypes_DictionaryString_get = passOnSuccess(dictionaryStringMock.get); -Scenarios.Type_Property_ValueTypes_DictionaryString_put = passOnSuccess(dictionaryStringMock.put); - -const neverMock = createMockApis("never", undefined); -Scenarios.Type_Property_ValueTypes_Never_get = passOnSuccess(neverMock.get); -Scenarios.Type_Property_ValueTypes_Never_put = passOnSuccess(neverMock.put); - -const unknownStringMock = createMockApis("unknown/string", "hello"); -Scenarios.Type_Property_ValueTypes_UnknownString_get = passOnSuccess(unknownStringMock.get); -Scenarios.Type_Property_ValueTypes_UnknownString_put = passOnSuccess(unknownStringMock.put); - -const unknownIntMock = createMockApis("unknown/int", 42); -Scenarios.Type_Property_ValueTypes_UnknownInt_get = passOnSuccess(unknownIntMock.get); -Scenarios.Type_Property_ValueTypes_UnknownInt_put = passOnSuccess(unknownIntMock.put); - -const unknownDictMock = createMockApis("unknown/dict", { k1: "hello", k2: 42 }); -Scenarios.Type_Property_ValueTypes_UnknownDict_get = passOnSuccess(unknownDictMock.get); -Scenarios.Type_Property_ValueTypes_UnknownDict_put = passOnSuccess(unknownDictMock.put); - -const unknownArrayMock = createMockApis("unknown/array", ["hello", "world"]); -Scenarios.Type_Property_ValueTypes_UnknownArray_get = passOnSuccess(unknownArrayMock.get); -Scenarios.Type_Property_ValueTypes_UnknownArray_put = passOnSuccess(unknownArrayMock.put); - -const stringLiteralMock = createMockApis("string/literal", "hello"); -Scenarios.Type_Property_ValueTypes_StringLiteral_get = passOnSuccess(stringLiteralMock.get); -Scenarios.Type_Property_ValueTypes_StringLiteral_put = passOnSuccess(stringLiteralMock.put); - -const intLiteralMock = createMockApis("int/literal", 42); -Scenarios.Type_Property_ValueTypes_IntLiteral_get = passOnSuccess(intLiteralMock.get); -Scenarios.Type_Property_ValueTypes_IntLiteral_put = passOnSuccess(intLiteralMock.put); - -const floatLiteralMock = createMockApis("float/literal", 43.125); -Scenarios.Type_Property_ValueTypes_FloatLiteral_get = passOnSuccess(floatLiteralMock.get); -Scenarios.Type_Property_ValueTypes_FloatLiteral_put = passOnSuccess(floatLiteralMock.put); - -const booleanLiteralMock = createMockApis("boolean/literal", true); -Scenarios.Type_Property_ValueTypes_BooleanLiteral_get = passOnSuccess(booleanLiteralMock.get); -Scenarios.Type_Property_ValueTypes_BooleanLiteral_put = passOnSuccess(booleanLiteralMock.put); - -const unionStringLiteralMock = createMockApis("union/string/literal", "world"); -Scenarios.Type_Property_ValueTypes_UnionStringLiteral_get = passOnSuccess(unionStringLiteralMock.get); -Scenarios.Type_Property_ValueTypes_UnionStringLiteral_put = passOnSuccess(unionStringLiteralMock.put); - -const unionIntLiteralMock = createMockApis("union/int/literal", 42); -Scenarios.Type_Property_ValueTypes_UnionIntLiteral_get = passOnSuccess(unionIntLiteralMock.get); -Scenarios.Type_Property_ValueTypes_UnionIntLiteral_put = passOnSuccess(unionIntLiteralMock.put); - -const unionFloatLiteralMock = createMockApis("union/float/literal", 46.875); -Scenarios.Type_Property_ValueTypes_UnionFloatLiteral_get = passOnSuccess(unionFloatLiteralMock.get); -Scenarios.Type_Property_ValueTypes_UnionFloatLiteral_put = passOnSuccess(unionFloatLiteralMock.put); - -const unionEnumValueMock = createMockApis("union-enum-value", "value2"); -Scenarios.Type_Property_ValueTypes_UnionEnumValue_get = passOnSuccess(unionEnumValueMock.get); -Scenarios.Type_Property_ValueTypes_UnionEnumValue_put = passOnSuccess(unionEnumValueMock.put); +const Type_Property_ValueTypes_Boolean = createServerTests(`/type/property/value-types/boolean`, { + property: true, +}); +Scenarios.Type_Property_ValueTypes_Boolean_get = Type_Property_ValueTypes_Boolean.get; +Scenarios.Type_Property_ValueTypes_Boolean_put = Type_Property_ValueTypes_Boolean.put; + +const Type_Property_ValueTypes_String = createServerTests(`/type/property/value-types/string`, { + property: "hello", +}); +Scenarios.Type_Property_ValueTypes_String_get = Type_Property_ValueTypes_String.get; +Scenarios.Type_Property_ValueTypes_String_put = Type_Property_ValueTypes_String.put; + +const Type_Property_ValueTypes_Bytes = createServerTests(`/type/property/value-types/bytes`, { + property: "aGVsbG8sIHdvcmxkIQ==", +}); +Scenarios.Type_Property_ValueTypes_Bytes_get = Type_Property_ValueTypes_Bytes.get; +Scenarios.Type_Property_ValueTypes_Bytes_put = Type_Property_ValueTypes_Bytes.put; + +const Type_Property_ValueTypes_Int = createServerTests(`/type/property/value-types/int`, { + property: 42, +}); +Scenarios.Type_Property_ValueTypes_Int_get = Type_Property_ValueTypes_Int.get; +Scenarios.Type_Property_ValueTypes_Int_put = Type_Property_ValueTypes_Int.put; + +const Type_Property_ValueTypes_Float = createServerTests(`/type/property/value-types/float`, { + property: 43.125, +}); +Scenarios.Type_Property_ValueTypes_Float_get = Type_Property_ValueTypes_Float.get; +Scenarios.Type_Property_ValueTypes_Float_put = Type_Property_ValueTypes_Float.put; + +const Type_Property_ValueTypes_Decimal = createServerTests(`/type/property/value-types/decimal`, { + property: 0.33333, +}); +Scenarios.Type_Property_ValueTypes_Decimal_get = Type_Property_ValueTypes_Decimal.get; +Scenarios.Type_Property_ValueTypes_Decimal_put = Type_Property_ValueTypes_Decimal.put; + +const Type_Property_ValueTypes_Decimal128 = createServerTests(`/type/property/value-types/decimal128`, { + property: 0.33333, +}); +Scenarios.Type_Property_ValueTypes_Decimal128_get = Type_Property_ValueTypes_Decimal128.get; +Scenarios.Type_Property_ValueTypes_Decimal128_put = Type_Property_ValueTypes_Decimal128.put; + +const Type_Property_ValueTypes_DateTime = createServerTests(`/type/property/value-types/datetime`, { + property: "2022-08-26T18:38:00Z", +}); +Scenarios.Type_Property_ValueTypes_Datetime_get = Type_Property_ValueTypes_DateTime.get; +Scenarios.Type_Property_ValueTypes_Datetime_put = Type_Property_ValueTypes_DateTime.put; + +const Type_Property_ValueTypes_Duration = createServerTests(`/type/property/value-types/duration`, { + property: "P123DT22H14M12.011S", +}); +Scenarios.Type_Property_ValueTypes_Duration_get = Type_Property_ValueTypes_Duration.get; +Scenarios.Type_Property_ValueTypes_Duration_put = Type_Property_ValueTypes_Duration.put; + +const Type_Property_ValueTypes_Enum = createServerTests(`/type/property/value-types/enum`, { + property: "ValueOne", +}); +Scenarios.Type_Property_ValueTypes_Enum_get = Type_Property_ValueTypes_Enum.get; +Scenarios.Type_Property_ValueTypes_Enum_put = Type_Property_ValueTypes_Enum.put; + +const Type_Property_ValueTypes_Extensible_Enum = createServerTests(`/type/property/value-types/extensible-enum`, { + property: "UnknownValue", +}); +Scenarios.Type_Property_ValueTypes_ExtensibleEnum_get = Type_Property_ValueTypes_Extensible_Enum.get; +Scenarios.Type_Property_ValueTypes_ExtensibleEnum_put = Type_Property_ValueTypes_Extensible_Enum.put; + +const Type_Property_ValueTypes_Model = createServerTests(`/type/property/value-types/model`, { + property: { property: "hello" }, +}); +Scenarios.Type_Property_ValueTypes_Model_get = Type_Property_ValueTypes_Model.get; +Scenarios.Type_Property_ValueTypes_Model_put = Type_Property_ValueTypes_Model.put; + +const Type_Property_ValueTypes_Collections_String = createServerTests(`/type/property/value-types/collections/string`, { + property: ["hello", "world"], +}); +Scenarios.Type_Property_ValueTypes_CollectionsString_get = Type_Property_ValueTypes_Collections_String.get; +Scenarios.Type_Property_ValueTypes_CollectionsString_put = Type_Property_ValueTypes_Collections_String.put; + +const Type_Property_ValueTypes_Collections_Int = createServerTests(`/type/property/value-types/collections/int`, { + property: [1, 2], +}); +Scenarios.Type_Property_ValueTypes_CollectionsInt_get = Type_Property_ValueTypes_Collections_Int.get; +Scenarios.Type_Property_ValueTypes_CollectionsInt_put = Type_Property_ValueTypes_Collections_Int.put; + +const Type_Property_ValueTypes_Collections_Model = createServerTests(`/type/property/value-types/collections/model`, { + property: [{ property: "hello" }, { property: "world" }], +}); +Scenarios.Type_Property_ValueTypes_CollectionsModel_get = Type_Property_ValueTypes_Collections_Model.get; +Scenarios.Type_Property_ValueTypes_CollectionsModel_put = Type_Property_ValueTypes_Collections_Model.put; + +const Type_Property_ValueTypes_Dictionary_String = createServerTests(`/type/property/value-types/dictionary/string`, { + property: { k1: "hello", k2: "world" }, +}); +Scenarios.Type_Property_ValueTypes_DictionaryString_get = Type_Property_ValueTypes_Dictionary_String.get; +Scenarios.Type_Property_ValueTypes_DictionaryString_put = Type_Property_ValueTypes_Dictionary_String.put; + +const Type_Property_ValueTypes_Never = createServerTests(`/type/property/value-types/never`, { + property: undefined, +}); +Scenarios.Type_Property_ValueTypes_Never_get = Type_Property_ValueTypes_Never.get; +Scenarios.Type_Property_ValueTypes_Never_put = Type_Property_ValueTypes_Never.put; + +const Type_Property_ValueTypes_Unknown_String = createServerTests(`/type/property/value-types/unknown/string`, { + property: "hello", +}); +Scenarios.Type_Property_ValueTypes_UnknownString_get = Type_Property_ValueTypes_Unknown_String.get; +Scenarios.Type_Property_ValueTypes_UnknownString_put = Type_Property_ValueTypes_Unknown_String.put; + +const Type_Property_ValueTypes_Unknown_Int = createServerTests(`/type/property/value-types/unknown/int`, { + property: 42, +}); +Scenarios.Type_Property_ValueTypes_UnknownInt_get = Type_Property_ValueTypes_Unknown_Int.get; +Scenarios.Type_Property_ValueTypes_UnknownInt_put = Type_Property_ValueTypes_Unknown_Int.put; + +const Type_Property_ValueTypes_Unknown_Dict = createServerTests(`/type/property/value-types/unknown/dict`, { + property: { k1: "hello", k2: 42 }, +}); +Scenarios.Type_Property_ValueTypes_UnknownDict_get = Type_Property_ValueTypes_Unknown_Dict.get; +Scenarios.Type_Property_ValueTypes_UnknownDict_put = Type_Property_ValueTypes_Unknown_Dict.put; + +const Type_Property_ValueTypes_Unknown_Array = createServerTests(`/type/property/value-types/unknown/array`, { + property: ["hello", "world"], +}); +Scenarios.Type_Property_ValueTypes_UnknownArray_get = Type_Property_ValueTypes_Unknown_Array.get; +Scenarios.Type_Property_ValueTypes_UnknownArray_put = Type_Property_ValueTypes_Unknown_Array.put; + +const Type_Property_ValueTypes_String_Literal = createServerTests(`/type/property/value-types/string/literal`, { + property: "hello", +}); +Scenarios.Type_Property_ValueTypes_StringLiteral_get = Type_Property_ValueTypes_String_Literal.get; +Scenarios.Type_Property_ValueTypes_StringLiteral_put = Type_Property_ValueTypes_String_Literal.put; + +const Type_Property_ValueTypes_Int_Literal = createServerTests(`/type/property/value-types/int/literal`, { + property: 42, +}); +Scenarios.Type_Property_ValueTypes_IntLiteral_get = Type_Property_ValueTypes_Int_Literal.get; +Scenarios.Type_Property_ValueTypes_IntLiteral_put = Type_Property_ValueTypes_Int_Literal.put; + +const Type_Property_ValueTypes_Float_Literal = createServerTests(`/type/property/value-types/float/literal`, { + property: 43.125, +}); +Scenarios.Type_Property_ValueTypes_FloatLiteral_get = Type_Property_ValueTypes_Float_Literal.get; +Scenarios.Type_Property_ValueTypes_FloatLiteral_put = Type_Property_ValueTypes_Float_Literal.put; + +const Type_Property_ValueTypes_Boolean_Literal = createServerTests(`/type/property/value-types/boolean/literal`, { + property: true, +}); +Scenarios.Type_Property_ValueTypes_BooleanLiteral_get = Type_Property_ValueTypes_Boolean_Literal.get; +Scenarios.Type_Property_ValueTypes_BooleanLiteral_put = Type_Property_ValueTypes_Boolean_Literal.put; + +const Type_Property_ValueTypes_Union_String_Literal = createServerTests( + `/type/property/value-types/union/string/literal`, + { + property: "world", + }, +); +Scenarios.Type_Property_ValueTypes_UnionStringLiteral_get = Type_Property_ValueTypes_Union_String_Literal.get; +Scenarios.Type_Property_ValueTypes_UnionStringLiteral_put = Type_Property_ValueTypes_Union_String_Literal.put; + +const Type_Property_ValueTypes_Union_Int_Literal = createServerTests(`/type/property/value-types/union/int/literal`, { + property: 42, +}); +Scenarios.Type_Property_ValueTypes_UnionIntLiteral_get = Type_Property_ValueTypes_Union_Int_Literal.get; +Scenarios.Type_Property_ValueTypes_UnionIntLiteral_put = Type_Property_ValueTypes_Union_Int_Literal.put; + +const Type_Property_ValueTypes_Union_Float_Literal = createServerTests( + `/type/property/value-types/union/float/literal`, + { + property: 46.875, + }, +); +Scenarios.Type_Property_ValueTypes_UnionFloatLiteral_get = Type_Property_ValueTypes_Union_Float_Literal.get; +Scenarios.Type_Property_ValueTypes_UnionFloatLiteral_put = Type_Property_ValueTypes_Union_Float_Literal.put; + +const Type_Property_ValueTypes_Union_Enum_Value = createServerTests(`/type/property/value-types/union-enum-value`, { + property: "value2", +}); +Scenarios.Type_Property_ValueTypes_UnionEnumValue_get = Type_Property_ValueTypes_Union_Enum_Value.get; +Scenarios.Type_Property_ValueTypes_UnionEnumValue_put = Type_Property_ValueTypes_Union_Enum_Value.put; diff --git a/packages/cadl-ranch-specs/http/type/scalar/mockapi.ts b/packages/cadl-ranch-specs/http/type/scalar/mockapi.ts index 486fec430..81ab4d694 100644 --- a/packages/cadl-ranch-specs/http/type/scalar/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/scalar/mockapi.ts @@ -1,119 +1,281 @@ -import { passOnSuccess, mockapi, json, MockApi } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -// string value -Scenarios.Type_Scalar_String_get = passOnSuccess( - mockapi.get("/type/scalar/string", (req) => { +Scenarios.Type_Scalar_String_get = passOnSuccess({ + uri: "/type/scalar/string", + method: `get`, + request: {}, + response: { + status: 200, + body: json("test"), + }, + handler: (req: MockRequest) => { return { status: 200, body: json("test") }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Type_Scalar_String_put = passOnSuccess( - mockapi.put("/type/scalar/string", (req) => { +Scenarios.Type_Scalar_String_put = passOnSuccess({ + uri: "/type/scalar/string", + method: `put`, + request: { + body: "test", + headers: { + "Content-Type": "text/plain", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals("test"); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -// boolean value -Scenarios.Type_Scalar_Boolean_get = passOnSuccess( - mockapi.get("/type/scalar/boolean", (req) => { +Scenarios.Type_Scalar_Boolean_get = passOnSuccess({ + uri: "/type/scalar/boolean", + method: `get`, + request: {}, + response: { + status: 200, + body: json(true), + }, + handler: (req: MockRequest) => { return { status: 200, body: json(true) }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Type_Scalar_Boolean_put = passOnSuccess( - mockapi.put("/type/scalar/boolean", (req) => { +Scenarios.Type_Scalar_Boolean_put = passOnSuccess({ + uri: "/type/scalar/boolean", + method: `put`, + request: { + body: true, + headers: { + "Content-Type": "application/json; charset=utf-8", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals(true); return { status: 204 }; - }), -); + }, + kind: "MockApiDefinition", +}); -//unknown value -Scenarios.Type_Scalar_Unknown_get = passOnSuccess( - mockapi.get("/type/scalar/unknown", (req) => { +Scenarios.Type_Scalar_Unknown_get = passOnSuccess({ + uri: "/type/scalar/unknown", + method: `get`, + request: {}, + response: { + status: 200, + body: json("test"), + }, + handler: (req: MockRequest) => { return { status: 200, body: json("test") }; - }), -); - -Scenarios.Type_Scalar_Unknown_put = passOnSuccess( - mockapi.put("/type/scalar/unknown", (req) => { + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Scalar_Unknown_put = passOnSuccess({ + uri: "/type/scalar/unknown", + method: `put`, + request: { + body: "test", + headers: { + "Content-Type": "text/plain", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { req.expect.bodyEquals("test"); return { status: 204 }; - }), -); - -interface MockApiOperations { - responseBody: MockApi; - requestBody: MockApi; - requestParameter: MockApi; -} - -function createModelMockApis(route: string, value: any): MockApiOperations { - return { - responseBody: mockapi.get(`/type/scalar/${route}/response_body`, (req) => { - return { - status: 200, - body: json(value), - }; - }), - requestBody: mockapi.put(`/type/scalar/${route}/resquest_body`, (req) => { - req.expect.bodyEquals(value); - return { - status: 204, - }; - }), - requestParameter: mockapi.get(`/type/scalar/${route}/request_parameter`, (req) => { - req.expect.containsQueryParam("value", `${value}`); - return { - status: 204, - }; - }), - }; -} - -const DecimalTypeMock = createModelMockApis("decimal", 0.33333); -Scenarios.Type_Scalar_DecimalType_responseBody = passOnSuccess(DecimalTypeMock.responseBody); -Scenarios.Type_Scalar_DecimalType_requestBody = passOnSuccess(DecimalTypeMock.requestBody); -Scenarios.Type_Scalar_DecimalType_requestParameter = passOnSuccess(DecimalTypeMock.requestParameter); - -const Decimal128TypeMock = createModelMockApis("decimal128", 0.33333); -Scenarios.Type_Scalar_Decimal128Type_responseBody = passOnSuccess(Decimal128TypeMock.responseBody); -Scenarios.Type_Scalar_Decimal128Type_requestBody = passOnSuccess(Decimal128TypeMock.requestBody); -Scenarios.Type_Scalar_Decimal128Type_requestParameter = passOnSuccess(Decimal128TypeMock.requestParameter); - -interface NumberTypesVerifyOperations { - prepareVerify: MockApi; - verify: MockApi; -} - -function createNumberTypesVerifyOperations( - route: string, - verifyValues: any, - resultValue: any, -): NumberTypesVerifyOperations { - return { - prepareVerify: mockapi.get(`/type/scalar/${route}/prepare_verify`, (req) => { - return { - status: 200, - body: json(verifyValues), - }; - }), - verify: mockapi.post(`/type/scalar/${route}/verify`, (req) => { - req.expect.bodyEquals(resultValue); - return { - status: 204, - }; - }), - }; -} - -const DecimalVerifyMock = createNumberTypesVerifyOperations("decimal", [0.1, 0.1, 0.1], 0.3); -Scenarios.Type_Scalar_DecimalVerify_prepareVerify = passOnSuccess(DecimalVerifyMock.prepareVerify); -Scenarios.Type_Scalar_DecimalVerify_verify = passOnSuccess(DecimalVerifyMock.verify); + }, + kind: "MockApiDefinition", +}); -const Decimal128VerifyMock = createNumberTypesVerifyOperations("decimal128", [0.1, 0.1, 0.1], 0.3); -Scenarios.Type_Scalar_Decimal128Verify_prepareVerify = passOnSuccess(Decimal128VerifyMock.prepareVerify); -Scenarios.Type_Scalar_Decimal128Verify_verify = passOnSuccess(Decimal128VerifyMock.verify); +Scenarios.Type_Scalar_DecimalType_responseBody = passOnSuccess({ + uri: "/type/scalar/decimal/response_body", + method: `get`, + request: {}, + response: { + status: 200, + body: json(0.33333), + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: json(0.33333), + }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Scalar_Decimal128Type_responseBody = passOnSuccess({ + uri: "/type/scalar/decimal128/response_body", + method: `get`, + request: {}, + response: { + status: 200, + body: json(0.33333), + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: json(0.33333), + }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Scalar_DecimalType_requestBody = passOnSuccess({ + uri: "/type/scalar/decimal/resquest_body", + method: `put`, + request: { + body: 0.33333, + headers: { + "Content-Type": "application/json; charset=utf-8", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals(0.33333); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Scalar_Decimal128Type_requestBody = passOnSuccess({ + uri: "/type/scalar/decimal128/resquest_body", + method: `put`, + request: { + body: 0.33333, + headers: { + "Content-Type": "application/json; charset=utf-8", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals(0.33333); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Scalar_DecimalType_requestParameter = passOnSuccess({ + uri: "/type/scalar/decimal/request_parameter", + method: `get`, + request: { + params: { value: 0.33333 }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("value", "0.33333"); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Scalar_Decimal128Type_requestParameter = passOnSuccess({ + uri: "/type/scalar/decimal128/request_parameter", + method: `get`, + request: { + params: { value: 0.33333 }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.containsQueryParam("value", "0.33333"); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Scalar_DecimalVerify_prepareVerify = passOnSuccess({ + uri: "/type/scalar/decimal/prepare_verify", + method: `get`, + request: {}, + response: { + status: 200, + body: json([0.1, 0.1, 0.1]), + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: json([0.1, 0.1, 0.1]), + }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Scalar_Decimal128Verify_prepareVerify = passOnSuccess({ + uri: "/type/scalar/decimal128/prepare_verify", + method: `get`, + request: {}, + response: { + status: 200, + body: json([0.1, 0.1, 0.1]), + }, + handler: (req: MockRequest) => { + return { + status: 200, + body: json([0.1, 0.1, 0.1]), + }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Scalar_DecimalVerify_verify = passOnSuccess({ + uri: "/type/scalar/decimal/verify", + method: `post`, + request: { + body: 0.3, + headers: { + "Content-Type": "application/json; charset=utf-8", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals(0.3); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", +}); +Scenarios.Type_Scalar_Decimal128Verify_verify = passOnSuccess({ + uri: "/type/scalar/decimal128/verify", + method: `post`, + request: { + body: 0.3, + headers: { + "Content-Type": "application/json; charset=utf-8", + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals(0.3); + return { + status: 204, + }; + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/type/union/mockapi.ts b/packages/cadl-ranch-specs/http/type/union/mockapi.ts index f123448db..14aeb7a30 100644 --- a/packages/cadl-ranch-specs/http/type/union/mockapi.ts +++ b/packages/cadl-ranch-specs/http/type/union/mockapi.ts @@ -1,71 +1,117 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -function createGetSendScenario(url: string, value: unknown) { - return { - get: passOnSuccess( - mockapi.get(url, (req) => { - return { status: 200, body: json({ prop: value }) }; - }), - ), - send: passOnSuccess( - mockapi.post(url, (req) => { - req.expect.bodyEquals({ prop: value }); - return { status: 204 }; - }), - ), - }; +function createGetServerTests(url: string, value: unknown) { + return passOnSuccess({ + uri: url, + method: `get`, + request: {}, + response: { + status: 200, + body: json({ prop: value }), + }, + handler: (req: MockRequest) => { + return { status: 200, body: json({ prop: value }) }; + }, + kind: "MockApiDefinition", + }); } -const Type_Union_StringsOnly = createGetSendScenario("/type/union/strings-only", "b"); -Scenarios.Type_Union_StringsOnly_get = Type_Union_StringsOnly.get; -Scenarios.Type_Union_StringsOnly_send = Type_Union_StringsOnly.send; -const Type_Union_StringExtensible = createGetSendScenario("/type/union/string-extensible", "custom"); -Scenarios.Type_Union_StringExtensible_get = Type_Union_StringExtensible.get; -Scenarios.Type_Union_StringExtensible_send = Type_Union_StringExtensible.send; +function createPostServerTests(url: string, value: unknown) { + return passOnSuccess({ + uri: url, + method: `post`, + request: { + body: { + prop: value, + }, + }, + response: { + status: 204, + }, + handler: (req: MockRequest) => { + req.expect.bodyEquals({ prop: value }); + return { status: 204 }; + }, + kind: "MockApiDefinition", + }); +} + +Scenarios.Type_Union_StringsOnly_get = createGetServerTests(`/type/union/strings-only`, "b"); +Scenarios.Type_Union_StringsOnly_send = createPostServerTests(`/type/union/strings-only`, "b"); -const Type_Union_StringExtensibleNamed = createGetSendScenario("/type/union/string-extensible-named", "custom"); -Scenarios.Type_Union_StringExtensibleNamed_get = Type_Union_StringExtensibleNamed.get; -Scenarios.Type_Union_StringExtensibleNamed_send = Type_Union_StringExtensibleNamed.send; +Scenarios.Type_Union_StringExtensible_get = createGetServerTests(`/type/union/string-extensible`, "custom"); +Scenarios.Type_Union_StringExtensible_send = createPostServerTests(`/type/union/string-extensible`, "custom"); -const Type_Union_IntsOnly = createGetSendScenario("/type/union/ints-only", 2); -Scenarios.Type_Union_IntsOnly_get = Type_Union_IntsOnly.get; -Scenarios.Type_Union_IntsOnly_send = Type_Union_IntsOnly.send; +Scenarios.Type_Union_StringExtensibleNamed_get = createGetServerTests(`/type/union/string-extensible-named`, "custom"); +Scenarios.Type_Union_StringExtensibleNamed_send = createPostServerTests( + `/type/union/string-extensible-named`, + "custom", +); -const Type_Union_FloatsOnly = createGetSendScenario("/type/union/floats-only", 2.2); -Scenarios.Type_Union_FloatsOnly_get = Type_Union_FloatsOnly.get; -Scenarios.Type_Union_FloatsOnly_send = Type_Union_FloatsOnly.send; +Scenarios.Type_Union_IntsOnly_get = createGetServerTests(`/type/union/ints-only`, 2); +Scenarios.Type_Union_IntsOnly_send = createPostServerTests(`/type/union/ints-only`, 2); -const Type_Union_ModelsOnly = createGetSendScenario("/type/union/models-only", { name: "test" }); -Scenarios.Type_Union_ModelsOnly_get = Type_Union_ModelsOnly.get; -Scenarios.Type_Union_ModelsOnly_send = Type_Union_ModelsOnly.send; +Scenarios.Type_Union_FloatsOnly_get = createGetServerTests(`/type/union/floats-only`, 2.2); +Scenarios.Type_Union_FloatsOnly_send = createPostServerTests(`/type/union/floats-only`, 2.2); + +Scenarios.Type_Union_ModelsOnly_get = createGetServerTests(`/type/union/models-only`, { + name: "test", +}); +Scenarios.Type_Union_ModelsOnly_send = createPostServerTests(`/type/union/models-only`, { + name: "test", +}); -const Type_Union_EnumsOnly = createGetSendScenario("/type/union/enums-only", { +Scenarios.Type_Union_EnumsOnly_get = createGetServerTests(`/type/union/enums-only`, { + lr: "right", + ud: "up", +}); +Scenarios.Type_Union_EnumsOnly_send = createPostServerTests(`/type/union/enums-only`, { lr: "right", ud: "up", }); -Scenarios.Type_Union_EnumsOnly_get = Type_Union_EnumsOnly.get; -Scenarios.Type_Union_EnumsOnly_send = Type_Union_EnumsOnly.send; -const Type_Union_StringAndArray = createGetSendScenario("/type/union/string-and-array", { +Scenarios.Type_Union_StringAndArray_get = createGetServerTests(`/type/union/string-and-array`, { + string: "test", + array: ["test1", "test2"], +}); +Scenarios.Type_Union_StringAndArray_send = createPostServerTests(`/type/union/string-and-array`, { string: "test", array: ["test1", "test2"], }); -Scenarios.Type_Union_StringAndArray_get = Type_Union_StringAndArray.get; -Scenarios.Type_Union_StringAndArray_send = Type_Union_StringAndArray.send; -const Type_Union_MixedLiterals = createGetSendScenario("/type/union/mixed-literals", { +Scenarios.Type_Union_MixedLiterals_get = createGetServerTests(`/type/union/mixed-literals`, { + stringLiteral: "a", + intLiteral: 2, + floatLiteral: 3.3, + booleanLiteral: true, +}); +Scenarios.Type_Union_MixedLiterals_send = createPostServerTests(`/type/union/mixed-literals`, { stringLiteral: "a", intLiteral: 2, floatLiteral: 3.3, booleanLiteral: true, }); -Scenarios.Type_Union_MixedLiterals_get = Type_Union_MixedLiterals.get; -Scenarios.Type_Union_MixedLiterals_send = Type_Union_MixedLiterals.send; -const Type_Union_MixedTypes = createGetSendScenario("/type/union/mixed-types", { +Scenarios.Type_Union_MixedTypes_get = createGetServerTests(`/type/union/mixed-types`, { + model: { + name: "test", + }, + literal: "a", + int: 2, + boolean: true, + array: [ + { + name: "test", + }, + "a", + 2, + true, + ], +}); +Scenarios.Type_Union_MixedTypes_send = createPostServerTests(`/type/union/mixed-types`, { model: { name: "test", }, @@ -81,5 +127,3 @@ const Type_Union_MixedTypes = createGetSendScenario("/type/union/mixed-types", { true, ], }); -Scenarios.Type_Union_MixedTypes_get = Type_Union_MixedTypes.get; -Scenarios.Type_Union_MixedTypes_send = Type_Union_MixedTypes.send; diff --git a/packages/cadl-ranch-specs/http/versioning/added/mockapi.ts b/packages/cadl-ranch-specs/http/versioning/added/mockapi.ts index 559167bbe..8a48fec21 100644 --- a/packages/cadl-ranch-specs/http/versioning/added/mockapi.ts +++ b/packages/cadl-ranch-specs/http/versioning/added/mockapi.ts @@ -1,35 +1,80 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Versioning_Added_v1 = passOnSuccess( - mockapi.post("/versioning/added/api-version:v2/v1", (req) => { +Scenarios.Versioning_Added_v1 = passOnSuccess({ + uri: `/versioning/added/api-version:v2/v1`, + method: `post`, + request: { + body: { + prop: "foo", + enumProp: "enumMemberV2", + unionProp: 10, + }, + headers: { + "header-v2": "bar", + }, + }, + response: { + status: 200, + body: json({ prop: "foo", enumProp: "enumMemberV2", unionProp: 10 }), + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ prop: "foo", enumProp: "enumMemberV2", unionProp: 10 }); req.expect.containsHeader("header-v2", "bar"); return { status: 200, body: json({ prop: "foo", enumProp: "enumMemberV2", unionProp: 10 }), }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Versioning_Added_v2 = passOnSuccess( - mockapi.post("/versioning/added/api-version:v2/v2", (req) => { +Scenarios.Versioning_Added_v2 = passOnSuccess({ + uri: `/versioning/added/api-version:v2/v2`, + method: `post`, + request: { + body: { + prop: "foo", + enumProp: "enumMember", + unionProp: "bar", + }, + }, + response: { + status: 200, + body: json({ prop: "foo", enumProp: "enumMember", unionProp: "bar" }), + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ prop: "foo", enumProp: "enumMember", unionProp: "bar" }); return { status: 200, body: json({ prop: "foo", enumProp: "enumMember", unionProp: "bar" }), }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Versioning_Added_InterfaceV2 = passOnSuccess( - mockapi.post("/versioning/added/api-version:v2/interface-v2/v2", (req) => { +Scenarios.Versioning_Added_InterfaceV2 = passOnSuccess({ + uri: `/versioning/added/api-version:v2/interface-v2/v2`, + method: `post`, + request: { + body: { + prop: "foo", + enumProp: "enumMember", + unionProp: "bar", + }, + }, + response: { + status: 200, + body: json({ prop: "foo", enumProp: "enumMember", unionProp: "bar" }), + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ prop: "foo", enumProp: "enumMember", unionProp: "bar" }); return { status: 200, body: json({ prop: "foo", enumProp: "enumMember", unionProp: "bar" }), }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/versioning/madeOptional/mockapi.ts b/packages/cadl-ranch-specs/http/versioning/madeOptional/mockapi.ts index 332a08adb..877d28b2e 100644 --- a/packages/cadl-ranch-specs/http/versioning/madeOptional/mockapi.ts +++ b/packages/cadl-ranch-specs/http/versioning/madeOptional/mockapi.ts @@ -1,14 +1,26 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Versioning_MadeOptional_test = passOnSuccess( - mockapi.post("/versioning/made-optional/api-version:v2/test", (req) => { +Scenarios.Versioning_MadeOptional_test = passOnSuccess({ + uri: `/versioning/made-optional/api-version:v2/test`, + method: `post`, + request: { + body: { + prop: "foo", + }, + }, + response: { + status: 200, + body: json({ prop: "foo" }), + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ prop: "foo" }); return { status: 200, body: json({ prop: "foo" }), }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/versioning/removed/mockapi.ts b/packages/cadl-ranch-specs/http/versioning/removed/mockapi.ts index 2118c265c..801ec6090 100644 --- a/packages/cadl-ranch-specs/http/versioning/removed/mockapi.ts +++ b/packages/cadl-ranch-specs/http/versioning/removed/mockapi.ts @@ -1,14 +1,28 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Versioning_Removed_v2 = passOnSuccess( - mockapi.post("/versioning/removed/api-version:v2/v2", (req) => { +Scenarios.Versioning_Removed_v2 = passOnSuccess({ + uri: `/versioning/removed/api-version:v2/v2`, + method: `post`, + request: { + body: { + prop: "foo", + enumProp: "enumMemberV2", + unionProp: "bar", + }, + }, + response: { + status: 200, + body: json({ prop: "foo", enumProp: "enumMemberV2", unionProp: "bar" }), + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ prop: "foo", enumProp: "enumMemberV2", unionProp: "bar" }); return { status: 200, body: json({ prop: "foo", enumProp: "enumMemberV2", unionProp: "bar" }), }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/versioning/renamedFrom/mockapi.ts b/packages/cadl-ranch-specs/http/versioning/renamedFrom/mockapi.ts index 1126ccd1a..6ca14928b 100644 --- a/packages/cadl-ranch-specs/http/versioning/renamedFrom/mockapi.ts +++ b/packages/cadl-ranch-specs/http/versioning/renamedFrom/mockapi.ts @@ -1,25 +1,56 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Versioning_RenamedFrom_newOp = passOnSuccess( - mockapi.post("/versioning/renamed-from/api-version:v2/test", (req) => { +Scenarios.Versioning_RenamedFrom_newOp = passOnSuccess({ + uri: `/versioning/renamed-from/api-version:v2/test`, + method: `post`, + request: { + body: { + newProp: "foo", + enumProp: "newEnumMember", + unionProp: 10, + }, + params: { + newQuery: "bar", + }, + }, + response: { + status: 200, + body: json({ newProp: "foo", enumProp: "newEnumMember", unionProp: 10 }), + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ newProp: "foo", enumProp: "newEnumMember", unionProp: 10 }); req.expect.containsQueryParam("newQuery", "bar"); return { status: 200, body: json({ newProp: "foo", enumProp: "newEnumMember", unionProp: 10 }), }; - }), -); + }, + kind: "MockApiDefinition", +}); -Scenarios.Versioning_RenamedFrom_NewInterface = passOnSuccess( - mockapi.post("/versioning/renamed-from/api-version:v2/interface/test", (req) => { +Scenarios.Versioning_RenamedFrom_NewInterface = passOnSuccess({ + uri: `/versioning/renamed-from/api-version:v2/interface/test`, + method: `post`, + request: { + body: { + newProp: "foo", + enumProp: "newEnumMember", + unionProp: 10, + }, + }, + response: { + status: 200, + body: json({ newProp: "foo", enumProp: "newEnumMember", unionProp: 10 }), + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ newProp: "foo", enumProp: "newEnumMember", unionProp: 10 }); return { status: 200, body: json({ newProp: "foo", enumProp: "newEnumMember", unionProp: 10 }), }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/versioning/returnTypeChangedFrom/mockapi.ts b/packages/cadl-ranch-specs/http/versioning/returnTypeChangedFrom/mockapi.ts index 86885217b..9c02743ea 100644 --- a/packages/cadl-ranch-specs/http/versioning/returnTypeChangedFrom/mockapi.ts +++ b/packages/cadl-ranch-specs/http/versioning/returnTypeChangedFrom/mockapi.ts @@ -1,14 +1,27 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Versioning_ReturnTypeChangedFrom_test = passOnSuccess( - mockapi.post("/versioning/return-type-changed-from/api-version:v2/test", (req) => { +Scenarios.Versioning_ReturnTypeChangedFrom_test = passOnSuccess({ + uri: `/versioning/return-type-changed-from/api-version:v2/test`, + method: `post`, + request: { + body: "test", + headers: { + "Content-Type": "text/plain", + }, + }, + response: { + status: 200, + body: json("test"), + }, + handler: (req: MockRequest) => { req.expect.bodyEquals("test"); return { status: 200, body: json("test"), }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/http/versioning/typeChangedFrom/mockapi.ts b/packages/cadl-ranch-specs/http/versioning/typeChangedFrom/mockapi.ts index 41e48d834..8e0826f2f 100644 --- a/packages/cadl-ranch-specs/http/versioning/typeChangedFrom/mockapi.ts +++ b/packages/cadl-ranch-specs/http/versioning/typeChangedFrom/mockapi.ts @@ -1,15 +1,31 @@ -import { passOnSuccess, mockapi, json } from "@azure-tools/cadl-ranch-api"; +import { passOnSuccess, json, MockRequest } from "@azure-tools/cadl-ranch-api"; import { ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; export const Scenarios: Record = {}; -Scenarios.Versioning_TypeChangedFrom_test = passOnSuccess( - mockapi.post("/versioning/type-changed-from/api-version:v2/test", (req) => { +Scenarios.Versioning_TypeChangedFrom_test = passOnSuccess({ + uri: `/versioning/type-changed-from/api-version:v2/test`, + method: `post`, + request: { + params: { + param: "baz", + }, + body: { + prop: "foo", + changedProp: "bar", + }, + }, + response: { + status: 200, + body: json({ prop: "foo", changedProp: "bar" }), + }, + handler: (req: MockRequest) => { req.expect.bodyEquals({ prop: "foo", changedProp: "bar" }); req.expect.containsQueryParam("param", "baz"); return { status: 200, body: json({ prop: "foo", changedProp: "bar" }), }; - }), -); + }, + kind: "MockApiDefinition", +}); diff --git a/packages/cadl-ranch-specs/package.json b/packages/cadl-ranch-specs/package.json index d294174b7..fc40d4b5c 100644 --- a/packages/cadl-ranch-specs/package.json +++ b/packages/cadl-ranch-specs/package.json @@ -8,12 +8,15 @@ "watch": "tsc -p ./tsconfig.build.json --watch", "build": "tsc -p ./tsconfig.build.json", "clean": "rimraf dist/ temp/", + "test:e2e": "pnpm validate-scenarios && pnpm validate-mock-apis && pnpm validate-client-server", "validate-scenarios": "cadl-ranch validate-scenarios ./http", "generate-scenarios-summary": "cadl-ranch generate-scenarios-summary ./http", "upload-manifest": "cadl-ranch upload-manifest ./http --storageAccountName azuresdkcadlranch", "upload-coverage": "cadl-ranch upload-coverage --storageAccountName azuresdkcadlranch", "validate-mock-apis": "cadl-ranch validate-mock-apis ./http", "check-scenario-coverage": "cadl-ranch check-coverage ./http", + "validate-client-server": "concurrently \"cadl-ranch server start ./http\" \"npm run client\" && cadl-ranch server stop", + "client": "cadl-ranch server-test ./http", "serve": "cadl-ranch serve ./http", "test": "echo \"Error: no test specified\" && exit 1" }, @@ -41,6 +44,7 @@ "@types/node": "^22.1.0", "@typespec/openapi": "~0.60.0", "@typespec/openapi3": "~0.60.0", + "concurrently": "^9.0.1", "rimraf": "^6.0.1", "typescript": "~5.5.4" }, diff --git a/packages/cadl-ranch/package.json b/packages/cadl-ranch/package.json index 4abdd99ea..2d64f4eec 100644 --- a/packages/cadl-ranch/package.json +++ b/packages/cadl-ranch/package.json @@ -50,7 +50,9 @@ "source-map-support": "^0.5.21", "winston": "^3.14.0", "xml2js": "^0.6.2", - "yargs": "^17.7.1" + "yargs": "^17.7.1", + "axios": "^1.7.5", + "form-data": "^3.0.1" }, "devDependencies": { "@types/body-parser": "^1.19.2", diff --git a/packages/cadl-ranch/src/actions/helper.ts b/packages/cadl-ranch/src/actions/helper.ts new file mode 100644 index 000000000..7558c9ce3 --- /dev/null +++ b/packages/cadl-ranch/src/actions/helper.ts @@ -0,0 +1,104 @@ +import { HttpMethod, ServiceRequestFile } from "@azure-tools/cadl-ranch-api"; +import axios, { AxiosRequestConfig, AxiosResponse } from "axios"; +import FormData from "form-data"; + +export interface ServiceRequest { + endPoint: string; + options?: { + requestBody?: any; + files?: ServiceRequestFile[]; + config?: AxiosRequestConfig | undefined; + }; +} + +function checkAndAddFormDataIfRequired(request: ServiceRequest) { + if (request.options?.config?.headers?.["Content-Type"] === "multipart/form-data") { + const formData = new FormData(); + if (request.options?.requestBody) { + for (const key in request.options.requestBody) { + formData.append(key, JSON.stringify(request.options.requestBody[key])); + } + } + if (request.options.files) { + request.options.files.forEach((file) => { + formData.append(`${file.fieldname}`, file.buffer, { + filename: file.originalname, + contentType: file.mimetype, + }); + }); + } + request.options.requestBody = formData; + request.options.config = { + ...request.options.config, + headers: formData.getHeaders(), + }; + } +} + +function checkAndUpdateEndpoint(request: ServiceRequest) { + if (request.options?.config?.params) { + for (const key in request.options.config.params) { + request.endPoint = request.endPoint.replace(`:${key}`, request.options.config.params[key]); + } + } + request.endPoint = request.endPoint.replace(/\[:\]/g, ":"); +} + +export async function makeServiceCall( + serviceCallType: HttpMethod, + request: ServiceRequest, +): Promise> { + checkAndUpdateEndpoint(request); + checkAndAddFormDataIfRequired(request); + if (serviceCallType === "put") { + return await makePutCall(request); + } + if (serviceCallType === "post") { + return await makePostCall(request); + } + if (serviceCallType === "get") { + return await makeGetCall(request); + } + if (serviceCallType === "delete") { + return await makeDeleteCall(request); + } + if (serviceCallType === "head") { + return await makeHeadCall(request); + } + return await makePatchCall(request); +} + +export async function makePutCall(request: ServiceRequest): Promise> { + const response = await axios.put(request.endPoint, request.options?.requestBody, request.options?.config); + return response; +} + +export async function makePostCall(request: ServiceRequest): Promise> { + const response = await axios.post(request.endPoint, request.options?.requestBody, request.options?.config); + return response; +} + +export async function makeGetCall(request: ServiceRequest): Promise> { + const response = await axios.get(request.endPoint, request.options?.config); + return response; +} + +export async function makePatchCall(request: ServiceRequest): Promise> { + const response = await axios.patch(request.endPoint, request.options?.requestBody, request.options?.config); + return response; +} + +export async function makeDeleteCall(request: ServiceRequest): Promise> { + const response = await axios.delete(request.endPoint, request.options?.config); + return response; +} + +export async function makeHeadCall(request: ServiceRequest): Promise> { + const response = await axios.head(request.endPoint, request.options?.config); + return response; +} + +type EncodingType = "utf-8" | "base64" | "base64url" | "hex"; +export function uint8ArrayToString(bytes: Uint8Array, format: EncodingType): string { + return Buffer.from(bytes).toString(format); +} diff --git a/packages/cadl-ranch/src/actions/server-test.ts b/packages/cadl-ranch/src/actions/server-test.ts new file mode 100644 index 000000000..e4ff70037 --- /dev/null +++ b/packages/cadl-ranch/src/actions/server-test.ts @@ -0,0 +1,172 @@ +import { MockApiDefinition } from "@azure-tools/cadl-ranch-api"; +import * as fs from "fs"; +import * as path from "path"; +import { logger } from "../logger.js"; +import { loadScenarioMockApis } from "../scenarios-resolver.js"; +import { makeServiceCall, uint8ArrayToString } from "./helper.js"; + +const DEFAULT_BASE_URL = "http://localhost:3000"; + +class ServerTestsGenerator { + private name: string = ""; + private mockApiDefinition: MockApiDefinition; + private serverBasePath: string = ""; + + constructor(name: string, mockApiDefinition: MockApiDefinition, serverBasePath: string) { + this.name = name; + this.mockApiDefinition = mockApiDefinition; + this.serverBasePath = serverBasePath; + } + + private getConfigObj() { + let config = {}; + if (this.mockApiDefinition.request.status) { + const validStatusCode = this.mockApiDefinition.request.status; + config = { + validateStatus: function (status: number) { + return (status >= 200 && status < 300) || validStatusCode === status; + }, + }; + } + if (this.mockApiDefinition.request.params) { + config = { + ...config, + params: this.mockApiDefinition.request.params, + }; + } + if (this.mockApiDefinition.request.headers) { + config = { + ...config, + headers: this.mockApiDefinition.request.headers, + }; + } + if (["head", "get", "delete"].includes(this.mockApiDefinition.method) && this.mockApiDefinition.request.body) { + config = { + ...config, + data: this.mockApiDefinition.request.body, + }; + } + return config; + } + + public async executeScenario() { + logger.info(`Executing ${this.name} endpoint - Method: ${this.mockApiDefinition.method}`); + + const response = await makeServiceCall(this.mockApiDefinition.method, { + endPoint: `${this.serverBasePath}${this.mockApiDefinition.uri}`, + options: { + requestBody: this.mockApiDefinition.request.body, + files: this.mockApiDefinition.request.files, + config: this.getConfigObj(), + }, + }); + + if (this.mockApiDefinition.response.status !== response.status) { + logger.error(`Status code mismatch for ${this.name} endpoint`); + logger.error(`Expected: ${this.mockApiDefinition.response.status} - Actual: ${response.status}`); + throw new Error(`Status code mismatch for ${this.name} endpoint`); + } + if (this.mockApiDefinition.response.body) { + if (this.mockApiDefinition.response.body.contentType === "application/xml") { + if (JSON.stringify(this.mockApiDefinition.response.body.rawContent) !== JSON.stringify(response.data)) { + logger.error(`Response data mismatch for ${this.name} endpoint`); + logger.error(`Expected: ${this.mockApiDefinition.response.body["rawContent"]} - Actual: ${response.data}`); + throw new Error(`Response data mismatch for ${this.name} endpoint`); + } + } else if (Buffer.isBuffer(this.mockApiDefinition.response.body.rawContent)) { + if ( + this.mockApiDefinition.request.headers && + this.mockApiDefinition.request.headers["accept"] === "application/json" + ) { + if (response.data.content !== this.mockApiDefinition.response.body.rawContent.toString("base64")) { + throw new Error(`Response data mismatch for ${this.name} endpoint`); + } + } else { + if ( + uint8ArrayToString(response.data, "utf-8") !== this.mockApiDefinition.response.body.rawContent.toString() + ) { + throw new Error(`Response data mismatch for ${this.name} endpoint`); + } + } + } else if (this.mockApiDefinition.response.body.contentType === "text/plain") { + if (this.mockApiDefinition.response.body.rawContent !== response.data) { + logger.error(`Response data mismatch for ${this.name} endpoint`); + logger.error(`Expected: ${this.mockApiDefinition.response.body} - Actual: ${response.data}`); + throw new Error(`Response data mismatch for ${this.name} endpoint`); + } + } else { + const responseData = JSON.stringify(response.data); + if (this.mockApiDefinition.response.body.rawContent !== responseData.replace(this.serverBasePath, "")) { + logger.error(`Response data mismatch for ${this.name} endpoint`); + logger.error(`Expected: ${this.mockApiDefinition.response.body} - Actual: ${response.data}`); + throw new Error(`Response data mismatch for ${this.name} endpoint`); + } + } + } + if (this.mockApiDefinition.response.headers) { + for (const key in this.mockApiDefinition.response.headers) { + if (this.mockApiDefinition.response.headers[key] !== response.headers[key].replace(this.serverBasePath, "")) { + logger.error(`Response headers mismatch for ${this.name} endpoint`); + logger.error(`Expected: ${this.mockApiDefinition.response.headers[key]} - Actual: ${response.headers[key]}`); + throw new Error(`Response headers mismatch for ${this.name} endpoint`); + } + } + } + } +} + +export interface ServerTestOptions { + baseUrl?: string; + runSingleScenario?: string; + runScenariosFromFile?: string; +} + +async function delay(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function waitForServer(baseUrl: string) { + logger.info(`Executing server tests with base URL: ${baseUrl}`); + let retry = 0; + + while (retry < 3) { + try { + await fetch(baseUrl); + break; + } catch (e) { + retry++; + logger.info("Retrying..."); + await delay(retry * 1000); + } + } + logger.info(` ${baseUrl} is ready!`); +} + +export async function serverTest(scenariosPath: string, options: ServerTestOptions = {}) { + const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL; + await waitForServer(baseUrl); + // 1. Get Testcases to run + const testCasesToRun: string[] = []; + if (options.runSingleScenario) { + testCasesToRun.push(options.runSingleScenario); + } else if (options.runScenariosFromFile) { + const data = fs.readFileSync(path.resolve(options.runScenariosFromFile), "utf8"); + const lines = data.split("\n"); + lines.forEach((line) => { + testCasesToRun.push(line.trim()); + }); + } + // 2. Load all the scenarios + const scenarios = await loadScenarioMockApis(scenariosPath); + // 3. Execute each scenario + for (const [name, scenario] of Object.entries(scenarios)) { + if (!Array.isArray(scenario.apis)) continue; + for (const api of scenario.apis) { + if (api.kind !== "MockApiDefinition") continue; + if (testCasesToRun.length === 0 || testCasesToRun.includes(name)) { + const obj: ServerTestsGenerator = new ServerTestsGenerator(name, api, baseUrl); + await obj.executeScenario(); + } + } + } +} diff --git a/packages/cadl-ranch/src/app/app.ts b/packages/cadl-ranch/src/app/app.ts index da8aa9dc0..a1c09c0e7 100644 --- a/packages/cadl-ranch/src/app/app.ts +++ b/packages/cadl-ranch/src/app/app.ts @@ -37,12 +37,24 @@ export class MockApiApp { private registerScenario(name: string, scenario: ScenarioMockApi) { for (const endpoint of scenario.apis) { - this.router.route(endpoint.uri)[endpoint.method]((req: RequestExt, res: Response) => { - processRequest(this.coverageTracker, name, endpoint.uri, req, res, endpoint.handler).catch((e) => { - logger.error("Unexpected request error", e); - res.status(500).end(); + if (endpoint.kind !== "MockApiDefinition") { + this.router.route(endpoint.uri)[endpoint.method]((req: RequestExt, res: Response) => { + processRequest(this.coverageTracker, name, endpoint.uri, req, res, endpoint.handler).catch((e) => { + logger.error("Unexpected request error", e); + res.status(500).end(); + }); }); - }); + } else { + if (!endpoint.handler) { + continue; + } + this.router.route(endpoint.uri)[endpoint.method]((req: RequestExt, res: Response) => { + processRequest(this.coverageTracker, name, endpoint.uri, req, res, endpoint.handler!).catch((e) => { + logger.error("Unexpected request error", e); + res.status(500).end(); + }); + }); + } } } } diff --git a/packages/cadl-ranch/src/cli/cli.ts b/packages/cadl-ranch/src/cli/cli.ts index ebaf946a9..806fc7630 100644 --- a/packages/cadl-ranch/src/cli/cli.ts +++ b/packages/cadl-ranch/src/cli/cli.ts @@ -10,6 +10,7 @@ import { generateScenarioSummary } from "../actions/generate-scenario-summary.js import { uploadScenarioManifest } from "../actions/upload-scenario-manifest.js"; import { uploadCoverageReport } from "../actions/upload-coverage-report.js"; import { getCommit } from "../utils/misc-utils.js"; +import { serverTest } from "../actions/server-test.js"; export const DEFAULT_PORT = 3000; @@ -147,6 +148,38 @@ async function main() { }); }, ) + .command( + "server-test ", + "Executes the test cases against the service", + (cmd) => { + return cmd + .positional("scenariosPath", { + description: "Path to the scenarios and mock apis", + type: "string", + demandOption: true, + }) + .option("baseUrl", { + description: "Path to the server", + type: "string", + }) + .option("runSingleScenario", { + description: "Single Scenario Case to run", + type: "string", + }) + .option("runScenariosFromFile", { + description: "File that has the Scenarios to run", + type: "string", + }) + .demandOption("scenariosPath", "serverBasePath"); + }, + async (args) => { + await serverTest(args.scenariosPath, { + baseUrl: args.baseUrl, + runSingleScenario: args.runSingleScenario, + runScenariosFromFile: args.runScenariosFromFile, + }); + }, + ) .command( "check-coverage ", "Serve the mock api at the given paths.", diff --git a/packages/cadl-ranch/src/coverage/coverage-tracker.ts b/packages/cadl-ranch/src/coverage/coverage-tracker.ts index d9f0e8829..e61e93440 100644 --- a/packages/cadl-ranch/src/coverage/coverage-tracker.ts +++ b/packages/cadl-ranch/src/coverage/coverage-tracker.ts @@ -1,4 +1,11 @@ -import { Fail, KeyedMockResponse, MockResponse, PassByKeyScenario, ScenarioMockApi } from "@azure-tools/cadl-ranch-api"; +import { + Fail, + KeyedMockResponse, + MockResponse, + PassByKeyScenario, + PassByServiceKeyScenario, + ScenarioMockApi, +} from "@azure-tools/cadl-ranch-api"; import { logger } from "../logger.js"; import { CoverageReport, ScenariosMetadata, ScenarioStatus } from "@azure-tools/cadl-ranch-coverage-sdk"; import { writeFileSync } from "fs"; @@ -88,7 +95,7 @@ export class CoverageTracker { return "pass"; } - function checkByKeys(scenario: PassByKeyScenario) { + function checkByKeys(scenario: PassByKeyScenario | PassByServiceKeyScenario) { for (const endpoint of scenario.apis) { const hits = scenarioHits?.get(endpoint.uri); if (hits === undefined) { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c3c688563..330ebd441 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -86,6 +86,9 @@ importers: ajv: specifier: 8.17.1 version: 8.17.1 + axios: + specifier: ^1.7.5 + version: 1.7.7 body-parser: specifier: ^1.20.2 version: 1.20.2 @@ -98,6 +101,9 @@ importers: express-promise-router: specifier: ^4.1.1 version: 4.1.1(@types/express@4.17.21)(express@4.19.2) + form-data: + specifier: ^3.0.1 + version: 3.0.1 glob: specifier: ^11.0.0 version: 11.0.0 @@ -395,6 +401,9 @@ importers: '@typespec/openapi3': specifier: ~0.60.0 version: 0.60.0(@typespec/compiler@0.60.0)(@typespec/http@0.60.0(@typespec/compiler@0.60.0))(@typespec/openapi@0.60.0(@typespec/compiler@0.60.0)(@typespec/http@0.60.0(@typespec/compiler@0.60.0)))(@typespec/versioning@0.60.0(@typespec/compiler@0.60.0))(openapi-types@12.1.3) + concurrently: + specifier: ^9.0.1 + version: 9.0.1 rimraf: specifier: ^6.0.1 version: 6.0.1 @@ -2503,6 +2512,9 @@ packages: resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==} engines: {node: '>= 0.4'} + axios@1.7.7: + resolution: {integrity: sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==} + babel-jest@29.7.0: resolution: {integrity: sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} @@ -2773,6 +2785,11 @@ packages: resolution: {integrity: sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==} engines: {'0': node >= 0.8} + concurrently@9.0.1: + resolution: {integrity: sha512-wYKvCd/f54sTXJMSfV6Ln/B8UrfLBKOYa+lzc6CHay3Qek+LorVSBdMVfyewFhRbH0Rbabsk4D+3PL/VjQ5gzg==} + engines: {node: '>=18'} + hasBin: true + content-disposition@0.5.4: resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==} engines: {node: '>= 0.6'} @@ -3359,6 +3376,15 @@ packages: fn.name@1.1.0: resolution: {integrity: sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==} + follow-redirects@1.15.9: + resolution: {integrity: sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==} + engines: {node: '>=4.0'} + peerDependencies: + debug: '*' + peerDependenciesMeta: + debug: + optional: true + for-each@0.3.3: resolution: {integrity: sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==} @@ -3366,6 +3392,10 @@ packages: resolution: {integrity: sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==} engines: {node: '>=14'} + form-data@3.0.1: + resolution: {integrity: sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==} + engines: {node: '>= 6'} + form-data@4.0.0: resolution: {integrity: sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==} engines: {node: '>= 6'} @@ -4181,6 +4211,9 @@ packages: lodash.startcase@4.4.0: resolution: {integrity: sha512-+WKqsK294HMSc2jEbNgpHpd0JfIBhp7rEV4aqXWqFr6AlXov+SlcgB1Fv01y2kGe3Gc8nMW7VA0SrGuSkRfIEg==} + lodash@4.17.21: + resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==} + log-symbols@4.1.0: resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==} engines: {node: '>=10'} @@ -4790,6 +4823,9 @@ packages: resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} engines: {node: '>= 0.10'} + proxy-from-env@1.1.0: + resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==} + pseudomap@1.0.2: resolution: {integrity: sha512-b/YwNhb8lk1Zz2+bXXpS/LK9OisiZZ1SNsSLxN1x2OXVEhW2Ckr/7mWE5vrC1ZTiJlD9g19jWszTmJsB+oEpFQ==} @@ -4970,6 +5006,9 @@ packages: run-parallel@1.2.0: resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} + rxjs@7.8.1: + resolution: {integrity: sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==} + safe-array-concat@1.1.2: resolution: {integrity: sha512-vj6RsCsWBCf19jIeHEfkRMw8DPiBb+DMXklQ/1SGDHOMlHdPUkZXFQ2YdplS23zESTijAcurb1aSgJA3AgMu1Q==} engines: {node: '>=0.4'} @@ -5048,6 +5087,9 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} + shell-quote@1.8.1: + resolution: {integrity: sha512-6j1W9l1iAs/4xYBI1SYOVZyFcCis9b4KCLQ8fgAGG07QvzaRLVVRQvAy85yNmmZSjYjg4MWh4gNvlPujU/5LpA==} + side-channel@1.0.6: resolution: {integrity: sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==} engines: {node: '>= 0.4'} @@ -5313,6 +5355,10 @@ packages: resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} engines: {node: '>=0.6'} + tree-kill@1.2.2: + resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==} + hasBin: true + trim-lines@3.0.1: resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} @@ -8710,6 +8756,14 @@ snapshots: dependencies: possible-typed-array-names: 1.0.0 + axios@1.7.7: + dependencies: + follow-redirects: 1.15.9 + form-data: 4.0.0 + proxy-from-env: 1.1.0 + transitivePeerDependencies: + - debug + babel-jest@29.7.0(@babel/core@7.25.2): dependencies: '@babel/core': 7.25.2 @@ -9024,6 +9078,16 @@ snapshots: readable-stream: 2.3.8 typedarray: 0.0.6 + concurrently@9.0.1: + dependencies: + chalk: 4.1.2 + lodash: 4.17.21 + rxjs: 7.8.1 + shell-quote: 1.8.1 + supports-color: 8.1.1 + tree-kill: 1.2.2 + yargs: 17.7.2 + content-disposition@0.5.4: dependencies: safe-buffer: 5.2.1 @@ -9802,6 +9866,8 @@ snapshots: fn.name@1.1.0: {} + follow-redirects@1.15.9: {} + for-each@0.3.3: dependencies: is-callable: 1.2.7 @@ -9811,6 +9877,12 @@ snapshots: cross-spawn: 7.0.3 signal-exit: 4.1.0 + form-data@3.0.1: + dependencies: + asynckit: 0.4.0 + combined-stream: 1.0.8 + mime-types: 2.1.35 + form-data@4.0.0: dependencies: asynckit: 0.4.0 @@ -10786,6 +10858,8 @@ snapshots: lodash.startcase@4.4.0: {} + lodash@4.17.21: {} + log-symbols@4.1.0: dependencies: chalk: 4.1.2 @@ -11584,6 +11658,8 @@ snapshots: forwarded: 0.2.0 ipaddr.js: 1.9.1 + proxy-from-env@1.1.0: {} + pseudomap@1.0.2: {} punycode@2.3.1: {} @@ -11805,6 +11881,10 @@ snapshots: dependencies: queue-microtask: 1.2.3 + rxjs@7.8.1: + dependencies: + tslib: 2.6.3 + safe-array-concat@1.1.2: dependencies: call-bind: 1.0.7 @@ -11899,6 +11979,8 @@ snapshots: shebang-regex@3.0.0: {} + shell-quote@1.8.1: {} + side-channel@1.0.6: dependencies: call-bind: 1.0.7 @@ -12180,6 +12262,8 @@ snapshots: toidentifier@1.0.1: {} + tree-kill@1.2.2: {} + trim-lines@3.0.1: {} triple-beam@1.4.1: {}