我编写了一个端点,该端点调用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)