summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
authorNed Batchelder <ned@nedbatchelder.com>2023-01-04 07:48:57 -0500
committerNed Batchelder <ned@nedbatchelder.com>2023-01-04 07:48:57 -0500
commitcaa7e4b47a2c64bd55a4e0611ca22a772ddaabd0 (patch)
tree65cc71293a30427018ae9fe9a73692f179353636 /tests
parentdbb94d570a2042409400c28ba3069dcb32a45159 (diff)
downloadpython-coveragepy-git-caa7e4b47a2c64bd55a4e0611ca22a772ddaabd0.tar.gz
mypy: test helpers: conftest.py mixins.py osinfo.py
Diffstat (limited to 'tests')
-rw-r--r--tests/conftest.py18
-rw-r--r--tests/mixins.py21
-rw-r--r--tests/osinfo.py22
3 files changed, 33 insertions, 28 deletions
diff --git a/tests/conftest.py b/tests/conftest.py
index d45cae1d..d87c1289 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -11,7 +11,9 @@ import os
import sys
import sysconfig
import warnings
+
from pathlib import Path
+from typing import Generator, Optional
import pytest
@@ -30,7 +32,7 @@ pytest_plugins = "tests.balance_xdist_plugin"
@pytest.fixture(autouse=True)
-def set_warnings():
+def set_warnings() -> None:
"""Configure warnings to show while running tests."""
warnings.simplefilter("default")
warnings.simplefilter("once", DeprecationWarning)
@@ -61,7 +63,7 @@ def set_warnings():
@pytest.fixture(autouse=True)
-def reset_sys_path():
+def reset_sys_path() -> Generator[None, None, None]:
"""Clean up sys.path changes around every test."""
sys_path = list(sys.path)
yield
@@ -69,7 +71,7 @@ def reset_sys_path():
@pytest.fixture(autouse=True)
-def reset_environment():
+def reset_environment() -> Generator[None, None, None]:
"""Make sure a test setting an envvar doesn't leak into another test."""
old_environ = os.environ.copy()
yield
@@ -78,14 +80,14 @@ def reset_environment():
@pytest.fixture(autouse=True)
-def reset_filesdotpy_globals():
+def reset_filesdotpy_globals() -> Generator[None, None, None]:
"""coverage/files.py has some unfortunate globals. Reset them every test."""
set_relative_directory()
yield
WORKER = os.environ.get("PYTEST_XDIST_WORKER", "none")
-def pytest_sessionstart():
+def pytest_sessionstart() -> None:
"""Run once at the start of the test session."""
# Only in the main process...
if WORKER == "none":
@@ -96,7 +98,7 @@ def pytest_sessionstart():
# subcover.pth is deleted by pytest_sessionfinish below.
-def pytest_sessionfinish():
+def pytest_sessionfinish() -> None:
"""Hook the end of a test session, to clean up."""
# This is called by each of the workers and by the main process.
if WORKER == "none":
@@ -106,7 +108,7 @@ def pytest_sessionfinish():
pth_file.unlink()
-def possible_pth_dirs():
+def possible_pth_dirs() -> Generator[Path, None, None]:
"""Produce a sequence of directories for trying to write .pth files."""
# First look through sys.path, and if we find a .pth file, then it's a good
# place to put ours.
@@ -120,7 +122,7 @@ def possible_pth_dirs():
yield Path(sysconfig.get_path("purelib")) # pragma: cant happen
-def find_writable_pth_directory():
+def find_writable_pth_directory() -> Optional[Path]:
"""Find a place to write a .pth file."""
for pth_dir in possible_pth_dirs(): # pragma: part covered
try_it = pth_dir / f"touch_{WORKER}.it"
diff --git a/tests/mixins.py b/tests/mixins.py
index f8cc5085..97fd2a91 100644
--- a/tests/mixins.py
+++ b/tests/mixins.py
@@ -12,8 +12,7 @@ import os
import os.path
import sys
-from typing import Iterator, Tuple
-from typing import Iterable, Optional
+from typing import Any, Callable, Iterable, Iterator, Optional, Tuple
import pytest
@@ -25,7 +24,11 @@ class PytestBase:
"""A base class to connect to pytest in a test class hierarchy."""
@pytest.fixture(autouse=True)
- def connect_to_pytest(self, request, monkeypatch) -> None:
+ def connect_to_pytest(
+ self,
+ request: pytest.FixtureRequest,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
"""Captures pytest facilities for use by other test helpers."""
# pylint: disable=attribute-defined-outside-init
self._pytest_request = request
@@ -36,15 +39,15 @@ class PytestBase:
"""Per-test initialization. Override this as you wish."""
pass
- def addCleanup(self, fn, *args) -> None:
+ def addCleanup(self, fn: Callable[..., None], *args: Any) -> None:
"""Like unittest's addCleanup: code to call when the test is done."""
self._pytest_request.addfinalizer(lambda: fn(*args))
- def set_environ(self, name, value) -> None:
+ def set_environ(self, name: str, value: str) -> None:
"""Set an environment variable `name` to be `value`."""
self._monkeypatch.setenv(name, value)
- def del_environ(self, name) -> None:
+ def del_environ(self, name: str) -> None:
"""Delete an environment variable, unless we set it."""
self._monkeypatch.delenv(name, raising=False)
@@ -133,12 +136,12 @@ class StdStreamCapturingMixin:
def stdouterr(self) -> Tuple[str, str]:
"""Returns (out, err), two strings for stdout and stderr."""
- return self.capsys.readouterr()
+ return self.capsys.readouterr() # type: ignore[no-any-return]
def stdout(self) -> str:
"""Returns a string, the captured stdout."""
- return self.capsys.readouterr().out
+ return self.capsys.readouterr().out # type: ignore[no-any-return]
def stderr(self) -> str:
"""Returns a string, the captured stderr."""
- return self.capsys.readouterr().err
+ return self.capsys.readouterr().err # type: ignore[no-any-return]
diff --git a/tests/osinfo.py b/tests/osinfo.py
index ec34c709..57d11273 100644
--- a/tests/osinfo.py
+++ b/tests/osinfo.py
@@ -3,12 +3,12 @@
"""OS information for testing."""
-from coverage import env
+import sys
-if env.WINDOWS:
+if sys.platform == "win32":
# Windows implementation
- def process_ram():
+ def process_ram() -> int:
"""How much RAM is this process using? (Windows)"""
import ctypes
# From: http://lists.ubuntu.com/archives/bazaar-commits/2009-February/011990.html
@@ -38,35 +38,35 @@ if env.WINDOWS:
return 0 # pragma: cant happen
return mem_struct.PrivateUsage
-elif env.LINUX:
+elif sys.platform.startswith("linux"):
# Linux implementation
import os
_scale = {'kb': 1024, 'mb': 1024*1024}
- def _VmB(key):
+ def _VmB(key: str) -> int:
"""Read the /proc/PID/status file to find memory use."""
try:
# Get pseudo file /proc/<pid>/status
- with open('/proc/%d/status' % os.getpid()) as t:
+ with open(f"/proc/{os.getpid()}/status") as t:
v = t.read()
except OSError: # pragma: cant happen
return 0 # non-Linux?
# Get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
i = v.index(key)
- v = v[i:].split(None, 3)
- if len(v) < 3: # pragma: part covered
+ vp = v[i:].split(None, 3)
+ if len(vp) < 3: # pragma: part covered
return 0 # pragma: cant happen
# Convert Vm value to bytes.
- return int(float(v[1]) * _scale[v[2].lower()])
+ return int(float(vp[1]) * _scale[vp[2].lower()])
- def process_ram():
+ def process_ram() -> int:
"""How much RAM is this process using? (Linux implementation)"""
return _VmB('VmRSS')
else:
# Generic implementation.
- def process_ram():
+ def process_ram() -> int:
"""How much RAM is this process using? (stdlib implementation)"""
import resource
return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss