Мониторинг и отчёты

Синтетическая проверка сценария

Выполняет цепочку HTTP-шагов из JSON-конфига и проверяет коды, текст и JSON-поля.

Python Windows macOS Linux Продвинутый
Скачать synthetic_check.py
Описание

Что делает скрипт

Скрипт читает сценарий из JSON, последовательно выполняет запросы и проверяет ожидаемый статус, наличие подстроки и значение JSON-поля. Для каждого шага измеряется время и задается свой лимит. Подходит для проверки ключевого пользовательского пути на example.com или localhost.

Запуск

Быстрый старт

python synthetic_check.py --config synthetic.json

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python synthetic_check.py --config synthetic.json --timeout 15
  • python synthetic_check.py --config synthetic.json --json
Зависимости

Что понадобится

Python 3.10+ Только стандартная библиотека
Windows winget install Python.Python.3.12
macOS brew install python
Linux sudo apt install python3
Исходник

synthetic_check.py

#!/usr/bin/env python3
"""Синтетическая проверка последовательности HTTP-шагов."""
from __future__ import annotations

import argparse
import json
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path


def load_steps(path: Path) -> list[dict]:
    data = json.loads(path.read_text(encoding="utf-8"))
    if isinstance(data, dict):
        data = data.get("steps")
    if not isinstance(data, list) or not data:
        raise ValueError("в конфиге нужен непустой список steps")
    for index, step in enumerate(data, start=1):
        if not isinstance(step, dict) or not step.get("url"):
            raise ValueError(f"шаг {index}: нет поля url")
        if not str(step["url"]).startswith(("http://", "https://")):
            raise ValueError(f"шаг {index}: нужен http или https")
    return data


def nested_value(payload, dotted: str):
    current = payload
    for part in dotted.split("."):
        if not isinstance(current, dict) or part not in current:
            return None
        current = current[part]
    return current


def run_step(step: dict, timeout: float) -> dict:
    method = str(step.get("method", "GET")).upper()
    headers = dict(step.get("headers") or {})
    body = None
    if "json" in step:
        body = json.dumps(step["json"]).encode("utf-8")
        headers.setdefault("Content-Type", "application/json")
    elif "body" in step:
        body = str(step["body"]).encode("utf-8")

    request = urllib.request.Request(str(step["url"]), data=body, headers=headers, method=method)
    started = time.perf_counter()
    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            status = int(response.status)
            raw = response.read()
    except urllib.error.HTTPError as error:
        status = int(error.code)
        raw = error.read()
    except (urllib.error.URLError, TimeoutError, OSError) as error:
        return {
            "name": step.get("name", step["url"]),
            "url": step["url"],
            "ok": False,
            "status": 0,
            "ms": 0,
            "error": str(error),
        }

    elapsed_ms = int((time.perf_counter() - started) * 1000)
    expected = step.get("expect_status", 200)
    if isinstance(expected, int):
        expected = [expected]
    problems = []
    if status not in expected:
        problems.append(f"status {status} not in {expected}")

    text = raw.decode("utf-8", errors="replace")
    if step.get("contains") and step["contains"] not in text:
        problems.append(f"body does not contain {step['contains']!r}")

    if step.get("json_field"):
        try:
            payload = json.loads(text)
        except json.JSONDecodeError:
            problems.append("body is not valid JSON")
        else:
            value = nested_value(payload, str(step["json_field"]))
            if "json_value" in step and value != step["json_value"]:
                problems.append(f"json field {step['json_field']} is {value!r}")

    max_ms = int(step.get("max_ms", 0) or 0)
    if max_ms and elapsed_ms > max_ms:
        problems.append(f"{elapsed_ms} ms above {max_ms} ms")

    return {
        "name": step.get("name", step["url"]),
        "url": step["url"],
        "ok": not problems,
        "status": status,
        "ms": elapsed_ms,
        "error": "; ".join(problems),
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="Синтетическая проверка HTTP-сценария")
    parser.add_argument("--config", required=True, type=Path)
    parser.add_argument("--timeout", type=float, default=10.0)
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()

    try:
        steps = load_steps(args.config)
    except (OSError, ValueError, json.JSONDecodeError) as error:
        print(f"ОШИБКА: {error}", file=sys.stderr)
        return 2

    results = [run_step(step, args.timeout) for step in steps]
    if args.json:
        print(json.dumps({"steps": results}, ensure_ascii=False, indent=2))
    else:
        for result in results:
            mark = "PASS" if result["ok"] else "FAIL"
            print(f"{mark} {result['name']}: HTTP {result['status']}, {result['ms']} ms")
            if result["error"]:
                print(f"     {result['error']}")
        failed = sum(1 for result in results if not result["ok"])
        print(f"Шагов: {len(results)}, ошибок: {failed}")

    return 1 if any(not result["ok"] for result in results) else 0


if __name__ == "__main__":
    raise SystemExit(main())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get monitoring-synthetic
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Мониторинг и отчёты

Сбор метрик, проверка доступности, отчёты и уведомления.