#!/usr/bin/env python3 # -*- coding: utf-8 -*- """集成测试:模拟完整请求流程,Mock外部微信API,仅验证本地路由""" import os, sys, json, unittest from unittest.mock import patch, MagicMock from pathlib import Path os.chdir(Path(__file__).parent) sys.path.insert(0, str(Path(__file__).parent)) import sqlite3, tempfile _TMP_DB_PATH = Path(tempfile.mktemp(suffix='.db')) class TestRoutes(unittest.TestCase): @classmethod def setUpClass(cls): import db as db_module cls._original_get_db = db_module.get_db cls._original_db_path = db_module.DB_PATH db_module.DB_PATH = _TMP_DB_PATH def _test_db(): conn = sqlite3.connect(str(db_module.DB_PATH)) conn.row_factory = sqlite3.Row return conn db_module.get_db = _test_db from db import init_db init_db() # Mock 外部依赖 cls._patchers = [] for target, ret in [ ('wechat.request_api', {"rtn_code": 0, "data": {"bicycleStation": []}}), ('wechat.request_with_user_auth', {"rtn_code": 0, "data": {"order_id": 99999999, "account": {}, "nonDealOrder": None, "minutes": 0, "code": "TEST"}}), ]: p = patch(target) m = p.start() m.return_value = ret cls._patchers.append(p) for target in ['requests.get', 'requests.post']: p = patch(target) m = p.start() mr = MagicMock() mr.json.return_value = {"rtn_code": 0, "data": {}} mr.status_code = 200 mr.text = '{}' mr.content = b'{}' m.return_value = mr cls._patchers.append(p) from app import app app.config['TESTING'] = True app.config['SECRET_KEY'] = 'test' cls.app = app cls.client = app.test_client() cls.token = None @classmethod def tearDownClass(cls): for p in cls._patchers: p.stop() import db as db_module db_module.get_db = cls._original_get_db db_module.DB_PATH = cls._original_db_path if _TMP_DB_PATH.exists(): _TMP_DB_PATH.unlink() def _h(self): return {"Authorization": f"Bearer {self.token}"} if self.token else {} def test_01_register(self): r = self.client.post("/api/auth/register", json={"email": "test@t.com", "password": "test123"}) d = r.get_json() print(f" /api/auth/register: {r.status_code} rtn={d.get('rtn_code')}") if d.get("rtn_code") == 0: self.__class__.token = d.get("data", {}).get("token") def test_02_login(self): r = self.client.post("/api/auth/login", json={"email": "test@t.com", "password": "test123"}) d = r.get_json() print(f" /api/auth/login: {r.status_code} rtn={d.get('rtn_code')}") self.assertEqual(d.get("rtn_code"), 0) self.__class__.token = d.get("data", {}).get("token") def test_03_profile(self): r = self.client.get("/api/auth/profile", headers=self._h()) print(f" /api/auth/profile: {r.status_code}") self.assertEqual(r.status_code, 200) def test_04_user_info(self): r = self.client.get("/api/auth/user_info", headers=self._h()) print(f" /api/auth/user_info: {r.status_code}") self.assertEqual(r.status_code, 200) def test_05_packages(self): r = self.client.get("/api/auth/packages", headers=self._h()) print(f" /api/auth/packages: {r.status_code}") self.assertNotEqual(r.status_code, 500) def test_06_config(self): r = self.client.get("/api/config") print(f" /api/config: {r.status_code}") self.assertEqual(r.status_code, 200) def test_07_map(self): r = self.client.get("/api/map?type=3") print(f" /api/map: {r.status_code}") self.assertEqual(r.status_code, 200) def test_08_order_unlock_no_params(self): r = self.client.post("/api/order/unlock", json={}, headers=self._h()) d = r.get_json() print(f" /api/order/unlock(no params): {r.status_code} rtn={d.get('rtn_code')}") if 'code' not in str(r.data) or 'latitude' not in str(r.data): self.assertIn(d.get("rtn_code"), (400, 401)) def test_09_order_return_no_params(self): r = self.client.post("/api/order/return", json={}, headers=self._h()) d = r.get_json() print(f" /api/order/return(no params): {r.status_code} rtn={d.get('rtn_code')}") self.assertIn(d.get("rtn_code"), (400, 401)) def test_10_rental_start_no_params(self): r = self.client.post("/api/rental/start", json={}, headers=self._h()) d = r.get_json() print(f" /api/rental/start(no params): {r.status_code} rtn={d.get('rtn_code')}") self.assertIn(d.get("rtn_code"), (400, 401)) def test_11_rental_status(self): r = self.client.get("/api/rental/status", headers=self._h()) d = r.get_json() print(f" /api/rental/status: {r.status_code} rtn={d.get('rtn_code')}") if self.token: self.assertEqual(d.get("rtn_code"), 0) def test_12_rental_return_no_params(self): r = self.client.post("/api/rental/return", json={}) d = r.get_json() print(f" /api/rental/return(no params): {r.status_code} rtn={d.get('rtn_code')}") self.assertEqual(d.get("rtn_code"), 400) def test_13_rental_sync(self): r = self.client.post("/api/rental/sync", headers=self._h()) d = r.get_json() print(f" /api/rental/sync: {r.status_code} rtn={d.get('rtn_code')}") if self.token: self.assertEqual(d.get("rtn_code"), 0) def test_14_admin_login_page(self): r = self.client.get("/admin/login") print(f" /admin/login: {r.status_code}") self.assertEqual(r.status_code, 200) def test_15_admin_login(self): r = self.client.post("/admin/login", json={"username": "admin", "password": "admin123"}) d = r.get_json() print(f" /admin/login POST: {r.status_code} rtn={d.get('rtn_code')}") self.assertEqual(d.get("rtn_code"), 0) def test_16_admin_page(self): self.client.post("/admin/login", data={"username": "admin", "password": "admin123"}) r = self.client.get("/admin") print(f" /admin: {r.status_code}") self.assertEqual(r.status_code, 200) def test_17_admin_users(self): self.client.post("/admin/login", data={"username": "admin", "password": "admin123"}) r = self.client.get("/api/admin/users") d = r.get_json() print(f" /api/admin/users: {r.status_code} rtn={d.get('rtn_code')}") self.assertEqual(d.get("rtn_code"), 0) def test_18_admin_rentals(self): self.client.post("/admin/login", data={"username": "admin", "password": "admin123"}) r = self.client.get("/api/admin/rentals") d = r.get_json() print(f" /api/admin/rentals: {r.status_code} rtn={d.get('rtn_code')}") self.assertEqual(d.get("rtn_code"), 0) def test_19_rental_start_with_code(self): r = self.client.post("/api/rental/start", json={"bike_code": "T001"}, headers=self._h()) d = r.get_json() print(f" /api/rental/start(T001): {r.status_code} rtn={d.get('rtn_code')}") if self.token: self.assertIn(d.get("rtn_code"), (0, 400)) def test_20_rental_return_with_id(self): # Get rental id first r = self.client.get("/api/rental/status", headers=self._h()) d = r.get_json() rid = d.get("data", {}).get("rental_id", 0) r = self.client.post("/api/rental/return", json={"rental_id": rid or 1}) d2 = r.get_json() print(f" /api/rental/return(rid={rid}): {r.status_code} rtn={d2.get('rtn_code')}") self.assertEqual(d2.get("rtn_code"), 0) def test_21_order_unlock_with_params(self): r = self.client.post("/api/order/unlock", json={"code": "T001", "latitude": 36.67, "longitude": 116.98}, headers=self._h()) d = r.get_json() print(f" /api/order/unlock(full): {r.status_code} rtn={d.get('rtn_code')}") self.assertNotEqual(r.status_code, 500) def test_22_order_return_with_params(self): r = self.client.post("/api/order/return", json={"order_id": 999, "latitude": 36.67, "longitude": 116.98, "code": "T001"}, headers=self._h()) d = r.get_json() print(f" /api/order/return(full): {r.status_code} rtn={d.get('rtn_code')}") self.assertNotEqual(r.status_code, 500) def test_23_index(self): r = self.client.get("/") print(f" /: {r.status_code}") self.assertEqual(r.status_code, 200) def test_24_auth_status(self): r = self.client.get("/api/auth/status", headers=self._h()) print(f" /api/auth/status: {r.status_code}") self.assertEqual(r.status_code, 200) def test_25_logout(self): r = self.client.post("/api/auth/logout", headers=self._h()) print(f" /api/auth/logout: {r.status_code}") self.assertEqual(r.status_code, 200) if __name__ == "__main__": suite = unittest.TestLoader().loadTestsFromTestCase(TestRoutes) runner = unittest.TextTestRunner(verbosity=0) result = runner.run(suite) total = result.testsRun fails = len(result.failures) errors = len(result.errors) passed = total - fails - errors print(f"\n{'='*50}") print(f" 总计: {total} 通过: {passed} 失败: {fails} 错误: {errors}") if fails: for t, trace in result.failures: print(f" X {t}") if errors: for t, trace in result.errors: print(f" X {t}") print(f"{'='*50}") sys.exit(0 if errors == 0 and fails == 0 else 1)