Compare commits

..

39 Commits

Author SHA1 Message Date
Ashwin Bhatkal
65581481ab test(frontend): restore jest's default 5 s test timeout 2026-11-24 12:09:09 +05:30
Ashwin Bhatkal
bf4e05bc90 test(frontend): check the lazy tab spinner's height through its styled rule 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
12c3248f28 test(frontend): drop the hidden option from role queries now that they are cheap 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
0bc66d9e66 docs(frontend): update the test rules for jsdom without library CSS 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
25f57d13b9 test(frontend): drop the mocks and timeouts that covered slow getComputedStyle 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
c16def0ae1 test(frontend): keep library CSS out of jsdom 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
4384c01527 test(frontend): stop relying on library CSS to show or hide elements 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
09a3b643c6 test(frontend): speed up the last slow tests and fix the member roles test 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
36774785cd test(frontend): find elements through Testing Library instead of the DOM 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
5fd637e7c7 test(dashboards): use menu row test IDs and split the list denial test 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
536c528d8e test(explorer): mock the query editor where it is not under test and drop role queries 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
0fab71c2a9 test(ai-assistant): fake the retry backoff timers 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
28bcecd95a test(llm-observability): use test IDs and fake the mapping save delay 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
2409dca47f test(integrations): split cloud account setup flows and wait for real readiness 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
645b555b04 test(saved-views): fake the hover delay and render the panel alone 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
d81d43a4e9 test(pipelines): split the pipeline edit flow and use test IDs 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
327f77f684 test(infra-monitoring): replace role queries in the k8s list and traces tables 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
5aa6b997c1 test(onboarding): test each questionnaire step on its own 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
bb0ea3e259 test(settings): speed up billing, general, ingestion and service account tests 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
7b9b3dca15 test(alerts): render alert list pieces directly and start flows from URL state 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
a1bb8d676b test(exceptions): wait for the run button to settle before clicking it 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
fd31af27a0 test(auth): fill login, sign-up and invite forms without per-key typing 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
8857cab23f test(roles): test the permission wizard directly instead of through the page 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
107d5ca6ae test(sso): query the auth domain form by test ID and drop slow role lookups 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
1ecc06f9d8 test(authz): wait for the permission batch instead of a fixed 200 ms window 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
4645fb4c92 test(frontend): type the click mock in the user-event wrapper test 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
f9e4ae78e0 test(frontend): cap local jest workers and recycle workers that grow past 1 GB 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
1492c7d3c1 test(frontend): skip antd popup scroll-container lookups in every test 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
b18766a9e1 docs(frontend): run checks only at the gate and add a no-checks keyword 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
5287e35545 docs(frontend): test rules that keep jest tests fast and stable 2026-11-24 12:08:59 +05:30
Ashwin Bhatkal
5970e58e7d test(frontend): skip pointer-events checks and Floating UI layout in every test 2026-11-24 12:08:59 +05:30
Tushar Vats
da35d99714 test(frontend): raise jest test timeout to 10s (#13721)
#### Description

- Multi-step `userEvent` tests (open a drawer, click, save, wait for the
refetch) pass Jest's default 5s on busy CI runners and fail with
`Exceeded timeout of 5000 ms`, though nothing is wrong.
- `jsci` failed three times on SigNoz/signoz#13713, a rules-only change,
each time on different tests (`QuickFilters`, `InviteMembers`,
`PricedModelsTab`, `AttributeMappingsTab`).
- Raises the default `testTimeout` to 10s. Tests with their own timeout
keep it; a truly hung test now takes 10s to fail.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 05:58:08 +00:00
Vinicius Lourenço
f955bb952a perf(settings): load each settings and alert details tab when it opens (#13694)
#### Description

Settings and alert details import every tab up front, so opening
Settings downloads billing (chart.js, uPlot, `moment-timezone`), service
accounts (CodeMirror) and every other tab before the one you asked for
renders. Each tab now loads when it opens, using the per-tab loading
state from #13691. Tab URLs, order, permissions and license checks stay
as they are.

Opening Settings goes from 11.76 MB to 10.95 MB on main today (3.19 MB
to 2.95 MB gzipped), and to 2.55 MB (0.77 MB gzipped) once the entry PRs
are in. The first time a tab opens in a session it shows a short spinner
beside the settings menu.

The ingestion page relied on the `.learn-more` style that the MCP server
tab happened to load; it now imports it itself.

Part of #10192

#### Screenshots / Screen Recordings

Opening Settings pages in Storybook, main on the left. The network is
slowed to 1.6 Mbps so the loading state is visible; at 4 Mbps a page
shows in about 0.3 s:


https://github.com/user-attachments/assets/02da6227-5dac-43a2-b6fe-dfd4968a009b

Across the 188 Settings and alert stories, the tabs render the same in
both themes once loaded, apart from a focus ring left on the members
search and a 1px edge in the role JSON panel. The other differences are
toasts and play steps caught at different moments.
2026-11-24 03:57:36 +00:00
Gaurav Tewari
cb0adcc618 refactor(ai-assistant): import assistant types from @signozhq/noz-client (#13526)
Some checks failed
cacheci / tests (push) Has been cancelled
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- AI Assistant DTOs and enums now come from the `@signozhq/noz-client`
package (pinned `1.12.2`) instead of a generated copy in
`src/api/ai-assistant/`. The API spec lives in the assistant repo, so
bumping a package version replaces hand-syncing the files on every
release.
- Deleted `sigNozAIAssistantAPI.schemas.ts` and the unused orval hooks
in `index.ts`. `chat.ts` (REST + SSE client) stays and keeps using
`AIAssistantInstance`.
- Only types and enums are imported, so the package's hooks and
`setGeneratedAPIInstance` are not wired.

#### Issues closed by this PR


https://github.com/orgs/SigNoz/projects/59/views/18?pane=issue&itemId=315100999&issue=SigNoz%7Cnerve-pod%7C677

#### Screenshots / Screen Recordings

#### Additional Information

- The package exports the same schemas as the deleted file, plus
`ReadinessChecksDTODrain`.

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-23 18:36:19 +00:00
Vinicius Lourenço
b14b634bce perf(web): keep the tab bar while a lazy tab loads (#13691)
#### Description

Pages with tabs (Settings, Logs, Traces, Metrics and others) render them
through `RouteTab`, which mounts only the active tab but receives every
tab's component already imported. To let a page load each tab when it
opens, a tab has to be able to suspend. Each tab pane now has its own
loading boundary, so a tab that is still loading shows a spinner under
the tab bar instead of the whole page turning into one.

Nothing changes on its own: no tab is lazy yet. The pages follow in
separate PRs per owner, and with them and the entry PRs in, opening
Settings goes from 11.76 MB to 2.55 MB (3.19 MB to 0.77 MB gzipped).

The jest setup's `getComputedStyle` fallback now returns a width and
height, since tables mounted inside a lazy pane crashed without them.

Part of #10192

#### Screenshots / Screen Recordings

Settings with its pages loading on demand through this change (the
follow-up PR), in Storybook with the network slowed to 1.6 Mbps, main on
the left:


https://github.com/user-attachments/assets/d22bf877-1ff8-4d25-a4eb-85a0a046998c
2026-11-23 17:48:51 +00:00
Vinicius Lourenço
7ea0d57417 fix(roles): keep the editor loading until the role's grants are in local state (#13671)
Some checks failed
build-staging / staging (push) Has been cancelled
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

Opening a role's JSON view from a link or after a reload
(`/settings/roles/:id/edit?viewMode=json`) could show `[]` instead of
the role's grants, and saving then replaced them with whatever was
typed. It happened whenever the permission check answered before the
role fetch.

The editor reads its value only once, when it mounts, so the page now
stays in its loading state until the fetched role is in local state.
2026-11-23 14:26:30 +00:00
Nikhil Soni
1e08a94ab8 fix: application support for clickhouse 26.8 (#13371)
#### Description

Part of SigNoz/platform-pod#3428.

- Run every integration suite against ClickHouse `26.8.34` (SQLite only,
non-blocking) to catch upgrade issues early.
- Bump the collector to `v0.144.17` for
SigNoz/signoz-otel-collector#990: 26.8 rejects the migrator's `CREATE`
of AggregatingMergeTree tables with plain columns outside the sorting
key.
- Pin `use_variant_as_common_type=0`: 26.8 turns mismatched types into
`Variant` instead of the no-common-type error. Handling `Variant`
results instead is tracked in SigNoz/events-pod#271.
- Drop `avg(timestamp)` from the pinned unsupported aggregations: 26.8
averages `DateTime64` into an instant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01X3AdVnw3X4N8Knhw8Yghtv
2026-11-23 13:24:36 +00:00
Vinicius Lourenço
cbfbb103af fix(web): correct the CSS modules guide, forbid component overrides, replace undefined tokens (#13697)
## Description

The CSS modules guide told us to write `:local(@keyframes name)`, and
Greptile now flags plain `@keyframes` in review because of it. That form
doesn't compile (Sass fails with `expected selector`), and it isn't
needed: CSS Modules already scope `@keyframes` in a `.module.scss` file.

While checking the rest of the guide against `@signozhq/ui` and the
design tokens, I fixed two more things that don't exist or don't behave
as written. The `--periscope-font-size-*` and `--font-size-*` tokens
aren't defined anywhere, so the checklist now points at the text style
tokens. And a nested `.icon` inside `.button` compiles to `.button
.icon`, so it is scoped under `.button`, contrary to what the comment
said.

The app had the same problem: the AI assistant, the Top List panel and
the Geo Map tooltip used `--periscope-font-size-*`, `--font-size-*` and
`--font-weight-*` tokens that were never defined, so their text fell
back to whatever size and weight it inherited. They now use the
typography tokens, so small labels render at 11px and medium or semibold
text gets its weight back. Expect those surfaces to look slightly
different.

The guide also taught how to override `@signozhq/ui` components through
their CSS variables and `data-*` attributes, and several of the
variables it listed didn't exist. That section now says not to override
them at all: use the component's props, put layout on a wrapper you own,
and when the component can't do what the design needs, file a UI
suggestion in `SigNoz/uforge-pod` instead of restyling it locally.
`frontend/CLAUDE.md` says the same, so agents stop writing overrides.

## Screenshots

AI assistant thread list: group headers and timestamps drop to 11px,
headers get bolder.
![AI assistant thread list, before and
after](https://github.com/user-attachments/assets/97d85d76-95d1-4793-b968-049ba21b11d1)

AI assistant suggested actions: the label drops to 11px, the action
buttons grow to 13px.
![AI assistant suggested actions, before and
after](https://github.com/user-attachments/assets/bc115d6d-2a95-47c5-8aeb-8d8da62cbd7a)

Geo Map tooltip: the place name goes to 13px medium, the code, label and
value to 11px.
![Geo Map tooltip, before and
after](https://github.com/user-attachments/assets/12b54137-2310-4e0b-976b-ac94e7ad364c)

Top List: the value column goes from regular to medium weight.
![Top List values, before and
after](https://github.com/user-attachments/assets/f90222b0-d256-499d-90b7-03065676886d)
2026-11-23 13:17:32 +00:00
Swapnil Nakade
fbca5e7d80 feat(auditor): add tls to the kafka auditor (#13710)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description
- Adds `auditor::kafka::tls` (`enabled`, `ca_file`, `cert_file`,
`key_file`) so the Kafka auditor can connect to brokers that require TLS
or mTLS, such as Redpanda's internal listener in TLS deployments.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR
closes https://github.com/SigNoz/keystone-pod/issues/225
2026-11-23 10:57:46 +00:00
210 changed files with 4304 additions and 7753 deletions

View File

@@ -9,12 +9,14 @@ paths:
Examples and the harness API live in [`frontend/src/tests/README.md`](../../frontend/src/tests/README.md).
- **Import from the harness.** `render`, `screen`, `userEvent`, `waitFor` and the rest come from `tests/test-utils`, never from `@testing-library/react`. The harness mounts the router, React Query, Redux, app context and preferences. When it can't do what a test needs, extend `tests/test-utils` instead of importing around it.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` computes the accessibility tree on every call and is the slowest query.
- **Interact like a user.** `const user = userEvent.setup({ pointerEventsCheck: 0 })`, then an awaited `user.click`, `hover`, `keyboard` or `type`. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` 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`. 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`.
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.
- **Router through the harness.** Pass `initialRoute`/`routePath` to `render` and assert with `getCurrentLocation()` from `lib/router/navigation`. Never mock `react-router`, `react-router-dom` or `lib/history`; when a test can't render at a route, use the `lib/router` spies in `tests/router-mocks`.
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides (`@testing-library/user-event` in `jest.setup.ts`) or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
- **Type mocks and fixtures.** `jest.mocked(fn)` for module mocks, `jest.fn() as jest.MockedFunction<T>` for a standalone mock you configure or assert on. Fixtures carry their real type, from `src/api/generated` where it exists. No `any`, no `as unknown as`. An inline `onX={jest.fn()}` on a typed prop that is never asserted needs no annotation.
- **A test fails without its change.** Revert the change, or break the line under test, and run the test before you finish: it must fail. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
- **One behaviour per test, at the smallest render.** Render the component that owns the behaviour, not the page around it, unless the page wiring is the behaviour. A flow of steps (a wizard, a multi-step form) becomes one test per step that starts at that step through props, store or route. A full click-through belongs in the e2e suite (`tests/e2e`).
- **Each test under 500 ms.** `pnpm jest <file> --verbose` prints each test's time. CI runs about four times slower than a laptop, and the timeout is 5 s. Never raise a timeout (`jest.setTimeout`, a third argument to `it`) to make a slow test pass; slim the test instead.
- **A test fails without its change.** At the gate in [`frontend/AGENTS.md`](../../frontend/AGENTS.md), revert the change, or break the line under test, and run the test: it must fail, and each test must stay under 500 ms. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
- **No limit on tests per file.** Split a file when it mixes unrelated behaviour, not to hit a count.

View File

@@ -94,7 +94,7 @@ jobs:
postgres:15 \
clickhouse/clickhouse-server:25.12.5 \
clickhouse/clickhouse-keeper:25.12.5 \
signoz/signoz-otel-collector:v0.144.16-rc.1 \
signoz/signoz-otel-collector:v0.144.17 \
wiremock/wiremock:2.35.1-1 \
| xargs -P 0 -n 1 docker pull -q
- name: python

View File

@@ -85,13 +85,18 @@ jobs:
- wal
clickhouse-version:
- 25.12.5
- 26.8.34
signoz-otel-collector-version:
- v0.144.16-rc.1
- v0.144.17
postgres-version:
- 15
exclude:
- sqlstore-provider: postgres
clickhouse-version: 26.8.34
if: |
((github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))) && contains(github.event.pull_request.labels.*.name, 'safe-to-integrate')
continue-on-error: ${{ matrix.clickhouse-version == '26.8.34' }}
runs-on: ubuntu-latest
steps:
- name: checkout

View File

@@ -474,6 +474,14 @@ auditor:
compression: lz4
# The maximum time to drain buffered events on shutdown. Undelivered events are dropped after it.
shutdown_timeout: 30s
tls:
# Whether to connect to the brokers over TLS.
enabled: false
# The PEM CA bundle that verifies broker certificates. Empty uses the system roots.
ca_file: ""
# The client certificate and key, for brokers that require client auth. Set both or neither.
cert_file: ""
key_file: ""
##################### Cloud Integration #####################
cloudintegration:

View File

@@ -2,7 +2,10 @@ package kafkaauditor
import (
"context"
"crypto/tls"
"crypto/x509"
"log/slog"
"os"
"github.com/twmb/franz-go/pkg/kgo"
"github.com/twmb/franz-go/plugin/kslog"
@@ -10,6 +13,7 @@ import (
"github.com/SigNoz/signoz/pkg/auditor"
"github.com/SigNoz/signoz/pkg/auditor/auditorserver"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/licensing"
"github.com/SigNoz/signoz/pkg/types/audittypes"
@@ -39,13 +43,25 @@ func newProvider(_ context.Context, providerSettings factory.ProviderSettings, c
// Acks from all in-sync replicas, idempotent writes and unbounded record retries are franz-go defaults and are kept as is.
// A delivery timeout or retry limit lets franz-go < v1.22.2 ack a record that was never written (twmb/franz-go#1484).
client, err := kgo.NewClient(
opts := []kgo.Opt{
kgo.SeedBrokers(config.Kafka.Brokers...),
kgo.ClientID(config.Kafka.ClientID),
kgo.ProducerBatchCompression(compressionCodec(config.Kafka.Compression)),
kgo.ProducerLinger(0),
kgo.WithLogger(kslog.New(settings.Logger())),
)
}
if config.Kafka.TLS.Enabled {
tlsConfig, err := newTLSConfig(config.Kafka.TLS)
if err != nil {
return nil, err
}
// franz-go sets ServerName per broker from the dialed address.
opts = append(opts, kgo.DialTLSConfig(tlsConfig))
}
client, err := kgo.NewClient(opts...)
if err != nil {
return nil, err
}
@@ -130,3 +146,30 @@ func compressionCodec(name string) kgo.CompressionCodec {
return kgo.NoCompression()
}
}
func newTLSConfig(config auditor.TLSConfig) (*tls.Config, error) {
tlsConfig := &tls.Config{}
if config.CAFile != "" {
caPEM, err := os.ReadFile(config.CAFile)
if err != nil {
return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot read auditor::kafka::tls::ca_file")
}
tlsConfig.RootCAs = x509.NewCertPool()
if !tlsConfig.RootCAs.AppendCertsFromPEM(caPEM) {
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "auditor::kafka::tls::ca_file %q holds no PEM certificate", config.CAFile)
}
}
if config.CertFile != "" {
cert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile)
if err != nil {
return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot load auditor::kafka::tls::cert_file and auditor::kafka::tls::key_file")
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
return tlsConfig, nil
}

View File

@@ -0,0 +1,269 @@
package kafkaauditor
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/twmb/franz-go/pkg/kfake"
"github.com/twmb/franz-go/pkg/kgo"
"github.com/SigNoz/signoz/pkg/auditor"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/types/audittypes"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/SigNoz/signoz/pkg/version"
)
func TestExport_MutualTLS(t *testing.T) {
certificates := newTestCertificates(t)
cluster, err := kfake.NewCluster(
kfake.NumBrokers(1),
kfake.SeedTopics(1, "tls_audit"),
kfake.TLS(&tls.Config{
Certificates: []tls.Certificate{certificates.server},
ClientCAs: certificates.caPool,
ClientAuth: tls.RequireAndVerifyClientCert,
}),
)
require.NoError(t, err)
t.Cleanup(cluster.Close)
testCases := []struct {
name string
tls auditor.TLSConfig
err bool
}{
{
name: "CAAndClientCertificate_Delivers",
tls: certificates.client,
},
{
name: "TLSDisabled_Fails",
tls: auditor.TLSConfig{},
err: true,
},
{
name: "WithoutClientCertificate_Fails",
tls: auditor.TLSConfig{Enabled: true, CAFile: certificates.client.CAFile},
err: true,
},
{
name: "WithoutCA_Fails",
tls: auditor.TLSConfig{Enabled: true, CertFile: certificates.client.CertFile, KeyFile: certificates.client.KeyFile},
err: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
config := auditor.Config{
Provider: "kafka",
BufferSize: 10,
BatchSize: 5,
FlushInterval: 50 * time.Millisecond,
Kafka: auditor.KafkaConfig{
Brokers: cluster.ListenAddrs(),
Topic: "tls_audit",
ClientID: "signoz-tls-test",
Compression: "lz4",
ShutdownTimeout: 30 * time.Second,
TLS: testCase.tls,
},
}
auditor, err := newProvider(context.Background(), instrumentationtest.New().ToProviderSettings(), config, nil, version.Info)
require.NoError(t, err)
provider := auditor.(*provider)
defer provider.client.Close()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err = provider.export(ctx, []audittypes.AuditEvent{newTestEvent(coretypes.ResourceUser, coretypes.VerbCreate, testCase.name)})
if testCase.err {
assert.True(t, errors.Is(err, context.DeadlineExceeded))
return
}
require.NoError(t, err)
})
}
consumerTLS, err := newTLSConfig(certificates.client)
require.NoError(t, err)
consumer, err := kgo.NewClient(
kgo.SeedBrokers(cluster.ListenAddrs()...),
kgo.DialTLSConfig(consumerTLS),
kgo.ConsumeTopics("tls_audit"),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
)
require.NoError(t, err)
defer consumer.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
fetches := consumer.PollFetches(ctx)
require.Empty(t, fetches.Errors())
assert.Len(t, fetches.Records(), 1)
}
func TestNewTLSConfig(t *testing.T) {
certificates := newTestCertificates(t)
notPEMFile := filepath.Join(t.TempDir(), "not-pem.crt")
require.NoError(t, os.WriteFile(notPEMFile, []byte("not a pem"), 0o600))
testCases := []struct {
name string
config auditor.TLSConfig
err bool
wantRootCAs bool
wantCertificates int
}{
{
name: "NoFiles_UsesSystemRoots",
config: auditor.TLSConfig{Enabled: true},
},
{
name: "CAOnly",
config: auditor.TLSConfig{Enabled: true, CAFile: certificates.client.CAFile},
wantRootCAs: true,
},
{
name: "CAAndClientCertificate",
config: certificates.client,
wantRootCAs: true,
wantCertificates: 1,
},
{
name: "CAFileMissing",
config: auditor.TLSConfig{Enabled: true, CAFile: filepath.Join(t.TempDir(), "missing-ca.crt")},
err: true,
},
{
name: "CAFileNotPEM",
config: auditor.TLSConfig{Enabled: true, CAFile: notPEMFile},
err: true,
},
{
name: "KeyFileMissing",
config: auditor.TLSConfig{Enabled: true, CertFile: certificates.client.CertFile, KeyFile: filepath.Join(t.TempDir(), "missing.key")},
err: true,
},
{
name: "CertFileNotPEM",
config: auditor.TLSConfig{Enabled: true, CertFile: notPEMFile, KeyFile: certificates.client.KeyFile},
err: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
tlsConfig, err := newTLSConfig(testCase.config)
if testCase.err {
assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
return
}
require.NoError(t, err)
assert.Equal(t, testCase.wantRootCAs, tlsConfig.RootCAs != nil)
assert.Len(t, tlsConfig.Certificates, testCase.wantCertificates)
})
}
}
type testCertificates struct {
caPool *x509.CertPool
server tls.Certificate
client auditor.TLSConfig
}
// Issues a CA, a broker certificate for 127.0.0.1 and a client certificate, writing the client side as ca.crt, tls.crt and tls.key.
func newTestCertificates(t *testing.T) testCertificates {
t.Helper()
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
caTemplate := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "test-ca"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(time.Hour),
IsCA: true,
BasicConstraintsValid: true,
KeyUsage: x509.KeyUsageCertSign,
}
caDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey)
require.NoError(t, err)
ca, err := x509.ParseCertificate(caDER)
require.NoError(t, err)
serverCertPEM, serverKeyPEM := issueTestCertificate(t, ca, caKey, &x509.Certificate{
SerialNumber: big.NewInt(2),
Subject: pkix.Name{CommonName: "broker"},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
})
server, err := tls.X509KeyPair(serverCertPEM, serverKeyPEM)
require.NoError(t, err)
clientCertPEM, clientKeyPEM := issueTestCertificate(t, ca, caKey, &x509.Certificate{
SerialNumber: big.NewInt(3),
Subject: pkix.Name{CommonName: "signoz"},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
})
dir := t.TempDir()
client := auditor.TLSConfig{
Enabled: true,
CAFile: filepath.Join(dir, "ca.crt"),
CertFile: filepath.Join(dir, "tls.crt"),
KeyFile: filepath.Join(dir, "tls.key"),
}
require.NoError(t, os.WriteFile(client.CAFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}), 0o600))
require.NoError(t, os.WriteFile(client.CertFile, clientCertPEM, 0o600))
require.NoError(t, os.WriteFile(client.KeyFile, clientKeyPEM, 0o600))
caPool := x509.NewCertPool()
caPool.AddCert(ca)
return testCertificates{caPool: caPool, server: server, client: client}
}
func issueTestCertificate(t *testing.T, ca *x509.Certificate, caKey *ecdsa.PrivateKey, template *x509.Certificate) ([]byte, []byte) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
template.NotBefore = time.Now().Add(-time.Hour)
template.NotAfter = time.Now().Add(time.Hour)
template.KeyUsage = x509.KeyUsageDigitalSignature
der, err := x509.CreateCertificate(rand.Reader, template, ca, &key.PublicKey, caKey)
require.NoError(t, err)
keyDER, err := x509.MarshalECPrivateKey(key)
require.NoError(t, err)
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
}

View File

@@ -99,7 +99,7 @@ is still by hand. The generator never adds a SideNav item; do that in
CSS Modules (`docs/css-modules-guide.md`), React Query for server state (prefer
`api/generated` hooks), nuqs for URL state, Zustand for client state, `data-testid` on
every interactive element.
5. **Verify** before reporting done:
5. **Verify** at the gate in `AGENTS.md` (commit, push or PR), not after each edit; skip it while the user says `no checks`:
```bash
pnpm tsgo --noEmit
pnpm oxlint src/pages/<Feature>

View File

@@ -28,20 +28,24 @@ You are operating within a constrained context window and strict system prompts.
- UI primitives come from `@signozhq/ui` (subpath imports) and icons from `@signozhq/icons`. No new `antd` component or direct icon library (`lucide-react`) where `@signozhq/ui` has an equivalent; `signoz/no-antd-components` enforces part of this list.
- Exception: a control added beside `antd` siblings of the same kind (a tab in an `antd` tab strip) matches them until that surface migrates. Say so in the PR.
- When `@signozhq/ui` or `@signozhq/icons` lacks what you need, say so in the PR before reaching for another library.
- Before styling a `@signozhq/ui` component, check its props in `node_modules/@signozhq/ui/dist/<component>/*.d.ts` for `className`/`style` support; some omit them. Avoid overriding the component's CSS vars unless explicitly needed.
- Never override a `@signozhq/ui` component's styles: no `--<component>-*` CSS variables, no `:global` class or `data-*` selectors, no restyling through `className`/`style`. Use its props, and put layout on a wrapper you own. When it can't do what the design needs, file a UI suggestion in `SigNoz/uforge-pod` (`ui-suggestion.yml` template) and link it in the PR.
- When writing code that could need authorization checks, read ./src/lib/authz/README.md
- A flow that gains a request also gates on that request's permission: a rename that now reads the view first needs `read` as well as `update`.
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.
- A payload saved under another kind or schema copies only the fields that schema accepts, and drops bindings to columns the user removed. The server rejects unknown or stale fields, so the preview works and the save fails.
3. FORCED VERIFICATION: Your internal tools mark file writes as successful even if the code does not compile. Run these checks once all changes of a task are done, never after each edit. You are FORBIDDEN from reporting a task as complete until you have:
3. CHECKS AT THE GATE: Your internal tools mark file writes as successful even if the code does not compile, so the checks below are required, but only at the gate. The gate is when the user says commit, push, raise or update the PR, mark it ready, or "run checks". Never run them after each edit or between the user's iterations.
- Between gates, after an edit, run at most the one test file that covers it.
- `no checks`: when the user says it (or "don't run tests", "just making changes"), run nothing: no tests, type check, lint, format or build. Make the change and stop. This holds until the user names a gate.
At the gate, you are FORBIDDEN from reporting a task as complete until you have:
- Run `pnpm tsgo --noEmit`
- Run `pnpm lint:js --quiet` to find critical errors
- Run `pnpm oxlint <file1> <file2>` and fix all warnings
- Run `pnpm build`
- Find if the file has tests for it, or if there's `__test__` folder or the parent folder has tests, and run. Run them before coding the change or after all changes, never in between.
- For e2e, run only the specs you added or changed: the stack is heavy. Leave the full jest and e2e suites to CI unless the user asks.
- For every test you added or changed, revert the change it covers and confirm the test fails
- For every test you added or changed, revert the change it covers and confirm the test fails, and that each test runs under 500 ms (`pnpm jest <file> --verbose`)
- On a stacked branch (`gh stack`), run `pnpm tsgo --noEmit` on every branch above it before pushing: a renamed prop or moved export breaks them
- Fixed ALL resulting errors

View File

@@ -9,12 +9,12 @@
- [ ] No deep class nesting (max 3 class levels; pseudo-classes/elements and parent-reference selectors like `&.active`, `&#bar` are not counted)
- [ ] No hardcoded colors - use `--l1/l2/l3-*` semantic tokens (not `--bg-*` primitives)
- [ ] No magic numbers - use `--spacing-*` tokens
- [ ] Typography uses `--periscope-font-size-*` or `--font-size-*` tokens
- [ ] @signozhq/ui overrides use CSS variables, not direct class overrides
- [ ] Global escapes only for third-party overrides
- [ ] Typography uses `--{variant}-{size}-{weight}-*` text style tokens (see Typography)
- [ ] No overrides of `@signozhq/ui` components (see below)
- [ ] Global escapes only for third-party overrides (`@signozhq/ui` is not third-party)
- [ ] No ID selectors
- [ ] No bare element selectors
- [ ] Keyframes use `:local(@keyframes name)` to avoid global collisions
- [ ] Keyframes are declared in the module with plain `@keyframes name` (already local)
## Config (vite.config.ts)
@@ -77,7 +77,7 @@ css: {
// BAD: Nesting creates separate classes you might not expect
.button {
.icon { } // -> styles.icon (separate class, not scoped under .button)
.icon { } // -> styles.icon, but the rule is `.button .icon`: it only matches inside .button
}
// GOOD: Flat structure
@@ -289,88 +289,32 @@ Use L1/L2/L3 semantic tokens - they handle light/dark theme automatically.
- L2 = elevated surfaces (cards, panels)
- L3 = nested/inset elements
## Overriding @signozhq/ui Components
## @signozhq/ui Components
Components expose CSS variables for customization.
Don't override them. That covers setting a component's `--<component>-*` CSS variables, targeting its classes or `data-*` attributes through `:global(...)`, and restyling it with `className` or `style`. An override keeps working until the component changes, then breaks with no type error or lint warning, and the screen drifts from every other one using that component.
You can ensure they exist by looking at ./node_modules/@signozhq/ui/dist.
Never write a override without confirm it exists.
Override via:
### Method 1: CSS Variables (Preferred)
Each component exposes `--<component>-<property>` variables:
- Use the component's props (`variant`, `color`, `size`, ...) for how it looks.
- Put layout (position, margin, width inside a flex or grid parent) on a wrapper element you own.
- If the component can't do what the design needs, file a [UI suggestion](https://github.com/SigNoz/uforge-pod/issues/new?template=ui-suggestion.yml) in `SigNoz/uforge-pod` and ship with the component as it renders until the suggestion is decided. Link the issue in the PR.
```scss
// Override Button
.customButton {
--button-background: var(--success-background);
--button-border-radius: var(--radius-2);
--button-padding: var(--spacing-4) var(--spacing-8);
--button-font-size: var(--label-base-400-font-size);
// BAD: Restyling the component
.saveButton {
--button-primary-background-color: var(--success-background);
}
// Override Input
.customInput {
--input-height: 2.5rem;
--input-border-color: var(--l2-border);
--input-padding: var(--spacing-2) var(--spacing-6);
--input-placeholder-color: var(--l3-foreground);
.toolbar :global([data-variant="outlined"]) {
--button-variant-outlined-border: 1px solid var(--accent-primary);
}
// Override nested parts
.customInput {
--input-prefix-padding: 0 var(--spacing-4) 0 var(--spacing-6);
--input-suffix-color: var(--accent-primary);
// GOOD: Layout on your own wrapper, looks from props
.toolbarActions {
display: flex;
gap: var(--spacing-4);
margin-left: auto;
}
```
### Method 2: Data Attributes
Components use data attributes for variants/states. Target them for state-specific overrides:
```scss
// Target variant
.wrapper :global([data-variant="outlined"]) {
--button-border-color: var(--accent-primary);
}
// Target size
.wrapper :global([data-size="sm"]) {
--button-font-size: var(--label-small-400-font-size);
}
// Target color
.wrapper :global([data-color="destructive"]) {
--button-background: var(--danger-background);
}
// Target state (Radix patterns)
.popover :global([data-state="open"]) {
opacity: 1;
}
.tooltip :global([data-side="top"]) {
margin-bottom: var(--spacing-2);
}
```
### Common Component CSS Variables
**Button:**
- `--button-background`, `--button-border-radius`, `--button-padding`
- `--button-font-size`, `--button-height`, `--button-gap`
- `--button-hover-background`, `--button-disabled-opacity`
**Input:**
- `--input-height`, `--input-border-color`, `--input-background`
- `--input-padding`, `--input-font-size`, `--input-placeholder-color`
- `--input-focus-outline-color`, `--input-hover-border-color`
- `--input-prefix-*`, `--input-suffix-*` for adornments
**General pattern:** `--<component>-<property>` or `--<component>-<state>-<property>`
## Good Patterns
### Structure
@@ -434,24 +378,21 @@ Components use data attributes for variants/states. Target them for state-specif
### Keyframes (Local Scoping)
Without `:local()`, keyframe names are global and can clash across modules:
CSS Modules scope `@keyframes` like classes: the build renames `fadeIn` to `_fadeIn_<hash>` and rewrites every `animation` in the same module that names it. Don't wrap it in `:local(...)`; Sass rejects `:local(@keyframes fadeIn)` with `expected selector`.
```scss
// BAD: Global keyframe - can conflict with other modules
// GOOD: Local to this module
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
// GOOD: Locally scoped keyframe
:local(@keyframes fadeIn) {
from { opacity: 0; }
to { opacity: 1; }
}
.modal {
animation: fadeIn 200ms ease;
}
// BAD: Doesn't compile
:local(@keyframes fadeIn) { }
```
## JS Import Patterns

View File

@@ -67,6 +67,8 @@ const config: Config.InitialOptions = {
testPathIgnorePatterns: ['/node_modules/', '/public/'],
moduleDirectories: ['node_modules', 'src'],
testEnvironment: '<rootDir>/jest.environment.cjs',
// Local only: the default (cores - 1) workers exhaust RAM when several runs overlap.
...(process.env.CI ? {} : { maxWorkers: 4, workerIdleMemoryLimit: '1GB' }),
coverageThreshold: {
global: {
statements: 80,

View File

@@ -16,6 +16,24 @@ class JSDOMWithRequestEnvironment extends TestEnvironment {
Object.defineProperty(this, 'signal', { value: signal ?? super.signal });
}
};
// Library CSS (antd's runtime styles, CodeMirror's theme, @signozhq/ui's
// injected modules) stays out of the document, as the app's own stylesheets
// already do through moduleNameMapper. jsdom matches every rule on each
// getComputedStyle call, which made a role query take up to half a second.
// rc-util adds and removes an empty style tag to find its container, so a
// dropped tag must also be removable.
const { Node, HTMLStyleElement, document } = this.global;
for (const method of ['appendChild', 'insertBefore', 'removeChild']) {
const original = Node.prototype[method];
Node.prototype[method] = function (node, ...rest) {
const isDroppedStyle =
this === document.head &&
node instanceof HTMLStyleElement &&
node.parentNode !== this;
return isDroppedStyle ? node : original.call(this, node, ...rest);
};
}
}
}

View File

@@ -39,6 +39,11 @@ if (!HTMLElement.prototype.scrollIntoView) {
HTMLElement.prototype.scrollIntoView = function (): void {};
}
// jsdom has no elementFromPoint; CodeMirror calls it on mousedown to place the cursor.
if (!document.elementFromPoint) {
document.elementFromPoint = (): Element | null => null;
}
// jsdom doesn't implement the Pointer Capture API, which Radix UI primitives
// (e.g. @signozhq/ui Select) call when opening. Stub them so those components
// can be exercised in tests.
@@ -120,29 +125,9 @@ if (typeof globalThis.DOMRect === 'undefined') {
};
}
// Patch getComputedStyle to handle CSS parsing errors from @signozhq/* packages.
// These packages inject CSS at import time via style-inject / vite-plugin-css-injected-by-js.
// jsdom's nwsapi cannot parse some of the injected selectors (e.g. Tailwind's :animate-in),
// causing SyntaxErrors during getComputedStyle / getByRole calls.
const _origGetComputedStyle = window.getComputedStyle;
window.getComputedStyle = function (
elt: Element,
pseudoElt?: string | null,
): CSSStyleDeclaration {
try {
return _origGetComputedStyle.call(window, elt, pseudoElt);
} catch {
// Return a minimal CSSStyleDeclaration so callers (testing-library, Radix UI)
// see the element as visible and without animations.
return {
display: '',
visibility: '',
opacity: '1',
animationName: 'none',
getPropertyValue: () => '',
} as unknown as CSSStyleDeclaration;
}
};
jest.mock('@testing-library/user-event', () =>
jest.requireActual('tests/userEventWithDefaults'),
);
beforeAll(() => server.listen());

View File

@@ -56,6 +56,7 @@
"@sentry/vite-plugin": "5.3.0",
"@signozhq/design-tokens": "2.8.0",
"@signozhq/icons": "0.4.0",
"@signozhq/noz-client": "1.13.0",
"@signozhq/ui": "0.4.0-rc.5",
"@tanstack/react-table": "8.21.3",
"@tanstack/react-virtual": "3.13.22",

View File

@@ -82,6 +82,9 @@ importers:
'@signozhq/icons':
specifier: 0.4.0
version: 0.4.0
'@signozhq/noz-client':
specifier: 1.13.0
version: 1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
'@signozhq/ui':
specifier: 0.4.0-rc.5
version: 0.4.0-rc.5(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
@@ -3248,6 +3251,13 @@ packages:
'@signozhq/icons@0.4.0':
resolution: {integrity: sha512-QctNvNPlQlsefFdIVmSy/P/7a1IcQ3IryKP0KPMqtoqew3q89FGUmFa5IfEJ7Z3CHhtG1zaXwBKqP72QkLyA3g==}
'@signozhq/noz-client@1.13.0':
resolution: {integrity: sha512-130L2xomHnQZK8ZtAst34qFz9d2rSF/JYpg9gKvJkZVS9+46CPZeTW8Va9PNS9Oa5owezVHIXZStTEbsHIxnwg==}
peerDependencies:
axios: ^1.20.0
react: ^18.2.0
react-query: ^3.39.3
'@signozhq/ui@0.4.0-rc.5':
resolution: {integrity: sha512-WlJMfeDfvL2hjMpTpHhhND/tuK7X0sfXQlx6E1ZG+6E/DYHpuhYljfvW3E6/BohIlHFlTyCs/ZMl9wnV2k9Zcw==}
peerDependencies:
@@ -12373,6 +12383,12 @@ snapshots:
'@signozhq/icons@0.4.0': {}
'@signozhq/noz-client@1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)':
dependencies:
axios: 1.21.1
react: 18.2.0
react-query: 3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
'@signozhq/ui@0.4.0-rc.5(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)':
dependencies:
'@base-ui/react': 1.8.0(@date-fns/tz@1.4.1)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)

View File

@@ -11,7 +11,7 @@
* to resume, which each return a new executionId to open a fresh SSE stream.
*
* Types in this file re-use the OpenAPI-generated DTOs in
* `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`.
* `@signozhq/noz-client`.
* Local types are defined only when the UI needs a different shape — for
* example, the SSE event union adds a literal `type` discriminator that the
* generated event DTOs leave loose.
@@ -60,7 +60,7 @@ import type {
PageTypeDTO,
ToolCallEventDTO,
ToolResultEventDTO,
} from './sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import { LOCALSTORAGE } from 'constants/localStorage';
import {

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -12,4 +12,5 @@
import '@signozhq/design-tokens';
import '@signozhq/icons';
import '@signozhq/noz-client';
import '@signozhq/ui';

View File

@@ -176,6 +176,7 @@ export default function DownloadOptionsMenu({
arrow={false}
open={isPopoverOpen}
onOpenChange={setIsPopoverOpen}
destroyTooltipOnHide
rootClassName="download-popover"
>
<Tooltip title="Download" placement="top">

View File

@@ -771,7 +771,11 @@ describe('EditMemberDrawer', () => {
it('keeps roles editable', async () => {
renderDrawer({ member: selfMember });
await expect(screen.findByText('Select roles')).resolves.toBeInTheDocument();
await expect(
screen.findByTestId(
`member-roles-select-chip-${managedRoles[0].id}-remove`,
),
).resolves.toBeInTheDocument();
expect(screen.queryByTestId('member-roles-locked')).not.toBeInTheDocument();
});
});

View File

@@ -2,6 +2,7 @@ import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import InviteMembers from '../InviteMembers';
import { InviteMembersProps } from '../types';
import { pickRole } from './roleSelectUtils';
import {
@@ -9,9 +10,12 @@ import {
createErrorHandler,
createRolesHandler,
createSuccessHandler,
enterInviteEmail,
VALID_EMAIL,
} from './testUtils';
type InviteCallback = Required<InviteMembersProps>['onSuccess'];
describe('InviteMembers - Edge Cases', () => {
beforeEach(() => {
server.use(createRolesHandler(), createSuccessHandler());
@@ -23,7 +27,7 @@ describe('InviteMembers - Edge Cases', () => {
describe('reset behavior', () => {
it('clears all rows when reset is called', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers
@@ -36,13 +40,12 @@ describe('InviteMembers - Edge Cases', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], VALID_EMAIL);
await user.type(emailInputs[1], 'bob@signoz.io');
await enterInviteEmail(user, 0, VALID_EMAIL);
await enterInviteEmail(user, 1, 'bob@signoz.io');
await user.click(screen.getByTestId('reset-btn'));
const resetInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
const resetInputs = screen.getAllByTestId(/^invite-email-.*-field$/);
expect(resetInputs).toHaveLength(2);
resetInputs.forEach((input) => {
expect(input).toHaveValue('');
@@ -50,7 +53,7 @@ describe('InviteMembers - Edge Cases', () => {
});
it('clears results on reset', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers
@@ -67,8 +70,7 @@ describe('InviteMembers - Edge Cases', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], VALID_EMAIL);
await enterInviteEmail(user, 0, VALID_EMAIL);
await pickRole(user, 0, 'role-viewer');
await user.click(screen.getByTestId('submit-btn'));
@@ -84,7 +86,7 @@ describe('InviteMembers - Edge Cases', () => {
describe('results cleared on edit', () => {
it('clears API error when email is edited', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(createErrorHandler('already_exists', 'User already exists'));
@@ -98,8 +100,7 @@ describe('InviteMembers - Edge Cases', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], VALID_EMAIL);
await enterInviteEmail(user, 0, VALID_EMAIL);
await pickRole(user, 0, 'role-viewer');
await user.click(screen.getByTestId('submit-btn'));
@@ -107,7 +108,7 @@ describe('InviteMembers - Edge Cases', () => {
screen.findByTestId('invite-api-error'),
).resolves.toBeInTheDocument();
await user.type(emailInputs[0], 'x');
await user.type(screen.getAllByTestId(/^invite-email-.*-field$/)[0], 'x');
await waitFor(() => {
expect(screen.queryByTestId('invite-api-error')).not.toBeInTheDocument();
@@ -115,7 +116,7 @@ describe('InviteMembers - Edge Cases', () => {
});
it('clears API error when role is changed', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(createErrorHandler('already_exists', 'User already exists'));
@@ -129,8 +130,7 @@ describe('InviteMembers - Edge Cases', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], VALID_EMAIL);
await enterInviteEmail(user, 0, VALID_EMAIL);
await pickRole(user, 0, 'role-viewer');
await user.click(screen.getByTestId('submit-btn'));
@@ -148,8 +148,8 @@ describe('InviteMembers - Edge Cases', () => {
describe('empty submission', () => {
it('does not submit when no rows are touched', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onSuccess = jest.fn();
const user = userEvent.setup();
const onSuccess = jest.fn() as jest.MockedFunction<InviteCallback>;
render(
<InviteMembers
@@ -170,7 +170,7 @@ describe('InviteMembers - Edge Cases', () => {
describe('submitting state', () => {
it('disables submit while submitting', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers
@@ -182,8 +182,7 @@ describe('InviteMembers - Edge Cases', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], VALID_EMAIL);
await enterInviteEmail(user, 0, VALID_EMAIL);
await pickRole(user, 0, 'role-viewer');
const submitBtn = screen.getByTestId('submit-btn');
@@ -197,7 +196,7 @@ describe('InviteMembers - Edge Cases', () => {
describe('whitespace handling', () => {
it('trims email whitespace before submission', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const calls: { email: string }[] = [];
server.use(
@@ -218,8 +217,7 @@ describe('InviteMembers - Edge Cases', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], ' alice@signoz.io ');
await enterInviteEmail(user, 0, ' alice@signoz.io ');
await pickRole(user, 0, 'role-viewer');
await user.click(screen.getByTestId('submit-btn'));

View File

@@ -2,6 +2,7 @@ import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import InviteMembers from '../InviteMembers';
import { InviteMembersProps } from '../types';
import { pickRole } from './roleSelectUtils';
import {
@@ -10,9 +11,12 @@ import {
createRolesHandler,
createSuccessHandler,
createTrackingHandler,
enterInviteEmail,
VALID_EMAIL,
} from './testUtils';
type InviteCallback = Required<InviteMembersProps>['onSuccess'];
describe('InviteMembers - Submission', () => {
beforeEach(() => {
server.use(createRolesHandler(), createSuccessHandler());
@@ -24,7 +28,7 @@ describe('InviteMembers - Submission', () => {
describe('API calls', () => {
it('calls createUser API for each touched row', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const { handler, calls } = createTrackingHandler();
server.use(handler);
@@ -39,8 +43,7 @@ describe('InviteMembers - Submission', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], 'alice@signoz.io');
await enterInviteEmail(user, 0, 'alice@signoz.io');
await pickRole(user, 0, 'role-viewer');
await user.click(screen.getByTestId('submit-btn'));
@@ -55,7 +58,7 @@ describe('InviteMembers - Submission', () => {
});
it('calls createUser API for multiple touched rows', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const { handler, calls } = createTrackingHandler();
server.use(handler);
@@ -70,15 +73,11 @@ describe('InviteMembers - Submission', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], 'alice@signoz.io');
await enterInviteEmail(user, 0, 'alice@signoz.io');
await pickRole(user, 0, 'role-viewer');
await user.type(emailInputs[1], 'bob@signoz.io');
await enterInviteEmail(user, 1, 'bob@signoz.io');
await pickRole(user, 1, 'role-editor');
await user.type(emailInputs[2], 'charlie@signoz.io');
await enterInviteEmail(user, 2, 'charlie@signoz.io');
await pickRole(user, 2, 'role-admin');
await user.click(screen.getByTestId('submit-btn'));
@@ -104,8 +103,8 @@ describe('InviteMembers - Submission', () => {
describe('callbacks', () => {
it('calls onSuccess when all invites succeed', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onSuccess = jest.fn();
const user = userEvent.setup();
const onSuccess = jest.fn() as jest.MockedFunction<InviteCallback>;
render(
<InviteMembers
@@ -118,8 +117,7 @@ describe('InviteMembers - Submission', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], VALID_EMAIL);
await enterInviteEmail(user, 0, VALID_EMAIL);
await pickRole(user, 0, 'role-viewer');
await user.click(screen.getByTestId('submit-btn'));
@@ -130,8 +128,8 @@ describe('InviteMembers - Submission', () => {
});
it('calls onAllFailed when all invites fail', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onAllFailed = jest.fn();
const user = userEvent.setup();
const onAllFailed = jest.fn() as jest.MockedFunction<InviteCallback>;
server.use(createErrorHandler('already_exists', 'User already exists'));
@@ -146,8 +144,7 @@ describe('InviteMembers - Submission', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], VALID_EMAIL);
await enterInviteEmail(user, 0, VALID_EMAIL);
await pickRole(user, 0, 'role-viewer');
await user.click(screen.getByTestId('submit-btn'));
@@ -166,10 +163,10 @@ describe('InviteMembers - Submission', () => {
});
it('calls onPartialSuccess when some invites succeed and some fail', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onPartialSuccess = jest.fn();
const onSuccess = jest.fn();
const onAllFailed = jest.fn();
const user = userEvent.setup();
const onPartialSuccess = jest.fn() as jest.MockedFunction<InviteCallback>;
const onSuccess = jest.fn() as jest.MockedFunction<InviteCallback>;
const onAllFailed = jest.fn() as jest.MockedFunction<InviteCallback>;
const apiCalls: string[] = [];
let callCount = 0;
@@ -208,12 +205,9 @@ describe('InviteMembers - Submission', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], 'alice@signoz.io');
await enterInviteEmail(user, 0, 'alice@signoz.io');
await pickRole(user, 0, 'role-viewer');
await user.type(emailInputs[1], 'bob@signoz.io');
await enterInviteEmail(user, 1, 'bob@signoz.io');
await pickRole(user, 1, 'role-editor');
await user.click(screen.getByTestId('submit-btn'));
@@ -252,7 +246,7 @@ describe('InviteMembers - Submission', () => {
describe('result display', () => {
it('shows success callout when all invites succeed', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers
@@ -264,8 +258,7 @@ describe('InviteMembers - Submission', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], VALID_EMAIL);
await enterInviteEmail(user, 0, VALID_EMAIL);
await pickRole(user, 0, 'role-viewer');
await user.click(screen.getByTestId('submit-btn'));
@@ -276,7 +269,7 @@ describe('InviteMembers - Submission', () => {
});
it('shows error callout with failed emails when API fails', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(createErrorHandler('already_exists', 'User already exists'));
@@ -290,8 +283,7 @@ describe('InviteMembers - Submission', () => {
/>,
);
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], VALID_EMAIL);
await enterInviteEmail(user, 0, VALID_EMAIL);
await pickRole(user, 0, 'role-viewer');
await user.click(screen.getByTestId('submit-btn'));
@@ -305,7 +297,7 @@ describe('InviteMembers - Submission', () => {
describe('footer props', () => {
it('provides correct canSubmit state', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers
@@ -319,14 +311,13 @@ describe('InviteMembers - Submission', () => {
expect(screen.getByTestId('submit-btn')).toBeDisabled();
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], VALID_EMAIL);
await enterInviteEmail(user, 0, VALID_EMAIL);
expect(screen.getByTestId('submit-btn')).not.toBeDisabled();
});
it('provides touchedCount', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<InviteMembers
@@ -339,12 +330,11 @@ describe('InviteMembers - Submission', () => {
expect(screen.getByTestId('touched-count')).toHaveTextContent('0');
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
await user.type(emailInputs[0], 'a@b.com');
await enterInviteEmail(user, 0, 'a@b.com');
expect(screen.getByTestId('touched-count')).toHaveTextContent('1');
await user.type(emailInputs[1], 'c@d.com');
await enterInviteEmail(user, 1, 'c@d.com');
expect(screen.getByTestId('touched-count')).toHaveTextContent('2');
});

View File

@@ -1,5 +1,8 @@
import { RestHandler } from 'msw';
import { rest } from 'mocks-server/server';
import { screen, userEvent } from 'tests/test-utils';
type User = ReturnType<typeof userEvent.setup>;
export const CREATE_USER_ENDPOINT = '*/api/v2/users';
export const LIST_ROLES_ENDPOINT = '*/api/v1/roles';
@@ -52,3 +55,12 @@ export function createTrackingHandler(): {
});
return { handler, calls };
}
export async function enterInviteEmail(
user: User,
rowIndex: number,
email: string,
): Promise<void> {
await user.click(screen.getAllByTestId(/^invite-email-.*-field$/)[rowIndex]);
await user.paste(email);
}

View File

@@ -43,6 +43,7 @@ function MultiSelectFilter({
allowClear
className={cx(styles.select, styles.selectWide)}
placeholder={placeholder}
aria-label={placeholder}
value={value}
options={options}
optionFilterProp="label"
@@ -52,7 +53,10 @@ function MultiSelectFilter({
disabled={disabled}
onClear={onClear}
optionRender={(option): JSX.Element => (
<div className={styles.checkOption}>
<div
className={styles.checkOption}
data-testid={`${testId}-option-${String(option.value)}`}
>
<div className={styles.checkOptionBox}>
<Checkbox
color="primary"

View File

@@ -27,7 +27,7 @@ import styles from './SearchBar.module.scss';
interface Props {
value: string;
grammar: DslGrammar;
// Ids: `${testIdPrefix}`, `-submit`, `-dirty`.
// Ids: `${testIdPrefix}`, `-field` (the editable area), `-submit`, `-dirty`.
testIdPrefix: string;
onChange: (value: string) => void;
onSubmit: () => void;
@@ -71,6 +71,7 @@ function SearchBar({
() => [
dslHighlight,
editorTheme,
EditorView.contentAttributes.of({ 'data-testid': `${testIdPrefix}-field` }),
// Wrap a long query onto the next line instead of scrolling horizontally.
EditorView.lineWrapping,
// Read-only is not enough: these open the list on click and accepting an
@@ -122,7 +123,7 @@ function SearchBar({
]),
),
],
[disabled],
[disabled, testIdPrefix],
);
return (

View File

@@ -1,40 +1,32 @@
import React, { ComponentType, Suspense } from 'react';
import {
render,
screen,
waitForElementToBeRemoved,
} from '@testing-library/react';
import { render, screen } from 'tests/test-utils';
import Loadable from './index';
// Sample component to be loaded lazily
function SampleComponent(): JSX.Element {
return <div>Sample Component</div>;
return <div data-testid="sample-component">Sample Component</div>;
}
const loadSampleComponent = (): Promise<{
default: ComponentType;
}> =>
new Promise<{ default: ComponentType }>((resolve) => {
setTimeout(() => {
resolve({ default: SampleComponent });
}, 500);
});
}> => Promise.resolve({ default: SampleComponent });
describe('Loadable', () => {
it('should render the lazily loaded component', async () => {
const LoadableSampleComponent = Loadable(loadSampleComponent);
const { container } = render(
<Suspense fallback={<div>Loading...</div>}>
render(
<Suspense fallback={<div data-testid="loading">Loading...</div>}>
<LoadableSampleComponent />
</Suspense>,
);
expect(screen.getByText('Loading...')).toBeInTheDocument();
await waitForElementToBeRemoved(() => screen.queryByText('Loading...'));
expect(container.querySelector('div')).toHaveTextContent('Sample Component');
expect(screen.getByTestId('loading')).toBeInTheDocument();
await expect(
screen.findByTestId('sample-component'),
).resolves.toHaveTextContent('Sample Component');
expect(screen.queryByTestId('loading')).not.toBeInTheDocument();
});
it('should call lazy with the provided import path', () => {

View File

@@ -273,7 +273,10 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
)}
{!showOnlyWhereClause && activeBuilder.queryFormulas?.length > 0 && (
<div className="qb-formulas-container">
<div
className="qb-formulas-container"
data-testid="qb-formulas-container"
>
{activeBuilder.queryFormulas.map((formula, index) => {
const query =
activeBuilder.queryData[index] || activeBuilder.queryData[0];
@@ -312,7 +315,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
</div>
{showQueryList && (
<div className="query-names-section">
<div className="query-names-section" data-testid="query-names-section">
{renderedQueries.map((query) => (
<div key={query.queryName} className="query-name">
{query.queryName}

View File

@@ -1,13 +1,12 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { jest } from '@jest/globals';
import { fireEvent, waitFor } from '@testing-library/react';
import { ENVIRONMENT } from 'constants/env';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen, userEvent } from 'tests/test-utils';
import { render, screen, userEvent, within } from 'tests/test-utils';
import {
Having,
IBuilderQuery,
@@ -171,6 +170,25 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
jest.clearAllMocks();
});
const renderQueryV2 = (queriesCount: number): void => {
const [queryA] = (baseQBContext.currentQuery as Query).builder.queryData;
render(
<QueryBuilderV2Provider>
<QueryV2
index={0}
query={queryA}
version="v4"
isAvailableToDisable={false}
isMultiQueryAllowed
queriesCount={queriesCount}
onSignalSourceChange={jest.fn()}
signalSourceChangeEnabled={false}
savePreviousQuery={false}
/>
</QueryBuilderV2Provider>,
);
};
it('renders limit input when dataSource is logs', () => {
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
@@ -184,43 +202,35 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
expect(limitInput).toHaveAttribute('data-testid', 'input-Limit-field');
});
it('Cmd+Enter on an input triggers handleRunQuery via container handler', async () => {
it('Cmd+Enter on the limit input triggers handleRunQuery via container handler', async () => {
const user = userEvent.setup();
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
const limitInput = screen.getByPlaceholderText('Enter limit');
fireEvent.keyDown(limitInput, {
key: 'Enter',
code: 'Enter',
metaKey: true,
});
screen.getByTestId('input-Limit-field').focus();
await user.keyboard('{Meta>}{Enter}{/Meta}');
expect(handleRunQueryMock).toHaveBeenCalled();
expect(handleRunQueryMock).toHaveBeenCalledTimes(1);
});
const legendInput = screen.getByPlaceholderText('Write legend format');
fireEvent.keyDown(legendInput, {
key: 'Enter',
code: 'Enter',
metaKey: true,
});
it('Cmd+Enter on the legend input triggers handleRunQuery via container handler', async () => {
const user = userEvent.setup();
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
expect(handleRunQueryMock).toHaveBeenCalled();
screen.getByPlaceholderText('Write legend format').focus();
await user.keyboard('{Meta>}{Enter}{/Meta}');
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
// Wait for CodeMirror to initialize
await waitFor(() => {
const editor = document.querySelector(CM_EDITOR_SELECTOR);
expect(editor).toBeInTheDocument();
});
expect(handleRunQueryMock).toHaveBeenCalledTimes(1);
});
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
await userEvent.click(editor);
fireEvent.keyDown(editor, {
key: 'Enter',
code: 'Enter',
metaKey: true,
});
it('Cmd+Enter in the where clause editor triggers handleRunQuery via container handler', async () => {
const user = userEvent.setup();
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
expect(handleRunQueryMock).toHaveBeenCalled();
const editorWrapper = await screen.findByTestId('query-where-clause-editor');
within(editorWrapper).getByRole('textbox').focus();
await user.keyboard('{Meta>}{Enter}{/Meta}');
expect(handleRunQueryMock).toHaveBeenCalledTimes(1);
});
it('does not crash when builder.queryFormulas/queryTraceOperator are missing (partial/legacy query)', () => {
@@ -243,22 +253,17 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
).not.toThrow();
// query list still renders from queryData, formulas block is skipped
expect(document.querySelector('.query-names-section')).toBeInTheDocument();
expect(
document.querySelector('.qb-formulas-container'),
).not.toBeInTheDocument();
expect(screen.getByTestId('query-names-section')).toBeInTheDocument();
expect(screen.queryByTestId('qb-formulas-container')).not.toBeInTheDocument();
});
describe('query actions menu', () => {
const openQueryActions = async (): Promise<void> => {
await userEvent.click(screen.getAllByTestId('query-actions')[0]);
};
it('Clone calls cloneQuery with the query', async () => {
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
const user = userEvent.setup();
renderQueryV2(1);
await openQueryActions();
await userEvent.click(
await user.click(screen.getByTestId('query-actions'));
await user.click(
await screen.findByTestId('query-actions-item-clone-query'),
);
@@ -270,9 +275,10 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
});
it('hides Delete when there is a single query', async () => {
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
const user = userEvent.setup();
renderQueryV2(1);
await openQueryActions();
await user.click(screen.getByTestId('query-actions'));
await screen.findByTestId('query-actions-item-clone-query');
expect(
@@ -281,39 +287,26 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
});
it('shows Delete with more than one query and deletes on click', async () => {
const [queryA] = (baseQBContext.currentQuery as Query).builder.queryData;
const user = userEvent.setup();
const handleDeleteQuery = jest.fn();
mockedUseQueryOperations.mockReturnValue({
...mockedUseQueryOperations({} as Parameters<UseQueryOperations>[0]),
handleDeleteQuery,
});
render(
<QueryBuilderV2Provider>
<QueryV2
index={0}
query={queryA}
version="v4"
isAvailableToDisable={false}
isMultiQueryAllowed
queriesCount={2}
onSignalSourceChange={jest.fn()}
signalSourceChangeEnabled={false}
savePreviousQuery={false}
/>
</QueryBuilderV2Provider>,
);
renderQueryV2(2);
await openQueryActions();
await userEvent.click(
await user.click(screen.getByTestId('query-actions'));
await user.click(
await screen.findByTestId('query-actions-item-delete-query'),
);
expect(handleDeleteQuery).toHaveBeenCalledTimes(1);
}, 15000);
});
});
it('fx button is disabled when functions already exist', () => {
it('fx button is disabled when functions already exist', async () => {
const user = userEvent.setup();
const currentQueryBase = baseQBContext.currentQuery as Query;
const supersetQueryBase = baseQBContext.supersetQuery as Query;
@@ -351,17 +344,13 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
const fxButton = document.querySelector('.function-btn') as HTMLButtonElement;
const fxButton = screen.getByTestId('query-functions-fx-btn');
expect(fxButton).toBeInTheDocument();
expect(fxButton).toBeDisabled();
const deleteButton = document.querySelector(
'.query-function-delete-btn',
) as HTMLButtonElement;
const deleteButton = screen.getByTestId('query-function-delete-btn');
expect(deleteButton).toBeInTheDocument();
userEvent.click(deleteButton);
waitFor(() => {
expect(fxButton).not.toBeDisabled();
});
await user.click(deleteButton);
expect(fxButton).not.toBeDisabled();
});
});

View File

@@ -208,6 +208,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
placeholder="Select a query"
searchInputProps={{ placeholder: 'Search queries' }}
items={queryItems}
testId="quick-filters-query-select"
value={String(validQueryIndex)}
onChange={(value): void => {
if (value !== undefined) {
@@ -318,6 +319,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
color="primary"
textPlacement="right"
value={showIP ?? true}
testId="quick-filters-show-ip"
onChange={(checked): void => {
void logEvent('API Monitoring: Show IP addresses clicked', {
showIP: checked,

View File

@@ -52,6 +52,7 @@ function SortableFilter({
<Button
className="remove-filter-btn periscope-btn"
size="small"
data-testid={`quick-filters-remove-${filter.key}`}
onClick={(): void => {
onRemove(filter);
}}
@@ -103,7 +104,7 @@ function AddedFilters({
const allowRemove = addedFilters.length > 1;
return (
<div className="qf-filters added-filters">
<div className="qf-filters added-filters" data-testid="quick-filters-added">
<div className="qf-filters-header">ADDED FILTERS</div>
<div className="qf-added-filters-list">
<OverlayScrollbar>

View File

@@ -102,6 +102,7 @@ function OtherFilters({
<Button
className="add-filter-btn periscope-btn"
size="small"
data-testid={`quick-filters-add-${filter.key}`}
onClick={(): void => handleAddFilter(filter)}
>
Add
@@ -111,7 +112,7 @@ function OtherFilters({
};
return (
<div className="qf-filters other-filters">
<div className="qf-filters other-filters" data-testid="quick-filters-other">
<div className="qf-filters-header">OTHER FILTERS</div>
<div className="qf-other-filters-list">
<OverlayScrollbar>

View File

@@ -84,6 +84,7 @@ function QuickFiltersSettings({
<Button
type="default"
onClick={handleDiscardChanges}
data-testid="quick-filters-settings-discard"
icon={<X size={16} />}
>
Discard
@@ -93,6 +94,7 @@ function QuickFiltersSettings({
onClick={handleSaveChanges}
icon={<Check size={16} />}
loading={isUpdatingCustomFilters}
data-testid="quick-filters-settings-save"
>
Save changes
</Button>

View File

@@ -1,4 +1,7 @@
import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
import {
QuickfiltertypesSourceDTO,
TelemetrytypesSignalDTO,
} from 'api/generated/services/sigNoz.schemas';
import { ENVIRONMENT } from 'constants/env';
import {
ApiMonitoringParams,
@@ -15,10 +18,13 @@ import {
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
import { QueryBuilderContextType } from 'types/common/queryBuilder';
import '@testing-library/jest-dom';
import QuickFilters from '../QuickFilters';
import QuickFiltersSettings from '../QuickFiltersSettings/QuickFiltersSettings';
import { IQuickFiltersConfig, QuickFiltersSource } from '../types';
import { QuickFiltersConfig, QuickFiltersFieldApis } from './constants';
@@ -26,10 +32,25 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: jest.fn(),
}));
jest.mock('container/ApiMonitoring/queryParams');
jest.mock(
'components/OverlayScrollbar/OverlayScrollbar',
() =>
function MockOverlayScrollbar({
children,
}: {
children: React.ReactNode;
}): JSX.Element {
return <div>{children}</div>;
},
);
const handleFilterVisibilityChange = jest.fn();
const redirectWithQueryBuilderData = jest.fn();
const putHandler = jest.fn();
const redirectWithQueryBuilderData = jest.fn() as jest.MockedFunction<
QueryBuilderContextType['redirectWithQueryBuilderData']
>;
const putHandler = jest.fn() as jest.MockedFunction<
(body: { filters: TelemetryFieldKey[] }) => void
>;
const mockSetApiMonitoringParams = jest.fn() as jest.MockedFunction<
(newParams: Partial<ApiMonitoringParams>, replace?: boolean) => void
>;
@@ -44,14 +65,27 @@ const fieldsValuesURL = `${BASE_URL}/api/v1/fields/values`;
const FILTER_OS_DESCRIPTION = 'os.description';
const FILTER_K8S_DEPLOYMENT_NAME = 'k8s.deployment.name';
const ADDED_FILTERS_LABEL = /ADDED FILTERS/i;
const OTHER_FILTERS_LABEL = /OTHER FILTERS/i;
const SAVE_CHANGES_TEXT = 'Save changes';
const DISCARD_TEXT = 'Discard';
const ADDED_FILTERS_TEST_ID = 'quick-filters-added';
const OTHER_FILTERS_TEST_ID = 'quick-filters-other';
const SAVE_TEST_ID = 'quick-filters-settings-save';
const SETTINGS_TEST_ID = 'settings-icon-container';
const REMOVE_OS_DESCRIPTION_TEST_ID =
'quick-filters-remove-resource:os.description:string';
const ADD_K8S_DEPLOYMENT_NAME_TEST_ID =
'quick-filters-add-resource:k8s.deployment.name:string';
const FILTER_SERVICE_NAME = 'Service Name';
const SETTINGS_ICON_TEST_ID = 'settings-icon';
const QUERY_NAME = 'Test Query';
const savedFilters = quickFiltersListResponse.data
.filters as TelemetryFieldKey[];
const smallFiltersListResponse = {
...quickFiltersListResponse,
data: {
...quickFiltersListResponse.data,
filters: savedFilters.slice(0, 2),
},
};
const setupServer = (): void => {
server.use(
rest.get(quickFiltersListURL, (_, res, ctx) =>
@@ -95,6 +129,24 @@ TestQuickFilters.defaultProps = {
config: QuickFiltersConfig,
};
function renderSettings(): void {
render(
<QuickFiltersSettings
savedFiltersSource={QuickfiltertypesSourceDTO.logs}
setIsSettingsOpen={jest.fn()}
customFilters={savedFilters}
refetchCustomFilters={jest.fn()}
/>,
);
}
async function openSettings(
user: ReturnType<typeof userEvent.setup>,
): Promise<void> {
await screen.findByText(FILTER_SERVICE_NAME);
await user.click(screen.getByTestId(SETTINGS_TEST_ID));
}
beforeAll(() => {
server.listen();
});
@@ -102,6 +154,7 @@ beforeAll(() => {
afterEach(() => {
server.resetHandlers();
jest.clearAllMocks();
jest.useRealTimers();
});
afterAll(() => {
@@ -138,8 +191,10 @@ describe('Quick Filters', () => {
});
it('should display and allow selection from query dropdown when multiple queries exist', async () => {
const setLastUsedQuery = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const setLastUsedQuery = jest.fn() as jest.MockedFunction<
QueryBuilderContextType['setLastUsedQuery']
>;
const user = userEvent.setup();
(useQueryBuilder as jest.Mock).mockReturnValue({
currentQuery: {
@@ -169,42 +224,35 @@ describe('Quick Filters', () => {
render(<TestQuickFilters />);
// The dropdown trigger should show the first query name
const trigger = screen.getByText('Query A');
expect(trigger).toBeInTheDocument();
const trigger = screen.getByTestId('quick-filters-query-select');
expect(trigger).toHaveTextContent('Query A');
// Click to open the dropdown
await user.click(trigger);
// All query options should be visible
await waitFor(() => {
expect(screen.getByRole('option', { name: 'Query A' })).toBeInTheDocument();
expect(screen.getByRole('option', { name: 'Query B' })).toBeInTheDocument();
expect(screen.getByRole('option', { name: 'Query C' })).toBeInTheDocument();
});
await expect(
screen.findByTestId('quick-filters-query-select-item-0'),
).resolves.toHaveTextContent('Query A');
expect(
screen.getByTestId('quick-filters-query-select-item-1'),
).toHaveTextContent('Query B');
expect(
screen.getByTestId('quick-filters-query-select-item-2'),
).toHaveTextContent('Query C');
// Select Query B with the keyboard: jsdom cannot deliver the pointer
// click Base UI expects, so filter through the search row and pick with
// Enter instead
await waitFor(() => {
// jsdom cannot deliver the pointer click Base UI expects on an option,
// so pick Query B with the arrow keys and Enter
await waitFor(() =>
expect(
screen.getByRole('combobox', { name: 'Search queries' }),
).toHaveFocus();
});
await user.keyboard('Query B');
await waitFor(() => {
expect(
screen.queryByRole('option', { name: 'Query A' }),
).not.toBeInTheDocument();
});
screen.getByTestId('quick-filters-query-select-search'),
).toHaveFocus(),
);
await user.keyboard('{ArrowDown}{Enter}');
// Verify setLastUsedQuery was called with index 1
await waitFor(() => {
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
});
// filtering and picking through the search row takes Base UI past the
// default 5s under jsdom
}, 20000);
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
});
it('should not display query dropdown in ListView', () => {
(useQueryBuilder as jest.Mock).mockReturnValue({
@@ -244,12 +292,13 @@ describe('Quick Filters', () => {
expect(screen.getByText(QUERY_NAME)).toBeInTheDocument();
// No dropdown should be present
const queryText = screen.getByText(QUERY_NAME);
expect(queryText.closest('[role="combobox"]')).not.toBeInTheDocument();
expect(
screen.queryByTestId('quick-filters-query-select'),
).not.toBeInTheDocument();
});
it('should add filter data to query when checkbox is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(<TestQuickFilters />);
@@ -281,33 +330,27 @@ describe('Quick Filters', () => {
});
});
it('toggles Show IP addresses and updates API Monitoring params', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.API_MONITORING} />,
);
// Switch should be rendered and initially checked
await expect(
screen.findByText('Show IP addresses'),
).resolves.toBeInTheDocument();
const toggle = screen.getByRole('switch');
const toggle = await screen.findByTestId('quick-filters-show-ip');
expect(screen.getByText('Show IP addresses')).toBeInTheDocument();
expect(toggle).toHaveAttribute('aria-checked', 'true');
await user.click(toggle);
await waitFor(() => {
expect(mockSetApiMonitoringParams).toHaveBeenCalledWith(
expect.objectContaining({ showIP: false }),
);
});
expect(mockSetApiMonitoringParams).toHaveBeenCalledWith(
expect.objectContaining({ showIP: false }),
);
});
});
describe('Quick Filters with custom filters', () => {
it('loads the custom filters correctly', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
@@ -318,28 +361,32 @@ describe('Quick Filters with custom filters', () => {
await screen.findByText(FILTER_SERVICE_NAME);
const allByText = await screen.findAllByText('otel-demo');
expect(allByText).toHaveLength(2);
});
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
const settingsButton = icon.closest('button') ?? icon;
await user.click(settingsButton);
await expect(
screen.findByText('Edit quick filters'),
).resolves.toBeInTheDocument();
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
expect(addedSection).toContainElement(
await screen.findByText(FILTER_OS_DESCRIPTION),
it('opens the settings with the saved filters added and the rest under other filters', async () => {
const user = userEvent.setup();
server.use(
rest.get(quickFiltersListURL, (_, res, ctx) =>
res(ctx.status(200), ctx.json(smallFiltersListResponse)),
),
);
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
expect(otherSection).toContainElement(
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
await openSettings(user);
expect(screen.getByText('Edit quick filters')).toBeInTheDocument();
expect(screen.getByTestId(ADDED_FILTERS_TEST_ID)).toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
expect(screen.getByTestId(OTHER_FILTERS_TEST_ID)).toContainElement(
await screen.findByText(FILTER_K8S_DEPLOYMENT_NAME),
);
});
it('keeps same-name fields with different context as distinct entries', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.get(quickFiltersSuggestionsURL, (_req, res, ctx) =>
res(
@@ -370,153 +417,86 @@ describe('Quick Filters with custom filters', () => {
),
);
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
await screen.findByText(FILTER_SERVICE_NAME);
renderSettings();
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
const settingsButton = icon.closest('button') ?? icon;
await user.click(settingsButton);
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
const otherSection = screen.getByTestId(OTHER_FILTERS_TEST_ID);
// Both `level` variants are shown despite sharing a name.
await waitFor(() =>
expect(within(otherSection).getAllByText('level')).toHaveLength(2),
const addButton = await screen.findByTestId(
'quick-filters-add-attribute:level:string',
);
expect(within(otherSection).getAllByText('level')).toHaveLength(2);
// Adding one variant removes only that one; the other stays.
const firstLevel = within(otherSection).getAllByText('level')[0];
const addButton = firstLevel.parentElement?.querySelector('button');
await user.click(addButton as HTMLButtonElement);
await user.click(addButton);
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
await waitFor(() => {
expect(within(addedSection).getAllByText('level')).toHaveLength(1);
expect(within(otherSection).getAllByText('level')).toHaveLength(1);
});
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
expect(within(addedSection).getAllByText('level')).toHaveLength(1);
expect(within(otherSection).getAllByText('level')).toHaveLength(1);
expect(
screen.getByTestId('quick-filters-add-span:level:string'),
).toBeInTheDocument();
});
it('adds a filter from OTHER FILTERS to ADDED FILTERS when clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
renderSettings();
await user.click(await screen.findByTestId(ADD_K8S_DEPLOYMENT_NAME_TEST_ID));
expect(screen.getByTestId(ADDED_FILTERS_TEST_ID)).toHaveTextContent(
FILTER_K8S_DEPLOYMENT_NAME,
);
await screen.findByText(FILTER_SERVICE_NAME);
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
const settingsButton = icon.closest('button') ?? icon;
await user.click(settingsButton);
const otherFilterItem = await screen.findByText(FILTER_K8S_DEPLOYMENT_NAME);
const addButton = otherFilterItem.parentElement?.querySelector('button');
expect(addButton).not.toBeNull();
await user.click(addButton as HTMLButtonElement);
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
await waitFor(() => {
expect(addedSection).toHaveTextContent(FILTER_K8S_DEPLOYMENT_NAME);
});
});
it('removes a filter from ADDED FILTERS and moves it to OTHER FILTERS', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
renderSettings();
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
const otherSection = screen.getByTestId(OTHER_FILTERS_TEST_ID);
await screen.findByTestId(ADD_K8S_DEPLOYMENT_NAME_TEST_ID);
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
expect(addedSection).not.toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
await screen.findByText(FILTER_SERVICE_NAME);
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
const settingsButton = icon.closest('button') ?? icon;
await user.click(settingsButton);
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
const removeBtn = target.parentElement?.querySelector('button');
expect(removeBtn).not.toBeNull();
await user.click(removeBtn as HTMLButtonElement);
await waitFor(() => {
expect(addedSection).not.toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
});
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
expect(otherSection).toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
});
it('restores original filter state on Discard', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
renderSettings();
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
const otherSection = screen.getByTestId(OTHER_FILTERS_TEST_ID);
await screen.findByTestId(ADD_K8S_DEPLOYMENT_NAME_TEST_ID);
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
expect(otherSection).toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
await screen.findByText(FILTER_SERVICE_NAME);
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
const settingsButton = icon.closest('button') ?? icon;
await user.click(settingsButton);
await user.click(screen.getByTestId('quick-filters-settings-discard'));
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
const removeBtn = target.parentElement?.querySelector('button');
expect(removeBtn).not.toBeNull();
await user.click(removeBtn as HTMLButtonElement);
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
await waitFor(() => {
expect(addedSection).not.toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
expect(otherSection).toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
});
const discardBtn = screen
.getByText(DISCARD_TEXT)
.closest('button') as HTMLButtonElement;
expect(discardBtn).not.toBeNull();
await user.click(discardBtn);
await waitFor(() => {
expect(addedSection).toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
expect(otherSection).not.toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
});
expect(addedSection).toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
expect(otherSection).not.toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
});
it('saves the updated filters by calling PUT with correct payload', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
await screen.findByText(FILTER_SERVICE_NAME);
renderSettings();
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
const settingsButton = icon.closest('button') ?? icon;
await user.click(settingsButton);
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
const removeBtn = target.parentElement?.querySelector('button');
expect(removeBtn).not.toBeNull();
await user.click(removeBtn as HTMLButtonElement);
const saveBtn = screen
.getByText(SAVE_CHANGES_TEXT)
.closest('button') as HTMLButtonElement;
expect(saveBtn).not.toBeNull();
await user.click(saveBtn);
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
await user.click(screen.getByTestId(SAVE_TEST_ID));
await waitFor(() => {
expect(putHandler).toHaveBeenCalled();
@@ -530,24 +510,37 @@ describe('Quick Filters with custom filters', () => {
});
it('should render duration slider for duration_nono filter', async () => {
server.use(
rest.get(quickFiltersListURL, (_, res, ctx) =>
res(
ctx.status(200),
ctx.json({
...quickFiltersListResponse,
data: {
...quickFiltersListResponse.data,
filters: savedFilters.filter(({ name }) => name === 'duration_nano'),
},
}),
),
),
);
// Use fake timers only in this test (for debounce), and wire them to userEvent
jest.useFakeTimers();
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
pointerEventsCheck: 0,
});
const { getByTestId } = render(
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
await screen.findByText(FILTER_SERVICE_NAME);
await screen.findByTestId('collapse-duration');
expect(screen.getByText('Duration')).toBeInTheDocument();
// Open the duration section (use role if it’s a button/collapse)
await user.click(screen.getByText('Duration'));
const minDuration = getByTestId('min-input') as HTMLInputElement;
const maxDuration = getByTestId('max-input') as HTMLInputElement;
const minDuration = screen.getByTestId('min-input') as HTMLInputElement;
const maxDuration = screen.getByTestId('max-input') as HTMLInputElement;
expect(minDuration).toHaveValue(null);
expect(minDuration).toHaveProperty('placeholder', '0');
@@ -649,7 +642,7 @@ describe('Quick Filters refetch behavior', () => {
server.use(
rest.get(quickFiltersListURL, (_req, res, ctx) => {
getCalls += 1;
return res(ctx.status(200), ctx.json(quickFiltersListResponse));
return res(ctx.status(200), ctx.json(smallFiltersListResponse));
}),
rest.put(saveQuickFiltersURL, async (req, res, ctx) => {
putHandler(await req.json());
@@ -657,26 +650,14 @@ describe('Quick Filters refetch behavior', () => {
}),
);
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
await expect(
screen.findByText(FILTER_SERVICE_NAME),
).resolves.toBeInTheDocument();
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
const settingsButton = icon.closest('button') ?? icon;
await user.click(settingsButton);
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
const removeBtn = target.parentElement?.querySelector(
'button',
) as HTMLButtonElement;
await user.click(removeBtn);
await user.click(screen.getByText(SAVE_CHANGES_TEXT));
await openSettings(user);
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
await user.click(screen.getByTestId(SAVE_TEST_ID));
await waitFor(() => expect(putHandler).toHaveBeenCalled());
await waitFor(() => expect(getCalls).toBeGreaterThanOrEqual(2));
@@ -684,11 +665,11 @@ describe('Quick Filters refetch behavior', () => {
it('renders updated filters after refetch post-save', async () => {
const updatedResponse = {
...quickFiltersListResponse,
...smallFiltersListResponse,
data: {
...quickFiltersListResponse.data,
...smallFiltersListResponse.data,
filters: [
...(quickFiltersListResponse.data.filters ?? []),
...smallFiltersListResponse.data.filters,
{
name: 'new.custom.filter',
fieldDataType: 'string',
@@ -704,38 +685,26 @@ describe('Quick Filters refetch behavior', () => {
getCount += 1;
return getCount >= 2
? res(ctx.status(200), ctx.json(updatedResponse))
: res(ctx.status(200), ctx.json(quickFiltersListResponse));
: res(ctx.status(200), ctx.json(smallFiltersListResponse));
}),
rest.put(saveQuickFiltersURL, async (_req, res, ctx) =>
res(ctx.status(200), ctx.json({})),
),
);
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
await expect(
screen.findByText(FILTER_SERVICE_NAME),
).resolves.toBeInTheDocument();
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
const settingsButton = icon.closest('button') ?? icon;
await user.click(settingsButton);
await openSettings(user);
// Make a minimal change so Save button appears
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
const removeBtn = target.parentElement?.querySelector(
'button',
) as HTMLButtonElement;
await user.click(removeBtn);
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
await user.click(screen.getByTestId(SAVE_TEST_ID));
await user.click(screen.getByText(SAVE_CHANGES_TEXT));
await waitFor(() => {
expect(screen.getByText('New Custom Filter')).toBeInTheDocument();
});
await expect(
screen.findByText('New Custom Filter'),
).resolves.toBeInTheDocument();
});
it('shows empty state when GET fails', async () => {

View File

@@ -1,3 +1,4 @@
import { lazy } from 'react';
import { navigate } from 'lib/router/navigation';
import { fireEvent, render, screen } from 'tests/test-utils';
@@ -98,4 +99,28 @@ describe('RouteTab component', () => {
fireEvent.click(screen.getByRole('tab', { name: 'Tab2' }));
expect(onChangeHandler).toHaveBeenCalled();
});
it('keeps the tab bar while a lazy tab loads', async () => {
let resolveTab: (module: { default: () => JSX.Element }) => void = () => {};
const LazyTab = lazy(
() =>
new Promise<{ default: () => JSX.Element }>((resolve) => {
resolveTab = resolve;
}),
);
render(
<RouteTab
routes={[{ ...testRoutes[0], Component: LazyTab }, testRoutes[1]]}
activeKey="Tab1"
/>,
);
expect(screen.getByRole('tab', { name: 'Tab1' })).toBeInTheDocument();
expect(screen.getByTestId('spinner')).toHaveStyleRule('height', '100%');
resolveTab({ default: DummyComponent1 });
await expect(
screen.findByText('Dummy Component 1'),
).resolves.toBeInTheDocument();
});
});

View File

@@ -1,7 +1,9 @@
import { Suspense } from 'react';
import { Tabs, TabsProps } from 'antd';
import cx from 'classnames';
import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
import Spinner from 'components/Spinner';
import { buildRoutePath } from 'lib/router/buildRoutePath';
import { matchRoute } from 'lib/router/matchRoute';
import { navigate } from 'lib/router/navigation';
@@ -58,7 +60,11 @@ function RouteTab({
tabKey: route,
children: (
<OverlayScrollbar>
<Component />
<Suspense
fallback={<Spinner size="large" tip="Loading..." height="100%" />}
>
<Component />
</Suspense>
</OverlayScrollbar>
),
}));

View File

@@ -44,6 +44,7 @@ function SaveErrorItem({
variant="link"
color="secondary"
aria-label="Retry"
testId="sa-error-retry-btn"
onClick={async (e): Promise<void> => {
e.stopPropagation();
setIsRetrying(true);

View File

@@ -176,8 +176,13 @@ describe('KeysTab', () => {
const revokeBtns = screen.getAllByTestId('keys-tab-revoke-btn');
await user.click(revokeBtns[0]);
const confirmBtn = await screen.findByRole('button', { name: /Revoke Key/i });
await user.click(confirmBtn);
await waitFor(() =>
expect(screen.getByTestId('revoke-key-confirm-btn')).not.toHaveAttribute(
'aria-disabled',
'true',
),
);
await user.click(screen.getByTestId('revoke-key-confirm-btn'));
await waitFor(() => {
expect(mockToast.success).toHaveBeenCalledWith('Key revoked successfully');

View File

@@ -1,3 +1,4 @@
import type { ServiceAccountRow } from 'container/ServiceAccountsSettings/utils';
import {
listRolesSuccessResponse,
managedRoles,
@@ -15,22 +16,25 @@ import {
buildSADeletePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/service-account.permissions';
import KeysTab from '../KeysTab';
import OverviewTab from '../OverviewTab';
import ServiceAccountDrawer from '../ServiceAccountDrawer';
const ROLES_ENDPOINT = '*/api/v1/roles';
const SA_KEYS_ENDPOINT = '*/api/v1/service_accounts/:id/keys';
const SA_ENDPOINT = '*/api/v1/service_accounts/sa-1';
const SA_DELETE_ENDPOINT = '*/api/v1/service_accounts/sa-1';
const SA_ROLES_ENDPOINT = '*/api/v1/service_account_roles';
const SA_ROLE_DELETE_ENDPOINT = '*/api/v1/service_account_roles/:id';
const activeAccountResponse = {
const account: ServiceAccountRow = {
id: 'sa-1',
name: 'CI Bot',
email: 'ci-bot@signoz.io',
status: 'ACTIVE',
createdAt: '2026-01-01T00:00:00Z',
updatedAt: '2026-01-02T00:00:00Z',
};
const activeAccountResponse = {
...account,
serviceAccountRoles: [
{
id: 'sar-admin-1',
@@ -41,93 +45,88 @@ const activeAccountResponse = {
],
};
function renderDrawer(
searchParams: Record<string, string> = { account: 'sa-1' },
): ReturnType<typeof render> {
function renderOverviewTab(): ReturnType<typeof render> {
return render(
<NuqsTestingAdapter searchParams={searchParams} hasMemory>
<ServiceAccountDrawer onSuccess={jest.fn()} />
</NuqsTestingAdapter>,
);
}
function setupBaseHandlers(): void {
server.use(
rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
),
rest.get(SA_KEYS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: [] })),
),
rest.get(SA_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: activeAccountResponse })),
),
rest.put(SA_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
),
rest.delete(SA_DELETE_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
),
rest.post(SA_ROLES_ENDPOINT, (_, res, ctx) =>
res(
ctx.status(201),
ctx.json({ status: 'success', data: { id: 'sar-new' } }),
),
),
rest.delete(SA_ROLE_DELETE_ENDPOINT, (_, res, ctx) => res(ctx.status(204))),
<OverviewTab
account={account}
localName="CI Bot"
onNameChange={jest.fn()}
localRoles={[]}
onRolesChange={jest.fn()}
isDisabled={false}
availableRoles={[]}
/>,
);
}
describe('ServiceAccountDrawer — permissions', () => {
beforeEach(() => {
jest.clearAllMocks();
setupBaseHandlers();
});
afterEach(() => {
server.resetHandlers();
});
it('shows PermissionDeniedCallout inside drawer when read permission is denied', async () => {
it('shows PermissionDeniedCallout in the Overview tab when read permission is denied', async () => {
server.use(setupAuthzDenyAll());
renderDrawer();
renderOverviewTab();
await waitFor(() => {
expect(screen.getByText(/read:serviceaccount/)).toBeInTheDocument();
});
await expect(
screen.findByTestId('permission-denied-callout'),
).resolves.toHaveTextContent('read:serviceaccount:sa-1');
});
it('shows drawer content when read permission is granted', async () => {
it('shows Overview tab content when read permission is granted', async () => {
server.use(setupAuthzAdmin());
renderDrawer();
renderOverviewTab();
await screen.findByDisplayValue('CI Bot');
expect(screen.queryByText(/serviceaccount:read/)).not.toBeInTheDocument();
expect(
screen.queryByTestId('permission-denied-callout'),
).not.toBeInTheDocument();
});
it('shows PermissionDeniedCallout in Keys tab when list-keys permission is denied', async () => {
server.use(setupAuthzDeny(APIKeyListPermission));
renderDrawer({ account: 'sa-1', tab: 'keys' });
render(
<KeysTab
keys={[]}
isLoading={false}
accountId="sa-1"
currentPage={1}
pageSize={15}
onPageChange={jest.fn()}
/>,
);
await waitFor(() => {
expect(screen.getByText(/list:factor-api-key/)).toBeInTheDocument();
});
await expect(
screen.findByTestId('permission-denied-callout'),
).resolves.toHaveTextContent('list:factor-api-key:*');
});
it('disables Delete button when delete permission is denied', async () => {
server.use(setupAuthzDeny(buildSADeletePermission('sa-1')));
renderDrawer();
await screen.findByDisplayValue('CI Bot');
const deleteBtn = screen.getByRole('button', {
name: /Delete Service Account/i,
});
await waitFor(() =>
expect(deleteBtn).toHaveAttribute('aria-disabled', 'true'),
server.use(
rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
),
rest.get(SA_KEYS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: [] })),
),
rest.get(SA_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: activeAccountResponse })),
),
setupAuthzDeny(buildSADeletePermission('sa-1')),
);
render(
<NuqsTestingAdapter searchParams={{ account: 'sa-1' }} hasMemory>
<ServiceAccountDrawer onSuccess={jest.fn()} />
</NuqsTestingAdapter>,
);
const deleteBtn = await screen.findByTestId('sa-delete-btn');
await waitFor(() =>
expect(deleteBtn).toHaveAttribute(
'data-denied-permissions',
buildSADeletePermission('sa-1'),
),
);
expect(deleteBtn).toHaveAttribute('aria-disabled', 'true');
});
});

View File

@@ -4,15 +4,11 @@ import {
} from 'mocks-server/__mockdata__/roles';
import { rest, server } from 'mocks-server/server';
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
import ServiceAccountDrawer from '../ServiceAccountDrawer';
// Picking a role in the Combobox inside the Drawer takes seconds in jsdom, and
// the 429 retry waits another second on top.
jest.setTimeout(20000);
const ROLES_ENDPOINT = '*/api/v1/roles';
const SA_KEYS_ENDPOINT = '*/api/v1/service_accounts/:id/keys';
const SA_ENDPOINT = '*/api/v1/service_accounts/sa-1';
@@ -97,7 +93,7 @@ describe('ServiceAccountDrawer', () => {
screen.findByDisplayValue('CI Bot'),
).resolves.toBeInTheDocument();
expect(screen.getByText('ci-bot@signoz.io')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Save Changes/i })).toHaveAttribute(
expect(screen.getByTestId('sa-save-btn')).toHaveAttribute(
'aria-disabled',
'true',
);
@@ -106,7 +102,7 @@ describe('ServiceAccountDrawer', () => {
it('editing name enables Save; clicking Save sends correct payload and calls onSuccess', async () => {
const onSuccess = jest.fn();
const updateSpy = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.put(SA_ENDPOINT, async (req, res, ctx) => {
@@ -125,7 +121,7 @@ describe('ServiceAccountDrawer', () => {
await user.clear(nameInput);
await user.type(nameInput, 'CI Bot Updated');
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
const saveBtn = screen.getByTestId('sa-save-btn');
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
@@ -144,7 +140,7 @@ describe('ServiceAccountDrawer', () => {
it('adding a role fires POST for the new role and no DELETE for existing roles', async () => {
const roleSpy = jest.fn();
const deleteSpy = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.post(SA_ROLES_ENDPOINT, async (req, res, ctx) => {
@@ -171,7 +167,7 @@ describe('ServiceAccountDrawer', () => {
`${managedRoles[2].name}{Enter}`,
);
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
const saveBtn = screen.getByTestId('sa-save-btn');
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
@@ -191,7 +187,7 @@ describe('ServiceAccountDrawer', () => {
it('removing a role fires DELETE for the removed role and no POST', async () => {
const roleSpy = jest.fn();
const deleteSpy = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.post(SA_ROLES_ENDPOINT, async (req, res, ctx) => {
@@ -218,7 +214,7 @@ describe('ServiceAccountDrawer', () => {
),
);
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
const saveBtn = screen.getByTestId('sa-save-btn');
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
@@ -232,7 +228,7 @@ describe('ServiceAccountDrawer', () => {
it('"Delete Service Account" opens confirm dialog; confirming sends delete request', async () => {
const deleteSpy = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.delete(SA_DELETE_ENDPOINT, (_, res, ctx) => {
@@ -245,9 +241,7 @@ describe('ServiceAccountDrawer', () => {
await screen.findByDisplayValue('CI Bot');
await user.click(
screen.getByRole('button', { name: /Delete Service Account/i }),
);
await user.click(screen.getByTestId('sa-delete-btn'));
await screen.findByTestId('delete-service-account-modal');
expect(
@@ -279,23 +273,19 @@ describe('ServiceAccountDrawer', () => {
await screen.findByText('CI Bot');
expect(
screen.queryByRole('button', { name: /Save Changes/i }),
).not.toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /Delete Service Account/i }),
).not.toBeInTheDocument();
expect(screen.queryByTestId('sa-save-btn')).not.toBeInTheDocument();
expect(screen.queryByTestId('sa-delete-btn')).not.toBeInTheDocument();
expect(screen.queryByDisplayValue('CI Bot')).not.toBeInTheDocument();
});
it('switching to Keys tab shows "No keys" empty state', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
renderDrawer();
await screen.findByDisplayValue('CI Bot');
await user.click(screen.getByRole('button', { name: /Keys/i }));
await user.click(screen.getByTestId('sa-tab-button-keys'));
await expect(screen.findByText(/No keys/i)).resolves.toBeInTheDocument();
});
@@ -348,11 +338,12 @@ describe('ServiceAccountDrawer – save-error UX', () => {
});
afterEach(() => {
jest.useRealTimers();
server.resetHandlers();
});
it('name update failure shows SaveErrorItem with "Name update" context', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.put(SA_ENDPOINT, (_, res, ctx) =>
@@ -374,7 +365,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
await user.clear(nameInput);
await user.type(nameInput, 'New Name');
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
const saveBtn = screen.getByTestId('sa-save-btn');
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
@@ -388,7 +379,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
});
it('role add failure shows SaveErrorItem with the role name context', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.post(SA_ROLES_ENDPOINT, (_, res, ctx) =>
@@ -415,7 +406,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
`${managedRoles[2].name}{Enter}`,
);
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
const saveBtn = screen.getByTestId('sa-save-btn');
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
@@ -429,7 +420,11 @@ describe('ServiceAccountDrawer – save-error UX', () => {
});
it('role add retries on 429 then succeeds without showing an error', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
jest.useFakeTimers();
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const onSuccess = jest.fn();
let roleAddCallCount = 0;
// First call → 429, second call → 201
@@ -446,7 +441,11 @@ describe('ServiceAccountDrawer – save-error UX', () => {
}),
);
renderDrawer();
render(
<NuqsTestingAdapter searchParams={{ account: 'sa-1' }} hasMemory>
<ServiceAccountDrawer onSuccess={onSuccess} />
</NuqsTestingAdapter>,
);
await screen.findByDisplayValue('CI Bot');
@@ -456,24 +455,24 @@ describe('ServiceAccountDrawer – save-error UX', () => {
`${managedRoles[2].name}{Enter}`,
);
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
const saveBtn = screen.getByTestId('sa-save-btn');
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
await user.click(saveBtn);
// Retried after 429 — at least 2 calls, no error shown
await waitFor(
() => {
expect(roleAddCallCount).toBeGreaterThanOrEqual(2);
},
{ timeout: 5000 },
await waitFor(() => expect(roleAddCallCount).toBe(1));
await act(() => jest.advanceTimersByTimeAsync(1000));
await waitFor(() =>
expect(onSuccess).toHaveBeenCalledWith({ closeDrawer: false }),
);
expect(roleAddCallCount).toBe(2);
expect(screen.queryByText(/role assign failed/i)).not.toBeInTheDocument();
expect(screen.queryByTestId('sa-error-retry-btn')).not.toBeInTheDocument();
});
it('clicking Retry on a name-update error re-triggers the request; on success the error item is removed', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
// First: PUT always fails so the error appears
server.use(
@@ -496,7 +495,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
await user.clear(nameInput);
await user.type(nameInput, 'Retry Test');
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
const saveBtn = screen.getByTestId('sa-save-btn');
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
@@ -512,7 +511,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
),
);
const retryBtn = screen.getByRole('button', { name: /Retry/i });
const retryBtn = screen.getByTestId('sa-error-retry-btn');
await user.click(retryBtn);
// Error item should be removed after successful retry

View File

@@ -6,7 +6,7 @@ import { SpinerStyle } from './styles';
function Spinner({ size, tip, height, style }: SpinnerProps): JSX.Element {
return (
<SpinerStyle height={height} style={style}>
<SpinerStyle height={height} style={style} data-testid="spinner">
<Spin
spinning
size={size}

View File

@@ -1,5 +1,4 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { render, screen, userEvent } from 'tests/test-utils';
import TagKeyValueInput from './TagKeyValueInput';

View File

@@ -152,6 +152,7 @@ function TanStackHeaderRow<TData>({
style={headerCellStyle}
data-dark-mode={isDarkMode}
data-single-column={hasSingleColumn || undefined}
data-testid={`tanstack-header-${columnId}`}
>
<span className={headerContentClassName}>
{isDragColumn ? (

View File

@@ -1,4 +1,4 @@
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { PageTypeDTO } from '@signozhq/noz-client';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';

View File

@@ -8,7 +8,7 @@
--input-focus-background: transparent;
--input-focus-outline-width: 0;
--input-box-shadow: none;
--input-font-size: var(--periscope-font-size-base);
--input-font-size: var(--label-base-400-font-size);
--input-line-height: 20px;
--input-placeholder-color: color-mix(
in srgb,

View File

@@ -12,8 +12,8 @@
}
.heading {
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;
@@ -34,9 +34,9 @@
--button-height: auto;
--button-padding: var(--spacing-4) var(--spacing-6);
--button-border-radius: var(--radius-3);
--button-font-size: var(--periscope-font-size-base);
--button-font-size: var(--label-base-400-font-size);
--button-size-line-height: var(--line-height-20);
--button-font-weight: var(--font-weight-normal);
--button-font-weight: var(--label-base-400-font-weight);
--button-variant-outlined-background-color: var(--l3-background-60);
--button-variant-outlined-border: none;
--button-variant-outlined-color: var(--l2-foreground);

View File

@@ -16,11 +16,11 @@ import {
import { v4 as uuidv4 } from 'uuid';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { MessageActionDTO } from '@signozhq/noz-client';
import {
ApplyFilterSignalDTO,
MessageActionKindDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import {
restoreExecution,
revertExecution,

View File

@@ -1,7 +1,4 @@
import {
MessageActionDTO,
MessageActionKindDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { MessageActionDTO, MessageActionKindDTO } from '@signozhq/noz-client';
import logEvent from 'api/common/logEvent';
import { getCurrentLocation, navigate } from 'lib/router/navigation';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';

View File

@@ -1,9 +1,9 @@
import { undoExecution } from 'api/ai-assistant/chat';
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { MessageActionDTO } from '@signozhq/noz-client';
import {
ApplyFilterSignalDTO,
MessageActionKindDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';

View File

@@ -1,4 +1,4 @@
import { ApplyFilterSignalDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { ApplyFilterSignalDTO } from '@signozhq/noz-client';
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { PANEL_TYPES } from 'constants/queryBuilder';

View File

@@ -2,7 +2,7 @@ import {
ApplyFilterSignalDTO,
MessageActionKindDTO,
SavedViewEntityDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import {
getSavedView,
listSavedViews,

View File

@@ -1,7 +1,7 @@
import {
type MessageActionDTO,
MessageActionKindDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import {
isSavedViewOpenAction,

View File

@@ -1,7 +1,7 @@
import {
ApplyFilterSignalDTO,
type MessageActionDTOQuery,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { PANEL_TYPES } from 'constants/queryBuilder';

View File

@@ -1,4 +1,4 @@
import type { MessageActionDTOQuery } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { MessageActionDTOQuery } from '@signozhq/noz-client';
import { normalizeTimeToMs } from 'utils/timeUtils';
export interface ActionTimeRange {

View File

@@ -1,8 +1,5 @@
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
SavedViewEntityDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { MessageActionDTO } from '@signozhq/noz-client';
import { ApplyFilterSignalDTO, SavedViewEntityDTO } from '@signozhq/noz-client';
import { DataSource } from 'types/common/queryBuilder';
import { ResourceType } from './resourceRoute';

View File

@@ -31,8 +31,8 @@
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
line-height: 18px;
letter-spacing: -0.005em;
}
@@ -54,7 +54,7 @@
.soloThought {
margin: 0;
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);
@@ -64,8 +64,8 @@
// While Noz works, the row names the step it's on.
.live .activitySummary {
font-size: var(--periscope-font-size-base);
font-weight: var(--font-weight-normal);
font-size: var(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
line-height: var(--line-height-20);
@include shimmer-text(var(--l3-foreground), var(--l1-foreground));
}

View File

@@ -59,7 +59,7 @@
border: none;
background: none;
font: inherit;
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -90,7 +90,7 @@ button.title {
}
.detail {
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);

View File

@@ -42,7 +42,7 @@
}
.headerLabel {
font-size: var(--font-size-sm);
font-size: var(--paragraph-base-400-font-size);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -61,7 +61,7 @@
.summary {
margin: 0;
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
line-height: var(--line-height-20);
color: var(--l2-foreground);
}

View File

@@ -8,7 +8,7 @@ import { Tooltip } from '@signozhq/ui/tooltip';
import type {
ApprovalEventDTO,
ApprovalEventDTODiff,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import {
Check,
Columns2,

View File

@@ -134,8 +134,8 @@
--button-padding: 7px #{$padding-inline};
--button-border-radius: 0;
--button-justify-content: flex-start;
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--button-font-size: var(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--button-variant-ghost-color: var(--l2-foreground);
--button-variant-ghost-hover-color: var(--l1-foreground);
--button-variant-ghost-hover-background-color: var(--l3-background);
@@ -180,8 +180,8 @@
height: 44px;
padding: 0 var(--spacing-7);
border-bottom: 1px solid var(--l2-border);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
font-size: var(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;

View File

@@ -8,8 +8,8 @@
border-radius: var(--radius-2);
background: var(--l3-background-60);
color: var(--l2-foreground);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-medium);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
line-height: 15px;
transition:
background-color 0.12s,

View File

@@ -40,7 +40,7 @@
}
.headerLabel {
font-size: var(--font-size-sm);
font-size: var(--paragraph-base-400-font-size);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -48,7 +48,7 @@
.message {
margin: 0;
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
line-height: var(--line-height-20);
color: var(--l2-foreground);
}

View File

@@ -6,11 +6,11 @@ import { Input } from '@signozhq/ui/input';
import { Select } from '@signozhq/ui/select';
import type { SelectItemType } from '@signozhq/ui/select';
import logEvent from 'api/common/logEvent';
import { ClarificationFieldTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { ClarificationFieldTypeDTO } from '@signozhq/noz-client';
import type {
ClarificationEventDTO,
ClarificationFieldEventDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import { CircleHelp, Send, X } from '@signozhq/icons';
import { AIAssistantEvents } from '../../events';

View File

@@ -53,7 +53,7 @@
}
.title {
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
line-height: 20px;
letter-spacing: -0.005em;
color: var(--text-vanilla-400);
@@ -73,7 +73,7 @@
// Wide enough to hold the action buttons that replace it.
min-width: 16px;
text-align: right;
font-size: var(--periscope-font-size-small);
font-size: var(--paragraph-small-400-font-size);
line-height: 18px;
color: var(--l3-foreground);
opacity: calc(1 - var(--actions-opacity, 0));
@@ -87,7 +87,7 @@
width: 100%;
border-bottom: 1px solid var(--accent-primary);
--input-padding: 1px 0;
--input-font-size: var(--periscope-font-size-base);
--input-font-size: var(--label-base-400-font-size);
--input-hover-border-color: transparent;
}

View File

@@ -56,7 +56,7 @@
--button-border-radius: 3px;
--button-justify-content: flex-start;
--button-gap: var(--spacing-4);
--button-font-weight: var(--font-weight-normal);
--button-font-weight: var(--label-base-400-font-weight);
--button-variant-outlined-background-color: var(--l2-background);
--button-variant-outlined-border: 1px solid var(--l1-border);
--button-variant-outlined-color: var(--l2-foreground);
@@ -144,8 +144,8 @@
.groupLabel {
display: block;
padding: 0 0 7px;
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
font-size: var(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
line-height: 1;
text-transform: uppercase;
letter-spacing: 0.04em;

View File

@@ -14,8 +14,8 @@
}
.note {
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
line-height: 1;
font-feature-settings:
'tnum' on,

View File

@@ -71,7 +71,7 @@
align-items: flex-start;
background: var(--l2-background);
color: var(--l1-foreground);
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
border-bottom-left-radius: var(--radius-2);
}
@@ -274,7 +274,7 @@
width: max-content;
min-width: 100%;
border-collapse: collapse;
font-size: var(--periscope-font-size-base);
font-size: var(--paragraph-base-400-font-size);
font-variant-numeric: tabular-nums;
word-break: normal;
@@ -286,8 +286,8 @@
th {
padding-block: 13px;
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;

View File

@@ -5,7 +5,7 @@ import remarkGfm from 'remark-gfm';
import { Button } from '@signozhq/ui/button';
import { RotateCw, TriangleAlert } from '@signozhq/icons';
import { RetryActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { RetryActionDTO } from '@signozhq/noz-client';
// Side-effect: registers all built-in block types into the BlockRegistry
import '../blocks';

View File

@@ -1,9 +1,6 @@
import React from 'react';
import { render, screen, userEvent } from 'tests/test-utils';
import {
ErrorCodeDTO,
RetryActionDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { ErrorCodeDTO, RetryActionDTO } from '@signozhq/noz-client';
import { Message } from '../../../types';

View File

@@ -10,7 +10,7 @@ import { useTimezone } from 'providers/Timezone';
import logEvent from 'api/common/logEvent';
import { FeedbackRatingDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { FeedbackRatingDTO } from '@signozhq/noz-client';
import { AIAssistantEvents } from '../../events';
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';

View File

@@ -6,7 +6,7 @@ import remarkGfm from 'remark-gfm';
import type {
ApprovalEventDTO,
ClarificationEventDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import { useVariant } from '../../VariantContext';
import { StreamingEventItem } from '../../types';

View File

@@ -44,8 +44,8 @@
--button-height: 32px;
--button-padding: 0 var(--spacing-6);
--button-border-radius: var(--radius-round);
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--button-font-size: var(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--button-secondary-background-color: var(--l3-background);
--button-secondary-hover-background-color: var(--l3-background-hover);
--button-secondary-solid-foreground: var(--l1-foreground);

View File

@@ -7,7 +7,7 @@ import { ArrowDown } from '@signozhq/icons';
import type {
ApprovalEventDTO,
ClarificationEventDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import logEvent from 'api/common/logEvent';
import { AIAssistantEvents } from '../../events';

View File

@@ -1,4 +1,4 @@
import type { ChipDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { ChipDTO } from '@signozhq/noz-client';
/** Static empty-state chips used when the contextual chips API is unavailable. */
export const EMPTY_STATE_CHIPS_FALLBACK: ChipDTO[] = [

View File

@@ -2,7 +2,7 @@ import { useMemo } from 'react';
import { useQuery } from 'react-query';
import { getEmptyStateChips } from 'api/ai-assistant/chat';
import type { ChipDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { ChipDTO } from '@signozhq/noz-client';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useResolvePageType } from 'hooks/aiAssistant/useResolvePageType';

View File

@@ -1,4 +1,4 @@
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { PageTypeDTO } from '@signozhq/noz-client';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { matchRoute } from 'lib/router/matchRoute';

View File

@@ -4,7 +4,7 @@ import {
MessageContextDTOType,
MessageRoleDTO,
RetryActionDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import type {
MessageContext,
SSEEvent,
@@ -73,6 +73,10 @@ describe('useAIAssistantStore — streaming error handling', () => {
});
});
afterEach(() => {
jest.useRealTimers();
});
it('commits a manually-retryable error bubble with friendly copy and metadata', async () => {
chat.createThread.mockResolvedValue('thread-1');
chat.sendMessage.mockResolvedValue('exec-1');
@@ -142,6 +146,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
});
it('silently retries auto-flagged errors, then downgrades to manual once spent', async () => {
jest.useFakeTimers();
chat.createThread.mockResolvedValue('thread-2');
chat.sendMessage.mockResolvedValue('exec');
// Always auto-retryable: 1 initial attempt + MAX_AUTO_RETRIES (2) = 3 sends.
@@ -152,7 +157,9 @@ describe('useAIAssistantStore — streaming error handling', () => {
);
useAIAssistantStore.getState().startNewConversation();
await useAIAssistantStore.getState().sendMessage('hi');
const sending = useAIAssistantStore.getState().sendMessage('hi');
await jest.runAllTimersAsync();
await sending;
expect(chat.sendMessage).toHaveBeenCalledTimes(3);
expect(lastMessage('thread-2')).toMatchObject({
@@ -161,7 +168,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
// Auto budget exhausted → presented as manual so a Retry button shows.
retryAction: RetryActionDTO.manual,
});
}, 10000);
});
it('marks rate-limit errors and offers no retry', async () => {
chat.createThread.mockResolvedValue('thread-3');
@@ -191,6 +198,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
});
it('recovers silently when an auto-flagged error succeeds on retry', async () => {
jest.useFakeTimers();
chat.createThread.mockResolvedValue('thread-4');
chat.sendMessage.mockResolvedValue('exec');
chat.streamEvents
@@ -212,7 +220,9 @@ describe('useAIAssistantStore — streaming error handling', () => {
);
useAIAssistantStore.getState().startNewConversation();
await useAIAssistantStore.getState().sendMessage('hi');
const sending = useAIAssistantStore.getState().sendMessage('hi');
await jest.runAllTimersAsync();
await sending;
// 1 initial attempt + 1 silent auto retry, then success — no error bubble.
expect(chat.sendMessage).toHaveBeenCalledTimes(2);
@@ -224,7 +234,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
content: 'Recovered',
});
expect(conv.messages.some((m) => m.isError)).toBe(false);
}, 10000);
});
it('replays the originating action on retry for a non-send error (approve)', async () => {
chat.approveExecution.mockResolvedValue('exec-a');

View File

@@ -7,8 +7,8 @@ import { immer } from 'zustand/middleware/immer';
import type {
MessageActionDTO,
MessageSummaryDTOBlocksAnyOfItem,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { RetryActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import { RetryActionDTO } from '@signozhq/noz-client';
import {
approveExecution,

View File

@@ -1,8 +1,7 @@
/**
* UI types for the AI Assistant.
*
* Wherever the OpenAPI-generated DTOs in
* `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`
* Wherever the OpenAPI-generated DTOs in `@signozhq/noz-client`
* already capture the right shape, this module re-exports them.
*
* A type is defined locally only when the UI needs a different shape than
@@ -20,7 +19,7 @@ import type {
MessageActionDTO,
MessageActionKindDTO,
RetryActionDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
import type { MessageContext } from 'api/ai-assistant/chat';
/** Client-only file attachment — no API equivalent (uploads happen via data URLs). */

View File

@@ -1,8 +1,5 @@
import { AxiosError } from 'axios';
import {
ErrorCodeDTO,
RetryActionDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { ErrorCodeDTO, RetryActionDTO } from '@signozhq/noz-client';
import { resolveAssistantError } from '../resolveAssistantError';

View File

@@ -4,7 +4,7 @@ import {
RetryActionDTO,
type ErrorBodyDTO,
type ErrorResponseDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
} from '@signozhq/noz-client';
export interface AssistantErrorResolution {
/** User-facing copy: code-specific FE copy → backend message → caller fallback. */

View File

@@ -6,7 +6,13 @@ import {
trialConvertedToSubscriptionResponse,
} from 'mocks-server/__mockdata__/licenses';
import { server } from 'mocks-server/server';
import { act, render, screen, getAppContextMock } from 'tests/test-utils';
import {
act,
render,
screen,
getAppContextMock,
within,
} from 'tests/test-utils';
import APIError from 'types/api/error';
import {
LicensePlatform,
@@ -26,8 +32,6 @@ window.ResizeObserver =
}));
describe('BillingContainer', () => {
jest.setTimeout(30000);
beforeEach(() => {
server.use(setupAuthzAdmin());
});
@@ -39,40 +43,47 @@ describe('BillingContainer', () => {
it('Component should render', async () => {
render(<BillingContainer />);
const dataInjection = await screen.findByRole('columnheader', {
name: /data ingested/i,
});
expect(dataInjection).toBeInTheDocument();
const pricePerUnit = await screen.findByRole('columnheader', {
name: /price per unit/i,
});
expect(pricePerUnit).toBeInTheDocument();
const cost = await screen.findByRole('columnheader', {
name: /cost/i,
});
expect(cost).toBeInTheDocument();
const dayRemainingInBillingPeriod = await screen.findByText(
/Please upgrade plan now to retain your data./i,
{},
{ timeout: 5000 },
);
expect(dayRemainingInBillingPeriod).toBeInTheDocument();
expect(
screen.getByText('Data Ingested', { selector: 'th' }),
).toBeInTheDocument();
expect(
screen.getByText('Price per Unit', { selector: 'th' }),
).toBeInTheDocument();
expect(screen.getByText('Cost', { selector: 'th' })).toBeInTheDocument();
const upgradePlanButton = screen.getByTestId('upgrade-plan-button');
expect(upgradePlanButton).toBeInTheDocument();
const dollar = await screen.findByText(/\$1,278.3/i, {}, { timeout: 5000 });
expect(dollar).toBeInTheDocument();
const currentBill = await screen.findByText('billing');
expect(currentBill).toBeInTheDocument();
expect(screen.getByText(/\$1,278.3/i)).toBeInTheDocument();
expect(screen.getByText('billing')).toBeInTheDocument();
});
describe('Trial scenarios', () => {
beforeEach(() => {
jest.useFakeTimers();
jest.setSystemTime(new Date('2023-10-20'));
jest.useFakeTimers({
now: new Date('2023-10-20'),
doNotFake: [
'hrtime',
'nextTick',
'performance',
'queueMicrotask',
'requestAnimationFrame',
'cancelAnimationFrame',
'requestIdleCallback',
'cancelIdleCallback',
'setImmediate',
'clearImmediate',
'setInterval',
'clearInterval',
'setTimeout',
'clearTimeout',
],
});
});
afterEach(() => {
@@ -88,14 +99,9 @@ describe('BillingContainer', () => {
{ appContextOverrides: { trialInfo: licensesSuccessResponse.data } },
);
// If the component schedules any setTimeout on mount, flush them:
jest.runOnlyPendingTimers();
await expect(screen.findByText('Free Trial')).resolves.toBeInTheDocument();
await expect(screen.findByText('billing')).resolves.toBeInTheDocument();
await expect(
screen.findByText(/\$0/i, {}, { timeout: 5000 }),
).resolves.toBeInTheDocument();
await expect(screen.findByText(/\$0/i)).resolves.toBeInTheDocument();
await expect(
screen.findByText(
@@ -107,18 +113,20 @@ describe('BillingContainer', () => {
screen.findByText(/1 days_remaining/i),
).resolves.toBeInTheDocument();
const upgradeButtons = await screen.findAllByRole('button', {
name: /upgrade_plan/i,
});
expect(upgradeButtons).toHaveLength(2);
expect(upgradeButtons[1]).toBeInTheDocument();
expect(screen.getByTestId('header-billing-button')).toHaveTextContent(
'upgrade_plan',
);
expect(screen.getByTestId('upgrade-plan-button')).toHaveTextContent(
'upgrade_plan',
);
await expect(
screen.findByText(/checkout_plans/i),
).resolves.toBeInTheDocument();
await expect(
screen.findByRole('link', { name: /here/i }),
).resolves.toBeInTheDocument();
expect(screen.getByText('here', { selector: 'a' })).toHaveAttribute(
'href',
'https://signoz.io/pricing/',
);
await expect(
screen.findByText('Cancel your subscription', { selector: 'span' }),
@@ -141,7 +149,7 @@ describe('BillingContainer', () => {
const currentBill = await screen.findByText('billing');
expect(currentBill).toBeInTheDocument();
const dollar0 = await screen.findByText(/\$0/i, {}, { timeout: 5000 });
const dollar0 = await screen.findByText(/\$0/i);
expect(dollar0).toBeInTheDocument();
const onTrail = await screen.findByText(
@@ -154,10 +162,9 @@ describe('BillingContainer', () => {
);
expect(receivedCardDetails).toBeInTheDocument();
const manageBillingButton = await screen.findByRole('button', {
name: /manage_billing/i,
});
expect(manageBillingButton).toBeInTheDocument();
expect(screen.getByTestId('header-billing-button')).toHaveTextContent(
'manage_billing',
);
const dayRemainingInBillingPeriod =
await screen.findByText(/1 days_remaining/i);
@@ -259,27 +266,23 @@ describe('BillingContainer', () => {
billingSuccessResponse.data.billingPeriodStart,
)} to ${getFormattedDate(billingSuccessResponse.data.billingPeriodEnd)}`;
const billingPeriod = await findByText(
billingPeriodText,
{},
{ timeout: 5000 },
);
const billingPeriod = await findByText(billingPeriodText);
expect(billingPeriod).toBeInTheDocument();
const currentBill = await screen.findByText('billing');
expect(currentBill).toBeInTheDocument();
expect(screen.getByText('billing')).toBeInTheDocument();
expect(screen.getByText(/\$1,278.3/i)).toBeInTheDocument();
const dollar0 = await screen.findByText(/\$1,278.3/i);
expect(dollar0).toBeInTheDocument();
const cellTexts = (productIndex: number, tierIndex: number): string[] =>
within(screen.getByTestId(`billing-usage-row-${productIndex}${tierIndex}`))
.getAllByRole('cell')
.map((cell) => cell.textContent ?? '');
const metricsRow = await screen.findByRole('row', {
name: /metrics 4012 Million 0.1 \$ 401.2/i,
});
expect(metricsRow).toBeInTheDocument();
const logRow = await screen.findByRole('row', {
name: /Logs 497 GB 0.4 \$ 198.8/i,
});
expect(logRow).toBeInTheDocument();
expect(cellTexts(0, 0)).toStrictEqual([
'Metrics',
'4012 Million',
'0.1',
'$ 401.2',
]);
expect(cellTexts(2, 0)).toStrictEqual(['Logs', '497 GB', '0.4', '$ 198.8']);
});
});

View File

@@ -597,6 +597,11 @@ export default function BillingContainer(): JSX.Element {
dataSource={data}
pagination={false}
bordered={false}
onRow={(
record,
): React.HTMLAttributes<HTMLElement> & { 'data-testid': string } => ({
'data-testid': `billing-usage-row-${record.key}`,
})}
components={{
header: {
cell: ({

View File

@@ -64,6 +64,31 @@ const multiOrgProps: ForgotPasswordRouteState = {
orgs: mockMultipleOrgs,
};
function mockForgot(): {
forgotCalls: () => number;
holdResponse: () => () => void;
} {
let calls = 0;
let pending: Promise<void> = Promise.resolve();
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, async (_req, res, ctx) => {
calls += 1;
await pending;
return res(ctx.status(200), ctx.json({ status: 'success' }));
}),
);
return {
forgotCalls: (): number => calls,
holdResponse: (): (() => void) => {
let release: () => void = () => {};
pending = new Promise((resolve) => {
release = resolve;
});
return release;
},
};
}
describe('ForgotPassword Component', () => {
beforeEach(() => {
jest.clearAllMocks();
@@ -136,7 +161,7 @@ describe('ForgotPassword Component', () => {
});
it('enables submit button after selecting an organization', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(<ForgotPassword {...multiOrgProps} />);
@@ -144,7 +169,7 @@ describe('ForgotPassword Component', () => {
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
// Click on the dropdown to reveal the options
await user.click(screen.getByRole('combobox'));
await user.click(screen.getByText('Select your organization'));
await user.click(screen.getByText('Organization One'));
await waitFor(() => {
@@ -168,7 +193,7 @@ describe('ForgotPassword Component', () => {
describe('Form Submission - Success', () => {
it('successfully submits forgot password request and shows success screen', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
@@ -190,7 +215,7 @@ describe('ForgotPassword Component', () => {
});
it('shows back to login button on success screen', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
@@ -209,7 +234,7 @@ describe('ForgotPassword Component', () => {
});
it('redirects to login when clicking back to login on success screen', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
@@ -235,7 +260,7 @@ describe('ForgotPassword Component', () => {
describe('Form Submission - Error Handling', () => {
it('displays error message when forgot password API fails', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.post(
@@ -255,7 +280,7 @@ describe('ForgotPassword Component', () => {
});
it('displays error message when API returns server error', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(rest.post(FORGOT_PASSWORD_ENDPOINT, handleInternalServerError));
@@ -270,7 +295,7 @@ describe('ForgotPassword Component', () => {
});
it('clears error message on new submission attempt', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
let requestCount = 0;
server.use(
@@ -314,7 +339,7 @@ describe('ForgotPassword Component', () => {
describe('Navigation', () => {
it('redirects to login when clicking back button on form', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
render(<ForgotPassword {...defaultProps} />);
@@ -327,13 +352,9 @@ describe('ForgotPassword Component', () => {
describe('Loading States', () => {
it('shows loading state during API call', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
res(ctx.delay(100), ctx.status(200), ctx.json({ status: 'success' })),
),
);
mockForgot().holdResponse();
render(<ForgotPassword {...defaultProps} />);
@@ -347,13 +368,9 @@ describe('ForgotPassword Component', () => {
});
it('disables submit button during loading', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
res(ctx.delay(100), ctx.status(200), ctx.json({ status: 'success' })),
),
);
mockForgot().holdResponse();
render(<ForgotPassword {...defaultProps} />);
@@ -410,23 +427,8 @@ describe('ForgotPassword Component', () => {
// The email input is disabled and Enter in the org Select opens it, so Enter
// only reaches the form through the focused submit button.
describe('Enter key submission', () => {
function mockForgot(delayMs = 0): { forgotCalls: () => number } {
let calls = 0;
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) => {
calls += 1;
return res(
ctx.delay(delayMs),
ctx.status(200),
ctx.json({ status: 'success' }),
);
}),
);
return { forgotCalls: (): number => calls };
}
it('sends the reset link once on Enter on the submit button', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const { forgotCalls } = mockForgot();
render(<ForgotPassword {...defaultProps} />);
@@ -443,7 +445,7 @@ describe('ForgotPassword Component', () => {
});
it('does not send on Enter while no organization is selected', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
const { forgotCalls } = mockForgot();
render(<ForgotPassword {...multiOrgProps} />);
@@ -459,8 +461,9 @@ describe('ForgotPassword Component', () => {
});
it('does not send again on Enter while the first request is loading', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const { forgotCalls } = mockForgot(1000);
const user = userEvent.setup();
const { forgotCalls, holdResponse } = mockForgot();
const releaseResponse = holdResponse();
render(<ForgotPassword {...defaultProps} />);
@@ -472,8 +475,9 @@ describe('ForgotPassword Component', () => {
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
await user.keyboard('{enter}');
releaseResponse();
await expect(
screen.findByText(/check your email/i, undefined, { timeout: 2000 }),
screen.findByText(/check your email/i),
).resolves.toBeInTheDocument();
expect(forgotCalls()).toBe(1);
});

View File

@@ -617,7 +617,10 @@ function GeneralSettings({
) {
return (
<Fragment key={category.name}>
<div className="retention-row">
<div
className="retention-row"
data-testid={`${category.type}-retention-row`}
>
<span className="retention-row-label">
{category.icon}
{category.name}
@@ -644,6 +647,7 @@ function GeneralSettings({
onClick={category.save.modalOpen}
disabled={category.save.isDisabled}
loading={category.save.isLoading}
testId={`${category.type}-retention-save-button`}
>
{category.save.saveButtonText}
</Button>
@@ -671,6 +675,9 @@ function GeneralSettings({
centered
open={category.save.modal}
confirmLoading={category.save.apiLoading}
okButtonProps={{
'data-testid': `${category.type}-retention-confirm-button`,
}}
>
<p className="retention-modal-description">
{t('retention_confirmation_description', {

View File

@@ -80,8 +80,14 @@ function Retention({
}
}, [initialTimeUnitValue]);
const testId = `${type}-${isS3Field ? 's3' : 'total'}-retention`;
const menuItems = availableUnits.map((option) => (
<Option key={option.value} value={option.value}>
<Option
key={option.value}
value={option.value}
data-testid={`${testId}-unit-option`}
>
{option.key}
</Option>
));
@@ -139,11 +145,13 @@ function Retention({
disabled={isCloudUserVal}
disabledTooltip={undefined}
onChange={(e): void => onChangeHandler(e, setSelectedValue)}
testId={testId}
/>
<Select
value={selectedTimeUnit}
onChange={currentSelectedOption}
disabled={isCloudUserVal}
data-testid={`${testId}-unit`}
>
{menuItems}
</Select>

View File

@@ -1,6 +1,6 @@
import setRetentionApiV2 from 'api/settings/setRetentionV2';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { fireEvent, render, screen, waitFor } from 'tests/test-utils';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { IDiskType } from 'types/api/disks/getDisks';
import {
PayloadPropsLogs,
@@ -93,10 +93,7 @@ const mockDisksWithoutS3: IDiskType[] = [
},
];
const getLogsRow = (): HTMLElement => {
const logsLabel = screen.getByText('Logs');
return logsLabel.closest('.retention-row') as HTMLElement;
};
const getLogsRow = (): HTMLElement => screen.getByTestId('logs-retention-row');
describe('GeneralSettings - S3 Logs Retention', () => {
beforeEach(() => {
@@ -108,7 +105,8 @@ describe('GeneralSettings - S3 Logs Retention', () => {
});
describe('Test 1: S3 Enabled - Only Days in Dropdown', () => {
it('should show only Days option for S3 retention and send correct API payload', async () => {
it('should show only Days option for S3 retention', async () => {
const user = userEvent.setup();
render(
<GeneralSettings
metricsTtlValuesPayload={mockMetricsRetention}
@@ -125,54 +123,52 @@ describe('GeneralSettings - S3 Logs Retention', () => {
expect(logsRow).toBeInTheDocument();
// Find all inputs in the Logs row - there should be 2 (total retention + S3)
const inputs = logsRow.querySelectorAll('input[type="number"]');
expect(inputs).toHaveLength(2);
// The second input is the S3 retention field
const s3Input = inputs[1] as HTMLInputElement;
// Find the S3 dropdown (next sibling of the S3 input)
const s3Dropdown = s3Input
?.closest('.retention-row-controls')
?.querySelectorAll('.ant-select-selector')[1] as HTMLElement;
expect(s3Dropdown).toBeInTheDocument();
expect(
within(logsRow).getByTestId('logs-total-retention-field'),
).toBeInTheDocument();
expect(
within(logsRow).getByTestId('logs-s3-retention-field'),
).toBeInTheDocument();
// Click the S3 dropdown to open it
fireEvent.mouseDown(s3Dropdown);
await user.click(
within(screen.getByTestId('logs-s3-retention-unit')).getByTitle('Days'),
);
// Wait for dropdown options to appear and verify only "Days" is available
await waitFor(() => {
const dropdownOptions = document.querySelectorAll('.ant-select-item');
expect(dropdownOptions).toHaveLength(1);
expect(dropdownOptions[0]).toHaveTextContent('Days');
});
const dropdownOptions = await screen.findAllByTestId(
'logs-s3-retention-unit-option',
);
expect(dropdownOptions).toHaveLength(1);
expect(dropdownOptions[0]).toHaveTextContent('Days');
});
// Close dropdown
fireEvent.click(document.body);
it('should send correct API payload for S3 retention', async () => {
const user = userEvent.setup();
render(
<GeneralSettings
metricsTtlValuesPayload={mockMetricsRetention}
tracesTtlValuesPayload={mockTracesRetention}
logsTtlValuesPayload={mockLogsRetentionWithS3}
getAvailableDiskPayload={mockDisksWithS3}
metricsTtlValuesRefetch={jest.fn()}
tracesTtlValuesRefetch={jest.fn()}
logsTtlValuesRefetch={jest.fn()}
/>,
);
const s3Input = screen.getByTestId('logs-s3-retention-field');
// Change S3 retention value to 5 days
fireEvent.change(s3Input, { target: { value: '5' } });
await user.clear(s3Input);
await user.type(s3Input, '5');
// Find the save button in the Logs row
const saveButton = logsRow.querySelector(
'button:not([disabled])',
) as HTMLButtonElement;
expect(saveButton).toBeInTheDocument();
const saveButton = screen.getByTestId('logs-retention-save-button');
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
await user.click(saveButton);
// Wait for button to be enabled
await waitFor(() => {
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
});
fireEvent.click(saveButton);
// Wait for modal to appear
const modal = await screen.findByRole('dialog');
expect(modal).toBeInTheDocument();
// Click OK button
const okButton = await screen.findByRole('button', { name: /ok/i });
fireEvent.click(okButton);
// Wait for modal to appear and click OK
await user.click(await screen.findByTestId('logs-retention-confirm-button'));
// Verify API was called with correct payload
await waitFor(() => {
@@ -201,13 +197,18 @@ describe('GeneralSettings - S3 Logs Retention', () => {
// Verify S3 field is visible
const logsRow = getLogsRow();
const inputs = logsRow.querySelectorAll('input[type="number"]');
expect(inputs).toHaveLength(2); // Total + S3
expect(
within(logsRow).getByTestId('logs-total-retention-field'),
).toBeInTheDocument();
expect(
within(logsRow).getByTestId('logs-s3-retention-field'),
).toBeInTheDocument();
});
});
describe('Test 2: S3 Disabled - Field Hidden', () => {
it('should hide S3 retention field and send empty S3 values to API', async () => {
const user = userEvent.setup();
render(
<GeneralSettings
metricsTtlValuesPayload={mockMetricsRetention}
@@ -224,55 +225,37 @@ describe('GeneralSettings - S3 Logs Retention', () => {
expect(logsRow).toBeInTheDocument();
// Only 1 input should be visible (total retention, no S3)
const inputs = logsRow.querySelectorAll('input[type="number"]');
expect(inputs).toHaveLength(1);
expect(
within(logsRow).queryByTestId('logs-s3-retention-field'),
).not.toBeInTheDocument();
// Change total retention value
const totalInput = inputs[0] as HTMLInputElement;
const totalInput = within(logsRow).getByTestId('logs-total-retention-field');
// First, change the dropdown to Days (it defaults to Months)
const totalDropdown = logsRow.querySelector(
'.ant-select-selector',
) as HTMLElement;
fireEvent.mouseDown(totalDropdown);
// Wait for dropdown options to appear
await waitFor(() => {
const options = document.querySelectorAll('.ant-select-item');
expect(options.length).toBeGreaterThan(0);
});
await user.click(
within(screen.getByTestId('logs-total-retention-unit')).getByTitle(
'Months',
),
);
// Find and click the Days option
const options = document.querySelectorAll('.ant-select-item');
const daysOption = Array.from(options).find((opt) =>
opt.textContent?.includes('Days'),
const [daysOption] = await screen.findAllByTestId(
'logs-total-retention-unit-option',
);
expect(daysOption).toBeInTheDocument();
fireEvent.click(daysOption as HTMLElement);
expect(daysOption).toHaveTextContent('Days');
await user.click(daysOption);
// Now change the value
fireEvent.change(totalInput, { target: { value: '60' } });
await user.clear(totalInput);
await user.type(totalInput, '60');
// Find the save button
const saveButton = logsRow.querySelector(
'button:not([disabled])',
) as HTMLButtonElement;
expect(saveButton).toBeInTheDocument();
const saveButton = screen.getByTestId('logs-retention-save-button');
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
await user.click(saveButton);
// Wait for button to be enabled
await waitFor(() => {
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
});
// Click save button
fireEvent.click(saveButton);
// Wait for modal to appear
const okButton = await screen.findByRole('button', { name: /ok/i });
expect(okButton).toBeInTheDocument();
// Click OK button
fireEvent.click(okButton);
// Wait for modal to appear and click OK
await user.click(await screen.findByTestId('logs-retention-confirm-button'));
// Verify API was called with empty S3 values (60 days)
await waitFor(() => {
@@ -301,26 +284,25 @@ describe('GeneralSettings - S3 Logs Retention', () => {
/>,
);
const logsRow = getLogsRow();
const inputs = logsRow.querySelectorAll('input[type="number"]');
// Total retention: 30 days = 1 month (displays as 1 Month)
const totalInput = inputs[0] as HTMLInputElement;
expect(totalInput.value).toBe('1');
expect(screen.getByTestId('logs-total-retention-field')).toHaveValue(1);
// S3 retention: 24 days
const s3Input = inputs[1] as HTMLInputElement;
expect(s3Input.value).toBe('24');
expect(screen.getByTestId('logs-s3-retention-field')).toHaveValue(24);
// Verify dropdowns: total shows Months, S3 shows Days
const dropdowns = logsRow.querySelectorAll('.ant-select-selection-item');
expect(dropdowns[0]).toHaveTextContent('Months');
expect(dropdowns[1]).toHaveTextContent('Days');
expect(screen.getByTestId('logs-total-retention-unit')).toHaveTextContent(
'Months',
);
expect(screen.getByTestId('logs-s3-retention-unit')).toHaveTextContent(
'Days',
);
});
});
describe('Test 4: Save Button State with S3 Disabled', () => {
it('should disable save button when cold_storage_ttl_days is -1 and no changes made', async () => {
const user = userEvent.setup();
render(
<GeneralSettings
metricsTtlValuesPayload={mockMetricsRetention}
@@ -336,35 +318,28 @@ describe('GeneralSettings - S3 Logs Retention', () => {
const logsRow = getLogsRow();
expect(logsRow).toBeInTheDocument();
// Find the save button by accessible name within the Logs row
const allSaveButtons = screen.getAllByRole('button', { name: /save/i });
const saveButton = allSaveButtons.find((btn) =>
logsRow.contains(btn),
) as HTMLButtonElement;
expect(saveButton).toBeInTheDocument();
const saveButton = screen.getByTestId('logs-retention-save-button');
expect(logsRow).toContainElement(saveButton);
// Verify save button is disabled on initial load
expect(saveButton).toHaveAttribute('aria-disabled', 'true');
// Find the total retention input
const inputs = logsRow.querySelectorAll('input[type="number"]');
const totalInput = inputs[0] as HTMLInputElement;
const totalInput = within(logsRow).getByTestId('logs-total-retention-field');
// Change total retention value to trigger button enable
fireEvent.change(totalInput, { target: { value: '60' } });
await user.clear(totalInput);
await user.type(totalInput, '60');
// Button should now be enabled after change
await waitFor(() => {
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
});
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
// Revert to original value (30 days displays as 1 Month)
fireEvent.change(totalInput, { target: { value: '1' } });
await user.clear(totalInput);
await user.type(totalInput, '1');
// Button should be disabled again (back to original state)
await waitFor(() => {
expect(saveButton).toHaveAttribute('aria-disabled', 'true');
});
expect(saveButton).toHaveAttribute('aria-disabled', 'true');
});
});
@@ -421,8 +396,11 @@ describe('GeneralSettings - S3 Logs Retention', () => {
).not.toBeInTheDocument();
// Save buttons should be visible for non-cloud users (these are from retentions)
const saveButtons = screen.getAllByRole('button', { name: /save/i });
expect(saveButtons.length).toBeGreaterThan(0);
['metrics', 'traces', 'logs'].forEach((type) => {
expect(
screen.getByTestId(`${type}-retention-save-button`),
).toHaveTextContent('retention_save_button.success');
});
});
});
});

View File

@@ -26,27 +26,6 @@ jest.mock('api/common/logEvent', () => ({
const logEventMock = jest.mocked(logEvent);
// The breadcrumb of the trail reads `maxWidth`, which the fallback style of
// jest.setup.ts does not carry.
const baseGetComputedStyle = window.getComputedStyle;
beforeAll(() => {
window.getComputedStyle = (
element: Element,
pseudoElement?: string | null,
): CSSStyleDeclaration => {
const style = baseGetComputedStyle(element, pseudoElement);
return style.maxWidth === undefined
? ({ ...style, maxWidth: '' } as CSSStyleDeclaration)
: style;
};
});
afterAll(() => {
window.getComputedStyle = baseGetComputedStyle;
});
type TestEntity = { name: string };
const mockEntity: TestEntity = { name: 'test-container' };

View File

@@ -23,6 +23,7 @@ import { openInNewTab } from 'utils/navigation';
import { TableColumnDef } from 'components/TanStackTableView';
import { ExpandButtonWrapper } from '../../components/ExpandButtonWrapper';
import { InfraMonitoringEntity } from '../../constants';
import { SelectedItemParams } from '../../hooks';
@@ -128,6 +129,24 @@ function createTestColumns(): TableColumnDef<TestItem>[] {
];
}
function createTestColumnsWithExpand(): TableColumnDef<TestItem>[] {
return [
{
id: 'group',
header: (): React.ReactNode => 'Group',
accessorFn: (row): string => row.id,
visibilityBehavior: 'hidden-on-collapse',
cell: ({ isExpanded, toggleExpanded }): React.ReactNode => (
<ExpandButtonWrapper
isExpanded={isExpanded}
toggleExpanded={toggleExpanded}
/>
),
},
...createTestColumns(),
];
}
function createTestColumnsWithName(): TableColumnDef<TestItemWithName>[] {
return [
{
@@ -426,15 +445,7 @@ describe('K8sBaseList', () => {
expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
});
// Find pagination navigation and page 2 button
const nav = screen.getByRole('navigation');
const page2Button = Array.from(nav.querySelectorAll('button')).find(
(btn) => btn.textContent?.trim() === '2',
);
if (!page2Button) {
throw new Error('Page 2 button not found in pagination');
}
await user.click(page2Button);
await user.click(screen.getByTestId('pagination-page-2'));
await waitFor(() => {
const lastPage = onUrlUpdateMock.mock.calls
@@ -447,13 +458,16 @@ describe('K8sBaseList', () => {
});
it('should open row in new tab when ctrl+click on row', async () => {
const user = userEvent.setup();
await waitFor(() => {
expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
});
const firstRow = screen.getByText(`PodId:${itemId}`);
// Ctrl+click to open in new tab
fireEvent.click(firstRow, { ctrlKey: true });
await user.keyboard('{Control>}');
await user.click(firstRow);
await user.keyboard('{/Control}');
await waitFor(() => {
expect(openInNewTabMock).toHaveBeenCalledTimes(1);
@@ -464,13 +478,16 @@ describe('K8sBaseList', () => {
});
it('should open row in new tab when meta+click (cmd on Mac) on row', async () => {
const user = userEvent.setup();
await waitFor(() => {
expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
});
const firstRow = screen.getByText(`PodId:${itemId}`);
// Meta+click (cmd on Mac) to open in new tab
fireEvent.click(firstRow, { metaKey: true });
await user.keyboard('{Meta>}');
await user.click(firstRow);
await user.keyboard('{/Meta}');
await waitFor(() => {
expect(openInNewTabMock).toHaveBeenCalledTimes(1);
@@ -511,7 +528,7 @@ describe('K8sBaseList', () => {
groupBy: JSON.stringify(groupByValue),
page: '3',
},
tableColumns: createTestColumns(),
tableColumns: createTestColumnsWithExpand(),
getRowKey: (row): string => row.id,
getItemKey: (row): string => row.id,
});
@@ -533,12 +550,9 @@ describe('K8sBaseList', () => {
});
it('should render expand icons when groupBy is set', async () => {
await waitFor(() => {
expect(screen.getByText('namespace-default')).toBeInTheDocument();
});
const row = await screen.findByTestId('row-namespace-default');
const expandButtons = screen.getAllByRole('button');
expect(expandButtons.length).toBeGreaterThan(0);
expect(within(row).getByTestId('expand-row-button')).toBeInTheDocument();
});
it('should render data with groupBy params', async () => {
@@ -585,7 +599,7 @@ describe('K8sBaseList', () => {
groupBy: JSON.stringify(groupByValue),
page: '3',
},
tableColumns: createTestColumns(),
tableColumns: createTestColumnsWithExpand(),
getRowKey: (row): string => row.id,
getItemKey: (row): string => row.id,
});
@@ -601,12 +615,9 @@ describe('K8sBaseList', () => {
});
it('should render expand icons when groupBy is set with new format', async () => {
await waitFor(() => {
expect(screen.getByText('namespace-default')).toBeInTheDocument();
});
const row = await screen.findByTestId('row-namespace-default');
const expandButtons = screen.getAllByRole('button');
expect(expandButtons.length).toBeGreaterThan(0);
expect(within(row).getByTestId('expand-row-button')).toBeInTheDocument();
});
it('should render data with new groupBy format', async () => {
@@ -941,12 +952,8 @@ describe('K8sBaseList', () => {
});
// All columns should be visible
expect(
screen.getByRole('columnheader', { name: /id/i }),
).toBeInTheDocument();
expect(
screen.getByRole('columnheader', { name: /name/i }),
).toBeInTheDocument();
expect(screen.getByTestId('tanstack-header-id')).toHaveTextContent('Id');
expect(screen.getByTestId('tanstack-header-name')).toHaveTextContent('Name');
});
});
@@ -989,9 +996,7 @@ describe('K8sBaseList', () => {
});
// Columns should be visible
expect(
screen.getByRole('columnheader', { name: /id/i }),
).toBeInTheDocument();
expect(screen.getByTestId('tanstack-header-id')).toHaveTextContent('Id');
});
it('should show columns when grouped', async () => {
@@ -1015,9 +1020,7 @@ describe('K8sBaseList', () => {
});
// Id should be visible
expect(
screen.getByRole('columnheader', { name: /id/i }),
).toBeInTheDocument();
expect(screen.getByTestId('tanstack-header-id')).toHaveTextContent('Id');
});
});
@@ -1097,12 +1100,8 @@ describe('K8sBaseList', () => {
});
// All columns should be visible
expect(
screen.getByRole('columnheader', { name: /id/i }),
).toBeInTheDocument();
expect(
screen.getByRole('columnheader', { name: /^name$/i }),
).toBeInTheDocument();
expect(screen.getByTestId('tanstack-header-id')).toHaveTextContent('Id');
expect(screen.getByTestId('tanstack-header-name')).toHaveTextContent('Name');
});
it('should render data in cells correctly', async () => {
@@ -1212,6 +1211,7 @@ describe('K8sBaseList', () => {
});
it('should include cluster and namespace params in new tab URL on ctrl+click', async () => {
const user = userEvent.setup();
renderComponent<TestItemWithTitle, SelectedItemParams>({
onUrlUpdate: onUrlUpdateMock,
entity: InfraMonitoringEntity.PODS,
@@ -1226,7 +1226,9 @@ describe('K8sBaseList', () => {
});
const firstRow = await screen.findByText(`PodId:${itemId}`);
fireEvent.click(firstRow, { ctrlKey: true });
await user.keyboard('{Control>}');
await user.click(firstRow);
await user.keyboard('{/Control}');
await waitFor(() => {
expect(openInNewTabMock).toHaveBeenCalledTimes(1);
@@ -1238,6 +1240,7 @@ describe('K8sBaseList', () => {
});
it('should omit null cluster/namespace params in new tab URL', async () => {
const user = userEvent.setup();
renderComponent<TestItemWithTitle, SelectedItemParams>({
onUrlUpdate: onUrlUpdateMock,
entity: InfraMonitoringEntity.PODS,
@@ -1252,7 +1255,9 @@ describe('K8sBaseList', () => {
});
const firstRow = await screen.findByText(`PodId:${itemId}`);
fireEvent.click(firstRow, { ctrlKey: true });
await user.keyboard('{Control>}');
await user.click(firstRow);
await user.keyboard('{/Control}');
await waitFor(() => {
expect(openInNewTabMock).toHaveBeenCalledTimes(1);
@@ -1614,11 +1619,11 @@ describe('K8sBaseList', () => {
});
// Open group by dropdown using testId
const groupByContainer = screen.getByTestId('k8s-table-group-by-select');
const groupBySelect = groupByContainer.querySelector(
'.ant-select-selector',
) as Element;
await user.click(groupBySelect);
await user.click(
within(screen.getByTestId('k8s-table-group-by-select')).getByText(
'Search for attribute',
),
);
// Wait for options to load and click on the namespace option
const namespaceOption = await screen.findByTitle('k8s.namespace.name');
@@ -1656,11 +1661,11 @@ describe('K8sBaseList', () => {
});
// Open group by dropdown using testId
const groupByContainer = screen.getByTestId('k8s-table-group-by-select');
const groupBySelect = groupByContainer.querySelector(
'.ant-select-selector',
) as Element;
await user.click(groupBySelect);
await user.click(
within(screen.getByTestId('k8s-table-group-by-select')).getByText(
'Search for attribute',
),
);
// Wait for options to load and click on the namespace option
const namespaceOption = await screen.findByTitle('k8s.namespace.name');

View File

@@ -180,7 +180,7 @@ function EntityTracesContent({
{isError && !isKeyNotFound && !isLoading && <EntityError />}
{(!isError || isKeyNotFound) && traces.length > 0 && (
<div className={styles.entityTracesTable}>
<div className={styles.entityTracesTable} data-testid="entity-traces-table">
<div className={styles.controls}>
<Controls
totalCount={hasMore ? currentCount + 1 : currentCount}
@@ -217,6 +217,7 @@ function EntityTracesContent({
dataSource={traces}
columns={traceListColumns}
onRow={(): Record<string, unknown> => ({
'data-testid': 'entity-traces-row',
onClick: (): void => handleRowClick(),
})}
/>

View File

@@ -31,26 +31,21 @@ describe('EntityTraces - Table Rendering', () => {
it('should render table with all column headers', async () => {
mockQueryRangeV5WithTracesResponse({ pageSize: 3 });
act(() => {
renderEntityTraces();
renderEntityTraces();
await screen.findAllByTestId('serviceName');
const table = screen.getByTestId('entity-traces-table');
[
'Timestamp',
'Service Name',
'Name',
'Duration',
'HTTP Method',
'Status Code',
].forEach((header) => {
expect(within(table).getByText(header)).toBeInTheDocument();
});
await expect(screen.findByText('Service Name')).resolves.toBeInTheDocument();
const headerTexts = within(screen.getByRole('table'))
.getAllByRole('columnheader')
.map((header) => header.textContent);
expect(headerTexts).toStrictEqual(
expect.arrayContaining([
'Timestamp',
'Service Name',
'Name',
'Duration',
'HTTP Method',
'Status Code',
]),
);
});
it('should render trace values in table cells', async () => {
@@ -152,13 +147,13 @@ describe('EntityTraces - Table Rendering', () => {
customTraces: [{ serviceName: 'frontend' }],
});
act(() => {
renderEntityTraces();
});
renderEntityTraces();
await expect(screen.findByTestId('serviceName')).resolves.toBeInTheDocument();
const links = within(screen.getByRole('table')).getAllByRole('link');
const links = within(screen.getByTestId('entity-traces-row')).getAllByTestId(
'trace-block-link',
);
expect(links.length).toBeGreaterThan(0);
links.forEach((link) => {
@@ -198,8 +193,7 @@ describe('EntityTraces - Table Rendering', () => {
renderEntityTraces();
const user = userEvent.setup();
const cell = await screen.findByTestId('serviceName');
await user.click(cell.closest('tr') as HTMLElement);
await user.click(await screen.findByTestId('entity-traces-row'));
expect(logEvent).toHaveBeenCalledWith(
'Infra Monitoring: Drawer trace clicked',

View File

@@ -83,6 +83,7 @@ import { MeterAggregateOperator } from 'types/common/queryBuilder';
import { USER_ROLES } from 'types/roles';
import { getDaysUntilExpiry } from 'utils/timeUtils';
import 'components/LearnMore/LearnMore.styles.scss';
import './IngestionSettings.styles.scss';
const { Option } = Select;
@@ -1184,6 +1185,7 @@ function MultiIngestionSettings(): JSX.Element {
icon
color="secondary"
aria-label={`Edit ${signalName} limit`}
testId={`edit-limit-btn-${signalName}`}
disabled={
!!(activeAPIKey?.id === APIKey?.id && activeSignal)
}
@@ -1710,6 +1712,7 @@ function MultiIngestionSettings(): JSX.Element {
target="_blank"
className="learn-more"
rel="noreferrer"
data-testid="ingestion-keys-learn-more"
>
Learn more <ArrowUpRight size={14} />
</a>

View File

@@ -1,13 +1,7 @@
import { GatewaytypesGettableIngestionKeysDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import { rest, server } from 'mocks-server/server';
import {
fireEvent,
render,
screen,
userEvent,
waitFor,
} from 'tests/test-utils';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import MultiIngestionSettings from '../MultiIngestionSettings';
@@ -48,6 +42,7 @@ describe('MultiIngestionSettings Page', () => {
});
afterEach(() => {
jest.useRealTimers();
jest.clearAllMocks();
});
@@ -62,7 +57,8 @@ describe('MultiIngestionSettings Page', () => {
screen.getByText('Create and manage ingestion keys for the SigNoz Cloud'),
).toBeInTheDocument();
const aboutKeyslink = screen.getByRole('link', { name: /Learn more/i });
const aboutKeyslink = screen.getByTestId('ingestion-keys-learn-more');
expect(aboutKeyslink).toHaveTextContent('Learn more');
expect(aboutKeyslink).toHaveAttribute(
'href',
'https://signoz.io/docs/ingestion/signoz-cloud/keys/',
@@ -73,6 +69,7 @@ describe('MultiIngestionSettings Page', () => {
});
it('navigates to create alert with metrics count threshold', async () => {
const user = userEvent.setup();
const response: TestGatewayIngestionKeysResponse = {
status: 'success',
data: {
@@ -111,13 +108,10 @@ describe('MultiIngestionSettings Page', () => {
render(<MultiIngestionSettings />, undefined, {
initialRoute: INGESTION_SETTINGS_ROUTE,
});
await screen.findByText('Key One');
fireEvent.click(screen.getByRole('button', { name: /right Key One/i }));
await user.click(await screen.findByText('Key One'));
await screen.findByText('LIMITS');
fireEvent.click(
(await screen.findByTestId('set-alert-btn-metrics')) as HTMLButtonElement,
);
await user.click(await screen.findByTestId('set-alert-btn-metrics'));
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledTimes(1);
@@ -151,6 +145,7 @@ describe('MultiIngestionSettings Page', () => {
});
it('navigates to create alert for logs with GiB threshold and bytes yAxisUnit', async () => {
const user = userEvent.setup();
const GIB = 1073741824;
const sizeInBytes = 400 * GIB;
@@ -192,13 +187,10 @@ describe('MultiIngestionSettings Page', () => {
render(<MultiIngestionSettings />, undefined, {
initialRoute: INGESTION_SETTINGS_ROUTE,
});
await screen.findByText('Key Logs');
fireEvent.click(screen.getByRole('button', { name: /right Key Logs/i }));
await user.click(await screen.findByText('Key Logs'));
await screen.findByText('LIMITS');
fireEvent.click(
(await screen.findByTestId('set-alert-btn-logs')) as HTMLButtonElement,
);
await user.click(await screen.findByTestId('set-alert-btn-logs'));
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledTimes(1);
@@ -231,6 +223,7 @@ describe('MultiIngestionSettings Page', () => {
});
it('shows alert CTAs in view mode and helper text in edit mode for configured limits', async () => {
const user = userEvent.setup();
const KEY_NAME = 'Key With Limits';
const response: TestGatewayIngestionKeysResponse = {
status: 'success',
@@ -276,22 +269,22 @@ describe('MultiIngestionSettings Page', () => {
initialRoute: INGESTION_SETTINGS_ROUTE,
});
await screen.findByText(KEY_NAME);
fireEvent.click(
screen.getByRole('button', { name: new RegExp(`right ${KEY_NAME}`, 'i') }),
);
await user.click(await screen.findByText(KEY_NAME));
await screen.findByText('LIMITS');
expect(screen.getAllByText('Set alert').length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Edit logs limit' }));
await user.click(screen.getByTestId('edit-limit-btn-logs'));
expect(
screen.getByText('You can set up an alert after saving'),
).toBeInTheDocument();
});
it('switches to search API when search text is entered', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
jest.useFakeTimers();
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const getResponse: TestGatewayIngestionKeysResponse = {
status: 'success',

View File

@@ -101,7 +101,7 @@ function S3BucketsSelector({
}
return (
<div className="s3-buckets-selector">
<div className="s3-buckets-selector" data-testid="s3-buckets-selector">
<div className="s3-buckets-selector-title">Select S3 Buckets by Region</div>
<div className="s3-buckets-selector-content">
{allRegions.map((region) => {
@@ -120,6 +120,7 @@ function S3BucketsSelector({
</div>
<div className="s3-buckets-selector-region-select">
<Select
data-testid={`s3-buckets-select-${region}`}
mode="tags"
placeholder={`Enter S3 bucket names for ${region}`}
value={bucketsByRegion[region] || []}

View File

@@ -1,5 +1,5 @@
import { ComponentProps } from 'react';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { rest, server } from 'mocks-server/server';
import { RestRequest } from 'msw';
import type logEvent from '../../../../../api/common/logEvent';
@@ -14,9 +14,6 @@ jest.mock('../../../../../api/common/logEvent', () => ({
default: jest.fn() as jest.MockedFunction<typeof logEvent>,
}));
// The form flow drives antd selects and typing, which outruns the 5s default on CI.
jest.setTimeout(15_000);
type OnClose = ComponentProps<typeof CloudAccountSetupModal>['onClose'];
const mockOnClose = (): jest.MockedFunction<OnClose> =>
@@ -84,26 +81,28 @@ const mockApi = ({ failFirstPoll = false } = {}): {
return api;
};
type User = ReturnType<typeof userEvent.setup>;
const generateCommand = async (user: User): Promise<void> => {
const select = await screen.findByTestId('aws-deployment-region-select');
await user.click(within(select).getByRole('combobox', { hidden: true }));
await user.click(await screen.findByText('US East (N. Virginia)'));
await user.click(screen.getByTestId('aws-region-us-east-1'));
await user.click(screen.getByTestId('aws-generate-command-btn'));
await screen.findByTestId('aws-agent-command');
};
describe('AWS CloudAccountSetupModal', () => {
it('creates the account and shows its setup command', async () => {
const api = mockApi();
const openSpy = jest.spyOn(window, 'open').mockImplementation(() => null);
const user = userEvent.setup();
const onClose = mockOnClose();
render(<CloudAccountSetupModal onClose={onClose} />);
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
await user.click(await screen.findByRole('combobox'));
await user.click(await screen.findByText('US East (N. Virginia)'));
await user.click(await screen.findByRole('checkbox', { name: /us-east-1/i }));
await user.click(screen.getByTestId('aws-generate-command-btn'));
await waitFor(() => {
expect(screen.getByTestId('aws-agent-command')).toHaveTextContent(
cliCommand,
);
});
await generateCommand(user);
expect(screen.getByTestId('aws-agent-command')).toHaveTextContent(cliCommand);
expect(api.createAccountPayload).toStrictEqual({
config: { aws: { deploymentRegion: 'us-east-1', regions: ['us-east-1'] } },
credentials,
@@ -111,11 +110,25 @@ describe('AWS CloudAccountSetupModal', () => {
expect(
screen.queryByTestId('aws-generate-command-btn'),
).not.toBeInTheDocument();
expect(screen.queryAllByRole('combobox')).toHaveLength(0);
expect(screen.getByText(/waiting for connection/i)).toBeInTheDocument();
expect(
screen.queryByTestId('aws-deployment-region-select'),
).not.toBeInTheDocument();
expect(screen.getByTestId('cloud-connect-waiting')).toHaveTextContent(
/waiting for connection/i,
);
expect(openSpy).not.toHaveBeenCalled();
openSpy.mockRestore();
});
it('asks before closing once a setup command exists', async () => {
mockApi();
const user = userEvent.setup();
const onClose = mockOnClose();
render(<CloudAccountSetupModal onClose={onClose} />);
await generateCommand(user);
await user.click(screen.getByTestId('aws-cancel-btn'));
await user.click(await screen.findByTestId('aws-continue-setup-btn'));
@@ -150,16 +163,15 @@ describe('AWS CloudAccountSetupModal', () => {
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
await user.click(await screen.findByRole('combobox'));
await user.click(await screen.findByText('US East (N. Virginia)'));
await user.click(await screen.findByRole('checkbox', { name: /us-east-1/i }));
await user.click(screen.getByTestId('aws-generate-command-btn'));
await generateCommand(user);
await user.click(await screen.findByTestId('aws-check-connection-btn'));
await waitFor(() => expect(api.pollCount()).toBe(2));
await screen.findByText(/waiting for connection/i);
await expect(
screen.findByTestId('cloud-connect-waiting'),
).resolves.toHaveTextContent(/waiting for connection/i);
expect(
screen.queryByTestId('aws-check-connection-btn'),
).not.toBeInTheDocument();

View File

@@ -1,6 +1,6 @@
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { server } from 'mocks-server/server';
import { rest, RestRequest } from 'msw';
import { screen, userEvent, waitFor, within } from 'tests/test-utils';
import {
accountsResponse,
@@ -11,19 +11,10 @@ import {
import {
assertGenericModalElements,
assertS3SyncSpecificElements,
bucketSelectInput,
renderServiceDetails,
} from './utils';
// --- RESIZE OBSERVER (required by @radix-ui in Tabs/Switch) ---
class ResizeObserverMock {
observe(): void {}
unobserve(): void {}
disconnect(): void {}
}
global.ResizeObserver = ResizeObserverMock as unknown as typeof ResizeObserver;
// --- MOCKS ---
jest.mock('components/MarkdownRenderer/MarkdownRenderer', () => ({
MarkdownRenderer: (): JSX.Element => <div data-testid="markdown-renderer" />,
@@ -36,27 +27,22 @@ jest.mock(
}),
);
let testServiceId = 's3sync';
let testInitialBuckets: Record<string, string[]> = {};
const mockGet = jest.fn((param: string) => {
if (param === 'cloudAccountId') {
return CLOUD_ACCOUNT_ID;
}
if (param === 'service') {
return testServiceId;
}
return null;
});
jest.mock('hooks/useUrlQuery', () => ({
__esModule: true,
default: (): { get: (param: string) => string | null } => ({ get: mockGet }),
}));
const addBucket = async (
user: ReturnType<typeof userEvent.setup>,
bucketName: string,
): Promise<void> => {
await screen.findByTestId('s3-buckets-select-ap-south-1');
await user.click(bucketSelectInput('ap-south-1'));
// antd reads the legacy keyCode on Enter, which user-event leaves at 0, so
// commit the tag with the select's comma separator instead.
await user.paste(`${bucketName},`);
};
// --- TEST SUITE ---
describe('ServiceDetails for S3 Sync service', () => {
jest.setTimeout(10000);
beforeEach(() => {
testServiceId = 's3sync';
testInitialBuckets = {};
server.use(
rest.get(
@@ -79,41 +65,34 @@ describe('ServiceDetails for S3 Sync service', () => {
});
it('should render with logs collection switch and bucket selectors (no buckets initially selected)', async () => {
renderServiceDetails({}); // No initial S3 buckets, defaults to 's3sync' serviceId
renderServiceDetails();
await assertGenericModalElements();
await assertS3SyncSpecificElements({});
});
it('should render with logs collection switch and bucket selectors (some buckets initially selected)', async () => {
testInitialBuckets = initialBuckets;
renderServiceDetails(initialBuckets);
renderServiceDetails();
await assertGenericModalElements();
await assertS3SyncSpecificElements(initialBuckets);
});
it('should enable save button after adding a new bucket via combobox', async () => {
const user = userEvent.setup();
testInitialBuckets = initialBuckets;
renderServiceDetails(initialBuckets);
await assertGenericModalElements();
await assertS3SyncSpecificElements(initialBuckets);
renderServiceDetails();
const targetCombobox = screen.getAllByRole('combobox')[0];
const newBucketName = 'a-newly-added-bucket';
await addBucket(user, newBucketName);
fireEvent.change(targetCombobox, { target: { value: newBucketName } });
fireEvent.keyDown(targetCombobox, {
key: 'Enter',
code: 'Enter',
keyCode: 13,
});
await waitFor(() => {
expect(screen.getByLabelText(newBucketName)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /save/i })).not.toHaveAttribute(
'aria-disabled',
'true',
);
});
expect(
within(screen.getByTestId('s3-buckets-select-ap-south-1')).getByTitle(
newBucketName,
),
).toHaveTextContent(newBucketName);
await expect(
screen.findByTestId('cloud-service-save-btn'),
).resolves.not.toHaveAttribute('aria-disabled', 'true');
});
it('should send updated bucket configuration on save', async () => {
@@ -127,29 +106,13 @@ describe('ServiceDetails for S3 Sync service', () => {
return res(ctx.status(200), ctx.json({ message: 'Config updated' }));
}),
);
const user = userEvent.setup();
testInitialBuckets = initialBuckets;
renderServiceDetails(initialBuckets);
await assertGenericModalElements();
await assertS3SyncSpecificElements(initialBuckets);
renderServiceDetails();
const newBucketName = 'another-new-bucket';
const targetCombobox = screen.getAllByRole('combobox')[0];
fireEvent.change(targetCombobox, { target: { value: newBucketName } });
fireEvent.keyDown(targetCombobox, {
key: 'Enter',
code: 'Enter',
keyCode: 13,
});
await waitFor(() => {
expect(screen.getByLabelText(newBucketName)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /save/i })).not.toHaveAttribute(
'aria-disabled',
'true',
);
});
fireEvent.click(screen.getByRole('button', { name: /save/i }));
await addBucket(user, newBucketName);
await user.click(await screen.findByTestId('cloud-service-save-btn'));
await waitFor(() => {
expect(capturedPayload).not.toBeNull();
@@ -172,13 +135,8 @@ describe('ServiceDetails for S3 Sync service', () => {
});
it('should not render S3 bucket region selector UI for services other than s3sync', async () => {
testServiceId = 'ec2';
testInitialBuckets = {};
renderServiceDetails({}, 'ec2');
await waitFor(() => {
expect(
screen.queryByText(/select s3 buckets by region/i),
).not.toBeInTheDocument();
});
renderServiceDetails('ec2');
await screen.findByTestId('markdown-renderer');
expect(screen.queryByTestId('s3-buckets-selector')).not.toBeInTheDocument();
});
});

View File

@@ -1,58 +1,66 @@
import { render, RenderResult, screen, waitFor } from '@testing-library/react';
import { render, RenderResult, screen, within } from 'tests/test-utils';
import { IntegrationType } from 'container/Integrations/types';
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
import ServiceDetails from '../ServiceDetails/ServiceDetails';
import { accountsResponse } from './mockData';
import { accountsResponse, CLOUD_ACCOUNT_ID } from './mockData';
/**
* Renders ServiceDetails (inline config form). Tests must register MSW handlers
* for GET accounts and GET service details, and mock useUrlQuery (cloudAccountId, service).
* Renders ServiceDetails (inline config form) for the account and service in the
* URL. Tests must register MSW handlers for GET accounts and GET service details.
*/
const renderServiceDetails = (
_initialConfigLogsS3Buckets: Record<string, string[]> = {},
_serviceId = 's3sync',
serviceId = 's3sync',
type: IntegrationType = IntegrationType.AWS_SERVICES,
): RenderResult =>
render(
<MockQueryClientProvider>
<ServiceDetails type={type} />
</MockQueryClientProvider>,
);
render(<ServiceDetails type={type} />, undefined, {
initialRoute: `/?cloudAccountId=${CLOUD_ACCOUNT_ID}&service=${serviceId}`,
});
/**
* Asserts generic UI elements of the ServiceDetails config form (Overview tab).
*/
const assertGenericModalElements = async (): Promise<void> => {
await waitFor(() => {
expect(screen.getByRole('switch')).toBeInTheDocument();
expect(screen.getByText(/log collection/i)).toBeInTheDocument();
});
await expect(
screen.findByTestId('cloud-service-logs-switch'),
).resolves.toBeInTheDocument();
expect(screen.getByText(/log collection/i)).toBeInTheDocument();
};
/**
* Asserts S3 bucket selector section: title, region labels, and one combobox per region.
* Does not assert placeholder text (antd Select may not expose it as placeholder attribute).
* Asserts S3 bucket selector section: title, a select per account region, and
* the buckets already selected in each region.
*/
const assertS3SyncSpecificElements = async (
_expectedBucketsByRegion: Record<string, string[]> = {},
expectedBucketsByRegion: Record<string, string[]> = {},
): Promise<void> => {
const regions = accountsResponse.data.accounts[0]?.config?.aws?.regions || [];
await waitFor(() => {
expect(screen.getByText(/select s3 buckets by region/i)).toBeInTheDocument();
const selector = await screen.findByTestId('s3-buckets-selector');
expect(selector).toHaveTextContent(/select s3 buckets by region/i);
regions.forEach((region) => {
expect(screen.getByText(region)).toBeInTheDocument();
regions.forEach((region) => {
expect(selector).toHaveTextContent(region);
expect(screen.getByTestId(`s3-buckets-select-${region}`)).toBeInTheDocument();
});
Object.entries(expectedBucketsByRegion).forEach(([region, buckets]) => {
buckets.forEach((bucket) => {
expect(screen.getByTestId(`s3-buckets-select-${region}`)).toHaveTextContent(
bucket,
);
});
const comboboxes = screen.getAllByRole('combobox');
expect(comboboxes.length).toBeGreaterThanOrEqual(regions.length);
});
};
const bucketSelectInput = (region: string): HTMLElement =>
within(screen.getByTestId(`s3-buckets-select-${region}`)).getByRole(
'combobox',
{ hidden: true },
);
export {
assertGenericModalElements,
assertS3SyncSpecificElements,
bucketSelectInput,
renderServiceDetails,
};

View File

@@ -237,6 +237,7 @@ function CloudAccountSetupModal({
className="cloud-account-setup-form__form-item"
>
<Select
data-testid="azure-deployment-region-select"
placeholder="e.g. East US"
options={AZURE_REGIONS.map((region) => ({
label: `${region.label} (${region.value})`,
@@ -267,6 +268,7 @@ function CloudAccountSetupModal({
className="cloud-account-setup-form__form-item"
>
<Select
data-testid="azure-resource-groups-select"
mode="tags"
placeholder="e.g. prod-platform-rg"
tokenSeparators={[',']}

View File

@@ -1,5 +1,5 @@
import { ComponentProps } from 'react';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { rest, server } from 'mocks-server/server';
import { RestRequest } from 'msw';
import type logEvent from '../../../../../api/common/logEvent';
@@ -14,9 +14,6 @@ jest.mock('../../../../../api/common/logEvent', () => ({
default: jest.fn() as jest.MockedFunction<typeof logEvent>,
}));
// The form flow drives antd selects and typing, which outruns the 5s default on CI.
jest.setTimeout(15_000);
type OnClose = ComponentProps<typeof CloudAccountSetupModal>['onClose'];
const mockOnClose = (): jest.MockedFunction<OnClose> =>
@@ -84,26 +81,35 @@ const mockApi = ({ failFirstPoll = false } = {}): {
return api;
};
type User = ReturnType<typeof userEvent.setup>;
const antdSelectInput = (testId: string): HTMLElement =>
within(screen.getByTestId(testId)).getByRole('combobox', { hidden: true });
const generateCommand = async (user: User): Promise<void> => {
await screen.findByTestId('azure-deployment-region-select');
await user.click(antdSelectInput('azure-deployment-region-select'));
await user.click(await screen.findByText('Australia East (australiaeast)'));
await user.click(antdSelectInput('azure-resource-groups-select'));
// antd reads the legacy keyCode on Enter, which user-event leaves at 0, so
// commit the tag with the select's comma separator instead.
await user.paste('prod-platform-rg,');
await user.click(screen.getByTestId('azure-generate-command-btn'));
await screen.findByTestId('azure-agent-command');
};
describe('Azure CloudAccountSetupModal', () => {
it('creates the account and shows its setup command', async () => {
const api = mockApi();
const user = userEvent.setup();
const onClose = mockOnClose();
render(<CloudAccountSetupModal onClose={onClose} />);
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
const [region, resourceGroups] = await screen.findAllByRole('combobox');
await user.click(region);
await user.click(await screen.findByText('Australia East (australiaeast)'));
await user.type(resourceGroups, 'prod-platform-rg{Enter}');
await user.click(screen.getByTestId('azure-generate-command-btn'));
await waitFor(() => {
expect(screen.getByTestId('azure-agent-command')).toHaveTextContent(
cliCommand,
);
});
await generateCommand(user);
expect(screen.getByTestId('azure-agent-command')).toHaveTextContent(
cliCommand,
);
expect(api.createAccountPayload).toStrictEqual({
config: {
azure: {
@@ -116,10 +122,25 @@ describe('Azure CloudAccountSetupModal', () => {
expect(
screen.queryByTestId('azure-generate-command-btn'),
).not.toBeInTheDocument();
expect(screen.queryAllByRole('combobox')).toHaveLength(0);
expect(
screen.queryByTestId('azure-deployment-region-select'),
).not.toBeInTheDocument();
expect(
screen.queryByTestId('azure-resource-groups-select'),
).not.toBeInTheDocument();
expect(
screen.getByText(/waiting for azure account connection/i),
).toBeInTheDocument();
});
it('asks before closing once a setup command exists', async () => {
mockApi();
const user = userEvent.setup();
const onClose = mockOnClose();
render(<CloudAccountSetupModal onClose={onClose} />);
await generateCommand(user);
await user.click(screen.getByTestId('azure-cancel-btn'));
await user.click(await screen.findByTestId('azure-continue-setup-btn'));
@@ -154,11 +175,7 @@ describe('Azure CloudAccountSetupModal', () => {
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
const [region, resourceGroups] = await screen.findAllByRole('combobox');
await user.click(region);
await user.click(await screen.findByText('Australia East (australiaeast)'));
await user.type(resourceGroups, 'prod-platform-rg{Enter}');
await user.click(screen.getByTestId('azure-generate-command-btn'));
await generateCommand(user);
await user.click(await screen.findByTestId('azure-check-connection-btn'));

View File

@@ -25,14 +25,6 @@ jest.mock('../../../../../../../api/common/logEvent', () => ({
default: jest.fn(),
}));
jest.mock('@floating-ui/dom', () =>
jest.requireActual('../../../__tests__/floatingUiDomMock').floatingUiDomMock(),
);
// Opening the region Combobox inside the Drawer takes seconds in jsdom: Base UI
// walks every tabbable with getComputedStyle on each focus move.
jest.setTimeout(20000);
describe('GCP AgentSetup form', () => {
let api: AgentSetupApiMock;
@@ -59,7 +51,9 @@ describe('GCP AgentSetup form', () => {
expect(
screen.queryByTestId('gcp-account-name-input'),
).not.toBeInTheDocument();
expect(document.querySelector('#gcp-project-ids-select')).toBeNull();
expect(
screen.queryByTestId('gcp-project-ids-select'),
).not.toBeInTheDocument();
expect(screen.getByTestId('gcp-setup-guide-callout')).toHaveTextContent(
'SigNoz integration sets up everything needed',
);
@@ -161,10 +155,15 @@ describe('GCP AgentSetup form', () => {
});
it('locks the connection method and keeps the submitted project while the command is generating', async () => {
let releaseCreate = (): void => {};
const createHeld = new Promise<void>((resolve) => {
releaseCreate = resolve;
});
server.use(
rest.post(GCP_ACCOUNTS_URL, (_req, res, ctx) =>
res(ctx.delay(300), ctx.status(201), ctx.json(createAgentAccountResponse)),
),
rest.post(GCP_ACCOUNTS_URL, async (_req, res, ctx) => {
await createHeld;
return res(ctx.status(201), ctx.json(createAgentAccountResponse));
}),
);
const user = userEvent.setup();
renderAgentSetup();
@@ -173,16 +172,18 @@ describe('GCP AgentSetup form', () => {
await user.click(screen.getByTestId('gcp-generate-command-btn'));
await waitFor(() => {
expect(screen.getByRole('radiogroup')).toHaveAttribute(
expect(screen.getByTestId('gcp-connection-method')).toHaveAttribute(
'aria-disabled',
'true',
);
});
await user.type(
screen.getByTestId('gcp-deployment-project-id-input-field'),
'-edited',
const projectInput = screen.getByTestId(
'gcp-deployment-project-id-input-field',
);
await user.type(projectInput, '-edited');
expect(projectInput).toHaveValue(`${DEPLOYMENT_PROJECT_ID}-edited`);
releaseCreate();
const commands = await screen.findByTestId('gcp-agent-command');
expect(commands).toHaveTextContent(`signed in to ${DEPLOYMENT_PROJECT_ID}.`);

View File

@@ -21,14 +21,6 @@ jest.mock('../../../../../../../api/common/logEvent', () => ({
default: jest.fn(),
}));
jest.mock('@floating-ui/dom', () =>
jest.requireActual('../../../__tests__/floatingUiDomMock').floatingUiDomMock(),
);
// Opening the region Combobox inside the Drawer takes seconds in jsdom: Base UI
// walks every tabbable with getComputedStyle on each focus move.
jest.setTimeout(20000);
describe('GCP AgentSetup connection polling', () => {
beforeEach(() => {
jest.clearAllMocks();

Some files were not shown because too many files have changed in this diff Show More