diff --git a/hacking/checks/imports.py b/hacking/checks/imports.py index 698eca7..610e442 100644 --- a/hacking/checks/imports.py +++ b/hacking/checks/imports.py @@ -72,7 +72,7 @@ def hacking_import_rules(logical_line, physical_line, filename, noqa): try: mod_name = mod while '.' in mod_name: - pack_name, _sep, mod_name = mod.partition('.') + pack_name, _sep, mod_name = mod_name.partition('.') f, p, d = imp.find_module(pack_name, search_path) search_path = [p] imp.find_module(mod_name, search_path) diff --git a/hacking/tests/checks/test_imports.py b/hacking/tests/checks/test_imports.py index 2e8e162..5a04aeb 100644 --- a/hacking/tests/checks/test_imports.py +++ b/hacking/tests/checks/test_imports.py @@ -15,6 +15,7 @@ import mock import six +import sys from hacking.checks import imports from hacking import tests @@ -29,6 +30,9 @@ def fake_find_module(module, path): return (None, './oslo', None) elif module == 'db' and path[0] == './oslo': return (None, './oslo/db', None) + elif module == 'abc' and path[0] == './oslo/db': + # Let's fake, there is no abc.py at ./oslo/db/ + raise ImportError elif './oslo/db' in path[0] and module != '_': return (None, '%s/%s' % (path[0], module), None) raise ImportError @@ -55,3 +59,23 @@ class ImportTestCase(tests.TestCase): mock_import.side_effect = ImportError mod_name = 'oslo.db.openstack.common.gettextutils._' self.assertEqual('project', imports._get_import_type(mod_name)) + + @mock.patch.object(sys, 'path', ['.']) + @mock.patch(import_name) + @mock.patch('imp.find_module') + def test_module_import(self, find_module, mock_import): + find_module.side_effect = fake_find_module + # API under test + aut = imports.hacking_import_rules + for num, msg in aut('from oslo.db import xyz', None, 'fake_file.py', + 0): + # xyz should be found and this generator should be empty + self.fail('Module xyz should have been found under oslo.db') + for num, msg in aut('from oslo.db import abc', None, 'fake_file.py', + 0): + # abc should not be found and we should get H302 + self.assertTrue(msg.startswith('H302')) + for num, msg in aut('from oslo.db.myz import *', None, 'fake_file.py', + 0): + # wildcard import is not allowed as per H303 + self.assertTrue(msg.startswith('H303'))