简体   繁体   English

Mocking 没有 `if __name__=="__main__":` 块的脚本

[英]Mocking a script with no `if __name__=="__main__":` block

Suppose I have files main.py and common.py in my root directory.假设我的根目录中有文件main.pycommon.py These represent third party modules which I would not like to touch for the time being.这些代表我暂时不想接触的第三方模块。 Suppose I also have a test.py file which I'd like to use to test main.py .假设我还有一个test.py文件,我想用它来测试main.py

common.py contains the following: common.py包含以下内容:

def hello():
  print("hello")

main.py contains the following: main.py包含以下内容:

from common import hello

hello()

Is there a way to monkey patch the hello function in test.py such that importing main.py will use the mocked function?有没有办法在test.py中修补hello function 以便导入main.py将使用模拟的 function? For instance, I'd like to monkey patch hello to print out goodbye .例如,我想用猴子补丁hello打印出goodbye

Pretty straightforward:很简单:

import common

common.hello = lambda: print("goodbye")

import main

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM