with mock.patch('os.listdir'):
will always work, even if it doesn't accomplish what you want. with mock.patch('mymodule.os.listdir')
will fail if that module does not explicitly import os and instead does something like from os import listdir (perhaps because a later dev did not realize importing os directly was actually a requirement for the test and changed the code). ImportError: No module named os
This can be fixed with e.g., assert hasattr(module, 'os'), "os module is not explicitly imported"
as a preamble to your test but ... it is not perfect by any means.
https://pypi.org/project/ConfigArgParse/