Files
SnowLuma/packages/core/tests/actions/profile.test.ts
T
DrSmoothl 8506b60d07 refactor(core): split bridge-actions.ts (1814 lines) into themed action modules
bridge-actions.ts was a single 1814-line file holding 55 unrelated
exported functions — admin/file/forward/interaction/recall/profile/
status/translate/sign/avatar all jumbled together. Each function
already takes `bridge: Bridge` as its first parameter, so the
"deepening" target (per-UIN state object threaded into themed action
functions) was structurally there — what was missing was a coherent
file-level grouping that AI tools and humans could navigate.

This commit is candidate #2 from the deepening list, A-only variant:
pure file split, no facade change, no caller change outside the
bridge module.

New layout under packages/core/src/bridge/actions/ :

  shared.ts        82  private helpers (toInt, ensureRetCodeZero,
                       resolveSelfUid) and the MediaIndexNode type.
  group-admin.ts  153  mute/kick/leave + setGroup{Admin/Card/Name/
                       SpecialTitle/AddOption/Search/Remark/AddRequest}
                       + getGroupAtAllRemain.                (14 fns)
  group-file.ts   821  upload/list/url/delete/move/folder ops, both
                       group + private files, media-URL fetchers for
                       ptt/video, fetchGroupFileCount. Owns file-
                       specific helpers (normalizeDirectory,
                       buildGroupFileUploadExt, normalizeMediaNode,
                       fetchNtv2DownloadUrl, ...).            (15 fns)
  group-message   101  recall* / markRead* / setGroupEssence.  (5 fns)
  interaction.ts   61  poke / like / reaction / emoji-likes.   (4 fns)
  forward.ts      197  uploadForwardNodes, fetchForwardNodes +
                       in-memory resId cache.                  (2 fns)
  friend.ts        53  setFriendAddRequest, deleteFriend,
                       setFriendRemark.                        (3 fns)
  profile.ts      269  setOnlineStatus, setProfile, setSelfLongNick,
                       setInputStatus, setAvatar, fetchCustomFace,
                       getProfileLike, getUnidirectionalFriendList.
                                                              (8 fns)
  misc.ts         173  translateEn2Zh, getMiniAppArk,
                       clickInlineKeyboardButton, sendGroupSign.
                                                              (4 fns)

bridge.ts updates its imports — one themed import block per action
module instead of one giant block from bridge-actions.ts. GroupFilesResult
and MediaIndexNode type imports now point at actions/group-file and
actions/shared. Public Bridge facade API is unchanged: every caller
outside `bridge/` keeps the same `bridge.X(...)` surface and the
delegated function it points at.

bridge-actions.ts is deleted. The new shared.ts holds the three
helpers that span themes; everything else lives co-located with the
functions that use it.

Adds 60 happy-path tests across tests/actions/ — one .test.ts per
themed file plus a shared `_helpers.ts` (mockBridge fixture):

  group-admin     10  command + payload dispatch, UID resolution,
                      flag-driven sub-command selection (mute on/off,
                      add-request filtered/unfiltered).
  group-file      13  fetchGroupFileCount, upload happy path with
                      and without highway, OIDB error bubbling, file
                      listing pagination + folder/file split, URL
                      builder shape, delete/move/folder dispatch,
                      NTV2 URL assembly.
  group-message    5  recall (group/private), markRead, essence on/off,
                      transport failure propagation.
  interaction      6  poke (group vs friend payload), like, reaction
                      on/off, emoji-likes cookie/isLast logic.
  forward          5  empty-array rejection, dispatch + res_id return,
                      transport failure, cache reuse after upload.
  friend           5  numeric flag → UID resolution path, opaque flag
                      passthrough, delete + best-effort cache refresh.
  profile          9  status dispatch, setProfile no-op when undefined,
                      setAvatar highway cmd 90, getProfileLike +
                      getUnidirectionalFriendList JSON parsing.
  misc             6  translate, mini-app type guard, click + sign
                      dispatch.

Tests use vi.mock on `bridge-oidb` (and `highway-client`/`highway-utils`
where relevant) so each action runs against a tiny fake Bridge, no
native pipe / real OIDB exchange needed. Previously these 55 functions
had zero unit-test coverage.

244 tests pass (was 184); only failing suite remains the pre-existing
macOS-arm64 missing websocket native addon, unrelated.
2026-05-12 16:51:34 +08:00

110 lines
4.6 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined),
sendOidbAndDecode: vi.fn(async () => ({})),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
}));
vi.mock('../../src/bridge/highway/highway-client', () => ({
fetchHighwaySession: vi.fn(async () => ({})),
uploadHighwayHttp: vi.fn(async () => undefined),
}));
vi.mock('../../src/bridge/highway/utils', () => ({
loadBinarySource: vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]), fileName: 'avatar.bin' })),
computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })),
computeMd5: vi.fn(() => new Uint8Array(16)),
}));
import * as oidb from '../../src/bridge/bridge-oidb';
import * as highwayClient from '../../src/bridge/highway/highway-client';
import * as profile from '../../src/bridge/actions/profile';
import { mockBridge } from './_helpers';
describe('actions/profile', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear();
vi.mocked(oidb.sendOidbAndDecode).mockClear();
vi.mocked(oidb.resolveUserUid).mockClear();
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
});
it('setOnlineStatus sends to status_svc.SetStatus and accepts an empty response', async () => {
const bridge = mockBridge();
await profile.setOnlineStatus(bridge as any, 11, 0, 100);
const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus');
});
it('setProfile is a no-op when both arguments are undefined', async () => {
const bridge = mockBridge();
await profile.setProfile(bridge as any);
expect(oidb.sendOidbAndCheck).not.toHaveBeenCalled();
});
it('setProfile only sends non-undefined fields', async () => {
const bridge = mockBridge();
await profile.setProfile(bridge as any, 'New Nick');
expect(oidb.sendOidbAndCheck).toHaveBeenCalledOnce();
const body: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4];
expect(body.stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]);
});
it('setSelfLongNick wraps the long nick in profile tag 102', async () => {
const bridge = mockBridge();
await profile.setSelfLongNick(bridge as any, 'hello world');
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!;
expect((call[4] as any).profile).toEqual({ tag: 102, value: 'hello world' });
});
it('setInputStatus resolves UID first and sends 0xcd4_1', async () => {
const bridge = mockBridge();
await profile.setInputStatus(bridge as any, 10001, 1);
expect(oidb.resolveUserUid).toHaveBeenCalledWith(bridge, 10001);
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!;
expect(call[1]).toBe('OidbSvcTrpcTcp.0xcd4_1');
});
it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => {
const bridge = mockBridge();
await profile.setAvatar(bridge as any, '/some/avatar.png');
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
const [, , cmdId] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!;
expect(cmdId).toBe(90);
});
it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
userLikeInfos: [{
uid: 'u',
time: 1700000000n,
favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 },
voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n },
}],
});
const out = await profile.getProfileLike(bridge as any);
expect(out.favoriteInfo.total_count).toBe(5);
expect(out.voteInfo.total_count).toBe(7);
});
it('getProfileLike throws on empty result', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ userLikeInfos: [] });
await expect(profile.getProfileLike(bridge as any)).rejects.toThrow(/empty/);
});
it('getUnidirectionalFriendList parses the embedded JSON body', async () => {
const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }),
});
const out = await profile.getUnidirectionalFriendList(bridge as any);
expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]);
});
});