Unit tests are mostly trivial to write with only those assert statements over the expected results of the function (which is to be tested) instances. But sometimes it gets difficult to test some functions which require test data and the place where you store the data is not accessible in the tests.
was trying to test my gpg utility which uses a home directory where all the public and secret key rings are stored(or supposed to be stored by default) whose hard-coded-path in my project is "/home/maxking/mailman/mailman/var/gpg" . Usually I can point to "/home/maxking/mailman/mailman/var/" with the "config.VAR_DIR" variable which gets initialized when the config layer is initialized during tests. What is a layer? Mailman uses "zope.testing" framework for testing, it has a concept of layers which instantiates all the modules of the project so that they can be used in the tests. Occasionally you can use temporary directories and values for testing purposes in-case you don't want the tests to alter your actual data. So config layer creates a temp "var director" during test runtime. See the code below for the initialization of the gpg handler:
1class GPG:
2 def __init__(self, dir):
3 self._gpg = None
4 self._home = dir
5 self._gpg = gnupg.GPG(gnupghome=self._home)
And this module is used as:
1 from mailman.utilities.gpg import GPG
2
3 gpg_dir = os.path.join(config.VAR_DIR, "gpg")
4 gpg = GPG(gpg_dir)
So the `config layer` creates a new temp var directory every time tests are run and thus my test data inside "/home/maxking/mailman/mailman/var/gpg" is never found during the test run. So the workaround that I was suggested by Barry to copy the test data to whatever temp var directory that is created the tests are now running smoothly. Below is a snippet of the code how it works:
1 from mailman.testing.helpers import setup_keyrings, makedirs
2
3 class TestGPG(unittest.TestCase):
4 """Testing functions in the gpg utility"""
5
6 layer = ConfigLayer
7
8 def test_keyring(self):
9 """verify the keyrings"""
10
11 gpg_dir = os.path.join(config.VAR_DIR, 'gpg')
12 makedirs(gpg_dir)
13 setup_keyrings(gpg_dir)
14 gpg = GPG(gpg_dir)
And below are the helper functions that are used above.
1def test_data_path(filename):
2 return os.path.abspath(
3 resource_filename(
4 'mailman.utilities.tests.data', filename))
5
6def makedirs(dir):
7 try:
8 os.makedirs(dir)
9 except OSError as e:
10 pass
11
12def copy(filename, dst):
13 src = test_data_path(filename)
14 makedirs(dst)
15 try:
16 shutil.copy(src, dst)
17 except IOError:
18 raise IOError('File {0} copy to {1} failed'.format(filename, dst))
19
20def setup_keyrings(dst):
21 """Copy the keyrings to the right place.
22 """
23 keyrings = ('pubring.gpg', 'secring.gpg')
24
25 for keyring in keyrings:
26 # The local keyrings live in the .gpg file with the same keyring name
27 # in the temporary directory.
28 copy(keyring, dst)