如何使用可测试端点的MOCKS编写单元测试

我编写了一个端点,该端点调用API以获取用户定义的时区的一天中的时间。现在,我需要模拟该端点,但是我很难找到正确的答案。这是我编写的代码:

我不太确定该打电话给我以得到答复。


import requests
import json
import jsonpath
import dateutil
from flask import flask,render_template,request
from flask import jsonify,make_response

app = flask(__name__,template_folder="templates")


@app.route('/get_time',methods=['GET'])
def get_time():

    try:
        time_zone = request.args.get('time_zone')
        url = "http://worldclockapi.com/api/json/" + time_zone + "/now"
        r = requests.get(url)
    except Exception:
        return make_response(jsonify({"Error": "Some error message"}),400)
    return r.json()["currentDateTime"]


    if response.status_code != 200:
        print("Error on response")
        return response.status_code,response.text

if __name__ == '__main__':
    app.run(debug=True)

这是我要参加的考试:

import json
import unittest
import unittest.mock
import requests

#name of the file being tested
import timeofday


class MockResponse:

    def __init__(self,text,status_code):
        self.text = text
        self.status_code = status_code

    def json(self):
        return json.loads(self.text)

    def __iter__(self):
        return self

    def __next__(self):
        return self

#json returned by the API http://worldclockapi.com/api/json/est/now
def mock_requests_timeofday(*args,**kwargs):
    text = """
    {
        "$id": "1","currentDateTime": "2019-11-08T15:52-05:00","utcOffset": "-05:00:00","isDayLightSavingsTime": false,"dayOfTheWeek": "Friday","timeZoneName": "Eastern Standard Time","currentFileTime": 132177019635463680,"ordinalDate": "2019-312","serviceResponse": null
    }}
    """
    response = MockResponse(text,200)
    return response


class TestLocation(unittest.TestCase):

    @unittest.mock.patch('requests.get',mock_requests_get_success)
    def test_get_time(self):

        self.assertEqual(response.status_code,200)


class TestTimeofday(unittest.TestCase):
    @unittest.mock.patch('timeofday.requests.get',mock_requests_timeofday)
    def get_time(self):
        self.assertEqual(response.status_code,200)
wangxuyua 回答:如何使用可测试端点的MOCKS编写单元测试

您的代码当前失败,因为您直接模拟了已导入测试文件中的模块的get函数。

为了使测试工作正常,您必须直接模拟其他文件的requests.get方法。

这是您在timeofday.py中执行的get方法的模拟看起来像: mock.patch('timeofday.requests.get',mock_requests_get_success)

现在,当您执行get_time时,应该对API调用进行模拟,您将收到定义的答案。

PS:请注意,在返回r.json()[“ currentDateTime”]之后编写的if语句将永远不会执行,因为使用return时函数将结束。

本文链接:https://www.f2er.com/3134893.html

大家都在问