Skip to content

Commit caa7e4b

Browse files
committed
mypy: test helpers: conftest.py mixins.py osinfo.py
1 parent dbb94d5 commit caa7e4b

File tree

4 files changed

+34
-29
lines changed

4 files changed

+34
-29
lines changed

tests/conftest.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111
import sys
1212
import sysconfig
1313
import warnings
14+
1415
from pathlib import Path
16+
from typing import Generator, Optional
1517

1618
import pytest
1719

@@ -30,7 +32,7 @@
3032

3133

3234
@pytest.fixture(autouse=True)
33-
def set_warnings():
35+
def set_warnings() -> None:
3436
"""Configure warnings to show while running tests."""
3537
warnings.simplefilter("default")
3638
warnings.simplefilter("once", DeprecationWarning)
@@ -61,15 +63,15 @@ def set_warnings():
6163

6264

6365
@pytest.fixture(autouse=True)
64-
def reset_sys_path():
66+
def reset_sys_path() -> Generator[None, None, None]:
6567
"""Clean up sys.path changes around every test."""
6668
sys_path = list(sys.path)
6769
yield
6870
sys.path[:] = sys_path
6971

7072

7173
@pytest.fixture(autouse=True)
72-
def reset_environment():
74+
def reset_environment() -> Generator[None, None, None]:
7375
"""Make sure a test setting an envvar doesn't leak into another test."""
7476
old_environ = os.environ.copy()
7577
yield
@@ -78,14 +80,14 @@ def reset_environment():
7880

7981

8082
@pytest.fixture(autouse=True)
81-
def reset_filesdotpy_globals():
83+
def reset_filesdotpy_globals() -> Generator[None, None, None]:
8284
"""coverage/files.py has some unfortunate globals. Reset them every test."""
8385
set_relative_directory()
8486
yield
8587

8688
WORKER = os.environ.get("PYTEST_XDIST_WORKER", "none")
8789

88-
def pytest_sessionstart():
90+
def pytest_sessionstart() -> None:
8991
"""Run once at the start of the test session."""
9092
# Only in the main process...
9193
if WORKER == "none":
@@ -96,7 +98,7 @@ def pytest_sessionstart():
9698
# subcover.pth is deleted by pytest_sessionfinish below.
9799

98100

99-
def pytest_sessionfinish():
101+
def pytest_sessionfinish() -> None:
100102
"""Hook the end of a test session, to clean up."""
101103
# This is called by each of the workers and by the main process.
102104
if WORKER == "none":
@@ -106,7 +108,7 @@ def pytest_sessionfinish():
106108
pth_file.unlink()
107109

108110

109-
def possible_pth_dirs():
111+
def possible_pth_dirs() -> Generator[Path, None, None]:
110112
"""Produce a sequence of directories for trying to write .pth files."""
111113
# First look through sys.path, and if we find a .pth file, then it's a good
112114
# place to put ours.
@@ -120,7 +122,7 @@ def possible_pth_dirs():
120122
yield Path(sysconfig.get_path("purelib")) # pragma: cant happen
121123

122124

123-
def find_writable_pth_directory():
125+
def find_writable_pth_directory() -> Optional[Path]:
124126
"""Find a place to write a .pth file."""
125127
for pth_dir in possible_pth_dirs(): # pragma: part covered
126128
try_it = pth_dir / f"touch_{WORKER}.it"

tests/mixins.py

+12-9
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
import os.path
1313
import sys
1414

15-
from typing import Iterator, Tuple
16-
from typing import Iterable, Optional
15+
from typing import Any, Callable, Iterable, Iterator, Optional, Tuple
1716

1817
import pytest
1918

@@ -25,7 +24,11 @@ class PytestBase:
2524
"""A base class to connect to pytest in a test class hierarchy."""
2625

2726
@pytest.fixture(autouse=True)
28-
def connect_to_pytest(self, request, monkeypatch) -> None:
27+
def connect_to_pytest(
28+
self,
29+
request: pytest.FixtureRequest,
30+
monkeypatch: pytest.MonkeyPatch,
31+
) -> None:
2932
"""Captures pytest facilities for use by other test helpers."""
3033
# pylint: disable=attribute-defined-outside-init
3134
self._pytest_request = request
@@ -36,15 +39,15 @@ def setUp(self) -> None:
3639
"""Per-test initialization. Override this as you wish."""
3740
pass
3841

39-
def addCleanup(self, fn, *args) -> None:
42+
def addCleanup(self, fn: Callable[..., None], *args: Any) -> None:
4043
"""Like unittest's addCleanup: code to call when the test is done."""
4144
self._pytest_request.addfinalizer(lambda: fn(*args))
4245

