Question

Mocks obtained from unittest.mock.create_autospec() do not seem to be performing argument checking for some functions. For example, consider the following code (I used CPython 3.4.0):

import os
from unittest.mock import create_autospec

def os_chdir(dir): # The same signature as os.chdir().
    pass

m1 = create_autospec(os_chdir)
m1('first', 'second') # Raises TypeError: too many positional arguments.

m2 = create_autospec(os.chdir)
m2('first', 'second') # Passes without an exception...

Why m1 correctly checks the argument count but m2 does not? The same situation is for other functions that identify themselves as built-in function when printed in an interactive session. The documentation does not seem to mention such situations.

Was it helpful?

Solution

From what I have found, the answer probably lies in the following:

import inspect

print(inspect.getfullargspec(os_chdir))
# Prints FullArgSpec(args=['dir'], varargs=None, varkw=None, defaults=None,
#                    kwonlyargs=[], kwonlydefaults=None, annotations={})

print(inspect.getfullargspec(os.chdir))
# Raises ValueError: no signature found for builtin <built-in function chdir>

That is, unittest.mock.create_autospec() has no way of finding the signature for such built-in functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top