直接上干货,不瞎扯。
前段时间在写conftest.py的时候,有个需要清理每次测试之后生成的测试数据的操作,但是每次生成的测试数据又在不同的文件夹中,这些文件夹被放在F盘中,我需要在每次测试执行前,将这些测试生成的文件全部删除或者转移到指定的路径中来,于是我在conftest.py中写一个清除生成文件的递归函数(多文件夹嵌套,所以用递归)的操作,并且,每次测试方法执行的时候都会执行一次。
附错误代码如下:
@pytest.fixture(scope='function', autouse=True) # 转移生成的测试数据
def clean_path(file_path=r'F:\data_test', find_str='自动化', suc_file=r'F:\zhuanyi'):
li = os.listdir(file_path)
for i in range(len(li)):
if os.path.isdir(os.path.join(file_path, li[i])):
clean_path(os.path.join(file_path, li[i]))
elif find_str in os.path.join(file_path, li[i]) and 'pdf' not in os.path.join(file_path, li[i]):
# print(os.path.join(file_path,li[i]))
print(os.system(f'chcp 65001'))
print(os.system(f'move {os.path.join(file_path, li[i])} {suc_file}'), 'success move file!')
执行错误信息如下:
test setup failed
Fixture "clean_path" called directly. Fixtures are not meant to be called directly,
but are created automatically when test functions request them as parameters.
See https://docs.pytest.org/en/stable/explanation/fixtures.html for more information about fixtures, and
https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly about how to update your code.
上面的代码中将,
clean_path(os.path.join(file_path, li[i]))
这一行代码注释掉(需要有个pass),则可以正常执行,debug查原因,发现才递归自己的时候,不能从递归里面出来(多次调用递归(调用了夹具,上面这行代码在递归的时候会把解释器一起启动,导致直接调用了夹具)就不行),于是修改代码,可以正常执行。
正确写法,代码如下:
def clean_path(file_path=r'F:\data_test', find_str='自动化', suc_file=r'F:\zhuanyi'):
li = os.listdir(file_path)
for i in range(len(li)):
if os.path.isdir(os.path.join(file_path, li[i])):
clean_path(os.path.join(file_path, li[i]))
elif find_str in os.path.join(file_path, li[i]) and 'pdf' not in os.path.join(file_path, li[i]):
# print(os.path.join(file_path,li[i]))
print(os.system(f'chcp 65001'))
print(os.system(f'move {os.path.join(file_path, li[i])} {suc_file}'), 'success move file!')
@pytest.fixture(scope='function', autouse=False) # 转移生成的测试数据
def clean_file():
print('执行环境清理操作')
clean_path()