Python mockito library spy2 not working with builtins.open

Viewed 29

found something strange.

The basic behavior of mockito permits to use spy2 on a function to mock the method only for specified arguments.

Example :

mockito.spy2(os.path.exists)
mockito.when(os.path).exists('.flake8').thenReturn("mdr")

print(os.path.exists("folder_that_doesnt_exist"))
print(os.path.exists(".flake8"))
mockito.unstub()

Return False and then True as expected. The behavior of os.path.exists is the normal behavior if the parameters is not ".flake8".

But if I try to do the same with builtins.open:

mockito.spy2(builtins.open)
mockito.when(builtins).open("not_existing_file.csv").thenReturn("test")

print(builtins.open("not_existing_file.csv"))
print(builtins.open("__init__.py"))
mockito.unstub()

I would expect __init__.py to be open as normal. Instead, this error is thrown :

   mockito.invocation.InvocationError: 
   Called but not expected:
   
       open('__init__.py')
   
   Stubbed invocations are:
   
       open('not_existing_file.csv')

Mockito seems to expect builtins.open("_init_.py") to be mocked too .

Do you know what cause the issue ? Thanks a lot !

1 Answers

May be a bug (if it is doable) or a limitation because builtins are usually hard. builtins.open actually points to _io.open. After spy2(builtins.open), builtins.open is unpatched but _io.open is.

Surprisingly spy2('builtins.open') does what you want.

Related