Skip to content

Commit f2b02bf

Browse files
author
DrGeoff
committed
Increased test isolation. Better resource cleanup by using context managers
1 parent 8637c42 commit f2b02bf

File tree

7 files changed

+245
-218
lines changed

7 files changed

+245
-218
lines changed

src/compiletools/test_base.py

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,17 @@ class BaseCompileToolsTestCase:
1717
"""Base test case with common setup/teardown for compiletools tests"""
1818

1919
def setup_method(self):
20-
uth.reset()
2120
self._tmpdir = tempfile.mkdtemp()
2221
self._origdir = os.getcwd()
22+
uth.delete_existing_parsers()
23+
compiletools.apptools.resetcallbacks()
2324

2425
def teardown_method(self):
2526
os.chdir(self._origdir)
2627
if hasattr(self, '_tmpdir') and self._tmpdir:
2728
shutil.rmtree(self._tmpdir, ignore_errors=True)
28-
uth.reset()
29+
uth.delete_existing_parsers()
30+
compiletools.apptools.resetcallbacks()
2931

3032
def _verify_one_exe_per_main(self, relativepaths):
3133
"""Common executable verification logic"""
@@ -93,37 +95,27 @@ def create_header_deps_parser(extraargs=None, cache_home="None", tempdir=None):
9395

9496
def compare_direct_cpp_magic(test_case, relativepath, tempdir=None):
9597
"""Utility to test that DirectMagicFlags and CppMagicFlags produce identical results"""
96-
if tempdir is None:
97-
tempdir = tempfile.mkdtemp()
98-
cleanup_tempdir = True
99-
else:
100-
cleanup_tempdir = False
101-
102-
origdir = os.getcwd()
103-
os.chdir(tempdir)
104-
105-
try:
98+
with uth.TempDirContext() as temp_ctx:
99+
if tempdir is not None:
100+
# If specific tempdir provided, copy current working dir content there
101+
os.chdir(tempdir)
102+
106103
samplesdir = uth.samplesdir()
107104
realpath = os.path.join(samplesdir, relativepath)
108105

109-
# Test direct parser
110-
magicparser_direct = create_magic_parser(["--magic", "direct"], tempdir=tempdir)
111-
result_direct = magicparser_direct.parse(realpath)
112-
113-
# Clear configargparse singleton state to allow second parser creation
114-
configargparse._parsers.clear()
106+
# Test direct parser with isolated context
107+
with uth.ParserContext():
108+
magicparser_direct = create_magic_parser(["--magic", "direct"], tempdir=os.getcwd())
109+
result_direct = magicparser_direct.parse(realpath)
115110

116-
# Test cpp parser
117-
magicparser_cpp = create_magic_parser(["--magic", "cpp"], tempdir=tempdir)
118-
result_cpp = magicparser_cpp.parse(realpath)
111+
# Test cpp parser with fresh isolated context
112+
with uth.ParserContext():
113+
magicparser_cpp = create_magic_parser(["--magic", "cpp"], tempdir=os.getcwd())
114+
result_cpp = magicparser_cpp.parse(realpath)
119115

120116
# Results should be identical
121117
assert result_direct == result_cpp, \
122118
f"DirectMagicFlags and CppMagicFlags gave different results for {relativepath}"
123-
finally:
124-
os.chdir(origdir)
125-
if cleanup_tempdir:
126-
shutil.rmtree(tempdir, ignore_errors=True)
127119

128120

129121
def compare_direct_cpp_headers(test_case, filename, extraargs=None):

src/compiletools/test_cake.py

Lines changed: 24 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,6 @@ def _call_ct_cake(self, extraargv=[], cache_home="None"):
3737
uth.reset()
3838
compiletools.cake.main(self._create_argv(cache_home) + extraargv)
3939

40-
def _setup_and_chdir_temp_dir(self):
41-
""" Returns the original working directory so you can chdir back to that at the end """
42-
#TODO Migrate all usage of this to uth.TempDirContext()
43-
origdir = os.getcwd()
44-
self._tmpdir = tempfile.mkdtemp()
45-
os.chdir(self._tmpdir)
46-
47-
return origdir
4840

