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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
|
import os
import platform
import re
import shutil
import sys
import textwrap
import traceback
from dataclasses import dataclass
from dataclasses import field
from pathlib import Path
from types import SimpleNamespace
from typing import Set
from unittest import mock
import black
import executing
import pytest
import inline_snapshot._external
from inline_snapshot._change import apply_all
from inline_snapshot._flags import Flags
from inline_snapshot._format import format_code
from inline_snapshot._rewrite_code import ChangeRecorder
from inline_snapshot._types import Category
from inline_snapshot.testing._example import snapshot_env
pytest_plugins = "pytester"
pytest.register_assert_rewrite("tests.example")
black.files.find_project_root = black.files.find_project_root.__wrapped__ # type: ignore
@pytest.fixture(autouse=True)
def check_pypy(request):
implementation = sys.implementation.name
node = request.node
if implementation != "cpython" and node.get_closest_marker("no_rewriting") is None:
pytest.skip(f"{implementation} is not supported")
yield
@pytest.fixture()
def check_update(source):
def w(source_code, *, flags="", reported_flags=None, number=1):
s = source(source_code)
flags = {*flags.split(",")} - {""}
if reported_flags is None:
reported_flags = flags
else:
reported_flags = {*reported_flags.split(",")} - {""}
assert s.flags == reported_flags
assert s.number_snapshots == number
assert s.error == ("fix" in s.flags)
s2 = s.run(*flags)
return s2.source
return w
@pytest.fixture()
def source(tmp_path: Path):
filecount = 1
@dataclass
class Source:
source: str
flags: Set[str] = field(default_factory=set)
error: bool = False
number_snapshots: int = 0
number_changes: int = 0
def run(self, *flags_arg: Category):
flags = Flags({*flags_arg})
nonlocal filecount
filename: Path = tmp_path / f"test_{filecount}.py"
filecount += 1
prefix = """\"\"\"
PYTEST_DONT_REWRITE
\"\"\"
# Àâà π
from inline_snapshot import snapshot
from inline_snapshot import external
from inline_snapshot import outsource
"""
source = prefix + textwrap.dedent(self.source)
filename.write_text(source, "utf-8")
print()
print("input:")
print(textwrap.indent(source, " |", lambda line: True).rstrip())
with snapshot_env() as state:
recorder = ChangeRecorder()
state.update_flags = flags
state.storage = inline_snapshot._external.DiscStorage(
tmp_path / ".storage"
)
error = False
try:
exec(compile(filename.read_text("utf-8"), filename, "exec"), {})
except AssertionError:
traceback.print_exc()
error = True
finally:
state.active = False
number_snapshots = len(state.snapshots)
changes = []
for snapshot in state.snapshots.values():
changes += snapshot._changes()
snapshot_flags = {change.flag for change in changes}
apply_all(
[
change
for change in changes
if change.flag in state.update_flags.to_set()
],
recorder,
)
recorder.fix_all()
source = filename.read_text("utf-8")[len(prefix) :]
print("reported_flags:", snapshot_flags)
print(
f'run: pytest --inline-snapshot={",".join(flags.to_set())}'
if flags
else ""
)
print("output:")
print(textwrap.indent(source, " |", lambda line: True).rstrip())
return Source(
source=source,
flags=snapshot_flags,
error=error,
number_snapshots=number_snapshots,
number_changes=len(changes),
)
def w(source):
return Source(source=source).run()
return w
ansi_escape = re.compile(
r"""
\x1B # ESC
(?: # 7-bit C1 Fe (except CSI)
[@-Z\\-_]
| # or [ for CSI, followed by a control sequence
\[
[0-?]* # Parameter bytes
[ -/]* # Intermediate bytes
[@-~] # Final byte
)
""",
re.VERBOSE,
)
class RunResult:
def __init__(self, result):
self._result = result
def __getattr__(self, name):
return getattr(self._result, name)
@staticmethod
def _join_lines(lines):
text = "\n".join(lines).rstrip()
if "\n" in text:
return text + "\n"
else:
return text
@property
def report(self):
result = []
record = False
for line in self._result.stdout.lines:
line = line.strip()
if line.startswith("===="):
record = False
if record and line:
result.append(line)
if line.startswith(("-----", "βββββ")) and "inline-snapshot" in line:
record = True
result = self._join_lines(result)
result = ansi_escape.sub("", result)
# fix windows problems
result = result.replace("\u2500", "-")
result = result.replace("\r", "")
return result
@property
def errors(self):
result = []
record = False
for line in self._result.stdout.lines:
line = line.strip()
if line.startswith("====") and "ERRORS" in line:
record = True
if record and line:
result.append(line)
result = self._join_lines(result)
result = re.sub(r"\d+\.\d+s", "<time>", result)
return result
@property
def stderr(self):
original = self._result.stderr.lines
lines = [
line
for line in original
if not any(
s in line
for s in [
'No entry for terminal type "unknown"',
"using dumb terminal settings.",
]
)
]
return pytest.LineMatcher(lines)
def errorLines(self):
result = self._join_lines(
[line for line in self.stdout.lines if line and line[:2] in ("> ", "E ")]
)
return result
@pytest.fixture
def project(pytester):
class Project:
def __init__(self):
self.term_columns = 80
def setup(self, source: str, add_header=True):
if add_header:
self.header = """\
# Àâà π
from inline_snapshot import snapshot
from inline_snapshot import outsource
"""
if "# no imports" in source:
self.header = """\
# Àâà π
"""
else:
self.header = """\
# Àâà π
from inline_snapshot import snapshot
from inline_snapshot import outsource
"""
else: # pragma: no cover
self.header = ""
header = self.header
if not source.startswith(("import ", "from ")):
header += "\n\n"
source = header + source
print("write code:")
print(source)
self._filename.write_text(source, "utf-8")
(pytester.path / "conftest.py").write_text(
"""
import datetime
import pytest
from freezegun.api import FakeDatetime,FakeDate
from inline_snapshot import customize_repr
@customize_repr
def _(value:FakeDatetime):
return value.__repr__().replace("FakeDatetime","datetime.datetime")
@customize_repr
def _(value:FakeDate):
return value.__repr__().replace("FakeDate","datetime.date")
@pytest.fixture(autouse=True)
def set_time(freezer):
freezer.move_to(datetime.datetime(2024, 3, 14, 0, 0, 0, 0))
yield
"""
)
@property
def _filename(self):
return pytester.path / "test_file.py"
def is_formatted(self):
code = self._filename.read_text("utf-8")
return code == format_code(code, self._filename)
def format(self):
self._filename.write_text(
format_code(self._filename.read_text("utf-8"), self._filename), "utf-8"
)
def pyproject(self, source):
self.write_file("pyproject.toml", source)
def write_file(self, filename, content):
(pytester.path / filename).write_text(content, "utf-8")
def storage(self, storage_dir=".inline-snapshot"):
if os.path.isabs(storage_dir):
dir = Path(storage_dir)
else:
dir = pytester.path / storage_dir
dir /= "external"
if not dir.exists():
return []
return sorted(p.name for p in dir.iterdir() if p.name != ".gitignore")
@property
def source(self):
assert self._filename.read_text("utf-8")[: len(self.header)] == self.header
return self._filename.read_text("utf-8")[len(self.header) :].lstrip()
def run(self, *args, stdin=""):
cache = pytester.path / "__pycache__"
if cache.exists():
shutil.rmtree(cache)
# pytest adds -v if it detects some github CI variable
old_environ = dict(os.environ)
if "CI" in os.environ:
del os.environ["CI"] # pragma: no cover
os.environ.pop("GITHUB_ACTIONS", None)
try:
with mock.patch.dict(
os.environ,
{
"TERM": "unknown",
"COLUMNS": str(
self.term_columns + 1
if platform.system() == "Windows"
else self.term_columns
),
},
):
if stdin:
result = pytester.run("pytest", *args, stdin=stdin)
else:
result = pytester.run("pytest", *args)
finally:
os.environ.update(old_environ)
return RunResult(result)
return Project()
@pytest.fixture(params=[True, False], ids=["executing", "without-executing"])
def executing_used(request, monkeypatch):
used = request.param
if used:
yield used
else:
def fake_executing(frame):
return SimpleNamespace(node=None)
monkeypatch.setattr(executing.Source, "executing", fake_executing)
yield used
|