Debian Codegraph @

testing/mozbase/mozpower/tests/test_intelpowergadget.py

raw
1 #!/usr/bin/env python
2
3 import datetime
4 import os
5 import time
6 from unittest import mock
7
8 import mozunit
9 import pytest
10 import six
11 from mozpower.intel_power_gadget import (
12 IPGEmptyFileError,
13 IPGMissingOutputFileError,
14 IPGTimeoutError,
15 IPGUnknownValueTypeError,
16 )
17
18
19 def thread_is_alive(thread):
20 if six.PY2:
21 return thread.isAlive()
22 return thread.is_alive()
23
24
25 def test_ipg_pathsplitting(ipg_obj):
26 """Tests that the output file path and prefix was properly split.
27 This test assumes that it is in the same directory as the conftest.py file.
28 """
29 assert (
30 ipg_obj.output_dir_path == os.path.abspath(os.path.dirname(__file__)) + "/files"
31 )
32 assert ipg_obj.output_file_prefix == "raptor-tp6-amazon-firefox_powerlog"
33
34
35 def test_ipg_get_output_file_path(ipg_obj):
36 """Tests that the output file path is constantly changing
37 based on the file_counter value.
38 """
39 test_path = "/test_path/"
40 test_ext = ".txt"
41 ipg_obj._file_counter = 1
42 ipg_obj._output_dir_path = test_path
43 ipg_obj._output_file_ext = test_ext
44
45 for i in range(1, 6):
46 fpath = ipg_obj._get_output_file_path()
47
48 assert fpath.startswith(test_path)
49 assert fpath.endswith(test_ext)
50 assert str(i) in fpath
51
52
53 def test_ipg_start_and_stop(ipg_obj):
54 """Tests that the IPG thread can start and stop properly."""
55
56 def subprocess_side_effect(*args, **kwargs):
57 time.sleep(1)
58
59 with mock.patch("subprocess.check_output") as m:
60 m.side_effect = subprocess_side_effect
61
62 # Start recording IPG measurements
63 ipg_obj.start_ipg()
64 assert not ipg_obj._stop
65
66 # Wait a bit for thread to start, then check it
67 timeout = 10
68 start = time.time()
69 while time.time() - start < timeout and not ipg_obj._running:
70 time.sleep(1)
71
72 assert ipg_obj._running
73 assert thread_is_alive(ipg_obj._thread)
74
75 # Stop recording IPG measurements
76 ipg_obj.stop_ipg(wait_interval=1, timeout=30)
77 assert ipg_obj._stop
78 assert not ipg_obj._running
79
80
81 def test_ipg_stopping_timeout(ipg_obj):
82 """Tests that an IPGTimeoutError is raised when
83 the thread is still "running" and the wait in _wait_for_ipg
84 has exceeded the timeout value.
85 """
86 with pytest.raises(IPGTimeoutError):
87 ipg_obj._running = True
88 ipg_obj._wait_for_ipg(wait_interval=1, timeout=2)
89
90
91 def test_ipg_rh_combine_cumulatives(ipg_rh_obj):
92 """Tests that cumulatives are correctly combined in
93 the _combine_cumulative_rows function.
94 """
95 cumulatives_to_combine = [
96 [0, 1, 2, 3, 4, 5],
97 [0, 1, 2, 3, 4, 5],
98 [0, 1, 2, 3, 4, 5],
99 [0, 1, 2, 3, 4, 5],
100 ]
101
102 combined_cumulatives = ipg_rh_obj._combine_cumulative_rows(cumulatives_to_combine)
103
104 # Check that accumulation worked, final value must be the maximum
105 assert combined_cumulatives[-1] == max(combined_cumulatives)
106
107 # Check that the cumulative values are monotonically increasing
108 for count, val in enumerate(combined_cumulatives[:-1]):
109 assert combined_cumulatives[count + 1] - val >= 0
110
111
112 def test_ipg_rh_clean_file(ipg_rh_obj):
113 """Tests that IPGResultsHandler correctly cleans the data
114 from one file.
115 """
116 file = ipg_rh_obj._output_files[0]
117 linecount = 0
118 with open(file) as f:
119 for line in f:
120 linecount += 1
121
122 results, summary, clean_file = ipg_rh_obj._clean_ipg_file(file)
123
124 # Check that each measure from the csv header
125 # is in the results dict and that the clean file output
126 # exists.
127 for measure in results:
128 assert measure in ipg_rh_obj._csv_header
129 assert os.path.exists(clean_file)
130
131 clean_rows = []
132 with open(clean_file) as f:
133 for line in f:
134 if line.strip():
135 clean_rows.append(line)
136
137 # Make sure that the results and summary entries
138 # have the expected lengths.
139 for measure in results:
140 # Add 6 for new lines that were removed
141 assert len(results[measure]) + len(summary) + 6 == linecount
142 # Subtract 1 for the csv header
143 assert len(results[measure]) == len(clean_rows) - 1
144
145
146 def test_ipg_rh_clean_ipg_data_no_files(ipg_rh_obj):
147 """Tests that IPGResultsHandler correctly handles the case
148 when no output files exist.
149 """
150 ipg_rh_obj._output_files = []
151 clean_data = ipg_rh_obj.clean_ipg_data()
152 assert clean_data is None
153
154
155 def test_ipg_rh_clean_ipg_data(ipg_rh_obj):
156 """Tests that IPGResultsHandler correctly handles cleaning
157 all known files and that the results and the merged output
158 are correct.
159 """
160 clean_data = ipg_rh_obj.clean_ipg_data()
161 clean_files = ipg_rh_obj.cleaned_files
162 merged_output_path = ipg_rh_obj.merged_output_path
163
164 # Check that the expected output exists
165 assert clean_data is not None
166 assert len(clean_files) == len(ipg_rh_obj._output_files)
167 assert os.path.exists(merged_output_path)
168
169 # Check that the merged file length and results length
170 # is correct, and that no lines were lost and no extra lines
171 # were added.
172 expected_merged_line_count = 0
173 for file in clean_files:
174 with open(file) as f:
175 for count, line in enumerate(f):
176 if count == 0:
177 continue
178 if line.strip():
179 expected_merged_line_count += 1
180
181 merged_line_count = 0
182 with open(merged_output_path) as f:
183 for count, line in enumerate(f):
184 if count == 0:
185 continue
186 if line.strip():
187 merged_line_count += 1
188
189 assert merged_line_count == expected_merged_line_count
190 for measure in clean_data:
191 assert len(clean_data[measure]) == merged_line_count
192
193 # Check that the clean data rows are ordered in increasing time
194 times_in_seconds = []
195 for sys_time in clean_data["System Time"]:
196 split_sys_time = sys_time.split(":")
197 hour_min_sec = ":".join(split_sys_time[:-1])
198 millis = float(split_sys_time[-1]) / 1000
199
200 timestruct = time.strptime(hour_min_sec, "%H:%M:%S")
201 times_in_seconds.append(
202 datetime.timedelta(
203 hours=timestruct.tm_hour,
204 minutes=timestruct.tm_min,
205 seconds=timestruct.tm_sec,
206 ).total_seconds()
207 + millis
208 )
209
210 for count, val in enumerate(times_in_seconds[:-1]):
211 assert times_in_seconds[count + 1] - val >= 0
212
213
214 def test_ipg_rh_format_to_perfherder_with_no_results(ipg_rh_obj):
215 """Tests that formatting the data to a perfherder-like format
216 fails when clean_ipg_data was not called beforehand.
217 """
218 formatted_data = ipg_rh_obj.format_ipg_data_to_partial_perfherder(
219 1000, ipg_rh_obj._output_file_prefix
220 )
221 assert formatted_data is None
222
223
224 def test_ipg_rh_format_to_perfherder_without_cutoff(ipg_rh_obj):
225 """Tests that formatting the data to a perfherder-like format
226 works as expected.
227 """
228 ipg_rh_obj.clean_ipg_data()
229 formatted_data = ipg_rh_obj.format_ipg_data_to_partial_perfherder(
230 1000, ipg_rh_obj._output_file_prefix
231 )
232
233 # Check that the expected entries exist
234 assert len(formatted_data.keys()) == 5
235 assert "utilization" in formatted_data and "power-usage" in formatted_data
236
237 assert (
238 formatted_data["power-usage"]["test"]
239 == ipg_rh_obj._output_file_prefix + "-cumulative"
240 )
241 assert (
242 formatted_data["utilization"]["test"]
243 == ipg_rh_obj._output_file_prefix + "-utilization"
244 )
245 assert (
246 formatted_data["frequency-gpu"]["test"]
247 == ipg_rh_obj._output_file_prefix + "-frequency-gpu"
248 )
249 assert (
250 formatted_data["frequency-cpu"]["test"]
251 == ipg_rh_obj._output_file_prefix + "-frequency-cpu"
252 )
253 assert (
254 formatted_data["power-watts"]["test"]
255 == ipg_rh_obj._output_file_prefix + "-watts"
256 )
257
258 for measure in formatted_data:
259 # Make sure that the data exists
260 assert len(formatted_data[measure]["values"]) >= 1
261
262 for valkey in formatted_data[measure]["values"]:
263 # Make sure the names were simplified
264 assert "(" not in valkey
265 assert ")" not in valkey
266
267 # Check that gpu utilization doesn't exist but cpu does
268 utilization_vals = formatted_data["utilization"]["values"]
269 assert "cpu" in utilization_vals
270 assert "gpu" not in utilization_vals
271
272 expected_fields = ["processor-cores", "processor-package", "gpu", "dram"]
273 consumption_vals = formatted_data["power-usage"]["values"]
274
275 consumption_vals_measures = list(consumption_vals.keys())
276
277 # This assertion ensures that the consumption values contain the expected
278 # fields and nothing more.
279 assert not list(set(consumption_vals_measures) - set(expected_fields))
280
281
282 def test_ipg_rh_format_to_perfherder_with_cutoff(ipg_rh_obj):
283 """Tests that formatting the data to a perfherder-like format
284 works as expected.
285 """
286 ipg_rh_obj.clean_ipg_data()
287 formatted_data = ipg_rh_obj.format_ipg_data_to_partial_perfherder(
288 2.5, ipg_rh_obj._output_file_prefix
289 )
290
291 # Check that the formatted data was cutoff at the correct point,
292 # expecting that only the first row of merged will exist.
293 utilization_vals = formatted_data["utilization"]["values"]
294 assert utilization_vals["cpu"] == 14
295
296 # Expected vals are ordered in this way: [processor, cores, dram, gpu]
297 expected_vals = [6.517, 5.847, 0.244, 0.006]
298 consumption_vals = [
299 formatted_data["power-usage"]["values"][measure]
300 for measure in formatted_data["power-usage"]["values"]
301 ]
302 assert not list(set(expected_vals) - set(consumption_vals))
303
304
305 def test_ipg_rh_missingoutputfile(ipg_rh_obj):
306 """Tests that the IPGMissingOutputFileError is raised
307 when a bad file path is passed to _clean_ipg_file.
308 """
309 bad_files = ["non-existent-file"]
310 with pytest.raises(IPGMissingOutputFileError):
311 ipg_rh_obj._clean_ipg_file(bad_files[0])
312
313 ipg_rh_obj._output_files = bad_files
314 with pytest.raises(IPGMissingOutputFileError):
315 ipg_rh_obj.clean_ipg_data()
316
317
318 def test_ipg_rh_emptyfile(ipg_rh_obj):
319 """Tests that the empty file error is raised when
320 a file exists, but does not contain any results in
321 it.
322 """
323 base_path = os.path.abspath(os.path.dirname(__file__)) + "/files/"
324 bad_files = [base_path + "emptyfile.txt"]
325 with pytest.raises(IPGEmptyFileError):
326 ipg_rh_obj._clean_ipg_file(bad_files[0])
327
328 ipg_rh_obj._output_files = bad_files
329 with pytest.raises(IPGEmptyFileError):
330 ipg_rh_obj.clean_ipg_data()
331
332
333 def test_ipg_rh_valuetypeerrorfile(ipg_rh_obj):
334 """Tests that the IPGUnknownValueTypeError is raised
335 when a bad entry is encountered in a file that is cleaned.
336 """
337 base_path = os.path.abspath(os.path.dirname(__file__)) + "/files/"
338 bad_files = [base_path + "valueerrorfile.txt"]
339 with pytest.raises(IPGUnknownValueTypeError):
340 ipg_rh_obj._clean_ipg_file(bad_files[0])
341
342 ipg_rh_obj._output_files = bad_files
343 with pytest.raises(IPGUnknownValueTypeError):
344 ipg_rh_obj.clean_ipg_data()
345
346
347 if __name__ == "__main__":
348 mozunit.main()