【问题标题】:Pytest how to pass parameters/data between tests?Pytest如何在测试之间传递参数/数据?
【发布时间】:2020-10-27 17:38:18
【问题描述】:

我正在尝试在测试用例之间传递参数。 我做了一个测试用例,它正在发出回复{"id":"5f985866f5532a52bb259926","name":"testName","desc":"","descData":null}

我想将 "id":"5f985866f5532a52bb259926" 作为参数传递给下一个测试用例。

我目前拥有的东西

@pytest.mark.first
def test_create_a_board():
    api_board = APIBoard()
    create_board = api_board.create_board_call(board_name='testName')
    Logger.LogInfo(f"creating a board named {create_board['name']}")


def test_create_3_cards_on_board():
    api_board = APIBoard()
    create_list = api_board.create_a_list_on_a_board_call()

def test_create_a_board 返回

{"id":"5f985866f5532a52bb259926"}

如何将 {"id":"5f985866f5532a52bb259926"} 从 test_create_a_board 传递到 test_create_3_cards_on_board ?来自Pytest的层面

【问题讨论】:

  • 让一个测试依赖于另一个测试的输出通常不是一个好主意。如果您真的想这样做,则必须为此使用 gloval 变量,但最好将测试重构为彼此独立。
  • 最好在一个测试中使用它,并使用多个断言。虽然我想最好的问题是真正问“我想要确保什么”并将其封装在单个测试中。
  • @MrBean Bremen 所以如果我需要 TC2 中的 Post 调用中的某些内容,我也应该在 TC2 中发送相同的 POST 调用?我还记得 Used Behave 时我使用上下文通过步骤和 tc 传递参数

标签: python pytest


【解决方案1】:

我建议使用类或模块范围的 fixture 来创建一个供多个测试共享的变量:

@pytest.fixture(scope="module")
def board():
    api_board = APIBoard()
    yield api_board.create_board_call(board_name="test_name")

def test_create_a_board(board):
    Logger.LogInfo(f"creating a board named {board['name']}")

def test_create_3_cards_on_board(board):
    create_list = board.create_a_list_on_a_board_call()

一些注意事项:

这些看起来可能是冒烟测试(即在没有断言的情况下运行以确保没有中断的测试),但您可以考虑在测试中添加断言:

def test_create_a_board(board):
    expected = {"expected": "output"}
    assert board['name'] == expected

def test_create_3_cards_on_board(board):
    create_list = board.create_a_list_on_a_board_call()
    assert create_list == ["whatever", "list"]

此外,除非这些测试是专门为测试外部资源而设计的,否则您可以考虑模拟 API 调用的结果。

@pytest.fixture(scope="module")
def mock_board():
    return {"board": "mock"}

或者考虑使用unittest.mock 模拟出您要测试的对象。

【讨论】:

    猜你喜欢
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多