pytest-revealtype-injector 0.2.3__py3-none-any.whl → 0.4.0__py3-none-any.whl

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.
@@ -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.3"
3
+ __version__ = "0.4.0"
@@ -1,13 +1,22 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from ..models import TypeCheckerAdapter
4
- from . import mypy_, pyright_
4
+ from . import basedpyright_, mypy_, pyright_
5
5
 
6
6
 
7
7
  # Hardcode will do for now, it's not like we're going to have more
8
8
  # adapters soon. Pyre and PyType are not there yet.
9
- def discovery() -> set[TypeCheckerAdapter]:
9
+ def generate() -> set[TypeCheckerAdapter]:
10
10
  return {
11
- pyright_.adapter,
12
- mypy_.adapter,
11
+ basedpyright_.generate_adapter(),
12
+ pyright_.generate_adapter(),
13
+ mypy_.generate_adapter(),
13
14
  }
15
+
16
+
17
+ def get_adapter_classes() -> list[type[TypeCheckerAdapter]]:
18
+ return [
19
+ basedpyright_.BasedPyrightAdapter,
20
+ pyright_.PyrightAdapter,
21
+ mypy_.MypyAdapter,
22
+ ]
@@ -0,0 +1,21 @@
1
+ from __future__ import annotations
2
+
3
+ from ..log import get_logger
4
+ from ..models import TypeCheckerAdapter
5
+ from . import pyright_
6
+
7
+ _logger = get_logger()
8
+
9
+
10
+ class NameCollector(pyright_.NameCollector):
11
+ type_checker = "basedpyright"
12
+
13
+
14
+ class BasedPyrightAdapter(pyright_.PyrightAdapter):
15
+ id = "basedpyright"
16
+ _executable = "basedpyright"
17
+ _namecollector_class = NameCollector
18
+
19
+
20
+ def generate_adapter() -> TypeCheckerAdapter:
21
+ return BasedPyrightAdapter()
@@ -1,3 +1,5 @@
1
+ from __future__ import annotations
2
+
1
3
  import ast
2
4
  import importlib
3
5
  import json
@@ -7,7 +9,6 @@ from collections.abc import (
7
9
  Iterable,
8
10
  )
9
11
  from typing import (
10
- Any,
11
12
  ForwardRef,
12
13
  Literal,
13
14
  TypedDict,
@@ -15,7 +16,6 @@ from typing import (
15
16
  )
16
17
 
17
18
  import mypy.api
18
- import pytest
19
19
  import schema as s
20
20
 
21
21
  from ..log import get_logger
@@ -40,7 +40,9 @@ class _MypyDiagObj(TypedDict):
40
40
  severity: Literal["note", "warning", "error"]
41
41
 
42
42
 
43
- class _NameCollector(NameCollectorBase):
43
+ class NameCollector(NameCollectorBase):
44
+ type_checker = "mypy"
45
+
44
46
  def visit_Attribute(self, node: ast.Attribute) -> ast.expr:
45
47
  prefix = ast.unparse(node.value)
46
48
  name = node.attr
@@ -69,7 +71,9 @@ class _NameCollector(NameCollectorBase):
69
71
  if resolved := getattr(self.collected[prefix], name, False):
70
72
  code = ast.unparse(node)
71
73
  self.collected[code] = resolved
72
- _logger.debug(f"Mypy NameCollector resolved '{code}' as {resolved}")
74
+ _logger.debug(
75
+ f"{self.type_checker} NameCollector resolved '{code}' as {resolved}"
76
+ )
73
77
  return node
74
78
 
75
79
  # For class defined in local scope, mypy just prepends test
@@ -102,13 +106,17 @@ class _NameCollector(NameCollectorBase):
102
106
  pass
103
107
  else:
104
108
  self.collected[name] = mod
105
- _logger.debug(f"Mypy NameCollector resolved '{name}' as {mod}")
109
+ _logger.debug(
110
+ f"{self.type_checker} NameCollector resolved '{name}' as {mod}"
111
+ )
106
112
  return node
107
113
 
108
114
  if hasattr(self.collected["typing"], name):
109
115
  obj = getattr(self.collected["typing"], name)
110
116
  self.collected[name] = obj
111
- _logger.debug(f"Mypy NameCollector resolved '{name}' as {obj}")
117
+ _logger.debug(
118
+ f"{self.type_checker} NameCollector resolved '{name}' as {obj}"
119
+ )
112
120
  return node
113
121
 
114
122
  raise NameError(f'Cannot resolve "{name}"')
@@ -118,17 +126,17 @@ class _NameCollector(NameCollectorBase):
118
126
  # Return only the left operand after processing.
119
127
  def visit_BinOp(self, node: ast.BinOp) -> ast.expr:
120
128
  if isinstance(node.op, ast.MatMult) and isinstance(node.right, ast.Constant):
121
- # Mypy disallows returning Any
122
129
  return cast("ast.expr", self.visit(node.left))
123
130
  # For expression that haven't been accounted for, just don't
124
131
  # process and allow name resolution to fail
125
132
  return node
126
133
 
127
134
 
128
- class _MypyAdapter(TypeCheckerAdapter):
135
+ class MypyAdapter(TypeCheckerAdapter):
129
136
  id = "mypy"
130
- typechecker_result = {}
131
- _type_mesg_re = re.compile(r'^Revealed type is "(?P<type>.+?)"$')
137
+ _executable = "" # unused, calls mypy.api.run() here
138
+ _type_mesg_re = re.compile(r'Revealed type is "(?P<type>.+?)"')
139
+ _namecollector_class = NameCollector
132
140
  _schema = s.Schema({
133
141
  "file": str,
134
142
  "line": int,
@@ -143,19 +151,20 @@ class _MypyAdapter(TypeCheckerAdapter):
143
151
  ),
144
152
  })
