source: trunk/src/allmydata/test/test_common_util.py

Last change on this file was 53084f7, checked in by Alexandre Detiste <alexandre.detiste@…>, at 2024-02-27T23:49:07Z

remove more Python2 compatibility

  • Property mode set to 100644
File size: 2.4 KB
Line 
1"""
2This module has been ported to Python 3.
3"""
4
5import sys
6import random
7
8from hypothesis import given
9from hypothesis.strategies import lists, sampled_from
10from testtools.matchers import Equals
11from twisted.python.reflect import (
12    ModuleNotFound,
13    namedAny,
14)
15
16from .common import (
17    SyncTestCase,
18    disable_modules,
19)
20from allmydata.test.common_util import flip_one_bit
21
22
23class TestFlipOneBit(SyncTestCase):
24
25    def setUp(self):
26        super(TestFlipOneBit, self).setUp()
27        # I tried using version=1 on PY3 to avoid the if below, to no avail.
28        random.seed(42)
29
30    def test_accepts_byte_string(self):
31        actual = flip_one_bit(b'foo')
32        self.assertEqual(actual, b'fom')
33
34    def test_rejects_unicode_string(self):
35        self.assertRaises(AssertionError, flip_one_bit, u'foo')
36
37
38
39def some_existing_modules():
40    """
41    Build the names of modules (as native strings) that exist and can be
42    imported.
43    """
44    candidates = sorted(
45        name
46        for name
47        in sys.modules
48        if "." not in name
49        and sys.modules[name] is not None
50    )
51    return sampled_from(candidates)
52
53class DisableModulesTests(SyncTestCase):
54    """
55    Tests for ``disable_modules``.
56    """
57    def setup_example(self):
58        return sys.modules.copy()
59
60    def teardown_example(self, safe_modules):
61        sys.modules.update(safe_modules)
62
63    @given(lists(some_existing_modules(), unique=True))
64    def test_importerror(self, module_names):
65        """
66        While the ``disable_modules`` context manager is active any import of the
67        modules identified by the names passed to it result in ``ImportError``
68        being raised.
69        """
70        def get_modules():
71            return list(
72                namedAny(name)
73                for name
74                in module_names
75            )
76        before_modules = get_modules()
77
78        with disable_modules(*module_names):
79            for name in module_names:
80                with self.assertRaises(ModuleNotFound):
81                    namedAny(name)
82
83        after_modules = get_modules()
84        self.assertThat(before_modules, Equals(after_modules))
85
86    def test_dotted_names_rejected(self):
87        """
88        If names with "." in them are passed to ``disable_modules`` then
89        ``ValueError`` is raised.
90        """
91        with self.assertRaises(ValueError):
92            with disable_modules("foo.bar"):
93                pass
Note: See TracBrowser for help on using the repository browser.