Created
April 4, 2022 19:19
-
-
Save moritz/04d38b1d0ec9330592ef74648b40f8b0 to your computer and use it in GitHub Desktop.
Python: dynamically load a script (without .py) extension and mock things in it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# scrript being tested. Goal: patch out getpid | |
from os import getpid | |
def double_pid(): | |
return 2 * getpid() | |
if __name__ == '__main__': | |
print(double_pid()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from importlib.util import spec_from_loader, module_from_spec | |
from importlib.machinery import SourceFileLoader | |
spec = spec_from_loader("recalcitrant", SourceFileLoader("recalcitrant", "./recalcitrant")) | |
recalcitrant = module_from_spec(spec) | |
spec.loader.exec_module(recalcitrant) | |
from unittest.mock import patch | |
with patch.object(recalcitrant, 'getpid') as mock: | |
mock.return_value = 21 | |
print(recalcitrant.double_pid()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment