test apispecific details for import e g raising the right exception when passing in an int for the module name def testraisesmodulenotfounderrorself with self assertraisesmodulenotfounderror util importimportlib some module that does not exist def testnamerequiresrparitionself raise typeerror if a nonstring is passed in for the module name with self assertraisestypeerror self import42 def testnegativelevelself raise valueerror when a negative level is specified pep 328 did away with sys module none entries and the ambiguity of absoluterelative imports with self assertraisesvalueerror self import os globals level1 def testnonexistentfromlistentryself if something in fromlist doesn t exist that s okay issue15715 mod types moduletypepkgname mod path xxx with util importstatemetapathself badfinderloader with util uncachepkgname sys modulespkgname mod self importpkgname fromlist not here def testfromlistloaderrorpropagatesself if something in fromlist triggers an exception not related to not existing let that exception propagate issue15316 mod types moduletypepkgname mod path xxx with util importstatemetapathself badfinderloader with util uncachepkgname sys modulespkgname mod with self assertraisesimporterror self importpkgname fromlistsubmodname rpartition 1 def testblockedfromlistself if fromlist entry is none let a modulenotfounderror propagate issue31642 mod types moduletypepkgname mod path with util importstatemetapathself badfinderloader with util uncachepkgname submodname sys modulespkgname mod sys modulessubmodname none with self assertraisesmodulenotfounderror as cm self importpkgname fromlistsubmodname rpartition 1 self assertequalcm exception name submodname class oldapitestsapitest badfinderloader badloaderfinder def testraisesmodulenotfounderrorself with warnings catchwarnings warnings simplefilterignore importwarning super testraisesmodulenotfounderror def testnamerequiresrparitionself with warnings catchwarnings warnings simplefilterignore importwarning super testnamerequiresrparition def testnegativelevelself with warnings catchwarnings warnings simplefilterignore importwarning super testnegativelevel def testnonexistentfromlistentryself with warnings catchwarnings warnings simplefilterignore importwarning super testnonexistentfromlistentry def testfromlistloaderrorpropagatesself with warnings catchwarnings warnings simplefilterignore importwarning super testfromlistloaderrorpropagates def testblockedfromlistself with warnings catchwarnings warnings simplefilterignore importwarning super testblockedfromlist frozenoldapitests sourceoldapitests util testbotholdapitests importutil import class specapitestsapitest badfinderloader badspecfinderloader frozenspecapitests sourcespecapitests util testbothspecapitests importutil import if name main unittest main test api specific details for __import__ e g raising the right exception when passing in an int for the module name raise typeerror if a non string is passed in for the module name raise valueerror when a negative level is specified pep 328 did away with sys module none entries and the ambiguity of absolute relative imports if something in fromlist doesn t exist that s okay issue15715 if something in fromlist triggers an exception not related to not existing let that exception propagate issue15316 if fromlist entry is none let a modulenotfounderror propagate issue31642
from test.test_importlib import util

from importlib import machinery
import sys
import types
import unittest
import warnings

PKG_NAME = 'fine'
SUBMOD_NAME = 'fine.bogus'


class BadSpecFinderLoader:
    @classmethod
    def find_spec(cls, fullname, path=None, target=None):
        if fullname == SUBMOD_NAME:
            spec = machinery.ModuleSpec(fullname, cls)
            return spec

    @staticmethod
    def create_module(spec):
        return None

    @staticmethod
    def exec_module(module):
        if module.__name__ == SUBMOD_NAME:
            raise ImportError('I cannot be loaded!')


class BadLoaderFinder:
    @classmethod
    def load_module(cls, fullname):
        if fullname == SUBMOD_NAME:
            raise ImportError('I cannot be loaded!')


class APITest:

    

    def test_raises_ModuleNotFoundError(self):
        with self.assertRaises(ModuleNotFoundError):
            util.import_importlib('some module that does not exist')

    def test_name_requires_rparition(self):
        
        with self.assertRaises(TypeError):
            self.__import__(42)

    def test_negative_level(self):
        
        
        
        with self.assertRaises(ValueError):
            self.__import__('os', globals(), level=-1)

    def test_nonexistent_fromlist_entry(self):
        
        
        mod = types.ModuleType(PKG_NAME)
        mod.__path__ = ['XXX']
        with util.import_state(meta_path=[self.bad_finder_loader]):
            with util.uncache(PKG_NAME):
                sys.modules[PKG_NAME] = mod
                self.__import__(PKG_NAME, fromlist=['not here'])

    def test_fromlist_load_error_propagates(self):
        
        
        
        mod = types.ModuleType(PKG_NAME)
        mod.__path__ = ['XXX']
        with util.import_state(meta_path=[self.bad_finder_loader]):
            with util.uncache(PKG_NAME):
                sys.modules[PKG_NAME] = mod
                with self.assertRaises(ImportError):
                    self.__import__(PKG_NAME,
                                    fromlist=[SUBMOD_NAME.rpartition('.')[-1]])

    def test_blocked_fromlist(self):
        
        
        mod = types.ModuleType(PKG_NAME)
        mod.__path__ = []
        with util.import_state(meta_path=[self.bad_finder_loader]):
            with util.uncache(PKG_NAME, SUBMOD_NAME):
                sys.modules[PKG_NAME] = mod
                sys.modules[SUBMOD_NAME] = None
                with self.assertRaises(ModuleNotFoundError) as cm:
                    self.__import__(PKG_NAME,
                                    fromlist=[SUBMOD_NAME.rpartition('.')[-1]])
                self.assertEqual(cm.exception.name, SUBMOD_NAME)


class OldAPITests(APITest):
    bad_finder_loader = BadLoaderFinder

    def test_raises_ModuleNotFoundError(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ImportWarning)
            super().test_raises_ModuleNotFoundError()

    def test_name_requires_rparition(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ImportWarning)
            super().test_name_requires_rparition()

    def test_negative_level(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ImportWarning)
            super().test_negative_level()

    def test_nonexistent_fromlist_entry(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ImportWarning)
            super().test_nonexistent_fromlist_entry()

    def test_fromlist_load_error_propagates(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ImportWarning)
            super().test_fromlist_load_error_propagates

    def test_blocked_fromlist(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ImportWarning)
            super().test_blocked_fromlist()


(Frozen_OldAPITests,
 Source_OldAPITests
 ) = util.test_both(OldAPITests, __import__=util.__import__)


class SpecAPITests(APITest):
    bad_finder_loader = BadSpecFinderLoader


(Frozen_SpecAPITests,
 Source_SpecAPITests
 ) = util.test_both(SpecAPITests, __import__=util.__import__)


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