145
153
 
146
- @classmethod
147
- def run_typechecker_on(cls, paths: Iterable[pathlib.Path]) -> None:
154
+ def run_typechecker_on(self, paths: Iterable[pathlib.Path]) -> None:
148
155
  mypy_args = [
149
156
  "--output=json",
150
157
  ]
151
- if cls.config_file is not None:
152
- cfg_str = str(cls.config_file)
153
- if cfg_str == ".": # see set_config_file() below
154
- cfg_str = ""
158
+ if self.config_file is not None:
159
+ if self.config_file == pathlib.Path():
160
+ cfg_str = "" # see preprocess_config_file() below
161
+ else:
162
+ cfg_str = str(self.config_file)
155
163
  mypy_args.append(f"--config-file={cfg_str}")
156
164
 
157
165
  mypy_args.extend(str(p) for p in paths)
158
166
 
167
+ _logger.debug(f"({self.id}) api.run(): {mypy_args}")
159
168
  stdout, stderr, returncode = mypy.api.run(mypy_args)
160
169
 
161
170
  # fatal error, before evaluation happens
@@ -163,24 +172,41 @@ class _MypyAdapter(TypeCheckerAdapter):
163
172
  if stderr:
164
173
  raise TypeCheckerError(stderr, None, None)
165
174
 
175
+ lines = stdout.splitlines()
176
+ _logger.info(
177
+ "({}) Return code = {}, diagnostic count = {}.{}".format(
178
+ self.id,
179
+ returncode,
180
+ len(lines),
181
+ " pytest -vv shows all items." if self.log_verbosity < 2 else "",
182
+ )
183
+ )
184
+
166
185
  # So-called mypy json output is merely a line-by-line
167
186
  # transformation of plain text output into json object
168
- for line in stdout.splitlines():
187
+ for line in lines:
169
188
  if len(line) <= 2 or line[0] != "{":
170
189
  continue
190
+ if self.log_verbosity >= 2:
191
+ _logger.debug(f"({self.id}) {line}")
171
192
  obj = json.loads(line)
172
- diag = cast(_MypyDiagObj, cls._schema.validate(obj))
193
+ diag = cast(_MypyDiagObj, self._schema.validate(obj))
173
194
  filename = pathlib.Path(diag["file"]).name
174
195
  pos = FilePos(filename, diag["line"])
196
+ # HACK: Never trust return code from mypy. During early 1.11.x
197
+ # versions, mypy always return 1 for JSON output even when
198
+ # there's no error. Later on mypy command line has fixed this,
199
+ # but not mypy.api.run(), as of 1.13.
175
200
  if diag["severity"] != "note":
