diff --git a/.github/workflows/wizard-e2e.yml b/.github/workflows/wizard-e2e.yml new file mode 100644 index 000000000..76a33ec7a --- /dev/null +++ b/.github/workflows/wizard-e2e.yml @@ -0,0 +1,49 @@ +name: Wizard E2E + +# `sentry wizard` end-to-end tests: each job sets up Sentry in a real +# framework app, installs its packages, and builds and runs it. They take +# minutes per app, so they run only when the wizard or its tests change. +on: + pull_request: + paths: + - "packages/cli/src/commands/wizard.ts" + - "packages/cli/src/lib/wizard/**" + - "packages/cli/test/wizard-e2e/**" + - "packages/cli/test/mocks/**" + - ".github/workflows/wizard-e2e.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + wizard-e2e: + name: Wizard E2E (${{ matrix.test }}) + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + # One job per file in packages/cli/test/wizard-e2e/. + test: + - help-message + - nextjs-14 + - nextjs-15 + - nextjs-16 + env: + SENTRY_CLIENT_ID: test-client-id + SENTRY_CLI_NO_TELEMETRY: "1" + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: "22.23.4" + cache: pnpm + - run: pnpm install --frozen-lockfile + - name: Run ${{ matrix.test }} + env: + TEST_FILE: test/wizard-e2e/${{ matrix.test }}.test.ts + run: pnpm --filter sentry run test:wizard-e2e "$TEST_FILE" diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 5217b46bd..9e34e9201 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -14,6 +14,7 @@ "packages/mcp-server-mocks/src/fixtures/**", "packages/mcp-core/src/ui/chart-app.generated.ts", "packages/codemod-cli3to4/tests/**", + "packages/cli/test/wizard-e2e/test-applications/**", "**/worker-configuration.d.ts", "**/tsconfig*.json" ] diff --git a/.oxlintrc.json b/.oxlintrc.json index 4304d7920..a03f0b98e 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -14,7 +14,8 @@ "**/tsconfig*.json", "packages/mcp-server-mocks/src/fixtures/**", "packages/mcp-core/src/ui/chart-app.generated.ts", - "packages/codemod-cli3to4/tests/**" + "packages/codemod-cli3to4/tests/**", + "packages/cli/test/wizard-e2e/test-applications/**" ], "rules": { "no-unused-vars": [ diff --git a/packages/cli/package.json b/packages/cli/package.json index 8f256c11d..d09e958d4 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -66,6 +66,7 @@ "test:unit": "node --experimental-strip-types --import ./script/require-shim.mjs script/generate.ts docs sdk && vitest run test/lib test/commands test/types test/script --coverage", "test:changed": "node --experimental-strip-types --import ./script/require-shim.mjs script/generate.ts docs sdk && vitest run --changed", "test:e2e": "pnpm ts script/prepare-e2e-bundle.ts && vitest run test/e2e", + "test:wizard-e2e": "pnpm ts script/prepare-e2e-bundle.ts && vitest run -c test/wizard-e2e/vitest.config.ts", "generate": "node --experimental-strip-types --import ./script/require-shim.mjs script/generate.ts docs sdk", "generate:sdk": "node --experimental-strip-types --import ./script/require-shim.mjs script/generate.ts sdk", "generate:skill": "node --experimental-strip-types --import ./script/require-shim.mjs script/generate.ts skill", diff --git a/packages/cli/test/tsconfig.json b/packages/cli/test/tsconfig.json index 4764d194e..97487f6ca 100644 --- a/packages/cli/test/tsconfig.json +++ b/packages/cli/test/tsconfig.json @@ -3,5 +3,6 @@ "compilerOptions": { "lib": ["ESNext", "DOM"] }, - "include": ["**/*.ts", "**/*.tsx", "../src/lib/wizard/xcode.d.ts"] + "include": ["**/*.ts", "**/*.tsx", "../src/lib/wizard/xcode.d.ts"], + "exclude": ["wizard-e2e/test-applications"] } diff --git a/packages/cli/test/wizard-e2e/README.md b/packages/cli/test/wizard-e2e/README.md new file mode 100644 index 000000000..0f568c437 --- /dev/null +++ b/packages/cli/test/wizard-e2e/README.md @@ -0,0 +1,62 @@ +# `sentry wizard` end-to-end tests + +Each test copies an app from `test-applications/` to a temporary git +repository, runs the CLI's `sentry wizard` in it while answering its prompts, +and then checks the files the wizard wrote and that the app still builds and +runs. They were moved here from getsentry/sentry-wizard's `e2e-tests/`. + +The wizard never talks to sentry.io. `global-setup.ts` starts a local mock +Sentry API (the routes in `../mocks/routes.ts`, plus org auth token creation). +Every run gets its URL in `SENTRY_URL` and its token in `SENTRY_AUTH_TOKEN`, +and `getWizardCommand()` runs `sentry wizard test-org/test-project `. +For a run without a project, pass `env: { SENTRY_SPOTLIGHT: "1" }` to +`withEnv()` and run `["wizard", ]`. No secrets are needed. + +## Running + +```bash +# From packages/cli. Builds the npm bundle, then runs every test file. +pnpm run test:wizard-e2e + +# One file +pnpm run test:wizard-e2e test/wizard-e2e/nextjs-15.test.ts +``` + +The tests run the npm bundle (`dist/bin.cjs`), or the CLI in +`SENTRY_CLI_BINARY` when set. They need network access for the apps' package +installs, and the package managers the tests pick (npm, pnpm and Yarn v1). + +- `SENTRY_WIZARD_E2E_DEBUG=true` streams the wizard's output. +- `SENTRY_WIZARD_E2E_KEEP_TEMP=true` keeps the temporary app directories. + +`test:unit` and `test:e2e` don't run these. In CI, `wizard-e2e.yml` runs one +job per test file on pull requests that change the wizard or these tests, and +on manual dispatch. Add a new test file to its matrix. + +## Writing tests + +Isolate each wizard run in its own `describe` block with +`createIsolatedTestEnv()`, run the wizard in `beforeAll`, and clean up in +`afterAll`. `withEnv().defineInteraction()` scripts the answers, in the shape +of the `clifty` builder the sentry-wizard tests used: + +```ts +const { projectDir, cleanup } = createIsolatedTestEnv("nextjs-15-test-app"); + +beforeAll(async () => { + wizardExitCode = await withEnv({ cwd: projectDir }) + .defineInteraction() + .whenAsked("Please select your package manager.") + .respondWith(KEYS.ENTER) + .expectOutput("Successfully installed the Sentry Next.js SDK!") + .run(getWizardCommand("nextjs")); +}); + +afterAll(() => { + cleanup(); +}); +``` + +Each step waits for its text after the previous step's match, so list prompts +in the order the wizard asks them. Test apps have no lockfiles, so the wizard +picks the package manager the test selects. diff --git a/packages/cli/test/wizard-e2e/constants.ts b/packages/cli/test/wizard-e2e/constants.ts new file mode 100644 index 000000000..29a399f8f --- /dev/null +++ b/packages/cli/test/wizard-e2e/constants.ts @@ -0,0 +1,22 @@ +/** + * The org, project, and tokens of the mock Sentry API that the wizard e2e + * tests run against. No vitest imports, so `global-setup.ts` can load it. + */ + +import { + TEST_DSN, + TEST_ORG, + TEST_PROJECT, + TEST_TOKEN, +} from "../mocks/routes.js"; + +/** The org, project, and tokens the mock Sentry API serves. */ +export const TEST_ARGS = { + /** The CLI's login token, which the mock API accepts. */ + LOGIN_TOKEN: TEST_TOKEN, + /** The org auth token the mock API mints for source map uploads. */ + AUTH_TOKEN: "sntrys_wizard-e2e-org-auth-token", + PROJECT_DSN: TEST_DSN, + ORG_SLUG: TEST_ORG, + PROJECT_SLUG: TEST_PROJECT, +} as const; diff --git a/packages/cli/test/wizard-e2e/global-setup.ts b/packages/cli/test/wizard-e2e/global-setup.ts new file mode 100644 index 000000000..99d908a14 --- /dev/null +++ b/packages/cli/test/wizard-e2e/global-setup.ts @@ -0,0 +1,43 @@ +/** + * Starts one mock Sentry API for every wizard e2e test, so a wizard run can + * log in, read its preselected org and project, and mint an org auth token + * without a Sentry account. Tests read its URL with `inject("sentryUrl")`. + */ + +import type { TestProject } from "vitest/node"; +import { apiRoutes } from "../mocks/routes.js"; +import { createMockServer } from "../mocks/server.js"; +import { TEST_ARGS } from "./constants.js"; + +declare module "vitest" { + export interface ProvidedContext { + /** Origin of the mock Sentry API, for `SENTRY_URL`. */ + sentryUrl: string; + } +} + +export default async function setup(project: TestProject): Promise<() => void> { + const server = createMockServer( + [ + ...apiRoutes, + { + method: "POST", + path: "/api/0/organizations/:orgSlug/org-auth-tokens/", + status: 201, + response: { + id: "1", + name: "Sentry Wizard", + scopes: ["org:ci"], + tokenLastCharacters: TEST_ARGS.AUTH_TOKEN.slice(-4), + dateCreated: "2024-01-01T00:00:00.000Z", + dateLastUsed: null, + token: TEST_ARGS.AUTH_TOKEN, + }, + }, + ], + { validTokens: [TEST_ARGS.LOGIN_TOKEN] }, + ); + await server.start(); + project.provide("sentryUrl", server.url); + return () => server.stop(); +} diff --git a/packages/cli/test/wizard-e2e/help-message.test.ts b/packages/cli/test/wizard-e2e/help-message.test.ts new file mode 100644 index 000000000..c54dd348e --- /dev/null +++ b/packages/cli/test/wizard-e2e/help-message.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest"; +import { runCli } from "./utils.js"; + +describe("sentry wizard --help", () => { + it("prints the up to date help", () => { + const { exitCode, stdout } = runCli(["wizard", "--help"]); + + expect(exitCode).toBe(0); + expect(stdout).toMatchInlineSnapshot(` + "USAGE + sentry wizard [/] [] + sentry wizard --help + + Set up Sentry in the project in the current directory. The wizard asks you a few questions, installs the Sentry SDK for your framework, writes its configuration, and sets up source map or debug file uploads. + + It logs in with your \`sentry auth login\` account (or starts a login) on the Sentry instance the rest of the CLI uses, and lets you pick or create the Sentry project to send data to. Pass \`/\` first to skip those questions, or \`/\` to pick only the project. Pass an integration, such as \`nextjs\`, to skip the integration picker. Integrations: reactNative, flutter, ios, appleSnapshots, angular, android, nextjs, nuxt, remix, reactRouter, sveltekit, cloudflare, sourcemaps. + + An integration id is never read as a project or org, and a single bare word is always read as an integration. To name a project or org, write it with a \`/\`: \`my-org/my-project\`, \`my-org/\`, or \`/my-project\` (for a project spelled like an integration, \`my-org/nextjs\`). + + Set \`SENTRY_SPOTLIGHT=1\` to set up Spotlight for local development instead, without a Sentry account or login. Use the global \`--verbose\` flag for the wizard's debug output. + + The wizard changes files in your project. To have a coding agent set up Sentry instead, run \`sentry init\`, which prints the agent's setup guide and changes nothing. + + Examples: + sentry wizard # Pick an integration and a project, then set it up + sentry wizard nextjs # Set up Next.js, picking the project + sentry wizard my-org/my-project nextjs # Set up Next.js for a known org and project + SENTRY_SPOTLIGHT=1 sentry wizard nextjs # Set up Next.js for Spotlight, without a Sentry account + + FLAGS + -f [--force] Change a project with uncommitted changes without asking, and install the SDK even when the package manager's checks fail [default = false] + -h --help Print help information and exit + -- All subsequent inputs should be interpreted as arguments + + ARGUMENTS + org/project-or-integration... / to set up (skips the project picker), then the integration (skips the integration picker) + " + `); + }); + + // Flags of `npx @sentry/wizard` that `sentry wizard` dropped. `--org` and + // `--project` still work: every CLI command takes them as hidden flags that + // set SENTRY_ORG and SENTRY_PROJECT. + it.each([ + ["--signup"], + ["-s"], + ["--promo-code", "CODE"], + ["--coming-from", "partner"], + ["-i", "nextjs"], + ["--url", "https://sentry.example.com"], + ["--saas"], + ["--spotlight"], + ["--force-install"], + ["--ignore-git-changes"], + ["--disable-telemetry"], + ["--debug"], + ])("rejects the removed flag %s", (...flag) => { + const { exitCode, stderr } = runCli(["wizard", ...flag]); + + expect(exitCode).not.toBe(0); + expect(stderr).toMatch(/^No (flag|alias) registered for /); + }); +}); diff --git a/packages/cli/test/wizard-e2e/nextjs-14.test.ts b/packages/cli/test/wizard-e2e/nextjs-14.test.ts new file mode 100644 index 000000000..351836a46 --- /dev/null +++ b/packages/cli/test/wizard-e2e/nextjs-14.test.ts @@ -0,0 +1,155 @@ +import { afterAll, beforeAll, describe, expect, test } from "vitest"; +import { + checkEnvBuildPlugin, + checkFileContents, + checkFileExists, + checkIfBuilds, + checkIfRunsOnDevMode, + checkIfRunsOnProdMode, + checkPackageJson, + createIsolatedTestEnv, + getWizardCommand, + KEYS, + withEnv, +} from "./utils.js"; + +describe("NextJS-14", () => { + let wizardExitCode: number; + + const { projectDir, cleanup } = createIsolatedTestEnv("nextjs-14-test-app"); + + beforeAll(async () => { + wizardExitCode = await withEnv({ cwd: projectDir }) + .defineInteraction() + .whenAsked("Please select your package manager.") + .respondWith(KEYS.DOWN, KEYS.ENTER) // Select yarn + .expectOutput("Installing @sentry/nextjs") + .whenAsked( + "Do you want to reduce this to avoid sending personally identifiable information", + { + timeout: 240_000, // package installation can take a while in CI + }, + ) + .respondWith(KEYS.ENTER) // No + .whenAsked( + "Do you want to route Sentry requests in the browser through your Next.js server", + ) + .respondWith(KEYS.ENTER) + .whenAsked("to track the performance of your application?") + .respondWith(KEYS.ENTER) + .whenAsked( + "to get a video-like reproduction of errors during a user session?", + ) + .respondWith(KEYS.ENTER) + .whenAsked("Do you want to create an example page") + .respondWith(KEYS.ENTER) + .whenAsked("Are you using a CI/CD tool") + .respondWith(KEYS.DOWN, KEYS.ENTER) // Select No + .whenAsked( + "Optionally add a project-scoped MCP server configuration for the Sentry MCP?", + ) + .respondWith(KEYS.DOWN, KEYS.ENTER) // Decline MCP config + .expectOutput("Successfully installed the Sentry Next.js SDK!") + .run(getWizardCommand("nextjs")); + }); + + afterAll(() => { + cleanup(); + }); + + test("exits with exit code 0", () => { + expect(wizardExitCode).toBe(0); + }); + + test("package.json is updated correctly", () => { + checkPackageJson(projectDir, "@sentry/nextjs"); + }); + + test(".env-sentry-build-plugin is created and contains the auth token", () => { + checkEnvBuildPlugin(projectDir); + }); + + test("example page exists", () => { + checkFileExists(`${projectDir}/src/app/layout.tsx`); + checkFileExists(`${projectDir}/src/app/sentry-example-page/page.tsx`); + checkFileExists(`${projectDir}/src/app/api/sentry-example-api/route.ts`); + }); + + test("config files created", () => { + checkFileExists(`${projectDir}/sentry.server.config.ts`); + checkFileExists(`${projectDir}/sentry.edge.config.ts`); + }); + + test("global error file exists", () => { + checkFileExists(`${projectDir}/src/app/global-error.tsx`); + }); + + test("instrumentation files exists", () => { + checkFileExists(`${projectDir}/src/instrumentation.ts`); + checkFileExists(`${projectDir}/src/instrumentation-client.ts`); + }); + + test("instrumentation file contains Sentry initialization", () => { + checkFileContents(`${projectDir}/src/instrumentation.ts`, [ + 'import * as Sentry from "@sentry/nextjs";', + `export async function register() { + if (process.env.NEXT_RUNTIME === "nodejs") { + await import("../sentry.server.config"); + } + + if (process.env.NEXT_RUNTIME === "edge") { + await import("../sentry.edge.config"); + } +} + +export const onRequestError = Sentry.captureRequestError;`, + ]); + }); + + test("next.config file contains Sentry wrapper", () => { + checkFileContents(`${projectDir}/next.config.mjs`, [ + "import { withSentryConfig } from '@sentry/nextjs/config'", + "export default withSentryConfig(nextConfig, {", + ]); + }); + + test("runs on dev mode correctly", async () => { + await checkIfRunsOnDevMode(projectDir, "Ready in"); + }); + + test("builds correctly", async () => { + await checkIfBuilds(projectDir); + }); + + test("runs on prod mode correctly", async () => { + await checkIfRunsOnProdMode(projectDir, "Ready in"); + }); + + test("root layout contains generateMetadata function", () => { + checkFileContents(`${projectDir}/src/app/layout.tsx`, [ + "// This file was generated by the Sentry wizard because we couldn't find a root layout file.", + "import * as Sentry from '@sentry/nextjs';", + "import type { Metadata } from 'next';", + "", + "export function generateMetadata(): Metadata {", + " return {", + " other: {", + " ...Sentry.getTraceData(),", + " }", + " }", + "};", + "", + "export default function RootLayout({", + " children,", + "}: {", + " children: React.ReactNode", + "}) {", + " return (", + ' ', + " {children}", + " ", + " )", + "}", + ]); + }); +}); diff --git a/packages/cli/test/wizard-e2e/nextjs-15.test.ts b/packages/cli/test/wizard-e2e/nextjs-15.test.ts new file mode 100644 index 000000000..9d3f7f769 --- /dev/null +++ b/packages/cli/test/wizard-e2e/nextjs-15.test.ts @@ -0,0 +1,242 @@ +import { afterAll, beforeAll, describe, expect, test } from "vitest"; +import { + checkEnvBuildPlugin, + checkFileContents, + checkFileDoesNotExist, + checkFileExists, + checkIfBuilds, + checkIfRunsOnDevMode, + checkIfRunsOnProdMode, + checkPackageJson, + createIsolatedTestEnv, + getWizardCommand, + KEYS, + withEnv, +} from "./utils.js"; +import { TEST_ARGS } from "./constants.js"; + +describe("NextJS-15", () => { + let wizardExitCode: number; + + const { projectDir, cleanup } = createIsolatedTestEnv("nextjs-15-test-app"); + + beforeAll(async () => { + wizardExitCode = await withEnv({ cwd: projectDir }) + .defineInteraction() + .expectOutput( + `Selected project ${TEST_ARGS.ORG_SLUG}/${TEST_ARGS.PROJECT_SLUG}`, + ) + .whenAsked("Please select your package manager.") + .respondWith(KEYS.DOWN, KEYS.DOWN, KEYS.DOWN, KEYS.ENTER) // Select pnpm + .whenAsked( + "Do you want to reduce this to avoid sending personally identifiable information", + { + timeout: 240_000, // package installation can take a while in CI + }, + ) + .respondWith(KEYS.ENTER) // No + .whenAsked( + "Do you want to route Sentry requests in the browser through your Next.js server", + ) + .respondWith(KEYS.ENTER) + .whenAsked("to track the performance of your application?") + .respondWith(KEYS.ENTER) + .whenAsked( + "to get a video-like reproduction of errors during a user session?", + ) + .respondWith(KEYS.ENTER) + .whenAsked("Do you want to create an example page") + .respondWith(KEYS.ENTER) + .whenAsked("Are you using a CI/CD tool") + .respondWith(KEYS.DOWN, KEYS.ENTER) // Select No + .whenAsked( + "Optionally add a project-scoped MCP server configuration for the Sentry MCP?", + ) + .respondWith(KEYS.ENTER) // Accept MCP config + .whenAsked("Which editor(s) do you want to configure?") + .respondWith(KEYS.SPACE, KEYS.ENTER) // Select Cursor + .expectOutput("Successfully installed the Sentry Next.js SDK!") + .run(getWizardCommand("nextjs")); + }); + + afterAll(() => { + cleanup(); + }); + + test("exits with exit code 0", () => { + expect(wizardExitCode).toBe(0); + }); + + test("package.json is updated correctly", () => { + checkPackageJson(projectDir, "@sentry/nextjs"); + }); + + test(".env-sentry-build-plugin is created and contains the auth token", () => { + checkEnvBuildPlugin(projectDir); + }); + + test("example page exists", () => { + checkFileExists(`${projectDir}/src/app/sentry-example-page/page.tsx`); + checkFileExists(`${projectDir}/src/app/api/sentry-example-api/route.ts`); + }); + + test("config files created", () => { + checkFileExists(`${projectDir}/sentry.server.config.ts`); + checkFileExists(`${projectDir}/sentry.edge.config.ts`); + }); + + test("config files contain the project's DSN", () => { + checkFileContents( + `${projectDir}/sentry.server.config.ts`, + `dsn: "${TEST_ARGS.PROJECT_DSN}"`, + ); + }); + + test("global error file exists", () => { + checkFileExists(`${projectDir}/src/app/global-error.tsx`); + }); + + test("instrumentation files exists", () => { + checkFileExists(`${projectDir}/src/instrumentation.ts`); + checkFileExists(`${projectDir}/src/instrumentation-client.ts`); + }); + + test("instrumentation file contains Sentry initialization", () => { + checkFileContents(`${projectDir}/src/instrumentation.ts`, [ + 'import * as Sentry from "@sentry/nextjs";', + `export async function register() { + if (process.env.NEXT_RUNTIME === "nodejs") { + await import("../sentry.server.config"); + } + + if (process.env.NEXT_RUNTIME === "edge") { + await import("../sentry.edge.config"); + } +} + +export const onRequestError = Sentry.captureRequestError;`, + ]); + }); + + test("next.config file contains Sentry wrapper", () => { + checkFileContents(`${projectDir}/next.config.ts`, [ + 'import { withSentryConfig } from "@sentry/nextjs/config"', + "export default withSentryConfig(nextConfig, {", + ]); + }); + + test("runs on dev mode correctly", async () => { + await checkIfRunsOnDevMode(projectDir, "Ready in"); + }); + + test("builds correctly", async () => { + await checkIfBuilds(projectDir); + }); + + test("runs on prod mode correctly", async () => { + await checkIfRunsOnProdMode(projectDir, "Ready in"); + }); + + test("MCP configuration file is created for Cursor", () => { + checkFileExists(`${projectDir}/.cursor/mcp.json`); + checkFileContents(`${projectDir}/.cursor/mcp.json`, [ + '"mcpServers"', + '"Sentry"', + `"url": "https://mcp.sentry.dev/mcp/${TEST_ARGS.ORG_SLUG}/${TEST_ARGS.PROJECT_SLUG}"`, + ]); + }); +}); + +describe("NextJS-15 Spotlight", () => { + let wizardExitCode: number; + + const { projectDir, cleanup } = createIsolatedTestEnv("nextjs-15-test-app"); + + beforeAll(async () => { + wizardExitCode = await withEnv({ + cwd: projectDir, + env: { SENTRY_SPOTLIGHT: "1" }, + }) + .defineInteraction() + .expectOutput("Spotlight mode enabled!") + .whenAsked("Please select your package manager.") + .respondWith(KEYS.DOWN, KEYS.DOWN, KEYS.DOWN, KEYS.ENTER) // Select pnpm + .expectOutput("Installing @sentry/nextjs") + .whenAsked( + "Do you want to reduce this to avoid sending personally identifiable information", + { + timeout: 240_000, // package installation can take a while in CI + }, + ) + .respondWith(KEYS.ENTER) // No + .whenAsked( + "Do you want to route Sentry requests in the browser through your Next.js server", + ) + .respondWith(KEYS.ENTER) + .whenAsked("to track the performance of your application?") + .respondWith(KEYS.ENTER) + .whenAsked( + "to get a video-like reproduction of errors during a user session?", + ) + .respondWith(KEYS.ENTER) + .whenAsked("Do you want to create an example page") + .respondWith(KEYS.DOWN, KEYS.ENTER) // Skip example page + .whenAsked( + "Optionally add a project-scoped MCP server configuration for the Sentry MCP?", + ) + .respondWith(KEYS.DOWN, KEYS.ENTER) // Decline MCP config + .expectOutput("Successfully installed the Sentry Next.js SDK!") + .run(["wizard", "nextjs"]); + }); + + afterAll(() => { + cleanup(); + }); + + test("exits with exit code 0", () => { + expect(wizardExitCode).toBe(0); + }); + + test("package.json is updated correctly", () => { + checkPackageJson(projectDir, "@sentry/nextjs"); + }); + + test(".env-sentry-build-plugin should NOT exist in spotlight mode", () => { + checkFileDoesNotExist(`${projectDir}/.env.sentry-build-plugin`); + }); + + test("config files created", () => { + checkFileExists(`${projectDir}/sentry.server.config.ts`); + checkFileExists(`${projectDir}/sentry.edge.config.ts`); + }); + + test("server config file contains empty DSN and spotlight flag", () => { + checkFileContents(`${projectDir}/sentry.server.config.ts`, [ + 'dsn: ""', + "spotlight: true", + ]); + }); + + test("edge config file contains empty DSN and spotlight flag", () => { + checkFileContents(`${projectDir}/sentry.edge.config.ts`, [ + 'dsn: ""', + "spotlight: true", + ]); + }); + + test("instrumentation client file contains empty DSN and spotlight flag", () => { + checkFileExists(`${projectDir}/src/instrumentation-client.ts`); + checkFileContents(`${projectDir}/src/instrumentation-client.ts`, [ + 'dsn: ""', + "spotlight: true", + ]); + }); + + test("builds correctly", async () => { + await checkIfBuilds(projectDir); + }); + + test("runs on dev mode correctly", async () => { + await checkIfRunsOnDevMode(projectDir, "Ready in"); + }); +}); diff --git a/packages/cli/test/wizard-e2e/nextjs-16.test.ts b/packages/cli/test/wizard-e2e/nextjs-16.test.ts new file mode 100644 index 000000000..f78e54a26 --- /dev/null +++ b/packages/cli/test/wizard-e2e/nextjs-16.test.ts @@ -0,0 +1,239 @@ +import { readFileSync } from "node:fs"; +import { afterAll, beforeAll, describe, expect, test } from "vitest"; +import { + checkEnvBuildPlugin, + checkFileContents, + checkFileExists, + checkIfBuilds, + checkIfLints, + checkIfRunsOnDevMode, + checkIfRunsOnProdMode, + checkPackageJson, + createIsolatedTestEnv, + getWizardCommand, + KEYS, + withEnv, +} from "./utils.js"; +import { TEST_ARGS } from "./constants.js"; + +describe("NextJS-16 with cacheComponents", () => { + let wizardExitCode: number; + + const { projectDir, cleanup } = createIsolatedTestEnv("nextjs-16-test-app"); + + beforeAll(async () => { + wizardExitCode = await withEnv({ cwd: projectDir }) + .defineInteraction() + .whenAsked("Please select your package manager", { + timeout: 300_000, + }) + .respondWith(KEYS.ENTER) // Select npm (first option) + .expectOutput("Installing @sentry/nextjs") + .whenAsked( + "Do you want to reduce this to avoid sending personally identifiable information", + { + timeout: 300_000, // package installation can take a while in CI + }, + ) + .respondWith(KEYS.ENTER) // No + .whenAsked( + "Do you want to route Sentry requests in the browser through your Next.js server", + ) + .respondWith(KEYS.ENTER) + .whenAsked("to track the performance of your application?") + .respondWith(KEYS.ENTER) + .whenAsked( + "to get a video-like reproduction of errors during a user session?", + ) + .respondWith(KEYS.ENTER) + .whenAsked("Do you want to create an example page") + .respondWith(KEYS.ENTER) + .whenAsked("Are you using a CI/CD tool") + .respondWith(KEYS.DOWN, KEYS.ENTER) // Select No + .whenAsked( + "Optionally add a project-scoped MCP server configuration for the Sentry MCP?", + ) + .respondWith(KEYS.ENTER) // Accept MCP config + .whenAsked("Which editor(s) do you want to configure?") + .respondWith(KEYS.SPACE, KEYS.ENTER) // Select Cursor + .whenAsked("Looks like you have Prettier and Biome in your project") + .respondWith(KEYS.DOWN, KEYS.ENTER) // Skip formatter run + .expectOutput("Successfully installed the Sentry Next.js SDK!") + .run(getWizardCommand("nextjs")); + }); + + afterAll(() => { + cleanup(); + }); + + test("exits with exit code 0", () => { + expect(wizardExitCode).toBe(0); + }); + + test("package.json is updated correctly", () => { + checkPackageJson(projectDir, "@sentry/nextjs"); + }); + + test(".env-sentry-build-plugin is created and contains the auth token", () => { + checkEnvBuildPlugin(projectDir); + }); + + test("example page exists", () => { + checkFileExists(`${projectDir}/app/sentry-example-page/page.tsx`); + checkFileExists(`${projectDir}/app/api/sentry-example-api/route.ts`); + }); + + test("config files created", () => { + checkFileExists(`${projectDir}/sentry.server.config.ts`); + checkFileExists(`${projectDir}/sentry.edge.config.ts`); + }); + + test("global error file exists", () => { + checkFileExists(`${projectDir}/app/global-error.tsx`); + }); + + test("instrumentation files exist", () => { + checkFileExists(`${projectDir}/instrumentation.ts`); + checkFileExists(`${projectDir}/instrumentation-client.ts`); + }); + + test("next.config file contains Sentry wrapper and keeps cacheComponents", () => { + checkFileContents(`${projectDir}/next.config.ts`, [ + 'import { withSentryConfig } from "@sentry/nextjs/config"', + "cacheComponents: true", + "export default withSentryConfig(nextConfig, {", + ]); + }); + + test("runs on dev mode correctly", async () => { + await checkIfRunsOnDevMode(projectDir, "Ready in"); + }); + + test("builds correctly", async () => { + await checkIfBuilds(projectDir); + }); + + test("runs on prod mode correctly", async () => { + await checkIfRunsOnProdMode(projectDir, "Ready in"); + }); + + test("MCP configuration file is created for Cursor", () => { + checkFileExists(`${projectDir}/.cursor/mcp.json`); + checkFileContents(`${projectDir}/.cursor/mcp.json`, [ + '"mcpServers"', + '"Sentry"', + `"url": "https://mcp.sentry.dev/mcp/${TEST_ARGS.ORG_SLUG}/${TEST_ARGS.PROJECT_SLUG}"`, + ]); + }); +}); + +describe("NextJS-16 with Prettier, Biome, and ESLint", () => { + let wizardExitCode: number; + + const { projectDir, cleanup } = createIsolatedTestEnv("nextjs-16-test-app"); + + beforeAll(async () => { + wizardExitCode = await withEnv({ cwd: projectDir }) + .defineInteraction() + .whenAsked("Please select your package manager", { + timeout: 300_000, + }) + .respondWith(KEYS.ENTER) // Select npm (first option) + .expectOutput("Installing @sentry/nextjs") + .whenAsked( + "Do you want to reduce this to avoid sending personally identifiable information", + { + timeout: 300_000, // package installation can take a while in CI + }, + ) + .respondWith(KEYS.ENTER) // No + .whenAsked( + "Do you want to route Sentry requests in the browser through your Next.js server", + ) + .respondWith(KEYS.ENTER) + .whenAsked("to track the performance of your application?") + .respondWith(KEYS.ENTER) + .whenAsked( + "to get a video-like reproduction of errors during a user session?", + ) + .respondWith(KEYS.ENTER) + .whenAsked("Do you want to create an example page") + .respondWith(KEYS.DOWN, KEYS.ENTER) // Skip example page + .whenAsked("Are you using a CI/CD tool") + .respondWith(KEYS.DOWN, KEYS.ENTER) // Select No + .whenAsked( + "Optionally add a project-scoped MCP server configuration for the Sentry MCP?", + ) + .respondWith(KEYS.DOWN, KEYS.ENTER) // Skip MCP config + .whenAsked("Looks like you have Prettier and Biome in your project") + .respondWith(KEYS.ENTER) // Accept formatter run + .expectOutput("Running formatters on your files") // clack drops the trailing dots + .expectOutput("Formatters have processed your files", { timeout: 60_000 }) + .expectOutput("Successfully installed the Sentry Next.js SDK!") + .run(getWizardCommand("nextjs")); + }); + + afterAll(() => { + cleanup(); + }); + + test("exits with exit code 0", () => { + expect(wizardExitCode).toBe(0); + }); + + test("package.json is updated correctly", () => { + checkPackageJson(projectDir, "@sentry/nextjs"); + }); + + test("config files created", () => { + checkFileExists(`${projectDir}/sentry.server.config.ts`); + checkFileExists(`${projectDir}/sentry.edge.config.ts`); + }); + + test("global error file exists", () => { + checkFileExists(`${projectDir}/app/global-error.tsx`); + }); + + test("instrumentation files exist", () => { + checkFileExists(`${projectDir}/instrumentation.ts`); + checkFileExists(`${projectDir}/instrumentation-client.ts`); + }); + + test("instrumentation file contains Sentry initialization", () => { + checkFileContents(`${projectDir}/instrumentation.ts`, [ + 'import * as Sentry from "@sentry/nextjs";', + `export async function register() { + if (process.env.NEXT_RUNTIME === "nodejs") { + await import("./sentry.server.config"); + } + + if (process.env.NEXT_RUNTIME === "edge") { + await import("./sentry.edge.config"); + } +} + +export const onRequestError = Sentry.captureRequestError;`, + ]); + }); + + test("next.config file contains Sentry wrapper", () => { + checkFileContents(`${projectDir}/next.config.ts`, [ + 'import { withSentryConfig } from "@sentry/nextjs/config"', + "withSentryConfig(nextConfig, {", + ]); + }); + + test("Generated code has proper import formatting", () => { + const configContent = readFileSync(`${projectDir}/next.config.ts`, "utf-8"); + // Verify proper spacing: import { withSentryConfig } from + expect(configContent).toMatch(/import\s+{\s+\w+\s+}\s+from/); + }); + + test("builds correctly", async () => { + await checkIfBuilds(projectDir); + }); + + test("lints correctly", async () => { + await checkIfLints(projectDir); + }); +}); diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/.gitignore b/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/.gitignore new file mode 100644 index 000000000..bad92b658 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/.gitignore @@ -0,0 +1,35 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js +.yarn/install-state.gz + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# local env files +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/next-env.d.ts b/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/next-env.d.ts new file mode 100644 index 000000000..40c3d6809 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/next-env.d.ts @@ -0,0 +1,5 @@ +/// +/// + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information. diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/next.config.mjs b/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/next.config.mjs new file mode 100644 index 000000000..4678774e6 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/next.config.mjs @@ -0,0 +1,4 @@ +/** @type {import('next').NextConfig} */ +const nextConfig = {}; + +export default nextConfig; diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/package.json b/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/package.json new file mode 100644 index 000000000..1a3c6b205 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/package.json @@ -0,0 +1,22 @@ +{ + "name": "nextjs-test-app", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev", + "build": "next build", + "start": "next start -p 8082", + "lint": "next lint" + }, + "dependencies": { + "react": "^18", + "react-dom": "^18", + "next": "14.2.35" + }, + "devDependencies": { + "typescript": "^5", + "@types/node": "^20", + "@types/react": "^18", + "@types/react-dom": "^18" + } +} diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/src/app/page.tsx b/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/src/app/page.tsx new file mode 100644 index 000000000..f282fb5c1 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/src/app/page.tsx @@ -0,0 +1,90 @@ +import Image from "next/image"; + +export default function Home() { + return ( +
+
+ Next.js logo +
    +
  1. + Get started by editing src/app/page.tsx. +
  2. +
  3. Save and see your changes instantly.
  4. +
