test that the semantics relating to the fromlist argument are correct from test testimportlib import util import warnings import unittest class returnvalue def testreturnfromimportself import return with util mockspec pkg init pkg module as importer with util importstatemetapathimporter module self import pkg module self assertequalmodule name pkg def testreturnfromfromimportself from return with util mockspec pkg init pkg module as importer with util importstatemetapathimporter module self import pkg module fromlist attr self assertequalmodule name pkg module frozenreturnvalue sourcereturnvalue util testbothreturnvalue importutil import class handlingfromlist def testobjectself object case with util mockspec module as importer with util importstatemetapathimporter module self import module fromlist attr self assertequalmodule name module def testnonexistentobjectself bad object with util mockspec module as importer with util importstatemetapathimporter module self import module fromlist nonexistent self assertequalmodule name module self assertfalsehasattrmodule nonexistent def testmodulefrompackageself module with util mockspec pkg init pkg module as importer with util importstatemetapathimporter module self import pkg fromlist module self assertequalmodule name pkg self asserttruehasattrmodule module self assertequalmodule module name pkg module def testnonexistentfrompackageself with util mockspec pkg init as importer with util importstatemetapathimporter module self import pkg fromlist nonexistent self assertequalmodule name pkg self assertfalsehasattrmodule nonexistent def testmodulefrompackagetriggersmodulenotfounderrorself if a submodule causes an modulenotfounderror because it tries to import a module which doesn t exist that should let the modulenotfounderror propagate def modulecode import idonotexist with util mockspec pkg init pkg mod modulecode pkg mod modulecode as importer with util importstatemetapathimporter with self assertraisesmodulenotfounderror as exc self import pkg fromlist mod self assertequal idonotexist exc exception name def testemptystringself with util mockspec pkg init pkg mod as importer with util importstatemetapathimporter module self import pkg mod fromlist self assertequalmodule name pkg mod def basicstartestself fromlist using with util mockspec pkg init pkg module as mock with util importstatemetapathmock mock pkg all module module self import pkg fromlistfromlist self assertequalmodule name pkg self asserttruehasattrmodule module self assertequalmodule module name pkg module def testusingstarself using self basicstartest def testfromlistastupleself self basicstartest def teststarwithothersself using with others context util mockspec pkg init pkg module1 pkg module2 with context as mock with util importstatemetapathmock mock pkg all module1 module self import pkg fromlist module2 self assertequalmodule name pkg self asserttruehasattrmodule module1 self asserttruehasattrmodule module2 self assertequalmodule module1 name pkg module1 self assertequalmodule module2 name pkg module2 def testnonexistentinallself with util mockspec pkg init as importer with util importstatemetapathimporter importer pkg all nonexistent module self import pkg fromlist self assertequalmodule name pkg self assertfalsehasattrmodule nonexistent def teststarinallself with util mockspec pkg init as importer with util importstatemetapathimporter importer pkg all module self import pkg fromlist self assertequalmodule name pkg self assertfalsehasattrmodule def testinvalidtypeself with util mockspec pkg init as importer with util importstatemetapathimporter warnings catchwarnings warnings simplefilter error byteswarning with self assertraisesregextypeerror r bfromb self import pkg fromlistb attr with self assertraisesregextypeerror r bfromb self import pkg fromlistiterb attr def testinvalidtypeinallself with util mockspec pkg init as importer with util importstatemetapathimporter warnings catchwarnings warnings simplefilter error byteswarning importer pkg all b attr with self assertraisesregextypeerror r bpkg allb self import pkg fromlist frozenfromlist sourcefromlist util testbothhandlingfromlist importutil import if name main unittest main the use of fromlist influences what import returns if direct import statement is used the root module or package is returned import return but if fromlist is set then the specified module is actually returned whether it is a relative import or not from return import return from return using fromlist triggers different actions based on what is being asked of it if fromlist specifies an object on a module nothing special happens object case this is even true if the object does not exist bad object if a package is being imported then what is listed in fromlist may be treated as a module to be imported module and this extends to what is contained in __all__ when is imported using and does not need to be the only name in the fromlist using with others object case bad object module if a submodule causes an modulenotfounderror because it tries to import a module which doesn t exist that should let the modulenotfounderror propagate using using using with others
from test.test_importlib import util
import warnings
import unittest


class ReturnValue:

    

    def test_return_from_import(self):
        
        with util.mock_spec('pkg.__init__', 'pkg.module') as importer:
            with util.import_state(meta_path=[importer]):
                module = self.__import__('pkg.module')
                self.assertEqual(module.__name__, 'pkg')

    def test_return_from_from_import(self):
        
        with util.mock_spec('pkg.__init__', 'pkg.module')as importer:
            with util.import_state(meta_path=[importer]):
                module = self.__import__('pkg.module', fromlist=['attr'])
                self.assertEqual(module.__name__, 'pkg.module')


(Frozen_ReturnValue,
 Source_ReturnValue
 ) = util.test_both(ReturnValue, __import__=util.__import__)


