【问题标题】:Is it possible to execute finalizer fixture in python only after all parameters of the test are executed? [duplicate]只有在执行了测试的所有参数之后,是否可以在 python 中执行终结器夹具? [复制]
【发布时间】:2016-03-15 15:35:44
【问题描述】:

我正在尝试在我的测试用例的所有参数运行后执行终结器夹具。问题是我的终结器在每个参数运行后都被执行,所以我需要的值被重置。示例:

@pytest.mark.parametrize('testcaseid',
                         ['1', '2', '3'])
@pytest.mark.parametrize('lang',
                         ["EN",
                          "FR"])
def test_lang(self, request, base_url, lang, testcaseid, connect_testrail):
    try:
        base_url = base_url.replace("english", "french") if lang == "FR" else base_url
        self.navigate(base_url)
        self.wait_for_page_loaded()
        result = self.check_correct_lang_displayed()

        assert result
        connect_testrail.add_to_result(testcaseid, result="Passed", cmnt=lang)
    except Exception as e:
        connect_testrail.add_to_result(testcaseid, result="Failed", cmnt=lang + ". Error: " + str(e))
        pytest.fail(str(e))

我在一个单独的类中的 add_to_result 函数如下:

    def add_to_result(self, case_id, result="Untested", cmnt='None'):
    self.testcase.setdefault(case_id, [])
    self.testcase[case_id].append(result)
    self.testcase[case_id].append(cmnt)

我在 conftest 文件中的拆解终结器是这样的:

@pytest.fixture(scope='function', autouse=True)
def update_test_case_status(request):
    logging.info("Starting Test case...")

    def update_at_the_end():
        logging.info("Ending Test Case...")
        results = test_results()
        for values in results.itervalues():
            if "Failed" in values[0]:
                test_rail_conn.update_test_status(test_result="Failed")
                break
            else:
                test_rail_conn.update_test_status(test_result="Passed")

        test_rail_conn.testcase.clear()

    request.addfinalizer(update_at_the_end)

目标是将所有测试用例及其结果放在字典“testcase”中,最后在终结器期间我想检查 value[0] field = result 并查看是否有任何失败。问题是每次参数运行后,测试用例字段都会被清除,我只能得到一个结果。

感谢任何帮助!

【问题讨论】:

    标签: python testing pytest finalizer fixture


    【解决方案1】:

    Fixtures 可以具有“类”范围 (@pytest.fixture(scope='class')) 并应用于具有 @pytest.mark.usesfixtures("fixture_name") 的类。这样,fixture 只在类内部运行的测试中使用一次,分组在一起(包括它们的参数化):

    https://pytest.org/latest/unittest.html#mixing-pytest-fixtures-into-unittest-testcase-style-tests

    您还可以看到“类”可用作固定装置的范围,如下所述:

    https://pytest.org/latest/fixture.html

    【讨论】:

    • 我的 add_to_result 函数是与 test_rail 相关的类的一部分。我的 update_test_case_status 夹具在 conftest 文件中......我不确定你的意思是什么......
    • @Frodo 测试本身可以放入类中,可以将其标记为使用带有pytest.mark.usefixtures() 的夹具。然后该类中的测试将一起运行,并且该固定装置可用于所有测试,并且如果您使用@pytest.mark.fixture(scope="class"),它将仅运行一次。我将编辑答案以包含更多相关文档。
    猜你喜欢
    • 2021-11-14
    • 1970-01-01
    • 2013-08-31
    • 2021-09-11
    • 2023-01-12
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多