模块Django命令UnitTests中的类变量

时间:2016-03-23 09:50:39

标签: python django unit-testing testing

我无法在命令中成功模拟pasue_timemax_tries。建议请。

命令

class Command(BaseCommand):
    """Update seat expire dates."""

    help = 'Fooo'
    pause_time = 5
    max_tries = 5

    def handle(self, *args, **options):
        if self.max_tries < tries:
            logger.error('error')

测试

@mock.patch('foo.bar.path.to.file.Command.max_tries')
def test_update_course_with_exception(self, param):
    param = 1

    expected = [
        # some information which is logged by management command
    ]
    with LogCapture(LOGGER_NAME) as lc:
        call_command('foo_command_name_bar')
        lc.check(*expected)

1 个答案:

答案 0 :(得分:2)

要模拟属性,您应该使用PropertyMock

class MyTestCase(TestCase):
    @mock.patch('app.management.commands.cmd.Command.max_tries', new_callable=mock.PropertyMock)
    def test_update_course_with_exception(self, max_tries_mock):
        max_tries_mock.return_value = 1

https://docs.python.org/3/library/unittest.mock.html#unittest.mock.PropertyMock