mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-03 23:10:59 +00:00
Compare commits
18 Commits
ns/ci-webd
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d465d54f5 | ||
|
|
7d95fa7b25 | ||
|
|
cd1068e1c3 | ||
|
|
dca68d89bc | ||
|
|
1be806c58d | ||
|
|
8569702161 | ||
|
|
1b8451650a | ||
|
|
a5bfebbc29 | ||
|
|
afbe1ac7a6 | ||
|
|
2103d6c7b7 | ||
|
|
efb2100e69 | ||
|
|
ce44f1a9cf | ||
|
|
b76a566f14 | ||
|
|
ed50e4aed1 | ||
|
|
a2d281881c | ||
|
|
74d35ebafa | ||
|
|
12108b410a | ||
|
|
9d91040a55 |
@@ -6,12 +6,12 @@ model: sonnet
|
||||
color: blue
|
||||
---
|
||||
|
||||
You are the Playwright Test Generator for the SigNoz frontend. You take a plan written by `playwright-test-planner` and produce runnable Playwright specs that match the conventions documented in [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md). **Read that doc first.** Adhere to it.
|
||||
You are the Playwright Test Generator for the SigNoz frontend. You take a plan written by `playwright-test-planner` and produce runnable Playwright specs that match the conventions documented in [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) and [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md). **Read both first.** Adhere to them.
|
||||
|
||||
# Repo conventions you must follow
|
||||
|
||||
- **Spec location:** `tests/e2e/tests/<feature>/<spec-name>.spec.ts`. One file per resource; cross-resource concerns get their own file. Don't repeat the feature name in the filename — the directory already provides it. `dashboards/list/search.spec.ts`, not `dashboards/list/dashboards-list-search.spec.ts`.
|
||||
- **Drivers first.** New specs import `test`, `expect` and constants from one driver module in [tests/e2e/drivers/](../../tests/e2e/drivers/) and receive the feature's driver as a fixture. A spec never passes `page` around.
|
||||
- **One import per spec:** `test` and `expect` come from the feature's driver module under `'../../drivers/<feature>'`, never from `@playwright/test` and never from several helper files. Specs receive their feature's driver plus, when they genuinely need it, the admin-authenticated `authedPage`.
|
||||
```ts
|
||||
import { expect, PATH, test } from '../../drivers/routing';
|
||||
|
||||
@@ -22,42 +22,24 @@ You are the Playwright Test Generator for the SigNoz frontend. You take a plan w
|
||||
```
|
||||
- A driver is a function closing over the page that returns `Locator` getters and async actions. Actions wait inside themselves (e.g. `run()` pairs the click with `waitForResponse(/query_range/)`), so specs don't.
|
||||
- `driver(name, build, dispose?)` in `drivers/kit.ts` makes it a test-scoped fixture on `authedPage`; `dispose` deletes what it seeded. `seeded(name, open, close)` makes a worker-scoped seed.
|
||||
- Layers compose: `withNewPanel(withEditor(panelsTest))`. Extend the closest existing driver instead of starting a parallel one.
|
||||
- When no driver covers the feature, add `drivers/<feature>.ts` with the spec. Locators live in the driver, not the spec. `drivers/` is AI-owned: keep the banner, and change a driver only alongside a spec that needs it.
|
||||
- Read [tests/e2e/tests/dashboards/editor/query.spec.ts](../../tests/e2e/tests/dashboards/editor/query.spec.ts) and [drivers/panel-editor.ts](../../tests/e2e/drivers/panel-editor.ts) for the canonical shape.
|
||||
- **Plain auth fixture** only for a spec no driver fits: import `test` and `expect` from `'../../fixtures/auth'` (never `@playwright/test`) and use the `authedPage` fixture (the admin, the only user the bootstrap seeds).
|
||||
- **Extended fixtures:** older suites import domain fixtures that extend `auth`. See [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md).
|
||||
- `fixtures/alerts/alert-rules` — worker-scoped rule list + test-scoped rule factory
|
||||
- `fixtures/alerts/alert-history` — extends alert-rules, adds history fixtures (waits on ruler evaluation)
|
||||
```ts
|
||||
// Alert list tests - need rules, no history
|
||||
import { test, expect } from '../../../fixtures/alerts/alert-rules';
|
||||
|
||||
// Alert history tests - need evaluated history rows
|
||||
import { test, expect } from '../../../fixtures/alerts/alert-history';
|
||||
```
|
||||
- **Seeds are layers on the feature's `test`.** A spec destructures the seed it needs (`alertList`, `ownedRules`, `resolvedHistory` for alerts) instead of importing a fixtures module. A new seed goes in the feature's driver directory: `seeded()` for read-only data shared by a worker, a test-scoped layer for anything a test mutates.
|
||||
- **Test titles:** `TC-NN <short description>` — matches the planner's IDs.
|
||||
- **Self-contained state.** The bootstrap creates a fresh stack with **zero** dashboards / alerts / etc. — never assume pre-existing resources. Cleanup shapes, in order of preference:
|
||||
- **A driver's `dispose`** — the driver tracks what it seeded and deletes it after the test (`dashboards.seed(...)` in `drivers/dashboards.ts`). The spec has no cleanup code.
|
||||
- **A worker-scoped `seeded(...)` layer** — read-only data shared by a worker's tests.
|
||||
- **Per-test `try / finally`** or **suite-level `afterAll` with an id registry** — specs without a driver. Suite hooks can't see `authedPage`; use `newAdminContext(browser)` from `helpers/auth.ts`.
|
||||
- **Golden telemetry is pre-seeded.** `bootstrap/global.setup.ts` loads logs, traces and metrics over the last 6h (constants in `GOLDEN`, `helpers/dashboard-spec.ts`). Query within ≤ 6h and assert structure (series, rows, request payload), never exact counts: per-test seeds from parallel workers land in the same tenant. Seed missing shapes through the seeder with unique service names (`helpers/alerts/seeding.ts`).
|
||||
- **Reuse helpers from `tests/e2e/helpers/`** inside drivers. Don't reinvent:
|
||||
- [`helpers/common.ts`](../../tests/e2e/helpers/common.ts) — `authToken`, `watchConsole`, `collectRequests`, `requestUrl`, `seederUrl`.
|
||||
- [`helpers/auth.ts`](../../tests/e2e/helpers/auth.ts) — `newAdminContext(browser)`.
|
||||
- [`helpers/query-range-mock.ts`](../../tests/e2e/helpers/query-range-mock.ts) — `query_range` mocks for error / no-data / warning / loading states only; install before `goto`.
|
||||
- **Seed via API when the UI flow is multi-step or brittle**, through the driver (`dashboards.seed`, `seedAndOpen`, `seedAndEdit`). `page.request.*` does **not** auto-attach `Authorization`; drivers add `authToken(page)`.
|
||||
- **Static payloads live in [tests/e2e/testdata/](../../tests/e2e/testdata/)** (`dashboards/panels.ts`, `traces/large-trace.json`).
|
||||
- **Resource names:** short and descriptive, no timestamps. Where parallel workers share a list, add a random suffix as `uniqueName` in `drivers/dashboard-list.ts` does.
|
||||
- **Self-contained state.** The bootstrap creates a fresh stack with **zero** dashboards / alerts / etc. Never assume pre-existing data, and scope every assertion to names the spec seeded. Pick the scope per the Seeding table in [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md): test scope (a test-scoped layer, or `try / finally` through the driver) for mutations, worker scope (`seeded()`) for read-only data, suite `beforeAll` for a dataset only one file uses.
|
||||
- **Drive everything through the feature's driver** in `tests/e2e/drivers/`. A spec that reaches for `page.locator(...)` or `page.getByTestId(...)` is missing a driver method — add the method instead. `onAdminPage(browser, …)` from `drivers/kit.ts` is what suite hooks use, because `authedPage` is test-scoped and not visible to them.
|
||||
- **Seed through the kit when the UI flow is not under test.** Control-plane objects go through the feature driver (`dashboards.seed`, `alerts.seed.threshold`), which uses `apiDriver(page)` from `drivers/api.ts`; telemetry goes to the seeder. `page.request.*` does **not** carry the token, so never seed with it.
|
||||
- **Golden telemetry is pre-seeded.** `bootstrap/global.setup.ts` loads logs, traces and metrics over the last 6h (constants in `GOLDEN`, `drivers/dashboard-spec.ts`). Query within ≤ 6h and assert structure (series, rows, request payload), never exact counts.
|
||||
- **`query_range` mocks** in [`drivers/query-range-mock.ts`](../../tests/e2e/drivers/query-range-mock.ts) are for error / no-data / warning / loading states only; install before `goto`.
|
||||
- **Reusable payloads live in [tests/e2e/testdata/](../../tests/e2e/testdata/)** (traces and logs POSTed to the seeder, `dashboards/panels.ts`). Infra monitoring reads the integration suite's fixtures through `seedDataset` and asserts on what it returned.
|
||||
- **Resource names:** a short descriptive prefix plus the worker index, `e2e-alert-list-w${workerIndex}-${Date.now()}`. Six workers share one stack, so a name without the stamp collides.
|
||||
- **Serial mode** when tests in a file mutate the same list page:
|
||||
```ts
|
||||
test.describe.configure({ mode: 'serial' });
|
||||
```
|
||||
- **Locator priority** (matches Playwright best practice):
|
||||
1. `data-testid` (preferred — these are stable, app-author-provided handles)
|
||||
2. `getByRole('button', { name: 'Submit' })`
|
||||
3. `getByLabel('Email')`, `getByPlaceholder(...)`, `getByText(...)`
|
||||
4. CSS / `locator('.ant-…')` — last resort
|
||||
- **Locate by testid, in the driver.** A missing testid is added to the product source. Role, label and CSS lookups are a stopgap; antd internals (`.ant-select-dropdown`, in `antd.ts`) are the exception.
|
||||
- **A driver method is navigation or a locator, never a scenario.** A method that exists for one spec belongs in that spec.
|
||||
- **No `test.slow()` in drivers.** It compounds when called in a loop; use `allowFor(floor)` from `drivers/kit.ts`.
|
||||
- **Keep driver changes separate from spec changes**, so they land in different commits (see Commits in [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md)).
|
||||
- **Never commit `test.only`.** CI runs with `forbidOnly: true`.
|
||||
- **No `page.waitForTimeout(ms)`** — always prefer `await expect(locator).toBe…()`.
|
||||
|
||||
@@ -78,8 +60,8 @@ For each scenario in the plan:
|
||||
- **`describe` block** matches the top-level plan section.
|
||||
- **Title** matches `TC-NN <description>` exactly.
|
||||
- **Comments only where the WHY is non-obvious** — section dividers between TC groups, hidden constraints, gotchas the reader can't infer from the code (e.g. "Monaco swallows Escape — click the title to blur first"). **Do not narrate steps** by pasting the plan's bullets back as `// 1. Navigate…` `// 2. Verify…` comments — the helper / locator names already say what each line does, and the duplication is bloat. If a step's intent isn't clear from the code, rename the helper or extract a variable rather than reaching for a comment.
|
||||
- **Imports** from the feature's driver module (or `../../fixtures/auth` when none fits). **Do not** import from `@playwright/test` directly.
|
||||
- **Cleanup** through the driver's `dispose`; `try / finally` only without a driver.
|
||||
- **Imports** from `../../drivers/<feature>`. **Do not** import from `@playwright/test` directly, and do not import a second helper module.
|
||||
- **Cleanup** comes from the seed layer or the driver's `dispose`. Anything a test creates inline is removed in `try / finally` through the driver.
|
||||
- **Move recorded locators and waits into the driver.** The log gives raw `page.*` calls; the spec should read as driver actions.
|
||||
|
||||
# Quality bar — what to write, what to skip
|
||||
@@ -140,7 +122,7 @@ test.describe('Dashboards — list search', () => {
|
||||
});
|
||||
```
|
||||
|
||||
Note: no cleanup code (the `dashboards` driver deletes its seed), no raw locators (they live in `drivers/dashboard-list.ts`), and no `// 1. …` step narration. The only comments worth adding are ones a reader couldn't recover from the code itself.
|
||||
Note: no cleanup code (the `dashboards` driver deletes its seed), no raw locators (they live in `drivers/dashboard-list.ts`), and no `// 1. …` step narration. If a step needs an element the driver does not expose, add a method to the driver; do not reach for `page.getByTestId(...)` in the spec. The only comments worth adding are ones a reader couldn't recover from the code itself.
|
||||
|
||||
# Known UI gotchas (apply when relevant)
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ model: sonnet
|
||||
color: red
|
||||
---
|
||||
|
||||
You are the Playwright Test Healer for the SigNoz E2E suite. You debug and fix red specs with a methodical approach. Read [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) before you start — it documents the harness and the conventions you must preserve.
|
||||
You are the Playwright Test Healer for the SigNoz E2E suite. You debug and fix red specs with a methodical approach. Read [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) and [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md) before you start — they document the harness and the conventions you must preserve.
|
||||
|
||||
# Preconditions
|
||||
|
||||
@@ -27,11 +27,11 @@ Don't try to start the stack yourself — it can take ~4 minutes on a cold build
|
||||
- `browser_network_requests` for API failures (the SigNoz API requires `Authorization: Bearer <localStorage.AUTH_TOKEN>`; 401s usually mean the test bypassed the fixture).
|
||||
- `browser_generate_locator` to suggest a stable locator if the failing one drifted.
|
||||
4. **Root-cause.** Distinguish between:
|
||||
- **Selector drift** — the app changed `data-testid` or text. Fix the locator where it lives: in the driver under `tests/e2e/drivers/` when the spec uses one, so every spec sharing it heals at once. Prefer `data-testid` (grep `frontend/src/<feature-dir>/` for the new one).
|
||||
- **Timing** — the test races a load. Replace `waitForTimeout` with `await expect(locator).toBe…()` or `page.waitForResponse(...)` on the triggering action — inside the driver action when there is one.
|
||||
- **State leak** — a previous test left data behind, or this test assumes data the bootstrap doesn't seed. Seed through the driver (its `dispose` cleans up) or via API with `try / finally`. The bootstrap creates a fresh stack with **zero** dashboards / alerts and only the golden telemetry; parallel per-test seeds share the tenant, so an exact-count assertion on telemetry is a test bug — assert structure instead.
|
||||
- **Selector drift** — the app changed `data-testid` or text. Fix the locator. Prefer `data-testid` (grep `frontend/src/<feature-dir>/` for the new one).
|
||||
- **Timing** — the test races a load. Replace `waitForTimeout` with `await expect(locator).toBe…()` or `page.waitForResponse(...)` on the triggering action.
|
||||
- **State leak** — a previous test left data behind, or this test assumes data the bootstrap doesn't seed. Ensure the test seeds through its seed layer or driver (a driver's `dispose` cleans up), scopes its assertions to the names it seeded (with the worker index), and cleans up. The bootstrap creates a fresh stack with **zero** dashboards / alerts and only the golden telemetry; parallel per-test seeds share the tenant, so an exact-count assertion on telemetry is a test bug. Assert structure instead.
|
||||
- **Genuine app bug** — the app is broken, not the test. Mark the test with `test.fixme(...)` and add a one-line `// known: <description>` comment. Don't silently change the assertion to make it pass.
|
||||
5. **Fix.** Edit the spec or its driver. Preserve TC-NN titles, the driver / `authedPage` fixtures, cleanup, and serial mode if present. A driver change must keep every other spec importing it green — run them too. If you renumber, retitle, or `test.fixme(...)` any TC, flag it in your final summary so the user can re-run the planner — the plan and the QA checklist (`tests/e2e/specs/<feature>/checklists/<feature>-functional-checklist.md`) re-derive from the current `.spec.ts` and will otherwise drift.
|
||||
5. **Fix.** Edit the driver first, the spec second. A driver change must keep every other spec importing it green, so run them too. Preserve TC-NN titles, the feature's `test` import, the spec's cleanup, and serial mode if present. If you renumber, retitle, or `test.fixme(...)` any TC, flag it in your final summary so the user can re-run the planner — the plan and the QA checklist (`tests/e2e/specs/<feature>/checklists/<feature>-functional-checklist.md`) re-derive from the current `.spec.ts` and will otherwise drift.
|
||||
6. **Re-run only the fixed test** before moving to the next failure. Three options:
|
||||
- `npx playwright test -g 'TC-09' --project=chromium` — target a single TC by title
|
||||
- `npx playwright test --last-failed --project=chromium` — replay everything that failed last run
|
||||
@@ -41,17 +41,20 @@ Don't try to start the stack yourself — it can take ~4 minutes on a cold build
|
||||
|
||||
# Repo-specific signals
|
||||
|
||||
- **Reuse drivers and helpers before adding new code.** [`tests/e2e/drivers/`](../../tests/e2e/drivers/) holds the per-feature seed, cleanup, navigation and action methods (`kit.ts` explains `driver` / `seeded`); [`helpers/common.ts`](../../tests/e2e/helpers/common.ts) and [`helpers/auth.ts`](../../tests/e2e/helpers/auth.ts) the plain plumbing. Prefer them over re-inlining auth/login/POST code in the spec.
|
||||
- **Fix it in the driver, not in the spec.** Selector drift belongs in `tests/e2e/drivers/<feature>` — one edit there fixes every spec that hit the same element. A `page.locator(...)` added to a spec body is a regression, not a fix.
|
||||
- **Ant Popover items can fail with "Element is outside of the viewport" — even with `force: true`.** `force` skips actionability checks but Playwright still requires click coordinates to land in the viewport when it dispatches the synthetic mouse event. The robust fix is `tooltip.getByText('…').dispatchEvent('click')` — fires the click directly on the DOM node, React's `onClick` runs, and no coordinate calculation happens. Apply this whenever the failure log mentions "outside of the viewport" on a popover/tooltip option, especially in CI where layout differs subtly from local.
|
||||
- **Action-icon rows below the fold.** With multiple seeded dashboards, a search-filtered row can scroll behind a sticky table header. Add `scrollIntoViewIfNeeded` before the click, in the driver action.
|
||||
- **Action-icon rows below the fold.** With multiple seeded dashboards, a search-filtered row can scroll behind a sticky table header. Add `scrollIntoViewIfNeeded` before the click, in the driver action (`dashboardList.openRowMenu(name)`).
|
||||
- **React Query mutations vs page.goto.** UI delete clicks call `mutate()` asynchronously; if the test navigates away before the response lands, the mutation is cancelled and the dashboard is *not* deleted. Wait for the DELETE response and the dialog dismissal explicitly: `page.waitForResponse((r) => r.request().method() === 'DELETE' && /\/dashboards\//.test(r.url()))` plus `await expect(dialog).not.toBeVisible()`.
|
||||
- **Monaco editor swallows Escape inside the Import JSON dialog.** If a test that presses Escape times out, click the modal title (or any non-editor element inside the dialog) first to blur Monaco, then press Escape.
|
||||
- **The list pages render zero-state when the workspace is empty.** List controls and the `new-dashboard-cta` testid are absent in zero-state. A timeout on those usually means the workspace was empty — seed first via `dashboards.seed(...)`.
|
||||
- **Auth.** `tests/e2e/fixtures/auth.ts` logs in once per worker and caches `storageState` (cookies + localStorage with `AUTH_TOKEN`). For API-driven seeding/cleanup, use `authToken(page)` from `helpers/common.ts` and pass `Authorization: Bearer <token>`. Never re-implement login.
|
||||
- **Extended fixtures.** Domain-specific fixtures extend `auth` and add seeded data. Alerts uses `fixtures/alerts/alert-rules` (worker-scoped rule list, test-scoped factory) and `fixtures/alerts/alert-history` (extends alert-rules, waits on ruler evaluation). See [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) for the pattern. When a test fails on missing data, check if it imports the wrong fixture level.
|
||||
- **The list pages render zero-state when the workspace is empty.** Many locators (search input, sort button, `new-dashboard-cta` testid, "All Dashboards" header) are absent in zero-state. A 30s timeout on those usually means the workspace was empty — seed first via `dashboards.seed(...)`.
|
||||
- **Auth.** `tests/e2e/drivers/auth.ts` logs in once per worker and caches `storageState` (localStorage with `AUTH_TOKEN`). For API-driven seeding and cleanup use `apiDriver(page)` from `drivers/api.ts`, which attaches the header for you. Never re-implement login.
|
||||
- **Seeds.** Feature seeds are layers on the feature's `test`, e.g. `alertList`, `ownedRules` and `resolvedHistory` in `drivers/alerts/seeds.ts`. When a test fails on missing data, check which seed it destructures and whether it scopes to that seed's names.
|
||||
- **Timeouts.** Never add `test.slow()` to a driver: it triples the remaining budget per call and compounds in loops. Use `allowFor(floor)` from `drivers/kit.ts`. Budgets and their measurements are in `tests/e2e/docs/flake-notes.md`.
|
||||
- **CI-only failures.** Reproduce with `STRESS=1 CI=1 pnpm test <path>` from `tests/e2e/` before calling it a product bug.
|
||||
- **Commits.** Driver fixes and spec fixes go in separate commits (see Commits in `tests/e2e/AGENTS.md`).
|
||||
- **Ant Design popovers** (sort menu, action menu) are click-toggle. The trigger element is often an inline `<svg>` with a `data-testid` — clicking it opens the popover; clicking it again closes. After selecting an option, the popover auto-closes. If a test interacts with the popover twice, wait for the menu items to be visible explicitly between toggles.
|
||||
- **Artifacts.** Every failed test writes to `tests/e2e/artifacts/results/<test-slug>/` — the `error-context.md` accessibility snapshot is the fastest way to see what the page actually looked like when it failed.
|
||||
- **Type-check.** After edits, run `npx tsc --noEmit -p tests/e2e/tsconfig.json` if it succeeds, or rely on `npx playwright test --list` to validate the spec parses.
|
||||
- **Type-check.** After edits, run `pnpm typecheck` and `pnpm lint` from `tests/e2e/`.
|
||||
|
||||
# Hard rules
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ model: sonnet
|
||||
color: green
|
||||
---
|
||||
|
||||
You are an expert E2E test planner for the SigNoz frontend, working inside the SigNoz monorepo. Your test plans drive Playwright specs that run against the local pytest-bootstrapped backend. Read [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) before planning — it documents the harness, the `authedPage` fixture, the TC-NN naming convention, and the self-contained-state principle that every plan you write must respect.
|
||||
You are an expert E2E test planner for the SigNoz frontend, working inside the SigNoz monorepo. Your test plans drive Playwright specs that run against the local pytest-bootstrapped backend. Read [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) and [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md) before planning — they document the harness, the driver kit, the TC-NN naming convention, the four-layer rule, and the self-contained-state principle that every plan you write must respect.
|
||||
|
||||
You will:
|
||||
|
||||
@@ -16,28 +16,62 @@ You will:
|
||||
- Interactive elements and their `data-testid` attributes (preferred locators)
|
||||
- Conditional rendering (empty states, loading, error, role-gated UI)
|
||||
- URL query-param state (search, sort, pagination)
|
||||
- API endpoints the UI calls — these inform what cleanup endpoints exist for `try/finally` teardown
|
||||
- The frontend stores its JWT in `localStorage` under `AUTH_TOKEN` and the API requires `Authorization: Bearer <token>` for protected endpoints. Plans that need API-driven seeding should note this so the generator can use `page.request.*`.
|
||||
- API endpoints the UI calls — these tell the generator which seed and cleanup calls the driver needs
|
||||
- Seeding goes through the feature driver (`apiDriver` underneath) for control-plane objects and through the seeder for telemetry, never through `page.request.*`. Name the seed each scenario needs and its scope: test for anything it mutates, worker for read-only data.
|
||||
|
||||
2. **Check what's already wired up.**
|
||||
- [tests/e2e/drivers/](../../tests/e2e/drivers/) holds one driver per feature (e.g. `dashboards.ts`, `dashboard-list.ts`, `panel-editor.ts`, `routing.ts`, `channels.ts`). A driver is a fixture exposing the feature's locators and actions, including API seeding that cleans itself up (`dashboards.seed(...)`). When one covers the feature, write steps in terms of its actions by name so the generator reuses them. When none does, say so: the generator adds one.
|
||||
- [tests/e2e/helpers/](../../tests/e2e/helpers/) holds plain helpers: `common.ts` (`authToken`, `watchConsole`, `collectRequests`, `seederUrl`), `auth.ts` (`newAdminContext`), `query-range-mock.ts` (mock `query_range` for error, no-data, warning and loading states only).
|
||||
- **Telemetry is pre-seeded.** `bootstrap/global.setup.ts` loads a golden OTel-demo dataset (logs, traces, metrics over the last 6h; constants in `GOLDEN` in `helpers/dashboard-spec.ts`). Plans that query data use a window ≤ 6h and assert structure, not exact counts. Data the golden set lacks is seeded per test through the seeder (`helpers/alerts/seeding.ts` shows how).
|
||||
- [tests/e2e/testdata/](../../tests/e2e/testdata/) holds static payloads (`dashboards/panels.ts`, `traces/large-trace.json`) — note in the plan if a scenario benefits from one.
|
||||
2. **Work out which layer each scenario belongs to — before planning it.**
|
||||
|
||||
3. **Navigate and explore**
|
||||
This is the step that keeps the suite small, and it has to happen here
|
||||
because by review time the spec already exists. Read
|
||||
[tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md) for the full rule. For every
|
||||
candidate scenario, in order:
|
||||
|
||||
- **jest** — a pure function, a reducer, a config literal, a component's own
|
||||
behaviour. Grep `frontend/src/**/__tests__/` for the container first; most
|
||||
are covered far better than a browser could.
|
||||
- **Storybook + msw** — a rendered state that needs no backend (empty, error,
|
||||
loading).
|
||||
- **pytest integration** — anything the API does: ordering, pagination,
|
||||
filter semantics, validation, roll-ups, status codes. **Grep
|
||||
`tests/integration/` and name the test you found.** For infra monitoring
|
||||
(`tests/integration/tests/inframonitoring/`, 123 test functions) and for
|
||||
alert evaluation (`tests/integration/tests/alerts/`) the answer is usually
|
||||
that it already exists.
|
||||
- **E2E** — only when a real response has to reach a real DOM: URL and
|
||||
history, a write path that must persist, cross-page navigation, one seeded
|
||||
proof per surface.
|
||||
|
||||
The plan must say, per scenario, why it is not one of the cheaper three. A
|
||||
scenario that cannot answer that does not go in the plan.
|
||||
|
||||
3. **Check what's already wired up.**
|
||||
- [tests/e2e/drivers/](../../tests/e2e/drivers/) holds one driver module per
|
||||
feature plus the shared ones (`tanstack`, `querysearch`, `antd`, `api`,
|
||||
`storage`, `console`). Reference driver methods by name in the steps so the
|
||||
generator reuses them rather than reinventing a locator.
|
||||
- If a step needs something the driver does not expose, say so — the
|
||||
generator adds a driver method, not a `page.locator` in the spec.
|
||||
- **Telemetry is pre-seeded.** `bootstrap/global.setup.ts` loads a golden
|
||||
OTel-demo dataset (logs, traces, metrics over the last 6h; constants in
|
||||
`GOLDEN` in `drivers/dashboard-spec.ts`). Plans that query data use a
|
||||
window ≤ 6h and assert structure, not exact counts.
|
||||
- [tests/e2e/testdata/](../../tests/e2e/testdata/) holds static payloads
|
||||
(`dashboards/panels.ts`, `traces/large-trace.json`); note in the plan if a
|
||||
scenario benefits from one.
|
||||
|
||||
4. **Navigate and explore**
|
||||
- Invoke `planner_setup_page` once before any other browser tool.
|
||||
- Use `browser_snapshot` to read the page's accessibility tree. **Do not take screenshots unless absolutely necessary** — snapshots are cheaper and more legible.
|
||||
- Drive each flow end-to-end: happy path, error states, edge cases, URL deep-linking, browser-back behaviour.
|
||||
|
||||
4. **Design comprehensive scenarios**
|
||||
5. **Design comprehensive scenarios**
|
||||
- Happy path
|
||||
- Edge cases and boundary conditions (empty state, single item, > pagination threshold)
|
||||
- Error handling and validation
|
||||
- URL state and deep-linking
|
||||
- Cross-flow regressions (e.g. searching while paginated)
|
||||
|
||||
5. **Structure the test plan**
|
||||
6. **Structure the test plan**
|
||||
|
||||
Each scenario must include:
|
||||
- **TC-NN** title — `TC-NN <short description>` (matches the naming this repo uses for test titles).
|
||||
@@ -46,7 +80,7 @@ You will:
|
||||
- Expected outcomes per step.
|
||||
- Cleanup notes (what gets created and how to remove it — usually via API).
|
||||
|
||||
6. **Save the plan and the checklist**
|
||||
7. **Save the plan and the checklist**
|
||||
- **Plan:** `tests/e2e/specs/<feature>/<feature>-test-plan.md`. **`tests/e2e/specs/` is gitignored** — plans are scratch artifacts: working input for the generator, regenerable, not committed. Don't treat them as durable documentation. The committed tests are the source of truth.
|
||||
- **Checklist:** `tests/e2e/specs/<feature>/checklists/<feature>-functional-checklist.md`. A manual-verification runbook that mirrors the TC list one-to-one (one checkbox per TC) for QA hand-off. Same gitignore, same scratch status.
|
||||
- **The checklist must stay in sync with the TCs.** When you regenerate the plan, regenerate the checklist alongside it — they share TC IDs and titles, and the checklist ordering must match. If the existing spec under `tests/e2e/tests/<feature>/` has more / fewer / different TCs than the prior plan, the spec is authoritative: re-derive plan and checklist from it.
|
||||
@@ -97,8 +131,8 @@ The dashboards list page (`/dashboard`) lists all dashboards in the workspace. F
|
||||
**Quality bar:**
|
||||
- Steps must be specific enough that any tester (or the generator agent) can follow without ambiguity.
|
||||
- Include negative scenarios — empty state, no-match search, validation errors.
|
||||
- Each scenario must own its preconditions and cleanup. **Do not invent cross-file global fixtures** — they break parallel-by-file execution. Prefer a driver's self-cleaning seed (`dispose`) or worker-scoped `seeded(...)` layer; without a driver, suite-level `beforeAll` / `afterAll` within one spec file or per-test `try / finally` both work.
|
||||
- Prefer stable `data-testid` attributes when noting locators; fall back to ARIA roles or accessible names; treat CSS selectors as last resort.
|
||||
- Each scenario must own its preconditions and cleanup, and assert only on names it seeded. **Never depend on data another spec file created.** Files run in parallel. Pick the seed scope from the Seeding table in [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md); a driver's self-cleaning seed (`dispose`) or a worker-scoped `seeded(...)` layer covers most cases.
|
||||
- Note the `data-testid` for every element a step touches. Where none exists, say so: the generator adds it to the product rather than falling back to roles or CSS (antd internals aside).
|
||||
- **Don't pad coverage.** Every TC must catch a regression that would actually ship if the test were missing — a real branch in the source, a real user-visible failure mode. A TC that asserts a hard-coded string is still rendered, or that a button is still a button, adds nothing but maintenance cost: it inflates the suite, slows CI, and trains readers to skim past the directory. Before writing a scenario, ask "what code change would break this?" — if the only answer is "deleting the literal under test," cut it or fold it into a richer scenario as one assertion among many.
|
||||
- **Collapse near-duplicates.** Two TCs that differ only in input value (search by title vs search by description, when the underlying code path is the same) should merge into one parameterised scenario unless each input genuinely exercises a distinct branch. Prefer one assertion-rich TC over three thin ones.
|
||||
- **Smoke-checks aren't TCs.** "Heading is visible" belongs as the first assertion inside a real scenario, not as its own numbered case.
|
||||
|
||||
6
.gitattributes
vendored
6
.gitattributes
vendored
@@ -2,3 +2,9 @@
|
||||
*.stories.mocks.tsx linguist-generated=true
|
||||
**/__story_mockdata__/** linguist-generated=true
|
||||
tests/e2e/drivers/** linguist-generated=true
|
||||
|
||||
# Transcribed E2E data: seeded telemetry, golden payloads and the entity
|
||||
# datasets. Regenerated from the seeder rather than hand-edited, and re-derived
|
||||
# by the specs that read them, so they are collapsed in review.
|
||||
tests/e2e/testdata/** linguist-generated=true
|
||||
tests/e2e/**/__generated__/** linguist-generated=true
|
||||
|
||||
7
.github/workflows/e2eci.yaml
vendored
7
.github/workflows/e2eci.yaml
vendored
@@ -2,6 +2,9 @@ name: e2eci
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
merge_group:
|
||||
types:
|
||||
- checks_requested
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
@@ -13,8 +16,12 @@ jobs:
|
||||
outputs:
|
||||
e2e: ${{ steps.changes.outputs.e2e }}
|
||||
steps:
|
||||
- name: merge-queue-pass
|
||||
if: github.event_name == 'merge_group'
|
||||
run: echo "::notice::Merge queue run. E2E already gated the PR, so the required e2e check auto-passes."
|
||||
- name: changes
|
||||
id: changes
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
|
||||
4
.github/workflows/integrationci.yaml
vendored
4
.github/workflows/integrationci.yaml
vendored
@@ -106,8 +106,8 @@ jobs:
|
||||
- name: webdriver
|
||||
if: matrix.suite == 'callbackauthn' || matrix.suite == 'basepath'
|
||||
run: |
|
||||
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
|
||||
echo "deb http://dl.google.com/linux/chrome/deb/ stable main" | sudo tee -a /etc/apt/sources.list.d/google-chrome.list
|
||||
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo gpg --batch --yes --dearmor -o /usr/share/keyrings/google-chrome.gpg
|
||||
echo "deb [signed-by=/usr/share/keyrings/google-chrome.gpg] http://dl.google.com/linux/chrome/deb/ stable main" | sudo tee -a /etc/apt/sources.list.d/google-chrome.list
|
||||
sudo apt-get update -qqy
|
||||
sudo apt-get -qqy install google-chrome-stable
|
||||
CHROME_VERSION=$(google-chrome-stable --version)
|
||||
|
||||
@@ -16,6 +16,14 @@ packages:
|
||||
filename: "maintenance.go"
|
||||
structname: 'Mock{{.InterfaceName}}'
|
||||
pkgname: '{{.SrcPackageName}}test'
|
||||
github.com/SigNoz/signoz/pkg/types/telemetrytypes:
|
||||
interfaces:
|
||||
SchemaMetadataStore:
|
||||
config:
|
||||
dir: '{{.InterfaceDir}}/telemetrytypestest'
|
||||
filename: "schema_metadata_store.go"
|
||||
structname: 'Mock{{.InterfaceName}}'
|
||||
pkgname: '{{.SrcPackageName}}test'
|
||||
github.com/SigNoz/signoz/pkg/tokenizer:
|
||||
config:
|
||||
all: true
|
||||
|
||||
@@ -178,6 +178,9 @@ querier:
|
||||
# range with padding to include slightly delayed log exports. Logs only; set
|
||||
# to 0 to disable.
|
||||
log_trace_id_window_padding: 5m
|
||||
schemametadatastore:
|
||||
# How long found schema metadata stays cached; 0 caches it for the life of the process.
|
||||
cache_ttl: 0s
|
||||
|
||||
##################### TelemetryStore #####################
|
||||
telemetrystore:
|
||||
|
||||
@@ -2205,10 +2205,10 @@ components:
|
||||
type: object
|
||||
CloudintegrationtypesAWSConnectionArtifact:
|
||||
properties:
|
||||
connectionUrl:
|
||||
cliCommand:
|
||||
type: string
|
||||
required:
|
||||
- connectionUrl
|
||||
- cliCommand
|
||||
type: object
|
||||
CloudintegrationtypesAWSIntegrationConfig:
|
||||
properties:
|
||||
@@ -2364,11 +2364,8 @@ components:
|
||||
properties:
|
||||
cliCommand:
|
||||
type: string
|
||||
cloudPowerShellCommand:
|
||||
type: string
|
||||
required:
|
||||
- cliCommand
|
||||
- cloudPowerShellCommand
|
||||
type: object
|
||||
CloudintegrationtypesAzureIntegrationConfig:
|
||||
properties:
|
||||
@@ -25153,9 +25150,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- rule:list
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- rule:list
|
||||
summary: List rule saved views
|
||||
tags:
|
||||
- rules
|
||||
@@ -25211,9 +25208,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- rule:list
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- rule:list
|
||||
summary: Create rule saved view
|
||||
tags:
|
||||
- rules
|
||||
@@ -25265,9 +25262,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- rule:list
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- rule:list
|
||||
summary: Delete rule saved view
|
||||
tags:
|
||||
- rules
|
||||
@@ -25334,9 +25331,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- rule:list
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- rule:list
|
||||
summary: Update rule saved view
|
||||
tags:
|
||||
- rules
|
||||
|
||||
@@ -28,7 +28,7 @@ func ConvertConfig(src ExternalConfig) (InternalConfig, error)
|
||||
// Over this:
|
||||
type ConfigAdapter struct { ... }
|
||||
func NewConfigAdapter(src ExternalConfig) *ConfigAdapter
|
||||
func (a *ConfigAdapter) ToInternal() (InternalConfig, error)
|
||||
func (adapter *ConfigAdapter) ToInternal() (InternalConfig, error)
|
||||
```
|
||||
|
||||
The two-step version is only justified when `ConfigAdapter` has multiple distinct consumers that use it in different ways.
|
||||
@@ -66,10 +66,10 @@ A method on a structured type should not strip meaning from the structure it bel
|
||||
|
||||
```go
|
||||
// Problematic: callers cannot distinguish how items were related.
|
||||
func (o *Order) AllLineItems() []LineItem { ... }
|
||||
func (order *Order) AllLineItems() []LineItem { ... }
|
||||
|
||||
// Better: the validation logic operates on the full structure.
|
||||
func ValidateOrder(o *Order) error { ... }
|
||||
func ValidateOrder(order *Order) error { ... }
|
||||
```
|
||||
|
||||
Public methods shape how a type is used. Once a lossy accessor exists, callers will depend on it, and the lost information becomes unrecoverable at those call sites.
|
||||
|
||||
@@ -74,7 +74,7 @@ The `*Visitor` passed in provides everything needed to build predicates. Use the
|
||||
In the simplest case, keys map straight to columns and the resolver is a switch. The doc's running example, an imaginary `sample_entity` table:
|
||||
|
||||
```go
|
||||
func (r sampleEntityFieldResolver) ResolveComparison(v *sqlcompiler.Visitor, key string, operation qbtypesv5.FilterOperator, ctx *grammar.ComparisonContext) string {
|
||||
func (resolver sampleEntityFieldResolver) ResolveComparison(v *sqlcompiler.Visitor, key string, operation qbtypesv5.FilterOperator, ctx *grammar.ComparisonContext) string {
|
||||
switch key {
|
||||
case "created_by":
|
||||
return v.BuildStringOperation(v.Sb, ctx, operation, "sample_entity.created_by", key)
|
||||
|
||||
@@ -82,7 +82,7 @@ In the module implementation, implement the new method. A typical implementation
|
||||
- Uses the `render` package to write responses or errors
|
||||
|
||||
```go
|
||||
func (h *handler) CreateThing(rw http.ResponseWriter, req *http.Request) {
|
||||
func (handler *handler) CreateThing(rw http.ResponseWriter, req *http.Request) {
|
||||
// Extract authentication and organization context from req.Context()
|
||||
claims, err := authtypes.ClaimsFromContext(req.Context())
|
||||
if err != nil {
|
||||
@@ -98,7 +98,7 @@ func (h *handler) CreateThing(rw http.ResponseWriter, req *http.Request) {
|
||||
}
|
||||
|
||||
// Call module functions
|
||||
out, err := h.module.CreateThing(req.Context(), claims.OrgID, &in)
|
||||
out, err := handler.module.CreateThing(req.Context(), claims.OrgID, &in)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
|
||||
@@ -59,7 +59,8 @@ Follow these rules:
|
||||
|
||||
### Unexported symbols
|
||||
|
||||
- Struct receivers: one or two characters (`c`, `f`, `br`).
|
||||
- Struct receivers: the lowercase name of the role the type plays, the same on every method of the type (`provider`, `module`, `handler`, `store`, `middleware`, `migration`). Never one or two characters: `c`, `h`, `m` say nothing at the call site and collide with local variables.
|
||||
- When the receiver name would shadow an imported package, alias the import, not the receiver (`pkghandler "github.com/SigNoz/signoz/pkg/http/handler"` with a `handler` receiver).
|
||||
- Helper functions: descriptive lowercase names (`parseToken`, `buildQuery`).
|
||||
|
||||
### Constants
|
||||
|
||||
@@ -70,16 +70,16 @@ The instrumentation SDK (`pkg/instrumentation/sdk.go`) is idle while running but
|
||||
```go
|
||||
// pkg/instrumentation/sdk.go
|
||||
|
||||
func (i *SDK) Start(ctx context.Context) error {
|
||||
<-i.startCh
|
||||
func (sdk *SDK) Start(ctx context.Context) error {
|
||||
<-sdk.startCh
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *SDK) Stop(ctx context.Context) error {
|
||||
close(i.startCh)
|
||||
func (sdk *SDK) Stop(ctx context.Context) error {
|
||||
close(sdk.startCh)
|
||||
return errors.Join(
|
||||
i.sdk.Shutdown(ctx),
|
||||
i.meterProviderShutdownFunc(ctx),
|
||||
sdk.sdk.Shutdown(ctx),
|
||||
sdk.meterProviderShutdownFunc(ctx),
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -197,8 +197,8 @@ A standalone service only has the `factory.Service` lifecycle i.e it does not se
|
||||
}
|
||||
}
|
||||
|
||||
func (s *service) Start(ctx context.Context) error { ... }
|
||||
func (s *service) Stop(ctx context.Context) error { ... }
|
||||
func (service *service) Start(ctx context.Context) error { ... }
|
||||
func (service *service) Stop(ctx context.Context) error { ... }
|
||||
```
|
||||
|
||||
### Provider that is also a service
|
||||
|
||||
@@ -17,7 +17,7 @@ Two rules shape how the core type behaves:
|
||||
func NewGettableAuthDomainFromAuthDomain(d *AuthDomain, info *AuthNProviderInfo) *GettableAuthDomain
|
||||
|
||||
// Receiver form
|
||||
func (m *PlannedMaintenanceWithRules) ToPlannedMaintenance() *PlannedMaintenance
|
||||
func (maintenance *PlannedMaintenanceWithRules) ToPlannedMaintenance() *PlannedMaintenance
|
||||
```
|
||||
- **`X` can double as the storage row** when the DB shape would be identical. `Channel` embeds `bun.BaseModel` directly, and there is no `StorableChannel`. This is the preferred shape when it works.
|
||||
|
||||
@@ -175,10 +175,10 @@ The rules that make the envelope work:
|
||||
|
||||
```go
|
||||
// Domain invariants: every write path re-runs these.
|
||||
func (x *X) Validate() error { ... }
|
||||
func (entity *X) Validate() error { ... }
|
||||
|
||||
// Request-shape-only: checks that do not apply once the value is persisted.
|
||||
func (p *PostableX) Validate() error { ... }
|
||||
func (postable *PostableX) Validate() error { ... }
|
||||
```
|
||||
- **Type aliases, not wrappers**, when two shapes are identical. `type GettableChannels = []*Channel` is correct because it adds no semantics beyond the underlying type.
|
||||
- **Serialization tags** follow [handler.md](handler.md): `required:"true"` means the JSON key must be present, `nullable:"true"` is required on any slice or map that may serialize as `null`, and types with a fixed value set must implement `Enum() []any`.
|
||||
|
||||
@@ -11,7 +11,7 @@ Before running E2E tests, ensure you have the following installed:
|
||||
- Python 3.13+
|
||||
- [uv](https://docs.astral.sh/uv/getting-started/installation/)
|
||||
- Docker (for containerized services)
|
||||
- Node 18+ and Yarn
|
||||
- Node 18+ and pnpm
|
||||
|
||||
### Initial Setup
|
||||
|
||||
@@ -24,8 +24,8 @@ uv sync
|
||||
2. Install Node deps and Playwright browsers:
|
||||
```bash
|
||||
cd e2e
|
||||
yarn install
|
||||
yarn install:browsers # one-time Playwright browser install
|
||||
pnpm install
|
||||
pnpm install:browsers # one-time Playwright browser install
|
||||
```
|
||||
|
||||
### Starting the Test Environment
|
||||
@@ -84,127 +84,118 @@ tests/
|
||||
├── playwright.config.ts # loads .env + .env.local via dotenv
|
||||
├── .env.example # staging-mode template
|
||||
├── .env.local # generated by bootstrap/setup.py (gitignored)
|
||||
├── AGENTS.md # read this before writing a spec
|
||||
├── bootstrap/
|
||||
│ └── setup.py # test_setup / test_teardown — pytest lifecycle
|
||||
├── drivers/ # the driver kit and one driver per feature
|
||||
│ ├── kit.ts
|
||||
│ └── routing.ts
|
||||
├── fixtures/ # Playwright test fixtures (test.extend) only
|
||||
│ └── auth.ts
|
||||
├── helpers/ # function helpers + the constants they share with tests
|
||||
│ ├── auth.ts
|
||||
│ └── logs-explorer.ts
|
||||
├── testdata/ # static data files (JSON) used by helpers and tests
|
||||
│ └── traces/large-trace.json # (example)
|
||||
├── tests/ # Playwright .spec.ts files, one dir per feature area
|
||||
├── drivers/ # the driver kit: one module per feature
|
||||
│ ├── kit.ts # layer(), seeded(), the root `test`
|
||||
│ ├── auth.ts # login + per-worker storageState
|
||||
│ ├── api.ts # authed HTTP client + seeder URL
|
||||
│ ├── tanstack.ts # the shared table driver
|
||||
│ ├── alerts/ # feature driver, seeds, payloads
|
||||
│ └── infra/ # feature driver, seeds, __generated__/datasets.ts
|
||||
├── docs/flake-notes.md # measurements and timeout budgets
|
||||
├── testdata/ # static data files (marked generated)
|
||||
├── tests/ # Playwright .spec.ts files, one dir per feature
|
||||
│ └── alerts/
|
||||
│ └── alerts.spec.ts # (example)
|
||||
│ └── list.spec.ts # (example)
|
||||
└── artifacts/ # per-run output (gitignored)
|
||||
├── html/ # HTML reporter output
|
||||
├── json/ # JSON reporter output
|
||||
└── results/ # per-test traces / screenshots / videos on failure
|
||||
```
|
||||
|
||||
### `fixtures/` vs `helpers/` — what goes where
|
||||
### The driver kit
|
||||
|
||||
These two folders look similar but mean different things:
|
||||
|
||||
- **`fixtures/`** holds *Playwright test fixtures* (created via `test.extend({...})`). By the canonical definition, a fixture is "a consistent, predefined set of data, objects, or environmental conditions used to ensure tests run in a stable state" — i.e. setup/teardown that runs *automatically* around each test or worker. `auth.ts` matches: it extends Playwright's `test` with an `authedPage` that's logged-in before every test runs and torn down after. If the only thing in this folder ever is `auth.ts`, that's fine — fixtures are a deliberately small surface.
|
||||
- **`helpers/`** holds plain function helpers that you call *explicitly* from a test or hook — they don't extend Playwright's `test`. This covers both behaviour helpers (e.g. `gotoLogsExplorer(page)`) and the constants those helpers and the tests both refer to (e.g. `LINKED_ROW_CLASS`). Constants live next to the helpers that use them so a single import line in a test covers both.
|
||||
- **`testdata/`** holds static data files (typically JSON / YAML) consumed by the helpers — for example, `traces/large-trace.json`, a real trace the trace-details helpers seed.
|
||||
|
||||
Rule of thumb: if it's a `test.extend` fixture, put it in `fixtures/`. If it's a function you call explicitly (or a constant the function uses), put it in `helpers/`. If it's a static file the helpers read, put it in `testdata/`.
|
||||
|
||||
### Drivers
|
||||
|
||||
New suites use a driver rather than loose helpers. A driver is a function that closes over the page and returns the feature's actions and locators. `drivers/kit.ts` turns it into a fixture, so a spec imports one module and never passes a `page` around:
|
||||
A spec imports **one** module: its feature's `test` constant. That constant is
|
||||
built by composing layers, and each layer adds one named driver to the test
|
||||
arguments — so a spec body never handles a `Page`:
|
||||
|
||||
```ts
|
||||
import { expect, PATH, test } from '../../drivers/routing';
|
||||
import { expect, test } from '../../drivers/alerts';
|
||||
|
||||
test('TC-09 RouteTab switches the url', async ({ routing }) => {
|
||||
await routing.goto(PATH.metricsSummary);
|
||||
await expect(routing.activeRouteTab(PATH.metricsSummary)).toBeVisible();
|
||||
test('TC-01 seeded rules render', async ({ alerts, alertList }) => {
|
||||
await alerts.list.goto({ search: alertList.namePrefix });
|
||||
await expect(alerts.list.rows()).toHaveCount(10);
|
||||
});
|
||||
```
|
||||
|
||||
- `driver(name, build, dispose?)` adds a test-scoped fixture built on `authedPage`. `dispose` runs after the test on the same page, so a driver can delete what it seeded.
|
||||
- `seeded(name, open, close)` adds a worker-scoped seed. `open` and `close` run on a throwaway admin page.
|
||||
- A driver reuses helpers by calling them, never by reaching for another fixture.
|
||||
- `drivers/` is AI-owned: coding agents generate and maintain it with the specs, and `.gitattributes` collapses it in diffs.
|
||||
|
||||
### Extended fixtures
|
||||
|
||||
For features needing complex setup (API-seeded data, ruler evaluation waits, cleanup), create domain-specific fixtures that extend `auth`. Group them in `fixtures/<domain>/`.
|
||||
- **`drivers/kit.ts`** holds the composition primitives. `driver(name, build, dispose?)`
|
||||
binds a factory to the authenticated page, and `dispose` runs after the test
|
||||
on the same page so a driver can delete what it seeded; `seeded(name, open, close)` seeds
|
||||
data once per worker on a throwaway admin page and tears it down after;
|
||||
`allowFor(floor)` raises the test timeout to a floor and never lowers it.
|
||||
`test.slow()` is banned in drivers, because it compounds when called in a loop.
|
||||
- **`drivers/<feature>.ts`** (or `drivers/<feature>/`) exports the feature's
|
||||
driver, its layers, and the composed `test`. A driver is a plain function
|
||||
returning an object of closures — no classes, and no `page` parameter on
|
||||
anything a spec calls.
|
||||
- **Shared drivers** — `tanstack.ts` (the table), `querysearch.ts` (the
|
||||
expression editor), `antd.ts` (select primitives), `console.ts`, `api.ts`,
|
||||
`storage.ts` — are composed into feature drivers by direct call, not by
|
||||
reaching for another fixture.
|
||||
- **`drivers/` is AI-owned**: coding agents generate and maintain it with the
|
||||
specs, and `.gitattributes` collapses it in diffs.
|
||||
- **`testdata/`** and any `__generated__/` directory hold transcribed data. Both
|
||||
are marked `linguist-generated`; something in the suite re-derives them at
|
||||
runtime, so a stale value fails loudly rather than silently.
|
||||
|
||||
**Fixture scopes:**
|
||||
- **test scope** — fresh data per test. Use for mutations (edit, delete, rename).
|
||||
- **worker scope** — shared across tests in one worker. Use for read-only data. Worker scope pays the setup cost once per worker instead of once per test.
|
||||
- **worker scope** — shared across a worker. Use for read-only data; it pays the
|
||||
setup cost once per worker instead of once per test. Playwright builds them
|
||||
lazily, so a spec that never destructures a seed never pays for it.
|
||||
- **suite scope**: a dataset only one file uses. Seed it in `test.beforeAll`
|
||||
through `onAdminPage(browser, …)`, since `authedPage` is test-scoped.
|
||||
|
||||
**The alerts pattern** (`fixtures/alerts/`) demonstrates extending fixtures:
|
||||
### Which layer does this test belong to?
|
||||
|
||||
```
|
||||
fixtures/alerts/
|
||||
├── alert-rules.ts # extends auth — worker-scoped rule list + test-scoped factory
|
||||
└── alert-history.ts # extends alert-rules — adds history fixtures (waits on ruler)
|
||||
```
|
||||
Four layers run against this codebase, in cost order: **jest → Storybook + msw →
|
||||
pytest integration → Playwright**. Before writing an E2E, check the cheaper
|
||||
three. [`tests/e2e/AGENTS.md`](../../../tests/e2e/AGENTS.md) has the full rule;
|
||||
the short version:
|
||||
|
||||
Specs import from the fixture they need:
|
||||
|
||||
```ts
|
||||
// List tests — just need rules, no history
|
||||
import { test, expect } from '../../../fixtures/alerts/alert-rules';
|
||||
|
||||
// History tests — need history rows from ruler evaluation
|
||||
import { test, expect } from '../../../fixtures/alerts/alert-history';
|
||||
```
|
||||
|
||||
**When creating new fixtures:**
|
||||
|
||||
1. **Identify scope** — Will tests mutate the data? If yes, test-scoped. If read-only, worker-scoped.
|
||||
2. **Group by domain** — Put fixtures in `fixtures/<domain>/`. Helpers in `helpers/<domain>/`.
|
||||
3. **Extend existing fixtures** — Chain from `auth` or another fixture to inherit its setup.
|
||||
4. **Handle timeouts** — Worker-scoped fixtures that wait on backend processing need explicit timeouts.
|
||||
5. **Clean up** — Always delete seeded data in the fixture teardown (after `use()`).
|
||||
6. **Extract logic into functions** — Keep the `test.extend()` block lean; move setup/teardown logic to named functions so the extend block reads as a manifest of "what fixtures exist."
|
||||
- A pure function, a reducer, a config literal or a component's own behaviour is
|
||||
a **jest** test. Most containers under `frontend/src/container/` already have
|
||||
one.
|
||||
- A rendered state that needs no backend (empty, error, loading) is a
|
||||
**Storybook** story or a jest test with a fixed mock.
|
||||
- Anything the **API** does — ordering, pagination, filter semantics, validation,
|
||||
roll-ups — is a pytest integration test, and for infra monitoring and alert
|
||||
evaluation it very likely already exists. Grep `tests/integration/` first.
|
||||
- An **E2E** is for a real response reaching a real DOM: URL and history, write
|
||||
paths that must persist, cross-page navigation, and one seeded proof per
|
||||
surface.
|
||||
|
||||
Each spec follows these principles:
|
||||
|
||||
1. **Directory per feature**: `tests/e2e/tests/<feature>/*.spec.ts`. Cross-resource junction concerns (e.g. cascade-delete) go in their own file, not packed into one giant spec.
|
||||
2. **Test titles use `TC-NN`**: `test('TC-01 alerts page — tabs render', ...)`. Preserves ordering at a glance and maps to external coverage tracking.
|
||||
3. **UI-first**: drive flows through the UI. Playwright traces capture every BE request/response the UI triggers, so asserting on UI outcomes implicitly validates BE contracts. Reach for direct `page.request.*` only when the test's *purpose* is asserting a response contract (use `page.waitForResponse` on a UI click) or when a specific UI step is structurally flaky (e.g. Ant DatePicker calendar-cell indices) — and even then try UI first.
|
||||
4. **Self-contained state**: each spec seeds its own data and cleans up at suite teardown. The pytest harness creates a fresh stack with **zero** dashboards / alerts / etc. — never assume pre-existing data. Patterns, in order of preference:
|
||||
- **Driver `dispose`** — the driver tracks what it seeded and deletes it after the test, so the spec has no cleanup code. See `dashboards.seed(...)` in `tests/e2e/drivers/dashboards.ts`.
|
||||
- **Per-test seed + cleanup in `try / finally`** — small specs without a driver, where each test owns its data.
|
||||
- **Suite-level seed + `afterAll` teardown** — larger specs without a driver. One `test.afterAll(...)` deletes everything the suite seeded. See `tests/e2e/tests/llm-o11y/llm-pricing.spec.ts`. `test.beforeAll` / `test.afterAll` cannot use `authedPage` directly (it's test-scoped); use `newAdminContext(browser)` from `helpers/auth.ts` instead — it performs one fresh login per suite hook.
|
||||
5. **Seed via API when the UI flow is multi-step or brittle.** The frontend stores its JWT in `localStorage` under `AUTH_TOKEN`; `page.request.*` inherits the auth fixture's storage state. A typical pattern:
|
||||
```ts
|
||||
const token = await page.evaluate(
|
||||
() => (globalThis as any).localStorage.getItem('AUTH_TOKEN') || '',
|
||||
);
|
||||
await page.request.post('/api/v1/dashboards', {
|
||||
data: { title: 'my-name', uploadedGrafana: false },
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
```
|
||||
This is faster and more reliable than a multi-step UI seed. Reach for the UI flow only when the test's *purpose* is asserting that flow.
|
||||
6. **Reusable static data lives in `tests/e2e/testdata/`.** For example, `traces/large-trace.json` is a real trace that `loadLargeTrace` (in `helpers/trace-details.ts`) seeds for the trace-details tests.
|
||||
3. **UI-first**: drive flows through the UI. Playwright traces capture every BE request/response the UI triggers, so asserting on UI outcomes implicitly validates BE contracts. To assert a write, attach `page.waitForResponse` before the click, then reload and re-read from the server.
|
||||
4. **Self-contained state**: each spec seeds its own data, scopes its assertions to the names it seeded, and cleans up. The pytest harness creates a fresh stack with **zero** dashboards / alerts / etc. Names carry the worker index, so parallel workers never collide. Pick the scope from the list above.
|
||||
5. **Seed through the kit when the UI flow is not under test.** `apiDriver(page)` (`drivers/api.ts`) creates control-plane objects with the session's token, and the seeder takes telemetry. The JWT lives in `localStorage`, so a spec never improvises with `page.request.*`. Feature drivers wrap both (`dashboards.seed`, `alerts.seed.threshold`).
|
||||
6. **Reusable static data lives in `tests/e2e/testdata/`.** For example, `traces/large-trace.json` is POSTed to the seeder by `drivers/traces.ts`. Infra monitoring reads the integration suite's fixtures through `seedDataset` (`drivers/infra/seed.ts`) instead of keeping a copy, and asserts on what it returned.
|
||||
7. **Locate by testid, in the driver.** A missing testid is added to the product in the same change. Role, label and CSS lookups are a stopgap, converted as that code is touched; antd internals (`.ant-select-dropdown`) are the exception, since the markup is not ours.
|
||||
|
||||
## How to write an E2E test?
|
||||
|
||||
Create a new file `tests/e2e/tests/alerts/smoke.spec.ts`:
|
||||
|
||||
```typescript
|
||||
import { test, expect } from '../../fixtures/auth';
|
||||
import { ALERT_LIST_PAGE_SIZE, expect, test } from '../../drivers/alerts';
|
||||
|
||||
test('TC-01 alerts page — tabs render', async ({ authedPage: page }) => {
|
||||
await page.goto('/alerts');
|
||||
await expect(page.getByRole('tab', { name: /alert rules/i })).toBeVisible();
|
||||
await expect(page.getByRole('tab', { name: /configuration/i })).toBeVisible();
|
||||
test('TC-01 seeded rules render and paginate', async ({ alerts, alertList }) => {
|
||||
await alerts.list.goto({ search: alertList.namePrefix });
|
||||
await expect(alerts.list.table.totalCount()).toContainText(`of ${alertList.count}`);
|
||||
await expect(alerts.list.rows()).toHaveCount(ALERT_LIST_PAGE_SIZE);
|
||||
});
|
||||
```
|
||||
|
||||
The `authedPage` fixture (from `tests/e2e/fixtures/auth.ts`) gives you a `Page` whose browser context is already authenticated as the admin user. First use per worker triggers one login; the resulting `storageState` is held in memory and reused for later requests.
|
||||
`alertList` is a worker-scoped seed: the rules exist before the test starts, are
|
||||
shared by every test in the worker that asks for them, and are deleted when the
|
||||
worker ends.
|
||||
|
||||
The `authedPage` fixture (from `tests/e2e/drivers/kit.ts`, re-exported by every feature's `test`) gives you a `Page` whose browser context is already authenticated as the admin user. First use per worker triggers one login; the resulting `storageState` is held in memory and reused for later requests. Take it only when the driver genuinely does not cover what you need — navigation, `goBack`, `waitForResponse`, a second tab.
|
||||
|
||||
To run just this test (assuming the stack is up via `test_setup`):
|
||||
|
||||
@@ -213,52 +204,56 @@ cd tests/e2e
|
||||
npx playwright test tests/alerts/smoke.spec.ts --project=chromium
|
||||
```
|
||||
|
||||
Here's a more comprehensive example that exercises a CRUD flow via the UI:
|
||||
Here's a more comprehensive example, driven entirely through the feature's
|
||||
driver:
|
||||
|
||||
```typescript
|
||||
import { test, expect } from '../../fixtures/auth';
|
||||
import { expect, test } from '../../drivers/alerts';
|
||||
|
||||
test.describe.configure({ mode: 'serial' });
|
||||
test('TC-02 row actions persist: disable, then enable', async ({
|
||||
authedPage: page,
|
||||
alerts,
|
||||
ownedRules,
|
||||
}) => {
|
||||
const name = `smoke-rule-${Date.now()}`;
|
||||
const ruleId = await ownedRules.threshold(name);
|
||||
|
||||
test('TC-02 alerts list — create, toggle, delete', async ({ authedPage: page }) => {
|
||||
await page.goto('/alerts?tab=AlertRules');
|
||||
const name = 'smoke-rule';
|
||||
await alerts.list.goto({ search: name });
|
||||
await expect(alerts.list.stateCell(ruleId)).toHaveText('OK');
|
||||
|
||||
// Seed via UI — click "New Alert", fill form, save.
|
||||
await page.getByRole('button', { name: /new alert/i }).click();
|
||||
await page.getByTestId('alert-name-input').fill(name);
|
||||
// ... fill metric / threshold / save ...
|
||||
await alerts.list.openFirstRowActions();
|
||||
await Promise.all([
|
||||
// waitForResponse captures the call the UI triggers — no parallel fetch.
|
||||
page.waitForResponse(
|
||||
(res) =>
|
||||
res.url().includes(`/api/v2/rules/${ruleId}`) &&
|
||||
res.request().method() === 'PATCH',
|
||||
),
|
||||
alerts.list.menuItem('Disable').click(),
|
||||
]);
|
||||
|
||||
// Find the row and exercise the action menu.
|
||||
const row = page.locator('tr', { hasText: name });
|
||||
await expect(row).toBeVisible();
|
||||
await row.locator('[data-testid="alert-actions"] button').first().click();
|
||||
|
||||
// waitForResponse captures the network call the UI triggers — no parallel fetch needed.
|
||||
const patchWait = page.waitForResponse(
|
||||
(r) => r.url().includes('/rules/') && r.request().method() === 'PATCH',
|
||||
);
|
||||
await page.getByRole('menuitem').filter({ hasText: /^disable$/i }).click();
|
||||
await patchWait;
|
||||
await expect(row).toContainText(/disabled/i);
|
||||
// Re-read from the server rather than trusting the optimistic update.
|
||||
await page.reload();
|
||||
await expect(alerts.list.stateCell(ruleId)).toHaveText('Disabled');
|
||||
});
|
||||
```
|
||||
|
||||
### Locator priority
|
||||
`ownedRules` is a test-scoped seed: every rule it creates is deleted when the
|
||||
test finishes, so the spec owns its data and nothing leaks into the next one.
|
||||
|
||||
1. `getByTestId('...')` — preferred when the source exposes one. Stable, app-author-provided handle that survives copy-edits.
|
||||
2. `getByRole('button', { name: 'Submit' })`
|
||||
3. `getByLabel('Email')`
|
||||
4. `getByPlaceholder('...')`
|
||||
5. `getByText('...')`
|
||||
6. `locator('.ant-select')` — last resort (Ant Design dropdowns often have no semantic alternative)
|
||||
### Commits
|
||||
|
||||
Commit driver changes apart from specs, product testids and tests moved to
|
||||
another layer, so each commit can be reviewed on its own.
|
||||
[`tests/e2e/AGENTS.md`](../../../tests/e2e/AGENTS.md#commits) has the order.
|
||||
`pnpm typecheck`, `pnpm lint` and `pnpm fmt:check` gate the suite.
|
||||
|
||||
## Agents
|
||||
|
||||
Three Claude agents in `.claude/agents/` accelerate writing and maintaining E2E specs:
|
||||
|
||||
- **`playwright-test-planner`** — explores a feature in a real browser plus the local frontend source and writes a test plan as a scratch markdown file (under `tests/e2e/specs/`, which is gitignored — plans are working artifacts for the generator, not committed docs).
|
||||
- **`playwright-test-generator`** — converts a test plan into Playwright spec files under `tests/e2e/tests/<feature>/`. Drives each scenario through MCP browser tools and emits TC-NN-titled tests using the `authedPage` fixture and the API-seed pattern.
|
||||
- **`playwright-test-generator`** — converts a test plan into Playwright spec files under `tests/e2e/tests/<feature>/`. Drives each scenario through MCP browser tools and emits TC-NN-titled tests on the feature's driver, adding the driver methods and seeds the plan needs.
|
||||
- **`playwright-test-healer`** — runs failing specs, debugs them with snapshots / console / network introspection, and edits the spec to fix selector drift, timing, or state-leak issues.
|
||||
|
||||
The agents rely on the Playwright-test MCP server (`mcp__playwright-test__*` tools). Configure it in your Claude MCP settings; the permission allowlist lives in [.claude/settings.local.json](../../../.claude/settings.local.json).
|
||||
@@ -270,15 +265,15 @@ The agents rely on the Playwright-test MCP server (`mcp__playwright-test__*` too
|
||||
With the stack already up, from `tests/e2e/`:
|
||||
|
||||
```bash
|
||||
yarn test # headless, all projects
|
||||
pnpm test # headless, all projects
|
||||
```
|
||||
|
||||
### Running Specific Projects
|
||||
|
||||
```bash
|
||||
yarn test:chromium # chromium only
|
||||
yarn test:firefox
|
||||
yarn test:webkit
|
||||
pnpm test:chromium # chromium only
|
||||
pnpm test:firefox
|
||||
pnpm test:webkit
|
||||
```
|
||||
|
||||
### Running Specific Tests
|
||||
@@ -296,17 +291,17 @@ npx playwright test tests/alerts/history/ --project=chromium
|
||||
npx playwright test tests/alerts/page.spec.ts --project=chromium
|
||||
|
||||
# Single test by title grep
|
||||
npx playwright test --project=chromium -g "AL-01"
|
||||
npx playwright test --project=chromium -g "TC-01"
|
||||
```
|
||||
|
||||
### Iterative modes
|
||||
|
||||
```bash
|
||||
yarn test:ui # Playwright UI mode — watch + step through
|
||||
yarn test:headed # headed browser
|
||||
yarn test:debug # Playwright inspector, pause-on-breakpoint
|
||||
yarn codegen # record-and-replay locator generation
|
||||
yarn report # open the last HTML report (artifacts/html)
|
||||
pnpm test:ui # Playwright UI mode — watch + step through
|
||||
pnpm test:headed # headed browser
|
||||
pnpm test:debug # Playwright inspector, pause-on-breakpoint
|
||||
pnpm codegen # record-and-replay locator generation
|
||||
pnpm report # open the last HTML report (artifacts/html)
|
||||
```
|
||||
|
||||
### Staging fallback
|
||||
@@ -316,7 +311,7 @@ Point `SIGNOZ_E2E_BASE_URL` at a remote env via `.env` — no local backend brin
|
||||
```bash
|
||||
cd tests/e2e
|
||||
cp .env.example .env # fill SIGNOZ_E2E_USERNAME / PASSWORD
|
||||
yarn test:staging
|
||||
pnpm test:staging
|
||||
```
|
||||
|
||||
## How to configure different options for E2E tests?
|
||||
@@ -364,12 +359,14 @@ The same pytest flags integration tests expose work here, since E2E reuses the s
|
||||
- **Always use the `--reuse` flag** when setting up the E2E stack. `--with-web` adds a ~4 min frontend build on a cold start; later builds are incremental.
|
||||
- **Changed backend or frontend code? Re-run the setup command** — it passes `--rebuild`, swapping the SigNoz container for one built from your current sources while the rest of the stack stays up.
|
||||
- **Don't teardown before setup.** `--reuse` correctly handles partially-set-up state, so chaining teardown → setup wastes time.
|
||||
- **Prefer UI-driven flows.** Playwright captures BE requests in the trace; a parallel `fetch` probe is almost always redundant. Drop to `page.request.*` only when the UI can't reach what you need.
|
||||
- **Prefer UI-driven flows.** Playwright captures BE requests in the trace; a parallel `fetch` probe is almost always redundant. Seed through the kit, never with `page.request.*`.
|
||||
- **Use `page.waitForResponse` on UI clicks** to assert BE contracts — it still exercises the UI trigger path.
|
||||
- **Title every test `TC-NN <short description>`** — keeps the suite navigable and reportable.
|
||||
- **Split by resource, not by regression suite.** One spec per feature resource; cross-resource junction concerns (cascade-delete, linked-edit) get their own file.
|
||||
- **Use short descriptive resource names** (`alerts-list-rule`, `labels-rule`, `downtime-once`) — no timestamp disambiguation. Each test owns its resources and cleans up in `try/finally`.
|
||||
- **Name resources by what they are, plus the worker index** (`e2e-alert-list-w${workerIndex}-${Date.now()}`). Six workers share one stack, so assert only on names you seeded.
|
||||
- **Never commit `test.only`** — a pre-commit check or CI runs with `forbidOnly: true`.
|
||||
- **Prefer explicit waits over `page.waitForTimeout(ms)`.** `await expect(locator).toBeVisible()` is always better than `waitForTimeout(5000)`.
|
||||
- **Unique test names won't save you from shared-tenant state.** When two tests hit the same list page, either serialize (`describe.configure({ mode: 'serial' })`) or isolate cleanup religiously.
|
||||
- **Green locally, red on CI?** Run `STRESS=1 CI=1 pnpm test <path>` (4x CPU throttle, 2 workers, 2 retries) before filing a product bug.
|
||||
- **Commit drivers apart from specs.** One concern per commit; see [Commits](#commits).
|
||||
- **Artifacts go to `tests/e2e/artifacts/`** — HTML report at `artifacts/html`, traces at `artifacts/results/<test>/`. All gitignored; archive the dir in CI.
|
||||
|
||||
@@ -2,8 +2,6 @@ package implcloudprovider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sort"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/modules/cloudintegration"
|
||||
@@ -18,29 +16,14 @@ func NewAWSCloudProvider(defStore cloudintegrationtypes.ServiceDefinitionStore)
|
||||
return &awscloudprovider{serviceDefinitions: defStore}, nil
|
||||
}
|
||||
|
||||
// TODO: move URL construction logic to cloudintegrationtypes and add unit tests for it.
|
||||
func (provider *awscloudprovider) GetConnectionArtifact(ctx context.Context, account *cloudintegrationtypes.Account, req *cloudintegrationtypes.GetConnectionArtifactRequest) (*cloudintegrationtypes.ConnectionArtifact, error) {
|
||||
baseURL := fmt.Sprintf(cloudintegrationtypes.CloudFormationQuickCreateBaseURL.StringValue(), req.Config.AWS.DeploymentRegion)
|
||||
u, _ := url.Parse(baseURL)
|
||||
|
||||
q := u.Query()
|
||||
q.Set("region", req.Config.AWS.DeploymentRegion)
|
||||
u.Fragment = "/stacks/quickcreate"
|
||||
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
q = u.Query()
|
||||
q.Set("stackName", cloudintegrationtypes.AgentCloudFormationBaseStackName.StringValue())
|
||||
q.Set("templateURL", fmt.Sprintf(cloudintegrationtypes.AgentCloudFormationTemplateS3Path.StringValue(), req.Config.AgentVersion))
|
||||
q.Set("param_SigNozIntegrationAgentVersion", req.Config.AgentVersion)
|
||||
q.Set("param_SigNozApiUrl", req.Credentials.SigNozAPIURL)
|
||||
q.Set("param_SigNozApiKey", req.Credentials.SigNozAPIKey)
|
||||
q.Set("param_SigNozAccountId", account.ID.StringValue())
|
||||
q.Set("param_IngestionUrl", req.Credentials.IngestionURL)
|
||||
q.Set("param_IngestionKey", req.Credentials.IngestionKey)
|
||||
connectionArtifact, err := cloudintegrationtypes.NewAWSConnectionArtifact(account.ID, req.Config.AgentVersion, req.Credentials, req.Config.AWS.DeploymentRegion)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &cloudintegrationtypes.ConnectionArtifact{
|
||||
AWS: cloudintegrationtypes.NewAWSConnectionArtifact(u.String() + "?&" + q.Encode()), // this format is required by AWS
|
||||
AWS: connectionArtifact,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@
|
||||
"placeholder_slack_description": "Description",
|
||||
"placeholder_pager_description": "Description",
|
||||
"help_pager_client": "Shows up as event source in Pagerduty",
|
||||
"help_pager_client_url": "Shows up as event source link in Pagerduty",
|
||||
"help_pager_client_url": "Shows up as event source link in Pagerduty. Leave empty to link to this SigNoz instance",
|
||||
"help_pager_class": "The class/type of the event",
|
||||
"help_pager_details": "Specify a key-value format (must be a valid json)",
|
||||
"help_pager_group": "A cluster or grouping of sources",
|
||||
|
||||
@@ -169,7 +169,7 @@
|
||||
"placeholder_opsgenie_message": "Message",
|
||||
"placeholder_opsgenie_priority": "Priority",
|
||||
"help_pager_client": "Shows up as event source in Pagerduty",
|
||||
"help_pager_client_url": "Shows up as event source link in Pagerduty",
|
||||
"help_pager_client_url": "Shows up as event source link in Pagerduty. Leave empty to link to this SigNoz instance",
|
||||
"help_pager_class": "The class/type of the event",
|
||||
"help_pager_details": "Specify a key-value format (must be a valid json)",
|
||||
"help_pager_group": "A cluster or grouping of sources",
|
||||
|
||||
@@ -3936,7 +3936,7 @@ export interface CloudintegrationtypesAWSConnectionArtifactDTO {
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
connectionUrl: string;
|
||||
cliCommand: string;
|
||||
}
|
||||
|
||||
export interface CloudintegrationtypesAWSLogsCollectionStrategyDTO {
|
||||
@@ -4146,10 +4146,6 @@ export interface CloudintegrationtypesAzureConnectionArtifactDTO {
|
||||
* @type string
|
||||
*/
|
||||
cliCommand: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
cloudPowerShellCommand: string;
|
||||
}
|
||||
|
||||
export interface CloudintegrationtypesAzureLogsCollectionStrategyDTO {
|
||||
|
||||
@@ -2,6 +2,13 @@ import { act, render, screen } from '@testing-library/react';
|
||||
|
||||
import LabelColumn from './LabelColumn';
|
||||
|
||||
// The global CSS mock maps every class to undefined; keep the names so overflow is assertable.
|
||||
jest.mock('./LabelColumn.module.scss', () => ({
|
||||
labelColumn: 'labelColumn',
|
||||
overflowed: 'overflowed',
|
||||
shrinkable: 'shrinkable',
|
||||
}));
|
||||
|
||||
const BADGE_WIDTH = 60;
|
||||
|
||||
let resizeCallbacks: ResizeObserverCallback[] = [];
|
||||
@@ -77,6 +84,20 @@ describe('LabelColumn', () => {
|
||||
expect(screen.getByTestId('label-overflow-badge')).toHaveTextContent('+3');
|
||||
});
|
||||
|
||||
it('should hide the labels past the visible count', () => {
|
||||
const labels = ['env', 'service', 'region', 'team', 'owner', 'version'];
|
||||
|
||||
// 3 badges (180px) + overflow reserve (40px)
|
||||
mockLayout(220);
|
||||
renderWithProviders(<LabelColumn labels={labels} />);
|
||||
|
||||
const isHidden = (label: string): boolean =>
|
||||
screen.getByTestId(`label-tag-${label}`).closest('.overflowed') !== null;
|
||||
|
||||
expect(labels.filter(isHidden)).toStrictEqual(['team', 'owner', 'version']);
|
||||
expect(screen.getByTestId('label-overflow-badge')).toHaveTextContent('+3');
|
||||
});
|
||||
|
||||
it('should render label with value when value prop provided', () => {
|
||||
const labels = ['env'];
|
||||
const value = { env: 'production' };
|
||||
|
||||
@@ -10,7 +10,7 @@ interface AuthErrorProps {
|
||||
|
||||
function AuthError({ error }: AuthErrorProps): JSX.Element {
|
||||
return (
|
||||
<div className="auth-error-container">
|
||||
<div className="auth-error-container" data-testid="auth-error">
|
||||
<ErrorContent
|
||||
error={error}
|
||||
icon={<CircleAlert size={12} className="auth-error-icon" />}
|
||||
|
||||
@@ -512,6 +512,7 @@ export default function CeleryOverviewTable({
|
||||
allowClear
|
||||
/>
|
||||
<ResizeTable
|
||||
data-testid="mq-overview-table"
|
||||
className="celery-overview-table"
|
||||
pagination={paginationConfig}
|
||||
size="middle"
|
||||
|
||||
@@ -28,6 +28,7 @@ function CeleryTaskConfigOptions(): JSX.Element {
|
||||
Task Name
|
||||
</Typography.Text>
|
||||
<Select
|
||||
data-testid="celery-task-name-select"
|
||||
placeholder="Task Name"
|
||||
showSearch
|
||||
mode="multiple"
|
||||
|
||||
@@ -105,7 +105,10 @@ export default function CeleryTaskGraphGrid({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="celery-task-graph-grid-container">
|
||||
<div
|
||||
className="celery-task-graph-grid-container"
|
||||
data-testid="celery-graph-grid"
|
||||
>
|
||||
<div className="metric-based-graphs">
|
||||
<CardContainer className="row-card" isDarkMode={isDarkMode}>
|
||||
<div className="row-panel">
|
||||
|
||||
@@ -80,6 +80,7 @@ function CeleryTaskStateGraphConfig({
|
||||
{tabs.map((tab, index) => (
|
||||
<Col
|
||||
key={tab.key}
|
||||
data-testid={`celery-state-tab-${tab.key}`}
|
||||
onClick={(): void => handleTabClick(tab.key as CeleryTaskState)}
|
||||
className={`celery-task-states__tab ${
|
||||
tab.key === barState ? 'celery-task-states__tab--selected' : ''
|
||||
|
||||
@@ -251,6 +251,7 @@ function CustomTimePickerPopoverContent({
|
||||
<Button
|
||||
className={cx('data-time-live', isLiveLogsEnabled ? 'active' : '')}
|
||||
type="text"
|
||||
data-testid="time-picker-live"
|
||||
onClick={handleGoLive}
|
||||
>
|
||||
Live
|
||||
|
||||
@@ -88,6 +88,7 @@ function TimezoneItem({
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
data-testid={`timezone-item-${timezone.value}`}
|
||||
className={cx('timezone-picker__item', {
|
||||
selected: isSelected,
|
||||
'has-divider': timezone.hasDivider,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { Provider } from 'react-redux';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { message } from 'antd';
|
||||
import configureStore from 'redux-mock-store';
|
||||
import store from 'store';
|
||||
@@ -194,6 +195,23 @@ describe.each([
|
||||
});
|
||||
});
|
||||
|
||||
it('sends the chosen jsonl format and 30k row limit', async () => {
|
||||
renderWithStore(dataSource);
|
||||
await userEvent.click(screen.getByTestId(testId));
|
||||
await userEvent.click(screen.getByRole('radio', { name: 'jsonl' }));
|
||||
await userEvent.click(screen.getByRole('radio', { name: '30k' }));
|
||||
await userEvent.click(screen.getByText('Export'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockDownloadExportData).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
const callArgs = mockDownloadExportData.mock.calls[0][0];
|
||||
expect(callArgs.format).toBe(DownloadFormats.JSONL);
|
||||
expect(callArgs.body.compositeQuery.queries[0].spec.limit).toBe(
|
||||
DownloadRowCounts.THIRTY_K,
|
||||
);
|
||||
});
|
||||
|
||||
it('clears groupBy and having in the export payload', async () => {
|
||||
const mockQuery = createMockStagedQuery(dataSource);
|
||||
mockQuery.builder.queryData[0].groupBy = [
|
||||
|
||||
@@ -52,6 +52,7 @@ function DeleteMemberDialog({
|
||||
variant="solid"
|
||||
color="danger"
|
||||
onClick={onConfirm}
|
||||
testId="member-delete-confirm-btn"
|
||||
loading={isDeleting}
|
||||
prefix={<Trash2 size={12} />}
|
||||
>
|
||||
|
||||
@@ -624,6 +624,7 @@ function EditMemberDrawer({
|
||||
disabledTooltip={getDeleteTooltip(isRootUser, isSelf)}
|
||||
size="md"
|
||||
onClick={(): void => setShowDeleteConfirm(true)}
|
||||
testId="member-delete-btn"
|
||||
disabled={isRootUser || isSelf}
|
||||
variant="link"
|
||||
color="danger"
|
||||
@@ -637,6 +638,7 @@ function EditMemberDrawer({
|
||||
disabledTooltip={ROOT_USER_TOOLTIP}
|
||||
size="md"
|
||||
onClick={handleGenerateResetLink}
|
||||
testId="member-reset-link-btn"
|
||||
disabled={isRootUser}
|
||||
loading={isGeneratingLink || isLoadingTokenStatus}
|
||||
variant="link"
|
||||
@@ -674,6 +676,7 @@ function EditMemberDrawer({
|
||||
color="primary"
|
||||
disabled={!isDirty || isRootUser}
|
||||
onClick={handleSave}
|
||||
testId="member-save-btn"
|
||||
loading={isSaving}
|
||||
>
|
||||
{isSaving ? 'Saving...' : 'Save Member Details'}
|
||||
|
||||
@@ -42,7 +42,12 @@ function ResetLinkDialog({
|
||||
</p>
|
||||
<div className="reset-link-dialog__link-row">
|
||||
<div className="reset-link-dialog__link-text-wrap">
|
||||
<span className="reset-link-dialog__link-text">{resetLink}</span>
|
||||
<span
|
||||
className="reset-link-dialog__link-text"
|
||||
data-testid="reset-link-text"
|
||||
>
|
||||
{resetLink}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
size="md"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { MetricQueryRangeSuccessResponse } from 'types/api/metrics/getQueryRange';
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
import { fireEvent, render, screen, userEvent } from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import ExportMenu from '../ExportMenu';
|
||||
@@ -76,6 +76,17 @@ describe('ExportMenu', () => {
|
||||
expect(mockHandleExport).toHaveBeenCalledWith({ format: 'jsonl' });
|
||||
});
|
||||
|
||||
it('exports the picked jsonl format and closes the popover', async () => {
|
||||
renderMenu();
|
||||
await userEvent.click(screen.getByTestId(TEST_ID));
|
||||
await userEvent.click(screen.getByRole('radio', { name: 'jsonl' }));
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Export' }));
|
||||
|
||||
expect(mockHandleExport).toHaveBeenCalledTimes(1);
|
||||
expect(mockHandleExport).toHaveBeenCalledWith({ format: 'jsonl' });
|
||||
expect(screen.queryByText('FORMAT')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('disables the trigger while an export is in progress', () => {
|
||||
mockIsExporting = true;
|
||||
renderMenu();
|
||||
|
||||
@@ -18,6 +18,7 @@ function InputWithLabel({
|
||||
className,
|
||||
closeIcon,
|
||||
disabled,
|
||||
sanitize,
|
||||
}: {
|
||||
label: string;
|
||||
initialValue?: string | number | null;
|
||||
@@ -29,14 +30,17 @@ function InputWithLabel({
|
||||
className?: string;
|
||||
closeIcon?: React.ReactNode;
|
||||
disabled?: boolean;
|
||||
/** Rewrites the typed value before it is shown and reported. */
|
||||
sanitize?: (value: string) => string;
|
||||
}): JSX.Element {
|
||||
const [inputValue, setInputValue] = useState<string>(
|
||||
initialValue ? initialValue.toString() : '',
|
||||
);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
|
||||
setInputValue(e.target.value);
|
||||
onChange?.(e.target.value);
|
||||
const value = sanitize ? sanitize(e.target.value) : e.target.value;
|
||||
setInputValue(value);
|
||||
onChange?.(value);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -78,6 +82,7 @@ InputWithLabel.defaultProps = {
|
||||
initialValue: undefined,
|
||||
className: undefined,
|
||||
closeIcon: undefined,
|
||||
sanitize: undefined,
|
||||
};
|
||||
|
||||
export default InputWithLabel;
|
||||
|
||||
@@ -308,7 +308,11 @@ function LogDetailInner({
|
||||
placement="left"
|
||||
mouseLeaveDelay={0}
|
||||
>
|
||||
<div className="log-body" dangerouslySetInnerHTML={htmlBody} />
|
||||
<div
|
||||
className="log-body"
|
||||
data-testid="log-detail-body"
|
||||
dangerouslySetInnerHTML={htmlBody}
|
||||
/>
|
||||
</Tooltip>
|
||||
|
||||
<div className="log-overflow-shadow"> </div>
|
||||
|
||||
@@ -182,6 +182,7 @@ function ListLogView({
|
||||
return (
|
||||
<>
|
||||
<Container
|
||||
data-testid={`logs-list-row-${logData.id}`}
|
||||
$isActiveLog={isHighlighted || activeLog?.id === logData.id}
|
||||
$isDarkMode={isDarkMode}
|
||||
$logType={logType}
|
||||
|
||||
@@ -23,6 +23,7 @@ function LogLinesActionButtons({
|
||||
icon={<TextSelect size={14} />}
|
||||
className="show-context-btn"
|
||||
onClick={handleShowContext}
|
||||
data-testid="log-line-show-context"
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title="Copy Link">
|
||||
@@ -31,6 +32,7 @@ function LogLinesActionButtons({
|
||||
icon={<Link size={14} />}
|
||||
onClick={onLogCopy}
|
||||
className="copy-log-btn"
|
||||
data-testid="log-line-copy-link"
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -156,6 +156,7 @@ function RawLogView({
|
||||
|
||||
return (
|
||||
<RawLogViewContainer
|
||||
data-testid={`logs-raw-row-${data.id}`}
|
||||
onClick={handleClickExpand}
|
||||
wrap={false}
|
||||
align="middle"
|
||||
|
||||
@@ -182,6 +182,7 @@ function OptionsMenu({
|
||||
<div
|
||||
className="item"
|
||||
key={item.label}
|
||||
data-testid={`format-option-${item.key}`}
|
||||
onClick={(): void => handleMenuItemClick(item.key)}
|
||||
>
|
||||
<div className={cx('item-label')}>
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { READ_ONLY_TOOLTIP } from '../constants';
|
||||
import InsertVariableMenu from '../InsertVariableMenu';
|
||||
import type { EditorVariable } from '../types';
|
||||
|
||||
const VARIABLES: EditorVariable[] = [
|
||||
{ name: 'environment', badge: 'QUERY' },
|
||||
{ name: 'service', badge: 'CUSTOM' },
|
||||
{ name: 'service_version' },
|
||||
];
|
||||
|
||||
function renderMenu(disabled = false): jest.Mock {
|
||||
const onSelect = jest.fn();
|
||||
render(
|
||||
<InsertVariableMenu
|
||||
variables={VARIABLES}
|
||||
onSelect={onSelect}
|
||||
disabled={disabled}
|
||||
/>,
|
||||
);
|
||||
return onSelect;
|
||||
}
|
||||
|
||||
function rowNames(): string[] {
|
||||
return screen
|
||||
.queryAllByTestId(/^markdown-variable-/)
|
||||
.map((row) => row.getAttribute('data-testid') ?? '');
|
||||
}
|
||||
|
||||
describe('InsertVariableMenu', () => {
|
||||
it('narrows the rows to names matching the search', async () => {
|
||||
renderMenu();
|
||||
await userEvent.click(screen.getByTestId('markdown-insert-variable'));
|
||||
await screen.findByTestId('markdown-variable-environment');
|
||||
expect(rowNames()).toHaveLength(3);
|
||||
|
||||
await userEvent.type(screen.getByPlaceholderText('Search variables'), 'SERV');
|
||||
|
||||
await waitFor(() =>
|
||||
expect(rowNames()).toStrictEqual([
|
||||
'markdown-variable-service',
|
||||
'markdown-variable-service_version',
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('hands the clicked variable name to onSelect', async () => {
|
||||
const onSelect = renderMenu();
|
||||
await userEvent.click(screen.getByTestId('markdown-insert-variable'));
|
||||
await userEvent.click(await screen.findByTestId('markdown-variable-service'));
|
||||
|
||||
expect(onSelect).toHaveBeenCalledTimes(1);
|
||||
expect(onSelect).toHaveBeenCalledWith('service');
|
||||
});
|
||||
|
||||
it('stays closed and explains why when read-only', async () => {
|
||||
const onSelect = renderMenu(true);
|
||||
const trigger = screen.getByTestId('markdown-insert-variable');
|
||||
expect(trigger).toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
await userEvent.click(trigger);
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument();
|
||||
expect(rowNames()).toHaveLength(0);
|
||||
|
||||
await userEvent.hover(trigger);
|
||||
await expect(screen.findByRole('tooltip')).resolves.toHaveTextContent(
|
||||
READ_ONLY_TOOLTIP,
|
||||
);
|
||||
expect(onSelect).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { render, screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
|
||||
import CustomMultiSelect from '../CustomMultiSelect';
|
||||
@@ -678,6 +678,64 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(mockOnChange.mock.calls[0][0]).toStrictEqual(['backend']);
|
||||
});
|
||||
|
||||
it('UI-03c: clicking an option checkbox toggles it exactly once', async () => {
|
||||
renderWithVirtuoso(
|
||||
<CustomMultiSelect
|
||||
options={mockOptions}
|
||||
onChange={mockOnChange}
|
||||
value={['frontend']}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('combobox'));
|
||||
const backendRow = (await screen.findByText('Backend')).closest(
|
||||
'[role="option"]',
|
||||
) as HTMLElement;
|
||||
mockOnChange.mockClear();
|
||||
await user.click(within(backendRow).getByRole('checkbox'));
|
||||
|
||||
expect(mockOnChange).toHaveBeenCalledTimes(1);
|
||||
expect(mockOnChange.mock.calls[0][0]).toStrictEqual(['frontend', 'backend']);
|
||||
});
|
||||
|
||||
it('UI-03d: clicking an option label toggles it exactly once', async () => {
|
||||
renderWithVirtuoso(
|
||||
<CustomMultiSelect
|
||||
options={mockOptions}
|
||||
onChange={mockOnChange}
|
||||
value={['frontend']}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('combobox'));
|
||||
const backendLabel = await screen.findByText('Backend');
|
||||
mockOnChange.mockClear();
|
||||
await user.click(backendLabel);
|
||||
|
||||
expect(mockOnChange).toHaveBeenCalledTimes(1);
|
||||
expect(mockOnChange.mock.calls[0][0]).toStrictEqual(['frontend', 'backend']);
|
||||
});
|
||||
|
||||
it('UI-03e: clicking "Toggle" does not also toggle the wrapping checkbox', async () => {
|
||||
renderWithVirtuoso(
|
||||
<CustomMultiSelect
|
||||
options={mockOptions}
|
||||
onChange={mockOnChange}
|
||||
value={['frontend', 'backend']}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('combobox'));
|
||||
const backendRow = (await screen.findByText('Backend')).closest(
|
||||
'[role="option"]',
|
||||
) as HTMLElement;
|
||||
mockOnChange.mockClear();
|
||||
await user.click(within(backendRow).getByText('Toggle'));
|
||||
|
||||
expect(mockOnChange).toHaveBeenCalledTimes(1);
|
||||
expect(mockOnChange.mock.calls[0][0]).toStrictEqual(['frontend']);
|
||||
});
|
||||
|
||||
it('UI-04: Should display values with loading info at bottom', async () => {
|
||||
renderWithVirtuoso(
|
||||
<CustomMultiSelect options={mockOptions} onChange={mockOnChange} loading />,
|
||||
|
||||
@@ -112,6 +112,7 @@ function ListViewOrderBy({
|
||||
placeholder="Select a field"
|
||||
style={{ width: 200 }}
|
||||
options={selectOptions}
|
||||
data-testid="list-view-order-by"
|
||||
filterOption={(input, option): boolean =>
|
||||
(option?.value ?? '').toLowerCase().includes(input.trim().toLowerCase())
|
||||
}
|
||||
|
||||
17
frontend/src/components/OverflowBadges/ItemBadge.tsx
Normal file
17
frontend/src/components/OverflowBadges/ItemBadge.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
|
||||
interface ItemBadgeProps {
|
||||
children: ReactNode;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
function ItemBadge({ children, testId }: ItemBadgeProps): JSX.Element {
|
||||
return (
|
||||
<Badge textTransform="none" variant="solid" color="secondary" testId={testId}>
|
||||
{children}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
export default ItemBadge;
|
||||
@@ -0,0 +1,32 @@
|
||||
.badges {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-2);
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.overflow {
|
||||
flex-shrink: 0;
|
||||
--badge-max-width: none;
|
||||
}
|
||||
|
||||
/* Lays every badge out at its natural width, off-screen, to size the visible row. */
|
||||
.measure {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
display: flex;
|
||||
width: max-content;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.extraBadges {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--spacing-2);
|
||||
max-width: 320px;
|
||||
}
|
||||
75
frontend/src/components/OverflowBadges/OverflowBadges.tsx
Normal file
75
frontend/src/components/OverflowBadges/OverflowBadges.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import { type CSSProperties, useRef } from 'react';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
|
||||
import ItemBadge from './ItemBadge';
|
||||
import type { OverflowBadgeItem } from './types';
|
||||
import { useOverflowBadgesLayout } from './useOverflowBadgesLayout';
|
||||
|
||||
import styles from './OverflowBadges.module.scss';
|
||||
|
||||
interface OverflowBadgesProps {
|
||||
items: OverflowBadgeItem[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A row of badges: as many as fit the width inline, the rest revealed on hover
|
||||
* of a "+N" badge. A lone badge too wide to fit truncates instead.
|
||||
*/
|
||||
function OverflowBadges({ items }: OverflowBadgesProps): JSX.Element {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const measureRef = useRef<HTMLDivElement>(null);
|
||||
const { visibleCount, firstMaxWidth, isMeasuring } = useOverflowBadgesLayout(
|
||||
items,
|
||||
containerRef,
|
||||
measureRef,
|
||||
);
|
||||
|
||||
const visible = items.slice(0, visibleCount);
|
||||
const extra = items.slice(visibleCount);
|
||||
// The app sets `--badge-max-width` globally, which outranks Badge's `maxWidth` prop.
|
||||
const containerStyle =
|
||||
firstMaxWidth === undefined
|
||||
? undefined
|
||||
: ({ '--badge-max-width': `${firstMaxWidth}px` } as CSSProperties);
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className={styles.badges} style={containerStyle}>
|
||||
{visible.map(({ key, label }) => (
|
||||
<ItemBadge key={key} testId="overflow-badges-item">
|
||||
{label}
|
||||
</ItemBadge>
|
||||
))}
|
||||
{extra.length > 0 && (
|
||||
<Tooltip
|
||||
side="bottom"
|
||||
title={
|
||||
<div className={styles.extraBadges}>
|
||||
{extra.map(({ key, label }) => (
|
||||
<ItemBadge key={key}>{label}</ItemBadge>
|
||||
))}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{/* Stop the click so the "+N" badge doesn't trigger the row's click. */}
|
||||
<span
|
||||
role="presentation"
|
||||
className={styles.overflow}
|
||||
onClick={(e): void => e.stopPropagation()}
|
||||
>
|
||||
<ItemBadge testId="overflow-badges-more">+{extra.length}</ItemBadge>
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
{isMeasuring && (
|
||||
<div ref={measureRef} className={styles.measure} aria-hidden>
|
||||
{items.map(({ key, label }) => (
|
||||
<ItemBadge key={key}>{label}</ItemBadge>
|
||||
))}
|
||||
<ItemBadge>+{items.length}</ItemBadge>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default OverflowBadges;
|
||||
@@ -0,0 +1,74 @@
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import OverflowBadges from '../OverflowBadges';
|
||||
import { computeOverflowBadgesLayout } from '../utils';
|
||||
|
||||
const items = ['alpha', 'beta', 'gamma', 'delta'].map((label) => ({
|
||||
key: label,
|
||||
label,
|
||||
}));
|
||||
|
||||
describe('computeOverflowBadgesLayout', () => {
|
||||
it('fits as many badges as the width allows, keeping room for +N', () => {
|
||||
// 50 + 4 + 50 + 4 + 30 (+N) = 138 fits; a third badge would not.
|
||||
expect(
|
||||
computeOverflowBadgesLayout(140, 4, [50, 50, 50, 50], 30),
|
||||
).toStrictEqual({ visibleCount: 2 });
|
||||
});
|
||||
|
||||
it('shows every badge without +N when all fit', () => {
|
||||
expect(computeOverflowBadgesLayout(200, 4, [50, 50, 50], 30)).toStrictEqual({
|
||||
visibleCount: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('truncates the first badge when even it does not fit', () => {
|
||||
expect(computeOverflowBadgesLayout(100, 4, [300, 50], 30)).toStrictEqual({
|
||||
visibleCount: 1,
|
||||
firstMaxWidth: 66,
|
||||
});
|
||||
});
|
||||
|
||||
it('gives a lone too-wide badge the full width', () => {
|
||||
expect(computeOverflowBadgesLayout(100, 4, [300], 30)).toStrictEqual({
|
||||
visibleCount: 1,
|
||||
firstMaxWidth: 100,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns visibleCount 0 when badgeWidths is empty', () => {
|
||||
expect(computeOverflowBadgesLayout(100, 4, [], 30)).toStrictEqual({
|
||||
visibleCount: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('OverflowBadges', () => {
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('collapses the badges that do not fit into +N', () => {
|
||||
jest.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(160);
|
||||
jest
|
||||
.spyOn(Element.prototype, 'getBoundingClientRect')
|
||||
.mockReturnValue({ width: 50 } as DOMRect);
|
||||
|
||||
render(<OverflowBadges items={items} />);
|
||||
|
||||
expect(screen.getAllByTestId('overflow-badges-item')).toHaveLength(2);
|
||||
expect(screen.getByTestId('overflow-badges-more')).toHaveTextContent('+2');
|
||||
});
|
||||
|
||||
it('omits +N when every badge fits', () => {
|
||||
jest.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(1000);
|
||||
jest
|
||||
.spyOn(Element.prototype, 'getBoundingClientRect')
|
||||
.mockReturnValue({ width: 50 } as DOMRect);
|
||||
|
||||
render(<OverflowBadges items={items} />);
|
||||
|
||||
expect(screen.getAllByTestId('overflow-badges-item')).toHaveLength(4);
|
||||
expect(screen.queryByTestId('overflow-badges-more')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
20
frontend/src/components/OverflowBadges/types.ts
Normal file
20
frontend/src/components/OverflowBadges/types.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { Key, ReactNode } from 'react';
|
||||
|
||||
export interface OverflowBadgeItem {
|
||||
key: Key;
|
||||
label: ReactNode;
|
||||
}
|
||||
|
||||
export interface OverflowBadgesLayout {
|
||||
visibleCount: number;
|
||||
/** Set when even the first badge does not fit and must truncate. */
|
||||
firstMaxWidth?: number;
|
||||
}
|
||||
|
||||
export interface OverflowBadgesMeasurement {
|
||||
/** The items these widths were measured for. */
|
||||
itemsKey: string;
|
||||
badgeWidths: number[];
|
||||
overflowWidth: number;
|
||||
gap: number;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { type RefObject, useLayoutEffect, useMemo, useState } from 'react';
|
||||
|
||||
import type {
|
||||
OverflowBadgeItem,
|
||||
OverflowBadgesLayout,
|
||||
OverflowBadgesMeasurement,
|
||||
} from './types';
|
||||
import { computeOverflowBadgesLayout } from './utils';
|
||||
|
||||
/**
|
||||
* Fits the badges to the container's width, re-fitting on resize. Badge widths
|
||||
* are measured once per set of items, from a measuring row holding every badge
|
||||
* at its natural width followed by "+N", rendered only while `isMeasuring`.
|
||||
*/
|
||||
export function useOverflowBadgesLayout(
|
||||
items: OverflowBadgeItem[],
|
||||
containerRef: RefObject<HTMLElement>,
|
||||
measureRef: RefObject<HTMLElement>,
|
||||
): OverflowBadgesLayout & { isMeasuring: boolean } {
|
||||
const itemsKey = items.map((item) => String(item.key)).join('\u0000');
|
||||
const [measurement, setMeasurement] =
|
||||
useState<OverflowBadgesMeasurement | null>(null);
|
||||
const [available, setAvailable] = useState(0);
|
||||
const isMeasuring = items.length > 0 && measurement?.itemsKey !== itemsKey;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const container = containerRef.current;
|
||||
const measure = measureRef.current;
|
||||
if (!isMeasuring || !container || !measure) {
|
||||
return;
|
||||
}
|
||||
// Rounded up so sub-pixel widths never add up past the container.
|
||||
const badgeWidths = Array.from(measure.children, (el) =>
|
||||
Math.ceil(el.getBoundingClientRect().width),
|
||||
);
|
||||
const overflowWidth = badgeWidths.pop() ?? 0;
|
||||
setMeasurement({
|
||||
itemsKey,
|
||||
badgeWidths,
|
||||
overflowWidth,
|
||||
gap: parseFloat(getComputedStyle(container).columnGap) || 0,
|
||||
});
|
||||
}, [isMeasuring, itemsKey, containerRef, measureRef]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container) {
|
||||
return undefined;
|
||||
}
|
||||
const update = (): void => setAvailable(container.clientWidth);
|
||||
update();
|
||||
const observer = new ResizeObserver(update);
|
||||
observer.observe(container);
|
||||
return (): void => observer.disconnect();
|
||||
}, [containerRef]);
|
||||
|
||||
const layout = useMemo(
|
||||
(): OverflowBadgesLayout =>
|
||||
isMeasuring || !measurement || available === 0
|
||||
? { visibleCount: items.length }
|
||||
: computeOverflowBadgesLayout(
|
||||
available,
|
||||
measurement.gap,
|
||||
measurement.badgeWidths,
|
||||
measurement.overflowWidth,
|
||||
),
|
||||
[isMeasuring, measurement, available, items.length],
|
||||
);
|
||||
|
||||
return { ...layout, isMeasuring };
|
||||
}
|
||||
33
frontend/src/components/OverflowBadges/utils.ts
Normal file
33
frontend/src/components/OverflowBadges/utils.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import type { OverflowBadgesLayout } from './types';
|
||||
|
||||
/**
|
||||
* How many badges fit `available` px, keeping room for the "+N" badge while any
|
||||
* are left out. Always shows at least one, capped to truncate when too wide.
|
||||
*/
|
||||
export const computeOverflowBadgesLayout = (
|
||||
available: number,
|
||||
gap: number,
|
||||
badgeWidths: number[],
|
||||
overflowWidth: number,
|
||||
): OverflowBadgesLayout => {
|
||||
if (badgeWidths.length === 0) {
|
||||
return { visibleCount: 0 };
|
||||
}
|
||||
|
||||
let used = 0;
|
||||
let visibleCount = 0;
|
||||
for (let i = 0; i < badgeWidths.length; i++) {
|
||||
const next = used + (i > 0 ? gap : 0) + badgeWidths[i];
|
||||
const reserve = i < badgeWidths.length - 1 ? gap + overflowWidth : 0;
|
||||
if (next + reserve > available) {
|
||||
break;
|
||||
}
|
||||
used = next;
|
||||
visibleCount++;
|
||||
}
|
||||
if (visibleCount > 0) {
|
||||
return { visibleCount };
|
||||
}
|
||||
const reserve = badgeWidths.length > 1 ? gap + overflowWidth : 0;
|
||||
return { visibleCount: 1, firstMaxWidth: Math.max(available - reserve, 0) };
|
||||
};
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
RAW_QUERY_FIELDS,
|
||||
resolveQueryBuilderFields,
|
||||
} from '../../queryBuilderFields.utils';
|
||||
import { parseLimit, sanitizeLimit } from '../../utils';
|
||||
|
||||
import BucketOptions from './BucketOptions/BucketOptions';
|
||||
import HavingFilter from './HavingFilter/HavingFilter';
|
||||
@@ -278,7 +279,7 @@ function QueryAddOns({
|
||||
|
||||
const handleChangeLimit = useCallback(
|
||||
(value: string) => {
|
||||
handleChangeQueryData('limit', Number(value) || null);
|
||||
handleChangeQueryData('limit', parseLimit(value));
|
||||
},
|
||||
[handleChangeQueryData],
|
||||
);
|
||||
@@ -374,6 +375,7 @@ function QueryAddOns({
|
||||
label="Limit"
|
||||
type="number"
|
||||
onChange={handleChangeLimit}
|
||||
sanitize={sanitizeLimit}
|
||||
initialValue={query?.limit ?? undefined}
|
||||
placeholder={placeholderOf(QueryBuilderField.Limit)}
|
||||
onClose={(): void => handleRemoveView(QueryBuilderField.Limit)}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
/* eslint-disable @typescript-eslint/explicit-function-return-type */
|
||||
import { jest } from '@jest/globals';
|
||||
import { fireEvent, waitFor } from '@testing-library/react';
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import {
|
||||
Having,
|
||||
@@ -22,6 +25,8 @@ import {
|
||||
import '@testing-library/jest-dom';
|
||||
|
||||
import { QueryBuilderV2 } from '../../QueryBuilderV2';
|
||||
import { QueryBuilderV2Provider } from '../../QueryBuilderV2Context';
|
||||
import { QueryV2 } from '../QueryV2';
|
||||
|
||||
// Local mocks for domain-specific heavy child components
|
||||
jest.mock(
|
||||
@@ -53,6 +58,15 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
let baseQBContext: QueryBuilderContextType;
|
||||
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.get(`${ENVIRONMENT.baseURL}/api/v1/fields/keys`, (_req, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({ status: 'success', data: { complete: true, keys: {} } }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const mockCloneQuery = jest.fn() as jest.MockedFunction<
|
||||
(type: string, q: IBuilderQuery) => void
|
||||
>;
|
||||
@@ -235,6 +249,70 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('query actions menu', () => {
|
||||
const openQueryActions = async (): Promise<void> => {
|
||||
await userEvent.click(screen.getAllByTestId('query-actions')[0]);
|
||||
};
|
||||
|
||||
it('Clone calls cloneQuery with the query', async () => {
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
await openQueryActions();
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('query-actions-item-clone-query'),
|
||||
);
|
||||
|
||||
expect(baseQBContext.cloneQuery).toHaveBeenCalledTimes(1);
|
||||
expect(baseQBContext.cloneQuery).toHaveBeenCalledWith(
|
||||
'query',
|
||||
expect.objectContaining({ queryName: 'A' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('hides Delete when there is a single query', async () => {
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
await openQueryActions();
|
||||
await screen.findByTestId('query-actions-item-clone-query');
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('query-actions-item-delete-query'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows Delete with more than one query and deletes on click', async () => {
|
||||
const [queryA] = (baseQBContext.currentQuery as Query).builder.queryData;
|
||||
const handleDeleteQuery = jest.fn();
|
||||
mockedUseQueryOperations.mockReturnValue({
|
||||
...mockedUseQueryOperations({} as Parameters<UseQueryOperations>[0]),
|
||||
handleDeleteQuery,
|
||||
});
|
||||
|
||||
render(
|
||||
<QueryBuilderV2Provider>
|
||||
<QueryV2
|
||||
index={0}
|
||||
query={queryA}
|
||||
version="v4"
|
||||
isAvailableToDisable={false}
|
||||
isMultiQueryAllowed
|
||||
queriesCount={2}
|
||||
onSignalSourceChange={jest.fn()}
|
||||
signalSourceChangeEnabled={false}
|
||||
savePreviousQuery={false}
|
||||
/>
|
||||
</QueryBuilderV2Provider>,
|
||||
);
|
||||
|
||||
await openQueryActions();
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('query-actions-item-delete-query'),
|
||||
);
|
||||
|
||||
expect(handleDeleteQuery).toHaveBeenCalledTimes(1);
|
||||
}, 15000);
|
||||
});
|
||||
|
||||
it('fx button is disabled when functions already exist', () => {
|
||||
const currentQueryBase = baseQBContext.currentQuery as Query;
|
||||
const supersetQueryBase = baseQBContext.supersetQuery as Query;
|
||||
|
||||
@@ -169,8 +169,15 @@ describe('QueryAddOns', () => {
|
||||
expect(screen.getByTestId('limit-content')).toBeInTheDocument();
|
||||
expect(input.value).toBe('5');
|
||||
|
||||
fireEvent.change(input, { target: { value: '10' } });
|
||||
expect(mockHandleChangeQueryData).toHaveBeenCalledWith('limit', 10);
|
||||
const user = userEvent.setup();
|
||||
await user.clear(input);
|
||||
await user.type(input, '10');
|
||||
expect(mockHandleChangeQueryData).toHaveBeenLastCalledWith('limit', 10);
|
||||
|
||||
await user.clear(input);
|
||||
await user.type(input, '-5');
|
||||
expect(input.value).toBe('5');
|
||||
expect(mockHandleChangeQueryData).toHaveBeenLastCalledWith('limit', 5);
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
@@ -12,10 +12,62 @@ import {
|
||||
convertExpressionToFilters,
|
||||
convertFiltersToExpression,
|
||||
convertFiltersToExpressionWithExistingQuery,
|
||||
convertHavingToExpression,
|
||||
formatValueForExpression,
|
||||
parseLimit,
|
||||
removeKeysFromExpression,
|
||||
sanitizeLimit,
|
||||
} from '../utils';
|
||||
|
||||
describe('convertHavingToExpression', () => {
|
||||
it.each([
|
||||
['COUNT()', 'count() > 5'],
|
||||
['COUNT_DISTINCT(service.name)', 'count_distinct(service.name) > 5'],
|
||||
['P99(duration_nano)', 'p99(duration_nano) > 5'],
|
||||
['SUM(http.Request.Size)', 'sum(http.Request.Size) > 5'],
|
||||
['count()', 'count() > 5'],
|
||||
])('references %s by its lower-case function', (columnName, expected) => {
|
||||
expect(
|
||||
convertHavingToExpression([{ columnName, op: '>', value: 5 }]),
|
||||
).toStrictEqual({ expression: expected });
|
||||
});
|
||||
|
||||
it('joins several conditions and formats list values', () => {
|
||||
expect(
|
||||
convertHavingToExpression([
|
||||
{ columnName: 'COUNT()', op: '>', value: 5 },
|
||||
{ columnName: 'COUNT()', op: 'NOT IN', value: [1, 2] },
|
||||
]),
|
||||
).toStrictEqual({ expression: 'count() > 5 AND count() NOT IN [1, 2]' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeLimit', () => {
|
||||
it.each([
|
||||
['10', '10'],
|
||||
['-10', '10'],
|
||||
['2.5', '25'],
|
||||
['1e3', '13'],
|
||||
['', ''],
|
||||
])('sanitizes %j to %j', (value, expected) => {
|
||||
expect(sanitizeLimit(value)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseLimit', () => {
|
||||
it.each([
|
||||
['10', 10],
|
||||
['1', 1],
|
||||
['', null],
|
||||
['0', null],
|
||||
['-5', null],
|
||||
['2.5', null],
|
||||
['abc', null],
|
||||
])('parses %j as %j', (value, expected) => {
|
||||
expect(parseLimit(value)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertFiltersToExpression', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
@@ -840,6 +840,16 @@ export const appendAndClause = (
|
||||
return hasTopLevelOr ? `(${base}) AND ${clause}` : `${base} AND ${clause}`;
|
||||
};
|
||||
|
||||
/** Strips everything but digits, so a limit input can't hold a sign or decimal. */
|
||||
export const sanitizeLimit = (value: string): string =>
|
||||
value.replace(/\D/g, '');
|
||||
|
||||
/** A query or formula limit: a positive integer, otherwise none. */
|
||||
export const parseLimit = (value: string): number | null => {
|
||||
const limit = Number(value);
|
||||
return Number.isInteger(limit) && limit > 0 ? limit : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert old having format to new having format
|
||||
* @param having - Array of old having objects with columnName, op, and value
|
||||
@@ -871,7 +881,14 @@ export const convertHavingToExpression = (
|
||||
formattedValue = String(value);
|
||||
}
|
||||
|
||||
return `${columnName} ${op} ${formattedValue}`;
|
||||
// The old having filter upper-cased the function (`COUNT()`); v5 only
|
||||
// resolves the aggregation's own lower-case expression.
|
||||
const reference = columnName.replace(
|
||||
/^\s*([A-Za-z_]\w*)\(/,
|
||||
(_, fn: string) => `${fn.toLowerCase()}(`,
|
||||
);
|
||||
|
||||
return `${reference} ${op} ${formattedValue}`;
|
||||
})
|
||||
.filter((expression) => expression !== ''); // Remove empty expressions
|
||||
|
||||
|
||||
@@ -183,7 +183,11 @@ export default function CheckboxFilterV2(
|
||||
wasSearchShown.current = isSearchShown;
|
||||
|
||||
return (
|
||||
<div className={styles.checkboxFilter} data-testid="checkbox-filter-v2">
|
||||
<div
|
||||
className={styles.checkboxFilter}
|
||||
data-testid="checkbox-filter-v2"
|
||||
data-filter-key={filter.attributeKey.key}
|
||||
>
|
||||
<CheckboxFilterV2Header
|
||||
title={filter.title}
|
||||
isOpen={isOpen}
|
||||
|
||||
@@ -22,7 +22,9 @@ function KeyCreatedPhase({
|
||||
<div className="add-key-modal__field">
|
||||
<span className="add-key-modal__label">Key</span>
|
||||
<div className="add-key-modal__key-display">
|
||||
<span className="add-key-modal__key-text">{createdKey.key}</span>
|
||||
<span className="add-key-modal__key-text" data-testid="created-key-value">
|
||||
{createdKey.key}
|
||||
</span>
|
||||
<Button
|
||||
size="md"
|
||||
variant="link"
|
||||
|
||||
@@ -61,6 +61,7 @@ export function RevokeKeyFooter({
|
||||
color="danger"
|
||||
loading={isRevoking}
|
||||
onClick={onConfirm}
|
||||
testId="revoke-key-confirm-btn"
|
||||
prefix={<Trash2 size={12} />}
|
||||
>
|
||||
Revoke Key
|
||||
|
||||
@@ -384,6 +384,7 @@ function ServiceAccountDrawer({
|
||||
void setIsDeleteOpen(true);
|
||||
}}
|
||||
prefix={<Trash2 size={12} />}
|
||||
testId="sa-delete-btn"
|
||||
>
|
||||
Delete Service Account
|
||||
</AuthZButton>
|
||||
@@ -409,6 +410,7 @@ function ServiceAccountDrawer({
|
||||
loading={isSaving}
|
||||
disabled={!isDirty}
|
||||
onClick={handleSave}
|
||||
testId="sa-save-btn"
|
||||
>
|
||||
Save Changes
|
||||
</AuthZButton>
|
||||
@@ -437,6 +439,7 @@ function ServiceAccountDrawer({
|
||||
type="single"
|
||||
value={activeTab}
|
||||
size="sm"
|
||||
testId="sa-tab"
|
||||
onChange={(val: string): void => {
|
||||
if (val) {
|
||||
void setActiveTab(val as ServiceAccountDrawerTab);
|
||||
@@ -478,6 +481,7 @@ function ServiceAccountDrawer({
|
||||
void setIsAddKeyOpen(true);
|
||||
}}
|
||||
prefix={<Plus size={12} />}
|
||||
testId="sa-add-key-btn"
|
||||
>
|
||||
Add Key
|
||||
</AuthZButton>
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
TouchEvent as ReactTouchEvent,
|
||||
} from 'react';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { flushSync } from 'react-dom';
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
@@ -31,7 +32,7 @@ type TanStackHeaderRowProps<TData = unknown> = {
|
||||
onRemoveColumn?: (columnId: string) => void;
|
||||
orderBy?: SortState | null;
|
||||
onSort?: (sort: SortState | null) => void;
|
||||
/** Last column cannot be resized */
|
||||
/** The fill column and any after it cannot be resized */
|
||||
isLastColumn?: boolean;
|
||||
};
|
||||
|
||||
@@ -89,6 +90,19 @@ function TanStackHeaderRow<TData>({
|
||||
): void => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// TanStack starts the drag from the configured size, which an auto or
|
||||
// redistributed column does not render at.
|
||||
const renderedWidth = Math.round(
|
||||
event.currentTarget.closest('th')?.getBoundingClientRect().width ?? 0,
|
||||
);
|
||||
if (header && renderedWidth > 0 && renderedWidth !== header.getSize()) {
|
||||
flushSync(() => {
|
||||
header.getContext().table.setColumnSizing((sizing) => ({
|
||||
...sizing,
|
||||
[header.column.id]: renderedWidth,
|
||||
}));
|
||||
});
|
||||
}
|
||||
resizeHandler?.(event);
|
||||
};
|
||||
const {
|
||||
|
||||
@@ -53,7 +53,11 @@ import { useFlatItems } from './useFlatItems';
|
||||
import { useResetScroll } from './useResetScroll';
|
||||
import { useRowKeyData } from './useRowKeyData';
|
||||
import { useTableParams } from './useTableParams';
|
||||
import { buildPageSizeItems, buildTanstackColumnDef } from './utils';
|
||||
import {
|
||||
buildPageSizeItems,
|
||||
buildTanstackColumnDef,
|
||||
getFillColumnIndex,
|
||||
} from './utils';
|
||||
import { VirtuosoTableColGroup } from './VirtuosoTableColGroup';
|
||||
|
||||
import tableStyles from './TanStackTable.module.scss';
|
||||
@@ -428,6 +432,9 @@ function TanStackTableInner<TData, TItemKey = string>(
|
||||
);
|
||||
|
||||
const tableHeader = useCallback(() => {
|
||||
const fillColumnIndex = getFillColumnIndex(
|
||||
flatHeaders.map((header) => columnsById.get(header.id)),
|
||||
);
|
||||
return (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
@@ -453,7 +460,7 @@ function TanStackTableInner<TData, TItemKey = string>(
|
||||
canRemoveColumn={canRemoveColumn}
|
||||
orderBy={orderBy}
|
||||
onSort={setOrderBy}
|
||||
isLastColumn={index === flatHeaders.length - 1}
|
||||
isLastColumn={index >= fillColumnIndex}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Table } from '@tanstack/react-table';
|
||||
|
||||
import type { TableColumnDef } from './types';
|
||||
import { getColumnWidthStyle } from './utils';
|
||||
import { getColumnWidthStyle, getFillColumnIndex } from './utils';
|
||||
|
||||
export function VirtuosoTableColGroup<TData>({
|
||||
columns,
|
||||
@@ -13,6 +13,9 @@ export function VirtuosoTableColGroup<TData>({
|
||||
const visibleTanstackColumns = table.getVisibleFlatColumns();
|
||||
const columnDefsById = new Map(columns.map((c) => [c.id, c]));
|
||||
const columnSizing = table.getState().columnSizing;
|
||||
const fillColumnIndex = getFillColumnIndex(
|
||||
visibleTanstackColumns.map((c) => columnDefsById.get(c.id)),
|
||||
);
|
||||
|
||||
return (
|
||||
<colgroup>
|
||||
@@ -22,7 +25,7 @@ export function VirtuosoTableColGroup<TData>({
|
||||
return <col key={tanstackCol.id} />;
|
||||
}
|
||||
const persistedWidth = columnSizing[tanstackCol.id];
|
||||
const isLastColumn = index === visibleTanstackColumns.length - 1;
|
||||
const isLastColumn = index === fillColumnIndex;
|
||||
return (
|
||||
<col
|
||||
key={tanstackCol.id}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { screen } from '@testing-library/react';
|
||||
|
||||
import type { TableColumnDef } from '../types';
|
||||
import { defaultColumns, renderTanStackTable, type TestRow } from './testUtils';
|
||||
|
||||
jest.mock('hooks/useDarkMode', () => ({
|
||||
useIsDarkMode: (): boolean => false,
|
||||
}));
|
||||
|
||||
const actionsColumn: TableColumnDef<TestRow> = {
|
||||
id: 'actions',
|
||||
header: 'Actions',
|
||||
cell: (): string => 'act',
|
||||
width: { fixed: '96px', passLastColumnFill: true },
|
||||
};
|
||||
|
||||
const colWidths = (container: HTMLElement): string[] =>
|
||||
Array.from(container.querySelectorAll('colgroup col')).map(
|
||||
(col) => (col as HTMLElement).style.width,
|
||||
);
|
||||
|
||||
const isResizable = (headerText: string): boolean =>
|
||||
Boolean(
|
||||
screen
|
||||
.getByText(headerText)
|
||||
.closest('th')
|
||||
?.querySelector('[title="Drag to resize column"]'),
|
||||
);
|
||||
|
||||
describe('TanStackTable column fill', () => {
|
||||
it('fills and locks the last column by default', () => {
|
||||
const { container } = renderTanStackTable();
|
||||
|
||||
expect(colWidths(container).at(-1)).toBe('100%');
|
||||
expect(isResizable('Name')).toBe(true);
|
||||
expect(isResizable('Value')).toBe(false);
|
||||
});
|
||||
|
||||
it('hands the fill to the previous column when the last passes it on', () => {
|
||||
const { container } = renderTanStackTable({
|
||||
props: { columns: [...defaultColumns, actionsColumn] },
|
||||
});
|
||||
|
||||
const widths = colWidths(container);
|
||||
expect(widths.at(-2)).toBe('100%');
|
||||
expect(widths.at(-1)).toBe('96px');
|
||||
expect(isResizable('Name')).toBe(true);
|
||||
expect(isResizable('Value')).toBe(false);
|
||||
expect(isResizable('Actions')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -263,6 +263,33 @@ describe('useColumnStore', () => {
|
||||
expect(result.current).toBe(firstSnapshot);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['only hiddenColumnIds', { hiddenColumnIds: ['persisted'] }],
|
||||
['only columnOrder', { columnOrder: ['a', 'b'] }],
|
||||
['an empty object', {}],
|
||||
['a wrong-typed hiddenColumnIds', { hiddenColumnIds: 'nope' }],
|
||||
])(
|
||||
'normalises a persisted value carrying %s so selectors never yield undefined',
|
||||
(_label, stored) => {
|
||||
localStorage.setItem(
|
||||
'@signoz/table-columns/test-table',
|
||||
JSON.stringify(stored),
|
||||
);
|
||||
|
||||
act(() => {
|
||||
useColumnStore.getState().initializeFromDefaults(TEST_KEY, []);
|
||||
});
|
||||
|
||||
const hidden = renderHook(() => useHiddenColumnIds(TEST_KEY));
|
||||
const order = renderHook(() => useColumnOrder(TEST_KEY));
|
||||
const sizing = renderHook(() => useColumnSizing(TEST_KEY));
|
||||
|
||||
expect(Array.isArray(hidden.result.current)).toBe(true);
|
||||
expect(Array.isArray(order.result.current)).toBe(true);
|
||||
expect(typeof sizing.result.current).toBe('object');
|
||||
},
|
||||
);
|
||||
|
||||
it('useColumnSizing returns sizing', () => {
|
||||
act(() => {
|
||||
useColumnStore.getState().initializeFromDefaults(TEST_KEY, []);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { TableColumnDef } from '../types';
|
||||
import { getFillColumnIndex } from '../utils';
|
||||
|
||||
const column = (
|
||||
id: string,
|
||||
width?: TableColumnDef<unknown>['width'],
|
||||
): TableColumnDef<unknown> => ({
|
||||
id,
|
||||
header: id,
|
||||
cell: (): null => null,
|
||||
width,
|
||||
});
|
||||
|
||||
describe('getFillColumnIndex', () => {
|
||||
it('fills the last column by default', () => {
|
||||
expect(getFillColumnIndex([column('a'), column('b')])).toBe(1);
|
||||
});
|
||||
|
||||
it('fills the previous column when the last passes it on', () => {
|
||||
expect(
|
||||
getFillColumnIndex([
|
||||
column('a'),
|
||||
column('b'),
|
||||
column('actions', { fixed: '96px', passLastColumnFill: true }),
|
||||
]),
|
||||
).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -74,6 +74,8 @@ export type TableColumnDef<
|
||||
default?: number | string;
|
||||
max?: number | string;
|
||||
ignoreLastColumnFill?: boolean;
|
||||
/** When last, hand the fill to the previous column instead of taking it. */
|
||||
passLastColumnFill?: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -66,7 +66,19 @@ const loadTableFromStorage = (tableKey: string): ColumnState | null => {
|
||||
return cached.parsed;
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(raw) as ColumnState;
|
||||
// Selectors read these fields directly, so a value persisted under an older
|
||||
// schema must be filled in rather than handed to callers as `undefined`.
|
||||
const stored = JSON.parse(raw) as Partial<ColumnState> | null;
|
||||
const parsed: ColumnState = {
|
||||
hiddenColumnIds: Array.isArray(stored?.hiddenColumnIds)
|
||||
? stored.hiddenColumnIds
|
||||
: [],
|
||||
columnOrder: Array.isArray(stored?.columnOrder) ? stored.columnOrder : [],
|
||||
columnSizing:
|
||||
stored?.columnSizing && typeof stored.columnSizing === 'object'
|
||||
? stored.columnSizing
|
||||
: {},
|
||||
};
|
||||
persistedTableCache.set(tableKey, { raw, parsed });
|
||||
return parsed;
|
||||
} catch {
|
||||
|
||||
@@ -63,6 +63,19 @@ export const getColumnWidthStyle = <TData>(
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Index of the column that fills spare width: the last one, or the one before
|
||||
* it when the last sets `width.passLastColumnFill`.
|
||||
*/
|
||||
export const getFillColumnIndex = <TData>(
|
||||
columns: (TableColumnDef<TData> | undefined)[],
|
||||
): number => {
|
||||
const lastIndex = columns.length - 1;
|
||||
return columns[lastIndex]?.width?.passLastColumnFill
|
||||
? lastIndex - 1
|
||||
: lastIndex;
|
||||
};
|
||||
|
||||
const isSkeletonRow = (row: unknown): boolean => {
|
||||
const r = row as Record<string, unknown>;
|
||||
return typeof r?.id === 'string' && r.id.startsWith('skeleton-');
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { timeItems } from 'constants/timePreference';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import TimePreference from '../index';
|
||||
|
||||
describe('TimePreferenceDropDown', () => {
|
||||
it('calls setSelectedTime with the clicked item', async () => {
|
||||
const setSelectedTime = jest.fn();
|
||||
render(
|
||||
<TimePreference
|
||||
selectedTime={timeItems[0]}
|
||||
setSelectedTime={setSelectedTime}
|
||||
/>,
|
||||
);
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /Global Time/ }));
|
||||
await userEvent.click(
|
||||
await screen.findByRole('menuitem', { name: 'Last 15 min' }),
|
||||
);
|
||||
|
||||
expect(setSelectedTime).toHaveBeenCalledTimes(1);
|
||||
expect(setSelectedTime).toHaveBeenCalledWith({
|
||||
name: 'Last 15 min',
|
||||
enum: 'LAST_15_MIN',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from 'api/ai-assistant/chat';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { buildExplorerNavigationUrl } from 'utils/buildExplorerNavigationUrl';
|
||||
import { openInNewTab } from 'utils/navigation';
|
||||
import {
|
||||
ArchiveRestore,
|
||||
@@ -47,6 +48,10 @@ import { AIAssistantEvents, SuggestedPromptCategory } from '../../events';
|
||||
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
|
||||
|
||||
import {
|
||||
getPanelTypeForRequestType,
|
||||
requestTypeFromActionQuery,
|
||||
} from './utils/getPanelTypeForRequestType';
|
||||
import { openSavedViewByKey } from './utils/openSavedView';
|
||||
import {
|
||||
isSavedViewOpenAction,
|
||||
@@ -333,6 +338,11 @@ function applyFilter(action: MessageActionDTO, deps: ApplyFilterDeps): void {
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Read before toUrlCompositeQuery, which drops the requestType envelope.
|
||||
const panelType = getPanelTypeForRequestType(
|
||||
requestTypeFromActionQuery(action.query),
|
||||
action.signal,
|
||||
);
|
||||
const normalized = withDerivedFilterExpressions(urlQuery as unknown as Query);
|
||||
// eslint-disable-next-line no-console
|
||||
console.log('[apply_filter] normalized', normalized);
|
||||
@@ -342,7 +352,9 @@ function applyFilter(action: MessageActionDTO, deps: ApplyFilterDeps): void {
|
||||
normalized.builder.queryData.forEach((q, i) => {
|
||||
deps.handleSetQueryData(i, q);
|
||||
});
|
||||
deps.redirectWithQueryBuilderData(normalized);
|
||||
deps.redirectWithQueryBuilderData(normalized, {
|
||||
[QueryParams.panelTypes]: panelType,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const base = explorerRouteForSignal(action.signal);
|
||||
@@ -353,8 +365,10 @@ function applyFilter(action: MessageActionDTO, deps: ApplyFilterDeps): void {
|
||||
}
|
||||
// eslint-disable-next-line no-console
|
||||
console.log('[apply_filter] off-page → navigate', base);
|
||||
const encoded = encodeURIComponent(JSON.stringify(normalized));
|
||||
navigate(`${base}?${QueryParams.compositeQuery}=${encoded}`);
|
||||
const url = buildExplorerNavigationUrl(base, normalized, {
|
||||
[QueryParams.panelTypes]: panelType,
|
||||
});
|
||||
navigate(url);
|
||||
}
|
||||
|
||||
/** Picks the right rollback API call for a given action kind. */
|
||||
@@ -613,6 +627,7 @@ export default function ActionsSection({
|
||||
disabled={isSuccess}
|
||||
loading={isLoading}
|
||||
aria-label={action.label}
|
||||
testId={`ai-action-chip-${action.kind}`}
|
||||
prefix={icon}
|
||||
>
|
||||
<span className={styles.chipLabel}>{action.label}</span>
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import { undoExecution } from 'api/ai-assistant/chat';
|
||||
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import {
|
||||
ApplyFilterSignalDTO,
|
||||
MessageActionKindDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { getCurrentLocation } from 'lib/router/navigation';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { QueryBuilderContextType } from 'types/common/queryBuilder';
|
||||
|
||||
import ActionsSection from '../ActionsSection';
|
||||
|
||||
jest.mock('api/ai-assistant/chat', () => ({
|
||||
undoExecution: jest.fn(),
|
||||
revertExecution: jest.fn(),
|
||||
restoreExecution: jest.fn(),
|
||||
}));
|
||||
jest.mock('api/common/logEvent', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn(),
|
||||
}));
|
||||
|
||||
const mockUndo = undoExecution as jest.MockedFunction<typeof undoExecution>;
|
||||
|
||||
const UNDO_ACTION = {
|
||||
kind: MessageActionKindDTO.undo,
|
||||
label: 'Undo change',
|
||||
actionMetadataId: 'exec-1',
|
||||
} as MessageActionDTO;
|
||||
|
||||
function renderUndoChip(): HTMLElement {
|
||||
render(<ActionsSection actions={[UNDO_ACTION]} messageId="m1" />);
|
||||
return screen.getByRole('button', { name: 'Undo change' });
|
||||
}
|
||||
|
||||
// Labels differ per test: auto-applied filters are deduped module-wide by label.
|
||||
function countByServiceAction(label: string): MessageActionDTO {
|
||||
return {
|
||||
kind: MessageActionKindDTO.apply_filter,
|
||||
label,
|
||||
signal: ApplyFilterSignalDTO.logs,
|
||||
query: {
|
||||
requestType: Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
compositeQuery: {
|
||||
queries: [
|
||||
{
|
||||
type: 'builder_query',
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: 'logs',
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
groupBy: [{ name: 'service.name' }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function currentPanelTypesParam(): string | null {
|
||||
return new URLSearchParams(getCurrentLocation().search).get(
|
||||
QueryParams.panelTypes,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ActionsSection rollback chip', () => {
|
||||
beforeEach(() => {
|
||||
mockUndo.mockReset();
|
||||
});
|
||||
|
||||
it('ignores clicks while the rollback is in flight', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockUndo.mockReturnValue(new Promise(() => {}));
|
||||
const chip = renderUndoChip();
|
||||
|
||||
await user.click(chip);
|
||||
await waitFor(() => expect(chip).toHaveAttribute('aria-busy', 'true'));
|
||||
await user.click(chip);
|
||||
|
||||
expect(mockUndo).toHaveBeenCalledTimes(1);
|
||||
expect(mockUndo).toHaveBeenCalledWith('exec-1');
|
||||
});
|
||||
|
||||
it('disables the chip after success and says why', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockUndo.mockResolvedValue({} as Awaited<ReturnType<typeof undoExecution>>);
|
||||
const chip = renderUndoChip();
|
||||
|
||||
await user.click(chip);
|
||||
await waitFor(() => expect(chip).toHaveAttribute('aria-disabled', 'true'));
|
||||
|
||||
await user.click(chip);
|
||||
expect(mockUndo).toHaveBeenCalledTimes(1);
|
||||
|
||||
// A click closes a Base UI tooltip until the pointer leaves the trigger.
|
||||
await user.unhover(chip);
|
||||
await user.hover(chip);
|
||||
await expect(
|
||||
screen.findByText('This action already ran'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the error text when the rollback fails', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockUndo.mockRejectedValue(new Error('Execution already reverted'));
|
||||
const chip = renderUndoChip();
|
||||
|
||||
await user.click(chip);
|
||||
await waitFor(() => expect(chip).not.toHaveAttribute('aria-busy', 'true'));
|
||||
expect(chip).not.toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
await user.unhover(chip);
|
||||
await user.hover(chip);
|
||||
await expect(
|
||||
screen.findByText('Execution already reverted'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ActionsSection apply_filter', () => {
|
||||
it('opens the explorer in the Table view when the chip is clicked from another page', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(
|
||||
<ActionsSection
|
||||
actions={[countByServiceAction('Open in Logs Explorer')]}
|
||||
messageId="message-1"
|
||||
/>,
|
||||
undefined,
|
||||
{ initialRoute: ROUTES.HOME },
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('ai-action-chip-apply_filter'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(getCurrentLocation().pathname).toBe(ROUTES.LOGS_EXPLORER),
|
||||
);
|
||||
expect(currentPanelTypesParam()).toBe(JSON.stringify(PANEL_TYPES.TABLE));
|
||||
});
|
||||
|
||||
it('switches the open explorer to the Table view when applied on it', async () => {
|
||||
const redirectWithQueryBuilderData = jest.fn() as jest.MockedFunction<
|
||||
QueryBuilderContextType['redirectWithQueryBuilderData']
|
||||
>;
|
||||
const handleSetQueryData = jest.fn() as jest.MockedFunction<
|
||||
QueryBuilderContextType['handleSetQueryData']
|
||||
>;
|
||||
render(
|
||||
<ActionsSection
|
||||
actions={[countByServiceAction('Apply on Logs Explorer')]}
|
||||
messageId="message-2"
|
||||
/>,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTES.LOGS_EXPLORER,
|
||||
queryBuilderOverrides: { redirectWithQueryBuilderData, handleSetQueryData },
|
||||
},
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(redirectWithQueryBuilderData).toHaveBeenCalledTimes(1),
|
||||
);
|
||||
expect(redirectWithQueryBuilderData).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ builder: expect.anything() }),
|
||||
{ [QueryParams.panelTypes]: PANEL_TYPES.TABLE },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { ApplyFilterSignalDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
|
||||
import {
|
||||
getPanelTypeForRequestType,
|
||||
requestTypeFromActionQuery,
|
||||
} from '../getPanelTypeForRequestType';
|
||||
|
||||
describe('getPanelTypeForRequestType', () => {
|
||||
it.each([
|
||||
[
|
||||
Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
ApplyFilterSignalDTO.logs,
|
||||
PANEL_TYPES.TABLE,
|
||||
],
|
||||
[
|
||||
Querybuildertypesv5RequestTypeDTO.time_series,
|
||||
ApplyFilterSignalDTO.logs,
|
||||
PANEL_TYPES.TIME_SERIES,
|
||||
],
|
||||
[
|
||||
Querybuildertypesv5RequestTypeDTO.raw,
|
||||
ApplyFilterSignalDTO.logs,
|
||||
PANEL_TYPES.LIST,
|
||||
],
|
||||
[
|
||||
Querybuildertypesv5RequestTypeDTO.trace,
|
||||
ApplyFilterSignalDTO.traces,
|
||||
PANEL_TYPES.TRACE,
|
||||
],
|
||||
[
|
||||
Querybuildertypesv5RequestTypeDTO.trace,
|
||||
ApplyFilterSignalDTO.logs,
|
||||
PANEL_TYPES.LIST,
|
||||
],
|
||||
[
|
||||
Querybuildertypesv5RequestTypeDTO.trace,
|
||||
ApplyFilterSignalDTO.metrics,
|
||||
PANEL_TYPES.LIST,
|
||||
],
|
||||
])('maps %s on the %s signal to the %s view', (requestType, signal, view) => {
|
||||
expect(getPanelTypeForRequestType(requestType, signal)).toBe(view);
|
||||
});
|
||||
|
||||
it.each([
|
||||
undefined,
|
||||
null,
|
||||
'',
|
||||
Querybuildertypesv5RequestTypeDTO.raw_stream,
|
||||
Querybuildertypesv5RequestTypeDTO.heatmap,
|
||||
'distribution',
|
||||
'nonsense',
|
||||
'toString',
|
||||
'constructor',
|
||||
42,
|
||||
{},
|
||||
])(
|
||||
'falls back to the List view for unmapped or invalid requestType (%p)',
|
||||
(value) => {
|
||||
expect(getPanelTypeForRequestType(value, ApplyFilterSignalDTO.traces)).toBe(
|
||||
PANEL_TYPES.LIST,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('requestTypeFromActionQuery', () => {
|
||||
it('reads the requestType envelope field and returns undefined when absent', () => {
|
||||
expect(
|
||||
requestTypeFromActionQuery({
|
||||
requestType: 'scalar',
|
||||
schemaVersion: 'v5',
|
||||
compositeQuery: { queries: [] },
|
||||
}),
|
||||
).toBe('scalar');
|
||||
expect(requestTypeFromActionQuery({})).toBeUndefined();
|
||||
expect(requestTypeFromActionQuery(null)).toBeUndefined();
|
||||
expect(requestTypeFromActionQuery(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('maps a grouped count() payload to the Table view', () => {
|
||||
const query = {
|
||||
requestType: 'scalar',
|
||||
schemaVersion: 'v5',
|
||||
compositeQuery: {
|
||||
queries: [
|
||||
{
|
||||
type: 'builder_query',
|
||||
spec: {
|
||||
signal: 'logs',
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
groupBy: [{ name: 'service.name' }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(
|
||||
getPanelTypeForRequestType(
|
||||
requestTypeFromActionQuery(query),
|
||||
ApplyFilterSignalDTO.logs,
|
||||
),
|
||||
).toBe(PANEL_TYPES.TABLE);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import {
|
||||
ApplyFilterSignalDTO,
|
||||
type MessageActionDTOQuery,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
|
||||
export function getPanelTypeForRequestType(
|
||||
requestType: unknown,
|
||||
signal: ApplyFilterSignalDTO,
|
||||
): PANEL_TYPES {
|
||||
switch (requestType) {
|
||||
case Querybuildertypesv5RequestTypeDTO.scalar:
|
||||
return PANEL_TYPES.TABLE;
|
||||
case Querybuildertypesv5RequestTypeDTO.time_series:
|
||||
return PANEL_TYPES.TIME_SERIES;
|
||||
case Querybuildertypesv5RequestTypeDTO.trace:
|
||||
return signal === ApplyFilterSignalDTO.traces
|
||||
? PANEL_TYPES.TRACE
|
||||
: PANEL_TYPES.LIST;
|
||||
default:
|
||||
return PANEL_TYPES.LIST;
|
||||
}
|
||||
}
|
||||
|
||||
export function requestTypeFromActionQuery(
|
||||
query: MessageActionDTOQuery | undefined,
|
||||
): unknown {
|
||||
return query?.requestType;
|
||||
}
|
||||
@@ -340,6 +340,7 @@ function AllErrors(): JSX.Element {
|
||||
render: (value, record): JSX.Element => (
|
||||
<Tooltip overlay={(): JSX.Element => value}>
|
||||
<AppLink
|
||||
data-testid="exception-row-link"
|
||||
to={`${ROUTES.ERROR_DETAIL}?groupId=${
|
||||
record.groupID
|
||||
}×tamp=${getNanoSeconds(record.lastSeen)}`}
|
||||
@@ -486,6 +487,7 @@ function AllErrors(): JSX.Element {
|
||||
|
||||
return (
|
||||
<ResizeTable
|
||||
data-testid="exceptions-table"
|
||||
columns={columns}
|
||||
tableLayout="fixed"
|
||||
dataSource={data?.payload as Exception[]}
|
||||
|
||||
@@ -161,7 +161,7 @@ function DomainDetails({
|
||||
<Divider type="vertical" />
|
||||
|
||||
{domainData?.domainName && (
|
||||
<Typography.Text className="title">
|
||||
<Typography.Text className="title" testId="domain-details-title">
|
||||
{domainData.domainName}
|
||||
</Typography.Text>
|
||||
)}
|
||||
@@ -214,6 +214,7 @@ function DomainDetails({
|
||||
background: 'var(--l1-background)',
|
||||
}}
|
||||
className="domain-detail-drawer"
|
||||
data-testid="domain-details-drawer"
|
||||
destroyOnClose
|
||||
closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
|
||||
>
|
||||
@@ -233,9 +234,21 @@ function DomainDetails({
|
||||
value={selectedView}
|
||||
size="md"
|
||||
items={[
|
||||
{ value: VIEW_TYPES.ALL_ENDPOINTS, label: 'All Endpoints' },
|
||||
{ value: VIEW_TYPES.ENDPOINT_STATS, label: 'Endpoint(s) Stats' },
|
||||
{ value: VIEW_TYPES.TOP_ERRORS, label: 'Top 10 Errors' },
|
||||
{
|
||||
value: VIEW_TYPES.ALL_ENDPOINTS,
|
||||
label: 'All Endpoints',
|
||||
testId: `domain-view-${VIEW_TYPES.ALL_ENDPOINTS}`,
|
||||
},
|
||||
{
|
||||
value: VIEW_TYPES.ENDPOINT_STATS,
|
||||
label: 'Endpoint(s) Stats',
|
||||
testId: `domain-view-${VIEW_TYPES.ENDPOINT_STATS}`,
|
||||
},
|
||||
{
|
||||
value: VIEW_TYPES.TOP_ERRORS,
|
||||
label: 'Top 10 Errors',
|
||||
testId: `domain-view-${VIEW_TYPES.TOP_ERRORS}`,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -176,6 +176,7 @@ function TopErrors({
|
||||
textPlacement="right"
|
||||
value={showStatusCodeErrors}
|
||||
onChange={setShowStatusCodeErrors}
|
||||
testId="top-errors-status-message-toggle"
|
||||
/>
|
||||
<span style={{ color: 'white', fontSize: '14px' }}>
|
||||
Status Message Exists
|
||||
@@ -186,7 +187,7 @@ function TopErrors({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="endpoints-table-container">
|
||||
<div className="endpoints-table-container" data-testid="top-errors-table">
|
||||
<div className="endpoints-table-header">
|
||||
{showStatusCodeErrors ? 'Errors with Status Message' : 'All Errors'}{' '}
|
||||
<Tooltip
|
||||
|
||||
@@ -64,7 +64,10 @@ function DependentServices({
|
||||
|
||||
return (
|
||||
<div className="top-services-content">
|
||||
<div className="dependent-services-container">
|
||||
<div
|
||||
className="dependent-services-container"
|
||||
data-testid="dependent-services-table"
|
||||
>
|
||||
<Table
|
||||
loading={isLoading || isRefetching}
|
||||
dataSource={dependentServicesData || []}
|
||||
|
||||
@@ -86,7 +86,7 @@ function DomainMetrics({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="domain-detail-drawer__endpoint">
|
||||
<div className="domain-detail-drawer__endpoint" data-testid="domain-metrics">
|
||||
<div className="domain-details-grid">
|
||||
<div className="labels-row">
|
||||
<Typography.Text color="muted" className="domain-details-metadata-label">
|
||||
@@ -103,7 +103,7 @@ function DomainMetrics({
|
||||
</Typography.Text>
|
||||
</div>
|
||||
|
||||
<div className="values-row">
|
||||
<div className="values-row" data-testid="domain-metrics-values">
|
||||
<Typography.Text className="domain-details-metadata-value">
|
||||
{isLoading || isRefetching ? (
|
||||
<Skeleton.Button active size="small" />
|
||||
|
||||
@@ -35,7 +35,10 @@ function StatusCodeTable({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="status-code-table-container">
|
||||
<div
|
||||
className="status-code-table-container"
|
||||
data-testid="endpoint-status-code-table"
|
||||
>
|
||||
<Table
|
||||
loading={isLoading || isRefetching}
|
||||
dataSource={statusCodeData || []}
|
||||
|
||||
@@ -166,7 +166,10 @@ function DomainList(): JSX.Element {
|
||||
!isFetching &&
|
||||
!isLoading &&
|
||||
formattedDataForTable.length === 0 && (
|
||||
<div className="no-filtered-domains-message-container">
|
||||
<div
|
||||
className="no-filtered-domains-message-container"
|
||||
data-testid="api-monitoring-empty-state"
|
||||
>
|
||||
<div className="no-filtered-domains-message-content">
|
||||
<img
|
||||
src={emptyStateUrl}
|
||||
@@ -200,6 +203,7 @@ function DomainList(): JSX.Element {
|
||||
{(isFetching || isLoading || formattedDataForTable.length > 0) && (
|
||||
<Table
|
||||
className="api-monitoring-domain-list-table"
|
||||
data-testid="api-monitoring-domain-table"
|
||||
dataSource={isFetching || isLoading ? [] : formattedDataForTable}
|
||||
columns={columnsConfig}
|
||||
loading={{
|
||||
@@ -210,7 +214,10 @@ function DomainList(): JSX.Element {
|
||||
}}
|
||||
scroll={{ x: true }}
|
||||
tableLayout="fixed"
|
||||
onRow={(record, index): { onClick: () => void; className: string } => ({
|
||||
onRow={(
|
||||
record,
|
||||
index,
|
||||
): { onClick: () => void; className: string; 'data-testid': string } => ({
|
||||
onClick: (): void => {
|
||||
if (index !== undefined) {
|
||||
const dataIndex = formattedDataForTable.findIndex(
|
||||
@@ -222,6 +229,7 @@ function DomainList(): JSX.Element {
|
||||
}
|
||||
},
|
||||
className: 'expanded-clickable-row',
|
||||
'data-testid': `domain-row-${record.domainName}`,
|
||||
})}
|
||||
rowClassName={(_, index): string =>
|
||||
index % 2 === 0 ? 'table-row-dark' : 'table-row-light'
|
||||
|
||||
@@ -85,7 +85,6 @@ export const PagerInitialConfig: Partial<AlertmanagertypesChannelPagerdutyConfig
|
||||
{{- end }}`,
|
||||
severity: '{{ (index .Alerts 0).Labels.severity }}',
|
||||
client: 'SigNoz Alert Manager',
|
||||
clientUrl: 'https://enter-signoz-host-n-port-here/alerts',
|
||||
details: {
|
||||
firing: `{{ .Alerts.Firing | toJson }}`,
|
||||
resolved: `{{ .Alerts.Resolved | toJson }}`,
|
||||
|
||||
@@ -5,6 +5,10 @@ import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
import { CreateAlertProvider } from '../../context';
|
||||
import {
|
||||
THRESHOLD_MATCH_TYPE_OPTIONS,
|
||||
THRESHOLD_OPERATOR_OPTIONS,
|
||||
} from '../../context/constants';
|
||||
import AlertThreshold from '../AlertThreshold';
|
||||
|
||||
const mockChannels: ChannelOption[] = [];
|
||||
@@ -289,4 +293,49 @@ describe('AlertThreshold', () => {
|
||||
verifySelectRenders(TEST_STRINGS.IS_ABOVE);
|
||||
verifySelectRenders(TEST_STRINGS.AT_LEAST_ONCE);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'operator',
|
||||
THRESHOLD_OPERATOR_OPTIONS,
|
||||
[
|
||||
'ABOVE',
|
||||
'BELOW',
|
||||
'EQUAL TO',
|
||||
'NOT EQUAL TO',
|
||||
'ABOVE OR EQUAL TO',
|
||||
'BELOW OR EQUAL TO',
|
||||
],
|
||||
],
|
||||
[
|
||||
'match type',
|
||||
THRESHOLD_MATCH_TYPE_OPTIONS,
|
||||
['AT LEAST ONCE', 'ALL THE TIME', 'ON AVERAGE', 'IN TOTAL', 'LAST'],
|
||||
],
|
||||
])(
|
||||
'the %s select offers exactly its documented options',
|
||||
(_label, options, expected) => {
|
||||
// Asserted on the options the select is fed rather than on the rendered
|
||||
// dropdown: antd virtualises its list, so in jsdom (zero-height viewport)
|
||||
// only the first two items exist in the DOM and their text is the wire
|
||||
// value, not the label.
|
||||
expect(options.map((option) => option.label)).toStrictEqual(expected);
|
||||
|
||||
renderAlertThreshold();
|
||||
expect(screen.getByText(options[0].label)).toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it('never renders the recovery threshold control', () => {
|
||||
// `showRecoveryThreshold` starts false and its only setter is commented
|
||||
// out, so neither the input nor its remove button can appear.
|
||||
renderAlertThreshold();
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('recovery-threshold-value-input'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('remove-recovery-threshold-button'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -106,6 +106,41 @@ describe('LabelsInput', () => {
|
||||
expect(mockOnLabelsChange).toHaveBeenCalledWith({ severity: 'high' });
|
||||
});
|
||||
|
||||
it('rejects a key that already exists, before validating it', () => {
|
||||
// Both rejection branches raise an antd notification rather than an
|
||||
// inline message, so the observable outcome is that nothing is added and
|
||||
// the editor stays on the key phase. The duplicate check short-circuits
|
||||
// ahead of `validateLabelsKey`.
|
||||
renderLabelsInput({ labels: { severity: 'high' } });
|
||||
|
||||
fireEvent.click(screen.getByText(ADD_LABELS_TEXT));
|
||||
const input = screen.getByPlaceholderText(ENTER_KEY_PLACEHOLDER);
|
||||
fireEvent.change(input, { target: { value: 'severity' } });
|
||||
fireEvent.keyDown(input, { key: 'Enter' });
|
||||
|
||||
expect(mockValidateLabelsKey).not.toHaveBeenCalled();
|
||||
expect(mockOnLabelsChange).not.toHaveBeenCalled();
|
||||
expect(
|
||||
screen.queryByPlaceholderText(ENTER_VALUE_PLACEHOLDER),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('rejects a key the validator refuses', () => {
|
||||
mockValidateLabelsKey.mockReturnValue('Cannot use a group-by key');
|
||||
renderLabelsInput();
|
||||
|
||||
fireEvent.click(screen.getByText(ADD_LABELS_TEXT));
|
||||
const input = screen.getByPlaceholderText(ENTER_KEY_PLACEHOLDER);
|
||||
fireEvent.change(input, { target: { value: 'service.name' } });
|
||||
fireEvent.keyDown(input, { key: 'Enter' });
|
||||
|
||||
expect(mockValidateLabelsKey).toHaveBeenCalledWith('service.name');
|
||||
expect(mockOnLabelsChange).not.toHaveBeenCalled();
|
||||
expect(
|
||||
screen.queryByPlaceholderText(ENTER_VALUE_PLACEHOLDER),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not switch to value input if key is empty', () => {
|
||||
renderLabelsInput();
|
||||
|
||||
|
||||
@@ -173,6 +173,45 @@ describe('CreateAlertProvider — edit mode ignores URL prefill', () => {
|
||||
|
||||
expect(screen.getByTestId('threshold-value')).toHaveTextContent('245');
|
||||
});
|
||||
|
||||
it('ignores prefill params that are present on an edit URL', () => {
|
||||
// A deep link into the editor can carry the create form's prefill params.
|
||||
// The loaded rule has to win, or opening an edited rule from such a link
|
||||
// would silently rewrite its condition.
|
||||
const initialAlertState = {
|
||||
...INITIAL_CREATE_ALERT_STATE,
|
||||
threshold: {
|
||||
...INITIAL_CREATE_ALERT_STATE.threshold,
|
||||
matchType: AlertThresholdMatchType.AT_LEAST_ONCE,
|
||||
thresholds: [
|
||||
{
|
||||
...INITIAL_CREATE_ALERT_STATE.threshold.thresholds[0],
|
||||
thresholdValue: 245,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
render(
|
||||
<CreateAlertProvider
|
||||
initialAlertType={AlertTypes.METRICS_BASED_ALERT}
|
||||
isEditMode
|
||||
ruleId="r1"
|
||||
initialAlertState={initialAlertState}
|
||||
>
|
||||
<Probe />
|
||||
</CreateAlertProvider>,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: `/alerts/overview?ruleId=r1&matchType=in_total&compareOp=below&thresholds=${serializeThreshold(
|
||||
90,
|
||||
)}`,
|
||||
},
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('threshold-value')).toHaveTextContent('245');
|
||||
expect(screen.getByTestId('match-type')).toHaveTextContent('at_least_once');
|
||||
});
|
||||
});
|
||||
|
||||
function ThresholdSetter(): JSX.Element {
|
||||
|
||||
@@ -148,13 +148,19 @@ function ErrorDetails(props: ErrorDetailsProps): JSX.Element {
|
||||
|
||||
return (
|
||||
<div className="error-details-container">
|
||||
<Typography.Title level={4}>{errorDetail.exceptionType}</Typography.Title>
|
||||
<Typography.Text>{errorDetail.exceptionMessage}</Typography.Text>
|
||||
<Typography.Title level={4} testId="error-details-type">
|
||||
{errorDetail.exceptionType}
|
||||
</Typography.Title>
|
||||
<Typography.Text testId="error-details-message">
|
||||
{errorDetail.exceptionMessage}
|
||||
</Typography.Text>
|
||||
<Divider />
|
||||
|
||||
<EventContainer>
|
||||
<div>
|
||||
<Typography>Event {errorDetail.errorId}</Typography>
|
||||
<Typography testId="error-details-event-id">
|
||||
Event {errorDetail.errorId}
|
||||
</Typography>
|
||||
<Typography>
|
||||
{formatTimezoneAdjustedTimestamp(
|
||||
errorDetail.timestamp,
|
||||
@@ -165,6 +171,7 @@ function ErrorDetails(props: ErrorDetailsProps): JSX.Element {
|
||||
<div>
|
||||
<Space align="end" direction="horizontal">
|
||||
<Button
|
||||
data-testid="error-details-older"
|
||||
loading={nextPrevStatus === 'loading'}
|
||||
disabled={nextPrevData?.payload?.prevErrorID.length === 0}
|
||||
onClick={(): Promise<void> =>
|
||||
@@ -177,6 +184,7 @@ function ErrorDetails(props: ErrorDetailsProps): JSX.Element {
|
||||
{t('older')}
|
||||
</Button>
|
||||
<Button
|
||||
data-testid="error-details-newer"
|
||||
loading={nextPrevStatus === 'loading'}
|
||||
disabled={nextPrevData?.payload?.nextErrorID.length === 0}
|
||||
onClick={(): Promise<void> =>
|
||||
@@ -194,17 +202,21 @@ function ErrorDetails(props: ErrorDetailsProps): JSX.Element {
|
||||
|
||||
<DashedContainer>
|
||||
<Typography>{t('see_trace_graph')}</Typography>
|
||||
<Button onClick={onClickTraceHandler} type="primary">
|
||||
<Button
|
||||
data-testid="error-details-view-trace"
|
||||
onClick={onClickTraceHandler}
|
||||
type="primary"
|
||||
>
|
||||
{t('see_error_in_trace_graph')}
|
||||
</Button>
|
||||
</DashedContainer>
|
||||
|
||||
<Typography.Title level={4}>{t('stack_trace')}</Typography.Title>
|
||||
<div className="error-container">
|
||||
<div className="error-container" data-testid="error-details-stacktrace">
|
||||
<Editor value={stackTraceValue} readOnly />
|
||||
</div>
|
||||
|
||||
<EditorContainer>
|
||||
<EditorContainer data-testid="error-details-attributes-table">
|
||||
<Space direction="vertical">
|
||||
<ResizeTable columns={columns} tableLayout="fixed" dataSource={data} />
|
||||
</Space>
|
||||
|
||||
@@ -406,4 +406,76 @@ describe('ForgotPassword Component', () => {
|
||||
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
// The email input is disabled and Enter in the org Select opens it, so Enter
|
||||
// only reaches the form through the focused submit button.
|
||||
describe('Enter key submission', () => {
|
||||
function mockForgot(delayMs = 0): { forgotCalls: () => number } {
|
||||
let calls = 0;
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) => {
|
||||
calls += 1;
|
||||
return res(
|
||||
ctx.delay(delayMs),
|
||||
ctx.status(200),
|
||||
ctx.json({ status: 'success' }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
return { forgotCalls: (): number => calls };
|
||||
}
|
||||
|
||||
it('sends the reset link once on Enter on the submit button', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { forgotCalls } = mockForgot();
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
await user.tab();
|
||||
await user.tab();
|
||||
expect(screen.getByTestId('forgot-password-submit')).toHaveFocus();
|
||||
await user.keyboard('{enter}');
|
||||
|
||||
await expect(
|
||||
screen.findByText(/check your email/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(forgotCalls()).toBe(1);
|
||||
});
|
||||
|
||||
it('does not send on Enter while no organization is selected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { forgotCalls } = mockForgot();
|
||||
|
||||
render(<ForgotPassword {...multiOrgProps} />);
|
||||
|
||||
const submitButton = screen.getByTestId('forgot-password-submit');
|
||||
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
|
||||
submitButton.focus();
|
||||
await user.keyboard('{enter}');
|
||||
|
||||
// Give a wrongly sent request time to land before asserting it never did.
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
expect(forgotCalls()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not send again on Enter while the first request is loading', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { forgotCalls } = mockForgot(1000);
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
const submitButton = screen.getByTestId('forgot-password-submit');
|
||||
submitButton.focus();
|
||||
await user.keyboard('{enter}');
|
||||
|
||||
await screen.findByText(/sending\.\.\./i);
|
||||
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
|
||||
await user.keyboard('{enter}');
|
||||
|
||||
await expect(
|
||||
screen.findByText(/check your email/i, undefined, { timeout: 2000 }),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(forgotCalls()).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -219,7 +219,12 @@ export default function AlertRules({
|
||||
<Card className="alert-rules-card home-data-card">
|
||||
{rulesExist && (
|
||||
<Card.Header>
|
||||
<div className="alert-rules-header home-data-card-header">Alerts</div>
|
||||
<div
|
||||
className="alert-rules-header home-data-card-header"
|
||||
data-testid="home-section-alerts"
|
||||
>
|
||||
Alerts
|
||||
</div>
|
||||
</Card.Header>
|
||||
)}
|
||||
<Card.Content>
|
||||
|
||||
@@ -202,7 +202,12 @@ export default function Dashboards({
|
||||
<Card className="dashboards-list-card home-data-card">
|
||||
{dashboardsExist && (
|
||||
<Card.Header>
|
||||
<div className="dashboards-header home-data-card-header">Dashboards</div>
|
||||
<div
|
||||
className="dashboards-header home-data-card-header"
|
||||
data-testid="home-section-dashboards"
|
||||
>
|
||||
Dashboards
|
||||
</div>
|
||||
</Card.Header>
|
||||
)}
|
||||
<Card.Content>
|
||||
|
||||
@@ -278,7 +278,7 @@ export default function Home(): JSX.Element {
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="home-container">
|
||||
<div className="home-container" data-testid="home-page">
|
||||
{getIsNoAuthMode() && <NoAuthBanner />}
|
||||
<div className="sticky-header">
|
||||
<Header
|
||||
@@ -316,6 +316,7 @@ export default function Home(): JSX.Element {
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
prefix={<ClipboardList size={14} />}
|
||||
testId="welcome-checklist-btn"
|
||||
>
|
||||
Welcome checklist
|
||||
</Button>
|
||||
@@ -662,7 +663,10 @@ export default function Home(): JSX.Element {
|
||||
exit={{ opacity: 0, scale: 0 }}
|
||||
key="box"
|
||||
>
|
||||
<div className="checklist-container">
|
||||
<div
|
||||
className="checklist-container"
|
||||
data-testid="home-checklist-card"
|
||||
>
|
||||
<div className="checklist-items-container">
|
||||
<StepsProgress checklistItems={checklistItems} />
|
||||
|
||||
@@ -701,6 +705,7 @@ export default function Home(): JSX.Element {
|
||||
color="secondary"
|
||||
onClick={handleWillDoThisLater}
|
||||
loading={updatingUserPreferences}
|
||||
testId="checklist-do-later-btn"
|
||||
>
|
||||
I'll do this later
|
||||
</Button>
|
||||
|
||||
@@ -68,6 +68,7 @@ function HomeChecklist({
|
||||
{whatsNextChecklistItems.map((item, index) => (
|
||||
<div
|
||||
key={item.id}
|
||||
data-testid={`checklist-item-${item.id}`}
|
||||
className={`whats-next-checklist-item ${
|
||||
item.isSkipped && !item.completed ? 'skipped' : ''
|
||||
} ${
|
||||
@@ -129,6 +130,7 @@ function HomeChecklist({
|
||||
<Button
|
||||
type="link"
|
||||
className="periscope-btn link skip-btn"
|
||||
data-testid={`checklist-skip-${item.id}`}
|
||||
onClick={(): void => {
|
||||
logEvent('Welcome Checklist: Skip clicked', {
|
||||
step: item.id,
|
||||
|
||||
@@ -301,7 +301,10 @@ export default function SavedViews({
|
||||
<Card className="saved-views-list-card home-data-card">
|
||||
{hasSavedViews && (
|
||||
<Card.Header>
|
||||
<div className="saved-views-header home-data-card-header">
|
||||
<div
|
||||
className="saved-views-header home-data-card-header"
|
||||
data-testid="home-section-saved-views"
|
||||
>
|
||||
Saved Views
|
||||
<div className="saved-views-header-actions">
|
||||
<Button.Group className="views-tabs">
|
||||
|
||||
@@ -315,7 +315,10 @@ function ServiceMetrics({
|
||||
<Card className="services-list-card home-data-card">
|
||||
{servicesExist && (
|
||||
<Card.Header>
|
||||
<div className="services-header home-data-card-header">
|
||||
<div
|
||||
className="services-header home-data-card-header"
|
||||
data-testid="home-section-services"
|
||||
>
|
||||
{' '}
|
||||
Services
|
||||
<div className="services-header-actions">
|
||||
|
||||
@@ -218,7 +218,10 @@ export default function ServiceTraces({
|
||||
<Card className="dashboards-list-card home-data-card">
|
||||
{servicesExist && (
|
||||
<Card.Header>
|
||||
<div className="services-header home-data-card-header">
|
||||
<div
|
||||
className="services-header home-data-card-header"
|
||||
data-testid="home-section-services"
|
||||
>
|
||||
Services
|
||||
<div className="services-header-actions">
|
||||
<Select
|
||||
|
||||
@@ -213,6 +213,7 @@ function Hosts(): JSX.Element {
|
||||
className="periscope-btn ghost"
|
||||
type="text"
|
||||
size="small"
|
||||
data-testid="quick-filters-toggle"
|
||||
onClick={handleFilterVisibilityChange}
|
||||
>
|
||||
<Filter size={14} />
|
||||
@@ -239,6 +240,7 @@ function Hosts(): JSX.Element {
|
||||
style={{ rotate: '270deg', cursor: 'pointer' }}
|
||||
onClick={handleFilterVisibilityChange}
|
||||
size="md"
|
||||
data-testid="quick-filters-toggle"
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -53,6 +53,7 @@ function StatusFilter(): JSX.Element {
|
||||
items={statusOptions.map((option) => ({
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
testId: `status-filter-${option.value}`,
|
||||
prefix: (
|
||||
<span
|
||||
className={`${styles.statusDot} ${
|
||||
|
||||
@@ -296,6 +296,7 @@ export default function K8sBaseDetails<T>({
|
||||
<DrawerWrapper
|
||||
open={!!selectedItem}
|
||||
onOpenChange={handleOpenChange}
|
||||
testId="drawer-wrapper"
|
||||
direction="right"
|
||||
title={drawerTitle}
|
||||
showCloseButton={false}
|
||||
|
||||
@@ -301,6 +301,7 @@ export default function K8sBaseDetailsContent<T>({
|
||||
type="single"
|
||||
onChange={handleTabChange}
|
||||
value={effectiveView}
|
||||
testId="drawer-tab-bar"
|
||||
items={[
|
||||
...(tabVisibility.showOverview
|
||||
? [
|
||||
@@ -387,6 +388,7 @@ export default function K8sBaseDetailsContent<T>({
|
||||
size="sm"
|
||||
icon
|
||||
color="secondary"
|
||||
testId="open-logs-explorer"
|
||||
onClick={handleExplorePagesRedirect}
|
||||
>
|
||||
<Compass size={18} />
|
||||
@@ -401,6 +403,7 @@ export default function K8sBaseDetailsContent<T>({
|
||||
size="sm"
|
||||
icon
|
||||
color="secondary"
|
||||
testId="open-traces-explorer"
|
||||
onClick={handleExplorePagesRedirect}
|
||||
>
|
||||
<Compass size={18} />
|
||||
|
||||
@@ -396,6 +396,11 @@ export function K8sBaseList<
|
||||
|
||||
const isGroupedByAttribute = groupBy.length > 0;
|
||||
|
||||
const getRowTestId = useCallback(
|
||||
(record: T): string => `row-${getRowKey(record)}`,
|
||||
[getRowKey],
|
||||
);
|
||||
|
||||
// Filter columns for expanded row based on parent's hidden columns
|
||||
const expandedRowColumns = useMemo(
|
||||
() => tableColumns.filter((col) => !hiddenColumnIds.includes(col.id)),
|
||||
@@ -417,6 +422,7 @@ export function K8sBaseList<
|
||||
extraQueryKeyParts={extraQueryKeyParts}
|
||||
getRowKey={getRowKey}
|
||||
getItemKey={getItemKey}
|
||||
getRowTestId={getRowTestId}
|
||||
detailsQueryKeyPrefix={detailsQueryKeyPrefix}
|
||||
/>
|
||||
),
|
||||
@@ -425,6 +431,7 @@ export function K8sBaseList<
|
||||
fetchListData,
|
||||
getRowKey,
|
||||
getItemKey,
|
||||
getRowTestId,
|
||||
expandedRowColumns,
|
||||
extraQueryKeyParts,
|
||||
detailsQueryKeyPrefix,
|
||||
@@ -506,6 +513,7 @@ export function K8sBaseList<
|
||||
isLoading={showTableLoadingState}
|
||||
getRowKey={getRowKey}
|
||||
getItemKey={getItemKey}
|
||||
getRowTestId={getRowTestId}
|
||||
groupBy={groupBy.map((g) => ({ key: g }))}
|
||||
getGroupKey={getGroupKeyFn}
|
||||
onRowClick={handleRowClick}
|
||||
|
||||
@@ -21,7 +21,7 @@ export function K8sEmptyState({
|
||||
|
||||
if (isError || error) {
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.container} data-testid="k8s-error-state">
|
||||
<div className={styles.errorContent}>
|
||||
<ErrorContent
|
||||
error={
|
||||
@@ -38,7 +38,7 @@ export function K8sEmptyState({
|
||||
|
||||
if (endTimeBeforeRetention) {
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.container} data-testid="k8s-empty-state-retention">
|
||||
<div className={styles.content}>
|
||||
<img className={styles.eyesEmoji} src={eyesEmojiUrl} alt="eyes emoji" />
|
||||
<div className={styles.noDataMessage}>
|
||||
@@ -56,7 +56,7 @@ export function K8sEmptyState({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.container} data-testid="k8s-empty-state">
|
||||
<div className={styles.content}>
|
||||
<img
|
||||
src={emptyStateUrl}
|
||||
|
||||
@@ -69,6 +69,7 @@ export type K8sExpandedRowProps<T, TItemKey = string> = {
|
||||
getRowKey?: (record: T) => string;
|
||||
/** Function to get the item key used for selection. Defaults to getRowKey if not provided. */
|
||||
getItemKey?: (record: T) => TItemKey;
|
||||
getRowTestId?: (record: T) => string;
|
||||
/** Query key prefix for pre-caching detail data on row click */
|
||||
detailsQueryKeyPrefix?: string;
|
||||
};
|
||||
@@ -85,6 +86,7 @@ export function K8sExpandedRow<
|
||||
extraQueryKeyParts = [],
|
||||
getRowKey,
|
||||
getItemKey,
|
||||
getRowTestId,
|
||||
detailsQueryKeyPrefix,
|
||||
}: K8sExpandedRowProps<T, TItemKey>): JSX.Element {
|
||||
const fontSize = useInfraMonitoringFontSize();
|
||||
@@ -321,6 +323,7 @@ export function K8sExpandedRow<
|
||||
isLoading={isLoading}
|
||||
getRowKey={getRowKey}
|
||||
getItemKey={getItemKey}
|
||||
getRowTestId={getRowTestId}
|
||||
onRowClick={handleRowClick}
|
||||
onSort={handleSort}
|
||||
enableQueryParams={{
|
||||
|
||||
@@ -141,6 +141,7 @@ function K8sHeader({
|
||||
isLoadingQueries={isFetching}
|
||||
onStageRunQuery={handleStageRunQuery}
|
||||
handleCancelQuery={handleCancelQuery}
|
||||
testId="list-run-query-btn"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user