0

There are many examples online and in the docs of patching static methods on classes, or mocking the entire class. What I want to do is create a new method on an existing class which is in a library that I do not own - requests.Response.

I tried the code below but it doesn't appear to work

import requests  # has requests.Response class
from unittest.mock import patch


def foo(self):
    print("foo called")
    return self.text

patch.object(requests.Response, "foo", foo)

# many tests down here which get a response object and call response.foo()

Is what I am trying to do possible?

Daniel Kats
  • 5,141
  • 15
  • 65
  • 102
  • 3
    You aren't patching an existing attribute name; you are adding a *new* one. `requests.Response.foo = foo` should work. – chepner Mar 18 '20 at 16:57
  • @chepner That should work, but it will not remove the modification after the test. It is always better to keep the test self contained. – Klaus D. Mar 18 '20 at 17:03
  • That's what fixtures are for. – chepner Mar 18 '20 at 17:09
  • You might try patching `requests.Response` itself with a `Mock` object that wraps the real module, then configure that mock with a `foo` attribute that calls your function. – chepner Mar 18 '20 at 17:12

0 Answers0