Files
openobserve/tests/api-testing/helpers/workflow/pages/dashboard_page.py
T
Shrinath RaoandClaude Opus 4.7 61aa772d57 test: revamp api-testing suite (framework + 16 file rewrites + CI matrix) (#12372)
## Summary

Comprehensive rework of the `tests/api-testing/` suite. 30+ commits
implementing all 6 phases of the [revamp
plan](../../tests/ui-testing/MD_Files/api%20tests%20revamp/API_TESTS_REVAMP.md).

**Before → After:**

| | Baseline | Final | Δ |
|---|---|---|---|
| passed | 421 | **443** | **+22 ✓** |
| failed | 3 | **2** | -1 (only same pre-existing) |
| skipped | 53 | 39 | -14 (unskipped dead tests now run) |
| xfailed | 1 | 2 | +1 (new visible backend-bug signal) |
| runtime | 588s | **387s** | **-201s (34% faster)** |

**Zero tests that passed in baseline are now failing.** The 2 remaining
failures are the exact pre-existing ones
(`test_enrichment_table_join.py` backend panic + `test_workflow.py` SMTP
env-miss).

## What's in the diff

- **New `support/` framework** — `OpenObserveClient`, endpoint wrappers
(`alerts`, `dashboards`, `streams`, `search`, etc.), `wait_until()`,
payload factories, pytest fixtures, SSE parser. 14 framework selfcheck
tests.
- **16 of 16 OLD-tier test files rewritten** — using the new framework,
unique-suffix names, body validation, `wait_until` instead of
`time.sleep`, parametrize where appropriate.
- **29 files moved into 12 feature folders** mirroring the UI suite
layout
(`tests/{alerts,dashboards,ingest,orgs,pipelines,regression,rum,search,streams,users,workflow}/`).
- **−6,500 LOC net** (copy-paste + dead code removal; new framework adds
back ~1,500).
- **Ruff config** in pyproject.toml: T201 ban on `print()`, PT pytest
rules, B bugbear, UP pyupgrade.

## CI workflow changes

- New job `api_regression_tests`: `strategy.matrix` over the 4 env-flag
combinations (UTF8_VIEW × JOIN_MATCH_ONE) — now runs in parallel instead
of as 4 sequential server reboots in the main job.
- New job `api_fuzz_tests`: schemathesis OpenAPI-driven fuzz against
`/api-doc/openapi.json` (214 endpoints tested). Informational
(`continue-on-error: true`). Each run surfaces **7–10 distinct 5xx
panics** (e.g., empty `sql` body returning 500 instead of 400, traces
endpoints crashing on unescaped path params that get interpolated into
SQL). Filed to backend team for separate triage.
- Server `o2_*.log` files uploaded as artifacts on failure (was:
silently lost).
- `api_tests_summary` now requires BOTH integration + regression to
pass.

### CI infrastructure fixes

A short hardening pass landed after the initial CI run surfaced several
issues:

- **pytest-sugar count inflation** — dropped `--force-sugar` from both
pytest invocations. The flag double-registered sugar on top of the
auto-loaded entry point, inflating the CI test counter ~3x (display
showed 1364 when collection was 486). Counter is now honest.
- **schemathesis 4.x flag migration** — `--base-url` → `-u`,
`--hypothesis-max-examples` → `-n`, `--hypothesis-deadline` →
`--request-timeout`, `--data-generation-method` → `-m`, dropped
`--auth-type basic`. The fuzz job was failing immediately on flag-parse
before this.
- **Regression matrix binary path** — used `${{ github.workspace
}}/target/debug/openobserve` so the absolute path resolves correctly
under `working-directory: tests/api-testing/` (was: every matrix job
failed with "No such file or directory").
- **`permissions: contents: read`** added to all 4 workflow jobs —
closes CodeQL alert #369.
- **Removed redundant server boot** in `api_integration_tests` (leftover
from main's structure after the regression matrix split; was silently
failing to bind to :5080 and getting masked by the first server).

## Backend bugs surfaced (for backend team to track)

The rework uncovered and visibly flagged these as `xfail`/documented
test comments:

1. `DELETE /api/organizations/{id}` returns 404 unconditionally even for
just-created orgs — endpoint appears unimplemented.
2. `test_dashboard_missing_required_fields` triggers backend panic
(returns 500 instead of 400/422).
3. JS `getEnrichmentTableData()` restricted to `_meta` org AND not
exposed in the `/functions/test` endpoint runtime — `ReferenceError`
even with explicit `enrichment_tables: [...]`.
4. Bulk API silently sanitizes invalid `_index` values (`****` → `_`)
without flagging — user data lands in unexpected index.
5. `AVG` of a single value drifts by ~1e-14 (likely float reduction
order; documented tolerance in `test_advanced_sql.py`).
6. Org name validation rejects hyphens (only
`A-Z/a-z/0-9/spaces/underscores`) — not in spec.

Plus 7–10 additional 5xx panics surfaced per fuzz run (input validation
gaps — separate triage list in fuzz job logs).

## Test bugs uncovered + fixed

- `test_pipeline.py`: had two function definitions named
`test_pipeline_creation_and_action_with_schedule` — Python's last-wins
meant the first test's body never executed for years.
- `test_alertsV2.py`: `assert alert_disabled == "False"` was indented
inside an `else:` branch that never executed because the response is
always a dict; AND `enabled` is a bool, not the string `"False"`. Two
layers of broken.
- `test_bulk.py`: variable typo (`valid_bulk_payload` reused on the POST
call) made the invalid-index test silently duplicate the valid case.
- `test_organisations.py`: `test_create_organization` used pre-pytest-4
`yield`-style fixtures — silently ignored by pytest 8.
- `test_js_result_array.py`: 8 tests skipped with `"Temporarily disabled
- failing test"` — the actual cause was that JS functions are restricted
to `_meta` org. One-line fix unskipped all 8.
- `test_fuzzy.py`: 4 tests `@pytest.mark.skip`-ed because they used a
1-minute time window against older static test data → 0 hits → flake →
skip. Wider window unskips them.
- 547 LOC of zombie commented-out test blocks deleted (15 commented `#
def test_` definitions, including one orphan case where the `def` was
commented but the indented body wasn't).

## Folder layout

```
tests/api-testing/
├── support/                    # NEW framework
│   ├── client.py               # OpenObserveClient
│   ├── endpoints/              # 7 per-resource wrappers
│   ├── factories.py            # unique_name, time_window, *_payload
│   ├── wait.py                 # wait_until + WaitTimeout
│   ├── sse.py                  # read_sse_response
│   └── fixtures.py             # client, temp_user_email, temp_stream_name, ...
├── helpers/                    # Non-test shared code (was scattered in tests/)
│   ├── sourcemap_helpers.py
│   └── workflow/               # workflow chain + pages/ live here now
├── fixtures/
│   └── rum/                    # Standalone RUM ingest scripts (was in tests/)
└── tests/
    ├── alerts/                 # 3 files
    ├── dashboards/             # 4 files
    ├── ingest/                 # 4 files
    ├── orgs/                   # 2 files
    ├── pipelines/              # 10 files
    ├── regression/             # 2 files (env-flag matrix targets)
    ├── rum/                    # 3 files
    ├── search/                 # 8 files
    ├── streams/                # 1 file
    ├── users/                  # 1 file
    ├── workflow/               # 3 files
    ├── conftest.py
    └── test_framework_selfcheck.py
```

## Test plan

- [x] `rye run pytest --collect-only` — 486 tests discovered
- [x] Full default-set run (`--ignore=tests/regression`) — 443 pass / 2
fail / 39 skip / 2 xfail in 387s
- [x] `rye run pytest -m framework` — 14/14 selfcheck tests pass
- [x] `rye run ruff check support/ tests/test_framework_selfcheck.py` —
clean
- [x] CI run on this PR — `api_integration_tests` + all 4
`api_regression_tests` matrix jobs green
- [x] CI run — `api_fuzz_tests` runs cleanly (informational; surfaces
7–10 unique 5xx panics per run)

## Note on test count

The `test_streaming.py` rewrite folded 7 "tests" (`test_ingest_data`,
`test_ingest_join`, `test_disable_streaming`,
`test_update_max_query_range`, `test_enable_streaming`,
`test_delete_stream`, `test_delete_stream_join`) into pytest fixtures.
Each only checked `status_code == 200` of a setup/teardown operation —
they were imperative steps masquerading as tests. The fixtures still
perform the same operations and assert their success; they're just no
longer counted as discrete pytest items. **Functional coverage is
identical.**

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-01 07:19:48 +00:00

910 lines
47 KiB
Python

import random
from requests.auth import HTTPBasicAuth
class DashboardPage:
# Make Unique_value_destination a class variable
Unique_value_dashboard = f"d3m21_{random.randint(100000, 999999)}"
def __init__(self, session, base_url, org_id):
self.session = session
self.base_url = base_url
self.org_id = org_id
def create_dashboard(self, session, base_url, user_email, user_password, org_id, stream_name, folder_id, dashboard_name):
"""Create a dashboard."""
session.auth = HTTPBasicAuth(user_email, user_password)
headers = {
"Content-Type": "application/json",
"Custom-Header": "value"
}
payload = {
"version": 5,
"title": dashboard_name,
"description": "",
"role": "",
"owner": user_email, # Set to the user's email
"tabs": [
{
"tabId": "default",
"name": "Default",
"panels": [
{
"id": "Panel_ID9034710",
"type": "bar",
"title": "P1",
"description": "",
"config": {
"show_legends": True,
"legends_position": None,
"decimals": 2,
"line_thickness": 1.5,
"step_value": "0",
"top_results_others": False,
"axis_border_show": False,
"label_option": {
"rotate": 0
},
"show_symbol": True,
"line_interpolation": "smooth",
"legend_width": {
"unit": "px"
},
"base_map": {
"type": "osm"
},
"map_type": {
"type": "world"
},
"map_view": {
"zoom": 1,
"lat": 0,
"lng": 0
},
"map_symbol_style": {
"size": "by Value",
"size_by_value": {
"min": 1,
"max": 100
},
"size_fixed": 2
},
"drilldown": [],
"mark_line": [],
"override_config": [],
"connect_nulls": False,
"no_value_replacement": "",
"wrap_table_cells": False,
"table_transpose": False,
"table_dynamic_columns": False,
"color": {
"mode": "palette-classic-by-series",
"fixedColor": [
"#53ca53"
],
"seriesBy": "last"
},
"trellis": {
"layout": None,
"num_of_columns": 1
}
},
"queryType": "sql",
"queries": [
{
"query": f"SELECT histogram(_timestamp) as \"x_axis_1\", count(kubernetes_namespace_name) as \"y_axis_1\", kubernetes_labels_name as \"breakdown_1\" FROM \"{stream_name}\" GROUP BY x_axis_1, breakdown_1 ORDER BY x_axis_1 ASC",
"vrlFunctionQuery": "",
"customQuery": False,
"fields": {
"stream": stream_name,
"stream_type": "logs",
"x": [
{
"label": "Timestamp",
"alias": "x_axis_1",
"column": "_timestamp",
"color": None,
"aggregationFunction": "histogram",
"sortBy": "ASC",
"isDerived": False
}
],
"y": [
{
"label": "Kubernetes Namespace Name",
"alias": "y_axis_1",
"column": "kubernetes_namespace_name",
"color": "#5960b2",
"aggregationFunction": "count",
"isDerived": False
}
],
"z": [],
"breakdown": [
{
"label": "Kubernetes Labels Name",
"alias": "breakdown_1",
"column": "kubernetes_labels_name",
"color": None,
"isDerived": False
}
],
"filter": {
"filterType": "group",
"logicalOperator": "AND",
"conditions": []
}
},
"config": {
"promql_legend": "",
"layer_type": "scatter",
"weight_fixed": 1,
"limit": 0,
"min": 0,
"max": 100,
"time_shift": []
}
}
],
"layout": {
"x": 0,
"y": 0,
"w": 24,
"h": 9,
"i": 1,
"moved": False
},
"htmlContent": "",
"markdownContent": "",
"customChartContent": " // To know more about ECharts , \n// visit: https://echarts.apache.org/examples/en/index.html \n// Example: https://echarts.apache.org/examples/en/editor.html?c=line-simple \n// Define your ECharts 'option' here. \n// 'data' variable is available for use and contains the response data from the search result and it is an array.\noption = { \n \n};\n "
},
{
"id": "Panel_ID8353510",
"type": "h-bar",
"title": "P4",
"description": "",
"config": {
"show_legends": True,
"legends_position": None,
"decimals": 2,
"line_thickness": 1.5,
"step_value": "0",
"top_results_others": False,
"axis_border_show": False,
"label_option": {
"rotate": 0
},
"show_symbol": True,
"line_interpolation": "smooth",
"legend_width": {
"unit": "px"
},
"base_map": {
"type": "osm"
},
"map_type": {
"type": "world"
},
"map_view": {
"zoom": 1,
"lat": 0,
"lng": 0
},
"map_symbol_style": {
"size": "by Value",
"size_by_value": {
"min": 1,
"max": 100
},
"size_fixed": 2
},
"drilldown": [],
"mark_line": [],
"override_config": [],
"connect_nulls": False,
"no_value_replacement": "",
"wrap_table_cells": False,
"table_transpose": False,
"table_dynamic_columns": False,
"color": {
"mode": "palette-classic-by-series",
"fixedColor": [
"#53ca53"
],
"seriesBy": "last"
},
"trellis": {
"layout": None,
"num_of_columns": 1
}
},
"queryType": "sql",
"queries": [
{
"query": f"SELECT histogram(_timestamp) as \"x_axis_1\", count(kubernetes_namespace_name) as \"y_axis_1\", kubernetes_labels_name as \"breakdown_1\" FROM \"{stream_name}\" GROUP BY x_axis_1, breakdown_1 ORDER BY x_axis_1 ASC",
"vrlFunctionQuery": "",
"customQuery": False,
"fields": {
"stream": stream_name,
"stream_type": "logs",
"x": [
{
"label": "Timestamp",
"alias": "x_axis_1",
"column": "_timestamp",
"color": None,
"aggregationFunction": "histogram",
"sortBy": "ASC",
"isDerived": False
}
],
"y": [
{
"label": "Kubernetes Namespace Name",
"alias": "y_axis_1",
"column": "kubernetes_namespace_name",
"color": "#5960b2",
"aggregationFunction": "count",
"isDerived": False
}
],
"z": [],
"breakdown": [
{
"label": "Kubernetes Labels Name",
"alias": "breakdown_1",
"column": "kubernetes_labels_name",
"color": None,
"isDerived": False
}
],
"filter": {
"filterType": "group",
"logicalOperator": "AND",
"conditions": []
}
},
"config": {
"promql_legend": "",
"layer_type": "scatter",
"weight_fixed": 1,
"limit": 0,
"min": 0,
"max": 100,
"time_shift": []
}
}
],
"layout": {
"x": 24,
"y": 0,
"w": 24,
"h": 9,
"i": 2,
"moved": False
},
"htmlContent": "",
"markdownContent": "",
"customChartContent": " // To know more about ECharts , \n// visit: https://echarts.apache.org/examples/en/index.html \n// Example: https://echarts.apache.org/examples/en/editor.html?c=line-simple \n// Define your ECharts 'option' here. \n// 'data' variable is available for use and contains the response data from the search result and it is an array.\noption = { \n \n};\n "
}
]
},
{
"tabId": "39193",
"name": "count",
"panels": [
{
"id": "Panel_ID1546910",
"type": "bar",
"title": "count",
"description": "",
"config": {
"show_legends": True,
"legends_position": None,
"decimals": 2,
"line_thickness": 1.5,
"step_value": "0",
"top_results_others": False,
"axis_border_show": False,
"label_option": {
"rotate": 0
},
"show_symbol": True,
"line_interpolation": "smooth",
"legend_width": {
"unit": "px"
},
"base_map": {
"type": "osm"
},
"map_type": {
"type": "world"
},
"map_view": {
"zoom": 1,
"lat": 0,
"lng": 0
},
"map_symbol_style": {
"size": "by Value",
"size_by_value": {
"min": 1,
"max": 100
},
"size_fixed": 2
},
"drilldown": [],
"mark_line": [],
"override_config": [],
"connect_nulls": False,
"no_value_replacement": "",
"wrap_table_cells": False,
"table_transpose": False,
"table_dynamic_columns": False,
"color": {
"mode": "palette-classic-by-series",
"fixedColor": [
"#53ca53"
],
"seriesBy": "last"
},
"trellis": {
"layout": None,
"num_of_columns": 1
}
},
"queryType": "sql",
"queries": [
{
"query": f"SELECT histogram(_timestamp) as \"x_axis_1\", count(_timestamp) as \"y_axis_1\" FROM \"{stream_name}\" GROUP BY x_axis_1 ORDER BY x_axis_1 ASC",
"vrlFunctionQuery": "",
"customQuery": False,
"fields": {
"stream": stream_name,
"stream_type": "logs",
"x": [
{
"label": "Timestamp",
"alias": "x_axis_1",
"column": "_timestamp",
"color": None,
"aggregationFunction": "histogram",
"sortBy": "ASC",
"isDerived": False
}
],
"y": [
{
"label": "Timestamp",
"alias": "y_axis_1",
"column": "_timestamp",
"color": "#5960b2",
"aggregationFunction": "count",
"isDerived": False
}
],
"z": [],
"breakdown": [],
"filter": {
"filterType": "group",
"logicalOperator": "AND",
"conditions": []
}
},
"config": {
"promql_legend": "",
"layer_type": "scatter",
"weight_fixed": 1,
"limit": 0,
"min": 0,
"max": 100,
"time_shift": []
}
}
],
"layout": {
"x": 0,
"y": 0,
"w": 24,
"h": 9,
"i": 1,
"moved": False
},
"htmlContent": "",
"markdownContent": "",
"customChartContent": " // To know more about ECharts , \n// visit: https://echarts.apache.org/examples/en/index.html \n// Example: https://echarts.apache.org/examples/en/editor.html?c=line-simple \n// Define your ECharts 'option' here. \n// 'data' variable is available for use and contains the response data from the search result and it is an array.\noption = { \n \n};\n "
},
{
"id": "Panel_ID1055010",
"type": "h-bar",
"title": "C1",
"description": "",
"config": {
"show_legends": True,
"legends_position": None,
"decimals": 2,
"line_thickness": 1.5,
"step_value": "0",
"top_results_others": False,
"axis_border_show": False,
"label_option": {
"rotate": 0
},
"show_symbol": True,
"line_interpolation": "smooth",
"legend_width": {
"unit": "px"
},
"base_map": {
"type": "osm"
},
"map_type": {
"type": "world"
},
"map_view": {
"zoom": 1,
"lat": 0,
"lng": 0
},
"map_symbol_style": {
"size": "by Value",
"size_by_value": {
"min": 1,
"max": 100
},
"size_fixed": 2
},
"drilldown": [],
"mark_line": [],
"override_config": [],
"connect_nulls": False,
"no_value_replacement": "",
"wrap_table_cells": False,
"table_transpose": False,
"table_dynamic_columns": False,
"color": {
"mode": "palette-classic-by-series",
"fixedColor": [
"#53ca53"
],
"seriesBy": "last"
},
"trellis": {
"layout": None,
"num_of_columns": 1
}
},
"queryType": "sql",
"queries": [
{
"query": f"SELECT histogram(_timestamp) as \"x_axis_1\", count(_timestamp) as \"y_axis_1\" FROM \"{stream_name}\" GROUP BY x_axis_1 ORDER BY x_axis_1 ASC",
"vrlFunctionQuery": "",
"customQuery": False,
"fields": {
"stream": stream_name,
"stream_type": "logs",
"x": [
{
"label": "Timestamp",
"alias": "x_axis_1",
"column": "_timestamp",
"color": None,
"aggregationFunction": "histogram",
"sortBy": "ASC",
"isDerived": False
}
],
"y": [
{
"label": "Timestamp",
"alias": "y_axis_1",
"column": "_timestamp",
"color": "#5960b2",
"aggregationFunction": "count",
"isDerived": False
}
],
"z": [],
"breakdown": [],
"filter": {
"filterType": "group",
"logicalOperator": "AND",
"conditions": []
}
},
"config": {
"promql_legend": "",
"layer_type": "scatter",
"weight_fixed": 1,
"limit": 0,
"min": 0,
"max": 100,
"time_shift": []
}
}
],
"layout": {
"x": 24,
"y": 0,
"w": 24,
"h": 9,
"i": 2,
"moved": False
},
"htmlContent": "",
"markdownContent": "",
"customChartContent": " // To know more about ECharts , \n// visit: https://echarts.apache.org/examples/en/index.html \n// Example: https://echarts.apache.org/examples/en/editor.html?c=line-simple \n// Define your ECharts 'option' here. \n// 'data' variable is available for use and contains the response data from the search result and it is an array.\noption = { \n \n};\n "
}
]
},
{
"tabId": "34948",
"name": "Tes",
"panels": [
{
"id": "Panel_ID5902410",
"type": "bar",
"title": "Test2",
"description": "",
"config": {
"show_legends": True,
"legends_position": None,
"decimals": 2,
"line_thickness": 1.5,
"step_value": "0",
"top_results_others": False,
"axis_border_show": False,
"label_option": {
"rotate": 0
},
"show_symbol": True,
"line_interpolation": "smooth",
"legend_width": {
"unit": "px"
},
"base_map": {
"type": "osm"
},
"map_type": {
"type": "world"
},
"map_view": {
"zoom": 1,
"lat": 0,
"lng": 0
},
"map_symbol_style": {
"size": "by Value",
"size_by_value": {
"min": 1,
"max": 100
},
"size_fixed": 2
},
"drilldown": [],
"mark_line": [],
"override_config": [],
"connect_nulls": False,
"no_value_replacement": "",
"wrap_table_cells": False,
"table_transpose": False,
"table_dynamic_columns": False,
"color": {
"mode": "palette-classic-by-series",
"fixedColor": [
"#53ca53"
],
"seriesBy": "last"
},
"trellis": {
"layout": None,
"num_of_columns": 1
}
},
"queryType": "sql",
"queries": [
{
"query": f"SELECT histogram(_timestamp) as \"x_axis_1\", count(distinct(_timestamp)) as \"y_axis_1\" FROM \"{stream_name}\" GROUP BY x_axis_1 ORDER BY x_axis_1 ASC",
"vrlFunctionQuery": "",
"customQuery": False,
"fields": {
"stream": stream_name,
"stream_type": "logs",
"x": [
{
"label": "Timestamp",
"alias": "x_axis_1",
"column": "_timestamp",
"color": None,
"aggregationFunction": "histogram",
"sortBy": "ASC",
"isDerived": False
}
],
"y": [
{
"label": "Timestamp",
"alias": "y_axis_1",
"column": "_timestamp",
"color": "#5960b2",
"aggregationFunction": "count-distinct",
"isDerived": False
}
],
"z": [],
"breakdown": [],
"filter": {
"filterType": "group",
"logicalOperator": "AND",
"conditions": []
}
},
"config": {
"promql_legend": "",
"layer_type": "scatter",
"weight_fixed": 1,
"limit": 0,
"min": 0,
"max": 100,
"time_shift": []
}
}
],
"layout": {
"x": 0,
"y": 0,
"w": 24,
"h": 9,
"i": 1,
"moved": False
},
"htmlContent": "",
"markdownContent": "",
"customChartContent": " // To know more about ECharts , \n// visit: https://echarts.apache.org/examples/en/index.html \n// Example: https://echarts.apache.org/examples/en/editor.html?c=line-simple \n// Define your ECharts 'option' here. \n// 'data' variable is available for use and contains the response data from the search result and it is an array.\noption = { \n \n};\n "
}
]
}
],
"variables": {
"list": [],
"showDynamicFilters": True
},
"defaultDatetimeDuration": {
"type": "relative",
"relativeTimePeriod": "45m"
}
}
response = session.post(f"{base_url}api/{org_id}/dashboards?folder={folder_id}", json=payload, headers=headers)
assert response.status_code == 200, f"Failed to create panel: {response.content.decode()}"
dashboard_id = response.json()["v5"]["dashboardId"]
return dashboard_id
def create_dashboard_with_time_shift(self, session, base_url, user_email, user_password, org_id, stream_name, folder_id, dashboard_name):
"""Create a dashboard with time_shift (comparison against past data)."""
session.auth = HTTPBasicAuth(user_email, user_password)
headers = {
"Content-Type": "application/json",
"Custom-Header": "value"
}
payload = {
"version": 5,
"title": dashboard_name,
"description": "Dashboard with time shift comparison",
"role": "",
"owner": user_email,
"tabs": [
{
"tabId": "default",
"name": "Time Comparison",
"panels": [
{
"id": "Panel_TimeShift_1",
"type": "line",
"title": "Count with Time Shift Comparison",
"description": "Comparing current data vs 1h ago, 1d ago, 1w ago",
"config": {
"show_legends": True,
"legends_position": "bottom",
"decimals": 2,
"line_thickness": 2,
"show_symbol": True,
"line_interpolation": "smooth",
"connect_nulls": False
},
"queryType": "sql",
"queries": [
{
"query": f"SELECT histogram(_timestamp) as \"x_axis_1\", count(*) as \"y_axis_1\" FROM \"{stream_name}\" GROUP BY x_axis_1 ORDER BY x_axis_1 ASC",
"vrlFunctionQuery": "",
"customQuery": False,
"fields": {
"stream": stream_name,
"stream_type": "logs",
"x": [
{
"label": "Timestamp",
"alias": "x_axis_1",
"column": "_timestamp",
"aggregationFunction": "histogram",
"sortBy": "ASC"
}
],
"y": [
{
"label": "Count",
"alias": "y_axis_1",
"column": "*",
"aggregationFunction": "count"
}
],
"z": [],
"breakdown": [],
"filter": {
"filterType": "group",
"logicalOperator": "AND",
"conditions": []
}
},
"config": {
"promql_legend": "",
"layer_type": "line",
"time_shift": [
{"offSet": "1h"},
{"offSet": "1d"},
{"offSet": "1w"}
]
}
}
],
"layout": {
"x": 0,
"y": 0,
"w": 48,
"h": 12,
"i": 1
}
},
{
"id": "Panel_TimeShift_2",
"type": "area",
"title": "Error Rate Comparison",
"description": "Error rate vs previous periods",
"config": {
"show_legends": True,
"legends_position": "right",
"decimals": 2,
"line_thickness": 1.5,
"show_symbol": False,
"line_interpolation": "smooth"
},
"queryType": "sql",
"queries": [
{
"query": f"SELECT histogram(_timestamp) as \"x_axis_1\", count(*) as \"y_axis_1\" FROM \"{stream_name}\" WHERE code >= 400 GROUP BY x_axis_1 ORDER BY x_axis_1 ASC",
"vrlFunctionQuery": "",
"customQuery": False,
"fields": {
"stream": stream_name,
"stream_type": "logs",
"x": [
{
"label": "Timestamp",
"alias": "x_axis_1",
"column": "_timestamp",
"aggregationFunction": "histogram",
"sortBy": "ASC"
}
],
"y": [
{
"label": "Error Count",
"alias": "y_axis_1",
"column": "*",
"aggregationFunction": "count"
}
],
"z": [],
"breakdown": [],
"filter": {
"filterType": "group",
"logicalOperator": "AND",
"conditions": []
}
},
"config": {
"promql_legend": "",
"layer_type": "area",
"time_shift": [
{"offSet": "24h"}
]
}
}
],
"layout": {
"x": 0,
"y": 12,
"w": 24,
"h": 10,
"i": 2
}
},
{
"id": "Panel_TimeShift_3",
"type": "bar",
"title": "Namespace Activity Comparison",
"description": "Activity by namespace vs yesterday",
"config": {
"show_legends": True,
"legends_position": "bottom",
"decimals": 0
},
"queryType": "sql",
"queries": [
{
"query": f"SELECT kubernetes_namespace_name as \"x_axis_1\", count(*) as \"y_axis_1\" FROM \"{stream_name}\" GROUP BY x_axis_1 ORDER BY y_axis_1 DESC LIMIT 10",
"vrlFunctionQuery": "",
"customQuery": False,
"fields": {
"stream": stream_name,
"stream_type": "logs",
"x": [
{
"label": "Namespace",
"alias": "x_axis_1",
"column": "kubernetes_namespace_name"
}
],
"y": [
{
"label": "Count",
"alias": "y_axis_1",
"column": "*",
"aggregationFunction": "count"
}
],
"z": [],
"breakdown": [],
"filter": {
"filterType": "group",
"logicalOperator": "AND",
"conditions": []
}
},
"config": {
"promql_legend": "",
"layer_type": "bar",
"time_shift": [
{"offSet": "1d"}
]
}
}
],
"layout": {
"x": 24,
"y": 12,
"w": 24,
"h": 10,
"i": 3
}
}
]
}
],
"variables": {
"list": [],
"showDynamicFilters": True
},
"defaultDatetimeDuration": {
"type": "relative",
"relativeTimePeriod": "6h"
}
}
response = session.post(f"{base_url}api/{org_id}/dashboards?folder={folder_id}", json=payload, headers=headers)
assert response.status_code == 200, f"Failed to create dashboard with time_shift: {response.content.decode()}"
dashboard_id = response.json()["v5"]["dashboardId"]
return dashboard_id