2017-09-03 121 views
-1

所以我有一个模块从Open Weather Map检索JSON。用户必须输入的位置和API密钥来接收针对所对应的位置的输出:比较JSON字符串使用相同的代码给出不同的结果

(主模块)

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和相同的输出(请参阅文本文件),我只在第三次执行时出错。

+0

您正在调用外部API;天气预报随时间而变化。 –

+0

但我没有对脚本进行任何硬编码。我为这两个文件中的每个运行调用一个外部API。 –

+3

单元测试不应该依赖外部代码,特别是不受您控制的外部服务随着时间的推移产生新数据。无论如何,测试他们的API并不是你的工作。 –

回答

0

所以,问题是附加有每一个响应消息ID:

message ID with the JSON string

我跳过的非常线和问题得到有效解决扫描。

相关问题