1#!/usr/bin/env python
2
3from __future__ import absolute_import
4
5from unittest import mock
6import mozunit
7import time
8
9
10def test_macintelpower_init(macintelpower_obj):
11    """Tests that the MacIntelPower object is correctly initialized."""
12    assert macintelpower_obj.ipg_path
13    assert macintelpower_obj.ipg
14    assert macintelpower_obj._os == "darwin"
15    assert macintelpower_obj._cpu == "intel"
16
17
18def test_macintelpower_measuring(macintelpower_obj):
19    """Tests that measurement initialization and finalization works
20    for the MacIntelPower object.
21    """
22    assert not macintelpower_obj.start_time
23    assert not macintelpower_obj.ipg._running
24    assert not macintelpower_obj.ipg._output_files
25    macintelpower_obj.initialize_power_measurements()
26
27    # Check that initialization set start_time, and started the
28    # IPG measurer thread.
29
30    # Wait a bit for thread to start, then check it
31    timeout = 10
32    start = time.time()
33    while time.time() - start < timeout and not macintelpower_obj.ipg._running:
34        time.sleep(1)
35
36    assert macintelpower_obj.start_time
37    assert macintelpower_obj.ipg._running
38
39    test_data = {"power-usage": "data"}
40
41    def formatter_side_effect(*args, **kwargs):
42        return test_data
43
44    with mock.patch(
45        "mozpower.intel_power_gadget.IPGResultsHandler.clean_ipg_data"
46    ) as _:
47        with mock.patch(
48            "mozpower.intel_power_gadget.IPGResultsHandler."
49            "format_ipg_data_to_partial_perfherder"
50        ) as formatter:
51            formatter.side_effect = formatter_side_effect
52
53            macintelpower_obj.finalize_power_measurements(wait_interval=2, timeout=30)
54
55            # Check that finalization set the end_time, stopped the IPG measurement
56            # thread, added atleast one output file name, and initialized
57            # an IPGResultsHandler object
58            assert macintelpower_obj.end_time
59            assert not macintelpower_obj.ipg._running
60            assert macintelpower_obj.ipg._output_files
61            assert macintelpower_obj.ipg_results_handler
62
63            # Check that the IPGResultHandler's methods were
64            # called
65            macintelpower_obj.ipg_results_handler.clean_ipg_data.assert_called()
66            macintelpower_obj.ipg_results_handler.format_ipg_data_to_partial_perfherder.assert_called_once_with(  # NOQA: E501
67                macintelpower_obj.end_time - macintelpower_obj.start_time,
68                "power-testing",
69            )
70
71            # Make sure we can get the expected perfherder data
72            # after formatting
73            assert macintelpower_obj.get_perfherder_data() == test_data
74
75
76if __name__ == "__main__":
77    mozunit.main()
78