pytest-revealtype-injector 0.2.1__tar.gz → 0.2.2__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.
Files changed (19) hide show
  1. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/PKG-INFO +26 -1
  2. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/README.md +25 -0
  3. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/pyproject.toml +1 -2
  4. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/src/pytest_revealtype_injector/__init__.py +1 -1
  5. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/src/pytest_revealtype_injector/adapter/mypy_.py +11 -6
  6. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/src/pytest_revealtype_injector/adapter/pyright_.py +8 -6
  7. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/src/pytest_revealtype_injector/hooks.py +3 -4
  8. pytest_revealtype_injector-0.2.2/src/pytest_revealtype_injector/log.py +19 -0
  9. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/src/pytest_revealtype_injector/main.py +15 -7
  10. pytest_revealtype_injector-0.2.2/tests/test_basic.py +91 -0
  11. pytest_revealtype_injector-0.2.1/tests/test_basic.py +0 -31
  12. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/.gitignore +0 -0
  13. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/COPYING +0 -0
  14. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/COPYING.mit +0 -0
  15. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/src/pytest_revealtype_injector/adapter/__init__.py +0 -0
  16. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/src/pytest_revealtype_injector/models.py +0 -0
  17. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/src/pytest_revealtype_injector/plugin.py +0 -0
  18. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/src/pytest_revealtype_injector/py.typed +0 -0
  19. {pytest_revealtype_injector-0.2.1 → pytest_revealtype_injector-0.2.2}/tests/conftest.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytest-revealtype-injector
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: Pytest plugin for replacing reveal_type() calls inside test functions with static and runtime type checking result comparison, for confirming type annotation validity.
5
5
  Project-URL: homepage, https://github.com/abelcheung/pytest-revealtype-injector
6
6
  Author-email: Abel Cheung <abelcheung@gmail.com>
@@ -84,6 +84,31 @@ def test_something():
84
84
 
