为什么pytest中的列表与控制台的输出相比有所不同?

时间:2019-06-15 11:08:48

标签: python list pytest assertion

我正在使用100天的代码。其中一个项目是对所选项目实施pytest。我选择了以前的项目,该项目采用了定义的汽车制造商和型号字典,并将输出返回给各种问题。我已经为其中两个功能编写了单元测试,但它们均失败了。

从控制台为功能get_all_jeeps()运行代码将返回:

  

大切诺基,切诺基,特雷霍克,Trackhawk

如果我使用以下代码运行pytest:

def test_get_all_jeeps():
    expected = 'Grand Cherokee, Cherokee, Trailhawk, Trackhawk'
    actual = get_all_jeeps()
    assert type(actual) == str
    assert actual == expected

它失败,因为pytests输出看起来像正在排序。为什么要这么做?

E       AssertionError: assert 'Cherokee, Gr...wk, Trailhawk' == 'Grand Cherokee...wk, Trackhawk'
E         - Cherokee, Grand Cherokee, Trackhawk, Trailhawk
E         + Grand Cherokee, Cherokee, Trailhawk, Trackhawk

另一个测试与从控制台运行时给出的输出不同。来自控制台的功能get_first_model_each_manufacturer()的输出为:

  

['Falcon','Commodore','Maxima','Civic','Grand Cherokee']

除了无法通过pytest:

    def test_get_first_model_each_manufacturer():
        expected = ['Falcon', 'Commodore', 'Maxima', 'Civic', 'Grand Cherokee']
        actual = get_first_model_each_manufacturer()
        assert type(actual) == list
>       assert actual == expected
E       AssertionError: assert ['Fairlane', ...', 'Cherokee'] == ['Falcon', 'Co...and Cherokee']
E         on index 0 diff: 'Fairlane' != 'Falcon'
E         Use -v to get the full diff

“ Fairlane”物品如何到达那里? pytest有何不同之处?

在此处https://github.com/cadamei/100daysofcode/tree/master/days/10-12-pytest

回购

所有函数都使用此字典作为数据:

cars = {
    'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'],
    'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'],
    'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'],
    'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'],
    'Jeep': ['Grand Cherokee', 'Cherokee', 'Trailhawk', 'Trackhawk']

1 个答案:

答案 0 :(得分:0)

您的cars.py脚本正在修改列表,因为它在导入时正在运行print(sort_car_models()),请删除这些行或将其放入if __name__ == '__main__':

要了解更多信息,请查看What does if __name__ == "__main__": do?