简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM