Old question but still #1 on searches, so wanted to give my take. The accepted answer does not work if sys
is imported by the package which is to be tested.
I used the following to change the value of sys.platform
in a tested package:
import unittest
import sys
from unittest import mock
class TestSystemCheck(unittest.TestCase):
"""Test the mypackage import"""
def tearDown(self):
"""Clean up after each test"""
for key in ['mypackage', 'mypackage._mypackage', 'mypackage._system_check']:
if key in sys.modules:
del sys.modules[key]
def test_check(self):
import mypackage
mypackage.MyClass()
@mock.patch('sys.platform', 'unsupported_platform')
def test_check_fail(self):
with self.assertRaises(RuntimeError):
import mypackage
mypackage.MyClass()
In the example the import will fail on an unsupported platform. Note that un-importing the hidden modules of mypackage
is needed to trigger a fresh import in each test.
sys.platform
should probably be mocked by a mock object instead of a plain string, but I could not get that to work.