Skip to content

Commit

Permalink
feat: ... is now a special value to create snapshot values
Browse files Browse the repository at this point in the history
  • Loading branch information
15r10nk committed Jan 25, 2025
1 parent 6f8e839 commit 43c2324
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 59 deletions.
1 change: 0 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ ci:

repos:
- hooks:
- id: check-yaml
- id: check-ast
- id: check-merge-conflict
- id: trailing-whitespace
Expand Down
25 changes: 16 additions & 9 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ theme:
features:
- toc.follow
- content.code.annotate
- navigation.tabs

palette:
- media: (prefers-color-scheme)

Expand All @@ -34,7 +36,13 @@ watch:
- src/inline_snapshot

nav:
- Introduction: index.md
- Home:
- Introduction: index.md
- Configuration: configuration.md
- pytest integration: pytest.md
- Categories: categories.md
- Code generation: code_generation.md
- Limitations: limitations.md
- Core:
- x == snapshot(): eq_snapshot.md
- x <= snapshot(): cmp_snapshot.md
Expand All @@ -46,14 +54,10 @@ nav:
- Extensions:
- first-party (extra): extra.md
- third-party: third_party.md
- pytest integration: pytest.md
- Categories: categories.md
- Configuration: configuration.md
- Code generation: code_generation.md
- Testing: testing.md
- Limitations: limitations.md
- Contributing: contributing.md
- Changelog: changelog.md
- Development:
- Testing: testing.md
- Contributing: contributing.md
- Changelog: changelog.md



Expand All @@ -73,6 +77,9 @@ markdown_extensions:
- pymdownx.tabbed:
alternate_style: true
- attr_list
- pymdownx.emoji:
emoji_index: !!python/name:material.extensions.emoji.twemoji
emoji_generator: !!python/name:material.extensions.emoji.to_svg

plugins:
- mkdocstrings:
Expand Down
17 changes: 10 additions & 7 deletions src/inline_snapshot/_adapter/value_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
import ast
import warnings

from inline_snapshot._code_repr import value_code_repr
from inline_snapshot._unmanaged import Unmanaged
from inline_snapshot._unmanaged import update_allowed
from inline_snapshot._utils import value_to_token
from inline_snapshot.syntax_warnings import InlineSnapshotInfo

from .._change import Replace
from .._code_repr import value_code_repr
from .._sentinels import undefined
from .._unmanaged import Unmanaged
from .._unmanaged import update_allowed
from .._utils import value_to_token
from ..syntax_warnings import InlineSnapshotInfo
from .adapter import Adapter


Expand Down Expand Up @@ -46,7 +46,10 @@ def assign(self, old_value, old_node, new_value):
return old_value

