import pytest import os import tempfile from dotenv import load_dotenv # 加载测试环境变量 load_dotenv('env.test') @pytest.fixture(scope='session') def app(): """创建测试应用实例""" from src.flask_prompt_master import create_app from config import TestingConfig # 创建临时数据库文件 db_fd, db_path = tempfile.mkstemp() # 设置测试环境变量 os.environ['FLASK_ENV'] = 'testing' os.environ['DATABASE_URL'] = f'sqlite:///{db_path}' app = create_app(TestingConfig) # 创建数据库表 with app.app_context(): from src.flask_prompt_master import db db.create_all() # 创建测试数据 create_test_data(db) yield app # 清理 os.close(db_fd) os.unlink(db_path) @pytest.fixture def client(app): """创建测试客户端""" return app.test_client() @pytest.fixture def runner(app): """创建测试运行器""" return app.test_cli_runner() def create_test_data(db): """创建测试数据""" from src.flask_prompt_master.models import PromptTemplate, User, WxUser # 创建测试模板 test_template = PromptTemplate( name='测试模板', description='这是一个测试模板', category='软件开发', industry='互联网', profession='开发工程师', sub_category='后端开发', system_prompt='你是一个专业的后端开发工程师...', is_default=True ) db.session.add(test_template) # 创建测试用户 test_user = User( username='testuser', email='test@example.com' ) db.session.add(test_user) # 创建测试微信用户 test_wx_user = WxUser( openid='test_openid_123', session_key='test_session_key_123', nickname='测试用户', avatar_url='https://example.com/avatar.jpg' ) db.session.add(test_wx_user) db.session.commit() @pytest.fixture def auth_headers(): """认证头信息""" return { 'Authorization': 'Bearer test_token_123', 'Content-Type': 'application/json' } @pytest.fixture def wx_auth_headers(): """微信认证头信息""" return { 'Content-Type': 'application/json' }