简体   繁体   中英

python Mock post inside a method

How can I mock a post inside a method, so i can have unittests?

    def send_report(self, data):
        url = settings.WEBHOOK_PO
        payload = json.dumps(data)
        requests.post(url, data=payload)
        url = settings.WEBHOOK_LQA
       response = requests.post(url, data=payload)
       return response.status_code

Is there a way to cover this method for unit test with not actually posting?

You can use the mock library to replace requests.post with something else:

with mock.patch('requests.post') as mock_post:
    foo.send_report(data)

( mock is a third-party package , but was added to the standard library, as part of the unittest package`, in Python 3.3.)

mock_post can be configured to provide the desired behavior during the test; consult the mock documentation for details.


Another option is to modify your method to take the post function as an argument, rather than hard-coding the function (this is an example of dependency injection ):

def send_report(self, data, poster=requests.post):
    url = settings.WEBHOOK_PO
    payload = json.dumps(data)
    poster(url, data=payload)
    url = settings.WEBHOOK_LQA
    response = poster(url, data=payload)
    return response.status_code

When you want to test the function, you simply pass a different callable object as the optional second argument.

Note that you can supply separate functions for the two types of posts, which might make it easier to test than with a mock:

from functools import partial

def send_report(self,
                data,
                post_po=partial(requests.post, settings.WEBHOOK_PO),
                post_lqa=partial(requests.post, settings.WEBHOOK_LQA)):
    payload = json.dumps(data)
    post_po(data=payload)
    response = post_lqa(data=payload)
    return response.status_code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM