""" 款式管理GUI测试模块 使用PyQt测试框架测试款式管理功能 """ import unittest import os import sys import tempfile from PyQt5.QtWidgets import QApplication, QMessageBox from PyQt5.QtTest import QTest from PyQt5.QtCore import Qt # 添加父目录到路径以导入模块 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from database import DatabaseManager from garment_dialogs import GarmentLibraryDialog class TestGarmentGUI(unittest.TestCase): """款式管理GUI测试类""" @classmethod def setUpClass(cls): """测试类初始化:创建QApplication实例""" cls.app = QApplication.instance() if cls.app is None: cls.app = QApplication(sys.argv) def setUp(self): """每个测试前准备:创建临时数据库和对话框""" self.temp_dir = tempfile.mkdtemp() self.db_path = os.path.join(self.temp_dir, "test_fabric.db") self.db_manager = DatabaseManager(self.db_path) # 添加测试原料 with self.db_manager.get_conn() as conn: conn.execute(''' INSERT INTO fabrics (model, category, color, unit, timestamp) VALUES (?, ?, ?, ?, datetime('now')) ''', ("TEST-FABRIC-001", "布料", "白色", "米")) conn.commit() # 创建对话框实例 self.dialog = GarmentLibraryDialog(self.db_path) # 保存原始消息框 self._original_msgbox = QMessageBox.information self._original_warning = QMessageBox.warning self._original_critical = QMessageBox.critical # Mock消息框 QMessageBox.information = lambda *args, **kwargs: None QMessageBox.warning = lambda *args, **kwargs: None QMessageBox.critical = lambda *args, **kwargs: None def tearDown(self): """每个测试后清理""" # 恢复消息框 QMessageBox.information = self._original_msgbox QMessageBox.warning = self._original_warning QMessageBox.critical = self._original_critical # 关闭对话框 self.dialog.close() self.dialog.deleteLater() # 清理数据库 import gc 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 test_load_garments(self): """测试加载款式列表""" # 添加测试款式 with self.dialog.get_conn() as conn: conn.execute(''' INSERT INTO garments (style_number) VALUES (?) ''', ("STYLE-001",)) conn.commit() # 刷新表格 self.dialog.load_garments() # 验证表格有数据 self.assertGreater(self.dialog.garment_table.rowCount(), 0, "表格应该有数据") def test_search_garments(self): """测试搜索款式""" # 添加多个测试款式 with self.dialog.get_conn() as conn: conn.execute(''' INSERT INTO garments (style_number) VALUES (?) ''', ("SEARCH-001",)) conn.execute(''' INSERT INTO garments (style_number) VALUES (?) ''', ("OTHER-001",)) conn.commit() # 搜索特定款式 self.dialog.search_input.setText("SEARCH") self.dialog.load_garments() # 验证只显示匹配的结果 row_count = self.dialog.garment_table.rowCount() for row in range(row_count): style_item = self.dialog.garment_table.item(row, 0) if style_item: self.assertIn("SEARCH", style_item.text(), "应该只显示匹配的款式号") if __name__ == "__main__": unittest.main()