Mocking module and all sub-modules before importCalling a function of a module by using its name (a string)How to import a module given the full path?Import a module from a relative pathHow to make mock to void methods with MockitoHow to upgrade all Python packages with pip?How do I list all files of a directory?What's the difference between a mock & stub?Module pytz was already importedError importing jpype modulePython Mock class import error

Should students have access to past exams or an exam bank?

Disease transmitted by postage stamps

When did J.K. Rowling decide to make Harry and Ginny a couple?

How to gracefully excuse yourself from a meeting due to emergencies such as a restroom break?

Can black block with a hanging piece in a back rank mate situation?

"DDoouubbllee ssppeeaakk!!"

Word for giving preference to the oldest child

Derivative is just speed of change?

Reasons for using monsters as bioweapons

What is the significance of $(logname)?

Can the additional attack from a Samurai's Rapid Strike have advantage?

How to structure presentation to avoid getting questions that will be answered later in the presentation?

Python π = 1 + (1/2) + (1/3) + (1/4) - (1/5) + (1/6) + (1/7) + (1/8) + (1/9) - (1/10) ...1748 Euler

If I buy and download a game through second Nintendo account do I own it on my main account too?

How do Canadians get a visa to go to Saudi Arabia?

Can living where magnetic ore is abundant provide any protection from cosmic radiation?

Skipping same old introductions

Password management for kids - what's a good way to start?

Error with uppercase in titlesec's label field

PI 4 screen rotation from the terminal

Is it really a problem to declare that a visitor to the UK is my "girlfriend", in terms of her successfully getting a Standard Visitor visa?

How do I safety check that there is no light in Darkroom / Darkbag?

Conflict between senior and junior members

How to derive trigonometric Cartesian equation from parametric



Mocking module and all sub-modules before import


Calling a function of a module by using its name (a string)How to import a module given the full path?Import a module from a relative pathHow to make mock to void methods with MockitoHow to upgrade all Python packages with pip?How do I list all files of a directory?What's the difference between a mock & stub?Module pytz was already importedError importing jpype modulePython Mock class import error






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am dealing with a codebase that has a large number of modules which instantiate database connections, read from registry, etc when they are imported. (Code in a main function or in a class, but in the global scope). I will call these modules 'bad modules'.



For reasons outside of the scope of this question, I need to be able to import other libraries ('good modules') relying on these libraries without failing, and my environment is such that these libraries will fail on import.



At the moment, I am doing this, where 'idmlib' is a bad module, and all of its children are bad modules:



sys.modules['idmlib'] = MagicMock()
sys.modules['idmlib.idmobject'] = Mock()
sys.modules['idmlib.idapi'] = Mock()
sys.modules['idmlib.database'] = Mock()
sys.modules['idmlib.plugins'] = Mock()
sys.modules['idmlib.plugins.authmod'] = Mock()

... other code ...


This works fine, but I need to predict every single child, grandchild, etc of idmlib which will be imported.



Instead, I would like to generically mock out idmlib and all of its sub-modules ahead of time, without needing to know what all of those sub-modules are.



Is there any way to make sys.modules['idmlib'] into a MagicMock whose sub-modules are all also MagicMocks?



My first thought is to have sys.modules be a mock wrapping the original sys.modules, which has some alternate behavior if it's being checked for something starting with 'idmlib' and otherwise just interacting with the original dictionary.



Unfortunately, this causes infinite recursion.



original_sys_modules = sys.modules
mock_sys_modules = MagicMock(wraps=original_sys_modules)


sys.modules = mock_sys_modules
import psutil


Error:



Traceback (most recent call last):
File "dryrun-script.py", line 26, in <module>
import psutil
File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
from . import _common
File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
from . import _common
File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
from . import _common
File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
from . import _common
File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
from . import _common
File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
from . import _common
File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
from . import _common
File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
from . import _common
...









