Patching __name__ in test

Viewed 33

I do understand that you can write this in other and maybe better ways - such as moving the logic outside of __name__ == "__main__" blocks. I am trying to understand íf you can write it like this.

print(__name__)  # This will print "entrypoint"
if __name__ == "__main__":
   print("Success")  # I would like to execute this line in my test
from unittest.mock import patch
def test_entrypoint():
   with patch("entrypoint.__name__", "__main__"):
            import entrypoint
            print(entrypoint.__name__)  # this will print correct

I also tried to use entrypoint._entrypoint__name__ to check if name wrangling is the source, but that also doesn't cut it.

This post suggest some options. It suggested the patch, which doesn't work. It also discusses why:

The problem with the import statement is that the test for 'main' runs as part of the import statement before you get a chance to assign to runpy.name.

But if I try the solution there (which was using imp now replaced by importlib, I am still not able to patch __name__.:

import importlib
module = importlib.import_module("__main__", "entrypoint")
0 Answers
Related