#NEWLINE# @ contextmanager #NEWLINE# def mock_module( * names ) : #NEWLINE# #INDENT# prev = { #NEWLINE# #INDENT# #NEWLINE# #UNINDENT# } #NEWLINE# class MockModule ( ModuleType ) : #NEWLINE# #INDENT# def __getattr__( self , attr ) : #NEWLINE# #INDENT# setattr ( self , attr , Mock ( ) ) #NEWLINE# return ModuleType . __getattribute__ ( self , attr ) #NEWLINE# #UNINDENT# #UNINDENT# mods = [ ] #NEWLINE# for name in names : #NEWLINE# #INDENT# try : #NEWLINE# #INDENT# prev [ name ] = sys . modules [ name ] #NEWLINE# #UNINDENT# except KeyError : #NEWLINE# #INDENT# pass #NEWLINE# #UNINDENT# mod = sys . modules [ name ] = MockModule ( name ) #NEWLINE# mods . append ( mod ) #NEWLINE# #UNINDENT# try : #NEWLINE# #INDENT# ( yield mods ) #NEWLINE# #UNINDENT# finally : #NEWLINE# #INDENT# for name in names : #NEWLINE# #INDENT# try : #NEWLINE# #INDENT# sys . modules [ name ] = prev [ name ] #NEWLINE# #UNINDENT# except KeyError : #NEWLINE# #INDENT# try : #NEWLINE# #INDENT# del sys . modules [ name ] #NEWLINE# #UNINDENT# except KeyError : #NEWLINE# #INDENT# pass