清理 pytest 中 POST 方法后的 API 数据。

huangapple go评论54阅读模式
英文:

Cleanup API data in pytest after post method

问题

这是从API中删除数据的最佳方式吗?

def test_can_get_all_items():
   ### 一些代码 ...

    # 在POST和GET方法后清除数据

    try:
        for item_id in range(n):
            delete_response = requests.delete(ENDPOINT + f"delete-item?item_id={item_id+1}")
            assert delete_response.status_code == 200
    except:
        pass

    ### 一些代码 ...

我使用了Delete方法来删除数据,但我不确定这种方法是否最优。

英文:

Is this optimal to delete data from API in this way?

def test_can_get_all_items():
   ### some code ...

    # CLEANUP DATA AFTER POST AND GET METHOD 

    try:
        for item_id in range(n):
            delete_response = requests.delete(ENDPOINT + f"delete-item?item_id={item_id+1}")
            assert delete_response.status_code == 200
    except:
        pass

    ### some code ...

I delete this with a Delete method but i dont know did this way is optimal.

答案1

得分: 0

你可以使用Python的yield关键字来实现这个目的。

举个例子:

import pytest

@pytest.fixture()
def cleanup():
    yield
    print("进行一些清理操作")

def addition(a, b):
    return a + b

def test_addition(cleanup):
    result = addition(1, 2)
    assert result == 3

在这种情况下,你将cleanup fixture传递给test_addition测试。这个fixture会"yield"到函数(也就是运行函数的内容),当函数执行完毕后,它会执行某些操作,例如在这种情况下会打印"进行一些清理操作"。

要在本地进行测试,运行pytest <文件名>.py -c-c选项允许你在终端中看到打印输出!

因此,在你的情况下,你可以在cleanup函数中添加删除操作:

@pytest.fixture()
def cleanup():
    yield
    for item_id in range(n):
        delete_response = requests.delete(ENDPOINT + f"delete-item?item_id={item_id+1}")
英文:

You can use python's yield keyword for this purpose.

As an example:

import pytest

@pytest.fixture()
def cleanup():
    yield
    print(&quot;do some cleanup&quot;)

def addition(a, b):
    return a + b

def test_addition(cleanup):
    result = addition(1, 2)
    assert result == 3

In this case, you pass the cleanup fixture to the test_addition test. The fixture will "yield" to the function (that is, will run the contents of the function) and when it is finished it will do something, in this case it will print "do some cleanup".

To test locally, run pytest &lt;file name&gt;.py -c. -c allow you to see the print in the terminal!

So in your case, you would add the delete in the cleanup function:

@pytest.fixture()
def cleanup():
   yield
   for item_id in range(n):
       delete_response = requests.delete(ENDPOINT + f&quot;delete-item?item_id={item_id+1}&quot;)

huangapple
  • 本文由 发表于 2023年3月7日 00:35:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653444.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定