2025-11-12 00:28:07 +08:00

253 lines
7.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
演示测试 - 测试基础功能(不实际发布)
"""
import asyncio
import sys
from pathlib import Path
# 简化的模型定义基于working_solution.py
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional
class PlatformType(Enum):
XIAOHONGSHU = "xiaohongshu"
DOUYIN = "douyin"
@dataclass
class ImageNote:
title: str
description: str
images: List[str] = field(default_factory=list)
tags: List[str] = field(default_factory=list)
visibility: str = "public"
cover_image: Optional[str] = None
@dataclass
class VideoContent:
title: str
description: str
video_path: str
tags: List[str] = field(default_factory=list)
visibility: str = "public"
cover_image: Optional[str] = None
@dataclass
class AccountInfo:
platform: PlatformType
username: str
cookie_file: str
is_active: bool = True
# 测试基础功能
def test_basic_functionality():
"""测试基础功能"""
print("🚀 开始基础功能测试")
print("=" * 50)
# 1. 测试内容创建
print("📝 1. 测试内容创建")
note = ImageNote(
title="我的旅行分享 🏔️",
description="今天去了很美的地方,和大家分享一些照片!",
images=["img1.jpg", "img2.jpg", "img3.jpg"],
tags=["旅行", "美景", "分享", "生活"]
)
print(f"✅ 图文笔记创建成功: {note.title}")
print(f" 描述: {note.description[:30]}...")
print(f" 图片数量: {len(note.images)}")
print(f" 标签: {', '.join(note.tags)}")
video = VideoContent(
title="我的日常生活vlog 📸",
description="记录一些日常生活的美好瞬间,希望大家喜欢!",
video_path="daily_vlog.mp4",
tags=["vlog", "日常", "生活记录", "分享"]
)
print(f"\n✅ 视频内容创建成功: {video.title}")
print(f" 描述: {video.description[:30]}...")
print(f" 视频路径: {video.video_path}")
print(f" 标签: {', '.join(video.tags)}")
# 2. 测试账号信息
print(f"\n👤 2. 测试账号信息")
xhs_account = AccountInfo(
platform=PlatformType.XIAOHONGSHU,
username="my_xhs_account",
cookie_file="my_xhs_account.json"
)
print(f"✅ 小红书账号: {xhs_account.platform.value}/{xhs_account.username}")
douyin_account = AccountInfo(
platform=PlatformType.DOUYIN,
username="my_douyin_account",
cookie_file="my_douyin_account.json"
)
print(f"✅ 抖音账号: {douyin_account.platform.value}/{douyin_account.username}")
# 3. 测试内容验证逻辑
print(f"\n✅ 3. 测试内容验证")
def validate_content(content, platform):
"""基础内容验证"""
errors = []
if not content.title.strip():
errors.append("标题不能为空")
elif len(content.title) > 100:
errors.append("标题过长")
if not content.description.strip():
errors.append("描述不能为空")
elif len(content.description) > 1000:
errors.append("描述过长")
if isinstance(content, ImageNote):
if not content.images:
errors.append("图文笔记必须包含图片")
elif len(content.images) > 9:
errors.append("图片数量不能超过9张")
elif isinstance(content, VideoContent):
if not content.video_path:
errors.append("视频路径不能为空")
return errors
# 验证图文笔记
note_errors = validate_content(note, PlatformType.XIAOHONGSHU)
print(f"✅ 图文笔记验证: {'通过' if not note_errors else f'失败 - {note_errors}'}")
# 验证视频内容
video_errors = validate_content(video, PlatformType.DOUYIN)
print(f"✅ 视频内容验证: {'通过' if not video_errors else f'失败 - {video_errors}'}")
return True
async def test_playwright_basic():
"""测试Playwright基础功能"""
print(f"\n🌐 4. 测试Playwright基础功能")
try:
from playwright.async_api import async_playwright
async with async_playwright() as p:
print("✅ Playwright启动成功")
# 创建浏览器实例(有头模式用于演示)
browser = await p.chromium.launch(headless=False)
print("✅ Chromium浏览器启动成功")
# 创建页面
page = await browser.new_page()
print("✅ 新页面创建成功")
# 测试基本导航
await page.goto("https://www.baidu.com")
title = await page.title()
print(f"✅ 页面导航成功: {title}")
# 获取截图(可选)
try:
await page.screenshot(path="demo_screenshot.png")
print("✅ 截图保存成功: demo_screenshot.png")
except Exception as e:
print(f"⚠️ 截图保存失败: {e}")
# 关闭浏览器
await browser.close()
print("✅ 浏览器关闭成功")
return True
except ImportError:
print("❌ Playwright未安装")
return False
except Exception as e:
print(f"❌ Playwright测试失败: {e}")
return False
def test_file_preparation():
"""测试文件准备"""
print(f"\n📁 5. 测试文件准备")
# 创建必要的目录
dirs_to_create = [
"media/images",
"media/videos",
"auth/cookies/xiaohongshu",
"auth/cookies/douyin",
"logs"
]
created_dirs = []
for dir_path in dirs_to_create:
path = Path(dir_path)
if not path.exists():
path.mkdir(parents=True, exist_ok=True)
created_dirs.append(dir_path)
print(f"✅ 创建目录: {dir_path}")
else:
print(f"✅ 目录已存在: {dir_path}")
# 创建测试文件
test_files = [
("media/images/test_image.jpg", "测试图片文件"),
("media/videos/test_video.mp4", "测试视频文件")
]
created_files = []
for file_path, description in test_files:
path = Path(file_path)
if not path.exists():
# 创建一个占位文件
path.touch()
created_files.append(file_path)
print(f"✅ 创建占位文件: {file_path} ({description})")
else:
print(f"✅ 文件已存在: {file_path}")
return True
async def main():
"""主测试函数"""
print("🎭 社交媒体自动发布器 - 功能演示测试")
print("📋 这个测试不会实际发布任何内容,只测试基础功能")
print("=" * 60)
success = True
# 1. 基础功能测试
if not test_basic_functionality():
success = False
# 2. 文件准备测试
if not test_file_preparation():
success = False
# 3. Playwright测试
playwright_success = await test_playwright_basic()
if not playwright_success:
print("⚠️ Playwright测试失败但基础功能正常")
print("\n" + "=" * 60)
if success:
print("🎉 基础功能测试完成!")
print("\n📝 接下来你可以:")
print("1. 安装浏览器: playwright install chromium")
print("2. 运行实际测试(需要扫码登录)")
print("3. 开始使用项目进行内容发布")
print("\n⚠️ 注意: 实际发布前请准备好真实的图片和视频文件")
return True
else:
print("❌ 部分测试失败,请检查环境配置")
return False
if __name__ == "__main__":
# 运行测试
result = asyncio.run(main())
sys.exit(0 if result else 1)