mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-28 11:11:13 +00:00
Compare commits
4 Commits
fix/flaky-
...
fix/dashbo
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ac1479cc3 | ||
|
|
a34b75f86d | ||
|
|
7339662720 | ||
|
|
d1dd086cec |
@@ -20,16 +20,12 @@ You are the Playwright Test Generator for the SigNoz frontend. You take a plan w
|
||||
await expect(routing.activeRouteTab(PATH.metricsSummary)).toBeVisible();
|
||||
});
|
||||
```
|
||||
- A driver is a function closing over the page that returns `Locator` getters and async actions. Actions wait inside themselves (e.g. `run()` pairs the click with `waitForResponse(/query_range/)`), so specs don't. A wait for "the request the action fired" skips aborted requests, which have no response: Run after a cancel re-sends the cancelled query and aborts it, and `query-builder/run` TC-34 read that one.
|
||||
- A page action that opens an explorer waits for the content pane's scrollbar viewport (`quick-filters-layout-content [data-overlayscrollbars-viewport]`) before anything types. The scrollbar starts on idle and re-parents the editors, so keys typed across it land at the start of the text. Typing into a CodeMirror editor retypes until the editor holds exactly the text, as `editorAt(...).type` and `querySearch.apply` do: `query-builder/aggregation` TC-17 sent `c()` for `count()`.
|
||||
- A driver is a function closing over the page that returns `Locator` getters and async actions. Actions wait inside themselves (e.g. `run()` pairs the click with `waitForResponse(/query_range/)`), so specs don't.
|
||||
- `driver(name, build, dispose?)` in `drivers/kit.ts` makes it a test-scoped fixture on `authedPage`; `dispose` deletes what it seeded. `seeded(name, open, close)` makes a worker-scoped seed.
|
||||
- Read [tests/e2e/tests/dashboards/editor/query.spec.ts](../../tests/e2e/tests/dashboards/editor/query.spec.ts) and [drivers/panel-editor.ts](../../tests/e2e/drivers/panel-editor.ts) for the canonical shape.
|
||||
- **Seeds are layers on the feature's `test`.** A spec destructures the seed it needs (`alertList`, `ownedRules`, `resolvedHistory` for alerts) instead of importing a fixtures module. A new seed goes in the feature's driver directory: `seeded()` for read-only data shared by a worker, a test-scoped layer for anything a test mutates.
|
||||
- **Test titles:** `TC-NN <short description>` — matches the planner's IDs.
|
||||
- **Self-contained state.** The bootstrap creates a fresh stack with **zero** dashboards / alerts / etc. Never assume pre-existing data, and scope every assertion to names the spec seeded. Pick the scope per the Seeding table in [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md): test scope (a test-scoped layer, or `try / finally` through the driver) for mutations, worker scope (`seeded()`) for read-only data, suite `beforeAll` for a dataset only one file uses.
|
||||
- **A seed adds to org-wide settings, never replaces them.** Quick filters, org preferences and similar settings are shared by every spec on the stack, and `fullyParallel` runs those specs at once. Read the stored value and write a superset with only the missing entries, as `quickFilters.seed` does. A seed that replaced the logs filters made `query-builder/filter` TC-16 fail later on the same stack, and a restore in teardown races a parallel spec that seeded the same setting.
|
||||
- **Close a multiple combobox from its trigger, never with Escape.** A multi-select stays open after a pick, and Escape also closes the dialog or page around it; `onboarding/get-started` TC-09 landed on `/home`. `comboboxAt(...).pick` already does this.
|
||||
- **A context you open yourself drops its routes before closing.** Call `page.unrouteAll({ behavior: 'ignoreErrors' })` before `ctx.close()`, as `authedPage` does; a handler still inside `route.fetch` otherwise fails a test that already passed.
|
||||
- **Drive everything through the feature's driver** in `tests/e2e/drivers/`. A spec that reaches for `page.locator(...)` or `page.getByTestId(...)` is missing a driver method — add the method instead. `onAdminPage(browser, …)` from `drivers/kit.ts` is what suite hooks use, because `authedPage` is test-scoped and not visible to them.
|
||||
- **Seed through the kit when the UI flow is not under test.** Control-plane objects go through the feature driver (`dashboards.seed`, `alerts.seed.threshold`), which uses `apiDriver(page)` from `drivers/api.ts`; telemetry goes to the seeder. `page.request.*` does **not** carry the token, so never seed with it.
|
||||
- **Golden telemetry is pre-seeded.** `bootstrap/global.setup.ts` loads logs, traces and metrics over the last 6h (constants in `GOLDEN`, `drivers/dashboard-spec.ts`). Query within ≤ 6h and assert structure (series, rows, request payload), never exact counts.
|
||||
|
||||
@@ -50,9 +50,6 @@ Don't try to start the stack yourself — it can take ~4 minutes on a cold build
|
||||
- **Auth.** `tests/e2e/drivers/auth.ts` logs in once per worker and caches `storageState` (localStorage with `AUTH_TOKEN`). For API-driven seeding and cleanup use `apiDriver(page)` from `drivers/api.ts`, which attaches the header for you. Never re-implement login.
|
||||
- **Seeds.** Feature seeds are layers on the feature's `test`, e.g. `alertList`, `ownedRules` and `resolvedHistory` in `drivers/alerts/seeds.ts`. When a test fails on missing data, check which seed it destructures and whether it scopes to that seed's names.
|
||||
- **Timeouts.** Never add `test.slow()` to a driver: it triples the remaining budget per call and compounds in loops. Use `allowFor(floor)` from `drivers/kit.ts`. Budgets and their measurements are in `tests/e2e/docs/flake-notes.md`.
|
||||
- **A failure that shows only late in a long local run.** Run that spec's shard alone on a freshly seeded stack before fixing it, as CI does. A setting another spec changed and never restored, or golden telemetry aging past a query window, fails it only after the rest of the suite.
|
||||
- **`route.fetch: Target page, context or browser has been closed` after the test passed.** A route handler was still fetching when the context closed. Unroute with `page.unrouteAll({ behavior: 'ignoreErrors' })` before `ctx.close()` in the fixture that opened the context.
|
||||
- **Escape after a multi-select pick lands on another page.** Escape closed the dialog around the combobox too. Close it from its trigger (`comboboxAt(...).pick` does), never with another Escape.
|
||||
- **CI-only failures.** Reproduce with `STRESS=1 CI=1 pnpm test <path>` from `tests/e2e/` before calling it a product bug.
|
||||
- **Commits.** Driver fixes and spec fixes go in separate commits (see Commits in `tests/e2e/AGENTS.md`).
|
||||
- **Ant Design popovers** (sort menu, action menu) are click-toggle. The trigger element is often an inline `<svg>` with a `data-testid` — clicking it opens the popover; clicking it again closes. After selecting an option, the popover auto-closes. If a test interacts with the popover twice, wait for the menu items to be visible explicitly between toggles.
|
||||
|
||||
@@ -11,7 +11,6 @@ Examples and the harness API live in [`frontend/src/tests/README.md`](../../fron
|
||||
- **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` checks the computed style of every element it visits and is the slowest query. Always go through Testing Library (`screen`, `within`), never the DOM: no `querySelector`, `closest`, `container` or `document.body`. `signoz/no-dom-node-access` flags the DOM calls in test files; a test that checks DOM structure on purpose disables it on that line with a reason. 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: Base UI popups sit inside an element with an inline `pointer-events: none`, and the stylesheet that turns it back on for the popup never loads in jsdom, so the check would block every click on them. Never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
|
||||
- **Drop user-event's pause: `userEvent.setup(NO_DELAY_USER_EVENT)`** from `tests/test-utils`; spread it when the test needs other options. The default `delay: 0` waits a `setTimeout` after every key and click, so typing 40 characters waits 40 timer turns, each slower on a busy CI runner. With `delay: null` the actions run back to back. For a long value, click the field and `user.paste(text)` instead of typing it. Keep the default when the test checks what happens between two actions, such as a debounce per key or an update on a timer or `requestAnimationFrame` between steps: with `null` that code runs only after the whole action. Under `null` the Jest timeout can't fire mid-action, so judge a slow test by its `--verbose` time, not by whether it fails.
|
||||
- **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`.
|
||||
|
||||
@@ -10,6 +10,5 @@
|
||||
- **Use convensional commit format** for commits and PR title.
|
||||
- **Do not amend the commits once pushed.** Always create a new commit once changes are pushed to remote.
|
||||
- **Review fixes are new commits too.** A force push hides what changed from human reviewers and makes Greptile post its findings again. Bring in `main` with a merge; only a stacked branch (`gh stack`) rebases, since the stack moves as a unit.
|
||||
- **A review fix to an AI-owned file fixes its generator too.** A file with the AI-owned banner (story mocks and plays, `tests/e2e/drivers/`) is rewritten by the skill or agent that made it, so a fix made only in the file comes back on the next run. In the same PR, add the lesson to that skill or agent as a concrete case.
|
||||
- **Answer every Greptile thread.** Reply with the commit that fixes it (`Fixed in 4df6f3198d: <what changed>`) or the reason it stays, then resolve. Never resolve one with neither: Greptile withdraws a finding, and remembers it, only when told why.
|
||||
- **Leave human review threads to the author.** Fix the code they ask for, but never reply to or resolve a human reviewer's thread.
|
||||
|
||||
@@ -110,9 +110,8 @@ await expect(toggle.getAttribute('aria-checked')).toBe(before);
|
||||
|
||||
CI runs each play once, with its story's own args. Anyone can flip a control in the panel, and nothing runs the play against that value, so a play that breaks on it goes unnoticed. Write each play so it cannot.
|
||||
|
||||
Before writing the clicks, list what has to be on screen for the play's target to exist. Then walk every control the story exposes, the page's own as well as the shared ones, and return early for each value that takes something on that list away. These are the cases plays have missed:
|
||||
Before writing the clicks, list what has to be on screen for the play's target to exist, and return early when the args take it away. These are the cases plays have missed:
|
||||
|
||||
- An arg the story sets. The story sets it because the play needs what that value renders, and the panel can flip it. On the `mine` view the dashboards Created-by filter opens with a tag to remove; on the other views it opens empty and there is no × to click. Check the tag is there by parsing the route the view resolves to.
|
||||
- The controls every story has. `State` on loading or error renders no rows and no filter suggestions. `Access`, `Permissions` and `Revoked` remove rows, row actions and gated buttons, and the `editor` and `viewer` presets grant telemetry reads only, so a page gated on its own resource shows them nothing. `Check state` on loading disables every gated control, and on error an `AuthZButton` stays enabled while an `AuthZGuardContent` set to fail closed hides what it wraps. `License` and `Banner` decide the plan, so a cloud-only form is gone on the others. `Hold tooltips open` shows a label a second time, inside its tooltip.
|
||||
- A count at 0. The page can swap its whole list for an empty state, and the header, filters and column picker go with it.
|
||||
- A view, filter or invalid query that leaves no rows, even when the count is above 0.
|
||||
@@ -123,11 +122,10 @@ Before writing the clicks, list what has to be on screen for the play's target t
|
||||
|
||||
Make those checks with the page's own code instead of restating a condition. Build the rows with the builder the handler uses and the view's own filter, and check a permission with the page's own check through `accessFor(...).allows(...)`, or the role against the constant the page gates on, such as `componentPermission.action`. Export the checks from the mocks module, next to the handlers, so a handler change moves them too. The alert rules page has `listedRules`, `hasRowMenu`, `showsNoRulesPage` and `listsSavedViews`; the dashboards list has `listedDashboards`, `canList`, `canCreate` and `canUpdate`.
|
||||
|
||||
Three habits cover the rest:
|
||||
Two habits cover the rest:
|
||||
|
||||
- Use `findAllBy*` and take the first whenever the text can appear twice, such as in a tooltip or a popover title.
|
||||
- Wrap `toBeVisible` in `waitFor` for anything that fades in. A tooltip or toast found the moment it mounts is not visible yet.
|
||||
- Wait for what a click depends on before clicking. A control can do something else until a request answers: in the cloud account setup, Cancel closes the drawer outright until the agent command exists, and asks to confirm only after. Clicking Cancel straight after Generate raced the account POST on CI; find `<provider>-agent-command` first.
|
||||
|
||||
## Rules
|
||||
|
||||
|
||||
12
.github/workflows/goci.yaml
vendored
12
.github/workflows/goci.yaml
vendored
@@ -63,7 +63,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: check-semconv-generated-files
|
||||
@@ -78,7 +78,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: qemu-install
|
||||
@@ -114,7 +114,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: generate-openapi
|
||||
@@ -131,7 +131,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: generate-authz
|
||||
@@ -148,7 +148,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: generate-web-settings
|
||||
@@ -165,7 +165,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: generate-transaction-groups
|
||||
|
||||
@@ -131,10 +131,6 @@ func runGenerateAuthz(_ context.Context) error {
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceNotificationChannel).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceUser).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceFactorPassword).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceIngestionKey).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceIngestionLimit).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceAuthDomain).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceOrganization).String(): true,
|
||||
}
|
||||
|
||||
allowedTypes := map[string]bool{}
|
||||
|
||||
@@ -318,11 +318,6 @@
|
||||
"name": "redux",
|
||||
"message": "[State mgmt] redux is deprecated. Migrate to Zustand, nuqs, or react-query."
|
||||
},
|
||||
{
|
||||
"name": "@signozhq/design-tokens",
|
||||
"importNames": ["Style"],
|
||||
"message": "[bundle] Style is a large object of CSS variable strings and is not tree-shaken. Write the CSS variable directly, for example 'var(--l3-foreground)'."
|
||||
},
|
||||
{
|
||||
"name": "react-redux",
|
||||
"message": "[State mgmt] react-redux is deprecated. Migrate to Zustand, nuqs, or react-query."
|
||||
@@ -345,11 +340,6 @@
|
||||
"importNames": ["patchDashboardV2", "usePatchDashboardV2"],
|
||||
"message": "[dashboard-v2] Don't call patchDashboardV2/usePatchDashboardV2 directly — use useOptimisticPatch().patchAsync so spec edits update the react-query cache optimistically and reconcile on settle."
|
||||
},
|
||||
{
|
||||
"name": "antd/lib",
|
||||
"allowTypeImports": true,
|
||||
"message": "[bundle] antd/lib is the CommonJS root and bundles every antd component. Import from 'antd' instead."
|
||||
},
|
||||
{
|
||||
"name": "motion/react-client",
|
||||
"message": "[motion] motion/react-client is for React Server Components only. Use 'motion/react' instead — it provides the same exports and works correctly in client-side SPAs."
|
||||
|
||||
@@ -197,9 +197,7 @@ const preview: Preview = {
|
||||
['Overview', 'Authz'],
|
||||
'Service Accounts',
|
||||
'Ingestion',
|
||||
['Overview', 'Authz'],
|
||||
'Single Sign-on',
|
||||
['Overview', 'Authz'],
|
||||
'Keyboard Shortcuts',
|
||||
],
|
||||
'Auth',
|
||||
|
||||
@@ -28,6 +28,4 @@ until curl -sf http://127.0.0.1:6006/index.json >/dev/null 2>&1; do
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# The first story of a heavy page compiles it on the cold dev server inside its
|
||||
# own test, which outlasts 30s on a loaded runner.
|
||||
pnpm exec test-storybook --ci --maxWorkers=2 --testTimeout 60000 "$@"
|
||||
pnpm exec test-storybook --ci --maxWorkers=2 --testTimeout 30000 "$@"
|
||||
|
||||
@@ -175,8 +175,8 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
pathname === ROUTES.SETTINGS ||
|
||||
pathname === ROUTES.BILLING ||
|
||||
pathname === ROUTES.MEMBERS_SETTINGS ||
|
||||
pathname === ROUTES.ORG_SETTINGS ||
|
||||
(isAdmin && pathname === ROUTES.MY_SETTINGS);
|
||||
(isAdmin &&
|
||||
(pathname === ROUTES.ORG_SETTINGS || pathname === ROUTES.MY_SETTINGS));
|
||||
|
||||
if (
|
||||
pathname !== ROUTES.WORKSPACE_LOCKED &&
|
||||
|
||||
@@ -808,7 +808,7 @@ describe('PrivateRoute', () => {
|
||||
assertStaysOnRoute(ROUTES.BILLING);
|
||||
});
|
||||
|
||||
it('should allow VIEWER to access org-settings when workspace is blocked', () => {
|
||||
it('should redirect VIEWER to workspace locked when trying to access org-settings', async () => {
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.ORG_SETTINGS,
|
||||
appContext: {
|
||||
@@ -821,7 +821,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertStaysOnRoute(ROUTES.ORG_SETTINGS);
|
||||
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
|
||||
});
|
||||
|
||||
it('should allow VIEWER to access members settings when workspace is blocked', () => {
|
||||
@@ -1707,7 +1707,6 @@ describe('PrivateRoute', () => {
|
||||
// Everything under /settings resolves to the non-exact SETTINGS route
|
||||
SETTINGS: { path: ROUTES.SETTINGS, deniedRoles: DENIED_ROLES },
|
||||
MY_SETTINGS: { path: ROUTES.MY_SETTINGS, deniedRoles: DENIED_ROLES },
|
||||
ORG_SETTINGS: { path: ROUTES.ORG_SETTINGS, deniedRoles: DENIED_ROLES },
|
||||
ROLES_SETTINGS: { path: ROUTES.ROLES_SETTINGS, deniedRoles: DENIED_ROLES },
|
||||
ROLE_CREATE: { path: ROUTES.ROLE_CREATE, deniedRoles: DENIED_ROLES },
|
||||
ROLE_DETAILS: {
|
||||
|
||||
@@ -64,7 +64,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
initialRowCount={2}
|
||||
initialRowCount={3}
|
||||
renderFooter={({ submit }): JSX.Element => (
|
||||
<button data-testid="submit-btn" onClick={submit}>
|
||||
Submit
|
||||
@@ -77,11 +77,13 @@ describe('InviteMembers - Submission', () => {
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
await pickRole(user, 1, 'role-editor');
|
||||
await enterInviteEmail(user, 2, 'charlie@signoz.io');
|
||||
await pickRole(user, 2, 'role-admin');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls).toHaveLength(3);
|
||||
});
|
||||
|
||||
expect(calls[0]).toMatchObject({
|
||||
@@ -92,6 +94,10 @@ describe('InviteMembers - Submission', () => {
|
||||
email: 'bob@signoz.io',
|
||||
userRoles: [{ id: 'role-editor' }],
|
||||
});
|
||||
expect(calls[2]).toMatchObject({
|
||||
email: 'charlie@signoz.io',
|
||||
userRoles: [{ id: 'role-admin' }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -14,14 +14,14 @@ export type CreatedByProps =
|
||||
creatorOptions: CreatorOption[];
|
||||
createdBy: string[];
|
||||
onCreatedByChange: (emails: string[]) => void;
|
||||
// Run a Created-by change made with the dropdown closed.
|
||||
onCreatedByCommit: (emails: string[]) => void;
|
||||
// Clear all Created-by selections and run immediately.
|
||||
onClearCreatedBy: () => void;
|
||||
}
|
||||
| {
|
||||
creatorOptions?: undefined;
|
||||
createdBy?: undefined;
|
||||
onCreatedByChange?: undefined;
|
||||
onCreatedByCommit?: undefined;
|
||||
onClearCreatedBy?: undefined;
|
||||
};
|
||||
|
||||
type Props = CreatedByProps & {
|
||||
@@ -61,8 +61,8 @@ function FilterChips(props: Props): JSX.Element {
|
||||
placeholder="Created by"
|
||||
testId={`${testIdPrefix}-filter-created-by`}
|
||||
disabled={disabled}
|
||||
onClear={props.onClearCreatedBy}
|
||||
onChange={props.onCreatedByChange}
|
||||
onCommit={props.onCreatedByCommit}
|
||||
onDropdownVisibleChange={runOnClose}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -81,7 +81,7 @@ function FilterZone({
|
||||
applyDraft,
|
||||
handleCreatedByChange,
|
||||
handleUpdatedChange,
|
||||
handleCreatedByCommit,
|
||||
handleClearCreatedBy,
|
||||
handleClear,
|
||||
} = useFilterZoneDraft({
|
||||
query,
|
||||
@@ -96,7 +96,7 @@ function FilterZone({
|
||||
creatorOptions,
|
||||
createdBy: reflected.createdBy,
|
||||
onCreatedByChange: handleCreatedByChange,
|
||||
onCreatedByCommit: handleCreatedByCommit,
|
||||
onClearCreatedBy: handleClearCreatedBy,
|
||||
}
|
||||
: {};
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { ConfigProvider, Select } from 'antd';
|
||||
import { Checkbox } from '@signozhq/ui/checkbox';
|
||||
import cx from 'classnames';
|
||||
@@ -21,9 +20,7 @@ interface Props {
|
||||
placeholder: string;
|
||||
testId: string;
|
||||
onChange: (values: string[]) => void;
|
||||
// A change made with the dropdown closed (a tag's ×, the clear icon) has no
|
||||
// close to run on, so it is committed here instead of staged via onChange.
|
||||
onCommit: (values: string[]) => void;
|
||||
onClear?: () => void;
|
||||
onDropdownVisibleChange?: (open: boolean) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
@@ -34,31 +31,10 @@ function MultiSelectFilter({
|
||||
placeholder,
|
||||
testId,
|
||||
onChange,
|
||||
onCommit,
|
||||
onClear,
|
||||
onDropdownVisibleChange,
|
||||
disabled = false,
|
||||
}: Props): JSX.Element {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(next: string[]): void => {
|
||||
if (!isOpen) {
|
||||
onCommit(next);
|
||||
return;
|
||||
}
|
||||
onChange(next);
|
||||
},
|
||||
[isOpen, onChange, onCommit],
|
||||
);
|
||||
|
||||
const handleDropdownVisibleChange = useCallback(
|
||||
(nextOpen: boolean): void => {
|
||||
setIsOpen(nextOpen);
|
||||
onDropdownVisibleChange?.(nextOpen);
|
||||
},
|
||||
[onDropdownVisibleChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<ConfigProvider theme={CHECKBOX_SELECT_THEME}>
|
||||
<Select
|
||||
@@ -75,6 +51,7 @@ function MultiSelectFilter({
|
||||
menuItemSelectedIcon={null}
|
||||
data-testid={testId}
|
||||
disabled={disabled}
|
||||
onClear={onClear}
|
||||
optionRender={(option): JSX.Element => (
|
||||
<div
|
||||
className={styles.checkOption}
|
||||
@@ -89,8 +66,8 @@ function MultiSelectFilter({
|
||||
<span className={styles.checkOptionLabel}>{option.label}</span>
|
||||
</div>
|
||||
)}
|
||||
onChange={(next): void => handleChange(next as string[])}
|
||||
onDropdownVisibleChange={handleDropdownVisibleChange}
|
||||
onChange={(next): void => onChange(next as string[])}
|
||||
onDropdownVisibleChange={onDropdownVisibleChange}
|
||||
/>
|
||||
</ConfigProvider>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, within } from 'tests/test-utils';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import type { DslGrammar } from '../../dsl/types';
|
||||
import FilterZone from '../FilterZone';
|
||||
@@ -48,33 +47,4 @@ describe('FilterZone', () => {
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('things-filter-updated')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('runs the query when a creator is removed with the dropdown closed', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onQueryChange = jest.fn();
|
||||
render(
|
||||
<FilterZone
|
||||
query="created_by = 'ada@example.com'"
|
||||
grammar={grammar}
|
||||
testIdPrefix="things"
|
||||
creatorOptions={[{ email: 'ada@example.com', label: 'Ada' }]}
|
||||
source={source}
|
||||
onQueryChange={onQueryChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
// antd renders the tag's × aria-hidden.
|
||||
await user.click(
|
||||
within(screen.getByTitle('Ada')).getByRole('img', {
|
||||
name: 'close',
|
||||
hidden: true,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
within(screen.getByTestId('things-filter-created-by')).getByRole('combobox'),
|
||||
).toHaveAttribute('aria-expanded', 'false');
|
||||
|
||||
expect(onQueryChange).toHaveBeenCalledWith('');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -106,20 +106,12 @@ describe('useFilterZoneDraft', () => {
|
||||
"created_by = 'a@x.io' AND name = 'x'",
|
||||
);
|
||||
|
||||
act(() => result.current.handleCreatedByCommit([]));
|
||||
act(() => result.current.handleClearCreatedBy());
|
||||
|
||||
expect(result.current.draft).toBe("name = 'x'");
|
||||
expect(onQueryChange).toHaveBeenCalledWith("name = 'x'");
|
||||
});
|
||||
|
||||
it('runs the remaining creators when one is removed', () => {
|
||||
const { result, onQueryChange } = setup("created_by IN ['a@x.io', 'b@x.io']");
|
||||
|
||||
act(() => result.current.handleCreatedByCommit(['b@x.io']));
|
||||
|
||||
expect(onQueryChange).toHaveBeenCalledWith("created_by = 'b@x.io'");
|
||||
});
|
||||
|
||||
it('empties the draft and runs the empty query on clear', () => {
|
||||
const { result, onQueryChange, onCleared, onClearAll } = setup();
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ interface FilterZoneDraft {
|
||||
applyDraft: (next: string) => void;
|
||||
handleCreatedByChange: (emails: string[]) => void;
|
||||
handleUpdatedChange: (window: UpdatedWindow) => void;
|
||||
handleCreatedByCommit: (emails: string[]) => void;
|
||||
handleClearCreatedBy: () => void;
|
||||
handleClear: () => void;
|
||||
}
|
||||
|
||||
@@ -97,14 +97,10 @@ export function useFilterZoneDraft({
|
||||
[draft, applyDraft, onFilterApplied],
|
||||
);
|
||||
|
||||
// Runs a Created-by change made with its dropdown closed.
|
||||
const handleCreatedByCommit = useCallback(
|
||||
(emails: string[]): void => {
|
||||
onFilterApplied?.('createdBy', { valueCount: emails.length });
|
||||
applyDraft(spliceClause(draft, 'created_by', createdByClause(emails)));
|
||||
},
|
||||
[draft, applyDraft, onFilterApplied],
|
||||
);
|
||||
// Clear-all on the Created-by select removes its clause and runs immediately.
|
||||
const handleClearCreatedBy = useCallback((): void => {
|
||||
applyDraft(spliceClause(draft, 'created_by', null));
|
||||
}, [draft, applyDraft]);
|
||||
|
||||
// Clear resets the draft and runs immediately (empty query).
|
||||
const handleClear = useCallback((): void => {
|
||||
@@ -126,7 +122,7 @@ export function useFilterZoneDraft({
|
||||
applyDraft,
|
||||
handleCreatedByChange,
|
||||
handleUpdatedChange,
|
||||
handleCreatedByCommit,
|
||||
handleClearCreatedBy,
|
||||
handleClear,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,7 +24,6 @@ interface Props {
|
||||
confirmLabel: string;
|
||||
/** Name the input holds each time the dialog opens. */
|
||||
initialName?: string;
|
||||
placeholder: string;
|
||||
testIdPrefix: string;
|
||||
}
|
||||
|
||||
@@ -36,7 +35,6 @@ function ViewNameDialog({
|
||||
description,
|
||||
confirmLabel,
|
||||
initialName = '',
|
||||
placeholder,
|
||||
testIdPrefix,
|
||||
}: Props): JSX.Element {
|
||||
const [name, setName] = useState(initialName);
|
||||
@@ -118,7 +116,7 @@ function ViewNameDialog({
|
||||
id={inputId}
|
||||
value={name}
|
||||
maxLength={VIEW_NAME_MAX_LENGTH}
|
||||
placeholder={placeholder}
|
||||
placeholder="e.g. Prod alerts"
|
||||
autoComplete="off"
|
||||
testId={`${testIdPrefix}-name`}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>): void =>
|
||||
|
||||
@@ -39,7 +39,6 @@ interface Props {
|
||||
saveTestIdPrefix?: string;
|
||||
renameTestIdPrefix?: string;
|
||||
customSectionLabel?: string;
|
||||
viewNamePlaceholder?: string;
|
||||
deleteDescription?: string;
|
||||
/** Wraps the rail body, e.g. in an authz guard. */
|
||||
guard?: (content: ReactElement) => ReactElement;
|
||||
@@ -68,7 +67,6 @@ function ViewsRail({
|
||||
saveTestIdPrefix = 'save-view',
|
||||
renameTestIdPrefix = 'rename-view',
|
||||
customSectionLabel = 'My views',
|
||||
viewNamePlaceholder = 'e.g. Production',
|
||||
deleteDescription = 'This removes the saved view.',
|
||||
guard,
|
||||
onViewSaved,
|
||||
@@ -289,7 +287,6 @@ function ViewsRail({
|
||||
title="Save as view"
|
||||
description="Save the current filters as a view you can return to."
|
||||
confirmLabel="Save view"
|
||||
placeholder={viewNamePlaceholder}
|
||||
testIdPrefix={saveTestIdPrefix}
|
||||
/>
|
||||
<ViewNameDialog
|
||||
@@ -300,7 +297,6 @@ function ViewsRail({
|
||||
description="The view keeps its filters under the new name."
|
||||
confirmLabel="Rename"
|
||||
initialName={renameTarget?.label}
|
||||
placeholder={viewNamePlaceholder}
|
||||
testIdPrefix={renameTestIdPrefix}
|
||||
/>
|
||||
{contextHolder}
|
||||
|
||||
@@ -163,22 +163,6 @@ describe('ViewsRail', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the list placeholder in the save and rename dialogs', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderRail({ viewNamePlaceholder: 'e.g. Prod things' });
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-save-trigger`));
|
||||
await expect(
|
||||
screen.findByTestId('save-view-name-field'),
|
||||
).resolves.toHaveAttribute('placeholder', 'e.g. Prod things');
|
||||
await user.click(screen.getByTestId('save-view-cancel'));
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-rename-view-1`));
|
||||
await expect(
|
||||
screen.findByTestId('rename-view-name-field'),
|
||||
).resolves.toHaveAttribute('placeholder', 'e.g. Prod things');
|
||||
});
|
||||
|
||||
it('opens the save dialog empty again after a cancel', async () => {
|
||||
const user = userEvent.setup();
|
||||
const props = renderRail({ isModified: true });
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
autocompletion,
|
||||
closeCompletion,
|
||||
@@ -16,7 +16,6 @@ import CodeMirror, { EditorView, keymap } from '@uiw/react-codemirror';
|
||||
import { Button } from 'antd';
|
||||
import { Having } from 'api/v5/v5';
|
||||
import { useQueryBuilderV2Context } from 'components/QueryBuilderV2/QueryBuilderV2Context';
|
||||
import { useEditorDraft } from 'components/QueryBuilderV2/QueryV2/useEditorDraft';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { ChevronUp } from '@signozhq/icons';
|
||||
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
@@ -100,20 +99,28 @@ function HavingFilter({
|
||||
const { getAggregationOptions } = useQueryBuilderV2Context();
|
||||
const aggregationOptions = getAggregationOptions(queryData.queryName);
|
||||
const having = queryData?.having as Having;
|
||||
const { editorRef, editorProps } = useEditorDraft(
|
||||
having?.expression || '',
|
||||
onChange,
|
||||
);
|
||||
const [input, setInput] = useState(having?.expression || '');
|
||||
|
||||
useEffect(() => {
|
||||
setInput(having?.expression || '');
|
||||
}, [having?.expression]);
|
||||
|
||||
const [isFocused, setIsFocused] = useState(false);
|
||||
|
||||
const editorRef = useRef<EditorView | null>(null);
|
||||
|
||||
const [options, setOptions] = useState<{ label: string; value: string }[]>([]);
|
||||
|
||||
const handleChange = (value: string): void => {
|
||||
setInput(value);
|
||||
onChange(value);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (isFocused && editorRef.current && options.length > 0) {
|
||||
startCompletion(editorRef.current);
|
||||
}
|
||||
}, [editorRef, isFocused, options]);
|
||||
}, [isFocused, options]);
|
||||
|
||||
// Update options when aggregation options change
|
||||
useEffect(() => {
|
||||
@@ -322,7 +329,8 @@ function HavingFilter({
|
||||
<div className="having-filter-container">
|
||||
<div className="having-filter-select-container">
|
||||
<CodeMirror
|
||||
{...editorProps}
|
||||
value={input}
|
||||
onChange={handleChange}
|
||||
theme={isDarkMode ? copilot : githubLight}
|
||||
data-testid="having-editor"
|
||||
className="having-filter-select-editor"
|
||||
@@ -346,6 +354,9 @@ function HavingFilter({
|
||||
autocompletion: true,
|
||||
completionKeymap: true,
|
||||
}}
|
||||
onCreateEditor={(view: EditorView): void => {
|
||||
editorRef.current = view;
|
||||
}}
|
||||
onFocus={(): void => {
|
||||
setIsFocused(true);
|
||||
if (editorRef.current) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/* eslint-disable import/no-extraneous-dependencies */
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
autocompletion,
|
||||
closeCompletion,
|
||||
@@ -36,7 +36,6 @@ import {
|
||||
} from 'types/common/queryBuilder';
|
||||
|
||||
import { useQueryBuilderV2Context } from '../../QueryBuilderV2Context';
|
||||
import { useEditorDraft } from '../useEditorDraft';
|
||||
|
||||
import './QueryAggregation.styles.scss';
|
||||
|
||||
@@ -176,17 +175,20 @@ function QueryAggregationSelect({
|
||||
[],
|
||||
);
|
||||
|
||||
const {
|
||||
draft: input,
|
||||
editorRef,
|
||||
editorProps,
|
||||
} = useEditorDraft(formatAggregations(queryData?.aggregations), onChange);
|
||||
const [input, setInput] = useState(
|
||||
formatAggregations(queryData?.aggregations),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setInput(formatAggregations(queryData?.aggregations));
|
||||
}, [queryData?.aggregations, formatAggregations]);
|
||||
|
||||
const [cursorPos, setCursorPos] = useState(0);
|
||||
const [functionArgPairs, setFunctionArgPairs] = useState<
|
||||
{ func: string; arg: string }[]
|
||||
>([]);
|
||||
const [validationError, setValidationError] = useState<string | null>(null);
|
||||
const editorRef = useRef<EditorView | null>(null);
|
||||
const [isFocused, setIsFocused] = useState(false);
|
||||
|
||||
// Get valid function names (lowercase)
|
||||
@@ -202,7 +204,7 @@ function QueryAggregationSelect({
|
||||
startCompletion(editorRef.current);
|
||||
}
|
||||
});
|
||||
}, [editorRef]);
|
||||
}, []);
|
||||
|
||||
// Update cursor position on every editor update
|
||||
const handleUpdate = (update: { view: EditorView }): void => {
|
||||
@@ -599,7 +601,11 @@ function QueryAggregationSelect({
|
||||
return (
|
||||
<div className="query-aggregation-select-container">
|
||||
<CodeMirror
|
||||
{...editorProps}
|
||||
value={input}
|
||||
onChange={(value): void => {
|
||||
setInput(value);
|
||||
onChange?.(value);
|
||||
}}
|
||||
data-testid="query-aggregation-editor"
|
||||
className={`query-aggregation-select-editor ${
|
||||
validationError ? 'error' : ''
|
||||
@@ -631,6 +637,9 @@ function QueryAggregationSelect({
|
||||
completionKeymap: true,
|
||||
}}
|
||||
onUpdate={handleUpdate}
|
||||
onCreateEditor={(view: EditorView): void => {
|
||||
editorRef.current = view;
|
||||
}}
|
||||
onFocus={(): void => {
|
||||
setIsFocused(true);
|
||||
safeStartCompletion();
|
||||
|
||||
@@ -8,14 +8,7 @@ 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,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import DistributionFieldSelect from '../DistributionFieldSelect';
|
||||
@@ -81,7 +74,7 @@ describe('DistributionFieldSelect', () => {
|
||||
});
|
||||
|
||||
it('picks a numeric field, keeping its context', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={onChange} />,
|
||||
@@ -104,7 +97,7 @@ describe('DistributionFieldSelect', () => {
|
||||
});
|
||||
|
||||
it('replaces the saved field with the newly picked one', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
|
||||
render(
|
||||
<DistributionFieldSelect
|
||||
@@ -126,7 +119,7 @@ describe('DistributionFieldSelect', () => {
|
||||
});
|
||||
|
||||
it('only offers listed fields: typed text is a filter, not a value', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
|
||||
);
|
||||
|
||||
@@ -105,8 +105,6 @@ const stopEventsExtension = EditorView.domEventHandlers({
|
||||
},
|
||||
});
|
||||
|
||||
const EDITOR_BASIC_SETUP = { lineNumbers: false };
|
||||
|
||||
interface QuerySearchProps {
|
||||
placeholder?: string;
|
||||
onChange: (value: string) => void;
|
||||
@@ -715,17 +713,14 @@ function QuerySearch({
|
||||
}
|
||||
}, []);
|
||||
|
||||
const onChangeRef = useRef(onChange);
|
||||
onChangeRef.current = onChange;
|
||||
|
||||
const handleChange = useCallback((value: string): void => {
|
||||
const handleChange = (value: string): void => {
|
||||
if (isProgrammaticChangeRef.current) {
|
||||
isProgrammaticChangeRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
onChangeRef.current(value);
|
||||
}, []);
|
||||
onChange(value);
|
||||
};
|
||||
|
||||
const handleBlur = (): void => {
|
||||
const currentExpression = getCurrentExpression();
|
||||
@@ -1479,65 +1474,6 @@ function QuerySearch({
|
||||
};
|
||||
}
|
||||
|
||||
const completionSourceRef = useRef(combinedSuggestions);
|
||||
completionSourceRef.current = combinedSuggestions;
|
||||
const handleRunRef = useRef(handleRun);
|
||||
handleRunRef.current = handleRun;
|
||||
|
||||
// Built once: new extensions reconfigure CodeMirror, which closes the open suggestions.
|
||||
const editorExtensions = useMemo(
|
||||
() => [
|
||||
autocompletion({
|
||||
override: [
|
||||
(context: CompletionContext): CompletionResult | null =>
|
||||
completionSourceRef.current(context),
|
||||
],
|
||||
defaultKeymap: true,
|
||||
closeOnBlur: true,
|
||||
activateOnTyping: true,
|
||||
maxRenderedOptions: 50,
|
||||
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
|
||||
}),
|
||||
javascript({ jsx: false, typescript: false }),
|
||||
EditorView.lineWrapping,
|
||||
stopEventsExtension,
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
...completionKeymap,
|
||||
{
|
||||
key: 'Escape',
|
||||
run: closeCompletion,
|
||||
},
|
||||
{
|
||||
key: 'Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Enter to add new line
|
||||
// and instead run a custom action
|
||||
run: (): boolean => true,
|
||||
},
|
||||
{
|
||||
key: 'Mod-Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Mod-Enter to add new line
|
||||
// and instead run a custom action
|
||||
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
|
||||
run: (): boolean => {
|
||||
handleRunRef.current();
|
||||
return true;
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'Shift-Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Shift-Enter to add new line
|
||||
run: (): boolean => true,
|
||||
},
|
||||
]),
|
||||
),
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
// Effect to handle focus state and trigger suggestions
|
||||
useEffect(() => {
|
||||
const clearTimeout = toggleSuggestions(10);
|
||||
@@ -1714,9 +1650,56 @@ function QuerySearch({
|
||||
hasErrors: validation.errors.length > 0,
|
||||
hasInitialExpression: isScopedFilter && !showScopeChip,
|
||||
})}
|
||||
extensions={editorExtensions}
|
||||
extensions={[
|
||||
autocompletion({
|
||||
override: [combinedSuggestions],
|
||||
defaultKeymap: true,
|
||||
closeOnBlur: true,
|
||||
activateOnTyping: true,
|
||||
maxRenderedOptions: 50,
|
||||
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
|
||||
}),
|
||||
javascript({ jsx: false, typescript: false }),
|
||||
EditorView.lineWrapping,
|
||||
stopEventsExtension,
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
...completionKeymap,
|
||||
{
|
||||
key: 'Escape',
|
||||
run: closeCompletion,
|
||||
},
|
||||
{
|
||||
key: 'Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Enter to add new line
|
||||
// and instead run a custom action
|
||||
run: (): boolean => true,
|
||||
},
|
||||
{
|
||||
key: 'Mod-Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Mod-Enter to add new line
|
||||
// and instead run a custom action
|
||||
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
|
||||
run: (): boolean => {
|
||||
handleRun();
|
||||
return true;
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'Shift-Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Shift-Enter to add new line
|
||||
run: (): boolean => true,
|
||||
},
|
||||
]),
|
||||
),
|
||||
]}
|
||||
placeholder={placeholder}
|
||||
basicSetup={EDITOR_BASIC_SETUP}
|
||||
basicSetup={{
|
||||
lineNumbers: false,
|
||||
}}
|
||||
onFocus={(): void => {
|
||||
setIsFocused(true);
|
||||
}}
|
||||
|
||||
@@ -192,8 +192,6 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
release();
|
||||
// Outlasts the 10 ms timer QuerySearch uses to reopen suggestions.
|
||||
await act(() => new Promise((resolve) => setTimeout(resolve, 50)));
|
||||
// Outlasts the 100 ms CodeMirror waits before it queries suggestions again.
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
|
||||
expect(screen.getByText('payment-service')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
import { EditorView } from '@uiw/react-codemirror';
|
||||
import { act, renderHook } from 'tests/test-utils';
|
||||
|
||||
import { useEditorDraft } from '../useEditorDraft';
|
||||
|
||||
function setup(
|
||||
external = '',
|
||||
onEdit?: (value: string) => void,
|
||||
): {
|
||||
result: { current: ReturnType<typeof useEditorDraft> };
|
||||
rerender: (props: { external: string }) => void;
|
||||
} {
|
||||
return renderHook(
|
||||
({ external: value }: { external: string }) => useEditorDraft(value, onEdit),
|
||||
{ initialProps: { external } },
|
||||
);
|
||||
}
|
||||
|
||||
// Reports document changes to `onChange` the way `@uiw/react-codemirror` does.
|
||||
function attachEditor(
|
||||
result: { current: ReturnType<typeof useEditorDraft> },
|
||||
doc: string,
|
||||
): EditorView {
|
||||
const view = new EditorView({
|
||||
doc,
|
||||
extensions: EditorView.updateListener.of((update) => {
|
||||
if (update.docChanged) {
|
||||
result.current.editorProps.onChange(update.state.doc.toString());
|
||||
}
|
||||
}),
|
||||
});
|
||||
act(() => result.current.editorProps.onCreateEditor(view));
|
||||
return view;
|
||||
}
|
||||
|
||||
function type(view: EditorView, text: string): void {
|
||||
act(() => {
|
||||
view.dispatch({ changes: { from: view.state.doc.length, insert: text } });
|
||||
});
|
||||
}
|
||||
|
||||
describe('useEditorDraft', () => {
|
||||
it('keeps newer typing when an older edit comes back', () => {
|
||||
const { result, rerender } = setup();
|
||||
|
||||
act(() => result.current.editorProps.onChange('count() > 1'));
|
||||
act(() => result.current.editorProps.onChange('count() > 10'));
|
||||
rerender({ external: 'count() > 1' });
|
||||
|
||||
expect(result.current.draft).toBe('count() > 10');
|
||||
});
|
||||
|
||||
it('takes a value set outside the editor', () => {
|
||||
const { result, rerender } = setup('count() > 1');
|
||||
|
||||
act(() => result.current.editorProps.onChange('count() > 10'));
|
||||
rerender({ external: 'count() > 10' });
|
||||
rerender({ external: 'count() < 5' });
|
||||
|
||||
expect(result.current.draft).toBe('count() < 5');
|
||||
});
|
||||
|
||||
it('takes an outside value equal to an edit older than the last echo', () => {
|
||||
const { result, rerender } = setup();
|
||||
|
||||
act(() => result.current.editorProps.onChange('a'));
|
||||
act(() => result.current.editorProps.onChange('ab'));
|
||||
rerender({ external: 'ab' });
|
||||
rerender({ external: 'a' });
|
||||
|
||||
expect(result.current.draft).toBe('a');
|
||||
});
|
||||
|
||||
it('keeps the editor value at the first text while the user types', () => {
|
||||
const { result, rerender } = setup('count()');
|
||||
|
||||
act(() => result.current.editorProps.onChange('count() >'));
|
||||
rerender({ external: 'count() >' });
|
||||
act(() => result.current.editorProps.onChange('count() > 1'));
|
||||
|
||||
expect(result.current.editorProps.value).toBe('count()');
|
||||
});
|
||||
|
||||
it('passes each edit on', () => {
|
||||
const onEdit = jest.fn();
|
||||
const { result } = setup('', onEdit);
|
||||
|
||||
act(() => result.current.editorProps.onChange('count()'));
|
||||
|
||||
expect(onEdit).toHaveBeenCalledWith('count()');
|
||||
});
|
||||
|
||||
it('writes an outside change into the editor without passing it on', () => {
|
||||
const onEdit = jest.fn();
|
||||
const { result, rerender } = setup('count() > 1', onEdit);
|
||||
const view = attachEditor(result, 'count() > 1');
|
||||
|
||||
rerender({ external: 'count() < 5' });
|
||||
|
||||
expect(view.state.doc.toString()).toBe('count() < 5');
|
||||
expect(view.state.selection.main.head).toBe('count() < 5'.length);
|
||||
expect(onEdit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('leaves the editor alone when an older edit comes back', () => {
|
||||
const { result, rerender } = setup();
|
||||
const view = attachEditor(result, '');
|
||||
|
||||
type(view, 'count_');
|
||||
type(view, 'di');
|
||||
rerender({ external: 'count_' });
|
||||
|
||||
expect(view.state.doc.toString()).toBe('count_di');
|
||||
});
|
||||
});
|
||||
@@ -1,109 +0,0 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { MutableRefObject } from 'react';
|
||||
import type { EditorView } from '@uiw/react-codemirror';
|
||||
|
||||
// Bounds the history when no parent ever echoes the edits back.
|
||||
const MAX_PENDING_ECHOES = 200;
|
||||
|
||||
interface EditorDraft {
|
||||
/** The editor's current text. */
|
||||
draft: string;
|
||||
editorRef: MutableRefObject<EditorView | null>;
|
||||
/** Spread on `CodeMirror`. */
|
||||
editorProps: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
onCreateEditor: (view: EditorView) => void;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Text of a query editor whose edits round-trip through query state. Each
|
||||
* edit comes back as `external` one or more renders later; writing an older
|
||||
* copy into the editor would drop the keys typed since and move the caret to
|
||||
* the start. Values the editor sent are ignored when they come back, and any
|
||||
* other `external` value replaces the text.
|
||||
*
|
||||
* The editor owns its text, so `editorProps.value` never changes after the
|
||||
* first render: `@uiw/react-codemirror` writes a changed `value` over the
|
||||
* document in a passive effect, which on a busy page runs after newer keys and
|
||||
* drops them. Outside changes are written through the view instead.
|
||||
*/
|
||||
export function useEditorDraft(
|
||||
external: string,
|
||||
onEdit?: (value: string) => void,
|
||||
): EditorDraft {
|
||||
const [draft, setDraft] = useState(external);
|
||||
const [initialValue] = useState(external);
|
||||
const editorRef = useRef<EditorView | null>(null);
|
||||
const pendingEchoes = useRef<string[]>([]);
|
||||
const writingOutsideChange = useRef(false);
|
||||
|
||||
const writeIntoEditor = useCallback((view: EditorView, text: string): void => {
|
||||
if (view.state.doc.toString() === text) {
|
||||
return;
|
||||
}
|
||||
writingOutsideChange.current = true;
|
||||
try {
|
||||
view.dispatch({
|
||||
changes: { from: 0, to: view.state.doc.length, insert: text },
|
||||
selection: { anchor: text.length },
|
||||
});
|
||||
} finally {
|
||||
writingOutsideChange.current = false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Echoes arrive in order, and a batched render can skip some, so a match
|
||||
// also drops every older entry: they can no longer come back.
|
||||
//
|
||||
// type "c", "co", "cou" pending [c, co, cou] draft "cou"
|
||||
// echo "c" pending [co, cou] ignored, draft stays "cou"
|
||||
// echo "cou" (skipped co) pending [] ignored
|
||||
// "count() > 5" from a saved view, never sent: applied
|
||||
//
|
||||
// Keeping the older entries would also swallow an outside change that
|
||||
// happens to equal one of them: after typing "a", "ab", a saved view with
|
||||
// "a" would be taken for an echo.
|
||||
useEffect(() => {
|
||||
const index = pendingEchoes.current.indexOf(external);
|
||||
if (index === -1) {
|
||||
pendingEchoes.current = [];
|
||||
setDraft(external);
|
||||
if (editorRef.current) {
|
||||
writeIntoEditor(editorRef.current, external);
|
||||
}
|
||||
return;
|
||||
}
|
||||
pendingEchoes.current = pendingEchoes.current.slice(index + 1);
|
||||
}, [external, writeIntoEditor]);
|
||||
|
||||
const onChange = useCallback(
|
||||
(value: string): void => {
|
||||
if (writingOutsideChange.current) {
|
||||
return;
|
||||
}
|
||||
pendingEchoes.current.push(value);
|
||||
if (pendingEchoes.current.length > MAX_PENDING_ECHOES) {
|
||||
pendingEchoes.current.shift();
|
||||
}
|
||||
setDraft(value);
|
||||
onEdit?.(value);
|
||||
},
|
||||
[onEdit],
|
||||
);
|
||||
|
||||
const onCreateEditor = useCallback(
|
||||
(view: EditorView): void => {
|
||||
editorRef.current = view;
|
||||
writeIntoEditor(view, draft);
|
||||
},
|
||||
[draft, writeIntoEditor],
|
||||
);
|
||||
|
||||
return {
|
||||
draft,
|
||||
editorRef,
|
||||
editorProps: { value: initialValue, onChange, onCreateEditor },
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { ChevronDown, ChevronRight, Undo2 } from '@signozhq/icons';
|
||||
|
||||
@@ -20,6 +22,31 @@ export function CheckboxFilterV2Header({
|
||||
onToggleOpen,
|
||||
onClear,
|
||||
}: CheckboxFilterHeaderProps): JSX.Element {
|
||||
const [isTitleTruncated, setIsTitleTruncated] = useState(false);
|
||||
|
||||
const measureTitle = (el: HTMLElement | null): void => {
|
||||
if (el) {
|
||||
setIsTitleTruncated(el.scrollWidth > el.clientWidth);
|
||||
}
|
||||
};
|
||||
|
||||
const titleText = (
|
||||
<Typography
|
||||
ref={measureTitle}
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
display="inline-block"
|
||||
minWidth={0}
|
||||
textOverflow="ellipsis"
|
||||
textTransform="capitalize"
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
);
|
||||
|
||||
return (
|
||||
<section
|
||||
role="button"
|
||||
@@ -40,19 +67,7 @@ export function CheckboxFilterV2Header({
|
||||
) : (
|
||||
<ChevronRight size={13} cursor="pointer" />
|
||||
)}
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
display="inline-block"
|
||||
minWidth={0}
|
||||
textOverflow="ellipsis"
|
||||
textTransform="capitalize"
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
<Tooltip title={isTitleTruncated ? title : undefined}>{titleText}</Tooltip>
|
||||
</section>
|
||||
{isOpen && canReset && (
|
||||
<section className={styles.rightAction}>
|
||||
|
||||
@@ -120,4 +120,43 @@ describe('CheckboxFilterV2Header', () => {
|
||||
expect(onToggleOpen).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('title tooltip', () => {
|
||||
// jsdom has no layout, so truncation is simulated at the prototype level
|
||||
// before mount (the component measures in a layout effect).
|
||||
function mockTitleWidths(scrollWidth: number, clientWidth: number): void {
|
||||
jest
|
||||
.spyOn(HTMLElement.prototype, 'scrollWidth', 'get')
|
||||
.mockReturnValue(scrollWidth);
|
||||
jest
|
||||
.spyOn(HTMLElement.prototype, 'clientWidth', 'get')
|
||||
.mockReturnValue(clientWidth);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('shows the full name on hover when the title is truncated', async () => {
|
||||
mockTitleWidths(200, 100);
|
||||
const user = userEvent.setup();
|
||||
render(<CheckboxFilterV2Header {...defaultProps} />);
|
||||
|
||||
await user.hover(screen.getByText(defaultProps.title));
|
||||
|
||||
await expect(screen.findByRole('tooltip')).resolves.toHaveTextContent(
|
||||
defaultProps.title,
|
||||
);
|
||||
});
|
||||
|
||||
it('shows no tooltip when the title fits', async () => {
|
||||
mockTitleWidths(100, 100);
|
||||
const user = userEvent.setup();
|
||||
render(<CheckboxFilterV2Header {...defaultProps} />);
|
||||
|
||||
await user.hover(screen.getByText(defaultProps.title));
|
||||
|
||||
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -114,19 +114,6 @@ export const loadingFiltersHandlers = [
|
||||
),
|
||||
];
|
||||
|
||||
export const longTitleConfig = [
|
||||
{
|
||||
attributeKey: {
|
||||
dataType: DataTypes.Int64,
|
||||
key: 'http.request.content_length_uncompressed',
|
||||
type: 'tag',
|
||||
},
|
||||
defaultOpen: false,
|
||||
title: 'Http Request Content Length Uncompressed',
|
||||
type: FiltersType.CHECKBOX,
|
||||
},
|
||||
];
|
||||
|
||||
export const LONG_FILTER_VALUES = [
|
||||
'checkout-service.production-eu-central-1.svc.cluster.local',
|
||||
'payments-authorisation-worker.production-us-east-2.svc.cluster.local',
|
||||
|
||||
@@ -8,7 +8,6 @@ import type { GlobalMockArgs } from '@/storybook/globals';
|
||||
import QuickFilters from '../QuickFilters';
|
||||
import {
|
||||
dirtySettings,
|
||||
hoverTruncatedTitle,
|
||||
openQueryPicker,
|
||||
openSettings,
|
||||
} from './__story_mockdata__/quickFilters.play';
|
||||
@@ -19,7 +18,6 @@ import {
|
||||
handlers,
|
||||
LONG_FILTER_VALUES,
|
||||
loadingFiltersHandlers,
|
||||
longTitleConfig,
|
||||
MANY_FILTER_VALUES,
|
||||
queryBuilder,
|
||||
selectedServiceQueryBuilder,
|
||||
@@ -161,15 +159,6 @@ export const Tooltips: GlobalArgsStory = {
|
||||
},
|
||||
};
|
||||
|
||||
/** A section title too long for the rail: hovering it shows the full title once. */
|
||||
export const TruncatedTitle: GlobalArgsStory = {
|
||||
args: { config: longTitleConfig },
|
||||
parameters: {
|
||||
msw: { handlers: [noSavedFiltersHandler, ...handlers] },
|
||||
},
|
||||
play: hoverTruncatedTitle,
|
||||
};
|
||||
|
||||
const [firstQuery] = queryBuilder.currentQuery.builder.queryData;
|
||||
|
||||
/** Interaction: the query picker lists every query the filters can follow. */
|
||||
|
||||
@@ -8,12 +8,9 @@ import { QuickFilterManagePermissions } from 'lib/authz/hooks/useAuthZ/permissio
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { grantsAll } from '@/storybook/access/access';
|
||||
import { hoverTruncatableText } from '@/storybook/play/truncatedText';
|
||||
import type { GlobalMockArgs } from '@/storybook/globals';
|
||||
|
||||
import type QuickFilters from '../../QuickFilters';
|
||||
import { longTitleConfig } from '../QuickFilters.stories.mocks';
|
||||
import { FiltersType } from '../../types';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
@@ -64,26 +61,6 @@ export const dirtySettings = async (context: PlayContext): Promise<void> => {
|
||||
await screen.findByRole('button', { name: 'Save changes' });
|
||||
};
|
||||
|
||||
export const hoverTruncatedTitle = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
const [filter] = args.config ?? [];
|
||||
// Duration and slider sections render no title of their own.
|
||||
if (filter?.type !== FiltersType.CHECKBOX || !filter.title) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [label] = await within(canvasElement).findAllByText(
|
||||
filter.title,
|
||||
{},
|
||||
UNTIL_LOADED,
|
||||
);
|
||||
await hoverTruncatableText(label, filter.title, {
|
||||
cut: filter.title === longTitleConfig[0].title || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
export const openQueryPicker = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
|
||||
@@ -10,8 +10,6 @@ import {
|
||||
import { getHostsQuickFiltersConfig } from 'container/InfraMonitoringHostsV2/utils';
|
||||
import { INFRA_MONITORING_ATTR_KEYS } from 'container/InfraMonitoringK8sV2/constants';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { mockUseAuthZGrantAll } from 'lib/authz/utils/authz-test-utils';
|
||||
import {
|
||||
otherFiltersResponse,
|
||||
quickFiltersFieldValuesResponse,
|
||||
@@ -19,14 +17,7 @@ import {
|
||||
} from 'mocks-server/__mockdata__/customQuickFilters';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
|
||||
import { QueryBuilderContextType } from 'types/common/queryBuilder';
|
||||
|
||||
@@ -41,7 +32,6 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: jest.fn(),
|
||||
}));
|
||||
jest.mock('container/ApiMonitoring/queryParams');
|
||||
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
|
||||
jest.mock(
|
||||
'components/OverlayScrollbar/OverlayScrollbar',
|
||||
() =>
|
||||
@@ -65,7 +55,6 @@ const mockSetApiMonitoringParams = jest.fn() as jest.MockedFunction<
|
||||
(newParams: Partial<ApiMonitoringParams>, replace?: boolean) => void
|
||||
>;
|
||||
const mockUseApiMonitoringParams = jest.mocked(useApiMonitoringParams);
|
||||
const mockedUseAuthZ = jest.mocked(useAuthZ);
|
||||
|
||||
const BASE_URL = ENVIRONMENT.baseURL;
|
||||
const quickFiltersListURL = `${BASE_URL}/api/v2/quick_filters/logs`;
|
||||
@@ -89,12 +78,11 @@ const QUERY_NAME = 'Test Query';
|
||||
|
||||
const savedFilters = quickFiltersListResponse.data
|
||||
.filters as TelemetryFieldKey[];
|
||||
const smallSavedFilters = savedFilters.slice(0, 2);
|
||||
const smallFiltersListResponse = {
|
||||
...quickFiltersListResponse,
|
||||
data: {
|
||||
...quickFiltersListResponse.data,
|
||||
filters: smallSavedFilters,
|
||||
filters: savedFilters.slice(0, 2),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -146,7 +134,7 @@ function renderSettings(): void {
|
||||
<QuickFiltersSettings
|
||||
savedFiltersSource={QuickfiltertypesSourceDTO.logs}
|
||||
setIsSettingsOpen={jest.fn()}
|
||||
customFilters={smallSavedFilters}
|
||||
customFilters={savedFilters}
|
||||
refetchCustomFilters={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
@@ -192,13 +180,12 @@ beforeEach(() => {
|
||||
{ showIP: true } as ApiMonitoringParams,
|
||||
mockSetApiMonitoringParams,
|
||||
]);
|
||||
mockedUseAuthZ.mockImplementation(mockUseAuthZGrantAll);
|
||||
setupServer();
|
||||
});
|
||||
|
||||
describe('Quick Filters', () => {
|
||||
it('displays the correct query name in the header', () => {
|
||||
render(<TestQuickFilters config={[]} />);
|
||||
render(<TestQuickFilters />);
|
||||
expect(screen.getByText('Filters for')).toBeInTheDocument();
|
||||
expect(screen.getByText(QUERY_NAME)).toBeInTheDocument();
|
||||
});
|
||||
@@ -207,7 +194,7 @@ describe('Quick Filters', () => {
|
||||
const setLastUsedQuery = jest.fn() as jest.MockedFunction<
|
||||
QueryBuilderContextType['setLastUsedQuery']
|
||||
>;
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useQueryBuilder as jest.Mock).mockReturnValue({
|
||||
currentQuery: {
|
||||
@@ -234,7 +221,7 @@ describe('Quick Filters', () => {
|
||||
panelType: 'graph', // not LIST view
|
||||
});
|
||||
|
||||
render(<TestQuickFilters config={[]} />);
|
||||
render(<TestQuickFilters />);
|
||||
|
||||
// The dropdown trigger should show the first query name
|
||||
const trigger = screen.getByTestId('quick-filters-query-select');
|
||||
@@ -256,10 +243,12 @@ describe('Quick Filters', () => {
|
||||
|
||||
// jsdom cannot deliver the pointer click Base UI expects on an option,
|
||||
// so pick Query B with the arrow keys and Enter
|
||||
await user.type(
|
||||
screen.getByTestId('quick-filters-query-select-search'),
|
||||
'{ArrowDown}{Enter}',
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByTestId('quick-filters-query-select-search'),
|
||||
).toHaveFocus(),
|
||||
);
|
||||
await user.keyboard('{ArrowDown}{Enter}');
|
||||
|
||||
// Verify setLastUsedQuery was called with index 1
|
||||
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
|
||||
@@ -286,7 +275,7 @@ describe('Quick Filters', () => {
|
||||
panelType: 'list', // ListView
|
||||
});
|
||||
|
||||
render(<TestQuickFilters config={[]} />);
|
||||
render(<TestQuickFilters />);
|
||||
|
||||
// Should show static query name without dropdown
|
||||
expect(screen.getByText('Query A')).toBeInTheDocument();
|
||||
@@ -297,7 +286,7 @@ describe('Quick Filters', () => {
|
||||
});
|
||||
|
||||
it('should display static query name when only one query exists', () => {
|
||||
render(<TestQuickFilters config={[]} />);
|
||||
render(<TestQuickFilters />);
|
||||
|
||||
// Should show static query name
|
||||
expect(screen.getByText(QUERY_NAME)).toBeInTheDocument();
|
||||
@@ -309,7 +298,7 @@ describe('Quick Filters', () => {
|
||||
});
|
||||
|
||||
it('should add filter data to query when checkbox is clicked', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<TestQuickFilters />);
|
||||
|
||||
@@ -341,7 +330,7 @@ describe('Quick Filters', () => {
|
||||
});
|
||||
});
|
||||
it('toggles Show IP addresses and updates API Monitoring params', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.API_MONITORING} />,
|
||||
@@ -375,7 +364,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('opens the settings with the saved filters added and the rest under other filters', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
rest.get(quickFiltersListURL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(smallFiltersListResponse)),
|
||||
@@ -397,7 +386,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('keeps same-name fields with different context as distinct entries', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
rest.get(quickFiltersSuggestionsURL, (_req, res, ctx) =>
|
||||
res(
|
||||
@@ -449,7 +438,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('adds a filter from OTHER FILTERS to ADDED FILTERS when clicked', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderSettings();
|
||||
|
||||
@@ -461,7 +450,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('removes a filter from ADDED FILTERS and moves it to OTHER FILTERS', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderSettings();
|
||||
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
|
||||
@@ -479,7 +468,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('restores original filter state on Discard', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderSettings();
|
||||
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
|
||||
@@ -502,7 +491,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('saves the updated filters by calling PUT with correct payload', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderSettings();
|
||||
|
||||
@@ -517,7 +506,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
expect(requestBody.filters).not.toContainEqual(
|
||||
expect.objectContaining({ name: FILTER_OS_DESCRIPTION }),
|
||||
);
|
||||
expect(requestBody.filters).toHaveLength(smallSavedFilters.length - 1);
|
||||
expect(requestBody.filters).toHaveLength(10);
|
||||
});
|
||||
|
||||
it('should render duration slider for duration_nono filter', async () => {
|
||||
@@ -559,10 +548,10 @@ describe('Quick Filters with custom filters', () => {
|
||||
expect(maxDuration).toHaveProperty('placeholder', '100000000');
|
||||
|
||||
// Type values and advance debounce
|
||||
await user.click(minDuration);
|
||||
await user.paste('10000');
|
||||
await user.click(maxDuration);
|
||||
await user.paste('20000');
|
||||
await user.clear(minDuration);
|
||||
await user.type(minDuration, '10000');
|
||||
await user.clear(maxDuration);
|
||||
await user.type(maxDuration, '20000');
|
||||
jest.advanceTimersByTime(2000);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -661,7 +650,7 @@ describe('Quick Filters refetch behavior', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
@@ -703,7 +692,7 @@ describe('Quick Filters refetch behavior', () => {
|
||||
),
|
||||
);
|
||||
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
|
||||
@@ -2,13 +2,7 @@ import {
|
||||
GetMetricQueryRange,
|
||||
GetQueryResultsProps,
|
||||
} from 'lib/dashboard/getQueryResults';
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { MetricQueryRangeSuccessResponse } from 'types/api/metrics/getQueryRange';
|
||||
|
||||
import EndPointPicker from '../Explorer/Domains/DomainDetails/components/EndPointPicker';
|
||||
@@ -71,7 +65,7 @@ describe('EndPointPicker', () => {
|
||||
});
|
||||
|
||||
it('reports the picked endpoint', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const onChange = jest.fn() as jest.MockedFunction<
|
||||
(endPointName: string) => void
|
||||
>;
|
||||
@@ -89,7 +83,7 @@ describe('EndPointPicker', () => {
|
||||
});
|
||||
|
||||
it('shows All endpoints when none is picked and clears through it', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const onChange = jest.fn() as jest.MockedFunction<
|
||||
(endPointName: string) => void
|
||||
>;
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
@@ -210,7 +209,7 @@ describe('TopErrors', () => {
|
||||
});
|
||||
|
||||
it('scopes the query to the endpoint picked in the picker', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const expressions: string[] = [];
|
||||
server.use(
|
||||
rest.post(V5_QUERY_RANGE_API_PATH, async (req) => {
|
||||
|
||||
@@ -10,23 +10,23 @@ import { useGetExportToDashboardLink } from 'hooks/dashboard/useGetExportToDashb
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
import {
|
||||
EXPLORER_ACTION_EVENTS,
|
||||
ExplorerActionsSource,
|
||||
getExplorerActionEventPayload,
|
||||
getExportPanelType,
|
||||
} from './utils';
|
||||
|
||||
function AddToDashboardButton({
|
||||
query,
|
||||
sourcePage,
|
||||
sourcepage,
|
||||
panelType,
|
||||
isOneChartPerQuery = false,
|
||||
}: {
|
||||
query: Query | null;
|
||||
sourcePage: ExplorerActionsSource;
|
||||
sourcepage: DataSource;
|
||||
panelType?: PANEL_TYPES;
|
||||
isOneChartPerQuery?: boolean;
|
||||
}): JSX.Element {
|
||||
@@ -40,9 +40,9 @@ function AddToDashboardButton({
|
||||
return;
|
||||
}
|
||||
void logEvent(
|
||||
EXPLORER_ACTION_EVENTS[sourcePage].addToDashboard,
|
||||
EXPLORER_ACTION_EVENTS[sourcepage].addToDashboard,
|
||||
getExplorerActionEventPayload({
|
||||
sourcePage,
|
||||
sourcepage,
|
||||
panelType: contextPanelType,
|
||||
isOneChartPerQuery,
|
||||
}),
|
||||
@@ -59,9 +59,9 @@ function AddToDashboardButton({
|
||||
}
|
||||
const exportPanelType = panelType ?? getExportPanelType(contextPanelType);
|
||||
|
||||
void logEvent(EXPLORER_ACTION_EVENTS[sourcePage].exported, {
|
||||
void logEvent(EXPLORER_ACTION_EVENTS[sourcepage].exported, {
|
||||
...getExplorerActionEventPayload({
|
||||
sourcePage,
|
||||
sourcepage,
|
||||
panelType: contextPanelType,
|
||||
isOneChartPerQuery,
|
||||
}),
|
||||
|
||||
@@ -5,21 +5,21 @@ import logEvent from 'api/common/logEvent';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useAppNavigate } from 'lib/router/useAppNavigate';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
EXPLORER_ACTION_EVENTS,
|
||||
ExplorerActionsSource,
|
||||
getCreateAlertLink,
|
||||
getExplorerActionEventPayload,
|
||||
} from './utils';
|
||||
|
||||
function CreateAlertButton({
|
||||
query,
|
||||
sourcePage,
|
||||
sourcepage,
|
||||
isOneChartPerQuery = false,
|
||||
}: {
|
||||
query: Query | null;
|
||||
sourcePage: ExplorerActionsSource;
|
||||
sourcepage: DataSource;
|
||||
isOneChartPerQuery?: boolean;
|
||||
}): JSX.Element {
|
||||
const navigate = useAppNavigate();
|
||||
@@ -30,8 +30,8 @@ function CreateAlertButton({
|
||||
return;
|
||||
}
|
||||
void logEvent(
|
||||
EXPLORER_ACTION_EVENTS[sourcePage].createAlert,
|
||||
getExplorerActionEventPayload({ sourcePage, panelType, isOneChartPerQuery }),
|
||||
EXPLORER_ACTION_EVENTS[sourcepage].createAlert,
|
||||
getExplorerActionEventPayload({ sourcepage, panelType, isOneChartPerQuery }),
|
||||
);
|
||||
navigate(getCreateAlertLink({ query, panelType }));
|
||||
};
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import AddToDashboardButton from './AddToDashboardButton';
|
||||
import CreateAlertButton from './CreateAlertButton';
|
||||
import { ExplorerActionsSource } from './utils';
|
||||
|
||||
function ExplorerActions({
|
||||
query,
|
||||
dashboardQuery = query,
|
||||
sourcePage,
|
||||
sourcepage,
|
||||
panelType,
|
||||
isOneChartPerQuery,
|
||||
}: {
|
||||
query: Query | null;
|
||||
// When the dashboard export differs from the alert one (traces list injects columns).
|
||||
dashboardQuery?: Query | null;
|
||||
sourcePage: ExplorerActionsSource;
|
||||
sourcepage: DataSource;
|
||||
panelType?: PANEL_TYPES;
|
||||
isOneChartPerQuery?: boolean;
|
||||
}): JSX.Element {
|
||||
@@ -23,12 +23,12 @@ function ExplorerActions({
|
||||
<>
|
||||
<CreateAlertButton
|
||||
query={query}
|
||||
sourcePage={sourcePage}
|
||||
sourcepage={sourcepage}
|
||||
isOneChartPerQuery={isOneChartPerQuery}
|
||||
/>
|
||||
<AddToDashboardButton
|
||||
query={dashboardQuery}
|
||||
sourcePage={sourcePage}
|
||||
sourcepage={sourcepage}
|
||||
panelType={panelType}
|
||||
isOneChartPerQuery={isOneChartPerQuery}
|
||||
/>
|
||||
|
||||
@@ -17,7 +17,7 @@ import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource, StringOperators } from 'types/common/queryBuilder';
|
||||
|
||||
import AddToDashboardButton from '../AddToDashboardButton';
|
||||
import { ExplorerActionsSource, getExportPanelType } from '../utils';
|
||||
import { getExportPanelType } from '../utils';
|
||||
|
||||
const DASHBOARD = { id: 'dash-1', title: 'Dash 1' };
|
||||
|
||||
@@ -94,7 +94,7 @@ function setPanelType(panelType: PANEL_TYPES): void {
|
||||
|
||||
async function exportTo(
|
||||
query: Query | null,
|
||||
sourcePage: ExplorerActionsSource,
|
||||
sourcepage: DataSource,
|
||||
panelType: PANEL_TYPES,
|
||||
panelTypeProp?: PANEL_TYPES,
|
||||
): Promise<void> {
|
||||
@@ -102,7 +102,7 @@ async function exportTo(
|
||||
render(
|
||||
<AddToDashboardButton
|
||||
query={query}
|
||||
sourcePage={sourcePage}
|
||||
sourcepage={sourcepage}
|
||||
panelType={panelTypeProp}
|
||||
/>,
|
||||
);
|
||||
@@ -128,12 +128,7 @@ describe('AddToDashboardButton', () => {
|
||||
|
||||
it('is disabled without a query and the picker stays closed', () => {
|
||||
setPanelType(PANEL_TYPES.LIST);
|
||||
render(
|
||||
<AddToDashboardButton
|
||||
query={null}
|
||||
sourcePage={ExplorerActionsSource.LOGS_EXPLORER}
|
||||
/>,
|
||||
);
|
||||
render(<AddToDashboardButton query={null} sourcepage={DataSource.LOGS} />);
|
||||
|
||||
expect(screen.getByTestId('explorer-add-to-dashboard')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
@@ -145,12 +140,7 @@ describe('AddToDashboardButton', () => {
|
||||
it('hands the picker the same query it will export', async () => {
|
||||
const query = stagedQuery(DataSource.LOGS);
|
||||
setPanelType(PANEL_TYPES.TIME_SERIES);
|
||||
render(
|
||||
<AddToDashboardButton
|
||||
query={query}
|
||||
sourcePage={ExplorerActionsSource.LOGS_EXPLORER}
|
||||
/>,
|
||||
);
|
||||
render(<AddToDashboardButton query={query} sourcepage={DataSource.LOGS} />);
|
||||
|
||||
await userEvent
|
||||
.setup()
|
||||
@@ -165,23 +155,19 @@ describe('AddToDashboardButton', () => {
|
||||
it("logs the explorer's own open and success events", async () => {
|
||||
const query = stagedQuery(DataSource.TRACES);
|
||||
|
||||
await exportTo(
|
||||
query,
|
||||
ExplorerActionsSource.TRACES_EXPLORER,
|
||||
PANEL_TYPES.TABLE,
|
||||
);
|
||||
await exportTo(query, DataSource.TRACES, PANEL_TYPES.TABLE);
|
||||
|
||||
expect(mockedLogEvent).toHaveBeenCalledWith(
|
||||
'Traces Explorer: Add to dashboard clicked',
|
||||
{
|
||||
sourcepage: ExplorerActionsSource.TRACES_EXPLORER,
|
||||
sourcepage: DataSource.TRACES,
|
||||
panelType: PANEL_TYPES.TABLE,
|
||||
},
|
||||
);
|
||||
expect(mockedLogEvent).toHaveBeenCalledWith(
|
||||
'Traces Explorer: Add to dashboard successful',
|
||||
{
|
||||
sourcepage: ExplorerActionsSource.TRACES_EXPLORER,
|
||||
sourcepage: DataSource.TRACES,
|
||||
panelType: PANEL_TYPES.TABLE,
|
||||
isNewDashboard: undefined,
|
||||
dashboardName: DASHBOARD.title,
|
||||
@@ -195,7 +181,7 @@ describe('AddToDashboardButton', () => {
|
||||
// context says list, the page says time series
|
||||
await exportTo(
|
||||
query,
|
||||
ExplorerActionsSource.METRICS_EXPLORER,
|
||||
DataSource.METRICS,
|
||||
PANEL_TYPES.LIST,
|
||||
PANEL_TYPES.TIME_SERIES,
|
||||
);
|
||||
@@ -220,11 +206,7 @@ describe('AddToDashboardButton', () => {
|
||||
PANEL_TYPES.LIST,
|
||||
) as Query;
|
||||
|
||||
await exportTo(
|
||||
exportQuery,
|
||||
ExplorerActionsSource.LOGS_EXPLORER,
|
||||
PANEL_TYPES.LIST,
|
||||
);
|
||||
await exportTo(exportQuery, DataSource.LOGS, PANEL_TYPES.LIST);
|
||||
|
||||
expect(exportQuery.builder.queryData[0].orderBy).toStrictEqual([
|
||||
{ columnName: 'timestamp', order: 'desc' },
|
||||
@@ -239,7 +221,7 @@ describe('AddToDashboardButton', () => {
|
||||
async (panelType) => {
|
||||
const exportQuery = getLogsExportQuery(staged, panelType) as Query;
|
||||
|
||||
await exportTo(exportQuery, ExplorerActionsSource.LOGS_EXPLORER, panelType);
|
||||
await exportTo(exportQuery, DataSource.LOGS, panelType);
|
||||
|
||||
expect(exportQuery).toBe(staged);
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith(
|
||||
@@ -259,11 +241,7 @@ describe('AddToDashboardButton', () => {
|
||||
options,
|
||||
);
|
||||
|
||||
await exportTo(
|
||||
exportQuery,
|
||||
ExplorerActionsSource.TRACES_EXPLORER,
|
||||
PANEL_TYPES.LIST,
|
||||
);
|
||||
await exportTo(exportQuery, DataSource.TRACES, PANEL_TYPES.LIST);
|
||||
|
||||
const [queryData] = exportQuery.builder.queryData;
|
||||
expect(queryData.selectColumns).toStrictEqual(COLUMNS);
|
||||
@@ -280,11 +258,7 @@ describe('AddToDashboardButton', () => {
|
||||
options,
|
||||
);
|
||||
|
||||
await exportTo(
|
||||
exportQuery,
|
||||
ExplorerActionsSource.TRACES_EXPLORER,
|
||||
PANEL_TYPES.TRACE,
|
||||
);
|
||||
await exportTo(exportQuery, DataSource.TRACES, PANEL_TYPES.TRACE);
|
||||
|
||||
expect(exportQuery.builder.queryData[0].selectColumns).toBeUndefined();
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith(
|
||||
@@ -304,11 +278,7 @@ describe('AddToDashboardButton', () => {
|
||||
options,
|
||||
);
|
||||
|
||||
await exportTo(
|
||||
exportQuery,
|
||||
ExplorerActionsSource.TRACES_EXPLORER,
|
||||
panelType,
|
||||
);
|
||||
await exportTo(exportQuery, DataSource.TRACES, panelType);
|
||||
|
||||
expect(exportQuery.builder.queryData[0].orderBy).toStrictEqual([]);
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith(
|
||||
@@ -326,11 +296,7 @@ describe('AddToDashboardButton', () => {
|
||||
options,
|
||||
);
|
||||
|
||||
await exportTo(
|
||||
exportQuery,
|
||||
ExplorerActionsSource.TRACES_EXPLORER,
|
||||
panelType,
|
||||
);
|
||||
await exportTo(exportQuery, DataSource.TRACES, panelType);
|
||||
|
||||
expect(exportQuery).toBe(staged);
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith(
|
||||
@@ -345,7 +311,7 @@ describe('AddToDashboardButton', () => {
|
||||
|
||||
await exportTo(
|
||||
query,
|
||||
ExplorerActionsSource.METRICS_EXPLORER,
|
||||
DataSource.METRICS,
|
||||
PANEL_TYPES.TIME_SERIES,
|
||||
PANEL_TYPES.TIME_SERIES,
|
||||
);
|
||||
|
||||
@@ -14,7 +14,6 @@ import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource, StringOperators } from 'types/common/queryBuilder';
|
||||
|
||||
import CreateAlertButton from '../CreateAlertButton';
|
||||
import { ExplorerActionsSource } from '../utils';
|
||||
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: jest.fn(),
|
||||
@@ -61,7 +60,7 @@ function pushedQuery(): Query {
|
||||
const [path, search] = (mockedNavigate.mock.calls[0][0] as string).split('?');
|
||||
expect(path).toBe(ROUTES.ALERTS_NEW);
|
||||
const raw = new URLSearchParams(search).get(QueryParams.compositeQuery);
|
||||
return JSON.parse(decodeURIComponent(raw as string));
|
||||
return JSON.parse(raw as string);
|
||||
}
|
||||
|
||||
function setPanelType(panelType: PANEL_TYPES): void {
|
||||
@@ -72,11 +71,11 @@ function setPanelType(panelType: PANEL_TYPES): void {
|
||||
|
||||
async function clickCreateAlert(
|
||||
query: Query | null,
|
||||
sourcePage: ExplorerActionsSource,
|
||||
sourcepage: DataSource,
|
||||
panelType: PANEL_TYPES,
|
||||
): Promise<void> {
|
||||
setPanelType(panelType);
|
||||
render(<CreateAlertButton query={query} sourcePage={sourcePage} />);
|
||||
render(<CreateAlertButton query={query} sourcepage={sourcepage} />);
|
||||
await userEvent.setup().click(screen.getByTestId('explorer-create-alert'));
|
||||
}
|
||||
|
||||
@@ -87,11 +86,7 @@ describe('CreateAlertButton', () => {
|
||||
});
|
||||
|
||||
it('is disabled and does nothing without a query', async () => {
|
||||
await clickCreateAlert(
|
||||
null,
|
||||
ExplorerActionsSource.LOGS_EXPLORER,
|
||||
PANEL_TYPES.LIST,
|
||||
);
|
||||
await clickCreateAlert(null, DataSource.LOGS, PANEL_TYPES.LIST);
|
||||
|
||||
expect(screen.getByTestId('explorer-create-alert')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
@@ -103,14 +98,10 @@ describe('CreateAlertButton', () => {
|
||||
it("logs the explorer's own create alert event", async () => {
|
||||
const query = stagedQuery(DataSource.TRACES, StringOperators.COUNT);
|
||||
|
||||
await clickCreateAlert(
|
||||
query,
|
||||
ExplorerActionsSource.TRACES_EXPLORER,
|
||||
PANEL_TYPES.TIME_SERIES,
|
||||
);
|
||||
await clickCreateAlert(query, DataSource.TRACES, PANEL_TYPES.TIME_SERIES);
|
||||
|
||||
expect(mockedLogEvent).toHaveBeenCalledWith('Traces Explorer: Create alert', {
|
||||
sourcepage: ExplorerActionsSource.TRACES_EXPLORER,
|
||||
sourcepage: DataSource.TRACES,
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
});
|
||||
});
|
||||
@@ -120,7 +111,7 @@ describe('CreateAlertButton', () => {
|
||||
render(
|
||||
<CreateAlertButton
|
||||
query={stagedQuery(DataSource.METRICS, StringOperators.COUNT)}
|
||||
sourcePage={ExplorerActionsSource.METRICS_EXPLORER}
|
||||
sourcepage={DataSource.METRICS}
|
||||
isOneChartPerQuery
|
||||
/>,
|
||||
);
|
||||
@@ -132,7 +123,7 @@ describe('CreateAlertButton', () => {
|
||||
expect(mockedLogEvent).toHaveBeenCalledWith(
|
||||
'Metrics Explorer: Add to alert clicked',
|
||||
{
|
||||
sourcepage: ExplorerActionsSource.METRICS_EXPLORER,
|
||||
sourcepage: DataSource.METRICS,
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
tab: 'explorer',
|
||||
oneChartPerQueryEnabled: true,
|
||||
@@ -155,11 +146,7 @@ describe('CreateAlertButton', () => {
|
||||
PANEL_TYPES.LIST,
|
||||
) as Query;
|
||||
|
||||
await clickCreateAlert(
|
||||
exportQuery,
|
||||
ExplorerActionsSource.LOGS_EXPLORER,
|
||||
PANEL_TYPES.LIST,
|
||||
);
|
||||
await clickCreateAlert(exportQuery, DataSource.LOGS, PANEL_TYPES.LIST);
|
||||
|
||||
const [queryData] = pushedQuery().builder.queryData;
|
||||
expect(queryData.aggregateOperator).toBe(StringOperators.COUNT);
|
||||
@@ -178,7 +165,7 @@ describe('CreateAlertButton', () => {
|
||||
|
||||
await clickCreateAlert(
|
||||
exportQuery,
|
||||
ExplorerActionsSource.LOGS_EXPLORER,
|
||||
DataSource.LOGS,
|
||||
PANEL_TYPES.TIME_SERIES,
|
||||
);
|
||||
|
||||
@@ -193,11 +180,7 @@ describe('CreateAlertButton', () => {
|
||||
PANEL_TYPES.TABLE,
|
||||
) as Query;
|
||||
|
||||
await clickCreateAlert(
|
||||
exportQuery,
|
||||
ExplorerActionsSource.LOGS_EXPLORER,
|
||||
PANEL_TYPES.TABLE,
|
||||
);
|
||||
await clickCreateAlert(exportQuery, DataSource.LOGS, PANEL_TYPES.TABLE);
|
||||
|
||||
expect(pushedQuery().builder).toStrictEqual(tableStaged.builder);
|
||||
});
|
||||
@@ -211,11 +194,7 @@ describe('CreateAlertButton', () => {
|
||||
async (panelType) => {
|
||||
const exportQuery = getTracesQueryByPanelType(staged, panelType);
|
||||
|
||||
await clickCreateAlert(
|
||||
exportQuery,
|
||||
ExplorerActionsSource.TRACES_EXPLORER,
|
||||
panelType,
|
||||
);
|
||||
await clickCreateAlert(exportQuery, DataSource.TRACES, panelType);
|
||||
|
||||
const [queryData] = pushedQuery().builder.queryData;
|
||||
expect(queryData.aggregateOperator).toBe(StringOperators.COUNT);
|
||||
@@ -232,11 +211,7 @@ describe('CreateAlertButton', () => {
|
||||
expect(staged.builder.queryData[0].orderBy).toStrictEqual(ORDER_BY);
|
||||
const exportQuery = getTracesQueryByPanelType(staged, panelType);
|
||||
|
||||
await clickCreateAlert(
|
||||
exportQuery,
|
||||
ExplorerActionsSource.TRACES_EXPLORER,
|
||||
panelType,
|
||||
);
|
||||
await clickCreateAlert(exportQuery, DataSource.TRACES, panelType);
|
||||
|
||||
expect(pushedQuery().builder.queryData[0].orderBy).toStrictEqual([]);
|
||||
},
|
||||
@@ -248,11 +223,7 @@ describe('CreateAlertButton', () => {
|
||||
const aggStaged = stagedQuery(DataSource.TRACES, StringOperators.COUNT);
|
||||
const exportQuery = getTracesQueryByPanelType(aggStaged, panelType);
|
||||
|
||||
await clickCreateAlert(
|
||||
exportQuery,
|
||||
ExplorerActionsSource.TRACES_EXPLORER,
|
||||
panelType,
|
||||
);
|
||||
await clickCreateAlert(exportQuery, DataSource.TRACES, panelType);
|
||||
|
||||
expect(pushedQuery().builder).toStrictEqual(aggStaged.builder);
|
||||
},
|
||||
@@ -262,11 +233,7 @@ describe('CreateAlertButton', () => {
|
||||
it('metrics: the chart query as is', async () => {
|
||||
const query = stagedQuery(DataSource.METRICS, StringOperators.COUNT);
|
||||
|
||||
await clickCreateAlert(
|
||||
query,
|
||||
ExplorerActionsSource.METRICS_EXPLORER,
|
||||
PANEL_TYPES.TIME_SERIES,
|
||||
);
|
||||
await clickCreateAlert(query, DataSource.METRICS, PANEL_TYPES.TIME_SERIES);
|
||||
|
||||
expect(pushedQuery().builder).toStrictEqual(query.builder);
|
||||
});
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
|
||||
import { AllTheProviders, renderHook } from 'tests/test-utils';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { StringOperators } from 'types/common/queryBuilder';
|
||||
|
||||
@@ -24,7 +22,7 @@ function withFirstQuery(
|
||||
function decodeQuery(link: string): Query {
|
||||
const search = link.split('?')[1];
|
||||
const raw = new URLSearchParams(search).get(QueryParams.compositeQuery);
|
||||
return JSON.parse(decodeURIComponent(raw as string));
|
||||
return JSON.parse(raw as string);
|
||||
}
|
||||
|
||||
describe('getExportPanelType', () => {
|
||||
@@ -57,26 +55,6 @@ describe('getCreateAlertLink', () => {
|
||||
expect(decodeQuery(link)).toStrictEqual(query);
|
||||
});
|
||||
|
||||
it.each(["service.name ILIKE 'api%'", "http.route = '/a+b'"])(
|
||||
'the alert page reads back the filter %s unchanged',
|
||||
(expression) => {
|
||||
const link = getCreateAlertLink({
|
||||
query: withFirstQuery(initialQueriesMap.logs, { filter: { expression } }),
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useGetCompositeQueryParam(), {
|
||||
wrapper: ({ children }): JSX.Element => (
|
||||
<AllTheProviders initialRoute={link}>{children}</AllTheProviders>
|
||||
),
|
||||
});
|
||||
|
||||
expect(result.current?.builder.queryData[0].filter?.expression).toBe(
|
||||
expression,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('logs list: noop becomes count and order by is dropped', () => {
|
||||
const query = withFirstQuery(initialQueriesMap.logs, {
|
||||
aggregateOperator: StringOperators.NOOP,
|
||||
@@ -10,57 +10,41 @@ import { cloneDeep } from 'lodash-es';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource, StringOperators } from 'types/common/queryBuilder';
|
||||
|
||||
// The explorer page, not its DataSource: the AI explorer queries traces but logs its own events.
|
||||
export const ExplorerActionsSource = {
|
||||
LOGS_EXPLORER: DataSource.LOGS,
|
||||
TRACES_EXPLORER: DataSource.TRACES,
|
||||
METRICS_EXPLORER: DataSource.METRICS,
|
||||
AI_OBSERVABILITY_EXPLORER: 'ai_observability',
|
||||
} as const;
|
||||
|
||||
export type ExplorerActionsSource =
|
||||
(typeof ExplorerActionsSource)[keyof typeof ExplorerActionsSource];
|
||||
|
||||
export const EXPLORER_ACTION_EVENTS: Record<
|
||||
ExplorerActionsSource,
|
||||
DataSource,
|
||||
{ createAlert: string; addToDashboard: string; exported: string }
|
||||
> = {
|
||||
[ExplorerActionsSource.LOGS_EXPLORER]: {
|
||||
[DataSource.LOGS]: {
|
||||
createAlert: 'Logs Explorer: Create alert',
|
||||
addToDashboard: 'Logs Explorer: Add to dashboard clicked',
|
||||
exported: 'Logs Explorer: Add to dashboard successful',
|
||||
},
|
||||
[ExplorerActionsSource.TRACES_EXPLORER]: {
|
||||
[DataSource.TRACES]: {
|
||||
createAlert: 'Traces Explorer: Create alert',
|
||||
addToDashboard: 'Traces Explorer: Add to dashboard clicked',
|
||||
exported: 'Traces Explorer: Add to dashboard successful',
|
||||
},
|
||||
[ExplorerActionsSource.METRICS_EXPLORER]: {
|
||||
[DataSource.METRICS]: {
|
||||
createAlert: MetricsExplorerEvents.AddToAlertClicked,
|
||||
addToDashboard: MetricsExplorerEvents.AddToDashboardClicked,
|
||||
exported: MetricsExplorerEvents.AddToDashboardSuccessful,
|
||||
},
|
||||
[ExplorerActionsSource.AI_OBSERVABILITY_EXPLORER]: {
|
||||
createAlert: 'AI Observability Explorer: Create alert',
|
||||
addToDashboard: 'AI Observability Explorer: Add to dashboard clicked',
|
||||
exported: 'AI Observability Explorer: Add to dashboard successful',
|
||||
},
|
||||
};
|
||||
|
||||
export function getExplorerActionEventPayload({
|
||||
sourcePage,
|
||||
sourcepage,
|
||||
panelType,
|
||||
isOneChartPerQuery,
|
||||
}: {
|
||||
sourcePage: ExplorerActionsSource;
|
||||
sourcepage: DataSource;
|
||||
panelType: PANEL_TYPES | null;
|
||||
isOneChartPerQuery: boolean;
|
||||
}): Record<string, unknown> {
|
||||
if (sourcePage !== ExplorerActionsSource.METRICS_EXPLORER) {
|
||||
return { sourcepage: sourcePage, panelType };
|
||||
if (sourcepage !== DataSource.METRICS) {
|
||||
return { sourcepage, panelType };
|
||||
}
|
||||
return {
|
||||
sourcepage: sourcePage,
|
||||
sourcepage,
|
||||
panelType,
|
||||
[MetricsExplorerEventKeys.Tab]: 'explorer',
|
||||
[MetricsExplorerEventKeys.OneChartPerQueryEnabled]: isOneChartPerQuery,
|
||||
@@ -95,8 +79,7 @@ export function getCreateAlertLink({
|
||||
orderBy: isListStyle ? [] : item.orderBy,
|
||||
}));
|
||||
|
||||
// Encoded twice: the alert page decodes it again after the URL does.
|
||||
return `${ROUTES.ALERTS_NEW}?${QueryParams.compositeQuery}=${encodeURIComponent(
|
||||
encodeURIComponent(JSON.stringify(alertQuery)),
|
||||
JSON.stringify(alertQuery),
|
||||
)}`;
|
||||
}
|
||||
|
||||
@@ -32,10 +32,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.ingestion-keys-search-auth-trigger {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.ant-table-row {
|
||||
.ant-table-cell {
|
||||
padding: 0;
|
||||
|
||||
@@ -26,13 +26,13 @@ import type { NotificationInstance } from 'antd/es/notification/interface';
|
||||
import type { CollapseProps } from 'antd/lib';
|
||||
import {
|
||||
useCreateIngestionKey,
|
||||
useCreateIngestionLimit,
|
||||
useCreateIngestionKeyLimit,
|
||||
useDeleteIngestionKey,
|
||||
useDeleteIngestionLimit,
|
||||
useDeleteIngestionKeyLimit,
|
||||
useGetIngestionKeys,
|
||||
useSearchIngestionKeys,
|
||||
useUpdateIngestionKey,
|
||||
useUpdateIngestionLimit,
|
||||
useUpdateIngestionKeyLimit,
|
||||
} from 'api/generated/services/gateway';
|
||||
import {
|
||||
GatewaytypesIngestionKeyDTO,
|
||||
@@ -71,21 +71,6 @@ import {
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from '@signozhq/icons';
|
||||
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
|
||||
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
|
||||
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
|
||||
import {
|
||||
buildIngestionKeyAttachPermission,
|
||||
buildIngestionKeyDeletePermission,
|
||||
buildIngestionKeyDetachPermission,
|
||||
buildIngestionKeyUpdatePermission,
|
||||
buildIngestionLimitDeletePermission,
|
||||
buildIngestionLimitUpdatePermission,
|
||||
IngestionKeyCreatePermission,
|
||||
IngestionKeyListPermission,
|
||||
IngestionLimitCreatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/ingestion.permissions';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import {
|
||||
@@ -225,13 +210,6 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
|
||||
const [totalIngestionKeys, setTotalIngestionKeys] = useState(0);
|
||||
|
||||
const { permissions: authzPermissions } = useAuthZ([
|
||||
IngestionKeyListPermission,
|
||||
]);
|
||||
|
||||
const canListIngestionKeys =
|
||||
authzPermissions?.[IngestionKeyListPermission].isGranted ?? false;
|
||||
|
||||
const [
|
||||
hasCreateLimitForIngestionKeyError,
|
||||
setHasCreateLimitForIngestionKeyError,
|
||||
@@ -336,7 +314,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
},
|
||||
{
|
||||
query: {
|
||||
enabled: !isSearching && canListIngestionKeys,
|
||||
enabled: !isSearching,
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -356,7 +334,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
},
|
||||
{
|
||||
query: {
|
||||
enabled: isSearching && canListIngestionKeys,
|
||||
enabled: isSearching,
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -367,14 +345,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
: ingestionKeysData;
|
||||
const isLoading = isSearching ? isLoadingSearch : isLoadingGet;
|
||||
const isRefetching = isSearching ? isRefetchingSearch : isRefetchingGet;
|
||||
const refetchKeysQuery = isSearching
|
||||
? refetchSearchAPIKeys
|
||||
: refetchGetAPIKeys;
|
||||
const refetchAPIKeys = async (): Promise<void> => {
|
||||
if (canListIngestionKeys) {
|
||||
await refetchKeysQuery();
|
||||
}
|
||||
};
|
||||
const refetchAPIKeys = isSearching ? refetchSearchAPIKeys : refetchGetAPIKeys;
|
||||
const error = isSearching ? searchError : getError;
|
||||
const isError = isSearching ? isSearchError : isGetError;
|
||||
|
||||
@@ -422,15 +393,15 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
useDeleteIngestionKey<AxiosError<RenderErrorResponseDTO>>();
|
||||
|
||||
const { mutate: createLimitForIngestionKey, isLoading: isLoadingLimitForKey } =
|
||||
useCreateIngestionLimit<AxiosError<RenderErrorResponseDTO>>();
|
||||
useCreateIngestionKeyLimit<AxiosError<RenderErrorResponseDTO>>();
|
||||
|
||||
const {
|
||||
mutate: updateLimitForIngestionKey,
|
||||
isLoading: isLoadingUpdatedLimitForKey,
|
||||
} = useUpdateIngestionLimit<AxiosError<RenderErrorResponseDTO>>();
|
||||
} = useUpdateIngestionKeyLimit<AxiosError<RenderErrorResponseDTO>>();
|
||||
|
||||
const { mutate: deleteLimitForKey, isLoading: isDeletingLimit } =
|
||||
useDeleteIngestionLimit<AxiosError<RenderErrorResponseDTO>>();
|
||||
useDeleteIngestionKeyLimit<AxiosError<RenderErrorResponseDTO>>();
|
||||
|
||||
const onDeleteHandler = (): void => {
|
||||
clearSearch();
|
||||
@@ -667,8 +638,8 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
|
||||
createLimitForIngestionKey(
|
||||
{
|
||||
pathParams: { keyId: payload.keyID },
|
||||
data: {
|
||||
keyId: payload.keyID,
|
||||
signal: payload.signal,
|
||||
config: payload.config,
|
||||
},
|
||||
@@ -1056,14 +1027,12 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
icon
|
||||
color="secondary"
|
||||
aria-label="Edit ingestion key"
|
||||
testId={`ingestion-key-edit-btn-${APIKey.id}`}
|
||||
onClick={onEditKey}
|
||||
>
|
||||
<PenLine size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
aria-label="Delete ingestion key"
|
||||
testId={`ingestion-key-delete-open-btn-${APIKey.id}`}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon
|
||||
@@ -1191,19 +1160,8 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
});
|
||||
};
|
||||
|
||||
const isAddingNewLimit = !hasLimits(signalName);
|
||||
|
||||
const ingestionLimitPermissions = APIKey?.id
|
||||
? isAddingNewLimit
|
||||
? [
|
||||
IngestionLimitCreatePermission,
|
||||
buildIngestionKeyAttachPermission(APIKey.id),
|
||||
]
|
||||
: [buildIngestionLimitUpdatePermission(limit.id)]
|
||||
: [];
|
||||
|
||||
const onSaveSignalLimit = (): void => {
|
||||
if (isAddingNewLimit) {
|
||||
if (!hasLimits(signalName)) {
|
||||
handleAddLimit(APIKey, signalName);
|
||||
} else {
|
||||
handleUpdateLimit(APIKey, limitsDict[signalName]);
|
||||
@@ -1242,7 +1200,6 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
icon
|
||||
color="danger"
|
||||
aria-label={`Delete ${signalName} limit`}
|
||||
testId={`ingestion-limit-delete-open-btn-${signalName}`}
|
||||
disabled={
|
||||
!!(activeAPIKey?.id === APIKey?.id && activeSignal)
|
||||
}
|
||||
@@ -1260,7 +1217,6 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
prefix={<Plus size={12} />}
|
||||
disabled={!!(activeAPIKey?.id === APIKey?.id && activeSignal)}
|
||||
onClick={onAddSignalLimit}
|
||||
testId={`ingestion-limit-add-btn-${signalName}`}
|
||||
>
|
||||
Limits
|
||||
</Button>
|
||||
@@ -1492,7 +1448,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
isEditAddLimitOpen && (
|
||||
<div className="signal-limit-save-discard">
|
||||
<div className="signal-limit-save-discard-actions">
|
||||
<AuthZButton
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
size="sm"
|
||||
@@ -1500,11 +1456,9 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
isLoadingLimitForKey || isLoadingUpdatedLimitForKey
|
||||
}
|
||||
onClick={onSaveSignalLimit}
|
||||
testId="ingestion-limit-save-btn"
|
||||
checks={ingestionLimitPermissions}
|
||||
>
|
||||
Save
|
||||
</AuthZButton>
|
||||
</Button>
|
||||
<Button
|
||||
disabledTooltip="Wait for the limit to save"
|
||||
variant="outlined"
|
||||
@@ -1827,50 +1781,42 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
)}
|
||||
|
||||
<div className="ingestion-keys-search-add-new">
|
||||
<AuthZTooltip
|
||||
triggerClassName="ingestion-keys-search-auth-trigger"
|
||||
checks={[IngestionKeyListPermission]}
|
||||
>
|
||||
<Input
|
||||
placeholder="Search for ingestion key..."
|
||||
prefix={<Search size={12} color={Color.BG_VANILLA_400} />}
|
||||
value={searchValue}
|
||||
onChange={handleSearch}
|
||||
/>
|
||||
</AuthZTooltip>
|
||||
<Input
|
||||
placeholder="Search for ingestion key..."
|
||||
prefix={<Search size={12} color={Color.BG_VANILLA_400} />}
|
||||
value={searchValue}
|
||||
onChange={handleSearch}
|
||||
/>
|
||||
|
||||
<div className="ingestion-keys-add-new">
|
||||
<AuthZButton
|
||||
<Button
|
||||
size="md"
|
||||
color="primary"
|
||||
variant="solid"
|
||||
prefix={<Plus size={14} />}
|
||||
onClick={showAddModal}
|
||||
testId="ingestion-key-add-btn"
|
||||
checks={[IngestionKeyCreatePermission]}
|
||||
>
|
||||
New Ingestion key
|
||||
</AuthZButton>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AuthZGuardContent checks={[IngestionKeyListPermission]}>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={dataSource}
|
||||
loading={isLoading || isRefetching}
|
||||
showHeader={false}
|
||||
onChange={handleTableChange}
|
||||
pagination={{
|
||||
pageSize: isSearching ? SEARCH_PAGE_SIZE : paginationParams?.per_page,
|
||||
hideOnSinglePage: true,
|
||||
showTotal: (total: number, range: number[]): string =>
|
||||
`${range[0]}-${range[1]} of ${total} Ingestion keys`,
|
||||
total: totalIngestionKeys,
|
||||
}}
|
||||
className="ingestion-keys-table"
|
||||
/>
|
||||
</AuthZGuardContent>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={dataSource}
|
||||
loading={isLoading || isRefetching}
|
||||
showHeader={false}
|
||||
onChange={handleTableChange}
|
||||
pagination={{
|
||||
pageSize: isSearching ? SEARCH_PAGE_SIZE : paginationParams?.per_page,
|
||||
hideOnSinglePage: true,
|
||||
showTotal: (total: number, range: number[]): string =>
|
||||
`${range[0]}-${range[1]} of ${total} Ingestion keys`,
|
||||
total: totalIngestionKeys,
|
||||
}}
|
||||
className="ingestion-keys-table"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Delete Key Modal */}
|
||||
@@ -1893,7 +1839,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
>
|
||||
Cancel
|
||||
</Button>,
|
||||
<AuthZButton
|
||||
<Button
|
||||
size="md"
|
||||
key="submit"
|
||||
variant="solid"
|
||||
@@ -1901,15 +1847,9 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
prefix={<Trash2 size={16} />}
|
||||
loading={isDeleteingAPIKey}
|
||||
onClick={onDeleteHandler}
|
||||
testId="ingestion-key-delete-btn"
|
||||
checks={
|
||||
isDeleteModalOpen && activeAPIKey?.id
|
||||
? [buildIngestionKeyDeletePermission(activeAPIKey.id)]
|
||||
: []
|
||||
}
|
||||
>
|
||||
Delete Ingestion Key
|
||||
</AuthZButton>,
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<Typography
|
||||
@@ -1946,7 +1886,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
>
|
||||
Cancel
|
||||
</Button>,
|
||||
<AuthZButton
|
||||
<Button
|
||||
size="md"
|
||||
key="submit"
|
||||
variant="solid"
|
||||
@@ -1954,18 +1894,9 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
prefix={<Trash2 size={16} />}
|
||||
loading={isDeletingLimit}
|
||||
onClick={onDeleteLimitHandler}
|
||||
testId="ingestion-limit-delete-btn"
|
||||
checks={
|
||||
isDeleteLimitModalOpen && activeSignal?.id && activeAPIKey?.id
|
||||
? [
|
||||
buildIngestionLimitDeletePermission(activeSignal.id),
|
||||
buildIngestionKeyDetachPermission(activeAPIKey.id),
|
||||
]
|
||||
: []
|
||||
}
|
||||
>
|
||||
Delete Limit
|
||||
</AuthZButton>,
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<Typography
|
||||
@@ -2005,7 +1936,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
>
|
||||
Cancel
|
||||
</Button>,
|
||||
<AuthZButton
|
||||
<Button
|
||||
size="md"
|
||||
color="primary"
|
||||
key="submit"
|
||||
@@ -2013,15 +1944,9 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
prefix={<Check size={14} />}
|
||||
loading={isLoadingUpdateAPIKey}
|
||||
onClick={onUpdateApiKey}
|
||||
testId="ingestion-key-update-btn"
|
||||
checks={
|
||||
isEditModalOpen && activeAPIKey?.id
|
||||
? [buildIngestionKeyUpdatePermission(activeAPIKey.id)]
|
||||
: []
|
||||
}
|
||||
>
|
||||
Update Ingestion Key
|
||||
</AuthZButton>,
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<Form
|
||||
|
||||
@@ -1,376 +0,0 @@
|
||||
import dayjs from 'dayjs';
|
||||
import type {
|
||||
AuthtypesTransactionDTO,
|
||||
GatewaytypesIngestionKeyDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
buildIngestionKeyAttachPermission,
|
||||
buildIngestionKeyDeletePermission,
|
||||
buildIngestionKeyDetachPermission,
|
||||
buildIngestionKeyUpdatePermission,
|
||||
buildIngestionLimitDeletePermission,
|
||||
buildIngestionLimitUpdatePermission,
|
||||
IngestionKeyCreatePermission,
|
||||
IngestionKeyListPermission,
|
||||
IngestionLimitCreatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/ingestion.permissions';
|
||||
import { gettableTransactionToPermission } from 'lib/authz/hooks/useAuthZ/utils';
|
||||
import {
|
||||
AUTHZ_CHECK_URL,
|
||||
setupAuthzAdmin,
|
||||
setupAuthzDeny,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import MultiIngestionSettings from '../MultiIngestionSettings';
|
||||
|
||||
jest.setTimeout(15_000);
|
||||
|
||||
const ROUTE = '/ingestion-settings';
|
||||
const DATE = '2024-01-01T00:00:00Z';
|
||||
const EXPIRES_AT = '2030-01-01T00:00:00Z';
|
||||
|
||||
const DENIED_TEXT = /is not authorized to perform/i;
|
||||
|
||||
const makeKey = (
|
||||
id: string,
|
||||
name: string,
|
||||
limits: GatewaytypesIngestionKeyDTO['limits'] = [],
|
||||
): GatewaytypesIngestionKeyDTO => ({
|
||||
id,
|
||||
name,
|
||||
value: 'secret',
|
||||
workspace_id: 'w1',
|
||||
expires_at: EXPIRES_AT,
|
||||
created_at: DATE,
|
||||
updated_at: DATE,
|
||||
tags: [],
|
||||
limits,
|
||||
});
|
||||
|
||||
const KEY_ONE = makeKey('k1', 'Key One', [
|
||||
{ id: 'l1', signal: 'logs', config: { day: { size: 1073741824 } } },
|
||||
]);
|
||||
const KEY_TWO = makeKey('k2', 'Key Two');
|
||||
const KEY_THREE = makeKey('k3', 'Key Three');
|
||||
|
||||
function mockKeys(keys: GatewaytypesIngestionKeyDTO[]): jest.Mock {
|
||||
const onList = jest.fn();
|
||||
server.use(
|
||||
rest.get('*/api/v1/global/config*', (_req, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: {
|
||||
external_url: '',
|
||||
ingestion_url: 'http://ingest.example.com',
|
||||
ai_assistant_url: null,
|
||||
mcp_url: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
rest.get('*/api/v2/gateway/ingestion_keys*', (_req, res, ctx) => {
|
||||
onList();
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: {
|
||||
keys,
|
||||
_pagination: {
|
||||
page: 1,
|
||||
per_page: 10,
|
||||
pages: 1,
|
||||
total: keys.length,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
return onList;
|
||||
}
|
||||
|
||||
function recordAuthzChecks(): Set<string> {
|
||||
const seen = new Set<string>();
|
||||
server.use(
|
||||
rest.post(AUTHZ_CHECK_URL, async (req) => {
|
||||
const payload = (await req.json()) as AuthtypesTransactionDTO[];
|
||||
payload.forEach((txn) => seen.add(gettableTransactionToPermission(txn)));
|
||||
return undefined;
|
||||
}),
|
||||
);
|
||||
return seen;
|
||||
}
|
||||
|
||||
async function expandKey(
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
name: string,
|
||||
): Promise<void> {
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: new RegExp(`right ${name}`, 'i') }),
|
||||
);
|
||||
await screen.findByText('LIMITS');
|
||||
}
|
||||
|
||||
async function settledButton(testId: string): Promise<HTMLElement> {
|
||||
const button = await screen.findByTestId(testId);
|
||||
await waitFor(() => {
|
||||
expect(button).not.toHaveAttribute('aria-busy');
|
||||
});
|
||||
return button;
|
||||
}
|
||||
|
||||
function renderPage(): ReturnType<typeof userEvent.setup> {
|
||||
render(<MultiIngestionSettings />, undefined, { initialRoute: ROUTE });
|
||||
return userEvent.setup({ pointerEventsCheck: 0 });
|
||||
}
|
||||
|
||||
describe('MultiIngestionSettings authz', () => {
|
||||
afterEach(async () => {
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, 100);
|
||||
});
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('ingestion-key:list', () => {
|
||||
it('hides the list, disables search and fires no list request when denied', async () => {
|
||||
const onList = mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzDeny(IngestionKeyListPermission));
|
||||
|
||||
renderPage();
|
||||
|
||||
await screen.findByText(DENIED_TEXT);
|
||||
expect(
|
||||
screen.getByPlaceholderText('Search for ingestion key...'),
|
||||
).toBeDisabled();
|
||||
expect(screen.queryByText('Key One')).not.toBeInTheDocument();
|
||||
expect(onList).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows the list and requests it when granted', async () => {
|
||||
const onList = mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzAdmin());
|
||||
|
||||
renderPage();
|
||||
|
||||
await screen.findByText('Key One');
|
||||
expect(onList).toHaveBeenCalled();
|
||||
expect(screen.queryByText(DENIED_TEXT)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ingestion-key:create', () => {
|
||||
it('disables "New Ingestion key" when denied', async () => {
|
||||
mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzDeny(IngestionKeyCreatePermission));
|
||||
|
||||
renderPage();
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-key-add-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('enables "New Ingestion key" and opens the modal when granted', async () => {
|
||||
mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzAdmin());
|
||||
|
||||
const user = renderPage();
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-key-add-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
await user.click(screen.getByTestId('ingestion-key-add-btn'));
|
||||
|
||||
await screen.findByTestId('create-new-key');
|
||||
});
|
||||
});
|
||||
|
||||
describe('creating a key without list access', () => {
|
||||
it('sends no list request after the key is created', async () => {
|
||||
const onList = mockKeys([KEY_ONE]);
|
||||
const onCreate = jest.fn();
|
||||
server.use(
|
||||
setupAuthzDeny(IngestionKeyListPermission),
|
||||
rest.post('*/api/v2/gateway/ingestion_keys', (_req, res, ctx) => {
|
||||
onCreate();
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json({ status: 'success', data: { id: 'k9', value: 'v' } }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const user = renderPage();
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-key-add-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
await user.click(screen.getByTestId('ingestion-key-add-btn'));
|
||||
await user.type(await screen.findByLabelText('Name'), 'new-key');
|
||||
await user.click(screen.getByLabelText('Expiration'));
|
||||
await user.click(
|
||||
await screen.findByTitle(dayjs().add(1, 'day').format('YYYY-MM-DD')),
|
||||
);
|
||||
await user.click(screen.getByTestId('create-new-key'));
|
||||
|
||||
await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1));
|
||||
await screen.findByText(DENIED_TEXT);
|
||||
expect(onList).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ingestion-key:update', () => {
|
||||
it('disables "Update Ingestion Key" for the denied key', async () => {
|
||||
mockKeys([KEY_ONE, KEY_TWO]);
|
||||
server.use(setupAuthzDeny(buildIngestionKeyUpdatePermission('k1')));
|
||||
|
||||
const user = renderPage();
|
||||
|
||||
await user.click(await screen.findByTestId('ingestion-key-edit-btn-k1'));
|
||||
await expect(
|
||||
settledButton('ingestion-key-update-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('keeps "Update Ingestion Key" enabled for another key', async () => {
|
||||
mockKeys([KEY_ONE, KEY_TWO]);
|
||||
server.use(setupAuthzDeny(buildIngestionKeyUpdatePermission('k1')));
|
||||
|
||||
const user = renderPage();
|
||||
|
||||
await user.click(await screen.findByTestId('ingestion-key-edit-btn-k2'));
|
||||
await expect(
|
||||
settledButton('ingestion-key-update-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ingestion-key:delete', () => {
|
||||
it('disables "Delete Ingestion Key" when denied for that key', async () => {
|
||||
mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzDeny(buildIngestionKeyDeletePermission('k1')));
|
||||
|
||||
const user = renderPage();
|
||||
|
||||
await user.click(
|
||||
await screen.findByTestId('ingestion-key-delete-open-btn-k1'),
|
||||
);
|
||||
await expect(
|
||||
settledButton('ingestion-key-delete-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('saving a new limit', () => {
|
||||
it('disables "Save" when attach is denied on the key', async () => {
|
||||
mockKeys([KEY_TWO]);
|
||||
server.use(setupAuthzDeny(buildIngestionKeyAttachPermission('k2')));
|
||||
|
||||
const user = renderPage();
|
||||
await expandKey(user, 'Key Two');
|
||||
await user.click(screen.getByTestId('ingestion-limit-add-btn-logs'));
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-limit-save-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('disables "Save" when ingestion-limit:create is denied', async () => {
|
||||
mockKeys([KEY_TWO]);
|
||||
server.use(setupAuthzDeny(IngestionLimitCreatePermission));
|
||||
|
||||
const user = renderPage();
|
||||
await expandKey(user, 'Key Two');
|
||||
await user.click(screen.getByTestId('ingestion-limit-add-btn-logs'));
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-limit-save-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('saving an existing limit', () => {
|
||||
it('disables "Save" when update is denied on that limit', async () => {
|
||||
mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzDeny(buildIngestionLimitUpdatePermission('l1')));
|
||||
|
||||
const user = renderPage();
|
||||
await expandKey(user, 'Key One');
|
||||
await user.click(screen.getByTestId('edit-limit-btn-logs'));
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-limit-save-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('keeps "Save" enabled when only create and attach are denied', async () => {
|
||||
mockKeys([KEY_ONE]);
|
||||
server.use(
|
||||
setupAuthzDeny(
|
||||
IngestionLimitCreatePermission,
|
||||
buildIngestionKeyAttachPermission('k1'),
|
||||
),
|
||||
);
|
||||
|
||||
const user = renderPage();
|
||||
await expandKey(user, 'Key One');
|
||||
await user.click(screen.getByTestId('edit-limit-btn-logs'));
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-limit-save-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleting a limit', () => {
|
||||
it.each([
|
||||
['ingestion-limit:delete', buildIngestionLimitDeletePermission('l1')],
|
||||
['ingestion-key:detach', buildIngestionKeyDetachPermission('k1')],
|
||||
])('disables "Delete Limit" when %s is denied', async (_name, denied) => {
|
||||
mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzDeny(denied));
|
||||
|
||||
const user = renderPage();
|
||||
await expandKey(user, 'Key One');
|
||||
await user.click(screen.getByTestId('ingestion-limit-delete-open-btn-logs'));
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-limit-delete-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('id checks', () => {
|
||||
it('only checks list and create on load, and per-id checks once a modal opens', async () => {
|
||||
mockKeys([KEY_ONE, KEY_TWO, KEY_THREE]);
|
||||
server.use(setupAuthzAdmin());
|
||||
const seen = recordAuthzChecks();
|
||||
|
||||
const user = renderPage();
|
||||
|
||||
await screen.findByText('Key Three');
|
||||
await expect(
|
||||
settledButton('ingestion-key-add-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
expect([...seen].sort()).toStrictEqual(
|
||||
[IngestionKeyListPermission, IngestionKeyCreatePermission].sort(),
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('ingestion-key-edit-btn-k1'));
|
||||
await expect(
|
||||
settledButton('ingestion-key-update-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
expect(seen.has(buildIngestionKeyUpdatePermission('k1'))).toBe(true);
|
||||
expect(seen.has(buildIngestionKeyUpdatePermission('k2'))).toBe(false);
|
||||
expect(seen.has(buildIngestionKeyUpdatePermission('k3'))).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import { GatewaytypesGettableIngestionKeysDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
@@ -40,7 +39,6 @@ const GLOBAL_CONFIG_RESPONSE = {
|
||||
describe('MultiIngestionSettings Page', () => {
|
||||
beforeEach(() => {
|
||||
mockNavigate.mockClear();
|
||||
server.use(setupAuthzAdmin());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -352,7 +350,7 @@ describe('MultiIngestionSettings Page', () => {
|
||||
initialRoute: INGESTION_SETTINGS_ROUTE,
|
||||
});
|
||||
|
||||
await screen.findByText('Key Regular', undefined, { timeout: 5000 });
|
||||
await screen.findByText('Key Regular');
|
||||
expect(getHandler).toHaveBeenCalled();
|
||||
expect(searchHandler).not.toHaveBeenCalled();
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@ import { Dispatch, SetStateAction, useEffect, useMemo, useState } from 'react';
|
||||
import { useAppNavigate } from 'lib/router/useAppNavigate';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Select, SelectProps, Skeleton } from 'antd';
|
||||
import { Select, Skeleton } from 'antd';
|
||||
import { SelectProps } from 'antd/lib';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { useListAccounts } from 'api/generated/services/cloudintegration';
|
||||
import cx from 'classnames';
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
import { ComponentProps } from 'react';
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} 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 { Region } from 'utils/regions';
|
||||
import type logEvent from '../../../../../api/common/logEvent';
|
||||
|
||||
import CloudAccountSetupModal from '../AddNewAccount/CloudAccountSetupModal';
|
||||
@@ -22,24 +14,6 @@ jest.mock('../../../../../api/common/logEvent', () => ({
|
||||
default: jest.fn() as jest.MockedFunction<typeof logEvent>,
|
||||
}));
|
||||
|
||||
jest.mock('utils/regions', () => {
|
||||
const regions: Region[] = [
|
||||
{
|
||||
id: 'north-america',
|
||||
name: 'North America',
|
||||
subRegions: [
|
||||
{
|
||||
id: 'us-east-1',
|
||||
name: 'us-east-1',
|
||||
displayName: 'US East (N. Virginia)',
|
||||
},
|
||||
{ id: 'us-east-2', name: 'us-east-2', displayName: 'US East (Ohio)' },
|
||||
],
|
||||
},
|
||||
];
|
||||
return { regions };
|
||||
});
|
||||
|
||||
type OnClose = ComponentProps<typeof CloudAccountSetupModal>['onClose'];
|
||||
|
||||
const mockOnClose = (): jest.MockedFunction<OnClose> =>
|
||||
@@ -122,7 +96,7 @@ 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(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
|
||||
|
||||
@@ -149,7 +123,7 @@ describe('AWS CloudAccountSetupModal', () => {
|
||||
|
||||
it('asks before closing once a setup command exists', async () => {
|
||||
mockApi();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
const onClose = mockOnClose();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={onClose} />);
|
||||
@@ -172,7 +146,7 @@ describe('AWS CloudAccountSetupModal', () => {
|
||||
|
||||
it('closes without asking before a setup command exists', async () => {
|
||||
mockApi();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
const onClose = mockOnClose();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={onClose} />);
|
||||
@@ -185,7 +159,7 @@ describe('AWS CloudAccountSetupModal', () => {
|
||||
|
||||
it('resumes polling with Check Again after the connection check fails', async () => {
|
||||
const api = mockApi({ failFirstPoll: true });
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Modal } from 'antd';
|
||||
import { Modal } from 'antd/lib';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { useDisconnectAccount } from 'api/generated/services/cloudintegration';
|
||||
import { CloudintegrationtypesGCPConnectionMethodDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
@@ -1,18 +1,10 @@
|
||||
import {
|
||||
SpantypesFieldContextDTO as FieldContext,
|
||||
SpantypesSpanMapperDTO as Mapper,
|
||||
SpantypesSpanMapperOperationDTO as MapperOperation,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
|
||||
jest.mock('@signozhq/ui/toast', () => ({
|
||||
...jest.requireActual('@signozhq/ui/toast'),
|
||||
@@ -48,9 +40,7 @@ import { DraftGroup } from 'container/LLMObservability/AttributeMapping/types';
|
||||
import AttributeMappingsTab from '../AttributeMappingsTab';
|
||||
import { useAttributeMappingEditor } from '../../hooks/useAttributeMappingEditor';
|
||||
|
||||
const [FIRST_GROUP] = mockGroups;
|
||||
|
||||
function setupGroups(groups = [FIRST_GROUP]): void {
|
||||
function setupGroups(groups = mockGroups): void {
|
||||
server.use(
|
||||
rest.get(GROUPS_ENDPOINT, (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(makeGroupsResponse(groups))),
|
||||
@@ -165,7 +155,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('renders each group header row with its name, condition count and status', async () => {
|
||||
setupGroups(mockGroups);
|
||||
setupGroups();
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
|
||||
// Condition filters are no longer shown inline as clauses — the header
|
||||
@@ -189,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(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
|
||||
@@ -201,7 +191,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('invokes onAddGroup from the toolbar button', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
const onAddGroup = jest.fn() as jest.MockedFunction<() => void>;
|
||||
setupGroups();
|
||||
render(<AttributeMappingsTabWithStore onAddGroup={onAddGroup} />);
|
||||
@@ -213,7 +203,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('invokes onEditGroup with the group when Edit is chosen from the actions menu', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
const onEditGroup = jest.fn() as jest.MockedFunction<
|
||||
(group: DraftGroup) => void
|
||||
>;
|
||||
@@ -234,8 +224,8 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('stages a group removal when Delete is chosen from the actions menu', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
setupGroups(mockGroups);
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
|
||||
await screen.findByTestId('group-name-group-1');
|
||||
@@ -251,7 +241,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it("reveals a group's mappers on expand and hides them on collapse", async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
setupMappers([makeMapper({ id: 'mapper-1' })]);
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
@@ -281,7 +271,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it("lazily fetches and renders a group's mappers on first expand", async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
setupMappers([
|
||||
makeMapper({ id: 'mapper-1', name: 'gen_ai.request.model', enabled: true }),
|
||||
@@ -310,7 +300,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('shows the mappers error state when the mappers request fails', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
server.use(
|
||||
rest.get(mappersEndpoint('group-1'), (_req, res, ctx) =>
|
||||
@@ -328,7 +318,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('shows the mappers empty state when a group has no mappers', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
setupMappers([]);
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
@@ -342,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(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
setupMappers([
|
||||
makeMapper({
|
||||
@@ -367,7 +357,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('shows a muted placeholder when a mapper has no sources', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
setupMappers([makeMapper({ id: 'mapper-1', config: { sources: [] } })]);
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
@@ -381,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(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
|
||||
let mappers = mockMappers;
|
||||
@@ -414,7 +404,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('warns and keeps the working copy when the post-save refresh fails', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
jest.mocked(toast.success).mockClear();
|
||||
jest.mocked(toast.warning).mockClear();
|
||||
|
||||
@@ -423,7 +413,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
rest.get(GROUPS_ENDPOINT, (_req, res, ctx) =>
|
||||
failRefresh
|
||||
? res(ctx.status(500), ctx.json({ status: 'error' }))
|
||||
: res(ctx.status(200), ctx.json(makeGroupsResponse([FIRST_GROUP]))),
|
||||
: res(ctx.status(200), ctx.json(makeGroupsResponse(mockGroups))),
|
||||
),
|
||||
rest.patch(`${GROUPS_ENDPOINT}/:groupId`, (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'ok' })),
|
||||
@@ -445,37 +435,21 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
describe('mapper drawer', () => {
|
||||
async function openGroup(
|
||||
async function openGroupWithMapper(
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
mappers: Mapper[],
|
||||
): Promise<void> {
|
||||
setupGroups();
|
||||
setupMappers(mappers);
|
||||
setupMappers([makeMapper({ id: 'mapper-1', name: 'gen_ai.request.model' })]);
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
|
||||
await screen.findByTestId('group-name-group-1');
|
||||
await expandGroup(user);
|
||||
}
|
||||
|
||||
async function openGroupWithMapper(
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
): Promise<void> {
|
||||
await openGroup(user, [
|
||||
makeMapper({ id: 'mapper-1', name: 'gen_ai.request.model' }),
|
||||
]);
|
||||
await screen.findByTestId('mapper-target-mapper-1');
|
||||
}
|
||||
|
||||
async function openEmptyGroup(
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
): Promise<void> {
|
||||
await openGroup(user, []);
|
||||
await screen.findByTestId('mappers-empty-group-1');
|
||||
}
|
||||
|
||||
it('opens the add-mapping drawer from a group\'s "Add mapping" button', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
await openEmptyGroup(user);
|
||||
const user = userEvent.setup();
|
||||
await openGroupWithMapper(user);
|
||||
|
||||
expect(screen.queryByTestId('mapper-form-drawer')).not.toBeInTheDocument();
|
||||
await user.click(screen.getByTestId('add-mapper-group-1'));
|
||||
@@ -487,7 +461,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('opens the edit drawer prefilled and locks the target attribute', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
await openGroupWithMapper(user);
|
||||
|
||||
await user.click(screen.getByTestId('mapper-actions-mapper-1'));
|
||||
@@ -505,7 +479,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it("toggles a mapper's enabled state through the store", async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
await openGroupWithMapper(user);
|
||||
|
||||
const toggle = screen.getByTestId('mapper-enabled-mapper-1');
|
||||
@@ -519,7 +493,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('removes a mapper via the row action menu', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
await openGroupWithMapper(user);
|
||||
|
||||
await user.click(screen.getByTestId('mapper-actions-mapper-1'));
|
||||
@@ -536,8 +510,8 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('creates a new mapping through the drawer and appends it to the group', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
await openEmptyGroup(user);
|
||||
const user = userEvent.setup();
|
||||
await openGroupWithMapper(user);
|
||||
|
||||
await user.click(screen.getByTestId('add-mapper-group-1'));
|
||||
await screen.findByTestId('mapper-form-drawer');
|
||||
@@ -597,7 +571,7 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('renders mappers read-only: no "Add mapping" button or row actions', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
setupGroups();
|
||||
setupMappers([makeMapper({ id: 'mapper-1', name: 'gen_ai.request.model' })]);
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
import { useMemo } from 'react';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import ExplorerActions from 'container/ExplorerActions/ExplorerActions';
|
||||
import { ExplorerActionsSource } from 'container/ExplorerActions/utils';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
|
||||
import { getAlertQuery, getExportQuery } from '../explorerUtils';
|
||||
|
||||
interface AIExplorerActionsProps {
|
||||
panelType: PANEL_TYPES;
|
||||
selectColumns?: TelemetryFieldKey[];
|
||||
}
|
||||
|
||||
function AIExplorerActions({
|
||||
panelType,
|
||||
selectColumns,
|
||||
}: AIExplorerActionsProps): JSX.Element {
|
||||
const { stagedQuery } = useQueryBuilder();
|
||||
|
||||
const alertQuery = useMemo(
|
||||
() => (stagedQuery ? getAlertQuery(stagedQuery, panelType) : null),
|
||||
[stagedQuery, panelType],
|
||||
);
|
||||
|
||||
const dashboardQuery = useMemo(
|
||||
() =>
|
||||
stagedQuery ? getExportQuery(stagedQuery, panelType, selectColumns) : null,
|
||||
[stagedQuery, panelType, selectColumns],
|
||||
);
|
||||
|
||||
return (
|
||||
<ExplorerActions
|
||||
query={alertQuery}
|
||||
dashboardQuery={dashboardQuery}
|
||||
sourcePage={ExplorerActionsSource.AI_OBSERVABILITY_EXPLORER}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default AIExplorerActions;
|
||||
@@ -1,301 +0,0 @@
|
||||
import { logEventMock } from '__tests__/logEventMock';
|
||||
import { safeNavigateMock } from '__tests__/safeNavigateMock';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import {
|
||||
initialFormulaBuilderFormValues,
|
||||
initialQueryAIWithType,
|
||||
PANEL_TYPES,
|
||||
} from 'constants/queryBuilder';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { ExplorerActionsSource } from 'container/ExplorerActions/utils';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { mockAppNavigate } from 'tests/router-mocks';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import AIExplorerActions from '../AIExplorerActions';
|
||||
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: jest.fn(),
|
||||
}));
|
||||
|
||||
const mockedUseQueryBuilder = jest.mocked(useQueryBuilder);
|
||||
|
||||
const FILTER = "gen_ai.request.model = 'gpt-4o'";
|
||||
|
||||
const USER_COLUMNS: TelemetryFieldKey[] = [
|
||||
{ name: 'gen_ai.request.model', fieldContext: 'attribute' },
|
||||
{ name: 'duration_nano' },
|
||||
];
|
||||
|
||||
function aiStagedQuery(aggregations?: IBuilderQuery['aggregations']): Query {
|
||||
const aiBuilder = getActiveBuilder(initialQueryAIWithType);
|
||||
return {
|
||||
...initialQueryAIWithType,
|
||||
builder_ai_query: {
|
||||
...aiBuilder,
|
||||
queryData: [
|
||||
{
|
||||
...aiBuilder.queryData[0],
|
||||
...(aggregations && { aggregations }),
|
||||
filter: { expression: FILTER },
|
||||
groupBy: [
|
||||
{ key: 'service.name', dataType: DataTypes.String, type: 'resource' },
|
||||
],
|
||||
having: { expression: 'count() > 5' },
|
||||
orderBy: [{ columnName: 'timestamp', order: 'asc' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function exportFrom(
|
||||
panelType: PANEL_TYPES,
|
||||
stagedQuery: Query = aiStagedQuery(),
|
||||
selectColumns?: TelemetryFieldKey[],
|
||||
): Promise<void> {
|
||||
mockedUseQueryBuilder.mockReturnValue({
|
||||
stagedQuery,
|
||||
panelType,
|
||||
} as ReturnType<typeof useQueryBuilder>);
|
||||
server.use(
|
||||
rest.get('*/api/v2/users/me/dashboards', (_req, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({ status: 'success', data: { dashboards: [] } }),
|
||||
),
|
||||
),
|
||||
rest.post('*/api/v2/dashboards', (_req, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({ status: 'success', data: { id: 'dash-1' } }),
|
||||
),
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<AIExplorerActions panelType={panelType} selectColumns={selectColumns} />,
|
||||
);
|
||||
await user.click(screen.getByTestId('explorer-add-to-dashboard'));
|
||||
await user.click(await screen.findByTestId('export-panel-new-dashboard'));
|
||||
|
||||
await waitFor(() => expect(safeNavigateMock).toHaveBeenCalledTimes(1));
|
||||
}
|
||||
|
||||
async function createAlertFrom(
|
||||
panelType: PANEL_TYPES,
|
||||
stagedQuery: Query = aiStagedQuery(),
|
||||
): Promise<Query> {
|
||||
const navigate = mockAppNavigate();
|
||||
mockedUseQueryBuilder.mockReturnValue({
|
||||
stagedQuery,
|
||||
panelType,
|
||||
} as ReturnType<typeof useQueryBuilder>);
|
||||
|
||||
render(<AIExplorerActions panelType={panelType} />);
|
||||
await userEvent.setup().click(screen.getByTestId('explorer-create-alert'));
|
||||
|
||||
expect(navigate).toHaveBeenCalledTimes(1);
|
||||
const [path, search] = (navigate.mock.calls[0][0] as string).split('?');
|
||||
expect(path).toBe(ROUTES.ALERTS_NEW);
|
||||
return JSON.parse(
|
||||
decodeURIComponent(
|
||||
new URLSearchParams(search).get(QueryParams.compositeQuery) ?? '',
|
||||
),
|
||||
) as Query;
|
||||
}
|
||||
|
||||
function exportedPanel(): { panelKind: string | null; query: Query } {
|
||||
const link = safeNavigateMock.mock.calls[0][0] as string;
|
||||
const params = new URLSearchParams(link.split('?')[1]);
|
||||
return {
|
||||
panelKind: params.get('panelKind'),
|
||||
query: JSON.parse(
|
||||
decodeURIComponent(params.get(QueryParams.compositeQuery) ?? ''),
|
||||
) as Query,
|
||||
};
|
||||
}
|
||||
|
||||
describe('AIExplorerActions', () => {
|
||||
it('logs the AI explorer events, not the traces ones', async () => {
|
||||
await exportFrom(PANEL_TYPES.TABLE);
|
||||
|
||||
expect(logEventMock).toHaveBeenCalledWith(
|
||||
'AI Observability Explorer: Add to dashboard clicked',
|
||||
{
|
||||
sourcepage: ExplorerActionsSource.AI_OBSERVABILITY_EXPLORER,
|
||||
panelType: PANEL_TYPES.TABLE,
|
||||
},
|
||||
);
|
||||
expect(logEventMock).toHaveBeenCalledWith(
|
||||
'AI Observability Explorer: Add to dashboard successful',
|
||||
{
|
||||
sourcepage: ExplorerActionsSource.AI_OBSERVABILITY_EXPLORER,
|
||||
panelType: PANEL_TYPES.TABLE,
|
||||
isNewDashboard: true,
|
||||
dashboardName: expect.any(String),
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('list: exports an AI List panel with the user picked columns and no group by, having or order by', async () => {
|
||||
await exportFrom(PANEL_TYPES.LIST, aiStagedQuery(), USER_COLUMNS);
|
||||
|
||||
const { panelKind, query } = exportedPanel();
|
||||
expect(panelKind).toBe('signoz/ListPanel');
|
||||
expect(query.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
|
||||
expect(getActiveBuilder(query).queryData[0]).toMatchObject({
|
||||
filter: { expression: FILTER },
|
||||
groupBy: [],
|
||||
having: { expression: '' },
|
||||
orderBy: [],
|
||||
selectColumns: USER_COLUMNS,
|
||||
});
|
||||
});
|
||||
|
||||
it('trace: exports an AI Time Series panel with no group by, having or order by', async () => {
|
||||
await exportFrom(PANEL_TYPES.TRACE);
|
||||
|
||||
const { panelKind, query } = exportedPanel();
|
||||
expect(panelKind).toBe('signoz/TimeSeriesPanel');
|
||||
expect(query.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
|
||||
const [queryData] = getActiveBuilder(query).queryData;
|
||||
expect(queryData).toMatchObject({
|
||||
filter: { expression: FILTER },
|
||||
groupBy: [],
|
||||
having: { expression: '' },
|
||||
orderBy: [],
|
||||
});
|
||||
expect(queryData.selectColumns).toBeUndefined();
|
||||
});
|
||||
|
||||
it('trace: exports without the formulas, step, limit and legend Timeseries set', async () => {
|
||||
const stagedQuery = aiStagedQuery();
|
||||
const aiBuilder = getActiveBuilder(stagedQuery);
|
||||
await exportFrom(PANEL_TYPES.TRACE, {
|
||||
...stagedQuery,
|
||||
builder_ai_query: {
|
||||
...aiBuilder,
|
||||
queryData: [
|
||||
{
|
||||
...aiBuilder.queryData[0],
|
||||
stepInterval: 300,
|
||||
limit: 10,
|
||||
legend: '{{service.name}}',
|
||||
},
|
||||
],
|
||||
queryFormulas: [
|
||||
{ ...initialFormulaBuilderFormValues, expression: 'A*100' },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const exported = getActiveBuilder(exportedPanel().query);
|
||||
expect(exported.queryFormulas).toStrictEqual([]);
|
||||
expect(exported.queryData[0]).toMatchObject({
|
||||
stepInterval: null,
|
||||
limit: null,
|
||||
legend: '',
|
||||
});
|
||||
});
|
||||
|
||||
it('create alert: logs the AI explorer event, not the traces one', async () => {
|
||||
await createAlertFrom(PANEL_TYPES.TIME_SERIES);
|
||||
|
||||
expect(logEventMock).toHaveBeenCalledWith(
|
||||
'AI Observability Explorer: Create alert',
|
||||
{
|
||||
sourcepage: ExplorerActionsSource.AI_OBSERVABILITY_EXPLORER,
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('without a staged query: both actions are disabled and create alert goes nowhere', async () => {
|
||||
const navigate = mockAppNavigate();
|
||||
mockedUseQueryBuilder.mockReturnValue({
|
||||
stagedQuery: null,
|
||||
panelType: PANEL_TYPES.LIST,
|
||||
} as ReturnType<typeof useQueryBuilder>);
|
||||
|
||||
render(<AIExplorerActions panelType={PANEL_TYPES.LIST} />);
|
||||
const createAlert = screen.getByTestId('explorer-create-alert');
|
||||
await userEvent.setup().click(createAlert);
|
||||
|
||||
expect(createAlert).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(screen.getByTestId('explorer-add-to-dashboard')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([PANEL_TYPES.TIME_SERIES, PANEL_TYPES.TABLE])(
|
||||
'create alert from %s: keeps the aggregation, group by, having and order by',
|
||||
async (panelType) => {
|
||||
const query = await createAlertFrom(
|
||||
panelType,
|
||||
aiStagedQuery([{ expression: 'avg(duration_nano)' }]),
|
||||
);
|
||||
|
||||
expect(query.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
|
||||
expect(getActiveBuilder(query).queryData[0]).toMatchObject({
|
||||
aggregations: [{ expression: 'avg(duration_nano)' }],
|
||||
filter: { expression: FILTER },
|
||||
groupBy: [
|
||||
{ key: 'service.name', dataType: DataTypes.String, type: 'resource' },
|
||||
],
|
||||
having: { expression: 'count() > 5' },
|
||||
orderBy: [{ columnName: 'timestamp', order: 'asc' }],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([PANEL_TYPES.LIST, PANEL_TYPES.TRACE])(
|
||||
'create alert from %s: a count with no group by, having or order by',
|
||||
async (panelType) => {
|
||||
const query = await createAlertFrom(
|
||||
panelType,
|
||||
aiStagedQuery([{ expression: 'avg(duration_nano)' }]),
|
||||
);
|
||||
|
||||
expect(query.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
|
||||
const [queryData] = getActiveBuilder(query).queryData;
|
||||
expect(queryData).toMatchObject({
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
filter: { expression: FILTER },
|
||||
groupBy: [],
|
||||
having: { expression: '' },
|
||||
orderBy: [],
|
||||
});
|
||||
expect(queryData.selectColumns).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([PANEL_TYPES.LIST, PANEL_TYPES.TRACE])(
|
||||
'create alert from %s: only the first query, the one the view shows',
|
||||
async (panelType) => {
|
||||
const stagedQuery = aiStagedQuery();
|
||||
const aiBuilder = getActiveBuilder(stagedQuery);
|
||||
const [first] = aiBuilder.queryData;
|
||||
const query = await createAlertFrom(panelType, {
|
||||
...stagedQuery,
|
||||
builder_ai_query: {
|
||||
...aiBuilder,
|
||||
queryData: [first, { ...first, queryName: 'B', expression: 'B' }],
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
getActiveBuilder(query).queryData.map(({ queryName }) => queryName),
|
||||
).toStrictEqual([first.queryName]);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -38,7 +38,6 @@ import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import { getListOrderBy, setListOrderBy } from 'utils/explorerUtils';
|
||||
|
||||
import AIExplorerActions from '../AIExplorerActions/AIExplorerActions';
|
||||
import TraceExplorerControls from '../Controls';
|
||||
import { getListViewQuery } from '../explorerUtils';
|
||||
import { PER_PAGE_OPTIONS, TIMESTAMP_FIELD } from './configs';
|
||||
@@ -214,10 +213,6 @@ function ListView({
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className="trace-explorer-controls">
|
||||
<AIExplorerActions
|
||||
panelType={PANEL_TYPES.LIST}
|
||||
selectColumns={selectColumns}
|
||||
/>
|
||||
<div className="order-by-container">
|
||||
<div className="order-by-label">
|
||||
Order by <Minus size={14} /> <ArrowUp10 size={14} />
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
useEffect,
|
||||
useMemo,
|
||||
} from 'react';
|
||||
import { QueryKey } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import Space from 'periscope/components/Space/Space';
|
||||
@@ -25,8 +24,6 @@ import { QueryDataV3 } from 'types/api/widgets/getQuery';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import AIExplorerActions from '../AIExplorerActions/AIExplorerActions';
|
||||
|
||||
import './TableView.styles.scss';
|
||||
|
||||
function TableView({
|
||||
@@ -36,7 +33,7 @@ function TableView({
|
||||
}: {
|
||||
setWarning: Dispatch<SetStateAction<Warning | undefined>>;
|
||||
setIsLoadingQueries: Dispatch<SetStateAction<boolean>>;
|
||||
queryKeyRef?: MutableRefObject<QueryKey | undefined>;
|
||||
queryKeyRef?: MutableRefObject<any>;
|
||||
}): JSX.Element {
|
||||
const { stagedQuery, panelType } = useQueryBuilder();
|
||||
|
||||
@@ -104,17 +101,14 @@ function TableView({
|
||||
return (
|
||||
<Space.Compact block direction="vertical">
|
||||
{isError && error && <ErrorInPlace error={error as APIError} />}
|
||||
{!isError && (
|
||||
{!isError && data && (
|
||||
<div className="traces-table-view-header">
|
||||
<AIExplorerActions panelType={PANEL_TYPES.TABLE} />
|
||||
{data && (
|
||||
<ExportMenu
|
||||
dataSource={DataSource.TRACES}
|
||||
data={data}
|
||||
query={stagedQuery || initialQueriesMap.traces}
|
||||
fileName="ai-traces-table"
|
||||
/>
|
||||
)}
|
||||
<ExportMenu
|
||||
dataSource={DataSource.TRACES}
|
||||
data={data}
|
||||
query={stagedQuery || initialQueriesMap.traces}
|
||||
fileName="ai-traces-table"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{!isError && (
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
useEffect,
|
||||
useMemo,
|
||||
} from 'react';
|
||||
import { QueryKey } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
@@ -23,8 +22,6 @@ import APIError from 'types/api/error';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import AIExplorerActions from '../AIExplorerActions/AIExplorerActions';
|
||||
|
||||
import './TimeSeriesView.styles.scss';
|
||||
|
||||
function TimeSeriesViewContainer({
|
||||
@@ -131,7 +128,6 @@ function TimeSeriesViewContainer({
|
||||
setWarning={setWarning}
|
||||
allowExport
|
||||
exportFileName="ai-traces-timeseries"
|
||||
headerActions={<AIExplorerActions panelType={PANEL_TYPES.TIME_SERIES} />}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -142,7 +138,7 @@ interface TimeSeriesViewProps {
|
||||
isFilterApplied: boolean;
|
||||
setWarning: Dispatch<SetStateAction<Warning | undefined>>;
|
||||
setIsLoadingQueries: Dispatch<SetStateAction<boolean>>;
|
||||
queryKeyRef?: MutableRefObject<QueryKey | undefined>;
|
||||
queryKeyRef?: MutableRefObject<any>;
|
||||
}
|
||||
|
||||
TimeSeriesViewContainer.defaultProps = {
|
||||
|
||||
@@ -34,7 +34,6 @@ import { Warning } from 'types/api';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import AIExplorerActions from '../AIExplorerActions/AIExplorerActions';
|
||||
import TraceExplorerControls from '../Controls';
|
||||
import {
|
||||
TRACE_VIEW_BUILDER_QUERY_TYPE,
|
||||
@@ -192,7 +191,6 @@ function TracesView({
|
||||
<div className={styles.container}>
|
||||
<div className={styles.actionsContainer}>
|
||||
<div className="trace-explorer-controls">
|
||||
<AIExplorerActions panelType={PANEL_TYPES.TRACE} />
|
||||
<div className={styles.orderByContainer}>
|
||||
<div className={styles.orderByLabel}>
|
||||
Order by <Minus size={14} /> <ArrowUp10 size={14} />
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { initialQueryAIWithType, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import ListView from '../ListView/ListView';
|
||||
import TableView from '../TableView/TableView';
|
||||
import TimeSeriesView from '../TimeSeriesView/TimeSeriesView';
|
||||
import TracesView from '../TracesView/TracesView';
|
||||
|
||||
const QUERY_RANGE_URL = `${ENVIRONMENT.baseURL}/api/v5/query_range`;
|
||||
|
||||
const VIEWS: [PANEL_TYPES, () => JSX.Element][] = [
|
||||
[
|
||||
PANEL_TYPES.LIST,
|
||||
(): JSX.Element => (
|
||||
<ListView
|
||||
isFilterApplied={false}
|
||||
setWarning={jest.fn()}
|
||||
setIsLoadingQueries={jest.fn()}
|
||||
/>
|
||||
),
|
||||
],
|
||||
[
|
||||
PANEL_TYPES.TRACE,
|
||||
(): JSX.Element => (
|
||||
<TracesView
|
||||
isFilterApplied={false}
|
||||
setWarning={jest.fn()}
|
||||
setIsLoadingQueries={jest.fn()}
|
||||
/>
|
||||
),
|
||||
],
|
||||
[
|
||||
PANEL_TYPES.TIME_SERIES,
|
||||
(): JSX.Element => (
|
||||
<TimeSeriesView
|
||||
dataSource={DataSource.TRACES}
|
||||
isFilterApplied={false}
|
||||
setWarning={jest.fn()}
|
||||
setIsLoadingQueries={jest.fn()}
|
||||
/>
|
||||
),
|
||||
],
|
||||
[
|
||||
PANEL_TYPES.TABLE,
|
||||
(): JSX.Element => (
|
||||
<TableView setWarning={jest.fn()} setIsLoadingQueries={jest.fn()} />
|
||||
),
|
||||
],
|
||||
];
|
||||
|
||||
describe('AI explorer views', () => {
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ data: { data: { results: [] } } })),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.each(VIEWS)(
|
||||
'%s: offers Create an alert and Add to dashboard for the staged query, before data arrives',
|
||||
(panelType, renderView) => {
|
||||
render(
|
||||
renderView(),
|
||||
{},
|
||||
{
|
||||
queryBuilderOverrides: {
|
||||
panelType,
|
||||
stagedQuery: initialQueryAIWithType,
|
||||
currentQuery: initialQueryAIWithType,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('explorer-create-alert')).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(screen.getByTestId('explorer-add-to-dashboard')).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,16 +1,9 @@
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import {
|
||||
getActiveBuilder,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
replaceBuilderBySlotKey,
|
||||
} from 'lib/query/builderSlot';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { cloneDeep } from 'lodash-es';
|
||||
import { OrderByPayload, Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { parseListOrderBy } from 'utils/explorerUtils';
|
||||
|
||||
import { defaultSelectedColumns } from './ListView/configs';
|
||||
|
||||
export const getListViewQuery = (
|
||||
stagedQuery: Query,
|
||||
orderBy?: string,
|
||||
@@ -35,43 +28,3 @@ export const getListViewQuery = (
|
||||
|
||||
return query;
|
||||
};
|
||||
|
||||
export const getAlertQuery = (
|
||||
stagedQuery: Query,
|
||||
panelType: PANEL_TYPES,
|
||||
): Query => {
|
||||
if (panelType !== PANEL_TYPES.LIST && panelType !== PANEL_TYPES.TRACE) {
|
||||
return stagedQuery;
|
||||
}
|
||||
const query = getListViewQuery(stagedQuery);
|
||||
const builder = getActiveBuilder(query);
|
||||
// List and Trace show only the first query's filter, so nothing another view set may reach the alert or chart.
|
||||
return replaceBuilderBySlotKey(
|
||||
query,
|
||||
getBuilderSlotKeyForQueryType(query.queryType),
|
||||
{
|
||||
...builder,
|
||||
queryData: builder.queryData.slice(0, 1).map((item) => ({
|
||||
...item,
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
stepInterval: null,
|
||||
limit: null,
|
||||
legend: '',
|
||||
})),
|
||||
queryFormulas: [],
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getExportQuery = (
|
||||
stagedQuery: Query,
|
||||
panelType: PANEL_TYPES,
|
||||
selectColumns: TelemetryFieldKey[] = defaultSelectedColumns,
|
||||
): Query => {
|
||||
const query = getAlertQuery(stagedQuery, panelType);
|
||||
const [queryData] = getActiveBuilder(query).queryData;
|
||||
if (panelType === PANEL_TYPES.LIST && queryData) {
|
||||
queryData.selectColumns = selectColumns;
|
||||
}
|
||||
return query;
|
||||
};
|
||||
|
||||
@@ -5,30 +5,11 @@ import {
|
||||
makeListResponse,
|
||||
makeUnmappedResponse,
|
||||
mockRules,
|
||||
mockUnpricedModels,
|
||||
} from 'container/LLMObservability/Settings/ModelPricing/__tests__/fixtures';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
|
||||
import UnpricedModelsTab from '../UnpricedModelsTab';
|
||||
import { usePendingMappingStore } from '../usePendingMappingStore';
|
||||
|
||||
// One antd skeleton renders per placeholder row and per dropdown option on every
|
||||
// load, so fewer of them keep each test's first paint cheap.
|
||||
jest.mock('container/LLMObservability/Settings/ModelPricing/constants', () => ({
|
||||
...jest.requireActual(
|
||||
'container/LLMObservability/Settings/ModelPricing/constants',
|
||||
),
|
||||
SKELETON_ROW_COUNT: 1,
|
||||
RULE_OPTIONS_LIMIT: 2,
|
||||
}));
|
||||
|
||||
const toastSuccess = jest.fn();
|
||||
const toastError = jest.fn();
|
||||
@@ -40,20 +21,12 @@ jest.mock('@signozhq/ui/toast', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const [UNPRICED_MODEL] = mockUnpricedModels;
|
||||
const MODEL = UNPRICED_MODEL.modelName;
|
||||
const [TARGET_RULE] = mockRules;
|
||||
|
||||
function stageMapping(): void {
|
||||
usePendingMappingStore.setState({
|
||||
pending: { model: UNPRICED_MODEL, rule: TARGET_RULE },
|
||||
});
|
||||
}
|
||||
const MODEL = 'gpt-4o-mini-2024-07-18';
|
||||
|
||||
function setup(): void {
|
||||
server.use(
|
||||
rest.get(LLM_UNMAPPED_ENDPOINT, (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(makeUnmappedResponse([UNPRICED_MODEL]))),
|
||||
res(ctx.status(200), ctx.json(makeUnmappedResponse())),
|
||||
),
|
||||
rest.get(LLM_PRICING_ENDPOINT, (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(makeListResponse(mockRules))),
|
||||
@@ -63,8 +36,8 @@ function setup(): void {
|
||||
|
||||
// Picks a billing model in a row's dropdown: open the combobox, wait for the
|
||||
// options (fetched from the rules list mocked above), then arrow down to the
|
||||
// option and press Enter in its search box. jsdom cannot deliver the pointer
|
||||
// click Base UI expects on an option.
|
||||
// option and press Enter. jsdom cannot deliver the pointer click Base UI
|
||||
// expects on an option.
|
||||
async function selectRule(
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
modelName: string,
|
||||
@@ -77,10 +50,10 @@ async function selectRule(
|
||||
.findIndex(
|
||||
(option) => option.getAttribute('data-testid') === `map-to-option-${ruleId}`,
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId(`map-to-select-${modelName}-search`),
|
||||
`${'{ArrowDown}'.repeat(index + 1)}{Enter}`,
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId(`map-to-select-${modelName}-search`)).toHaveFocus(),
|
||||
);
|
||||
await user.keyboard(`${'{ArrowDown}'.repeat(index + 1)}{Enter}`);
|
||||
}
|
||||
|
||||
describe('UnpricedModelsTab (integration)', () => {
|
||||
@@ -91,36 +64,12 @@ describe('UnpricedModelsTab (integration)', () => {
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
usePendingMappingStore.getState().clearPending();
|
||||
toastSuccess.mockClear();
|
||||
toastError.mockClear();
|
||||
});
|
||||
|
||||
it('cancels the mapping without committing', async () => {
|
||||
const sent: LlmpricingruletypesUpdatableLLMPricingRulesDTO[] = [];
|
||||
server.use(
|
||||
rest.put(LLM_PRICING_ENDPOINT, async (req, res, ctx) => {
|
||||
sent.push(await req.json());
|
||||
return res(ctx.status(200), ctx.json({ status: 'success' }));
|
||||
}),
|
||||
);
|
||||
|
||||
stageMapping();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
render(<UnpricedModelsTab />);
|
||||
|
||||
await user.click(await screen.findByTestId('unpriced-map-cancel-btn'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryByTestId(`unpriced-map-confirm-item-${MODEL}`),
|
||||
).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(sent).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('opens the confirm dialog with the target rule pricing when a model is picked', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
render(<UnpricedModelsTab />);
|
||||
|
||||
await screen.findByTestId(`unpriced-model-name-${MODEL}`);
|
||||
@@ -145,20 +94,26 @@ describe('UnpricedModelsTab (integration)', () => {
|
||||
});
|
||||
|
||||
it('reverts the row trigger to the placeholder when the mapping is cancelled', async () => {
|
||||
stageMapping();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
render(<UnpricedModelsTab />);
|
||||
|
||||
const trigger = await screen.findByTestId(`map-to-select-${MODEL}`);
|
||||
expect(
|
||||
within(trigger).getByText('openai:gpt-4o ($3.00/$9.00)'),
|
||||
).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByTestId('unpriced-map-cancel-btn'));
|
||||
await screen.findByTestId(`unpriced-model-name-${MODEL}`);
|
||||
await selectRule(user, MODEL, 'rule-openai');
|
||||
|
||||
expect(
|
||||
within(trigger).getByText('Select / Create a pricing model'),
|
||||
within(screen.getByTestId(`map-to-select-${MODEL}`)).getByText(
|
||||
'openai:gpt-4o ($3.00/$9.00)',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
|
||||
await user.click(await screen.findByTestId('unpriced-map-cancel-btn'));
|
||||
|
||||
await waitFor(() => {
|
||||
const trigger = screen.getByTestId(`map-to-select-${MODEL}`);
|
||||
expect(
|
||||
within(trigger).getByText('Select / Create a pricing model'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('commits the mapping in one request when confirmed', async () => {
|
||||
@@ -170,10 +125,12 @@ describe('UnpricedModelsTab (integration)', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
stageMapping();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
render(<UnpricedModelsTab />);
|
||||
|
||||
await screen.findByTestId(`unpriced-model-name-${MODEL}`);
|
||||
await selectRule(user, MODEL, 'rule-openai');
|
||||
|
||||
await user.click(await screen.findByTestId('unpriced-map-confirm-btn'));
|
||||
|
||||
await waitFor(() => expect(sent).toHaveLength(1));
|
||||
@@ -190,8 +147,33 @@ describe('UnpricedModelsTab (integration)', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('cancels the mapping without committing', async () => {
|
||||
const sent: LlmpricingruletypesUpdatableLLMPricingRulesDTO[] = [];
|
||||
server.use(
|
||||
rest.put(LLM_PRICING_ENDPOINT, async (req, res, ctx) => {
|
||||
sent.push(await req.json());
|
||||
return res(ctx.status(200), ctx.json({ status: 'success' }));
|
||||
}),
|
||||
);
|
||||
|
||||
const user = userEvent.setup();
|
||||
render(<UnpricedModelsTab />);
|
||||
|
||||
await screen.findByTestId(`unpriced-model-name-${MODEL}`);
|
||||
await selectRule(user, MODEL, 'rule-openai');
|
||||
|
||||
await user.click(await screen.findByTestId('unpriced-map-cancel-btn'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryByTestId(`unpriced-map-confirm-item-${MODEL}`),
|
||||
).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(sent).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('opens the add-cost drawer prefilled when creating pricing for a model', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
render(<UnpricedModelsTab />);
|
||||
|
||||
await screen.findByTestId(`unpriced-model-name-${MODEL}`);
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
import {
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { renderListAlertRules } from './_helpers';
|
||||
|
||||
@@ -21,7 +16,7 @@ describe('ListAlertRules — columns selector', () => {
|
||||
});
|
||||
|
||||
it('opens columns popover and lists toggleable columns', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
@@ -49,7 +44,7 @@ describe('ListAlertRules — columns selector', () => {
|
||||
});
|
||||
|
||||
it('toggling Created At on writes to localStorage and adds the header', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { getCurrentNuqsSearchParams } from 'tests/nuqs-helpers';
|
||||
import { screen, waitFor, NO_DELAY_USER_EVENT } from 'tests/test-utils';
|
||||
import { screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { renderListAlertRules } from './_helpers';
|
||||
|
||||
@@ -18,7 +18,7 @@ describe('ListAlertRules — empty states', () => {
|
||||
});
|
||||
|
||||
it('renders AlertsEmptyState when API returns no rules', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
|
||||
server.use(
|
||||
rest.get('http://localhost/api/v3/rules', (req, res, ctx) =>
|
||||
@@ -49,7 +49,7 @@ describe('ListAlertRules — empty states', () => {
|
||||
});
|
||||
|
||||
it('renders ErrorEmptyState when API returns 500; refresh triggers a refetch', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
|
||||
let callCount = 0;
|
||||
server.use(
|
||||
@@ -76,7 +76,7 @@ describe('ListAlertRules — empty states', () => {
|
||||
});
|
||||
|
||||
it('renders NoResultsEmptyState when the query matches nothing; Clear Search resets it', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
|
||||
server.use(
|
||||
rest.get('http://localhost/api/v3/rules', (req, res, ctx) =>
|
||||
@@ -116,7 +116,7 @@ describe('ListAlertRules — empty states', () => {
|
||||
});
|
||||
|
||||
it('renders NoResultsEmptyState when the states filter matches nothing; Clear Search resets it', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
|
||||
renderListAlertRules({ initialRoute: '/?states=nodata' });
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
} from 'mocks-server/__mockdata__/alert_rules';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { screen, waitFor, NO_DELAY_USER_EVENT } from 'tests/test-utils';
|
||||
import { screen, waitFor } from 'tests/test-utils';
|
||||
import { getCurrentNuqsQueryString } from 'tests/nuqs-helpers';
|
||||
|
||||
import { renderListAlertRules } from './_helpers';
|
||||
@@ -53,7 +53,7 @@ describe('ListAlertRules — pagination', () => {
|
||||
});
|
||||
|
||||
it('navigates to page 2 by requesting the next offset', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('Pag Rule 0');
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import { safeNavigateMock } from '__tests__/safeNavigateMock';
|
||||
import { useAlertRuleViewsStore } from 'container/ListAlertRules/useAlertRuleViewsStore';
|
||||
import {
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { renderListAlertRules } from './_helpers';
|
||||
|
||||
@@ -18,7 +13,7 @@ describe('ListAlertRules — row click navigation', () => {
|
||||
});
|
||||
|
||||
it('clicking a row calls safeNavigate to alerts/overview with ruleId', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderListAlertRules();
|
||||
|
||||
await user.click(await screen.findByTestId(RULE_NAME_CELL_TEST_ID));
|
||||
@@ -34,7 +29,7 @@ describe('ListAlertRules — row click navigation', () => {
|
||||
});
|
||||
|
||||
it('records an opened rule as recently viewed, most recent first', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
useAlertRuleViewsStore.setState({ recent: ['rule-2', 'rule-1'] });
|
||||
renderListAlertRules();
|
||||
|
||||
@@ -49,7 +44,7 @@ describe('ListAlertRules — row click navigation', () => {
|
||||
});
|
||||
|
||||
it('ctrl+click on a row navigates with newTab option', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderListAlertRules();
|
||||
|
||||
const ruleCell = await screen.findByTestId(RULE_NAME_CELL_TEST_ID);
|
||||
|
||||
@@ -4,13 +4,7 @@ import {
|
||||
} from 'mocks-server/__mockdata__/alert_rules';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import {
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import {
|
||||
getCurrentNuqsQueryString,
|
||||
getCurrentNuqsSearchParams,
|
||||
@@ -140,7 +134,7 @@ describe('ListAlertRules — search', () => {
|
||||
});
|
||||
|
||||
it('runs the draft when the search box loses focus', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
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();
|
||||
@@ -160,7 +154,7 @@ describe('ListAlertRules — search', () => {
|
||||
});
|
||||
|
||||
it('keeps the draft unrun when focus leaves the window', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import { renderListAlertRules, runSearchQuery } from './_helpers';
|
||||
@@ -173,7 +172,7 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('Enabled sends every state except disabled', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const requests = captureRulesRequests();
|
||||
renderListAlertRules();
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
@@ -189,7 +188,7 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('Recently viewed lists the opened rules in visit order from one large page', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const requests = captureRulesRequests();
|
||||
useAlertRuleViewsStore.setState({ recent: ['rule-3', 'rule-1'] });
|
||||
renderListAlertRules();
|
||||
@@ -214,7 +213,7 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
});
|
||||
|
||||
it('an empty Recently viewed keeps the search and says how it fills', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
@@ -565,7 +564,7 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
),
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
await selectView(user, 'view-1');
|
||||
await waitFor(() => expect(urlParam('orderBy')).toBe(VIEW_1_ORDER_BY));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import MultiSelectFilter, {
|
||||
type MultiSelectFilterOption,
|
||||
@@ -25,27 +25,25 @@ function RuleStatesFilter({
|
||||
onChange,
|
||||
}: RuleStatesFilterProps): JSX.Element {
|
||||
const [draft, setDraft] = useState(states);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setDraft(states);
|
||||
}, [states]);
|
||||
|
||||
const handleCommit = useCallback(
|
||||
(next: string[]): void => {
|
||||
setDraft(next);
|
||||
const handleChange = (next: string[]): void => {
|
||||
setDraft(next);
|
||||
if (!open) {
|
||||
onChange(next);
|
||||
},
|
||||
[onChange],
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDropdownVisibleChange = useCallback(
|
||||
(isOpen: boolean): void => {
|
||||
if (!isOpen && !isSameStates(draft, states)) {
|
||||
onChange(draft);
|
||||
}
|
||||
},
|
||||
[draft, states, onChange],
|
||||
);
|
||||
const handleDropdownVisibleChange = (nextOpen: boolean): void => {
|
||||
setOpen(nextOpen);
|
||||
if (!nextOpen && !isSameStates(draft, states)) {
|
||||
onChange(draft);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<MultiSelectFilter
|
||||
@@ -53,8 +51,7 @@ function RuleStatesFilter({
|
||||
options={STATE_OPTIONS}
|
||||
placeholder="Status"
|
||||
testId="alert-rules-filter-states"
|
||||
onChange={setDraft}
|
||||
onCommit={handleCommit}
|
||||
onChange={handleChange}
|
||||
onDropdownVisibleChange={handleDropdownVisibleChange}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -212,7 +212,6 @@ function ListAlertRules(): JSX.Element {
|
||||
testIdPrefix="alert-rules"
|
||||
saveTestIdPrefix="save-alert-rule-view"
|
||||
renameTestIdPrefix="rename-alert-rule-view"
|
||||
viewNamePlaceholder="e.g. Prod alerts"
|
||||
deleteDescription="Views are shared across your organization, so this removes it for everyone. Alert rules are not affected."
|
||||
/>
|
||||
<div className={styles.main}>
|
||||
|
||||
@@ -36,7 +36,6 @@ import {
|
||||
getQueryByPanelType,
|
||||
} from 'container/LogsExplorerViews/explorerUtils';
|
||||
import ExplorerActions from 'container/ExplorerActions/ExplorerActions';
|
||||
import { ExplorerActionsSource } from 'container/ExplorerActions/utils';
|
||||
import TimeSeriesView from 'container/TimeSeriesView/TimeSeriesView';
|
||||
import { useCopyLogLink } from 'hooks/logs/useCopyLogLink';
|
||||
import { useGetExplorerQueryRange } from 'hooks/queryBuilder/useGetExplorerQueryRange';
|
||||
@@ -137,10 +136,7 @@ function LogsExplorerViewsContainer({
|
||||
|
||||
const explorerActions = useMemo(
|
||||
() => (
|
||||
<ExplorerActions
|
||||
query={exportDefaultQuery}
|
||||
sourcePage={ExplorerActionsSource.LOGS_EXPLORER}
|
||||
/>
|
||||
<ExplorerActions query={exportDefaultQuery} sourcepage={DataSource.LOGS} />
|
||||
),
|
||||
[exportDefaultQuery],
|
||||
);
|
||||
|
||||
@@ -21,7 +21,6 @@ import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { MAX_QUERY_RETRIES } from 'constants/reactQuery';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import ExplorerActions from 'container/ExplorerActions/ExplorerActions';
|
||||
import { ExplorerActionsSource } from 'container/ExplorerActions/utils';
|
||||
import TimeSeriesView from 'container/TimeSeriesView/TimeSeriesView';
|
||||
import { convertDataValueToMs } from 'container/TimeSeriesView/utils';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
@@ -348,7 +347,7 @@ function TimeSeries({
|
||||
headerActions={
|
||||
<ExplorerActions
|
||||
query={stagedQuery ? exportQuery : null}
|
||||
sourcePage={ExplorerActionsSource.METRICS_EXPLORER}
|
||||
sourcepage={DataSource.METRICS}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
isOneChartPerQuery={changeLayoutForOneChartPerQuery}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Color, Style } from '@signozhq/design-tokens';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
@@ -81,7 +81,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="google-domain">
|
||||
Domain
|
||||
<Tooltip title="The email domain for users who should use SSO (e.g., `example.com` for users with `@example.com` emails)">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -104,7 +104,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="google-client-id">
|
||||
Client ID
|
||||
<Tooltip title="ClientID is the application's ID. For example, 292085223830.apps.googleusercontent.com.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -122,7 +122,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="google-client-secret">
|
||||
Client Secret
|
||||
<Tooltip title="It is the application's secret.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -161,7 +161,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title='Whether to skip email verification. Defaults to "false"'>
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -243,7 +243,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title="Enable fetching Google Workspace groups for the user. Requires service account configuration.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -256,7 +256,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
>
|
||||
Service Account JSON
|
||||
<Tooltip title="The JSON content of the Google Service Account credentials file. Required for group fetching.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -298,7 +298,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title="If enabled, recursively fetch groups that contain other groups (transitive membership).">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -309,7 +309,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
>
|
||||
Allowed Groups
|
||||
<Tooltip title="Optional list of allowed groups. If configured, only users belonging to one of these groups will be allowed to login.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Style } from '@signozhq/design-tokens';
|
||||
import { CircleHelp, TriangleAlert } from '@signozhq/icons';
|
||||
import { Callout } from '@signozhq/ui/callout';
|
||||
import { Checkbox } from '@signozhq/ui/checkbox';
|
||||
@@ -54,7 +55,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="oidc-domain">
|
||||
Domain
|
||||
<Tooltip title="The email domain for users who should use SSO (e.g., `example.com` for users with `@example.com` emails)">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -76,7 +77,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="oidc-issuer">
|
||||
Issuer URL
|
||||
<Tooltip title='The URL identifier for the OIDC provider. For example: "https://accounts.google.com" or "https://login.salesforce.com".'>
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -94,7 +95,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="oidc-issuer-alias">
|
||||
Issuer Alias
|
||||
<Tooltip title="Optional: Override the issuer URL from .well-known/openid-configuration for providers like Azure or Oracle IDCS.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -109,7 +110,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="oidc-client-id">
|
||||
Client ID
|
||||
<Tooltip title="The application's client ID from your OIDC provider.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -127,7 +128,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="oidc-client-secret">
|
||||
Client Secret
|
||||
<Tooltip title="The application's client secret from your OIDC provider.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -165,7 +166,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title='Whether to skip email verification. Defaults to "false"'>
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -186,7 +187,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title="Use the userinfo endpoint to get additional claims. Useful when providers return thin ID tokens.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className="authn-provider__callout-wrapper">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Style } from '@signozhq/design-tokens';
|
||||
import { CircleHelp, TriangleAlert } from '@signozhq/icons';
|
||||
import { Callout } from '@signozhq/ui/callout';
|
||||
import { Checkbox } from '@signozhq/ui/checkbox';
|
||||
@@ -53,7 +54,7 @@ function ConfigureSAMLAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="saml-domain">
|
||||
Domain
|
||||
<Tooltip title="The email domain for users who should use SSO (e.g., `example.com` for users with `@example.com` emails)">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -75,7 +76,7 @@ function ConfigureSAMLAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="saml-acs-url">
|
||||
SAML ACS URL
|
||||
<Tooltip title="The SSO endpoint of the SAML identity provider. It can typically be found in the SingleSignOnService element in the SAML metadata of the identity provider.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -97,7 +98,7 @@ function ConfigureSAMLAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="saml-entity-id">
|
||||
SAML Entity ID
|
||||
<Tooltip title="The entityID of the SAML identity provider. It can typically be found in the EntityID attribute of the EntityDescriptor element in the SAML metadata.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -119,7 +120,7 @@ function ConfigureSAMLAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="saml-certificate">
|
||||
SAML X.509 Certificate
|
||||
<Tooltip title="The certificate of the SAML identity provider. It can typically be found in the X509Certificate element in the SAML metadata.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -162,7 +163,7 @@ function ConfigureSAMLAuthnProvider({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title="Whether to skip signing the SAML requests. For providers like JumpCloud, this should be enabled.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Color, Style } from '@signozhq/design-tokens';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
@@ -98,7 +98,7 @@ function AttributeMappingSection({
|
||||
>
|
||||
Email Attribute
|
||||
<Tooltip title="The SAML attribute key that contains the user's email. Default: 'email'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -117,7 +117,7 @@ function AttributeMappingSection({
|
||||
>
|
||||
Name Attribute
|
||||
<Tooltip title="The SAML attribute key that contains the user's display name. Default: 'name'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -136,7 +136,7 @@ function AttributeMappingSection({
|
||||
>
|
||||
Groups Attribute
|
||||
<Tooltip title="The SAML attribute key that contains the user's group memberships. Used for role mapping. Default: 'groups'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -155,7 +155,7 @@ function AttributeMappingSection({
|
||||
>
|
||||
Role Attribute
|
||||
<Tooltip title="The SAML attribute key that contains the user's role directly from the IDP. Default: 'role'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Color, Style } from '@signozhq/design-tokens';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
@@ -93,7 +93,7 @@ function ClaimMappingSection({
|
||||
<label className="claim-mapping-section__label" htmlFor="email-claim">
|
||||
Email Claim
|
||||
<Tooltip title="The claim key that contains the user's email address. Default: 'email'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -109,7 +109,7 @@ function ClaimMappingSection({
|
||||
<label className="claim-mapping-section__label" htmlFor="name-claim">
|
||||
Name Claim
|
||||
<Tooltip title="The claim key that contains the user's display name. Default: 'name'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -125,7 +125,7 @@ function ClaimMappingSection({
|
||||
<label className="claim-mapping-section__label" htmlFor="groups-claim">
|
||||
Groups Claim
|
||||
<Tooltip title="The claim key that contains the user's group memberships. Used for role mapping. Default: 'groups'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -141,7 +141,7 @@ function ClaimMappingSection({
|
||||
<label className="claim-mapping-section__label" htmlFor="role-claim">
|
||||
Role Claim
|
||||
<Tooltip title="The claim key that contains the user's role directly from the IDP. Default: 'role'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Color, Style } from '@signozhq/design-tokens';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
@@ -108,7 +108,7 @@ function RoleMappingSection({
|
||||
<label className="role-mapping-section__label" htmlFor="default-role">
|
||||
Default Role
|
||||
<Tooltip title='The default role assigned to new SSO users if no other role mapping applies. Default: "signoz-viewer"'>
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -148,7 +148,7 @@ function RoleMappingSection({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title="If enabled, the role claim/attribute from the IDP will be used directly instead of group mappings. The role value must match a SigNoz role name (e.g. signoz-viewer, signoz-editor, signoz-admin, or a custom role).">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,201 +0,0 @@
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import {
|
||||
AuthDomainListPermission,
|
||||
buildAuthDomainDeletePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/auth-domain.permissions';
|
||||
import {
|
||||
setupAuthzAdmin,
|
||||
setupAuthzAllow,
|
||||
setupAuthzDeny,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import AuthDomain from '../index';
|
||||
import {
|
||||
AUTH_DOMAINS_DELETE_ENDPOINT,
|
||||
AUTH_DOMAINS_LIST_ENDPOINT,
|
||||
mockDeleteSuccessResponse,
|
||||
mockDomainsListResponse,
|
||||
mockGoogleAuthDomain,
|
||||
} from './mocks';
|
||||
|
||||
jest.mock('@signozhq/ui/toast', () => ({
|
||||
...jest.requireActual('@signozhq/ui/toast'),
|
||||
toast: {
|
||||
success: jest.fn(),
|
||||
danger: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const FIRST_ID = mockGoogleAuthDomain.id ?? '';
|
||||
const FIRST_ROW = `auth-domain-row-${mockGoogleAuthDomain.name}`;
|
||||
|
||||
function useListHandler(): { calls: () => number } {
|
||||
let calls = 0;
|
||||
server.use(
|
||||
rest.get(AUTH_DOMAINS_LIST_ENDPOINT, (_, res, ctx) => {
|
||||
calls += 1;
|
||||
return res(ctx.status(200), ctx.json(mockDomainsListResponse));
|
||||
}),
|
||||
);
|
||||
return { calls: (): number => calls };
|
||||
}
|
||||
|
||||
async function openDeleteModal(rowIndex = 0): Promise<void> {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
await screen.findByTestId(FIRST_ROW);
|
||||
await user.click(screen.getAllByTestId('auth-domain-delete')[rowIndex]);
|
||||
await screen.findByTestId('auth-domain-delete-confirm');
|
||||
}
|
||||
|
||||
async function confirmAfterCheck(): Promise<HTMLElement> {
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('auth-domain-delete-confirm')).not.toHaveAttribute(
|
||||
'aria-busy',
|
||||
),
|
||||
);
|
||||
return screen.getByTestId('auth-domain-delete-confirm');
|
||||
}
|
||||
|
||||
describe('AuthDomain — authz', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('list', () => {
|
||||
it('renders the domains when list is granted', async () => {
|
||||
server.use(setupAuthzAdmin());
|
||||
useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
|
||||
await expect(screen.findByTestId(FIRST_ROW)).resolves.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByText(/is not authorized to perform/i),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the permission-denied UI and sends no list request when list is denied', async () => {
|
||||
server.use(setupAuthzDeny(AuthDomainListPermission));
|
||||
const list = useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
|
||||
await expect(
|
||||
screen.findByText(/is not authorized to perform/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.queryByTestId(FIRST_ROW)).not.toBeInTheDocument();
|
||||
expect(list.calls()).toBe(0);
|
||||
});
|
||||
|
||||
it('keeps Add Domain and Configure enabled without create or update grants', async () => {
|
||||
server.use(setupAuthzAllow(AuthDomainListPermission));
|
||||
useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
|
||||
await screen.findByTestId(FIRST_ROW);
|
||||
|
||||
expect(screen.getByTestId('auth-domain-add')).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(
|
||||
screen.getAllByTestId('auth-domain-configure')[0],
|
||||
).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('deletes the domain and refetches the list when delete is granted', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
let deletedId: string | readonly string[] | undefined;
|
||||
server.use(
|
||||
setupAuthzAdmin(),
|
||||
rest.delete(AUTH_DOMAINS_DELETE_ENDPOINT, (req, res, ctx) => {
|
||||
deletedId = req.params.id;
|
||||
return res(ctx.status(200), ctx.json(mockDeleteSuccessResponse));
|
||||
}),
|
||||
);
|
||||
const list = useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
await openDeleteModal();
|
||||
|
||||
const confirm = await confirmAfterCheck();
|
||||
expect(confirm).not.toHaveAttribute('aria-disabled', 'true');
|
||||
await user.click(confirm);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(toast.success).toHaveBeenCalledWith('Domain deleted successfully'),
|
||||
);
|
||||
expect(deletedId).toBe(mockGoogleAuthDomain.id);
|
||||
await waitFor(() => expect(list.calls()).toBeGreaterThan(1));
|
||||
});
|
||||
|
||||
it('disables confirm with the denied permission when delete is denied on that domain', async () => {
|
||||
server.use(setupAuthzDeny(buildAuthDomainDeletePermission(FIRST_ID)));
|
||||
useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
await openDeleteModal();
|
||||
|
||||
const confirm = await confirmAfterCheck();
|
||||
expect(confirm).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(confirm).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
expect.stringContaining(FIRST_ID),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps confirm enabled on a domain whose delete is granted', async () => {
|
||||
server.use(setupAuthzDeny(buildAuthDomainDeletePermission(FIRST_ID)));
|
||||
useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
await openDeleteModal(1);
|
||||
|
||||
const confirm = await confirmAfterCheck();
|
||||
expect(confirm).not.toHaveAttribute('data-denied-permissions');
|
||||
expect(confirm).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('shows the error modal and keeps the domain when the delete is rejected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
server.use(
|
||||
setupAuthzAdmin(),
|
||||
rest.delete(AUTH_DOMAINS_DELETE_ENDPOINT, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(403),
|
||||
ctx.json({
|
||||
error: {
|
||||
code: 'authz_forbidden',
|
||||
message: 'not allowed to delete this domain',
|
||||
url: '',
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
await openDeleteModal();
|
||||
|
||||
const confirm = await confirmAfterCheck();
|
||||
expect(confirm).not.toHaveAttribute('aria-disabled', 'true');
|
||||
await user.click(confirm);
|
||||
|
||||
expect(
|
||||
(await screen.findAllByText(/not allowed to delete this domain/i)).length,
|
||||
).toBeGreaterThan(0);
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
expect(screen.getByTestId(FIRST_ROW)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
@@ -21,7 +20,6 @@ jest.mock('@signozhq/ui/toast', () => ({
|
||||
describe('AuthDomain', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
server.use(setupAuthzAdmin());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import CreateEdit from '../CreateEdit/CreateEdit';
|
||||
import {
|
||||
AUTH_DOMAINS_CREATE_ENDPOINT,
|
||||
AUTH_DOMAINS_UPDATE_ENDPOINT,
|
||||
mockGoogleAuthDomain,
|
||||
} from './mocks';
|
||||
|
||||
// The real @signozhq/ui/button keeps form.validateFields() from resolving inside
|
||||
// act(); see CreateEdit.payload.test.tsx for the same workaround.
|
||||
jest.mock('@signozhq/ui/button', () => ({
|
||||
...jest.requireActual('@signozhq/ui/button'),
|
||||
Button: ({
|
||||
children,
|
||||
onClick,
|
||||
loading,
|
||||
disabled,
|
||||
testId,
|
||||
}: {
|
||||
children?: React.ReactNode;
|
||||
onClick?: React.MouseEventHandler<HTMLButtonElement>;
|
||||
loading?: boolean;
|
||||
disabled?: boolean;
|
||||
testId?: string;
|
||||
}) => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled || loading}
|
||||
data-testid={testId}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
}));
|
||||
|
||||
const FORBIDDEN_RESPONSE = {
|
||||
error: {
|
||||
code: 'authz_forbidden',
|
||||
message: 'not allowed to save this domain',
|
||||
url: '',
|
||||
},
|
||||
};
|
||||
|
||||
describe('CreateEdit — authz', () => {
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('shows the error modal and keeps the filled form when create is rejected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onClose = jest.fn();
|
||||
server.use(
|
||||
rest.post(AUTH_DOMAINS_CREATE_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(403), ctx.json(FORBIDDEN_RESPONSE)),
|
||||
),
|
||||
);
|
||||
|
||||
render(<CreateEdit isCreate onClose={onClose} />);
|
||||
|
||||
await user.click(
|
||||
await screen.findByTestId('authn-provider-configure-google'),
|
||||
);
|
||||
await user.type(await screen.findByLabelText(/^domain/i), 'acme.io');
|
||||
await user.type(screen.getByLabelText(/client id/i), 'client-id');
|
||||
await user.type(screen.getByLabelText(/client secret/i), 'secret');
|
||||
await user.click(screen.getByTestId('auth-domain-save'));
|
||||
|
||||
expect(
|
||||
(
|
||||
await screen.findAllByText(/not allowed to save this domain/i, undefined, {
|
||||
timeout: 5000,
|
||||
})
|
||||
).length,
|
||||
).toBeGreaterThan(0);
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
expect(screen.getByLabelText(/^domain/i)).toHaveValue('acme.io');
|
||||
expect(screen.getByLabelText(/client id/i)).toHaveValue('client-id');
|
||||
});
|
||||
|
||||
it('shows the error modal and keeps the form when update is rejected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onClose = jest.fn();
|
||||
let updateCalls = 0;
|
||||
server.use(
|
||||
rest.put(AUTH_DOMAINS_UPDATE_ENDPOINT, (_, res, ctx) => {
|
||||
updateCalls += 1;
|
||||
return res(ctx.status(403), ctx.json(FORBIDDEN_RESPONSE));
|
||||
}),
|
||||
);
|
||||
|
||||
render(
|
||||
<CreateEdit
|
||||
isCreate={false}
|
||||
record={mockGoogleAuthDomain}
|
||||
onClose={onClose}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(await screen.findByTestId('auth-domain-save'));
|
||||
|
||||
await waitFor(() => expect(updateCalls).toBe(1));
|
||||
expect(
|
||||
(
|
||||
await screen.findAllByText(/not allowed to save this domain/i, undefined, {
|
||||
timeout: 5000,
|
||||
})
|
||||
).length,
|
||||
).toBeGreaterThan(0);
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
expect(screen.getByLabelText(/client id/i)).toHaveValue('test-client-id');
|
||||
});
|
||||
});
|
||||
@@ -156,44 +156,6 @@ describe('SSOEnforcementToggle', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('reverts the switch and shows the error modal when the update is forbidden', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
server.use(
|
||||
rest.put(AUTH_DOMAINS_UPDATE_ENDPOINT, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(403),
|
||||
ctx.json({
|
||||
error: {
|
||||
code: 'authz_forbidden',
|
||||
message: 'not allowed to update this domain',
|
||||
url: '',
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
render(
|
||||
<SSOEnforcementToggle
|
||||
isDefaultChecked={true}
|
||||
record={mockGoogleAuthDomain}
|
||||
/>,
|
||||
);
|
||||
|
||||
const switchElement = screen.getByRole('switch');
|
||||
await user.click(switchElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/not allowed to update this domain/i),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'true'),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not call API when record has no id', async () => {
|
||||
const user = userEvent.setup();
|
||||
let apiCalled = false;
|
||||
|
||||
@@ -24,13 +24,6 @@ import SSOEnforcementToggle from './SSOEnforcementToggle';
|
||||
|
||||
import './AuthDomain.styles.scss';
|
||||
import '../../IngestionSettings/IngestionSettings.styles.scss';
|
||||
import { useAuthZ } from '@/lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import {
|
||||
AuthDomainListPermission,
|
||||
buildAuthDomainDeletePermission,
|
||||
} from '@/lib/authz/hooks/useAuthZ/permissions/auth-domain.permissions';
|
||||
import { AuthZGuardContent } from '@/lib/authz/components/AuthZGuard/AuthZGuardContent';
|
||||
import AuthZButton from '@/lib/authz/components/AuthZButton/AuthZButton';
|
||||
|
||||
export const SSOType = new Map<string, string>([
|
||||
['google', 'Google Auth'],
|
||||
@@ -48,18 +41,13 @@ function AuthDomain(): JSX.Element {
|
||||
|
||||
const { showErrorModal } = useErrorModal();
|
||||
|
||||
const { permissions: authzPermissions } = useAuthZ([AuthDomainListPermission]);
|
||||
|
||||
const canListAuthDomains =
|
||||
authzPermissions?.[AuthDomainListPermission]?.isGranted ?? false;
|
||||
|
||||
const {
|
||||
data: authDomainListResponse,
|
||||
isLoading: isLoadingAuthDomainListResponse,
|
||||
isFetching: isFetchingAuthDomainListResponse,
|
||||
error: errorFetchingAuthDomainListResponse,
|
||||
refetch: refetchAuthDomainListResponse,
|
||||
} = useListAuthDomains({ query: { enabled: canListAuthDomains } });
|
||||
} = useListAuthDomains();
|
||||
|
||||
const { mutate: deleteAuthDomain, isLoading } =
|
||||
useDeleteAuthDomain<AxiosError<RenderErrorResponseDTO>>();
|
||||
@@ -210,29 +198,25 @@ function AuthDomain(): JSX.Element {
|
||||
</Button>
|
||||
</section>
|
||||
{formattedError && <ErrorContent error={formattedError} />}
|
||||
<AuthZGuardContent checks={[AuthDomainListPermission]}>
|
||||
{!errorFetchingAuthDomainListResponse ? (
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={authDomainListResponse?.data}
|
||||
onRow={(
|
||||
record: AuthtypesGettableAuthDomainDTO,
|
||||
): HTMLAttributes<HTMLElement> =>
|
||||
// data-* attributes are valid row props but absent from the antd typing
|
||||
({
|
||||
'data-testid': `auth-domain-row-${record.name}`,
|
||||
}) as unknown as HTMLAttributes<HTMLElement>
|
||||
}
|
||||
loading={
|
||||
isLoadingAuthDomainListResponse || isFetchingAuthDomainListResponse
|
||||
}
|
||||
className="auth-domain-list"
|
||||
rowKey="id"
|
||||
/>
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</AuthZGuardContent>
|
||||
{!errorFetchingAuthDomainListResponse && (
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={authDomainListResponse?.data}
|
||||
onRow={(
|
||||
record: AuthtypesGettableAuthDomainDTO,
|
||||
): HTMLAttributes<HTMLElement> =>
|
||||
// data-* attributes are valid row props but absent from the antd typing
|
||||
({
|
||||
'data-testid': `auth-domain-row-${record.name}`,
|
||||
}) as unknown as HTMLAttributes<HTMLElement>
|
||||
}
|
||||
loading={
|
||||
isLoadingAuthDomainListResponse || isFetchingAuthDomainListResponse
|
||||
}
|
||||
className="auth-domain-list"
|
||||
rowKey="id"
|
||||
/>
|
||||
)}
|
||||
{(addDomain || record) && (
|
||||
<CreateEdit
|
||||
isCreate={!record}
|
||||
@@ -240,9 +224,7 @@ function AuthDomain(): JSX.Element {
|
||||
onClose={(): void => {
|
||||
setAddDomain(false);
|
||||
setRecord(undefined);
|
||||
if (canListAuthDomains) {
|
||||
void refetchAuthDomainListResponse();
|
||||
}
|
||||
refetchAuthDomainListResponse();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -266,7 +248,7 @@ function AuthDomain(): JSX.Element {
|
||||
>
|
||||
Cancel
|
||||
</Button>,
|
||||
<AuthZButton
|
||||
<Button
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="danger"
|
||||
@@ -275,14 +257,9 @@ function AuthDomain(): JSX.Element {
|
||||
onClick={handleDeleteDomain}
|
||||
loading={isLoading}
|
||||
testId="auth-domain-delete-confirm"
|
||||
checks={
|
||||
isDeleteModalOpen && activeDomain?.id
|
||||
? [buildAuthDomainDeletePermission(activeDomain.id)]
|
||||
: []
|
||||
}
|
||||
>
|
||||
Delete Domain
|
||||
</AuthZButton>,
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<p className="delete-text">
|
||||
|
||||
@@ -8,10 +8,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.org-input-disabled-tooltip-class {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.field-error {
|
||||
color: var(--destructive);
|
||||
margin-top: var(--spacing-2);
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
import {
|
||||
buildOrganizationReadPermission,
|
||||
buildOrganizationUpdatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/organization.permissions';
|
||||
import {
|
||||
setupAuthzAdmin,
|
||||
setupAuthzDeny,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import DisplayName from '../index';
|
||||
|
||||
const ORG_ID = 'does-not-matter-id';
|
||||
const ORG_ME_ENDPOINT = '*/api/v2/orgs/me';
|
||||
|
||||
function renderWithoutSavedName(): void {
|
||||
render(<DisplayName index={0} id={ORG_ID} />, undefined, {
|
||||
appContextOverrides: {
|
||||
org: [{ createdAt: 0, id: ORG_ID, displayName: '' }],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function useOrgFetchHandler(): { calls: () => number } {
|
||||
let calls = 0;
|
||||
server.use(
|
||||
rest.get(ORG_ME_ENDPOINT, (_, res, ctx) => {
|
||||
calls += 1;
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: { id: ORG_ID, displayName: 'Fetched Org' },
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
return { calls: (): number => calls };
|
||||
}
|
||||
|
||||
describe('DisplayName — authz', () => {
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('disables the input and submit with the denied permission when update is denied', async () => {
|
||||
server.use(setupAuthzDeny(buildOrganizationUpdatePermission(ORG_ID)));
|
||||
|
||||
render(<DisplayName index={0} id={ORG_ID} />);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('org-display-name-submit')).not.toHaveAttribute(
|
||||
'aria-busy',
|
||||
),
|
||||
);
|
||||
const submit = screen.getByTestId('org-display-name-submit');
|
||||
expect(submit).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(submit).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
expect.stringContaining('update'),
|
||||
);
|
||||
expect(screen.getByTestId('org-display-name-input-field')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows the denial instead of the form and skips the fetch when read is denied', async () => {
|
||||
server.use(setupAuthzDeny(buildOrganizationReadPermission(ORG_ID)));
|
||||
const fetch = useOrgFetchHandler();
|
||||
|
||||
renderWithoutSavedName();
|
||||
|
||||
await expect(
|
||||
screen.findByText(/is not authorized/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText(/read:organization/i)).toBeInTheDocument();
|
||||
expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('org-display-name-submit'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(fetch.calls()).toBe(0);
|
||||
});
|
||||
|
||||
it('fetches the organization when read is granted', async () => {
|
||||
const fetch = useOrgFetchHandler();
|
||||
server.use(setupAuthzAdmin());
|
||||
|
||||
renderWithoutSavedName();
|
||||
|
||||
await waitFor(() => expect(fetch.calls()).toBe(1));
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import {
|
||||
fireEvent,
|
||||
@@ -26,7 +25,6 @@ const defaultProps = { index: 0, id: 'does-not-matter-id' };
|
||||
describe('DisplayName', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
server.use(setupAuthzAdmin());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -36,15 +34,10 @@ describe('DisplayName', () => {
|
||||
it('renders form pre-filled with org displayName from context', async () => {
|
||||
render(<DisplayName {...defaultProps} />);
|
||||
|
||||
const input = await screen.findByTestId('org-display-name-input-field');
|
||||
const input = await screen.findByRole('textbox');
|
||||
expect(input).toHaveValue('Pentagon');
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('org-display-name-submit')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
),
|
||||
);
|
||||
expect(screen.getByRole('button', { name: /submit/i })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables submit and calls PUT when display name is changed', async () => {
|
||||
@@ -54,15 +47,12 @@ describe('DisplayName', () => {
|
||||
|
||||
render(<DisplayName {...defaultProps} />);
|
||||
|
||||
const input = await screen.findByTestId('org-display-name-input-field');
|
||||
await waitFor(() => expect(input).toBeEnabled());
|
||||
const input = await screen.findByRole('textbox');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'New Org Name');
|
||||
|
||||
const submitBtn = screen.getByTestId('org-display-name-submit');
|
||||
await waitFor(() =>
|
||||
expect(submitBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
const submitBtn = screen.getByRole('button', { name: /submit/i });
|
||||
expect(submitBtn).toBeEnabled();
|
||||
|
||||
await user.click(submitBtn);
|
||||
|
||||
@@ -76,8 +66,7 @@ describe('DisplayName', () => {
|
||||
|
||||
render(<DisplayName {...defaultProps} />);
|
||||
|
||||
const input = await screen.findByTestId('org-display-name-input-field');
|
||||
await waitFor(() => expect(input).toBeEnabled());
|
||||
const input = await screen.findByRole('textbox');
|
||||
await user.clear(input);
|
||||
|
||||
fireEvent.submit(screen.getByTestId('org-display-name-form'));
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import { Button, Input } from 'antd';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import {
|
||||
useGetMyOrganization,
|
||||
@@ -10,42 +10,25 @@ import {
|
||||
} from 'api/generated/services/orgs';
|
||||
import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { AxiosError } from 'axios';
|
||||
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
|
||||
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
|
||||
import {
|
||||
buildOrganizationReadPermission,
|
||||
buildOrganizationUpdatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/organization.permissions';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { IUser } from 'providers/App/types';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import APIError from 'types/api/error';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
import { requireErrorMessage } from 'utils/form/requireErrorMessage';
|
||||
|
||||
import { getSubmitBlockedReason } from './utils';
|
||||
|
||||
import './DisplayName.styles.scss';
|
||||
import { AuthZGuardContent } from '@/lib/authz/components/AuthZGuard/AuthZGuardContent';
|
||||
|
||||
function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
|
||||
const { t } = useTranslation(['organizationsettings', 'common']);
|
||||
const { showErrorModal } = useErrorModal();
|
||||
const { org, updateOrg } = useAppContext();
|
||||
const { org, updateOrg, user } = useAppContext();
|
||||
const currentOrg = (org || [])[index];
|
||||
const readPermission = buildOrganizationReadPermission(orgId);
|
||||
const updatePermission = buildOrganizationUpdatePermission(orgId);
|
||||
const { permissions: authzPermissions } = useAuthZ([
|
||||
readPermission,
|
||||
updatePermission,
|
||||
]);
|
||||
|
||||
const canReadOrg = authzPermissions?.[readPermission]?.isGranted ?? false;
|
||||
const canUpdateOrg = authzPermissions?.[updatePermission]?.isGranted ?? false;
|
||||
const isAdmin = user.role === USER_ROLES.ADMIN;
|
||||
|
||||
const { data: orgData } = useGetMyOrganization({
|
||||
query: {
|
||||
enabled: canReadOrg && !currentOrg?.displayName,
|
||||
enabled: isAdmin && !currentOrg?.displayName,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -93,11 +76,7 @@ function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
|
||||
return <div />;
|
||||
}
|
||||
|
||||
const submitBlockedReason = getSubmitBlockedReason({
|
||||
canUpdate: canUpdateOrg,
|
||||
name: orgName,
|
||||
savedName: displayName,
|
||||
});
|
||||
const isDisabled = isLoading || orgName === displayName || !orgName;
|
||||
|
||||
return (
|
||||
<form
|
||||
@@ -108,50 +87,38 @@ function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
|
||||
>
|
||||
<div className="form-field">
|
||||
<label htmlFor="displayName">Display name</label>
|
||||
<AuthZGuardContent checks={[readPermission]}>
|
||||
<Controller
|
||||
name="displayName"
|
||||
control={control}
|
||||
rules={{ required: requireErrorMessage('Display name') }}
|
||||
render={({ field, fieldState }): JSX.Element => (
|
||||
<>
|
||||
<AuthZTooltip
|
||||
triggerClassName="org-input-disabled-tooltip-class"
|
||||
checks={[updatePermission]}
|
||||
>
|
||||
<Input
|
||||
{...field}
|
||||
id="displayName"
|
||||
testId="org-display-name-input"
|
||||
size="lg"
|
||||
placeholder={t('signoz')}
|
||||
status={fieldState.error ? 'danger' : undefined}
|
||||
/>
|
||||
</AuthZTooltip>
|
||||
{fieldState.error && (
|
||||
<div className="field-error">{fieldState.error.message}</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</AuthZGuardContent>
|
||||
<Controller
|
||||
name="displayName"
|
||||
control={control}
|
||||
rules={{ required: requireErrorMessage('Display name') }}
|
||||
render={({ field, fieldState }): JSX.Element => (
|
||||
<>
|
||||
<Input
|
||||
{...field}
|
||||
id="displayName"
|
||||
data-testid="org-display-name-input"
|
||||
size="large"
|
||||
placeholder={t('signoz')}
|
||||
status={fieldState.error ? 'error' : ''}
|
||||
/>
|
||||
{fieldState.error && (
|
||||
<div className="field-error">{fieldState.error.message}</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
loading={isLoading}
|
||||
disabled={isDisabled}
|
||||
type="primary"
|
||||
htmlType="submit"
|
||||
data-testid="org-display-name-submit"
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
{canReadOrg && (
|
||||
<div>
|
||||
<AuthZButton
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
type="submit"
|
||||
loading={isLoading}
|
||||
disabledTooltip={submitBlockedReason}
|
||||
testId="org-display-name-submit"
|
||||
checks={[updatePermission]}
|
||||
>
|
||||
Submit
|
||||
</AuthZButton>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
interface SubmitBlockedReasonArgs {
|
||||
canUpdate: boolean;
|
||||
name: string;
|
||||
savedName: string;
|
||||
}
|
||||
|
||||
// A permission denial is left to AuthZButton, which names the missing scope.
|
||||
export function getSubmitBlockedReason({
|
||||
canUpdate,
|
||||
name,
|
||||
savedName,
|
||||
}: SubmitBlockedReasonArgs): string | undefined {
|
||||
if (!canUpdate) {
|
||||
return undefined;
|
||||
}
|
||||
if (name === savedName) {
|
||||
return 'No change detected';
|
||||
}
|
||||
if (!name) {
|
||||
return "Can't be empty";
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -11,13 +11,7 @@ import {
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { ErrorType } from 'api/generatedAPIInstance';
|
||||
import { mockAppLocation, mockNavigate } from 'tests/router-mocks';
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
within,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
|
||||
import { PlannedDowntime } from '../PlannedDowntime';
|
||||
@@ -246,15 +240,14 @@ describe('PlannedDowntime Component', () => {
|
||||
});
|
||||
|
||||
it('should filter downtime schedules by name when searching', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
renderPage();
|
||||
|
||||
await expect(
|
||||
screen.findByText(MOCK_DOWNTIME_1_NAME),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByTestId(SEARCH_TEST_ID));
|
||||
await user.paste(MOCK_DOWNTIME_1_NAME);
|
||||
await user.type(screen.getByTestId(SEARCH_TEST_ID), MOCK_DOWNTIME_1_NAME);
|
||||
|
||||
await expect(
|
||||
screen.findByText(MOCK_DOWNTIME_1_NAME),
|
||||
@@ -264,7 +257,7 @@ describe('PlannedDowntime Component', () => {
|
||||
});
|
||||
|
||||
it('should filter downtime schedules with partial name match', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
renderPage();
|
||||
|
||||
await expect(
|
||||
@@ -281,11 +274,10 @@ describe('PlannedDowntime Component', () => {
|
||||
});
|
||||
|
||||
it('should show no results when search term matches nothing', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
renderPage();
|
||||
|
||||
await user.click(screen.getByTestId(SEARCH_TEST_ID));
|
||||
await user.paste('NonExistentDowntime');
|
||||
await user.type(screen.getByTestId(SEARCH_TEST_ID), 'NonExistentDowntime');
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('no-results-empty-state'),
|
||||
@@ -294,7 +286,7 @@ describe('PlannedDowntime Component', () => {
|
||||
});
|
||||
|
||||
it('opens the delete confirmation from the row actions', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup();
|
||||
renderPage();
|
||||
|
||||
await user.click(await screen.findByTestId('downtime-actions-1'));
|
||||
|
||||
@@ -108,8 +108,6 @@
|
||||
.left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
gap: 8px;
|
||||
|
||||
.value {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Tooltip } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import cx from 'classnames';
|
||||
import { isEmpty, isObject } from 'lodash-es';
|
||||
@@ -45,73 +46,28 @@ function Suggestions(props: ISuggestionsProps): React.ReactElement {
|
||||
return (
|
||||
<div className="option">
|
||||
{!isEmpty(optionType) && isObject(value) ? (
|
||||
<div className="container">
|
||||
<section className="left-section">
|
||||
{value.isIndexed ? (
|
||||
<Zap size={12} fill={Color.BG_AMBER_500} />
|
||||
) : (
|
||||
<div className="dot" />
|
||||
)}
|
||||
<div className="value">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="p"
|
||||
textOverflow="ellipsis"
|
||||
>
|
||||
{label}
|
||||
</Typography>
|
||||
</div>
|
||||
</section>
|
||||
<section className="right-section">
|
||||
<div className="data-type">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="p"
|
||||
textOverflow="visible"
|
||||
>
|
||||
{value.dataType}
|
||||
</Typography>
|
||||
</div>
|
||||
<section className={cx('type-tag', value.type)}>
|
||||
<div className="dot" />
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="small"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="visible"
|
||||
textTransform="capitalize"
|
||||
>
|
||||
{value.type}
|
||||
</Typography>
|
||||
<Tooltip title={value.key} placement="topLeft">
|
||||
<div className="container">
|
||||
<section className="left-section">
|
||||
{value.isIndexed ? (
|
||||
<Zap size={12} fill={Color.BG_AMBER_500} />
|
||||
) : (
|
||||
<div className="dot" />
|
||||
)}
|
||||
<div className="value">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="p"
|
||||
textOverflow="ellipsis"
|
||||
>
|
||||
{label}
|
||||
</Typography>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
</div>
|
||||
) : (
|
||||
<div className="container-without-tag">
|
||||
<section className="left">
|
||||
<div className="dot" />
|
||||
<div className={cx('value', option)}>
|
||||
<Typography
|
||||
{...labelTextStyle}
|
||||
size="base"
|
||||
color="inherit"
|
||||
as="p"
|
||||
textOverflow="ellipsis"
|
||||
>
|
||||
{`${label}`}
|
||||
</Typography>
|
||||
</div>
|
||||
</section>
|
||||
<section className="right">
|
||||
{dataType && (
|
||||
<section className="right-section">
|
||||
<div className="data-type">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
@@ -121,13 +77,62 @@ function Suggestions(props: ISuggestionsProps): React.ReactElement {
|
||||
as="p"
|
||||
textOverflow="visible"
|
||||
>
|
||||
{dataType}
|
||||
{value.dataType}
|
||||
</Typography>
|
||||
</div>
|
||||
)}
|
||||
{tagValue.includes(label) && <Check size={14} />}
|
||||
</section>
|
||||
</div>
|
||||
<section className={cx('type-tag', value.type)}>
|
||||
<div className="dot" />
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="small"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="visible"
|
||||
textTransform="capitalize"
|
||||
>
|
||||
{value.type}
|
||||
</Typography>
|
||||
</section>
|
||||
</section>
|
||||
</div>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Tooltip title={label} placement="topLeft">
|
||||
<div className="container-without-tag">
|
||||
<section className="left">
|
||||
<div className="dot" />
|
||||
<div className={cx('value', option)}>
|
||||
<Typography
|
||||
{...labelTextStyle}
|
||||
size="base"
|
||||
color="inherit"
|
||||
as="p"
|
||||
textOverflow="ellipsis"
|
||||
>
|
||||
{`${label}`}
|
||||
</Typography>
|
||||
</div>
|
||||
</section>
|
||||
<section className="right">
|
||||
{dataType && (
|
||||
<div className="data-type">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="p"
|
||||
textOverflow="visible"
|
||||
>
|
||||
{dataType}
|
||||
</Typography>
|
||||
</div>
|
||||
)}
|
||||
{tagValue.includes(label) && <Check size={14} />}
|
||||
</section>
|
||||
</div>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -19,7 +19,6 @@ import { QueryBuilderContext } from 'providers/QueryBuilder';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { FieldDataType, TelemetryFieldKey } from 'types/api/v5/queryRange';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { NO_DELAY_USER_EVENT } from 'tests/test-utils';
|
||||
|
||||
import QueryBuilderSearchV2 from '../QueryBuilderSearchV2';
|
||||
|
||||
@@ -149,7 +148,7 @@ jest.mock('hooks/dashboard/useDynamicVariableSuggestions', () => ({
|
||||
|
||||
describe('Suggestion Key -> Operator -> Value Flow', () => {
|
||||
it('should complete full flow from key selection to value', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderWithContext();
|
||||
|
||||
const combobox = getSearchCombobox();
|
||||
@@ -200,7 +199,7 @@ describe('Suggestion Key -> Operator -> Value Flow', () => {
|
||||
|
||||
describe('Operator suggestions for data types missing from the operators map', () => {
|
||||
it('should fall back to universal operators for a non-canonical data type', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderWithContext();
|
||||
|
||||
const combobox = getSearchCombobox();
|
||||
@@ -227,7 +226,7 @@ describe('Operator suggestions for data types missing from the operators map', (
|
||||
|
||||
describe('Dynamic Variable Suggestions', () => {
|
||||
it('should suggest dynamic variable when key matches a variable attribute', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderWithContext();
|
||||
|
||||
const combobox = getSearchCombobox();
|
||||
@@ -299,7 +298,7 @@ describe('Filter chips', () => {
|
||||
});
|
||||
|
||||
it('removes the filter once when the chip close button is clicked', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderWithContext({ query: queryWithFilter });
|
||||
|
||||
await user.click(
|
||||
@@ -313,7 +312,7 @@ describe('Filter chips', () => {
|
||||
});
|
||||
|
||||
it('moves the filter into the search input when the chip body is clicked', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderWithContext({ query: queryWithFilter });
|
||||
|
||||
await user.click(screen.getByText(CHIP_LABEL));
|
||||
@@ -357,7 +356,7 @@ describe('Key fetch context', () => {
|
||||
|
||||
describe('Keys the legacy filter builders cannot read', () => {
|
||||
it('does not suggest body JSON keys or span search scope selectors', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderWithContext();
|
||||
|
||||
const combobox = getSearchCombobox();
|
||||
@@ -373,7 +372,7 @@ describe('Keys the legacy filter builders cannot read', () => {
|
||||
|
||||
describe('Span field keys', () => {
|
||||
it('marks span fields as columns and looks up their values in the span context', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderWithContext();
|
||||
|
||||
const combobox = getSearchCombobox();
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import {
|
||||
getResourcePanel,
|
||||
getResourceVerbs,
|
||||
RESOURCE_ORDER,
|
||||
} from '../permissions.config';
|
||||
|
||||
describe('ingestion permissions in the roles editor', () => {
|
||||
it('lists both entities', () => {
|
||||
expect(RESOURCE_ORDER).toContain('ingestion-key');
|
||||
expect(RESOURCE_ORDER).toContain('ingestion-limit');
|
||||
expect(getResourcePanel('ingestion-key').label).toBe('Ingestion Keys');
|
||||
expect(getResourcePanel('ingestion-limit').label).toBe('Ingestion Limits');
|
||||
});
|
||||
|
||||
it('offers every metaresource verb for ingestion-key', () => {
|
||||
expect([...getResourceVerbs('ingestion-key')].sort()).toStrictEqual([
|
||||
'attach',
|
||||
'create',
|
||||
'delete',
|
||||
'detach',
|
||||
'list',
|
||||
'read',
|
||||
'update',
|
||||
]);
|
||||
});
|
||||
|
||||
it('offers no attach or detach for ingestion-limit', () => {
|
||||
expect([...getResourceVerbs('ingestion-limit')].sort()).toStrictEqual([
|
||||
'create',
|
||||
'delete',
|
||||
'list',
|
||||
'read',
|
||||
'update',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -329,19 +329,15 @@ describe('transformTransactionGroupsToResourcePermissions', () => {
|
||||
it('returns all resources from RESOURCE_ORDER even with empty transaction groups', () => {
|
||||
const result = transformTransactionGroupsToResourcePermissions([]);
|
||||
|
||||
expect(result).toHaveLength(19);
|
||||
expect(result).toHaveLength(15);
|
||||
expect(result.map((r) => r.resourceKind)).toStrictEqual([
|
||||
'factor-api-key',
|
||||
'auth-domain',
|
||||
'dashboard',
|
||||
'ingestion-key',
|
||||
'ingestion-limit',
|
||||
'license',
|
||||
'logs',
|
||||
'meter-metrics',
|
||||
'metrics',
|
||||
'notification-channel',
|
||||
'organization',
|
||||
'factor-password',
|
||||
'quick-filter',
|
||||
'role',
|
||||
@@ -430,19 +426,15 @@ describe('createEmptyRolePermissions', () => {
|
||||
it('creates permissions for all resources in RESOURCE_ORDER', () => {
|
||||
const result = createEmptyRolePermissions();
|
||||
|
||||
expect(result).toHaveLength(19);
|
||||
expect(result).toHaveLength(15);
|
||||
expect(result.map((r) => r.resourceKind)).toStrictEqual([
|
||||
'factor-api-key',
|
||||
'auth-domain',
|
||||
'dashboard',
|
||||
'ingestion-key',
|
||||
'ingestion-limit',
|
||||
'license',
|
||||
'logs',
|
||||
'meter-metrics',
|
||||
'metrics',
|
||||
'notification-channel',
|
||||
'organization',
|
||||
'factor-password',
|
||||
'quick-filter',
|
||||
'role',
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
Bot,
|
||||
Building,
|
||||
Cable,
|
||||
ChartLine,
|
||||
DraftingCompass,
|
||||
@@ -9,7 +8,6 @@ import {
|
||||
Grid3X3,
|
||||
Key,
|
||||
ListFilter,
|
||||
LogIn,
|
||||
Logs,
|
||||
Receipt,
|
||||
Shield,
|
||||
@@ -167,37 +165,6 @@ export const RESOURCE_PANELS: Record<AuthZResource, ResourcePanelConfig> = {
|
||||
'Type password ID, separate multiple with comma or space',
|
||||
docsAnchor: 'factor-password',
|
||||
},
|
||||
'ingestion-key': {
|
||||
label: 'Ingestion Keys',
|
||||
description: 'Keys used to send telemetry to the workspace.',
|
||||
icon: Key,
|
||||
selectorPlaceholder:
|
||||
'Type ingestion key ID, separate multiple with comma or space',
|
||||
docsAnchor: 'ingestion-key',
|
||||
},
|
||||
'ingestion-limit': {
|
||||
label: 'Ingestion Limits',
|
||||
description: 'Daily and per-second limits set on ingestion keys.',
|
||||
icon: Gauge,
|
||||
selectorPlaceholder:
|
||||
'Type ingestion limit ID, separate multiple with comma or space',
|
||||
docsAnchor: 'ingestion-limit',
|
||||
},
|
||||
'auth-domain': {
|
||||
label: 'Auth Domains',
|
||||
description: 'SSO domains and the roles they grant at sign-in.',
|
||||
icon: LogIn,
|
||||
selectorPlaceholder:
|
||||
'Type auth domain ID, separate multiple with comma or space',
|
||||
docsAnchor: 'auth-domain',
|
||||
},
|
||||
organization: {
|
||||
label: 'Organization',
|
||||
description: 'The workspace organization and its display name.',
|
||||
icon: Building,
|
||||
selectorPlaceholder: 'Type * to cover the workspace organization',
|
||||
docsAnchor: 'organization',
|
||||
},
|
||||
};
|
||||
|
||||
export const RESOURCE_ORDER = (
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { useCallback } from 'react';
|
||||
import MultiSelectFilter from 'components/ListFilter/FilterZone/MultiSelectFilter';
|
||||
|
||||
import { SERVICE_ACCOUNTS_STATUS_OPTIONS } from './list.config';
|
||||
@@ -11,34 +10,15 @@ interface Props {
|
||||
setDraft: (newDraft: string) => void;
|
||||
}
|
||||
|
||||
// Picks splice into the draft and run when the dropdown closes; a tag's × or
|
||||
// Clear runs at once. A status term the box holds with another operator shows
|
||||
// as nothing picked.
|
||||
// Picks splice into the draft and run when the dropdown closes; Clear runs at
|
||||
// once. A status term the box holds with another operator shows as nothing
|
||||
// picked.
|
||||
function ServiceAccountStatusFilter({
|
||||
draft,
|
||||
disabled,
|
||||
onApplyDraft,
|
||||
setDraft,
|
||||
}: Props): JSX.Element {
|
||||
const handleChange = useCallback(
|
||||
(statuses: string[]): void => setDraft(withStatuses(draft, statuses)),
|
||||
[draft, setDraft],
|
||||
);
|
||||
|
||||
const handleCommit = useCallback(
|
||||
(statuses: string[]): void => onApplyDraft(withStatuses(draft, statuses)),
|
||||
[draft, onApplyDraft],
|
||||
);
|
||||
|
||||
const handleDropdownVisibleChange = useCallback(
|
||||
(isOpen: boolean): void => {
|
||||
if (!isOpen) {
|
||||
onApplyDraft(draft);
|
||||
}
|
||||
},
|
||||
[draft, onApplyDraft],
|
||||
);
|
||||
|
||||
return (
|
||||
<MultiSelectFilter
|
||||
value={statusesOfQuery(draft)}
|
||||
@@ -46,9 +26,13 @@ function ServiceAccountStatusFilter({
|
||||
placeholder="Status"
|
||||
testId="sa-filter-status"
|
||||
disabled={disabled}
|
||||
onChange={handleChange}
|
||||
onCommit={handleCommit}
|
||||
onDropdownVisibleChange={handleDropdownVisibleChange}
|
||||
onChange={(statuses): void => setDraft(withStatuses(draft, statuses))}
|
||||
onClear={(): void => onApplyDraft(withStatuses(draft, []))}
|
||||
onDropdownVisibleChange={(open): void => {
|
||||
if (!open) {
|
||||
onApplyDraft(draft);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -135,10 +135,9 @@ describe('ServiceAccountsSettings — FGA', () => {
|
||||
renderPage();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('new-sa-btn')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(
|
||||
screen.getByRole('button', { name: /New Service Account/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -161,10 +160,9 @@ describe('ServiceAccountsSettings — FGA', () => {
|
||||
renderPage();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('new-sa-btn')).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(
|
||||
screen.getByRole('button', { name: /New Service Account/i }),
|
||||
).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -37,6 +37,7 @@ import { GlobalShortcuts } from 'constants/shortcuts/globalShortcuts';
|
||||
import { USER_PREFERENCES } from 'constants/userPreferences';
|
||||
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
|
||||
import { useKeyboardHotkeys } from 'hooks/hotkeys/useKeyboardHotkeys';
|
||||
import useComponentPermission from 'hooks/useComponentPermission';
|
||||
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
|
||||
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
@@ -614,7 +615,14 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
|
||||
changelog,
|
||||
]);
|
||||
|
||||
const settingsRoute = ROUTES.ORG_SETTINGS;
|
||||
const [isCurrentOrgSettings] = useComponentPermission(
|
||||
['current_org_settings'],
|
||||
user.role,
|
||||
);
|
||||
|
||||
const settingsRoute = isCurrentOrgSettings
|
||||
? ROUTES.ORG_SETTINGS
|
||||
: ROUTES.SETTINGS;
|
||||
|
||||
const handleMenuItemClick = (event: MouseEvent, item: SidebarItem): void => {
|
||||
if (item.key === ROUTES.SETTINGS) {
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
SettingsNavSection,
|
||||
SidebarItem,
|
||||
} from './sideNav.types';
|
||||
import { Style } from '@signozhq/design-tokens';
|
||||
import Noz from 'components/Noz/Noz';
|
||||
import { NOZ_TOOLTIP_TITLE } from 'components/Noz/Noz.constants';
|
||||
|
||||
@@ -522,7 +523,7 @@ export const getUserSettingsDropdownMenuItems = ({
|
||||
type: 'item',
|
||||
value: 'workspace',
|
||||
label: USER_SETTINGS_MENU_LABELS.workspace,
|
||||
prefix: <Building2 size={14} color="var(--l1-foreground)" />,
|
||||
prefix: <Building2 size={14} color={Style.L1_FOREGROUND} />,
|
||||
testId: 'workspace-settings-nav-item',
|
||||
disabled: isWorkspaceBlocked,
|
||||
disabledTooltip: WORKSPACE_LOCKED_TOOLTIP,
|
||||
@@ -532,7 +533,7 @@ export const getUserSettingsDropdownMenuItems = ({
|
||||
type: 'item',
|
||||
value: 'account',
|
||||
label: USER_SETTINGS_MENU_LABELS.account,
|
||||
prefix: <User size={14} color="var(--l1-foreground)" />,
|
||||
prefix: <User size={14} color={Style.L1_FOREGROUND} />,
|
||||
testId: 'account-settings-nav-item',
|
||||
onClick: (event): void => onSelect('account', event),
|
||||
},
|
||||
@@ -543,7 +544,7 @@ export const getUserSettingsDropdownMenuItems = ({
|
||||
type: 'item',
|
||||
value: 'license',
|
||||
label: USER_SETTINGS_MENU_LABELS.license,
|
||||
prefix: <Shield size={14} color="var(--l1-foreground)" />,
|
||||
prefix: <Shield size={14} color={Style.L1_FOREGROUND} />,
|
||||
testId: 'manage-license-nav-item',
|
||||
onClick: (event): void => onSelect('license', event),
|
||||
});
|
||||
@@ -553,7 +554,7 @@ export const getUserSettingsDropdownMenuItems = ({
|
||||
type: 'item',
|
||||
value: 'keyboard-shortcuts',
|
||||
label: USER_SETTINGS_MENU_LABELS['keyboard-shortcuts'],
|
||||
prefix: <Keyboard size={14} color="var(--l1-foreground)" />,
|
||||
prefix: <Keyboard size={14} color={Style.L1_FOREGROUND} />,
|
||||
testId: 'keyboard-shortcuts-nav-item',
|
||||
onClick: (event): void => onSelect('keyboard-shortcuts', event),
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { screen, waitFor, NO_DELAY_USER_EVENT } from 'tests/test-utils';
|
||||
import { screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { renderTriggeredAlerts } from './_helpers';
|
||||
|
||||
describe('TriggeredAlerts — severity filter', () => {
|
||||
it('filters to only critical-severity rows when "Critical" is selected', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderTriggeredAlerts();
|
||||
|
||||
await waitFor(() =>
|
||||
@@ -30,7 +30,7 @@ describe('TriggeredAlerts — severity filter', () => {
|
||||
});
|
||||
|
||||
it('shows union when multiple severities are selected', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderTriggeredAlerts();
|
||||
|
||||
await waitFor(() =>
|
||||
@@ -55,7 +55,7 @@ describe('TriggeredAlerts — severity filter', () => {
|
||||
});
|
||||
|
||||
it('clearing the filter shows all rows again', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderTriggeredAlerts();
|
||||
|
||||
await waitFor(() =>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user