share|improve this question
































    0















    I am dealing with a codebase that has a large number of modules which instantiate database connections, read from registry, etc when they are imported. (Code in a main function or in a class, but in the global scope). I will call these modules 'bad modules'.



    For reasons outside of the scope of this question, I need to be able to import other libraries ('good modules') relying on these libraries without failing, and my environment is such that these libraries will fail on import.



    At the moment, I am doing this, where 'idmlib' is a bad module, and all of its children are bad modules:



    sys.modules['idmlib'] = MagicMock()
    sys.modules['idmlib.idmobject'] = Mock()
    sys.modules['idmlib.idapi'] = Mock()
    sys.modules['idmlib.database'] = Mock()
    sys.modules['idmlib.plugins'] = Mock()
    sys.modules['idmlib.plugins.authmod'] = Mock()

    ... other code ...


    This works fine, but I need to predict every single child, grandchild, etc of idmlib which will be imported.



    Instead, I would like to generically mock out idmlib and all of its sub-modules ahead of time, without needing to know what all of those sub-modules are.



    Is there any way to make sys.modules['idmlib'] into a MagicMock whose sub-modules are all also MagicMocks?



    My first thought is to have sys.modules be a mock wrapping the original sys.modules, which has some alternate behavior if it's being checked for something starting with 'idmlib' and otherwise just interacting with the original dictionary.



    Unfortunately, this causes infinite recursion.



    original_sys_modules = sys.modules
    mock_sys_modules = MagicMock(wraps=original_sys_modules)


    sys.modules = mock_sys_modules
    import psutil


    Error:



    Traceback (most recent call last):
    File "dryrun-script.py", line 26, in <module>
    import psutil
    File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
    from . import _common
    File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
    from . import _common
    File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
    from . import _common
    File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
    from . import _common
    File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
    from . import _common
    File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
    from . import _common
    File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
    from . import _common
    File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
    from . import _common
    ...









    share|improve this question




























      0












      0








      0








      I am dealing with a codebase that has a large number of modules which instantiate database connections, read from registry, etc when they are imported. (Code in a main function or in a class, but in the global scope). I will call these modules 'bad modules'.



      For reasons outside of the scope of this question, I need to be able to import other libraries ('good modules') relying on these libraries without failing, and my environment is such that these libraries will fail on import.



      At the moment, I am doing this, where 'idmlib' is a bad module, and all of its children are bad modules:



      sys.modules['idmlib'] = MagicMock()
      sys.modules['idmlib.idmobject'] = Mock()
      sys.modules['idmlib.idapi'] = Mock()
      sys.modules['idmlib.database'] = Mock()
      sys.modules['idmlib.plugins'] = Mock()
      sys.modules['idmlib.plugins.authmod'] = Mock()

      ... other code ...


      This works fine, but I need to predict every single child, grandchild, etc of idmlib which will be imported.



      Instead, I would like to generically mock out idmlib and all of its sub-modules ahead of time, without needing to know what all of those sub-modules are.



      Is there any way to make sys.modules['idmlib'] into a MagicMock whose sub-modules are all also MagicMocks?



      My first thought is to have sys.modules be a mock wrapping the original sys.modules, which has some alternate behavior if it's being checked for something starting with 'idmlib' and otherwise just interacting with the original dictionary.



      Unfortunately, this causes infinite recursion.



      original_sys_modules = sys.modules
      mock_sys_modules = MagicMock(wraps=original_sys_modules)


      sys.modules = mock_sys_modules
      import psutil


      Error:



      Traceback (most recent call last):
      File "dryrun-script.py", line 26, in <module>
      import psutil
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      ...









      share|improve this question
















      I am dealing with a codebase that has a large number of modules which instantiate database connections, read from registry, etc when they are imported. (Code in a main function or in a class, but in the global scope). I will call these modules 'bad modules'.



      For reasons outside of the scope of this question, I need to be able to import other libraries ('good modules') relying on these libraries without failing, and my environment is such that these libraries will fail on import.



      At the moment, I am doing this, where 'idmlib' is a bad module, and all of its children are bad modules:



      sys.modules['idmlib'] = MagicMock()
      sys.modules['idmlib.idmobject'] = Mock()
      sys.modules['idmlib.idapi'] = Mock()
      sys.modules['idmlib.database'] = Mock()
      sys.modules['idmlib.plugins'] = Mock()
      sys.modules['idmlib.plugins.authmod'] = Mock()

      ... other code ...


      This works fine, but I need to predict every single child, grandchild, etc of idmlib which will be imported.



      Instead, I would like to generically mock out idmlib and all of its sub-modules ahead of time, without needing to know what all of those sub-modules are.



      Is there any way to make sys.modules['idmlib'] into a MagicMock whose sub-modules are all also MagicMocks?



      My first thought is to have sys.modules be a mock wrapping the original sys.modules, which has some alternate behavior if it's being checked for something starting with 'idmlib' and otherwise just interacting with the original dictionary.



      Unfortunately, this causes infinite recursion.



      original_sys_modules = sys.modules
      mock_sys_modules = MagicMock(wraps=original_sys_modules)


      sys.modules = mock_sys_modules
      import psutil


      Error:



      Traceback (most recent call last):
      File "dryrun-script.py", line 26, in <module>
      import psutil
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      File "C:Usersdanie01.AD.virtualenvsrobotframework-O8sDx-L-libsite-packagespsutil__init__.py", line 41, in <module>
      from . import _common
      ...






      python mocking python-unittest






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 26 at 23:57







      Daniel Paczuski Bak

















      asked Mar 26 at 23:41









      Daniel Paczuski BakDaniel Paczuski Bak

      1,0011 gold badge11 silver badges36 bronze badges




      1,0011 gold badge11 silver badges36 bronze badges

























          0






          active

          oldest

          votes










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55367732%2fmocking-module-and-all-sub-modules-before-import%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes




          Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.







          Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55367732%2fmocking-module-and-all-sub-modules-before-import%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현