summaryrefslogtreecommitdiffstats
path: root/test/test-defs.py
blob: 9098ef04797bfc2573b0a58369bc712ab5caff28 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/python3
import contextlib
import os
import sys
import unittest
from unittest import mock


class MockLibnvmeTestCase(unittest.TestCase):
    '''Testing defs.py by mocking the libnvme package'''

    def test_libnvme_version(self):
        # Ensure that we re-import staslib & staslib.defs if the current Python
        # process has them already imported.
        with contextlib.suppress(KeyError):
            sys.modules.pop('staslib.defs')
        with contextlib.suppress(KeyError):
            sys.modules.pop('staslib')

        from staslib import defs

        libnvme_ver = defs.LIBNVME_VERSION
        self.assertEqual(libnvme_ver, '?.?')

    @classmethod
    def setUpClass(cls):  # called once before all the tests
        # define what to patch sys.modules with
        cls._modules_patcher = mock.patch.dict(sys.modules, {'libnvme': mock.Mock()})

        # actually patch it
        cls._modules_patcher.start()

        # make the package globally visible and import it,
        #   just like if you have imported it in a usual way
        #   placing import statement at the top of the file,
        #   but relying on a patched dependency
        global libnvme
        import libnvme

    @classmethod  # called once after all tests
    def tearDownClass(cls):
        # restore initial sys.modules state back
        cls._modules_patcher.stop()


class RealLibnvmeUnitTest(unittest.TestCase):
    '''Testing defs.py with the real libnvme package'''

    def test_libnvme_version(self):
        try:
            # We can't proceed with this test if the
            # module libnvme is not installed.
            import libnvme
        except ModuleNotFoundError:
            return

        from staslib import defs

        libnvme_ver = defs.LIBNVME_VERSION
        self.assertNotEqual(libnvme_ver, '?.?')


if __name__ == '__main__':
    unittest.main()