使用Doctest的Python单元测试无法按预期工作

时间:2017-11-14 17:54:41

标签: python python-3.x unit-testing doctest

我创建了一个python模块,通过将特定位置作为输入来生成天气数据(纬度,经度,高程和其他细节)。

根据标准更新它,“pycodestyle”包用于检查PEP8标准不会引发任何错误或警告。

我的代码如下:

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)

如上所示,预期条件应返回在被测试函数中创建的list / dataframe / variable的内容。试一试,我只是试图打印列表的内容,但我的单元测试输出抛出错误如下,因为预期值和得到的值不匹配:

  
    

PS C:\ Users \ JKC> python -m doctest testcases.txt     ************************************************** ********************文件“testcases.txt”,第7行,在testcases.txt中失败示例:         fetch_location_info([“Sydney,Australia”],open('data / error_log.txt','w'))

  
     

预期:

     
print(input_info) 
  
     

GOT:

     
[{'Location': 'Sydney,Australia', 'Latitude': -33.8688197, 'Longitude': 151. 2092955, 'Elevation': 24.5399284362793}]
  

因此,您可以看到测试用例工作正常,但由于我无法打印列表的内容,因此测试用例失败了。

我的问题是如何在单元测试用例的预期部分显示列表内容?

如果我没错,我是否需要在单元测试用例的预期部分中提及输出值?

任何输入都会有所帮助

1 个答案:

答案 0 :(得分:1)

你需要让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}]