if not old_value == new_value:
flag = "fix"
if old_value is undefined:
flag = "create"
else:
flag = "fix"
elif (
old_node is not None
and update_allowed(old_value)
Expand Down
17 changes: 12 additions & 5 deletions src/inline_snapshot/_flags.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Set
from __future__ import annotations

from ._types import Category

Expand All @@ -11,14 +11,21 @@ class Flags:
trim: the snapshot contains more values than neccessary. 1 could be trimmed in `5 in snapshot([1,5])`.
"""

def __init__(self, flags: Set[Category] = set()):
self.fix = "fix" in flags
self.update = "update" in flags
def __init__(self, flags: set[Category] = set()):
self.create = "create" in flags
self.fix = "fix" in flags
self.trim = "trim" in flags
self.update = "update" in flags

def to_set(self):
def to_set(self) -> set[Category]:
return {k for k, v in self.__dict__.items() if v}

def __iter__(self):
return (k for k, v in self.__dict__.items() if v)

def __repr__(self):
return f"Flags({self.to_set()})"

@staticmethod
def all() -> Flags:
return Flags({"fix", "create", "update", "trim"})
8 changes: 1 addition & 7 deletions src/inline_snapshot/_sentinels.py
Original file line number Diff line number Diff line change
@@ -1,7 +1 @@
# sentinels
class Undefined:
def __repr__(self):
return "undefined"


undefined = Undefined()
undefined = ...
23 changes: 7 additions & 16 deletions src/inline_snapshot/pytest_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def pytest_addoption(parser, pluginmanager):
)


categories = {"create", "update", "trim", "fix"}
categories = Flags.all().to_set()
flags = set()


Expand Down Expand Up @@ -114,7 +114,7 @@ def pytest_configure(config):
elif flags & {"review"}:
state().active = True

state().update_flags = Flags({"fix", "create", "update", "trim"})
state().update_flags = Flags.all()
else:

state().active = "disable" not in flags
Expand Down Expand Up @@ -167,6 +167,7 @@ def snapshot_check():


def pytest_assertrepr_compare(config, op, left, right):

results = []
if isinstance(left, GenericValue):
results = config.hook.pytest_assertrepr_compare(
Expand Down Expand Up @@ -254,19 +255,9 @@ def apply_changes(flag):
return False

# auto mode
changes = {
"update": [],
"fix": [],
"trim": [],
"create": [],
}

snapshot_changes = {
"update": 0,
"fix": 0,
"trim": 0,
"create": 0,
}
changes = {f: [] for f in Flags.all()}

snapshot_changes = {f: 0 for f in Flags.all()}

for snapshot in state().snapshots.values():
all_categories = set()
Expand Down Expand Up @@ -331,7 +322,7 @@ def report(flag, message, message_n):
)

used_changes = []
for flag in ("create", "fix", "trim", "update"):
for flag in Flags.all():
if not changes[flag]:
continue

Expand Down
19 changes: 9 additions & 10 deletions src/inline_snapshot/testing/_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,14 +132,13 @@ def run_inline(

self._write_files(tmp_path)

raised_exception = None
raised_exception = []
with snapshot_env() as state:
with ChangeRecorder().activate() as recorder:
state.update_flags = Flags({*flags})
inline_snapshot._external.storage = (
inline_snapshot._external.DiscStorage(tmp_path / ".storage")
)

try:
for filename in tmp_path.glob("*.py"):
globals: dict[str, Any] = {}
Expand All @@ -152,11 +151,11 @@ def run_inline(
# run all test_* functions
for k, v in globals.items():
if k.startswith("test_") and callable(v):
v()
except Exception as e:
traceback.print_exc()
raised_exception = e

try:
v()
except Exception as e:
traceback.print_exc()
raised_exception.append(e)
finally:
state.active = False

Expand Down Expand Up @@ -184,9 +183,9 @@ def run_inline(
if reported_categories is not None:
assert sorted(snapshot_flags) == reported_categories

if raised_exception is not None:
assert raises == f"{type(raised_exception).__name__}:\n" + str(
raised_exception
if raised_exception:
assert raises == "\n".join(
f"{type(e).__name__}:\n" + str(e) for e in raised_exception
)
else:
assert raises == None
Expand Down
12 changes: 8 additions & 4 deletions tests/test_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
from typing import Optional

import pytest
from executing import is_pytest_compatible

from inline_snapshot import snapshot
from inline_snapshot._flags import Flags
from inline_snapshot._global_state import state
from inline_snapshot.extra import raises

Expand Down Expand Up @@ -279,7 +281,6 @@ def test_block(block: Block):

if block.code_header.startswith("todo-inline-snapshot:"):
return block
assert False

nonlocal last_code
with subtests.test(line=block.line):
Expand All @@ -288,7 +289,10 @@ def test_block(block: Block):

options = set(block.code_header.split())

flags = options & {"fix", "update", "create", "trim"}
if "requires_assert" in options and not is_pytest_compatible():
return block

flags = options & Flags.all().to_set()

args = ["--inline-snapshot", ",".join(flags)] if flags else []

Expand Down Expand Up @@ -328,7 +332,7 @@ def test_block(block: Block):

block.code_header = "inline-snapshot: " + " ".join(
sorted(flags)
+ sorted(options & {"first_block", "show_error"})
+ sorted(options & {"first_block", "show_error", "requires_assert"})
+ [
f"outcome-{k}={v}"
for k, v in result.parseoutcomes().items()
Expand Down Expand Up @@ -359,7 +363,7 @@ def test_block(block: Block):

block.code = new_code

if flags:
if flags - {"create"}:
assert result.ret == 0

last_code = code
Expand Down

0 comments on commit 43c2324

Please sign in to comment.