# post.py
# 帖子实体类：模拟社区帖子功能，包含标题、作者、内容、点赞数等属性与方法

class Post:
    def __init__(self, title: str, author: str, content: str):
        """
        初始化帖子对象
        :param title: 帖子标题
        :param author: 发帖人
        :param content: 帖子内容
        """
        # 校验标题：去除首尾空格后为空则抛出异常
        if not title.strip():
            raise ValueError("标题不能为空")
        
        self.title = title
        self.author = author
        self.content = content
        self.likes = 0  # 点赞数，初始值为0

    def like(self):
        """点赞方法：每调用一次，点赞数 +1"""
        self.likes += 1

# test_post.py
# 单元测试文件：针对帖子类 Post 编写测试用例
import pytest
# 导入待测试的 Post 实体类
from post import Post


# ====================== pytest 夹具（Fixture） ======================
# @pytest.fixture：定义测试夹具，用于复用测试对象/测试前置逻辑
# 默认作用域：每个测试函数执行前都会重新调用该函数，生成全新对象
@pytest.fixture
def sample_post():
    """
    测试夹具：生成一个通用的帖子测试实例
    作用：所有引用该夹具的测试函数，会自动接收此返回对象，避免重复创建实例
    """
    # 创建测试用帖子对象并返回
    return Post("有人一起跑步吗", "刘世强", "明天早6点图书馆门口")


# ====================== 测试用例 1：测试初始点赞数 ======================
# 函数形参名 = 夹具名(sample_post)，pytest 会自动将夹具返回值注入进来
def test_initial_likes(sample_post):
    """测试帖子初始化后，点赞数默认等于 0"""
    # 断言：校验初始点赞数是否符合预期
    assert sample_post.likes == 0


# ====================== 测试用例 2：测试点赞功能 ======================
def test_like_increments(sample_post):
    """测试点赞方法：调用like()后，点赞数正常累加"""
    # 执行两次点赞操作
    sample_post.like()
    sample_post.like()
    # 断言：点赞数应为 2
    assert sample_post.likes == 2


# ====================== 测试用例 3：测试标题非空校验 ======================
def test_title_not_empty(sample_post):
    """测试正常创建的帖子，标题不为空"""
    assert sample_post.title != ""


# ====================== 测试用例 4：测试空标题异常抛出 ======================
def test_empty_title_raises():
    """测试场景：传入空白标题，预期抛出指定异常及异常信息"""
    # pytest.raises：捕获指定异常
    # match 参数：精准匹配异常提示文本，避免捕获无关异常
    with pytest.raises(ValueError, match="标题不能为空"):
        # 传入全空格的标题，触发异常
        Post("   ", "张三", "内容")