jeudi 5 novembre 2020

Patch a deeply nested method call only

In my function to test I have code like this:

task = TransferTask.objects.get(id=id) # a Django database access
source_connector = task.job.source.server.create_connector()
dest_connector = task.job.destination.server.create_connector()

What I want is to patch only the create_connector method call to return a fake object. But I want to return different fake objects for source_connector and dest_connector, that's why patch.object(MyServerClass, "create_connector", return_value=my_fake_connector) does not work out as both would end up with the same fake object.

I tried something like patch("my_module.TransferTask.job.source.server.create_connector", return_value=my_fake_source_connector), but I get an error that there is no attribute source (maybe because it is a related Django model?!).

I also want to retain the real objects of task, job, source and server, and only patch the create_connector method of server, as those others are called in other parts of the function to test and must keep their functionality.

So, what is the best way to patch it?

Aucun commentaire:

Enregistrer un commentaire