176
201
  raise TypeCheckerError(
177
- "Mypy {} with exit code {}: {}".format(
178
- diag["severity"], returncode, diag["message"]
202
+ "{} {} with exit code {}: {}".format(
203
+ self.id, diag["severity"], returncode, diag["message"]
179
204
  ),
180
205
  diag["file"],
181
206
  diag["line"],
207
+ diag["code"],
182
208
  )
183
- if (m := cls._type_mesg_re.match(diag["message"])) is None:
209
+ if (m := self._type_mesg_re.fullmatch(diag["message"])) is None:
184
210
  continue
185
211
  # Mypy can insert extra character into expression so that it
186
212
  # becomes invalid and unparsable. 0.9x days there
@@ -190,14 +216,14 @@ class _MypyAdapter(TypeCheckerAdapter):
190
216
  expression = m["type"].translate({ord(c): None for c in "*?="})
191
217
  try:
192
218
  # Unlike pyright, mypy output doesn't contain variable name
193
- cls.typechecker_result[pos] = VarType(None, ForwardRef(expression))
219
+ self.typechecker_result[pos] = VarType(None, ForwardRef(expression))
194
220
  except SyntaxError as e:
195
221
  if (
196
222
  m := re.fullmatch(r"<Deleted '(?P<var>.+)'>", expression)
197
223
  ) is not None:
198
224
  raise TypeCheckerError(
199
225
  "{} does not support reusing deleted variable '{}'".format(
200
- cls.id, m["var"]
226
+ self.id, m["var"]
201
227
  ),
202
228
  diag["file"],
203
229
  diag["line"],
@@ -208,46 +234,17 @@ class _MypyAdapter(TypeCheckerAdapter):
208
234
  diag["line"],
209
235
  ) from e
210
236
 
211
- @classmethod
212
- def create_collector(
213
- cls, globalns: dict[str, Any], localns: dict[str, Any]
214
- ) -> _NameCollector:
215
- return _NameCollector(globalns, localns)
216
-
217
- @classmethod
218
- def set_config_file(cls, config: pytest.Config) -> None:
219
- if (path_str := config.option.revealtype_mypy_config) is None:
220
- _logger.info("Using default mypy configuration")
221
- return
222
-
237
+ def preprocess_config_file(self, path_str: str) -> bool:
238
+ if path_str:
239
+ return False
223
240
  # HACK: when path_str is empty string, use no config file
224
241
  # ('mypy --config-file=')
225
- # Take advantage of pathlib.Path() behavior that empty string
226
- # is treated as current directory, which is not a valid
227
- # config file name, while satisfying typing constraint
228
- if not path_str:
229
- cls.config_file = pathlib.Path()
230
- return
231
-
232
- relpath = pathlib.Path(path_str)
233
- if relpath.is_absolute():
234
- raise ValueError(f"Path '{path_str}' must be relative to pytest rootdir")
235
- result = (config.rootpath / relpath).resolve()
236
- if not result.exists():
237
- raise FileNotFoundError(f"Path '{result}' not found")
238
-
239
- _logger.info(f"Using mypy configuration file at {result}")
240
- cls.config_file = result
241
-
242
- @staticmethod
243
- def add_pytest_option(group: pytest.OptionGroup) -> None:
244
- group.addoption(
245
- "--revealtype-mypy-config",
246
- type=str,
247
- default=None,
248
- help="Mypy configuration file, path is relative to pytest rootdir. "
249
- "If unspecified, use mypy default behavior",
250
- )
242
+ # The special value is for satisfying typing constraint;
243
+ # it will be treated specially in run_typechecker_on()
244
+ self.config_file = pathlib.Path()
245
+ self._logger.info(f"({self.id}) Config file usage forbidden")
246
+ return True
251
247
 
252
248
 
253
- adapter = _MypyAdapter()
249
+ def generate_adapter() -> TypeCheckerAdapter:
250
+ return MypyAdapter()
@@ -1,22 +1,27 @@
1
+ from __future__ import annotations
2
+
1
3
  import ast
2
4
  import json
3
5
  import pathlib
4
6
  import re
5
7
  import shutil
6
8
  import subprocess
9
+ import sys
7
10
  from collections.abc import (
8
11
  Iterable,
9
12
  )
10
13
  from typing import (
11
- Any,
12
14
  ForwardRef,
13
15
  Literal,
14
- TypedDict,
15
16
  TypeVar,
16
17
  cast,
17
18
  )
18
19
 
19
- import pytest
20
+ if sys.version_info >= (3, 11):
21
+ from typing import NotRequired, TypedDict
22
+ else:
23
+ from typing_extensions import NotRequired, TypedDict
24
+
20
25
  import schema as s
21
26
 
22
27
  from ..log import get_logger
@@ -46,9 +51,10 @@ class _PyrightDiagItem(TypedDict):
46
51
  severity: Literal["information", "warning", "error"]
47
52
  message: str
48
53
  range: _PyrightDiagRange
54
+ rule: NotRequired[str]
49
55
 
50
-
51
- class _NameCollector(NameCollectorBase):
56
+ class NameCollector(NameCollectorBase):
57
+ type_checker = "pyright"
52
58
  # Pre-register common used bare names from typing
53
59
  collected = NameCollectorBase.collected | {
54
60
  k: v
@@ -68,18 +74,21 @@ class _NameCollector(NameCollectorBase):
68
74
  continue
69
75
  obj = getattr(self.collected[m], name)
70
76
  self.collected[name] = obj
71
- _logger.debug(f"Pyright NameCollector resolved '{name}' as {obj}")
77
+ _logger.debug(
78
+ f"{self.type_checker} NameCollector resolved '{name}' as {obj}"
79
+ )
72
80
  return node
73
81
  raise
74
82
  return node
75
83
 
76
84
 
77
- class _PyrightAdapter(TypeCheckerAdapter):
85
+ class PyrightAdapter(TypeCheckerAdapter):
78
86
  id = "pyright"
79
- typechecker_result = {}
80
- _type_mesg_re = re.compile('^Type of "(?P<var>.+?)" is "(?P<type>.+?)"$')
81
- # We only care about diagnostic messages that contain type information.
82
- # Metadata not specified here.
87
+ _executable = "pyright"
88
+ _type_mesg_re = re.compile('Type of "(?P<var>.+?)" is "(?P<type>.+?)"')
89
+ _namecollector_class = NameCollector
90
+ # We only care about diagnostic messages that contain type information, that
91
+ # is, items under "generalDiagnostics" key. Metadata not validated here.
83
92
  _schema = s.Schema({
84
93
  "file": str,
85
94
  "severity": s.Or(
@@ -92,30 +101,42 @@ class _PyrightAdapter(TypeCheckerAdapter):
92
101
  "start": {"line": int, "character": int},
93
102
  "end": {"line": int, "character": int},
94
103
  },
104
+ s.Optional("rule"): str,
95
105
  })
96
106
 
97
- @classmethod
98
- def run_typechecker_on(cls, paths: Iterable[pathlib.Path]) -> None:
107
+ def run_typechecker_on(self, paths: Iterable[pathlib.Path]) -> None:
99
108
  cmd: list[str] = []
100
- if shutil.which("pyright") is not None:
101
- cmd.append("pyright")
109
+ if shutil.which(self._executable) is not None:
110
+ cmd.append(self._executable)
102
111
  elif shutil.which("npx") is not None:
103
- cmd.extend(["npx", "pyright"])
112
+ cmd.extend(["npx", self._executable])
104
113
  else:
105
- raise FileNotFoundError("Pyright is required to run test suite")
114
+ raise FileNotFoundError(f"{self._executable} is required to run test suite")
106
115
 
107
116
  cmd.append("--outputjson")
108
- if cls.config_file is not None:
109
- cmd.extend(["--project", str(cls.config_file)])
117
+ if self.config_file is not None:
118
+ cmd.extend(["--project", str(self.config_file)])
110
119
  cmd.extend(str(p) for p in paths)
111
120
 
121
+ _logger.debug(f"({self.id}) Run command: {cmd}")
112
122
  proc = subprocess.run(cmd, capture_output=True)
113
123
  if len(proc.stderr):
114
124
  raise TypeCheckerError(proc.stderr.decode(), None, None)
115
125
 
116
126
  report = json.loads(proc.stdout)
127
+ _logger.info(
128
+ "({}) Return code = {}, diagnostic count = {}.{}".format(
129
+ self.id,
130
+ proc.returncode,
131
+ len(report["generalDiagnostics"]),
132
+ " pytest -vv shows all items." if self.log_verbosity < 2 else "",
133
+ )
134
+ )
135
+
117
136
  for item in report["generalDiagnostics"]:
118
- diag = cast(_PyrightDiagItem, cls._schema.validate(item))
137
+ diag = cast(_PyrightDiagItem, self._schema.validate(item))
138
+ if self.log_verbosity >= 2:
139
+ _logger.debug(f"({self.id}) {diag}")
119
140
  if diag["severity"] != ("error" if proc.returncode else "information"):
120
141
  continue
121
142
  # Pyright report lineno is 0-based, while
@@ -123,43 +144,20 @@ class _PyrightAdapter(TypeCheckerAdapter):
123
144
  lineno = diag["range"]["start"]["line"] + 1
124
145
  filename = pathlib.Path(diag["file"]).name
125
146
  if proc.returncode:
126
- raise TypeCheckerError(diag["message"], filename, lineno)
127
- if (m := cls._type_mesg_re.match(diag["message"])) is None:
147
+ assert "rule" in diag
148
+ raise TypeCheckerError(
149
+ "{} {} with exit code {}: {}".format(
150
+ self.id, diag["severity"], proc.returncode, diag["message"]
151
+ ),
152
+ filename,
153
+ lineno,
154
+ diag["rule"],
155
+ )
156
+ if (m := self._type_mesg_re.fullmatch(diag["message"])) is None:
128
157
  continue
129
158
  pos = FilePos(filename, lineno)
130
- cls.typechecker_result[pos] = VarType(m["var"], ForwardRef(m["type"]))
131
-
132
- @classmethod
133
- def create_collector(
134
- cls, globalns: dict[str, Any], localns: dict[str, Any]
135
- ) -> _NameCollector:
136
- return _NameCollector(globalns, localns)
137
-
138
- @classmethod
139
- def set_config_file(cls, config: pytest.Config) -> None:
140
- if (path_str := config.option.revealtype_pyright_config) is None:
141
- _logger.info("Using default pyright configuration")
142
- return
143
-
144
- relpath = pathlib.Path(path_str)
145
- if relpath.is_absolute():
146
- raise ValueError(f"Path '{path_str}' must be relative to pytest rootdir")
147
- result = (config.rootpath / relpath).resolve()
148
- if not result.exists():
149
- raise FileNotFoundError(f"Path '{result}' not found")
150
-
151
- _logger.info(f"Using pyright configuration file at {result}")
152
- cls.config_file = result
153
-
154
- @staticmethod
155
- def add_pytest_option(group: pytest.OptionGroup) -> None:
156
- group.addoption(
157
- "--revealtype-pyright-config",
158
- type=str,
159
- default=None,
160
- help="Pyright configuration file, path is relative to pytest rootdir. "
161
- "If unspecified, use pyright default behavior",
162
- )
159
+ self.typechecker_result[pos] = VarType(m["var"], ForwardRef(m["type"]))
163
160
 
164
161
 
165
- adapter = _PyrightAdapter()
162
+ def generate_adapter() -> TypeCheckerAdapter:
163
+ return PyrightAdapter()
@@ -1,17 +1,24 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import functools
3
4
  import inspect
5
+ from typing import cast
4
6
 
5
7
  import pytest
6
8
 
7
9
  from . import adapter, log
8
10
  from .main import revealtype_injector
11
+ from .models import TypeCheckerAdapter
9
12
 
10
13
  _logger = log.get_logger()
14
+ adapter_stash_key: pytest.StashKey[set[TypeCheckerAdapter]]
11
15
 
12
16
 
13
17
  def pytest_pyfunc_call(pyfuncitem: pytest.Function) -> None:
14
18
  assert pyfuncitem.module is not None
19
+ adapters = pyfuncitem.config.stash[adapter_stash_key].copy()
20
+ injected = functools.partial(revealtype_injector, adapters=adapters)
21
+
15
22
  for name in dir(pyfuncitem.module):
16
23
  if name.startswith("__") or name.startswith("@py"):
17
24
  continue
@@ -22,26 +29,29 @@ def pytest_pyfunc_call(pyfuncitem: pytest.Function) -> None:
22
29
  "typing",
23
30
  "typing_extensions",
24
31
  }:
25
- setattr(pyfuncitem.module, name, revealtype_injector)
26
- _logger.info(
27
- f"Replaced {name}() from global import with {revealtype_injector}"
28
- )
32
+ setattr(pyfuncitem.module, name, injected)
33
+ _logger.info(f"Replaced {name}() from global import with {injected}")
29
34
  continue
30
35
 
31
36
  if inspect.ismodule(item):
32
37
  if item.__name__ not in {"typing", "typing_extensions"}:
33
38
  continue
34
39
  assert hasattr(item, "reveal_type")
35
- setattr(item, "reveal_type", revealtype_injector)
36
- _logger.info(f"Replaced {name}.reveal_type() with {revealtype_injector}")
40
+ setattr(item, "reveal_type", injected)
41
+ _logger.info(f"Replaced {name}.reveal_type() with {injected}")
37
42
  continue
38
43
 
39
44
 
40
45
  def pytest_collection_finish(session: pytest.Session) -> None:
41
46
  files = {i.path for i in session.items}
42
- for adp in adapter.discovery():
43
- if adp.enabled:
47
+ for adp in session.config.stash[adapter_stash_key]:
48
+ try:
44
49
  adp.run_typechecker_on(files)
50
+ except Exception as e:
51
+ _logger.error(f"({adp.id}) {e}")
52
+ pytest.exit(f"({type(e).__name__}) " + str(e), pytest.ExitCode.INTERNAL_ERROR)
53
+ else:
54
+ _logger.info(f"({adp.id}) Type checker ran successfully")
45
55
 
46
56
 
47
57
  def pytest_addoption(parser: pytest.Parser) -> None:
@@ -49,25 +59,32 @@ def pytest_addoption(parser: pytest.Parser) -> None:
49
59
  "revealtype-injector",
50
60
  description="Type checker related options for revealtype-injector",
51
61
  )
