-
Notifications
You must be signed in to change notification settings - Fork 6
Fix mocking of gRPC-web and Connect GET requests #100
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
c26ef2a
Handle grpc web transports
smaye81 98e11c8
Fix tests
smaye81 d9447c1
Fixes
smaye81 c4c08b9
Fixes
smaye81 07faa38
Update packages/connect-playwright-example/src/App.tsx
smaye81 bbe18c6
Comment
smaye81 d129330
Feedback
smaye81 2611c79
Add GET tests
smaye81 31203a6
Comments
smaye81 3c307cb
Feedback
smaye81 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
67 changes: 67 additions & 0 deletions
67
packages/connect-playwright-example/tests/transport.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
// Copyright 2023-2024 The Connect Authors | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
import { expect, Locator, test } from "@playwright/test"; | ||
|
||
import { ElizaService } from "../src/gen/connectrpc/eliza/v1/eliza_connect.js"; | ||
import { createMockRouter, MockRouter } from "@connectrpc/connect-playwright"; | ||
|
||
test.describe("transports", () => { | ||
let respText: Locator; | ||
let statementInput: Locator; | ||
let sendButton: Locator; | ||
let mock: MockRouter; | ||
let baseURL = ""; | ||
|
||
test.beforeEach(async ({ page, context }, { project }) => { | ||
respText = page.locator(".eliza-resp-container p"); | ||
statementInput = page.locator("#statement-input"); | ||
sendButton = page.locator("#send"); | ||
|
||
baseURL = project.use.baseURL ?? ""; | ||
|
||
mock = createMockRouter(context, { | ||
baseUrl: "https://demo.connectrpc.com", | ||
}); | ||
|
||
await mock.service(ElizaService, { | ||
say() { | ||
return { | ||
sentence: "Mock response", | ||
}; | ||
}, | ||
}); | ||
}); | ||
|
||
[ | ||
baseURL, | ||
baseURL + "?transport=connect", | ||
baseURL + "?transport=connect&useHttpGet=true", | ||
baseURL + "?transport=connect&format=binary", | ||
baseURL + "?transport=connect&format=binary&useHttpGet=true", | ||
baseURL + "?transport=grpcweb", | ||
baseURL + "?transport=grpcweb&format=json", | ||
Comment on lines
+48
to
+54
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nice to have coverage against regressions 🎉 |
||
].forEach((url) => { | ||
test(`correctly mocks with params ${url}`, async ({ page }) => { | ||
await page.goto(url); | ||
|
||
// Type a name and send | ||
await statementInput.fill("Hello"); | ||
await sendButton.click(); | ||
|
||
// This should be the mocked response we return from say() above | ||
await expect(respText).toHaveText("Mock response"); | ||
}); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -21,11 +21,18 @@ import type { | |
BinaryReadOptions, | ||
BinaryWriteOptions, | ||
JsonReadOptions, | ||
JsonValue, | ||
JsonWriteOptions, | ||
} from "@bufbuild/protobuf"; | ||
import { MethodKind } from "@bufbuild/protobuf"; | ||
import type { UniversalHandler } from "@connectrpc/connect/protocol"; | ||
import { readAllBytes } from "@connectrpc/connect/protocol"; | ||
import type { | ||
UniversalHandler, | ||
UniversalServerRequest, | ||
} from "@connectrpc/connect/protocol"; | ||
import { | ||
readAllBytes, | ||
createAsyncIterable, | ||
} from "@connectrpc/connect/protocol"; | ||
|
||
export interface MockRouter { | ||
service: <S extends ServiceType>( | ||
|
@@ -55,6 +62,17 @@ interface Options { | |
binaryOptions?: Partial<BinaryReadOptions & BinaryWriteOptions>; | ||
} | ||
|
||
// Builds a regular expression for matching paths by appending the suffix onto | ||
// base and escaping forward slashes and periods | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
function buildPathRegex(base: string, suffix: string) { | ||
const sanitized = base | ||
.replace(/\/?$/, suffix) | ||
.replace(/\./g, "\\.") | ||
.replace(/\//g, "\\/"); | ||
|
||
return new RegExp(sanitized); | ||
} | ||
|
||
export function createMockRouter( | ||
context: BrowserContext, | ||
options: Options, | ||
|
@@ -74,11 +92,13 @@ export function createMockRouter( | |
if (method.kind !== MethodKind.Unary) { | ||
throw new Error("Cannot add non-unary method."); | ||
} | ||
const requestPath = baseUrl | ||
.toString() | ||
.replace(/\/?$/, `/${service.typeName}/${method.name}`); | ||
|
||
return context.route(requestPath, async (route, request) => { | ||
const pathRegex = buildPathRegex( | ||
baseUrl, | ||
`/${service.typeName}/${method.name}`, | ||
); | ||
|
||
return context.route(pathRegex, async (route, request) => { | ||
if (handler !== "mock") { | ||
const router = createConnectRouter(routerOptions).rpc( | ||
service, | ||
|
@@ -122,11 +142,9 @@ export function createMockRouter( | |
}), | ||
); | ||
} | ||
const requestPath = baseUrl | ||
.toString() | ||
.replace(/\/?$/, `/${service.typeName}/**`); | ||
const pathRegex = buildPathRegex(baseUrl, `/${service.typeName}/*`); | ||
|
||
return context.route(requestPath, async (route, request) => { | ||
return context.route(pathRegex, async (route, request) => { | ||
const remainingPath = new URL(request.url()).pathname.replace( | ||
new RegExp(`^/${service.typeName}/`), | ||
"", | ||
|
@@ -184,18 +202,26 @@ async function universalHandlerToRouteResponse({ | |
}) { | ||
const headers = await request.allHeaders(); | ||
const abortSignal = new AbortController().signal; | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- The Serializable type isn't exposed by Playwright | ||
let body: any; | ||
|
||
// Default body to an empty byte stream | ||
let body: UniversalServerRequest["body"]; | ||
|
||
if (headers["content-type"] === "application/json") { | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment | ||
body = request.postDataJSON(); | ||
// If content type headers are present and set to JSON, this is a POST | ||
// request with a JSON body | ||
body = request.postDataJSON() as JsonValue; | ||
} else { | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment | ||
body = request.postDataBuffer(); | ||
const buffer = request.postDataBuffer(); | ||
if (buffer !== null) { | ||
// If postDataBuffer returns a non-null body, this is a POST | ||
// request with a binary body | ||
body = createAsyncIterable<Uint8Array>([buffer]); | ||
} else { | ||
body = createAsyncIterable<Uint8Array>([]); | ||
} | ||
} | ||
|
||
const response = await routeHandler({ | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- No current way around this, we just have no idea what this returns | ||
body, | ||
url: request.url(), | ||
header: new Headers(headers), | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.