pr-perfguard 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pr_perfguard-0.2.0/PKG-INFO +153 -0
- pr_perfguard-0.2.0/README.md +137 -0
- pr_perfguard-0.2.0/pyproject.toml +38 -0
- pr_perfguard-0.2.0/setup.cfg +4 -0
- pr_perfguard-0.2.0/src/perfguard/__init__.py +3 -0
- pr_perfguard-0.2.0/src/perfguard/cli.py +188 -0
- pr_perfguard-0.2.0/src/perfguard/config.py +239 -0
- pr_perfguard-0.2.0/src/perfguard/metrics.py +281 -0
- pr_perfguard-0.2.0/src/perfguard/reporter.py +120 -0
- pr_perfguard-0.2.0/src/perfguard/runner.py +386 -0
- pr_perfguard-0.2.0/src/pr_perfguard.egg-info/PKG-INFO +153 -0
- pr_perfguard-0.2.0/src/pr_perfguard.egg-info/SOURCES.txt +18 -0
- pr_perfguard-0.2.0/src/pr_perfguard.egg-info/dependency_links.txt +1 -0
- pr_perfguard-0.2.0/src/pr_perfguard.egg-info/entry_points.txt +2 -0
- pr_perfguard-0.2.0/src/pr_perfguard.egg-info/requires.txt +7 -0
- pr_perfguard-0.2.0/src/pr_perfguard.egg-info/top_level.txt +1 -0
- pr_perfguard-0.2.0/tests/test_cli_and_runner.py +306 -0
- pr_perfguard-0.2.0/tests/test_config.py +117 -0
- pr_perfguard-0.2.0/tests/test_metrics.py +116 -0
- pr_perfguard-0.2.0/tests/test_reporter.py +128 -0
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pr-perfguard
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: CLI and GitHub Action for automated API performance regression testing in Pull Requests.
|
|
5
|
+
Author-email: Bekzat <intelect23235@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: benchmark,load-testing,ci,github-action,performance,regression
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
Requires-Dist: httpx>=0.27.0
|
|
11
|
+
Requires-Dist: psutil>=6.0.0
|
|
12
|
+
Requires-Dist: PyYAML>=6.0.1
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
15
|
+
Requires-Dist: ruff>=0.6.0; extra == "dev"
|
|
16
|
+
|
|
17
|
+
# PR-PerfGuard
|
|
18
|
+
|
|
19
|
+
**CLI и GitHub Action для автоматического регрессионного нагрузочного тестирования в Pull Requests.**
|
|
20
|
+
|
|
21
|
+
PR-PerfGuard поднимает ваш сервис прямо в CI, прогревает его, прогоняет асинхронный нагрузочный сценарий (`RPS`, `p50 / p95 / p99` latency, `error rate`, `peak RSS memory`), сравнивает результаты с baseline-отчётом из `main` и публикует в PR наглядный Markdown-отчёт (sticky comment) со статусом **PASS / FAIL** по заданным порогам.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Пример отчёта в Pull Request
|
|
26
|
+
|
|
27
|
+
> ## 🛡️ PR-PerfGuard Report — ❌ **REGRESSION DETECTED**
|
|
28
|
+
>
|
|
29
|
+
> - **Target:** `http://127.0.0.1:8000/api/items`
|
|
30
|
+
> - **Load:** `25` concurrent workers × `15.0s` (`18420` requests)
|
|
31
|
+
>
|
|
32
|
+
> | Metric | Baseline (`main`) | PR | Delta | Threshold | Status |
|
|
33
|
+
> | :--- | ---: | ---: | ---: | :--- | :---: |
|
|
34
|
+
> | p50 Latency | 12.40 ms | 13.10 ms | +5.65% | `info` | ✅ |
|
|
35
|
+
> | p95 Latency | 24.80 ms | 32.50 ms | +31.05% | `<= +15.0%` | ❌ |
|
|
36
|
+
> | p99 Latency | 41.20 ms | 48.00 ms | +16.50% | `<= +25.0%` | ✅ |
|
|
37
|
+
> | Throughput (RPS) | 1280.00 req/s | 1228.00 req/s | -4.06% | `drop <= 10.0%` | ✅ |
|
|
38
|
+
> | Error Rate | 0.00% | 0.00% | +0.00 pp | `<= 1.0%` | ✅ |
|
|
39
|
+
> | Peak RSS Memory | 84.50 MB | 88.20 MB | +4.38% | `<= +20.0%` | ✅ |
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## Установка и быстрый старт
|
|
44
|
+
|
|
45
|
+
Из GitHub (без публикации в PyPI):
|
|
46
|
+
```bash
|
|
47
|
+
pip install git+https://github.com/b3mug1/pr-perfguard.git
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Или локально для разработки:
|
|
51
|
+
```bash
|
|
52
|
+
pip install -e ".[dev]"
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### 1. Создайте конфиг `perfguard.yml`
|
|
56
|
+
```bash
|
|
57
|
+
perfguard init
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### 2. Снимите baseline (например, на ветке `main`)
|
|
61
|
+
```bash
|
|
62
|
+
perfguard run --config perfguard.yml --out .perfguard/baseline.json
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### 3. Проверьте изменения в PR
|
|
66
|
+
```bash
|
|
67
|
+
perfguard check --config perfguard.yml --baseline .perfguard/baseline.json --out .perfguard/current.json
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Команда вернёт exit code `1`, если хотя бы одна метрика превысила допустимый порог регрессии.
|
|
71
|
+
|
|
72
|
+
Также можно запускать без `perfguard.yml` — напрямую через флаги:
|
|
73
|
+
```bash
|
|
74
|
+
perfguard run --url http://127.0.0.1:8000/health --concurrency 20 --duration 10 --repeats 3 --out baseline.json
|
|
75
|
+
perfguard compare baseline.json current.json
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## Продвинутая конфигурация (`perfguard.yml`)
|
|
81
|
+
|
|
82
|
+
- **Мульти-эндпоинтовые сценарии (`load.endpoints`)**: задавайте несколько маршрутов с весами (`weight`), разными HTTP-методами, заголовками, телом запроса и ожидаемыми статус-кодами (`expected_statuses`, по умолчанию `200..399`).
|
|
83
|
+
- **Переменные окружения**: в `url`, `headers` и `body` поддерживается подстановка `${VAR_NAME}` из `os.environ`.
|
|
84
|
+
- **Фиксированный RPS (`load.target_rps` / `--target-rps`)**: позволяет задать целевую интенсивность нагрузки (req/s) вместо максимального насыщения — удобно для точного сравнения latency между `main` и PR при одинаковом трафике.
|
|
85
|
+
- **Защита от шума CI**:
|
|
86
|
+
- `load.repeats` (или `--repeats N`) — прогоняет N замеров после прогрева и берёт медиану по каждой метрике.
|
|
87
|
+
- `thresholds.min_p95_delta_ms` / `min_p99_delta_ms` — минимальный абсолютный порог прироста задержки в миллисекундах, чтобы микроскопические колебания не давали ложный `FAIL`.
|
|
88
|
+
- **Строгая валидация**: опечатки в ключах и неверные значения в `perfguard.yml` сразу приводят к понятной ошибке при старте.
|
|
89
|
+
|
|
90
|
+
Полный пример смотрите в [examples/perfguard.yml](examples/perfguard.yml).
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Использование как GitHub Action
|
|
95
|
+
|
|
96
|
+
```yaml
|
|
97
|
+
name: Performance Guard
|
|
98
|
+
on:
|
|
99
|
+
push:
|
|
100
|
+
branches: [main]
|
|
101
|
+
pull_request:
|
|
102
|
+
branches: [main]
|
|
103
|
+
|
|
104
|
+
jobs:
|
|
105
|
+
baseline:
|
|
106
|
+
if: github.event_name == 'push'
|
|
107
|
+
runs-on: ubuntu-latest
|
|
108
|
+
steps:
|
|
109
|
+
- uses: actions/checkout@v4
|
|
110
|
+
- uses: actions/setup-python@v5
|
|
111
|
+
with:
|
|
112
|
+
python-version: "3.12"
|
|
113
|
+
- run: pip install git+https://github.com/b3mug1/pr-perfguard.git
|
|
114
|
+
- run: perfguard run --config perfguard.yml --out .perfguard/baseline.json
|
|
115
|
+
- uses: actions/cache/save@v4
|
|
116
|
+
with:
|
|
117
|
+
path: .perfguard/baseline.json
|
|
118
|
+
key: perfguard-baseline-${{ github.sha }}
|
|
119
|
+
|
|
120
|
+
perfguard:
|
|
121
|
+
if: github.event_name == 'pull_request'
|
|
122
|
+
runs-on: ubuntu-latest
|
|
123
|
+
permissions:
|
|
124
|
+
pull-requests: write
|
|
125
|
+
steps:
|
|
126
|
+
- uses: actions/checkout@v4
|
|
127
|
+
|
|
128
|
+
- uses: actions/cache/restore@v4
|
|
129
|
+
with:
|
|
130
|
+
path: .perfguard/baseline.json
|
|
131
|
+
key: perfguard-baseline-${{ github.event.pull_request.base.sha }}
|
|
132
|
+
restore-keys: perfguard-baseline-
|
|
133
|
+
|
|
134
|
+
- id: guard
|
|
135
|
+
uses: b3mug1/pr-perfguard@v1
|
|
136
|
+
env:
|
|
137
|
+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
138
|
+
with:
|
|
139
|
+
config: perfguard.yml
|
|
140
|
+
baseline: .perfguard/baseline.json
|
|
141
|
+
pr-number: ${{ github.event.pull_request.number }}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Action также выставляет outputs `passed` (`"true"` / `"false"`) и `report-path` (путь к сгенерированному Markdown-отчёту).
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
## Разработка и тесты
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
ruff check src tests
|
|
152
|
+
pytest -v
|
|
153
|
+
```
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# PR-PerfGuard
|
|
2
|
+
|
|
3
|
+
**CLI и GitHub Action для автоматического регрессионного нагрузочного тестирования в Pull Requests.**
|
|
4
|
+
|
|
5
|
+
PR-PerfGuard поднимает ваш сервис прямо в CI, прогревает его, прогоняет асинхронный нагрузочный сценарий (`RPS`, `p50 / p95 / p99` latency, `error rate`, `peak RSS memory`), сравнивает результаты с baseline-отчётом из `main` и публикует в PR наглядный Markdown-отчёт (sticky comment) со статусом **PASS / FAIL** по заданным порогам.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Пример отчёта в Pull Request
|
|
10
|
+
|
|
11
|
+
> ## 🛡️ PR-PerfGuard Report — ❌ **REGRESSION DETECTED**
|
|
12
|
+
>
|
|
13
|
+
> - **Target:** `http://127.0.0.1:8000/api/items`
|
|
14
|
+
> - **Load:** `25` concurrent workers × `15.0s` (`18420` requests)
|
|
15
|
+
>
|
|
16
|
+
> | Metric | Baseline (`main`) | PR | Delta | Threshold | Status |
|
|
17
|
+
> | :--- | ---: | ---: | ---: | :--- | :---: |
|
|
18
|
+
> | p50 Latency | 12.40 ms | 13.10 ms | +5.65% | `info` | ✅ |
|
|
19
|
+
> | p95 Latency | 24.80 ms | 32.50 ms | +31.05% | `<= +15.0%` | ❌ |
|
|
20
|
+
> | p99 Latency | 41.20 ms | 48.00 ms | +16.50% | `<= +25.0%` | ✅ |
|
|
21
|
+
> | Throughput (RPS) | 1280.00 req/s | 1228.00 req/s | -4.06% | `drop <= 10.0%` | ✅ |
|
|
22
|
+
> | Error Rate | 0.00% | 0.00% | +0.00 pp | `<= 1.0%` | ✅ |
|
|
23
|
+
> | Peak RSS Memory | 84.50 MB | 88.20 MB | +4.38% | `<= +20.0%` | ✅ |
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## Установка и быстрый старт
|
|
28
|
+
|
|
29
|
+
Из GitHub (без публикации в PyPI):
|
|
30
|
+
```bash
|
|
31
|
+
pip install git+https://github.com/b3mug1/pr-perfguard.git
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Или локально для разработки:
|
|
35
|
+
```bash
|
|
36
|
+
pip install -e ".[dev]"
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### 1. Создайте конфиг `perfguard.yml`
|
|
40
|
+
```bash
|
|
41
|
+
perfguard init
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### 2. Снимите baseline (например, на ветке `main`)
|
|
45
|
+
```bash
|
|
46
|
+
perfguard run --config perfguard.yml --out .perfguard/baseline.json
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### 3. Проверьте изменения в PR
|
|
50
|
+
```bash
|
|
51
|
+
perfguard check --config perfguard.yml --baseline .perfguard/baseline.json --out .perfguard/current.json
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Команда вернёт exit code `1`, если хотя бы одна метрика превысила допустимый порог регрессии.
|
|
55
|
+
|
|
56
|
+
Также можно запускать без `perfguard.yml` — напрямую через флаги:
|
|
57
|
+
```bash
|
|
58
|
+
perfguard run --url http://127.0.0.1:8000/health --concurrency 20 --duration 10 --repeats 3 --out baseline.json
|
|
59
|
+
perfguard compare baseline.json current.json
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## Продвинутая конфигурация (`perfguard.yml`)
|
|
65
|
+
|
|
66
|
+
- **Мульти-эндпоинтовые сценарии (`load.endpoints`)**: задавайте несколько маршрутов с весами (`weight`), разными HTTP-методами, заголовками, телом запроса и ожидаемыми статус-кодами (`expected_statuses`, по умолчанию `200..399`).
|
|
67
|
+
- **Переменные окружения**: в `url`, `headers` и `body` поддерживается подстановка `${VAR_NAME}` из `os.environ`.
|
|
68
|
+
- **Фиксированный RPS (`load.target_rps` / `--target-rps`)**: позволяет задать целевую интенсивность нагрузки (req/s) вместо максимального насыщения — удобно для точного сравнения latency между `main` и PR при одинаковом трафике.
|
|
69
|
+
- **Защита от шума CI**:
|
|
70
|
+
- `load.repeats` (или `--repeats N`) — прогоняет N замеров после прогрева и берёт медиану по каждой метрике.
|
|
71
|
+
- `thresholds.min_p95_delta_ms` / `min_p99_delta_ms` — минимальный абсолютный порог прироста задержки в миллисекундах, чтобы микроскопические колебания не давали ложный `FAIL`.
|
|
72
|
+
- **Строгая валидация**: опечатки в ключах и неверные значения в `perfguard.yml` сразу приводят к понятной ошибке при старте.
|
|
73
|
+
|
|
74
|
+
Полный пример смотрите в [examples/perfguard.yml](examples/perfguard.yml).
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
|
|
78
|
+
## Использование как GitHub Action
|
|
79
|
+
|
|
80
|
+
```yaml
|
|
81
|
+
name: Performance Guard
|
|
82
|
+
on:
|
|
83
|
+
push:
|
|
84
|
+
branches: [main]
|
|
85
|
+
pull_request:
|
|
86
|
+
branches: [main]
|
|
87
|
+
|
|
88
|
+
jobs:
|
|
89
|
+
baseline:
|
|
90
|
+
if: github.event_name == 'push'
|
|
91
|
+
runs-on: ubuntu-latest
|
|
92
|
+
steps:
|
|
93
|
+
- uses: actions/checkout@v4
|
|
94
|
+
- uses: actions/setup-python@v5
|
|
95
|
+
with:
|
|
96
|
+
python-version: "3.12"
|
|
97
|
+
- run: pip install git+https://github.com/b3mug1/pr-perfguard.git
|
|
98
|
+
- run: perfguard run --config perfguard.yml --out .perfguard/baseline.json
|
|
99
|
+
- uses: actions/cache/save@v4
|
|
100
|
+
with:
|
|
101
|
+
path: .perfguard/baseline.json
|
|
102
|
+
key: perfguard-baseline-${{ github.sha }}
|
|
103
|
+
|
|
104
|
+
perfguard:
|
|
105
|
+
if: github.event_name == 'pull_request'
|
|
106
|
+
runs-on: ubuntu-latest
|
|
107
|
+
permissions:
|
|
108
|
+
pull-requests: write
|
|
109
|
+
steps:
|
|
110
|
+
- uses: actions/checkout@v4
|
|
111
|
+
|
|
112
|
+
- uses: actions/cache/restore@v4
|
|
113
|
+
with:
|
|
114
|
+
path: .perfguard/baseline.json
|
|
115
|
+
key: perfguard-baseline-${{ github.event.pull_request.base.sha }}
|
|
116
|
+
restore-keys: perfguard-baseline-
|
|
117
|
+
|
|
118
|
+
- id: guard
|
|
119
|
+
uses: b3mug1/pr-perfguard@v1
|
|
120
|
+
env:
|
|
121
|
+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
122
|
+
with:
|
|
123
|
+
config: perfguard.yml
|
|
124
|
+
baseline: .perfguard/baseline.json
|
|
125
|
+
pr-number: ${{ github.event.pull_request.number }}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Action также выставляет outputs `passed` (`"true"` / `"false"`) и `report-path` (путь к сгенерированному Markdown-отчёту).
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
## Разработка и тесты
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
ruff check src tests
|
|
136
|
+
pytest -v
|
|
137
|
+
```
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pr-perfguard"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "CLI and GitHub Action for automated API performance regression testing in Pull Requests."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Bekzat", email = "intelect23235@gmail.com" }]
|
|
13
|
+
keywords = ["benchmark", "load-testing", "ci", "github-action", "performance", "regression"]
|
|
14
|
+
dependencies = [
|
|
15
|
+
"httpx>=0.27.0",
|
|
16
|
+
"psutil>=6.0.0",
|
|
17
|
+
"PyYAML>=6.0.1",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.optional-dependencies]
|
|
21
|
+
dev = [
|
|
22
|
+
"pytest>=8.0.0",
|
|
23
|
+
"ruff>=0.6.0",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.scripts]
|
|
27
|
+
perfguard = "perfguard.cli:main"
|
|
28
|
+
|
|
29
|
+
[tool.setuptools.packages.find]
|
|
30
|
+
where = ["src"]
|
|
31
|
+
|
|
32
|
+
[tool.pytest.ini_options]
|
|
33
|
+
testpaths = ["tests"]
|
|
34
|
+
pythonpath = ["src"]
|
|
35
|
+
|
|
36
|
+
[tool.ruff]
|
|
37
|
+
line-length = 100
|
|
38
|
+
target-version = "py311"
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Command-line interface for PR-PerfGuard."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from perfguard import __version__
|
|
10
|
+
from perfguard.config import (
|
|
11
|
+
LoadConfig,
|
|
12
|
+
PerfGuardConfig,
|
|
13
|
+
ServiceConfig,
|
|
14
|
+
ThresholdConfig,
|
|
15
|
+
default_config_yaml,
|
|
16
|
+
load_config,
|
|
17
|
+
validate_config,
|
|
18
|
+
)
|
|
19
|
+
from perfguard.metrics import compare_reports, load_report, save_report
|
|
20
|
+
from perfguard.reporter import post_pr_comment, render_markdown, render_single_run_summary
|
|
21
|
+
from perfguard.runner import run_benchmark
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _build_config_from_args(args: argparse.Namespace) -> PerfGuardConfig:
|
|
25
|
+
if getattr(args, "config", None) and Path(args.config).exists():
|
|
26
|
+
cfg = load_config(args.config)
|
|
27
|
+
else:
|
|
28
|
+
cfg = PerfGuardConfig(
|
|
29
|
+
service=ServiceConfig(),
|
|
30
|
+
load=LoadConfig(),
|
|
31
|
+
thresholds=ThresholdConfig(),
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
if getattr(args, "url", None):
|
|
35
|
+
cfg.load.url = args.url
|
|
36
|
+
if getattr(args, "cmd", None):
|
|
37
|
+
cfg.service.command = args.cmd
|
|
38
|
+
if getattr(args, "healthcheck_url", None):
|
|
39
|
+
cfg.service.healthcheck_url = args.healthcheck_url
|
|
40
|
+
if getattr(args, "concurrency", None) is not None:
|
|
41
|
+
cfg.load.concurrency = args.concurrency
|
|
42
|
+
if getattr(args, "duration", None) is not None:
|
|
43
|
+
cfg.load.duration_seconds = args.duration
|
|
44
|
+
if getattr(args, "warmup", None) is not None:
|
|
45
|
+
cfg.load.warmup_seconds = args.warmup
|
|
46
|
+
if getattr(args, "repeats", None) is not None:
|
|
47
|
+
cfg.load.repeats = args.repeats
|
|
48
|
+
if getattr(args, "target_rps", None) is not None:
|
|
49
|
+
cfg.load.target_rps = args.target_rps
|
|
50
|
+
validate_config(cfg)
|
|
51
|
+
return cfg
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _write_text_file(path: str | Path, content: str) -> Path:
|
|
55
|
+
out = Path(path)
|
|
56
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
57
|
+
out.write_text(content, encoding="utf-8")
|
|
58
|
+
return out
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _cmd_init(args: argparse.Namespace) -> int:
|
|
62
|
+
target = Path(args.path)
|
|
63
|
+
if target.exists() and not args.force:
|
|
64
|
+
print(f"Error: {target} already exists (use --force to overwrite)", file=sys.stderr)
|
|
65
|
+
return 2
|
|
66
|
+
_write_text_file(target, default_config_yaml())
|
|
67
|
+
print(f"Created {target}")
|
|
68
|
+
return 0
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _cmd_run(args: argparse.Namespace) -> int:
|
|
72
|
+
cfg = _build_config_from_args(args)
|
|
73
|
+
report = run_benchmark(cfg)
|
|
74
|
+
if args.out:
|
|
75
|
+
save_report(report, args.out)
|
|
76
|
+
print(f"Saved report to {args.out}")
|
|
77
|
+
print(render_single_run_summary(report))
|
|
78
|
+
return 0
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _cmd_compare(args: argparse.Namespace) -> int:
|
|
82
|
+
thresholds = (
|
|
83
|
+
load_config(args.config).thresholds
|
|
84
|
+
if args.config and Path(args.config).exists()
|
|
85
|
+
else ThresholdConfig()
|
|
86
|
+
)
|
|
87
|
+
baseline = load_report(args.baseline)
|
|
88
|
+
current = load_report(args.current)
|
|
89
|
+
result = compare_reports(baseline, current, thresholds)
|
|
90
|
+
md = render_markdown(result)
|
|
91
|
+
|
|
92
|
+
if args.markdown_out:
|
|
93
|
+
_write_text_file(args.markdown_out, md)
|
|
94
|
+
print(md)
|
|
95
|
+
|
|
96
|
+
if args.pr_number:
|
|
97
|
+
post_pr_comment(md, pr_number=args.pr_number)
|
|
98
|
+
|
|
99
|
+
return 0 if result.passed else 1
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _cmd_check(args: argparse.Namespace) -> int:
|
|
103
|
+
cfg = _build_config_from_args(args)
|
|
104
|
+
current = run_benchmark(cfg)
|
|
105
|
+
if args.out:
|
|
106
|
+
save_report(current, args.out)
|
|
107
|
+
|
|
108
|
+
baseline_path = Path(args.baseline)
|
|
109
|
+
if not baseline_path.exists():
|
|
110
|
+
print(f"Baseline not found at {baseline_path}; skipping regression comparison.")
|
|
111
|
+
print(render_single_run_summary(current))
|
|
112
|
+
return 0
|
|
113
|
+
|
|
114
|
+
baseline = load_report(baseline_path)
|
|
115
|
+
result = compare_reports(baseline, current, cfg.thresholds)
|
|
116
|
+
md = render_markdown(result)
|
|
117
|
+
|
|
118
|
+
if args.markdown_out:
|
|
119
|
+
_write_text_file(args.markdown_out, md)
|
|
120
|
+
print(md)
|
|
121
|
+
|
|
122
|
+
if args.pr_number:
|
|
123
|
+
post_pr_comment(md, pr_number=args.pr_number)
|
|
124
|
+
|
|
125
|
+
return 0 if result.passed else 1
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
129
|
+
parser = argparse.ArgumentParser(
|
|
130
|
+
prog="perfguard",
|
|
131
|
+
description="Automated API performance regression testing for Pull Requests.",
|
|
132
|
+
)
|
|
133
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
134
|
+
sub = parser.add_subparsers(dest="subcommand", required=True)
|
|
135
|
+
|
|
136
|
+
# init
|
|
137
|
+
p_init = sub.add_parser("init", help="Create a starter perfguard.yml file.")
|
|
138
|
+
p_init.add_argument("--path", default="perfguard.yml")
|
|
139
|
+
p_init.add_argument("--force", action="store_true")
|
|
140
|
+
p_init.set_defaults(func=_cmd_init)
|
|
141
|
+
|
|
142
|
+
# shared run options
|
|
143
|
+
def add_run_flags(p: argparse.ArgumentParser) -> None:
|
|
144
|
+
p.add_argument("-c", "--config", default="perfguard.yml", help="Path to perfguard.yml")
|
|
145
|
+
p.add_argument("--url", help="Target HTTP URL to benchmark")
|
|
146
|
+
p.add_argument("--cmd", help="Shell command to start the target service")
|
|
147
|
+
p.add_argument("--healthcheck-url", help="Healthcheck URL for service startup")
|
|
148
|
+
p.add_argument("--concurrency", type=int, help="Number of concurrent workers")
|
|
149
|
+
p.add_argument("--duration", type=float, help="Load test duration in seconds")
|
|
150
|
+
p.add_argument("--warmup", type=float, help="Warmup duration in seconds")
|
|
151
|
+
p.add_argument("--repeats", type=int, help="Number of benchmark repeats (median aggregated)")
|
|
152
|
+
p.add_argument("--target-rps", type=float, help="Optional fixed total request rate (req/s)")
|
|
153
|
+
p.add_argument("-o", "--out", help="Write JSON report to this path")
|
|
154
|
+
|
|
155
|
+
p_run = sub.add_parser("run", help="Run a load test and output metrics.")
|
|
156
|
+
add_run_flags(p_run)
|
|
157
|
+
p_run.set_defaults(func=_cmd_run)
|
|
158
|
+
|
|
159
|
+
p_compare = sub.add_parser("compare", help="Compare baseline and current JSON reports.")
|
|
160
|
+
p_compare.add_argument("baseline", help="Path to baseline JSON report")
|
|
161
|
+
p_compare.add_argument("current", help="Path to current PR JSON report")
|
|
162
|
+
p_compare.add_argument("-c", "--config", default="perfguard.yml", help="Config for thresholds")
|
|
163
|
+
p_compare.add_argument("--markdown-out", help="Write Markdown diff report to file")
|
|
164
|
+
p_compare.add_argument("--pr-number", type=int, help="Post/update comment on GitHub PR")
|
|
165
|
+
p_compare.set_defaults(func=_cmd_compare)
|
|
166
|
+
|
|
167
|
+
p_check = sub.add_parser("check", help="Run benchmark and compare against baseline.")
|
|
168
|
+
add_run_flags(p_check)
|
|
169
|
+
p_check.add_argument("--baseline", required=True, help="Path to baseline JSON report")
|
|
170
|
+
p_check.add_argument("--markdown-out", help="Write Markdown diff report to file")
|
|
171
|
+
p_check.add_argument("--pr-number", type=int, help="Post/update comment on GitHub PR")
|
|
172
|
+
p_check.set_defaults(func=_cmd_check)
|
|
173
|
+
|
|
174
|
+
return parser
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def main(argv: list[str] | None = None) -> int:
|
|
178
|
+
parser = build_parser()
|
|
179
|
+
args = parser.parse_args(argv)
|
|
180
|
+
try:
|
|
181
|
+
return args.func(args)
|
|
182
|
+
except Exception as exc: # noqa: BLE001
|
|
183
|
+
print(f"perfguard error: {exc}", file=sys.stderr)
|
|
184
|
+
return 2
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
if __name__ == "__main__":
|
|
188
|
+
raise SystemExit(main())
|