Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
coveragepy/tests/mixins.py at main · coveragepy/coveragepy · GitHub
Skip to content
Navigation Menu
Sign in
Products
Platform
GitHub
Repository hosting, code review, and collaboration
Copilot
AI coding agent for tasks, projects and automated work
Build & Ship
Actions
CI/CD and automation
Code Quality
Quality analysis, fixes, and enforcement
Codespaces
Cloud development environments
Secure
Code Security
Vulnerability detection and remediation
Secret Protection
Secret scanning and leak prevention
All Features
Developers
Learn
Documentation
Training
Certifications
Build
Build with Copilot
Customize Copilot
Integrations
Explore
Trending repos
GitHub Sponsors
Events
Changelog
Changelog
Your source for the latest features, improvements, and fixes across GitHub products, all in one place.
Businesses
By Stage
Enterprises
Team
Startups
Nonprofits
By Industry
Healthcare
Financial services
Manufacturing
Government
See all industries
Evaluate GitHub
Why GitHub
Customer Stories
Business insights
Trust Center
Add-ons
GitHub Advanced Security
Enterprise-grade code security
Copilot for business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Resources
Learn & Connect
Documentation
Resource center
Blog
Events & webinars
Community Forum
Customer Stories
Integrations
Support
Customer support
Training
GitHub Status
Company
About
Partners
Changelog
GitHub Universe
GitHub Universe
The event for developers, by developers — talks, workshops, and what’s next for GitHub.
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
coveragepy
coveragepy
Repository navigation
Code
Issues
259
(259)
Pull requests
56
(56)
Actions
Security and quality
Insights
More
items
Files
Expand file tree
main
Breadcrumbs
coveragepy
/
tests
/
mixins.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
152 lines (117 loc) · 4.97 KB
main
Breadcrumbs
coveragepy
/
tests
/
mixins.py
Copy path
Top
File metadata and controls
Code
Blame
152 lines (117 loc) · 4.97 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/coveragepy/coveragepy/blob/main/NOTICE.txt
"""
Test class mixins
Some of these are transitional while working toward pure-pytest style.
"""
# pragma: enforce 100% coverage
from
__future__
import
annotations
import
importlib
import
os
import
os
.
path
import
sys
from
collections
.
abc
import
Callable
,
Iterable
from
contextlib
import
chdir
from
typing
import
Any
,
cast
import
pytest
from
coverage
.
misc
import
SysModuleSaver
from
tests
.
helpers
import
make_file
,
remove_tree
class
PytestBase
:
"""A base class to connect to pytest in a test class hierarchy."""
@
pytest
.
fixture
(
autouse
=
True
)
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
self
.
_monkeypatch
=
monkeypatch
self
.
setUp
()
def
setUp
(
self
)
->
None
:
"""Per-test initialization. Override this as you wish."""
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
:
str
,
value
:
str
)
->
None
:
"""Set an environment variable `name` to be `value`."""
self
.
_monkeypatch
.
setenv
(
name
,
value
)
def
del_environ
(
self
,
name
:
str
)
->
None
:
"""Delete an environment variable, unless we set it."""
self
.
_monkeypatch
.
delenv
(
name
,
raising
=
False
)
class
TempDirMixin
:
"""Provides temp dir and data file helpers for tests."""
# Our own setting: most of these tests run in their own temp directory.
# Set this to False in your subclass if you don't want a temp directory
# created.
run_in_temp_dir
=
True
@
pytest
.
fixture
(
autouse
=
True
)
def
_temp_dir
(
self
,
tmp_path_factory
:
pytest
.
TempPathFactory
)
->
Iterable
[
None
]:
"""Create a temp dir for the tests, if they want it."""
if
self
.
run_in_temp_dir
:
tmpdir
=
tmp_path_factory
.
mktemp
(
"t"
)
self
.
temp_dir
=
str
(
tmpdir
)
with
chdir
(
self
.
temp_dir
):
# Modules should be importable from this temp directory. We don't
# use '' because we make lots of different temp directories and
# nose's caching importer can get confused. The full path prevents
# problems.
sys
.
path
.
insert
(
0
,
os
.
getcwd
())
yield
else
:
yield
def
make_file
(
self
,
filename
:
str
,
text
:
str
=
""
,
bytes
:
bytes
=
b""
,
newline
:
str
|
None
=
None
,
)
->
str
:
"""Make a file. See `tests.helpers.make_file`"""
# pylint: disable=redefined-builtin # bytes
assert
self
.
run_in_temp_dir
,
"Only use make_file when running in a temp dir"
return
make_file
(
filename
,
text
,
bytes
,
newline
)
class
RestoreModulesMixin
:
"""Auto-restore the imported modules at the end of each test."""
@
pytest
.
fixture
(
autouse
=
True
)
def
_module_saving
(
self
)
->
Iterable
[
None
]:
"""Remove modules we imported during the test."""
self
.
_sys_module_saver
=
SysModuleSaver
()
try
:
yield
finally
:
self
.
_sys_module_saver
.
restore
()
def
clean_local_file_imports
(
self
)
->
None
:
"""Clean up the results of calls to `import_local_file`.
Use this if you need to `import_local_file` the same file twice in
one test.
"""
# So that we can re-import files, clean them out first.
self
.
_sys_module_saver
.
restore
()
# Also have to clean out the .pyc files, since the time stamp
# resolution is only one second, a changed file might not be
# picked up.
remove_tree
(
"__pycache__"
)
importlib
.
invalidate_caches
()
class
StdStreamCapturingMixin
:
"""
Adapter from the pytest capsys fixture to more convenient methods.
This doesn't also output to the real stdout, so we probably want to move
to "real" capsys when we can use fixtures in test methods.
Once you've used one of these methods, the capturing is reset, so another
invocation will only return the delta.
"""
@
pytest
.
fixture
(
autouse
=
True
)
def
_capcapsys
(
self
,
capsys
:
pytest
.
CaptureFixture
[
str
])
->
None
:
"""Grab the fixture so our methods can use it."""
self
.
capsys
=
capsys
def
stdouterr
(
self
)
->
tuple
[
str
,
str
]:
"""Returns (out, err), two strings for stdout and stderr."""
return
cast
(
tuple
[
str
,
str
],
self
.
capsys
.
readouterr
())
def
stdout
(
self
)
->
str
:
"""Returns a string, the captured stdout."""
return
self
.
capsys
.
readouterr
().
out
def
stderr
(
self
)
->
str
:
"""Returns a string, the captured stderr."""
return
self
.
capsys
.
readouterr
().
err
You can’t perform that action at this time.