python: mock a module

后端 未结 4 1093
故里飘歌
故里飘歌 2020-12-03 11:09

Is it possible to mock a module in python using unittest.mock? I have a module named config, while running tests I want to mock it by another modul

4条回答
  •  孤城傲影
    2020-12-03 11:48

    If you're always accessing the variables in config.py like this:

    import config
    ...
    config.VAR1
    

    You can replace the config module imported by whatever module you're actually trying to test. So, if you're testing a module called foo, and it imports and uses config, you can say:

    from mock import patch
    import foo
    import config_test
    ....
    with patch('foo.config', new=config_test):
       foo.whatever()
    

    But this isn't actually replacing the module globally, it's only replacing it within the foo module's namespace. So you would need to patch it everywhere it's imported. It also wouldn't work if foo does this instead of import config:

    from config import VAR1
    

    You can also mess with sys.modules to do this:

    import config_test
    import sys
    sys.modules["config"] = config_test
    # import modules that uses "import config" here, and they'll actually get config_test
    

    But generally it's not a good idea to mess with sys.modules, and I don't think this case is any different. I would favor all of the other suggestions made over it.

提交回复
热议问题