所以我试图为我正在创建的这个电影网站编写一个测试用例,我想测试 add_user 功能,每次测试它时,它都会在我的 SQLite 数据库中创建用户。然后返回失败,表明用户已经存在。
def add_user(self, name):
param = {'name': name}
query = text('Insert into users (name) values (:name)')
check_usr_query = text('Select name from users '
'Where name = :name')
check_usr = self._execute_query(check_usr_query, param).fetchone()
if check_usr is not None:
return 'User Already Exists in Database'
else:
with self.engine.connect() as conn:
conn.execute(query, param)
conn.commit()
return 'Successfully added user'
import pytest
from DataManager.sql_data_manager import SQLiteDataManager
dataManager = SQLiteDataManager('DataManager/movie.db')
def test_add_user():
name = 'Esth'
test_data = dataManager.add_user(name)
check_usr = dataManager.get_user_by_name(name)
if test_data == 'Successfully added user':
assert test_data == 'Successfully added user'
print(name + ' added to db')
elif test_data == 'User Already Exists in Database':
assert check_usr is not None
print(name + ' Already exists in the db')
您有多种选择:
使用 pytest 拆解装置在测试完成时清理用户
在测试启动时删除用户
Esth
(如果存在)
使用随机名称
创建用户在每次测试运行时创建新数据库