-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit_pytest.py
More file actions
178 lines (150 loc) · 5.04 KB
/
init_pytest.py
File metadata and controls
178 lines (150 loc) · 5.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/env python3
"""
Initialize a robust pytest setup in the current directory (or --path).
Creates:
- tests/test_sample.py
- tests/conftest.py
- pytest.ini
- .coveragerc
- requirements-dev.txt
- .github/workflows/python-tests.yml (with --ci)
Usage:
python3 skill-pytest/init_pytest.py [--path .] [--package yourpkg] [--ci] [--overwrite]
Run dev deps:
python3 -m pip install -r requirements-dev.txt
pytest -q --cov
"""
from __future__ import annotations
import argparse
import os
from pathlib import Path
import textwrap
def write_file(path: Path, content: str, overwrite: bool = False) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
if path.exists() and not overwrite:
return
path.write_text(content, encoding="utf-8")
def main() -> int:
p = argparse.ArgumentParser(description="Scaffold pytest configuration and CI")
p.add_argument("--path", default=".", help="Target project directory")
p.add_argument("--package", default="", help="Package/module name for coverage source (optional)")
p.add_argument("--ci", action="store_true", help="Add GitHub Actions workflow")
p.add_argument("--overwrite", action="store_true", help="Overwrite existing files if present")
args = p.parse_args()
root = Path(args.path).resolve()
overwrite = args.overwrite
pkg = args.package.strip()
cov_source = pkg if pkg else ""
# tests/test_sample.py
test_sample = textwrap.dedent(
"""
def test_sample_sum():
assert sum([1, 2, 3]) == 6
"""
).lstrip()
write_file(root / "tests" / "test_sample.py", test_sample, overwrite)
# tests/conftest.py
conftest = textwrap.dedent(
"""
import os
import random
import pytest
@pytest.fixture(autouse=True)
def _seed_random():
random.seed(1337)
os.environ.setdefault("PYTHONHASHSEED", "0")
@pytest.fixture
def tmp_cwd(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
return tmp_path
"""
).lstrip()
write_file(root / "tests" / "conftest.py", conftest, overwrite)
# pytest.ini
pytest_ini = textwrap.dedent(
"""
[pytest]
minversion = 7.0
addopts = -ra
testpaths = tests
xfail_strict = true
filterwarnings =
error::DeprecationWarning
markers =
unit: fast unit tests
integration: tests using external services or IO
slow: long-running tests
flaky: non-deterministic tests (aim to eliminate)
"""
).lstrip()
write_file(root / "pytest.ini", pytest_ini, overwrite)
# .coveragerc
coveragerc = textwrap.dedent(
f"""
[run]
branch = True
{('source =\n ' + cov_source) if cov_source else '# Set --package to track a package as coverage source'}
[report]
show_missing = True
skip_covered = True
fail_under = 80
"""
).lstrip()
write_file(root / ".coveragerc", coveragerc, overwrite)
# requirements-dev.txt
reqs = textwrap.dedent(
"""
pytest>=7.0
pytest-cov>=4.0
pytest-asyncio>=0.23
pytest-mock>=3.12
"""
).lstrip()
write_file(root / "requirements-dev.txt", reqs, overwrite)
# GitHub Actions workflow (optional)
if args.ci:
workflow = textwrap.dedent(
f"""
name: Python tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install deps
run: |
python -m pip install --upgrade pip
if [ -f requirements-dev.txt ]; then pip install -r requirements-dev.txt; fi
if [ -f pyproject.toml ]; then pip install -e .; fi
- name: Run tests
run: |
pytest -q {'--cov=' + cov_source if cov_source else ''} --cov-report=term-missing
"""
).lstrip()
write_file(root / ".github" / "workflows" / "python-tests.yml", workflow, overwrite)
created = [
root / "tests" / "test_sample.py",
root / "tests" / "conftest.py",
root / "pytest.ini",
root / ".coveragerc",
root / "requirements-dev.txt",
]
if args.ci:
created.append(root / ".github" / "workflows" / "python-tests.yml")
print("Created/verified files:")
for p in created:
rel = os.path.relpath(p, start=os.getcwd())
print(" -", rel)
print("\nNext:")
print(" python3 -m pip install -r requirements-dev.txt")
print(" pytest -q --cov")
return 0
if __name__ == "__main__":
raise SystemExit(main())