52
- adapters = adapter.discovery()
53
- choices = tuple(adp.id for adp in adapters)
62
+ classes = adapter.get_adapter_classes()
54
63
  group.addoption(
55
64
  "--revealtype-disable-adapter",
56
65
  type=str,
57
- choices=choices,
58
- default=None,
59
- help="Disable this type checker when using revealtype-injector plugin",
66
+ choices=tuple(c.id for c in classes),
67
+ action="append",
68
+ default=[],
69
+ help="Disable specific type checker. Can be used multiple times"
70
+ " to disable multiple checkers",
60
71
  )
61
- for adp in adapters:
62
- adp.add_pytest_option(group)
72
+ for c in classes:
73
+ c.add_pytest_option(group)
63
74
 
64
75
 
65
76
  def pytest_configure(config: pytest.Config) -> None:
66
- _logger.setLevel(config.get_verbosity(config.VERBOSITY_TEST_CASES))
67
- # Forget config stash, it can't store collection of unserialized objects
68
- for adp in adapter.discovery():
69
- if config.option.revealtype_disable_adapter == adp.id:
70
- adp.enabled = False
71
- _logger.info(f"Disable {adp.id} adapter based on command line option")
72
- else:
73
- adp.set_config_file(config)
77
+ global adapter_stash_key
78
+ adapter_stash_key = pytest.StashKey[set[TypeCheckerAdapter]]()
79
+ config.stash[adapter_stash_key] = set()
80
+ verbosity = config.get_verbosity(config.VERBOSITY_TEST_CASES)
81
+ log.set_verbosity(verbosity)
82
+ to_be_disabled = cast(list[str], config.getoption("revealtype_disable_adapter"))
83
+ for klass in adapter.get_adapter_classes():
84
+ if klass.id in to_be_disabled:
85
+ _logger.info(f"({klass.id}) adapter disabled with command line option")
86
+ continue
87
+ adp = klass()
88
+ adp.set_config_file(config)
89
+ adp.log_verbosity = verbosity
90
+ config.stash[adapter_stash_key].add(adp)
@@ -11,6 +11,7 @@ _verbosity_map = {
11
11
  2: logging.DEBUG,
12
12
  }
