0

I am using mock for testing in Python. I am trying to unit test a metaclass which overwrites the __new__ method and then calls type.__new__(cls) internally.

I don't want to actually call type.__new__, so I want to mock out type. Of course, I can't patch __builtin__.type because it breaks object construction within the test.

So, I really want to limit mocking type within the module under test. Is this possible?

Travis Parks
  • 8,435
  • 12
  • 52
  • 85

1 Answers1

1

Yes. You patch as close to where you're going to call your function as possible for just these sort of reasons. So, in your test case, only around the function (or whatever callable) you'll call that's under tests, you can patch type.

The documentation for patch has plenty of examples for doing this if you'd like to peruse them.

Cheers.

Julian
  • 3,375
  • 16
  • 27
  • The problem is type.__new__ prevents the creation of mocks and any other objects that aren't within the module. This include mock.Mock itself. – Travis Parks Jul 27 '12 at 20:04
  • 1
    Right. You'd need to create the mock beforehand, and pass it to `patch`. More fundamentally, the reason this is difficult is because mocking `type.__new__` is really really broad as you're noticing. Perhaps you want to try a different strategy altogether. – Julian Jul 27 '12 at 20:07