formateu
formateu

Reputation: 167

Python, unit test, mock built-in/extension type class method

def testedFunction(param):
    try:
        dic = OrderedDict(...)
    except Exception:
        ...

I want to unit test exception, thrown inside given function, so in order to achieve this, I've tried to use unittest.mock.patch or unittest.mock.patch.object, both failed with :

TypeError: can't set attributes of built-in/extension type 'collections.OrderedDict'

I read some topics already and searched for tools like forbiddenfruit, but that seems to dont work at all neither.

How can I mock constructor of that kind of class?

Upvotes: 1

Views: 1653

Answers (1)

Maciej Małycha
Maciej Małycha

Reputation: 405

This worked for me. It patches class OrderedDict with mock and throws exception when object construction attempt calls the mock:

import collections
from unittest.mock import patch

def testedFunction(param):
    try:
        dic = collections.OrderedDict()
    except Exception:
        print("Exception!!!")


with patch('collections.OrderedDict') as mock:
    mock.side_effect = Exception()
    testedFunction(1)

when ran it displays:

python mock_builtin.py
Exception!!!

Process finished with exit code 0

For 'from collections import OrderedDict' syntax, imported class needs to be mocked. So, for module named mock_builtin.py following code gives same result:

from collections import OrderedDict
from unittest.mock import patch

def testedFunction(param):
    try:
        dic = OrderedDict()
    except Exception:
        print("Exception!!!")


with patch('mock_builtin.OrderedDict') as mock:
    mock.side_effect = Exception()
    testedFunction(1)

Upvotes: 1

Related Questions