【发布时间】:2023-04-07 19:09:01
【问题描述】:
所以我有一个从Open Weather Map 检索 JSON 的模块。用户必须输入位置和 API 密钥才能接收相应位置的输出:
(主模块)
def weather_response(location, API_key):
location=format(location) #Formats the location name if proper form
url='http://api.openweathermap.org/data/2.5/forecast?q='+location+'&APPID='+API_key
json=urllib.request.urlopen(url)
json=json.read()
json=json.decode()
urllib.request.urlretrieve(url,"main3.txt")
return json
我也有一个相同的测试文件:
(测试模块)
def test_weather_response(self):
global json_de
global json_ny
self.assertEqual(weather_response("Delhi","<APPID>"),json_de)
self.assertNotEqual(weather_response("Mumbai","<APPID>"),json_de)
self.assertEqual(weather_response("delhi","<APPID>"),json_de)
self.assertEqual(weather_response(" dElHi ","<APPID>"),json_de)
self.assertNotEqual(weather_response("Pizza","<APPID>"),json_de)
,其中 json_de 和 json_ny 声明如下:
(测试模块)
url='http://api.openweathermap.org/data/2.5/forecast?q=Delhi&APPID=<APPID>'
json_de=urllib.request.urlopen(url)
json_de=json_de.read()
json_de=json_de.decode()
url2='http://api.openweathermap.org/data/2.5/forecast?q=NewYork&APPID=<APPID>'
json_ny=urllib.request.urlopen(url2)
json_ny=json_ny.read()
json_ny=json_ny.decode()
urllib.request.urlretrieve(url,"tested3.txt")
如您所见,我已将响应保存在每个文件中,以便在测试失败时跟踪错误。
Testing_1:
结果:
输出文件:
来自主函数:main.txt
来自测试功能:tested.txt
测试_2:
结果:
输出文件:
来自主函数:main2.txt
来自测试功能:testing2.txt
Testing_3:
结果:
输出文件:
来自主函数:main3.txt
来自测试功能:testing3.txt
现在,我不知道为什么对于相同的代码、相同的 url 和相同的输出(请参阅文本文件),我只在第三次执行时遇到错误。
【问题讨论】:
-
您正在调用外部 API;天气预报会随着时间而变化。
-
但我没有将任何内容硬编码到脚本中。我为这两个文件中的每次运行调用一个外部 API。
-
单元测试不应该依赖于外部代码,尤其是你无法控制的外部服务会随着时间的推移产生新的数据。无论如何,测试他们的 API 不是你的工作。
-
请也解释反对票(无论是谁做的)。很难理解我做错了什么。
-
是的,您多次调用外部 API,然后当它们突然不为多次调用返回完全相同的数据时,您的测试就会失败。这不是一个好的测试,它很脆弱,而且无论如何覆盖都是错误的。
标签: python json python-3.x unit-testing debugging