43-
def set_environ(self, name, value) -> None:
46+
def set_environ(self, name: str, value: str) -> None:
4447
"""Set an environment variable `name` to be `value`."""
4548
self._monkeypatch.setenv(name, value)
4649

47-
def del_environ(self, name) -> None:
50+
def del_environ(self, name: str) -> None:
4851
"""Delete an environment variable, unless we set it."""
4952
self._monkeypatch.delenv(name, raising=False)
5053

@@ -133,12 +136,12 @@ def _capcapsys(self, capsys: pytest.CaptureFixture[str]) -> None:
133136

134137
def stdouterr(self) -> Tuple[str, str]:
135138
"""Returns (out, err), two strings for stdout and stderr."""
136-
return self.capsys.readouterr()
139+
return self.capsys.readouterr() # type: ignore[no-any-return]
137140

138141
def stdout(self) -> str:
139142
"""Returns a string, the captured stdout."""
140-
return self.capsys.readouterr().out
143+
return self.capsys.readouterr().out # type: ignore[no-any-return]
141144

142145
def stderr(self) -> str:
143146
"""Returns a string, the captured stderr."""
144-
return self.capsys.readouterr().err
147+
return self.capsys.readouterr().err # type: ignore[no-any-return]

tests/osinfo.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,12 @@
33

44
"""OS information for testing."""
55

6-
from coverage import env
6+
import sys
77

88

9-
if env.WINDOWS:
9+
if sys.platform == "win32":
1010
# Windows implementation
11-
def process_ram():
11+
def process_ram() -> int:
1212
"""How much RAM is this process using? (Windows)"""
1313
import ctypes
1414
# From: http://lists.ubuntu.com/archives/bazaar-commits/2009-February/011990.html
@@ -38,35 +38,35 @@ class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
3838
return 0 # pragma: cant happen
3939
return mem_struct.PrivateUsage
4040

41-
elif env.LINUX:
41+
elif sys.platform.startswith("linux"):
4242
# Linux implementation
4343
import os
4444

4545
_scale = {'kb': 1024, 'mb': 1024*1024}
4646

47-
def _VmB(key):
47+
def _VmB(key: str) -> int:
4848
"""Read the /proc/PID/status file to find memory use."""
4949
try:
5050
# Get pseudo file /proc/<pid>/status
51-
with open('/proc/%d/status' % os.getpid()) as t:
51+
with open(f"/proc/{os.getpid()}/status") as t:
5252
v = t.read()
5353
except OSError: # pragma: cant happen
5454
return 0 # non-Linux?
5555
# Get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
5656
i = v.index(key)
57-
v = v[i:].split(None, 3)
58-
if len(v) < 3: # pragma: part covered
57+
vp = v[i:].split(None, 3)
58+
if len(vp) < 3: # pragma: part covered
5959
return 0 # pragma: cant happen
6060
# Convert Vm value to bytes.
61-
return int(float(v[1]) * _scale[v[2].lower()])
61+
return int(float(vp[1]) * _scale[vp[2].lower()])
6262

63-
def process_ram():
63+
def process_ram() -> int:
6464
"""How much RAM is this process using? (Linux implementation)"""
6565
return _VmB('VmRSS')
6666

6767
else:
6868
# Generic implementation.
69-
def process_ram():
69+
def process_ram() -> int:
7070
"""How much RAM is this process using? (stdlib implementation)"""
7171
import resource
7272
return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

tox.ini

+1-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ setenv =
101101
C4=coverage/files.py coverage/inorout.py coverage/jsonreport.py coverage/lcovreport.py coverage/misc.py coverage/multiproc.py coverage/numbits.py
102102
C5=coverage/parser.py coverage/phystokens.py coverage/plugin.py coverage/plugin_support.py coverage/python.py
103103
C6=coverage/report.py coverage/results.py coverage/sqldata.py coverage/summary.py coverage/tomlconfig.py coverage/types.py coverage/version.py coverage/xmlreport.py
104-
T1=tests/coveragetest.py tests/goldtest.py tests/helpers.py
104+
T1=tests/conftest.py tests/coveragetest.py tests/goldtest.py tests/helpers.py tests/mixins.py tests/osinfo.py
105105
T2=tests/test_annotate.py tests/test_api.py tests/test_arcs.py tests/test_cmdline.py tests/test_collector.py tests/test_concurrency.py
106106
T3=tests/test_config.py tests/test_context.py tests/test_html.py tests/test_misc.py tests/test_python.py tests/test_summary.py tests/test_xml.py
107107
TYPEABLE={env:C1} {env:C2} {env:C3} {env:C4} {env:C5} {env:C6} {env:T1} {env:T2} {env:T3}

0 commit comments

Comments
 (0)