如何测试OperationFailure异常代码?

时间:2014-04-12 17:31:05

标签: python mocking pymongo nose python-unittest

这是需要测试的代码:

from pymongo.errors import OperationFailure

try:
    _id = self.collection.save(something)
    if _id is not None:
        return Result(RESULT_OK)
# What i need to test starts here
except OperationFailure as e:
    print "OperationFailure : code=" + e.code + ", details=" + e.details
    result = Result(RESULT_ERROR, MESSAGE)
# ends here

测试:

from pymongo.errors import OperationFailure
from mock import patch
import nose.tools

def test_save_fails_if_operation_failure(self):
    handler = Whatever()
    with patch.object(handler, "_save") as _save_mock:
        with nose.tools.assert_raises(OperationFailure) as cm:
            _save_mock.side_effect = OperationFailure(0, code=1, details="message")
            handler._save({'key': 'value'})
    ex = cm.exception
    self.assertEqual(ex.code, 1, 'OperationFailure code')
    self.assertEqual(ex.details, "message", 'OperationFailure sent a message')
    handler._close()

测试通过,但是在覆盖范围内,您会看到3条线未被覆盖。 如果您对3行进行注释,则测试也会通过。

0 个答案:

没有答案