Compare commits

..

2 Commits

Author SHA1 Message Date
Vinícius Lourenço
649c3a250c build(web): pin hashed asset names that the immutable cache relies on 2026-11-23 22:46:11 -03:00
Vinícius Lourenço
f7b1383427 perf(web): cache hashed frontend assets as immutable 2026-11-23 22:46:09 -03:00
337 changed files with 8294 additions and 11352 deletions

View File

@@ -9,14 +9,12 @@ 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. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check, which walks `getComputedStyle` up the tree on every action; never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
- **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`.
- **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 (`@floating-ui/dom`, `@testing-library/user-event` and antd's `collectScroller` in `jest.setup.ts`) or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
- **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`).
- **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.
- **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.
- **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.
- **No limit on tests per file.** Split a file when it mixes unrelated behaviour, not to hit a count.

View File

@@ -15,4 +15,3 @@ paths:
- When defining types, keep the structure of file to have any constants and variables first, then exported types and exported methods and then finally the unexported types and methods.
- Never import types or other modules in migration files, duplicate the required type or method to keep migration free from changes.
- Always run the gofmt tool for formating beforing commiting any changes.
- **Never copy through a pointer dereference** (`copied := *original`). It copies only the top level: pointer, slice and map fields stay shared, so changing the copy can change the original. Use the type's `Copy()` when it has one (`QueryBuilderFormula.Copy`); otherwise create a new struct literal from the fields you need. A `Copy()` itself may dereference, as long as it then replaces every pointer, slice and map field.

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.17 \
signoz/signoz-otel-collector:v0.144.16-rc.1 \
wiremock/wiremock:2.35.1-1 \
| xargs -P 0 -n 1 docker pull -q
- name: python

View File

@@ -85,18 +85,13 @@ jobs:
- wal
clickhouse-version:
- 25.12.5
- 26.8.34
signoz-otel-collector-version:
- v0.144.17
- v0.144.16-rc.1
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,14 +474,6 @@ 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

@@ -4523,114 +4523,6 @@ components:
required:
- name
type: object
DashboardtypesDistributionAxes:
properties:
x:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionXAxis'
description: The bucket axis.
"y":
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionYAxis'
description: The count axis.
type: object
DashboardtypesDistributionChartAppearance:
properties:
percentiles:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionPercentiles'
description: Percentile markers drawn across the bucket axis.
type: object
DashboardtypesDistributionPanelSpec:
properties:
axes:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionAxes'
description: The X (bucket) axis range and Y (count) axis scale.
chartAppearance:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionChartAppearance'
description: Percentile markers.
formatting:
allOf:
- $ref: '#/components/schemas/DashboardtypesPanelFormatting'
description: Unit and decimal precision of the bucket bounds; counts take
no unit.
legend:
allOf:
- $ref: '#/components/schemas/DashboardtypesLegend'
description: Legend placement and series colors.
visualization:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionVisualization'
description: The time range the bucket counts are summed over, and how groups
stack.
type: object
DashboardtypesDistributionPercentiles:
properties:
enabled:
description: Whether percentile markers are drawn. Null draws them.
nullable: true
type: boolean
values:
description: The percentiles to mark, each in (0, 100), at most 5, no duplicates.
Null means [50, 90, 99]; [] marks none.
items:
format: double
type: number
nullable: true
type: array
type: object
DashboardtypesDistributionStackMode:
enum:
- none
- normal
- percent
type: string
DashboardtypesDistributionVisualization:
properties:
stack:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionStackMode'
description: 'How groups combine in a bucket: normal (default) stacks them,
none draws them side by side, percent stacks them as shares of the bucket.'
timePreference:
allOf:
- $ref: '#/components/schemas/DashboardtypesTimePreference'
description: 'The time range the panel queries: global_time (default) follows
the dashboard range; last_5_min, last_15_min, last_30_min, last_1_hr,
last_6_hr, last_1_day, last_3_days, last_1_week or last_1_month pin a
fixed window.'
required:
- stack
type: object
DashboardtypesDistributionXAxis:
properties:
max:
description: Buckets wholly above this value are hidden. Null shows them
all.
nullable: true
type: number
min:
description: Buckets wholly below this value are hidden. Null shows them
all.
nullable: true
type: number
type: object
DashboardtypesDistributionYAxis:
properties:
scale:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionYScale'
description: 'How counts are spaced: linear (default) or log.'
required:
- scale
type: object
DashboardtypesDistributionYScale:
enum:
- linear
- log
type: string
DashboardtypesDynamicVariableSignal:
enum:
- traces
@@ -5626,7 +5518,6 @@ components:
mapping:
signoz/AreaChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec'
signoz/BarChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec'
signoz/DistributionPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec'
signoz/GeoMapPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
signoz/HeatmapPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
signoz/HistogramPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec'
@@ -5653,7 +5544,6 @@ components:
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec'
type: object
DashboardtypesPanelPluginKind:
enum:
@@ -5670,7 +5560,6 @@ components:
- signoz/ScatterPlotPanel
- signoz/GeoMapPanel
- signoz/TopListPanel
- signoz/DistributionPanel
type: string
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
properties:
@@ -5702,21 +5591,6 @@ components:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec:
properties:
kind:
description: The panel kind.
enum:
- signoz/DistributionPanel
type: string
spec:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionPanelSpec'
description: The options for this panel kind. {} accepts every default.
required:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec:
properties:
kind:
@@ -5900,9 +5774,9 @@ components:
- $ref: '#/components/schemas/DashboardtypesPanelPlugin'
description: 'The visualization: kind is one of signoz/TimeSeriesPanel,
signoz/BarChartPanel, signoz/AreaChartPanel, signoz/NumberPanel, signoz/PieChartPanel,
signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel,
signoz/HeatmapPanel or signoz/DistributionPanel, and spec holds that kind''s
options ({} accepts every default).'
signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel
or signoz/HeatmapPanel, and spec holds that kind''s options ({} accepts
every default).'
queries:
description: The queries the panel runs. Use exactly one entry for a data
panel and [] for signoz/TextPanel. To run several named queries or formulas,
@@ -6038,8 +5912,8 @@ components:
- $ref: '#/components/schemas/Querybuildertypesv5RequestType'
description: 'The result shape the panel requests: time_series for time
series, bar, area and histogram panels, scalar for number, table and pie
panels, raw for list panels, heatmap for heatmap panels, distribution
for distribution panels, trace for trace panels.'
panels, raw for list panels, heatmap for heatmap panels, trace for trace
panels.'
spec:
allOf:
- $ref: '#/components/schemas/DashboardtypesQuerySpec'
@@ -6196,9 +6070,9 @@ components:
(builder query over AI observability traces), signoz/CompositeQuery (several
named queries and formulas), signoz/Formula, signoz/PromQLQuery, signoz/ClickHouseSQL
or signoz/TraceOperator, and spec holds that kind''s query. Pie and table
panels reject signoz/PromQLQuery; heatmap and distribution panels reject
signoz/AIBuilderQuery and signoz/TraceOperator; list panels accept only
signoz/BuilderQuery and signoz/AIBuilderQuery.'
panels reject signoz/PromQLQuery; heatmap panels reject signoz/AIBuilderQuery
and signoz/TraceOperator; list panels accept only signoz/BuilderQuery
and signoz/AIBuilderQuery.'
required:
- plugin
type: object
@@ -16400,22 +16274,13 @@ paths:
where it is case-sensitive and % and _ act as wildcards. For keys, a context
prefix such as resource.service.name sets fieldContext when it is empty.'
type: string
- description: 'The key whose values to return, such as service.name. With fieldContext
set, it is the stored name as is. Otherwise a context prefix such as resource.service.name
sets the context and a type suffix such as service.name:string sets fieldDataType
when that is empty; as in filter expressions, a prefixed name also matches
a key stored under the full name, whose values come first: log.level returns
values of a key named log.level, then of the log field level.'
- description: The key whose values to return, such as service.name. A context
prefix such as resource.service.name sets fieldContext when it is empty.
in: query
name: name
schema:
description: 'The key whose values to return, such as service.name. With
fieldContext set, it is the stored name as is. Otherwise a context prefix
such as resource.service.name sets the context and a type suffix such
as service.name:string sets fieldDataType when that is empty; as in filter
expressions, a prefixed name also matches a key stored under the full
name, whose values come first: log.level returns values of a key named
log.level, then of the log field level.'
description: The key whose values to return, such as service.name. A context
prefix such as resource.service.name sets fieldContext when it is empty.
type: string
- description: Filter expression already applied in the explorer. When set,
relatedValues lists the values seen on data matching it.
@@ -29062,22 +28927,13 @@ paths:
where it is case-sensitive and % and _ act as wildcards. For keys, a context
prefix such as resource.service.name sets fieldContext when it is empty.'
type: string
- description: 'The key whose values to return, such as service.name. With fieldContext
set, it is the stored name as is. Otherwise a context prefix such as resource.service.name
sets the context and a type suffix such as service.name:string sets fieldDataType
when that is empty; as in filter expressions, a prefixed name also matches
a key stored under the full name, whose values come first: log.level returns
values of a key named log.level, then of the log field level.'
- description: The key whose values to return, such as service.name. A context
prefix such as resource.service.name sets fieldContext when it is empty.
in: query
name: name
schema:
description: 'The key whose values to return, such as service.name. With
fieldContext set, it is the stored name as is. Otherwise a context prefix
such as resource.service.name sets the context and a type suffix such
as service.name:string sets fieldDataType when that is empty; as in filter
expressions, a prefixed name also matches a key stored under the full
name, whose values come first: log.level returns values of a key named
log.level, then of the log field level.'
description: The key whose values to return, such as service.name. A context
prefix such as resource.service.name sets fieldContext when it is empty.
type: string
- description: Filter expression already applied in the explorer. When set,
relatedValues lists the values seen on data matching it.

View File

