Skip to content
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

Fix mocking of gRPC-web and Connect GET requests #100

Merged
merged 10 commits into from
Jan 24, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions packages/connect-playwright-example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,39 @@

import { useCallback, useState, FormEvent, FC } from "react";
import { ConnectError, createPromiseClient } from "@connectrpc/connect";
import { createConnectTransport } from "@connectrpc/connect-web";
import {
createGrpcWebTransport,
createConnectTransport,
} from "@connectrpc/connect-web";
import { ElizaService } from "./gen/connectrpc/eliza/v1/eliza_connect.js";

interface ChatMessage {
text: string;
sender: "eliza" | "user";
}

// Read the transport and format parameters from the URL
smaye81 marked this conversation as resolved.
Show resolved Hide resolved
const params = new URLSearchParams(window.location.search);
const transportParam = params.get("transport");
const format = params.get("format");

let useBinaryFormat;
let transportFn;
if (transportParam === "grpcweb") {
transportFn = createGrpcWebTransport;
// gRPC-web uses the binary format by default
useBinaryFormat = format !== null ? format === "binary" : true;
smaye81 marked this conversation as resolved.
Show resolved Hide resolved
} else {
transportFn = createConnectTransport;
// Connect uses the JSON format by default
useBinaryFormat = format !== null ? format === "binary" : false;
}

const elizaClient = createPromiseClient(
ElizaService,
createConnectTransport({
transportFn({
baseUrl: "https://demo.connectrpc.com",
useBinaryFormat,
}),
);

Expand Down
65 changes: 65 additions & 0 deletions packages/connect-playwright-example/tests/transport.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// 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&format=binary",
baseURL + "?transport=grpcweb",
baseURL + "?transport=grpcweb&format=json",
].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");
});
});
});
14 changes: 12 additions & 2 deletions packages/connect-playwright/src/create-mock-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ import type {
} from "@bufbuild/protobuf";
import { MethodKind } from "@bufbuild/protobuf";
import type { UniversalHandler } from "@connectrpc/connect/protocol";
import { readAllBytes } from "@connectrpc/connect/protocol";
import {
readAllBytes,
createAsyncIterable,
} from "@connectrpc/connect/protocol";

export interface MockRouter {
service: <S extends ServiceType>(
Expand Down Expand Up @@ -186,12 +189,19 @@ async function universalHandlerToRouteResponse({
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;
if (headers["content-type"] === "application/json") {

const contentType = headers["content-type"];

if (contentType === "application/json") {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
body = request.postDataJSON();
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
body = request.postDataBuffer();
// gRPC-web expects the body to be an AsyncIterable
if (contentType.startsWith("application/grpc-web")) {
body = createAsyncIterable([body]);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The body property of the type UniversalServerRequest is AsyncIterable<Uint8Array> | JsonValue. We're still passing in other types here. We do not need to special case the gRPC-web content type, only application/json.

Please update let body: any to not use any - this is how this bug slipped in in the first place. I suggest we use let body: UniversalServerRequest["body"].

}

const response = await routeHandler({
Expand Down