請教一個 pytest 中 fixture 相關問題:將 fixture 中寫入 allure 附件的程式碼提出來定義成自定義方法後,就無法按預期寫入 allure 附件了

耿晓發表於2024-07-02

我定義了一個 fixture,他本身斷言失敗後,會在 allure 報告中新增附件,記錄這個 fixture 的響應資訊。但是為了程式碼複用,我將斷言相關程式碼提了出來,但是提出來之後發現,如果 fixture 內部斷言失敗,並不會在 allure 報告中新增附件,請問是為什麼?我該怎麼解決?

這是原始碼,可以正常新增附件,allure 報告效果如下:

@pytest.fixture(scope="session", autouse=True)
def tf_get_trainerId_xiehe(tf_getSession):
    url = Environment.HOST_ADMIN + 'managerList'
    data = {'page': 1,
            'limit': 30,
            'keys': Environment.userphone_tea,
            'characterType': 1,
            'roles': ''}
    resp = tf_getSession.post(url=url, data=data)

    """
    初始想法:我定義了許多fixture,有大部分fixture都需要下面的斷言並寫allure附件的程式碼,
    所以為了複用,我期望是將下面的程式碼提出來,但提出來之後發現就無法成功寫入allure附件了。
    """
    allure.step("Check response status code and content")
    try:
        assert resp.status_code == 200, f"Expected status code 200 but got {resp.status_code}"
        assert resp.json()['code'] == 2000, f"Expected code {2000} but got {resp.json()['code']}"
        AssociatedDataTanQiang.id_xiehe_admin = resp.json()['data']['list'][0]['id']
    except (AssertionError,IndexError) as e:
        allure.attach(
            json.dumps(resp.json(), ensure_ascii=False, indent=2),
            name="response.json",
            attachment_type=allure.attachment_type.JSON
        )
        allure.attach(
            resp.text,
            name="response.text",
            attachment_type=allure.attachment_type.TEXT
        )
        raise AssertionError(f"Fixture: {tf_get_trainerId_xiehe.__name__}斷言失敗") from e

    yield

這是修改後的程式碼,無法正常在 allure 報告中新增附件:

def check_response(resp, target_position, expected_code=2000):
    allure.step("Check response status code and content")
    try:
        assert resp.status_code == 200, f"Expected status code 200 but got {resp.status_code}"
        assert resp.json()['code'] == expected_code, f"Expected code {expected_code} but got {resp.json()['code']}"
        return target_position
    except (AssertionError,IndexError) as e:
        allure.attach(
            json.dumps(resp.json(), ensure_ascii=False, indent=2),
            name="response.json",
            attachment_type=allure.attachment_type.JSON
        )
        allure.attach(
            resp.text,
            name="response.text",
            attachment_type=allure.attachment_type.TEXT
        )
        raise AssertionError(f"Fixture: 斷言失敗") from e


@pytest.fixture(scope="session", autouse=True)
def tf_get_trainerId_xiehe(tf_getSession):
    url = Environment.HOST_ADMIN + 'managerList'
    data = {'page': 1,
            'limit': 30,
            'keys': Environment.userphone_tea,
            'characterType': 1,
            'roles': ''}
    resp = tf_getSession.post(url=url, data=data)

    AssociatedDataTanQiang.id_xiehe_admin = check_response(resp,resp.json()['data']['list'][0]['id'])
       yield

相關文章