如何使用flask_testing测试POST请求

时间:2019-07-25 12:42:03

标签: flask-testing

我有一条在数据库中插入新项目的途径。

@projects.route('/add_project', methods=['POST', 'GET'])
@login_required
def add_project():
    form = request.form
    customers = CustomerList.get_all(filters={'status': 'active'}, columns_order='customer_id')
    users = UserProperty.get_all(join_model='User', filters={'active': 1}, columns_order='full_name')

    if request.method == 'POST':

        new_project_id = Offer.get_next_project_id(customer_id=form['customer_id'])

        offer = Offer(customer_id=form['customer_id'], project_id=new_project_id[-3:],
                      project_fullname=form['project_name'])
        DBSession.commit_to_db(offer)

        new_project = ProjectListDB(project_id=new_project_id, customer_id=form['customer_id'],
                                    project_name=form['project_name'],
                                    group_id=form['group_id'], project_manager=form['project_manager'],
                                    technical_lead=form['technical_lead'], status='active', wh_status=form['wh_status'])
        DBSession.commit_to_db(new_project)

        flash("You've just inserted new project {}".format(new_project.project_id))

    return render_template('projects/add_project.html', customers=customers, users=users)

如何测试此路线? 我应该检查响应码200吗? 该测试返回respose_code 200,但我发现该项目尚未插入数据库表中。

这是我的测试脚本

import os
import unittest
from sqlalchemy.exc import IntegrityError

from flask_testing import TestCase

from app import create_app, db
app = create_app('testing')


class TestPageLoad(TestCase):

    def create_app(self):
        app.config.from_object('config.TestingConfig')

        return app

    def setUp(self):
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.client = self.app.test_client(use_cookies=True)
        db.create_all()

    def tearDown(self):
        """Defines what should be done after every single test in this test group."""
        db.session.remove()
        self.app_context.pop()

    def test_add_new_project(self):
        form = dict(
            project_id='1901P01',
            customer_id=1901,
            project_name='Example project name',
            group_id='NRS', project_manager=146, technical_lead=146, status='active', wh_status='active',
            project_fullname='Project full_name'
        )
        response = self.client.post('/projects/add_project', data=form)
        self.assertStatus(response, 200)

0 个答案:

没有答案