Files
openobserve/tests/api-testing/tests/conftest.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

147 lines
5.3 KiB
Python

import requests
import pytest
import os
import random
import string
import logging
from pathlib import Path
import base64
# Make the new framework fixtures available to all tests (Phase 4+).
# Legacy tests still use create_session/base_url/org_id below.
from support.fixtures import client, temp_stream_name, temp_user_email, temp_dashboard_id # noqa: F401
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
BASE_URL = os.environ["ZO_BASE_URL"]
DEFAULT_ORG_ID = os.environ.get("TEST_ORG_ID", "default")
root_dir = Path(__file__).parent.parent.parent
@pytest.fixture(scope="module")
def random_string():
"""Generate a random string of specified length."""
def _generate(length=5):
# ascii_letters consist of alphabets for 'a' to 'z' and 'A' to 'Z'
# digits consist of '0' to '9'
characters = string.ascii_letters + string.digits
return "".join(random.choices(characters, k=length))
return _generate
def _create_session_inner():
s = requests.Session()
username = os.environ["ZO_ROOT_USER_EMAIL"]
password = os.environ["ZO_ROOT_USER_PASSWORD"]
s.auth = (username, password)
resp = s.post(BASE_URL)
return s
def _create_session_inner_v2():
s = requests.Session()
username = os.environ["ZO_ROOT_USER_EMAIL"]
password = os.environ["ZO_ROOT_USER_PASSWORD"]
# Set Authorization header for all requests
basic_auth = base64.b64encode(f"{username}:{password}".encode()).decode()
s.headers.update({"Authorization": f"Basic {basic_auth}"})
return s
@pytest.fixture(scope="module")
def create_session():
"""Create a session and return it."""
return _create_session_inner_v2()
@pytest.fixture(scope="module")
def base_url():
"""Return the base URL with trailing slash."""
url = BASE_URL
return url if url.endswith('/') else url + '/'
@pytest.fixture(scope="module")
def org_id():
"""Return the organization ID for testing.
Can be overridden via TEST_ORG_ID environment variable.
"""
return DEFAULT_ORG_ID
@pytest.fixture(scope="session", autouse=True)
def ingest_data():
"""Ingest data into the openobserve running instance.
Replaces blind `time.sleep(N)` waits with a wait_until predicate that
polls the search endpoint until the ingested rows are visible.
"""
from support.wait import wait_until
# Use v2 session for consistent auth header
session = _create_session_inner_v2()
# Ingest main test data
with open(root_dir / "test-data/logs_data.json") as f:
data = f.read()
stream_name = "stream_pytest_data"
org = DEFAULT_ORG_ID
base_url_with_slash = BASE_URL if BASE_URL.endswith('/') else BASE_URL + '/'
url = f"{base_url_with_slash}api/{org}/{stream_name}/_json"
resp1 = session.post(url, data=data, headers={"Content-Type": "application/json"})
logging.info("Main data ingested successfully, status code: %s", resp1.status_code)
assert resp1.status_code == 200, \
f"Failed to ingest main test data: {resp1.status_code} - {resp1.text[:500]}"
# Ingest camel case test data
with open(root_dir / "test-data/match_all.json") as f:
camel_data = f.read()
resp2 = session.post(url, data=camel_data, headers={"Content-Type": "application/json"})
logging.info("Camel case data ingested successfully, status code: %s", resp2.status_code)
assert resp2.status_code == 200, \
f"Failed to ingest camel case test data: {resp2.status_code} - {resp2.text[:500]}"
# Flush data to ensure it's indexed (no-op in local mode; returns 404)
flush_url = f"{base_url_with_slash}node/flush"
logging.info("Flushing data to ensure indexing...")
flush_resp = session.put(flush_url)
if flush_resp.status_code == 200:
logging.info("Data flushed successfully")
elif flush_resp.status_code == 404:
logging.info("Flush not needed (local mode), polling for auto-indexing...")
else:
logging.warning("Flush request returned status %s: %s", flush_resp.status_code, flush_resp.text[:200])
# Poll the search endpoint until ingested data is visible — replaces the
# combined 5s of `time.sleep` with a deterministic check that exits as
# soon as the data is queryable (typically <1s on local, may take longer
# on slow CI runners).
def _data_is_searchable():
# Use the same auth/session shape that tests use.
search_url = f"{base_url_with_slash}api/{org}/_search?type=logs"
# Wide window: data fixtures may have older timestamps.
from datetime import datetime, timedelta, timezone
now = datetime.now(timezone.utc)
end_us = int(now.timestamp() * 1_000_000)
start_us = int((now - timedelta(weeks=2)).timestamp() * 1_000_000)
payload = {
"query": {
"sql": f'SELECT COUNT(*) AS c FROM "{stream_name}"',
"start_time": start_us,
"end_time": end_us,
"from": 0,
"size": 1,
}
}
r = session.post(search_url, json=payload)
if r.status_code != 200:
return False
hits = r.json().get("hits", [])
return bool(hits and hits[0].get("c", 0) > 0)
wait_until(_data_is_searchable, timeout=30, interval=0.5, msg="ingested data not searchable")
logging.info("Ingested data is searchable")
return True