使用Doctest的Python单元测试未按预期工作
我创建了一个python模块,通过将特定位置作为输入来生成天气数据(纬度、经度、海拔和其他细节) 根据标准进行更新,用于检查PEP8标准的“pycodestyle”包不会抛出任何错误或警告 我的代码如下:使用Doctest的Python单元测试未按预期工作,python,python-3.x,unit-testing,doctest,Python,Python 3.x,Unit Testing,Doctest,我创建了一个python模块,通过将特定位置作为输入来生成天气数据(纬度、经度、海拔和其他细节) 根据标准进行更新,用于检查PEP8标准的“pycodestyle”包不会抛出任何错误或警告 我的代码如下: def fetch_location_info(input_list, err_file): # URL which gives us Latitude, Longitude values LatLong_URL = ( 'http://maps.googleapi
def fetch_location_info(input_list, err_file):
# URL which gives us Latitude, Longitude values
LatLong_URL = (
'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address='
)
# URL which gives us Elevation values
Elevation_URL = (
'https://maps.googleapis.com/maps/api/elevation/json?locations='
)
# Initializing Error Logs with relevant title for writing error records
err_line_header = "Logging Location Data Errors"
print(err_line_header, file=err_file)
# Insert a new line in the error file after the Error Header
print("\n", file=err_file)
# Fetch and Extract Location details from google maps
input_info = []
for location in input_list:
temp_info = {'Location': location}
latlong_response = requests.get(LatLong_URL + location).json()
if latlong_response.get('results'):
for latlong_results in latlong_response.get('results'):
latlong = (
latlong_results
.get('geometry', '0')
.get('location', '0')
)
temp_info['Latitude'] = latlong.get('lat', '0')
temp_info['Longitude'] = latlong.get('lng', '0')
elevation_response = requests.get(
Elevation_URL
+ str(temp_info['Latitude'])
+ ','
+ str(temp_info['Longitude'])
).json()
if elevation_response.get('results'):
for elevation_results in elevation_response.get('results'):
temp_info['Elevation'] = (
elevation_results.get('elevation', '0'))
input_info.append(temp_info)
break
else:
print("Elevation_URL is not fetching values for {}"
.format(location),
file=err_file
)
break
else:
print("LatLong_URL is not fetching values for {}"
.format(location),
file=err_file
)
print("\n", file=err_file)
return input_info
现在,作为下一步,我将尝试使用doctest进行单元测试。我选择将测试用例保存在一个单独的文件中。因此,我创建了以下.txt文件,并将其保存在与代码相同的目录中
This is a doctest based regression suite for Test_Weather.py
Each '>>' line is run as if in a python shell, and counts as a test.
The next line, if not '>>' is the expected output of the previous line.
If anything doesn't match exactly (including trailing spaces), the test fails.
>>> from Test_Weather import fetch_location_info
>>> fetch_location_info(["Sydney,Australia"], open('data/error_log.txt', 'w'))
print(input_info)
如上所述,预期条件应返回在被测试函数中创建的列表/数据帧/变量的内容。尝试一下,我只是尝试打印列表的内容,但我的单元测试输出抛出如下错误,因为预期值和get值不匹配:
PS C:\Users\JKC>python-m doctest testcases.txt
**********************************************************************testcases.txt文件第7行“testcases.txt”失败示例:
获取位置信息([“澳大利亚悉尼”],打开('data/error\u log.txt','w'))
预期:
得到:
在这里,您可以看到测试用例工作得很好,但是由于我无法打印列表的内容,所以它没有通过测试用例
我的问题是如何在单元测试用例的预期部分显示列表的内容?
如果我没有错,我是否需要在单元测试用例的预期部分中直接提到输出值
任何输入都会有帮助您需要让doctest看起来与在Python REPL上运行时完全一样:
>>> from Test_Weather import fetch_location_info
>>> fetch_location_info(["Sydney,Australia"], open('data/error_log.txt', 'w'))
[{'Location': 'Sydney,Australia', 'Latitude': -33.8688197, 'Longitude': 151.2092955, 'Elevation': 24.5399284362793}]
您的测试用例需要文本
print(input_info)
。感谢您的回复@user2357112,这正是我被击中的地方。我已经编写了测试用例来打印输入信息列表的内容,但它没有打印内容。那么如何打印内容呢。有什么提示吗?请看一下单元测试用例文件的内容,以便更清楚地了解。我已经更新了这个问题,使其更具可读性,感谢您的回复。所以我需要手动捕获我在测试用例中给出的输入值的输出值,并在测试用例中提到相同的值。是吗?是的。基本上,从解释器运行代码并捕获结果(当然,如果它是正确的)。或者,如果遵循最佳实践并在生成代码之前编写测试,请手动编写代码在解释器中的工作方式及其生成的输出,然后使代码通过测试。太好了。非常感谢。还有一个疑问。我将日期值作为输入之一传递给函数。因此,当我试图在单元测试用例中将datetime.datetime(2017,6,1)作为函数的一个输入值时,它向我抛出了一个错误:“datetime未定义”。这意味着我是否需要在我的单元测试用例中的函数调用行之前包含“>>>import datetime”语句?@JKC Yes..这正是在解释器中使其工作所必须做的。还有一件事。如果一个函数需要一个数据帧作为输入,我如何在测试用例中提到这一点。有什么想法吗?
[{'Location': 'Sydney,Australia', 'Latitude': -33.8688197, 'Longitude': 151. 2092955, 'Elevation': 24.5399284362793}]
>>> from Test_Weather import fetch_location_info
>>> fetch_location_info(["Sydney,Australia"], open('data/error_log.txt', 'w'))
[{'Location': 'Sydney,Australia', 'Latitude': -33.8688197, 'Longitude': 151.2092955, 'Elevation': 24.5399284362793}]