fix(scraper): 群抓取改用 friend_list/es+friendTypeYunke=2(替换 getChatroomList)
getChatroomList 在云客真机返回 0 行(已 Playwright 2026-08-10 验证)。 群与好友共用 /wechatweb/wxFriends/friend_list/es,仅以 friendTypeYunke 区分 (1=好友 / 2=群),响应信封一致(basicResult),复用 _parse_total/_parse_rows。 - 删除 CHATROOM_LIST_PATH / _parse_chatroom_total / _parse_chatroom_rows / _build_chatroom_body / _parse_member_ids(改写后已无引用) - 新增 _build_group_body(pageNum/pageSize/friendTypeYunke="2") - 重写 _normalize_chat_group 映射 friend_list/es 字段 (friendWxId->room_id, friendWxNickname->room_name, friendNum->member_count, wxId/ownerName/userId, phone||wechatPhone, messageCount/sendNum/lastChatTime) - friend_list/es 不返回成员明细,member_ids/member_ids_list 固定 None/[] (群列表可用;成员镜像延后) - 删除 tests/cassettes/chatroom_fixture.py,改复用 wxFriends_fixture 信封 - 重写 test_scrape_wechat_groups:断言新端点 URL + friendTypeYunke="2" body + 新字段映射;member_ids 边界用例改为"始终 None/[]" scrape_wechat_groups 签名不变(client + page_size),orchestrator/scheduler 未改。 Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -4,6 +4,13 @@ Drives the real page-number pagination + normalization logic through
|
||||
``respx`` by wiring a real ``YunkeClient`` (primed with a fake session so the
|
||||
login flow is skipped) against a mocked transport.
|
||||
|
||||
Groups reuse the SAME upstream endpoint as friends
|
||||
(``POST /wechatweb/wxFriends/friend_list/es``); the ``friendTypeYunke="2"``
|
||||
body parameter selects groups (``"1"`` selects friends). The response
|
||||
envelope is identical to the friend scraper's, so this test reuses
|
||||
:func:`tests.cassettes.wxFriends_fixture.make_friend_list_response` to build
|
||||
capture-shaped envelopes.
|
||||
|
||||
The fixture ships 3 records across 2 pages of size 2, plus a terminating
|
||||
empty page (the documented primary stop signal for page-number endpoints):
|
||||
|
||||
@@ -12,33 +19,89 @@ empty page (the documented primary stop signal for page-number endpoints):
|
||||
* page 3 -> empty ``data`` array (no more rows)
|
||||
|
||||
The scraper must yield exactly the 3 records (normalized to ``ChatGroup``
|
||||
snake_case columns + ``raw_json``), parse ``memberIds`` into
|
||||
``member_ids_list`` (dropping empty segments), make exactly 3 calls, and stop
|
||||
without a 4th.
|
||||
snake_case columns + ``raw_json``), make exactly 3 calls, and stop without a
|
||||
4th. Member details are NOT surfaced by ``friend_list/es`` — ``member_ids``
|
||||
is ``None`` and ``member_ids_list`` is ``[]`` on every yielded record.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json as _json
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import respx
|
||||
|
||||
from app.scraper.wechat import scrape_wechat_groups
|
||||
from app.session.yunke_client import YunkeClient
|
||||
from tests.cassettes.chatroom_fixture import (
|
||||
CHATROOM_RECORDS,
|
||||
DEFAULT_PAGE_SIZE,
|
||||
TOTAL,
|
||||
make_chatroom_list_response,
|
||||
)
|
||||
from tests.cassettes.wxFriends_fixture import make_friend_list_response
|
||||
|
||||
BASE = "https://crm2.yunkecn.com"
|
||||
CHATROOM_LIST_URL = f"{BASE}/wechatweb/chatroom/getChatroomList"
|
||||
FRIEND_LIST_URL = f"{BASE}/wechatweb/wxFriends/friend_list/es"
|
||||
|
||||
USERID = "a" * 32
|
||||
COMPANY = "8m0atd"
|
||||
|
||||
# Realistic, capture-shaped group records. Field names are EXACTLY what the
|
||||
# live ``friend_list/es`` endpoint returns for ``friendTypeYunke="2"``
|
||||
# (verified 2026-08-10 Playwright capture). Every field with a target
|
||||
# ``ChatGroup`` column is populated so the test asserts a full mapping
|
||||
# end-to-end. (Member ids are NOT in this payload — the endpoint surfaces
|
||||
# only the ``friendNum`` count — so ``member_ids`` / ``member_ids_list`` are
|
||||
# exercised as None / [] separately.)
|
||||
GROUP_RECORDS: list[dict[str, Any]] = [
|
||||
{
|
||||
"friendWxId": "12345678901@chatroom",
|
||||
"friendWxNickname": "VIP客户交流群",
|
||||
"friendNum": 3,
|
||||
"friendHeadImageUrl": "https://wx.qlogo.cn/room_12345678901.png",
|
||||
"wxId": "wxid_staff_alice01",
|
||||
"ownerName": "Alice WeChat",
|
||||
"userId": "staff_user_001",
|
||||
"phone": "13800000001",
|
||||
"wechatPhone": "13800000011",
|
||||
"messageCount": 4521,
|
||||
"sendNum": 1204,
|
||||
"lastChatTime": 1700000000123,
|
||||
"version": "v1.20260731.room1",
|
||||
},
|
||||
{
|
||||
"friendWxId": "98765432109@chatroom",
|
||||
"friendWxNickname": "华东销售大群",
|
||||
"friendNum": 2,
|
||||
"friendHeadImageUrl": "https://wx.qlogo.cn/room_98765432109.png",
|
||||
"wxId": "wxid_staff_bob02",
|
||||
"ownerName": "Bob WeChat",
|
||||
"userId": "staff_user_002",
|
||||
"phone": "13800000002",
|
||||
"wechatPhone": "13800000022",
|
||||
"messageCount": 9821,
|
||||
"sendNum": 211,
|
||||
"lastChatTime": 1700000000456,
|
||||
"version": "v1.20260731.room2",
|
||||
},
|
||||
{
|
||||
# A group whose owner has no resolved staff id (userId None) — the
|
||||
# scraper must still yield it; None-safe fields stay None.
|
||||
"friendWxId": "55555555555@chatroom",
|
||||
"friendWxNickname": "External Coordination",
|
||||
"friendNum": 1,
|
||||
"friendHeadImageUrl": "https://wx.qlogo.cn/room_55555555555.png",
|
||||
"wxId": "wxid_staff_orphan04",
|
||||
"ownerName": "Orphan WeChat",
|
||||
"userId": None,
|
||||
"phone": None,
|
||||
"wechatPhone": None,
|
||||
"messageCount": 12,
|
||||
"sendNum": 0,
|
||||
"lastChatTime": 1700000000789,
|
||||
"version": "v1.20260731.room3",
|
||||
},
|
||||
]
|
||||
|
||||
TOTAL = len(GROUP_RECORDS)
|
||||
DEFAULT_PAGE_SIZE = 2
|
||||
|
||||
|
||||
def _primed_client() -> YunkeClient:
|
||||
"""A YunkeClient already in a logged-in state (login flow skipped)."""
|
||||
@@ -46,24 +109,24 @@ def _primed_client() -> YunkeClient:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# End-to-end: pagination + field mapping + member_ids_list parsing
|
||||
# End-to-end: pagination + field mapping
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_scrape_wechat_groups_yields_records_and_paginates():
|
||||
"""Two full pages + a terminating empty page -> 3 records, 3 calls."""
|
||||
page1 = make_chatroom_list_response(
|
||||
CHATROOM_RECORDS[:2], total=TOTAL, page_num=1, page_size=DEFAULT_PAGE_SIZE
|
||||
page1 = make_friend_list_response(
|
||||
GROUP_RECORDS[:2], total=TOTAL, page_num=1, page_size=DEFAULT_PAGE_SIZE
|
||||
)
|
||||
page2 = make_chatroom_list_response(
|
||||
CHATROOM_RECORDS[2:], total=TOTAL, page_num=2, page_size=DEFAULT_PAGE_SIZE
|
||||
page2 = make_friend_list_response(
|
||||
GROUP_RECORDS[2:], total=TOTAL, page_num=2, page_size=DEFAULT_PAGE_SIZE
|
||||
)
|
||||
page3 = make_chatroom_list_response(
|
||||
page3 = make_friend_list_response(
|
||||
[], total=TOTAL, page_num=3, page_size=DEFAULT_PAGE_SIZE
|
||||
)
|
||||
|
||||
route = respx.post(CHATROOM_LIST_URL).mock(
|
||||
route = respx.post(FRIEND_LIST_URL).mock(
|
||||
side_effect=[
|
||||
httpx.Response(200, json=page1),
|
||||
httpx.Response(200, json=page2),
|
||||
@@ -85,39 +148,41 @@ async def test_scrape_wechat_groups_yields_records_and_paginates():
|
||||
# Exactly the 3 fixture records (not duplicated, not dropped).
|
||||
assert len(results) == 3
|
||||
assert {r["room_id"] for r in results} == {
|
||||
rec["chatRoomId"] for rec in CHATROOM_RECORDS
|
||||
rec["friendWxId"] for rec in GROUP_RECORDS
|
||||
}
|
||||
|
||||
# Field mapping for each record (compare against the source record).
|
||||
for result, record in zip(results, CHATROOM_RECORDS, strict=True):
|
||||
for result, record in zip(results, GROUP_RECORDS, strict=True):
|
||||
# Identity + channel.
|
||||
assert result["room_id"] == record["chatRoomId"]
|
||||
assert result["room_id"] == record["friendWxId"]
|
||||
assert result["channel"] == "wechat"
|
||||
|
||||
# Naming + ownership.
|
||||
assert result["room_name"] == record["chatRoomName"]
|
||||
assert result["owner_account_id"] == record["wechatId"]
|
||||
assert result["owner_account_nickname"] == record["wechatNickName"]
|
||||
assert result["room_name"] == record["friendWxNickname"]
|
||||
assert result["owner_account_id"] == record["wxId"]
|
||||
assert result["owner_account_nickname"] == record["ownerName"]
|
||||
assert result["owner_user_id"] == record["userId"]
|
||||
assert result["owner_user_phone"] == record["userPhone"]
|
||||
# phone preferred, wechatPhone fallback.
|
||||
assert result["owner_user_phone"] == (
|
||||
record["phone"] or record["wechatPhone"]
|
||||
)
|
||||
|
||||
# Counts.
|
||||
assert result["member_count"] == record["memberCount"]
|
||||
assert result["member_count"] == record["friendNum"]
|
||||
assert result["message_count"] == record["messageCount"]
|
||||
assert result["own_message_count"] == record["ownMessageCount"]
|
||||
assert result["loss_members"] == record["lossMembers"]
|
||||
assert result["add_members"] == record["addMembers"]
|
||||
assert result["own_message_count"] == record["sendNum"]
|
||||
|
||||
# Avatar + timestamps.
|
||||
assert result["head_image_url"] == record["headImageUrl"]
|
||||
assert result["head_image_url"] == record["friendHeadImageUrl"]
|
||||
assert result["last_chat_time"] == record["lastChatTime"]
|
||||
assert result["update_time"] == record["updateTime"]
|
||||
|
||||
# member_ids carried raw; member_ids_list parsed (empties dropped).
|
||||
assert result["member_ids"] == record["memberIds"]
|
||||
assert result["member_ids_list"] == [
|
||||
seg for seg in record["memberIds"].split(";") if seg
|
||||
]
|
||||
# Member details NOT surfaced by friend_list/es -> None / [].
|
||||
assert result["member_ids"] is None
|
||||
assert result["member_ids_list"] == []
|
||||
# Fields the new endpoint does not carry.
|
||||
assert result["loss_members"] is None
|
||||
assert result["add_members"] is None
|
||||
assert result["update_time"] is None
|
||||
|
||||
# Version carried verbatim; raw_json preserves the original record.
|
||||
assert result["version"] == record["version"]
|
||||
@@ -125,46 +190,26 @@ async def test_scrape_wechat_groups_yields_records_and_paginates():
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# member_ids_list parsing edge cases
|
||||
# member_ids behaviour: always None / [] (not surfaced by friend_list/es)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_scrape_wechat_groups_drops_empty_member_id_segments():
|
||||
"""Trailing/empty ``memberIds`` segments are dropped from member_ids_list."""
|
||||
# Record 2 has a trailing ";" -> one empty segment that must be dropped.
|
||||
page1 = make_chatroom_list_response(
|
||||
[CHATROOM_RECORDS[1]], total=1, page_num=1, page_size=DEFAULT_PAGE_SIZE
|
||||
)
|
||||
page2 = make_chatroom_list_response([], total=1, page_num=2)
|
||||
respx.post(CHATROOM_LIST_URL).mock(
|
||||
async def test_scrape_wechat_groups_emits_empty_member_ids():
|
||||
"""``friend_list/es`` does not surface member ids; they are always
|
||||
``None`` / ``[]`` on yielded records (member mirroring deferred)."""
|
||||
record = dict(GROUP_RECORDS[0])
|
||||
page1 = make_friend_list_response([record], total=1, page_num=1)
|
||||
page2 = make_friend_list_response([], total=1, page_num=2)
|
||||
respx.post(FRIEND_LIST_URL).mock(
|
||||
side_effect=[httpx.Response(200, json=page1), httpx.Response(200, json=page2)]
|
||||
)
|
||||
|
||||
client = _primed_client()
|
||||
try:
|
||||
results = [r async for r in scrape_wechat_groups(client, page_size=DEFAULT_PAGE_SIZE)]
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
assert len(results) == 1
|
||||
# "wxid_member_b1;wxid_member_b2;" -> 2 ids (trailing empty dropped).
|
||||
assert results[0]["member_ids_list"] == ["wxid_member_b1", "wxid_member_b2"]
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_scrape_wechat_groups_handles_missing_member_ids():
|
||||
"""A group with no ``memberIds`` field yields an empty member_ids_list."""
|
||||
record = {"chatRoomId": "x@chatroom", "chatRoomName": "Empty"}
|
||||
page1 = make_chatroom_list_response([record], total=1, page_num=1)
|
||||
page2 = make_chatroom_list_response([], total=1, page_num=2)
|
||||
respx.post(CHATROOM_LIST_URL).mock(
|
||||
side_effect=[httpx.Response(200, json=page1), httpx.Response(200, json=page2)]
|
||||
)
|
||||
|
||||
client = _primed_client()
|
||||
try:
|
||||
results = [r async for r in scrape_wechat_groups(client, page_size=DEFAULT_PAGE_SIZE)]
|
||||
results = [
|
||||
r async for r in scrape_wechat_groups(client, page_size=DEFAULT_PAGE_SIZE)
|
||||
]
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
@@ -174,18 +219,18 @@ async def test_scrape_wechat_groups_handles_missing_member_ids():
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pagination body: pageNum/pageSize advanced correctly
|
||||
# Pagination body: pageNum/pageSize advanced + friendTypeYunke="2"
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_scrape_wechat_groups_sends_pagination_body():
|
||||
"""Outgoing request body carries pageNum/pageSize; advances per page."""
|
||||
page1 = make_chatroom_list_response(
|
||||
[CHATROOM_RECORDS[0]], total=TOTAL, page_num=1, page_size=1
|
||||
"""Outgoing body carries pageNum/pageSize and ``friendTypeYunke="2"``."""
|
||||
page1 = make_friend_list_response(
|
||||
[GROUP_RECORDS[0]], total=TOTAL, page_num=1, page_size=1
|
||||
)
|
||||
page2 = make_chatroom_list_response([], total=TOTAL, page_num=2, page_size=1)
|
||||
route = respx.post(CHATROOM_LIST_URL).mock(
|
||||
page2 = make_friend_list_response([], total=TOTAL, page_num=2, page_size=1)
|
||||
route = respx.post(FRIEND_LIST_URL).mock(
|
||||
side_effect=[httpx.Response(200, json=page1), httpx.Response(200, json=page2)]
|
||||
)
|
||||
|
||||
@@ -202,10 +247,13 @@ async def test_scrape_wechat_groups_sends_pagination_body():
|
||||
body1 = _json.loads(route.calls[0].request.content.decode())
|
||||
assert body1["pageNum"] == 1
|
||||
assert body1["pageSize"] == 1
|
||||
# The crucial switch: friendTypeYunke="2" selects GROUPS ("1" = friends).
|
||||
assert body1["friendTypeYunke"] == "2"
|
||||
|
||||
body2 = _json.loads(route.calls[1].request.content.decode())
|
||||
assert body2["pageNum"] == 2
|
||||
assert body2["pageSize"] == 1
|
||||
assert body2["friendTypeYunke"] == "2"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -216,8 +264,8 @@ async def test_scrape_wechat_groups_sends_pagination_body():
|
||||
@respx.mock
|
||||
async def test_scrape_wechat_groups_stops_on_empty_first_page():
|
||||
"""If the very first page is empty, scraper stops without over-fetching."""
|
||||
empty = make_chatroom_list_response([], total=0, page_num=1)
|
||||
route = respx.post(CHATROOM_LIST_URL).mock(
|
||||
empty = make_friend_list_response([], total=0, page_num=1)
|
||||
route = respx.post(FRIEND_LIST_URL).mock(
|
||||
return_value=httpx.Response(200, json=empty)
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user