0

I am trying to use unittest.mock.MagicMock to mock an API. I am not understanding to how check the arguments passed to a method on a mocked object. I thought that this should work:

from unittest import mock

import unittest

class TestMock(unittest.TestCase):
    def setUp(self):
        pass

    def test_basic(self):
        obj = unittest.mock.MagicMock()
        obj.update(1,2,a=3)

        print("obj.update: ", obj.update)
        print("obj.update.call_args: ", obj.update.call_args)
        print("obj.update.call_args.args: ", obj.update.call_args.args)

        self.assertEqual((1,2), obj.update.call_args.args)

However, pytest test_mock.py fails:

test_mock.py:17: AssertionError
------------------------------------------------ Captured stdout call ------------------------------------------------
obj.update:  <MagicMock name='mock.update' id='140707024533072'>
obj.update.call_args:  call(1, 2, a=3)
obj.update.call_args.args:  args
============================================== short test summary info ===============================================
FAILED test_mock.py::TestMock::test_basic - AssertionError: (1, 2) != args
================================================= 1 failed in 0.10s ==================================================

The docs say that I should be able to access the positional args via the call_args.args, but that seems to be creating a mocked field instead. What is the correct way to verify the arguments?

Troy Daniels
  • 3,270
  • 2
  • 25
  • 57
  • I can't reproduce this. Ran your exact code in the REPL and `obj.update.call_args.args` is `(1, 2)`. What is this `args` object that you've got? It's not a mock object, and I don't think it's a string either. I'd be very curious what `type(obj.update.call_args.args)` shows. – Samwise Apr 15 '22 at 15:02
  • `type(obj.update.call_args.args): `. I figured out the problem. `args` and `kwargs` were added in 3.8 and this project is using 3.7. – Troy Daniels Apr 15 '22 at 15:47
  • 1
    Does this answer your question? [How do I correctly use mock call\_args with Python's unittest.mock?](https://stackoverflow.com/questions/60105443/how-do-i-correctly-use-mock-call-args-with-pythons-unittest-mock). Ah - I see you already found it. – MrBean Bremen Apr 15 '22 at 15:47

1 Answers1

0

The args and kwargs values were introduce in Python 3.8. This behavior is seen when using Python 3.7 or earlier.

Troy Daniels
  • 3,270
  • 2
  • 25
  • 57