How to run the tests in same order given in pytest parametrize

40 views Asked by At

I have test case which I want to execute with multiple test data. Using CSV to provide data and use same data for parameterization. But when I execute parameterize test case, the sequence of test data is get shuffled. I need to execute test case in same sequence as given in CSV. Even for normal parameterization I am facing same issue it does not execute test in same order as given.

CSV_FILE_NAME = "CSV file path"
CSV_FILE_PATH = os.path.join(os.getcwd(), CSV_FILE_NAME)

def load_tests_from_csv(file_path):
    with open(file_path, newline='', encoding='utf-8-sig') as csvfile:
        reader = csv.DictReader(csvfile)
        return list(reader)

test_data = load_tests_from_csv(CSV_FILE_NAME)

class TestClassTest:

    @pytest.fixture(params=test_data, scope="class")
    def test_data(self, request):
        return request.param

    def test_generated(self, test_data):
        assert True
        # Use test_data in your test logic
        print(f"Running test with row data: {test_data}")

Does any one have idea how to execute this test cases in same sequence as given in CSV? Also, I can not use ordering for each test case as I have more than 50 test scenarios in CSV.

I have tried with providing scope to the fixture. Also using pytest hook pytest_generate_tests but did not work.

1

There are 1 answers

0
laven On

should use @pytest.mark.parametrize

CSV_FILE_NAME = "./test.csv"
CSV_FILE_PATH = os.path.join(os.getcwd(), CSV_FILE_NAME)
def csv_load_type1(csv_path):
    """
    - 加载csv文件,并返回除第一行之外的内容,csv类型样本参考 2.2.4.2_testcase.csv

    Returns:
        csv_ret(list): [[test_stream,backbet_expected_file,intercept_log_expected_file]]
    """
    csv_ret = []
    try:
        with open(csv_path, 'r', newline='') as fr:
            csvreader = csv.reader(fr)
            next(csvreader)  # 跳过标题行
            for row in csvreader:
                row_list = []
                if len(''.join(row).strip()) == 0:
                    continue
                for each_field in row:
                    if each_field == 'None':
                        each_field = None
                    row_list.append(each_field)
                csv_ret.append(row_list)

    except:
        
        assert False
    return csv_ret

test_data = csv_load_type1(CSV_FILE_PATH)

print(test_data)

class TestClassTest:
    
    @pytest.mark.parametrize('col1,col2',test_data)
    def test_new(self,col1,col2):
        print(col1,col2)
        

csv file like: enter image description here