| 1 |
# -*- coding: utf-8 -*- |
| 2 |
"""Functions and classes for testing.""" |
| 3 |
|
| 4 |
import os |
| 5 |
import shutil |
| 6 |
import tempfile |
| 7 |
import unittest |
| 8 |
|
| 9 |
from acstore.containers import interface as containers_interface |
| 10 |
|
| 11 |
|
| 12 |
# The path to top of the dfWinReg source tree. |
| 13 |
PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) |
| 14 |
|
| 15 |
# The paths below are all derived from the project path directory. |
| 16 |
# They are enumerated explicitly here so that they can be overwritten for |
| 17 |
# compatibility with different build systems. |
| 18 |
TEST_DATA_PATH = os.path.join(PROJECT_PATH, 'test_data') |
| 19 |
|
| 20 |
|
| 21 |
class TestAttributeContainer(containers_interface.AttributeContainer): |
| 22 |
"""Attribute container for testing purposes. |
| 23 |
|
| 24 |
Attributes: |
| 25 |
attribute (str): attribute for testing purposes. |
| 26 |
""" |
| 27 |
|
| 28 |
CONTAINER_TYPE = 'test_container' |
| 29 |
|
| 30 |
SCHEMA = {'attribute': 'str'} |
| 31 |
|
| 32 |
def __init__(self): |
| 33 |
"""Initializes an attribute container.""" |
| 34 |
super(TestAttributeContainer, self).__init__() |
| 35 |
self.attribute = None |
| 36 |
|
| 37 |
|
| 38 |
class BaseTestCase(unittest.TestCase): |
| 39 |
"""The base test case.""" |
| 40 |
|
| 41 |
# Show full diff results. |
| 42 |
maxDiff = None |
| 43 |
|
| 44 |
def _GetTestFilePath(self, path_segments): |
| 45 |
"""Retrieves the path of a test file relative to the test data directory. |
| 46 |
|
| 47 |
Args: |
| 48 |
path_segments (list[str]): path segments inside the test data directory. |
| 49 |
|
| 50 |
Returns: |
| 51 |
str: path of the test file. |
| 52 |
""" |
| 53 |
# Note that we need to pass the individual path segments to os.path.join |
| 54 |
# and not a list. |
| 55 |
return os.path.join(TEST_DATA_PATH, *path_segments) |
| 56 |
|
| 57 |
def _SkipIfPathNotExists(self, path): |
| 58 |
"""Skips the test if the path does not exist. |
| 59 |
|
| 60 |
Args: |
| 61 |
path (str): path of a test file. |
| 62 |
|
| 63 |
Raises: |
| 64 |
SkipTest: if the path does not exist and the test should be skipped. |
| 65 |
""" |
| 66 |
if not os.path.exists(path): |
| 67 |
filename = os.path.basename(path) |
| 68 |
raise unittest.SkipTest(f'missing test file: {filename:s}') |
| 69 |
|
| 70 |
|
| 71 |
class TempDirectory(object): |
| 72 |
"""Class that implements a temporary directory.""" |
| 73 |
|
| 74 |
def __init__(self): |
| 75 |
"""Initializes a temporary directory.""" |
| 76 |
super(TempDirectory, self).__init__() |
| 77 |
self.name = '' |
| 78 |
|
| 79 |
def __enter__(self): |
| 80 |
"""Make this work with the 'with' statement.""" |
| 81 |
self.name = tempfile.mkdtemp() |
| 82 |
return self.name |
| 83 |
|
| 84 |
def __exit__(self, exception_type, value, traceback): |
| 85 |
"""Make this work with the 'with' statement.""" |
| 86 |
shutil.rmtree(self.name, True) |