+ + +
+ +
+ ); +} diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/tsconfig.json b/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/tsconfig.json new file mode 100644 index 000000000..7b2858930 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-14-test-app/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "noEmit": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "preserve", + "incremental": true, + "plugins": [ + { + "name": "next" + } + ], + "paths": { + "@/*": ["./src/*"] + } + }, + "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/.gitignore b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/.gitignore new file mode 100644 index 000000000..4e5059289 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/.gitignore @@ -0,0 +1,40 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# env files (can opt-in for committing if needed) +.env* + +# vercel +.vercel + +# typescript +*.tsbuildinfo diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/next-env.d.ts b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/next-env.d.ts new file mode 100644 index 000000000..1b3be0840 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/next-env.d.ts @@ -0,0 +1,5 @@ +/// +/// + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/next.config.ts b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/next.config.ts new file mode 100644 index 000000000..e9ffa3083 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/next.config.ts @@ -0,0 +1,7 @@ +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + /* config options here */ +}; + +export default nextConfig; diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/package.json b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/package.json new file mode 100644 index 000000000..94e6bb45a --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/package.json @@ -0,0 +1,22 @@ +{ + "name": "nextjs-15-test-app", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev", + "build": "next build", + "start": "next start -p 8083", + "lint": "next lint" + }, + "dependencies": { + "next": "15.5.28", + "react": "^19.0.1", + "react-dom": "^19.0.1" + }, + "devDependencies": { + "@types/node": "^20", + "@types/react": "^19", + "@types/react-dom": "^19", + "typescript": "^5" + } +} diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/src/app/layout.tsx b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/src/app/layout.tsx new file mode 100644 index 000000000..4fafd86b4 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/src/app/layout.tsx @@ -0,0 +1,20 @@ +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: "Create Next App", + description: "Generated by create next app", +}; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + + + {children} + + + ); +} diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/src/app/page.tsx b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/src/app/page.tsx new file mode 100644 index 000000000..010721e6f --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/src/app/page.tsx @@ -0,0 +1,90 @@ +import Image from 'next/image'; + +export default function Home() { + return ( +
+
+ Next.js logo +
    +
  1. + Get started by editing src/app/page.tsx. +
  2. +
  3. Save and see your changes instantly.
  4. +
+ + +
+ +
+ ); +} diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/tsconfig.json b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/tsconfig.json new file mode 100644 index 000000000..c1334095f --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-15-test-app/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "ES2017", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "noEmit": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "preserve", + "incremental": true, + "plugins": [ + { + "name": "next" + } + ], + "paths": { + "@/*": ["./src/*"] + } + }, + "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/.prettierrc b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/.prettierrc new file mode 100644 index 000000000..055317212 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/.prettierrc @@ -0,0 +1,8 @@ +{ + "semi": true, + "trailingComma": "all", + "singleQuote": false, + "printWidth": 80, + "tabWidth": 2, + "arrowParens": "always" +} diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/app/layout.tsx b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/app/layout.tsx new file mode 100644 index 000000000..112756e6b --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/app/layout.tsx @@ -0,0 +1,18 @@ +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: "Create Next App", + description: "Generated by create next app", +}; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + + {children} + + ); +} diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/app/page.tsx b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/app/page.tsx new file mode 100644 index 000000000..394a7a939 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/app/page.tsx @@ -0,0 +1,10 @@ +export default function Home() { + return ( +
+
+

