-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcommand_comparer_tests.py
More file actions
328 lines (244 loc) · 12.1 KB
/
command_comparer_tests.py
File metadata and controls
328 lines (244 loc) · 12.1 KB
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
from subprocess import CalledProcessError
import pytest
import sys
from assertpy import assert_that # type: ignore
from command_comparer import *
from contextlib import contextmanager
from datetime import timedelta
from pyfakefs.fake_filesystem_unittest import TestCase # type: ignore
from pyfakefs.fake_filesystem_unittest import Pause
from typing import Dict, Tuple, Any
from types import ModuleType
@contextmanager
def mock_types(mock_map: Dict[Tuple[ModuleType, str], Any]):
original_map: Dict[Tuple[ModuleType, str], Any] = {}
# replace types with the given mocks
for (module, original_attribute_name), mock_object in mock_map.items():
original_map[(module, original_attribute_name)] = getattr(module, original_attribute_name)
setattr(module, original_attribute_name, mock_object)
try:
yield
finally:
# replace mocks with original types
for (module, original_attribute_name), original_attribute_object in original_map.items():
setattr(module, original_attribute_name, original_attribute_object)
class MockTest(Test):
def run(self, repo_root: Optional[Path] = None, working_directory: Optional[Path] = None) -> TestResult:
time_delta = self.test_command.mock_time_delta() # type: ignore
return TestResult(self.name, time_delta, None)
class MockTimeDeltaCommand(Command):
def __init__(self, time_deltas: Sequence[timedelta] = None):
super().__init__()
self.time_delta_iterator = iter(()) if time_deltas is None else (x for x in time_deltas)
self.name = str([td.total_seconds() for td in time_deltas]) if time_deltas is not None else "Mock Command"
self._invokeCalls = 0
self.with_working_directory_calls = 0
def mock_time_delta(self) -> timedelta:
td = next(self.time_delta_iterator)
print(f"===>>> {self.name} : {td}")
return td
def _invoke(self):
self._invokeCalls = self._invokeCalls + 1
return ""
def with_working_directory(self, working_directory: Path):
self.with_working_directory_calls = self.with_working_directory_calls + 1
self.working_directory = working_directory
return self
class MockException(Exception):
pass
class ExceptionCommand(Command):
def __init__(self, message: str):
super().__init__()
self.message = message
def _invoke(self):
raise MockException(self.message)
class MockCommand(Command):
def __init__(self, command_output: str, validation_checks=None):
super(MockCommand, self).__init__(validation_checks)
self.command_output = command_output
def _invoke(self) -> str:
return self.command_output
class Tests(TestCase):
def setUp(self):
self.setUpPyfakefs()
self.test_root = Path("/PythonTests")
self.test_root.mkdir()
def test_ProcessCommand_calls_process(self):
with Pause(self.fs):
command = ProcessCommand(sys.executable, "-c", "print('foo', end='')")
assert_that(command.working_directory).is_equal_to(Path.cwd())
command.run()
assert_that(command.captured_output).is_equal_to(b"foo")
def test_PowershellCommand_calls_process(self):
with Pause(self.fs):
command = PowershellCommand("Write-Host -NoNewline 'foobar'")
assert_that(command.working_directory).is_equal_to(Path.cwd())
command.run()
assert_that(command.captured_output).is_equal_to(b"foobar")
def test_ProcessCommand_changes_working_directory(self):
working_directory = Path("working_directory")
working_directory.mkdir()
command1 = ProcessCommand(sys.executable, "-c", "print('foo')")
command2 = command1.with_working_directory(working_directory)
assert_that(command1).is_not_same_as(command2)
def test_Test_calls_commands(self):
test_command = MockTimeDeltaCommand()
repo_root_setup = MockTimeDeltaCommand()
setup_command = MockTimeDeltaCommand()
test = Test(
"test",
test_command,
repo_root_setup,
setup_command
)
repo_root = Path("root")
working_directory = Path("working directory")
repo_root.mkdir()
working_directory.mkdir()
test.run(
repo_root=repo_root,
working_directory=working_directory
)
assert_that(repo_root_setup._invokeCalls).is_equal_to(1)
assert_that(repo_root_setup.with_working_directory_calls).is_equal_to(1)
assert_that(repo_root_setup.working_directory).is_equal_to(repo_root)
assert_that(setup_command._invokeCalls).is_equal_to(1)
assert_that(setup_command.with_working_directory_calls).is_equal_to(1)
assert_that(setup_command.working_directory).is_equal_to(working_directory)
assert_that(test_command._invokeCalls).is_equal_to(1)
assert_that(test_command.with_working_directory_calls).is_equal_to(1)
assert_that(test_command.working_directory).is_equal_to(working_directory)
def test_Test_validates_commands_and_fails_validation(self):
with Pause(self.fs):
test = Test("t", NullCommand(), repo_root_setup_command=MockCommand("", [Func(lambda _: False, "lambda")]))
with pytest.raises(ValidationException) as exc_info:
test.run()
assert_that(exc_info.value.args[0]).starts_with("Validation failed: lambda")
multiline = """FooBar
Hello (World)"""
test = Test("t", NullCommand(), setup_command=MockCommand(multiline, [Include("hello")]))
with pytest.raises(ValidationException) as exc_info:
test.run()
assert_that(exc_info.value.args[0]).starts_with("Validation failed: Include(hello)")
test = Test("t", MockCommand(multiline, [Exclude("Hello")]))
with pytest.raises(ValidationException) as exc_info:
test.run()
assert_that(exc_info.value.args[0]).starts_with("Validation failed: Exclude(Hello)")
def test_Test_validates_commands_and_passes_validation(self):
with Pause(self.fs):
test = Test("t", NullCommand(), repo_root_setup_command=MockCommand("", [Func(lambda _: True, "lambda")]))
test.run()
multiline = """FooBar
Hello (World)"""
test = Test("t", NullCommand(), setup_command=MockCommand(multiline, [Include("(Worl")]))
test.run()
test = Test("t", MockCommand(multiline, [Exclude("wor")]))
test.run()
def test_Validation_can_be_added_to(self):
with Pause(self.fs):
command = MockCommand("FooBar", [Exclude("oba")])
command = command.add_validation_checks([Exclude("Bar")])
test = Test("t", command)
with pytest.raises(ValidationException) as exc_info:
test.run()
assert_that(exc_info.value.args[0]).starts_with("Validation failed: Exclude(Bar)")
command = MockCommand("FooBar", [Exclude("oBa")])
command = command.add_validation_checks([Include("Bar")])
command.run()
with pytest.raises(ValidationException) as exc_info:
command.validate()
assert_that(exc_info.value.args[0]).starts_with("Validation failed: Exclude(oBa)")
def test_Validation_works_with_real_command_output(self):
with Pause(self.fs):
command = PowershellCommand("Write-Host -NoNewline This is a test", validation_checks=[Include("foobar")])
test = Test("t", command)
with pytest.raises(ValidationException) as exc_info:
test.run()
assert_that(exc_info.value.args[0]).starts_with("Validation failed: Include(foobar)")
def test_nonzero_return_fails(self):
with Pause(self.fs):
test = Test("t", PowershellCommand("Invalid Powershell"))
with pytest.raises(CalledProcessError) as exc_info:
test.run()
assert_that(exc_info.value.cmd[-1]).is_equal_to("Invalid Powershell")
def test_suite_exposes_command_exception(self):
suite = TestSuite("s", [Test("t", ExceptionCommand("foo exception"))])
with pytest.raises(MockException) as exc_info:
suite.run()
assert_that(exc_info.value.args).contains("foo exception")
def test_suite_exposes_command_exception_when_environment_vars_are_set(self):
suite = TestSuite("s", [Test("t", ExceptionCommand("foo exception"))], {"foo": "bar"})
with pytest.raises(MockException) as exc_info:
suite.run()
assert_that(exc_info.value.args).contains("foo exception")
def test_suite_can_set_environment_variables(self):
with Pause(self.fs):
assert_that(os.environ).does_not_contain_key("foo")
initial_environment = os.environ.copy()
suite_result = TestSuite(
"s",
[Test("t", PowershellCommand("Write-Host -NoNewline $env:foo"))],
{"foo": "bar"}
).run()
assert_that(suite_result.test_results[0].command.captured_output).is_equal_to(b'bar')
assert_that(os.environ).is_equal_to(initial_environment)
def test_run_tests_executes_suites_and_averages_runtimes(self):
repo_path = self.test_root / "r1"
repo_path.mkdir()
repos = [
RepoSpec(
"r1",
"r1s1",
"r1s2"
)
]
test_suites = [
TestSuite(
"s1",
[
MockTest(
"s1t1",
MockTimeDeltaCommand(
[
# mean is 3
timedelta(seconds=1),
timedelta(seconds=2),
timedelta(seconds=6),
# mean is 4
timedelta(seconds=1),
timedelta(seconds=3),
timedelta(seconds=8),
])
),
MockTest(
"s1t2",
MockTimeDeltaCommand(
[
# mean is 6
timedelta(seconds=3),
timedelta(seconds=5),
timedelta(seconds=10),
# mean is 5
timedelta(seconds=3),
timedelta(seconds=4),
timedelta(seconds=8),
])
)
]
)
]
results = run_tests(repos, self.test_root, test_suites, repetitions=3)
assert_that(results[0].name).is_equal_to(f"r1{os.sep}r1s1")
assert_that(len(results[0].test_suite_results)).is_equal_to(1)
assert_that(len(results[0].test_suite_results[0].test_results)).is_equal_to(2)
assert_that(results[0].test_suite_results[0].test_results[1].name).is_equal_to("s1t2")
assert_that(results[0].test_suite_results[0].test_results[1].time_delta.total_seconds()).is_equal_to(6)
assert_that(results[0].test_suite_results[0].test_results[0].name).is_equal_to("s1t1")
assert_that(results[0].test_suite_results[0].test_results[0].time_delta.total_seconds()).is_equal_to(3)
assert_that(results[1].name).is_equal_to(f"r1{os.sep}r1s2")
assert_that(len(results[1].test_suite_results)).is_equal_to(1)
assert_that(len(results[1].test_suite_results[0].test_results)).is_equal_to(2)
assert_that(results[1].test_suite_results[0].test_results[0].name).is_equal_to("s1t1")
assert_that(results[1].test_suite_results[0].test_results[0].time_delta.total_seconds()).is_equal_to(4)
assert_that(results[1].test_suite_results[0].test_results[1].name).is_equal_to("s1t2")
assert_that(results[1].test_suite_results[0].test_results[1].time_delta.total_seconds()).is_equal_to(5)