Reputation: 11614
I don't want to create real files in my unittest. So i find myself often tinkering with nonsense boilerplate and creating mock-factories for pseudo-files. I was wondering if it wouldn't be nicer to avoid (in this instance) these pointless efforts and try something like in the scope of a local unittest method:
open = lambda x: StringIO()
Would this be ok? Or are there major caveats/don't issue in this approach and be better of with mock-factories?
Upvotes: 7
Views: 1454
Reputation: 49826
This is fine, as long as you understand how python scopes work (i.e. locally is fine, globally will cause problems).
You should probably also consider that your monkeypatches will have different failure modes from the originals, and have appropriate tests to ensure that your code interacts correctly with the builtins.
Upvotes: 6