85
85
  2. `reveal_type()` calls have to stay in a single line, without anything else. This limitation comes from using [`eval` mode in AST parsing](https://docs.python.org/3/library/ast.html#ast.Expression).
86
86
 
87
+ ## Logging
88
+
89
+ This plugin uses standard [`logging`](https://docs.python.org/3/library/logging.html) internally. `pytest -v` can be used to reveal `INFO` and `DEBUG` logs. Given following example:
90
+
91
+ ```python
92
+ def test_superfluous(self) -> None:
93
+ x: list[str] = ['a', 'b', 'c', 1] # type: ignore # pyright: ignore
94
+ reveal_type(x)
95
+ ```
96
+
97
+ Something like this will be shown as test result:
98
+
99
+ ```
100
+ ...
101
+ raise TypeCheckError(f"is not an instance of {qualified_name(origin_type)}")
102
+ E typeguard.TypeCheckError: item 3 is not an instance of str (from pyright)
103
+ ------------------------------------------------------------- Captured log call -------------------------------------------------------------
104
+ INFO revealtype-injector:hooks.py:26 Replaced reveal_type() from global import with <function revealtype_injector at 0x00000238DB923D00>
105
+ DEBUG revealtype-injector:main.py:60 Extraction OK: code='reveal_type(x)', result='x'
106
+ ========================================================== short test summary info ==========================================================
107
+ FAILED tests/runtime/test_attrib.py::TestAttrib::test_superfluous - typeguard.TypeCheckError: item 3 is not an instance of str (from pyright)
108
+ ============================================================= 1 failed in 3.38s =============================================================
109
+ ```
110
+
111
+
87
112
  ## History
88
113
 
89
114
  This pytest plugin starts its life as part of testsuite related utilities within [`types-lxml`](https://github.com/abelcheung/types-lxml). As `lxml` is a `cython` project and probably never incorporate inline python annotation in future, there is need to compare runtime result to static type checker output for discrepancy. As time goes by, it starts to make sense to manage as an independent project.
@@ -54,6 +54,31 @@ def test_something():
54
54
 
55
55
  2. `reveal_type()` calls have to stay in a single line, without anything else. This limitation comes from using [`eval` mode in AST parsing](https://docs.python.org/3/library/ast.html#ast.Expression).
56
56
 
57
+ ## Logging
58
+
59
+ This plugin uses standard [`logging`](https://docs.python.org/3/library/logging.html) internally. `pytest -v` can be used to reveal `INFO` and `DEBUG` logs. Given following example:
60
+
61
+ ```python
62
+ def test_superfluous(self) -> None:
63
+ x: list[str] = ['a', 'b', 'c', 1] # type: ignore # pyright: ignore
64
+ reveal_type(x)
65
+ ```
66
+
67
+ Something like this will be shown as test result:
68
+
69
+ ```
70
+ ...
71
+ raise TypeCheckError(f"is not an instance of {qualified_name(origin_type)}")
72
+ E typeguard.TypeCheckError: item 3 is not an instance of str (from pyright)
73
+ ------------------------------------------------------------- Captured log call -------------------------------------------------------------
74
+ INFO revealtype-injector:hooks.py:26 Replaced reveal_type() from global import with <function revealtype_injector at 0x00000238DB923D00>
75
+ DEBUG revealtype-injector:main.py:60 Extraction OK: code='reveal_type(x)', result='x'
76
+ ========================================================== short test summary info ==========================================================
77
+ FAILED tests/runtime/test_attrib.py::TestAttrib::test_superfluous - typeguard.TypeCheckError: item 3 is not an instance of str (from pyright)
78
+ ============================================================= 1 failed in 3.38s =============================================================
79
+ ```
80
+
81
+
57
82
  ## History
58
83
 
59
84
  This pytest plugin starts its life as part of testsuite related utilities within [`types-lxml`](https://github.com/abelcheung/types-lxml). As `lxml` is a `cython` project and probably never incorporate inline python annotation in future, there is need to compare runtime result to static type checker output for discrepancy. As time goes by, it starts to make sense to manage as an independent project.
@@ -1,8 +1,7 @@
1
1
  #:schema https://json.schemastore.org/pyproject.json
2
2
 
3
3
  [build-system]
4
- # replace with 'hatchling >= 1.27.0' when things are sorted out
5
- requires = ['hatchling @ git+https://github.com/pypa/hatch.git@72d57279ac8fa58b1981734b58d55cf607e84656#subdirectory=backend']
4
+ requires = ['hatchling ~= 1.27']
6
5
  build-backend = 'hatchling.build'
7
6
 
8
7
  [project]
@@ -1,3 +1,3 @@
1
1
  """Pytest plugin for replacing reveal_type() calls inside test functions with static and runtime type checking result comparison, for confirming type annotation validity.""" # noqa: E501
2
2
 
3
- __version__ = "0.2.1"
3
+ __version__ = "0.2.2"
@@ -1,7 +1,6 @@
1
1
  import ast
2
2
  import importlib
3
3
  import json
4
- import logging
5
4
  import pathlib
6
5
  import re
7
6
  from collections.abc import (
@@ -19,6 +18,7 @@ import mypy.api
19
18
  import pytest
20
19
  import schema as s
21
20
 
21
+ from ..log import get_logger
22
22
  from ..models import (
23
23
  FilePos,
24
24
  NameCollectorBase,
@@ -27,8 +27,7 @@ from ..models import (
27
27
  VarType,
28
28
  )
29
29
 
30
- _logger = logging.getLogger(__name__)
31
- _logger.setLevel(logging.INFO)
30
+ _logger = get_logger()
32
31
 
33
32
 
34
33
  class _MypyDiagObj(TypedDict):
@@ -68,7 +67,9 @@ class _NameCollector(NameCollectorBase):
68
67
  _ = self.visit(node.value)
69
68
 
70
69
  if resolved := getattr(self.collected[prefix], name, False):
71
- self.collected[ast.unparse(node)] = resolved
70
+ code = ast.unparse(node)
71
+ self.collected[code] = resolved
72
+ _logger.debug(f"Mypy NameCollector resolved '{code}' as {resolved}")
72
73
  return node
73
74
 
74
75
  # For class defined in local scope, mypy just prepends test
@@ -101,10 +102,13 @@ class _NameCollector(NameCollectorBase):
101
102
  pass
102
103
  else:
103
104
  self.collected[name] = mod
105
+ _logger.debug(f"Mypy NameCollector resolved '{name}' as {mod}")
104
106
  return node
105
107
 
106
108
  if hasattr(self.collected["typing"], name):
107
- self.collected[name] = getattr(self.collected["typing"], name)
109
+ obj = getattr(self.collected["typing"], name)
110
+ self.collected[name] = obj
111
+ _logger.debug(f"Mypy NameCollector resolved '{name}' as {obj}")
108
112
  return node
109
113
 
110
114
  raise NameError(f'Cannot resolve "{name}"')
@@ -162,6 +166,8 @@ class _MypyAdapter(TypeCheckerAdapter):
162
166
  # So-called mypy json output is merely a line-by-line
163
167
  # transformation of plain text output into json object
164
168
  for line in stdout.splitlines():
169
+ if len(line) <= 2 or line[0] != "{":
170
+ continue
165
171
  obj = json.loads(line)
166
172
  diag = cast(_MypyDiagObj, cls._schema.validate(obj))
167
173
  filename = pathlib.Path(diag["file"]).name
@@ -210,7 +216,6 @@ class _MypyAdapter(TypeCheckerAdapter):
210
216
 
211
217
  @classmethod
212
218
  def set_config_file(cls, config: pytest.Config) -> None:
213
- # Mypy doesn't have a default config file
214
219
  if (path_str := config.option.revealtype_mypy_config) is None:
215
220
  _logger.info("Using default mypy configuration")
216
221
  return
@@ -1,6 +1,5 @@
1
1
  import ast
2
2
  import json
3
- import logging
4
3
  import pathlib
5
4
  import re
6
5
  import shutil
@@ -19,6 +18,7 @@ from typing import (
19
18
  import pytest
20
19
  import schema as s
21
20
 
21
+ from ..log import get_logger
22
22
  from ..models import (
23
23
  FilePos,
24
24
  NameCollectorBase,
@@ -27,8 +27,7 @@ from ..models import (
27
27
  VarType,
28
28
  )
29
29
 
30
- _logger = logging.getLogger(__name__)
31
- _logger.setLevel(logging.INFO)
30
+ _logger = get_logger()
32
31
 
33
32
 
34
33
  class _PyrightDiagPosition(TypedDict):
@@ -55,9 +54,12 @@ class _NameCollector(NameCollectorBase):
55
54
  eval(name, self._globalns, self._localns | self.collected)
56
55
  except NameError:
57
56
  for m in ("typing", "typing_extensions"):
58
- if hasattr(self.collected[m], name):
59
- self.collected[name] = getattr(self.collected[m], name)
60
- return node
57
+ if not hasattr(self.collected[m], name):
58
+ continue
59
+ obj = getattr(self.collected[m], name)
60
+ self.collected[name] = obj
61
+ _logger.debug(f"Pyright NameCollector resolved '{name}' as {obj}")
62
+ return node
61
63
  raise
62
64
  return node
63
65
 
@@ -1,15 +1,13 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import inspect
4
- import logging
5
4
 
6
5
  import pytest
7
6
 
8
- from . import adapter
7
+ from . import adapter, log
9
8
  from .main import revealtype_injector
10
9
 
11
- _logger = logging.getLogger(__name__)
12
- _logger.setLevel(logging.INFO)
10
+ _logger = log.get_logger()
13
11
 
14
12
 
15
13
  def pytest_pyfunc_call(pyfuncitem: pytest.Function) -> None:
@@ -65,6 +63,7 @@ def pytest_addoption(parser: pytest.Parser) -> None:
65
63
 
66
64
 
67
65
  def pytest_configure(config: pytest.Config) -> None:
66
+ _logger.setLevel(config.get_verbosity(config.VERBOSITY_TEST_CASES))
68
67
  # Forget config stash, it can't store collection of unserialized objects
69
68
  for adp in adapter.discovery():
70
69
  if config.option.revealtype_disable_adapter == adp.id:
@@ -0,0 +1,19 @@
1
+ import logging
2
+
3
+ LOGGER_NAME = "revealtype-injector"
4
+
5
+ _logger = logging.getLogger(LOGGER_NAME)
6
+
7
+ # Mapping of pytest.Config.VERBOSITY_TEST_CASES to logging levels
8
+ _verbosity_map = {
9
+ 0: logging.WARNING,
10
+ 1: logging.INFO,
11
+ 2: logging.DEBUG,
12
+ }
13
+
14
+ def get_logger() -> logging.Logger:
15
+ return _logger
16
+
17
+
18
+ def set_verbosity(verbosity: int) -> None:
19
+ _logger.setLevel(_verbosity_map.get(verbosity, logging.DEBUG))
@@ -1,6 +1,5 @@
1
1
  import ast
2
2
  import inspect
3
- import logging
4
3
  import pathlib
5
4
  import sys
6
5
  from typing import (
@@ -15,7 +14,7 @@ from typeguard import (
15
14
  check_type_internal,
16
15
  )
17
16
 
18
- from . import adapter
17
+ from . import adapter, log
19
18
  from .models import (
20
19
  FilePos,
21
20
  TypeCheckerError,
@@ -24,8 +23,7 @@ from .models import (
24
23
 
25
24
  _T = TypeVar("_T")
26
25
 
27
- _logger = logging.getLogger(__name__)
28
- _logger.setLevel(logging.WARN)
26
+ _logger = log.get_logger()
29
27
 
30
28
 
31
29
  class RevealTypeExtractor(ast.NodeVisitor):
@@ -42,8 +40,15 @@ class RevealTypeExtractor(ast.NodeVisitor):
42
40
 
43
41
 
44
42
  def _get_var_name(frame: inspect.Traceback) -> str | None:
43
+ filename = pathlib.Path(frame.filename)
44
+ if not filename.exists():
45
+ _logger.warning(
46
+ f"Stack frame points to file '{filename}' "
47
+ "which doesn't exist on local system."
48
+ )
45
49
  ctxt, idx = frame.code_context, frame.index
46
- assert ctxt is not None and idx is not None
50
+ assert ctxt is not None
51
+ assert idx is not None
47
52
  code = ctxt[idx].strip()
48
53
 
49
54
  walker = RevealTypeExtractor()
@@ -51,7 +56,9 @@ def _get_var_name(frame: inspect.Traceback) -> str | None:
51
56
  # as much restriction on test code as 'eval' mode does.
52
57
  walker.visit(ast.parse(code, mode="eval"))
53
58
  assert walker.target is not None
54
- return ast.get_source_segment(code, walker.target)
59
+ result = ast.get_source_segment(code, walker.target)
60
+ _logger.debug(f"Extraction OK: {code=}, {result=}")
61
+ return result
55
62
 
56
63
 
57
64
  def revealtype_injector(var: _T) -> _T:
@@ -134,7 +141,8 @@ def revealtype_injector(var: _T) -> _T:
134
141
  try:
135
142
  check_type_internal(var, ref, memo)
136
143
  except TypeCheckError as e:
137
- e.args = (f"({adp.id}) " + e.args[0],) + e.args[1:]
144
+ # Only args[0] contains message
145
+ e.args = (e.args[0] + f" (from {adp.id})",) + e.args[1:]
138
146
  raise
139
147
 
140
148
  return var
@@ -0,0 +1,91 @@
1
+ import pytest
2
+
3
+
4
+ def test_basic(pytester: pytest.Pytester) -> None:
5
+ pytester.makeconftest(
6
+ "pytest_plugins = ['pytest_revealtype_injector.plugin']"
7
+ )
8
+
9
+ pytester.makepyfile( # pyright: ignore[reportUnknownMemberType]
10
+ """
11
+ import sys
12
+ import pytest
13
+ from typeguard import TypeCheckError
14
+
15
+ if sys.version_info >= (3, 11):
16
+ from typing import reveal_type
17
+ else:
18
+ from typing_extensions import reveal_type
19
+
20
+ def test_inferred():
21
+ x = 1
22
+ reveal_type(x)
23
+
24
+ def test_bad_inline_hint():
25
+ x: str = 1 # type: ignore # pyright: ignore
26
+ with pytest.raises(TypeCheckError, match='is not an instance of str'):
27
+ reveal_type(x)
28
+ """
29
+ )
30
+ result = pytester.runpytest()
31
+ result.assert_outcomes(passed=2)
32
+
33
+
34
+ def test_import_as(pytester: pytest.Pytester) -> None:
35
+ pytester.makeconftest(
36
+ "pytest_plugins = ['pytest_revealtype_injector.plugin']"
37
+ )
38
+
39
+ pytester.makepyfile( # pyright: ignore[reportUnknownMemberType]
40
+ """
41
+ import sys
42
+ import pytest
43
+ from typeguard import TypeCheckError
44
+
45
+ if sys.version_info >= (3, 11):
46
+ from typing import reveal_type as rt
47
+ else:
48
+ from typing_extensions import reveal_type as rt
49
+
50
+ def test_inferred():
51
+ x = 1
52
+ rt(x)
53
+
54
+ def test_bad_inline_hint():
55
+ x: str = 1 # type: ignore # pyright: ignore
56
+ with pytest.raises(TypeCheckError, match='is not an instance of str'):
57
+ rt(x)
58
+ """
59
+ )
60
+ result = pytester.runpytest()
61
+ result.assert_outcomes(passed=2)
62
+
63
+
64
+ def test_import_module_as(pytester: pytest.Pytester) -> None:
65
+ pytester.makeconftest(
66
+ "pytest_plugins = ['pytest_revealtype_injector.plugin']"
67
+ )
68
+
69
+ pytester.makepyfile( # pyright: ignore[reportUnknownMemberType]
70
+ """
71
+ import sys
72
+ import pytest
73
+ from typeguard import TypeCheckError
74
+
75
+ if sys.version_info >= (3, 11):
76
+ import typing as t
77
+ else:
78
+ import typing_extensions as t
79
+
80
+ def test_inferred():
81
+ x = 1
82
+ t.reveal_type(x)
83
+
84
+ def test_bad_inline_hint():
85
+ x: str = 1 # type: ignore # pyright: ignore
86
+ with pytest.raises(TypeCheckError, match='is not an instance of str'):
87
+ t.reveal_type(x)
88
+ """
89
+ )
90
+ result = pytester.runpytest()
91
+ result.assert_outcomes(passed=2)
@@ -1,31 +0,0 @@
1
- import pytest
2
-
3
-
4
- def test_basic(pytester: pytest.Pytester):
5
- pytester.makeconftest(
6
- "pytest_plugins = ['pytest_revealtype_injector.plugin']"
7
- )
8
-
9
- pytester.makepyfile( # pyright: ignore[reportUnknownMemberType]
10
- """
11
- import sys
12
- import pytest
13
- from typeguard import TypeCheckError
14
-
15
- if sys.version_info >= (3, 11):
16
- from typing import reveal_type
17
- else:
18
- from typing_extensions import reveal_type
19
-
20
- def test_inferred():
21
- x = 1
22
- reveal_type(x)
23
-
24
- def test_bad_inline_hint():
25
- x: str = 1 # type: ignore # pyright: ignore
26
- with pytest.raises(TypeCheckError, match='is not an instance of str'):
27
- reveal_type(x)
28
- """
29
- )
30
- result = pytester.runpytest()
31
- result.assert_outcomes(passed=2)