1

My function that I am trying to test is returning list of strings:

def listForumsIds:
    response = requests.get(url)
    forums= response.json().get('forums')
    forumsIds= [forum['documentId'] for forum in forums]
    # return like: ['id1', 'id2', 'id3'.....]
    return forumsIds

My test function:

@requests_mock.mock()
def test_forms(self, m):
    # I also used json='response'
    m.get('valid url', text="response", status_code=200)
    resp = listForumsIds('valid url')
    # ERROR !!!!
    assert resp == "response"

I am getting error like: json.decoder.JSONDecodeError or str object has no attribute get

How to fake my response to be match return value of my function?

hoefling
  • 59,418
  • 12
  • 147
  • 194
stefani
  • 19
  • 1
  • 2
  • Does this answer your question? [How to use pytest capsys on tests that have mocking decorators?](https://stackoverflow.com/questions/52060950/how-to-use-pytest-capsys-on-tests-that-have-mocking-decorators) – hoefling Mar 02 '20 at 15:37
  • @hoefling NO, it is not simialr, basically how am I tell the mock that my request return wont be just text='text' or just json='response', it is json object that I will get the forums header and inside it ill get all forums IDs – stefani Mar 02 '20 at 18:18
  • What are you testing for? the `get` method from json? You should be mocking as per @hoefling's answer. You could be looking into `pytest.patch.object` for mocking request and json methods as well (with a `returned_value` argument) – thoroc Aug 27 '20 at 10:13

1 Answers1

3

You have to pass the desired payload in the json field of the mocked response. Example, adapted to your code:

class MyTests(unittest.TestCase):

    @requests_mock.mock()
    def test_forms(self, m):
        payload = {"forums": [{"documentId": "id1"}]}
        m.register_uri("GET", "https://www.example.com", json=payload)
        ids = listForumsIds('https://www.example.com')
        assert ids == ['id1']
hoefling
  • 59,418
  • 12
  • 147
  • 194
  • 1
    This answer is the best of all since it covers the basic yet crucial hint that we have to register the API URL we want to mock. Thank you @hoefling – Arindam Roychowdhury May 09 '23 at 12:13