Python单元测试模拟:从导入的类引发异常

时间:2019-03-18 21:03:31

标签: python unit-testing exception mocking

当我运行单元测试时,我希望从自动保存脚本中的 transaction.AutoSave.save()(导入)抛出 OperationalError 异常,但不会抛出异常。例外,即使我没有捕获到 OperationalError 例外,它也只是通过了测试。我在模拟对象时做错什么了吗?我尝试了mock_request.return_valuemock_request.side_effectmock_request.return_value.side_effect,但没有一个起作用。为了清晰起见,代码仅是部分代码。

自动保存脚本的单元测试:

from django.db.utils import OperationalError
from mock import patch

class CommandsTestCase(TestCase):

    class FakeResponse(object):

        def __init__(self, content, should_raise=False):
            self.content = content
            self.should_raise = should_raise

        def raise_for_status(self):
            if self.should_raise:
                raise OperationalError('TEST: This exception is raised to mock a Database failure.')

    def test_autosave(self):
        with patch('folder.apps.AutoSave.AutoSave.save') as mock_request:
            mock_request.return_value = self.FakeResponse(content='', should_raise=True)
            call_command('autosave')

autosave.py脚本

from isc_utils.commands import MyCommand
from isc_utils.db import queryset_iterator
from folder.apps.folder.models import Transaction
from folder.apps.AutoSave import AutoSave

class Command(MyCommand):
    def run(self, *args, **kwargs):
        upload_dt = datetime.datetime.now()
        qs = Transaction.objects.filter(
            upload_datetime__gte=upload_dt
        )
        for transaction in queryset_iterator(qs):
            transaction_id = transaction.id

            try:
                transaction.AutoSave.save()
            except (ValidationError, ResourceNotFound):
                self.logger.error('autosave failed RID %s', transaction.id, exc_info=True)
                continue

0 个答案:

没有答案