4941
def test_no_git_root(self):
5042
with uth.TempDirContext():
@@ -154,16 +146,12 @@ def _create_recompile_test_files(self, deeper_is_included=False):
154146
This will allow us to test that editing any of those files
155147
triggers a recompile.
156148
"""
157-
origdir = self._setup_and_chdir_temp_dir()
158-
159149
self._create_main_cpp()
160150
self._create_extra_hpp()
161151
self._create_extra_cpp()
162152
self._create_deeper_hpp()
163153
self._create_deeper_cpp()
164154

165-
os.chdir(origdir)
166-
167155
def _grab_timestamps(self, deeper_is_included=False):
168156
""" There are 8 files we want timestamps for.
169157
main.cpp, extra.hpp, extra.cpp, deeper.hpp, deeper.cpp, deeper.o, main.o, extra.o
@@ -225,42 +213,37 @@ def _compile_edit_compile(
225213
self, files_to_edit, expected_changes, deeper_is_included=False
226214
):
227215
""" Test that the compile, edit, compile cycle works as you expect """
228-
# print(self._tmpdir)
229-
origdir = os.getcwd()
230-
self._create_recompile_test_files(deeper_is_included)
231-
os.chdir(self._tmpdir)
232-
233-
# Do an initial build
234-
self._config_name = uth.create_temp_config(self._tmpdir)
235-
uth.create_temp_ct_conf(
236-
tempdir=self._tmpdir,
237-
defaultvariant=os.path.basename(self._config_name)[:-5],
238-
)
239-
self._call_ct_cake(extraargv=[])
216+
with uth.TempDirContext() as ctx:
217+
self._tmpdir = os.getcwd()
218+
self._create_recompile_test_files(deeper_is_included)
240219

241-
# Grab the timestamps on the build products so that later we can test that only the expected ones changed
242-
# deeper_is_included must be false at this point becuase the option to inject it comes later/ver
243-
prets = self._grab_timestamps(deeper_is_included=False)
220+
# Do an initial build
221+
self._config_name = uth.create_temp_config(self._tmpdir)
222+
uth.create_temp_ct_conf(
223+
tempdir=self._tmpdir,
224+
defaultvariant=os.path.basename(self._config_name)[:-5],
225+
)
226+
self._call_ct_cake(extraargv=[])
244227

245-
# Edit the files for this test
246-
if deeper_is_included:
247-
self._inject_deeper_hpp_into_extra_hpp()
228+
# Grab the timestamps on the build products so that later we can test that only the expected ones changed
229+
# deeper_is_included must be false at this point becuase the option to inject it comes later/ver
230+
prets = self._grab_timestamps(deeper_is_included=False)
248231

249-
for fname in files_to_edit:
250-
_touch(fname)
232+
# Edit the files for this test
233+
if deeper_is_included:
234+
self._inject_deeper_hpp_into_extra_hpp()
251235

252-
# Rebuild
253-
self._call_ct_cake(extraargv=[])
236+
for fname in files_to_edit:
237+
_touch(fname)
254238

255-
# Grab the timestamps on the build products for comparison
256-
postts = self._grab_timestamps(deeper_is_included)
239+
# Rebuild
240+
self._call_ct_cake(extraargv=[])
257241

258-
# Check that only the expected timestamps have changed
259-
self._verify_timestamps(expected_changes, prets, postts)
242+
# Grab the timestamps on the build products for comparison
243+
postts = self._grab_timestamps(deeper_is_included)
260244

261-
# Cleanup
262-
os.chdir(origdir)
263-
shutil.rmtree(self._tmpdir, ignore_errors=True)
245+
# Check that only the expected timestamps have changed
246+
self._verify_timestamps(expected_changes, prets, postts)
264247

265248
def test_source_edit_recompiles(self):
266249
""" Make sure that when the source file is altered that a rebuild occurs """

src/compiletools/test_configutils.py

Lines changed: 61 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
class TestVariant:
1313
def setup_method(self):
1414
uth.reset()
15-
self._tmpdir = None
1615

1716
def test_extract_value_from_argv(self):
1817
argv = ['/usr/bin/ct-config', '--pkg-config=fig', '-v']
@@ -44,95 +43,74 @@ def test_extract_variant(self):
4443

