How to write Python unit test cases for the function written using Flask Framework

时间:2019-03-19 14:53:47

标签: python python-3.x python-2.7 flask flask-sqlalchemy

I am new to writing unit test cases in Python. I wrote below API code using Flask and want to write unit test for it. I read a lot of unit test suggestions from http://flask.pocoo.org/docs/0.12/testing/ but none of them are working

Flask API code. It registers the users and then allows the login. I am using SQLALCHEMY.

from api import app
from api.models import User
from api import auth
from flask import Flask, abort, request, jsonify, g, url_for
from api import db
from flask_jwt_extended import (JWTManager, jwt_required, create_access_token,
    get_jwt_identity)

@auth.verify_password
def verify_password(username, password):
    user = User.query.filter_by(username = username).first()
    if not user or not user.verify_password(password):
        return False
    g.user = user
    return True

@app.route('/api/users', methods=['POST'])
def new_user():
    username = request.json.get('username')
    password = request.json.get('password')
    bio = request.json.get('bio')
    image = request.json.get('image')
    follow = request.json.get('follow')
    user = User(username = username, bio=bio, image=image, follow=follow)
    user.hash_password(password)
    db.session.add(user)
    db.session.commit()
    return ("user added")

@app.route('/api/users/login', methods=['POST'])
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400

    # Identity can be any data that is json serializable
    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token), 200

Model code

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(32), index=True)
#    password = db.Column(db.String(64))
    bio = db.Column(db.String(64))
    image = db.Column(db.String(64))
    follow = db.Column(db.String(32))
    password_hash = db.Column(db.String(128))

    def hash_password(self, password):
        self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):
        return pwd_context.verify(password, self.password_hash) 

Test case:

import os
import api
import unittest
import tempfile
import flask
from flask import jsonify

app = flask.Flask(__name__)

class apiTestCase(unittest.TestCase):

    def setUp(self):
        self.db_fd, api.app.config['DATABASE'] = tempfile.mkstemp()
        api.app.testing = True
        self.app = api.app.login()
        with api.app.app_context():
            api.route.login()

    def tearDown(self):
        os.close(self.db_fd)
        os.unlink(api.app.config['DATABASE'])

    def login(self, username, password):
        data=jsonify({"username": "username", "password":"password"})
        return self.app.post('/api/users/login', data
        , follow_redirects=True)   

    def test_login(self):
        rv = self.login('abc123', 'xyz123')
        print "hi" 
        print rv



if __name__ == '__main__':
    unittest.main()

Error

ERROR: test_login (__main__.apiTestCase)
---------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 15, in setUp
    self.app = api.app.login()
AttributeError: 'Flask' object has no attribute 'login'

Any help would be highly appreciated.

0 个答案:

没有答案