热门IT资讯网

python中的单元测试和数据库测试

发表于:2024-11-28 作者:热门IT资讯网编辑
编辑最后更新 2024年11月28日,登录测试被测试的代码逻辑@app.route('/login', methods=['POST'])def login(): username = request.form.get('usern

登录测试
被测试的代码逻辑

@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 jsonimport unittestfrom demo1_login import appclass 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-8import unittestfrom 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)
0