4544
def test_extract_variant_from_ct_conf(self):
4645
# Should find the one in the temp directory ct.conf
47-
origdir = self._setup_and_chdir_temp_dir()
48-
local_ct_conf = compiletools.unittesthelper.create_temp_ct_conf(self._tmpdir)
49-
variant = compiletools.configutils.extract_item_from_ct_conf(
50-
key="variant",
51-
user_config_dir="/var",
52-
system_config_dir="/var",
53-
exedir=uth.cakedir(),
54-
gitroot=self._tmpdir,
55-
)
56-
assert "debug" == variant
57-
58-
# Cleanup
59-
os.chdir(origdir)
60-
shutil.rmtree(self._tmpdir, ignore_errors=True)
46+
with uth.TempDirContext() as ctx:
47+
local_ct_conf = compiletools.unittesthelper.create_temp_ct_conf(os.getcwd())
48+
variant = compiletools.configutils.extract_item_from_ct_conf(
49+
key="variant",
50+
user_config_dir="/var",
51+
system_config_dir="/var",
52+
exedir=uth.cakedir(),
53+
gitroot=os.getcwd(),
54+
)
55+
assert "debug" == variant
6156

6257
def test_extract_variant_from_blank_argv(self):
6358
# Force to find the temp directory ct.conf
64-
origdir = self._setup_and_chdir_temp_dir()
65-
local_ct_conf = compiletools.unittesthelper.create_temp_ct_conf(self._tmpdir)
66-
variant = compiletools.configutils.extract_variant(
67-
user_config_dir="/var",
68-
system_config_dir="/var",
69-
exedir=uth.cakedir(),
70-
verbose=0,
71-
gitroot=self._tmpdir,
72-
)
73-
assert "debug" == variant
74-
75-
# Cleanup
76-
os.chdir(origdir)
77-
shutil.rmtree(self._tmpdir, ignore_errors=True)
78-
79-
def _setup_and_chdir_temp_dir(self):
80-
""" Returns the original working directory so you can chdir back to that at the end """
81-
origdir = os.getcwd()
82-
self._tmpdir = tempfile.mkdtemp()
83-
os.chdir(self._tmpdir)
84-
return origdir
59+
with uth.TempDirContext() as ctx:
60+
local_ct_conf = compiletools.unittesthelper.create_temp_ct_conf(os.getcwd())
61+
variant = compiletools.configutils.extract_variant(
62+
argv=[],
63+
user_config_dir="/var",
64+
system_config_dir="/var",
65+
exedir=uth.cakedir(),
66+
verbose=0,
67+
gitroot=os.getcwd(),
68+
)
69+
assert "debug" == variant
70+
8571

8672
def test_default_configs(self):
87-
origdir = self._setup_and_chdir_temp_dir()
88-
local_ct_conf = compiletools.unittesthelper.create_temp_ct_conf(self._tmpdir)
89-
local_config_name = compiletools.unittesthelper.create_temp_config(self._tmpdir)
90-
91-
configs = compiletools.configutils.defaultconfigs(
92-
user_config_dir="/var",
93-
system_config_dir="/var",
94-
exedir=uth.cakedir(),
95-
verbose=0,
96-
gitroot=self._tmpdir,
97-
)
98-
99-
assert [
100-
os.path.join(self._tmpdir, "ct.conf"),
101-
] == \
102-
configs
103-
104-
# Cleanup
105-
os.chdir(origdir)
106-
shutil.rmtree(self._tmpdir, ignore_errors=True)
73+
with uth.TempDirContext() as ctx:
74+
local_ct_conf = compiletools.unittesthelper.create_temp_ct_conf(os.getcwd())
75+
local_config_name = compiletools.unittesthelper.create_temp_config(os.getcwd())
76+
77+
configs = compiletools.configutils.defaultconfigs(
78+
user_config_dir="/var",
79+
system_config_dir="/var",
80+
exedir=uth.cakedir(),
81+
verbose=0,
82+
gitroot=os.getcwd(),
83+
)
84+
85+
assert [
86+
os.path.join(os.getcwd(), "ct.conf"),
87+
] == \
88+
configs
10789