class HandlingFromlist:

    

    def test_object(self):
        
        with util.mock_spec('module') as importer:
            with util.import_state(meta_path=[importer]):
                module = self.__import__('module', fromlist=['attr'])
                self.assertEqual(module.__name__, 'module')

    def test_nonexistent_object(self):
        
        with util.mock_spec('module') as importer:
            with util.import_state(meta_path=[importer]):
                module = self.__import__('module', fromlist=['non_existent'])
                self.assertEqual(module.__name__, 'module')
                self.assertFalse(hasattr(module, 'non_existent'))

    def test_module_from_package(self):
        
        with util.mock_spec('pkg.__init__', 'pkg.module') as importer:
            with util.import_state(meta_path=[importer]):
                module = self.__import__('pkg', fromlist=['module'])
                self.assertEqual(module.__name__, 'pkg')
                self.assertTrue(hasattr(module, 'module'))
                self.assertEqual(module.module.__name__, 'pkg.module')

    def test_nonexistent_from_package(self):
        with util.mock_spec('pkg.__init__') as importer:
            with util.import_state(meta_path=[importer]):
                module = self.__import__('pkg', fromlist=['non_existent'])
                self.assertEqual(module.__name__, 'pkg')
                self.assertFalse(hasattr(module, 'non_existent'))

    def test_module_from_package_triggers_ModuleNotFoundError(self):
        
        
        
        def module_code():
            import i_do_not_exist
        with util.mock_spec('pkg.__init__', 'pkg.mod',
                               module_code={'pkg.mod': module_code}) as importer:
            with util.import_state(meta_path=[importer]):
                with self.assertRaises(ModuleNotFoundError) as exc:
                    self.__import__('pkg', fromlist=['mod'])
                self.assertEqual('i_do_not_exist', exc.exception.name)

    def test_empty_string(self):
        with util.mock_spec('pkg.__init__', 'pkg.mod') as importer:
            with util.import_state(meta_path=[importer]):
                module = self.__import__('pkg.mod', fromlist=[''])
                self.assertEqual(module.__name__, 'pkg.mod')

    def basic_star_test(self, fromlist=['*']):
        
        with util.mock_spec('pkg.__init__', 'pkg.module') as mock:
            with util.import_state(meta_path=[mock]):
                mock['pkg'].__all__ = ['module']
                module = self.__import__('pkg', fromlist=fromlist)
                self.assertEqual(module.__name__, 'pkg')
                self.assertTrue(hasattr(module, 'module'))
                self.assertEqual(module.module.__name__, 'pkg.module')

    def test_using_star(self):
        
        self.basic_star_test()

    def test_fromlist_as_tuple(self):
        self.basic_star_test(('*',))

    def test_star_with_others(self):
        
        context = util.mock_spec('pkg.__init__', 'pkg.module1', 'pkg.module2')
        with context as mock:
            with util.import_state(meta_path=[mock]):
                mock['pkg'].__all__ = ['module1']
                module = self.__import__('pkg', fromlist=['module2', '*'])
                self.assertEqual(module.__name__, 'pkg')
                self.assertTrue(hasattr(module, 'module1'))
                self.assertTrue(hasattr(module, 'module2'))
                self.assertEqual(module.module1.__name__, 'pkg.module1')
                self.assertEqual(module.module2.__name__, 'pkg.module2')

    def test_nonexistent_in_all(self):
        with util.mock_spec('pkg.__init__') as importer:
            with util.import_state(meta_path=[importer]):
                importer['pkg'].__all__ = ['non_existent']
                module = self.__import__('pkg', fromlist=['*'])
                self.assertEqual(module.__name__, 'pkg')
                self.assertFalse(hasattr(module, 'non_existent'))

    def test_star_in_all(self):
        with util.mock_spec('pkg.__init__') as importer:
            with util.import_state(meta_path=[importer]):
                importer['pkg'].__all__ = ['*']
                module = self.__import__('pkg', fromlist=['*'])
                self.assertEqual(module.__name__, 'pkg')
                self.assertFalse(hasattr(module, '*'))

    def test_invalid_type(self):
        with util.mock_spec('pkg.__init__') as importer:
            with util.import_state(meta_path=[importer]), \
                 warnings.catch_warnings():
                warnings.simplefilter('error', BytesWarning)
                with self.assertRaisesRegex(TypeError, r'\bfrom\b'):
                    self.__import__('pkg', fromlist=[b'attr'])
                with self.assertRaisesRegex(TypeError, r'\bfrom\b'):
                    self.__import__('pkg', fromlist=iter([b'attr']))

    def test_invalid_type_in_all(self):
        with util.mock_spec('pkg.__init__') as importer:
            with util.import_state(meta_path=[importer]), \
                 warnings.catch_warnings():
                warnings.simplefilter('error', BytesWarning)
                importer['pkg'].__all__ = [b'attr']
                with self.assertRaisesRegex(TypeError, r'\bpkg\.__all__\b'):
                    self.__import__('pkg', fromlist=['*'])


(Frozen_FromList,
 Source_FromList
 ) = util.test_both(HandlingFromlist, __import__=util.__import__)


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