1. 程式人生 > >python中的單元測試和數據庫測試

python中的單元測試和數據庫測試

ces log def client tca 定義 aaaaa .com code

登錄測試
被測試的代碼邏輯

@app.route(‘/login‘, methods=[‘POST‘])
def login():
    username = request.form.get(‘username‘)
    password = request.form.get(‘password‘)

    # 判斷參數是否為空
    if not all([username, password]):
        result = {
            "errcode": -2,
            "errmsg": "params error"
        }
        return jsonify(result)

    # a = 1 / 0
    # 如果賬號密碼正確
    # 判斷賬號密碼是否正確
    if username == ‘itheima‘ and password == ‘python‘:
        result = {
            "errcode": 0,
            "errmsg": "success"
        }
        return jsonify(result)
    else:
        result = {
            "errcode": -1,
            "errmsg": "wrong username or password"
        }
        return jsonify(result)

單元測試代碼

import json
import unittest
from demo1_login import app

class LoginTest(unittest.TestCase):
    """為登錄邏輯編寫測試案例"""

    def setUp(self):
        app.testing = True
        self.client = app.test_client()

    def test_empty_username_password(self):
        """測試用戶名與密碼為空的情況[當參數不全的話,返回errcode=-2]"""
        response = app.test_client().post(‘/login‘, data={})
        json_data = response.data
        json_dict = json.loads(json_data)

        self.assertIn(‘errcode‘, json_dict, ‘數據格式返回錯誤‘)
        self.assertEqual(json_dict[‘errcode‘], -2, ‘狀態碼返回錯誤‘)

        # TODO 測試用戶名為空的情況

        # TODO 測試密碼為空的情況

    def test_error_username_password(self):
        """測試用戶名和密碼錯誤的情況[當登錄名和密碼錯誤的時候,返回 errcode = -1]"""
        response = app.test_client().post(‘/login‘, data={"username": "aaaaa", "password": "12343"})
        json_data = response.data
        json_dict = json.loads(json_data)
        self.assertIn(‘errcode‘, json_dict, ‘數據格式返回錯誤‘)
        self.assertEqual(json_dict[‘errcode‘], -1, ‘狀態碼返回錯誤‘)

        # TODO 測試用戶名錯誤的情況

        # TODO 測試密碼錯誤的情況

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

數據庫測試:

#coding=utf-8
import unittest
from author_book import *

#自定義測試類,setUp方法和tearDown方法會分別在測試前後執行。以test_開頭的函數就是具體的測試代碼。
class DatabaseTestCase(unittest.TestCase):
    def setUp(self):
        app.config[‘TESTING‘] = True
        app.config[‘SQLALCHEMY_DATABASE_URI‘] = ‘mysql://root:mysql@localhost/test0‘
        self.app = app
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    #測試代碼
    def test_append_data(self):
        au = Author(name=‘xxxxx‘)
        bk = Book(info=‘python‘)
        db.session.add_all([au,bk])
        db.session.commit()
        author = Author.query.filter_by(name=‘itcast‘).first()
        book = Book.query.filter_by(info=‘python‘).first()
        #斷言數據存在
        self.assertIsNotNone(author)
        self.assertIsNotNone(book)

python中的單元測試和數據庫測試