Debian Codegraph @

tests/test_lib.py

raw
1 # -*- coding: utf-8 -*-
2 """Shared functions and classes for testing."""
3
4 import os
5 import shutil
6 import tempfile
7 import unittest
8
9
10 class BaseTestCase(unittest.TestCase):
11 """The base test case."""
12
13 _DATA_PATH = os.path.join(os.getcwd(), 'data')
14 _TEST_DATA_PATH = os.path.join(os.getcwd(), 'test_data')
15
16 # Show full diff results, part of TestCase so does not follow our naming
17 # conventions.
18 maxDiff = None
19
20 def _GetTestFilePath(self, path_segments):
21 """Retrieves the path of a test file in the test data directory.
22
23 Args:
24 path_segments (list[str]): path segments inside the test data directory.
25
26 Returns:
27 str: path of the test file.
28 """
29 # Note that we need to pass the individual path segments to os.path.join
30 # and not a list.
31 return os.path.join(self._TEST_DATA_PATH, *path_segments)
32
33 def _SkipIfPathNotExists(self, path):
34 """Skips the test if the path does not exist.
35
36 Args:
37 path (str): path of a test file.
38
39 Raises:
40 SkipTest: if the path path does not exist and the test should be skipped.
41 """
42 if not os.path.exists(path):
43 filename = os.path.basename(path)
44 raise unittest.SkipTest(f'missing test file: {filename:s}')
45
46
47 class TempDirectory(object):
48 """Class that implements a temporary directory."""
49
50 def __init__(self):
51 """Initializes a temporary directory."""
52 super(TempDirectory, self).__init__()
53 self.name = ''
54
55 def __enter__(self):
56 """Make this work with the 'with' statement."""
57 self.name = tempfile.mkdtemp()
58 return self.name
59
60 def __exit__(self, unused_type, unused_value, unused_traceback):
61 """Make this work with the 'with' statement."""
62 shutil.rmtree(self.name, True)