Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monkey-patch a builtin function for a unit-test?

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?

like image 857
Don Question Avatar asked Feb 15 '12 20:02

Don Question


People also ask

What is monkey patching in Pytest?

monkeypatch can be used to patch functions dependent on the user to always return a specific value. In this example, monkeypatch. setattr is used to patch Path. home so that the known testing path Path("/abc") is always used when the test is run. This removes any dependency on the running user for testing purposes.

What does monkey Patch_all () do?

A monkey patch is a way to change, extend, or modify a library, plugin, or supporting system software locally. This means applying a monkey patch to a 3rd party library will not change the library itself but only the local copy of the library you have on your machine.

What is the use of monkey patching in Python?

In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time. We use above module (monk) in below code and change behavior of func() at run-time by assigning different value.

Why do we need monkey patching?

Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. A monkey patch (also spelled monkey-patch, MonkeyPatch) is a way to extend or modify the runtime code of dynamic languages (e.g. Smalltalk, JavaScript, Objective-C, Ruby, Perl, Python, Groovy, etc.)


1 Answers

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.

like image 139
Marcin Avatar answered Oct 20 '22 04:10

Marcin