英文:
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("do some cleanup")
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 <file name>.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"delete-item?item_id={item_id+1}")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论