@@ -2,10 +2,7 @@ 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"
@@ -13,7 +10,6 @@ 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"
@@ -43,25 +39,13 @@ 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).
opts := []kgo.Opt{
client, err := kgo.NewClient(
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
}
@@ -146,30 +130,3 @@ 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

@@ -1,269 +0,0 @@
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** at the gate in `AGENTS.md` (commit, push or PR), not after each edit; skip it while the user says `no checks`:
5. **Verify** before reporting done:
```bash
pnpm tsgo --noEmit
pnpm oxlint src/pages/<Feature>

3
frontend/.gitignore vendored
View File

@@ -1,4 +1,7 @@
# Vite copies public/ unhashed, and the Go server caches /assets/ as immutable
/public/assets/
# Sentry Config File
.env.sentry-build-plugin
.qodo

View File

@@ -28,24 +28,20 @@ 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.
- 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.
- 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.
- 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. 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:
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:
- 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, and that each test runs under 500 ms (`pnpm jest <file> --verbose`)
- For every test you added or changed, revert the change it covers and confirm the test fails
- 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 `--{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)
- [ ] 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
- [ ] No ID selectors
- [ ] No bare element selectors
- [ ] Keyframes are declared in the module with plain `@keyframes name` (already local)
- [ ] Keyframes use `:local(@keyframes name)` to avoid global collisions
## Config (vite.config.ts)
@@ -77,7 +77,7 @@ css: {
// BAD: Nesting creates separate classes you might not expect
.button {
.icon { } // -> styles.icon, but the rule is `.button .icon`: it only matches inside .button
.icon { } // -> styles.icon (separate class, not scoped under .button)
}
// GOOD: Flat structure
@@ -289,32 +289,88 @@ Use L1/L2/L3 semantic tokens - they handle light/dark theme automatically.
- L2 = elevated surfaces (cards, panels)
- L3 = nested/inset elements
## @signozhq/ui Components
## Overriding @signozhq/ui Components
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.
Components expose CSS variables for customization.
- 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.
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:
```scss
// BAD: Restyling the component
.saveButton {
--button-primary-background-color: var(--success-background);
// 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);
}
.toolbar :global([data-variant="outlined"]) {
--button-variant-outlined-border: 1px solid var(--accent-primary);
// 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);
}
// GOOD: Layout on your own wrapper, looks from props
.toolbarActions {
display: flex;
gap: var(--spacing-4);
margin-left: auto;
// Override nested parts
.customInput {
--input-prefix-padding: 0 var(--spacing-4) 0 var(--spacing-6);
--input-suffix-color: var(--accent-primary);
}
```
### 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
@@ -378,21 +434,24 @@ Don't override them. That covers setting a component's `--<component>-*` CSS var
### Keyframes (Local Scoping)
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`.
Without `:local()`, keyframe names are global and can clash across modules:
```scss
// GOOD: Local to this module
// BAD: Global keyframe - can conflict with other modules
@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

@@ -6,14 +6,12 @@ const LOG_EVENT_MOCK_PATH = '<rootDir>/src/__tests__/logEventMock.ts';
const config: Config.InitialOptions = {
silent: true,
// CI runners are slow enough that multi-step userEvent tests pass 5s.
testTimeout: 10000,
clearMocks: true,
coverageDirectory: 'coverage',
coverageReporters: ['text', 'cobertura', 'html', 'json-summary'],
collectCoverageFrom: ['src/**/*.{ts,tsx}'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
modulePathIgnorePatterns: ['<rootDir>/dist/'],
modulePathIgnorePatterns: ['dist'],
moduleNameMapper: {
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff)$':
'<rootDir>/__mocks__/fileMock.ts',
@@ -69,8 +67,6 @@ 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

@@ -137,8 +137,6 @@ window.getComputedStyle = function (
return {
display: '',
visibility: '',
width: '',
height: '',
opacity: '1',
animationName: 'none',
getPropertyValue: () => '',
@@ -146,39 +144,6 @@ window.getComputedStyle = function (
}
};
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
// popover ancestor costs up to ~1 s per open.
jest.mock('@floating-ui/dom', () => ({
...jest.requireActual('@floating-ui/dom'),
autoUpdate: (): (() => void) => (): void => {},
computePosition: (
_reference: unknown,
_floating: unknown,
{ placement = 'bottom', strategy = 'absolute' } = {},
): Promise<unknown> =>
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
}));
jest.mock('@testing-library/user-event', () =>
jest.requireActual('tests/userEventWithDefaults'),
);
// antd popups walk getComputedStyle up every ancestor to find scroll
// containers on each open. pnpm keeps the package under antd, not at the root.
jest.mock(
require.resolve('@rc-component/trigger/lib/util', {
paths: [require.resolve('antd')],
}),
() => ({
...jest.requireActual(
require.resolve('@rc-component/trigger/lib/util', {
paths: [require.resolve('antd')],
}),
),
collectScroller: (): HTMLElement[] => [],
}),
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());

View File

@@ -56,7 +56,6 @@
"@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,9 +82,6 @@ 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)
@@ -3251,13 +3248,6 @@ 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:
@@ -12383,12 +12373,6 @@ 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

@@ -321,8 +321,8 @@ const createTracesResponse = ({
httpMethod: trace.httpMethod ?? httpMethods[index % httpMethods.length],
responseStatusCode:
trace.responseStatusCode ?? statusCodes[index % statusCodes.length],
trace_id: `trace-id-${index}`,
span_id: `span-id-${index}`,
traceID: `trace-id-${index}`,
spanID: `span-id-${index}`,
},
};
})
@@ -340,8 +340,8 @@ const createTracesResponse = ({
durationNano: 1000000 + cumulativeIndex * 100000,
httpMethod: httpMethods[cumulativeIndex % httpMethods.length],
responseStatusCode: statusCodes[cumulativeIndex % statusCodes.length],
trace_id: `trace-id-${cumulativeIndex}`,
span_id: `span-id-${cumulativeIndex}`,
traceID: `trace-id-${cumulativeIndex}`,
spanID: `span-id-${cumulativeIndex}`,
},
};
},

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
* `@signozhq/noz-client`.
* `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`.
* 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 '@signozhq/noz-client';
} from './sigNozAIAssistantAPI.schemas';
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

@@ -15619,7 +15619,7 @@ export type GetFieldsValuesParams = {
searchText?: string;
/**
* @type string
* @description The key whose values to return, such as service.name. With fieldContext set, it is the stored name as is. Otherwise a context prefix such as resource.service.name sets the context and a type suffix such as service.name:string sets fieldDataType when that is empty; as in filter expressions, a prefixed name also matches a key stored under the full name, whose values come first: log.level returns values of a key named log.level, then of the log field level.
* @description The key whose values to return, such as service.name. A context prefix such as resource.service.name sets fieldContext when it is empty.
*/
name?: string;
/**
@@ -17236,7 +17236,7 @@ export type GetRuleHistoryFilterValuesParams = {
searchText?: string;
/**
* @type string
* @description The key whose values to return, such as service.name. With fieldContext set, it is the stored name as is. Otherwise a context prefix such as resource.service.name sets the context and a type suffix such as service.name:string sets fieldDataType when that is empty; as in filter expressions, a prefixed name also matches a key stored under the full name, whose values come first: log.level returns values of a key named log.level, then of the log field level.
* @description The key whose values to return, such as service.name. A context prefix such as resource.service.name sets fieldContext when it is empty.
*/
name?: string;
/**

View File

@@ -21,7 +21,6 @@ import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import {
convertBuilderQueriesToV5,
createAggregation,
mapPanelTypeToRequestType,
prepareQueryRangePayloadV5,
} from './prepareQueryRangePayloadV5';
@@ -1016,47 +1015,3 @@ describe('convertBuilderQueriesToV5 builder query type', () => {
expect(buildEnvelope(builderQueryType, 'trace').type).toBe('builder_query');
});
});
describe('createAggregation fallback', () => {
const logsQuery = (expression: string): Partial<IBuilderQuery> => ({
dataSource: DataSource.LOGS,
aggregations: [{ expression }],
});
it('sends no aggregation for a heatmap with no field', () => {
expect(createAggregation(logsQuery(''), PANEL_TYPES.HEATMAP)).toStrictEqual(
[],
);
});
it('reads a field on a heatmap and turns it into count() elsewhere', () => {
expect(
createAggregation(logsQuery('duration_nano'), PANEL_TYPES.HEATMAP),
).toStrictEqual([{ expression: 'duration_nano' }]);
expect(
createAggregation(logsQuery('duration_nano'), PANEL_TYPES.TIME_SERIES),
).toStrictEqual([{ expression: 'count()' }]);
});
it('still defaults other panels to count()', () => {
expect(
createAggregation(logsQuery(''), PANEL_TYPES.TIME_SERIES),
).toStrictEqual([{ expression: 'count()' }]);
});
it('sends the field of a logs heatmap query', () => {
const [envelope] = convertBuilderQueriesToV5(
{
A: {
...logsQuery('duration_nano'),
queryName: 'A',
} as IBuilderQuery,
},
mapPanelTypeToRequestType(PANEL_TYPES.HEATMAP),
PANEL_TYPES.HEATMAP,
);
expect((envelope.spec as LogBuilderQuery).aggregations).toStrictEqual([
{ expression: 'duration_nano' },
]);
});
});

View File

@@ -5,8 +5,6 @@ import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { foldAISlot } from 'lib/query/builderSlot';
import getStartEndRangeTime from 'lib/getStartEndRangeTime';
import { parseAggregations } from 'lib/query/aggregationExpression';
import { aggregatesDistributionField } from 'lib/query/distributionField';
import { mapQueryDataToApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi';
import { isEmpty } from 'lodash-es';
import { DynamicVariableSuggestion } from 'providers/Dashboard/store/dynamicVariableSuggestions';
@@ -242,6 +240,32 @@ function createBaseSpec(
};
}
// Utility to parse aggregation expressions with optional alias
export function parseAggregations(
expression: string,
availableAlias?: string,
): { expression: string; alias?: string }[] {
const result: { expression: string; alias?: string }[] = [];
// Matches function calls like "count()" or "sum(field)" with optional alias like "as 'alias'"
// Handles quoted ('alias'), dash-separated (field-name), and unquoted values after "as" keyword
const regex =
/([a-zA-Z0-9_]+\([^)]*\))(?:\s*as\s+((?:'[^']*'|"[^"]*"|[a-zA-Z0-9_-]+)))?/g;
let match = regex.exec(expression);
while (match !== null) {
const expr = match[1];
let alias = match[2] || availableAlias; // Use provided alias or availableAlias if not matched
if (alias) {
// Remove quotes if present
alias = alias.replace(/^['"]|['"]$/g, '');
result.push({ expression: expr, alias });
} else {
result.push({ expression: expr });
}
match = regex.exec(expression);
}
return result;
}
export function createAggregation(
queryData: any,
panelType?: PANEL_TYPES,
@@ -286,28 +310,18 @@ export function createAggregation(
];
}
// A heatmap buckets the field the user names; count() would be rejected as one.
// Elsewhere a field is not an aggregation, so it falls back to count().
const isDistributionField = aggregatesDistributionField(
panelType,
queryData.dataSource,
);
const fallback = isDistributionField ? [] : [{ expression: 'count()' }];
if (queryData.aggregations?.length > 0) {
return queryData.aggregations.flatMap(
(agg: { expression: string; alias?: string }) => {
const parsedAggregations = parseAggregations(
agg.expression,
agg?.alias,
isDistributionField,
);
return isEmpty(parsedAggregations) ? fallback : parsedAggregations;
const parsedAggregations = parseAggregations(agg.expression, agg?.alias);
return isEmpty(parsedAggregations)
? [{ expression: 'count()' }]
: parsedAggregations;
},
);
}
return fallback;
return [{ expression: 'count()' }];
}
/**

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,8 +1,5 @@
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';
@@ -55,12 +52,3 @@ 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

@@ -31,7 +31,7 @@ interface Props {
placeholder?: string;
// Rendered at the end of the search row (e.g. the New Dashboard action).
rightSlot?: ReactNode;
// Rendered in the filters row before the chips. A function receives the draft.
// Rendered in the filters row after the chips. A function receives the draft.
extraFilters?: ReactNode | ((api: ExtraFiltersApi) => ReactNode);
// Shows Clear even when the query is empty.
hasExtraFilters?: boolean;
@@ -142,9 +142,6 @@ function FilterZone({
className={styles.filterControls}
data-testid={`${testIdPrefix}-filter-zone`}
>
{typeof extraFilters === 'function'
? extraFilters({ draft, applyDraft, setDraft })
: extraFilters}
<FilterChips
{...createdByProps}
updated={reflected.updated}
@@ -153,6 +150,9 @@ function FilterZone({
onApply={run}
disabled={disabled}
/>
{typeof extraFilters === 'function'
? extraFilters({ draft, applyDraft, setDraft })
: extraFilters}
{(!isEmpty || hasExtraFilters) && (
<Button
disabledTooltip={undefined}

View File

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

View File

@@ -1,10 +1,4 @@
import {
type FocusEvent,
type MouseEvent,
useCallback,
useMemo,
useRef,
} from 'react';
import { type MouseEvent, useCallback, useMemo, useRef } from 'react';
import {
autocompletion,
closeCompletion,
@@ -33,7 +27,7 @@ import styles from './SearchBar.module.scss';
interface Props {
value: string;
grammar: DslGrammar;
// Ids: `${testIdPrefix}`, `-field` (the editable area), `-submit`, `-dirty`.
// Ids: `${testIdPrefix}`, `-submit`, `-dirty`.
testIdPrefix: string;
onChange: (value: string) => void;
onSubmit: () => void;
@@ -73,25 +67,10 @@ function SearchBar({
const onSubmitRef = useRef(handleSubmit);
onSubmitRef.current = handleSubmit;
// Leaving the box runs an unrun draft, e.g. terms picked from the suggestions.
// A blur from switching windows or tabs does not.
const handleBlur = useCallback(
(event: FocusEvent<HTMLDivElement>): void => {
const stillInside = event.currentTarget.contains(
event.relatedTarget as Node | null,
);
if (!stillInside && dirty && !disabled && document.hasFocus()) {
handleSubmit();
}
},
[dirty, disabled, handleSubmit],
);
const extensions = useMemo(
() => [
dslHighlight,
editorTheme,
EditorView.contentAttributes.of({ 'data-testid': `${testIdPrefix}-field` }),
// Wrap a long query onto the next line instead of scrolling horizontally.
EditorView.lineWrapping,
// Read-only is not enough: these open the list on click and accepting an
@@ -143,15 +122,12 @@ function SearchBar({
]),
),
],
[disabled, testIdPrefix],
[disabled],
);
return (
<div className={styles.wrapper}>
<div
className={cx(styles.field, { [styles.disabled]: disabled })}
onBlur={handleBlur}
>
<div className={cx(styles.field, { [styles.disabled]: disabled })}>
<Search
size={12}
color={Color.BG_VANILLA_400}

View File

@@ -1,101 +0,0 @@
import type { ComponentProps } from 'react';
import { render, screen, userEvent } from 'tests/test-utils';
import type { DslGrammar } from '../../dsl/types';
import SearchBar from '../SearchBar';
type SearchBarProps = ComponentProps<typeof SearchBar>;
const GRAMMAR: DslGrammar = {
fields: [{ key: 'name', type: 'string' }],
dynamicKey: { detail: 'tag', prefix: '' },
};
function renderSearchBar(props: { dirty: boolean; disabled?: boolean }): {
onSubmit: jest.MockedFunction<SearchBarProps['onSubmit']>;
onSubmitted: jest.MockedFunction<NonNullable<SearchBarProps['onSubmitted']>>;
} {
const onSubmit = jest.fn() as jest.MockedFunction<SearchBarProps['onSubmit']>;
const onSubmitted = jest.fn() as jest.MockedFunction<
NonNullable<SearchBarProps['onSubmitted']>
>;
render(
<>
<SearchBar
value="name = 'x'"
grammar={GRAMMAR}
testIdPrefix="list-search"
onChange={jest.fn()}
onSubmit={onSubmit}
onSubmitted={onSubmitted}
dirty={props.dirty}
disabled={props.disabled}
/>
<button type="button" data-testid="outside">
outside
</button>
</>,
);
return { onSubmit, onSubmitted };
}
function searchContent(): HTMLElement {
return screen
.getByTestId('list-search')
.querySelector('.cm-content') as HTMLElement;
}
describe('SearchBar — run on blur', () => {
let hasFocus: jest.SpyInstance<boolean, []>;
beforeEach(() => {
// jsdom reports no focus once it leaves the editor; a focused browser window does.
hasFocus = jest.spyOn(document, 'hasFocus').mockReturnValue(true);
});
afterEach(() => {
jest.restoreAllMocks();
});
it('runs an unrun draft when focus leaves the box', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const { onSubmit, onSubmitted } = renderSearchBar({ dirty: true });
await user.click(searchContent());
await user.click(screen.getByTestId('outside'));
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmitted).toHaveBeenCalledWith(true);
});
it('does nothing when the draft was already run', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const { onSubmit } = renderSearchBar({ dirty: false });
await user.click(searchContent());
await user.click(screen.getByTestId('outside'));
expect(onSubmit).not.toHaveBeenCalled();
});
it('does nothing when focus leaves the window', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const { onSubmit } = renderSearchBar({ dirty: true });
await user.click(searchContent());
hasFocus.mockReturnValue(false);
await user.click(screen.getByTestId('outside'));
expect(onSubmit).not.toHaveBeenCalled();
});
it('runs once when Run query is clicked with an unrun draft', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const { onSubmit } = renderSearchBar({ dirty: true });
await user.click(searchContent());
await user.click(screen.getByTestId('list-search-submit'));
expect(onSubmit).toHaveBeenCalledTimes(1);
});
});

View File

@@ -1,15 +0,0 @@
.headerZone {
// Sticks to the top of a scrolling list so the heading and filters stay put
// while results scroll beneath. The DSL suggestion popup (z-index 1000) still
// layers above it.
position: sticky;
top: 0;
z-index: 10;
display: flex;
flex-direction: column;
flex-shrink: 0;
gap: 14px;
padding: 20px 24px;
background: var(--l2-background);
border-bottom: 1px solid var(--l2-border);
}

View File

@@ -1,19 +0,0 @@
import type { ReactNode } from 'react';
import styles from './ListHeaderZone.module.scss';
interface Props {
/** Rendered regardless of whether the list has anything in it. */
children: ReactNode;
testId?: string;
}
function ListHeaderZone({ children, testId }: Props): JSX.Element {
return (
<div className={styles.headerZone} data-testid={testId}>
{children}
</div>
);
}
export default ListHeaderZone;

View File

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

View File

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

View File

@@ -106,10 +106,8 @@ function QueryAddOns({
if (
panelType === PANEL_TYPES.HEATMAP &&
!(
query.dataSource === DataSource.METRICS &&
HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')
)
query.dataSource === DataSource.METRICS &&
!HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')
) {
addOns = [...addOns, BUCKET_OPTIONS];
}
@@ -438,7 +436,6 @@ function QueryAddOns({
onChange={handleChangeOrderByKeys}
isRawQuery={isRawQuery}
isNewQueryV2
panelType={panelType ?? undefined}
placeholder={placeholderOf(QueryBuilderField.OrderBy)}
/>
</div>

View File

@@ -107,8 +107,8 @@ export const BASE_ADD_ONS = (
export const REDUCE_TO = toAddOn(QueryBuilderField.ReduceTo);
// Offered only by a heatmap: the bucket axis is what a heatmap plots against, and no
// other panel type sends one. A histogram metric brings its own buckets.
// Offered only by a heatmap over metrics: the bucket axis is what a heatmap plots
// against, and no other panel type sends one. A histogram brings its own buckets.
export const HISTOGRAM_ATTRIBUTE_TYPES = new Set<string>([
ATTRIBUTE_TYPES.HISTOGRAM,
ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM,

View File

@@ -1,5 +0,0 @@
// Fills the row like the filter and Group By boxes.
.select {
flex: 1;
min-width: 400px;
}

View File

@@ -1,69 +0,0 @@
import { useMemo, useState } from 'react';
import { Combobox } from '@signozhq/ui/combobox';
import { TelemetrytypesFieldDataTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
import useDebounce from 'hooks/useDebounce';
import { getDistributionFieldPlaceholder } from 'lib/query/distributionField';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { DATA_SOURCE_TO_SIGNAL } from 'types/common/queryBuilder';
import { toDistributionFieldOptions } from './distributionFieldOptions';
import Styles from './DistributionFieldSelect.module.scss';
/** A logs or traces heatmap's aggregation: the one numeric field it buckets. */
export default function DistributionFieldSelect({
queryData,
onChange,
}: {
queryData: IBuilderQuery;
onChange?: (field: string) => void;
}): JSX.Element {
const [search, setSearch] = useState('');
const searchText = useDebounce(search, DEBOUNCE_DELAY);
// The keys API caps its answer, so a field past the cap is reached by searching.
const {
data: fieldKeys,
isLoading,
isFetching,
} = useFieldKeysSuggestion(
{
signal: DATA_SOURCE_TO_SIGNAL[queryData.dataSource],
searchText,
fieldDataType: TelemetrytypesFieldDataTypeDTO.number,
},
queryData.builderQueryType,
{ keepPreviousData: true },
);
const [aggregation] = queryData.aggregations ?? [];
const selectedField =
aggregation && 'expression' in aggregation ? aggregation.expression : '';
const items = useMemo(
() => toDistributionFieldOptions(fieldKeys ?? [], selectedField),
[fieldKeys, selectedField],
);
return (
<div className={Styles.select}>
<Combobox
items={items}
value={selectedField || undefined}
onChange={(field): void => onChange?.(field ?? '')}
allowClear
placeholder={getDistributionFieldPlaceholder(queryData.dataSource)}
searchInputProps={{
placeholder: 'Search numeric fields',
loading: isFetching,
onChange: setSearch,
}}
loading={isLoading}
noContent="No numeric fields"
testId="distribution-field-select"
/>
</div>
);
}

View File

@@ -6,7 +6,6 @@ import {
IBuilderQuery,
IBuilderTraceOperator,
} from 'types/api/queryBuilder/queryBuilderData';
import { aggregatesDistributionField } from 'lib/query/distributionField';
import { DataSource } from 'types/common/queryBuilder';
import {
@@ -20,7 +19,6 @@ import {
} from '../../queryBuilderFields.utils';
import { isScalarPanelType } from '../panelTypes';
import DistributionFieldSelect from './DistributionFieldSelect';
import QueryAggregationSelect from './QueryAggregationSelect';
import './QueryAggregation.styles.scss';
@@ -65,21 +63,17 @@ function QueryAggregationOptions({
data-testid="query-aggregation-container"
>
<div className="aggregation-container">
{aggregatesDistributionField(panelType, dataSource) ? (
<DistributionFieldSelect queryData={queryData} onChange={onChange} />
) : (
<QueryAggregationSelect
onChange={onChange}
queryData={queryData}
maxAggregations={
panelType === PANEL_TYPES.VALUE ||
panelType === PANEL_TYPES.PIE ||
panelType === PANEL_TYPES.TOP_LIST
? 1
: undefined
}
/>
)}
<QueryAggregationSelect
onChange={onChange}
queryData={queryData}
maxAggregations={
panelType === PANEL_TYPES.VALUE ||
panelType === PANEL_TYPES.PIE ||
panelType === PANEL_TYPES.TOP_LIST
? 1
: undefined
}
/>
{!stepInterval.hidden && (
<div className="query-aggregation-interval">

View File

@@ -1,163 +0,0 @@
import {
TelemetrytypesFieldContextDTO,
TelemetrytypesFieldDataTypeDTO,
TelemetrytypesSignalDTO,
type GetFieldsKeys200,
} from 'api/generated/services/sigNoz.schemas';
import { ENVIRONMENT } from 'constants/env';
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
import { initialQueriesMap } from 'constants/queryBuilder';
import { rest, server } from 'mocks-server/server';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import DistributionFieldSelect from '../DistributionFieldSelect';
const keysResponse: GetFieldsKeys200 = {
status: 'success',
data: {
complete: true,
keys: {
duration_nano: [
{
name: 'duration_nano',
fieldContext: TelemetrytypesFieldContextDTO.span,
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
signal: TelemetrytypesSignalDTO.traces,
},
],
quantity: [
{
name: 'quantity',
fieldContext: TelemetrytypesFieldContextDTO.attribute,
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
signal: TelemetrytypesSignalDTO.traces,
},
],
},
},
};
const tracesQuery = (expression: string): IBuilderQuery => ({
...(initialQueriesMap.traces.builder.queryData[0] as IBuilderQuery),
aggregations: [{ expression }],
});
describe('DistributionFieldSelect', () => {
const requests: URLSearchParams[] = [];
afterEach(() => {
jest.useRealTimers();
});
beforeEach(() => {
requests.length = 0;
server.use(
rest.get(`${ENVIRONMENT.baseURL}/api/v1/fields/keys`, (req, res, ctx) => {
requests.push(req.url.searchParams);
return res(ctx.status(200), ctx.json(keysResponse));
}),
);
});
it('shows the saved field', () => {
render(
<DistributionFieldSelect
queryData={tracesQuery('duration_nano')}
onChange={jest.fn()}
/>,
);
expect(screen.getByTestId('distribution-field-select')).toHaveTextContent(
'duration_nano',
);
});
it('picks a numeric field, keeping its context', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
render(
<DistributionFieldSelect queryData={tracesQuery('')} onChange={onChange} />,
);
await user.click(screen.getByTestId('distribution-field-select'));
await screen.findByTestId(
'distribution-field-select-item-attribute.quantity',
);
await user.type(
screen.getByTestId('distribution-field-select-search'),
'attribute.quantity{Enter}',
);
expect(onChange).toHaveBeenCalledWith('attribute.quantity');
expect(requests[0].get('fieldDataType')).toBe(
TelemetrytypesFieldDataTypeDTO.number,
);
expect(requests[0].get('signal')).toBe('traces');
});
it('replaces the saved field with the newly picked one', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
render(
<DistributionFieldSelect
queryData={tracesQuery('duration_nano')}
onChange={onChange}
/>,
);
await user.click(screen.getByTestId('distribution-field-select'));
await screen.findByTestId(
'distribution-field-select-item-attribute.quantity',
);
await user.type(
screen.getByTestId('distribution-field-select-search'),
'attribute.quantity{Enter}',
);
expect(onChange).toHaveBeenCalledWith('attribute.quantity');
});
it('only offers listed fields: typed text is a filter, not a value', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
render(
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
);
await user.click(screen.getByTestId('distribution-field-select'));
await screen.findByTestId(
'distribution-field-select-item-attribute.quantity',
);
await user.type(
screen.getByTestId('distribution-field-select-search'),
'no_such_field',
);
await screen.findByText('No numeric fields');
expect(
screen.queryByTestId('distribution-field-select-item-no_such_field'),
).not.toBeInTheDocument();
});
it('searches the server for typed text, past the listed fields', async () => {
jest.useFakeTimers();
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
pointerEventsCheck: 0,
});
render(
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
);
await user.click(screen.getByTestId('distribution-field-select'));
await user.type(
await screen.findByTestId('distribution-field-select-search'),
'queue',
);
act(() => {
jest.advanceTimersByTime(DEBOUNCE_DELAY);
});
await waitFor(() => expect(requests.at(-1)?.get('searchText')).toBe('queue'));
});
});

View File

@@ -1,84 +0,0 @@
import { TelemetrytypesFieldContextDTO as FieldContext } from 'api/generated/services/sigNoz.schemas';
import {
toDistributionFieldOptions,
toDistributionFieldText,
} from '../distributionFieldOptions';
const key = (
name: string,
fieldContext: FieldContext,
): { name: string; fieldContext: FieldContext } => ({ name, fieldContext });
const KEYS = [
key('quantity', FieldContext.resource),
key('duration_nano', FieldContext.span),
key('quantity', FieldContext.attribute),
key('total_tokens', FieldContext.trace),
key('latency', FieldContext.body),
key('duration_nano', FieldContext.span),
];
describe('toDistributionFieldText', () => {
it.each([
[key('duration_nano', FieldContext.span), 'duration_nano'],
[key('severity_number', FieldContext.log), 'severity_number'],
[
key('http.status_code', FieldContext.attribute),
'attribute.http.status_code',
],
[key('latency', FieldContext.body), 'body.latency'],
])('%j → %s', (fieldKey, text) => {
expect(toDistributionFieldText(fieldKey)).toBe(text);
});
});
const item = (
text: string,
): { type: 'item'; label: string; value: string } => ({
type: 'item',
label: text,
value: text,
});
describe('toDistributionFieldOptions', () => {
it('groups columns first, keeps contexts apart, drops trace keys and repeats', () => {
expect(toDistributionFieldOptions(KEYS, 'duration_nano')).toStrictEqual([
{
type: 'group',
label: 'Columns',
value: 'column',
items: [item('duration_nano')],
},
{
type: 'group',
label: 'Attribute',
value: 'attribute',
items: [item('attribute.quantity')],
},
{
type: 'group',
label: 'Resource',
value: 'resource',
items: [item('resource.quantity')],
},
{
type: 'group',
label: 'Body',
value: 'body',
items: [item('body.latency')],
},
]);
});
it('leads with a saved field the keys do not carry', () => {
const options = toDistributionFieldOptions(KEYS, 'queue-depth');
expect(options[0]).toStrictEqual(item('queue-depth'));
expect(options).toHaveLength(5);
});
it('adds nothing for an empty or listed field', () => {
expect(toDistributionFieldOptions(KEYS, '')).toHaveLength(4);
expect(toDistributionFieldOptions(KEYS, 'body.latency')).toHaveLength(4);
});
});

View File

@@ -1,81 +0,0 @@
import type {
ComboboxItemType,
ComboboxOptionItemType,
} from '@signozhq/ui/combobox';
import { TelemetrytypesFieldContextDTO as FieldContext } from 'api/generated/services/sigNoz.schemas';
import { upperFirst } from 'lodash-es';
import type { TelemetryFieldKey } from 'types/api/v5/queryRange';
// Span and log columns are read by their name alone; anything else keeps its
// context so `attribute.quantity` and `resource.quantity` stay apart.
const COLUMN_CONTEXTS = new Set<string | undefined>([
FieldContext.span,
FieldContext.log,
FieldContext[''],
]);
const GROUP_ORDER: string[] = [
'column',
FieldContext.attribute,
FieldContext.resource,
];
const headingOf = (group: string): string =>
group === 'column' ? 'Columns' : upperFirst(group);
const toItem = (text: string): ComboboxOptionItemType => ({
type: 'item',
label: text,
value: text,
});
/** The key text the querier parses back into this key (`GetFieldKeyFromKeyText`). */
export function toDistributionFieldText(key: TelemetryFieldKey): string {
return COLUMN_CONTEXTS.has(key.fieldContext)
? key.name
: `${key.fieldContext}.${key.name}`;
}
/**
* Numeric keys grouped by context, each one once. `trace.*` keys are per-trace
* aggregates, which a heatmap cannot bucket. A saved field the keys do not carry
* leads as its own item, so the combobox can still show it.
*/
export function toDistributionFieldOptions(
keys: TelemetryFieldKey[],
selectedField: string,
): ComboboxItemType[] {
const byGroup = new Map<string, Set<string>>();
keys
.filter((key) => key.fieldContext !== FieldContext.trace)
.forEach((key) => {
const group = COLUMN_CONTEXTS.has(key.fieldContext)
? 'column'
: String(key.fieldContext);
byGroup.set(
group,
(byGroup.get(group) ?? new Set()).add(toDistributionFieldText(key)),
);
});
const isSelectedListed = [...byGroup.values()].some((texts) =>
texts.has(selectedField),
);
const rank = (group: string): number => {
const index = GROUP_ORDER.indexOf(group);
return index === -1 ? GROUP_ORDER.length : index;
};
const groups = [...byGroup.entries()]
.sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))
.map(([group, texts]): ComboboxItemType => ({
type: 'group',
label: headingOf(group),
value: group,
items: [...texts].map(toItem),
}));
return selectedField && !isSelectedListed
? [toItem(selectedField), ...groups]
: groups;
}

View File

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

View File

@@ -506,7 +506,7 @@ describe('QueryAddOns', () => {
);
}
it('is offered on a metrics heatmap', () => {
it('is offered on a metrics heatmap only', () => {
renderHeatmap();
expect(
@@ -532,16 +532,23 @@ describe('QueryAddOns', () => {
).not.toBeInTheDocument();
});
it.each([DataSource.LOGS, DataSource.TRACES])(
'is offered on a %s heatmap',
(dataSource) => {
renderHeatmap({ dataSource });
it('is not offered on a heatmap over another signal', () => {
render(
<QueryAddOns
query={baseQuery({ dataSource: DataSource.LOGS })}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.HEATMAP}
index={0}
isForTraceOperator={false}
/>,
);
expect(
screen.getByTestId('query-add-on-bucket_options'),
).toBeInTheDocument();
},
);
expect(
screen.queryByTestId('query-add-on-bucket_options'),
).not.toBeInTheDocument();
});
it.each([ATTRIBUTE_TYPES.HISTOGRAM, ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM])(
'is not offered for a %s metric, which carries its own buckets',

View File

@@ -8,7 +8,7 @@ import QueryAggregationOptions from '../QueryV2/QueryAggregation/QueryAggregatio
jest.mock('../QueryV2/QueryAggregation/QueryAggregationSelect', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="aggregation-select" />,
default: (): null => null,
}));
const queryData = initialQueriesMap.traces.builder
@@ -69,18 +69,3 @@ describe('QueryAggregationOptions step interval', () => {
expect(screen.getByText('every')).toBeInTheDocument();
});
});
describe('QueryAggregationOptions on a heatmap', () => {
it.each([
[PANEL_TYPES.HEATMAP, DataSource.TRACES, true],
[PANEL_TYPES.HEATMAP, DataSource.METRICS, false],
[PANEL_TYPES.TIME_SERIES, DataSource.TRACES, false],
])(
'%s over %s renders the field picker: %s',
(panelType, dataSource, picker) => {
renderFor(panelType, dataSource);
expect(!!screen.queryByTestId('distribution-field-select')).toBe(picker);
expect(!!screen.queryByTestId('aggregation-select')).toBe(!picker);
},
);
});

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,4 @@
import {
QuickfiltertypesSourceDTO,
TelemetrytypesSignalDTO,
} from 'api/generated/services/sigNoz.schemas';
import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
import { ENVIRONMENT } from 'constants/env';
import {
ApiMonitoringParams,
@@ -18,13 +15,10 @@ 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';
@@ -32,25 +26,10 @@ 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() as jest.MockedFunction<
QueryBuilderContextType['redirectWithQueryBuilderData']
>;
const putHandler = jest.fn() as jest.MockedFunction<
(body: { filters: TelemetryFieldKey[] }) => void
>;
const redirectWithQueryBuilderData = jest.fn();
const putHandler = jest.fn();
const mockSetApiMonitoringParams = jest.fn() as jest.MockedFunction<
(newParams: Partial<ApiMonitoringParams>, replace?: boolean) => void
>;
@@ -65,27 +44,14 @@ 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_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 ADDED_FILTERS_LABEL = /ADDED FILTERS/i;
const OTHER_FILTERS_LABEL = /OTHER FILTERS/i;
const SAVE_CHANGES_TEXT = 'Save changes';
const DISCARD_TEXT = 'Discard';
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) =>
@@ -129,24 +95,6 @@ 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();
});
@@ -154,7 +102,6 @@ beforeAll(() => {
afterEach(() => {
server.resetHandlers();
jest.clearAllMocks();
jest.useRealTimers();
});
afterAll(() => {
@@ -191,10 +138,8 @@ describe('Quick Filters', () => {
});
it('should display and allow selection from query dropdown when multiple queries exist', async () => {
const setLastUsedQuery = jest.fn() as jest.MockedFunction<
QueryBuilderContextType['setLastUsedQuery']
>;
const user = userEvent.setup();
const setLastUsedQuery = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
(useQueryBuilder as jest.Mock).mockReturnValue({
currentQuery: {
@@ -224,35 +169,42 @@ describe('Quick Filters', () => {
render(<TestQuickFilters />);
// The dropdown trigger should show the first query name
const trigger = screen.getByTestId('quick-filters-query-select');
expect(trigger).toHaveTextContent('Query A');
const trigger = screen.getByText('Query A');
expect(trigger).toBeInTheDocument();
// Click to open the dropdown
await user.click(trigger);
// All query options should be visible
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');
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();
});
// jsdom cannot deliver the pointer click Base UI expects on an option,
// so pick Query B with the arrow keys and Enter
await waitFor(() =>
// 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(() => {
expect(
screen.getByTestId('quick-filters-query-select-search'),
).toHaveFocus(),
);
screen.getByRole('combobox', { name: 'Search queries' }),
).toHaveFocus();
});
await user.keyboard('Query B');
await waitFor(() => {
expect(
screen.queryByRole('option', { name: 'Query A' }),
).not.toBeInTheDocument();
});
await user.keyboard('{ArrowDown}{Enter}');
// Verify setLastUsedQuery was called with index 1
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
});
await waitFor(() => {
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
});
// filtering and picking through the search row takes Base UI past the
// default 5s under jsdom
}, 20000);
it('should not display query dropdown in ListView', () => {
(useQueryBuilder as jest.Mock).mockReturnValue({
@@ -292,13 +244,12 @@ describe('Quick Filters', () => {
expect(screen.getByText(QUERY_NAME)).toBeInTheDocument();
// No dropdown should be present
expect(
screen.queryByTestId('quick-filters-query-select'),
).not.toBeInTheDocument();
const queryText = screen.getByText(QUERY_NAME);
expect(queryText.closest('[role="combobox"]')).not.toBeInTheDocument();
});
it('should add filter data to query when checkbox is clicked', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<TestQuickFilters />);
@@ -330,27 +281,33 @@ describe('Quick Filters', () => {
});
});
it('toggles Show IP addresses and updates API Monitoring params', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.API_MONITORING} />,
);
// Switch should be rendered and initially checked
const toggle = await screen.findByTestId('quick-filters-show-ip');
expect(screen.getByText('Show IP addresses')).toBeInTheDocument();
await expect(
screen.findByText('Show IP addresses'),
).resolves.toBeInTheDocument();
const toggle = screen.getByRole('switch');
expect(toggle).toHaveAttribute('aria-checked', 'true');
await user.click(toggle);
expect(mockSetApiMonitoringParams).toHaveBeenCalledWith(
expect.objectContaining({ showIP: false }),
);
await waitFor(() => {
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} />,
);
@@ -361,32 +318,28 @@ describe('Quick Filters with custom filters', () => {
await screen.findByText(FILTER_SERVICE_NAME);
const allByText = await screen.findAllByText('otel-demo');
expect(allByText).toHaveLength(2);
});
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 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),
);
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(
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
expect(otherSection).toContainElement(
await screen.findByText(FILTER_K8S_DEPLOYMENT_NAME),
);
});
it('keeps same-name fields with different context as distinct entries', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(quickFiltersSuggestionsURL, (_req, res, ctx) =>
res(
@@ -417,86 +370,153 @@ describe('Quick Filters with custom filters', () => {
),
);
renderSettings();
const otherSection = screen.getByTestId(OTHER_FILTERS_TEST_ID);
// Both `level` variants are shown despite sharing a name.
const addButton = await screen.findByTestId(
'quick-filters-add-attribute:level:string',
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
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 otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
// Both `level` variants are shown despite sharing a name.
await waitFor(() =>
expect(within(otherSection).getAllByText('level')).toHaveLength(2),
);
expect(within(otherSection).getAllByText('level')).toHaveLength(2);
// Adding one variant removes only that one; the other stays.
await user.click(addButton);
const firstLevel = within(otherSection).getAllByText('level')[0];
const addButton = firstLevel.parentElement?.querySelector('button');
await user.click(addButton as HTMLButtonElement);
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();
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
await waitFor(() => {
expect(within(addedSection).getAllByText('level')).toHaveLength(1);
expect(within(otherSection).getAllByText('level')).toHaveLength(1);
});
});
it('adds a filter from OTHER FILTERS to ADDED FILTERS when clicked', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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,
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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),
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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),
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
await screen.findByText(FILTER_SERVICE_NAME);
await user.click(screen.getByTestId('quick-filters-settings-discard'));
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
const settingsButton = icon.closest('button') ?? icon;
await user.click(settingsButton);
expect(addedSection).toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
expect(otherSection).not.toContainElement(
screen.getByText(FILTER_OS_DESCRIPTION),
);
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),
);
});
});
it('saves the updated filters by calling PUT with correct payload', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderSettings();
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
await screen.findByText(FILTER_SERVICE_NAME);
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
await user.click(screen.getByTestId(SAVE_TEST_ID));
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 waitFor(() => {
expect(putHandler).toHaveBeenCalled();
@@ -510,37 +530,24 @@ 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,
});
render(
const { getByTestId } = render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
await screen.findByTestId('collapse-duration');
await screen.findByText(FILTER_SERVICE_NAME);
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 = screen.getByTestId('min-input') as HTMLInputElement;
const maxDuration = screen.getByTestId('max-input') as HTMLInputElement;
const minDuration = getByTestId('min-input') as HTMLInputElement;
const maxDuration = getByTestId('max-input') as HTMLInputElement;
expect(minDuration).toHaveValue(null);
expect(minDuration).toHaveProperty('placeholder', '0');
@@ -642,7 +649,7 @@ describe('Quick Filters refetch behavior', () => {
server.use(
rest.get(quickFiltersListURL, (_req, res, ctx) => {
getCalls += 1;
return res(ctx.status(200), ctx.json(smallFiltersListResponse));
return res(ctx.status(200), ctx.json(quickFiltersListResponse));
}),
rest.put(saveQuickFiltersURL, async (req, res, ctx) => {
putHandler(await req.json());
@@ -650,14 +657,26 @@ describe('Quick Filters refetch behavior', () => {
}),
);
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
await openSettings(user);
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
await user.click(screen.getByTestId(SAVE_TEST_ID));
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 waitFor(() => expect(putHandler).toHaveBeenCalled());
await waitFor(() => expect(getCalls).toBeGreaterThanOrEqual(2));
@@ -665,11 +684,11 @@ describe('Quick Filters refetch behavior', () => {
it('renders updated filters after refetch post-save', async () => {
const updatedResponse = {
...smallFiltersListResponse,
...quickFiltersListResponse,
data: {
...smallFiltersListResponse.data,
...quickFiltersListResponse.data,
filters: [
...smallFiltersListResponse.data.filters,
...(quickFiltersListResponse.data.filters ?? []),
{
name: 'new.custom.filter',
fieldDataType: 'string',
@@ -685,26 +704,38 @@ describe('Quick Filters refetch behavior', () => {
getCount += 1;
return getCount >= 2
? res(ctx.status(200), ctx.json(updatedResponse))
: res(ctx.status(200), ctx.json(smallFiltersListResponse));
: res(ctx.status(200), ctx.json(quickFiltersListResponse));
}),
rest.put(saveQuickFiltersURL, async (_req, res, ctx) =>
res(ctx.status(200), ctx.json({})),
),
);
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
await openSettings(user);
// Make a minimal change so Save button appears
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
await user.click(screen.getByTestId(SAVE_TEST_ID));
await expect(
screen.findByText('New Custom Filter'),
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);
// 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.getByText(SAVE_CHANGES_TEXT));
await waitFor(() => {
expect(screen.getByText('New Custom Filter')).toBeInTheDocument();
});
});
it('shows empty state when GET fails', async () => {

View File

@@ -1,4 +1,3 @@
import { lazy } from 'react';
import { navigate } from 'lib/router/navigation';
import { fireEvent, render, screen } from 'tests/test-utils';
@@ -99,30 +98,4 @@ 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.getByLabelText('loading').closest('.ant-spin')?.parentElement,
).toHaveStyle({ height: '100%' });
resolveTab({ default: DummyComponent1 });
await expect(
screen.findByText('Dummy Component 1'),
).resolves.toBeInTheDocument();
});
});

View File

@@ -1,9 +1,7 @@
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';
@@ -60,11 +58,7 @@ function RouteTab({
tabKey: route,
children: (
<OverlayScrollbar>
<Suspense
fallback={<Spinner size="large" tip="Loading..." height="100%" />}
>
<Component />
</Suspense>
<Component />
</OverlayScrollbar>
),
}));

View File

@@ -44,7 +44,6 @@ 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

@@ -1,4 +1,3 @@
import type { ServiceAccountRow } from 'container/ServiceAccountsSettings/utils';
import {
listRolesSuccessResponse,
managedRoles,
@@ -16,25 +15,22 @@ 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 account: ServiceAccountRow = {
const activeAccountResponse = {
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',
@@ -45,88 +41,93 @@ const activeAccountResponse = {
],
};
function renderOverviewTab(): ReturnType<typeof render> {
function renderDrawer(
searchParams: Record<string, string> = { account: 'sa-1' },
): ReturnType<typeof render> {
return render(
<OverviewTab
account={account}
localName="CI Bot"
onNameChange={jest.fn()}
localRoles={[]}
onRolesChange={jest.fn()}
isDisabled={false}
availableRoles={[]}
/>,
<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))),
);
}
describe('ServiceAccountDrawer — permissions', () => {
it('shows PermissionDeniedCallout in the Overview tab when read permission is denied', async () => {
server.use(setupAuthzDenyAll());
renderOverviewTab();
await expect(
screen.findByTestId('permission-denied-callout'),
).resolves.toHaveTextContent('read:serviceaccount:sa-1');
beforeEach(() => {
jest.clearAllMocks();
setupBaseHandlers();
});
it('shows Overview tab content when read permission is granted', async () => {
afterEach(() => {
server.resetHandlers();
});
it('shows PermissionDeniedCallout inside drawer when read permission is denied', async () => {
server.use(setupAuthzDenyAll());
renderDrawer();
await waitFor(() => {
expect(screen.getByText(/read:serviceaccount/)).toBeInTheDocument();
});
});
it('shows drawer content when read permission is granted', async () => {
server.use(setupAuthzAdmin());
renderOverviewTab();
renderDrawer();
await screen.findByDisplayValue('CI Bot');
expect(
screen.queryByTestId('permission-denied-callout'),
).not.toBeInTheDocument();
expect(screen.queryByText(/serviceaccount:read/)).not.toBeInTheDocument();
});
it('shows PermissionDeniedCallout in Keys tab when list-keys permission is denied', async () => {
server.use(setupAuthzDeny(APIKeyListPermission));
render(
<KeysTab
keys={[]}
isLoading={false}
accountId="sa-1"
currentPage={1}
pageSize={15}
onPageChange={jest.fn()}
/>,
);
renderDrawer({ account: 'sa-1', tab: 'keys' });
await expect(
screen.findByTestId('permission-denied-callout'),
).resolves.toHaveTextContent('list:factor-api-key:*');
await waitFor(() => {
expect(screen.getByText(/list:factor-api-key/)).toBeInTheDocument();
});
});
it('disables Delete button when delete permission is denied', async () => {
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')),
);
server.use(setupAuthzDeny(buildSADeletePermission('sa-1')));
render(
<NuqsTestingAdapter searchParams={{ account: 'sa-1' }} hasMemory>
<ServiceAccountDrawer onSuccess={jest.fn()} />
</NuqsTestingAdapter>,
);
renderDrawer();
await screen.findByDisplayValue('CI Bot');
const deleteBtn = await screen.findByTestId('sa-delete-btn');
const deleteBtn = screen.getByRole('button', {
name: /Delete Service Account/i,
});
await waitFor(() =>
expect(deleteBtn).toHaveAttribute(
'data-denied-permissions',
buildSADeletePermission('sa-1'),
),
expect(deleteBtn).toHaveAttribute('aria-disabled', 'true'),
);
expect(deleteBtn).toHaveAttribute('aria-disabled', 'true');
});
});

View File

@@ -4,12 +4,14 @@ import {
} from 'mocks-server/__mockdata__/roles';
import { rest, server } from 'mocks-server/server';
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
import ServiceAccountDrawer, {
ServiceAccountDrawerProps,
} from '../ServiceAccountDrawer';
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';
@@ -95,18 +97,16 @@ describe('ServiceAccountDrawer', () => {
screen.findByDisplayValue('CI Bot'),
).resolves.toBeInTheDocument();
expect(screen.getByText('ci-bot@signoz.io')).toBeInTheDocument();
expect(screen.getByTestId('sa-save-btn')).toHaveAttribute(
expect(screen.getByRole('button', { name: /Save Changes/i })).toHaveAttribute(
'aria-disabled',
'true',
);
});
it('editing name enables Save; clicking Save sends correct payload and calls onSuccess', async () => {
const onSuccess = jest.fn() as jest.MockedFunction<
ServiceAccountDrawerProps['onSuccess']
>;
const onSuccess = jest.fn();
const updateSpy = jest.fn();
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.put(SA_ENDPOINT, async (req, res, ctx) => {
@@ -125,7 +125,7 @@ describe('ServiceAccountDrawer', () => {
await user.clear(nameInput);
await user.type(nameInput, 'CI Bot Updated');
const saveBtn = screen.getByTestId('sa-save-btn');
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
@@ -144,7 +144,7 @@ describe('ServiceAccountDrawer', () => {
it('adding a role fires POST for the new role and no DELETE for existing roles', async () => {
const roleSpy = jest.fn();
const deleteSpy = jest.fn();
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.post(SA_ROLES_ENDPOINT, async (req, res, ctx) => {
@@ -171,7 +171,7 @@ describe('ServiceAccountDrawer', () => {
`${managedRoles[2].name}{Enter}`,
);
const saveBtn = screen.getByTestId('sa-save-btn');
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
@@ -191,7 +191,7 @@ describe('ServiceAccountDrawer', () => {
it('removing a role fires DELETE for the removed role and no POST', async () => {
const roleSpy = jest.fn();
const deleteSpy = jest.fn();
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.post(SA_ROLES_ENDPOINT, async (req, res, ctx) => {
@@ -218,7 +218,7 @@ describe('ServiceAccountDrawer', () => {
),
);
const saveBtn = screen.getByTestId('sa-save-btn');
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
@@ -232,7 +232,7 @@ describe('ServiceAccountDrawer', () => {
it('"Delete Service Account" opens confirm dialog; confirming sends delete request', async () => {
const deleteSpy = jest.fn();
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.delete(SA_DELETE_ENDPOINT, (_, res, ctx) => {
@@ -245,7 +245,9 @@ describe('ServiceAccountDrawer', () => {
await screen.findByDisplayValue('CI Bot');
await user.click(screen.getByTestId('sa-delete-btn'));
await user.click(
screen.getByRole('button', { name: /Delete Service Account/i }),
);
await screen.findByTestId('delete-service-account-modal');
expect(
@@ -277,19 +279,23 @@ describe('ServiceAccountDrawer', () => {
await screen.findByText('CI Bot');
expect(screen.queryByTestId('sa-save-btn')).not.toBeInTheDocument();
expect(screen.queryByTestId('sa-delete-btn')).not.toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /Save Changes/i }),
).not.toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /Delete Service Account/i }),
).not.toBeInTheDocument();
expect(screen.queryByDisplayValue('CI Bot')).not.toBeInTheDocument();
});
it('switching to Keys tab shows "No keys" empty state', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer();
await screen.findByDisplayValue('CI Bot');
await user.click(screen.getByTestId('sa-tab-button-keys'));
await user.click(screen.getByRole('button', { name: /Keys/i }));
await expect(screen.findByText(/No keys/i)).resolves.toBeInTheDocument();
});
@@ -342,12 +348,11 @@ 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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.put(SA_ENDPOINT, (_, res, ctx) =>
@@ -369,7 +374,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
await user.clear(nameInput);
await user.type(nameInput, 'New Name');
const saveBtn = screen.getByTestId('sa-save-btn');
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
@@ -383,7 +388,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
});
it('role add failure shows SaveErrorItem with the role name context', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.post(SA_ROLES_ENDPOINT, (_, res, ctx) =>
@@ -410,7 +415,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
`${managedRoles[2].name}{Enter}`,
);
const saveBtn = screen.getByTestId('sa-save-btn');
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
@@ -424,13 +429,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
});
it('role add retries on 429 then succeeds without showing an error', async () => {
jest.useFakeTimers();
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const onSuccess = jest.fn() as jest.MockedFunction<
ServiceAccountDrawerProps['onSuccess']
>;
const user = userEvent.setup({ pointerEventsCheck: 0 });
let roleAddCallCount = 0;
// First call → 429, second call → 201
@@ -447,11 +446,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
}),
);
render(
<NuqsTestingAdapter searchParams={{ account: 'sa-1' }} hasMemory>
<ServiceAccountDrawer onSuccess={onSuccess} />
</NuqsTestingAdapter>,
);
renderDrawer();
await screen.findByDisplayValue('CI Bot');
@@ -461,24 +456,24 @@ describe('ServiceAccountDrawer – save-error UX', () => {
`${managedRoles[2].name}{Enter}`,
);
const saveBtn = screen.getByTestId('sa-save-btn');
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
await user.click(saveBtn);
await waitFor(() => expect(roleAddCallCount).toBe(1));
await act(() => jest.advanceTimersByTimeAsync(1000));
await waitFor(() =>
expect(onSuccess).toHaveBeenCalledWith({ closeDrawer: false }),
// Retried after 429 — at least 2 calls, no error shown
await waitFor(
() => {
expect(roleAddCallCount).toBeGreaterThanOrEqual(2);
},
{ timeout: 5000 },
);
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
// First: PUT always fails so the error appears
server.use(
@@ -501,7 +496,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
await user.clear(nameInput);
await user.type(nameInput, 'Retry Test');
const saveBtn = screen.getByTestId('sa-save-btn');
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
await waitFor(() =>
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
@@ -517,7 +512,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
),
);
const retryBtn = screen.getByTestId('sa-error-retry-btn');
const retryBtn = screen.getByRole('button', { name: /Retry/i });
await user.click(retryBtn);
// Error item should be removed after successful retry

View File

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

View File

@@ -152,7 +152,6 @@ 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 '@signozhq/noz-client';
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
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(--label-base-400-font-size);
--input-font-size: var(--periscope-font-size-base);
--input-line-height: 20px;
--input-placeholder-color: color-mix(
in srgb,

View File

@@ -12,8 +12,8 @@
}
.heading {
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
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(--label-base-400-font-size);
--button-font-size: var(--periscope-font-size-base);
--button-size-line-height: var(--line-height-20);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-weight: var(--font-weight-normal);
--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 '@signozhq/noz-client';
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
MessageActionKindDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
restoreExecution,
revertExecution,

View File

@@ -1,4 +1,7 @@
import { MessageActionDTO, MessageActionKindDTO } from '@signozhq/noz-client';
import {
MessageActionDTO,
MessageActionKindDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
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 '@signozhq/noz-client';
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
MessageActionKindDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';

View File

@@ -1,4 +1,4 @@
import { ApplyFilterSignalDTO } from '@signozhq/noz-client';
import { ApplyFilterSignalDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
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 '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
getSavedView,
listSavedViews,

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,8 @@
import type { MessageActionDTO } from '@signozhq/noz-client';
import { ApplyFilterSignalDTO, SavedViewEntityDTO } from '@signozhq/noz-client';
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
SavedViewEntityDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
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(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 18px;
letter-spacing: -0.005em;
}
@@ -54,7 +54,7 @@
.soloThought {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
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(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
font-size: var(--periscope-font-size-base);
font-weight: var(--font-weight-normal);
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(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -90,7 +90,7 @@ button.title {
}
.detail {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);

View File

@@ -42,7 +42,7 @@
}
.headerLabel {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--font-size-sm);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -61,7 +61,7 @@
.summary {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
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 '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
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(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--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(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
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(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-medium);
line-height: 15px;
transition:
background-color 0.12s,

View File

@@ -40,7 +40,7 @@
}
.headerLabel {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--font-size-sm);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -48,7 +48,7 @@
.message {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
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 '@signozhq/noz-client';
import { ClarificationFieldTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type {
ClarificationEventDTO,
ClarificationFieldEventDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { CircleHelp, Send, X } from '@signozhq/icons';
import { AIAssistantEvents } from '../../events';

View File

@@ -53,7 +53,7 @@
}
.title {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
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(--paragraph-small-400-font-size);
font-size: var(--periscope-font-size-small);
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(--label-base-400-font-size);
--input-font-size: var(--periscope-font-size-base);
--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(--label-base-400-font-weight);
--button-font-weight: var(--font-weight-normal);
--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(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
line-height: 1;
text-transform: uppercase;
letter-spacing: 0.04em;

View File

@@ -14,8 +14,8 @@
}
.note {
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
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(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
border-bottom-left-radius: var(--radius-2);
}
@@ -274,7 +274,7 @@
width: max-content;
min-width: 100%;
border-collapse: collapse;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
font-variant-numeric: tabular-nums;
word-break: normal;
@@ -286,8 +286,8 @@
th {
padding-block: 13px;
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
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 '@signozhq/noz-client';
import { RetryActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
// Side-effect: registers all built-in block types into the BlockRegistry
import '../blocks';

View File

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

View File

@@ -10,7 +10,7 @@ import { useTimezone } from 'providers/Timezone';
import logEvent from 'api/common/logEvent';
import { FeedbackRatingDTO } from '@signozhq/noz-client';
import { FeedbackRatingDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
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 '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
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(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--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 '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import logEvent from 'api/common/logEvent';
import { AIAssistantEvents } from '../../events';

View File

@@ -1,4 +1,4 @@
import type { ChipDTO } from '@signozhq/noz-client';
import type { ChipDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
/** 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 '@signozhq/noz-client';
import type { ChipDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useResolvePageType } from 'hooks/aiAssistant/useResolvePageType';

View File

@@ -1,4 +1,4 @@
import { PageTypeDTO } from '@signozhq/noz-client';
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
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 '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type {
MessageContext,
SSEEvent,
@@ -73,10 +73,6 @@ 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');
@@ -146,7 +142,6 @@ 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.
@@ -157,9 +152,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
);
useAIAssistantStore.getState().startNewConversation();
const sending = useAIAssistantStore.getState().sendMessage('hi');
await jest.runAllTimersAsync();
await sending;
await useAIAssistantStore.getState().sendMessage('hi');
expect(chat.sendMessage).toHaveBeenCalledTimes(3);
expect(lastMessage('thread-2')).toMatchObject({
@@ -168,7 +161,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
// Auto budget exhausted → presented as manual so a Retry button shows.
retryAction: RetryActionDTO.manual,
});
});
}, 10000);
it('marks rate-limit errors and offers no retry', async () => {
chat.createThread.mockResolvedValue('thread-3');
@@ -198,7 +191,6 @@ 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
@@ -220,9 +212,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
);
useAIAssistantStore.getState().startNewConversation();
const sending = useAIAssistantStore.getState().sendMessage('hi');
await jest.runAllTimersAsync();
await sending;
await useAIAssistantStore.getState().sendMessage('hi');
// 1 initial attempt + 1 silent auto retry, then success — no error bubble.
expect(chat.sendMessage).toHaveBeenCalledTimes(2);
@@ -234,7 +224,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 '@signozhq/noz-client';
import { RetryActionDTO } from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { RetryActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
approveExecution,

View File

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

View File

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

View File

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

View File

@@ -6,14 +6,7 @@ import {
trialConvertedToSubscriptionResponse,
} from 'mocks-server/__mockdata__/licenses';
import { server } from 'mocks-server/server';
import {
act,
render,
screen,
getAppContextMock,
within,
} from 'tests/test-utils';
import { REAL_TIMER_APIS } from 'tests/realTimerApis';
import { act, render, screen, getAppContextMock } from 'tests/test-utils';
import APIError from 'types/api/error';
import {
LicensePlatform,
@@ -33,6 +26,8 @@ window.ResizeObserver =
}));
describe('BillingContainer', () => {
jest.setTimeout(30000);
beforeEach(() => {
server.use(setupAuthzAdmin());
});
@@ -44,32 +39,40 @@ 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();
expect(screen.getByText(/\$1,278.3/i)).toBeInTheDocument();
expect(screen.getByText('billing')).toBeInTheDocument();
const dollar = await screen.findByText(/\$1,278.3/i, {}, { timeout: 5000 });
expect(dollar).toBeInTheDocument();
const currentBill = await screen.findByText('billing');
expect(currentBill).toBeInTheDocument();
});
describe('Trial scenarios', () => {
beforeEach(() => {
jest.useFakeTimers({
now: new Date('2023-10-20'),
doNotFake: REAL_TIMER_APIS,
});
jest.useFakeTimers();
jest.setSystemTime(new Date('2023-10-20'));
});
afterEach(() => {
@@ -85,9 +88,14 @@ 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)).resolves.toBeInTheDocument();
await expect(
screen.findByText(/\$0/i, {}, { timeout: 5000 }),
).resolves.toBeInTheDocument();
await expect(
screen.findByText(
@@ -99,20 +107,18 @@ describe('BillingContainer', () => {
screen.findByText(/1 days_remaining/i),
).resolves.toBeInTheDocument();
expect(screen.getByTestId('header-billing-button')).toHaveTextContent(
'upgrade_plan',
);
expect(screen.getByTestId('upgrade-plan-button')).toHaveTextContent(
'upgrade_plan',
);
const upgradeButtons = await screen.findAllByRole('button', {
name: /upgrade_plan/i,
});
expect(upgradeButtons).toHaveLength(2);
expect(upgradeButtons[1]).toBeInTheDocument();
await expect(
screen.findByText(/checkout_plans/i),
).resolves.toBeInTheDocument();
expect(screen.getByText('here', { selector: 'a' })).toHaveAttribute(
'href',
'https://signoz.io/pricing/',
);
await expect(
screen.findByRole('link', { name: /here/i }),
).resolves.toBeInTheDocument();
await expect(
screen.findByText('Cancel your subscription', { selector: 'span' }),
@@ -135,7 +141,7 @@ describe('BillingContainer', () => {
const currentBill = await screen.findByText('billing');
expect(currentBill).toBeInTheDocument();
const dollar0 = await screen.findByText(/\$0/i);
const dollar0 = await screen.findByText(/\$0/i, {}, { timeout: 5000 });
expect(dollar0).toBeInTheDocument();
const onTrail = await screen.findByText(
@@ -148,9 +154,10 @@ describe('BillingContainer', () => {
);
expect(receivedCardDetails).toBeInTheDocument();
expect(screen.getByTestId('header-billing-button')).toHaveTextContent(
'manage_billing',
);
const manageBillingButton = await screen.findByRole('button', {
name: /manage_billing/i,
});
expect(manageBillingButton).toBeInTheDocument();
const dayRemainingInBillingPeriod =
await screen.findByText(/1 days_remaining/i);
@@ -252,23 +259,27 @@ describe('BillingContainer', () => {
billingSuccessResponse.data.billingPeriodStart,
)} to ${getFormattedDate(billingSuccessResponse.data.billingPeriodEnd)}`;
const billingPeriod = await findByText(billingPeriodText);
const billingPeriod = await findByText(
billingPeriodText,
{},
{ timeout: 5000 },
);
expect(billingPeriod).toBeInTheDocument();
expect(screen.getByText('billing')).toBeInTheDocument();
expect(screen.getByText(/\$1,278.3/i)).toBeInTheDocument();
const currentBill = await screen.findByText('billing');
expect(currentBill).toBeInTheDocument();
const cellTexts = (productIndex: number, tierIndex: number): string[] =>
within(screen.getByTestId(`billing-usage-row-${productIndex}${tierIndex}`))
.getAllByRole('cell', { hidden: true })
.map((cell) => cell.textContent ?? '');
const dollar0 = await screen.findByText(/\$1,278.3/i);
expect(dollar0).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']);
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();
});
});

View File

@@ -597,11 +597,6 @@ 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

@@ -6,7 +6,6 @@ import {
rest,
server,
} from 'mocks-server/server';
import { holdResponse } from 'tests/holdResponse';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { OrgSessionContext } from 'types/api/v2/sessions/context/get';
@@ -65,18 +64,6 @@ const multiOrgProps: ForgotPasswordRouteState = {
orgs: mockMultipleOrgs,
};
function mockForgot(held?: Promise<void>): { forgotCalls: () => number } {
let calls = 0;
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, async (_req, res, ctx) => {
calls += 1;
await held;
return res(ctx.status(200), ctx.json({ status: 'success' }));
}),
);
return { forgotCalls: (): number => calls };
}
describe('ForgotPassword Component', () => {
beforeEach(() => {
jest.clearAllMocks();
@@ -149,7 +136,7 @@ describe('ForgotPassword Component', () => {
});
it('enables submit button after selecting an organization', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<ForgotPassword {...multiOrgProps} />);
@@ -157,7 +144,7 @@ describe('ForgotPassword Component', () => {
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
// Click on the dropdown to reveal the options
await user.click(screen.getByText('Select your organization'));
await user.click(screen.getByRole('combobox'));
await user.click(screen.getByText('Organization One'));
await waitFor(() => {
@@ -181,7 +168,7 @@ describe('ForgotPassword Component', () => {
describe('Form Submission - Success', () => {
it('successfully submits forgot password request and shows success screen', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
@@ -203,7 +190,7 @@ describe('ForgotPassword Component', () => {
});
it('shows back to login button on success screen', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
@@ -222,7 +209,7 @@ describe('ForgotPassword Component', () => {
});
it('redirects to login when clicking back to login on success screen', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
@@ -248,7 +235,7 @@ describe('ForgotPassword Component', () => {
describe('Form Submission - Error Handling', () => {
it('displays error message when forgot password API fails', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.post(
@@ -268,7 +255,7 @@ describe('ForgotPassword Component', () => {
});
it('displays error message when API returns server error', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(rest.post(FORGOT_PASSWORD_ENDPOINT, handleInternalServerError));
@@ -283,7 +270,7 @@ describe('ForgotPassword Component', () => {
});
it('clears error message on new submission attempt', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
let requestCount = 0;
server.use(
@@ -327,7 +314,7 @@ describe('ForgotPassword Component', () => {
describe('Navigation', () => {
it('redirects to login when clicking back button on form', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<ForgotPassword {...defaultProps} />);
@@ -340,10 +327,13 @@ describe('ForgotPassword Component', () => {
describe('Loading States', () => {
it('shows loading state during API call', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const response = holdResponse();
mockForgot(response.held);
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
res(ctx.delay(100), ctx.status(200), ctx.json({ status: 'success' })),
),
);
render(<ForgotPassword {...defaultProps} />);
@@ -354,14 +344,16 @@ describe('ForgotPassword Component', () => {
await expect(
screen.findByText(/sending\.\.\./i),
).resolves.toBeInTheDocument();
response.release();
});
it('disables submit button during loading', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const response = holdResponse();
mockForgot(response.held);
server.use(
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
res(ctx.delay(100), ctx.status(200), ctx.json({ status: 'success' })),
),
);
render(<ForgotPassword {...defaultProps} />);
@@ -371,7 +363,6 @@ describe('ForgotPassword Component', () => {
await waitFor(() => {
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
});
response.release();
});
});
@@ -419,8 +410,23 @@ 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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const { forgotCalls } = mockForgot();
render(<ForgotPassword {...defaultProps} />);
@@ -437,7 +443,7 @@ describe('ForgotPassword Component', () => {
});
it('does not send on Enter while no organization is selected', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const { forgotCalls } = mockForgot();
render(<ForgotPassword {...multiOrgProps} />);
@@ -453,9 +459,8 @@ describe('ForgotPassword Component', () => {
});
it('does not send again on Enter while the first request is loading', async () => {
const user = userEvent.setup();
const response = holdResponse();
const { forgotCalls } = mockForgot(response.held);
const user = userEvent.setup({ pointerEventsCheck: 0 });
const { forgotCalls } = mockForgot(1000);
render(<ForgotPassword {...defaultProps} />);
@@ -467,9 +472,8 @@ describe('ForgotPassword Component', () => {
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
await user.keyboard('{enter}');
response.release();
await expect(
screen.findByText(/check your email/i),
screen.findByText(/check your email/i, undefined, { timeout: 2000 }),
).resolves.toBeInTheDocument();
expect(forgotCalls()).toBe(1);
});

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