I have code reviewed a piece of Python code, but to me it looks really ugly, hacky and complex for something that can be achieved very easily.The code looks something similar to the following:_extra.py (this is supposed to be a private module because of the underscore):import dependencyclass Extra(dependency.Cls):    ...setup.pysetup(    ...    name='somepkg',    extras_require={        ...        'extra': ['dependency']})public.py_dist = pkg_resources.working_set.find(    pkg_resources.Requirement.parse('somepkg'))if 'extra' in _dist:    from _extra import ExtraSo that the extras_require can be tested using:class ExtraTest(unittest.TestCase):    ...    # Some test cases where the requirement actually is available    def test_require_extra(self):        dist = mock.Mock(pkg_resources.Distribution)        self.dist.extras = []        public = helper.import_or_reload('public')        with self.assertRaises(AttributeError):            public.ExtraMy initial thought would be to not have _extra.py exist and have public.py look like:try:    import dependencyexcept ImportError    passelse:    class Extra(dependency.Cls):        ...I don't really care that it isn't tested that it can't be imported if it is not in the extras_require.Does the original code seem like a logical solution?Should extras_require be tested in any way? If so, how?
Is there a cleaner way to test extras_require
python;unit testing;testing;dependency management
If this is all done just to make it possible to test the Extra class, then the code is overcomplicating matters. The code is asking for permission rather than for forgiveness.You are quite correct, changing the code to catch the ImportError exception would vastly simplify the codebase. The code shouldn't even try to test the detection, but simply rely on Python's own unit tests to have tested throwing an ImportError properly. At best the unittest should verify what happens if extra is not set (perhaps by the code setting extra = None if the dependency is missing, testing is then as easy as mocking extra = None).