{
  "$type": "site.standard.document",
  "canonicalUrl": "https://rednafi.com/python/partially-assert-callable-arguments/",
  "description": "Assert specific mock call arguments while ignoring others using unittest.mock.ANY for flexible test assertions without brittle checks.",
  "path": "/python/partially-assert-callable-arguments/",
  "publishedAt": "2022-07-17T00:00:00.000Z",
  "site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
  "tags": [
    "Python",
    "Testing"
  ],
  "textContent": "I just found out that you can use Python's unittest.mock.ANY to make assertions about\ncertain arguments in a mock call, without caring about the other arguments. This can be\nhandy if you want to test how a callable is called but only want to make assertions about\nsome arguments. Consider the following example:\n\nLet's say we only want to test the process function. But process ultimately depends on\nthe fetch function, which has multiple side effects - it returns pseudo-random values and\nwaits for 2 seconds on a fictitious network call. Since we only care about process, we'll\nmock the other two functions. Here's how unittest.mock.ANY can make life easier:\n\nWhile this is a simple example, I found ANY to be quite useful while making assertions\nabout callables that accept multiple complex objects as parameters. Being able to ignore\nsome aruments while calling mock_callable.assert_called_with() can make the tests more\ntractable.\n\nUnder the hood, the implementation of ANY is quite simple. It's an instance of a class\nthat defines __eq__ and __ne__ in a way that comparing any value with ANY will return\nTrue. Here's the full implementation:\n\nIt always returns True whenever compared with some value:\n\nFurther reading\n\n- [unittest.mock.ANY]\n- [ANY in the wild]\n\n\n\n\n[unittest.mock.ANY]:\n    https://docs.python.org/3/library/unittest.mock.html#any\n\n[any in the wild]:\n    https://github.com/rednafi/example-rq-sentry/blob/9630e8ae31197fea6606a1972a108fa70de8b331/tests/test_tasks.py#L19",
  "title": "Partially assert callable arguments with 'unittest.mock.ANY'"
}