import asyncio
from local_broker import client, local_broker, string

async def main():
    topic = "fixture/offline"
    def valid_topic(value):
        if not value or "\x00" in value:
            raise ValueError("主题不能为空或含NUL")
    valid_topic(topic)
    try:
        valid_topic("")
        raise AssertionError("空主题应拒绝")
    except ValueError:
        pass
    print("空主题断言通过")
    async with local_broker() as port:
        async with client(port,"persistent",expected_present=False) as (r,w):
            body=b"\x00\x01"+string(topic)+b"\x01"
            w.write(bytes([0x82,len(body)])+body);await w.drain()
            assert await asyncio.wait_for(r.readexactly(5),3)==b"\x90\x03\x00\x01\x01"
        await asyncio.sleep(0.1)
        async with client(port,"publisher") as (r,w):
            body=string(topic)+b"\x00\x01Q-ONE"
            w.write(bytes([0x32,len(body)])+body);await w.drain()
            assert await asyncio.wait_for(r.readexactly(4),3)==b"\x40\x02\x00\x01"
            print("离线发布获得PUBACK")
        async with client(port,"persistent",expected_present=True) as (r,w):
            header=await asyncio.wait_for(r.readexactly(2),3)
            assert header[0]&0xF0==0x30 and header[1]<128
            body=await r.readexactly(header[1])
            length=int.from_bytes(body[:2],"big")
            assert body[2:2+length].decode()==topic
            packet_id=body[2+length:4+length]
            assert body[4+length:]==b"Q-ONE"
            w.write(b"\x40\x02"+packet_id);await w.drain()
            try:
                await asyncio.wait_for(r.read(1),0.15)
                raise AssertionError("应只有一份消息")
            except TimeoutError:pass
            print("恢复会话收到唯一 Q-ONE")
if __name__=="__main__":asyncio.run(main())