Next.js 16 Biome Test App

+

This is a test application for Sentry wizard e2e tests.

+
+
+ ); +} diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/biome.json b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/biome.json new file mode 100644 index 000000000..f7896c346 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/biome.json @@ -0,0 +1,32 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.2.0/schema.json", + "vcs": { + "enabled": false + }, + "files": { + "ignoreUnknown": true, + "includes": ["**", "!node_modules", "!.next", "!dist", "!build"] + }, + "formatter": { + "enabled": true, + "indentStyle": "space", + "indentWidth": 2 + }, + "linter": { + "enabled": true, + "rules": { + "recommended": true + }, + "domains": { + "next": "recommended", + "react": "recommended" + } + }, + "assist": { + "actions": { + "source": { + "organizeImports": "on" + } + } + } +} diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/eslint.config.mjs b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/eslint.config.mjs new file mode 100644 index 000000000..05e726d1b --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/eslint.config.mjs @@ -0,0 +1,18 @@ +import { defineConfig, globalIgnores } from "eslint/config"; +import nextVitals from "eslint-config-next/core-web-vitals"; +import nextTs from "eslint-config-next/typescript"; + +const eslintConfig = defineConfig([ + ...nextVitals, + ...nextTs, + // Override default ignores of eslint-config-next. + globalIgnores([ + // Default ignores of eslint-config-next: + ".next/**", + "out/**", + "build/**", + "next-env.d.ts", + ]), +]); + +export default eslintConfig; diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/next.config.ts b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/next.config.ts new file mode 100644 index 000000000..584cbfce3 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/next.config.ts @@ -0,0 +1,7 @@ +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + cacheComponents: true, +}; + +export default nextConfig; diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/package.json b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/package.json new file mode 100644 index 000000000..7a8294cb4 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/package.json @@ -0,0 +1,27 @@ +{ + "name": "nextjs-16-test-app", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev", + "build": "next build", + "start": "next start -p 8086", + "lint": "biome check && eslint", + "format": "prettier --write . && biome format --write ." + }, + "dependencies": { + "next": "16.4.1", + "react": "19.2.0", + "react-dom": "19.2.0" + }, + "devDependencies": { + "@biomejs/biome": "2.2.0", + "@types/node": "^20", + "@types/react": "^19", + "@types/react-dom": "^19", + "eslint": "^9", + "eslint-config-next": "16.0.7", + "prettier": "^3", + "typescript": "^5" + } +} diff --git a/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/tsconfig.json b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/tsconfig.json new file mode 100644 index 000000000..3a13f90a7 --- /dev/null +++ b/packages/cli/test/wizard-e2e/test-applications/nextjs-16-test-app/tsconfig.json @@ -0,0 +1,34 @@ +{ + "compilerOptions": { + "target": "ES2017", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "noEmit": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "react-jsx", + "incremental": true, + "plugins": [ + { + "name": "next" + } + ], + "paths": { + "@/*": ["./*"] + } + }, + "include": [ + "next-env.d.ts", + "**/*.ts", + "**/*.tsx", + ".next/types/**/*.ts", + ".next/dev/types/**/*.ts", + "**/*.mts" + ], + "exclude": ["node_modules"] +} diff --git a/packages/cli/test/wizard-e2e/utils.ts b/packages/cli/test/wizard-e2e/utils.ts new file mode 100644 index 000000000..058d8f5c6 --- /dev/null +++ b/packages/cli/test/wizard-e2e/utils.ts @@ -0,0 +1,559 @@ +/** + * Harness for the `sentry wizard` end-to-end tests, ported from + * getsentry/sentry-wizard's `e2e-tests/utils`. + * + * A test copies one app from `test-applications/` to a temporary git + * repository ({@link createIsolatedTestEnv}), runs the real CLI's `sentry + * wizard` in it while answering its prompts ({@link withEnv}), and then checks + * the files the wizard wrote and that the app still builds and runs. + * + * The wizard never talks to sentry.io: runs that need a project set + * `SENTRY_URL` to the local mock Sentry API that `global-setup.ts` starts, and + * Spotlight runs (`SENTRY_SPOTLIGHT=1`) need no project at all. + */ + +import { + type ChildProcess, + execFileSync, + spawn, + spawnSync, +} from "node:child_process"; +import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { expect, inject } from "vitest"; +import { logger } from "../../src/lib/logger.js"; +import type { WizardIntegration } from "../../src/lib/wizard/run.js"; +import { BUNDLE_BIN_PATH } from "../e2e/bundle-setup.js"; +import { TEST_ARGS } from "./constants.js"; + +const log = logger.withTag("wizard-e2e"); + +/** Key sequences to answer clack prompts with. */ +export const KEYS = { + UP: "\u001b[A", + DOWN: "\u001b[B", + LEFT: "\u001b[D", + RIGHT: "\u001b[C", + ENTER: "\r", + SPACE: " ", +} as const; + +/** Default time to wait for one prompt or output, as in clifty. */ +const DEFAULT_STEP_TIMEOUT = 10_000; + +/** Time a wizard run may take after its last expected output. */ +const EXIT_TIMEOUT = 60_000; + +/** + * The command that runs the CLI: `SENTRY_CLI_BINARY` (a native binary, or a + * `.cjs`/`.js` bundle run with this Node), else the npm bundle that + * `pnpm run bundle` writes to `dist/bin.cjs`. + */ +function getCliCommand(): [string, ...string[]] { + const binary = process.env["SENTRY_CLI_BINARY"] || BUNDLE_BIN_PATH; + if (!existsSync(binary)) { + throw new Error( + `No CLI at ${binary}. Run \`pnpm run bundle\` in packages/cli, or set SENTRY_CLI_BINARY.`, + ); + } + return /\.[cm]?js$/i.test(binary) ? [process.execPath, binary] : [binary]; +} + +/** + * The `sentry wizard` arguments that set up `integration` for the mock + * Sentry API's org and project. The run logs in with the environment token + * that {@link wizardEnv} sets for the mock's `SENTRY_URL`. + */ +export function getWizardCommand(integration: WizardIntegration): string[] { + return [ + "wizard", + `${TEST_ARGS.ORG_SLUG}/${TEST_ARGS.PROJECT_SLUG}`, + integration, + ]; +} + +/** + * This process's environment without Sentry and npm script variables, for + * the processes a test starts. `pnpm run` sets npm_* variables, which would + * change how package managers run in the test app. + */ +function cleanEnv(): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { NEXT_TELEMETRY_DISABLED: "1" }; + for (const [key, value] of Object.entries(process.env)) { + if (!(key.startsWith("SENTRY_") || key.startsWith("npm_"))) { + env[key] = value; + } + } + return env; +} + +/** + * CLI config directory of this test file's runs, so they don't read the + * user's login. The runs log in with an environment token and keep no state. + */ +const CONFIG_DIR = mkdtempSync(join(tmpdir(), "sentry-wizard-e2e-config-")); + +/** + * The environment of a CLI run: its own config directory, and the mock API's + * login token for its URL. (The CLI sends an environment token only to the + * host in `SENTRY_URL`.) + */ +function wizardEnv(): NodeJS.ProcessEnv { + return { + ...cleanEnv(), + SENTRY_CONFIG_DIR: CONFIG_DIR, + SENTRY_URL: inject("sentryUrl"), + SENTRY_AUTH_TOKEN: TEST_ARGS.LOGIN_TOKEN, + SENTRY_CLI_NO_TELEMETRY: "1", + SENTRY_CLI_NO_UPDATE_CHECK: "1", + }; +} + +/** + * Run the CLI with `args` to completion, without answering prompts, such as + * for `wizard --help`. + */ +export function runCli(args: readonly string[]): { + exitCode: number | null; + stdout: string; + stderr: string; +} { + const [command, ...commandArgs] = getCliCommand(); + const result = spawnSync(command, [...commandArgs, ...args], { + env: wizardEnv(), + encoding: "utf-8", + }); + return { + exitCode: result.status, + stdout: result.stdout, + stderr: result.stderr, + }; +} + +/** + * Copy the app `testAppName` from `test-applications/` into a new temporary + * directory and commit it to a new git repository there, so the wizard sees + * a clean working tree. Each call makes a new directory. + * + * Set `SENTRY_WIZARD_E2E_KEEP_TEMP=true` to keep the directory for debugging. + */ +export function createIsolatedTestEnv(testAppName: string): { + projectDir: string; + cleanup: () => void; +} { + const sourceDir = resolve( + import.meta.dirname, + "test-applications", + testAppName, + ); + const projectDir = mkdtempSync( + join(tmpdir(), `sentry-wizard-e2e-${testAppName}-`), + ); + cpSync(sourceDir, projectDir, { recursive: true }); + initGit(projectDir); + log.info(`Created isolated test env at ${projectDir}`); + + const cleanup = () => { + if (process.env["SENTRY_WIZARD_E2E_KEEP_TEMP"] === "true") { + log.info(`Keeping temp directory for debugging: ${projectDir}`); + return; + } + rmSync(projectDir, { recursive: true, force: true }); + }; + return { projectDir, cleanup }; +} + +/** Commit everything in `projectDir` to a new git repository. */ +function initGit(projectDir: string): void { + const git = (...args: string[]) => + execFileSync("git", args, { cwd: projectDir, stdio: "pipe" }); + git("init", "--quiet"); + git("add", "-A"); + git( + "-c", + "user.email=test@test.sentry.io", + "-c", + "user.name=Test", + "-c", + "commit.gpgsign=false", + "commit", + "--quiet", + "-m", + "init", + ); +} + +type InteractionStep = { + /** Text the output must contain, after the previous step's match. */ + output: string; + timeout: number; + /** Keys to type once `output` appears; unset for `expectOutput`. */ + response?: readonly string[]; +}; + +/** + * Scripted answers to the wizard's prompts, in the shape of clifty's + * `defineInteraction()` builder that sentry-wizard's tests used. + */ +class Interaction { + readonly #steps: InteractionStep[] = []; + readonly #cwd: string; + readonly #env: NodeJS.ProcessEnv; + readonly #debug: boolean; + + constructor(cwd: string, env: NodeJS.ProcessEnv, debug: boolean) { + this.#cwd = cwd; + this.#env = env; + this.#debug = debug; + } + + /** Wait for the prompt `output`, then answer it with `respondWith`. */ + whenAsked( + output: string, + options: { timeout?: number } = {}, + ): { respondWith: (...keys: string[]) => Interaction } { + return { + respondWith: (...keys: string[]) => { + this.#steps.push({ + output, + timeout: options.timeout ?? DEFAULT_STEP_TIMEOUT, + response: keys, + }); + return this; + }, + }; + } + + /** Wait for `output` without answering anything. */ + expectOutput(output: string, options: { timeout?: number } = {}): this { + this.#steps.push({ + output, + timeout: options.timeout ?? DEFAULT_STEP_TIMEOUT, + }); + return this; + } + + /** + * Run the CLI with `args`, go through the steps, and resolve to its exit + * code. Rejects when a step's output doesn't appear in time. + */ + async run(args: readonly string[]): Promise { + const [command, ...commandArgs] = getCliCommand(); + const child = spawn(command, [...commandArgs, ...args], { + cwd: this.#cwd, + env: this.#env, + stdio: "pipe", + }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk: Buffer) => { + stdout += chunk.toString(); + }); + child.stderr.on("data", (chunk: Buffer) => { + stderr += chunk.toString(); + }); + if (this.#debug) { + child.stdout.pipe(process.stdout); + child.stderr.pipe(process.stderr); + } + const exited = new Promise((resolveExit, rejectExit) => { + child.once("error", rejectExit); + child.once("close", (code, signal) => + code === null + ? rejectExit(new Error(`Wizard was killed by ${signal ?? "?"}`)) + : resolveExit(code), + ); + }); + + try { + let cursor = 0; + for (const step of this.#steps) { + cursor = await waitForOutput(() => stdout, cursor, step, exited); + for (const key of step.response ?? []) { + child.stdin.write(key); + } + } + child.stdin.end(); + const exitCode = await withTimeout( + exited, + EXIT_TIMEOUT, + "Wizard did not exit after its last step", + ); + if (exitCode !== 0) { + log.error( + `Wizard exited with ${exitCode}.\nstdout:\n${stdout}\nstderr:\n${stderr}`, + ); + } + return exitCode; + } catch (error) { + child.kill("SIGKILL"); + throw new Error( + `${error instanceof Error ? error.message : String(error)}\n\nstdout:\n${stdout}\nstderr:\n${stderr}`, + ); + } + } +} + +/** + * Wait until `read()` contains `step.output` at or after `cursor`, and + * return the index just after the match. Rejects on timeout, or when the + * process exits first. + */ +async function waitForOutput( + read: () => string, + cursor: number, + step: InteractionStep, + exited: Promise, +): Promise { + const deadline = Date.now() + step.timeout; + let exitCode: number | undefined; + exited.then( + (code) => { + exitCode = code; + }, + () => { + exitCode = -1; + }, + ); + for (;;) { + const index = read().indexOf(step.output, cursor); + if (index !== -1) { + return index + step.output.length; + } + if (exitCode !== undefined) { + throw new Error( + `Wizard exited with ${exitCode} while waiting for: ${step.output}`, + ); + } + if (Date.now() > deadline) { + throw new Error( + `Timed out after ${step.timeout} ms waiting for: ${step.output}`, + ); + } + await new Promise((resolveSleep) => setTimeout(resolveSleep, 50)); + } +} + +/** `promise`, or a rejection with `message` after `ms`. */ +async function withTimeout( + promise: Promise, + ms: number, + message: string, +): Promise { + let timer: NodeJS.Timeout | undefined; + try { + return await Promise.race([ + promise, + new Promise((_, rejectTimeout) => { + timer = setTimeout(() => rejectTimeout(new Error(message)), ms); + }), + ]); + } finally { + clearTimeout(timer); + } +} + +/** + * Start describing a wizard run in `cwd`, with `env` added to its + * environment. Set `debug` (or `SENTRY_WIZARD_E2E_DEBUG=true`) to stream the + * wizard's output. + */ +export function withEnv(options: { + cwd: string; + env?: NodeJS.ProcessEnv; + debug?: boolean; +}): { + defineInteraction: () => Interaction; +} { + return { + defineInteraction: () => + new Interaction( + options.cwd, + { ...wizardEnv(), ...options.env }, + options.debug ?? process.env["SENTRY_WIZARD_E2E_DEBUG"] === "true", + ), + }; +} + +/** A command started in a test app, such as `npm run dev`. */ +class ProcessRunner { + readonly #child: ChildProcess; + #output = ""; + + constructor( + command: string, + args: readonly string[], + options: { cwd: string }, + ) { + this.#child = spawn(command, args, { + cwd: options.cwd, + env: cleanEnv(), + stdio: "pipe", + // Own process group, so kill() also stops the servers npm starts. + detached: process.platform !== "win32", + }); + this.#child.stdout?.on("data", (chunk: Buffer) => { + this.#output += chunk.toString(); + }); + this.#child.stderr?.on("data", (chunk: Buffer) => { + this.#output += chunk.toString(); + }); + } + + /** Resolves to whether the command exits with `statusCode` in time. */ + async waitForStatusCode( + statusCode: number, + options: { timeout?: number } = {}, + ): Promise { + const exited = new Promise((resolveExit, rejectExit) => { + this.#child.once("error", rejectExit); + this.#child.once("exit", resolveExit); + }); + try { + const code = await withTimeout( + exited, + options.timeout ?? 60_000, + `Timed out waiting for exit code ${statusCode}`, + ); + if (code !== statusCode) { + log.error(`Exited with ${code ?? "a signal"}:\n${this.#output}`); + } + return code === statusCode; + } finally { + this.kill(); + } + } + + /** Resolves to whether the command prints `output` in time. */ + async waitForOutput( + output: string, + options: { timeout?: number } = {}, + ): Promise { + const deadline = Date.now() + (options.timeout ?? 60_000); + while (Date.now() < deadline) { + if (this.#output.includes(output)) { + return true; + } + if (this.#child.exitCode !== null) { + break; + } + await new Promise((resolveSleep) => setTimeout(resolveSleep, 100)); + } + log.error(`Did not print "${output}":\n${this.#output}`); + return false; + } + + /** Stop the command and everything it started. */ + kill(): void { + if (this.#child.exitCode !== null || this.#child.pid === undefined) { + return; + } + try { + if (process.platform === "win32") { + this.#child.kill(); + } else { + process.kill(-this.#child.pid, "SIGKILL"); + } + } catch (error) { + log.debug("Could not stop process", error); + } + } +} + +/** Check that `filePath` contains each of `content`. */ +export function checkFileContents( + filePath: string, + content: string | readonly string[], +): void { + const fileContent = readFileSync(filePath, "utf-8"); + for (const c of typeof content === "string" ? [content] : content) { + expect(fileContent).toContain(c); + } +} + +export function checkFileExists(filePath: string): void { + expect(existsSync(filePath), `${filePath} exists`).toBe(true); +} + +export function checkFileDoesNotExist(filePath: string): void { + expect(existsSync(filePath), `${filePath} does not exist`).toBe(false); +} + +/** + * Check that the project's `package.json` lists `packageName` in its + * dependencies (or, with `devDependency`, its dev dependencies). + */ +export function checkPackageJson( + projectDir: string, + packageName: string, + devDependency = false, +): void { + const packageJson = JSON.parse( + readFileSync(join(projectDir, "package.json"), "utf-8"), + ) as { + dependencies?: Record; + devDependencies?: Record; + }; + const version = + packageJson.dependencies?.[packageName] ?? + (devDependency ? packageJson.devDependencies?.[packageName] : undefined); + expect(version, `${packageName} in package.json`).toBeTruthy(); +} + +/** Check that `.env.sentry-build-plugin` has the minted org auth token. */ +export function checkEnvBuildPlugin(projectDir: string): void { + checkFileContents( + join(projectDir, ".env.sentry-build-plugin"), + `SENTRY_AUTH_TOKEN=${TEST_ARGS.AUTH_TOKEN}`, + ); +} + +/** Check that `npm run build` succeeds. */ +export async function checkIfBuilds(projectDir: string): Promise { + const runner = new ProcessRunner("npm", ["run", "build"], { + cwd: projectDir, + }); + expect(await runner.waitForStatusCode(0, { timeout: 120_000 })).toBe(true); +} + +/** Check that `npm run lint` succeeds. */ +export async function checkIfLints(projectDir: string): Promise { + const runner = new ProcessRunner("npm", ["run", "lint"], { + cwd: projectDir, + }); + expect(await runner.waitForStatusCode(0, { timeout: 120_000 })).toBe(true); +} + +/** Check that `npm run dev` prints `expectedOutput`. */ +export async function checkIfRunsOnDevMode( + projectDir: string, + expectedOutput: string, +): Promise { + const runner = new ProcessRunner("npm", ["run", "dev"], { cwd: projectDir }); + try { + expect( + await runner.waitForOutput(expectedOutput, { timeout: 120_000 }), + ).toBe(true); + } finally { + runner.kill(); + } +} + +/** Check that `npm run ` prints `expectedOutput`. */ +export async function checkIfRunsOnProdMode( + projectDir: string, + expectedOutput: string, + startCommand = "start", +): Promise { + const runner = new ProcessRunner("npm", ["run", startCommand], { + cwd: projectDir, + }); + try { + expect( + await runner.waitForOutput(expectedOutput, { timeout: 120_000 }), + ).toBe(true); + } finally { + runner.kill(); + } +} diff --git a/packages/cli/test/wizard-e2e/vitest.config.ts b/packages/cli/test/wizard-e2e/vitest.config.ts new file mode 100644 index 000000000..7fe45f06c --- /dev/null +++ b/packages/cli/test/wizard-e2e/vitest.config.ts @@ -0,0 +1,32 @@ +/** + * Vitest config of the `sentry wizard` e2e tests (`pnpm run test:wizard-e2e`). + * + * They install npm packages and build real framework apps, so they stay out + * of `test:unit` and `test:e2e` and run in `wizard-e2e.yml`, one test file + * per job. Files run one at a time: the apps' dev and prod servers use fixed + * ports. + */ + +import { join } from "node:path"; +import { defineConfig } from "vitest/config"; +import baseConfig from "../../vitest.config.js"; + +// Keep the base config's resolver plugins, but none of its test settings: +// its preload stubs fetch and the config directory for in-process tests, and +// these tests only spawn processes. +const { test: _baseTest, ...sharedConfig } = baseConfig; + +export default defineConfig({ + ...sharedConfig, + root: join(import.meta.dirname, "../.."), + test: { + include: ["test/wizard-e2e/**/*.test.ts"], + globalSetup: ["test/wizard-e2e/global-setup.ts"], + // A `beforeAll` runs a whole scripted wizard run, whose step timeouts + // (up to 5 minutes for a package install) add up, so leave room for all + // of them within the 20-minute CI job. + testTimeout: 900_000, + hookTimeout: 900_000, + fileParallelism: false, + }, +}); diff --git a/packages/cli/vitest.config.ts b/packages/cli/vitest.config.ts index 8ed25f2d0..7e3d84b8f 100644 --- a/packages/cli/vitest.config.ts +++ b/packages/cli/vitest.config.ts @@ -108,7 +108,8 @@ export default defineConfig({ isolate: true, pool: "forks", include: ["test/**/*.test.ts"], - exclude: ["**/node_modules/**", "**/dist/**"], + // `test:wizard-e2e` runs these with their own config. + exclude: ["**/node_modules/**", "**/dist/**", "test/wizard-e2e/**"], coverage: { reporter: ["lcov"], }, diff --git a/scripts/tsconfig-policy.test.mjs b/scripts/tsconfig-policy.test.mjs index 727a0bf9c..dd7837143 100644 --- a/scripts/tsconfig-policy.test.mjs +++ b/scripts/tsconfig-policy.test.mjs @@ -33,6 +33,11 @@ const UNCHECKED = [ reason: "packed-package consumer, compiled against the tarball by test/package/check.sh", }, + { + pattern: /^packages\/cli\/test\/wizard-e2e\/test-applications\//, + reason: + "apps the `sentry wizard` e2e tests copy, install and build with their own dependencies", + }, { pattern: /^packages\/mcp-cloudflare\/worker-configuration\.d\.ts$/, reason: diff --git a/scripts/workflow-policy.test.mjs b/scripts/workflow-policy.test.mjs index ae3f786a2..c4a32faa9 100644 --- a/scripts/workflow-policy.test.mjs +++ b/scripts/workflow-policy.test.mjs @@ -21,6 +21,10 @@ const PULL_REQUEST_WORKFLOWS = new Map([ "Starts the MCP Worker and publishes a smoke-test report.", ], ["token-cost.yml", "Reports MCP tool token costs against main."], + [ + "wizard-e2e.yml", + "Runs one sentry wizard E2E test per job; each installs and builds a framework app.", + ], ]); const PULL_REQUEST_EVENTS = [