A.J.
A.J.

Reputation: 9025

Mock Django Commands class variable in UnitTests

I am not able to successfully mock pasue_time and max_tries in the command. Suggestions please.

Command

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')

Test

@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)

Upvotes: 0

Views: 769

Answers (1)

Ilya Tikhonov
Ilya Tikhonov

Reputation: 1429

To mock properties, you should use 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

Upvotes: 3

Related Questions