'How can I mock the value of sys.platform in python
My aim is to mock the value of sys.platform in python to be linux instead of win32 for my unittests. I found that some people use mock.patch but that does not change the value of sys.platform for the rest of execution of the python session.
Is there any way to mock that value for ever in the python session?
Thanks
Solution: I found the solution to this problem. The issue was that I was mocking sys.platform in one script and in another I was importint platform from sys. That is not the same thing for python and I was getting another value for the platform.
The way I solved this was by mocing the whole path to platform: module_1.submodule_1.platform = mock.MagicMock(return_value='whatever')
Solution 1:[1]
Hope this is what you are looking for, here is how I was able to mock the platform (running on Mac):
myfunc.py
import sys
# function that I am testing
def print_os():
if sys.platform == "win32":
return "We are Windows"
elif sys.platform == "darwin":
return "We are Darwin"
elif sys.platform == "linux":
return "We are Linux"
myfunc_test.py
import unittest
from unittest.mock import patch
import myfunc
@patch('sys.platform', 'linux')
class TestOS(unittest.TestCase):
def test_print_os(self):
self.assertEqual(myfunc.print_os(), "We are Linux")
if __name__ == '__main__':
unittest.main()
testing:
$ python -m unittest -v myfunc_test.py
test_print_os (main_test.TestOS) ... ok
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jabbson |
