""" 登录模块测试 - 测试密码验证和密码管理功能 """ import unittest import os import tempfile import gc from database import DatabaseManager, get_db_connection class TestLogin(unittest.TestCase): """登录功能测试类""" def setUp(self): self.temp_dir = tempfile.mkdtemp() self.db_path = os.path.join(self.temp_dir, "test_login.db") self.db_manager = DatabaseManager(self.db_path) self.conn = None def tearDown(self): if self.conn: try: self.conn.close() except: pass gc.collect() try: if os.path.exists(self.db_path): os.remove(self.db_path) if os.path.exists(self.temp_dir): os.rmdir(self.temp_dir) except: pass def get_conn(self): self.conn = get_db_connection(self.db_path) return self.conn def test_default_admin_password(self): """测试默认管理员密码""" with self.get_conn() as conn: cursor = conn.execute( "SELECT value FROM admin_settings WHERE key = ?", ("admin_password",) ) row = cursor.fetchone() self.assertEqual(row[0], "123456") def test_default_user_password(self): """测试默认普通用户密码""" with self.get_conn() as conn: cursor = conn.execute( "SELECT value FROM admin_settings WHERE key = ?", ("user_password",) ) row = cursor.fetchone() self.assertEqual(row[0], "123456") def test_update_admin_password(self): """测试更新管理员密码""" with self.get_conn() as conn: conn.execute( "UPDATE admin_settings SET value = ? WHERE key = ?", ("newpass123", "admin_password") ) conn.commit() cursor = conn.execute( "SELECT value FROM admin_settings WHERE key = ?", ("admin_password",) ) row = cursor.fetchone() self.assertEqual(row[0], "newpass123") def test_update_user_password(self): """测试更新普通用户密码""" with self.get_conn() as conn: conn.execute( "UPDATE admin_settings SET value = ? WHERE key = ?", ("userpass456", "user_password") ) conn.commit() cursor = conn.execute( "SELECT value FROM admin_settings WHERE key = ?", ("user_password",) ) row = cursor.fetchone() self.assertEqual(row[0], "userpass456") def test_password_verification_correct(self): """测试正确密码验证""" with self.get_conn() as conn: cursor = conn.execute( "SELECT value FROM admin_settings WHERE key = ?", ("admin_password",) ) stored_pwd = cursor.fetchone()[0] self.assertEqual(stored_pwd, "123456") def test_password_verification_incorrect(self): """测试错误密码验证""" with self.get_conn() as conn: cursor = conn.execute( "SELECT value FROM admin_settings WHERE key = ?", ("admin_password",) ) stored_pwd = cursor.fetchone()[0] self.assertNotEqual(stored_pwd, "wrongpassword") def test_insert_or_replace_password(self): """测试INSERT OR REPLACE密码设置""" with self.get_conn() as conn: conn.execute( "INSERT OR REPLACE INTO admin_settings (key, value) VALUES (?, ?)", ("admin_password", "replaced123") ) conn.commit() cursor = conn.execute( "SELECT value FROM admin_settings WHERE key = ?", ("admin_password",) ) row = cursor.fetchone() self.assertEqual(row[0], "replaced123") if __name__ == "__main__": unittest.main()