Skip to content
Advertisement

Tag: monkeypatching

How to monkeypatch a python library class method?

I am trying to modify a better_profanity library to include an additional argument to get_replacement_for_swear_word function. To do so I first import the necessary parts of the library and test its functionality before: Now I get the source code of the class method, modify it and execute it to __main___: Now I replace this function inside the class: Note that

How to mock a function that is not part of any class using monkeypatch in Python?

Consider a function: and it’s mock function: How do I mock some_function() function using monkeypath.setattr()? Something similar to: monkeypatch.setattr(<class name>, “some_function”, dummy_function) Not sure what <class name> here should be. Answer obj should be the current module: If some_function is inside another file, you need to import this file to your current module:

Changing monkeypatch setattr multiple times

I am trying to test code that depends on a third party and would like to use monkeypatch to replicate what I expect a request will return. Here is a minimal example of the code that I have. For my tests, I have something like the following: How can I monkeypatch each of the calls to requests.get using monkeypatch.setattr? The

How to monkeypatch builtin function datetime.datetime.now?

I’d like to make sure that datetime.datetime.now() returns a specific datetime for testing purposes, How do I do this? I’ve tried with pytest’s monkeypatch But this gives me the error TypeError: can’t set attributes of built-in/extension type ‘datetime.datetime’ Answer As the error tells you, you can’t monkeypatch the attributes of many extension types implemented in C. (Other Python implementations may

Advertisement