test_aigen.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # -*- coding: utf-8 -*-
  2. """aigen 模块测试:prompt 组装与生成器构造(不发起网络请求)。"""
  3. import sys
  4. from pathlib import Path
  5. sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
  6. from kuaishou_tool import aigen
  7. def test_build_prompt_structure():
  8. p = aigen.build_prompt('a red ceramic teapot')
  9. # 主体在首位
  10. assert p.startswith('a red ceramic teapot')
  11. # 负面人物词在末尾
  12. assert 'people, person, human' in p
  13. assert p.endswith('excluded)')
  14. def test_build_prompt_randomness():
  15. # 词库随机:多次生成应产生差异(极小概率全同, 取8次比较)
  16. ps = {aigen.build_prompt('x') for _ in range(8)}
  17. assert len(ps) > 1
  18. def test_vocab_buckets_all_nonempty():
  19. for name, bucket in aigen.VOCAB.items():
  20. words = [w for w in bucket.split('|') if w.strip()]
  21. assert len(words) >= 5, f'桶 {name} 词数不足: {words}'
  22. def test_load_generator_from_cfg(tmp_path=None):
  23. cfg = {'ai': {'zhipu_api_key': 'k', 'model': 'cogview-3-flash',
  24. 'pollinations_fallback': True}}
  25. gen = aigen.load_generator(cfg, str(Path(tmp_path or '.')))
  26. assert gen.api_key == 'k'
  27. assert gen.model == 'cogview-3-flash'
  28. assert gen.fallback is True
  29. assert gen.out_dir.name == '实拍'
  30. def test_generator_no_key_skips_main_channel():
  31. gen = aigen.AIGenerator(api_key='', out_dir='实拍')
  32. r = gen._zhipu_generate('test prompt')
  33. assert r is None # 无 key 直接跳过主通道
  34. if __name__ == '__main__':
  35. import inspect
  36. fails = 0
  37. for name, fn in sorted(inspect.getmembers(sys.modules[__name__], inspect.isfunction)):
  38. if not name.startswith('test_'):
  39. continue
  40. try:
  41. sig = inspect.signature(fn)
  42. if 'tmp_path' in sig.parameters or 'caplog' in sig.parameters:
  43. import tempfile
  44. with tempfile.TemporaryDirectory() as td:
  45. fn(td if 'tmp_path' in sig.parameters else None)
  46. else:
  47. fn()
  48. print(f'PASS {name}')
  49. except Exception as e:
  50. fails += 1
  51. print(f'FAIL {name}: {e}')
  52. sys.exit(1 if fails else 0)