conftest.py中的递归函数的使用

直接上干货,不瞎扯。

        前段时间在写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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值