Skip to content

Instantly share code, notes, and snippets.

@moritz
Created April 4, 2022 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moritz/04d38b1d0ec9330592ef74648b40f8b0 to your computer and use it in GitHub Desktop.
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
#!/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())
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