At the beginning of the script, I use platform.system
and platform.release
to determine which OS and version the script is running on (so it knows it's data is in Application Support on Mac, home on unix-like and non-mac unix, appdata on windows <= XP, and appdata/roaming on windows >= Vista). I'd like to test my series of if
s, elif
s, and else
s what determine the os and release, but I only have access to Mac 10.6.7, some unknown release of Linux, and Windows 7. Is there a way to feed platform
fake system and release information so I can be sure XP, Solaris, etc, would handle the script properly without having an installation?
4 に答える
Maybe something like
>>> platform.system = lambda: "whatever"
>>> platform.system()
'whatever'
You probably want to explore mocking platform
for your testing. Alternatively, you could directly monkey patch platform
, or even mess with sys.modules
directly to override the default platform
module, but mock is already designed to be self contained and also has the benefit of pretty clearly showing in your code what is and is not test instrumentation, so you don't accidentally get test functionality released in your production code.
you could create your initialization functions to take those variables as parameters so it is easy to spoof them in testing
For me, directly patching platform.system
with pytest-mock did not work. A simple trick though is to abstract the retrieval of this information in a utility function of your own (which you can successfully patch with pytest-mock this time).
Hence, in your implementation module/class:
def _get_system() -> str:
return platform.system().lower()
def _is_windows() -> bool:
return _get_system() == 'windows'
And in your test, here using pytest + pytest-mock:
def test_win_no_pad_code():
with patch('module_name._get_system', MagicMock(return_value='windows')):
assert module_name._is_windows()
This is one way of doing using module, but you can do the equivalent using a class instead.