13
13
 
14
+
14
15
  def get_logger() -> logging.Logger:
15
16
  return _logger
16
17
 
@@ -14,15 +14,15 @@ from typeguard import (
14
14
  check_type_internal,
15
15
  )
16
16
 
17
- from . import adapter, log
17
+ from . import log
18
18
  from .models import (
19
19
  FilePos,
20
+ TypeCheckerAdapter,
20
21
  TypeCheckerError,
21
22
  VarType,
22
23
  )
23
24
 
24
25
  _T = TypeVar("_T")
25
-
26
26
  _logger = log.get_logger()
27
27
 
28
28
 
@@ -61,7 +61,7 @@ def _get_var_name(frame: inspect.Traceback) -> str | None:
61
61
  return result
62
62
 
63
63
 
64
- def revealtype_injector(var: _T) -> _T:
64
+ def revealtype_injector(var: _T, adapters: set[TypeCheckerAdapter]) -> _T:
65
65
  """Replacement of `reveal_type()` that matches static and runtime type
66
66
  checking result
67
67
 
@@ -105,9 +105,7 @@ def revealtype_injector(var: _T) -> _T:
105
105
  globalns = caller_frame.f_globals
106
106
  localns = caller_frame.f_locals
107
107
 
108
- for adp in adapter.discovery():
109
- if not adp.enabled:
110
- continue
108
+ for adp in adapters:
111
109
  try:
112
110
  tc_result = adp.typechecker_result[pos]
113
111
  except KeyError as e:
@@ -128,12 +126,26 @@ def revealtype_injector(var: _T) -> _T:
128
126
  ref = tc_result.type
129
127
  walker = adp.create_collector(globalns, localns)
130
128
  try:
131
- _ = eval(ref.__forward_arg__, globalns, localns | walker.collected)
129
+ evaluated = eval(ref.__forward_arg__, globalns, localns | walker.collected)
132
130
  except (TypeError, NameError):
133
- ref_ast = ast.parse(ref.__forward_arg__, mode="eval")
134
- new_ast = walker.visit(ref_ast)
131
+ old_ast = ast.parse(ref.__forward_arg__, mode="eval")
132
+ new_ast = walker.visit(old_ast)
135
133
  if walker.modified:
136
134
  ref = ForwardRef(ast.unparse(new_ast))
135
+ evaluated = eval(ref.__forward_arg__, globalns, localns | walker.collected)
136
+
137
+ # HACK Mainly serves as a guard against mypy's behavior of blanket
138
+ # inferring to Any when it can't determine the type under non-strict
139
+ # mode. This behavior causes typeguard to remain silent, since Any is
140
+ # compatible with everything. This has a side effect of disallowing
141
+ # use of reveal_type() on data truly of Any type.
142
+ if evaluated is Any:
143
+ raise TypeCheckerError(
144
+ f"Inferred type of '{var_name}' is Any, which "
145
+ "defeats the purpose of type checking",
146
+ pos.file,
147
+ pos.lineno,
148
+ )
137
149
  memo = TypeCheckMemo(globalns, localns | walker.collected)
138
150
 
139
151
  try:
@@ -15,8 +15,11 @@ from typing import (
15
15
  )
16
16
 
17
17
  import pytest
18
+ from _pytest.config import Notset
18
19
  from schema import Schema
19
20
 
21
+ from .log import get_logger
22
+
20
23
 
21
24
  class FilePos(NamedTuple):
22
25
  file: str
@@ -30,16 +33,24 @@ class VarType(NamedTuple):
30
33
 
31
34
  class TypeCheckerError(Exception):
32
35
  # Can be None when type checker dies before any code evaluation
33
- def __init__(self, message: str, filename: str | None, lineno: int | None) -> None:
36
+ def __init__(
37
+ self,
38
+ message: str,
39
+ filename: str | None,
40
+ lineno: int | None,
41
+ rule: str | None = None,
42
+ ) -> None:
34
43
  super().__init__(message)
35
44
  self._filename = filename
36
45
  self._lineno = lineno
46
+ self._rule = rule
37
47
 
38
48
  def __str__(self) -> str:
39
49
  if self._filename:
40
- return '"{}"{}: {}'.format(
50
+ return '"{}"{}{}: {}'.format(
41
51
  self._filename,
42
52
  " line " + str(self._lineno) if self._lineno else "",
53
+ ', violating "' + self._rule + '" rule' if self._rule else "",
43
54
  self.args[0],
44
55
  )
45
56
  else:
@@ -47,12 +58,14 @@ class TypeCheckerError(Exception):
47
58
 
48
59
 
49
60
  class NameCollectorBase(ast.NodeTransformer):
61
+ type_checker: ClassVar[str]
50
62
  # typing_extensions guaranteed to be present,
51
63
  # as a dependency of typeguard
52
64
  collected: dict[str, Any] = {
53
65
  m: importlib.import_module(m)
54
66
  for m in ("builtins", "typing", "typing_extensions")
55
67
  }
68
+
56
69
  def __init__(
57
70
  self,
58
71
  globalns: dict[str, Any],
@@ -86,26 +99,69 @@ class NameCollectorBase(ast.NodeTransformer):
86
99
 
87
100
 
88
101
  class TypeCheckerAdapter:
89
- enabled: bool = True
90
- config_file: ClassVar[pathlib.Path | None] = None
91
102
  # Subclasses need to specify default values for below
92
103
  id: ClassVar[str]
93
- # {('file.py', 10): ('var_name', 'list[str]'), ...}
94
- typechecker_result: ClassVar[dict[FilePos, VarType]]
104
+ _executable: ClassVar[str]
95
105
  _type_mesg_re: ClassVar[re.Pattern[str]]
96
106
  _schema: ClassVar[Schema]
107
+ _namecollector_class: ClassVar[type[NameCollectorBase]]
108
+
109
+ def __init__(self) -> None:
110
+ # {('file.py', 10): ('var_name', 'list[str]'), ...}
111
+ self.typechecker_result: dict[FilePos, VarType] = {}
112
+ self._logger = get_logger()
113
+ # logger level is already set by pytest_configure()
114
+ # this only affects how much debug message is shown
115
+ self.log_verbosity: int = 1
116
+ self.enabled: bool = True
117
+ self.config_file: pathlib.Path | None = None
97
118
 
98
119
  @classmethod
120
+ def longopt_for_config(cls) -> str:
121
+ return f"--revealtype-{cls.id}-config"
122
+
99
123
  @abc.abstractmethod
100
- def run_typechecker_on(cls, paths: Iterable[pathlib.Path]) -> None: ...
101
- @classmethod
102
- @abc.abstractmethod
124
+ def run_typechecker_on(self, paths: Iterable[pathlib.Path]) -> None: ...
125
+
103
126
  def create_collector(
104
- cls, globalns: dict[str, Any], localns: dict[str, Any]
105
- ) -> NameCollectorBase: ...
127
+ self, globalns: dict[str, Any], localns: dict[str, Any]
128
+ ) -> NameCollectorBase:
129
+ return self._namecollector_class(globalns, localns)
130
+
131
+ def preprocess_config_file(self, path_str: str) -> bool:
132
+ """Optional preprocessing of configuration file"""
133
+ return False
134
+
135
+ def set_config_file(self, config: pytest.Config) -> None:
136
+ path_str = config.getoption(self.longopt_for_config())
137
+ # pytest addoption() should have set default value
138
+ # to None even when option is not specified
139
+ assert not isinstance(path_str, Notset)
140
+
141
+ if path_str is None:
142
+ self._logger.info(f"({self.id}) Using default configuration")
143
+ return
144
+
145
+ if self.preprocess_config_file(path_str):
146
+ return
147
+
148
+ relpath = pathlib.Path(path_str)
149
+ if relpath.is_absolute():
150
+ raise ValueError(f"Path '{path_str}' must be relative to pytest rootdir")
151
+ result = (config.rootpath / relpath).resolve()
152
+ if not result.exists():
153
+ raise FileNotFoundError(f"Path '{result}' not found")
154
+
155
+ self._logger.info(f"({self.id}) Using config file at {result}")
156
+ self.config_file = result
157
+
106
158
  @classmethod
107
- @abc.abstractmethod
108
- def set_config_file(cls, config: pytest.Config) -> None: ...
109
- @staticmethod
110
- @abc.abstractmethod
111
- def add_pytest_option(group: pytest.OptionGroup) -> None: ...
159
+ def add_pytest_option(cls, group: pytest.OptionGroup) -> None:
160
+ group.addoption(
161
+ cls.longopt_for_config(),
162
+ type=str,
163
+ default=None,
164
+ metavar="RELATIVE_PATH",
165
+ help=f"{cls.id} configuration file, path is relative to pytest "
166
+ f"rootdir. If unspecified, use {cls.id} default behavior",
167
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytest-revealtype-injector
3
- Version: 0.2.3
3
+ Version: 0.4.0
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>
@@ -21,11 +21,13 @@ Classifier: Programming Language :: Python :: 3.13
21
21
  Classifier: Topic :: Software Development :: Testing
22
22
  Classifier: Typing :: Typed
23
23
  Requires-Python: >=3.10
24
+ Requires-Dist: basedpyright>=1.0
24
25
  Requires-Dist: mypy>=1.11.2
25
- Requires-Dist: pyright~=1.1
26
- Requires-Dist: pytest>=7.0
26
+ Requires-Dist: pyright>=1.1
27
+ Requires-Dist: pytest<9,>=7.0
27
28
  Requires-Dist: schema==0.7.7
28
- Requires-Dist: typeguard~=4.3
29
+ Requires-Dist: typeguard>=4.3
30
+ Requires-Dist: typing-extensions>=4.0; python_version < '3.11'
29
31
  Description-Content-Type: text/markdown
30
32
 
31
33
  ![PyPI - Version](https://img.shields.io/pypi/v/pytest-revealtype-injector)
@@ -0,0 +1,17 @@
1
+ pytest_revealtype_injector/__init__.py,sha256=hHWlJeHmCZawdklN1L2-t_-JGINlVjJ1fK6c2z5jzrA,211
2
+ pytest_revealtype_injector/hooks.py,sha256=yOwey95EtwuImcveGXn5DaKhCgJ2cgFR16sLbJuXMwo,3169
3
+ pytest_revealtype_injector/log.py,sha256=Ptd3yp1H1GlUum6BAwHc9cdyeGmaY8XYf0jp6qJmG4M,418
4
+ pytest_revealtype_injector/main.py,sha256=nRh2uk64nsn9Y3PdGYew-Bhpfl0HZxmIur39RWpMNCk,5434
5
+ pytest_revealtype_injector/models.py,sha256=VhjpVbbJE3ZtTPAtkJ8hZtl6sg070A875PgaTybxCO4,5170
6
+ pytest_revealtype_injector/plugin.py,sha256=fkI6yF0dFVba0jEikIrsRp1NUQd2ohWLq4x2lSvFyH0,211
7
+ pytest_revealtype_injector/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ pytest_revealtype_injector/adapter/__init__.py,sha256=FRVB1eUrXaMzdQG0wRdIEKhx2dzGdyJcHDBb3eTTeOY,602
9
+ pytest_revealtype_injector/adapter/basedpyright_.py,sha256=8LX7GmJmg4OZ3LKO5WoQ7Ocub6Lxi3HTStIorMApzUA,466
10
+ pytest_revealtype_injector/adapter/mypy_.py,sha256=J9duK2hFo7lZMB_Lz8ccntqZerBFCQBhw--jqkGsUeE,8808
11
+ pytest_revealtype_injector/adapter/pyright_.py,sha256=V0BE6sUJURtwXp_W5vP3EmIdXTL6pB8Yewq-L_YgCb0,5121
12
+ pytest_revealtype_injector-0.4.0.dist-info/METADATA,sha256=rUmQ1UPMdTfkCXP7q8_OuU01NMAjLAXMUAnx-pqnL3E,5619
13
+ pytest_revealtype_injector-0.4.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
14
+ pytest_revealtype_injector-0.4.0.dist-info/entry_points.txt,sha256=UfOm7y3WQnOoGV1mgTMb42MI6iBRPIl88FJiAOnt6SY,74
15
+ pytest_revealtype_injector-0.4.0.dist-info/licenses/COPYING,sha256=LSYUX8PcSMvHCkhM5oi07eOrSLV89qdEJ-FVZmbcpNE,355
16
+ pytest_revealtype_injector-0.4.0.dist-info/licenses/COPYING.mit,sha256=IzYEFDIOECyuupg_B3O9FvgjnU9i4JtambpbleoYHdQ,1060
17
+ pytest_revealtype_injector-0.4.0.dist-info/RECORD,,
@@ -1,16 +0,0 @@
1
- pytest_revealtype_injector/__init__.py,sha256=I8FXkeB3TED-tbJ3KWZ60nazA1c8pSsF_10q0NGof-I,211
2
- pytest_revealtype_injector/hooks.py,sha256=cj1iXJJrVtqylXvvdLfjZ61HGBt5wsGBUe-iAgu9WiU,2434
3
- pytest_revealtype_injector/log.py,sha256=U9IvsoZzhFQcdFmVtuSmt2OTYxxFuIP5o321dyE4hiA,417
4
- pytest_revealtype_injector/main.py,sha256=ZNb_hDeuEIWDC_eSCLmXXfGCarHF1lsXIOE_BWL-940,4731
5
- pytest_revealtype_injector/models.py,sha256=FKYznMaNP9a4_AUN3vMdRQBvQUkbdCYTYjDccgdrV6w,3238
6
- pytest_revealtype_injector/plugin.py,sha256=fkI6yF0dFVba0jEikIrsRp1NUQd2ohWLq4x2lSvFyH0,211
7
- pytest_revealtype_injector/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
- pytest_revealtype_injector/adapter/__init__.py,sha256=wQg3Ply0Xrfe9US_lzgqRgKFE89ZBvDFti6_77X_NKk,339
9
- pytest_revealtype_injector/adapter/mypy_.py,sha256=q-stxOY2bffTAm2SoHiCAb7VA_f9jXc4UxlyimXV-RY,8840
10
- pytest_revealtype_injector/adapter/pyright_.py,sha256=Um_HiYDehffci2l9DYXvOfxHNEVuKQsQ9MOsO5mXal4,5126
11
- pytest_revealtype_injector-0.2.3.dist-info/METADATA,sha256=zrqkK8CDEbkQi2yI1rCnRAf41QAsPkgNIx-dV9UzBvU,5520
12
- pytest_revealtype_injector-0.2.3.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
13
- pytest_revealtype_injector-0.2.3.dist-info/entry_points.txt,sha256=UfOm7y3WQnOoGV1mgTMb42MI6iBRPIl88FJiAOnt6SY,74
14
- pytest_revealtype_injector-0.2.3.dist-info/licenses/COPYING,sha256=LSYUX8PcSMvHCkhM5oi07eOrSLV89qdEJ-FVZmbcpNE,355
15
- pytest_revealtype_injector-0.2.3.dist-info/licenses/COPYING.mit,sha256=IzYEFDIOECyuupg_B3O9FvgjnU9i4JtambpbleoYHdQ,1060
16
- pytest_revealtype_injector-0.2.3.dist-info/RECORD,,