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

Why are the lists different in pytest compared to the output from console?

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

运行 来自控制台的函数 get_all_jeeps() 的代码将 return:

Grand Cherokee, Cherokee, Trailhawk, 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']

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

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