Debian Codegraph @

tests/base/interactive.py

raw symbols SCIP
1 import os
2 import array
3 import shutil
4 import warnings
5
6 import pytest
7
8 import pyglet
9 from pyglet.image import get_buffer_manager
10
11 from .data import PygletTestCase
12
13 local_dir = os.path.dirname(__file__)
14 test_dir = os.path.normpath(os.path.join(local_dir, '..'))
15
16 base_screenshot_path = os.path.join(test_dir, 'interactive', 'screenshots')
17 committed_screenshot_path = os.path.join(base_screenshot_path, 'committed')
18 session_screenshot_path = os.path.join(base_screenshot_path, 'session')
19
20 del local_dir, test_dir
21
22
23 class InteractiveFixture:
24 """Fixture for interactive test cases. Provides interactive prompts and
25 verifying screenshots.
26 """
27 def __init__(self, request):
28 self.screenshots = []
29 self._request = request
30
31 @property
32 def interactive(self):
33 return not self.sanity and not self.non_interactive
34
35 @property
36 def sanity(self):
37 return self._request.config.getoption('--sanity', False)
38
39 @property
40 def non_interactive(self):
41 return self._request.config.getoption('--non-interactive', False)
42
43 @property
44 def allow_missing_screenshots(self):
45 return not self.non_interactive
46
47 @property
48 def testname(self):
49 parts = []
50 parts.append(self._request.node.module.__name__)
51 if self._request.node.cls:
52 parts.append(self._request.node.cls.__name__)
53 parts.append(self._request.node.name)
54 return '.'.join(parts)
55
56 def ask_question(self, description=None):
57 """Ask a question to verify the current test result. Uses the console or an external gui
58 as no window is available."""
59 failure_description = None
60 if self.interactive:
61 failure_description = _ask_user_to_verify(description)
62 if failure_description is not None:
63 self.fail(failure_description)
64
65 def _take_screenshot(self, window=None):
66 """
67 Take a screenshot to allow visual verification.
68 """
69 screenshot_name = self._get_next_screenshot_name()
70 screenshot_file_name = self._get_screenshot_session_file_name(screenshot_name)
71
72 if window is not None:
73 window.switch_to()
74
75 get_buffer_manager().get_color_buffer().get_image_data().save(screenshot_file_name)
76 self.screenshots.append(screenshot_name)
77 self._schedule_commit()
78
79 return screenshot_name
80
81 def _check_screenshot(self, screenshot_name):
82 session_file_name = self._get_screenshot_session_file_name(screenshot_name)
83 committed_file_name = self._get_screenshot_committed_file_name(screenshot_name)
84
85 assert os.path.isfile(session_file_name)
86 if os.path.isfile(committed_file_name):
87 committed_image = pyglet.image.load(committed_file_name)
88 session_image = pyglet.image.load(session_file_name)
89 self.assert_image_equal(committed_image, session_image)
90 else:
91 assert self.allow_missing_screenshots
92 warnings.warn('No committed reference screenshot available.')
93
94 def _get_next_screenshot_name(self):
95 """
96 Get the unique name for the next screenshot.
97 """
98 return '{}.{:03d}.png'.format(self.testname,
99 len(self.screenshots)+1)
100
101 def _get_screenshot_session_file_name(self, screenshot_name):
102 return os.path.join(session_screenshot_path, screenshot_name)
103
104 def _get_screenshot_committed_file_name(self, screenshot_name):
105 return os.path.join(committed_screenshot_path, screenshot_name)
106
107 def _schedule_commit(self):
108 if not hasattr(self._request.session, 'pending_screenshots'):
109 self._request.session.pending_screenshots = set()
110 self._request.session.pending_screenshots.add(self)
111
112 def assert_image_equal(self, a, b, tolerance=0, msg=None):
113 if msg is None:
114 msg = 'Screenshot does not match last committed screenshot'
115 if a is None:
116 assert b is None, msg
117 else:
118 assert b is not None, msg
119
120 a_data = a.get_image_data()
121 b_data = b.get_image_data()
122
123 assert a_data.width == b_data.width, msg
124 assert a_data.height == b_data.height, msg
125 assert a_data.format == b_data.format, msg
126 assert a_data.pitch == b_data.pitch, msg
127 self.assert_buffer_equal(a_data.data, b_data.data, tolerance, msg)
128
129 def assert_buffer_equal(self, a, b, tolerance=0, msg=None):
130 if tolerance == 0:
131 assert a == b, msg
132
133 assert len(a) == len(b), msg
134
135 a = array.array('B', a)
136 b = array.array('B', b)
137 for (aa, bb) in zip(a, b):
138 assert abs(aa - bb) <= tolerance, msg
139
140 def commit_screenshots(self):
141 """
142 Store the screenshots for reference if the test case is successful.
143 """
144 for screenshot_name in self.screenshots:
145 shutil.copyfile(self._get_screenshot_session_file_name(screenshot_name),
146 self._get_screenshot_committed_file_name(screenshot_name))
147
148
149 class InteractiveTestCase(PygletTestCase):
150 """
151 Base class for interactive tests.
152
153 Interactive tests exist on several levels of interactivity. The least interactive tests store
154 screenshots of user validated output that can be used to automatically compare to in a non
155 interactive run. More interactive tests cannot validate the results automatically, but can
156 run fully automatic for sanity checks. Finally there are tests that really require the user
157 to perform an action for the test to continue.
158
159 Use the decorators @only_interactive, @requires_user_validation and @requires_user_action to
160 mark a test case as such. This only works on the test suite (class) level.
161 """
162 # Show interactive prompts
163 interactive = True
164
165 # Allow tests missing reference screenshots to pass
166 allow_missing_screenshots = False
167
168 def __init__(self, methodName):
169 super().__init__(methodName=methodName)
170 self._screenshots = []
171
172 def check_screenshots(self):
173 # If we arrive here, there have not been any failures yet
174 if self.interactive:
175 self._commit_screenshots()
176 else:
177 if self._has_reference_screenshots():
178 self._validate_screenshots()
179 # Always commit the screenshots here. They can be used for the next test run.
180 # If reference screenshots were already present and there was a mismatch, it should
181 # have failed above.
182 self._commit_screenshots()
183
184 elif self.allow_missing_screenshots:
185 warnings.warn('No committed reference screenshots available. Ignoring.')
186 else:
187 self.fail('No committed reference screenshots available. Run interactive first.')
188
189 def user_verify(self, description, take_screenshot=True):
190 """
191 Request the user to verify the current display is correct.
192 """
193 failed = False
194 failure_description = None
195
196 if self.interactive:
197 failure_description = _ask_user_to_verify(description)
198 if take_screenshot:
199 self._take_screenshot()
200
201 if failure_description is not None:
202 self.fail(failure_description)
203
204 def assert_image_equal(self, a, b, tolerance=0, msg=None):
205 if msg is None:
206 msg = 'Screenshot does not match last committed screenshot'
207 if a is None:
208 self.assertIsNone(b, msg)
209 else:
210 self.assertIsNotNone(b, msg)
211
212 a_data = a.get_image_data()
213 b_data = b.get_image_data()
214
215 self.assertEqual(a_data.width, b_data.width, msg)
216 self.assertEqual(a_data.height, b_data.height, msg)
217 self.assertEqual(a_data.format, b_data.format, msg)
218 self.assertEqual(a_data.pitch, b_data.pitch, msg)
219 self.assert_buffer_equal(a_data.data, b_data.data, tolerance, msg)
220
221 def assert_buffer_equal(self, a, b, tolerance=0, msg=None):
222 if tolerance == 0:
223 self.assertEqual(a, b, msg)
224
225 self.assertEqual(len(a), len(b), msg)
226
227 a = array.array('B', a)
228 b = array.array('B', b)
229 for (aa, bb) in zip(a, b):
230 self.assertTrue(abs(aa - bb) <= tolerance, msg)
231
232 def _take_screenshot(self):
233 """
234 Take a screenshot to allow visual verification.
235 """
236 screenshot_name = self._get_next_screenshot_name()
237 screenshot_file_name = self._get_screenshot_session_file_name(screenshot_name)
238
239 get_buffer_manager().get_color_buffer().get_image_data().save(screenshot_file_name)
240
241 self._screenshots.append(screenshot_name)
242
243 def _commit_screenshots(self):
244 """
245 Store the screenshots for reference if the test case is successful.
246 """
247 for screenshot_name in self._screenshots:
248 shutil.copyfile(self._get_screenshot_session_file_name(screenshot_name),
249 self._get_screenshot_committed_file_name(screenshot_name))
250
251 def _validate_screenshots(self):
252 """
253 Check the screenshot against regression reference images if available.
254 """
255 for screenshot_name in self._screenshots:
256 committed_image = pyglet.image.load(self._get_screenshot_committed_file_name(screenshot_name))
257 session_image = pyglet.image.load(self._get_screenshot_session_file_name(screenshot_name))
258 self.assert_image_equal(committed_image, session_image)
259
260 def _has_reference_screenshots(self):
261 """
262 Check whether there are screenshots from a previous successful run available to validate
263 against. Use after taking all required screenshots. Also validates the number of required
264 screenshots.
265 """
266 for screenshot_name in self._screenshots:
267 if not os.path.isfile(self._get_screenshot_committed_file_name(screenshot_name)):
268 return False
269 else:
270 return True
271
272 def _get_next_screenshot_name(self):
273 """
274 Get the unique name for the next screenshot.
275 """
276 return '{}.{}.{}.{:03d}.png'.format(self.__class__.__module__,
277 self.__class__.__name__,
278 self._testMethodName,
279 len(self._screenshots)+1)
280
281 def _get_screenshot_session_file_name(self, screenshot_name):
282 return os.path.join(session_screenshot_path, screenshot_name)
283
284 def _get_screenshot_committed_file_name(self, screenshot_name):
285 return os.path.join(committed_screenshot_path, screenshot_name)
286
287 def _ask_user_to_verify(description):
288 failure_description = None
289 print()
290 print(description)
291 while True:
292 response = input('Passed [Yn]: ')
293 if not response:
294 break
295 elif response in 'Nn':
296 failure_description = input('Enter failure description: ')
297 if not failure_description:
298 failure_description = 'No description entered'
299 break
300 elif response in 'Yy':
301 break
302 else:
303 print('Invalid response')
304 return failure_description
305
306 @pytest.fixture
307 def interactive(request):
308 """Fixture for interactive test cases. Returns an object that can be used for
309 requesting interactive prompts and verifying screenshots.
310 """
311 return InteractiveFixture(request)