mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-24 17:21:06 +00:00
Compare commits
10 Commits
ci/e2e-sha
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
09d905edc4 | ||
|
|
d473d022b0 | ||
|
|
1664c29cf4 | ||
|
|
f4bc90da34 | ||
|
|
02de020642 | ||
|
|
570e622a46 | ||
|
|
381cda6821 | ||
|
|
9dbe4db00e | ||
|
|
da35d99714 | ||
|
|
f955bb952a |
@@ -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.
|
||||
|
||||
@@ -15,3 +15,4 @@ paths:
|
||||
- When defining types, keep the structure of file to have any constants and variables first, then exported types and exported methods and then finally the unexported types and methods.
|
||||
- Never import types or other modules in migration files, duplicate the required type or method to keep migration free from changes.
|
||||
- Always run the gofmt tool for formating beforing commiting any changes.
|
||||
- **Never copy through a pointer dereference** (`copied := *original`). It copies only the top level: pointer, slice and map fields stay shared, so changing the copy can change the original. Use the type's `Copy()` when it has one (`QueryBuilderFormula.Copy`); otherwise create a new struct literal from the fields you need. A `Copy()` itself may dereference, as long as it then replaces every pointer, slice and map field.
|
||||
|
||||
@@ -16274,13 +16274,22 @@ paths:
|
||||
where it is case-sensitive and % and _ act as wildcards. For keys, a context
|
||||
prefix such as resource.service.name sets fieldContext when it is empty.'
|
||||
type: string
|
||||
- description: The key whose values to return, such as service.name. A context
|
||||
prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
- description: 'The key whose values to return, such as service.name. With fieldContext
|
||||
set, it is the stored name as is. Otherwise a context prefix such as resource.service.name
|
||||
sets the context and a type suffix such as service.name:string sets fieldDataType
|
||||
when that is empty; as in filter expressions, a prefixed name also matches
|
||||
a key stored under the full name, whose values come first: log.level returns
|
||||
values of a key named log.level, then of the log field level.'
|
||||
in: query
|
||||
name: name
|
||||
schema:
|
||||
description: The key whose values to return, such as service.name. A context
|
||||
prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
description: 'The key whose values to return, such as service.name. With
|
||||
fieldContext set, it is the stored name as is. Otherwise a context prefix
|
||||
such as resource.service.name sets the context and a type suffix such
|
||||
as service.name:string sets fieldDataType when that is empty; as in filter
|
||||
expressions, a prefixed name also matches a key stored under the full
|
||||
name, whose values come first: log.level returns values of a key named
|
||||
log.level, then of the log field level.'
|
||||
type: string
|
||||
- description: Filter expression already applied in the explorer. When set,
|
||||
relatedValues lists the values seen on data matching it.
|
||||
@@ -28927,13 +28936,22 @@ paths:
|
||||
where it is case-sensitive and % and _ act as wildcards. For keys, a context
|
||||
prefix such as resource.service.name sets fieldContext when it is empty.'
|
||||
type: string
|
||||
- description: The key whose values to return, such as service.name. A context
|
||||
prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
- description: 'The key whose values to return, such as service.name. With fieldContext
|
||||
set, it is the stored name as is. Otherwise a context prefix such as resource.service.name
|
||||
sets the context and a type suffix such as service.name:string sets fieldDataType
|
||||
when that is empty; as in filter expressions, a prefixed name also matches
|
||||
a key stored under the full name, whose values come first: log.level returns
|
||||
values of a key named log.level, then of the log field level.'
|
||||
in: query
|
||||
name: name
|
||||
schema:
|
||||
description: The key whose values to return, such as service.name. A context
|
||||
prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
description: 'The key whose values to return, such as service.name. With
|
||||
fieldContext set, it is the stored name as is. Otherwise a context prefix
|
||||
such as resource.service.name sets the context and a type suffix such
|
||||
as service.name:string sets fieldDataType when that is empty; as in filter
|
||||
expressions, a prefixed name also matches a key stored under the full
|
||||
name, whose values come first: log.level returns values of a key named
|
||||
log.level, then of the log field level.'
|
||||
type: string
|
||||
- description: Filter expression already applied in the explorer. When set,
|
||||
relatedValues lists the values seen on data matching it.
|
||||
|
||||
@@ -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,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
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ const LOG_EVENT_MOCK_PATH = '<rootDir>/src/__tests__/logEventMock.ts';
|
||||
|
||||
const config: Config.InitialOptions = {
|
||||
silent: true,
|
||||
// CI runners are slow enough that multi-step userEvent tests pass 5s.
|
||||
testTimeout: 10000,
|
||||
clearMocks: true,
|
||||
coverageDirectory: 'coverage',
|
||||
coverageReporters: ['text', 'cobertura', 'html', 'json-summary'],
|
||||
@@ -67,6 +69,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,
|
||||
|
||||
@@ -146,6 +146,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());
|
||||
|
||||
@@ -321,8 +321,8 @@ const createTracesResponse = ({
|
||||
httpMethod: trace.httpMethod ?? httpMethods[index % httpMethods.length],
|
||||
responseStatusCode:
|
||||
trace.responseStatusCode ?? statusCodes[index % statusCodes.length],
|
||||
traceID: `trace-id-${index}`,
|
||||
spanID: `span-id-${index}`,
|
||||
trace_id: `trace-id-${index}`,
|
||||
span_id: `span-id-${index}`,
|
||||
},
|
||||
};
|
||||
})
|
||||
@@ -340,8 +340,8 @@ const createTracesResponse = ({
|
||||
durationNano: 1000000 + cumulativeIndex * 100000,
|
||||
httpMethod: httpMethods[cumulativeIndex % httpMethods.length],
|
||||
responseStatusCode: statusCodes[cumulativeIndex % statusCodes.length],
|
||||
traceID: `trace-id-${cumulativeIndex}`,
|
||||
spanID: `span-id-${cumulativeIndex}`,
|
||||
trace_id: `trace-id-${cumulativeIndex}`,
|
||||
span_id: `span-id-${cumulativeIndex}`,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -15619,7 +15619,7 @@ export type GetFieldsValuesParams = {
|
||||
searchText?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description The key whose values to return, such as service.name. A context prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
* @description The key whose values to return, such as service.name. With fieldContext set, it is the stored name as is. Otherwise a context prefix such as resource.service.name sets the context and a type suffix such as service.name:string sets fieldDataType when that is empty; as in filter expressions, a prefixed name also matches a key stored under the full name, whose values come first: log.level returns values of a key named log.level, then of the log field level.
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
@@ -17236,7 +17236,7 @@ export type GetRuleHistoryFilterValuesParams = {
|
||||
searchText?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description The key whose values to return, such as service.name. A context prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
* @description The key whose values to return, such as service.name. With fieldContext set, it is the stored name as is. Otherwise a context prefix such as resource.service.name sets the context and a type suffix such as service.name:string sets fieldDataType when that is empty; as in filter expressions, a prefixed name also matches a key stored under the full name, whose values come first: log.level returns values of a key named log.level, then of the log field level.
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
|
||||
@@ -21,6 +21,7 @@ import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
convertBuilderQueriesToV5,
|
||||
createAggregation,
|
||||
mapPanelTypeToRequestType,
|
||||
prepareQueryRangePayloadV5,
|
||||
} from './prepareQueryRangePayloadV5';
|
||||
@@ -1015,3 +1016,47 @@ describe('convertBuilderQueriesToV5 builder query type', () => {
|
||||
expect(buildEnvelope(builderQueryType, 'trace').type).toBe('builder_query');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createAggregation fallback', () => {
|
||||
const logsQuery = (expression: string): Partial<IBuilderQuery> => ({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregations: [{ expression }],
|
||||
});
|
||||
|
||||
it('sends no aggregation for a heatmap with no field', () => {
|
||||
expect(createAggregation(logsQuery(''), PANEL_TYPES.HEATMAP)).toStrictEqual(
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
it('reads a field on a heatmap and turns it into count() elsewhere', () => {
|
||||
expect(
|
||||
createAggregation(logsQuery('duration_nano'), PANEL_TYPES.HEATMAP),
|
||||
).toStrictEqual([{ expression: 'duration_nano' }]);
|
||||
expect(
|
||||
createAggregation(logsQuery('duration_nano'), PANEL_TYPES.TIME_SERIES),
|
||||
).toStrictEqual([{ expression: 'count()' }]);
|
||||
});
|
||||
|
||||
it('still defaults other panels to count()', () => {
|
||||
expect(
|
||||
createAggregation(logsQuery(''), PANEL_TYPES.TIME_SERIES),
|
||||
).toStrictEqual([{ expression: 'count()' }]);
|
||||
});
|
||||
|
||||
it('sends the field of a logs heatmap query', () => {
|
||||
const [envelope] = convertBuilderQueriesToV5(
|
||||
{
|
||||
A: {
|
||||
...logsQuery('duration_nano'),
|
||||
queryName: 'A',
|
||||
} as IBuilderQuery,
|
||||
},
|
||||
mapPanelTypeToRequestType(PANEL_TYPES.HEATMAP),
|
||||
PANEL_TYPES.HEATMAP,
|
||||
);
|
||||
expect((envelope.spec as LogBuilderQuery).aggregations).toStrictEqual([
|
||||
{ expression: 'duration_nano' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,8 @@ import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
|
||||
import { foldAISlot } from 'lib/query/builderSlot';
|
||||
import getStartEndRangeTime from 'lib/getStartEndRangeTime';
|
||||
import { parseAggregations } from 'lib/query/aggregationExpression';
|
||||
import { aggregatesDistributionField } from 'lib/query/distributionField';
|
||||
import { mapQueryDataToApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
import { DynamicVariableSuggestion } from 'providers/Dashboard/store/dynamicVariableSuggestions';
|
||||
@@ -240,32 +242,6 @@ function createBaseSpec(
|
||||
};
|
||||
}
|
||||
|
||||
// Utility to parse aggregation expressions with optional alias
|
||||
export function parseAggregations(
|
||||
expression: string,
|
||||
availableAlias?: string,
|
||||
): { expression: string; alias?: string }[] {
|
||||
const result: { expression: string; alias?: string }[] = [];
|
||||
// Matches function calls like "count()" or "sum(field)" with optional alias like "as 'alias'"
|
||||
// Handles quoted ('alias'), dash-separated (field-name), and unquoted values after "as" keyword
|
||||
const regex =
|
||||
/([a-zA-Z0-9_]+\([^)]*\))(?:\s*as\s+((?:'[^']*'|"[^"]*"|[a-zA-Z0-9_-]+)))?/g;
|
||||
let match = regex.exec(expression);
|
||||
while (match !== null) {
|
||||
const expr = match[1];
|
||||
let alias = match[2] || availableAlias; // Use provided alias or availableAlias if not matched
|
||||
if (alias) {
|
||||
// Remove quotes if present
|
||||
alias = alias.replace(/^['"]|['"]$/g, '');
|
||||
result.push({ expression: expr, alias });
|
||||
} else {
|
||||
result.push({ expression: expr });
|
||||
}
|
||||
match = regex.exec(expression);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function createAggregation(
|
||||
queryData: any,
|
||||
panelType?: PANEL_TYPES,
|
||||
@@ -310,18 +286,28 @@ export function createAggregation(
|
||||
];
|
||||
}
|
||||
|
||||
// A heatmap buckets the field the user names; count() would be rejected as one.
|
||||
// Elsewhere a field is not an aggregation, so it falls back to count().
|
||||
const isDistributionField = aggregatesDistributionField(
|
||||
panelType,
|
||||
queryData.dataSource,
|
||||
);
|
||||
const fallback = isDistributionField ? [] : [{ expression: 'count()' }];
|
||||
|
||||
if (queryData.aggregations?.length > 0) {
|
||||
return queryData.aggregations.flatMap(
|
||||
(agg: { expression: string; alias?: string }) => {
|
||||
const parsedAggregations = parseAggregations(agg.expression, agg?.alias);
|
||||
return isEmpty(parsedAggregations)
|
||||
? [{ expression: 'count()' }]
|
||||
: parsedAggregations;
|
||||
const parsedAggregations = parseAggregations(
|
||||
agg.expression,
|
||||
agg?.alias,
|
||||
isDistributionField,
|
||||
);
|
||||
return isEmpty(parsedAggregations) ? fallback : parsedAggregations;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return [{ expression: 'count()' }];
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -771,7 +771,11 @@ describe('EditMemberDrawer', () => {
|
||||
it('keeps roles editable', async () => {
|
||||
renderDrawer({ member: selfMember });
|
||||
|
||||
await expect(screen.findByText('Select roles')).resolves.toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByTestId(
|
||||
`member-roles-select-chip-${managedRoles[0].id}-remove`,
|
||||
),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('member-roles-locked')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import InviteMembers from '../InviteMembers';
|
||||
import { InviteMembersProps } from '../types';
|
||||
|
||||
import { pickRole } from './roleSelectUtils';
|
||||
import {
|
||||
@@ -9,9 +10,12 @@ import {
|
||||
createErrorHandler,
|
||||
createRolesHandler,
|
||||
createSuccessHandler,
|
||||
enterInviteEmail,
|
||||
VALID_EMAIL,
|
||||
} from './testUtils';
|
||||
|
||||
type InviteCallback = Required<InviteMembersProps>['onSuccess'];
|
||||
|
||||
describe('InviteMembers - Edge Cases', () => {
|
||||
beforeEach(() => {
|
||||
server.use(createRolesHandler(), createSuccessHandler());
|
||||
@@ -23,7 +27,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
|
||||
@@ -36,13 +40,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-.*-field$/);
|
||||
expect(resetInputs).toHaveLength(2);
|
||||
resetInputs.forEach((input) => {
|
||||
expect(input).toHaveValue('');
|
||||
@@ -50,7 +53,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
});
|
||||
|
||||
it('clears results on reset', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -67,8 +70,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -84,7 +86,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,8 +100,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -107,7 +108,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
screen.findByTestId('invite-api-error'),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
await user.type(emailInputs[0], 'x');
|
||||
await user.type(screen.getAllByTestId(/^invite-email-.*-field$/)[0], 'x');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId('invite-api-error')).not.toBeInTheDocument();
|
||||
@@ -115,7 +116,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'));
|
||||
|
||||
@@ -129,8 +130,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -148,8 +148,8 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('empty submission', () => {
|
||||
it('does not submit when no rows are touched', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onSuccess = jest.fn();
|
||||
const user = userEvent.setup();
|
||||
const onSuccess = jest.fn() as jest.MockedFunction<InviteCallback>;
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -170,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
|
||||
@@ -182,8 +182,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
const submitBtn = screen.getByTestId('submit-btn');
|
||||
@@ -197,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(
|
||||
@@ -218,8 +217,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], ' alice@signoz.io ');
|
||||
await enterInviteEmail(user, 0, ' alice@signoz.io ');
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -2,6 +2,7 @@ import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import InviteMembers from '../InviteMembers';
|
||||
import { InviteMembersProps } from '../types';
|
||||
|
||||
import { pickRole } from './roleSelectUtils';
|
||||
import {
|
||||
@@ -10,9 +11,12 @@ import {
|
||||
createRolesHandler,
|
||||
createSuccessHandler,
|
||||
createTrackingHandler,
|
||||
enterInviteEmail,
|
||||
VALID_EMAIL,
|
||||
} from './testUtils';
|
||||
|
||||
type InviteCallback = Required<InviteMembersProps>['onSuccess'];
|
||||
|
||||
describe('InviteMembers - Submission', () => {
|
||||
beforeEach(() => {
|
||||
server.use(createRolesHandler(), createSuccessHandler());
|
||||
@@ -24,7 +28,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);
|
||||
|
||||
@@ -39,8 +43,7 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], 'alice@signoz.io');
|
||||
await enterInviteEmail(user, 0, 'alice@signoz.io');
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -55,7 +58,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,15 +73,11 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
|
||||
await user.type(emailInputs[0], 'alice@signoz.io');
|
||||
await enterInviteEmail(user, 0, 'alice@signoz.io');
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.type(emailInputs[1], 'bob@signoz.io');
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
await pickRole(user, 1, 'role-editor');
|
||||
|
||||
await user.type(emailInputs[2], 'charlie@signoz.io');
|
||||
await enterInviteEmail(user, 2, 'charlie@signoz.io');
|
||||
await pickRole(user, 2, 'role-admin');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -104,8 +103,8 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('callbacks', () => {
|
||||
it('calls onSuccess when all invites succeed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onSuccess = jest.fn();
|
||||
const user = userEvent.setup();
|
||||
const onSuccess = jest.fn() as jest.MockedFunction<InviteCallback>;
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -118,8 +117,7 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -130,8 +128,8 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('calls onAllFailed when all invites fail', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onAllFailed = jest.fn();
|
||||
const user = userEvent.setup();
|
||||
const onAllFailed = jest.fn() as jest.MockedFunction<InviteCallback>;
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
|
||||
@@ -146,8 +144,7 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -166,10 +163,10 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('calls onPartialSuccess when some invites succeed and some fail', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onPartialSuccess = jest.fn();
|
||||
const onSuccess = jest.fn();
|
||||
const onAllFailed = jest.fn();
|
||||
const user = userEvent.setup();
|
||||
const onPartialSuccess = jest.fn() as jest.MockedFunction<InviteCallback>;
|
||||
const onSuccess = jest.fn() as jest.MockedFunction<InviteCallback>;
|
||||
const onAllFailed = jest.fn() as jest.MockedFunction<InviteCallback>;
|
||||
const apiCalls: string[] = [];
|
||||
let callCount = 0;
|
||||
|
||||
@@ -208,12 +205,9 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
|
||||
await user.type(emailInputs[0], 'alice@signoz.io');
|
||||
await enterInviteEmail(user, 0, 'alice@signoz.io');
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.type(emailInputs[1], 'bob@signoz.io');
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
await pickRole(user, 1, 'role-editor');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -252,7 +246,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
|
||||
@@ -264,8 +258,7 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -276,7 +269,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'));
|
||||
|
||||
@@ -290,8 +283,7 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -305,7 +297,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
|
||||
@@ -319,14 +311,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
|
||||
@@ -339,12 +330,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,12 @@ 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-.*-field$/)[rowIndex]);
|
||||
await user.paste(email);
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ interface Props {
|
||||
placeholder?: string;
|
||||
// Rendered at the end of the search row (e.g. the New Dashboard action).
|
||||
rightSlot?: ReactNode;
|
||||
// Rendered in the filters row after the chips. A function receives the draft.
|
||||
// Rendered in the filters row before the chips. A function receives the draft.
|
||||
extraFilters?: ReactNode | ((api: ExtraFiltersApi) => ReactNode);
|
||||
// Shows Clear even when the query is empty.
|
||||
hasExtraFilters?: boolean;
|
||||
@@ -142,6 +142,9 @@ function FilterZone({
|
||||
className={styles.filterControls}
|
||||
data-testid={`${testIdPrefix}-filter-zone`}
|
||||
>
|
||||
{typeof extraFilters === 'function'
|
||||
? extraFilters({ draft, applyDraft, setDraft })
|
||||
: extraFilters}
|
||||
<FilterChips
|
||||
{...createdByProps}
|
||||
updated={reflected.updated}
|
||||
@@ -150,9 +153,6 @@ function FilterZone({
|
||||
onApply={run}
|
||||
disabled={disabled}
|
||||
/>
|
||||
{typeof extraFilters === 'function'
|
||||
? extraFilters({ draft, applyDraft, setDraft })
|
||||
: extraFilters}
|
||||
{(!isEmpty || hasExtraFilters) && (
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
|
||||
@@ -43,6 +43,7 @@ function MultiSelectFilter({
|
||||
allowClear
|
||||
className={cx(styles.select, styles.selectWide)}
|
||||
placeholder={placeholder}
|
||||
aria-label={placeholder}
|
||||
value={value}
|
||||
options={options}
|
||||
optionFilterProp="label"
|
||||
@@ -52,7 +53,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,4 +1,10 @@
|
||||
import { type MouseEvent, useCallback, useMemo, useRef } from 'react';
|
||||
import {
|
||||
type FocusEvent,
|
||||
type MouseEvent,
|
||||
useCallback,
|
||||
useMemo,
|
||||
useRef,
|
||||
} from 'react';
|
||||
import {
|
||||
autocompletion,
|
||||
closeCompletion,
|
||||
@@ -27,7 +33,7 @@ import styles from './SearchBar.module.scss';
|
||||
interface Props {
|
||||
value: string;
|
||||
grammar: DslGrammar;
|
||||
// Ids: `${testIdPrefix}`, `-submit`, `-dirty`.
|
||||
// Ids: `${testIdPrefix}`, `-field` (the editable area), `-submit`, `-dirty`.
|
||||
testIdPrefix: string;
|
||||
onChange: (value: string) => void;
|
||||
onSubmit: () => void;
|
||||
@@ -67,10 +73,25 @@ function SearchBar({
|
||||
const onSubmitRef = useRef(handleSubmit);
|
||||
onSubmitRef.current = handleSubmit;
|
||||
|
||||
// Leaving the box runs an unrun draft, e.g. terms picked from the suggestions.
|
||||
// A blur from switching windows or tabs does not.
|
||||
const handleBlur = useCallback(
|
||||
(event: FocusEvent<HTMLDivElement>): void => {
|
||||
const stillInside = event.currentTarget.contains(
|
||||
event.relatedTarget as Node | null,
|
||||
);
|
||||
if (!stillInside && dirty && !disabled && document.hasFocus()) {
|
||||
handleSubmit();
|
||||
}
|
||||
},
|
||||
[dirty, disabled, handleSubmit],
|
||||
);
|
||||
|
||||
const extensions = useMemo(
|
||||
() => [
|
||||
dslHighlight,
|
||||
editorTheme,
|
||||
EditorView.contentAttributes.of({ 'data-testid': `${testIdPrefix}-field` }),
|
||||
// Wrap a long query onto the next line instead of scrolling horizontally.
|
||||
EditorView.lineWrapping,
|
||||
// Read-only is not enough: these open the list on click and accepting an
|
||||
@@ -122,12 +143,15 @@ function SearchBar({
|
||||
]),
|
||||
),
|
||||
],
|
||||
[disabled],
|
||||
[disabled, testIdPrefix],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.wrapper}>
|
||||
<div className={cx(styles.field, { [styles.disabled]: disabled })}>
|
||||
<div
|
||||
className={cx(styles.field, { [styles.disabled]: disabled })}
|
||||
onBlur={handleBlur}
|
||||
>
|
||||
<Search
|
||||
size={12}
|
||||
color={Color.BG_VANILLA_400}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import type { DslGrammar } from '../../dsl/types';
|
||||
import SearchBar from '../SearchBar';
|
||||
|
||||
type SearchBarProps = ComponentProps<typeof SearchBar>;
|
||||
|
||||
const GRAMMAR: DslGrammar = {
|
||||
fields: [{ key: 'name', type: 'string' }],
|
||||
dynamicKey: { detail: 'tag', prefix: '' },
|
||||
};
|
||||
|
||||
function renderSearchBar(props: { dirty: boolean; disabled?: boolean }): {
|
||||
onSubmit: jest.MockedFunction<SearchBarProps['onSubmit']>;
|
||||
onSubmitted: jest.MockedFunction<NonNullable<SearchBarProps['onSubmitted']>>;
|
||||
} {
|
||||
const onSubmit = jest.fn() as jest.MockedFunction<SearchBarProps['onSubmit']>;
|
||||
const onSubmitted = jest.fn() as jest.MockedFunction<
|
||||
NonNullable<SearchBarProps['onSubmitted']>
|
||||
>;
|
||||
render(
|
||||
<>
|
||||
<SearchBar
|
||||
value="name = 'x'"
|
||||
grammar={GRAMMAR}
|
||||
testIdPrefix="list-search"
|
||||
onChange={jest.fn()}
|
||||
onSubmit={onSubmit}
|
||||
onSubmitted={onSubmitted}
|
||||
dirty={props.dirty}
|
||||
disabled={props.disabled}
|
||||
/>
|
||||
<button type="button" data-testid="outside">
|
||||
outside
|
||||
</button>
|
||||
</>,
|
||||
);
|
||||
return { onSubmit, onSubmitted };
|
||||
}
|
||||
|
||||
function searchContent(): HTMLElement {
|
||||
return screen
|
||||
.getByTestId('list-search')
|
||||
.querySelector('.cm-content') as HTMLElement;
|
||||
}
|
||||
|
||||
describe('SearchBar — run on blur', () => {
|
||||
let hasFocus: jest.SpyInstance<boolean, []>;
|
||||
|
||||
beforeEach(() => {
|
||||
// jsdom reports no focus once it leaves the editor; a focused browser window does.
|
||||
hasFocus = jest.spyOn(document, 'hasFocus').mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('runs an unrun draft when focus leaves the box', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { onSubmit, onSubmitted } = renderSearchBar({ dirty: true });
|
||||
|
||||
await user.click(searchContent());
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
expect(onSubmitted).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('does nothing when the draft was already run', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { onSubmit } = renderSearchBar({ dirty: false });
|
||||
|
||||
await user.click(searchContent());
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does nothing when focus leaves the window', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { onSubmit } = renderSearchBar({ dirty: true });
|
||||
|
||||
await user.click(searchContent());
|
||||
hasFocus.mockReturnValue(false);
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs once when Run query is clicked with an unrun draft', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { onSubmit } = renderSearchBar({ dirty: true });
|
||||
|
||||
await user.click(searchContent());
|
||||
await user.click(screen.getByTestId('list-search-submit'));
|
||||
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
.headerZone {
|
||||
// Sticks to the top of a scrolling list so the heading and filters stay put
|
||||
// while results scroll beneath. The DSL suggestion popup (z-index 1000) still
|
||||
// layers above it.
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
gap: 14px;
|
||||
padding: 20px 24px;
|
||||
background: var(--l2-background);
|
||||
border-bottom: 1px solid var(--l2-border);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import styles from './ListHeaderZone.module.scss';
|
||||
|
||||
interface Props {
|
||||
/** Rendered regardless of whether the list has anything in it. */
|
||||
children: ReactNode;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
function ListHeaderZone({ children, testId }: Props): JSX.Element {
|
||||
return (
|
||||
<div className={styles.headerZone} data-testid={testId}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ListHeaderZone;
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -273,7 +273,10 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
)}
|
||||
|
||||
{!showOnlyWhereClause && activeBuilder.queryFormulas?.length > 0 && (
|
||||
<div className="qb-formulas-container">
|
||||
<div
|
||||
className="qb-formulas-container"
|
||||
data-testid="qb-formulas-container"
|
||||
>
|
||||
{activeBuilder.queryFormulas.map((formula, index) => {
|
||||
const query =
|
||||
activeBuilder.queryData[index] || activeBuilder.queryData[0];
|
||||
@@ -312,7 +315,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
</div>
|
||||
|
||||
{showQueryList && (
|
||||
<div className="query-names-section">
|
||||
<div className="query-names-section" data-testid="query-names-section">
|
||||
{renderedQueries.map((query) => (
|
||||
<div key={query.queryName} className="query-name">
|
||||
{query.queryName}
|
||||
|
||||
@@ -106,8 +106,10 @@ function QueryAddOns({
|
||||
|
||||
if (
|
||||
panelType === PANEL_TYPES.HEATMAP &&
|
||||
query.dataSource === DataSource.METRICS &&
|
||||
!HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')
|
||||
!(
|
||||
query.dataSource === DataSource.METRICS &&
|
||||
HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')
|
||||
)
|
||||
) {
|
||||
addOns = [...addOns, BUCKET_OPTIONS];
|
||||
}
|
||||
@@ -436,6 +438,7 @@ function QueryAddOns({
|
||||
onChange={handleChangeOrderByKeys}
|
||||
isRawQuery={isRawQuery}
|
||||
isNewQueryV2
|
||||
panelType={panelType ?? undefined}
|
||||
placeholder={placeholderOf(QueryBuilderField.OrderBy)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -107,8 +107,8 @@ export const BASE_ADD_ONS = (
|
||||
|
||||
export const REDUCE_TO = toAddOn(QueryBuilderField.ReduceTo);
|
||||
|
||||
// Offered only by a heatmap over metrics: the bucket axis is what a heatmap plots
|
||||
// against, and no other panel type sends one. A histogram brings its own buckets.
|
||||
// Offered only by a heatmap: the bucket axis is what a heatmap plots against, and no
|
||||
// other panel type sends one. A histogram metric brings its own buckets.
|
||||
export const HISTOGRAM_ATTRIBUTE_TYPES = new Set<string>([
|
||||
ATTRIBUTE_TYPES.HISTOGRAM,
|
||||
ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
// Fills the row like the filter and Group By boxes.
|
||||
.select {
|
||||
flex: 1;
|
||||
min-width: 400px;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Combobox } from '@signozhq/ui/combobox';
|
||||
import { TelemetrytypesFieldDataTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
|
||||
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
|
||||
import useDebounce from 'hooks/useDebounce';
|
||||
import { getDistributionFieldPlaceholder } from 'lib/query/distributionField';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DATA_SOURCE_TO_SIGNAL } from 'types/common/queryBuilder';
|
||||
|
||||
import { toDistributionFieldOptions } from './distributionFieldOptions';
|
||||
|
||||
import Styles from './DistributionFieldSelect.module.scss';
|
||||
|
||||
/** A logs or traces heatmap's aggregation: the one numeric field it buckets. */
|
||||
export default function DistributionFieldSelect({
|
||||
queryData,
|
||||
onChange,
|
||||
}: {
|
||||
queryData: IBuilderQuery;
|
||||
onChange?: (field: string) => void;
|
||||
}): JSX.Element {
|
||||
const [search, setSearch] = useState('');
|
||||
const searchText = useDebounce(search, DEBOUNCE_DELAY);
|
||||
|
||||
// The keys API caps its answer, so a field past the cap is reached by searching.
|
||||
const {
|
||||
data: fieldKeys,
|
||||
isLoading,
|
||||
isFetching,
|
||||
} = useFieldKeysSuggestion(
|
||||
{
|
||||
signal: DATA_SOURCE_TO_SIGNAL[queryData.dataSource],
|
||||
searchText,
|
||||
fieldDataType: TelemetrytypesFieldDataTypeDTO.number,
|
||||
},
|
||||
queryData.builderQueryType,
|
||||
{ keepPreviousData: true },
|
||||
);
|
||||
|
||||
const [aggregation] = queryData.aggregations ?? [];
|
||||
const selectedField =
|
||||
aggregation && 'expression' in aggregation ? aggregation.expression : '';
|
||||
|
||||
const items = useMemo(
|
||||
() => toDistributionFieldOptions(fieldKeys ?? [], selectedField),
|
||||
[fieldKeys, selectedField],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={Styles.select}>
|
||||
<Combobox
|
||||
items={items}
|
||||
value={selectedField || undefined}
|
||||
onChange={(field): void => onChange?.(field ?? '')}
|
||||
allowClear
|
||||
placeholder={getDistributionFieldPlaceholder(queryData.dataSource)}
|
||||
searchInputProps={{
|
||||
placeholder: 'Search numeric fields',
|
||||
loading: isFetching,
|
||||
onChange: setSearch,
|
||||
}}
|
||||
loading={isLoading}
|
||||
noContent="No numeric fields"
|
||||
testId="distribution-field-select"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
IBuilderQuery,
|
||||
IBuilderTraceOperator,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { aggregatesDistributionField } from 'lib/query/distributionField';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
} from '../../queryBuilderFields.utils';
|
||||
|
||||
import { isScalarPanelType } from '../panelTypes';
|
||||
import DistributionFieldSelect from './DistributionFieldSelect';
|
||||
import QueryAggregationSelect from './QueryAggregationSelect';
|
||||
|
||||
import './QueryAggregation.styles.scss';
|
||||
@@ -63,17 +65,21 @@ function QueryAggregationOptions({
|
||||
data-testid="query-aggregation-container"
|
||||
>
|
||||
<div className="aggregation-container">
|
||||
<QueryAggregationSelect
|
||||
onChange={onChange}
|
||||
queryData={queryData}
|
||||
maxAggregations={
|
||||
panelType === PANEL_TYPES.VALUE ||
|
||||
panelType === PANEL_TYPES.PIE ||
|
||||
panelType === PANEL_TYPES.TOP_LIST
|
||||
? 1
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{aggregatesDistributionField(panelType, dataSource) ? (
|
||||
<DistributionFieldSelect queryData={queryData} onChange={onChange} />
|
||||
) : (
|
||||
<QueryAggregationSelect
|
||||
onChange={onChange}
|
||||
queryData={queryData}
|
||||
maxAggregations={
|
||||
panelType === PANEL_TYPES.VALUE ||
|
||||
panelType === PANEL_TYPES.PIE ||
|
||||
panelType === PANEL_TYPES.TOP_LIST
|
||||
? 1
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!stepInterval.hidden && (
|
||||
<div className="query-aggregation-interval">
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import {
|
||||
TelemetrytypesFieldContextDTO,
|
||||
TelemetrytypesFieldDataTypeDTO,
|
||||
TelemetrytypesSignalDTO,
|
||||
type GetFieldsKeys200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import DistributionFieldSelect from '../DistributionFieldSelect';
|
||||
|
||||
const keysResponse: GetFieldsKeys200 = {
|
||||
status: 'success',
|
||||
data: {
|
||||
complete: true,
|
||||
keys: {
|
||||
duration_nano: [
|
||||
{
|
||||
name: 'duration_nano',
|
||||
fieldContext: TelemetrytypesFieldContextDTO.span,
|
||||
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
|
||||
signal: TelemetrytypesSignalDTO.traces,
|
||||
},
|
||||
],
|
||||
quantity: [
|
||||
{
|
||||
name: 'quantity',
|
||||
fieldContext: TelemetrytypesFieldContextDTO.attribute,
|
||||
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
|
||||
signal: TelemetrytypesSignalDTO.traces,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const tracesQuery = (expression: string): IBuilderQuery => ({
|
||||
...(initialQueriesMap.traces.builder.queryData[0] as IBuilderQuery),
|
||||
aggregations: [{ expression }],
|
||||
});
|
||||
|
||||
describe('DistributionFieldSelect', () => {
|
||||
const requests: URLSearchParams[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
server.use(
|
||||
rest.get(`${ENVIRONMENT.baseURL}/api/v1/fields/keys`, (req, res, ctx) => {
|
||||
requests.push(req.url.searchParams);
|
||||
return res(ctx.status(200), ctx.json(keysResponse));
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the saved field', () => {
|
||||
render(
|
||||
<DistributionFieldSelect
|
||||
queryData={tracesQuery('duration_nano')}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('distribution-field-select')).toHaveTextContent(
|
||||
'duration_nano',
|
||||
);
|
||||
});
|
||||
|
||||
it('picks a numeric field, keeping its context', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={onChange} />,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
await screen.findByTestId(
|
||||
'distribution-field-select-item-attribute.quantity',
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId('distribution-field-select-search'),
|
||||
'attribute.quantity{Enter}',
|
||||
);
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('attribute.quantity');
|
||||
expect(requests[0].get('fieldDataType')).toBe(
|
||||
TelemetrytypesFieldDataTypeDTO.number,
|
||||
);
|
||||
expect(requests[0].get('signal')).toBe('traces');
|
||||
});
|
||||
|
||||
it('replaces the saved field with the newly picked one', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
|
||||
render(
|
||||
<DistributionFieldSelect
|
||||
queryData={tracesQuery('duration_nano')}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
await screen.findByTestId(
|
||||
'distribution-field-select-item-attribute.quantity',
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId('distribution-field-select-search'),
|
||||
'attribute.quantity{Enter}',
|
||||
);
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('attribute.quantity');
|
||||
});
|
||||
|
||||
it('only offers listed fields: typed text is a filter, not a value', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
await screen.findByTestId(
|
||||
'distribution-field-select-item-attribute.quantity',
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId('distribution-field-select-search'),
|
||||
'no_such_field',
|
||||
);
|
||||
|
||||
await screen.findByText('No numeric fields');
|
||||
expect(
|
||||
screen.queryByTestId('distribution-field-select-item-no_such_field'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('searches the server for typed text, past the listed fields', async () => {
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
pointerEventsCheck: 0,
|
||||
});
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
await user.type(
|
||||
await screen.findByTestId('distribution-field-select-search'),
|
||||
'queue',
|
||||
);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(DEBOUNCE_DELAY);
|
||||
});
|
||||
|
||||
await waitFor(() => expect(requests.at(-1)?.get('searchText')).toBe('queue'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { TelemetrytypesFieldContextDTO as FieldContext } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import {
|
||||
toDistributionFieldOptions,
|
||||
toDistributionFieldText,
|
||||
} from '../distributionFieldOptions';
|
||||
|
||||
const key = (
|
||||
name: string,
|
||||
fieldContext: FieldContext,
|
||||
): { name: string; fieldContext: FieldContext } => ({ name, fieldContext });
|
||||
|
||||
const KEYS = [
|
||||
key('quantity', FieldContext.resource),
|
||||
key('duration_nano', FieldContext.span),
|
||||
key('quantity', FieldContext.attribute),
|
||||
key('total_tokens', FieldContext.trace),
|
||||
key('latency', FieldContext.body),
|
||||
key('duration_nano', FieldContext.span),
|
||||
];
|
||||
|
||||
describe('toDistributionFieldText', () => {
|
||||
it.each([
|
||||
[key('duration_nano', FieldContext.span), 'duration_nano'],
|
||||
[key('severity_number', FieldContext.log), 'severity_number'],
|
||||
[
|
||||
key('http.status_code', FieldContext.attribute),
|
||||
'attribute.http.status_code',
|
||||
],
|
||||
[key('latency', FieldContext.body), 'body.latency'],
|
||||
])('%j → %s', (fieldKey, text) => {
|
||||
expect(toDistributionFieldText(fieldKey)).toBe(text);
|
||||
});
|
||||
});
|
||||
|
||||
const item = (
|
||||
text: string,
|
||||
): { type: 'item'; label: string; value: string } => ({
|
||||
type: 'item',
|
||||
label: text,
|
||||
value: text,
|
||||
});
|
||||
|
||||
describe('toDistributionFieldOptions', () => {
|
||||
it('groups columns first, keeps contexts apart, drops trace keys and repeats', () => {
|
||||
expect(toDistributionFieldOptions(KEYS, 'duration_nano')).toStrictEqual([
|
||||
{
|
||||
type: 'group',
|
||||
label: 'Columns',
|
||||
value: 'column',
|
||||
items: [item('duration_nano')],
|
||||
},
|
||||
{
|
||||
type: 'group',
|
||||
label: 'Attribute',
|
||||
value: 'attribute',
|
||||
items: [item('attribute.quantity')],
|
||||
},
|
||||
{
|
||||
type: 'group',
|
||||
label: 'Resource',
|
||||
value: 'resource',
|
||||
items: [item('resource.quantity')],
|
||||
},
|
||||
{
|
||||
type: 'group',
|
||||
label: 'Body',
|
||||
value: 'body',
|
||||
items: [item('body.latency')],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('leads with a saved field the keys do not carry', () => {
|
||||
const options = toDistributionFieldOptions(KEYS, 'queue-depth');
|
||||
expect(options[0]).toStrictEqual(item('queue-depth'));
|
||||
expect(options).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('adds nothing for an empty or listed field', () => {
|
||||
expect(toDistributionFieldOptions(KEYS, '')).toHaveLength(4);
|
||||
expect(toDistributionFieldOptions(KEYS, 'body.latency')).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import type {
|
||||
ComboboxItemType,
|
||||
ComboboxOptionItemType,
|
||||
} from '@signozhq/ui/combobox';
|
||||
import { TelemetrytypesFieldContextDTO as FieldContext } from 'api/generated/services/sigNoz.schemas';
|
||||
import { upperFirst } from 'lodash-es';
|
||||
import type { TelemetryFieldKey } from 'types/api/v5/queryRange';
|
||||
|
||||
// Span and log columns are read by their name alone; anything else keeps its
|
||||
// context so `attribute.quantity` and `resource.quantity` stay apart.
|
||||
const COLUMN_CONTEXTS = new Set<string | undefined>([
|
||||
FieldContext.span,
|
||||
FieldContext.log,
|
||||
FieldContext[''],
|
||||
]);
|
||||
|
||||
const GROUP_ORDER: string[] = [
|
||||
'column',
|
||||
FieldContext.attribute,
|
||||
FieldContext.resource,
|
||||
];
|
||||
|
||||
const headingOf = (group: string): string =>
|
||||
group === 'column' ? 'Columns' : upperFirst(group);
|
||||
|
||||
const toItem = (text: string): ComboboxOptionItemType => ({
|
||||
type: 'item',
|
||||
label: text,
|
||||
value: text,
|
||||
});
|
||||
|
||||
/** The key text the querier parses back into this key (`GetFieldKeyFromKeyText`). */
|
||||
export function toDistributionFieldText(key: TelemetryFieldKey): string {
|
||||
return COLUMN_CONTEXTS.has(key.fieldContext)
|
||||
? key.name
|
||||
: `${key.fieldContext}.${key.name}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Numeric keys grouped by context, each one once. `trace.*` keys are per-trace
|
||||
* aggregates, which a heatmap cannot bucket. A saved field the keys do not carry
|
||||
* leads as its own item, so the combobox can still show it.
|
||||
*/
|
||||
export function toDistributionFieldOptions(
|
||||
keys: TelemetryFieldKey[],
|
||||
selectedField: string,
|
||||
): ComboboxItemType[] {
|
||||
const byGroup = new Map<string, Set<string>>();
|
||||
keys
|
||||
.filter((key) => key.fieldContext !== FieldContext.trace)
|
||||
.forEach((key) => {
|
||||
const group = COLUMN_CONTEXTS.has(key.fieldContext)
|
||||
? 'column'
|
||||
: String(key.fieldContext);
|
||||
byGroup.set(
|
||||
group,
|
||||
(byGroup.get(group) ?? new Set()).add(toDistributionFieldText(key)),
|
||||
);
|
||||
});
|
||||
|
||||
const isSelectedListed = [...byGroup.values()].some((texts) =>
|
||||
texts.has(selectedField),
|
||||
);
|
||||
const rank = (group: string): number => {
|
||||
const index = GROUP_ORDER.indexOf(group);
|
||||
return index === -1 ? GROUP_ORDER.length : index;
|
||||
};
|
||||
|
||||
const groups = [...byGroup.entries()]
|
||||
.sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))
|
||||
.map(([group, texts]): ComboboxItemType => ({
|
||||
type: 'group',
|
||||
label: headingOf(group),
|
||||
value: group,
|
||||
items: [...texts].map(toItem),
|
||||
}));
|
||||
|
||||
return selectedField && !isSelectedListed
|
||||
? [toItem(selectedField), ...groups]
|
||||
: groups;
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
/* eslint-disable @typescript-eslint/explicit-function-return-type */
|
||||
import { jest } from '@jest/globals';
|
||||
import { fireEvent, waitFor } from '@testing-library/react';
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
import {
|
||||
Having,
|
||||
IBuilderQuery,
|
||||
@@ -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,35 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
expect(limitInput).toHaveAttribute('data-testid', 'input-Limit-field');
|
||||
});
|
||||
|
||||
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-field').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 editorWrapper = await screen.findByTestId('query-where-clause-editor');
|
||||
within(editorWrapper).getByRole('textbox', { hidden: true }).focus();
|
||||
await user.keyboard('{Meta>}{Enter}{/Meta}');
|
||||
|
||||
expect(handleRunQueryMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not crash when builder.queryFormulas/queryTraceOperator are missing (partial/legacy query)', () => {
|
||||
@@ -243,22 +253,17 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
).not.toThrow();
|
||||
|
||||
// query list still renders from queryData, formulas block is skipped
|
||||
expect(document.querySelector('.query-names-section')).toBeInTheDocument();
|
||||
expect(
|
||||
document.querySelector('.qb-formulas-container'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('query-names-section')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('qb-formulas-container')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('query actions menu', () => {
|
||||
const openQueryActions = async (): Promise<void> => {
|
||||
await userEvent.click(screen.getAllByTestId('query-actions')[0]);
|
||||
};
|
||||
|
||||
it('Clone calls cloneQuery with the query', async () => {
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
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 +275,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 +287,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;
|
||||
|
||||
@@ -351,17 +344,13 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
const fxButton = document.querySelector('.function-btn') as HTMLButtonElement;
|
||||
const fxButton = screen.getByTestId('query-functions-fx-btn');
|
||||
expect(fxButton).toBeInTheDocument();
|
||||
expect(fxButton).toBeDisabled();
|
||||
|
||||
const deleteButton = document.querySelector(
|
||||
'.query-function-delete-btn',
|
||||
) as HTMLButtonElement;
|
||||
const deleteButton = screen.getByTestId('query-function-delete-btn');
|
||||
expect(deleteButton).toBeInTheDocument();
|
||||
userEvent.click(deleteButton);
|
||||
waitFor(() => {
|
||||
expect(fxButton).not.toBeDisabled();
|
||||
});
|
||||
await user.click(deleteButton);
|
||||
expect(fxButton).not.toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -506,7 +506,7 @@ describe('QueryAddOns', () => {
|
||||
);
|
||||
}
|
||||
|
||||
it('is offered on a metrics heatmap only', () => {
|
||||
it('is offered on a metrics heatmap', () => {
|
||||
renderHeatmap();
|
||||
|
||||
expect(
|
||||
@@ -532,23 +532,16 @@ describe('QueryAddOns', () => {
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('is not offered on a heatmap over another signal', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery({ dataSource: DataSource.LOGS })}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.HEATMAP}
|
||||
index={0}
|
||||
isForTraceOperator={false}
|
||||
/>,
|
||||
);
|
||||
it.each([DataSource.LOGS, DataSource.TRACES])(
|
||||
'is offered on a %s heatmap',
|
||||
(dataSource) => {
|
||||
renderHeatmap({ dataSource });
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('query-add-on-bucket_options'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
expect(
|
||||
screen.getByTestId('query-add-on-bucket_options'),
|
||||
).toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([ATTRIBUTE_TYPES.HISTOGRAM, ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM])(
|
||||
'is not offered for a %s metric, which carries its own buckets',
|
||||
|
||||
@@ -8,7 +8,7 @@ import QueryAggregationOptions from '../QueryV2/QueryAggregation/QueryAggregatio
|
||||
|
||||
jest.mock('../QueryV2/QueryAggregation/QueryAggregationSelect', () => ({
|
||||
__esModule: true,
|
||||
default: (): null => null,
|
||||
default: (): JSX.Element => <div data-testid="aggregation-select" />,
|
||||
}));
|
||||
|
||||
const queryData = initialQueriesMap.traces.builder
|
||||
@@ -69,3 +69,18 @@ describe('QueryAggregationOptions step interval', () => {
|
||||
expect(screen.getByText('every')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('QueryAggregationOptions on a heatmap', () => {
|
||||
it.each([
|
||||
[PANEL_TYPES.HEATMAP, DataSource.TRACES, true],
|
||||
[PANEL_TYPES.HEATMAP, DataSource.METRICS, false],
|
||||
[PANEL_TYPES.TIME_SERIES, DataSource.TRACES, false],
|
||||
])(
|
||||
'%s over %s renders the field picker: %s',
|
||||
(panelType, dataSource, picker) => {
|
||||
renderFor(panelType, dataSource);
|
||||
expect(!!screen.queryByTestId('distribution-field-select')).toBe(picker);
|
||||
expect(!!screen.queryByTestId('aggregation-select')).toBe(!picker);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -208,6 +208,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
placeholder="Select a query"
|
||||
searchInputProps={{ placeholder: 'Search queries' }}
|
||||
items={queryItems}
|
||||
testId="quick-filters-query-select"
|
||||
value={String(validQueryIndex)}
|
||||
onChange={(value): void => {
|
||||
if (value !== undefined) {
|
||||
@@ -318,6 +319,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
color="primary"
|
||||
textPlacement="right"
|
||||
value={showIP ?? true}
|
||||
testId="quick-filters-show-ip"
|
||||
onChange={(checked): void => {
|
||||
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>
|
||||
|
||||
@@ -84,6 +84,7 @@ function QuickFiltersSettings({
|
||||
<Button
|
||||
type="default"
|
||||
onClick={handleDiscardChanges}
|
||||
data-testid="quick-filters-settings-discard"
|
||||
icon={<X size={16} />}
|
||||
>
|
||||
Discard
|
||||
@@ -93,6 +94,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,13 @@ 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 { QueryBuilderContextType } from 'types/common/queryBuilder';
|
||||
|
||||
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,10 +32,25 @@ 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();
|
||||
const putHandler = jest.fn();
|
||||
const redirectWithQueryBuilderData = jest.fn() as jest.MockedFunction<
|
||||
QueryBuilderContextType['redirectWithQueryBuilderData']
|
||||
>;
|
||||
const putHandler = jest.fn() as jest.MockedFunction<
|
||||
(body: { filters: TelemetryFieldKey[] }) => void
|
||||
>;
|
||||
const mockSetApiMonitoringParams = jest.fn() as jest.MockedFunction<
|
||||
(newParams: Partial<ApiMonitoringParams>, replace?: boolean) => void
|
||||
>;
|
||||
@@ -44,14 +65,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 +129,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 +154,7 @@ beforeAll(() => {
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
jest.clearAllMocks();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
@@ -138,8 +191,10 @@ 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 setLastUsedQuery = jest.fn() as jest.MockedFunction<
|
||||
QueryBuilderContextType['setLastUsedQuery']
|
||||
>;
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useQueryBuilder as jest.Mock).mockReturnValue({
|
||||
currentQuery: {
|
||||
@@ -169,42 +224,35 @@ 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-select-item-0'),
|
||||
).resolves.toHaveTextContent('Query A');
|
||||
expect(
|
||||
screen.getByTestId('quick-filters-query-select-item-1'),
|
||||
).toHaveTextContent('Query B');
|
||||
expect(
|
||||
screen.getByTestId('quick-filters-query-select-item-2'),
|
||||
).toHaveTextContent('Query C');
|
||||
|
||||
// Select Query B with the keyboard: jsdom cannot deliver the pointer
|
||||
// click Base UI expects, so filter through the search row and pick with
|
||||
// Enter instead
|
||||
await waitFor(() => {
|
||||
// jsdom cannot deliver the pointer click Base UI expects on an option,
|
||||
// so pick Query B with the arrow keys and Enter
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole('combobox', { name: 'Search queries' }),
|
||||
).toHaveFocus();
|
||||
});
|
||||
await user.keyboard('Query B');
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.queryByRole('option', { name: 'Query A' }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
screen.getByTestId('quick-filters-query-select-search'),
|
||||
).toHaveFocus(),
|
||||
);
|
||||
await user.keyboard('{ArrowDown}{Enter}');
|
||||
|
||||
// Verify setLastUsedQuery was called with index 1
|
||||
await waitFor(() => {
|
||||
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
|
||||
});
|
||||
// filtering and picking through the search row takes Base UI past the
|
||||
// default 5s under jsdom
|
||||
}, 20000);
|
||||
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('should not display query dropdown in ListView', () => {
|
||||
(useQueryBuilder as jest.Mock).mockReturnValue({
|
||||
@@ -244,12 +292,13 @@ describe('Quick Filters', () => {
|
||||
expect(screen.getByText(QUERY_NAME)).toBeInTheDocument();
|
||||
|
||||
// No dropdown should be present
|
||||
const queryText = screen.getByText(QUERY_NAME);
|
||||
expect(queryText.closest('[role="combobox"]')).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('quick-filters-query-select'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should add filter data to query when checkbox is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<TestQuickFilters />);
|
||||
|
||||
@@ -281,33 +330,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} />,
|
||||
);
|
||||
@@ -318,28 +361,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(
|
||||
@@ -370,153 +417,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();
|
||||
@@ -530,24 +510,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');
|
||||
@@ -649,7 +642,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());
|
||||
@@ -657,26 +650,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));
|
||||
@@ -684,11 +665,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',
|
||||
@@ -704,38 +685,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,14 +4,12 @@ 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';
|
||||
|
||||
// Picking a role in the Combobox inside the Drawer takes seconds in jsdom, and
|
||||
// the 429 retry waits another second on top.
|
||||
jest.setTimeout(20000);
|
||||
import ServiceAccountDrawer, {
|
||||
ServiceAccountDrawerProps,
|
||||
} from '../ServiceAccountDrawer';
|
||||
|
||||
const ROLES_ENDPOINT = '*/api/v1/roles';
|
||||
const SA_KEYS_ENDPOINT = '*/api/v1/service_accounts/:id/keys';
|
||||
@@ -97,16 +95,18 @@ 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',
|
||||
);
|
||||
});
|
||||
|
||||
it('editing name enables Save; clicking Save sends correct payload and calls onSuccess', async () => {
|
||||
const onSuccess = jest.fn();
|
||||
const onSuccess = jest.fn() as jest.MockedFunction<
|
||||
ServiceAccountDrawerProps['onSuccess']
|
||||
>;
|
||||
const updateSpy = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.put(SA_ENDPOINT, async (req, res, ctx) => {
|
||||
@@ -125,7 +125,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'),
|
||||
);
|
||||
@@ -144,7 +144,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) => {
|
||||
@@ -171,7 +171,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
`${managedRoles[2].name}{Enter}`,
|
||||
);
|
||||
|
||||
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'),
|
||||
);
|
||||
@@ -191,7 +191,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) => {
|
||||
@@ -218,7 +218,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
),
|
||||
);
|
||||
|
||||
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'),
|
||||
);
|
||||
@@ -232,7 +232,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) => {
|
||||
@@ -245,9 +245,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(
|
||||
@@ -279,23 +277,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();
|
||||
});
|
||||
@@ -348,11 +342,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) =>
|
||||
@@ -374,7 +369,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'),
|
||||
);
|
||||
@@ -388,7 +383,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) =>
|
||||
@@ -415,7 +410,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
`${managedRoles[2].name}{Enter}`,
|
||||
);
|
||||
|
||||
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'),
|
||||
);
|
||||
@@ -429,7 +424,13 @@ 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() as jest.MockedFunction<
|
||||
ServiceAccountDrawerProps['onSuccess']
|
||||
>;
|
||||
let roleAddCallCount = 0;
|
||||
|
||||
// First call → 429, second call → 201
|
||||
@@ -446,7 +447,11 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
renderDrawer();
|
||||
render(
|
||||
<NuqsTestingAdapter searchParams={{ account: 'sa-1' }} hasMemory>
|
||||
<ServiceAccountDrawer onSuccess={onSuccess} />
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
|
||||
await screen.findByDisplayValue('CI Bot');
|
||||
|
||||
@@ -456,24 +461,24 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
`${managedRoles[2].name}{Enter}`,
|
||||
);
|
||||
|
||||
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(
|
||||
@@ -496,7 +501,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'),
|
||||
);
|
||||
@@ -512,7 +517,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';
|
||||
|
||||
|
||||
@@ -152,6 +152,7 @@ function TanStackHeaderRow<TData>({
|
||||
style={headerCellStyle}
|
||||
data-dark-mode={isDarkMode}
|
||||
data-single-column={hasSingleColumn || undefined}
|
||||
data-testid={`tanstack-header-${columnId}`}
|
||||
>
|
||||
<span className={headerContentClassName}>
|
||||
{isDragColumn ? (
|
||||
|
||||
@@ -73,6 +73,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');
|
||||
@@ -142,6 +146,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.
|
||||
@@ -152,7 +157,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({
|
||||
@@ -161,7 +168,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');
|
||||
@@ -191,6 +198,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
|
||||
@@ -212,7 +220,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);
|
||||
@@ -224,7 +234,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');
|
||||
|
||||
@@ -6,7 +6,14 @@ import {
|
||||
trialConvertedToSubscriptionResponse,
|
||||
} from 'mocks-server/__mockdata__/licenses';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { act, render, screen, getAppContextMock } from 'tests/test-utils';
|
||||
import {
|
||||
act,
|
||||
render,
|
||||
screen,
|
||||
getAppContextMock,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
import { REAL_TIMER_APIS } from 'tests/realTimerApis';
|
||||
import APIError from 'types/api/error';
|
||||
import {
|
||||
LicensePlatform,
|
||||
@@ -26,8 +33,6 @@ window.ResizeObserver =
|
||||
}));
|
||||
|
||||
describe('BillingContainer', () => {
|
||||
jest.setTimeout(30000);
|
||||
|
||||
beforeEach(() => {
|
||||
server.use(setupAuthzAdmin());
|
||||
});
|
||||
@@ -39,40 +44,32 @@ 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: REAL_TIMER_APIS,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -88,14 +85,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 +99,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 +135,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 +148,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 +252,23 @@ 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 = (productIndex: number, tierIndex: number): string[] =>
|
||||
within(screen.getByTestId(`billing-usage-row-${productIndex}${tierIndex}`))
|
||||
.getAllByRole('cell', { hidden: true })
|
||||
.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(0, 0)).toStrictEqual([
|
||||
'Metrics',
|
||||
'4012 Million',
|
||||
'0.1',
|
||||
'$ 401.2',
|
||||
]);
|
||||
expect(cellTexts(2, 0)).toStrictEqual(['Logs', '497 GB', '0.4', '$ 198.8']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -597,6 +597,11 @@ export default function BillingContainer(): JSX.Element {
|
||||
dataSource={data}
|
||||
pagination={false}
|
||||
bordered={false}
|
||||
onRow={(
|
||||
record,
|
||||
): React.HTMLAttributes<HTMLElement> & { 'data-testid': string } => ({
|
||||
'data-testid': `billing-usage-row-${record.key}`,
|
||||
})}
|
||||
components={{
|
||||
header: {
|
||||
cell: ({
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
rest,
|
||||
server,
|
||||
} from 'mocks-server/server';
|
||||
import { holdResponse } from 'tests/holdResponse';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { OrgSessionContext } from 'types/api/v2/sessions/context/get';
|
||||
|
||||
@@ -64,6 +65,18 @@ const multiOrgProps: ForgotPasswordRouteState = {
|
||||
orgs: mockMultipleOrgs,
|
||||
};
|
||||
|
||||
function mockForgot(held?: Promise<void>): { forgotCalls: () => number } {
|
||||
let calls = 0;
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, async (_req, res, ctx) => {
|
||||
calls += 1;
|
||||
await held;
|
||||
return res(ctx.status(200), ctx.json({ status: 'success' }));
|
||||
}),
|
||||
);
|
||||
return { forgotCalls: (): number => calls };
|
||||
}
|
||||
|
||||
describe('ForgotPassword Component', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
@@ -136,7 +149,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 +157,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 +181,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 +203,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 +222,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 +248,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 +268,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 +283,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 +327,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 +340,10 @@ 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' })),
|
||||
),
|
||||
);
|
||||
const response = holdResponse();
|
||||
mockForgot(response.held);
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
@@ -344,16 +354,14 @@ describe('ForgotPassword Component', () => {
|
||||
await expect(
|
||||
screen.findByText(/sending\.\.\./i),
|
||||
).resolves.toBeInTheDocument();
|
||||
response.release();
|
||||
});
|
||||
|
||||
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' })),
|
||||
),
|
||||
);
|
||||
const response = holdResponse();
|
||||
mockForgot(response.held);
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
@@ -363,6 +371,7 @@ describe('ForgotPassword Component', () => {
|
||||
await waitFor(() => {
|
||||
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
response.release();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -410,23 +419,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 +437,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 +453,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 response = holdResponse();
|
||||
const { forgotCalls } = mockForgot(response.held);
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
@@ -472,8 +467,9 @@ describe('ForgotPassword Component', () => {
|
||||
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
|
||||
await user.keyboard('{enter}');
|
||||
|
||||
response.release();
|
||||
await expect(
|
||||
screen.findByText(/check your email/i, undefined, { timeout: 2000 }),
|
||||
screen.findByText(/check your email/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(forgotCalls()).toBe(1);
|
||||
});
|
||||
|
||||
@@ -617,7 +617,10 @@ function GeneralSettings({
|
||||
) {
|
||||
return (
|
||||
<Fragment key={category.name}>
|
||||
<div className="retention-row">
|
||||
<div
|
||||
className="retention-row"
|
||||
data-testid={`${category.type}-retention-row`}
|
||||
>
|
||||
<span className="retention-row-label">
|
||||
{category.icon}
|
||||
{category.name}
|
||||
@@ -644,6 +647,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 +675,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', {
|
||||
|
||||
@@ -80,8 +80,14 @@ function Retention({
|
||||
}
|
||||
}, [initialTimeUnitValue]);
|
||||
|
||||
const testId = `${type}-${isS3Field ? 's3' : 'total'}-retention`;
|
||||
|
||||
const menuItems = availableUnits.map((option) => (
|
||||
<Option key={option.value} value={option.value}>
|
||||
<Option
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
data-testid={`${testId}-unit-option-${option.value}`}
|
||||
>
|
||||
{option.key}
|
||||
</Option>
|
||||
));
|
||||
@@ -139,11 +145,13 @@ function Retention({
|
||||
disabled={isCloudUserVal}
|
||||
disabledTooltip={undefined}
|
||||
onChange={(e): void => onChangeHandler(e, setSelectedValue)}
|
||||
testId={testId}
|
||||
/>
|
||||
<Select
|
||||
value={selectedTimeUnit}
|
||||
onChange={currentSelectedOption}
|
||||
disabled={isCloudUserVal}
|
||||
data-testid={`${testId}-unit`}
|
||||
>
|
||||
{menuItems}
|
||||
</Select>
|
||||
|
||||
@@ -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, within } from 'tests/test-utils';
|
||||
import { IDiskType } from 'types/api/disks/getDisks';
|
||||
import {
|
||||
PayloadPropsLogs,
|
||||
@@ -93,10 +93,7 @@ const mockDisksWithoutS3: IDiskType[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const getLogsRow = (): HTMLElement => {
|
||||
const logsLabel = screen.getByText('Logs');
|
||||
return logsLabel.closest('.retention-row') as HTMLElement;
|
||||
};
|
||||
const getLogsRow = (): HTMLElement => screen.getByTestId('logs-retention-row');
|
||||
|
||||
describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
beforeEach(() => {
|
||||
@@ -108,7 +105,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}
|
||||
@@ -125,54 +123,56 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
expect(logsRow).toBeInTheDocument();
|
||||
|
||||
// Find all inputs in the Logs row - there should be 2 (total retention + S3)
|
||||
const inputs = logsRow.querySelectorAll('input[type="number"]');
|
||||
expect(inputs).toHaveLength(2);
|
||||
|
||||
// The second input is the S3 retention field
|
||||
const s3Input = inputs[1] as HTMLInputElement;
|
||||
|
||||
// Find the S3 dropdown (next sibling of the S3 input)
|
||||
const s3Dropdown = s3Input
|
||||
?.closest('.retention-row-controls')
|
||||
?.querySelectorAll('.ant-select-selector')[1] as HTMLElement;
|
||||
expect(s3Dropdown).toBeInTheDocument();
|
||||
expect(
|
||||
within(logsRow).getByTestId('logs-total-retention-field'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
within(logsRow).getByTestId('logs-s3-retention-field'),
|
||||
).toBeInTheDocument();
|
||||
|
||||
// Click the S3 dropdown to open it
|
||||
fireEvent.mouseDown(s3Dropdown);
|
||||
await user.click(
|
||||
within(screen.getByTestId('logs-s3-retention-unit')).getByTitle('Days'),
|
||||
);
|
||||
|
||||
// Wait for dropdown options to appear and verify only "Days" is available
|
||||
await waitFor(() => {
|
||||
const dropdownOptions = document.querySelectorAll('.ant-select-item');
|
||||
expect(dropdownOptions).toHaveLength(1);
|
||||
expect(dropdownOptions[0]).toHaveTextContent('Days');
|
||||
});
|
||||
await expect(
|
||||
screen.findByTestId('logs-s3-retention-unit-option-day'),
|
||||
).resolves.toHaveTextContent('Days');
|
||||
expect(
|
||||
screen.queryByTestId('logs-s3-retention-unit-option-hr'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('logs-s3-retention-unit-option-month'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
// 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 = screen.getByTestId('logs-s3-retention-field');
|
||||
|
||||
// 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(() => {
|
||||
@@ -201,13 +201,18 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
|
||||
// Verify S3 field is visible
|
||||
const logsRow = getLogsRow();
|
||||
const inputs = logsRow.querySelectorAll('input[type="number"]');
|
||||
expect(inputs).toHaveLength(2); // Total + S3
|
||||
expect(
|
||||
within(logsRow).getByTestId('logs-total-retention-field'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
within(logsRow).getByTestId('logs-s3-retention-field'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
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}
|
||||
@@ -224,55 +229,35 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
expect(logsRow).toBeInTheDocument();
|
||||
|
||||
// Only 1 input should be visible (total retention, no S3)
|
||||
const inputs = logsRow.querySelectorAll('input[type="number"]');
|
||||
expect(inputs).toHaveLength(1);
|
||||
expect(
|
||||
within(logsRow).queryByTestId('logs-s3-retention-field'),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
// Change total retention value
|
||||
const totalInput = inputs[0] as HTMLInputElement;
|
||||
const totalInput = within(logsRow).getByTestId('logs-total-retention-field');
|
||||
|
||||
// First, change the dropdown to Days (it defaults to Months)
|
||||
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(
|
||||
within(screen.getByTestId('logs-total-retention-unit')).getByTitle(
|
||||
'Months',
|
||||
),
|
||||
);
|
||||
|
||||
// Find and click the Days option
|
||||
const options = document.querySelectorAll('.ant-select-item');
|
||||
const daysOption = Array.from(options).find((opt) =>
|
||||
opt.textContent?.includes('Days'),
|
||||
await user.click(
|
||||
await screen.findByTestId('logs-total-retention-unit-option-day'),
|
||||
);
|
||||
expect(daysOption).toBeInTheDocument();
|
||||
fireEvent.click(daysOption as HTMLElement);
|
||||
|
||||
// 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(() => {
|
||||
@@ -301,26 +286,25 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const logsRow = getLogsRow();
|
||||
const inputs = logsRow.querySelectorAll('input[type="number"]');
|
||||
|
||||
// Total retention: 30 days = 1 month (displays as 1 Month)
|
||||
const totalInput = inputs[0] as HTMLInputElement;
|
||||
expect(totalInput.value).toBe('1');
|
||||
expect(screen.getByTestId('logs-total-retention-field')).toHaveValue(1);
|
||||
|
||||
// S3 retention: 24 days
|
||||
const s3Input = inputs[1] as HTMLInputElement;
|
||||
expect(s3Input.value).toBe('24');
|
||||
expect(screen.getByTestId('logs-s3-retention-field')).toHaveValue(24);
|
||||
|
||||
// Verify dropdowns: total shows Months, S3 shows Days
|
||||
const dropdowns = logsRow.querySelectorAll('.ant-select-selection-item');
|
||||
expect(dropdowns[0]).toHaveTextContent('Months');
|
||||
expect(dropdowns[1]).toHaveTextContent('Days');
|
||||
expect(screen.getByTestId('logs-total-retention-unit')).toHaveTextContent(
|
||||
'Months',
|
||||
);
|
||||
expect(screen.getByTestId('logs-s3-retention-unit')).toHaveTextContent(
|
||||
'Days',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
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,35 +320,28 @@ 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');
|
||||
|
||||
// Find the total retention input
|
||||
const inputs = logsRow.querySelectorAll('input[type="number"]');
|
||||
const totalInput = inputs[0] as HTMLInputElement;
|
||||
const totalInput = within(logsRow).getByTestId('logs-total-retention-field');
|
||||
|
||||
// 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 +398,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');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -23,6 +23,7 @@ import { openInNewTab } from 'utils/navigation';
|
||||
|
||||
import { TableColumnDef } from 'components/TanStackTableView';
|
||||
|
||||
import { ExpandButtonWrapper } from '../../components/ExpandButtonWrapper';
|
||||
import { InfraMonitoringEntity } from '../../constants';
|
||||
import { SelectedItemParams } from '../../hooks';
|
||||
|
||||
@@ -128,6 +129,24 @@ function createTestColumns(): TableColumnDef<TestItem>[] {
|
||||
];
|
||||
}
|
||||
|
||||
function createTestColumnsWithExpand(): TableColumnDef<TestItem>[] {
|
||||
return [
|
||||
{
|
||||
id: 'group',
|
||||
header: (): React.ReactNode => 'Group',
|
||||
accessorFn: (row): string => row.id,
|
||||
visibilityBehavior: 'hidden-on-collapse',
|
||||
cell: ({ isExpanded, toggleExpanded }): React.ReactNode => (
|
||||
<ExpandButtonWrapper
|
||||
isExpanded={isExpanded}
|
||||
toggleExpanded={toggleExpanded}
|
||||
/>
|
||||
),
|
||||
},
|
||||
...createTestColumns(),
|
||||
];
|
||||
}
|
||||
|
||||
function createTestColumnsWithName(): TableColumnDef<TestItemWithName>[] {
|
||||
return [
|
||||
{
|
||||
@@ -426,15 +445,7 @@ describe('K8sBaseList', () => {
|
||||
expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Find pagination navigation and page 2 button
|
||||
const nav = screen.getByRole('navigation');
|
||||
const page2Button = Array.from(nav.querySelectorAll('button')).find(
|
||||
(btn) => btn.textContent?.trim() === '2',
|
||||
);
|
||||
if (!page2Button) {
|
||||
throw new Error('Page 2 button not found in pagination');
|
||||
}
|
||||
await user.click(page2Button);
|
||||
await user.click(screen.getByTestId('pagination-page-2'));
|
||||
|
||||
await waitFor(() => {
|
||||
const lastPage = onUrlUpdateMock.mock.calls
|
||||
@@ -447,13 +458,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);
|
||||
@@ -464,13 +478,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);
|
||||
@@ -511,7 +528,7 @@ describe('K8sBaseList', () => {
|
||||
groupBy: JSON.stringify(groupByValue),
|
||||
page: '3',
|
||||
},
|
||||
tableColumns: createTestColumns(),
|
||||
tableColumns: createTestColumnsWithExpand(),
|
||||
getRowKey: (row): string => row.id,
|
||||
getItemKey: (row): string => row.id,
|
||||
});
|
||||
@@ -533,12 +550,9 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
it('should render expand icons when groupBy is set', async () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('namespace-default')).toBeInTheDocument();
|
||||
});
|
||||
const row = await screen.findByTestId('row-namespace-default');
|
||||
|
||||
const expandButtons = screen.getAllByRole('button');
|
||||
expect(expandButtons.length).toBeGreaterThan(0);
|
||||
expect(within(row).getByTestId('expand-row-button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render data with groupBy params', async () => {
|
||||
@@ -585,7 +599,7 @@ describe('K8sBaseList', () => {
|
||||
groupBy: JSON.stringify(groupByValue),
|
||||
page: '3',
|
||||
},
|
||||
tableColumns: createTestColumns(),
|
||||
tableColumns: createTestColumnsWithExpand(),
|
||||
getRowKey: (row): string => row.id,
|
||||
getItemKey: (row): string => row.id,
|
||||
});
|
||||
@@ -601,12 +615,9 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
it('should render expand icons when groupBy is set with new format', async () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('namespace-default')).toBeInTheDocument();
|
||||
});
|
||||
const row = await screen.findByTestId('row-namespace-default');
|
||||
|
||||
const expandButtons = screen.getAllByRole('button');
|
||||
expect(expandButtons.length).toBeGreaterThan(0);
|
||||
expect(within(row).getByTestId('expand-row-button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render data with new groupBy format', async () => {
|
||||
@@ -941,12 +952,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.getByTestId('tanstack-header-id')).toHaveTextContent('Id');
|
||||
expect(screen.getByTestId('tanstack-header-name')).toHaveTextContent('Name');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -989,9 +996,7 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// Columns should be visible
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /id/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTestId('tanstack-header-id')).toHaveTextContent('Id');
|
||||
});
|
||||
|
||||
it('should show columns when grouped', async () => {
|
||||
@@ -1015,9 +1020,7 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// Id should be visible
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /id/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTestId('tanstack-header-id')).toHaveTextContent('Id');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1097,12 +1100,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.getByTestId('tanstack-header-id')).toHaveTextContent('Id');
|
||||
expect(screen.getByTestId('tanstack-header-name')).toHaveTextContent('Name');
|
||||
});
|
||||
|
||||
it('should render data in cells correctly', async () => {
|
||||
@@ -1212,6 +1211,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,
|
||||
@@ -1226,7 +1226,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);
|
||||
@@ -1238,6 +1240,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,
|
||||
@@ -1252,7 +1255,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);
|
||||
@@ -1614,11 +1619,11 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// Open group by dropdown using testId
|
||||
const groupByContainer = screen.getByTestId('k8s-table-group-by-select');
|
||||
const groupBySelect = groupByContainer.querySelector(
|
||||
'.ant-select-selector',
|
||||
) as Element;
|
||||
await user.click(groupBySelect);
|
||||
await user.click(
|
||||
within(screen.getByTestId('k8s-table-group-by-select')).getByText(
|
||||
'Search for attribute',
|
||||
),
|
||||
);
|
||||
|
||||
// Wait for options to load and click on the namespace option
|
||||
const namespaceOption = await screen.findByTitle('k8s.namespace.name');
|
||||
@@ -1656,11 +1661,11 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// Open group by dropdown using testId
|
||||
const groupByContainer = screen.getByTestId('k8s-table-group-by-select');
|
||||
const groupBySelect = groupByContainer.querySelector(
|
||||
'.ant-select-selector',
|
||||
) as Element;
|
||||
await user.click(groupBySelect);
|
||||
await user.click(
|
||||
within(screen.getByTestId('k8s-table-group-by-select')).getByText(
|
||||
'Search for attribute',
|
||||
),
|
||||
);
|
||||
|
||||
// Wait for options to load and click on the namespace option
|
||||
const namespaceOption = await screen.findByTitle('k8s.namespace.name');
|
||||
|
||||
@@ -31,7 +31,11 @@ import { useEntityDetailsTime } from '../EntityDateTimeSelector/useEntityDetails
|
||||
import EntityEmptyState from '../EntityEmptyState/EntityEmptyState';
|
||||
import EntityError from '../EntityError/EntityError';
|
||||
import { isKeyNotFoundError, selectedEntityTracesColumns } from '../utils';
|
||||
import { K8S_ENTITY_TRACES_EXPRESSION_KEY, useEntityTraces } from './hooks';
|
||||
import {
|
||||
K8S_ENTITY_TRACES_EXPRESSION_KEY,
|
||||
TraceRow,
|
||||
useEntityTraces,
|
||||
} from './hooks';
|
||||
import { getTraceListColumns } from './traceListColumns';
|
||||
import { getEntityTracesQueryPayload } from './utils';
|
||||
|
||||
@@ -180,7 +184,7 @@ function EntityTracesContent({
|
||||
{isError && !isKeyNotFound && !isLoading && <EntityError />}
|
||||
|
||||
{(!isError || isKeyNotFound) && traces.length > 0 && (
|
||||
<div className={styles.entityTracesTable}>
|
||||
<div className={styles.entityTracesTable} data-testid="entity-traces-table">
|
||||
<div className={styles.controls}>
|
||||
<Controls
|
||||
totalCount={hasMore ? currentCount + 1 : currentCount}
|
||||
@@ -216,7 +220,8 @@ function EntityTracesContent({
|
||||
loading={isFetching && traces.length === 0}
|
||||
dataSource={traces}
|
||||
columns={traceListColumns}
|
||||
onRow={(): Record<string, unknown> => ({
|
||||
onRow={(record: TraceRow): Record<string, unknown> => ({
|
||||
'data-testid': `entity-traces-row-${String(record.data.span_id)}`,
|
||||
onClick: (): void => handleRowClick(),
|
||||
})}
|
||||
/>
|
||||
|
||||
@@ -31,26 +31,21 @@ describe('EntityTraces - Table Rendering', () => {
|
||||
it('should render table with all column headers', async () => {
|
||||
mockQueryRangeV5WithTracesResponse({ pageSize: 3 });
|
||||
|
||||
act(() => {
|
||||
renderEntityTraces();
|
||||
renderEntityTraces();
|
||||
|
||||
await screen.findAllByTestId('serviceName');
|
||||
const table = screen.getByTestId('entity-traces-table');
|
||||
|
||||
[
|
||||
'Timestamp',
|
||||
'Service Name',
|
||||
'Name',
|
||||
'Duration',
|
||||
'HTTP Method',
|
||||
'Status Code',
|
||||
].forEach((header) => {
|
||||
expect(within(table).getByText(header)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
await expect(screen.findByText('Service Name')).resolves.toBeInTheDocument();
|
||||
|
||||
const headerTexts = within(screen.getByRole('table'))
|
||||
.getAllByRole('columnheader')
|
||||
.map((header) => header.textContent);
|
||||
|
||||
expect(headerTexts).toStrictEqual(
|
||||
expect.arrayContaining([
|
||||
'Timestamp',
|
||||
'Service Name',
|
||||
'Name',
|
||||
'Duration',
|
||||
'HTTP Method',
|
||||
'Status Code',
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('should render trace values in table cells', async () => {
|
||||
@@ -152,13 +147,13 @@ describe('EntityTraces - Table Rendering', () => {
|
||||
customTraces: [{ serviceName: 'frontend' }],
|
||||
});
|
||||
|
||||
act(() => {
|
||||
renderEntityTraces();
|
||||
});
|
||||
renderEntityTraces();
|
||||
|
||||
await expect(screen.findByTestId('serviceName')).resolves.toBeInTheDocument();
|
||||
|
||||
const links = within(screen.getByRole('table')).getAllByRole('link');
|
||||
const links = within(
|
||||
screen.getByTestId('entity-traces-row-span-id-0'),
|
||||
).getAllByTestId('trace-block-link');
|
||||
|
||||
expect(links.length).toBeGreaterThan(0);
|
||||
links.forEach((link) => {
|
||||
@@ -198,8 +193,7 @@ describe('EntityTraces - Table Rendering', () => {
|
||||
renderEntityTraces();
|
||||
|
||||
const user = userEvent.setup();
|
||||
const cell = await screen.findByTestId('serviceName');
|
||||
await user.click(cell.closest('tr') as HTMLElement);
|
||||
await user.click(await screen.findByTestId('entity-traces-row-span-id-0'));
|
||||
|
||||
expect(logEvent).toHaveBeenCalledWith(
|
||||
'Infra Monitoring: Drawer trace clicked',
|
||||
|
||||
@@ -83,6 +83,7 @@ import { MeterAggregateOperator } from 'types/common/queryBuilder';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
import { getDaysUntilExpiry } from 'utils/timeUtils';
|
||||
|
||||
import 'components/LearnMore/LearnMore.styles.scss';
|
||||
import './IngestionSettings.styles.scss';
|
||||
|
||||
const { Option } = Select;
|
||||
@@ -1184,6 +1185,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
icon
|
||||
color="secondary"
|
||||
aria-label={`Edit ${signalName} limit`}
|
||||
testId={`edit-limit-btn-${signalName}`}
|
||||
disabled={
|
||||
!!(activeAPIKey?.id === APIKey?.id && activeSignal)
|
||||
}
|
||||
@@ -1710,6 +1712,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,
|
||||
};
|
||||
|
||||
@@ -237,6 +237,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})`,
|
||||
@@ -267,6 +268,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'));
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { holdResponse } from 'tests/holdResponse';
|
||||
|
||||
import {
|
||||
DEPLOYMENT_PROJECT_ID,
|
||||
@@ -59,7 +60,9 @@ describe('GCP AgentSetup form', () => {
|
||||
expect(
|
||||
screen.queryByTestId('gcp-account-name-input'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(document.querySelector('#gcp-project-ids-select')).toBeNull();
|
||||
expect(
|
||||
screen.queryByTestId('gcp-project-ids-select'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('gcp-setup-guide-callout')).toHaveTextContent(
|
||||
'SigNoz integration sets up everything needed',
|
||||
);
|
||||
@@ -161,10 +164,12 @@ describe('GCP AgentSetup form', () => {
|
||||
});
|
||||
|
||||
it('locks the connection method and keeps the submitted project while the command is generating', async () => {
|
||||
const create = holdResponse();
|
||||
server.use(
|
||||
rest.post(GCP_ACCOUNTS_URL, (_req, res, ctx) =>
|
||||
res(ctx.delay(300), ctx.status(201), ctx.json(createAgentAccountResponse)),
|
||||
),
|
||||
rest.post(GCP_ACCOUNTS_URL, async (_req, res, ctx) => {
|
||||
await create.held;
|
||||
return res(ctx.status(201), ctx.json(createAgentAccountResponse));
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderAgentSetup();
|
||||
@@ -173,16 +178,18 @@ describe('GCP AgentSetup form', () => {
|
||||
await user.click(screen.getByTestId('gcp-generate-command-btn'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('radiogroup')).toHaveAttribute(
|
||||
expect(screen.getByTestId('gcp-connection-method')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
|
||||
await user.type(
|
||||
screen.getByTestId('gcp-deployment-project-id-input-field'),
|
||||
'-edited',
|
||||
const projectInput = screen.getByTestId(
|
||||
'gcp-deployment-project-id-input-field',
|
||||
);
|
||||
await user.type(projectInput, '-edited');
|
||||
expect(projectInput).toHaveValue(`${DEPLOYMENT_PROJECT_ID}-edited`);
|
||||
create.release();
|
||||
|
||||
const commands = await screen.findByTestId('gcp-agent-command');
|
||||
expect(commands).toHaveTextContent(`signed in to ${DEPLOYMENT_PROJECT_ID}.`);
|
||||
|
||||
@@ -53,12 +53,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-field'),
|
||||
DEPLOYMENT_PROJECT_ID,
|
||||
);
|
||||
await user.click(screen.getByTestId('gcp-deployment-project-id-input-field'));
|
||||
await user.paste(DEPLOYMENT_PROJECT_ID);
|
||||
await selectRegion(user, 'Mumbai');
|
||||
};
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ function ConnectionMethodSelector({
|
||||
<RadioGroup
|
||||
color="primary"
|
||||
textOverflow="wrap"
|
||||
testId="gcp-connection-method"
|
||||
value={value}
|
||||
onChange={(next): void =>
|
||||
onChange(next as CloudintegrationtypesGCPConnectionMethodDTO)
|
||||
|
||||
@@ -30,10 +30,6 @@ jest.mock('@signozhq/ui/toast', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('@floating-ui/dom', () =>
|
||||
jest.requireActual('./floatingUiDomMock').floatingUiDomMock(),
|
||||
);
|
||||
|
||||
type AccountSettingsDrawerProps = ComponentProps<typeof AccountSettingsDrawer>;
|
||||
|
||||
const onClose = jest.fn() as jest.MockedFunction<
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { RestRequest } from 'msw';
|
||||
import { holdResponse } from 'tests/holdResponse';
|
||||
|
||||
import CloudAccountSetupDrawer from '../AddNewAccount/CloudAccountSetupDrawer';
|
||||
import {
|
||||
@@ -112,11 +113,12 @@ 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.
|
||||
const checkIn = holdResponse();
|
||||
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 checkIn.held;
|
||||
return res(ctx.status(200), ctx.json(checkInResponse));
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
@@ -145,7 +147,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',
|
||||
);
|
||||
@@ -175,11 +177,14 @@ describe('GCP CloudAccountSetupDrawer', () => {
|
||||
data: {},
|
||||
});
|
||||
});
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
|
||||
checkIn.release();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
}, 15000);
|
||||
});
|
||||
|
||||
it('shows the backend error inline when account creation fails', async () => {
|
||||
server.use(
|
||||
@@ -221,5 +226,5 @@ describe('GCP CloudAccountSetupDrawer', () => {
|
||||
});
|
||||
expect(checkInPayload).toBeNull();
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
}, 15000);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
/** Opens the project IDs input and adds each ID the way a user does: type, then Enter. */
|
||||
/** Opens the project IDs input and adds each ID the way a user does: paste, then Enter. */
|
||||
export const addProjectIds = async (
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
testId: string,
|
||||
projectIds: string[],
|
||||
): Promise<void> => {
|
||||
await user.click(screen.getByTestId(testId));
|
||||
const input = await screen.findByPlaceholderText(
|
||||
'Type a project ID and press Enter',
|
||||
);
|
||||
await user.click(await screen.findByTestId(`${testId}-search`));
|
||||
for (const projectId of projectIds) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await user.type(input, `${projectId}{Enter}`);
|
||||
await user.paste(projectId);
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await user.keyboard('{Enter}');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
/** Types the label into the search and presses Enter: jsdom drops a click on a Combobox row. */
|
||||
/** Pastes the label into the search and presses Enter: jsdom drops a click on a Combobox row. */
|
||||
export const selectRegion = async (
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
label: string,
|
||||
): Promise<void> => {
|
||||
await user.click(screen.getByTestId('gcp-deployment-region-select'));
|
||||
await user.type(
|
||||
await user.click(
|
||||
await screen.findByTestId('gcp-deployment-region-select-search'),
|
||||
`${label}{Enter}`,
|
||||
);
|
||||
await user.paste(label);
|
||||
await user.keyboard('{Enter}');
|
||||
};
|
||||
|
||||
@@ -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>
|
||||
) : (
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
// (synchronous) so the functional tests stay synchronous; the read-only block
|
||||
// below flips it to deny-all.
|
||||
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
|
||||
const mockedUseAuthZ = useAuthZ as jest.MockedFunction<typeof useAuthZ>;
|
||||
const mockedUseAuthZ = jest.mocked(useAuthZ);
|
||||
|
||||
import {
|
||||
GROUPS_ENDPOINT,
|
||||
@@ -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,8 +191,8 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('invokes onAddGroup from the toolbar button', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onAddGroup = jest.fn();
|
||||
const user = userEvent.setup();
|
||||
const onAddGroup = jest.fn() as jest.MockedFunction<() => void>;
|
||||
setupGroups();
|
||||
render(<AttributeMappingsTabWithStore onAddGroup={onAddGroup} />);
|
||||
|
||||
@@ -201,14 +203,18 @@ 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 onEditGroup = jest.fn();
|
||||
const user = userEvent.setup();
|
||||
const onEditGroup = jest.fn() as jest.MockedFunction<
|
||||
(group: DraftGroup) => void
|
||||
>;
|
||||
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 +224,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 +241,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 />);
|
||||
@@ -241,13 +249,15 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
await screen.findByTestId('group-name-group-1');
|
||||
// The clickable Collapse header owns the expanded state; find it by the
|
||||
// aria-expanded contract rather than any framework-internal class.
|
||||
const header = screen
|
||||
.getByTestId('group-expand-group-1')
|
||||
.closest('[aria-expanded]') as HTMLElement;
|
||||
expect(header).toHaveAttribute('aria-expanded', 'false');
|
||||
const table = within(screen.getByTestId('mappings-table'));
|
||||
expect(
|
||||
table.queryByRole('button', { hidden: true, expanded: true }),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
await expandGroup(user);
|
||||
expect(header).toHaveAttribute('aria-expanded', 'true');
|
||||
expect(
|
||||
table.getByRole('button', { hidden: true, expanded: true }),
|
||||
).toContainElement(screen.getByTestId('group-expand-group-1'));
|
||||
await expect(
|
||||
screen.findByTestId('mapper-target-mapper-1'),
|
||||
).resolves.toBeInTheDocument();
|
||||
@@ -261,7 +271,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 }),
|
||||
@@ -278,7 +288,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
|
||||
const target = await screen.findByTestId('mapper-target-mapper-1');
|
||||
expect(target).toHaveTextContent('gen_ai.request.model');
|
||||
const mapperRow = target.closest('tr') as HTMLElement;
|
||||
const mapperRow = screen.getByTestId('mapper-row-mapper-1');
|
||||
// Sources ordered by priority, highest first (see fixtures).
|
||||
const sources = within(mapperRow).getByTestId('mapper-sources-mapper-1');
|
||||
expect(sources).toHaveTextContent('genai.model');
|
||||
@@ -290,7 +300,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 +318,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 +332,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 +357,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 +371,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,9 +404,9 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('warns and keeps the working copy when the post-save refresh fails', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
(toast.success as jest.Mock).mockClear();
|
||||
(toast.warning as jest.Mock).mockClear();
|
||||
const user = userEvent.setup();
|
||||
jest.mocked(toast.success).mockClear();
|
||||
jest.mocked(toast.warning).mockClear();
|
||||
|
||||
let failRefresh = false;
|
||||
server.use(
|
||||
@@ -438,7 +448,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 +461,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 +479,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 +493,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 +510,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,14 +521,10 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
'true',
|
||||
);
|
||||
|
||||
await user.type(
|
||||
screen.getByTestId('mapper-form-target-field'),
|
||||
'gen_ai.response.model',
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId('mapper-form-source-0-field'),
|
||||
'raw.model',
|
||||
);
|
||||
await user.click(screen.getByTestId('mapper-form-target-field'));
|
||||
await user.paste('gen_ai.response.model');
|
||||
await user.click(screen.getByTestId('mapper-form-source-0-field'));
|
||||
await user.paste('raw.model');
|
||||
|
||||
const create = screen.getByTestId('mapper-form-save');
|
||||
await waitFor(() =>
|
||||
@@ -561,7 +571,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 />);
|
||||
@@ -577,7 +587,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);
|
||||
|
||||
@@ -75,7 +75,7 @@ describe('AI observability Explorer', () => {
|
||||
});
|
||||
|
||||
it('clears the url columns of the panel being left', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const traceColumns = [{ name: 'span_count' }];
|
||||
localStorage.setItem(
|
||||
LOCALSTORAGE.AI_OBSERVABILITY_PANEL_COLUMNS,
|
||||
@@ -104,5 +104,5 @@ describe('AI observability Explorer', () => {
|
||||
...defaultOptionsQuery,
|
||||
selectColumns: [],
|
||||
});
|
||||
}, 15_000);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -59,29 +59,6 @@ export function AlertsEmptyState({
|
||||
return (
|
||||
<div className={styles.alertListContainer}>
|
||||
<div className={styles.alertListViewContent}>
|
||||
<div>
|
||||
<Typography
|
||||
variant="label"
|
||||
size="large"
|
||||
weight="regular"
|
||||
color="main"
|
||||
as="h1"
|
||||
marginY={4}
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Alert Rules
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Create and manage alert rules for your resources.
|
||||
</Typography>
|
||||
</div>
|
||||
<section className={styles.emptyAlertInfoContainer}>
|
||||
<div className={styles.alertContent}>
|
||||
<section className={styles.heading}>
|
||||
|
||||
@@ -15,18 +15,6 @@
|
||||
background: var(--l1-background);
|
||||
}
|
||||
|
||||
.headerZone {
|
||||
position: relative;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
gap: 14px;
|
||||
padding: 20px 24px;
|
||||
background: var(--l2-background);
|
||||
border-bottom: 1px solid var(--l2-border);
|
||||
}
|
||||
|
||||
.tableContainer {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@@ -1,65 +1,66 @@
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { logEventMock } from '__tests__/logEventMock';
|
||||
import { safeNavigateMock } from '__tests__/safeNavigateMock';
|
||||
import { ActionsMenu } from 'container/ListAlertRules/components';
|
||||
import type { AlertRule } from 'container/ListAlertRules/types';
|
||||
import { useAlertRulesHandlers } from 'container/ListAlertRules/useAlertRulesHandlers';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { alertRulesFixture } from 'mocks-server/__mockdata__/alert_rules';
|
||||
import { rest } from 'msw';
|
||||
import { screen, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { findAlertRow, renderListAlertRules } from './_helpers';
|
||||
const [HIGH_CPU_RULE, , , DISABLED_RULE] = alertRulesFixture.map(
|
||||
(rule): AlertRule => ({ ...rule, thresholds: [] }),
|
||||
);
|
||||
|
||||
async function openActionsMenu(row: HTMLElement): Promise<void> {
|
||||
const trigger = row.querySelector(
|
||||
'[data-testid="alert-actions"]',
|
||||
) as HTMLElement | null;
|
||||
expect(trigger).not.toBeNull();
|
||||
const user = userEvent.setup({ delay: null });
|
||||
await user.click(trigger as HTMLElement);
|
||||
// Radix renders the menu items in a portal once the trigger is activated.
|
||||
await screen.findByRole('menu');
|
||||
function ActionsMenuWithHandlers({ rule }: { rule: AlertRule }): JSX.Element {
|
||||
const { handleEdit } = useAlertRulesHandlers(alertRulesFixture.length);
|
||||
return <ActionsMenu rule={rule} onEdit={handleEdit} />;
|
||||
}
|
||||
|
||||
async function clickMenuItem(label: string): Promise<void> {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const item = await screen.findByRole('menuitem', { name: label });
|
||||
await user.click(item);
|
||||
async function openActionsMenu(
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
rule: AlertRule = HIGH_CPU_RULE,
|
||||
): Promise<void> {
|
||||
render(<ActionsMenuWithHandlers rule={rule} />);
|
||||
await user.click(screen.getByTestId('alert-actions'));
|
||||
await screen.findByTestId('alert-actions-item-edit');
|
||||
}
|
||||
|
||||
describe('ListAlertRules — actions menu', () => {
|
||||
beforeEach(() => {
|
||||
jest.setSystemTime(new Date('2023-10-20T12:00:00Z'));
|
||||
});
|
||||
|
||||
it('renders Enable/Disable/Edit/Edit in New Tab/Clone/Delete items after opening the menu', async () => {
|
||||
renderListAlertRules();
|
||||
const row = await findAlertRow('High CPU Alert');
|
||||
const user = userEvent.setup();
|
||||
render(<ActionsMenuWithHandlers rule={HIGH_CPU_RULE} />);
|
||||
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('alert-actions-item-edit'),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
await openActionsMenu(row);
|
||||
await user.click(screen.getByTestId('alert-actions'));
|
||||
|
||||
const items = screen.getAllByRole('menuitem');
|
||||
const labels = items.map((it) => it.textContent);
|
||||
expect(labels).toStrictEqual(
|
||||
expect.arrayContaining([
|
||||
'Edit',
|
||||
'Edit in New Tab',
|
||||
'Clone',
|
||||
'Delete',
|
||||
'Disable',
|
||||
]),
|
||||
await expect(
|
||||
screen.findByTestId('alert-actions-item-toggle'),
|
||||
).resolves.toHaveTextContent(/^Disable$/);
|
||||
expect(screen.getByTestId('alert-actions-item-edit')).toHaveTextContent(
|
||||
/^Edit$/,
|
||||
);
|
||||
expect(
|
||||
screen.getByTestId('alert-actions-item-edit-new-tab'),
|
||||
).toHaveTextContent(/^Edit in New Tab$/);
|
||||
expect(screen.getByTestId('alert-actions-item-clone')).toHaveTextContent(
|
||||
/^Clone$/,
|
||||
);
|
||||
expect(screen.getByTestId('alert-actions-item-delete')).toHaveTextContent(
|
||||
/^Delete$/,
|
||||
);
|
||||
});
|
||||
|
||||
it('disabled rule (rule-4) shows "Enable" instead of "Disable"', async () => {
|
||||
renderListAlertRules();
|
||||
const row = await findAlertRow('Disabled Alert');
|
||||
await openActionsMenu(row);
|
||||
const user = userEvent.setup();
|
||||
await openActionsMenu(user, DISABLED_RULE);
|
||||
|
||||
const items = screen.getAllByRole('menuitem');
|
||||
const labels = items.map((it) => it.textContent);
|
||||
expect(labels).toContain('Enable');
|
||||
expect(labels).not.toContain('Disable');
|
||||
expect(screen.getByTestId('alert-actions-item-toggle')).toHaveTextContent(
|
||||
/^Enable$/,
|
||||
);
|
||||
});
|
||||
|
||||
it('toggle action: clicking Disable sends PATCH with disabled:true', async () => {
|
||||
@@ -73,10 +74,9 @@ describe('ListAlertRules — actions menu', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
renderListAlertRules();
|
||||
const row = await findAlertRow('High CPU Alert');
|
||||
await openActionsMenu(row);
|
||||
await clickMenuItem('Disable');
|
||||
const user = userEvent.setup();
|
||||
await openActionsMenu(user);
|
||||
await user.click(screen.getByTestId('alert-actions-item-toggle'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(capturedBody).toStrictEqual(
|
||||
@@ -92,10 +92,9 @@ describe('ListAlertRules — actions menu', () => {
|
||||
});
|
||||
|
||||
it('edit action: clicking Edit navigates via safeNavigate and logs event', async () => {
|
||||
renderListAlertRules();
|
||||
const row = await findAlertRow('High CPU Alert');
|
||||
await openActionsMenu(row);
|
||||
await clickMenuItem('Edit');
|
||||
const user = userEvent.setup();
|
||||
await openActionsMenu(user);
|
||||
await user.click(screen.getByTestId('alert-actions-item-edit'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(safeNavigateMock).toHaveBeenCalled();
|
||||
@@ -109,10 +108,9 @@ describe('ListAlertRules — actions menu', () => {
|
||||
});
|
||||
|
||||
it('edit in new tab action: clicking opens with newTab:true', async () => {
|
||||
renderListAlertRules();
|
||||
const row = await findAlertRow('High CPU Alert');
|
||||
await openActionsMenu(row);
|
||||
await clickMenuItem('Edit in New Tab');
|
||||
const user = userEvent.setup();
|
||||
await openActionsMenu(user);
|
||||
await user.click(screen.getByTestId('alert-actions-item-edit-new-tab'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(safeNavigateMock).toHaveBeenCalled();
|
||||
@@ -133,7 +131,7 @@ describe('ListAlertRules — actions menu', () => {
|
||||
ctx.status(201),
|
||||
ctx.json({
|
||||
data: {
|
||||
...alertRulesFixture[0],
|
||||
...HIGH_CPU_RULE,
|
||||
id: 'cloned-from-server',
|
||||
alert: 'High CPU Alert - Copy',
|
||||
},
|
||||
@@ -144,10 +142,9 @@ describe('ListAlertRules — actions menu', () => {
|
||||
),
|
||||
);
|
||||
|
||||
renderListAlertRules();
|
||||
const row = await findAlertRow('High CPU Alert');
|
||||
await openActionsMenu(row);
|
||||
await clickMenuItem('Clone');
|
||||
const user = userEvent.setup();
|
||||
await openActionsMenu(user);
|
||||
await user.click(screen.getByTestId('alert-actions-item-clone'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(capturedRuleId).toBe('rule-1');
|
||||
@@ -177,10 +174,9 @@ describe('ListAlertRules — actions menu', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
renderListAlertRules();
|
||||
const row = await findAlertRow('High CPU Alert');
|
||||
await openActionsMenu(row);
|
||||
await clickMenuItem('Delete');
|
||||
const user = userEvent.setup();
|
||||
await openActionsMenu(user);
|
||||
await user.click(screen.getByTestId('alert-actions-item-delete'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(deletedId).toBe('rule-1');
|
||||
@@ -201,10 +197,9 @@ describe('ListAlertRules — actions menu', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
renderListAlertRules();
|
||||
const row = await findAlertRow('High CPU Alert');
|
||||
await openActionsMenu(row);
|
||||
await clickMenuItem('Disable');
|
||||
const user = userEvent.setup();
|
||||
await openActionsMenu(user);
|
||||
await user.click(screen.getByTestId('alert-actions-item-toggle'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(patchAttempted).toBe(true);
|
||||
|
||||
@@ -35,6 +35,10 @@ describe('ListAlertRules — empty states', () => {
|
||||
expect(
|
||||
screen.getByText('Create an Alert Rule to get started'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTestId('alert-rules-list-search')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('list-alerts-new-alert-button'),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
// New Alert Rule button is visible and triggers safeNavigate to ALERTS_NEW.
|
||||
await user.click(screen.getByTestId('add-alert'));
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { screen, waitFor } from 'tests/test-utils';
|
||||
import {
|
||||
alertRulesFixture,
|
||||
listRulesV3Response,
|
||||
} from 'mocks-server/__mockdata__/alert_rules';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { screen } from 'tests/test-utils';
|
||||
|
||||
import { renderListAlertRules } from './_helpers';
|
||||
|
||||
@@ -7,6 +13,25 @@ describe('ListAlertRules — list rendering', () => {
|
||||
jest.setSystemTime(new Date('2023-10-20T12:00:00Z'));
|
||||
});
|
||||
|
||||
it('asks for rules sorted by status, firing first, by default', async () => {
|
||||
const requests: URLSearchParams[] = [];
|
||||
server.use(
|
||||
rest.get('http://localhost/api/v3/rules', (req, res, ctx) => {
|
||||
requests.push(req.url.searchParams);
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json(listRulesV3Response(alertRulesFixture, req.url.searchParams)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
expect(requests[0].get('sort')).toBe('state');
|
||||
expect(requests[0].get('order')).toBe('desc');
|
||||
});
|
||||
|
||||
it('renders alert rules from API', async () => {
|
||||
renderListAlertRules();
|
||||
|
||||
@@ -27,9 +52,7 @@ describe('ListAlertRules — list rendering', () => {
|
||||
it('renders state badges via STATE_CONFIG mapping', async () => {
|
||||
renderListAlertRules();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('alert-row-rule-1-state')).toBeInTheDocument(),
|
||||
);
|
||||
await screen.findByTestId('alert-row-rule-1-state');
|
||||
|
||||
expect(screen.getByTestId('alert-row-rule-1-state')).toHaveTextContent(
|
||||
'Firing',
|
||||
@@ -47,9 +70,7 @@ describe('ListAlertRules — list rendering', () => {
|
||||
it('renders state badges with semantic colors', async () => {
|
||||
renderListAlertRules();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('alert-row-rule-1-state')).toBeInTheDocument(),
|
||||
);
|
||||
await screen.findByTestId('alert-row-rule-1-state');
|
||||
|
||||
expect(screen.getByTestId('alert-row-rule-1-state')).toHaveAttribute(
|
||||
'data-color',
|
||||
@@ -101,9 +122,7 @@ describe('ListAlertRules — list rendering', () => {
|
||||
it('renders header controls (search, states, columns, new alert)', async () => {
|
||||
renderListAlertRules();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('alert-row-rule-1-name')).toBeInTheDocument(),
|
||||
);
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
expect(screen.getByTestId('alert-rules-list-search')).toBeInTheDocument();
|
||||
expect(
|
||||
@@ -111,11 +130,8 @@ describe('ListAlertRules — list rendering', () => {
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTestId('alert-rules-filter-states')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('alert-columns-button')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByTestId('list-alerts-new-alert-button'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('button', { name: /new alert/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTestId('list-alerts-new-alert-button')).toHaveTextContent(
|
||||
'New Alert',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,27 +1,29 @@
|
||||
import { logEventMock } from '__tests__/logEventMock';
|
||||
import { safeNavigateMock } from '__tests__/safeNavigateMock';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { screen, waitFor } from 'tests/test-utils';
|
||||
import AlertRulesHeaderActions from 'container/ListAlertRules/components/AlertRulesHeaderActions';
|
||||
import { useAlertRulesHandlers } from 'container/ListAlertRules/useAlertRulesHandlers';
|
||||
import { alertRulesFixture } from 'mocks-server/__mockdata__/alert_rules';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import { renderListAlertRules } from './_helpers';
|
||||
function HeaderActionsWithHandlers(): JSX.Element {
|
||||
const { handleNewAlert } = useAlertRulesHandlers(alertRulesFixture.length);
|
||||
return (
|
||||
<AlertRulesHeaderActions
|
||||
columns={[]}
|
||||
canAddAlert
|
||||
onNewAlert={handleNewAlert}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe('ListAlertRules — new alert button', () => {
|
||||
beforeEach(() => {
|
||||
jest.setSystemTime(new Date('2023-10-20T12:00:00Z'));
|
||||
});
|
||||
|
||||
it('plain click navigates to ALERTS_NEW with newTab:false', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderListAlertRules();
|
||||
const user = userEvent.setup();
|
||||
render(<HeaderActionsWithHandlers />);
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
await user.click(screen.getByTestId('list-alerts-new-alert-button'));
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /new alert/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(safeNavigateMock).toHaveBeenCalled();
|
||||
});
|
||||
expect(safeNavigateMock).toHaveBeenCalledWith(
|
||||
ROUTES.ALERTS_NEW,
|
||||
expect.objectContaining({ newTab: false }),
|
||||
@@ -29,34 +31,28 @@ describe('ListAlertRules — new alert button', () => {
|
||||
});
|
||||
|
||||
it('logs Alert: New alert button clicked', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderListAlertRules();
|
||||
const user = userEvent.setup();
|
||||
render(<HeaderActionsWithHandlers />);
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
await user.click(screen.getByTestId('list-alerts-new-alert-button'));
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /new alert/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(logEventMock).toHaveBeenCalledWith(
|
||||
'Alert: New alert button clicked',
|
||||
expect.objectContaining({ layout: 'new' }),
|
||||
);
|
||||
});
|
||||
expect(logEventMock).toHaveBeenCalledWith(
|
||||
'Alert: New alert button clicked',
|
||||
expect.objectContaining({
|
||||
layout: 'new',
|
||||
number: alertRulesFixture.length,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('ctrl+click on New Alert opens in a new tab (newTab:true)', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
const user = userEvent.setup();
|
||||
render(<HeaderActionsWithHandlers />);
|
||||
|
||||
await user.keyboard('{Control>}');
|
||||
await user.click(screen.getByRole('button', { name: /new alert/i }));
|
||||
await user.click(screen.getByTestId('list-alerts-new-alert-button'));
|
||||
await user.keyboard('{/Control}');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(safeNavigateMock).toHaveBeenCalled();
|
||||
});
|
||||
expect(safeNavigateMock).toHaveBeenCalledWith(
|
||||
ROUTES.ALERTS_NEW,
|
||||
expect.objectContaining({ newTab: true }),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { screen, waitFor } from 'tests/test-utils';
|
||||
import { alertRulesFixture } from 'mocks-server/__mockdata__/alert_rules';
|
||||
import { screen } from 'tests/test-utils';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
|
||||
import { renderListAlertRules } from './_helpers';
|
||||
@@ -11,61 +12,33 @@ describe('ListAlertRules — permissions', () => {
|
||||
it('VIEWER role hides "New Alert" button and "Actions" column', async () => {
|
||||
renderListAlertRules({ role: USER_ROLES.VIEWER });
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('list-alerts-new-alert-button'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /new alert/i }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('New Alert')).not.toBeInTheDocument();
|
||||
|
||||
const headers = Array.from(document.querySelectorAll('th')).map(
|
||||
(h) => h.textContent ?? '',
|
||||
);
|
||||
expect(headers.some((t) => t.includes('Actions'))).toBe(false);
|
||||
expect(
|
||||
screen.queryByTestId('tanstack-header-actions'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('alert-actions')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('ADMIN role shows "New Alert" button and "Actions" column', async () => {
|
||||
renderListAlertRules({ role: USER_ROLES.ADMIN });
|
||||
it.each([USER_ROLES.ADMIN, USER_ROLES.EDITOR])(
|
||||
'%s role shows "New Alert" button and "Actions" column',
|
||||
async (role) => {
|
||||
renderListAlertRules({ role });
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
|
||||
expect(
|
||||
screen.getByTestId('list-alerts-new-alert-button'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('button', { name: /new alert/i }),
|
||||
).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
const headers = Array.from(document.querySelectorAll('th')).map(
|
||||
(h) => h.textContent ?? '',
|
||||
await expect(screen.findAllByTestId('alert-actions')).resolves.toHaveLength(
|
||||
alertRulesFixture.length,
|
||||
);
|
||||
expect(headers.some((t) => t.includes('Actions'))).toBe(true);
|
||||
});
|
||||
expect(screen.getAllByTestId('alert-actions').length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('EDITOR role behaves like ADMIN (New Alert + Actions visible)', async () => {
|
||||
renderListAlertRules({ role: USER_ROLES.EDITOR });
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
|
||||
expect(
|
||||
screen.getByTestId('list-alerts-new-alert-button'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('button', { name: /new alert/i }),
|
||||
).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
const headers = Array.from(document.querySelectorAll('th')).map(
|
||||
(h) => h.textContent ?? '',
|
||||
expect(screen.getByTestId('list-alerts-new-alert-button')).toHaveTextContent(
|
||||
'New Alert',
|
||||
);
|
||||
expect(headers.some((t) => t.includes('Actions'))).toBe(true);
|
||||
});
|
||||
expect(screen.getAllByTestId('alert-actions').length).toBeGreaterThan(0);
|
||||
});
|
||||
expect(screen.getByTestId('tanstack-header-actions')).toHaveTextContent(
|
||||
'Actions',
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { safeNavigateMock } from '__tests__/safeNavigateMock';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { useAlertRuleViewsStore } from 'container/ListAlertRules/useAlertRuleViewsStore';
|
||||
import { screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { renderListAlertRules } from './_helpers';
|
||||
@@ -7,6 +8,7 @@ import { renderListAlertRules } from './_helpers';
|
||||
describe('ListAlertRules — row click navigation', () => {
|
||||
beforeEach(() => {
|
||||
jest.setSystemTime(new Date('2023-10-20T12:00:00Z'));
|
||||
useAlertRuleViewsStore.setState({ recent: [] });
|
||||
});
|
||||
|
||||
it('clicking a row calls safeNavigate to alerts/overview with ruleId', async () => {
|
||||
@@ -29,6 +31,22 @@ describe('ListAlertRules — row click navigation', () => {
|
||||
expect(url).not.toContain('compositeQuery=');
|
||||
});
|
||||
|
||||
it('records an opened rule as recently viewed, most recent first', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
useAlertRuleViewsStore.setState({ recent: ['rule-2', 'rule-1'] });
|
||||
renderListAlertRules();
|
||||
|
||||
const ruleCell = await screen.findByTestId('alert-row-rule-1-name');
|
||||
await user.click(ruleCell.closest('td') as HTMLElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(useAlertRuleViewsStore.getState().recent).toStrictEqual([
|
||||
'rule-1',
|
||||
'rule-2',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it('ctrl+click on a row navigates with newTab option', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderListAlertRules();
|
||||
|
||||
@@ -19,6 +19,16 @@ import {
|
||||
|
||||
const QUERY = "name CONTAINS 'CPU'";
|
||||
|
||||
function getSearchContent(): HTMLElement {
|
||||
const content = screen
|
||||
.getByTestId('alert-rules-list-search')
|
||||
.querySelector<HTMLElement>('.cm-content');
|
||||
if (!content) {
|
||||
throw new Error('Search editor content not found');
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
function lastRequest(requests: URLSearchParams[]): URLSearchParams {
|
||||
return requests[requests.length - 1];
|
||||
}
|
||||
@@ -26,6 +36,10 @@ function lastRequest(requests: URLSearchParams[]): URLSearchParams {
|
||||
describe('ListAlertRules — search', () => {
|
||||
let requests: URLSearchParams[];
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setSystemTime(new Date('2023-10-20T12:00:00Z'));
|
||||
requests = [];
|
||||
@@ -41,10 +55,10 @@ describe('ListAlertRules — search', () => {
|
||||
});
|
||||
|
||||
it('sends the draft query only when Run is clicked', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
setSearchDraft(QUERY);
|
||||
|
||||
@@ -68,19 +82,13 @@ describe('ListAlertRules — search', () => {
|
||||
});
|
||||
|
||||
it('runs the draft on Mod-Enter', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
setSearchDraft(QUERY);
|
||||
const content = screen
|
||||
.getByTestId('alert-rules-list-search')
|
||||
.querySelector<HTMLElement>('.cm-content');
|
||||
if (!content) {
|
||||
throw new Error('Editor content not found');
|
||||
}
|
||||
content.focus();
|
||||
screen.getByTestId('alert-rules-list-search-field').focus();
|
||||
await user.keyboard('{Control>}{Enter}{/Control}');
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -89,10 +97,10 @@ describe('ListAlertRules — search', () => {
|
||||
});
|
||||
|
||||
it('trims the submitted query', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
await runSearchQuery(user, ` ${QUERY} `);
|
||||
|
||||
@@ -107,14 +115,14 @@ describe('ListAlertRules — search', () => {
|
||||
initialRoute: `/?query=${encodeURIComponent(QUERY)}`,
|
||||
});
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
expect(getSearchDraft()).toBe(QUERY);
|
||||
expect(requests[0].get('query')).toBe(QUERY);
|
||||
});
|
||||
|
||||
it('resets page to 1 when a query is run', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules({ initialRoute: '/?page=2' });
|
||||
|
||||
await screen.findByTestId('alert-rules-list-search');
|
||||
@@ -129,29 +137,65 @@ describe('ListAlertRules — search', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('sends the selected states once, as repeated states= params, when the dropdown closes', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
it('runs the draft when the search box loses focus', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
// jsdom reports no focus once it lands on <body>; a focused browser window does.
|
||||
jest.spyOn(document, 'hasFocus').mockReturnValue(true);
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
|
||||
await user.click(getSearchContent());
|
||||
setSearchDraft(QUERY);
|
||||
await user.click(document.body);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(lastRequest(requests).get('query')).toBe(QUERY);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(getCurrentNuqsSearchParams().get('query')).toBe(QUERY);
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the draft unrun when focus leaves the window', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
|
||||
await user.click(getSearchContent());
|
||||
setSearchDraft(QUERY);
|
||||
jest.spyOn(document, 'hasFocus').mockReturnValue(false);
|
||||
await user.click(document.body);
|
||||
|
||||
expect(requests.some((r) => r.has('query'))).toBe(false);
|
||||
expect(
|
||||
screen.getByTestId('alert-rules-list-search-dirty'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('sends the selected states once, as repeated states= params, when the dropdown closes', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
await user.click(
|
||||
within(screen.getByTestId('alert-rules-filter-states')).getByRole(
|
||||
'combobox',
|
||||
within(screen.getByTestId('alert-rules-filter-states')).getByLabelText(
|
||||
'Status',
|
||||
),
|
||||
);
|
||||
const dropdown = await waitFor(() => {
|
||||
const element = document.querySelector<HTMLElement>('.ant-select-dropdown');
|
||||
expect(element).not.toBeNull();
|
||||
return element as HTMLElement;
|
||||
});
|
||||
await user.click(within(dropdown).getByText('Firing'));
|
||||
await user.click(within(dropdown).getByText('Disabled'));
|
||||
await user.click(
|
||||
await screen.findByTestId('alert-rules-filter-states-option-firing'),
|
||||
);
|
||||
await user.click(
|
||||
screen.getByTestId('alert-rules-filter-states-option-disabled'),
|
||||
);
|
||||
|
||||
expect(requests.some((r) => r.has('states'))).toBe(false);
|
||||
expect(getCurrentNuqsSearchParams().has('states')).toBe(false);
|
||||
|
||||
await user.click(document.body);
|
||||
await user.click(screen.getByTestId('alert-rules-search-zone'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(lastRequest(requests).getAll('states')).toStrictEqual([
|
||||
@@ -164,15 +208,15 @@ describe('ListAlertRules — search', () => {
|
||||
await waitFor(() => {
|
||||
expect(getCurrentNuqsSearchParams().get('states')).toBe('firing,disabled');
|
||||
});
|
||||
}, 15_000);
|
||||
});
|
||||
|
||||
it('Clear empties the query and the states', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules({
|
||||
initialRoute: `/?query=${encodeURIComponent(QUERY)}&states=firing`,
|
||||
});
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
expect(lastRequest(requests).get('query')).toBe(QUERY);
|
||||
|
||||
await user.click(screen.getByTestId('alert-rules-filter-clear'));
|
||||
@@ -196,7 +240,7 @@ describe('ListAlertRules — search', () => {
|
||||
it.each(['rule_list_filter_invalid', 'rule_list_invalid'])(
|
||||
'shows the invalid query state with the backend message for %s',
|
||||
async (code) => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
rest.get('http://localhost/api/v3/rules', (req, res, ctx) => {
|
||||
if (req.url.searchParams.has('query')) {
|
||||
@@ -214,7 +258,7 @@ describe('ListAlertRules — search', () => {
|
||||
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
await runSearchQuery(user, "nme = 'x'");
|
||||
|
||||
|
||||
@@ -33,16 +33,16 @@ const makeRule = (overrides: Partial<AlertRule>): AlertRule => ({
|
||||
});
|
||||
|
||||
describe('toListSort', () => {
|
||||
it('returns the default sort when orderBy is null', () => {
|
||||
it('returns the default sort, status first, when orderBy is null', () => {
|
||||
expect(toListSort(null)).toStrictEqual({
|
||||
sort: RuletypesListSortDTO.updated_at,
|
||||
sort: RuletypesListSortDTO.state,
|
||||
order: RuletypesListOrderDTO.desc,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the default sort for an unknown column', () => {
|
||||
expect(toListSort({ columnName: 'labels', order: 'asc' })).toStrictEqual({
|
||||
sort: RuletypesListSortDTO.updated_at,
|
||||
sort: RuletypesListSortDTO.state,
|
||||
order: RuletypesListOrderDTO.desc,
|
||||
});
|
||||
});
|
||||
@@ -71,10 +71,16 @@ describe('toListSort', () => {
|
||||
describe('toOrderBy', () => {
|
||||
it('returns null for the default sort', () => {
|
||||
expect(
|
||||
toOrderBy(RuletypesListSortDTO.updated_at, RuletypesListOrderDTO.desc),
|
||||
toOrderBy(RuletypesListSortDTO.state, RuletypesListOrderDTO.desc),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the previous default, updated_at desc, as an explicit sort', () => {
|
||||
expect(
|
||||
toOrderBy(RuletypesListSortDTO.updated_at, RuletypesListOrderDTO.desc),
|
||||
).toStrictEqual<SortState>({ columnName: 'updatedAt', order: 'desc' });
|
||||
});
|
||||
|
||||
it('returns the column for a non-default sort', () => {
|
||||
expect(
|
||||
toOrderBy(RuletypesListSortDTO.created_at, RuletypesListOrderDTO.asc),
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from 'mocks-server/__mockdata__/alert_rules';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { holdResponse } from 'tests/holdResponse';
|
||||
import { getCurrentNuqsSearchParams } from 'tests/nuqs-helpers';
|
||||
import {
|
||||
getAppContextMock,
|
||||
@@ -18,23 +19,17 @@ import {
|
||||
|
||||
import { renderListAlertRules, runSearchQuery } from './_helpers';
|
||||
|
||||
// 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: {} }),
|
||||
}));
|
||||
|
||||
jest.setTimeout(15_000);
|
||||
|
||||
const VIEW_1_ORDER_BY = JSON.stringify({ columnName: 'name', order: 'asc' });
|
||||
const VIEW_1_QUERY = "thresholds = 'critical'";
|
||||
const VIEW_2_QUERY = "team = 'infra'";
|
||||
|
||||
const VIEW_1_ROUTE = `/?view=view-1&query=${encodeURIComponent(
|
||||
VIEW_1_QUERY,
|
||||
)}&states=firing&orderBy=${encodeURIComponent(VIEW_1_ORDER_BY)}`;
|
||||
const VIEW_1_EDITED_ROUTE = `/?view=view-1&query=foo&states=firing&orderBy=${encodeURIComponent(
|
||||
VIEW_1_ORDER_BY,
|
||||
)}`;
|
||||
const VIEW_2_ROUTE = `/?view=view-2&query=${encodeURIComponent(VIEW_2_QUERY)}`;
|
||||
|
||||
type Body = Record<string, unknown>;
|
||||
type User = ReturnType<typeof userEvent.setup>;
|
||||
@@ -131,17 +126,19 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
beforeEach(() => {
|
||||
jest.setSystemTime(new Date('2023-10-20T12:00:00Z'));
|
||||
localStorage.removeItem(LOCALSTORAGE.ALERT_RULES_LIST_VIEWS);
|
||||
useAlertRuleViewsStore.setState({ railCollapsed: false });
|
||||
useAlertRuleViewsStore.setState({ railCollapsed: false, recent: [] });
|
||||
});
|
||||
|
||||
describe('builtin views', () => {
|
||||
it('renders the builtin views with All active by default', async () => {
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
expect(viewItem('mine')).toHaveTextContent('My alert rules');
|
||||
expect(viewItem('all')).toHaveTextContent('All alert rules');
|
||||
expect(viewItem('recent')).toHaveTextContent('Recently viewed');
|
||||
expect(viewItem('firing')).toHaveTextContent('Firing');
|
||||
expect(viewItem('enabled')).toHaveTextContent('Enabled');
|
||||
expect(viewItem('disabled')).toHaveTextContent('Disabled');
|
||||
expect(activeHeading()).toHaveTextContent('All alert rules');
|
||||
expect(
|
||||
@@ -156,10 +153,10 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
['firing', 'Firing'],
|
||||
['disabled', 'Disabled'],
|
||||
])('%s sends states=%s', async (id, label) => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const requests = captureRulesRequests();
|
||||
renderListAlertRules();
|
||||
await screen.findByText('High CPU Alert');
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
await selectView(user, id);
|
||||
|
||||
@@ -174,12 +171,72 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('My alert rules filters by the current user as creator', async () => {
|
||||
it('Enabled sends every state except disabled', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const requests = captureRulesRequests();
|
||||
renderListAlertRules();
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
await selectView(user, 'enabled');
|
||||
|
||||
const enabled = ['inactive', 'pending', 'recovering', 'firing', 'nodata'];
|
||||
await waitFor(() => {
|
||||
expect(lastRequest(requests).getAll('states')).toStrictEqual(enabled);
|
||||
});
|
||||
expect(lastRequest(requests).has('query')).toBe(false);
|
||||
expect(activeHeading()).toHaveTextContent('Enabled');
|
||||
});
|
||||
|
||||
it('Recently viewed lists the opened rules in visit order from one large page', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const requests = captureRulesRequests();
|
||||
useAlertRuleViewsStore.setState({ recent: ['rule-3', 'rule-1'] });
|
||||
renderListAlertRules();
|
||||
await screen.findByTestId('alert-row-rule-2-name');
|
||||
|
||||
await selectView(user, 'recent');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(lastRequest(requests).get('limit')).toBe('200');
|
||||
});
|
||||
expect(lastRequest(requests).get('offset')).toBe('0');
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.queryByTestId('alert-row-rule-2-name'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
const names = screen
|
||||
.getAllByTestId(/^alert-row-.+-name$/)
|
||||
.map((cell) => cell.textContent);
|
||||
expect(names).toStrictEqual(['Healthy Alert', 'High CPU Alert']);
|
||||
expect(activeHeading()).toHaveTextContent('Recently viewed');
|
||||
});
|
||||
|
||||
it('an empty Recently viewed keeps the search and says how it fills', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
await selectView(user, 'recent');
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('no-results-title'),
|
||||
).resolves.toHaveTextContent('No recently viewed alert rules');
|
||||
expect(screen.getByTestId('no-results-subtitle')).toHaveTextContent(
|
||||
'Alert rules you open will appear here.',
|
||||
);
|
||||
expect(screen.getByTestId('alert-rules-list-search')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('no-results-clear-button'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('My alert rules filters by the current user as creator', async () => {
|
||||
const user = userEvent.setup();
|
||||
const requests = captureRulesRequests();
|
||||
const { email } = getAppContextMock('ADMIN').user;
|
||||
renderListAlertRules();
|
||||
await screen.findByText('High CPU Alert');
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
await selectView(user, 'mine');
|
||||
|
||||
@@ -192,22 +249,29 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
expect(activeHeading()).toHaveTextContent('My alert rules');
|
||||
});
|
||||
|
||||
it('editing a builtin view filter offers save as new view, which POSTs', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const captured = captureViewWrites();
|
||||
it('editing a builtin view filter offers save as new view only', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules();
|
||||
await screen.findByText('High CPU Alert');
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
await runSearchQuery(user, 'foo');
|
||||
|
||||
await user.click(await screen.findByTestId('alert-rules-view-save-as-new'));
|
||||
await screen.findByTestId('alert-rules-view-save-as-new');
|
||||
expect(
|
||||
screen.queryByTestId('alert-rules-view-save-changes'),
|
||||
).not.toBeInTheDocument();
|
||||
await user.type(
|
||||
});
|
||||
|
||||
it('save as new view from an edited builtin view POSTs', async () => {
|
||||
const user = userEvent.setup();
|
||||
const captured = captureViewWrites();
|
||||
renderListAlertRules({ initialRoute: '/?query=foo' });
|
||||
|
||||
await user.click(await screen.findByTestId('alert-rules-view-save-as-new'));
|
||||
await user.click(
|
||||
await screen.findByTestId('save-alert-rule-view-name-field'),
|
||||
'Foo alerts',
|
||||
);
|
||||
await user.paste('Foo alerts');
|
||||
await user.click(screen.getByTestId('save-alert-rule-view-confirm'));
|
||||
|
||||
await waitFor(() => expect(captured.posts).toHaveLength(1));
|
||||
@@ -217,7 +281,7 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
version: 'v1',
|
||||
query: 'foo',
|
||||
states: [],
|
||||
sort: 'updated_at',
|
||||
sort: 'state',
|
||||
order: 'desc',
|
||||
},
|
||||
});
|
||||
@@ -227,7 +291,7 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
|
||||
describe('saved views', () => {
|
||||
it('lists saved views and applies the selected one', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const requests = captureRulesRequests();
|
||||
renderListAlertRules({ initialRoute: '/?page=2' });
|
||||
|
||||
@@ -259,9 +323,9 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('shows the unsaved-changes panel after editing an applied view filter', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
await selectView(user, 'view-1');
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules({ initialRoute: VIEW_1_ROUTE });
|
||||
await screen.findByTestId('alert-rules-view-view-1');
|
||||
|
||||
await runSearchQuery(user, 'foo');
|
||||
|
||||
@@ -274,11 +338,9 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('Save PUTs the full current filter and the unchanged name', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const captured = captureViewWrites();
|
||||
renderListAlertRules();
|
||||
await selectView(user, 'view-1');
|
||||
await runSearchQuery(user, 'foo');
|
||||
renderListAlertRules({ initialRoute: VIEW_1_EDITED_ROUTE });
|
||||
|
||||
await user.click(await screen.findByTestId('alert-rules-view-save-changes'));
|
||||
|
||||
@@ -304,17 +366,15 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('Save as POSTs a new view and activates it', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const captured = captureViewWrites();
|
||||
renderListAlertRules();
|
||||
await selectView(user, 'view-1');
|
||||
await runSearchQuery(user, 'foo');
|
||||
renderListAlertRules({ initialRoute: VIEW_1_EDITED_ROUTE });
|
||||
|
||||
await user.click(await screen.findByTestId('alert-rules-view-save-as'));
|
||||
await user.type(
|
||||
await user.click(
|
||||
await screen.findByTestId('save-alert-rule-view-name-field'),
|
||||
'My view',
|
||||
);
|
||||
await user.paste('My view');
|
||||
await user.click(screen.getByTestId('save-alert-rule-view-confirm'));
|
||||
|
||||
await waitFor(() => expect(captured.posts).toHaveLength(1));
|
||||
@@ -333,14 +393,14 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('caps a view name at 64 characters', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const captured = captureViewWrites();
|
||||
renderListAlertRules();
|
||||
await screen.findByText('High CPU Alert');
|
||||
|
||||
await user.click(screen.getByLabelText('Save current filters as a view'));
|
||||
await user.click(await screen.findByTestId('alert-rules-view-save-trigger'));
|
||||
const input = await screen.findByTestId('save-alert-rule-view-name-field');
|
||||
await user.type(input, 'x'.repeat(70));
|
||||
await user.click(input);
|
||||
await user.paste('x'.repeat(70));
|
||||
|
||||
expect(input).toHaveValue('x'.repeat(64));
|
||||
await user.click(screen.getByTestId('save-alert-rule-view-confirm'));
|
||||
@@ -350,11 +410,8 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('Reset restores the active view filter', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
await selectView(user, 'view-1');
|
||||
await runSearchQuery(user, 'foo');
|
||||
await waitFor(() => expect(urlParam('query')).toBe('foo'));
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules({ initialRoute: VIEW_1_EDITED_ROUTE });
|
||||
|
||||
await user.click(await screen.findByTestId('alert-rules-view-reset'));
|
||||
|
||||
@@ -370,19 +427,16 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('rename PUTs the new name and keeps the stored filter', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const captured = captureViewWrites();
|
||||
renderListAlertRules();
|
||||
await selectView(user, 'view-2');
|
||||
await runSearchQuery(user, 'foo');
|
||||
renderListAlertRules({ initialRoute: '/?view=view-2&query=foo' });
|
||||
await screen.findByTestId('alert-rules-view-save-changes');
|
||||
|
||||
const row = viewItem('view-1').parentElement as HTMLElement;
|
||||
await user.click(within(row).getByLabelText('Rename view'));
|
||||
await user.click(screen.getByTestId('alert-rules-view-rename-view-1'));
|
||||
const input = await screen.findByTestId('rename-alert-rule-view-name-field');
|
||||
expect(input).toHaveValue('Critical firing');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'Renamed');
|
||||
await user.paste('Renamed');
|
||||
await user.click(screen.getByTestId('rename-alert-rule-view-confirm'));
|
||||
|
||||
await waitFor(() => expect(captured.puts).toHaveLength(1));
|
||||
@@ -403,12 +457,13 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('delete asks for confirmation and sends DELETE', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const captured = captureViewWrites();
|
||||
renderListAlertRules();
|
||||
await selectView(user, 'view-1');
|
||||
renderListAlertRules({ initialRoute: VIEW_1_ROUTE });
|
||||
|
||||
await user.click(screen.getByTestId('alert-rules-view-delete-view-2'));
|
||||
await user.click(
|
||||
await screen.findByTestId('alert-rules-view-delete-view-2'),
|
||||
);
|
||||
|
||||
await expect(
|
||||
screen.findByText(/Views are shared across your organization/),
|
||||
@@ -421,13 +476,13 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('deleting the active view falls back to All', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const captured = captureViewWrites();
|
||||
renderListAlertRules();
|
||||
await selectView(user, 'view-1');
|
||||
await waitFor(() => expect(urlParam('query')).toBe(VIEW_1_QUERY));
|
||||
renderListAlertRules({ initialRoute: VIEW_1_ROUTE });
|
||||
|
||||
await user.click(screen.getByTestId('alert-rules-view-delete-view-1'));
|
||||
await user.click(
|
||||
await screen.findByTestId('alert-rules-view-delete-view-1'),
|
||||
);
|
||||
await user.click(await findConfirmDelete());
|
||||
|
||||
await waitFor(() => expect(captured.deletes).toStrictEqual(['view-1']));
|
||||
@@ -440,12 +495,10 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('All alert rules clears the view and its filters', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
await selectView(user, 'view-1');
|
||||
await waitFor(() => expect(urlParam('query')).not.toBeNull());
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules({ initialRoute: VIEW_1_ROUTE });
|
||||
|
||||
await user.click(viewItem('all'));
|
||||
await user.click(await screen.findByTestId('alert-rules-view-all'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(urlParam('view')).toBeNull();
|
||||
@@ -482,9 +535,9 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('marks a cleared view filter in the URL', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
await selectView(user, 'view-2');
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules({ initialRoute: VIEW_2_ROUTE });
|
||||
await screen.findByTestId('alert-rules-view-view-2');
|
||||
|
||||
await user.click(screen.getByTestId('alert-rules-filter-clear'));
|
||||
|
||||
@@ -492,6 +545,37 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
expect(urlParam('view')).toBe('view-2');
|
||||
});
|
||||
|
||||
it('marks the empty query when a sort changes on a view without one', async () => {
|
||||
server.use(
|
||||
rest.get('http://localhost/api/v2/rule_views', (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
data: {
|
||||
views: [
|
||||
{
|
||||
...ruleViewsFixture[0],
|
||||
data: { ...ruleViewsFixture[0].data, query: '', states: [] },
|
||||
},
|
||||
],
|
||||
},
|
||||
status: 'success',
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
await selectView(user, 'view-1');
|
||||
await waitFor(() => expect(urlParam('orderBy')).toBe(VIEW_1_ORDER_BY));
|
||||
expect(urlParam('query')).toBeNull();
|
||||
|
||||
await user.click(screen.getByTitle('Alert Name'));
|
||||
|
||||
await waitFor(() => expect(urlParam('query')).toBe(''));
|
||||
expect(urlParam('view')).toBe('view-1');
|
||||
});
|
||||
|
||||
it('keeps a cleared view filter cleared on reload', async () => {
|
||||
const requests = captureRulesRequests();
|
||||
renderListAlertRules({ initialRoute: '/?view=view-1&query=' });
|
||||
@@ -504,24 +588,24 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('keeps a query run while the linked views are still loading', async () => {
|
||||
const views = holdResponse();
|
||||
server.use(
|
||||
rest.get('http://localhost/api/v2/rule_views', (_, res, ctx) =>
|
||||
res(
|
||||
ctx.delay(300),
|
||||
rest.get('http://localhost/api/v2/rule_views', async (_, res, ctx) => {
|
||||
await views.held;
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json({ data: { views: ruleViewsFixture }, status: 'success' }),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules({ initialRoute: '/?view=view-1' });
|
||||
|
||||
await runSearchQuery(user, 'foo');
|
||||
await screen.findByTestId(
|
||||
'alert-rules-view-save-changes',
|
||||
{},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
await waitFor(() => expect(urlParam('query')).toBe('foo'));
|
||||
views.release();
|
||||
|
||||
await screen.findByTestId('alert-rules-view-save-changes');
|
||||
await urlSettled();
|
||||
expect(urlParam('query')).toBe('foo');
|
||||
expect(urlParam('states')).toBeNull();
|
||||
@@ -530,7 +614,7 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
|
||||
describe('rail chrome', () => {
|
||||
it('filters views by name', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules();
|
||||
await screen.findByTestId('alert-rules-view-view-2');
|
||||
|
||||
@@ -550,11 +634,10 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('collapses the rail from the status bar and persists it', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderListAlertRules();
|
||||
await screen.findByText('High CPU Alert');
|
||||
|
||||
const toggle = screen.getByTestId('alert-rules-rail-toggle');
|
||||
const toggle = await screen.findByTestId('alert-rules-rail-toggle');
|
||||
expect(toggle).toHaveTextContent('Collapse');
|
||||
|
||||
await user.click(toggle);
|
||||
|
||||
@@ -163,7 +163,13 @@ function ActionsMenu({ rule, onEdit }: ActionsMenuProps): JSX.Element {
|
||||
return (
|
||||
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
|
||||
<div onClick={handleClick}>
|
||||
<Dropdown items={menuItems} nativeButton align="end" side="bottom">
|
||||
<Dropdown
|
||||
items={menuItems}
|
||||
nativeButton
|
||||
align="end"
|
||||
side="bottom"
|
||||
testId="alert-actions"
|
||||
>
|
||||
<Button
|
||||
aria-label="Action"
|
||||
variant="outlined"
|
||||
|
||||
@@ -49,7 +49,7 @@ function RuleStatesFilter({
|
||||
<MultiSelectFilter
|
||||
value={draft}
|
||||
options={STATE_OPTIONS}
|
||||
placeholder="State"
|
||||
placeholder="Status"
|
||||
testId="alert-rules-filter-states"
|
||||
onChange={handleChange}
|
||||
onDropdownVisibleChange={handleDropdownVisibleChange}
|
||||
|
||||
@@ -3,6 +3,7 @@ import ErrorEmptyState from 'components/Alerts/ErrorEmptyState';
|
||||
import NoResultsEmptyState from 'components/Alerts/NoResultsEmptyState';
|
||||
import InvalidQueryState from 'components/ListFilter/InvalidQueryState/InvalidQueryState';
|
||||
import ListCommandHeader from 'components/ListViews/ListCommandHeader/ListCommandHeader';
|
||||
import ListHeaderZone from 'components/ListViews/ListHeaderZone/ListHeaderZone';
|
||||
import ListStatusBar from 'components/ListViews/ListStatusBar/ListStatusBar';
|
||||
import ViewsRail from 'components/ListViews/ViewsRail/ViewsRail';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
@@ -27,7 +28,13 @@ import { useAlertRulesHandlers } from './useAlertRulesHandlers';
|
||||
import { useAlertRulesListFilter } from './useAlertRulesListFilter';
|
||||
import { useAlertRuleViews } from './useAlertRuleViews';
|
||||
import { useAlertRuleViewsStore } from './useAlertRuleViewsStore';
|
||||
import { DEFAULT_RULE_VIEW, RULE_BUILTIN_VIEWS } from './list.config';
|
||||
import {
|
||||
DEFAULT_RULE_VIEW,
|
||||
findRuleBuiltinView,
|
||||
RULE_BUILTIN_VIEWS,
|
||||
} from './list.config';
|
||||
import { useRuleViewCtx } from './useRuleViewCtx';
|
||||
import { ruleListEmptyState } from './utils';
|
||||
|
||||
const QUERY_PARAMS_CONFIG = {
|
||||
orderBy: 'orderBy',
|
||||
@@ -35,6 +42,9 @@ const QUERY_PARAMS_CONFIG = {
|
||||
limit: 'limit',
|
||||
} as const;
|
||||
|
||||
// Client-filtered views (Recently viewed) narrow one page of the API's max size.
|
||||
const CLIENT_VIEW_LIMIT = 200;
|
||||
|
||||
const DEFAULT_PAGE = 1;
|
||||
const DEFAULT_LIMIT = 10;
|
||||
|
||||
@@ -63,7 +73,7 @@ function ListAlertRules(): JSX.Element {
|
||||
},
|
||||
);
|
||||
|
||||
const { filter, applyFilter, submitQuery, changeStates } =
|
||||
const { filter, applyFilter, submitQuery, changeStates, changeSort } =
|
||||
useAlertRulesListFilter({ orderBy, setOrderBy, setPage });
|
||||
|
||||
const ruleViews = useAlertRuleViews({ filter, applyFilter });
|
||||
@@ -74,21 +84,25 @@ function ListAlertRules(): JSX.Element {
|
||||
setRailCollapsed(!railCollapsed);
|
||||
}, [setRailCollapsed, railCollapsed]);
|
||||
|
||||
const viewCtx = useRuleViewCtx();
|
||||
const clientFilter = findRuleBuiltinView(ruleViews.activeViewId)?.clientFilter;
|
||||
const clientView = !!clientFilter;
|
||||
|
||||
const listParams = useMemo(
|
||||
() => ({
|
||||
query: filter.query || undefined,
|
||||
states: filter.states.length ? filter.states : undefined,
|
||||
sort: filter.sort,
|
||||
order: filter.order,
|
||||
limit,
|
||||
offset: (page - 1) * limit,
|
||||
limit: clientView ? CLIENT_VIEW_LIMIT : limit,
|
||||
offset: clientView ? 0 : (page - 1) * limit,
|
||||
}),
|
||||
[filter, limit, page],
|
||||
[filter, limit, page, clientView],
|
||||
);
|
||||
|
||||
const {
|
||||
rules,
|
||||
total,
|
||||
rules: fetchedRules,
|
||||
total: fetchedTotal,
|
||||
labels,
|
||||
reservedKeywords,
|
||||
isFetching,
|
||||
@@ -97,6 +111,19 @@ function ListAlertRules(): JSX.Element {
|
||||
refetch,
|
||||
} = useAlertRulesData(listParams);
|
||||
|
||||
const clientRules = useMemo(
|
||||
() => (clientFilter ? clientFilter(fetchedRules, viewCtx) : null),
|
||||
[clientFilter, fetchedRules, viewCtx],
|
||||
);
|
||||
const rules = useMemo(
|
||||
() =>
|
||||
clientRules
|
||||
? clientRules.slice((page - 1) * limit, page * limit)
|
||||
: fetchedRules,
|
||||
[clientRules, fetchedRules, page, limit],
|
||||
);
|
||||
const total = clientRules ? clientRules.length : fetchedTotal;
|
||||
|
||||
const { creatorOptions, source } = useAlertRulesFilterSource({
|
||||
rules,
|
||||
labels,
|
||||
@@ -150,10 +177,16 @@ function ListAlertRules(): JSX.Element {
|
||||
}, [action, columns, handleEdit]);
|
||||
|
||||
const hasActiveFilters = filter.query.length > 0 || filter.states.length > 0;
|
||||
const isEmptyDueToFilters =
|
||||
!isFetching && total === 0 && (hasActiveFilters || !!queryError);
|
||||
const isEmptyNoRules =
|
||||
!isFetching && !isError && !queryError && !hasActiveFilters && total === 0;
|
||||
const { isEmptyDueToFilters, isEmptyNoRules, noResults, onClear } =
|
||||
ruleListEmptyState({
|
||||
isFetching,
|
||||
isError,
|
||||
queryError,
|
||||
hasActiveFilters,
|
||||
total,
|
||||
viewEmptyState: findRuleBuiltinView(ruleViews.activeViewId)?.emptyState,
|
||||
onClear: handleClearFilters,
|
||||
});
|
||||
|
||||
const activeLabel =
|
||||
ruleViews.activeView?.name ??
|
||||
@@ -182,32 +215,30 @@ function ListAlertRules(): JSX.Element {
|
||||
deleteDescription="Views are shared across your organization, so this removes it for everyone. Alert rules are not affected."
|
||||
/>
|
||||
<div className={styles.main}>
|
||||
{!isEmptyNoRules && (
|
||||
<div className={styles.headerZone}>
|
||||
<ListCommandHeader
|
||||
label={activeLabel}
|
||||
count={total}
|
||||
isCountLoading={isFetching}
|
||||
isModified={ruleViews.isModified}
|
||||
testIdPrefix="alert-rules"
|
||||
action={
|
||||
<AlertRulesHeaderActions
|
||||
columns={columns}
|
||||
canAddAlert={addNewAlert}
|
||||
onNewAlert={handleNewAlert}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<AlertRulesFilterZone
|
||||
query={filter.query}
|
||||
states={filter.states}
|
||||
creatorOptions={creatorOptions}
|
||||
source={source}
|
||||
onQueryChange={submitQuery}
|
||||
onStatesChange={changeStates}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<ListHeaderZone testId="alert-rules-header-zone">
|
||||
<ListCommandHeader
|
||||
label={activeLabel}
|
||||
count={total}
|
||||
isCountLoading={isFetching}
|
||||
isModified={ruleViews.isModified}
|
||||
testIdPrefix="alert-rules"
|
||||
action={
|
||||
<AlertRulesHeaderActions
|
||||
columns={columns}
|
||||
canAddAlert={addNewAlert && !isEmptyNoRules}
|
||||
onNewAlert={handleNewAlert}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<AlertRulesFilterZone
|
||||
query={filter.query}
|
||||
states={filter.states}
|
||||
creatorOptions={creatorOptions}
|
||||
source={source}
|
||||
onQueryChange={submitQuery}
|
||||
onStatesChange={changeStates}
|
||||
/>
|
||||
</ListHeaderZone>
|
||||
|
||||
<div ref={containerRef} className={styles.tableContainer}>
|
||||
{isError ? (
|
||||
@@ -220,9 +251,9 @@ function ListAlertRules(): JSX.Element {
|
||||
/>
|
||||
) : isEmptyDueToFilters ? (
|
||||
<NoResultsEmptyState
|
||||
title="No matching alert rules"
|
||||
subtitle="No alert rules match your search. Try adjusting your search criteria."
|
||||
onClear={handleClearFilters}
|
||||
title={noResults.title}
|
||||
subtitle={noResults.description}
|
||||
onClear={onClear}
|
||||
clearButtonText="Clear Search"
|
||||
/>
|
||||
) : isEmptyNoRules ? (
|
||||
@@ -236,6 +267,7 @@ function ListAlertRules(): JSX.Element {
|
||||
getItemKey={(row): string => row.id ?? ''}
|
||||
columnStorageKey="alert-rules-columns"
|
||||
enableQueryParams={QUERY_PARAMS_CONFIG}
|
||||
onSort={changeSort}
|
||||
onRowClick={handleRowClick}
|
||||
onRowClickNewTab={handleRowClickNewTab}
|
||||
pagination={{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { BellOff, Flame, Layers, User } from '@signozhq/icons';
|
||||
import { Bell, BellOff, Clock, Flame, Layers, User } from '@signozhq/icons';
|
||||
import { clause } from 'components/ListFilter/dsl/filterQuery';
|
||||
import type {
|
||||
ClauseBuilder,
|
||||
@@ -7,7 +7,7 @@ import type {
|
||||
} from 'components/ListFilter/dsl/types';
|
||||
import type { BuiltinViewConfig } from 'components/ListViews/types';
|
||||
|
||||
import type { RuleListFilter, RuleViewCtx } from './types';
|
||||
import type { AlertRule, RuleListFilter, RuleViewCtx } from './types';
|
||||
|
||||
// Mirrors pkg/types/ruletypes/list_filter.go. Label keys go under `labels.`.
|
||||
export const RULES_DSL_GRAMMAR = {
|
||||
@@ -44,9 +44,14 @@ const where: ClauseBuilder<
|
||||
(typeof RULES_DSL_GRAMMAR)['fields'][number]['key']
|
||||
> = clause;
|
||||
|
||||
type RuleViewConfig = BuiltinViewConfig<RuleListFilter, RuleViewCtx>;
|
||||
type RuleViewConfig = BuiltinViewConfig<RuleListFilter, RuleViewCtx, AlertRule>;
|
||||
|
||||
const ENABLED_STATES = Object.values(RuletypesAlertStateDTO).filter(
|
||||
(state) => state !== RuletypesAlertStateDTO.disabled,
|
||||
);
|
||||
|
||||
// Built-in views replace query and states; the current sort/order is kept.
|
||||
// `clientFilter` views narrow one large fetched page in the browser.
|
||||
const views = [
|
||||
{
|
||||
id: 'mine',
|
||||
@@ -59,6 +64,24 @@ const views = [
|
||||
states: [],
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'recent',
|
||||
label: 'Recently viewed',
|
||||
icon: Clock,
|
||||
section: 'personal',
|
||||
filter: (current): RuleListFilter => ({ ...current, query: '', states: [] }),
|
||||
// Keeps visit order, whatever the active sort.
|
||||
clientFilter: (rows, { recent }): AlertRule[] => {
|
||||
const order = new Map(recent.map((id, index) => [id, index]));
|
||||
return rows
|
||||
.filter((rule) => !!rule.id && order.has(rule.id))
|
||||
.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0));
|
||||
},
|
||||
emptyState: {
|
||||
title: 'No recently viewed alert rules',
|
||||
description: 'Alert rules you open will appear here.',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'all',
|
||||
label: 'All alert rules',
|
||||
@@ -77,6 +100,17 @@ const views = [
|
||||
states: [RuletypesAlertStateDTO.firing],
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'enabled',
|
||||
label: 'Enabled',
|
||||
icon: Bell,
|
||||
section: 'system',
|
||||
filter: (current): RuleListFilter => ({
|
||||
...current,
|
||||
query: '',
|
||||
states: ENABLED_STATES,
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'disabled',
|
||||
label: 'Disabled',
|
||||
@@ -95,3 +129,6 @@ export type RuleViewId = (typeof views)[number]['id'];
|
||||
export const RULE_BUILTIN_VIEWS: readonly RuleViewConfig[] = views;
|
||||
|
||||
export const DEFAULT_RULE_VIEW: RuleViewId = 'all';
|
||||
|
||||
export const findRuleBuiltinView = (id: string): RuleViewConfig | undefined =>
|
||||
RULE_BUILTIN_VIEWS.find((v) => v.id === id);
|
||||
|
||||
@@ -19,4 +19,5 @@ export type RuleView = SavedListView<RuleListFilter>;
|
||||
|
||||
export interface RuleViewCtx {
|
||||
userEmail: string;
|
||||
recent: string[];
|
||||
}
|
||||
|
||||
@@ -20,8 +20,7 @@ export interface UseAlertRuleViewsResult extends UseListViewsResult<RuleListFilt
|
||||
}
|
||||
|
||||
// A link carrying only `view=<custom id>` gets that view's filter applied once
|
||||
// the views load; a link carrying its own filter params keeps them. Clearing a
|
||||
// custom view's filter writes an empty `query=` so a reload keeps it cleared.
|
||||
// the views load; a link carrying its own filter params keeps them.
|
||||
export function useAlertRuleViews({
|
||||
filter,
|
||||
applyFilter,
|
||||
@@ -42,21 +41,12 @@ export function useAlertRuleViews({
|
||||
});
|
||||
|
||||
const { activeView } = views;
|
||||
const [rawQuery, setRawQuery] = useQueryState(ALERT_RULES_PARAMS.QUERY);
|
||||
const [rawQuery] = useQueryState(ALERT_RULES_PARAMS.QUERY);
|
||||
const startedFromViewLink = useRef(
|
||||
isDefaultRuleListFilter(filter) && rawQuery === null,
|
||||
);
|
||||
const hasResolvedLinkedView = useRef(false);
|
||||
|
||||
// Declared before the restore so it skips the render that applies a linked view.
|
||||
const clearedCustomView =
|
||||
!!activeView && rawQuery === null && isDefaultRuleListFilter(filter);
|
||||
useEffect(() => {
|
||||
if (hasResolvedLinkedView.current && clearedCustomView) {
|
||||
void setRawQuery('', { clearOnDefault: false, history: 'replace' });
|
||||
}
|
||||
}, [clearedCustomView, setRawQuery]);
|
||||
|
||||
useEffect(() => {
|
||||
if (hasResolvedLinkedView.current || api.isLoading) {
|
||||
return;
|
||||
|
||||
@@ -2,18 +2,29 @@ import { create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
|
||||
// Most-recently-viewed list is capped so it stays a useful shortlist.
|
||||
const RECENT_LIMIT = 20;
|
||||
|
||||
interface AlertRuleViewsState {
|
||||
railCollapsed: boolean;
|
||||
recent: string[]; // rule ids, most-recent first
|
||||
setRailCollapsed: (collapsed: boolean) => void;
|
||||
markViewed: (id: string) => void;
|
||||
}
|
||||
|
||||
export const useAlertRuleViewsStore = create<AlertRuleViewsState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
railCollapsed: false,
|
||||
recent: [],
|
||||
setRailCollapsed: (collapsed): void => {
|
||||
set({ railCollapsed: collapsed });
|
||||
},
|
||||
markViewed: (id): void => {
|
||||
set((s) => ({
|
||||
recent: [id, ...s.recent.filter((r) => r !== id)].slice(0, RECENT_LIMIT),
|
||||
}));
|
||||
},
|
||||
}),
|
||||
{ name: LOCALSTORAGE.ALERT_RULES_LIST_VIEWS },
|
||||
),
|
||||
|
||||
@@ -8,6 +8,7 @@ import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { isModifierKeyPressed } from 'utils/app';
|
||||
|
||||
import type { AlertRule } from './types';
|
||||
import { useAlertRuleViewsStore } from './useAlertRuleViewsStore';
|
||||
|
||||
interface UseAlertRulesHandlersReturn {
|
||||
handleEdit: (
|
||||
@@ -24,6 +25,16 @@ export function useAlertRulesHandlers(
|
||||
): UseAlertRulesHandlersReturn {
|
||||
const { safeNavigate } = useSafeNavigate();
|
||||
const params = useUrlQuery();
|
||||
const markViewed = useAlertRuleViewsStore((s) => s.markViewed);
|
||||
|
||||
const markRuleViewed = useCallback(
|
||||
(rule: Pick<AlertRule, 'id'>): void => {
|
||||
if (rule.id) {
|
||||
markViewed(rule.id);
|
||||
}
|
||||
},
|
||||
[markViewed],
|
||||
);
|
||||
|
||||
const getEditUrl = useCallback(
|
||||
(rule: Pick<AlertRule, 'id'>): string => {
|
||||
@@ -36,9 +47,10 @@ export function useAlertRulesHandlers(
|
||||
|
||||
const handleEdit = useCallback(
|
||||
(rule: Pick<AlertRule, 'id'>, options?: { newTab?: boolean }): void => {
|
||||
markRuleViewed(rule);
|
||||
safeNavigate(getEditUrl(rule), options);
|
||||
},
|
||||
[getEditUrl, safeNavigate],
|
||||
[getEditUrl, safeNavigate, markRuleViewed],
|
||||
);
|
||||
|
||||
const handleNewAlert = useCallback(
|
||||
@@ -57,6 +69,7 @@ export function useAlertRulesHandlers(
|
||||
const { handleRowClick, handleRowClickNewTab } = useTableRowClick<AlertRule>({
|
||||
getUrl: getEditUrl,
|
||||
onNavigate: safeNavigate,
|
||||
onBeforeNavigate: markRuleViewed,
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import type { SortState } from 'components/TanStackTableView/types';
|
||||
import { useQueryState } from 'nuqs';
|
||||
|
||||
import { useAlertRulesQuery, useAlertRulesStates } from './hooks';
|
||||
import {
|
||||
ALERT_RULES_PARAMS,
|
||||
useAlertRulesQuery,
|
||||
useAlertRulesStates,
|
||||
} from './hooks';
|
||||
import { findRuleBuiltinView } from './list.config';
|
||||
import type { RuleListFilter } from './types';
|
||||
import { toListSort, toOrderBy } from './utils';
|
||||
|
||||
@@ -16,6 +22,8 @@ interface UseAlertRulesListFilterResult {
|
||||
applyFilter: (filter: RuleListFilter) => void;
|
||||
submitQuery: (query: string) => void;
|
||||
changeStates: (states: string[]) => void;
|
||||
/** The table writes `orderBy` itself; this only keeps a custom view's empty query. */
|
||||
changeSort: () => void;
|
||||
}
|
||||
|
||||
// The v3 list filter, read from and written to the URL. Every change goes back to page 1.
|
||||
@@ -42,21 +50,42 @@ export function useAlertRulesListFilter({
|
||||
[setQuery, setStates, setOrderBy, setPage],
|
||||
);
|
||||
|
||||
// Clearing a custom view's filter writes an empty `query=`, so a reload does
|
||||
// not re-apply the view.
|
||||
const [viewId] = useQueryState(ALERT_RULES_PARAMS.VIEW);
|
||||
const onCustomView = !!viewId && !findRuleBuiltinView(viewId);
|
||||
const pinEmptyQuery = useCallback((): void => {
|
||||
void setQuery('', { clearOnDefault: false });
|
||||
}, [setQuery]);
|
||||
|
||||
const submitQuery = useCallback(
|
||||
(next: string): void => {
|
||||
void setQuery(next || null);
|
||||
if (!next && onCustomView) {
|
||||
pinEmptyQuery();
|
||||
} else {
|
||||
void setQuery(next || null);
|
||||
}
|
||||
setPage(1);
|
||||
},
|
||||
[setQuery, setPage],
|
||||
[onCustomView, pinEmptyQuery, setQuery, setPage],
|
||||
);
|
||||
|
||||
const changeStates = useCallback(
|
||||
(next: string[]): void => {
|
||||
void setStates(next.length ? next : null);
|
||||
if (!query && onCustomView) {
|
||||
pinEmptyQuery();
|
||||
}
|
||||
setPage(1);
|
||||
},
|
||||
[setStates, setPage],
|
||||
[setStates, query, onCustomView, pinEmptyQuery, setPage],
|
||||
);
|
||||
|
||||
return { filter, applyFilter, submitQuery, changeStates };
|
||||
const changeSort = useCallback((): void => {
|
||||
if (!query && onCustomView) {
|
||||
pinEmptyQuery();
|
||||
}
|
||||
}, [query, onCustomView, pinEmptyQuery]);
|
||||
|
||||
return { filter, applyFilter, submitQuery, changeStates, changeSort };
|
||||
}
|
||||
|
||||
@@ -2,8 +2,13 @@ import { useMemo } from 'react';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
|
||||
import type { RuleViewCtx } from './types';
|
||||
import { useAlertRuleViewsStore } from './useAlertRuleViewsStore';
|
||||
|
||||
export function useRuleViewCtx(): RuleViewCtx {
|
||||
const { user } = useAppContext();
|
||||
return useMemo(() => ({ userEmail: user.email }), [user.email]);
|
||||
const recent = useAlertRuleViewsStore((s) => s.recent);
|
||||
return useMemo(
|
||||
() => ({ userEmail: user.email, recent }),
|
||||
[user.email, recent],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
RuletypesListOrderDTO,
|
||||
RuletypesListSortDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { EmptyStateCopy } from 'components/ListViews/types';
|
||||
import type { SortState } from 'components/TanStackTableView/types';
|
||||
import { dataSourceForAlertType } from 'constants/alerts';
|
||||
|
||||
@@ -45,7 +46,8 @@ const COLUMN_TO_SORT: Record<string, RuletypesListSortDTO> = {
|
||||
updatedAt: RuletypesListSortDTO.updated_at,
|
||||
};
|
||||
|
||||
export const DEFAULT_RULE_LIST_SORT = RuletypesListSortDTO.updated_at;
|
||||
// Status, highest rank first: firing, nodata, pending, recovering, inactive, disabled.
|
||||
export const DEFAULT_RULE_LIST_SORT = RuletypesListSortDTO.state;
|
||||
export const DEFAULT_RULE_LIST_ORDER = RuletypesListOrderDTO.desc;
|
||||
|
||||
// `rule_list_filter_invalid`: DSL syntax / key / operator; `rule_list_invalid`: other list params.
|
||||
@@ -114,3 +116,48 @@ export const DEFAULT_RULE_LIST_FILTER: RuleListFilter = {
|
||||
export function isDefaultRuleListFilter(filter: RuleListFilter): boolean {
|
||||
return isSameRuleListFilter(filter, DEFAULT_RULE_LIST_FILTER);
|
||||
}
|
||||
|
||||
interface RuleListEmptyStateArgs {
|
||||
isFetching: boolean;
|
||||
isError: boolean;
|
||||
queryError: string | null;
|
||||
hasActiveFilters: boolean;
|
||||
total: number;
|
||||
viewEmptyState?: EmptyStateCopy;
|
||||
onClear: () => void;
|
||||
}
|
||||
|
||||
interface RuleListEmptyState {
|
||||
isEmptyDueToFilters: boolean;
|
||||
isEmptyNoRules: boolean;
|
||||
noResults: EmptyStateCopy;
|
||||
// Unset for an empty view with its own copy (Recently viewed): no search to clear.
|
||||
onClear?: () => void;
|
||||
}
|
||||
|
||||
export function ruleListEmptyState({
|
||||
isFetching,
|
||||
isError,
|
||||
queryError,
|
||||
hasActiveFilters,
|
||||
total,
|
||||
viewEmptyState,
|
||||
onClear,
|
||||
}: RuleListEmptyStateArgs): RuleListEmptyState {
|
||||
const viewEmptyCopy =
|
||||
hasActiveFilters || queryError ? undefined : viewEmptyState;
|
||||
const isEmpty = !isFetching && total === 0;
|
||||
const noResults: EmptyStateCopy = viewEmptyCopy ?? {
|
||||
title: 'No matching alert rules',
|
||||
description:
|
||||
'No alert rules match your search. Try adjusting your search criteria.',
|
||||
};
|
||||
return {
|
||||
isEmptyDueToFilters:
|
||||
isEmpty && (hasActiveFilters || !!queryError || !!viewEmptyCopy),
|
||||
isEmptyNoRules:
|
||||
isEmpty && !isError && !queryError && !hasActiveFilters && !viewEmptyCopy,
|
||||
noResults,
|
||||
onClear: viewEmptyCopy ? undefined : onClear,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -272,6 +272,7 @@ function LogsExplorerList({
|
||||
>
|
||||
<OverlayScrollbar isVirtuoso>
|
||||
<Virtuoso
|
||||
data-testid="logs-list-virtuoso-scroller"
|
||||
key={activeLogIndex || 'logs-virtuoso'}
|
||||
ref={ref as React.Ref<VirtuosoHandle>}
|
||||
initialTopMostItemIndex={activeLogIndex !== -1 ? activeLogIndex : 0}
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
AllTheProviders,
|
||||
fireEvent,
|
||||
render,
|
||||
RenderResult,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
@@ -127,6 +126,13 @@ jest.mock(
|
||||
return <div>MockQueryBuilderSearchV2</div>;
|
||||
},
|
||||
);
|
||||
jest.mock(
|
||||
'components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch',
|
||||
() =>
|
||||
function MockQuerySearch(): JSX.Element {
|
||||
return <div>MockQuerySearch</div>;
|
||||
},
|
||||
);
|
||||
jest.mock(
|
||||
'components/QuickFilters/QuickFilters',
|
||||
() =>
|
||||
@@ -223,7 +229,6 @@ describe.skip('LogsExplorerViews Pagination', () => {
|
||||
});
|
||||
|
||||
it('should fetch next page with correct payload when scrolled to end', async () => {
|
||||
let renderResult: RenderResult;
|
||||
// Define item height and viewport height for Virtuoso mock
|
||||
const itemHeight = 100;
|
||||
const viewportHeight = 500;
|
||||
@@ -233,10 +238,9 @@ describe.skip('LogsExplorerViews Pagination', () => {
|
||||
// Calculate the scroll position needed to reach the end of the initial list
|
||||
const totalHeight = initialItemCount * itemHeight;
|
||||
const targetScrollTop = totalHeight - viewportHeight;
|
||||
let scrollableElement: HTMLElement;
|
||||
|
||||
act(() => {
|
||||
renderResult = render(
|
||||
render(
|
||||
<VirtuosoMockContext.Provider value={{ viewportHeight, itemHeight }}>
|
||||
<LogsExplorer />
|
||||
</VirtuosoMockContext.Provider>,
|
||||
@@ -256,23 +260,15 @@ describe.skip('LogsExplorerViews Pagination', () => {
|
||||
verifyPayload({ payload: firstPayload, expectedOffset: 0 });
|
||||
|
||||
// Wait for the scrollable element to be available and simulate scrolling
|
||||
await waitFor(async () => {
|
||||
// Find the Virtuoso scroller element by its data-test-id
|
||||
scrollableElement = renderResult.container.querySelector(
|
||||
'[data-test-id="virtuoso-scroller"]',
|
||||
) as HTMLElement;
|
||||
const scrollableElement = await screen.findByTestId(
|
||||
'logs-list-virtuoso-scroller',
|
||||
);
|
||||
|
||||
// Ensure the element exists
|
||||
expect(scrollableElement).not.toBeNull();
|
||||
// Set the scrollTop property to simulate scrolling to the calculated end position
|
||||
scrollableElement.scrollTop = targetScrollTop;
|
||||
|
||||
if (scrollableElement) {
|
||||
// Set the scrollTop property to simulate scrolling to the calculated end position
|
||||
scrollableElement.scrollTop = targetScrollTop;
|
||||
|
||||
act(() => {
|
||||
fireEvent.scroll(scrollableElement);
|
||||
});
|
||||
}
|
||||
act(() => {
|
||||
fireEvent.scroll(scrollableElement);
|
||||
});
|
||||
|
||||
// Verify the second page request was made
|
||||
@@ -472,21 +468,16 @@ describe('Logs Explorer -> stage and run query', () => {
|
||||
{ initialRoute: '/logs' },
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.queryByText('pending_data_placeholder'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
await screen.findByTestId('logs-list-virtuoso');
|
||||
expect(
|
||||
screen.queryByText('pending_data_placeholder'),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
// check for no data state to not be present
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText(/No logs yet/)).not.toBeInTheDocument();
|
||||
});
|
||||
expect(screen.queryByText(/No logs yet/)).not.toBeInTheDocument();
|
||||
|
||||
// Wait for the initial API calls to be made (component may make multiple calls during initialization)
|
||||
await waitFor(() => {
|
||||
expect(capturedPayloads.length).toBeGreaterThan(0);
|
||||
});
|
||||
expect(capturedPayloads.length).toBeGreaterThan(0);
|
||||
|
||||
// Store the initial payload timestamps (use the last one as the baseline)
|
||||
const initialPayload = capturedPayloads[capturedPayloads.length - 1];
|
||||
@@ -494,20 +485,13 @@ describe('Logs Explorer -> stage and run query', () => {
|
||||
const initialEnd = initialPayload.end;
|
||||
|
||||
// Click the Run Query button
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
await user.click(
|
||||
screen.getByRole('button', {
|
||||
name: /run query/i,
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
await user.click(screen.getByTestId('explorer-run-query-btn'));
|
||||
|
||||
// Wait for additional API calls to be made after clicking Run Query
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(capturedPayloads.length).toBeGreaterThan(1);
|
||||
},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(capturedPayloads.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
// Verify that the IDs have changed
|
||||
expect(currentStagedQuery.id).not.toBe(initialStagedQueryId);
|
||||
@@ -528,5 +512,5 @@ describe('Logs Explorer -> stage and run query', () => {
|
||||
// Verify that the IDs have changed (this confirms the Stage & Run Query button worked)
|
||||
expect(currentStagedQuery.id).not.toBe(initialStagedQueryId);
|
||||
expect(currentCurrentQuery.id).not.toBe(initialCurrentQueryId);
|
||||
}, 15000);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -139,6 +139,7 @@ export function AboutSigNozQuestions({
|
||||
<div className="question">How did you first come across SigNoz?</div>
|
||||
|
||||
<Input.TextArea
|
||||
testId="discover-signoz-input"
|
||||
placeholder="e.g., I asked ChatGPT for Datadog alternatives, searched Google for “OpenTelemetry tools,” saw a Reddit or LinkedIn post, or heard about it from a colleague."
|
||||
value={discoverSignoz}
|
||||
autoFocus
|
||||
@@ -156,6 +157,7 @@ export function AboutSigNozQuestions({
|
||||
<Checkbox
|
||||
color="primary"
|
||||
id={`checkbox-${option}`}
|
||||
testId={`interest-${option}`}
|
||||
value={interestInSignoz.includes(option)}
|
||||
onChange={createInterestChangeHandler(option)}
|
||||
>
|
||||
@@ -168,6 +170,7 @@ export function AboutSigNozQuestions({
|
||||
<Checkbox
|
||||
color="primary"
|
||||
id="others-checkbox"
|
||||
testId="interest-Others"
|
||||
value={interestInSignoz.includes('Others')}
|
||||
onChange={createInterestChangeHandler('Others')}
|
||||
>
|
||||
@@ -178,6 +181,7 @@ export function AboutSigNozQuestions({
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="What got you interested in SigNoz?"
|
||||
testId="other-interest-input"
|
||||
value={otherInterestInSignoz}
|
||||
autoFocus
|
||||
width="100%"
|
||||
@@ -200,6 +204,7 @@ export function AboutSigNozQuestions({
|
||||
disabled={isNextDisabled}
|
||||
disabledTooltip={getNextDisabledReason()}
|
||||
suffix={<ArrowRight size={12} />}
|
||||
testId="about-signoz-next"
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user