【问题标题】:can pytest fixture cleanup iff test passes?如果测试通过,pytest 夹具可以清理吗?
【发布时间】:2019-03-14 00:31:52
【问题描述】:

有没有使用pytest 固定装置(尤其是pytest-tmpdir)的好方法,只有在测试通过时才进行清理?

我正在测试一些 terraform,并希望保留带有状态文件的测试目录,以防万一失败,我必须清理 aws 资源。

我可以使用xtest 样式,但宁愿不要。

不知道如何在 send 中使用 yield 语法,但似乎可行。

我现在是

@pytest.fixture(scope='function')
def tf_ut():
    tmp_dir = tempfile.mkdtemp(dir=test_root) # test_root is a session dir that contains the test dirs
    logging.debug('test fixture directory: %s', tmp_dir)
    shutil.copy(os.path.join(PROJECT_ROOT, 'terraform-provider-http'), tmp_dir)
    shutil.copy(os.path.join(PROJECT_ROOT, 'terraform-provider-bwafapi'), tmp_dir)
    tf = Terraform(working_dir=tmp_dir)
    tf.init(PROJECT_ROOT)
    return tf


def test_plan_default(tf_ut):
    ret, out, err = tf_ut.init()
    assert ret is 0
    ret, out, err = tf_ut.plan(PROJECT_ROOT, var_file=os.path.join(PROJECT_ROOT, 'presets/stsdev-dms.tfvars'))
    assert 'Terraform will perform the following actions:' in out
    shutil.rmtree(tf_ut.working_dir)

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    您可以使用pytest_runtest_makereport 钩子在测试项目中设置测试阶段的结果,并创建一个夹具来检查设置和测试执行的状态。如果两者都通过了,那么您可以调用清理逻辑。

    @pytest.hookimpl(hookwrapper=True, tryfirst=True)
    def pytest_runtest_makereport(item, call):
        outcome = yield
        rep = outcome.get_result()  
        setattr(item, "rep_" + rep.when, rep)
    
    @pytest.yield_fixture
    def teardown(request):
        yield
        item = request.node
        if item.rep_setup.passed:
            try:
                call_status = item.rep_call.passed
                if call_status:
                    <YOUR CLEAN_UP STEPS>
            except AttributeError:
                <YOUR CLEAN_UP STEPS>
    

    【讨论】:

      【解决方案2】:

      您可以使用 addfinalizer 进行清理。

      @pytest.fixture(scope='function')
      def tf_ut(request, tmpdir):
          tmp_dir = tempfile.mkdtemp(dir=test_root) # test_root is a session dir that contains the test dirs
          logging.debug('test fixture directory: %s', tmp_dir)
          shutil.copy(os.path.join(PROJECT_ROOT, 'terraform-provider-http'), tmp_dir)
          shutil.copy(os.path.join(PROJECT_ROOT, 'terraform-provider-bwafapi'), tmp_dir)
          tf = Terraform(working_dir=tmp_dir)
          tf.init(PROJECT_ROOT)
      
          def cleanup(tmpdir):
              if request.node.rep_setup.passed:
                 #clean up tmpdir
      
          request.addfinalizer(cleanup)
      
          return tf
      

      cleanup 函数将在每个夹具作用域之后运行(此处为函数)。

      【讨论】:

        猜你喜欢
        • 2013-09-20
        • 1970-01-01
        • 1970-01-01
        • 2020-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-19
        相关资源
        最近更新 更多