I am new to Django and unit tests, so any feedback is very helpful.
I built a small integration with a third party to create a matching account in their system whenever an account is created in our system. I do this on a signal in the model class. The signal is simple and looks like this:
@receiver(post_save, sender=Company)
def create_integration_company(sender, instance, created, **kwargs):
if created:
company_integration_id = third_party.create_crm_company(instance)
instance.integration_id = company_integration_id
instance.save()
When I ran our tests, it created thousands of accounts in this third party's system, so I discovered mock
.
We have a bunch of tests that create companies and I was wondering if I have to add this to every one of them? @mock.patch("apps.accounts.utils.build_request", return_value="123")
My question is: at which level should I mock the response and just return 123
for the new integration id? Can I do it at the model level? Or do I have to do this for every test case we have?
CodePudding user response:
Mocking will work but the better option would be to disconnect the signals for the unit tests. Please see https://docs.djangoproject.com/en/4.0/topics/signals/#disconnecting-signals on how to disconnect signal. You can create a test-only mixin which you can include in your test suite. Ideally, you can do this in mixin's init or setUpClass. Say the mixin is SignalDisconnector, which you will use as:
class TestSuite(TestCase, SignalDisconnector)
This will only test the behavior which you are intending in the test suite without experiencing any side effects.