mardi 1 mars 2016

Mock two separate responses to same function in same test

In my previous question, I asked how to Mock a class that wraps requests.get in my class. The answer provided works well, if I am only calling requests.get once. However, it turns out my class is more complicated than I made my example.

My class calls request.get twice. Once at initialization, because it hits an API end point that returns API values I need to use in my actual request, and once when I make my .fetch call.

import requests
class ExampleAPI(object):
    def __init__(self):
        self.important_tokens = requests.get(url_to_tokens)['tokens']

    def fetch(self, url, params=None, key=None, token=None, **kwargs):
        return requests.get(url, params=self.important_tokens).json() 

Now, it turns out I need to create two mock responses. One for the initialization and one for the .fetch. Using the code from the previous answer:

@patch('mymodule.requests.get')
def test_fetch(self, fake_get):
    expected = {"result": "True"}
    fake_get.return_value.json.return_value = expected
    e = ExampleAPI()    # This needs one set of mocked responses
    self.assertEqual(e.fetch('http://ift.tt/24A9JOI'), expected)    # This needs a second set

How can I create seperate responses for these two seperate calls to request.get?

Aucun commentaire:

Enregistrer un commentaire