我正在使用flask做一些api端点。我想知道如何设置测试的tearDown,以使两个测试(即GET特定报告和DELETE特定报告)不会冲突。这是我的代码:
models.py
reports = [
{
"id": 1,
"createdOn": "25-11-2018 09:57",
"createdBy": 1,
"type": "Red Flag Report",
"location": "1,1",
"status": "Resolved",
"comment": "Act quickly"
},
{
"id": 2,
"createdOn": "26-11-2018 09:57",
"createdBy": 2,
"type": "Red Flag Report",
"location": "2,2",
"status": "Under investigation",
"comment": "Don't let them get away with it"
}
]
class ReportsModel():
def __init__(self):
self.db = reports
def get_specific(self, report_id):
return next(filter(lambda x: x["id"] == int(report_id), self.db), None)
def delete(self, report_index):
self.db.pop(report_index)
views.py
from flask import Flask, request
from flask_restful import Resource
from .models import ReportsModel
class Report(Resource):
def __init__(self):
self.reports = ReportsModel()
def get(self, id):
report = self.reports.get_specific(id)
if report:
return {"status": 200, "data": [report]}
else:
return {"status": 404, "error": "Report record not found"}, 404
def delete(self, id):
report= self.reports.get_specific(id)
if report:
self.reports.delete(self.reports.db.index(report))
return {"status": 200,"data": [{"id": int(id), "message": "Report record has been deleted"}]}
else:
return {"status": 404, "error": "Report record not found"}, 404
test_reports.py
from unittest import TestCase
from flask import json
from flask_restful import request
from app import create_app
from app.api.v1.models import ReportsModel
app = create_app()
class TestReports(TestCase):
def setUp(self):
self.reports = ReportsModel()
self.app = app.test_client()
self.app.testing = True
def test_get_specific_report(self):
response = self.app.get('/api/v1/reports/1')
data = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(data, {"status": 200, "data": [self.reports.get_specific(1)]})
def test_delete_a_specific_report(self):
response = self.app.delete('/api/v1/reports/1')
data = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(data, {"status": 200, "data": [{"id": 1, "message": "Report record has been deleted"}]})
当我在Postman上运行代码时,它可以完美运行。但是,当我运行测试时,第一个测试失败,提示预期状态代码为404,并且显示未找到报告的消息。如果我将id 2放在两个测试中,则结果相同。 但是,如果我在一个测试中使用1,在另一个测试中使用2,则测试通过。
我有什么办法可以阻止测试失败?
编辑:我应该提到,我的想法是添加一个tearDown(),以便可以为每个测试重置所有内容。不幸的是,到目前为止,我的想法是:
def tearDown(self):
self.reports = 0 #or some other value
但是我还没有找到合适的方法来做到这一点。
del self.reports
也没有用。