How can I mock exists() for certain paths only while making it do the real thing for any other path?
For example the class under test will call exists() and would fail on the paths that were supplied to it, because they do not exist on the system where the tests are running.
With Mox one could completely stub out exists(), but this would make the test fail because calls not related to the class under test will not act in the real way.
I guess I could use WithSideEffects() to call my own function when exists() is being called branching the call in two directions, but how can I access the original exists()?
This is what I have so far:
def test_with_os_path_exists_partially_mocked(self):
self.mox.StubOutWithMock(os.path, 'exists')
def exists(path):
if not re.match("^/test-path.*$", path):
return call_original_exists_somehow(path)
else:
# /test-path should always exist
return True
os.path.exists(mox.Regex("^.*$")).MultipleTimes().WithSideEffects(exists)
self.mox.ReplayAll()
under_test.run()
self.mox.VerifyAll()
Mox internally uses "Stubout" for the actual stubbing:
Stubout saves the stub in an internal collection:
Since the return value of intermediate calls is cached in the mocked method object, it has to be reset in a side effect callback.
When a method mock is being created, it will be pushed to will be stored in
_expected_calls_queue. In replay mode, an expected call is repesented by aMultipleTimesGroupinstance which will track calls to each method referenced in_methods.So, one can refer to the origial method by navigating
Mox.stubs.cache.This example will mock
exists()passing through calls to the original function if they do not start with/test-path, any other call will always returnTrue.