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 7 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
28 changes: 26 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,42 @@

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
// Note that users do not need to worry about this since this is just for
// testing purposes so that we can easily verify various transports and
// serialization formats.
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 === "binary";
} 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");
});
});
});
25 changes: 16 additions & 9 deletions packages/connect-playwright/src/create-mock-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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>(
Expand Down Expand Up @@ -184,18 +191,18 @@ 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;
let body: UniversalServerRequest["body"] = [];
Copy link
Member Author

Choose a reason for hiding this comment

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

Not sure of the best default value for this.

Copy link
Member

Choose a reason for hiding this comment

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

[] is not a type error because the body can be pre-parsed JSON, and [] is a valid JSON value.

You are providing the request body [] to the call, if the original request had an empty body. That's no good. To provide an empty request body, create an empty byte stream with createAsyncIterable<Uint8Array>([]).

Let's also add a test for Connect GET, because I'm pretty sure we would crash on it.


if (headers["content-type"] === "application/json") {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
body = request.postDataJSON();
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) {
body = createAsyncIterable([buffer]);
}
}

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),
Expand Down