首页 > 解决方案 > Pytest 测试用例失败,但从具有相同输入的终端运行时给出正确结果

问题描述

我是 pytest 的新手,并使用它对我的 python 代码进行单元测试。我ProblemSorting在文件中有一个名为difficulty. 类中有一个方法get_difficulty_order()

以下是我为测试该方法而编写的单元测试:

import pytest
from difficulty import ProblemSorting

@pytest.mark.parametrize("num_of_problems, num_of_subtasks, problems, result",
                         [
                             pytest.param(3, 3, [[16, 24, 60],
                                                 [498, 861, 589],
                                                 [14, 24, 62],
                                                 [72, 557, 819],
                                                 [16, 15, 69],
                                                 [435, 779, 232]], [2, 1, 3]),
                             pytest.param(1, 1, [[2], [5]], [1]),
                             pytest.param(0, 0, [], [])])
def test_get_difficulty_order(num_of_problems, num_of_subtasks, problems, result):
    '''hello'''
    prob_sort = ProblemSorting(num_of_problems, num_of_subtasks, problems)
    assert prob_sort.get_difficulty_order() == result

现在的问题是2nd测试用例失败了。但是当我删除1st3rd测试用例并保留2nd测试用例时,它可以工作。即使我使用2nd输入手动检查代码,它也会给出预期的结果。

注意:我还注意到,无论它有多少测试用例,它只会成功第一个和最后一个测试用例,而中间的所有测试用例都失败了。

编辑:难度.py '''检查'''

import operator

class ProblemSorting:
    '''Class implementing various methods to solve the problem
       which requires ordering of problem based on its difficulty level
    '''

    # stores the tuple (i, difficulty) where 'i' is the problem number
    # and 'difficulty' is the difficulty level associated with the 'i'th problem
    difficulty_of_problems = list()

    def __init__(self, num_of_problems, num_of_subtasks, problems):
        self.num_of_problems = num_of_problems
        self.num_of_subtasks = num_of_subtasks
        self.problems = problems

我不明白这有什么问题。任何帮助将不胜感激。

标签: pythonunit-testingpytest

解决方案


推荐阅读