在一系列测试中测试之间保存数据的模式

时间:2018-03-30 17:15:14

标签: python testing integration-testing pytest python-unittest

当我需要获取一些数据并在其他请求中使用它时,我可以使用哪些模式进行API测试?

下一个例子:

def test_item_get():
    r = get_json('/item')
    assert r.status_code == 200


def test_item_update():
    r = get_json('/item')
    assert r.status_code == 200

    item_uuid = r.json[0]['uuid']
    assert is_uuid(item_uuid)

    r = put_json('/item/{}'.format(item_uuid), {'description': 'New desc'})
    assert r.status_code == 200


def test_item_manager():
    r = get_json('/item')
    assert r.status_code == 200

    item_uuid = r.json[0]['uuid']
    assert is_uuid(item_uuid)

    r = put_json('/item/{}'.format(item_uuid), {'description': 'New desc'})
    assert r.status_code == 200

    r = get_json('/item/{}'.format(item_uuid))
    assert r.status_code == 200
    assert r.json['description'] = 'New desc'

    r = delete_json('/item/{}'.format(item_uuid))
    assert r.status_code == 200
    assert r.json['result'] == True

    r = delete_json('/item/{}'.format(item_uuid))
    assert r.status_code == 404

看起来我应该将test_item_manager分成更小的部分,但我不确定选择哪种方式。

完美地说,如果有pytestunittest的方式,但是其他测试模块甚至是带有类似任务解决方案的源代码链接都会很好。

1 个答案:

答案 0 :(得分:1)

理想情况下,您必须将test_item_manager分成多个测试,以分别测试每个CRUD操作。您可以拥有一个功能级别夹具,它可以为您提供可以执行操作的item_uuid。当然,你必须确保你的item_uuid灯具为每个测试返回一个有效的uuid

对于e.x

@pytest.fixture
def item_uuid():
    r = get_json('/item')
    assert r.status_code == 200
    return r.json[0]['uuid']

def test_item_get():
    # You can keep this test or remove as it gets covered under fixture.
    r = get_json('/item')
    assert r.status_code == 200


def test_item_update(item_uuid):
    assert is_uuid(item_uuid)

    r = put_json('/item/{}'.format(item_uuid), {'description': 'New desc'})
    assert r.status_code == 200
    assert r.json['description'] = 'New desc'


def test_item_delete(item_uuid):
   r = delete_json('/item/{}'.format(item_uuid))
   assert r.status_code == 200
   assert r.json['result'] == True

   r = delete_json('/item/{}'.format(item_uuid))
   assert r.status_code == 404