Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Suppose I have files main.py and common.py in my root directory. 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.

common.py contains the following:

def hello():
  print("hello")

main.py contains the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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? For instance, I’d like to monkey patch hello to print out goodbye.

>Solution :

Pretty straightforward:

import common

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

import main
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading