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

标签 python list pytest assertion

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

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

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 有何不同之处?

这里 repo 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?

关于python - 为什么 pytest 中的列表与控制台的输出不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56609791/

相关文章:

python - 如何模拟/修补整个类(class)?

python - 在 Elasticsearch 中搜索句点和连字符分隔的字段

python - 使用 Python 和 Redis 进行优雅的缓存

java - 将 3 个数组列表合并为一个

c++ - 删除 std :list<User_Define> that satisfy certain conditions? 中元素的最佳方法是什么

python - Pytest 日志记录忽略 pytest.ini 中的选项

python - 使用 pytest fixtures 的测试可以交互运行吗?

python - 基于亲和性矩阵的谱聚类

python - opencv:将像素写入图像

python - 在遍历列表时在数据框的一行中添加多个值