Skip to content

Commit

Permalink
Merge pull request #129 from 15r10nk/fix-cli
Browse files Browse the repository at this point in the history
fix some usability issues
  • Loading branch information
15r10nk authored Nov 10, 2024
2 parents 8a80a5b + dffb339 commit 7bf7c68
Show file tree
Hide file tree
Showing 18 changed files with 273 additions and 62 deletions.
40 changes: 40 additions & 0 deletions changelog.d/20241108_192001_15r10nk-git_fix_cli.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<!--
A new scriv changelog fragment.
Uncomment the section that is right (remove the HTML comment wrapper).
-->

<!--
### Removed
- A bullet item for the Removed category.
-->
### Added

- command line shortcuts can be defined to simplify your workflows. `--review` and `--fix` are defined by default. See the [documentation](https://15r10nk.github.io/inline-snapshot/configuration/) for details.

<!--
### Changed
- A bullet item for the Changed category.
-->
<!--
### Deprecated
- A bullet item for the Deprecated category.
-->
<!--
### Fixed
- A bullet item for the Fixed category.
-->
<!--
### Security
- A bullet item for the Security category.
-->
42 changes: 42 additions & 0 deletions changelog.d/20241109_074441_15r10nk-git_fix_cli.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<!--
A new scriv changelog fragment.
Uncomment the section that is right (remove the HTML comment wrapper).
-->

<!--
### Removed
- A bullet item for the Removed category.
-->
<!--
### Added
- A bullet item for the Added category.
-->

### Changed

- `--inline-snapshot=create/fix/trim/update` will no longer show reports for other categories.
You can use `--inline-snapshot=create,report` if you want to use the old behaviour.

<!--
### Deprecated
- A bullet item for the Deprecated category.
-->
<!--
### Fixed
- A bullet item for the Fixed category.
-->
<!--
### Security
- A bullet item for the Security category.
-->
2 changes: 1 addition & 1 deletion docs/categories.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ The result of each comparison is `True` if you change something from this catego

<div class="grid" markdown>

<!-- inline-snapshot: first_block outcome-failed=1 -->
<!-- inline-snapshot: first_block outcome-failed=1 outcome-errors=1 -->
``` python
def test_something():
assert 8 == snapshot(5)
Expand Down
13 changes: 9 additions & 4 deletions docs/configuration.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@


Default configuration:

``` toml
[tool.inline-snapshot]
hash-length=15
default-flags=["short-report"]

[tool.inline-snapshot.shortcuts]
review=["review"]
fix=["create","fix"]
```

* *hash-length:* specifies the length of the hash used by `external()` in the code representation.
* **hash-length:** specifies the length of the hash used by `external()` in the code representation.
This does not affect the hash length used to store the data.
The hash should be long enough to avoid hash collisions.
* *default-flags:* defines which flags should be used if there are no flags specified with `--inline-snapshot=...`.
* **default-flags:** defines which flags should be used if there are no flags specified with `--inline-snapshot=...`.
You can also use the environment variable `INLINE_SNAPSHOT_DEFAULT_FLAGS=...` to specify the flags and to override those in the configuration file.

* **shortcuts:** allows you to define custom commands to simplify your workflows.
`--fix` and `--review` are defined by default, but this configuration can be changed to fit your needs.
4 changes: 2 additions & 2 deletions docs/eq_snapshot.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Example:
```

=== "value changed"
<!-- inline-snapshot: outcome-failed=1 -->
<!-- inline-snapshot: outcome-failed=1 outcome-errors=1 -->
``` python hl_lines="2"
def test_something():
assert 2 + 40 == snapshot(4)
Expand Down Expand Up @@ -111,7 +111,7 @@ Example:
```

=== "changed payload"
<!-- inline-snapshot: outcome-failed=1 -->
<!-- inline-snapshot: outcome-failed=1 outcome-errors=1 -->
``` python hl_lines="9"
from inline_snapshot import snapshot
from dirty_equals import IsDatetime
Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ Maybe that is correct and you should fix your code, or
your code is correct and you want to update your test results.

=== "changed code"
<!-- inline-snapshot: outcome-failed=1 -->
<!-- inline-snapshot: outcome-failed=1 outcome-errors=1 -->
``` python hl_lines="2"
def something():
return (1548 * 18489) // 18
Expand Down
8 changes: 8 additions & 0 deletions docs/limitations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

## pytest assert rewriting is disabled

inline-snapshot must disable pytest assert-rewriting if you use report/review/create/fix/trim/update flags.

## xdist is not supported

You can not use inline-snapshot in combination with `pytest-xdist`. The use of `-n=...` implies `--inline-snapshot=disable`.
2 changes: 1 addition & 1 deletion docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ The following example shows how you can use the `Example` class to test what inl
report=snapshot(
"""\
Error: one snapshot is missing a value (--inline-snapshot=create)
You can also use --inline-snapshot=review to approve the changes interactiv\
You can also use --inline-snapshot=review to approve the changes interactively\
"""
),
).run_pytest( # run with create flag and check the changed files
Expand Down
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ nav:
- Configuration: configuration.md
- Code generation: code_generation.md
- Testing: testing.md
- Limitations: limitations.md
- Contributing: contributing.md
- Changelog: changelog.md

Expand Down
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,7 @@ venvPath = ".nox"
[tool.scriv]
format = "md"
version = "command: cz bump --get-next"

[tool.inline-snapshot.shortcuts]
sfix="create,fix"
review="create,review"
8 changes: 8 additions & 0 deletions src/inline_snapshot/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
from dataclasses import dataclass
from dataclasses import field
from pathlib import Path
from typing import Dict
from typing import List


if sys.version_info >= (3, 11):
from tomllib import loads
else:
Expand All @@ -15,6 +17,7 @@
class Config:
hash_length: int = 12
default_flags: List[str] = field(default_factory=lambda: ["short-report"])
shortcuts: Dict[str, List[str]] = field(default_factory=dict)


config = Config()
Expand All @@ -35,11 +38,16 @@ def read_config(path: Path) -> Config:
result.hash_length = config["hash-length"]
except KeyError:
pass

try:
result.default_flags = config["default-flags"]
except KeyError:
pass

result.shortcuts = config.get(
"shortcuts", {"fix": ["create", "fix"], "review": ["review"]}
)

env_var = "INLINE_SNAPSHOT_DEFAULT_FLAGS"
if env_var in os.environ:
result.default_flags = os.environ[env_var].split(",")
Expand Down
27 changes: 20 additions & 7 deletions src/inline_snapshot/_inline_snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ class NotImplementedYet(Exception):
_files_with_snapshots: Set[str] = set()

_missing_values = 0
_incorrect_values = 0


def _return(result):
global _incorrect_values
if not result:
_incorrect_values += 1
return result


class InlineSnapshotSyntaxWarning(Warning):
Expand Down Expand Up @@ -328,8 +336,11 @@ def use_valid_old_values(old_value, new_value):

if self._new_value is undefined:
self._new_value = use_valid_old_values(self._old_value, clone(other))

return self._visible_value() == other
if self._old_value is undefined or ignore_old_value():
return True
return _return(self._old_value == other)
else:
return _return(self._new_value == other)

def _new_code(self):
return self._value_to_code(self._new_value)
Expand Down Expand Up @@ -514,12 +525,14 @@ def _generic_cmp(self, other):

if self._new_value is undefined:
self._new_value = clone(other)
if self._old_value is undefined or ignore_old_value():
return True
return _return(self.cmp(self._old_value, other))
else:
self._new_value = (
self._new_value if self.cmp(self._new_value, other) else clone(other)
)
if not self.cmp(self._new_value, other):
self._new_value = clone(other)

return self.cmp(self._visible_value(), other)
return _return(self.cmp(self._visible_value(), other))

def _new_code(self):
return self._value_to_code(self._new_value)
Expand Down Expand Up @@ -609,7 +622,7 @@ def __contains__(self, item):
if ignore_old_value() or self._old_value is undefined:
return True
else:
return item in self._old_value
return _return(item in self._old_value)

def _new_code(self):
return self._value_to_code(self._new_value)
Expand Down
34 changes: 29 additions & 5 deletions src/inline_snapshot/pytest_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from ._rewrite_code import ChangeRecorder


def pytest_addoption(parser):
def pytest_addoption(parser, pluginmanager):
group = parser.getgroup("inline-snapshot")

group.addoption(
Expand All @@ -39,9 +39,22 @@ def pytest_addoption(parser):
"fix: change snapshots which currently break your tests\n",
)

config_path = Path("pyproject.toml")
if config_path.exists():
config = _config.read_config(Path("pyproject.toml"))
for name, value in config.shortcuts.items():
value = ",".join(value)
group.addoption(
f"--{name}",
action="store_const",
const=value,
dest="inline_snapshot",
help=f'shortcut for "--inline-snapshot={value}"',
)


categories = {"create", "update", "trim", "fix"}
flags = {}
flags = set()


def xdist_running(config):
Expand Down Expand Up @@ -104,20 +117,28 @@ def pytest_configure(config):
@pytest.fixture(autouse=True)
def snapshot_check():
_inline_snapshot._missing_values = 0
_inline_snapshot._incorrect_values = 0
yield

missing_values = _inline_snapshot._missing_values
incorrect_values = _inline_snapshot._incorrect_values

if missing_values != 0 and not _inline_snapshot._update_flags.create:
pytest.fail(
(
f"your snapshot is missing one value run pytest with --inline-snapshot=create to create it"
f"your snapshot is missing one value."
if missing_values == 1
else f"your snapshot is missing {missing_values} values run pytest with --inline-snapshot=create to create them"
else f"your snapshot is missing {missing_values} values."
),
pytrace=False,
)

if incorrect_values != 0 and not _inline_snapshot._update_flags.fix:
pytest.fail(
"some snapshots in this test have incorrect values.",
pytrace=False,
)


def pytest_assertrepr_compare(config, op, left, right):
results = []
Expand Down Expand Up @@ -264,7 +285,7 @@ def report(flag, message, message_n):

if sum(snapshot_changes.values()) != 0:
console.print(
"\nYou can also use [b]--inline-snapshot=review[/] to approve the changes interactiv",
"\nYou can also use [b]--inline-snapshot=review[/] to approve the changes interactively",
highlight=False,
)

Expand All @@ -279,6 +300,9 @@ def report(flag, message, message_n):
if not changes[flag]:
continue

if not {"review", "report", flag} & flags:
continue

console.rule(f"[yellow bold]{flag.capitalize()} snapshots")

with ChangeRecorder().activate() as cr:
Expand Down
3 changes: 3 additions & 0 deletions src/inline_snapshot/testing/_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def snapshot_env():
external.storage,
inline_snapshot._files_with_snapshots,
inline_snapshot._missing_values,
inline_snapshot._incorrect_values,
)

inline_snapshot.snapshots = {}
Expand All @@ -40,6 +41,7 @@ def snapshot_env():
external.storage = None
inline_snapshot._files_with_snapshots = set()
inline_snapshot._missing_values = 0
inline_snapshot._incorrect_values = 0

try:
yield
Expand All @@ -51,6 +53,7 @@ def snapshot_env():
external.storage,
inline_snapshot._files_with_snapshots,
inline_snapshot._missing_values,
inline_snapshot._incorrect_values,
) = current


Expand Down
13 changes: 13 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,16 @@ def test_config_env():
Example(file_to_trim).run_pytest(
env={"INLINE_SNAPSHOT_DEFAULT_FLAGS": "trim"}, changed_files=trimmed_files
)


def test_shortcuts():

Example(
{
**file_to_trim,
"pyproject.toml": """
[tool.inline-snapshot.shortcuts]
strim=["trim"]
""",
}
).run_pytest(["--strim"], changed_files=trimmed_files)
Loading

0 comments on commit 7bf7c68

Please sign in to comment.