Comment

Alec Munro

We've hit things like this a lot. What we decided to do was make the os module a dependency of our object.

So:

def __init__(self, ..., os_mod=os):
...
self.os = os_mod

def method_that_uses_os:
self.os.stat(...)

This can then easily be injected when creating your test objects, and used in your tests (we use mocker for mocking, but the pattern applies pretty much universally).

def test_method_that_uses_os(self):
m_os = self.mocker.mock()
test_obj = SomeObj(..., os_mod=m_os)

m_os.stat(...)

self.mocker.replay()
test_obj.method_that_uses_os()

The only particular annoyance to this method is that the dependency list can get quite long. But it does keep things very explicit. :)