tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

monitors_unittests.py (1850B)


      1 #!/usr/bin/env vpython3
      2 
      3 # Copyright 2024 The Chromium Authors
      4 # Use of this source code is governed by a BSD-style license that can be
      5 # found in the LICENSE file.
      6 """File for testing monitors.py."""
      7 
      8 import importlib
      9 import os
     10 import tempfile
     11 import unittest
     12 import unittest.mock as mock
     13 
     14 import monitors
     15 
     16 
     17 def dump() -> bool:
     18    """Tries to dump the metrics into a temporary file and returns if the
     19    file exits."""
     20    with tempfile.TemporaryDirectory() as tmpdir:
     21        monitors.dump(tmpdir)
     22        return os.path.isfile(
     23            os.path.join(tmpdir, 'test_script_metrics.jsonpb'))
     24 
     25 
     26 class MonitorsRealTest(unittest.TestCase):
     27    """Test real implementation of monitors.py."""
     28 
     29    def test_run_real_implementation(self) -> None:
     30        """Ensures the real version of the monitors is loaded."""
     31        importlib.reload(monitors)
     32        ave = monitors.average('test', 'run', 'real', 'implementation')
     33        ave.record(1)
     34        ave.record(2)
     35        self.assertTrue(dump())
     36 
     37    @mock.patch('os.path.isdir', side_effect=[False, True])
     38    def test_run_dummy_implementation(self, *_) -> None:
     39        """Ensures the dummy version of the monitors is loaded."""
     40        importlib.reload(monitors)
     41        ave = monitors.average('test', 'run', 'dummy', 'implementation')
     42        ave.record(1)
     43        ave.record(2)
     44        self.assertFalse(dump())
     45 
     46    @mock.patch('os.path.isdir', side_effect=[False, True])
     47    def test_with_dummy_implementation(self, *_) -> None:
     48        """Ensures the dummy version of the monitors can be used by 'with'
     49        statement."""
     50        importlib.reload(monitors)
     51        executed = False
     52        with monitors.time_consumption('test', 'with', 'dummy'):
     53            executed = True
     54        self.assertTrue(executed)
     55        self.assertFalse(dump())
     56 
     57 
     58 if __name__ == '__main__':
     59    unittest.main()