0
我只是想测试Flask REST服务的CRUD
操作。单元测试REST API Python
- 在
CREATE
操作中,我想创建一个新的对象。 - 在
UPDATE
操作中,我需要获取创建操作中创建的对象的id并更新它。 - 在
DELETE
操作中,我需要删除创建操作中创建的对象。
我该如何解决这个问题?
当前的代码看起来是这样的
class BaseTestCase(TestCase):
def create_app(self):
return create_app('testing')
def setUp(self):
self.response = self.client.get('/api/v1/list_portfolios').json
self.portfolio_id = self.response['respbody']['Portfolios'][0]['_id']
self.view_response = self.client.get('/api/v1/view_portfolio/' + self.portfolio_id).json
class ModelTestAPI(BaseTestCase):
def test_model_create(self):
model_create_data = {
"PortfolioId": "558d0e575dddb726b8cd06bc",
"ModelName": "New Model",
"ModelLifetimePeriod": "Month",
"ModelLifetimeDuration": 12
}
response = self.client.post('/api/v1/model/create', data=dumps(model_create_data),
content_type='application/json').json
portfolio_model_id = response['respbody']['_id']
print(portfolio_model_id)
new_model_dict = model_create_data.copy()
new_model_dict['_id'] = portfolio_model_id
new_json = response['respbody'].copy()
new_json.pop('CreateDate', None)
new_json.pop('LastUpdateDate', None)
self.assertDictEqual(new_model_dict, new_json)
def test_model_update(self):
data = {
"ModelName": "UPDATE New Model",
"ModelLifetimePeriod": "Month",
"ModelLifetimeDuration": 6
}
portfolio_model_id = self.view_response['respbody']['PortfolioModels'][-1]['_id']
json = self.client.put('/api/v1/model/' + portfolio_model_id, data=dumps(data),
content_type='application/json').json
data['_id'] = portfolio_model_id
new_json = json['respbody'].copy()
new_json.pop('CreateDate', None)
new_json.pop('LastUpdateDate', None)
new_json.pop('PortfolioId', None)
self.assertDictEqual(data, new_json)
def test_model_delete(self):
portfolio_model_id = self.view_response['respbody']['PortfolioModels'][-1]['_id']
json = self.client.delete('http://localhost:5000/api/v1/model/' + portfolio_model_id).json
expected_dict = {'success': True}
self.assertDictEqual(expected_dict, json['respbody'])
你正在使用什么框架?,以及当前的代码没有做,它应该做什么? –