mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-19 23:01:18 +00:00
Compare commits
35 Commits
fix/alert-
...
test/jest-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e9f611b12 | ||
|
|
a3ef0d3044 | ||
|
|
32e550666c | ||
|
|
4bdda574c2 | ||
|
|
79af7a6c32 | ||
|
|
8a0a5baee4 | ||
|
|
9d7092cc1b | ||
|
|
da89bd1a0a | ||
|
|
de6739eb8a | ||
|
|
ed940b7f3e | ||
|
|
4ed05f4a8a | ||
|
|
b521c822c8 | ||
|
|
bb1b4bc3fd | ||
|
|
fc224f2eb0 | ||
|
|
cd1264883b | ||
|
|
feef647b95 | ||
|
|
aad689acd2 | ||
|
|
77ebf4dca9 | ||
|
|
c4ac1929fa | ||
|
|
df0f26b5fb | ||
|
|
3843ac4eeb | ||
|
|
0add9cce0d | ||
|
|
4ffa6ac5da | ||
|
|
824315b093 | ||
|
|
1ee097b60a | ||
|
|
f0370c6cc1 | ||
|
|
b106d86bef | ||
|
|
d8c00a34b9 | ||
|
|
0d3eee5c78 | ||
|
|
9d5c5871cb | ||
|
|
f1f1b14f00 | ||
|
|
6480c786be | ||
|
|
313de0a00c | ||
|
|
e972f26992 | ||
|
|
42e84652bf |
@@ -9,12 +9,14 @@ paths:
|
||||
Examples and the harness API live in [`frontend/src/tests/README.md`](../../frontend/src/tests/README.md).
|
||||
|
||||
- **Import from the harness.** `render`, `screen`, `userEvent`, `waitFor` and the rest come from `tests/test-utils`, never from `@testing-library/react`. The harness mounts the router, React Query, Redux, app context and preferences. When it can't do what a test needs, extend `tests/test-utils` instead of importing around it.
|
||||
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` computes the accessibility tree on every call and is the slowest query.
|
||||
- **Interact like a user.** `const user = userEvent.setup({ pointerEventsCheck: 0 })`, then an awaited `user.click`, `hover`, `keyboard` or `type`. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
|
||||
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` computes the accessibility tree on every call and is the slowest query. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
|
||||
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check, which walks `getComputedStyle` up the tree on every action; never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
|
||||
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
|
||||
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.
|
||||
- **Router through the harness.** Pass `initialRoute`/`routePath` to `render` and assert with `getCurrentLocation()` from `lib/router/navigation`. Never mock `react-router`, `react-router-dom` or `lib/history`; when a test can't render at a route, use the `lib/router` spies in `tests/router-mocks`.
|
||||
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
|
||||
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides (`@floating-ui/dom`, `@testing-library/user-event` and antd's `collectScroller` in `jest.setup.ts`) or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
|
||||
- **Type mocks and fixtures.** `jest.mocked(fn)` for module mocks, `jest.fn() as jest.MockedFunction<T>` for a standalone mock you configure or assert on. Fixtures carry their real type, from `src/api/generated` where it exists. No `any`, no `as unknown as`. An inline `onX={jest.fn()}` on a typed prop that is never asserted needs no annotation.
|
||||
- **A test fails without its change.** Revert the change, or break the line under test, and run the test before you finish: it must fail. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
|
||||
- **One behaviour per test, at the smallest render.** Render the component that owns the behaviour, not the page around it, unless the page wiring is the behaviour. A flow of steps (a wizard, a multi-step form) becomes one test per step that starts at that step through props, store or route. A full click-through belongs in the e2e suite (`tests/e2e`).
|
||||
- **Each test under 500 ms.** `pnpm jest <file> --verbose` prints each test's time. CI runs about four times slower than a laptop, and the timeout is 5 s. Never raise a timeout (`jest.setTimeout`, a third argument to `it`) to make a slow test pass; slim the test instead.
|
||||
- **A test fails without its change.** At the gate in [`frontend/AGENTS.md`](../../frontend/AGENTS.md), revert the change, or break the line under test, and run the test: it must fail, and each test must stay under 500 ms. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
|
||||
- **No limit on tests per file.** Split a file when it mixes unrelated behaviour, not to hit a count.
|
||||
|
||||
@@ -18,7 +18,9 @@ tag <diff> <tag> <story-id>... # what the reviewer should look at
|
||||
export <diff> --out <dir> # a static site, hostable
|
||||
```
|
||||
|
||||
`<storybook>` is a running dev server (`http://localhost:6006`), a build directory holding `index.json`, or a project directory with `.storybook/`. The frontend has **no `build-storybook` script**, only `storybook dev -p 6006`, so point `capture` at a dev server.
|
||||
`<storybook>` is a running dev server (`http://localhost:6006`), a build directory holding `index.json`, or a project directory with `.storybook/`. **Capture from a build**: `pnpm storybook:build` in `frontend` (about 2 minutes) writes `storybook-static/`. A dev server serves the preview module by module, which adds 5 to 10 seconds to every story and, with several stories at once, ends in `page.goto: Timeout 30000ms exceeded` retries.
|
||||
|
||||
Pass `--globals 'a11y.manual:!true'` to every `capture`. The a11y addon otherwise runs axe after every story, about 2 seconds each, and nothing it does shows in a shot.
|
||||
|
||||
## Cover the change with stories first
|
||||
|
||||
@@ -30,7 +32,7 @@ Then confirm it worked: the two runs' story counts should differ by exactly the
|
||||
|
||||
## Rules that are not optional
|
||||
|
||||
**One freshly started Storybook per ref.** Never start one server and switch git branches under it. Vite's HMR reloads the page, but some modules do not re-initialise, so the shot differs silently from a clean boot and the difference looks like a real change. Settle time does not fix this and is not the variable. Use one worktree and one port per ref, and stop each server before the next.
|
||||
**One freshly started Storybook per ref.** Never start one server and switch git branches under it. Vite's HMR reloads the page, but some modules do not re-initialise, so the shot differs silently from a clean boot and the difference looks like a real change. Settle time does not fix this and is not the variable. Use one worktree and one port per ref, and stop each server before the next. A build made in each ref's worktree has none of this.
|
||||
|
||||
**Capture both themes: `--theme dark,light`.** Without it sbshot shoots the story's own default and everything lands in a single `default/` folder, so every regression in the other theme is invisible. Themes double the shot count, so scope with `--stories` or `--title`, never by dropping a theme.
|
||||
|
||||
|
||||
@@ -364,7 +364,7 @@ tokenizer:
|
||||
interval: 1h
|
||||
token:
|
||||
# The maximum number of tokens a user can have. This limits the number of concurrent sessions a user can have.
|
||||
max_per_user: 5
|
||||
max_per_user: 20
|
||||
|
||||
##################### Flagger #####################
|
||||
flagger:
|
||||
|
||||
@@ -4420,7 +4420,8 @@ components:
|
||||
description: The dashboard title and description.
|
||||
duration:
|
||||
description: The default time range, as a Prometheus duration such as 1h
|
||||
or 7d. Stored, but not applied by the UI.
|
||||
or 7d. The UI opens the dashboard on it, rounded up to whole minutes,
|
||||
when neither the URL nor the viewer's last pick sets a time range.
|
||||
type: string
|
||||
layouts:
|
||||
description: The Grid layouts that place panels, at most 500. Each panel
|
||||
@@ -5527,6 +5528,7 @@ components:
|
||||
signoz/TablePanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec'
|
||||
signoz/TextPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpec'
|
||||
signoz/TimeSeriesPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec'
|
||||
signoz/TopListPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec'
|
||||
@@ -5541,6 +5543,7 @@ components:
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
|
||||
type: object
|
||||
DashboardtypesPanelPluginKind:
|
||||
enum:
|
||||
@@ -5556,6 +5559,7 @@ components:
|
||||
- signoz/HeatmapPanel
|
||||
- signoz/ScatterPlotPanel
|
||||
- signoz/GeoMapPanel
|
||||
- signoz/TopListPanel
|
||||
type: string
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
|
||||
properties:
|
||||
@@ -5737,6 +5741,21 @@ components:
|
||||
- kind
|
||||
- spec
|
||||
type: object
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec:
|
||||
properties:
|
||||
kind:
|
||||
description: The panel kind.
|
||||
enum:
|
||||
- signoz/TopListPanel
|
||||
type: string
|
||||
spec:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesTopListPanelSpec'
|
||||
description: The options for this panel kind. {} accepts every default.
|
||||
required:
|
||||
- kind
|
||||
- spec
|
||||
type: object
|
||||
DashboardtypesPanelSpec:
|
||||
properties:
|
||||
display:
|
||||
@@ -6499,6 +6518,43 @@ components:
|
||||
last_6_hr, last_1_day, last_3_days, last_1_week or last_1_month pin a
|
||||
fixed window.'
|
||||
type: object
|
||||
DashboardtypesTopListAppearance:
|
||||
properties:
|
||||
barColor:
|
||||
description: Hex color of every bar; a matching background threshold overrides
|
||||
it.
|
||||
type: string
|
||||
showRank:
|
||||
description: Numbers each row by its position in the list.
|
||||
type: boolean
|
||||
showShare:
|
||||
description: Shows each row's share of the listed rows' total.
|
||||
type: boolean
|
||||
required:
|
||||
- barColor
|
||||
type: object
|
||||
DashboardtypesTopListPanelSpec:
|
||||
properties:
|
||||
appearance:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesTopListAppearance'
|
||||
description: Rank, share and bar color options.
|
||||
formatting:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelFormatting'
|
||||
description: Unit and decimal precision of the values.
|
||||
thresholds:
|
||||
description: Rules that recolor a row when its value compares to a threshold
|
||||
as specified.
|
||||
items:
|
||||
$ref: '#/components/schemas/DashboardtypesComparisonThreshold'
|
||||
nullable: true
|
||||
type: array
|
||||
visualization:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesBasicVisualization'
|
||||
description: The time range the rows are computed over.
|
||||
type: object
|
||||
DashboardtypesUpdatableDashboardV2:
|
||||
properties:
|
||||
image:
|
||||
|
||||
@@ -99,7 +99,7 @@ is still by hand. The generator never adds a SideNav item; do that in
|
||||
CSS Modules (`docs/css-modules-guide.md`), React Query for server state (prefer
|
||||
`api/generated` hooks), nuqs for URL state, Zustand for client state, `data-testid` on
|
||||
every interactive element.
|
||||
5. **Verify** before reporting done:
|
||||
5. **Verify** at the gate in `AGENTS.md` (commit, push or PR), not after each edit; skip it while the user says `no checks`:
|
||||
```bash
|
||||
pnpm tsgo --noEmit
|
||||
pnpm oxlint src/pages/<Feature>
|
||||
|
||||
@@ -34,6 +34,12 @@
|
||||
pylon: { enabled: false, appId: '', identitySecret: '' },
|
||||
},
|
||||
};
|
||||
|
||||
// OverlayScrollbars drives its handles with scroll-driven animations when the
|
||||
// browser has `ScrollTimeline`. Those never finish, and Storybook waits up to
|
||||
// 5s for running animations after every `play`, so each story with a scroller
|
||||
// would pay the full 5s. Without it the handles are positioned from script.
|
||||
delete window.ScrollTimeline;
|
||||
</script>
|
||||
|
||||
<script>
|
||||
|
||||
@@ -34,14 +34,18 @@ You are operating within a constrained context window and strict system prompts.
|
||||
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.
|
||||
- A payload saved under another kind or schema copies only the fields that schema accepts, and drops bindings to columns the user removed. The server rejects unknown or stale fields, so the preview works and the save fails.
|
||||
|
||||
3. FORCED VERIFICATION: Your internal tools mark file writes as successful even if the code does not compile. Run these checks once all changes of a task are done, never after each edit. You are FORBIDDEN from reporting a task as complete until you have:
|
||||
3. CHECKS AT THE GATE: Your internal tools mark file writes as successful even if the code does not compile, so the checks below are required, but only at the gate. The gate is when the user says commit, push, raise or update the PR, mark it ready, or "run checks". Never run them after each edit or between the user's iterations.
|
||||
- Between gates, after an edit, run at most the one test file that covers it.
|
||||
- `no checks`: when the user says it (or "don't run tests", "just making changes"), run nothing: no tests, type check, lint, format or build. Make the change and stop. This holds until the user names a gate.
|
||||
|
||||
At the gate, you are FORBIDDEN from reporting a task as complete until you have:
|
||||
- Run `pnpm tsgo --noEmit`
|
||||
- Run `pnpm lint:js --quiet` to find critical errors
|
||||
- Run `pnpm oxlint <file1> <file2>` and fix all warnings
|
||||
- Run `pnpm build`
|
||||
- Find if the file has tests for it, or if there's `__test__` folder or the parent folder has tests, and run. Run them before coding the change or after all changes, never in between.
|
||||
- For e2e, run only the specs you added or changed: the stack is heavy. Leave the full jest and e2e suites to CI unless the user asks.
|
||||
- For every test you added or changed, revert the change it covers and confirm the test fails
|
||||
- For every test you added or changed, revert the change it covers and confirm the test fails, and that each test runs under 500 ms (`pnpm jest <file> --verbose`)
|
||||
- On a stacked branch (`gh stack`), run `pnpm tsgo --noEmit` on every branch above it before pushing: a renamed prop or moved export breaks them
|
||||
- Fixed ALL resulting errors
|
||||
|
||||
|
||||
@@ -65,6 +65,8 @@ const config: Config.InitialOptions = {
|
||||
testPathIgnorePatterns: ['/node_modules/', '/public/'],
|
||||
moduleDirectories: ['node_modules', 'src'],
|
||||
testEnvironment: '<rootDir>/jest.environment.cjs',
|
||||
// Local only: the default (cores - 1) workers exhaust RAM when several runs overlap.
|
||||
...(process.env.CI ? {} : { maxWorkers: 4, workerIdleMemoryLimit: '1GB' }),
|
||||
coverageThreshold: {
|
||||
global: {
|
||||
statements: 80,
|
||||
|
||||
@@ -144,6 +144,39 @@ window.getComputedStyle = function (
|
||||
}
|
||||
};
|
||||
|
||||
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
|
||||
// popover ancestor costs up to ~1 s per open.
|
||||
jest.mock('@floating-ui/dom', () => ({
|
||||
...jest.requireActual('@floating-ui/dom'),
|
||||
autoUpdate: (): (() => void) => (): void => {},
|
||||
computePosition: (
|
||||
_reference: unknown,
|
||||
_floating: unknown,
|
||||
{ placement = 'bottom', strategy = 'absolute' } = {},
|
||||
): Promise<unknown> =>
|
||||
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
|
||||
}));
|
||||
|
||||
jest.mock('@testing-library/user-event', () =>
|
||||
jest.requireActual('tests/userEventWithDefaults'),
|
||||
);
|
||||
|
||||
// antd popups walk getComputedStyle up every ancestor to find scroll
|
||||
// containers on each open. pnpm keeps the package under antd, not at the root.
|
||||
jest.mock(
|
||||
require.resolve('@rc-component/trigger/lib/util', {
|
||||
paths: [require.resolve('antd')],
|
||||
}),
|
||||
() => ({
|
||||
...jest.requireActual(
|
||||
require.resolve('@rc-component/trigger/lib/util', {
|
||||
paths: [require.resolve('antd')],
|
||||
}),
|
||||
),
|
||||
collectScroller: (): HTMLElement[] => [],
|
||||
}),
|
||||
);
|
||||
|
||||
beforeAll(() => server.listen());
|
||||
|
||||
afterEach(() => server.resetHandlers());
|
||||
|
||||
@@ -7190,6 +7190,63 @@ export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDa
|
||||
spec: DashboardtypesGeoMapPanelSpecDTO;
|
||||
}
|
||||
|
||||
/**
|
||||
* The panel kind.
|
||||
*/
|
||||
export enum DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind {
|
||||
'signoz/TopListPanel' = 'signoz/TopListPanel',
|
||||
}
|
||||
export interface DashboardtypesTopListAppearanceDTO {
|
||||
/**
|
||||
* @type string
|
||||
* @description Hex color of every bar; a matching background threshold overrides it.
|
||||
*/
|
||||
barColor: string;
|
||||
/**
|
||||
* @type boolean
|
||||
* @description Numbers each row by its position in the list.
|
||||
*/
|
||||
showRank?: boolean;
|
||||
/**
|
||||
* @type boolean
|
||||
* @description Shows each row's share of the listed rows' total.
|
||||
*/
|
||||
showShare?: boolean;
|
||||
}
|
||||
|
||||
export interface DashboardtypesTopListPanelSpecDTO {
|
||||
/**
|
||||
* @description Rank, share and bar color options.
|
||||
*/
|
||||
appearance?: DashboardtypesTopListAppearanceDTO;
|
||||
/**
|
||||
* @description Unit and decimal precision of the values.
|
||||
*/
|
||||
formatting?: DashboardtypesPanelFormattingDTO;
|
||||
/**
|
||||
* @type array,null
|
||||
* @description Rules that recolor a row when its value compares to a threshold as specified.
|
||||
*/
|
||||
thresholds?: DashboardtypesComparisonThresholdDTO[] | null;
|
||||
/**
|
||||
* @description The time range the rows are computed over.
|
||||
*/
|
||||
visualization?: DashboardtypesBasicVisualizationDTO;
|
||||
}
|
||||
|
||||
export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO {
|
||||
/**
|
||||
* @enum signoz/TopListPanel
|
||||
* @type string
|
||||
* @description The panel kind.
|
||||
*/
|
||||
kind: DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind;
|
||||
/**
|
||||
* @description The options for this panel kind. {} accepts every default.
|
||||
*/
|
||||
spec: DashboardtypesTopListPanelSpecDTO;
|
||||
}
|
||||
|
||||
export type DashboardtypesPanelPluginDTO =
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTO
|
||||
@@ -7202,7 +7259,8 @@ export type DashboardtypesPanelPluginDTO =
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO;
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO;
|
||||
|
||||
export enum Querybuildertypesv5RequestTypeDTO {
|
||||
scalar = 'scalar',
|
||||
@@ -7984,7 +8042,7 @@ export interface DashboardtypesDashboardSpecDTO {
|
||||
display: DashboardtypesDisplayDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description The default time range, as a Prometheus duration such as 1h or 7d. Stored, but not applied by the UI.
|
||||
* @description The default time range, as a Prometheus duration such as 1h or 7d. The UI opens the dashboard on it, rounded up to whole minutes, when neither the URL nor the viewer's last pick sets a time range.
|
||||
*/
|
||||
duration?: string;
|
||||
/**
|
||||
@@ -8490,6 +8548,7 @@ export enum DashboardtypesPanelPluginKindDTO {
|
||||
'signoz/HeatmapPanel' = 'signoz/HeatmapPanel',
|
||||
'signoz/ScatterPlotPanel' = 'signoz/ScatterPlotPanel',
|
||||
'signoz/GeoMapPanel' = 'signoz/GeoMapPanel',
|
||||
'signoz/TopListPanel' = 'signoz/TopListPanel',
|
||||
}
|
||||
/**
|
||||
* The RFC 6902 operations, applied in order against the dashboard's postable shape.
|
||||
|
||||
@@ -903,6 +903,40 @@ describe('prepareQueryRangePayloadV5', () => {
|
||||
const logSpec = builderQuery.spec as LogBuilderQuery;
|
||||
expect(logSpec.filter).toStrictEqual({ expression: '' });
|
||||
});
|
||||
|
||||
it('sends the AI slot as builder_ai_query envelopes, ignoring builder', () => {
|
||||
const props: GetQueryResultsProps = {
|
||||
query: {
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
id: 'q-ai',
|
||||
unit: undefined,
|
||||
promql: [],
|
||||
clickhouse_sql: [],
|
||||
builder: {
|
||||
queryData: [baseBuilderQuery({ queryName: 'M' })],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
builder_ai_query: {
|
||||
queryData: [
|
||||
baseBuilderQuery({ queryName: 'A', dataSource: DataSource.TRACES }),
|
||||
],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
},
|
||||
graphType: PANEL_TYPES.TIME_SERIES,
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
start,
|
||||
end,
|
||||
};
|
||||
|
||||
const { queries } =
|
||||
prepareQueryRangePayloadV5(props).queryPayload.compositeQuery;
|
||||
expect(
|
||||
queries.map((q) => [q.type, (q.spec as { name: string }).name]),
|
||||
).toStrictEqual([['builder_ai_query', 'A']]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mapPanelTypeToRequestType', () => {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
|
||||
import { foldAISlot } from 'lib/query/builderSlot';
|
||||
import getStartEndRangeTime from 'lib/getStartEndRangeTime';
|
||||
import { mapQueryDataToApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
@@ -55,6 +56,7 @@ export function mapPanelTypeToRequestType(panelType: PANEL_TYPES): RequestType {
|
||||
case PANEL_TYPES.PIE:
|
||||
case PANEL_TYPES.VALUE:
|
||||
case PANEL_TYPES.GEO_MAP:
|
||||
case PANEL_TYPES.TOP_LIST:
|
||||
return 'scalar';
|
||||
case PANEL_TYPES.TRACE:
|
||||
return 'trace';
|
||||
@@ -279,7 +281,8 @@ export function createAggregation(
|
||||
panelType === PANEL_TYPES.SCATTER ||
|
||||
panelType === PANEL_TYPES.PIE ||
|
||||
panelType === PANEL_TYPES.VALUE ||
|
||||
panelType === PANEL_TYPES.GEO_MAP);
|
||||
panelType === PANEL_TYPES.GEO_MAP ||
|
||||
panelType === PANEL_TYPES.TOP_LIST);
|
||||
|
||||
if (queryData.dataSource === DataSource.METRICS) {
|
||||
return [
|
||||
@@ -561,9 +564,15 @@ export const prepareQueryRangePayloadV5 = (
|
||||
const requestType = mapPanelTypeToRequestType(graphType);
|
||||
let queries: QueryEnvelope[] = [];
|
||||
|
||||
switch (query.queryType) {
|
||||
const foldedQuery = foldAISlot(query);
|
||||
|
||||
switch (foldedQuery.queryType) {
|
||||
case EQueryType.QUERY_BUILDER: {
|
||||
const { queryData: data, queryFormulas, queryTraceOperator } = query.builder;
|
||||
const {
|
||||
queryData: data,
|
||||
queryFormulas,
|
||||
queryTraceOperator,
|
||||
} = foldedQuery.builder;
|
||||
const currentQueryData = mapQueryDataToApi(data, 'queryName', tableParams);
|
||||
const currentFormulas = mapQueryDataToApi(queryFormulas, 'queryName');
|
||||
|
||||
@@ -625,13 +634,15 @@ export const prepareQueryRangePayloadV5 = (
|
||||
break;
|
||||
}
|
||||
case EQueryType.PROM: {
|
||||
const promQueries = reduceQueriesToObject(query[query.queryType]);
|
||||
const promQueries = reduceQueriesToObject(
|
||||
foldedQuery[foldedQuery.queryType],
|
||||
);
|
||||
queries = convertPromQueriesToV5(promQueries.queries);
|
||||
legendMap = promQueries.legends;
|
||||
break;
|
||||
}
|
||||
case EQueryType.CLICKHOUSE: {
|
||||
const chQueries = reduceQueriesToObject(query[query.queryType]);
|
||||
const chQueries = reduceQueriesToObject(foldedQuery[foldedQuery.queryType]);
|
||||
queries = convertClickHouseQueriesToV5(chQueries.queries);
|
||||
legendMap = chQueries.legends;
|
||||
break;
|
||||
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
createErrorHandler,
|
||||
createRolesHandler,
|
||||
createSuccessHandler,
|
||||
enterInviteEmail,
|
||||
pickInviteRole,
|
||||
VALID_EMAIL,
|
||||
} from './testUtils';
|
||||
|
||||
@@ -22,7 +24,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('reset behavior', () => {
|
||||
it('clears all rows when reset is called', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -35,13 +37,12 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.type(emailInputs[1], 'bob@signoz.io');
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
|
||||
await user.click(screen.getByTestId('reset-btn'));
|
||||
|
||||
const resetInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
const resetInputs = screen.getAllByTestId(/^invite-email-/);
|
||||
expect(resetInputs).toHaveLength(2);
|
||||
resetInputs.forEach((input) => {
|
||||
expect(input).toHaveValue('');
|
||||
@@ -49,7 +50,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
});
|
||||
|
||||
it('clears results on reset', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -66,10 +67,8 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
await expect(
|
||||
@@ -84,7 +83,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('results cleared on edit', () => {
|
||||
it('clears API error when email is edited', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
|
||||
@@ -98,17 +97,15 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
await expect(
|
||||
screen.findByTestId('invite-api-error'),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
await user.type(emailInputs[0], 'x');
|
||||
await user.type(screen.getAllByTestId(/^invite-email-/)[0], 'x');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId('invite-api-error')).not.toBeInTheDocument();
|
||||
@@ -116,7 +113,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
});
|
||||
|
||||
it('clears API error when role is changed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
|
||||
@@ -130,10 +127,8 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
await expect(
|
||||
@@ -153,7 +148,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('empty submission', () => {
|
||||
it('does not submit when no rows are touched', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onSuccess = jest.fn();
|
||||
|
||||
render(
|
||||
@@ -175,7 +170,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('submitting state', () => {
|
||||
it('disables submit while submitting', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -187,10 +182,8 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
const submitBtn = screen.getByTestId('submit-btn');
|
||||
await user.click(submitBtn);
|
||||
@@ -203,7 +196,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('whitespace handling', () => {
|
||||
it('trims email whitespace before submission', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const calls: { email: string }[] = [];
|
||||
|
||||
server.use(
|
||||
@@ -224,10 +217,8 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], ' alice@signoz.io ');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, ' alice@signoz.io ');
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
createRolesHandler,
|
||||
createSuccessHandler,
|
||||
createTrackingHandler,
|
||||
enterInviteEmail,
|
||||
pickInviteRole,
|
||||
VALID_EMAIL,
|
||||
} from './testUtils';
|
||||
|
||||
@@ -23,7 +25,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('API calls', () => {
|
||||
it('calls createUser API for each touched row', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const { handler, calls } = createTrackingHandler();
|
||||
server.use(handler);
|
||||
|
||||
@@ -38,10 +40,8 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], 'alice@signoz.io');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, 'alice@signoz.io');
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -55,7 +55,7 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('calls createUser API for multiple touched rows', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const { handler, calls } = createTrackingHandler();
|
||||
server.use(handler);
|
||||
|
||||
@@ -70,21 +70,12 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
|
||||
await user.type(emailInputs[0], 'alice@signoz.io');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
|
||||
await user.type(emailInputs[1], 'bob@signoz.io');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
const editorOptions = await screen.findAllByTitle('Editor');
|
||||
await user.click(editorOptions[editorOptions.length - 1]);
|
||||
|
||||
await user.type(emailInputs[2], 'charlie@signoz.io');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
const adminOptions = await screen.findAllByTitle('Admin');
|
||||
await user.click(adminOptions[adminOptions.length - 1]);
|
||||
await enterInviteEmail(user, 0, 'alice@signoz.io');
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
await pickInviteRole(user, 'Editor');
|
||||
await enterInviteEmail(user, 2, 'charlie@signoz.io');
|
||||
await pickInviteRole(user, 'Admin');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -109,7 +100,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('callbacks', () => {
|
||||
it('calls onSuccess when all invites succeed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onSuccess = jest.fn();
|
||||
|
||||
render(
|
||||
@@ -123,10 +114,8 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -136,7 +125,7 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('calls onAllFailed when all invites fail', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onAllFailed = jest.fn();
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
@@ -152,10 +141,8 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -173,7 +160,7 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('calls onPartialSuccess when some invites succeed and some fail', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onPartialSuccess = jest.fn();
|
||||
const onSuccess = jest.fn();
|
||||
const onAllFailed = jest.fn();
|
||||
@@ -215,16 +202,10 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
|
||||
await user.type(emailInputs[0], 'alice@signoz.io');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
|
||||
await user.type(emailInputs[1], 'bob@signoz.io');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
const editorOptions = await screen.findAllByTitle('Editor');
|
||||
await user.click(editorOptions[editorOptions.length - 1]);
|
||||
await enterInviteEmail(user, 0, 'alice@signoz.io');
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
await pickInviteRole(user, 'Editor');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -262,7 +243,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('result display', () => {
|
||||
it('shows success callout when all invites succeed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -274,10 +255,8 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -287,7 +266,7 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('shows error callout with failed emails when API fails', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
|
||||
@@ -301,10 +280,8 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -317,7 +294,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('footer props', () => {
|
||||
it('provides correct canSubmit state', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -331,14 +308,13 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
expect(screen.getByTestId('submit-btn')).toBeDisabled();
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
|
||||
expect(screen.getByTestId('submit-btn')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('provides touchedCount', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -351,12 +327,11 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
expect(screen.getByTestId('touched-count')).toHaveTextContent('0');
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], 'a@b.com');
|
||||
await enterInviteEmail(user, 0, 'a@b.com');
|
||||
|
||||
expect(screen.getByTestId('touched-count')).toHaveTextContent('1');
|
||||
|
||||
await user.type(emailInputs[1], 'c@d.com');
|
||||
await enterInviteEmail(user, 1, 'c@d.com');
|
||||
|
||||
expect(screen.getByTestId('touched-count')).toHaveTextContent('2');
|
||||
});
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { RestHandler } from 'msw';
|
||||
import { rest } from 'mocks-server/server';
|
||||
import { screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
type User = ReturnType<typeof userEvent.setup>;
|
||||
|
||||
export const CREATE_USER_ENDPOINT = '*/api/v2/users';
|
||||
export const LIST_ROLES_ENDPOINT = '*/api/v1/roles';
|
||||
@@ -52,3 +55,18 @@ export function createTrackingHandler(): {
|
||||
});
|
||||
return { handler, calls };
|
||||
}
|
||||
|
||||
export async function enterInviteEmail(
|
||||
user: User,
|
||||
rowIndex: number,
|
||||
email: string,
|
||||
): Promise<void> {
|
||||
await user.click(screen.getAllByTestId(/^invite-email-/)[rowIndex]);
|
||||
await user.paste(email);
|
||||
}
|
||||
|
||||
export async function pickInviteRole(user: User, role: string): Promise<void> {
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
const options = await screen.findAllByTitle(role);
|
||||
await user.click(options[options.length - 1]);
|
||||
}
|
||||
|
||||
@@ -52,7 +52,10 @@ function MultiSelectFilter({
|
||||
disabled={disabled}
|
||||
onClear={onClear}
|
||||
optionRender={(option): JSX.Element => (
|
||||
<div className={styles.checkOption}>
|
||||
<div
|
||||
className={styles.checkOption}
|
||||
data-testid={`${testId}-option-${String(option.value)}`}
|
||||
>
|
||||
<div className={styles.checkOptionBox}>
|
||||
<Checkbox
|
||||
color="primary"
|
||||
|
||||
@@ -1,40 +1,32 @@
|
||||
import React, { ComponentType, Suspense } from 'react';
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
waitForElementToBeRemoved,
|
||||
} from '@testing-library/react';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import Loadable from './index';
|
||||
|
||||
// Sample component to be loaded lazily
|
||||
function SampleComponent(): JSX.Element {
|
||||
return <div>Sample Component</div>;
|
||||
return <div data-testid="sample-component">Sample Component</div>;
|
||||
}
|
||||
|
||||
const loadSampleComponent = (): Promise<{
|
||||
default: ComponentType;
|
||||
}> =>
|
||||
new Promise<{ default: ComponentType }>((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve({ default: SampleComponent });
|
||||
}, 500);
|
||||
});
|
||||
}> => Promise.resolve({ default: SampleComponent });
|
||||
|
||||
describe('Loadable', () => {
|
||||
it('should render the lazily loaded component', async () => {
|
||||
const LoadableSampleComponent = Loadable(loadSampleComponent);
|
||||
|
||||
const { container } = render(
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
render(
|
||||
<Suspense fallback={<div data-testid="loading">Loading...</div>}>
|
||||
<LoadableSampleComponent />
|
||||
</Suspense>,
|
||||
);
|
||||
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
await waitForElementToBeRemoved(() => screen.queryByText('Loading...'));
|
||||
|
||||
expect(container.querySelector('div')).toHaveTextContent('Sample Component');
|
||||
expect(screen.getByTestId('loading')).toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByTestId('sample-component'),
|
||||
).resolves.toHaveTextContent('Sample Component');
|
||||
expect(screen.queryByTestId('loading')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should call lazy with the provided import path', () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { Formula } from 'container/QueryBuilder/components/Formula';
|
||||
import { QueryBuilderProps } from 'container/QueryBuilder/QueryBuilder.interfaces';
|
||||
@@ -49,6 +50,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
initialDataSource,
|
||||
handleRunQuery,
|
||||
} = useQueryBuilder();
|
||||
const activeBuilder = getActiveBuilder(currentQuery);
|
||||
|
||||
const containerRef = useRef(null);
|
||||
|
||||
@@ -129,28 +131,28 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
const renderedQueries = useMemo(
|
||||
() =>
|
||||
isMultiQueryAllowed
|
||||
? currentQuery.builder.queryData
|
||||
: currentQuery.builder.queryData.slice(0, 1),
|
||||
[isMultiQueryAllowed, currentQuery.builder.queryData],
|
||||
? activeBuilder.queryData
|
||||
: activeBuilder.queryData.slice(0, 1),
|
||||
[isMultiQueryAllowed, activeBuilder.queryData],
|
||||
);
|
||||
|
||||
const traceOperator = useMemo((): IBuilderTraceOperator | undefined => {
|
||||
if (
|
||||
currentQuery.builder.queryTraceOperator &&
|
||||
currentQuery.builder.queryTraceOperator.length > 0
|
||||
activeBuilder.queryTraceOperator &&
|
||||
activeBuilder.queryTraceOperator.length > 0
|
||||
) {
|
||||
return currentQuery.builder.queryTraceOperator[0];
|
||||
return activeBuilder.queryTraceOperator[0];
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [currentQuery.builder.queryTraceOperator]);
|
||||
}, [activeBuilder.queryTraceOperator]);
|
||||
|
||||
const hasAtLeastOneTraceQuery = useMemo(
|
||||
() =>
|
||||
currentQuery.builder.queryData.some(
|
||||
activeBuilder.queryData.some(
|
||||
(query) => query.dataSource === DataSource.TRACES,
|
||||
),
|
||||
[currentQuery.builder.queryData],
|
||||
[activeBuilder.queryData],
|
||||
);
|
||||
|
||||
const hasTraceOperator = useMemo(
|
||||
@@ -225,9 +227,9 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
{!isMultiQueryAllowed ? (
|
||||
<QueryV2
|
||||
ref={containerRef}
|
||||
key={currentQuery.builder.queryData[0].queryName}
|
||||
key={activeBuilder.queryData[0].queryName}
|
||||
index={0}
|
||||
query={currentQuery.builder.queryData[0]}
|
||||
query={activeBuilder.queryData[0]}
|
||||
fieldsConfig={fieldsConfig}
|
||||
allowedDataSources={queryDataSources}
|
||||
isMultiQueryAllowed={isMultiQueryAllowed}
|
||||
@@ -238,7 +240,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
queryVariant={config?.queryVariant || 'dropdown'}
|
||||
showOnlyWhereClause={showOnlyWhereClause}
|
||||
isRawQuery={isRawQuery}
|
||||
signalSource={currentQuery.builder.queryData[0].source as 'meter' | ''}
|
||||
signalSource={activeBuilder.queryData[0].source as 'meter' | ''}
|
||||
onSignalSourceChange={onSignalSourceChange || ((): void => {})}
|
||||
signalSourceChangeEnabled={signalSourceChangeEnabled}
|
||||
queriesCount={1}
|
||||
@@ -264,28 +266,26 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
signalSource={query.source as 'meter' | ''}
|
||||
onSignalSourceChange={onSignalSourceChange || ((): void => {})}
|
||||
signalSourceChangeEnabled={signalSourceChangeEnabled}
|
||||
queriesCount={currentQuery.builder.queryData.length}
|
||||
queriesCount={activeBuilder.queryData.length}
|
||||
savePreviousQuery={savePreviousQuery}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
|
||||
{!showOnlyWhereClause &&
|
||||
currentQuery.builder.queryFormulas?.length > 0 && (
|
||||
<div className="qb-formulas-container">
|
||||
{currentQuery.builder.queryFormulas.map((formula, index) => {
|
||||
const query =
|
||||
currentQuery.builder.queryData[index] ||
|
||||
currentQuery.builder.queryData[0];
|
||||
{!showOnlyWhereClause && activeBuilder.queryFormulas?.length > 0 && (
|
||||
<div className="qb-formulas-container">
|
||||
{activeBuilder.queryFormulas.map((formula, index) => {
|
||||
const query =
|
||||
activeBuilder.queryData[index] || activeBuilder.queryData[0];
|
||||
|
||||
return (
|
||||
<div key={formula.queryName} className="qb-formula">
|
||||
<Formula query={query} formula={formula} index={index} isQBV2 />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
return (
|
||||
<div key={formula.queryName} className="qb-formula">
|
||||
<Formula query={query} formula={formula} index={index} isQBV2 />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{shouldShowFooter && (
|
||||
<QueryFooter
|
||||
@@ -319,7 +319,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
</div>
|
||||
))}
|
||||
|
||||
{currentQuery.builder.queryFormulas?.map((formula) => (
|
||||
{activeBuilder.queryFormulas?.map((formula) => (
|
||||
<div key={formula.queryName} className="formula-name">
|
||||
{formula.queryName}
|
||||
</div>
|
||||
|
||||
@@ -88,6 +88,9 @@ export function QueryBuilderV2Provider({
|
||||
);
|
||||
}
|
||||
|
||||
export const useIsInQueryBuilderV2 = (): boolean =>
|
||||
useContext(QueryBuilderV2Context) !== undefined;
|
||||
|
||||
export const useQueryBuilderV2Context = (): QueryBuilderV2ContextType => {
|
||||
const context = useContext(QueryBuilderV2Context);
|
||||
if (!context) {
|
||||
|
||||
@@ -12,7 +12,13 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
|
||||
import { get, isEmpty } from 'lodash-es';
|
||||
import { ChevronUp } from '@signozhq/icons';
|
||||
import { Querybuildertypesv5BucketOptionsDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
Querybuildertypesv5BucketOptionsDTO,
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
|
||||
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
|
||||
Querybuildertypesv5QueryEnvelopeTraceOperatorDTOType,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { isLoneBuilderQuery } from 'lib/query/builderEnvelope';
|
||||
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { MetricAggregation } from 'types/api/v5/queryRange';
|
||||
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
@@ -147,10 +153,34 @@ function QueryAddOns({
|
||||
[resolvedFields],
|
||||
);
|
||||
|
||||
// A panel's default limit applies only to a lone query: per-query limits can keep
|
||||
// different groups and break a formula's join.
|
||||
const isLoneQuery = useMemo(
|
||||
() =>
|
||||
isLoneBuilderQuery([
|
||||
...(currentQuery.builder?.queryData ?? [query]).map((data) => ({
|
||||
type:
|
||||
data.builderQueryType ??
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
|
||||
})),
|
||||
...(currentQuery.builder?.queryFormulas ?? []).map(() => ({
|
||||
type: Querybuildertypesv5QueryEnvelopeFormulaDTOType.builder_formula,
|
||||
})),
|
||||
...(currentQuery.builder?.queryTraceOperator ?? []).map(() => ({
|
||||
type:
|
||||
Querybuildertypesv5QueryEnvelopeTraceOperatorDTOType.builder_trace_operator,
|
||||
})),
|
||||
]),
|
||||
[currentQuery.builder, query],
|
||||
);
|
||||
|
||||
const placeholderOf = useCallback(
|
||||
(key: InputAddOnField): string =>
|
||||
resolvedFields.get(key)?.placeholder ?? ADD_ON_DEFINITIONS[key].placeholder,
|
||||
[resolvedFields],
|
||||
(key === QueryBuilderField.Limit && !isLoneQuery
|
||||
? undefined
|
||||
: resolvedFields.get(key)?.placeholder) ??
|
||||
ADD_ON_DEFINITIONS[key].placeholder,
|
||||
[resolvedFields, isLoneQuery],
|
||||
);
|
||||
|
||||
const isDisabled = useCallback(
|
||||
|
||||
@@ -67,7 +67,9 @@ function QueryAggregationOptions({
|
||||
onChange={onChange}
|
||||
queryData={queryData}
|
||||
maxAggregations={
|
||||
panelType === PANEL_TYPES.VALUE || panelType === PANEL_TYPES.PIE
|
||||
panelType === PANEL_TYPES.VALUE ||
|
||||
panelType === PANEL_TYPES.PIE ||
|
||||
panelType === PANEL_TYPES.TOP_LIST
|
||||
? 1
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import CodeMirror, {
|
||||
import { Button, Popover, Tooltip } from 'antd';
|
||||
import { TelemetrytypesFieldDataTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { tracesAggregateOperatorOptions } from 'constants/queryBuilderOperators';
|
||||
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
|
||||
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { Info, TriangleAlert } from '@signozhq/icons';
|
||||
@@ -321,6 +322,7 @@ function QueryAggregationSelect({
|
||||
functionContextForFetch &&
|
||||
OPERATORS_WITHOUT_DATA_TYPE.includes(functionContextForFetch)
|
||||
);
|
||||
const builderQueryType = useBuilderQueryType(queryData);
|
||||
const { data: fieldKeys, isLoading: isLoadingFields } = useFieldKeysSuggestion(
|
||||
{
|
||||
signal: DATA_SOURCE_TO_SIGNAL[queryData.dataSource],
|
||||
@@ -329,7 +331,7 @@ function QueryAggregationSelect({
|
||||
? TelemetrytypesFieldDataTypeDTO.number
|
||||
: undefined,
|
||||
},
|
||||
queryData.builderQueryType,
|
||||
builderQueryType,
|
||||
{
|
||||
enabled:
|
||||
!!functionContextForFetch &&
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useMemo } from 'react';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { Button, Tooltip } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import WarningPopover from 'components/WarningPopover/WarningPopover';
|
||||
@@ -15,28 +16,25 @@ function TraceOperatorSection({
|
||||
addTraceOperator?: () => void;
|
||||
}): JSX.Element {
|
||||
const { currentQuery, panelType } = useQueryBuilder();
|
||||
const activeBuilder = getActiveBuilder(currentQuery);
|
||||
|
||||
const showTraceOperatorWarning = useMemo(() => {
|
||||
const isRawQueryPanel =
|
||||
panelType === PANEL_TYPES.LIST || panelType === PANEL_TYPES.TRACE;
|
||||
const hasMultipleQueries = currentQuery.builder.queryData.length > 1;
|
||||
const hasMultipleQueries = activeBuilder.queryData.length > 1;
|
||||
const hasTraceOperator =
|
||||
currentQuery.builder.queryTraceOperator &&
|
||||
currentQuery.builder.queryTraceOperator.length > 0;
|
||||
activeBuilder.queryTraceOperator &&
|
||||
activeBuilder.queryTraceOperator.length > 0;
|
||||
return isRawQueryPanel && hasMultipleQueries && !hasTraceOperator;
|
||||
}, [
|
||||
currentQuery?.builder?.queryData,
|
||||
currentQuery?.builder?.queryTraceOperator,
|
||||
panelType,
|
||||
]);
|
||||
}, [activeBuilder.queryData, activeBuilder.queryTraceOperator, panelType]);
|
||||
|
||||
const traceOperatorWarning = useMemo(() => {
|
||||
if (currentQuery.builder.queryData.length === 0) {
|
||||
if (activeBuilder.queryData.length === 0) {
|
||||
return '';
|
||||
}
|
||||
const firstQuery = currentQuery.builder.queryData[0];
|
||||
const firstQuery = activeBuilder.queryData[0];
|
||||
return `Currently, you are only seeing results from query ${firstQuery.queryName}. Add a trace operator to combine results of multiple queries.`;
|
||||
}, [currentQuery]);
|
||||
}, [activeBuilder.queryData]);
|
||||
return (
|
||||
<div className="qb-trace-operator-button-container">
|
||||
<Tooltip
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
queryOperatorSuggestions,
|
||||
} from 'constants/antlrQueryConstants';
|
||||
import { useDynamicVariableSuggestions } from 'hooks/dashboard/useDynamicVariableSuggestions';
|
||||
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import useDebounce from 'hooks/useDebounce';
|
||||
import { debounce, isNull } from 'lodash-es';
|
||||
@@ -148,6 +149,7 @@ function QuerySearch({
|
||||
metricNamespace,
|
||||
valueSuggestionsOverride,
|
||||
}: QuerySearchProps): JSX.Element {
|
||||
const builderQueryType = useBuilderQueryType(queryData);
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const [valueSuggestions, setValueSuggestions] = useState<any[]>([]);
|
||||
const [activeKey, setActiveKey] = useState<string>('');
|
||||
@@ -359,7 +361,7 @@ function QuerySearch({
|
||||
source: signalSource as TelemetrytypesSourceDTO,
|
||||
metricNamespace,
|
||||
},
|
||||
queryData.builderQueryType,
|
||||
builderQueryType,
|
||||
);
|
||||
|
||||
if (response.data.keys) {
|
||||
@@ -397,7 +399,7 @@ function QuerySearch({
|
||||
hardcodedAttributeKeys,
|
||||
showFilterSuggestionsWithoutMetric,
|
||||
metricNamespace,
|
||||
queryData.builderQueryType,
|
||||
builderQueryType,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -539,7 +541,7 @@ function QuerySearch({
|
||||
source: signalSource as TelemetrytypesSourceDTO,
|
||||
metricName: debouncedMetricName ?? undefined,
|
||||
},
|
||||
queryData.builderQueryType,
|
||||
builderQueryType,
|
||||
).then((response) => {
|
||||
const responseData = response.data;
|
||||
const responseDataValues = responseData.values;
|
||||
@@ -642,7 +644,7 @@ function QuerySearch({
|
||||
signalSource,
|
||||
toggleSuggestions,
|
||||
valueSuggestionsOverride,
|
||||
queryData.builderQueryType,
|
||||
builderQueryType,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import { ENTITY_VERSION_V4, ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import QBEntityOptions from 'container/QueryBuilder/components/QBEntityOptions/QBEntityOptions';
|
||||
import { QueryProps } from 'container/QueryBuilder/type';
|
||||
import SpanScopeSelector from 'container/QueryBuilder/filters/QueryBuilderSearchV2/SpanScopeSelector';
|
||||
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
|
||||
import { Copy, Ellipsis, Trash } from '@signozhq/icons';
|
||||
@@ -62,7 +63,8 @@ export const QueryV2 = forwardRef(function QueryV2(
|
||||
const { cloneQuery, panelType } = useQueryBuilder();
|
||||
|
||||
const hasQueryFunctions = query?.functions?.length > 0;
|
||||
const { dataSource, builderQueryType } = query;
|
||||
const { dataSource } = query;
|
||||
const builderQueryType = useBuilderQueryType(query);
|
||||
|
||||
const [isCollapsed, setIsCollapsed] = useState(false);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
/* eslint-disable sonarjs/no-identical-functions */
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import {
|
||||
autocompletion,
|
||||
closeCompletion,
|
||||
@@ -87,17 +88,18 @@ function TraceOperatorEditor({
|
||||
const [isExternalQueryChange, setIsExternalQueryChange] = useState(false);
|
||||
const [lastExternalValue, setLastExternalValue] = useState<string>('');
|
||||
const { currentQuery } = useQueryBuilder();
|
||||
const activeBuilder = getActiveBuilder(currentQuery);
|
||||
|
||||
const queryOptions = useMemo(
|
||||
() =>
|
||||
currentQuery.builder.queryData
|
||||
activeBuilder.queryData
|
||||
.filter((query) => query.dataSource === DataSource.TRACES) // Only show trace queries
|
||||
.map((query) => ({
|
||||
label: query.queryName,
|
||||
type: 'atom',
|
||||
apply: query.queryName,
|
||||
})),
|
||||
[currentQuery.builder.queryData],
|
||||
[activeBuilder.queryData],
|
||||
);
|
||||
|
||||
const toggleSuggestions = useCallback(
|
||||
|
||||
@@ -10,7 +10,11 @@ import { ENVIRONMENT } from 'constants/env';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import { QueryBuilderV2Provider } from '../../QueryBuilderV2Context';
|
||||
import QueryAggregationSelect from '../QueryAggregation/QueryAggregationSelect';
|
||||
@@ -107,12 +111,18 @@ beforeEach(() => {
|
||||
);
|
||||
});
|
||||
|
||||
async function enterAggregation(text: string): Promise<void> {
|
||||
async function enterAggregation(
|
||||
text: string,
|
||||
queryData: IBuilderQuery = aiQuery,
|
||||
currentQuery?: Query,
|
||||
): Promise<void> {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(
|
||||
<QueryBuilderV2Provider>
|
||||
<QueryAggregationSelect queryData={aiQuery} />
|
||||
<QueryAggregationSelect queryData={queryData} />
|
||||
</QueryBuilderV2Provider>,
|
||||
undefined,
|
||||
{ queryBuilderOverrides: currentQuery && { currentQuery } },
|
||||
);
|
||||
|
||||
const content = (
|
||||
@@ -165,4 +175,26 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
|
||||
},
|
||||
TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'uses the AI keys endpoint for an untagged query on the AI query type',
|
||||
async () => {
|
||||
await enterAggregation(
|
||||
'avg(',
|
||||
{ ...aiQuery, builderQueryType: undefined },
|
||||
{ ...initialQueriesMap.traces, queryType: EQueryType.AI_QUERY_BUILDER },
|
||||
);
|
||||
|
||||
await waitFor(
|
||||
() =>
|
||||
expect(suggestionLabels()).toStrictEqual([
|
||||
'duration_nano',
|
||||
'trace.total_tokens',
|
||||
]),
|
||||
{ timeout: SUGGESTIONS_TIMEOUT_MS },
|
||||
);
|
||||
expect(keysRequests).toHaveLength(0);
|
||||
},
|
||||
TEST_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
/* 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';
|
||||
@@ -171,6 +170,25 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
const renderQueryV2 = (queriesCount: number): void => {
|
||||
const [queryA] = (baseQBContext.currentQuery as Query).builder.queryData;
|
||||
render(
|
||||
<QueryBuilderV2Provider>
|
||||
<QueryV2
|
||||
index={0}
|
||||
query={queryA}
|
||||
version="v4"
|
||||
isAvailableToDisable={false}
|
||||
isMultiQueryAllowed
|
||||
queriesCount={queriesCount}
|
||||
onSignalSourceChange={jest.fn()}
|
||||
signalSourceChangeEnabled={false}
|
||||
savePreviousQuery={false}
|
||||
/>
|
||||
</QueryBuilderV2Provider>,
|
||||
);
|
||||
};
|
||||
|
||||
it('renders limit input when dataSource is logs', () => {
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
@@ -184,43 +202,37 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
expect(limitInput).toHaveAttribute('data-testid', 'input-Limit');
|
||||
});
|
||||
|
||||
it('Cmd+Enter on an input triggers handleRunQuery via container handler', async () => {
|
||||
it('Cmd+Enter on the limit input triggers handleRunQuery via container handler', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
const limitInput = screen.getByPlaceholderText('Enter limit');
|
||||
fireEvent.keyDown(limitInput, {
|
||||
key: 'Enter',
|
||||
code: 'Enter',
|
||||
metaKey: true,
|
||||
});
|
||||
screen.getByTestId('input-Limit').focus();
|
||||
await user.keyboard('{Meta>}{Enter}{/Meta}');
|
||||
|
||||
expect(handleRunQueryMock).toHaveBeenCalled();
|
||||
expect(handleRunQueryMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
const legendInput = screen.getByPlaceholderText('Write legend format');
|
||||
fireEvent.keyDown(legendInput, {
|
||||
key: 'Enter',
|
||||
code: 'Enter',
|
||||
metaKey: true,
|
||||
});
|
||||
it('Cmd+Enter on the legend input triggers handleRunQuery via container handler', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
expect(handleRunQueryMock).toHaveBeenCalled();
|
||||
screen.getByPlaceholderText('Write legend format').focus();
|
||||
await user.keyboard('{Meta>}{Enter}{/Meta}');
|
||||
|
||||
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
|
||||
// Wait for CodeMirror to initialize
|
||||
await waitFor(() => {
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(editor).toBeInTheDocument();
|
||||
});
|
||||
expect(handleRunQueryMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
await userEvent.click(editor);
|
||||
fireEvent.keyDown(editor, {
|
||||
key: 'Enter',
|
||||
code: 'Enter',
|
||||
metaKey: true,
|
||||
});
|
||||
it('Cmd+Enter in the where clause editor triggers handleRunQuery via container handler', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
expect(handleRunQueryMock).toHaveBeenCalled();
|
||||
const editor = (
|
||||
await screen.findByTestId('query-where-clause-editor')
|
||||
).querySelector('.cm-content') as HTMLElement;
|
||||
editor.focus();
|
||||
await user.keyboard('{Meta>}{Enter}{/Meta}');
|
||||
|
||||
expect(handleRunQueryMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not crash when builder.queryFormulas/queryTraceOperator are missing (partial/legacy query)', () => {
|
||||
@@ -250,15 +262,12 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
});
|
||||
|
||||
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" />);
|
||||
const user = userEvent.setup();
|
||||
renderQueryV2(1);
|
||||
|
||||
await openQueryActions();
|
||||
await userEvent.click(
|
||||
await user.click(screen.getByTestId('query-actions'));
|
||||
await user.click(
|
||||
await screen.findByTestId('query-actions-item-clone-query'),
|
||||
);
|
||||
|
||||
@@ -270,9 +279,10 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
});
|
||||
|
||||
it('hides Delete when there is a single query', async () => {
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
const user = userEvent.setup();
|
||||
renderQueryV2(1);
|
||||
|
||||
await openQueryActions();
|
||||
await user.click(screen.getByTestId('query-actions'));
|
||||
await screen.findByTestId('query-actions-item-clone-query');
|
||||
|
||||
expect(
|
||||
@@ -281,39 +291,26 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
});
|
||||
|
||||
it('shows Delete with more than one query and deletes on click', async () => {
|
||||
const [queryA] = (baseQBContext.currentQuery as Query).builder.queryData;
|
||||
const user = userEvent.setup();
|
||||
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>,
|
||||
);
|
||||
renderQueryV2(2);
|
||||
|
||||
await openQueryActions();
|
||||
await userEvent.click(
|
||||
await user.click(screen.getByTestId('query-actions'));
|
||||
await user.click(
|
||||
await screen.findByTestId('query-actions-item-delete-query'),
|
||||
);
|
||||
|
||||
expect(handleDeleteQuery).toHaveBeenCalledTimes(1);
|
||||
}, 15000);
|
||||
});
|
||||
});
|
||||
|
||||
it('fx button is disabled when functions already exist', () => {
|
||||
it('fx button is disabled when functions already exist', async () => {
|
||||
const user = userEvent.setup();
|
||||
const currentQueryBase = baseQBContext.currentQuery as Query;
|
||||
const supersetQueryBase = baseQBContext.supersetQuery as Query;
|
||||
|
||||
@@ -359,9 +356,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
'.query-function-delete-btn',
|
||||
) as HTMLButtonElement;
|
||||
expect(deleteButton).toBeInTheDocument();
|
||||
userEvent.click(deleteButton);
|
||||
waitFor(() => {
|
||||
expect(fxButton).not.toBeDisabled();
|
||||
});
|
||||
await user.click(deleteButton);
|
||||
expect(fxButton).not.toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ const SCALAR_PANEL_TYPES: ReadonlySet<string> = new Set<string>([
|
||||
PANEL_TYPES.PIE,
|
||||
PANEL_TYPES.VALUE,
|
||||
PANEL_TYPES.GEO_MAP,
|
||||
PANEL_TYPES.TOP_LIST,
|
||||
]);
|
||||
|
||||
export function isScalarPanelType(panelType?: string | null): boolean {
|
||||
|
||||
@@ -15,6 +15,9 @@ import QueryAddOns from '../QueryV2/QueryAddOns/QueryAddOns';
|
||||
// Mocks: only what is required for this component to render and for us to assert handler calls
|
||||
const mockHandleChangeQueryData = jest.fn();
|
||||
const mockHandleSetQueryData = jest.fn();
|
||||
let mockCurrentQuery: { unit: string | undefined; builder?: unknown } = {
|
||||
unit: undefined,
|
||||
};
|
||||
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilderOperations', () => ({
|
||||
useQueryOperations: (): {
|
||||
@@ -27,10 +30,10 @@ jest.mock('hooks/queryBuilder/useQueryBuilderOperations', () => ({
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: (): {
|
||||
handleSetQueryData: typeof mockHandleSetQueryData;
|
||||
currentQuery: { unit: string | undefined };
|
||||
currentQuery: typeof mockCurrentQuery;
|
||||
} => ({
|
||||
handleSetQueryData: mockHandleSetQueryData,
|
||||
currentQuery: { unit: undefined },
|
||||
currentQuery: mockCurrentQuery,
|
||||
}),
|
||||
}));
|
||||
|
||||
@@ -229,6 +232,77 @@ describe('QueryAddOns', () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe('a pinned limit with a default', () => {
|
||||
const renderPinnedLimit = (): void => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery()}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.TOP_LIST}
|
||||
index={0}
|
||||
fieldsConfig={{
|
||||
[QueryBuilderField.Limit]: {
|
||||
state: 'pinned',
|
||||
placeholder: 'Default 10',
|
||||
},
|
||||
}}
|
||||
isForTraceOperator={false}
|
||||
/>,
|
||||
);
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
mockCurrentQuery = { unit: undefined };
|
||||
});
|
||||
|
||||
it('is open with its default as the placeholder', () => {
|
||||
renderPinnedLimit();
|
||||
|
||||
expect(screen.getByTestId('input-Limit')).toHaveAttribute(
|
||||
'placeholder',
|
||||
'Default 10',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the default for an AI query, which the request leaves unlimited', () => {
|
||||
mockCurrentQuery = {
|
||||
unit: undefined,
|
||||
builder: {
|
||||
queryData: [{ ...baseQuery(), builderQueryType: 'builder_ai_query' }],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
};
|
||||
|
||||
renderPinnedLimit();
|
||||
|
||||
expect(screen.getByTestId('input-Limit')).toHaveAttribute(
|
||||
'placeholder',
|
||||
'Enter limit',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the default once a formula joins the query', () => {
|
||||
mockCurrentQuery = {
|
||||
unit: undefined,
|
||||
builder: {
|
||||
queryData: [baseQuery()],
|
||||
queryFormulas: [{ expression: 'A * 2' }],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
};
|
||||
|
||||
renderPinnedLimit();
|
||||
|
||||
expect(screen.getByTestId('input-Limit')).toHaveAttribute(
|
||||
'placeholder',
|
||||
'Enter limit',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('auto-opens Order By and Limit when present in query', () => {
|
||||
const query = baseQuery({
|
||||
orderBy: [{ columnName: 'duration', order: 'desc' }],
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import {
|
||||
initialQueriesMap,
|
||||
initialQueryAIWithType,
|
||||
PANEL_TYPES,
|
||||
} from 'constants/queryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import { QueryBuilderV2 } from '../QueryBuilderV2';
|
||||
|
||||
jest.mock('../QueryV2/QueryV2', () => ({
|
||||
QueryV2: ({ query }: { query: IBuilderQuery }): JSX.Element => (
|
||||
<div data-testid="query-v2">{query.queryName}</div>
|
||||
),
|
||||
}));
|
||||
jest.mock('../QueryV2/QueryFooter/QueryFooter', () => (): null => null);
|
||||
|
||||
function renderWith(currentQuery: Query): void {
|
||||
render(
|
||||
<QueryBuilderV2 panelType={PANEL_TYPES.TIME_SERIES} version="v3" />,
|
||||
undefined,
|
||||
{
|
||||
queryBuilderOverrides: {
|
||||
currentQuery,
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
initialDataSource: null,
|
||||
handleSetConfig: jest.fn(),
|
||||
addNewBuilderQuery: jest.fn(),
|
||||
addNewFormula: jest.fn(),
|
||||
addTraceOperator: jest.fn(),
|
||||
handleRunQuery: jest.fn(),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const builderWithQuery = (
|
||||
builder: Query['builder'],
|
||||
queryName: string,
|
||||
): Query['builder'] => ({
|
||||
...builder,
|
||||
queryData: [{ ...builder.queryData[0], queryName }],
|
||||
});
|
||||
|
||||
const query: Query = {
|
||||
...initialQueriesMap.metrics,
|
||||
builder: builderWithQuery(initialQueriesMap.metrics.builder, 'MAIN'),
|
||||
builder_ai_query: builderWithQuery(
|
||||
getActiveBuilder(initialQueryAIWithType),
|
||||
'AI',
|
||||
),
|
||||
};
|
||||
|
||||
describe('QueryBuilderV2 builder slot', () => {
|
||||
it('renders the AI slot when AI is the query type', () => {
|
||||
renderWith({ ...query, queryType: EQueryType.AI_QUERY_BUILDER });
|
||||
|
||||
expect(screen.getByTestId('query-v2')).toHaveTextContent('AI');
|
||||
});
|
||||
|
||||
it('renders builder when Query Builder is the query type', () => {
|
||||
renderWith(query);
|
||||
|
||||
expect(screen.getByTestId('query-v2')).toHaveTextContent('MAIN');
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { render } from 'tests/test-utils';
|
||||
import { QueryMode } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { QueryBuilderV2 } from '../QueryBuilderV2';
|
||||
@@ -19,7 +19,7 @@ const aiQuery: Query = {
|
||||
...initialQueriesMap.traces.builder,
|
||||
queryData: initialQueriesMap.traces.builder.queryData.map((query) => ({
|
||||
...query,
|
||||
builderQueryType: QueryMode.AI_QUERY_BUILDER,
|
||||
builderQueryType: EQueryType.AI_QUERY_BUILDER,
|
||||
})),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { negateOperator, OPERATORS } from 'constants/antlrQueryConstants';
|
||||
import { initialQueryBuilderFormValuesMap } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { Query, TagFilter } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
import { extractQueryPairs } from 'utils/queryContextUtils';
|
||||
|
||||
import {
|
||||
adjustQueryForV5,
|
||||
convertAggregationToExpression,
|
||||
convertExpressionToFilters,
|
||||
convertFiltersToExpression,
|
||||
@@ -1684,3 +1687,31 @@ describe('formatValueForExpression', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('adjustQueryForV5', () => {
|
||||
it('adjusts the AI builder slot for AI query builder queries', () => {
|
||||
const emptyBuilder = {
|
||||
queryData: [],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
};
|
||||
const query: Query = {
|
||||
id: 'q',
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
promql: [],
|
||||
clickhouse_sql: [],
|
||||
builder: emptyBuilder,
|
||||
builder_ai_query: {
|
||||
...emptyBuilder,
|
||||
queryData: [initialQueryBuilderFormValuesMap.logs],
|
||||
},
|
||||
};
|
||||
|
||||
const result = adjustQueryForV5(query);
|
||||
|
||||
expect(result.builder).toBe(emptyBuilder);
|
||||
expect(result.builder_ai_query?.queryData[0]).not.toHaveProperty(
|
||||
'aggregateOperator',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
@@ -20,7 +21,8 @@ export function useSyncQueryBuilderFields(
|
||||
fields: SyncedQueryBuilderField[] = NO_FIELDS,
|
||||
): void {
|
||||
const { currentQuery, handleSetQueryData } = useQueryBuilder();
|
||||
const queries = currentQuery.builder.queryData;
|
||||
const activeBuilder = getActiveBuilder(currentQuery);
|
||||
const queries = activeBuilder.queryData;
|
||||
const previousRef = useRef<Map<string, IBuilderQuery>>();
|
||||
const enabled = fields.length > 0;
|
||||
|
||||
|
||||
@@ -9,6 +9,11 @@ import {
|
||||
QUERY_BUILDER_FUNCTIONS,
|
||||
} from 'constants/antlrQueryConstants';
|
||||
import { getOperatorValue } from 'container/QueryBuilder/filters/QueryBuilderSearchV2/utils';
|
||||
import {
|
||||
getActiveBuilder,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
isBuilderQueryType,
|
||||
} from 'lib/query/builderSlot';
|
||||
import FilterQueryLexer from 'parser/FilterQueryLexer';
|
||||
import FilterQueryParser, {
|
||||
AndExpressionContext,
|
||||
@@ -33,7 +38,6 @@ import {
|
||||
MetricAggregation,
|
||||
TraceAggregation,
|
||||
} from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
import { extractQueryPairs } from 'utils/queryContextUtils';
|
||||
import { isQuoted, unquote } from 'utils/stringUtils';
|
||||
@@ -1030,8 +1034,9 @@ export function getQueryLabelWithAggregation(
|
||||
}
|
||||
|
||||
export const adjustQueryForV5 = (currentQuery: Query): Query => {
|
||||
if (currentQuery.queryType === EQueryType.QUERY_BUILDER) {
|
||||
const newQueryData = currentQuery.builder.queryData.map((query) => {
|
||||
if (isBuilderQueryType(currentQuery.queryType)) {
|
||||
const activeBuilder = getActiveBuilder(currentQuery);
|
||||
const newQueryData = activeBuilder.queryData.map((query) => {
|
||||
const aggregations = query.aggregations?.map((aggregation) => {
|
||||
if (query.dataSource === DataSource.METRICS) {
|
||||
const metricAggregation = aggregation as MetricAggregation;
|
||||
@@ -1072,8 +1077,8 @@ export const adjustQueryForV5 = (currentQuery: Query): Query => {
|
||||
|
||||
return {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
[getBuilderSlotKeyForQueryType(currentQuery.queryType)]: {
|
||||
...activeBuilder,
|
||||
queryData: newQueryData,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4,6 +4,8 @@ function QueryTypeTag({ queryType }: IQueryTypeTagProps): JSX.Element {
|
||||
switch (queryType) {
|
||||
case EQueryType.QUERY_BUILDER:
|
||||
return <span>Query Builder</span>;
|
||||
case EQueryType.AI_QUERY_BUILDER:
|
||||
return <span>AI Query Builder</span>;
|
||||
|
||||
case EQueryType.CLICKHOUSE:
|
||||
return <span>ClickHouse Query</span>;
|
||||
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
convertFiltersToExpressionWithExistingQuery,
|
||||
} from 'components/QueryBuilderV2/utils';
|
||||
import { QuickFiltersSource } from 'components/QuickFilters/types';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import {
|
||||
Query,
|
||||
TagFilter,
|
||||
@@ -556,3 +558,50 @@ describe('clearFilterFromQuery', () => {
|
||||
expect(active.filter?.expression).toBe(`http.method = 'GET'`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('quick filters on an AI query', () => {
|
||||
const builderQuery = buildQuery([], '').builder;
|
||||
const aiQuery: Query = {
|
||||
...initialQueriesMap.traces,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder: builderQuery,
|
||||
builder_ai_query: buildQuery(
|
||||
[{ key: KEY, op: 'in', value: ['a'] }],
|
||||
`${KEY} IN ['a']`,
|
||||
).builder,
|
||||
};
|
||||
|
||||
it('a checkbox toggle writes into the AI slot and leaves builder alone', () => {
|
||||
const result = applyCheckboxToggle({
|
||||
currentQuery: aiQuery,
|
||||
activeQueryIndex: 0,
|
||||
filter: { attributeKey: { key: KEY, type: 'tag' } } as never,
|
||||
quickFilterSource: QuickFiltersSource.AI_OBSERVABILITY,
|
||||
attributeValues: ['a', 'b', 'c'],
|
||||
value: 'b',
|
||||
checked: true,
|
||||
isOnlyOrAllClicked: false,
|
||||
});
|
||||
|
||||
expect(result.builder).toBe(builderQuery);
|
||||
expect(
|
||||
result.builder_ai_query?.queryData[0].filters?.items.map(
|
||||
(item) => item.value,
|
||||
),
|
||||
).toStrictEqual([['a', 'b']]);
|
||||
});
|
||||
|
||||
it('clearing a filter clears it from the AI slot', () => {
|
||||
const result = clearFilterFromQuery({
|
||||
currentQuery: aiQuery,
|
||||
filterKey: KEY,
|
||||
activeQueryIndex: 0,
|
||||
});
|
||||
|
||||
expect(result.builder).toBe(builderQuery);
|
||||
expect(result.builder_ai_query?.queryData[0].filters?.items).toStrictEqual(
|
||||
[],
|
||||
);
|
||||
expect(result.builder_ai_query?.queryData[0].filter?.expression).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,6 +10,11 @@ import {
|
||||
import { OPERATORS } from 'constants/antlrQueryConstants';
|
||||
import { getOperatorValue } from 'container/QueryBuilder/filters/QueryBuilderSearchV2/utils';
|
||||
import { cloneDeep, isArray } from 'lodash-es';
|
||||
import {
|
||||
getBuilderBySlotKey,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
replaceBuilderBySlotKey,
|
||||
} from 'lib/query/builderSlot';
|
||||
import { Query, TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
@@ -157,8 +162,10 @@ export function applyCheckboxToggle({
|
||||
previousState?: CheckedState;
|
||||
sectionType?: SectionType;
|
||||
}): Query {
|
||||
const slotKey = getBuilderSlotKeyForQueryType(currentQuery.queryType);
|
||||
const activeBuilder = getBuilderBySlotKey(currentQuery, slotKey);
|
||||
const activeItems =
|
||||
currentQuery.builder.queryData?.[activeQueryIndex]?.filters?.items;
|
||||
activeBuilder.queryData?.[activeQueryIndex]?.filters?.items;
|
||||
|
||||
const isSomeFilterPresentForCurrentAttribute = !!activeItems?.some((item) =>
|
||||
isKeyMatch(item.key?.key, filter.attributeKey.key),
|
||||
@@ -173,7 +180,7 @@ export function applyCheckboxToggle({
|
||||
const isMultipleValuesTrueForTheKey =
|
||||
Object.values(currentFilterState).filter((val) => val).length > 1;
|
||||
|
||||
const query = cloneDeep(currentQuery.builder.queryData?.[activeQueryIndex]);
|
||||
const query = cloneDeep(activeBuilder.queryData?.[activeQueryIndex]);
|
||||
|
||||
// if only or all are clicked we do not need to worry about anything just override whatever we have
|
||||
// by either adding a new IN operator value clause in case of ONLY or remove everything we have for ALL.
|
||||
@@ -430,18 +437,15 @@ export function applyCheckboxToggle({
|
||||
query.filters = synced.filters;
|
||||
}
|
||||
|
||||
return {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: [
|
||||
...currentQuery.builder.queryData.map((q, idx) => {
|
||||
if (idx === activeQueryIndex) {
|
||||
return query;
|
||||
}
|
||||
return q;
|
||||
}),
|
||||
],
|
||||
},
|
||||
};
|
||||
return replaceBuilderBySlotKey(currentQuery, slotKey, {
|
||||
...activeBuilder,
|
||||
queryData: [
|
||||
...activeBuilder.queryData.map((q, idx) => {
|
||||
if (idx === activeQueryIndex) {
|
||||
return query;
|
||||
}
|
||||
return q;
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { IQuickFiltersConfig } from 'components/QuickFilters/types';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
|
||||
import { DEFAULT_VISIBLE_ITEMS_COUNT } from './constants';
|
||||
import { isKeyMatch } from './utils';
|
||||
@@ -37,12 +38,13 @@ function useCheckboxDisclosure({
|
||||
DEFAULT_VISIBLE_ITEMS_COUNT,
|
||||
);
|
||||
|
||||
const { queryData } = getActiveBuilder(currentQuery);
|
||||
const isSomeFilterPresentForCurrentAttribute = useMemo(
|
||||
() =>
|
||||
!!currentQuery.builder.queryData?.[activeQueryIndex]?.filters?.items?.some(
|
||||
(item) => isKeyMatch(item.key?.key, filter.attributeKey.key),
|
||||
!!queryData?.[activeQueryIndex]?.filters?.items?.some((item) =>
|
||||
isKeyMatch(item.key?.key, filter.attributeKey.key),
|
||||
),
|
||||
[currentQuery.builder.queryData, activeQueryIndex, filter.attributeKey.key],
|
||||
[queryData, activeQueryIndex, filter.attributeKey.key],
|
||||
);
|
||||
|
||||
const isOpen = useMemo(() => {
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
QuickFiltersSource,
|
||||
} from 'components/QuickFilters/types';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { isEqual, isFunction } from 'lodash-es';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
@@ -77,7 +78,7 @@ function useCheckboxFilterActions({
|
||||
dispatch(updatedQuery);
|
||||
|
||||
if (onQuickFilterChange) {
|
||||
const queryData = updatedQuery.builder.queryData[activeQueryIndex];
|
||||
const queryData = getActiveBuilder(updatedQuery).queryData[activeQueryIndex];
|
||||
const expression = queryData?.filter?.expression || '';
|
||||
const filterItemKeys = (queryData?.filters?.items || [])
|
||||
.map((item) => item.key?.key)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useMemo } from 'react';
|
||||
import { IQuickFiltersConfig } from 'components/QuickFilters/types';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
|
||||
import { deriveCheckboxState } from './checkboxFilterQuery';
|
||||
import { isKeyMatch } from './utils';
|
||||
@@ -31,33 +32,28 @@ function useCheckboxFilterState({
|
||||
activeQueryIndex,
|
||||
}: UseCheckboxFilterStateProps): UseCheckboxFilterStateReturn {
|
||||
const { currentQuery } = useQueryBuilder();
|
||||
const activeQueryData = currentQuery
|
||||
? getActiveBuilder(currentQuery).queryData
|
||||
: undefined;
|
||||
|
||||
// derive the state of each filter key here and keep it in sync with current query
|
||||
const currentFilterState = useMemo(
|
||||
() =>
|
||||
deriveCheckboxState({
|
||||
attributeValues,
|
||||
filterItems:
|
||||
currentQuery?.builder.queryData?.[activeQueryIndex]?.filters?.items,
|
||||
filterItems: activeQueryData?.[activeQueryIndex]?.filters?.items,
|
||||
filterKey: filter.attributeKey.key,
|
||||
}),
|
||||
[
|
||||
attributeValues,
|
||||
currentQuery?.builder.queryData,
|
||||
filter.attributeKey,
|
||||
activeQueryIndex,
|
||||
],
|
||||
[attributeValues, activeQueryData, filter.attributeKey, activeQueryIndex],
|
||||
);
|
||||
|
||||
// disable the filter when there are multiple entries of the same attribute key present in the filter bar
|
||||
const isFilterDisabled = useMemo(
|
||||
() =>
|
||||
(currentQuery?.builder?.queryData?.[
|
||||
activeQueryIndex
|
||||
]?.filters?.items?.filter((item) =>
|
||||
(activeQueryData?.[activeQueryIndex]?.filters?.items?.filter((item) =>
|
||||
isKeyMatch(item.key?.key, filter.attributeKey.key),
|
||||
)?.length || 0) > 1,
|
||||
[currentQuery?.builder?.queryData, activeQueryIndex, filter.attributeKey],
|
||||
[activeQueryData, activeQueryIndex, filter.attributeKey],
|
||||
);
|
||||
|
||||
// whether the current filter has multiple values to its name in the key op value section
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from 'components/QuickFilters/types';
|
||||
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import useDebouncedFn from 'hooks/useDebouncedFunction';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
@@ -128,18 +129,15 @@ export default function CheckboxFilterV2(
|
||||
onToggleOpen();
|
||||
};
|
||||
|
||||
const activeQueryData = currentQuery
|
||||
? getActiveBuilder(currentQuery).queryData
|
||||
: undefined;
|
||||
const currentFilterOp = useMemo(() => {
|
||||
const filterSync = currentQuery?.builder.queryData?.[
|
||||
activeQueryIndex
|
||||
]?.filters?.items.find((item) =>
|
||||
isKeyMatch(item.key?.key, filter.attributeKey.key),
|
||||
const filterSync = activeQueryData?.[activeQueryIndex]?.filters?.items.find(
|
||||
(item) => isKeyMatch(item.key?.key, filter.attributeKey.key),
|
||||
);
|
||||
return filterSync?.op;
|
||||
}, [
|
||||
currentQuery?.builder.queryData,
|
||||
activeQueryIndex,
|
||||
filter.attributeKey.key,
|
||||
]);
|
||||
}, [activeQueryData, activeQueryIndex, filter.attributeKey.key]);
|
||||
|
||||
const isNotInOperator = NON_SELECTED_OPERATORS.includes(currentFilterOp || '');
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
|
||||
import { QuickFilterCheckboxUseFieldApis } from 'components/QuickFilters/types';
|
||||
|
||||
@@ -18,6 +19,9 @@ export function useExistingQuery({
|
||||
activeQueryIndex,
|
||||
}: UseExistingQueryParams): UseExistingQueryResult {
|
||||
const { stagedQuery } = useQueryBuilder();
|
||||
const stagedQueryData = stagedQuery
|
||||
? getActiveBuilder(stagedQuery).queryData
|
||||
: undefined;
|
||||
|
||||
const existingQuery = useMemo(() => {
|
||||
if (useFieldApis.existingQuery === null) {
|
||||
@@ -28,7 +32,7 @@ export function useExistingQuery({
|
||||
return useFieldApis.existingQuery;
|
||||
}
|
||||
|
||||
const queryData = stagedQuery?.builder.queryData?.[activeQueryIndex];
|
||||
const queryData = stagedQueryData?.[activeQueryIndex];
|
||||
|
||||
// Prefer V5 filter.expression
|
||||
if (queryData?.filter?.expression) {
|
||||
@@ -41,21 +45,17 @@ export function useExistingQuery({
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [
|
||||
useFieldApis.existingQuery,
|
||||
stagedQuery?.builder.queryData,
|
||||
activeQueryIndex,
|
||||
]);
|
||||
}, [useFieldApis.existingQuery, stagedQueryData, activeQueryIndex]);
|
||||
|
||||
// Check if ANY filters exist in query (V3 items or V5 expression)
|
||||
// This is separate from existingQuery because existingQuery can be explicitly
|
||||
// disabled (null) while filters still exist in the query for UI purposes
|
||||
const hasExistingQuery = useMemo(() => {
|
||||
const queryData = stagedQuery?.builder.queryData?.[activeQueryIndex];
|
||||
const queryData = stagedQueryData?.[activeQueryIndex];
|
||||
const hasV3Items = (queryData?.filters?.items?.length ?? 0) > 0;
|
||||
const hasV5Expression = !!queryData?.filter?.expression;
|
||||
return hasV3Items || hasV5Expression || !!existingQuery;
|
||||
}, [stagedQuery?.builder.queryData, activeQueryIndex, existingQuery]);
|
||||
}, [stagedQueryData, activeQueryIndex, existingQuery]);
|
||||
|
||||
return { existingQuery, hasExistingQuery };
|
||||
}
|
||||
|
||||
@@ -9,6 +9,12 @@ import {
|
||||
import { getMs } from 'utils/timeUtils';
|
||||
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import {
|
||||
getActiveBuilder,
|
||||
getBuilderBySlotKey,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
replaceBuilderBySlotKey,
|
||||
} from 'lib/query/builderSlot';
|
||||
import { cloneDeep, isArray, isEqual, isFunction } from 'lodash-es';
|
||||
import {
|
||||
AllTraceFilterKeys,
|
||||
@@ -57,7 +63,8 @@ function Duration({
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
const syncSelectedFilters = useMemo((): FilterType => {
|
||||
const filters =
|
||||
compositeQuery?.builder.queryData?.[activeQueryIndex]?.filters;
|
||||
compositeQuery &&
|
||||
getActiveBuilder(compositeQuery).queryData?.[activeQueryIndex]?.filters;
|
||||
if (!filters) {
|
||||
return {} as FilterType;
|
||||
}
|
||||
@@ -183,49 +190,51 @@ function Duration({
|
||||
};
|
||||
|
||||
const removeFilterItemIds = (query: Query): Query => {
|
||||
const clonedQuery = cloneDeep(query);
|
||||
clonedQuery.builder.queryData = clonedQuery.builder.queryData.map((data) => ({
|
||||
...data,
|
||||
filters: {
|
||||
...data.filters,
|
||||
items:
|
||||
data.filters?.items?.map((item) => ({
|
||||
...item,
|
||||
id: '',
|
||||
})) || [],
|
||||
op: data.filters?.op || 'AND',
|
||||
},
|
||||
}));
|
||||
return clonedQuery;
|
||||
const slotKey = getBuilderSlotKeyForQueryType(query.queryType);
|
||||
const activeBuilder = getBuilderBySlotKey(query, slotKey);
|
||||
return replaceBuilderBySlotKey(cloneDeep(query), slotKey, {
|
||||
...activeBuilder,
|
||||
queryData: activeBuilder.queryData.map((data) => ({
|
||||
...data,
|
||||
filters: {
|
||||
...data.filters,
|
||||
items:
|
||||
data.filters?.items?.map((item) => ({
|
||||
...item,
|
||||
id: '',
|
||||
})) || [],
|
||||
op: data.filters?.op || 'AND',
|
||||
},
|
||||
})),
|
||||
});
|
||||
};
|
||||
|
||||
const handleRun = useCallback(
|
||||
(props?: HandleRunProps): void => {
|
||||
const preparedQuery: Query = {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: currentQuery.builder.queryData.map((item, idx) => {
|
||||
if (idx !== activeQueryIndex) {
|
||||
return item;
|
||||
}
|
||||
return {
|
||||
...item,
|
||||
filters: {
|
||||
...item.filters,
|
||||
items: props?.resetAll
|
||||
? []
|
||||
: (unionTagFilterItems(item.filters?.items || [], preparePostData())
|
||||
.map((item) =>
|
||||
item.key?.key === props?.clearByType ? undefined : item,
|
||||
)
|
||||
.filter((i) => i) as TagFilterItem[]),
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
};
|
||||
}),
|
||||
},
|
||||
};
|
||||
const slotKey = getBuilderSlotKeyForQueryType(currentQuery.queryType);
|
||||
const activeBuilder = getBuilderBySlotKey(currentQuery, slotKey);
|
||||
const preparedQuery: Query = replaceBuilderBySlotKey(currentQuery, slotKey, {
|
||||
...activeBuilder,
|
||||
queryData: activeBuilder.queryData.map((item, idx) => {
|
||||
if (idx !== activeQueryIndex) {
|
||||
return item;
|
||||
}
|
||||
return {
|
||||
...item,
|
||||
filters: {
|
||||
...item.filters,
|
||||
items: props?.resetAll
|
||||
? []
|
||||
: (unionTagFilterItems(item.filters?.items || [], preparePostData())
|
||||
.map((item) =>
|
||||
item.key?.key === props?.clearByType ? undefined : item,
|
||||
)
|
||||
.filter((i) => i) as TagFilterItem[]),
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
const currentQueryWithoutIds = removeFilterItemIds(currentQuery);
|
||||
const preparedQueryWithoutIds = removeFilterItemIds(preparedQuery);
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { removeKeysFromExpression } from 'components/QueryBuilderV2/utils';
|
||||
import {
|
||||
getBuilderBySlotKey,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
replaceBuilderBySlotKey,
|
||||
} from 'lib/query/builderSlot';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import { getKeySpellings, isKeyMatch } from '../Checkbox/utils';
|
||||
@@ -20,34 +25,33 @@ export function clearFilterFromQuery({
|
||||
activeQueryIndex: number;
|
||||
operators?: string[];
|
||||
}): Query {
|
||||
return {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: currentQuery.builder.queryData.map((item, idx) => {
|
||||
if (idx !== activeQueryIndex) {
|
||||
return item;
|
||||
}
|
||||
return {
|
||||
...item,
|
||||
filter: {
|
||||
expression: removeKeysFromExpression(
|
||||
item.filter?.expression ?? '',
|
||||
getKeySpellings(filterKey),
|
||||
false,
|
||||
operators,
|
||||
),
|
||||
},
|
||||
filters: {
|
||||
...item.filters,
|
||||
items:
|
||||
item.filters?.items?.filter(
|
||||
(fil) => !isKeyMatch(fil.key?.key, filterKey),
|
||||
) || [],
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
};
|
||||
}),
|
||||
},
|
||||
};
|
||||
const slotKey = getBuilderSlotKeyForQueryType(currentQuery.queryType);
|
||||
const activeBuilder = getBuilderBySlotKey(currentQuery, slotKey);
|
||||
return replaceBuilderBySlotKey(currentQuery, slotKey, {
|
||||
...activeBuilder,
|
||||
queryData: activeBuilder.queryData.map((item, idx) => {
|
||||
if (idx !== activeQueryIndex) {
|
||||
return item;
|
||||
}
|
||||
return {
|
||||
...item,
|
||||
filter: {
|
||||
expression: removeKeysFromExpression(
|
||||
item.filter?.expression ?? '',
|
||||
getKeySpellings(filterKey),
|
||||
false,
|
||||
operators,
|
||||
),
|
||||
},
|
||||
filters: {
|
||||
...item.filters,
|
||||
items:
|
||||
item.filters?.items?.filter(
|
||||
(fil) => !isKeyMatch(fil.key?.key, filterKey),
|
||||
) || [],
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -32,6 +32,11 @@ import {
|
||||
QuickFilterReadPermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/quick-filter.permissions';
|
||||
import { isFunction } from 'lodash-es';
|
||||
import {
|
||||
getActiveBuilder,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
replaceBuilderBySlotKey,
|
||||
} from 'lib/query/builderSlot';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import useActiveQueryIndex from './hooks/useActiveQueryIndex';
|
||||
@@ -87,15 +92,15 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
panelType,
|
||||
} = useQueryBuilder();
|
||||
const [open, setOpen] = useState(false);
|
||||
const activeBuilder = currentQuery
|
||||
? getActiveBuilder(currentQuery)
|
||||
: undefined;
|
||||
|
||||
// Sync lastUsedQuery when queries change (e.g., after deletion)
|
||||
const validQueryIndex = useMemo(
|
||||
() =>
|
||||
Math.min(
|
||||
lastUsedQuery || 0,
|
||||
(currentQuery?.builder?.queryData?.length || 1) - 1,
|
||||
),
|
||||
[lastUsedQuery, currentQuery?.builder?.queryData?.length],
|
||||
Math.min(lastUsedQuery || 0, (activeBuilder?.queryData?.length || 1) - 1),
|
||||
[lastUsedQuery, activeBuilder?.queryData?.length],
|
||||
);
|
||||
|
||||
// Determine if we're in ListView mode
|
||||
@@ -103,15 +108,15 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
|
||||
// Generate query options based on available queries
|
||||
const queryOptions = useMemo(() => {
|
||||
if (!currentQuery?.builder?.queryData) {
|
||||
if (!activeBuilder?.queryData) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return currentQuery.builder.queryData.map((query, index) => ({
|
||||
return activeBuilder.queryData.map((query, index) => ({
|
||||
label: query.queryName || String.fromCharCode(65 + index),
|
||||
value: index,
|
||||
}));
|
||||
}, [currentQuery?.builder?.queryData]);
|
||||
}, [activeBuilder?.queryData]);
|
||||
|
||||
// Show dropdown in ListView only for TRACES_EXPLORER source
|
||||
const shouldShowDropdownInListView =
|
||||
@@ -127,36 +132,34 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
|
||||
// clear all the filters for the query which is in sync with filters
|
||||
const handleReset = (): void => {
|
||||
const activeQuery = currentQuery?.builder.queryData?.[activeQueryIndex];
|
||||
const activeQuery = activeBuilder?.queryData?.[activeQueryIndex];
|
||||
|
||||
if (!activeQuery) {
|
||||
if (!activeBuilder || !activeQuery) {
|
||||
return;
|
||||
}
|
||||
|
||||
const preparedQuery: Query = {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: currentQuery.builder.queryData.map((item, idx) => {
|
||||
if (idx !== activeQueryIndex) {
|
||||
return item;
|
||||
}
|
||||
const slotKey = getBuilderSlotKeyForQueryType(currentQuery.queryType);
|
||||
const preparedQuery: Query = replaceBuilderBySlotKey(currentQuery, slotKey, {
|
||||
...activeBuilder,
|
||||
queryData: activeBuilder.queryData.map((item, idx) => {
|
||||
if (idx !== activeQueryIndex) {
|
||||
return item;
|
||||
}
|
||||
|
||||
return {
|
||||
...item,
|
||||
filter: {
|
||||
...item.filter,
|
||||
expression: '',
|
||||
},
|
||||
filters: {
|
||||
...item.filters,
|
||||
items: [],
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
};
|
||||
}),
|
||||
},
|
||||
};
|
||||
return {
|
||||
...item,
|
||||
filter: {
|
||||
...item.filter,
|
||||
expression: '',
|
||||
},
|
||||
filters: {
|
||||
...item.filters,
|
||||
items: [],
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
if (onFilterChange && isFunction(onFilterChange)) {
|
||||
onFilterChange(preparedQuery);
|
||||
@@ -166,13 +169,12 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
};
|
||||
|
||||
const lastQueryName =
|
||||
showQueryName &&
|
||||
currentQuery.builder.queryData?.[lastUsedQuery || 0]?.queryName;
|
||||
showQueryName && activeBuilder?.queryData?.[lastUsedQuery || 0]?.queryName;
|
||||
|
||||
// In ListView, always show the 0th query's name; otherwise use the active query's name
|
||||
const displayedQueryName =
|
||||
isListView || isAIObservabilityRowView
|
||||
? showQueryName && currentQuery.builder.queryData?.[0]?.queryName
|
||||
? showQueryName && activeBuilder?.queryData?.[0]?.queryName
|
||||
: lastQueryName;
|
||||
|
||||
const handleQueryChange = (value: number): void => {
|
||||
@@ -193,6 +195,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
placeholder="Select a query"
|
||||
value={queryOptions.find((f) => f.value === validQueryIndex)?.label || ''}
|
||||
className="select-box"
|
||||
testId="quick-filters-query-select"
|
||||
/>
|
||||
{open && (
|
||||
<ComboboxContent>
|
||||
@@ -207,6 +210,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
setOpen(false);
|
||||
}}
|
||||
isSelected={validQueryIndex === option.value}
|
||||
testId={`quick-filters-query-option-${option.value}`}
|
||||
>
|
||||
{option.label}
|
||||
</ComboboxItem>
|
||||
@@ -300,6 +304,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
color="primary"
|
||||
textPlacement="right"
|
||||
value={showIP ?? true}
|
||||
testId="quick-filters-show-ip"
|
||||
onChange={(checked): void => {
|
||||
logEvent('API Monitoring: Show IP addresses clicked', {
|
||||
showIP: checked,
|
||||
|
||||
@@ -52,6 +52,7 @@ function SortableFilter({
|
||||
<Button
|
||||
className="remove-filter-btn periscope-btn"
|
||||
size="small"
|
||||
data-testid={`quick-filters-remove-${filter.key}`}
|
||||
onClick={(): void => {
|
||||
onRemove(filter);
|
||||
}}
|
||||
@@ -103,7 +104,7 @@ function AddedFilters({
|
||||
const allowRemove = addedFilters.length > 1;
|
||||
|
||||
return (
|
||||
<div className="qf-filters added-filters">
|
||||
<div className="qf-filters added-filters" data-testid="quick-filters-added">
|
||||
<div className="qf-filters-header">ADDED FILTERS</div>
|
||||
<div className="qf-added-filters-list">
|
||||
<OverlayScrollbar>
|
||||
|
||||
@@ -102,6 +102,7 @@ function OtherFilters({
|
||||
<Button
|
||||
className="add-filter-btn periscope-btn"
|
||||
size="small"
|
||||
data-testid={`quick-filters-add-${filter.key}`}
|
||||
onClick={(): void => handleAddFilter(filter)}
|
||||
>
|
||||
Add
|
||||
@@ -111,7 +112,7 @@ function OtherFilters({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="qf-filters other-filters">
|
||||
<div className="qf-filters other-filters" data-testid="quick-filters-other">
|
||||
<div className="qf-filters-header">OTHER FILTERS</div>
|
||||
<div className="qf-other-filters-list">
|
||||
<OverlayScrollbar>
|
||||
|
||||
@@ -83,6 +83,7 @@ function QuickFiltersSettings({
|
||||
<Button
|
||||
type="default"
|
||||
onClick={handleDiscardChanges}
|
||||
data-testid="quick-filters-settings-discard"
|
||||
icon={<X size={16} />}
|
||||
>
|
||||
Discard
|
||||
@@ -92,6 +93,7 @@ function QuickFiltersSettings({
|
||||
onClick={handleSaveChanges}
|
||||
icon={<Check size={16} />}
|
||||
loading={isUpdatingCustomFilters}
|
||||
data-testid="quick-filters-settings-save"
|
||||
>
|
||||
Save changes
|
||||
</Button>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
QuickfiltertypesSourceDTO,
|
||||
TelemetrytypesSignalDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import {
|
||||
ApiMonitoringParams,
|
||||
@@ -15,10 +18,12 @@ import {
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
|
||||
|
||||
import '@testing-library/jest-dom';
|
||||
|
||||
import QuickFilters from '../QuickFilters';
|
||||
import QuickFiltersSettings from '../QuickFiltersSettings/QuickFiltersSettings';
|
||||
import { IQuickFiltersConfig, QuickFiltersSource } from '../types';
|
||||
import { QuickFiltersConfig, QuickFiltersFieldApis } from './constants';
|
||||
|
||||
@@ -26,6 +31,17 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: jest.fn(),
|
||||
}));
|
||||
jest.mock('container/ApiMonitoring/queryParams');
|
||||
jest.mock(
|
||||
'components/OverlayScrollbar/OverlayScrollbar',
|
||||
() =>
|
||||
function MockOverlayScrollbar({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}): JSX.Element {
|
||||
return <div>{children}</div>;
|
||||
},
|
||||
);
|
||||
|
||||
const handleFilterVisibilityChange = jest.fn();
|
||||
const redirectWithQueryBuilderData = jest.fn();
|
||||
@@ -44,14 +60,27 @@ const fieldsValuesURL = `${BASE_URL}/api/v1/fields/values`;
|
||||
|
||||
const FILTER_OS_DESCRIPTION = 'os.description';
|
||||
const FILTER_K8S_DEPLOYMENT_NAME = 'k8s.deployment.name';
|
||||
const ADDED_FILTERS_LABEL = /ADDED FILTERS/i;
|
||||
const OTHER_FILTERS_LABEL = /OTHER FILTERS/i;
|
||||
const SAVE_CHANGES_TEXT = 'Save changes';
|
||||
const DISCARD_TEXT = 'Discard';
|
||||
const ADDED_FILTERS_TEST_ID = 'quick-filters-added';
|
||||
const OTHER_FILTERS_TEST_ID = 'quick-filters-other';
|
||||
const SAVE_TEST_ID = 'quick-filters-settings-save';
|
||||
const SETTINGS_TEST_ID = 'settings-icon-container';
|
||||
const REMOVE_OS_DESCRIPTION_TEST_ID =
|
||||
'quick-filters-remove-resource:os.description:string';
|
||||
const ADD_K8S_DEPLOYMENT_NAME_TEST_ID =
|
||||
'quick-filters-add-resource:k8s.deployment.name:string';
|
||||
const FILTER_SERVICE_NAME = 'Service Name';
|
||||
const SETTINGS_ICON_TEST_ID = 'settings-icon';
|
||||
const QUERY_NAME = 'Test Query';
|
||||
|
||||
const savedFilters = quickFiltersListResponse.data
|
||||
.filters as TelemetryFieldKey[];
|
||||
const smallFiltersListResponse = {
|
||||
...quickFiltersListResponse,
|
||||
data: {
|
||||
...quickFiltersListResponse.data,
|
||||
filters: savedFilters.slice(0, 2),
|
||||
},
|
||||
};
|
||||
|
||||
const setupServer = (): void => {
|
||||
server.use(
|
||||
rest.get(quickFiltersListURL, (_, res, ctx) =>
|
||||
@@ -95,6 +124,24 @@ TestQuickFilters.defaultProps = {
|
||||
config: QuickFiltersConfig,
|
||||
};
|
||||
|
||||
function renderSettings(): void {
|
||||
render(
|
||||
<QuickFiltersSettings
|
||||
savedFiltersSource={QuickfiltertypesSourceDTO.logs}
|
||||
setIsSettingsOpen={jest.fn()}
|
||||
customFilters={savedFilters}
|
||||
refetchCustomFilters={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
async function openSettings(
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
): Promise<void> {
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
await user.click(screen.getByTestId(SETTINGS_TEST_ID));
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
server.listen();
|
||||
});
|
||||
@@ -102,6 +149,7 @@ beforeAll(() => {
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
jest.clearAllMocks();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
@@ -139,7 +187,7 @@ describe('Quick Filters', () => {
|
||||
|
||||
it('should display and allow selection from query dropdown when multiple queries exist', async () => {
|
||||
const setLastUsedQuery = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useQueryBuilder as jest.Mock).mockReturnValue({
|
||||
currentQuery: {
|
||||
@@ -169,27 +217,28 @@ describe('Quick Filters', () => {
|
||||
render(<TestQuickFilters />);
|
||||
|
||||
// The dropdown trigger should show the first query name
|
||||
const trigger = screen.getByText('Query A');
|
||||
expect(trigger).toBeInTheDocument();
|
||||
const trigger = screen.getByTestId('quick-filters-query-select');
|
||||
expect(trigger).toHaveTextContent('Query A');
|
||||
|
||||
// Click to open the dropdown
|
||||
await user.click(trigger);
|
||||
|
||||
// All query options should be visible
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('option', { name: 'Query A' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('option', { name: 'Query B' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('option', { name: 'Query C' })).toBeInTheDocument();
|
||||
});
|
||||
await expect(
|
||||
screen.findByTestId('quick-filters-query-option-0'),
|
||||
).resolves.toHaveTextContent('Query A');
|
||||
expect(screen.getByTestId('quick-filters-query-option-1')).toHaveTextContent(
|
||||
'Query B',
|
||||
);
|
||||
expect(screen.getByTestId('quick-filters-query-option-2')).toHaveTextContent(
|
||||
'Query C',
|
||||
);
|
||||
|
||||
// Select Query B
|
||||
const queryBOption = screen.getByRole('option', { name: 'Query B' });
|
||||
await user.click(queryBOption);
|
||||
await user.click(screen.getByTestId('quick-filters-query-option-1'));
|
||||
|
||||
// Verify setLastUsedQuery was called with index 1
|
||||
await waitFor(() => {
|
||||
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
|
||||
});
|
||||
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('should not display query dropdown in ListView', () => {
|
||||
@@ -235,7 +284,7 @@ describe('Quick Filters', () => {
|
||||
});
|
||||
|
||||
it('should add filter data to query when checkbox is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<TestQuickFilters />);
|
||||
|
||||
@@ -267,33 +316,27 @@ describe('Quick Filters', () => {
|
||||
});
|
||||
});
|
||||
it('toggles Show IP addresses and updates API Monitoring params', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.API_MONITORING} />,
|
||||
);
|
||||
|
||||
// Switch should be rendered and initially checked
|
||||
await expect(
|
||||
screen.findByText('Show IP addresses'),
|
||||
).resolves.toBeInTheDocument();
|
||||
const toggle = screen.getByRole('switch');
|
||||
const toggle = await screen.findByTestId('quick-filters-show-ip');
|
||||
expect(screen.getByText('Show IP addresses')).toBeInTheDocument();
|
||||
expect(toggle).toHaveAttribute('aria-checked', 'true');
|
||||
|
||||
await user.click(toggle);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSetApiMonitoringParams).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ showIP: false }),
|
||||
);
|
||||
});
|
||||
expect(mockSetApiMonitoringParams).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ showIP: false }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Quick Filters with custom filters', () => {
|
||||
it('loads the custom filters correctly', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
@@ -304,28 +347,32 @@ describe('Quick Filters with custom filters', () => {
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
const allByText = await screen.findAllByText('otel-demo');
|
||||
expect(allByText).toHaveLength(2);
|
||||
});
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
await expect(
|
||||
screen.findByText('Edit quick filters'),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
|
||||
expect(addedSection).toContainElement(
|
||||
await screen.findByText(FILTER_OS_DESCRIPTION),
|
||||
it('opens the settings with the saved filters added and the rest under other filters', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
rest.get(quickFiltersListURL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(smallFiltersListResponse)),
|
||||
),
|
||||
);
|
||||
|
||||
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
|
||||
expect(otherSection).toContainElement(
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
await openSettings(user);
|
||||
|
||||
expect(screen.getByText('Edit quick filters')).toBeInTheDocument();
|
||||
expect(screen.getByTestId(ADDED_FILTERS_TEST_ID)).toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
expect(screen.getByTestId(OTHER_FILTERS_TEST_ID)).toContainElement(
|
||||
await screen.findByText(FILTER_K8S_DEPLOYMENT_NAME),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps same-name fields with different context as distinct entries', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
rest.get(quickFiltersSuggestionsURL, (_req, res, ctx) =>
|
||||
res(
|
||||
@@ -356,153 +403,86 @@ describe('Quick Filters with custom filters', () => {
|
||||
),
|
||||
);
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
renderSettings();
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
|
||||
const otherSection = screen.getByTestId(OTHER_FILTERS_TEST_ID);
|
||||
// Both `level` variants are shown despite sharing a name.
|
||||
await waitFor(() =>
|
||||
expect(within(otherSection).getAllByText('level')).toHaveLength(2),
|
||||
const addButton = await screen.findByTestId(
|
||||
'quick-filters-add-attribute:level:string',
|
||||
);
|
||||
expect(within(otherSection).getAllByText('level')).toHaveLength(2);
|
||||
|
||||
// Adding one variant removes only that one; the other stays.
|
||||
const firstLevel = within(otherSection).getAllByText('level')[0];
|
||||
const addButton = firstLevel.parentElement?.querySelector('button');
|
||||
await user.click(addButton as HTMLButtonElement);
|
||||
await user.click(addButton);
|
||||
|
||||
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
|
||||
await waitFor(() => {
|
||||
expect(within(addedSection).getAllByText('level')).toHaveLength(1);
|
||||
expect(within(otherSection).getAllByText('level')).toHaveLength(1);
|
||||
});
|
||||
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
|
||||
expect(within(addedSection).getAllByText('level')).toHaveLength(1);
|
||||
expect(within(otherSection).getAllByText('level')).toHaveLength(1);
|
||||
expect(
|
||||
screen.getByTestId('quick-filters-add-span:level:string'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('adds a filter from OTHER FILTERS to ADDED FILTERS when clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
renderSettings();
|
||||
|
||||
await user.click(await screen.findByTestId(ADD_K8S_DEPLOYMENT_NAME_TEST_ID));
|
||||
|
||||
expect(screen.getByTestId(ADDED_FILTERS_TEST_ID)).toHaveTextContent(
|
||||
FILTER_K8S_DEPLOYMENT_NAME,
|
||||
);
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
const otherFilterItem = await screen.findByText(FILTER_K8S_DEPLOYMENT_NAME);
|
||||
const addButton = otherFilterItem.parentElement?.querySelector('button');
|
||||
expect(addButton).not.toBeNull();
|
||||
await user.click(addButton as HTMLButtonElement);
|
||||
|
||||
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
|
||||
await waitFor(() => {
|
||||
expect(addedSection).toHaveTextContent(FILTER_K8S_DEPLOYMENT_NAME);
|
||||
});
|
||||
});
|
||||
|
||||
it('removes a filter from ADDED FILTERS and moves it to OTHER FILTERS', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
renderSettings();
|
||||
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
|
||||
const otherSection = screen.getByTestId(OTHER_FILTERS_TEST_ID);
|
||||
await screen.findByTestId(ADD_K8S_DEPLOYMENT_NAME_TEST_ID);
|
||||
|
||||
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
|
||||
|
||||
expect(addedSection).not.toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
|
||||
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
|
||||
const removeBtn = target.parentElement?.querySelector('button');
|
||||
expect(removeBtn).not.toBeNull();
|
||||
|
||||
await user.click(removeBtn as HTMLButtonElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(addedSection).not.toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
});
|
||||
|
||||
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
|
||||
expect(otherSection).toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
});
|
||||
|
||||
it('restores original filter state on Discard', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
renderSettings();
|
||||
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
|
||||
const otherSection = screen.getByTestId(OTHER_FILTERS_TEST_ID);
|
||||
await screen.findByTestId(ADD_K8S_DEPLOYMENT_NAME_TEST_ID);
|
||||
|
||||
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
|
||||
expect(otherSection).toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
await user.click(screen.getByTestId('quick-filters-settings-discard'));
|
||||
|
||||
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
|
||||
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
|
||||
const removeBtn = target.parentElement?.querySelector('button');
|
||||
expect(removeBtn).not.toBeNull();
|
||||
await user.click(removeBtn as HTMLButtonElement);
|
||||
|
||||
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
|
||||
await waitFor(() => {
|
||||
expect(addedSection).not.toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
expect(otherSection).toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
});
|
||||
|
||||
const discardBtn = screen
|
||||
.getByText(DISCARD_TEXT)
|
||||
.closest('button') as HTMLButtonElement;
|
||||
expect(discardBtn).not.toBeNull();
|
||||
await user.click(discardBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(addedSection).toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
expect(otherSection).not.toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
});
|
||||
expect(addedSection).toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
expect(otherSection).not.toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
});
|
||||
|
||||
it('saves the updated filters by calling PUT with correct payload', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
renderSettings();
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
|
||||
const removeBtn = target.parentElement?.querySelector('button');
|
||||
expect(removeBtn).not.toBeNull();
|
||||
await user.click(removeBtn as HTMLButtonElement);
|
||||
|
||||
const saveBtn = screen
|
||||
.getByText(SAVE_CHANGES_TEXT)
|
||||
.closest('button') as HTMLButtonElement;
|
||||
expect(saveBtn).not.toBeNull();
|
||||
await user.click(saveBtn);
|
||||
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
|
||||
await user.click(screen.getByTestId(SAVE_TEST_ID));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(putHandler).toHaveBeenCalled();
|
||||
@@ -516,24 +496,37 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('should render duration slider for duration_nono filter', async () => {
|
||||
server.use(
|
||||
rest.get(quickFiltersListURL, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
...quickFiltersListResponse,
|
||||
data: {
|
||||
...quickFiltersListResponse.data,
|
||||
filters: savedFilters.filter(({ name }) => name === 'duration_nano'),
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
// Use fake timers only in this test (for debounce), and wire them to userEvent
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
pointerEventsCheck: 0,
|
||||
});
|
||||
|
||||
const { getByTestId } = render(
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
await screen.findByTestId('collapse-duration');
|
||||
expect(screen.getByText('Duration')).toBeInTheDocument();
|
||||
|
||||
// Open the duration section (use role if it’s a button/collapse)
|
||||
await user.click(screen.getByText('Duration'));
|
||||
|
||||
const minDuration = getByTestId('min-input') as HTMLInputElement;
|
||||
const maxDuration = getByTestId('max-input') as HTMLInputElement;
|
||||
const minDuration = screen.getByTestId('min-input') as HTMLInputElement;
|
||||
const maxDuration = screen.getByTestId('max-input') as HTMLInputElement;
|
||||
|
||||
expect(minDuration).toHaveValue(null);
|
||||
expect(minDuration).toHaveProperty('placeholder', '0');
|
||||
@@ -635,7 +628,7 @@ describe('Quick Filters refetch behavior', () => {
|
||||
server.use(
|
||||
rest.get(quickFiltersListURL, (_req, res, ctx) => {
|
||||
getCalls += 1;
|
||||
return res(ctx.status(200), ctx.json(quickFiltersListResponse));
|
||||
return res(ctx.status(200), ctx.json(smallFiltersListResponse));
|
||||
}),
|
||||
rest.put(saveQuickFiltersURL, async (req, res, ctx) => {
|
||||
putHandler(await req.json());
|
||||
@@ -643,26 +636,14 @@ describe('Quick Filters refetch behavior', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
|
||||
await expect(
|
||||
screen.findByText(FILTER_SERVICE_NAME),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
|
||||
const removeBtn = target.parentElement?.querySelector(
|
||||
'button',
|
||||
) as HTMLButtonElement;
|
||||
await user.click(removeBtn);
|
||||
|
||||
await user.click(screen.getByText(SAVE_CHANGES_TEXT));
|
||||
await openSettings(user);
|
||||
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
|
||||
await user.click(screen.getByTestId(SAVE_TEST_ID));
|
||||
|
||||
await waitFor(() => expect(putHandler).toHaveBeenCalled());
|
||||
await waitFor(() => expect(getCalls).toBeGreaterThanOrEqual(2));
|
||||
@@ -670,11 +651,11 @@ describe('Quick Filters refetch behavior', () => {
|
||||
|
||||
it('renders updated filters after refetch post-save', async () => {
|
||||
const updatedResponse = {
|
||||
...quickFiltersListResponse,
|
||||
...smallFiltersListResponse,
|
||||
data: {
|
||||
...quickFiltersListResponse.data,
|
||||
...smallFiltersListResponse.data,
|
||||
filters: [
|
||||
...(quickFiltersListResponse.data.filters ?? []),
|
||||
...smallFiltersListResponse.data.filters,
|
||||
{
|
||||
name: 'new.custom.filter',
|
||||
fieldDataType: 'string',
|
||||
@@ -690,38 +671,26 @@ describe('Quick Filters refetch behavior', () => {
|
||||
getCount += 1;
|
||||
return getCount >= 2
|
||||
? res(ctx.status(200), ctx.json(updatedResponse))
|
||||
: res(ctx.status(200), ctx.json(quickFiltersListResponse));
|
||||
: res(ctx.status(200), ctx.json(smallFiltersListResponse));
|
||||
}),
|
||||
rest.put(saveQuickFiltersURL, async (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({})),
|
||||
),
|
||||
);
|
||||
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
|
||||
await expect(
|
||||
screen.findByText(FILTER_SERVICE_NAME),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
await openSettings(user);
|
||||
// Make a minimal change so Save button appears
|
||||
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
|
||||
const removeBtn = target.parentElement?.querySelector(
|
||||
'button',
|
||||
) as HTMLButtonElement;
|
||||
await user.click(removeBtn);
|
||||
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
|
||||
await user.click(screen.getByTestId(SAVE_TEST_ID));
|
||||
|
||||
await user.click(screen.getByText(SAVE_CHANGES_TEXT));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('New Custom Filter')).toBeInTheDocument();
|
||||
});
|
||||
await expect(
|
||||
screen.findByText('New Custom Filter'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows empty state when GET fails', async () => {
|
||||
|
||||
@@ -44,6 +44,7 @@ function SaveErrorItem({
|
||||
variant="link"
|
||||
color="secondary"
|
||||
aria-label="Retry"
|
||||
testId="sa-error-retry-btn"
|
||||
onClick={async (e): Promise<void> => {
|
||||
e.stopPropagation();
|
||||
setIsRetrying(true);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ServiceAccountRow } from 'container/ServiceAccountsSettings/utils';
|
||||
import {
|
||||
listRolesSuccessResponse,
|
||||
managedRoles,
|
||||
@@ -15,22 +16,25 @@ import {
|
||||
buildSADeletePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/service-account.permissions';
|
||||
|
||||
import KeysTab from '../KeysTab';
|
||||
import OverviewTab from '../OverviewTab';
|
||||
import ServiceAccountDrawer from '../ServiceAccountDrawer';
|
||||
|
||||
const ROLES_ENDPOINT = '*/api/v1/roles';
|
||||
const SA_KEYS_ENDPOINT = '*/api/v1/service_accounts/:id/keys';
|
||||
const SA_ENDPOINT = '*/api/v1/service_accounts/sa-1';
|
||||
const SA_DELETE_ENDPOINT = '*/api/v1/service_accounts/sa-1';
|
||||
const SA_ROLES_ENDPOINT = '*/api/v1/service_account_roles';
|
||||
const SA_ROLE_DELETE_ENDPOINT = '*/api/v1/service_account_roles/:id';
|
||||
|
||||
const activeAccountResponse = {
|
||||
const account: ServiceAccountRow = {
|
||||
id: 'sa-1',
|
||||
name: 'CI Bot',
|
||||
email: 'ci-bot@signoz.io',
|
||||
status: 'ACTIVE',
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-02T00:00:00Z',
|
||||
};
|
||||
|
||||
const activeAccountResponse = {
|
||||
...account,
|
||||
serviceAccountRoles: [
|
||||
{
|
||||
id: 'sar-admin-1',
|
||||
@@ -41,93 +45,88 @@ const activeAccountResponse = {
|
||||
],
|
||||
};
|
||||
|
||||
function renderDrawer(
|
||||
searchParams: Record<string, string> = { account: 'sa-1' },
|
||||
): ReturnType<typeof render> {
|
||||
function renderOverviewTab(): ReturnType<typeof render> {
|
||||
return render(
|
||||
<NuqsTestingAdapter searchParams={searchParams} hasMemory>
|
||||
<ServiceAccountDrawer onSuccess={jest.fn()} />
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
}
|
||||
|
||||
function setupBaseHandlers(): void {
|
||||
server.use(
|
||||
rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
|
||||
),
|
||||
rest.get(SA_KEYS_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ data: [] })),
|
||||
),
|
||||
rest.get(SA_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ data: activeAccountResponse })),
|
||||
),
|
||||
rest.put(SA_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
|
||||
),
|
||||
rest.delete(SA_DELETE_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
|
||||
),
|
||||
rest.post(SA_ROLES_ENDPOINT, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(201),
|
||||
ctx.json({ status: 'success', data: { id: 'sar-new' } }),
|
||||
),
|
||||
),
|
||||
rest.delete(SA_ROLE_DELETE_ENDPOINT, (_, res, ctx) => res(ctx.status(204))),
|
||||
<OverviewTab
|
||||
account={account}
|
||||
localName="CI Bot"
|
||||
onNameChange={jest.fn()}
|
||||
localRoles={[]}
|
||||
onRolesChange={jest.fn()}
|
||||
isDisabled={false}
|
||||
availableRoles={[]}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ServiceAccountDrawer — permissions', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
setupBaseHandlers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('shows PermissionDeniedCallout inside drawer when read permission is denied', async () => {
|
||||
it('shows PermissionDeniedCallout in the Overview tab when read permission is denied', async () => {
|
||||
server.use(setupAuthzDenyAll());
|
||||
|
||||
renderDrawer();
|
||||
renderOverviewTab();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/read:serviceaccount/)).toBeInTheDocument();
|
||||
});
|
||||
await expect(
|
||||
screen.findByTestId('permission-denied-callout'),
|
||||
).resolves.toHaveTextContent('read:serviceaccount:sa-1');
|
||||
});
|
||||
|
||||
it('shows drawer content when read permission is granted', async () => {
|
||||
it('shows Overview tab content when read permission is granted', async () => {
|
||||
server.use(setupAuthzAdmin());
|
||||
|
||||
renderDrawer();
|
||||
renderOverviewTab();
|
||||
|
||||
await screen.findByDisplayValue('CI Bot');
|
||||
expect(screen.queryByText(/serviceaccount:read/)).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('permission-denied-callout'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows PermissionDeniedCallout in Keys tab when list-keys permission is denied', async () => {
|
||||
server.use(setupAuthzDeny(APIKeyListPermission));
|
||||
|
||||
renderDrawer({ account: 'sa-1', tab: 'keys' });
|
||||
render(
|
||||
<KeysTab
|
||||
keys={[]}
|
||||
isLoading={false}
|
||||
accountId="sa-1"
|
||||
currentPage={1}
|
||||
pageSize={15}
|
||||
onPageChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/list:factor-api-key/)).toBeInTheDocument();
|
||||
});
|
||||
await expect(
|
||||
screen.findByTestId('permission-denied-callout'),
|
||||
).resolves.toHaveTextContent('list:factor-api-key:*');
|
||||
});
|
||||
|
||||
it('disables Delete button when delete permission is denied', async () => {
|
||||
server.use(setupAuthzDeny(buildSADeletePermission('sa-1')));
|
||||
|
||||
renderDrawer();
|
||||
await screen.findByDisplayValue('CI Bot');
|
||||
|
||||
const deleteBtn = screen.getByRole('button', {
|
||||
name: /Delete Service Account/i,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(deleteBtn).toHaveAttribute('aria-disabled', 'true'),
|
||||
server.use(
|
||||
rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
|
||||
),
|
||||
rest.get(SA_KEYS_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ data: [] })),
|
||||
),
|
||||
rest.get(SA_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ data: activeAccountResponse })),
|
||||
),
|
||||
setupAuthzDeny(buildSADeletePermission('sa-1')),
|
||||
);
|
||||
|
||||
render(
|
||||
<NuqsTestingAdapter searchParams={{ account: 'sa-1' }} hasMemory>
|
||||
<ServiceAccountDrawer onSuccess={jest.fn()} />
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
|
||||
const deleteBtn = await screen.findByTestId('sa-delete-btn');
|
||||
await waitFor(() =>
|
||||
expect(deleteBtn).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
buildSADeletePermission('sa-1'),
|
||||
),
|
||||
);
|
||||
expect(deleteBtn).toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
} from 'mocks-server/__mockdata__/roles';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
|
||||
|
||||
import ServiceAccountDrawer from '../ServiceAccountDrawer';
|
||||
@@ -93,7 +93,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
screen.findByDisplayValue('CI Bot'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText('ci-bot@signoz.io')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Save Changes/i })).toHaveAttribute(
|
||||
expect(screen.getByTestId('sa-save-btn')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
@@ -102,7 +102,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
it('editing name enables Save; clicking Save sends correct payload and calls onSuccess', async () => {
|
||||
const onSuccess = jest.fn();
|
||||
const updateSpy = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.put(SA_ENDPOINT, async (req, res, ctx) => {
|
||||
@@ -121,7 +121,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'CI Bot Updated');
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
@@ -140,7 +140,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
it('adding a role fires POST for the new role and no DELETE for existing roles', async () => {
|
||||
const roleSpy = jest.fn();
|
||||
const deleteSpy = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(SA_ROLES_ENDPOINT, async (req, res, ctx) => {
|
||||
@@ -164,7 +164,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
await user.click(screen.getByLabelText('Roles'));
|
||||
await user.click(await screen.findByTitle('signoz-viewer'));
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
@@ -184,7 +184,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
it('removing a role fires DELETE for the removed role and no POST', async () => {
|
||||
const roleSpy = jest.fn();
|
||||
const deleteSpy = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(SA_ROLES_ENDPOINT, async (req, res, ctx) => {
|
||||
@@ -211,7 +211,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
) as Element;
|
||||
await user.click(removeBtn);
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
@@ -225,7 +225,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
|
||||
it('"Delete Service Account" opens confirm dialog; confirming sends delete request', async () => {
|
||||
const deleteSpy = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.delete(SA_DELETE_ENDPOINT, (_, res, ctx) => {
|
||||
@@ -238,9 +238,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
|
||||
await screen.findByDisplayValue('CI Bot');
|
||||
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: /Delete Service Account/i }),
|
||||
);
|
||||
await user.click(screen.getByTestId('sa-delete-btn'));
|
||||
|
||||
await screen.findByTestId('delete-service-account-modal');
|
||||
expect(
|
||||
@@ -272,23 +270,19 @@ describe('ServiceAccountDrawer', () => {
|
||||
|
||||
await screen.findByText('CI Bot');
|
||||
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /Save Changes/i }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /Delete Service Account/i }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('sa-save-btn')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('sa-delete-btn')).not.toBeInTheDocument();
|
||||
expect(screen.queryByDisplayValue('CI Bot')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('switching to Keys tab shows "No keys" empty state', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer();
|
||||
|
||||
await screen.findByDisplayValue('CI Bot');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Keys/i }));
|
||||
await user.click(screen.getByTestId('sa-tab-button-keys'));
|
||||
|
||||
await expect(screen.findByText(/No keys/i)).resolves.toBeInTheDocument();
|
||||
});
|
||||
@@ -341,11 +335,12 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('name update failure shows SaveErrorItem with "Name update" context', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.put(SA_ENDPOINT, (_, res, ctx) =>
|
||||
@@ -367,7 +362,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'New Name');
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
@@ -381,7 +376,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
});
|
||||
|
||||
it('role add failure shows SaveErrorItem with the role name context', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(SA_ROLES_ENDPOINT, (_, res, ctx) =>
|
||||
@@ -405,7 +400,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
await user.click(screen.getByLabelText('Roles'));
|
||||
await user.click(await screen.findByTitle('signoz-viewer'));
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
@@ -419,7 +414,11 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
});
|
||||
|
||||
it('role add retries on 429 then succeeds without showing an error', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
const onSuccess = jest.fn();
|
||||
let roleAddCallCount = 0;
|
||||
|
||||
// First call → 429, second call → 201
|
||||
@@ -436,31 +435,35 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
renderDrawer();
|
||||
render(
|
||||
<NuqsTestingAdapter searchParams={{ account: 'sa-1' }} hasMemory>
|
||||
<ServiceAccountDrawer onSuccess={onSuccess} />
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
|
||||
await screen.findByDisplayValue('CI Bot');
|
||||
|
||||
await user.click(screen.getByLabelText('Roles'));
|
||||
await user.click(await screen.findByTitle('signoz-viewer'));
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
await user.click(saveBtn);
|
||||
|
||||
// Retried after 429 — at least 2 calls, no error shown
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(roleAddCallCount).toBeGreaterThanOrEqual(2);
|
||||
},
|
||||
{ timeout: 5000 },
|
||||
await waitFor(() => expect(roleAddCallCount).toBe(1));
|
||||
await act(() => jest.advanceTimersByTimeAsync(1000));
|
||||
await waitFor(() =>
|
||||
expect(onSuccess).toHaveBeenCalledWith({ closeDrawer: false }),
|
||||
);
|
||||
expect(roleAddCallCount).toBe(2);
|
||||
expect(screen.queryByText(/role assign failed/i)).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('sa-error-retry-btn')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking Retry on a name-update error re-triggers the request; on success the error item is removed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
// First: PUT always fails so the error appears
|
||||
server.use(
|
||||
@@ -483,7 +486,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'Retry Test');
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
@@ -499,7 +502,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
),
|
||||
);
|
||||
|
||||
const retryBtn = screen.getByRole('button', { name: /Retry/i });
|
||||
const retryBtn = screen.getByTestId('sa-error-retry-btn');
|
||||
await user.click(retryBtn);
|
||||
|
||||
// Error item should be removed after successful retry
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import TagKeyValueInput from './TagKeyValueInput';
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ export const getComponentForPanelType = (
|
||||
// V2-only kind; it renders through the V2 panel registry.
|
||||
[PANEL_TYPES.HEATMAP]: null,
|
||||
[PANEL_TYPES.GEO_MAP]: null,
|
||||
[PANEL_TYPES.TOP_LIST]: null,
|
||||
// Dashboards v2 renders this kind; nothing reaches the V1 chart map for it.
|
||||
[PANEL_TYPES.TEXT]: null,
|
||||
[PANEL_TYPES.SCATTER]: null,
|
||||
|
||||
@@ -311,14 +311,10 @@ export const initialQueryMeterWithType: Query = {
|
||||
|
||||
export const initialQueryAIWithType: Query = {
|
||||
...initialQueryWithType,
|
||||
builder: {
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder_ai_query: {
|
||||
...initialQueryWithType.builder,
|
||||
queryData: [
|
||||
{
|
||||
...initialQueryBuilderFormValuesMap.traces,
|
||||
builderQueryType: 'builder_ai_query',
|
||||
},
|
||||
],
|
||||
queryData: [initialQueryBuilderFormValuesMap.traces],
|
||||
},
|
||||
};
|
||||
|
||||
@@ -341,6 +337,7 @@ export enum PANEL_TYPES {
|
||||
HISTOGRAM = 'histogram',
|
||||
HEATMAP = 'heatmap',
|
||||
GEO_MAP = 'geo_map',
|
||||
TOP_LIST = 'top_list',
|
||||
TEXT = 'text',
|
||||
EMPTY_WIDGET = 'EMPTY_WIDGET',
|
||||
}
|
||||
|
||||
@@ -56,6 +56,8 @@
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
gap: 7px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
@@ -63,6 +65,7 @@
|
||||
}
|
||||
|
||||
.shortcut {
|
||||
flex-shrink: 0;
|
||||
font-size: 10px;
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-weight: 500;
|
||||
@@ -81,6 +84,7 @@
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { TextEllipsis } from '@signozhq/ui/text-ellipsis';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
normalizePage,
|
||||
useAIAssistantAnalyticsContext,
|
||||
} from '../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useActiveChatTitle } from '../hooks/useActiveChatTitle';
|
||||
import { useAIAssistantStore } from '../store/useAIAssistantStore';
|
||||
import { VariantContext } from '../VariantContext';
|
||||
|
||||
@@ -39,6 +41,7 @@ export default function AIAssistantModal(): JSX.Element | null {
|
||||
const activeConversationId = useAIAssistantStore(
|
||||
(s) => s.activeConversationId,
|
||||
);
|
||||
const chatTitle = useActiveChatTitle();
|
||||
const openModal = useAIAssistantStore((s) => s.openModal);
|
||||
const closeModal = useAIAssistantStore((s) => s.closeModal);
|
||||
const minimizeModal = useAIAssistantStore((s) => s.minimizeModal);
|
||||
@@ -151,7 +154,7 @@ export default function AIAssistantModal(): JSX.Element | null {
|
||||
<div className={styles.header}>
|
||||
<div className={`${styles.title} noz-wave`}>
|
||||
<Noz size={16} />
|
||||
<span>Noz</span>
|
||||
{chatTitle && <TextEllipsis position="end">{chatTitle}</TextEllipsis>}
|
||||
<kbd className={styles.shortcut}>
|
||||
<span>⌘</span>
|
||||
<span>J</span>
|
||||
|
||||
@@ -1,39 +1,3 @@
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
height: 100%;
|
||||
border-left: 1px solid var(--l1-border);
|
||||
background: var(--l1-background);
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.resizeHandle {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 4px;
|
||||
height: 100%;
|
||||
cursor: col-resize;
|
||||
z-index: 10;
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 1px;
|
||||
width: 2px;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
transition: background 0.15s ease;
|
||||
}
|
||||
|
||||
&:hover::after {
|
||||
background: var(--accent-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -47,6 +11,8 @@
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
@@ -55,6 +21,7 @@
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { TextEllipsis } from '@signozhq/ui/text-ellipsis';
|
||||
import { matchRoute } from 'lib/router/matchRoute';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
@@ -7,6 +8,9 @@ import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { History, Maximize2, Plus, X } from '@signozhq/icons';
|
||||
import Noz from 'components/Noz/Noz';
|
||||
import { BOTTOM_STRIP_HEIGHT } from 'container/BottomStrip';
|
||||
import { supportChatObstacle } from 'container/BottomStrip/SupportButton/supportChatObstacle';
|
||||
import { FloatingPanel } from 'periscope/components/FloatingPanel';
|
||||
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
@@ -14,13 +18,28 @@ import ConversationsList from '../components/ConversationsList';
|
||||
import ConversationView from '../ConversationView';
|
||||
import { AIAssistantEvents } from '../events';
|
||||
import { useAIAssistantAnalyticsContext } from '../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useActiveChatTitle } from '../hooks/useActiveChatTitle';
|
||||
import { useAIAssistantStore } from '../store/useAIAssistantStore';
|
||||
import { VariantContext } from '../VariantContext';
|
||||
|
||||
import styles from './AIAssistantPanel.module.scss';
|
||||
|
||||
const AI_ASSISTANT_PANEL_OPEN_CLASS = 'ai-assistant-panel-open';
|
||||
const AI_ASSISTANT_PANEL_WIDTH_VAR = '--ai-assistant-panel-width';
|
||||
const PANEL_WIDTH = 420;
|
||||
const PANEL_HEIGHT = 601;
|
||||
const PANEL_MIN_WIDTH = 380;
|
||||
const PANEL_MIN_HEIGHT = 500;
|
||||
const PANEL_MARGIN = 8;
|
||||
const PANEL_RESIZE_EDGES = {
|
||||
top: true,
|
||||
right: true,
|
||||
bottom: true,
|
||||
left: true,
|
||||
topRight: false,
|
||||
bottomRight: false,
|
||||
bottomLeft: false,
|
||||
topLeft: false,
|
||||
};
|
||||
const PANEL_AVOID = [supportChatObstacle];
|
||||
|
||||
export default function AIAssistantPanel(): JSX.Element | null {
|
||||
const { pathname } = useAppLocation();
|
||||
@@ -38,6 +57,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
(s) => s.startNewConversation,
|
||||
);
|
||||
const analyticsCtx = useAIAssistantAnalyticsContext();
|
||||
const chatTitle = useActiveChatTitle();
|
||||
|
||||
const handleExpand = useCallback(() => {
|
||||
if (!activeConversationId) {
|
||||
@@ -72,75 +92,36 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
setShowHistory(false);
|
||||
}, []);
|
||||
|
||||
// ── Resize logic ──────────────────────────────────────────────────────────
|
||||
const [panelWidth, setPanelWidth] = useState(380);
|
||||
const dragStartX = useRef(0);
|
||||
const dragStartWidth = useRef(0);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const shouldOffsetChatSupport = isOpen && !isFullScreenPage;
|
||||
|
||||
document.body.classList.toggle(
|
||||
AI_ASSISTANT_PANEL_OPEN_CLASS,
|
||||
shouldOffsetChatSupport,
|
||||
);
|
||||
|
||||
if (shouldOffsetChatSupport) {
|
||||
document.body.style.setProperty(
|
||||
AI_ASSISTANT_PANEL_WIDTH_VAR,
|
||||
`${panelWidth}px`,
|
||||
);
|
||||
} else {
|
||||
document.body.style.removeProperty(AI_ASSISTANT_PANEL_WIDTH_VAR);
|
||||
}
|
||||
|
||||
return (): void => {
|
||||
document.body.classList.remove(AI_ASSISTANT_PANEL_OPEN_CLASS);
|
||||
document.body.style.removeProperty(AI_ASSISTANT_PANEL_WIDTH_VAR);
|
||||
};
|
||||
}, [isFullScreenPage, isOpen, panelWidth]);
|
||||
|
||||
const handleResizeMouseDown = useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
dragStartX.current = e.clientX;
|
||||
dragStartWidth.current = panelWidth;
|
||||
|
||||
const onMouseMove = (ev: MouseEvent): void => {
|
||||
// Panel is on the right; dragging left (lower clientX) increases width
|
||||
const delta = dragStartX.current - ev.clientX;
|
||||
const next = Math.min(Math.max(dragStartWidth.current + delta, 380), 800);
|
||||
setPanelWidth(next);
|
||||
};
|
||||
|
||||
const onMouseUp = (): void => {
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
document.body.style.cursor = '';
|
||||
document.body.style.userSelect = '';
|
||||
};
|
||||
|
||||
document.body.style.cursor = 'col-resize';
|
||||
document.body.style.userSelect = 'none';
|
||||
document.addEventListener('mousemove', onMouseMove);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
},
|
||||
[panelWidth],
|
||||
);
|
||||
|
||||
if (!isOpen || isFullScreenPage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const availableHeight = Math.max(
|
||||
0,
|
||||
window.innerHeight - BOTTOM_STRIP_HEIGHT - 2 * PANEL_MARGIN,
|
||||
);
|
||||
const panelHeight = Math.min(PANEL_HEIGHT, availableHeight);
|
||||
|
||||
return (
|
||||
<VariantContext.Provider value="panel">
|
||||
<div className={styles.panel} style={{ width: panelWidth }}>
|
||||
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
|
||||
<div className={styles.resizeHandle} onMouseDown={handleResizeMouseDown} />
|
||||
<div className={styles.header}>
|
||||
<FloatingPanel
|
||||
isOpen
|
||||
width={PANEL_WIDTH}
|
||||
height={panelHeight}
|
||||
minWidth={PANEL_MIN_WIDTH}
|
||||
minHeight={Math.min(PANEL_MIN_HEIGHT, availableHeight)}
|
||||
enableResizing={PANEL_RESIZE_EDGES}
|
||||
keepInViewport
|
||||
avoid={PANEL_AVOID}
|
||||
defaultPosition={{
|
||||
x: window.innerWidth - PANEL_WIDTH - PANEL_MARGIN,
|
||||
y: PANEL_MARGIN + availableHeight - panelHeight,
|
||||
}}
|
||||
>
|
||||
<div className={`${styles.header} floating-panel__drag-handle`}>
|
||||
<div className={`${styles.title} noz-wave`}>
|
||||
<Noz size={18} />
|
||||
<span>Noz</span>
|
||||
{chatTitle && <TextEllipsis position="end">{chatTitle}</TextEllipsis>}
|
||||
</div>
|
||||
|
||||
<div className={styles.actions}>
|
||||
@@ -191,6 +172,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
size="sm"
|
||||
icon
|
||||
color="secondary"
|
||||
testId="ai-assistant-panel-close"
|
||||
onClick={closeDrawer}
|
||||
aria-label="Close panel"
|
||||
>
|
||||
@@ -207,7 +189,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
<ConversationView conversationId={activeConversationId} />
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</FloatingPanel>
|
||||
</VariantContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,13 +17,17 @@
|
||||
|
||||
.empty {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
// `safe` falls back to the top once the content overflows, so it stays scrollable.
|
||||
justify-content: safe center;
|
||||
padding: 32px 24px;
|
||||
gap: 8px;
|
||||
text-align: center;
|
||||
@include scrollbar;
|
||||
}
|
||||
|
||||
.emptyIcon {
|
||||
@@ -54,6 +58,7 @@
|
||||
}
|
||||
|
||||
.suggestion {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--l2-border);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
|
||||
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
|
||||
import type { Conversation } from '../../types';
|
||||
import { NEW_CHAT_TITLE, useActiveChatTitle } from '../useActiveChatTitle';
|
||||
|
||||
const initialState = useAIAssistantStore.getState();
|
||||
|
||||
const open = (conversation: Conversation): void => {
|
||||
useAIAssistantStore.setState({
|
||||
conversations: { [conversation.id]: conversation },
|
||||
activeConversationId: conversation.id,
|
||||
});
|
||||
};
|
||||
|
||||
describe('useActiveChatTitle', () => {
|
||||
afterEach(() => {
|
||||
useAIAssistantStore.setState(initialState, true);
|
||||
});
|
||||
|
||||
it('is the open chat’s title', () => {
|
||||
open({ id: 'a', title: 'Checkout p99', messages: [], createdAt: 0 });
|
||||
|
||||
const { result } = renderHook(() => useActiveChatTitle());
|
||||
|
||||
expect(result.current).toBe('Checkout p99');
|
||||
});
|
||||
|
||||
it('is "New chat" until the chat has a title', () => {
|
||||
open({ id: 'a', messages: [], createdAt: 0 });
|
||||
|
||||
const { result } = renderHook(() => useActiveChatTitle());
|
||||
|
||||
expect(result.current).toBe(NEW_CHAT_TITLE);
|
||||
});
|
||||
|
||||
it('is empty while a restored chat loads, rather than flashing "New chat"', () => {
|
||||
open({ id: 'a', messages: [], createdAt: 0, isHydrating: true });
|
||||
|
||||
const { result } = renderHook(() => useActiveChatTitle());
|
||||
|
||||
expect(result.current).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useAIAssistantStore } from '../store/useAIAssistantStore';
|
||||
|
||||
export const NEW_CHAT_TITLE = 'New chat';
|
||||
|
||||
/** The open chat's title for a header: "New chat" until it has one, null while a restored chat loads. */
|
||||
export function useActiveChatTitle(): string | null {
|
||||
return useAIAssistantStore((s) => {
|
||||
const conversation = s.activeConversationId
|
||||
? s.conversations[s.activeConversationId]
|
||||
: undefined;
|
||||
if (conversation?.title) {
|
||||
return conversation.title;
|
||||
}
|
||||
return conversation?.isHydrating ? null : NEW_CHAT_TITLE;
|
||||
});
|
||||
}
|
||||
@@ -13,6 +13,11 @@ import {
|
||||
Query,
|
||||
TagFilterItem,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import {
|
||||
getBuilderBySlotKey,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
replaceBuilderBySlotKey,
|
||||
} from 'lib/query/builderSlot';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
/** Param shape emitted by the AI for every filter-touching action. */
|
||||
@@ -56,12 +61,14 @@ export function replaceFirstQueryData(
|
||||
query: Query,
|
||||
updated: IBuilderQuery,
|
||||
): Query {
|
||||
const queryData = [...query.builder.queryData];
|
||||
const slotKey = getBuilderSlotKeyForQueryType(query.queryType);
|
||||
const activeBuilder = getBuilderBySlotKey(query, slotKey);
|
||||
const queryData = [...activeBuilder.queryData];
|
||||
queryData[0] = updated;
|
||||
return {
|
||||
...query,
|
||||
builder: { ...query.builder, queryData },
|
||||
};
|
||||
return replaceBuilderBySlotKey(query, slotKey, {
|
||||
...activeBuilder,
|
||||
queryData,
|
||||
});
|
||||
}
|
||||
|
||||
/** Page-state deps required by the runQuery / addFilter actions. */
|
||||
|
||||
@@ -66,6 +66,10 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('commits a manually-retryable error bubble with friendly copy and metadata', async () => {
|
||||
chat.createThread.mockResolvedValue('thread-1');
|
||||
chat.sendMessage.mockResolvedValue('exec-1');
|
||||
@@ -135,6 +139,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
});
|
||||
|
||||
it('silently retries auto-flagged errors, then downgrades to manual once spent', async () => {
|
||||
jest.useFakeTimers();
|
||||
chat.createThread.mockResolvedValue('thread-2');
|
||||
chat.sendMessage.mockResolvedValue('exec');
|
||||
// Always auto-retryable: 1 initial attempt + MAX_AUTO_RETRIES (2) = 3 sends.
|
||||
@@ -145,7 +150,9 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
);
|
||||
|
||||
useAIAssistantStore.getState().startNewConversation();
|
||||
await useAIAssistantStore.getState().sendMessage('hi');
|
||||
const sending = useAIAssistantStore.getState().sendMessage('hi');
|
||||
await jest.runAllTimersAsync();
|
||||
await sending;
|
||||
|
||||
expect(chat.sendMessage).toHaveBeenCalledTimes(3);
|
||||
expect(lastMessage('thread-2')).toMatchObject({
|
||||
@@ -154,7 +161,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
// Auto budget exhausted → presented as manual so a Retry button shows.
|
||||
retryAction: RetryActionDTO.manual,
|
||||
});
|
||||
}, 10000);
|
||||
});
|
||||
|
||||
it('marks rate-limit errors and offers no retry', async () => {
|
||||
chat.createThread.mockResolvedValue('thread-3');
|
||||
@@ -184,6 +191,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
});
|
||||
|
||||
it('recovers silently when an auto-flagged error succeeds on retry', async () => {
|
||||
jest.useFakeTimers();
|
||||
chat.createThread.mockResolvedValue('thread-4');
|
||||
chat.sendMessage.mockResolvedValue('exec');
|
||||
chat.streamEvents
|
||||
@@ -205,7 +213,9 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
);
|
||||
|
||||
useAIAssistantStore.getState().startNewConversation();
|
||||
await useAIAssistantStore.getState().sendMessage('hi');
|
||||
const sending = useAIAssistantStore.getState().sendMessage('hi');
|
||||
await jest.runAllTimersAsync();
|
||||
await sending;
|
||||
|
||||
// 1 initial attempt + 1 silent auto retry, then success — no error bubble.
|
||||
expect(chat.sendMessage).toHaveBeenCalledTimes(2);
|
||||
@@ -217,7 +227,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
content: 'Recovered',
|
||||
});
|
||||
expect(conv.messages.some((m) => m.isError)).toBe(false);
|
||||
}, 10000);
|
||||
});
|
||||
|
||||
it('replays the originating action on retry for a non-send error (approve)', async () => {
|
||||
chat.approveExecution.mockResolvedValue('exec-a');
|
||||
|
||||
@@ -26,8 +26,6 @@ window.ResizeObserver =
|
||||
}));
|
||||
|
||||
describe('BillingContainer', () => {
|
||||
jest.setTimeout(30000);
|
||||
|
||||
beforeEach(() => {
|
||||
server.use(setupAuthzAdmin());
|
||||
});
|
||||
@@ -39,40 +37,47 @@ describe('BillingContainer', () => {
|
||||
it('Component should render', async () => {
|
||||
render(<BillingContainer />);
|
||||
|
||||
const dataInjection = await screen.findByRole('columnheader', {
|
||||
name: /data ingested/i,
|
||||
});
|
||||
expect(dataInjection).toBeInTheDocument();
|
||||
const pricePerUnit = await screen.findByRole('columnheader', {
|
||||
name: /price per unit/i,
|
||||
});
|
||||
expect(pricePerUnit).toBeInTheDocument();
|
||||
const cost = await screen.findByRole('columnheader', {
|
||||
name: /cost/i,
|
||||
});
|
||||
expect(cost).toBeInTheDocument();
|
||||
|
||||
const dayRemainingInBillingPeriod = await screen.findByText(
|
||||
/Please upgrade plan now to retain your data./i,
|
||||
{},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
expect(dayRemainingInBillingPeriod).toBeInTheDocument();
|
||||
|
||||
expect(
|
||||
screen.getByText('Data Ingested', { selector: 'th' }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('Price per Unit', { selector: 'th' }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('Cost', { selector: 'th' })).toBeInTheDocument();
|
||||
|
||||
const upgradePlanButton = screen.getByTestId('upgrade-plan-button');
|
||||
expect(upgradePlanButton).toBeInTheDocument();
|
||||
|
||||
const dollar = await screen.findByText(/\$1,278.3/i, {}, { timeout: 5000 });
|
||||
expect(dollar).toBeInTheDocument();
|
||||
|
||||
const currentBill = await screen.findByText('billing');
|
||||
expect(currentBill).toBeInTheDocument();
|
||||
expect(screen.getByText(/\$1,278.3/i)).toBeInTheDocument();
|
||||
expect(screen.getByText('billing')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('Trial scenarios', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
jest.setSystemTime(new Date('2023-10-20'));
|
||||
jest.useFakeTimers({
|
||||
now: new Date('2023-10-20'),
|
||||
doNotFake: [
|
||||
'hrtime',
|
||||
'nextTick',
|
||||
'performance',
|
||||
'queueMicrotask',
|
||||
'requestAnimationFrame',
|
||||
'cancelAnimationFrame',
|
||||
'requestIdleCallback',
|
||||
'cancelIdleCallback',
|
||||
'setImmediate',
|
||||
'clearImmediate',
|
||||
'setInterval',
|
||||
'clearInterval',
|
||||
'setTimeout',
|
||||
'clearTimeout',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -88,14 +93,9 @@ describe('BillingContainer', () => {
|
||||
{ appContextOverrides: { trialInfo: licensesSuccessResponse.data } },
|
||||
);
|
||||
|
||||
// If the component schedules any setTimeout on mount, flush them:
|
||||
jest.runOnlyPendingTimers();
|
||||
|
||||
await expect(screen.findByText('Free Trial')).resolves.toBeInTheDocument();
|
||||
await expect(screen.findByText('billing')).resolves.toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByText(/\$0/i, {}, { timeout: 5000 }),
|
||||
).resolves.toBeInTheDocument();
|
||||
await expect(screen.findByText(/\$0/i)).resolves.toBeInTheDocument();
|
||||
|
||||
await expect(
|
||||
screen.findByText(
|
||||
@@ -107,18 +107,20 @@ describe('BillingContainer', () => {
|
||||
screen.findByText(/1 days_remaining/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
const upgradeButtons = await screen.findAllByRole('button', {
|
||||
name: /upgrade_plan/i,
|
||||
});
|
||||
expect(upgradeButtons).toHaveLength(2);
|
||||
expect(upgradeButtons[1]).toBeInTheDocument();
|
||||
expect(screen.getByTestId('header-billing-button')).toHaveTextContent(
|
||||
'upgrade_plan',
|
||||
);
|
||||
expect(screen.getByTestId('upgrade-plan-button')).toHaveTextContent(
|
||||
'upgrade_plan',
|
||||
);
|
||||
|
||||
await expect(
|
||||
screen.findByText(/checkout_plans/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByRole('link', { name: /here/i }),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText('here', { selector: 'a' })).toHaveAttribute(
|
||||
'href',
|
||||
'https://signoz.io/pricing/',
|
||||
);
|
||||
|
||||
await expect(
|
||||
screen.findByText('Cancel your subscription', { selector: 'span' }),
|
||||
@@ -141,7 +143,7 @@ describe('BillingContainer', () => {
|
||||
const currentBill = await screen.findByText('billing');
|
||||
expect(currentBill).toBeInTheDocument();
|
||||
|
||||
const dollar0 = await screen.findByText(/\$0/i, {}, { timeout: 5000 });
|
||||
const dollar0 = await screen.findByText(/\$0/i);
|
||||
expect(dollar0).toBeInTheDocument();
|
||||
|
||||
const onTrail = await screen.findByText(
|
||||
@@ -154,10 +156,9 @@ describe('BillingContainer', () => {
|
||||
);
|
||||
expect(receivedCardDetails).toBeInTheDocument();
|
||||
|
||||
const manageBillingButton = await screen.findByRole('button', {
|
||||
name: /manage_billing/i,
|
||||
});
|
||||
expect(manageBillingButton).toBeInTheDocument();
|
||||
expect(screen.getByTestId('header-billing-button')).toHaveTextContent(
|
||||
'manage_billing',
|
||||
);
|
||||
|
||||
const dayRemainingInBillingPeriod =
|
||||
await screen.findByText(/1 days_remaining/i);
|
||||
@@ -259,27 +260,26 @@ describe('BillingContainer', () => {
|
||||
billingSuccessResponse.data.billingPeriodStart,
|
||||
)} to ${getFormattedDate(billingSuccessResponse.data.billingPeriodEnd)}`;
|
||||
|
||||
const billingPeriod = await findByText(
|
||||
billingPeriodText,
|
||||
{},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
const billingPeriod = await findByText(billingPeriodText);
|
||||
expect(billingPeriod).toBeInTheDocument();
|
||||
|
||||
const currentBill = await screen.findByText('billing');
|
||||
expect(currentBill).toBeInTheDocument();
|
||||
expect(screen.getByText('billing')).toBeInTheDocument();
|
||||
expect(screen.getByText(/\$1,278.3/i)).toBeInTheDocument();
|
||||
|
||||
const dollar0 = await screen.findByText(/\$1,278.3/i);
|
||||
expect(dollar0).toBeInTheDocument();
|
||||
const cellTexts = (rowName: string): string[] =>
|
||||
Array.from(
|
||||
screen
|
||||
.getByText(rowName, { selector: 'td > div' })
|
||||
.closest('tr')
|
||||
?.querySelectorAll('td') ?? [],
|
||||
).map((cell) => cell.textContent ?? '');
|
||||
|
||||
const metricsRow = await screen.findByRole('row', {
|
||||
name: /metrics 4012 Million 0.1 \$ 401.2/i,
|
||||
});
|
||||
expect(metricsRow).toBeInTheDocument();
|
||||
|
||||
const logRow = await screen.findByRole('row', {
|
||||
name: /Logs 497 GB 0.4 \$ 198.8/i,
|
||||
});
|
||||
expect(logRow).toBeInTheDocument();
|
||||
expect(cellTexts('Metrics')).toStrictEqual([
|
||||
'Metrics',
|
||||
'4012 Million',
|
||||
'0.1',
|
||||
'$ 401.2',
|
||||
]);
|
||||
expect(cellTexts('Logs')).toStrictEqual(['Logs', '497 GB', '0.4', '$ 198.8']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -23,7 +23,8 @@ import styles from './AskNoz.module.scss';
|
||||
|
||||
/**
|
||||
* Opens the Noz drawer, matching the header entry it replaces. Cmd+K opens the
|
||||
* modal instead; this is deliberately the drawer.
|
||||
* modal instead; this is deliberately the drawer. It stays while the drawer is
|
||||
* open, where it closes the drawer and keeps the chat for the next open.
|
||||
*
|
||||
* Carries the header's pending badge: when Noz is blocked on the user
|
||||
* (`awaiting_approval` / `awaiting_clarification`) a dot pulses. Without it,
|
||||
@@ -38,21 +39,28 @@ function AskNoz(): JSX.Element | null {
|
||||
selectPendingUserInputStreamCount,
|
||||
);
|
||||
|
||||
// Noz is already on screen in the modal, so the "needs you" dot would be noise.
|
||||
const showPendingBadge = pendingUserInputCount > 0 && !isModalOpen;
|
||||
const closeDrawer = useAIAssistantStore((state) => state.closeDrawer);
|
||||
|
||||
// Noz is already on screen in the drawer or modal, so the "needs you" dot would be noise.
|
||||
const showPendingBadge =
|
||||
pendingUserInputCount > 0 && !isDrawerOpen && !isModalOpen;
|
||||
|
||||
// The drawer does not render on the Noz full page, so the button would be inert.
|
||||
const isAIAssistantPage = pathname.startsWith(ROUTES.AI_ASSISTANT_BASE);
|
||||
|
||||
const handleOpen = useCallback((): void => {
|
||||
const handleClick = useCallback((): void => {
|
||||
if (isDrawerOpen) {
|
||||
closeDrawer();
|
||||
return;
|
||||
}
|
||||
void logEvent(AIAssistantEvents.Opened, {
|
||||
source: AIAssistantOpenSource.BottomStrip,
|
||||
currentPage: normalizePage(pathname),
|
||||
});
|
||||
openAIAssistant();
|
||||
}, [pathname]);
|
||||
}, [closeDrawer, isDrawerOpen, pathname]);
|
||||
|
||||
if (!isAIAssistantEnabled || isDrawerOpen || isAIAssistantPage) {
|
||||
if (!isAIAssistantEnabled || isAIAssistantPage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -72,7 +80,9 @@ function AskNoz(): JSX.Element | null {
|
||||
color="secondary"
|
||||
size="sm"
|
||||
prefix={<Noz size={16} />}
|
||||
onClick={handleOpen}
|
||||
testId="bottom-strip-ask-noz-button"
|
||||
onClick={handleClick}
|
||||
aria-pressed={isDrawerOpen}
|
||||
aria-label={
|
||||
showPendingBadge
|
||||
? `Ask Noz, ${pendingUserInputCount} ${
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { fireEvent } from '@testing-library/react';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import {
|
||||
AIAssistantEvents,
|
||||
@@ -6,15 +5,11 @@ import {
|
||||
} from 'container/AIAssistant/events';
|
||||
import { openAIAssistant } from 'container/AIAssistant/store/useAIAssistantStore';
|
||||
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
|
||||
import { render } from 'tests/test-utils';
|
||||
import { render, userEvent } from 'tests/test-utils';
|
||||
|
||||
import AskNoz from '../AskNoz';
|
||||
|
||||
jest.mock('hooks/useIsAIAssistantEnabled');
|
||||
jest.mock('api/common/logEvent', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn(),
|
||||
}));
|
||||
jest.mock('container/AIAssistant/store/useAIAssistantStore', () => ({
|
||||
openAIAssistant: jest.fn(),
|
||||
useAIAssistantStore: jest.fn(),
|
||||
@@ -24,6 +19,7 @@ const mockEnabled = useIsAIAssistantEnabled as jest.MockedFunction<
|
||||
typeof useIsAIAssistantEnabled
|
||||
>;
|
||||
const mockOpen = openAIAssistant as jest.MockedFunction<typeof openAIAssistant>;
|
||||
const mockClose = jest.fn() as jest.MockedFunction<() => void>;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const { useAIAssistantStore } = jest.requireMock(
|
||||
@@ -40,7 +36,12 @@ function mockStore({
|
||||
isModalOpen?: boolean;
|
||||
pendingCount?: number;
|
||||
} = {}): void {
|
||||
const state = { isDrawerOpen, isModalOpen, streams: {} };
|
||||
const state = {
|
||||
isDrawerOpen,
|
||||
isModalOpen,
|
||||
streams: {},
|
||||
closeDrawer: mockClose,
|
||||
};
|
||||
useAIAssistantStore.mockImplementation((selector: (s: unknown) => unknown) => {
|
||||
const picked = selector(state);
|
||||
// `selectPendingUserInputStreamCount` walks `streams`, which is empty here,
|
||||
@@ -49,9 +50,8 @@ function mockStore({
|
||||
});
|
||||
}
|
||||
|
||||
// `TooltipSimple` replaces its trigger's props, so the testId lives on the
|
||||
// wrapper and the button itself is reached by role — there is only ever one.
|
||||
const SLOT = 'bottom-strip-ask-noz';
|
||||
const BUTTON = 'bottom-strip-ask-noz-button';
|
||||
|
||||
describe('AskNoz', () => {
|
||||
beforeEach(() => {
|
||||
@@ -62,9 +62,9 @@ describe('AskNoz', () => {
|
||||
|
||||
describe('visibility', () => {
|
||||
it('renders when the assistant is enabled', () => {
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toBeInTheDocument();
|
||||
expect(getByTestId(BUTTON)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders nothing when the assistant is disabled', () => {
|
||||
@@ -75,12 +75,12 @@ describe('AskNoz', () => {
|
||||
expect(queryByTestId(SLOT)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders nothing while the drawer is open', () => {
|
||||
it('stays pressed while the drawer is open', () => {
|
||||
mockStore({ isDrawerOpen: true });
|
||||
|
||||
const { queryByTestId } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(queryByTestId(SLOT)).not.toBeInTheDocument();
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
|
||||
it('renders nothing on the Noz full page, where the drawer does not mount', () => {
|
||||
@@ -93,18 +93,32 @@ describe('AskNoz', () => {
|
||||
});
|
||||
|
||||
describe('what it does', () => {
|
||||
it('opens the drawer on click', () => {
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
it('opens the drawer on click', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
fireEvent.click(getByRole('button'));
|
||||
await user.click(getByTestId(BUTTON));
|
||||
|
||||
expect(mockOpen).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reports the open as coming from the strip', () => {
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
it('closes the open drawer on the same chat instead of starting a new one', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
mockStore({ isDrawerOpen: true });
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
fireEvent.click(getByRole('button'));
|
||||
await user.click(getByTestId(BUTTON));
|
||||
|
||||
expect(mockClose).toHaveBeenCalledTimes(1);
|
||||
expect(mockOpen).not.toHaveBeenCalled();
|
||||
expect(logEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports the open as coming from the strip', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
await user.click(getByTestId(BUTTON));
|
||||
|
||||
expect(logEvent).toHaveBeenCalledWith(
|
||||
AIAssistantEvents.Opened,
|
||||
@@ -117,9 +131,9 @@ describe('AskNoz', () => {
|
||||
it('announces the count when Noz is waiting on the user', () => {
|
||||
mockStore({ pendingCount: 2 });
|
||||
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toHaveAttribute(
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute(
|
||||
'aria-label',
|
||||
'Ask Noz, 2 actions need your response',
|
||||
);
|
||||
@@ -128,26 +142,34 @@ describe('AskNoz', () => {
|
||||
it('uses the singular for one pending action', () => {
|
||||
mockStore({ pendingCount: 1 });
|
||||
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toHaveAttribute(
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute(
|
||||
'aria-label',
|
||||
'Ask Noz, 1 action needs your response',
|
||||
);
|
||||
});
|
||||
|
||||
it('stays quiet when nothing is pending', () => {
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
});
|
||||
|
||||
it('stays quiet while the drawer is open, Noz is already on screen', () => {
|
||||
mockStore({ isDrawerOpen: true, pendingCount: 3 });
|
||||
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
});
|
||||
|
||||
it('stays quiet while the modal is open, Noz is already on screen', () => {
|
||||
mockStore({ isModalOpen: true, pendingCount: 3 });
|
||||
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { FloatingRect } from 'periscope/components/FloatingPanel/types';
|
||||
|
||||
import { supportChatObstacle } from '../supportChatObstacle';
|
||||
|
||||
type Pylon = Window['Pylon'];
|
||||
|
||||
const SUPPORT_CHAT: FloatingRect = { x: 882, y: 286, width: 384, height: 478 };
|
||||
const CLOSED_CLASS = 'PylonChat-chatWindowFrameContainer--closed';
|
||||
|
||||
const originalPylon = window.Pylon;
|
||||
const pylonCallbacks = new Map<string, unknown>();
|
||||
const unsubscribes: (() => void)[] = [];
|
||||
|
||||
function subscribe(onChange: () => void): () => void {
|
||||
const unsubscribe = supportChatObstacle.subscribe(onChange);
|
||||
unsubscribes.push(unsubscribe);
|
||||
return unsubscribe;
|
||||
}
|
||||
|
||||
function installPylon(): jest.MockedFunction<Pylon> {
|
||||
const pylon = jest.fn<ReturnType<Pylon>, Parameters<Pylon>>(
|
||||
(command, callback) => {
|
||||
pylonCallbacks.set(command, callback);
|
||||
},
|
||||
);
|
||||
window.Pylon = pylon;
|
||||
return pylon;
|
||||
}
|
||||
|
||||
function firePylon(event: 'onShow' | 'onHide'): void {
|
||||
const callback = pylonCallbacks.get(event);
|
||||
if (typeof callback === 'function') {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
|
||||
function renderSupportChat(): HTMLElement {
|
||||
const element = document.createElement('div');
|
||||
element.className = 'PylonChat-chatWindowFrameContainer';
|
||||
Object.defineProperties(element, {
|
||||
offsetLeft: { value: SUPPORT_CHAT.x },
|
||||
offsetTop: { value: SUPPORT_CHAT.y },
|
||||
offsetWidth: { value: SUPPORT_CHAT.width },
|
||||
offsetHeight: { value: SUPPORT_CHAT.height },
|
||||
});
|
||||
document.body.appendChild(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
describe('supportChatObstacle', () => {
|
||||
beforeEach(() => pylonCallbacks.clear());
|
||||
|
||||
afterEach(() => {
|
||||
unsubscribes.splice(0).forEach((unsubscribe) => unsubscribe());
|
||||
window.Pylon = originalPylon;
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('reports the chat window box only while it is open', () => {
|
||||
const chat = renderSupportChat();
|
||||
|
||||
expect(supportChatObstacle.getRect()).toStrictEqual(SUPPORT_CHAT);
|
||||
|
||||
chat.classList.add(CLOSED_CLASS);
|
||||
|
||||
expect(supportChatObstacle.getRect()).toBeNull();
|
||||
});
|
||||
|
||||
it('treats the chat as closed once Pylon reports it hidden', () => {
|
||||
installPylon();
|
||||
renderSupportChat();
|
||||
subscribe(jest.fn());
|
||||
|
||||
firePylon('onHide');
|
||||
|
||||
expect(supportChatObstacle.getRect()).toBeNull();
|
||||
});
|
||||
|
||||
it('notifies every subscriber through one Pylon registration', () => {
|
||||
const pylon = installPylon();
|
||||
const first = jest.fn() as jest.MockedFunction<() => void>;
|
||||
const second = jest.fn() as jest.MockedFunction<() => void>;
|
||||
subscribe(first);
|
||||
subscribe(second);
|
||||
|
||||
firePylon('onShow');
|
||||
|
||||
expect(pylon.mock.calls.map(([command]) => command)).toStrictEqual([
|
||||
'onShow',
|
||||
'onHide',
|
||||
]);
|
||||
expect(first).toHaveBeenCalledTimes(1);
|
||||
expect(second).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('unregisters through the loaded widget, not the stub it registered with', () => {
|
||||
const stub = installPylon();
|
||||
const unsubscribe = subscribe(jest.fn());
|
||||
// Pylon's script swaps out the queueing stub, which then can no longer be called.
|
||||
const widget = installPylon();
|
||||
|
||||
unsubscribe();
|
||||
|
||||
expect(stub.mock.calls.map(([command]) => command)).toStrictEqual([
|
||||
'onShow',
|
||||
'onHide',
|
||||
]);
|
||||
expect(widget.mock.calls).toStrictEqual([
|
||||
['onShow', null],
|
||||
['onHide', null],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import type {
|
||||
FloatingObstacle,
|
||||
FloatingRect,
|
||||
} from 'periscope/components/FloatingPanel/types';
|
||||
|
||||
// Pylon's own class names, which styles.scss also targets.
|
||||
const SUPPORT_CHAT_SELECTOR = '.PylonChat-chatWindowFrameContainer';
|
||||
const SUPPORT_CHAT_CLOSED_CLASS = 'PylonChat-chatWindowFrameContainer--closed';
|
||||
|
||||
const listeners = new Set<() => void>();
|
||||
// Pylon's last show/hide while subscribed; undefined until one arrives.
|
||||
let isOpen: boolean | undefined;
|
||||
|
||||
function setOpen(open: boolean): void {
|
||||
isOpen = open;
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
const onShow = (): void => setOpen(true);
|
||||
const onHide = (): void => setOpen(false);
|
||||
|
||||
// Offsets ignore the scale animation Pylon opens with, so this is the settled box.
|
||||
function getSupportChatRect(): FloatingRect | null {
|
||||
const element = document.querySelector<HTMLElement>(SUPPORT_CHAT_SELECTOR);
|
||||
if (!element) {
|
||||
return null;
|
||||
}
|
||||
// Pylon's event decides; the class covers a chat opened before anyone subscribed.
|
||||
if (!(isOpen ?? !element.classList.contains(SUPPORT_CHAT_CLOSED_CLASS))) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
x: element.offsetLeft,
|
||||
y: element.offsetTop,
|
||||
width: element.offsetWidth,
|
||||
height: element.offsetHeight,
|
||||
};
|
||||
}
|
||||
|
||||
function subscribeToSupportChat(onChange: () => void): () => void {
|
||||
if (!window.Pylon) {
|
||||
return (): void => undefined;
|
||||
}
|
||||
listeners.add(onChange);
|
||||
// Pylon keeps a single callback per event, so all listeners share one registration.
|
||||
if (listeners.size === 1) {
|
||||
window.Pylon('onShow', onShow);
|
||||
window.Pylon('onHide', onHide);
|
||||
}
|
||||
return (): void => {
|
||||
listeners.delete(onChange);
|
||||
if (listeners.size === 0) {
|
||||
isOpen = undefined;
|
||||
// Read `window.Pylon` again: once loaded, the widget replaces the stub, which then throws.
|
||||
window.Pylon?.('onShow', null);
|
||||
window.Pylon?.('onHide', null);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const supportChatObstacle: FloatingObstacle = {
|
||||
getRect: getSupportChatRect,
|
||||
subscribe: subscribeToSupportChat,
|
||||
};
|
||||
@@ -40,6 +40,7 @@ export function getQueryNames(currentQuery: Query): BaseOptionType[] {
|
||||
[EQueryType.PROM]: () => getSelectedQueryOptions(currentQuery.promql),
|
||||
[EQueryType.CLICKHOUSE]: () =>
|
||||
getSelectedQueryOptions(currentQuery.clickhouse_sql),
|
||||
[EQueryType.AI_QUERY_BUILDER]: () => [],
|
||||
};
|
||||
|
||||
return queryConfig[currentQuery.queryType]?.() || [];
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
background-color: var(--l1-background);
|
||||
border-top: 1px solid var(--l1-border);
|
||||
padding: 12px;
|
||||
z-index: 1000;
|
||||
// Below FloatingPanel (999), so the Noz panel stacks over the footer.
|
||||
z-index: 998;
|
||||
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
@@ -31,7 +32,3 @@
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
body.ai-assistant-panel-open .create-alert-v2-footer {
|
||||
right: var(--ai-assistant-panel-width, 380px);
|
||||
}
|
||||
|
||||
@@ -160,11 +160,14 @@ describe('jira reopen duration', () => {
|
||||
).toMatchObject({ reopenDuration: sent });
|
||||
});
|
||||
|
||||
it('leaves a duration it cannot parse for the validator to reject', () => {
|
||||
expect(
|
||||
toChannelConfig(ChannelKind.jira, { reopenDuration: 'tomorrow' }).spec,
|
||||
).toMatchObject({ reopenDuration: 'tomorrow' });
|
||||
});
|
||||
it.each(['tomorrow', '30m1h'])(
|
||||
'leaves %s, which it cannot parse, for the validator to reject',
|
||||
(typed) => {
|
||||
expect(
|
||||
toChannelConfig(ChannelKind.jira, { reopenDuration: typed }).spec,
|
||||
).toMatchObject({ reopenDuration: typed });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('jira deployment', () => {
|
||||
|
||||
@@ -1,31 +1,18 @@
|
||||
import {
|
||||
PROMETHEUS_DURATION_UNIT_MS,
|
||||
prometheusDurationToMs,
|
||||
} from 'utils/prometheusDuration';
|
||||
|
||||
import { ChannelFormValues, WebhookAuth } from './types';
|
||||
|
||||
// mirrors go's prometheus model.Duration units
|
||||
const JIRA_DURATION_UNIT_MS: Record<string, number> = {
|
||||
ms: 1,
|
||||
s: 1_000,
|
||||
m: 60_000,
|
||||
h: 3_600_000,
|
||||
d: 86_400_000,
|
||||
w: 604_800_000,
|
||||
y: 31_536_000_000,
|
||||
};
|
||||
const JIRA_DURATION_RE = /^(\d+(ms|s|m|h|d|w|y))+$/;
|
||||
const JIRA_DURATION_TOKEN_RE = /(\d+)(ms|s|m|h|d|w|y)/g;
|
||||
const JIRA_MIN_REOPEN_MS = 60_000;
|
||||
|
||||
export const isValidJiraReopenDuration = (value: string): boolean => {
|
||||
if (!value || value === '0') {
|
||||
return true;
|
||||
}
|
||||
if (!JIRA_DURATION_RE.test(value)) {
|
||||
return false;
|
||||
}
|
||||
let totalMs = 0;
|
||||
for (const [, amount, unit] of value.matchAll(JIRA_DURATION_TOKEN_RE)) {
|
||||
totalMs += Number(amount) * JIRA_DURATION_UNIT_MS[unit];
|
||||
}
|
||||
return totalMs >= JIRA_MIN_REOPEN_MS;
|
||||
const totalMs = prometheusDurationToMs(value);
|
||||
return totalMs !== null && totalMs >= JIRA_MIN_REOPEN_MS;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -33,25 +20,23 @@ export const isValidJiraReopenDuration = (value: string): boolean => {
|
||||
* back: "72h" becomes "3d", "7d" becomes "1w".
|
||||
*/
|
||||
const JIRA_DURATION_FORMAT: { unit: string; ms: number; exact: boolean }[] = [
|
||||
{ unit: 'y', ms: JIRA_DURATION_UNIT_MS.y, exact: true },
|
||||
{ unit: 'w', ms: JIRA_DURATION_UNIT_MS.w, exact: true },
|
||||
{ unit: 'd', ms: JIRA_DURATION_UNIT_MS.d, exact: false },
|
||||
{ unit: 'h', ms: JIRA_DURATION_UNIT_MS.h, exact: false },
|
||||
{ unit: 'm', ms: JIRA_DURATION_UNIT_MS.m, exact: false },
|
||||
{ unit: 's', ms: JIRA_DURATION_UNIT_MS.s, exact: false },
|
||||
{ unit: 'ms', ms: JIRA_DURATION_UNIT_MS.ms, exact: false },
|
||||
{ unit: 'y', ms: PROMETHEUS_DURATION_UNIT_MS.y, exact: true },
|
||||
{ unit: 'w', ms: PROMETHEUS_DURATION_UNIT_MS.w, exact: true },
|
||||
{ unit: 'd', ms: PROMETHEUS_DURATION_UNIT_MS.d, exact: false },
|
||||
{ unit: 'h', ms: PROMETHEUS_DURATION_UNIT_MS.h, exact: false },
|
||||
{ unit: 'm', ms: PROMETHEUS_DURATION_UNIT_MS.m, exact: false },
|
||||
{ unit: 's', ms: PROMETHEUS_DURATION_UNIT_MS.s, exact: false },
|
||||
{ unit: 'ms', ms: PROMETHEUS_DURATION_UNIT_MS.ms, exact: false },
|
||||
];
|
||||
|
||||
/** The API rejects a duration it would print differently. */
|
||||
export const canonicalJiraReopenDuration = (value: string): string => {
|
||||
if (!value || value === '0' || !JIRA_DURATION_RE.test(value)) {
|
||||
const totalMs = value && value !== '0' ? prometheusDurationToMs(value) : null;
|
||||
if (totalMs === null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
let remaining = 0;
|
||||
for (const [, amount, unit] of value.matchAll(JIRA_DURATION_TOKEN_RE)) {
|
||||
remaining += Number(amount) * JIRA_DURATION_UNIT_MS[unit];
|
||||
}
|
||||
let remaining = totalMs;
|
||||
if (remaining === 0) {
|
||||
return '0s';
|
||||
}
|
||||
|
||||
@@ -64,6 +64,31 @@ const multiOrgProps: ForgotPasswordRouteState = {
|
||||
orgs: mockMultipleOrgs,
|
||||
};
|
||||
|
||||
function mockForgot(): {
|
||||
forgotCalls: () => number;
|
||||
holdResponse: () => () => void;
|
||||
} {
|
||||
let calls = 0;
|
||||
let pending: Promise<void> = Promise.resolve();
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, async (_req, res, ctx) => {
|
||||
calls += 1;
|
||||
await pending;
|
||||
return res(ctx.status(200), ctx.json({ status: 'success' }));
|
||||
}),
|
||||
);
|
||||
return {
|
||||
forgotCalls: (): number => calls,
|
||||
holdResponse: (): (() => void) => {
|
||||
let release: () => void = () => {};
|
||||
pending = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
return release;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('ForgotPassword Component', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
@@ -136,7 +161,7 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('enables submit button after selecting an organization', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<ForgotPassword {...multiOrgProps} />);
|
||||
|
||||
@@ -144,7 +169,7 @@ describe('ForgotPassword Component', () => {
|
||||
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
// Click on the dropdown to reveal the options
|
||||
await user.click(screen.getByRole('combobox'));
|
||||
await user.click(screen.getByText('Select your organization'));
|
||||
await user.click(screen.getByText('Organization One'));
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -168,7 +193,7 @@ describe('ForgotPassword Component', () => {
|
||||
|
||||
describe('Form Submission - Success', () => {
|
||||
it('successfully submits forgot password request and shows success screen', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
|
||||
@@ -190,7 +215,7 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('shows back to login button on success screen', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
|
||||
@@ -209,7 +234,7 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('redirects to login when clicking back to login on success screen', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
|
||||
@@ -235,7 +260,7 @@ describe('ForgotPassword Component', () => {
|
||||
|
||||
describe('Form Submission - Error Handling', () => {
|
||||
it('displays error message when forgot password API fails', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(
|
||||
@@ -255,7 +280,7 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('displays error message when API returns server error', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(rest.post(FORGOT_PASSWORD_ENDPOINT, handleInternalServerError));
|
||||
|
||||
@@ -270,7 +295,7 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('clears error message on new submission attempt', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
let requestCount = 0;
|
||||
|
||||
server.use(
|
||||
@@ -314,7 +339,7 @@ describe('ForgotPassword Component', () => {
|
||||
|
||||
describe('Navigation', () => {
|
||||
it('redirects to login when clicking back button on form', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
@@ -327,13 +352,9 @@ describe('ForgotPassword Component', () => {
|
||||
|
||||
describe('Loading States', () => {
|
||||
it('shows loading state during API call', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
|
||||
res(ctx.delay(100), ctx.status(200), ctx.json({ status: 'success' })),
|
||||
),
|
||||
);
|
||||
mockForgot().holdResponse();
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
@@ -347,13 +368,9 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('disables submit button during loading', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
|
||||
res(ctx.delay(100), ctx.status(200), ctx.json({ status: 'success' })),
|
||||
),
|
||||
);
|
||||
mockForgot().holdResponse();
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
@@ -410,23 +427,8 @@ describe('ForgotPassword Component', () => {
|
||||
// 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 user = userEvent.setup();
|
||||
const { forgotCalls } = mockForgot();
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
@@ -443,7 +445,7 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('does not send on Enter while no organization is selected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const { forgotCalls } = mockForgot();
|
||||
|
||||
render(<ForgotPassword {...multiOrgProps} />);
|
||||
@@ -459,8 +461,9 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('does not send again on Enter while the first request is loading', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { forgotCalls } = mockForgot(1000);
|
||||
const user = userEvent.setup();
|
||||
const { forgotCalls, holdResponse } = mockForgot();
|
||||
const releaseResponse = holdResponse();
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
@@ -472,8 +475,9 @@ describe('ForgotPassword Component', () => {
|
||||
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
|
||||
await user.keyboard('{enter}');
|
||||
|
||||
releaseResponse();
|
||||
await expect(
|
||||
screen.findByText(/check your email/i, undefined, { timeout: 2000 }),
|
||||
screen.findByText(/check your email/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(forgotCalls()).toBe(1);
|
||||
});
|
||||
|
||||
@@ -644,6 +644,7 @@ function GeneralSettings({
|
||||
onClick={category.save.modalOpen}
|
||||
disabled={category.save.isDisabled}
|
||||
loading={category.save.isLoading}
|
||||
testId={`${category.type}-retention-save-button`}
|
||||
>
|
||||
{category.save.saveButtonText}
|
||||
</Button>
|
||||
@@ -671,6 +672,9 @@ function GeneralSettings({
|
||||
centered
|
||||
open={category.save.modal}
|
||||
confirmLoading={category.save.apiLoading}
|
||||
okButtonProps={{
|
||||
'data-testid': `${category.type}-retention-confirm-button`,
|
||||
}}
|
||||
>
|
||||
<p className="retention-modal-description">
|
||||
{t('retention_confirmation_description', {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import setRetentionApiV2 from 'api/settings/setRetentionV2';
|
||||
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
|
||||
import { fireEvent, render, screen, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { IDiskType } from 'types/api/disks/getDisks';
|
||||
import {
|
||||
PayloadPropsLogs,
|
||||
@@ -108,7 +108,8 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
});
|
||||
|
||||
describe('Test 1: S3 Enabled - Only Days in Dropdown', () => {
|
||||
it('should show only Days option for S3 retention and send correct API payload', async () => {
|
||||
it('should show only Days option for S3 retention', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<GeneralSettings
|
||||
metricsTtlValuesPayload={mockMetricsRetention}
|
||||
@@ -138,7 +139,7 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
expect(s3Dropdown).toBeInTheDocument();
|
||||
|
||||
// Click the S3 dropdown to open it
|
||||
fireEvent.mouseDown(s3Dropdown);
|
||||
await user.click(s3Dropdown);
|
||||
|
||||
// Wait for dropdown options to appear and verify only "Days" is available
|
||||
await waitFor(() => {
|
||||
@@ -146,33 +147,34 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
expect(dropdownOptions).toHaveLength(1);
|
||||
expect(dropdownOptions[0]).toHaveTextContent('Days');
|
||||
});
|
||||
});
|
||||
|
||||
// Close dropdown
|
||||
fireEvent.click(document.body);
|
||||
it('should send correct API payload for S3 retention', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<GeneralSettings
|
||||
metricsTtlValuesPayload={mockMetricsRetention}
|
||||
tracesTtlValuesPayload={mockTracesRetention}
|
||||
logsTtlValuesPayload={mockLogsRetentionWithS3}
|
||||
getAvailableDiskPayload={mockDisksWithS3}
|
||||
metricsTtlValuesRefetch={jest.fn()}
|
||||
tracesTtlValuesRefetch={jest.fn()}
|
||||
logsTtlValuesRefetch={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
const s3Input = getLogsRow().querySelectorAll('input[type="number"]')[1];
|
||||
|
||||
// Change S3 retention value to 5 days
|
||||
fireEvent.change(s3Input, { target: { value: '5' } });
|
||||
await user.clear(s3Input);
|
||||
await user.type(s3Input, '5');
|
||||
|
||||
// Find the save button in the Logs row
|
||||
const saveButton = logsRow.querySelector(
|
||||
'button:not([disabled])',
|
||||
) as HTMLButtonElement;
|
||||
expect(saveButton).toBeInTheDocument();
|
||||
const saveButton = screen.getByTestId('logs-retention-save-button');
|
||||
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
|
||||
await user.click(saveButton);
|
||||
|
||||
// Wait for button to be enabled
|
||||
await waitFor(() => {
|
||||
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
fireEvent.click(saveButton);
|
||||
|
||||
// Wait for modal to appear
|
||||
const modal = await screen.findByRole('dialog');
|
||||
expect(modal).toBeInTheDocument();
|
||||
|
||||
// Click OK button
|
||||
const okButton = await screen.findByRole('button', { name: /ok/i });
|
||||
fireEvent.click(okButton);
|
||||
// Wait for modal to appear and click OK
|
||||
await user.click(await screen.findByTestId('logs-retention-confirm-button'));
|
||||
|
||||
// Verify API was called with correct payload
|
||||
await waitFor(() => {
|
||||
@@ -208,6 +210,7 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
|
||||
describe('Test 2: S3 Disabled - Field Hidden', () => {
|
||||
it('should hide S3 retention field and send empty S3 values to API', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<GeneralSettings
|
||||
metricsTtlValuesPayload={mockMetricsRetention}
|
||||
@@ -234,45 +237,28 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
const totalDropdown = logsRow.querySelector(
|
||||
'.ant-select-selector',
|
||||
) as HTMLElement;
|
||||
fireEvent.mouseDown(totalDropdown);
|
||||
|
||||
// Wait for dropdown options to appear
|
||||
await waitFor(() => {
|
||||
const options = document.querySelectorAll('.ant-select-item');
|
||||
expect(options.length).toBeGreaterThan(0);
|
||||
});
|
||||
await user.click(totalDropdown);
|
||||
|
||||
// Find and click the Days option
|
||||
const options = document.querySelectorAll('.ant-select-item');
|
||||
const daysOption = Array.from(options).find((opt) =>
|
||||
opt.textContent?.includes('Days'),
|
||||
);
|
||||
expect(daysOption).toBeInTheDocument();
|
||||
fireEvent.click(daysOption as HTMLElement);
|
||||
const daysOption = await waitFor(() => {
|
||||
const option = Array.from(
|
||||
document.querySelectorAll('.ant-select-item'),
|
||||
).find((opt) => opt.textContent?.includes('Days'));
|
||||
expect(option).toBeInTheDocument();
|
||||
return option as HTMLElement;
|
||||
});
|
||||
await user.click(daysOption);
|
||||
|
||||
// Now change the value
|
||||
fireEvent.change(totalInput, { target: { value: '60' } });
|
||||
await user.clear(totalInput);
|
||||
await user.type(totalInput, '60');
|
||||
|
||||
// Find the save button
|
||||
const saveButton = logsRow.querySelector(
|
||||
'button:not([disabled])',
|
||||
) as HTMLButtonElement;
|
||||
expect(saveButton).toBeInTheDocument();
|
||||
const saveButton = screen.getByTestId('logs-retention-save-button');
|
||||
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
|
||||
await user.click(saveButton);
|
||||
|
||||
// Wait for button to be enabled
|
||||
await waitFor(() => {
|
||||
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
// Click save button
|
||||
fireEvent.click(saveButton);
|
||||
|
||||
// Wait for modal to appear
|
||||
const okButton = await screen.findByRole('button', { name: /ok/i });
|
||||
expect(okButton).toBeInTheDocument();
|
||||
|
||||
// Click OK button
|
||||
fireEvent.click(okButton);
|
||||
// Wait for modal to appear and click OK
|
||||
await user.click(await screen.findByTestId('logs-retention-confirm-button'));
|
||||
|
||||
// Verify API was called with empty S3 values (60 days)
|
||||
await waitFor(() => {
|
||||
@@ -321,6 +307,7 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
|
||||
describe('Test 4: Save Button State with S3 Disabled', () => {
|
||||
it('should disable save button when cold_storage_ttl_days is -1 and no changes made', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<GeneralSettings
|
||||
metricsTtlValuesPayload={mockMetricsRetention}
|
||||
@@ -336,12 +323,8 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
const logsRow = getLogsRow();
|
||||
expect(logsRow).toBeInTheDocument();
|
||||
|
||||
// Find the save button by accessible name within the Logs row
|
||||
const allSaveButtons = screen.getAllByRole('button', { name: /save/i });
|
||||
const saveButton = allSaveButtons.find((btn) =>
|
||||
logsRow.contains(btn),
|
||||
) as HTMLButtonElement;
|
||||
expect(saveButton).toBeInTheDocument();
|
||||
const saveButton = screen.getByTestId('logs-retention-save-button');
|
||||
expect(logsRow).toContainElement(saveButton);
|
||||
|
||||
// Verify save button is disabled on initial load
|
||||
expect(saveButton).toHaveAttribute('aria-disabled', 'true');
|
||||
@@ -351,20 +334,18 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
const totalInput = inputs[0] as HTMLInputElement;
|
||||
|
||||
// Change total retention value to trigger button enable
|
||||
fireEvent.change(totalInput, { target: { value: '60' } });
|
||||
await user.clear(totalInput);
|
||||
await user.type(totalInput, '60');
|
||||
|
||||
// Button should now be enabled after change
|
||||
await waitFor(() => {
|
||||
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
// Revert to original value (30 days displays as 1 Month)
|
||||
fireEvent.change(totalInput, { target: { value: '1' } });
|
||||
await user.clear(totalInput);
|
||||
await user.type(totalInput, '1');
|
||||
|
||||
// Button should be disabled again (back to original state)
|
||||
await waitFor(() => {
|
||||
expect(saveButton).toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
expect(saveButton).toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -421,8 +402,11 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
// Save buttons should be visible for non-cloud users (these are from retentions)
|
||||
const saveButtons = screen.getAllByRole('button', { name: /save/i });
|
||||
expect(saveButtons.length).toBeGreaterThan(0);
|
||||
['metrics', 'traces', 'logs'].forEach((type) => {
|
||||
expect(
|
||||
screen.getByTestId(`${type}-retention-save-button`),
|
||||
).toHaveTextContent('retention_save_button.success');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -426,7 +426,7 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// Find pagination navigation and page 2 button
|
||||
const nav = screen.getByRole('navigation');
|
||||
const nav = document.querySelector('nav') as HTMLElement;
|
||||
const page2Button = Array.from(nav.querySelectorAll('button')).find(
|
||||
(btn) => btn.textContent?.trim() === '2',
|
||||
);
|
||||
@@ -446,13 +446,16 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
it('should open row in new tab when ctrl+click on row', async () => {
|
||||
const user = userEvent.setup();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const firstRow = screen.getByText(`PodId:${itemId}`);
|
||||
// Ctrl+click to open in new tab
|
||||
fireEvent.click(firstRow, { ctrlKey: true });
|
||||
await user.keyboard('{Control>}');
|
||||
await user.click(firstRow);
|
||||
await user.keyboard('{/Control}');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(openInNewTabMock).toHaveBeenCalledTimes(1);
|
||||
@@ -463,13 +466,16 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
it('should open row in new tab when meta+click (cmd on Mac) on row', async () => {
|
||||
const user = userEvent.setup();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const firstRow = screen.getByText(`PodId:${itemId}`);
|
||||
// Meta+click (cmd on Mac) to open in new tab
|
||||
fireEvent.click(firstRow, { metaKey: true });
|
||||
await user.keyboard('{Meta>}');
|
||||
await user.click(firstRow);
|
||||
await user.keyboard('{/Meta}');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(openInNewTabMock).toHaveBeenCalledTimes(1);
|
||||
@@ -536,7 +542,7 @@ describe('K8sBaseList', () => {
|
||||
expect(screen.getByText('namespace-default')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const expandButtons = screen.getAllByRole('button');
|
||||
const expandButtons = document.querySelectorAll('button');
|
||||
expect(expandButtons.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
@@ -604,7 +610,7 @@ describe('K8sBaseList', () => {
|
||||
expect(screen.getByText('namespace-default')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const expandButtons = screen.getAllByRole('button');
|
||||
const expandButtons = document.querySelectorAll('button');
|
||||
expect(expandButtons.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
@@ -940,12 +946,8 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// All columns should be visible
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /id/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /name/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Id').closest('th')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Name').closest('th')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -988,9 +990,7 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// Columns should be visible
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /id/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Id').closest('th')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show columns when grouped', async () => {
|
||||
@@ -1014,9 +1014,7 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// Id should be visible
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /id/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Id').closest('th')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1096,12 +1094,8 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// All columns should be visible
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /id/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /^name$/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Id').closest('th')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Name').closest('th')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render data in cells correctly', async () => {
|
||||
@@ -1211,6 +1205,7 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
it('should include cluster and namespace params in new tab URL on ctrl+click', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderComponent<TestItemWithTitle, SelectedItemParams>({
|
||||
onUrlUpdate: onUrlUpdateMock,
|
||||
entity: InfraMonitoringEntity.PODS,
|
||||
@@ -1225,7 +1220,9 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
const firstRow = await screen.findByText(`PodId:${itemId}`);
|
||||
fireEvent.click(firstRow, { ctrlKey: true });
|
||||
await user.keyboard('{Control>}');
|
||||
await user.click(firstRow);
|
||||
await user.keyboard('{/Control}');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(openInNewTabMock).toHaveBeenCalledTimes(1);
|
||||
@@ -1237,6 +1234,7 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
it('should omit null cluster/namespace params in new tab URL', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderComponent<TestItemWithTitle, SelectedItemParams>({
|
||||
onUrlUpdate: onUrlUpdateMock,
|
||||
entity: InfraMonitoringEntity.PODS,
|
||||
@@ -1251,7 +1249,9 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
const firstRow = await screen.findByText(`PodId:${itemId}`);
|
||||
fireEvent.click(firstRow, { ctrlKey: true });
|
||||
await user.keyboard('{Control>}');
|
||||
await user.click(firstRow);
|
||||
await user.keyboard('{/Control}');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(openInNewTabMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { InfraMonitoringEntity } from 'container/InfraMonitoringK8sV2/constants';
|
||||
import { act, screen, userEvent, within } from 'tests/test-utils';
|
||||
import { act, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import { renderEntityTraces } from './testUtils';
|
||||
import { mockQueryRangeV5WithTracesResponse } from '__tests__/query_range_v5.util';
|
||||
@@ -31,15 +31,13 @@ describe('EntityTraces - Table Rendering', () => {
|
||||
it('should render table with all column headers', async () => {
|
||||
mockQueryRangeV5WithTracesResponse({ pageSize: 3 });
|
||||
|
||||
act(() => {
|
||||
renderEntityTraces();
|
||||
});
|
||||
const { container } = renderEntityTraces();
|
||||
|
||||
await expect(screen.findByText('Service Name')).resolves.toBeInTheDocument();
|
||||
|
||||
const headerTexts = within(screen.getByRole('table'))
|
||||
.getAllByRole('columnheader')
|
||||
.map((header) => header.textContent);
|
||||
const headerTexts = Array.from(
|
||||
container.querySelectorAll('table thead th'),
|
||||
).map((header) => header.textContent);
|
||||
|
||||
expect(headerTexts).toStrictEqual(
|
||||
expect.arrayContaining([
|
||||
@@ -152,13 +150,11 @@ describe('EntityTraces - Table Rendering', () => {
|
||||
customTraces: [{ serviceName: 'frontend' }],
|
||||
});
|
||||
|
||||
act(() => {
|
||||
renderEntityTraces();
|
||||
});
|
||||
const { container } = renderEntityTraces();
|
||||
|
||||
await expect(screen.findByTestId('serviceName')).resolves.toBeInTheDocument();
|
||||
|
||||
const links = within(screen.getByRole('table')).getAllByRole('link');
|
||||
const links = container.querySelectorAll('table a[href]');
|
||||
|
||||
expect(links.length).toBeGreaterThan(0);
|
||||
links.forEach((link) => {
|
||||
|
||||
@@ -1141,6 +1141,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
icon
|
||||
color="secondary"
|
||||
aria-label={`Edit ${signalName} limit`}
|
||||
testId={`edit-limit-btn-${signalName}`}
|
||||
disabled={
|
||||
!!(activeAPIKey?.id === APIKey?.id && activeSignal)
|
||||
}
|
||||
@@ -1637,6 +1638,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
target="_blank"
|
||||
className="learn-more"
|
||||
rel="noreferrer"
|
||||
data-testid="ingestion-keys-learn-more"
|
||||
>
|
||||
Learn more <ArrowUpRight size={14} />
|
||||
</a>
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import { GatewaytypesGettableIngestionKeysDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
} from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import MultiIngestionSettings from '../MultiIngestionSettings';
|
||||
|
||||
@@ -48,6 +42,7 @@ describe('MultiIngestionSettings Page', () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
@@ -62,7 +57,8 @@ describe('MultiIngestionSettings Page', () => {
|
||||
screen.getByText('Create and manage ingestion keys for the SigNoz Cloud'),
|
||||
).toBeInTheDocument();
|
||||
|
||||
const aboutKeyslink = screen.getByRole('link', { name: /Learn more/i });
|
||||
const aboutKeyslink = screen.getByTestId('ingestion-keys-learn-more');
|
||||
expect(aboutKeyslink).toHaveTextContent('Learn more');
|
||||
expect(aboutKeyslink).toHaveAttribute(
|
||||
'href',
|
||||
'https://signoz.io/docs/ingestion/signoz-cloud/keys/',
|
||||
@@ -73,6 +69,7 @@ describe('MultiIngestionSettings Page', () => {
|
||||
});
|
||||
|
||||
it('navigates to create alert with metrics count threshold', async () => {
|
||||
const user = userEvent.setup();
|
||||
const response: TestGatewayIngestionKeysResponse = {
|
||||
status: 'success',
|
||||
data: {
|
||||
@@ -111,13 +108,10 @@ describe('MultiIngestionSettings Page', () => {
|
||||
render(<MultiIngestionSettings />, undefined, {
|
||||
initialRoute: INGESTION_SETTINGS_ROUTE,
|
||||
});
|
||||
await screen.findByText('Key One');
|
||||
fireEvent.click(screen.getByRole('button', { name: /right Key One/i }));
|
||||
await user.click(await screen.findByText('Key One'));
|
||||
|
||||
await screen.findByText('LIMITS');
|
||||
fireEvent.click(
|
||||
(await screen.findByTestId('set-alert-btn-metrics')) as HTMLButtonElement,
|
||||
);
|
||||
await user.click(await screen.findByTestId('set-alert-btn-metrics'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledTimes(1);
|
||||
@@ -151,6 +145,7 @@ describe('MultiIngestionSettings Page', () => {
|
||||
});
|
||||
|
||||
it('navigates to create alert for logs with GiB threshold and bytes yAxisUnit', async () => {
|
||||
const user = userEvent.setup();
|
||||
const GIB = 1073741824;
|
||||
const sizeInBytes = 400 * GIB;
|
||||
|
||||
@@ -192,13 +187,10 @@ describe('MultiIngestionSettings Page', () => {
|
||||
render(<MultiIngestionSettings />, undefined, {
|
||||
initialRoute: INGESTION_SETTINGS_ROUTE,
|
||||
});
|
||||
await screen.findByText('Key Logs');
|
||||
fireEvent.click(screen.getByRole('button', { name: /right Key Logs/i }));
|
||||
await user.click(await screen.findByText('Key Logs'));
|
||||
|
||||
await screen.findByText('LIMITS');
|
||||
fireEvent.click(
|
||||
(await screen.findByTestId('set-alert-btn-logs')) as HTMLButtonElement,
|
||||
);
|
||||
await user.click(await screen.findByTestId('set-alert-btn-logs'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledTimes(1);
|
||||
@@ -231,6 +223,7 @@ describe('MultiIngestionSettings Page', () => {
|
||||
});
|
||||
|
||||
it('shows alert CTAs in view mode and helper text in edit mode for configured limits', async () => {
|
||||
const user = userEvent.setup();
|
||||
const KEY_NAME = 'Key With Limits';
|
||||
const response: TestGatewayIngestionKeysResponse = {
|
||||
status: 'success',
|
||||
@@ -276,22 +269,22 @@ describe('MultiIngestionSettings Page', () => {
|
||||
initialRoute: INGESTION_SETTINGS_ROUTE,
|
||||
});
|
||||
|
||||
await screen.findByText(KEY_NAME);
|
||||
fireEvent.click(
|
||||
screen.getByRole('button', { name: new RegExp(`right ${KEY_NAME}`, 'i') }),
|
||||
);
|
||||
await user.click(await screen.findByText(KEY_NAME));
|
||||
await screen.findByText('LIMITS');
|
||||
|
||||
expect(screen.getAllByText('Set alert').length).toBeGreaterThan(0);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Edit logs limit' }));
|
||||
await user.click(screen.getByTestId('edit-limit-btn-logs'));
|
||||
expect(
|
||||
screen.getByText('You can set up an alert after saving'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('switches to search API when search text is entered', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
|
||||
const getResponse: TestGatewayIngestionKeysResponse = {
|
||||
status: 'success',
|
||||
|
||||
@@ -101,7 +101,7 @@ function S3BucketsSelector({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="s3-buckets-selector">
|
||||
<div className="s3-buckets-selector" data-testid="s3-buckets-selector">
|
||||
<div className="s3-buckets-selector-title">Select S3 Buckets by Region</div>
|
||||
<div className="s3-buckets-selector-content">
|
||||
{allRegions.map((region) => {
|
||||
@@ -120,6 +120,7 @@ function S3BucketsSelector({
|
||||
</div>
|
||||
<div className="s3-buckets-selector-region-select">
|
||||
<Select
|
||||
data-testid={`s3-buckets-select-${region}`}
|
||||
mode="tags"
|
||||
placeholder={`Enter S3 bucket names for ${region}`}
|
||||
value={bucketsByRegion[region] || []}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { RestRequest } from 'msw';
|
||||
import type logEvent from '../../../../../api/common/logEvent';
|
||||
@@ -14,9 +14,6 @@ jest.mock('../../../../../api/common/logEvent', () => ({
|
||||
default: jest.fn() as jest.MockedFunction<typeof logEvent>,
|
||||
}));
|
||||
|
||||
// The form flow drives antd selects and typing, which outruns the 5s default on CI.
|
||||
jest.setTimeout(15_000);
|
||||
|
||||
type OnClose = ComponentProps<typeof CloudAccountSetupModal>['onClose'];
|
||||
|
||||
const mockOnClose = (): jest.MockedFunction<OnClose> =>
|
||||
@@ -84,26 +81,28 @@ const mockApi = ({ failFirstPoll = false } = {}): {
|
||||
return api;
|
||||
};
|
||||
|
||||
type User = ReturnType<typeof userEvent.setup>;
|
||||
|
||||
const generateCommand = async (user: User): Promise<void> => {
|
||||
const select = await screen.findByTestId('aws-deployment-region-select');
|
||||
await user.click(within(select).getByRole('combobox', { hidden: true }));
|
||||
await user.click(await screen.findByText('US East (N. Virginia)'));
|
||||
await user.click(screen.getByTestId('aws-region-us-east-1'));
|
||||
await user.click(screen.getByTestId('aws-generate-command-btn'));
|
||||
await screen.findByTestId('aws-agent-command');
|
||||
};
|
||||
|
||||
describe('AWS CloudAccountSetupModal', () => {
|
||||
it('creates the account and shows its setup command', async () => {
|
||||
const api = mockApi();
|
||||
const openSpy = jest.spyOn(window, 'open').mockImplementation(() => null);
|
||||
const user = userEvent.setup();
|
||||
const onClose = mockOnClose();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={onClose} />);
|
||||
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
|
||||
|
||||
await user.click(await screen.findByRole('combobox'));
|
||||
await user.click(await screen.findByText('US East (N. Virginia)'));
|
||||
await user.click(await screen.findByRole('checkbox', { name: /us-east-1/i }));
|
||||
await user.click(screen.getByTestId('aws-generate-command-btn'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('aws-agent-command')).toHaveTextContent(
|
||||
cliCommand,
|
||||
);
|
||||
});
|
||||
await generateCommand(user);
|
||||
|
||||
expect(screen.getByTestId('aws-agent-command')).toHaveTextContent(cliCommand);
|
||||
expect(api.createAccountPayload).toStrictEqual({
|
||||
config: { aws: { deploymentRegion: 'us-east-1', regions: ['us-east-1'] } },
|
||||
credentials,
|
||||
@@ -111,11 +110,25 @@ describe('AWS CloudAccountSetupModal', () => {
|
||||
expect(
|
||||
screen.queryByTestId('aws-generate-command-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryAllByRole('combobox')).toHaveLength(0);
|
||||
expect(screen.getByText(/waiting for connection/i)).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('aws-deployment-region-select'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('cloud-connect-waiting')).toHaveTextContent(
|
||||
/waiting for connection/i,
|
||||
);
|
||||
expect(openSpy).not.toHaveBeenCalled();
|
||||
|
||||
openSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('asks before closing once a setup command exists', async () => {
|
||||
mockApi();
|
||||
const user = userEvent.setup();
|
||||
const onClose = mockOnClose();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={onClose} />);
|
||||
|
||||
await generateCommand(user);
|
||||
|
||||
await user.click(screen.getByTestId('aws-cancel-btn'));
|
||||
await user.click(await screen.findByTestId('aws-continue-setup-btn'));
|
||||
@@ -150,16 +163,15 @@ describe('AWS CloudAccountSetupModal', () => {
|
||||
|
||||
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
|
||||
|
||||
await user.click(await screen.findByRole('combobox'));
|
||||
await user.click(await screen.findByText('US East (N. Virginia)'));
|
||||
await user.click(await screen.findByRole('checkbox', { name: /us-east-1/i }));
|
||||
await user.click(screen.getByTestId('aws-generate-command-btn'));
|
||||
await generateCommand(user);
|
||||
|
||||
await user.click(await screen.findByTestId('aws-check-connection-btn'));
|
||||
|
||||
await waitFor(() => expect(api.pollCount()).toBe(2));
|
||||
|
||||
await screen.findByText(/waiting for connection/i);
|
||||
await expect(
|
||||
screen.findByTestId('cloud-connect-waiting'),
|
||||
).resolves.toHaveTextContent(/waiting for connection/i);
|
||||
expect(
|
||||
screen.queryByTestId('aws-check-connection-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest, RestRequest } from 'msw';
|
||||
import { screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
|
||||
import {
|
||||
accountsResponse,
|
||||
@@ -11,19 +11,10 @@ import {
|
||||
import {
|
||||
assertGenericModalElements,
|
||||
assertS3SyncSpecificElements,
|
||||
bucketSelectInput,
|
||||
renderServiceDetails,
|
||||
} from './utils';
|
||||
|
||||
// --- RESIZE OBSERVER (required by @radix-ui in Tabs/Switch) ---
|
||||
class ResizeObserverMock {
|
||||
observe(): void {}
|
||||
|
||||
unobserve(): void {}
|
||||
|
||||
disconnect(): void {}
|
||||
}
|
||||
global.ResizeObserver = ResizeObserverMock as unknown as typeof ResizeObserver;
|
||||
|
||||
// --- MOCKS ---
|
||||
jest.mock('components/MarkdownRenderer/MarkdownRenderer', () => ({
|
||||
MarkdownRenderer: (): JSX.Element => <div data-testid="markdown-renderer" />,
|
||||
@@ -36,27 +27,22 @@ jest.mock(
|
||||
}),
|
||||
);
|
||||
|
||||
let testServiceId = 's3sync';
|
||||
let testInitialBuckets: Record<string, string[]> = {};
|
||||
const mockGet = jest.fn((param: string) => {
|
||||
if (param === 'cloudAccountId') {
|
||||
return CLOUD_ACCOUNT_ID;
|
||||
}
|
||||
if (param === 'service') {
|
||||
return testServiceId;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
jest.mock('hooks/useUrlQuery', () => ({
|
||||
__esModule: true,
|
||||
default: (): { get: (param: string) => string | null } => ({ get: mockGet }),
|
||||
}));
|
||||
|
||||
const addBucket = async (
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
bucketName: string,
|
||||
): Promise<void> => {
|
||||
await screen.findByTestId('s3-buckets-select-ap-south-1');
|
||||
await user.click(bucketSelectInput('ap-south-1'));
|
||||
// antd reads the legacy keyCode on Enter, which user-event leaves at 0, so
|
||||
// commit the tag with the select's comma separator instead.
|
||||
await user.paste(`${bucketName},`);
|
||||
};
|
||||
|
||||
// --- TEST SUITE ---
|
||||
describe('ServiceDetails for S3 Sync service', () => {
|
||||
jest.setTimeout(10000);
|
||||
beforeEach(() => {
|
||||
testServiceId = 's3sync';
|
||||
testInitialBuckets = {};
|
||||
server.use(
|
||||
rest.get(
|
||||
@@ -79,41 +65,34 @@ describe('ServiceDetails for S3 Sync service', () => {
|
||||
});
|
||||
|
||||
it('should render with logs collection switch and bucket selectors (no buckets initially selected)', async () => {
|
||||
renderServiceDetails({}); // No initial S3 buckets, defaults to 's3sync' serviceId
|
||||
renderServiceDetails();
|
||||
await assertGenericModalElements();
|
||||
await assertS3SyncSpecificElements({});
|
||||
});
|
||||
|
||||
it('should render with logs collection switch and bucket selectors (some buckets initially selected)', async () => {
|
||||
testInitialBuckets = initialBuckets;
|
||||
renderServiceDetails(initialBuckets);
|
||||
renderServiceDetails();
|
||||
await assertGenericModalElements();
|
||||
await assertS3SyncSpecificElements(initialBuckets);
|
||||
});
|
||||
|
||||
it('should enable save button after adding a new bucket via combobox', async () => {
|
||||
const user = userEvent.setup();
|
||||
testInitialBuckets = initialBuckets;
|
||||
renderServiceDetails(initialBuckets);
|
||||
await assertGenericModalElements();
|
||||
await assertS3SyncSpecificElements(initialBuckets);
|
||||
renderServiceDetails();
|
||||
|
||||
const targetCombobox = screen.getAllByRole('combobox')[0];
|
||||
const newBucketName = 'a-newly-added-bucket';
|
||||
await addBucket(user, newBucketName);
|
||||
|
||||
fireEvent.change(targetCombobox, { target: { value: newBucketName } });
|
||||
fireEvent.keyDown(targetCombobox, {
|
||||
key: 'Enter',
|
||||
code: 'Enter',
|
||||
keyCode: 13,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText(newBucketName)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /save/i })).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
expect(
|
||||
within(screen.getByTestId('s3-buckets-select-ap-south-1')).getByTitle(
|
||||
newBucketName,
|
||||
),
|
||||
).toHaveTextContent(newBucketName);
|
||||
await expect(
|
||||
screen.findByTestId('cloud-service-save-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('should send updated bucket configuration on save', async () => {
|
||||
@@ -127,29 +106,13 @@ describe('ServiceDetails for S3 Sync service', () => {
|
||||
return res(ctx.status(200), ctx.json({ message: 'Config updated' }));
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
testInitialBuckets = initialBuckets;
|
||||
renderServiceDetails(initialBuckets);
|
||||
await assertGenericModalElements();
|
||||
await assertS3SyncSpecificElements(initialBuckets);
|
||||
renderServiceDetails();
|
||||
|
||||
const newBucketName = 'another-new-bucket';
|
||||
const targetCombobox = screen.getAllByRole('combobox')[0];
|
||||
|
||||
fireEvent.change(targetCombobox, { target: { value: newBucketName } });
|
||||
fireEvent.keyDown(targetCombobox, {
|
||||
key: 'Enter',
|
||||
code: 'Enter',
|
||||
keyCode: 13,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText(newBucketName)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /save/i })).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
fireEvent.click(screen.getByRole('button', { name: /save/i }));
|
||||
await addBucket(user, newBucketName);
|
||||
await user.click(await screen.findByTestId('cloud-service-save-btn'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(capturedPayload).not.toBeNull();
|
||||
@@ -172,13 +135,8 @@ describe('ServiceDetails for S3 Sync service', () => {
|
||||
});
|
||||
|
||||
it('should not render S3 bucket region selector UI for services other than s3sync', async () => {
|
||||
testServiceId = 'ec2';
|
||||
testInitialBuckets = {};
|
||||
renderServiceDetails({}, 'ec2');
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.queryByText(/select s3 buckets by region/i),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
renderServiceDetails('ec2');
|
||||
await screen.findByTestId('markdown-renderer');
|
||||
expect(screen.queryByTestId('s3-buckets-selector')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,58 +1,66 @@
|
||||
import { render, RenderResult, screen, waitFor } from '@testing-library/react';
|
||||
import { render, RenderResult, screen, within } from 'tests/test-utils';
|
||||
import { IntegrationType } from 'container/Integrations/types';
|
||||
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
|
||||
|
||||
import ServiceDetails from '../ServiceDetails/ServiceDetails';
|
||||
import { accountsResponse } from './mockData';
|
||||
import { accountsResponse, CLOUD_ACCOUNT_ID } from './mockData';
|
||||
|
||||
/**
|
||||
* Renders ServiceDetails (inline config form). Tests must register MSW handlers
|
||||
* for GET accounts and GET service details, and mock useUrlQuery (cloudAccountId, service).
|
||||
* Renders ServiceDetails (inline config form) for the account and service in the
|
||||
* URL. Tests must register MSW handlers for GET accounts and GET service details.
|
||||
*/
|
||||
const renderServiceDetails = (
|
||||
_initialConfigLogsS3Buckets: Record<string, string[]> = {},
|
||||
_serviceId = 's3sync',
|
||||
serviceId = 's3sync',
|
||||
type: IntegrationType = IntegrationType.AWS_SERVICES,
|
||||
): RenderResult =>
|
||||
render(
|
||||
<MockQueryClientProvider>
|
||||
<ServiceDetails type={type} />
|
||||
</MockQueryClientProvider>,
|
||||
);
|
||||
render(<ServiceDetails type={type} />, undefined, {
|
||||
initialRoute: `/?cloudAccountId=${CLOUD_ACCOUNT_ID}&service=${serviceId}`,
|
||||
});
|
||||
|
||||
/**
|
||||
* Asserts generic UI elements of the ServiceDetails config form (Overview tab).
|
||||
*/
|
||||
const assertGenericModalElements = async (): Promise<void> => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('switch')).toBeInTheDocument();
|
||||
expect(screen.getByText(/log collection/i)).toBeInTheDocument();
|
||||
});
|
||||
await expect(
|
||||
screen.findByTestId('cloud-service-logs-switch'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText(/log collection/i)).toBeInTheDocument();
|
||||
};
|
||||
|
||||
/**
|
||||
* Asserts S3 bucket selector section: title, region labels, and one combobox per region.
|
||||
* Does not assert placeholder text (antd Select may not expose it as placeholder attribute).
|
||||
* Asserts S3 bucket selector section: title, a select per account region, and
|
||||
* the buckets already selected in each region.
|
||||
*/
|
||||
const assertS3SyncSpecificElements = async (
|
||||
_expectedBucketsByRegion: Record<string, string[]> = {},
|
||||
expectedBucketsByRegion: Record<string, string[]> = {},
|
||||
): Promise<void> => {
|
||||
const regions = accountsResponse.data.accounts[0]?.config?.aws?.regions || [];
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/select s3 buckets by region/i)).toBeInTheDocument();
|
||||
const selector = await screen.findByTestId('s3-buckets-selector');
|
||||
expect(selector).toHaveTextContent(/select s3 buckets by region/i);
|
||||
|
||||
regions.forEach((region) => {
|
||||
expect(screen.getByText(region)).toBeInTheDocument();
|
||||
regions.forEach((region) => {
|
||||
expect(selector).toHaveTextContent(region);
|
||||
expect(screen.getByTestId(`s3-buckets-select-${region}`)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
Object.entries(expectedBucketsByRegion).forEach(([region, buckets]) => {
|
||||
buckets.forEach((bucket) => {
|
||||
expect(screen.getByTestId(`s3-buckets-select-${region}`)).toHaveTextContent(
|
||||
bucket,
|
||||
);
|
||||
});
|
||||
|
||||
const comboboxes = screen.getAllByRole('combobox');
|
||||
expect(comboboxes.length).toBeGreaterThanOrEqual(regions.length);
|
||||
});
|
||||
};
|
||||
|
||||
const bucketSelectInput = (region: string): HTMLElement =>
|
||||
within(screen.getByTestId(`s3-buckets-select-${region}`)).getByRole(
|
||||
'combobox',
|
||||
{ hidden: true },
|
||||
);
|
||||
|
||||
export {
|
||||
assertGenericModalElements,
|
||||
assertS3SyncSpecificElements,
|
||||
bucketSelectInput,
|
||||
renderServiceDetails,
|
||||
};
|
||||
|
||||
@@ -243,6 +243,7 @@ function CloudAccountSetupModal({
|
||||
className="cloud-account-setup-form__form-item"
|
||||
>
|
||||
<Select
|
||||
data-testid="azure-deployment-region-select"
|
||||
placeholder="e.g. East US"
|
||||
options={AZURE_REGIONS.map((region) => ({
|
||||
label: `${region.label} (${region.value})`,
|
||||
@@ -273,6 +274,7 @@ function CloudAccountSetupModal({
|
||||
className="cloud-account-setup-form__form-item"
|
||||
>
|
||||
<Select
|
||||
data-testid="azure-resource-groups-select"
|
||||
mode="tags"
|
||||
placeholder="e.g. prod-platform-rg"
|
||||
tokenSeparators={[',']}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { RestRequest } from 'msw';
|
||||
import type logEvent from '../../../../../api/common/logEvent';
|
||||
@@ -14,9 +14,6 @@ jest.mock('../../../../../api/common/logEvent', () => ({
|
||||
default: jest.fn() as jest.MockedFunction<typeof logEvent>,
|
||||
}));
|
||||
|
||||
// The form flow drives antd selects and typing, which outruns the 5s default on CI.
|
||||
jest.setTimeout(15_000);
|
||||
|
||||
type OnClose = ComponentProps<typeof CloudAccountSetupModal>['onClose'];
|
||||
|
||||
const mockOnClose = (): jest.MockedFunction<OnClose> =>
|
||||
@@ -84,26 +81,35 @@ const mockApi = ({ failFirstPoll = false } = {}): {
|
||||
return api;
|
||||
};
|
||||
|
||||
type User = ReturnType<typeof userEvent.setup>;
|
||||
|
||||
const antdSelectInput = (testId: string): HTMLElement =>
|
||||
within(screen.getByTestId(testId)).getByRole('combobox', { hidden: true });
|
||||
|
||||
const generateCommand = async (user: User): Promise<void> => {
|
||||
await screen.findByTestId('azure-deployment-region-select');
|
||||
await user.click(antdSelectInput('azure-deployment-region-select'));
|
||||
await user.click(await screen.findByText('Australia East (australiaeast)'));
|
||||
await user.click(antdSelectInput('azure-resource-groups-select'));
|
||||
// antd reads the legacy keyCode on Enter, which user-event leaves at 0, so
|
||||
// commit the tag with the select's comma separator instead.
|
||||
await user.paste('prod-platform-rg,');
|
||||
await user.click(screen.getByTestId('azure-generate-command-btn'));
|
||||
await screen.findByTestId('azure-agent-command');
|
||||
};
|
||||
|
||||
describe('Azure CloudAccountSetupModal', () => {
|
||||
it('creates the account and shows its setup command', async () => {
|
||||
const api = mockApi();
|
||||
const user = userEvent.setup();
|
||||
const onClose = mockOnClose();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={onClose} />);
|
||||
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
|
||||
|
||||
const [region, resourceGroups] = await screen.findAllByRole('combobox');
|
||||
await user.click(region);
|
||||
await user.click(await screen.findByText('Australia East (australiaeast)'));
|
||||
await user.type(resourceGroups, 'prod-platform-rg{Enter}');
|
||||
await user.click(screen.getByTestId('azure-generate-command-btn'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('azure-agent-command')).toHaveTextContent(
|
||||
cliCommand,
|
||||
);
|
||||
});
|
||||
await generateCommand(user);
|
||||
|
||||
expect(screen.getByTestId('azure-agent-command')).toHaveTextContent(
|
||||
cliCommand,
|
||||
);
|
||||
expect(api.createAccountPayload).toStrictEqual({
|
||||
config: {
|
||||
azure: {
|
||||
@@ -116,10 +122,25 @@ describe('Azure CloudAccountSetupModal', () => {
|
||||
expect(
|
||||
screen.queryByTestId('azure-generate-command-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryAllByRole('combobox')).toHaveLength(0);
|
||||
expect(
|
||||
screen.queryByTestId('azure-deployment-region-select'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('azure-resource-groups-select'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(/waiting for azure account connection/i),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('asks before closing once a setup command exists', async () => {
|
||||
mockApi();
|
||||
const user = userEvent.setup();
|
||||
const onClose = mockOnClose();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={onClose} />);
|
||||
|
||||
await generateCommand(user);
|
||||
|
||||
await user.click(screen.getByTestId('azure-cancel-btn'));
|
||||
await user.click(await screen.findByTestId('azure-continue-setup-btn'));
|
||||
@@ -154,11 +175,7 @@ describe('Azure CloudAccountSetupModal', () => {
|
||||
|
||||
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
|
||||
|
||||
const [region, resourceGroups] = await screen.findAllByRole('combobox');
|
||||
await user.click(region);
|
||||
await user.click(await screen.findByText('Australia East (australiaeast)'));
|
||||
await user.type(resourceGroups, 'prod-platform-rg{Enter}');
|
||||
await user.click(screen.getByTestId('azure-generate-command-btn'));
|
||||
await generateCommand(user);
|
||||
|
||||
await user.click(await screen.findByTestId('azure-check-connection-btn'));
|
||||
|
||||
|
||||
@@ -52,12 +52,13 @@ export const fillAgentForm = async (
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
): Promise<void> => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('gcp-generate-command-btn')).toBeEnabled();
|
||||
expect(screen.getByTestId('gcp-generate-command-btn')).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
await user.type(
|
||||
screen.getByTestId('gcp-deployment-project-id-input'),
|
||||
DEPLOYMENT_PROJECT_ID,
|
||||
);
|
||||
await user.click(screen.getByTestId('gcp-deployment-project-id-input'));
|
||||
await user.paste(DEPLOYMENT_PROJECT_ID);
|
||||
await user.click(screen.getByTestId('gcp-deployment-region-select'));
|
||||
await user.click(await screen.findByText('Mumbai (asia-south1)'));
|
||||
};
|
||||
|
||||
@@ -31,6 +31,7 @@ function ConnectionMethodSelector({
|
||||
<RadioGroup
|
||||
color="primary"
|
||||
textOverflow="wrap"
|
||||
testId="gcp-connection-method"
|
||||
value={value}
|
||||
onChange={(next): void =>
|
||||
onChange(next as CloudintegrationtypesGCPConnectionMethodDTO)
|
||||
|
||||
@@ -30,19 +30,6 @@ jest.mock('@signozhq/ui/sonner', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
|
||||
// popover ancestor costs ~1 s per open here, enough to time out under load.
|
||||
jest.mock('@floating-ui/dom', () => ({
|
||||
...jest.requireActual('@floating-ui/dom'),
|
||||
autoUpdate: (): (() => void) => (): void => {},
|
||||
computePosition: (
|
||||
_reference: unknown,
|
||||
_floating: unknown,
|
||||
{ placement = 'bottom', strategy = 'absolute' } = {},
|
||||
): Promise<unknown> =>
|
||||
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
|
||||
}));
|
||||
|
||||
type AccountSettingsDrawerProps = ComponentProps<typeof AccountSettingsDrawer>;
|
||||
|
||||
const onClose = jest.fn() as jest.MockedFunction<
|
||||
|
||||
@@ -107,11 +107,15 @@ describe('GCP CloudAccountSetupDrawer', () => {
|
||||
});
|
||||
|
||||
it('creates the account, checks the agent in, and closes the drawer', async () => {
|
||||
// A slow check-in keeps the connection in flight long enough to observe it.
|
||||
let releaseCheckIn = (): void => {};
|
||||
const checkInHeld = new Promise<void>((resolve) => {
|
||||
releaseCheckIn = resolve;
|
||||
});
|
||||
server.use(
|
||||
rest.post(GCP_CHECK_IN_URL, async (req: RestRequest, res, ctx) => {
|
||||
checkInPayload = await req.json();
|
||||
return res(ctx.delay(300), ctx.status(200), ctx.json(checkInResponse));
|
||||
await checkInHeld;
|
||||
return res(ctx.status(200), ctx.json(checkInResponse));
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
@@ -141,7 +145,7 @@ describe('GCP CloudAccountSetupDrawer', () => {
|
||||
|
||||
// Switching away mid-request would let its success close the other form.
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('radiogroup')).toHaveAttribute(
|
||||
expect(screen.getByTestId('gcp-connection-method')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
@@ -171,11 +175,14 @@ describe('GCP CloudAccountSetupDrawer', () => {
|
||||
data: {},
|
||||
});
|
||||
});
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
|
||||
releaseCheckIn();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
}, 15000);
|
||||
});
|
||||
|
||||
it('shows the backend error inline when account creation fails', async () => {
|
||||
server.use(
|
||||
@@ -218,5 +225,5 @@ describe('GCP CloudAccountSetupDrawer', () => {
|
||||
});
|
||||
expect(checkInPayload).toBeNull();
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
}, 15000);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,7 +20,11 @@ function AttributeMappingsTab({
|
||||
return (
|
||||
<div data-testid="attribute-mappings-tab">
|
||||
{editor.isError ? (
|
||||
<div className={styles.pageError} role="alert">
|
||||
<div
|
||||
className={styles.pageError}
|
||||
role="alert"
|
||||
data-testid="mapping-groups-error"
|
||||
>
|
||||
Failed to load mapping groups. Please try again.
|
||||
</div>
|
||||
) : (
|
||||
|
||||
@@ -129,7 +129,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('group-name-group-1')).toBeInTheDocument(),
|
||||
);
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('mapping-groups-error')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows an error banner when the groups request fails', async () => {
|
||||
@@ -138,7 +138,9 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
);
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
|
||||
await expect(screen.findByRole('alert')).resolves.toHaveTextContent(
|
||||
await expect(
|
||||
screen.findByTestId('mapping-groups-error'),
|
||||
).resolves.toHaveTextContent(
|
||||
'Failed to load mapping groups. Please try again.',
|
||||
);
|
||||
});
|
||||
@@ -177,7 +179,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it("stages a toggle of the group's enabled state via the header switch", async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
|
||||
@@ -189,7 +191,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('invokes onAddGroup from the toolbar button', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onAddGroup = jest.fn();
|
||||
setupGroups();
|
||||
render(<AttributeMappingsTabWithStore onAddGroup={onAddGroup} />);
|
||||
@@ -201,14 +203,16 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('invokes onEditGroup with the group when Edit is chosen from the actions menu', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onEditGroup = jest.fn();
|
||||
setupGroups();
|
||||
render(<AttributeMappingsTabWithStore onEditGroup={onEditGroup} />);
|
||||
|
||||
await screen.findByTestId('group-name-group-1');
|
||||
await openGroupActionsMenu(user, 'group-1');
|
||||
await user.click(await screen.findByRole('menuitem', { name: 'Edit' }));
|
||||
await user.click(
|
||||
await screen.findByTestId('group-actions-group-1-item-edit'),
|
||||
);
|
||||
|
||||
expect(onEditGroup).toHaveBeenCalledTimes(1);
|
||||
expect(onEditGroup.mock.calls[0][0]).toMatchObject({
|
||||
@@ -218,13 +222,15 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('stages a group removal when Delete is chosen from the actions menu', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
|
||||
await screen.findByTestId('group-name-group-1');
|
||||
await openGroupActionsMenu(user, 'group-1');
|
||||
await user.click(await screen.findByRole('menuitem', { name: 'Delete' }));
|
||||
await user.click(
|
||||
await screen.findByTestId('group-actions-group-1-item-delete'),
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByTestId('group-name-group-1')).not.toBeInTheDocument(),
|
||||
@@ -233,7 +239,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it("reveals a group's mappers on expand and hides them on collapse", async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
setupMappers([makeMapper({ id: 'mapper-1' })]);
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
@@ -261,7 +267,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it("lazily fetches and renders a group's mappers on first expand", async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
setupMappers([
|
||||
makeMapper({ id: 'mapper-1', name: 'gen_ai.request.model', enabled: true }),
|
||||
@@ -290,7 +296,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('shows the mappers error state when the mappers request fails', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
server.use(
|
||||
rest.get(mappersEndpoint('group-1'), (_req, res, ctx) =>
|
||||
@@ -308,7 +314,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('shows the mappers empty state when a group has no mappers', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
setupMappers([]);
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
@@ -322,7 +328,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('collapses extra mapper sources into a "+N more" label beyond the visible cap', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
setupMappers([
|
||||
makeMapper({
|
||||
@@ -347,7 +353,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('shows a muted placeholder when a mapper has no sources', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
setupMappers([makeMapper({ id: 'mapper-1', config: { sources: [] } })]);
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
@@ -361,7 +367,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it("re-fetches an open group's mappers on save instead of showing stale rows", async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
|
||||
let mappers = mockMappers;
|
||||
@@ -394,7 +400,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('warns and keeps the working copy when the post-save refresh fails', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
(toast.success as jest.Mock).mockClear();
|
||||
(toast.warning as jest.Mock).mockClear();
|
||||
|
||||
@@ -438,7 +444,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
}
|
||||
|
||||
it('opens the add-mapping drawer from a group\'s "Add mapping" button', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await openGroupWithMapper(user);
|
||||
|
||||
expect(screen.queryByTestId('mapper-form-drawer')).not.toBeInTheDocument();
|
||||
@@ -451,11 +457,13 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('opens the edit drawer prefilled and locks the target attribute', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await openGroupWithMapper(user);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Mapping actions' }));
|
||||
await user.click(await screen.findByRole('menuitem', { name: 'Edit' }));
|
||||
await user.click(screen.getByTestId('mapper-actions-mapper-1'));
|
||||
await user.click(
|
||||
await screen.findByTestId('mapper-actions-mapper-1-item-edit'),
|
||||
);
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('mapper-form-drawer'),
|
||||
@@ -467,7 +475,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it("toggles a mapper's enabled state through the store", async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await openGroupWithMapper(user);
|
||||
|
||||
const toggle = screen.getByTestId('mapper-enabled-mapper-1');
|
||||
@@ -481,11 +489,13 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('removes a mapper via the row action menu', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await openGroupWithMapper(user);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Mapping actions' }));
|
||||
await user.click(await screen.findByRole('menuitem', { name: 'Delete' }));
|
||||
await user.click(screen.getByTestId('mapper-actions-mapper-1'));
|
||||
await user.click(
|
||||
await screen.findByTestId('mapper-actions-mapper-1-item-delete'),
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
@@ -496,7 +506,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('creates a new mapping through the drawer and appends it to the group', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await openGroupWithMapper(user);
|
||||
|
||||
await user.click(screen.getByTestId('add-mapper-group-1'));
|
||||
@@ -507,11 +517,10 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
'true',
|
||||
);
|
||||
|
||||
await user.type(
|
||||
screen.getByTestId('mapper-form-target'),
|
||||
'gen_ai.response.model',
|
||||
);
|
||||
await user.type(screen.getByTestId('mapper-form-source-0'), 'raw.model');
|
||||
await user.click(screen.getByTestId('mapper-form-target'));
|
||||
await user.paste('gen_ai.response.model');
|
||||
await user.click(screen.getByTestId('mapper-form-source-0'));
|
||||
await user.paste('raw.model');
|
||||
|
||||
const create = screen.getByTestId('mapper-form-save');
|
||||
await waitFor(() =>
|
||||
@@ -558,7 +567,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('renders mappers read-only: no "Add mapping" button or row actions', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
setupMappers([makeMapper({ id: 'mapper-1', name: 'gen_ai.request.model' })]);
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
@@ -574,7 +583,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
screen.queryByTestId('mapper-enabled-mapper-1'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'Mapping actions' }),
|
||||
screen.queryByTestId('mapper-actions-mapper-1'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -38,7 +38,13 @@ function GroupActionsMenu({
|
||||
);
|
||||
|
||||
return (
|
||||
<Dropdown items={menuItems} nativeButton align="end" side="bottom">
|
||||
<Dropdown
|
||||
items={menuItems}
|
||||
nativeButton
|
||||
align="end"
|
||||
side="bottom"
|
||||
testId={`group-actions-${group.localId}`}
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
|
||||
@@ -38,7 +38,13 @@ function MapperActionsMenu({
|
||||
);
|
||||
|
||||
return (
|
||||
<Dropdown items={menuItems} nativeButton align="end" side="bottom">
|
||||
<Dropdown
|
||||
items={menuItems}
|
||||
nativeButton
|
||||
align="end"
|
||||
side="bottom"
|
||||
testId={`mapper-actions-${mapper.localId}`}
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
|
||||
@@ -5,7 +5,7 @@ import set from 'api/browser/localstorage/set';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { mockUseAuthZGrantAll } from 'lib/authz/utils/authz-test-utils';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
jest.mock('@monaco-editor/react', () => ({
|
||||
__esModule: true,
|
||||
@@ -28,8 +28,10 @@ jest.mock('@monaco-editor/react', () => ({
|
||||
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
|
||||
const mockedUseAuthZ = useAuthZ as jest.MockedFunction<typeof useAuthZ>;
|
||||
|
||||
import LLMObservabilityAttributeMapping from '../../LLMObservabilityAttributeMapping';
|
||||
import { useAttributeMappingEditor } from '../../hooks/useAttributeMappingEditor';
|
||||
import { SAMPLE_SPAN_JSON } from '../spanInputStorage';
|
||||
import TestTab from '../TestTab';
|
||||
import { useTestSpanMapper } from '../useTestSpanMapper';
|
||||
import {
|
||||
GROUPS_ENDPOINT,
|
||||
makeGroupsResponse,
|
||||
@@ -85,6 +87,12 @@ const EXTRA_KEY_RESULT_SPAN = {
|
||||
|
||||
const SPAN_INPUT_KEY = LOCALSTORAGE.LLM_ATTRIBUTE_MAPPING_TEST_SPAN;
|
||||
|
||||
function TestTabWithEditor(): JSX.Element {
|
||||
const editor = useAttributeMappingEditor();
|
||||
const spanTest = useTestSpanMapper(editor.snapshot, editor.groups);
|
||||
return <TestTab spanTest={spanTest} />;
|
||||
}
|
||||
|
||||
describe('TestTab — sample-span flow', () => {
|
||||
beforeEach(() => {
|
||||
window.history.pushState(null, '', '/');
|
||||
@@ -97,17 +105,20 @@ describe('TestTab — sample-span flow', () => {
|
||||
mockedUseAuthZ.mockImplementation(mockUseAuthZGrantAll);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('runs the sample span through the mappers and renders the populated result', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
rest.post(TEST_ENDPOINT, (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(makeTestResponse([RESULT_SPAN]))),
|
||||
),
|
||||
);
|
||||
|
||||
render(<LLMObservabilityAttributeMapping />);
|
||||
render(<TestTabWithEditor />);
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Test' }));
|
||||
const runBtn = await screen.findByTestId('run-test-button');
|
||||
expect(screen.getByTestId('test-results-placeholder')).toBeInTheDocument();
|
||||
|
||||
@@ -125,7 +136,7 @@ describe('TestTab — sample-span flow', () => {
|
||||
});
|
||||
|
||||
it('trims extra top-level keys and sends only the envelope', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
let body: { spans?: { attributes?: Record<string, unknown> }[] } | undefined;
|
||||
server.use(
|
||||
rest.post(TEST_ENDPOINT, async (req, res, ctx) => {
|
||||
@@ -137,9 +148,8 @@ describe('TestTab — sample-span flow', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
render(<LLMObservabilityAttributeMapping />);
|
||||
render(<TestTabWithEditor />);
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Test' }));
|
||||
const runBtn = await screen.findByTestId('run-test-button');
|
||||
|
||||
await user.clear(screen.getByTestId('monaco'));
|
||||
@@ -166,7 +176,7 @@ describe('TestTab — sample-span flow', () => {
|
||||
});
|
||||
|
||||
it('surfaces a backend error and renders no results', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
rest.post(TEST_ENDPOINT, (_req, res, ctx) =>
|
||||
res(
|
||||
@@ -176,9 +186,8 @@ describe('TestTab — sample-span flow', () => {
|
||||
),
|
||||
);
|
||||
|
||||
render(<LLMObservabilityAttributeMapping />);
|
||||
render(<TestTabWithEditor />);
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Test' }));
|
||||
await user.click(await screen.findByTestId('run-test-button'));
|
||||
|
||||
await expect(screen.findByTestId('test-error')).resolves.toHaveTextContent(
|
||||
@@ -188,37 +197,38 @@ describe('TestTab — sample-span flow', () => {
|
||||
});
|
||||
|
||||
it('persists an edited span to local storage and restores it on remount', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { unmount } = render(<LLMObservabilityAttributeMapping />);
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
const { unmount } = render(<TestTabWithEditor />);
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Test' }));
|
||||
await screen.findByTestId('run-test-button');
|
||||
|
||||
const editor = screen.getByTestId('monaco');
|
||||
const editor = await screen.findByTestId('monaco');
|
||||
expect(editor).toHaveValue(SAMPLE_SPAN_JSON);
|
||||
|
||||
await user.clear(editor);
|
||||
await user.paste(EDITED_SPAN_JSON);
|
||||
expect(get(SPAN_INPUT_KEY)).toBeFalsy();
|
||||
|
||||
await waitFor(() => expect(get(SPAN_INPUT_KEY)).toBe(EDITED_SPAN_JSON), {
|
||||
timeout: 2000,
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(500);
|
||||
});
|
||||
expect(get(SPAN_INPUT_KEY)).toBe(EDITED_SPAN_JSON);
|
||||
|
||||
unmount();
|
||||
render(<LLMObservabilityAttributeMapping />);
|
||||
render(<TestTabWithEditor />);
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Test' }));
|
||||
await screen.findByTestId('run-test-button');
|
||||
expect(screen.getByTestId('monaco')).toHaveValue(EDITED_SPAN_JSON);
|
||||
await expect(screen.findByTestId('monaco')).resolves.toHaveValue(
|
||||
EDITED_SPAN_JSON,
|
||||
);
|
||||
});
|
||||
|
||||
it('resets to the sample span and clears the persisted input', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
set(SPAN_INPUT_KEY, EDITED_SPAN_JSON);
|
||||
|
||||
render(<LLMObservabilityAttributeMapping />);
|
||||
render(<TestTabWithEditor />);
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Test' }));
|
||||
const resetBtn = await screen.findByTestId('reset-template-button');
|
||||
|
||||
expect(screen.getByTestId('monaco')).toHaveValue(EDITED_SPAN_JSON);
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
useHandleExplorerTabChange,
|
||||
} from 'hooks/useHandleExplorerTabChange';
|
||||
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
|
||||
import { ExplorerViews } from 'pages/LogsExplorer/utils';
|
||||
@@ -186,7 +187,9 @@ function Explorer(): JSX.Element {
|
||||
|
||||
const isFilterApplied = useMemo(() => {
|
||||
// if any of the non-disabled queries has filters applied, return true
|
||||
const result = stagedQuery?.builder?.queryData?.filter(
|
||||
const result = (
|
||||
stagedQuery ? getActiveBuilder(stagedQuery) : undefined
|
||||
)?.queryData?.filter(
|
||||
(item) => !isEmpty(item.filters?.items) && !item.disabled,
|
||||
);
|
||||
return !!result?.length;
|
||||
|
||||
@@ -15,6 +15,7 @@ import { convertDataValueToMs } from 'container/TimeSeriesView/utils';
|
||||
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import useUrlYAxisUnit from 'hooks/useUrlYAxisUnit';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { Warning } from 'types/api';
|
||||
import APIError from 'types/api/error';
|
||||
@@ -35,7 +36,7 @@ function TimeSeriesViewContainer({
|
||||
const isValidToConvertToMs = useMemo(() => {
|
||||
const isValid: boolean[] = [];
|
||||
|
||||
currentQuery.builder.queryData.forEach(
|
||||
getActiveBuilder(currentQuery).queryData.forEach(
|
||||
({ aggregateAttribute, aggregateOperator }) => {
|
||||
const isExistDurationNanoAttribute =
|
||||
aggregateAttribute?.key === 'durationNano' ||
|
||||
|
||||
@@ -33,7 +33,7 @@ jest.mock('../../TracesTable/TracesTable', () => ({
|
||||
<button
|
||||
data-testid="remove-total-tokens"
|
||||
type="button"
|
||||
onClick={(): void => onColumnRemove?.('trace:total_tokens:float64')}
|
||||
onClick={(): void => onColumnRemove?.('trace:total_tokens:number')}
|
||||
>
|
||||
remove
|
||||
</button>
|
||||
@@ -48,7 +48,7 @@ const QUERY_RANGE_URL = `${ENVIRONMENT.baseURL}/api/v5/query_range`;
|
||||
const TOTAL_TOKENS = {
|
||||
name: 'total_tokens',
|
||||
fieldContext: 'trace',
|
||||
fieldDataType: 'float64',
|
||||
fieldDataType: 'number',
|
||||
};
|
||||
|
||||
const storedColumnNames = (): string[] | undefined => {
|
||||
|
||||
@@ -63,7 +63,7 @@ const mockFieldKeys = (names: string[]): void => {
|
||||
{
|
||||
name,
|
||||
fieldContext: TelemetrytypesFieldContextDTO.trace,
|
||||
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
|
||||
fieldDataType: TelemetrytypesFieldDataTypeDTO.number,
|
||||
},
|
||||
],
|
||||
]),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user