3

I have been using patch.object(obj, attribute) to patch an attribute of obj:

with patch.object(StorageSaver, 'save_listing'):
    ImportJob.objects.import_feed(feed.id)

but is there a way to patch the whole obj? Eg.

with patch.object(StorageSaver):
    ...
James Lin
  • 25,028
  • 36
  • 133
  • 233
  • The fact that it's `StorageSaver` instead of `some_module.StorageSaver` here suggests that you might be trying to do this from inside the module that defines `StorageSaver`, in which case this probably isn't a unit test and you *really* shouldn't be using `patch` at all. Alternatively, maybe you used a `from` import, in which case you should just not use `from` imports for this thing. – user2357112 Jul 06 '16 at 21:48
  • It's indeed a unittest, I originally used patch 'module.StorageSaver' whilst it worked on that particular test case, when I run the whole test suite, it didn't work because some other module imports affected it, I have not wrapped my mind around it yet, but the test suite works when I explicitly imported `StorageSaver` and patch it's attributes. – James Lin Jul 06 '16 at 21:57
  • Sounds like the other modules are using `StorageSaver` in a way that doesn't play well with patching. It could be something as simple as those modules importing it with a `from` import, or it could be that they need to do some static initialization that uses `StorageSaver` and won't pick up any attempts to replace it. There's no way to use `patch` to outright replace an object with a mock; you can only replace specific references. – user2357112 Jul 06 '16 at 22:04
  • ok, thank you for the info, I will have another look at how other modules are affecting it. – James Lin Jul 06 '16 at 22:29
  • I just realised one of my unittest against the storagesaver is directly importing it to run tests against it., so this very likely the cause of my other unittests not working properly. – James Lin Jul 06 '16 at 22:54

0 Answers0