| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416 |
- # -*- coding: utf-8 -*-
- """collect.py 单元测试:纯 Python 断言,无 pytest 依赖。
- - 临时 db:db.conn 传入临时文件路径(测试前重置 db._CONN 单例)
- - 临时目录:cfg['dirs'] 用绝对路径,把 素材//产品主图/ 重定向到临时目录
- (config.dir_of 对绝对路径参数直接透传,pathlib 语义)
- - HTTP 打桩:以 monkeypatch 方式把 collect.KSClient 换成 _FakeKS,
- 伪造响应对象带 .json()/.content,绝不真实联网
- 运行:python -X utf8 tests/test_collect.py
- """
- import copy
- import os
- import sys
- import tempfile
- import time
- sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
- from kuaishou_tool import collect, config, db # noqa: E402
- from kuaishou_tool.httpclient import KSClient # noqa: E402
- _TMP = tempfile.mkdtemp(prefix='test_collect_')
- CFG = {
- 'db_path': os.path.join(_TMP, 'data.db'),
- 'dirs': {'素材': os.path.join(_TMP, '素材'),
- '产品主图': os.path.join(_TMP, '产品主图')},
- 'collect': {'did': 'TEST-DID', 'max_pages': 5, 'filters': {}},
- }
- # ---- 打桩:伪造 KSClient(feed_list_ios / profile_feed_web / get) ----
- class _Resp:
- def __init__(self, j=None, content=b'', headers=None):
- self.j, self.content = j, content
- self.headers = headers or {}
- def json(self):
- return self.j
- class _FakeKS:
- ios_pages = {} # (uid, pcursor) -> _Resp
- web_pages = {} # (uid, pcursor) -> _Resp
- profiles = {} # uid -> _Resp(M8 query_profile 桩)
- opens = {} # photoId -> _Resp(R1 open_share 桩)
- redirects = {} # url -> Location(短链跟随桩)
- gets = [] # 下载请求 URL 记录
- dl = [] # [(url前缀, 字节内容)] 下载响应脚本
- def __init__(self, cookie='', did='', proxy=None, as_ios=False):
- self.as_ios = as_ios
- def feed_list_ios(self, uid, pcursor=''):
- return _FakeKS.ios_pages[(uid, pcursor)] # 未预置则 KeyError → 走兜底
- def profile_feed_web(self, uid, pcursor=''):
- return _FakeKS.web_pages[(uid, pcursor)]
- def query_profile(self, uid):
- return _FakeKS.profiles[uid]
- def open_share(self, photo_id, share_object_id=''):
- return _FakeKS.opens[photo_id]
- def get(self, url, params=None, **kw):
- _FakeKS.gets.append(url)
- if url in _FakeKS.redirects: # 短链:302 Location 跟随桩
- return _Resp(j=None, headers={'Location': _FakeKS.redirects[url]})
- for pre, body in _FakeKS.dl:
- if url.startswith(pre):
- return _Resp(content=body)
- return _Resp(content=b'UNMATCHED')
- _ORIG_KS = collect.KSClient
- def _fresh():
- """每个用例前的准备:重置临时库 + 打桩 + 清空 monitoring/biaoti。"""
- if db._CONN is not None:
- db._CONN.close()
- db._CONN = None
- db.conn(CFG)
- collect.KSClient = _FakeKS
- _FakeKS.ios_pages, _FakeKS.web_pages = {}, {}
- _FakeKS.profiles, _FakeKS.opens, _FakeKS.redirects = {}, {}, {}
- _FakeKS.gets, _FakeKS.dl = [], []
- db.exe('DELETE FROM monitoring')
- db.exe('DELETE FROM biaoti')
- def _cfg(**filters):
- """复制 CFG 并覆盖 filters(逐用例独立阈值)。"""
- c = copy.deepcopy(CFG)
- c['collect']['filters'] = filters
- return c
- def _item(**kw):
- """构造统一 item(默认可通过全部过滤)。"""
- d = {'uid': 'u1', 'videoId': 't1', 'biaoti': '好物分享', 'likes': 100,
- 'plays': 1000, 'pub_ts': int(time.time()), 'url': 'http://x/t1.mp4',
- 'itemId': 'g1', 'itemImgUrl': 'http://img/g1.jpg',
- 'commission': None, 'price': None, 'shop': ''}
- d.update(kw)
- return d
- def _feed(vid, caption='标题', likes=100, views=1000, ts=None, url=None,
- item='g1', img='http://img/g1.jpg'):
- """构造 iOS openShare feeds 元素(E线 R1 字段)。"""
- return {'photo_id': vid, 'caption': caption, 'like_count': likes,
- 'view_count': views, 'timestamp': ts or int(time.time()),
- 'main_mv_urls': [{'url': url or f'http://cdn/{vid}.mp4'}],
- 'item_id': item, 'item_img_url': img}
- def _page(feeds, pcursor='no_more'):
- return _Resp({'result': 2100000, 'data': {'feeds': feeds, 'pcursor': pcursor}})
- # ---- 用例 ----
- def test_add_monitor_and_stats():
- """新增监控(查重)+ 粉丝/作品数落库(dict 与 Row 均可)。"""
- _fresh()
- assert collect.add_monitor('达人甲', 'u1') is True
- assert collect.add_monitor('达人甲', 'u1') is False # 记录已经存在
- assert collect.add_monitor('', '') is False # 空 uid 拒绝
- collect.update_monitor_stats({'uid': 'u1', 'name': '达人甲·改', 'fensishu': '123',
- 'guanzhushu': 10, 'zuopinshu': 45, 'shangpinshu': 8})
- row = db.query("SELECT * FROM monitoring WHERE uid='u1'")[0]
- assert row['name'] == '达人甲·改'
- assert (row['fensishu'], row['guanzhushu'], row['zuopinshu'], row['shangpinshu']) \
- == (123, 10, 45, 8) # 字符串数字被规整为 int
- # sqlite3.Row 回写(模拟 select 出的行再落库),name 为 None 时保留原值
- collect.update_monitor_stats(row)
- row2 = db.query("SELECT * FROM monitoring WHERE uid='u1'")[0]
- assert row2['name'] == '达人甲·改' and row2['fensishu'] == 123
- def test_poll_once_ios_paging():
- """iOS 通道:pcursor 翻页到 no_more;字段提取;shangcitime 回写。"""
- _fresh()
- collect.add_monitor('甲', 'u1')
- _FakeKS.ios_pages = {
- ('u1', ''): _page([_feed('v1'), _feed('v2', likes=5, views=50)], 'p2'),
- ('u1', 'p2'): _page([_feed('v3')], 'no_more'),
- }
- items = collect.poll_once(CFG, {'uid': 'u1', 'name': '甲'})
- assert [i['videoId'] for i in items] == ['v1', 'v2', 'v3'] # 翻了两页共3条
- it = items[0]
- assert it['uid'] == 'u1' and it['biaoti'] == '标题'
- assert it['likes'] == 100 and it['plays'] == 1000
- assert it['url'] == 'http://cdn/v1.mp4'
- assert it['itemId'] == 'g1' and it['itemImgUrl'] == 'http://img/g1.jpg'
- assert 0 < it['pub_ts'] <= time.time()
- sc = db.query("SELECT shangcitime FROM monitoring WHERE uid='u1'")[0]['shangcitime']
- assert sc # 「轮询用户完成」收尾回写
- # 翻页上限:max_pages=1 时只取第一页
- cfg1 = copy.deepcopy(CFG)
- cfg1['collect']['max_pages'] = 1
- assert len(collect.poll_once(cfg1, {'uid': 'u1'})) == 2
- def test_poll_once_web_fallback():
- """iOS 首页失败 → 网页 graphql 兜底(feeds[i].photo 包一层)。"""
- _fresh()
- collect.add_monitor('乙', 'u2')
- # ios_pages 不预置 → feed_list_ios 抛 KeyError → 切网页通道
- _FakeKS.web_pages = {('u2', ''): _Resp({'data': {'visionProfilePhotoList': {
- 'feeds': [{'photo': {'id': 'w1', 'caption': '网页源', 'likeCount': 5,
- 'viewCount': 6, 'timestamp': int(time.time()) * 1000,
- 'photoUrls': [{'url': 'http://w/w1.mp4'}],
- 'itemId': 'gw1', 'itemImgUrl': 'http://img/w1.jpg'}}],
- 'pcursor': 'no_more'}}})}
- items = collect.poll_once(CFG, {'uid': 'u2'})
- assert len(items) == 1
- it = items[0]
- assert it['videoId'] == 'w1' and it['biaoti'] == '网页源'
- assert it['url'] == 'http://w/w1.mp4' and it['itemId'] == 'gw1'
- assert abs(it['pub_ts'] - time.time()) < 5 # 毫秒时间戳已转秒
- assert it['likes'] == 5 and it['plays'] == 6
- def test_extract_page_rest_top_level():
- """网页 rest/v/profile/feed 形态(C4 实测):顶层 feeds/pcursor。"""
- feeds, pc = collect._extract_page({'result': 1, 'feeds': [
- {'photo': {'id': 'r1', 'caption': 'rest源', 'likeCount': 7,
- 'viewCount': 8, 'timestamp': int(time.time()),
- 'photoUrls': [{'url': 'http://w/r1.mp4'}]}}],
- 'pcursor': '1.782E12'})
- assert len(feeds) == 1 and pc == '1.782E12'
- it = collect._feed_to_item(feeds[0], 'u9')
- assert it['videoId'] == 'r1' and it['biaoti'] == 'rest源'
- assert it['likes'] == 7 and it['plays'] == 8
- assert it['url'] == 'http://w/r1.mp4'
- def test_filter_pass_nine_levels():
- """九级过滤漏斗逐级验证(L1~L9)。"""
- _fresh()
- # L1 视频重复:biaoti 已入库该 videoId(独占 itemId,避免污染 L8 商品重复判定)
- collect.save_biaoti(_item(videoId='dup1', itemId='gdup0'))
- assert collect.filter_pass(_cfg(), _item(videoId='dup1')) is False
- assert collect.filter_pass(_cfg(), _item(videoId='dup2')) is True
- # L2 时间:发布超 max_age_hours 过滤;0(默认)不启用
- old = _item(pub_ts=int(time.time()) - 72 * 3600)
- assert collect.filter_pass(_cfg(max_age_hours=24), old) is False
- assert collect.filter_pass(_cfg(), old) is True
- # L3 点赞 / L4 播放
- assert collect.filter_pass(_cfg(min_likes=10), _item(likes=9)) is False
- assert collect.filter_pass(_cfg(min_plays=100), _item(plays=99)) is False
- # L5 关键词/违禁词
- assert collect.filter_pass(_cfg(keywords_block=['福利', '免费领']),
- _item(biaoti='限时免费领福利')) is False
- assert collect.filter_pass(_cfg(keywords_block=['福利']), _item()) is True
- # L6 特殊字符:block_special 过滤 / strip_special 就地清洗
- sp = _item(biaoti='限量❗秒杀')
- assert collect.filter_pass(_cfg(block_special=True), _item(biaoti='限量❗秒杀')) is False
- it = _item(biaoti='限量❗秒杀')
- assert collect.filter_pass(_cfg(strip_special=True), it) is True
- assert '❗' not in it['biaoti'] and it['biaoti'] == '限量秒杀'
- # L7 有无商品:默认 need_goods=True;可关(「不挂车爆款视频下载」模式)
- assert collect.filter_pass(_cfg(), _item(itemId='')) is False
- assert collect.filter_pass(_cfg(need_goods=False), _item(itemId='')) is True
- # L8a 商品重复:goodsId 已挂过其他 video
- collect.save_biaoti(_item(videoId='ga', itemId='gdup'))
- assert collect.filter_pass(_cfg(), _item(videoId='gb', itemId='gdup')) is False
- # L8b 佣金 / L8c 客单价(阈值 0 = 不启用,对齐 DEFAULTS)
- assert collect.filter_pass(_cfg(min_commission=1.0), _item(commission=0.5)) is False
- assert collect.filter_pass(_cfg(), _item(commission=0.5)) is True
- assert collect.filter_pass(_cfg(max_price=100), _item(price=200)) is False
- assert collect.filter_pass(_cfg(max_price=100), _item(price=50)) is True
- # L8d 店铺:黑名单 + 快手优选官方商品
- assert collect.filter_pass(_cfg(ban_shops=['黑心店']), _item(shop='黑心店')) is False
- assert collect.filter_pass(_cfg(ban_official=True), _item(shop='快手优选自营')) is False
- assert collect.filter_pass(_cfg(), _item(shop='快手优选自营')) is True
- # L9 作品失效:标记失效 / 无下载地址
- assert collect.filter_pass(_cfg(), _item(invalid=True)) is False
- assert collect.filter_pass(_cfg(), _item(url='')) is False
- def test_download():
- """下载:视频→素材/,商品图→产品主图/(文件名=videoId);幂等不重下。"""
- _fresh()
- _FakeKS.dl = [('http://cdn/d1.mp4', b'VIDEOBYTES'),
- ('http://img/d1.jpg', b'JPG-BYTES')]
- it = _item(videoId='d1', url='http://cdn/d1.mp4', itemImgUrl='http://img/d1.jpg')
- p = collect.download(CFG, it)
- assert p == config.dir_of(CFG, '素材') / 'd1.mp4' and p.exists()
- assert p.read_bytes() == b'VIDEOBYTES'
- g = config.dir_of(CFG, '产品主图') / 'd1.jpg'
- assert g.exists() and g.read_bytes() == b'JPG-BYTES'
- assert len(_FakeKS.gets) == 2
- # 幂等:文件已存在,不再发请求
- collect.download(CFG, it)
- assert len(_FakeKS.gets) == 2
- # 无商品图:只下视频
- _FakeKS.dl = [('http://cdn/d2.mp4', b'V2')]
- p2 = collect.download(CFG, _item(videoId='d2', url='http://cdn/d2.mp4',
- itemImgUrl=''))
- assert p2.exists() and len(_FakeKS.gets) == 3
- # URL 无合法后缀 → 商品图兜底 .jpg
- _FakeKS.dl = [('http://img/noext?x=1', b'IMG')]
- collect.download(CFG, _item(videoId='d3', url='http://cdn/d3.mp4',
- itemImgUrl='http://img/noext?x=1'))
- assert (config.dir_of(CFG, '产品主图') / 'd3.jpg').exists()
- def test_save_biaoti():
- """入库:biaoti1=videoId/biaoti2=标题/goodsId/goodsImg;OR IGNORE 幂等。"""
- _fresh()
- collect.save_biaoti(_item(videoId='s1', biaoti='标题A', itemId='g9',
- itemImgUrl='http://img/9.jpg'))
- row = db.query("SELECT * FROM biaoti WHERE biaoti1='s1'")[0]
- assert row['biaoti2'] == '标题A' and row['goodsId'] == 'g9'
- assert row['goodsImg'] == 'http://img/9.jpg' and row['createdTime'] != ''
- collect.save_biaoti(_item(videoId='s1', biaoti='标题B')) # 重复插不生效
- rows = db.query("SELECT * FROM biaoti WHERE biaoti1='s1'")
- assert len(rows) == 1 and rows[0]['biaoti2'] == '标题A'
- def test_save_biaoti_asset_columns():
- """资产维度:来源监控号/名称/分类快照 + 点赞/播放数一并落库。"""
- _fresh()
- collect.batch_add(['u1'], fenlei='女装组') # _item 默认 uid='u1'
- db.exe("UPDATE monitoring SET name='达人甲' WHERE uid='u1'")
- collect.save_biaoti(_item(videoId='s2', likes=66, plays=88000))
- r = db.query("SELECT * FROM biaoti WHERE biaoti1='s2'")[0]
- assert (r['laiyuan'], r['laiyuanName'], r['laiyuanFenlei']) == \
- ('u1', '达人甲', '女装组')
- assert r['dianzan'] == 66 and r['bofang'] == 88000
- def test_poll_all():
- """遍历 monitoring 逐个轮询,返回通过过滤的新增作品总数。"""
- _fresh()
- collect.add_monitor('甲', 'u1')
- collect.add_monitor('乙', 'u2')
- _FakeKS.ios_pages = {
- ('u1', ''): _page([_feed('v1'), _feed('v2')], 'no_more'),
- ('u2', ''): _page([_feed('w1', likes=1, views=1)], 'no_more'),
- }
- # u2 的作品低于阈值被 L3/L4 过滤
- cfg = _cfg(min_likes=10, min_plays=10)
- assert collect.poll_all(cfg) == 2
- for uid in ('u1', 'u2'):
- assert db.query('SELECT shangcitime FROM monitoring WHERE uid=?',
- (uid,))[0]['shangcitime'] != ''
- # 入库后(biaoti 查重)再次轮询 → 全部 L1 过滤,新增 0
- for vid in ('v1', 'v2'):
- collect.save_biaoti(_item(videoId=vid))
- assert collect.poll_all(cfg) == 0
- def test_batch_add_and_delete_monitor():
- """M7 批量导入:逐个查重跳过已存在;M10 删除监控账号。"""
- _fresh()
- added, skipped = collect.batch_add(['u1', 'u2', 'u1', ''], fenlei='测试组')
- assert (added, skipped) == (2, 2) # 空 uid 与重复 u1 各计一次跳过
- rows = db.query('SELECT uid, fenlei FROM monitoring ORDER BY uid')
- assert [(r['uid'], r['fenlei']) for r in rows] == [('u1', '测试组'), ('u2', '测试组')]
- # 与既有单个导入共存:add_monitor 先入库后,batch_add 不重复插入
- collect.add_monitor('丙', 'u3')
- added2, skipped2 = collect.batch_add(['u1', 'u3', 'u4'])
- assert (added2, skipped2) == (1, 2)
- # M10 删除
- assert collect.delete_monitor('u2') is True
- assert collect.delete_monitor('u2') is False # 已不存在
- assert not db.query("SELECT id FROM monitoring WHERE uid='u2'")
- def test_refresh_monitor_stats():
- """M8 资料查询:query_profile 响应 → monitoring 粉丝/关注/作品/商品数落库。"""
- _fresh()
- collect.add_monitor('甲', 'u1')
- collect.add_monitor('乙', 'u2')
- _FakeKS.profiles = {
- 'u1': _Resp({'userProfile': {'profile': {'user_name': '达人甲Pro'},
- 'ownerCount': {'fan': 12000, 'follow': 88,
- 'photo_public': 210},
- 'extraLink': {'subTitle': '35件商品'}}}),
- }
- # u2 无桩 → 查询异常时保留原值不中断
- n = collect.refresh_monitor_stats(_cfg(), uid='u1')
- assert n == 1
- row = db.query("SELECT * FROM monitoring WHERE uid='u1'")[0]
- assert row['name'] == '达人甲Pro'
- assert (row['fensishu'], row['guanzhushu'], row['zuopinshu'],
- row['shangpinshu']) == (12000, 88, 210, 35) # subTitle "N件商品"解析
- # 全量刷新:u1 更新、u2 桩缺失仅计数跳过
- n2 = collect.refresh_monitor_stats(_cfg())
- assert n2 == 1
- assert 'Pro' in db.query("SELECT name FROM monitoring WHERE uid='u1'")[0]['name']
- def test_parse_profile_html():
- """M8 web 版:SSR 主页 HTML 抠 user_name + ownerCount。"""
- html = ('...{"user_id":"3xsn","user_name":"泽小泽_","headurl":"http://x/uhead",'
- '"userId":"494608718","ownerCount":{"fan":579174,"like":17688318,'
- '"follow":177,"photo_public":333},"isUserIso...}')
- d = collect._parse_profile_html(html)
- assert d['name'] == '泽小泽_'
- assert d['fensishu'] == 579174 and d['guanzhushu'] == 177
- assert d['zuopinshu'] == 333
- assert collect._parse_profile_html('风控页无资料') == {}
- def test_resolve_photo():
- """R1 单作品解析:分享文本提链接/短链跟随/result 失效判定/item 字段统一。"""
- _fresh()
- _FakeKS.opens = {
- '3xabc123': _Resp({'result': 2100000,
- 'data': {'feeds': [_feed('3xabc123', caption='磁力好物',
- likes=55, views=660)]}}),
- 'dead000': _Resp({'result': 2101001}), # 非成功码 → 作品失效
- }
- _FakeKS.redirects = {
- 'https://v.kuaishou.com/ShortL': 'https://www.kuaishou.com/short-video/3xabc123',
- }
- # (1) 短链 → 跟随 Location → 提取 photoId → openShare 解析
- it = collect.resolve_photo(_cfg(), '看看这个 https://v.kuaishou.com/ShortL 复制打开')
- assert it and it['videoId'] == '3xabc123' and it['biaoti'] == '磁力好物'
- assert (it['likes'], it['plays']) == (55, 660)
- assert any('v.kuaishou.com/ShortL' in u for u in _FakeKS.gets) # 短链确实被请求
- # (2) 直链(short-video/<id>)不发起跟随请求
- _FakeKS.gets.clear()
- it2 = collect.resolve_photo(_cfg(), 'https://www.kuaishou.com/short-video/3xabc123')
- assert it2 and it2['videoId'] == '3xabc123'
- assert not _FakeKS.gets # 直链无需 GET
- # (3) 纯 photoId 直接解析
- it3 = collect.resolve_photo(_cfg(), 'dead000')
- assert it3 is None or it3.get('invalid') # 失效码 → invalid 标记
- # (4) 无 id 可提取 → None
- assert collect.resolve_photo(_cfg(), '没有链接的纯文本') is None
- if __name__ == '__main__':
- _fns = [v for k, v in list(globals().items())
- if k.startswith('test_') and callable(v)]
- failed = 0
- for fn in _fns:
- try:
- fn()
- print('PASS', fn.__name__)
- except AssertionError as e:
- failed += 1
- print('FAIL', fn.__name__, '--', e)
- except Exception as e:
- failed += 1
- print('ERROR', fn.__name__, '--', repr(e))
- collect.KSClient = _ORIG_KS # 恢复打桩
- print(f'{len(_fns) - failed}/{len(_fns)} 个用例通过')
- sys.exit(1 if failed else 0)
|