【问题标题】:Why are the lists different in pytest compared to the output from console?为什么 pytest 中的列表与控制台的输出不同?
【发布时间】:2019-06-15 11:08:48
【问题描述】:

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

从控制台运行函数get_all_jeeps() 的代码将返回:

大切诺基、切诺基、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() 的控制台输出为:

[“猎鹰”、“准将”、“千里马”、“思域”、“大切诺基”]

除非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']

【问题讨论】:

  • 您在使用数据库吗?一些数据库不保证查询之间的顺序一致(尤其是 Postgresql)。无论如何,如果订单不相关,您可以使用 assert set(actual) == set(expected) 修复测试。
  • 我已经添加了它使用的字典。这有帮助吗?

标签: python list pytest assertion


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 2022-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多