Skip to content

Commit 7450b6d

Browse files
authored
Merge pull request #7418 from bluetech/typing-3
More typing work
2 parents 61014c5 + f382a6b commit 7450b6d

File tree

17 files changed

+197
-147
lines changed

17 files changed

+197
-147
lines changed

changelog/7418.breaking.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Remove the `pytest_doctest_prepare_content` hook specification. This hook
2+
hasn't been triggered by pytest for at least 10 years.

src/_pytest/fixtures.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -924,9 +924,7 @@ def _teardown_yield_fixture(fixturefunc, it) -> None:
924924
except StopIteration:
925925
pass
926926
else:
927-
fail_fixturefunc(
928-
fixturefunc, "yield_fixture function has more than one 'yield'"
929-
)
927+
fail_fixturefunc(fixturefunc, "fixture function has more than one 'yield'")
930928

931929

932930
def _eval_scope_callable(

src/_pytest/freeze_support.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,13 @@
22
Provides a function to report all internal modules for using freezing tools
33
pytest
44
"""
5+
import types
6+
from typing import Iterator
7+
from typing import List
8+
from typing import Union
59

610

7-
def freeze_includes():
11+
def freeze_includes() -> List[str]:
812
"""
913
Returns a list of module names used by pytest that should be
1014
included by cx_freeze.
@@ -17,7 +21,9 @@ def freeze_includes():
1721
return result
1822

1923

20-
def _iter_all_modules(package, prefix=""):
24+
def _iter_all_modules(
25+
package: Union[str, types.ModuleType], prefix: str = "",
26+
) -> Iterator[str]:
2127
"""
2228
Iterates over the names of all modules that can be found in the given
2329
package, recursively.
@@ -29,10 +35,13 @@ def _iter_all_modules(package, prefix=""):
2935
import os
3036
import pkgutil
3137

32-
if type(package) is not str:
33-
path, prefix = package.__path__[0], package.__name__ + "."
34-
else:
38+
if isinstance(package, str):
3539
path = package
40+
else:
41+
# Type ignored because typeshed doesn't define ModuleType.__path__
42+
# (only defined on packages).
43+
package_path = package.__path__ # type: ignore[attr-defined]
44+
path, prefix = package_path[0], package.__name__ + "."
3645
for _, name, is_package in pkgutil.iter_modules([path]):
3746
if is_package:
3847
for m in _iter_all_modules(os.path.join(path, name), prefix=name + "."):

src/_pytest/hookspec.py

Lines changed: 51 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
""" hook specifications for pytest plugins, invoked from main.py and builtin plugins. """
22
from typing import Any
3+
from typing import Dict
34
from typing import List
45
from typing import Mapping
56
from typing import Optional
@@ -37,7 +38,6 @@
3738
from _pytest.python import Metafunc
3839
from _pytest.python import Module
3940
from _pytest.python import PyCollector
40-
from _pytest.reports import BaseReport
4141
from _pytest.reports import CollectReport
4242
from _pytest.reports import TestReport
4343
from _pytest.runner import CallInfo
@@ -172,7 +172,7 @@ def pytest_cmdline_preparse(config: "Config", args: List[str]) -> None:
172172

173173

174174
@hookspec(firstresult=True)
175-
def pytest_cmdline_main(config: "Config") -> "Optional[Union[ExitCode, int]]":
175+
def pytest_cmdline_main(config: "Config") -> Optional[Union["ExitCode", int]]:
176176
""" called for performing the main command line action. The default
177177
implementation will invoke the configure hooks and runtest_mainloop.
178178
@@ -206,7 +206,7 @@ def pytest_load_initial_conftests(
206206

207207

208208
@hookspec(firstresult=True)
209-
def pytest_collection(session: "Session") -> Optional[Any]:
209+
def pytest_collection(session: "Session") -> Optional[object]:
210210
"""Perform the collection protocol for the given session.
211211
212212
Stops at first non-None result, see :ref:`firstresult`.
@@ -242,39 +242,41 @@ def pytest_collection_modifyitems(
242242
"""
243243

244244

245-
def pytest_collection_finish(session: "Session"):
246-
""" called after collection has been performed and modified.
245+
def pytest_collection_finish(session: "Session") -> None:
246+
"""Called after collection has been performed and modified.
247247
248248
:param _pytest.main.Session session: the pytest session object
249249
"""
250250

251251

252252
@hookspec(firstresult=True)
253-
def pytest_ignore_collect(path, config: "Config"):
254-
""" return True to prevent considering this path for collection.
253+
def pytest_ignore_collect(path: py.path.local, config: "Config") -> Optional[bool]:
254+
"""Return True to prevent considering this path for collection.
255+
255256
This hook is consulted for all files and directories prior to calling
256257
more specific hooks.
257258
258-
Stops at first non-None result, see :ref:`firstresult`
259+
Stops at first non-None result, see :ref:`firstresult`.
259260
260261
:param path: a :py:class:`py.path.local` - the path to analyze
261262
:param _pytest.config.Config config: pytest config object
262263
"""
263264

264265

265266
@hookspec(firstresult=True, warn_on_impl=COLLECT_DIRECTORY_HOOK)
266-
def pytest_collect_directory(path, parent):
267-
""" called before traversing a directory for collection files.
267+
def pytest_collect_directory(path: py.path.local, parent) -> Optional[object]:
268+
"""Called before traversing a directory for collection files.
268269
269-
Stops at first non-None result, see :ref:`firstresult`
270+
Stops at first non-None result, see :ref:`firstresult`.
270271
271272
:param path: a :py:class:`py.path.local` - the path to analyze
272273
"""
273274

274275

275276
def pytest_collect_file(path: py.path.local, parent) -> "Optional[Collector]":
276-
""" return collection Node or None for the given path. Any new node
277-
needs to have the specified ``parent`` as a parent.
277+
"""Return collection Node or None for the given path.
278+
279+
Any new node needs to have the specified ``parent`` as a parent.
278280
279281
:param path: a :py:class:`py.path.local` - the path to collect
280282
"""
@@ -287,16 +289,16 @@ def pytest_collectstart(collector: "Collector") -> None:
287289
""" collector starts collecting. """
288290

289291

290-
def pytest_itemcollected(item):
291-
""" we just collected a test item. """
292+
def pytest_itemcollected(item: "Item") -> None:
293+
"""We just collected a test item."""
292294

293295

294296
def pytest_collectreport(report: "CollectReport") -> None:
295297
""" collector finished collecting. """
296298

297299

298-
def pytest_deselected(items):
299-
""" called for test items deselected, e.g. by keyword. """
300+
def pytest_deselected(items: Sequence["Item"]) -> None:
301+
"""Called for deselected test items, e.g. by keyword."""
300302

301303

302304
@hookspec(firstresult=True)
@@ -312,25 +314,27 @@ def pytest_make_collect_report(collector: "Collector") -> "Optional[CollectRepor
312314

313315

314316
@hookspec(firstresult=True)
315-
def pytest_pycollect_makemodule(path: py.path.local, parent) -> "Optional[Module]":
316-
""" return a Module collector or None for the given path.
317+
def pytest_pycollect_makemodule(path: py.path.local, parent) -> Optional["Module"]:
318+
"""Return a Module collector or None for the given path.
319+
317320
This hook will be called for each matching test module path.
318321
The pytest_collect_file hook needs to be used if you want to
319322
create test modules for files that do not match as a test module.
320323
321-
Stops at first non-None result, see :ref:`firstresult`
324+
Stops at first non-None result, see :ref:`firstresult`.
322325
323326
:param path: a :py:class:`py.path.local` - the path of module to collect
324327
"""
325328

326329

327330
@hookspec(firstresult=True)
328331
def pytest_pycollect_makeitem(
329-
collector: "PyCollector", name: str, obj
330-
) -> "Union[None, Item, Collector, List[Union[Item, Collector]]]":
331-
""" return custom item/collector for a python object in a module, or None.
332+
collector: "PyCollector", name: str, obj: object
333+
) -> Union[None, "Item", "Collector", List[Union["Item", "Collector"]]]:
334+
"""Return a custom item/collector for a Python object in a module, or None.
332335
333-
Stops at first non-None result, see :ref:`firstresult` """
336+
Stops at first non-None result, see :ref:`firstresult`.
337+
"""
334338

335339

336340
@hookspec(firstresult=True)
@@ -466,7 +470,7 @@ def pytest_runtest_call(item: "Item") -> None:
466470
"""
467471

468472

469-
def pytest_runtest_teardown(item: "Item", nextitem: "Optional[Item]") -> None:
473+
def pytest_runtest_teardown(item: "Item", nextitem: Optional["Item"]) -> None:
470474
"""Called to perform the teardown phase for a test item.
471475
472476
The default implementation runs the finalizers and calls ``teardown()``
@@ -505,15 +509,19 @@ def pytest_runtest_logreport(report: "TestReport") -> None:
505509

506510

507511
@hookspec(firstresult=True)
508-
def pytest_report_to_serializable(config: "Config", report: "BaseReport"):
512+
def pytest_report_to_serializable(
513+
config: "Config", report: Union["CollectReport", "TestReport"],
514+
) -> Optional[Dict[str, Any]]:
509515
"""
510516
Serializes the given report object into a data structure suitable for sending
511517
over the wire, e.g. converted to JSON.
512518
"""
513519

514520

515521
@hookspec(firstresult=True)
516-
def pytest_report_from_serializable(config: "Config", data):
522+
def pytest_report_from_serializable(
523+
config: "Config", data: Dict[str, Any],
524+
) -> Optional[Union["CollectReport", "TestReport"]]:
517525
"""
518526
Restores a report object previously serialized with pytest_report_to_serializable().
519527
"""
@@ -528,11 +536,11 @@ def pytest_report_from_serializable(config: "Config", data):
528536
def pytest_fixture_setup(
529537
fixturedef: "FixtureDef", request: "SubRequest"
530538
) -> Optional[object]:
531-
""" performs fixture setup execution.
539+
"""Performs fixture setup execution.
532540
533-
:return: The return value of the call to the fixture function
541+
:return: The return value of the call to the fixture function.
534542
535-
Stops at first non-None result, see :ref:`firstresult`
543+
Stops at first non-None result, see :ref:`firstresult`.
536544
537545
.. note::
538546
If the fixture function returns None, other implementations of
@@ -555,25 +563,25 @@ def pytest_fixture_post_finalizer(
555563

556564

557565
def pytest_sessionstart(session: "Session") -> None:
558-
""" called after the ``Session`` object has been created and before performing collection
566+
"""Called after the ``Session`` object has been created and before performing collection
559567
and entering the run test loop.
560568
561569
:param _pytest.main.Session session: the pytest session object
562570
"""
563571

564572

565573
def pytest_sessionfinish(
566-
session: "Session", exitstatus: "Union[int, ExitCode]"
574+
session: "Session", exitstatus: Union[int, "ExitCode"],
567575
) -> None:
568-
""" called after whole test run finished, right before returning the exit status to the system.
576+
"""Called after whole test run finished, right before returning the exit status to the system.
569577
570578
:param _pytest.main.Session session: the pytest session object
571579
:param int exitstatus: the status which pytest will return to the system
572580
"""
573581

574582

575583
def pytest_unconfigure(config: "Config") -> None:
576-
""" called before test process is exited.
584+
"""Called before test process is exited.
577585
578586
:param _pytest.config.Config config: pytest config object
579587
"""
@@ -587,7 +595,7 @@ def pytest_unconfigure(config: "Config") -> None:
587595
def pytest_assertrepr_compare(
588596
config: "Config", op: str, left: object, right: object
589597
) -> Optional[List[str]]:
590-
"""return explanation for comparisons in failing assert expressions.
598+
"""Return explanation for comparisons in failing assert expressions.
591599
592600
Return None for no custom explanation, otherwise return a list
593601
of strings. The strings will be joined by newlines but any newlines
@@ -598,7 +606,7 @@ def pytest_assertrepr_compare(
598606
"""
599607

600608

601-
def pytest_assertion_pass(item, lineno: int, orig: str, expl: str) -> None:
609+
def pytest_assertion_pass(item: "Item", lineno: int, orig: str, expl: str) -> None:
602610
"""
603611
**(Experimental)**
604612
@@ -665,12 +673,12 @@ def pytest_report_header(
665673

666674

667675
def pytest_report_collectionfinish(
668-
config: "Config", startdir: py.path.local, items: "Sequence[Item]"
676+
config: "Config", startdir: py.path.local, items: Sequence["Item"],
669677
) -> Union[str, List[str]]:
670678
"""
671679
.. versionadded:: 3.2
672680
673-
return a string or list of strings to be displayed after collection has finished successfully.
681+
Return a string or list of strings to be displayed after collection has finished successfully.
674682
675683
These strings will be displayed after the standard "collected X items" message.
676684
@@ -689,7 +697,7 @@ def pytest_report_collectionfinish(
689697

690698
@hookspec(firstresult=True)
691699
def pytest_report_teststatus(
692-
report: "BaseReport", config: "Config"
700+
report: Union["CollectReport", "TestReport"], config: "Config"
693701
) -> Tuple[
694702
str, str, Union[str, Mapping[str, bool]],
695703
]:
@@ -734,7 +742,7 @@ def pytest_terminal_summary(
734742
def pytest_warning_captured(
735743
warning_message: "warnings.WarningMessage",
736744
when: "Literal['config', 'collect', 'runtest']",
737-
item: "Optional[Item]",
745+
item: Optional["Item"],
738746
location: Optional[Tuple[str, int, str]],
739747
) -> None:
740748
"""(**Deprecated**) Process a warning captured by the internal pytest warnings plugin.
@@ -797,18 +805,6 @@ def pytest_warning_recorded(
797805
"""
798806

799807

800-
# -------------------------------------------------------------------------
801-
# doctest hooks
802-
# -------------------------------------------------------------------------
803-
804-
805-
@hookspec(firstresult=True)
806-
def pytest_doctest_prepare_content(content):
807-
""" return processed content for a given doctest
808-
809-
Stops at first non-None result, see :ref:`firstresult` """
810-
811-
812808
# -------------------------------------------------------------------------
813809
# error handling and internal debugging hooks
814810
# -------------------------------------------------------------------------
@@ -831,7 +827,9 @@ def pytest_keyboard_interrupt(
831827

832828

833829
def pytest_exception_interact(
834-
node: "Node", call: "CallInfo[object]", report: "Union[CollectReport, TestReport]"
830+
node: "Node",
831+
call: "CallInfo[object]",
832+
report: Union["CollectReport", "TestReport"],
835833
) -> None:
836834
"""Called when an exception was raised which can potentially be
837835
interactively handled.

src/_pytest/main.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -302,8 +302,8 @@ def _main(config: Config, session: "Session") -> Optional[Union[int, ExitCode]]:
302302
return None
303303

304304

305-
def pytest_collection(session: "Session") -> Sequence[nodes.Item]:
306-
return session.perform_collect()
305+
def pytest_collection(session: "Session") -> None:
306+
session.perform_collect()
307307

308308

309309
def pytest_runtestloop(session: "Session") -> bool:
@@ -343,9 +343,7 @@ def _in_venv(path: py.path.local) -> bool:
343343
return any([fname.basename in activates for fname in bindir.listdir()])
344344

345345

346-
def pytest_ignore_collect(
347-
path: py.path.local, config: Config
348-
) -> "Optional[Literal[True]]":
346+
def pytest_ignore_collect(path: py.path.local, config: Config) -> Optional[bool]:
349347
ignore_paths = config._getconftest_pathlist("collect_ignore", path=path.dirpath())
350348
ignore_paths = ignore_paths or []
351349
excludeopt = config.getoption("ignore")

src/_pytest/python.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,7 @@ def sort_key(item):
422422
return values
423423

424424
def _makeitem(
425-
self, name: str, obj
425+
self, name: str, obj: object
426426
) -> Union[
427427
None, nodes.Item, nodes.Collector, List[Union[nodes.Item, nodes.Collector]]
428428
]:

0 commit comments

Comments
 (0)