pytest烧瓶404 test_client

时间:2019-05-28 14:15:39

标签: python flask pytest

我编写了以下代码来对我的登录功能进行单元测试:

conftest.py

import pytest 
from api import app

@pytest.fixture
def client(request):
    test_client = app.test_client()

    def teardown():
        pass

    request.addfinalizer(teardown)
    return test_client

test_users.py

import json

def test_new_user(client):
    data = {    
        "username": 'xxx.com',
        'password': 'xxx'
    }
    response = client.post('/login', data=json.dumps(data), content_type='application/json')
    assert response.status_code == 200

api.py

import json, configparser
from flask import Flask, Response
from flask_cors import CORS
from utils.database import db, Role, Module

app = Flask(__name__)
parser = configparser.ConfigParser()
parser.read('config.ini')

db_username = parser.get('PRODUCTION', 'db_username')
db_password = parser.get('PRODUCTION', 'db_password')
db_host = parser.get('PRODUCTION', 'db_host')
db_port = parser.get('PRODUCTION', 'db_port')
db_name = parser.get('PRODUCTION', 'db_name')

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://' +  db_username + ":" + db_password + "@" + db_host + ":" + db_port + "/" + db_name 

CORS(app)

with app.app_context():
    db.init_app(app)
    admin_role = Role(name="admin")
    user_role = Role(name="user")

    db.create_all()

    if(Role.query.filter_by(name='admin').first()) == None:
        db.session.add(admin_role)
    if(Role.query.filter_by(name='user').first()) == None:
        db.session.add(user_role)

    modules = {
        'x': "a", 
        'y': "b", 
        'z': "c"
    }

    for module in modules.keys():
        if(Module.query.filter_by(name=module).first() == None):
            db.session.add(Module(name=module, description=modules[module]))

    db.session.commit()

但是当我运行pipenv run pytest时,得到了以下响应E

E    assert 404 == 200
E        +  where 404 = <Response streamed [404 NOT FOUND]>.status_code

暗示该路由不存在。如何创建功能测试客户端,该客户端不返回在应用程序中存在的路由上找不到的404?

0 个答案:

没有答案