用pytest测试POST请求

问题描述 投票:0回答:1

我正在为我的python应用(flask)用pytest写一个测试.AddMessage函数接收用户输入,生成一个消息,并将其存储在数据库中。

@app.route('/AddMessage',methods = ['POST', 'GET'])
def AddMessage():
   if request.method == 'POST':
       data = request.form
       user_id = data['user_id']
       content = data['content']
       paticipants = [data['participant1'],data['participant2'],data['participant3']]
       m = Message(user_id=user_id,content=content,participants=paticipants)
       db.session.add(m)
       db.session.commit()
       return 'Your message has been successfully saved'

我如何测试它?毕竟,在测试过程中,我无法获得输入,是吗?

python http post pytest
1个回答
0
投票

你可以试试这段代码。

def test_addMessage(self):
        with self.app() as client, self.app_context():
            data = {
                "user_id": "1", 
                "content": "a content", 
                "participant1":"participant1",
                "participant2":"participant2",
                "participant3":"participants"
            }

            response = client.post(
                "/AddMessage",
                data=json.dumps(data),
                headers={"Content-Type": "application/json"},
            )
            self.assertEqual(201, response.status_code)
            self.assertEqual('Your message has been successfully saved', response.data)

另一种更简单的方法是提出请求。

import requests
import json
data = {
         "user_id": "1", 
         "content": "a content", 
         "participant1":"participant1",
         "participant2":"participant2",
         "participant3":"participants"
       }
response = requests.post("/AddMessage", json=json.dumps(data))
json_response = response.json()
print(json_response)

更多细节,请阅读请求 文件

© www.soinside.com 2019 - 2024. All rights reserved.