10890
def test_config_files_from_variant(self):
109-
origdir = self._setup_and_chdir_temp_dir()
110-
local_ct_conf = compiletools.unittesthelper.create_temp_ct_conf(self._tmpdir)
111-
# Deliberately call the next config gcc.debug.conf to verify that
112-
# the hierarchy of directories is working
113-
local_config_name = compiletools.unittesthelper.create_temp_config(
114-
self._tmpdir, "gcc.debug.conf"
115-
)
116-
117-
configs = compiletools.configutils.config_files_from_variant(
118-
variant="gcc.debug",
119-
argv=[],
120-
user_config_dir="/var",
121-
system_config_dir="/var",
122-
exedir=uth.cakedir(),
123-
verbose=0,
124-
gitroot=self._tmpdir,
125-
)
126-
127-
assert [
128-
os.path.join(self._tmpdir, "ct.conf"),
129-
os.path.join(self._tmpdir, "gcc.debug.conf"),
130-
] == \
131-
configs
132-
133-
# Cleanup
134-
os.chdir(origdir)
135-
shutil.rmtree(self._tmpdir, ignore_errors=True)
91+
with uth.TempDirContext() as ctx:
92+
local_ct_conf = compiletools.unittesthelper.create_temp_ct_conf(os.getcwd())
93+
# Deliberately call the next config gcc.debug.conf to verify that
94+
# the hierarchy of directories is working
95+
local_config_name = compiletools.unittesthelper.create_temp_config(
96+
os.getcwd(), "gcc.debug.conf"
97+
)
98+
99+
configs = compiletools.configutils.config_files_from_variant(
100+
variant="gcc.debug",
101+
argv=[],
102+
user_config_dir="/var",
103+
system_config_dir="/var",
104+
exedir=uth.cakedir(),
105+
verbose=0,
106+
gitroot=os.getcwd(),
107+
)
108+
109+
assert [
110+
os.path.join(os.getcwd(), "ct.conf"),
111+
os.path.join(os.getcwd(), "gcc.debug.conf"),
112+
] == \
113+
configs
136114

137115
def teardown_method(self):
138116
uth.reset()

src/compiletools/test_cppdeps.py

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -16,38 +16,38 @@
1616
import compiletools.unittesthelper as uth
1717

1818

19-
def _reload_ct(cache_home):
19+
def _reload_ct_with_cache(cache_home):
2020
""" Set the CTCACHE environment variable to cache_home
2121
and reload the compiletools.* modules
2222
"""
23-
os.environ["CTCACHE"] = cache_home
24-
reload(compiletools.headerdeps)
25-
reload(compiletools.cppdeps)
23+
with uth.EnvironmentContext({"CTCACHE": cache_home}):
24+
reload(compiletools.headerdeps)
25+
reload(compiletools.cppdeps)
26+
return cache_home
2627

2728

2829
def test_cppdeps():
2930
uth.reset()
3031

31-
tempdir = tempfile.mkdtemp()
32-
try:
33-
_reload_ct(tempdir)
34-
uth.reset()
35-
36-
output_buffer = io.StringIO()
37-
with redirect_stdout(output_buffer):
38-
compiletools.cppdeps.main(
39-
[os.path.join(uth.samplesdir(), "numbers/test_direct_include.cpp")]
40-
)
41-
42-
output = output_buffer.getvalue().strip().split()
43-
expected_output = [
44-
os.path.join(uth.samplesdir(), "numbers/get_double.hpp"),
45-
os.path.join(uth.samplesdir(), "numbers/get_int.hpp"),
46-
os.path.join(uth.samplesdir(), "numbers/get_numbers.hpp"),
47-
]
48-
assert sorted(expected_output) == sorted(output)
49-
finally:
50-
shutil.rmtree(tempdir)
32+
with uth.TempDirContext() as ctx:
33+
with uth.EnvironmentContext({"CTCACHE": os.getcwd()}):
34+
reload(compiletools.headerdeps)
35+
reload(compiletools.cppdeps)
36+
uth.reset()
37+
38+
output_buffer = io.StringIO()
39+
with redirect_stdout(output_buffer):
40+
compiletools.cppdeps.main(
41+
[os.path.join(uth.samplesdir(), "numbers/test_direct_include.cpp")]
42+
)
43+
44+
output = output_buffer.getvalue().strip().split()
45+
expected_output = [
46+
os.path.join(uth.samplesdir(), "numbers/get_double.hpp"),
47+
os.path.join(uth.samplesdir(), "numbers/get_int.hpp"),
48+
os.path.join(uth.samplesdir(), "numbers/get_numbers.hpp"),
49+
]
50+
assert sorted(expected_output) == sorted(output)
5151
uth.reset()
5252

5353

0 commit comments

Comments
 (0)