比较JSON字符串使用相同的代码

时间:2017-09-03 13:59:18

标签: python json python-3.x unit-testing debugging

所以我有一个从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:

结果:

Test_1

输出文件:

来自主要功能:main.txt

来自测试功能:tested.txt

Testing_2:

结果:

Test_2

输出文件:

来自主要功能:main2.txt

来自测试功能:testing2.txt

Testing_3:

结果:

Test_3

输出文件:

来自主要功能:main3.txt

来自测试功能:testing3.txt

现在,我不知道为什么对于相同的代码,相同的url和相同的输出(请参阅文本文件),我只在第三次执行时收到错误。

1 个答案:

答案 0 :(得分:0)

所以问题是每个响应附带的消息ID:

message ID with the JSON string

我跳过了扫描线,问题解决了。