Merge remote-tracking branch 'origin/master' into feat/game-fork
Project CI / AI game creator shell Rust lane 1/2 (pull_request) Successful in 7m31s
Project CI / AI game creator shell Rust lane 2/2 (pull_request) Successful in 6m20s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 4m3s
Project CI / Frontend tests (pull_request) Successful in 2m54s
Project CI / Backend tests (pull_request) Successful in 7m36s
Project CI / AI game creator shell web tests (pull_request) Successful in 3m26s
Project CI / Repository checks (pull_request) Successful in 6m25s
Project CI / Native shell tests (pull_request) Successful in 9m34s
Project CI / AI game creator shell Rust lane 1/2 (pull_request) Successful in 7m31s
Project CI / AI game creator shell Rust lane 2/2 (pull_request) Successful in 6m20s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 4m3s
Project CI / Frontend tests (pull_request) Successful in 2m54s
Project CI / Backend tests (pull_request) Successful in 7m36s
Project CI / AI game creator shell web tests (pull_request) Successful in 3m26s
Project CI / Repository checks (pull_request) Successful in 6m25s
Project CI / Native shell tests (pull_request) Successful in 9m34s
# Conflicts: # deploy/container/nginx.conf # deploy/nginx/genarrative-dev-http.conf # deploy/nginx/genarrative.conf # server-rs/crates/api-server/src/modules/game_distribution.rs # src/components/game-distribution/GameDetailPage.tsx # src/components/game-distribution/GameDistributionPages.test.tsx # src/components/platform-entry/PlatformEntryActiveFlowShell.tsx
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
// 检查 game-distribution 的 Rust DTO 与手写 TS DTO 是否一致。
|
||||
// 检查游戏分发与创作者公开查询的 Rust DTO 与手写 TS DTO 是否一致。
|
||||
//
|
||||
// 为什么需要它:`packages/shared/src/contracts/gameDistribution.ts` 是手写的,没有生成绑定兜底。
|
||||
// Rust 侧加字段而 TS 侧忘改时,只有跑起来才会发现。这里用一张显式映射表逐字段/逐变体比对:
|
||||
@@ -16,11 +16,19 @@ const RUST_FILE = 'server-rs/crates/shared-contracts/src/game_distribution.rs';
|
||||
const TS_FILE = 'packages/shared/src/contracts/gameDistribution.ts';
|
||||
const ADMIN_RUST_FILE = 'server-rs/crates/shared-contracts/src/admin.rs';
|
||||
const ADMIN_TS_FILE = 'apps/admin-web/src/api/adminApiTypes.ts';
|
||||
const CREATOR_RUST_FILE = 'server-rs/crates/shared-contracts/src/creator.rs';
|
||||
const CREATOR_TS_FILE = 'packages/shared/src/contracts/creator.ts';
|
||||
const API_MODULE_FILE =
|
||||
'server-rs/crates/api-server/src/modules/game_distribution.rs';
|
||||
|
||||
// [Rust 类型名, TS 类型名]
|
||||
const PAIRS = [
|
||||
['CreatorUser', 'CreatorUser'],
|
||||
['CreatorRelationship', 'CreatorRelationship'],
|
||||
['CreatorProfile', 'CreatorProfile'],
|
||||
['CreatorConnection', 'CreatorConnection'],
|
||||
['CreatorConnections', 'CreatorConnections'],
|
||||
['CreatorRelationshipResponse', 'CreatorRelationshipResponse'],
|
||||
[
|
||||
'GameDistributionPublishMetadataSuggestionRequest',
|
||||
'GameDistributionPublishMetadataSuggestionRequest',
|
||||
@@ -147,7 +155,7 @@ function renamedMember(value, kind, rename) {
|
||||
function rustDefinitions(source) {
|
||||
const result = new Map();
|
||||
const pattern =
|
||||
/\n(?<attrs>(?:#\[[^\n]*\]\n)*)pub (?<kind>struct|enum) (?<name>GameDistribution\w+|AdminGameReview\w*)(?<body>[\s\S]*?)\n\}/g;
|
||||
/\n(?<attrs>(?:#\[[^\n]*\]\n)*)pub (?<kind>struct|enum) (?<name>GameDistribution\w+|AdminGameReview\w*|Creator\w+)(?<body>[\s\S]*?)\n\}/g;
|
||||
let match;
|
||||
while ((match = pattern.exec(source))) {
|
||||
const { attrs, kind, name, body } = match.groups;
|
||||
@@ -168,7 +176,7 @@ function rustDefinitions(source) {
|
||||
function tsDefinitions(source) {
|
||||
const result = new Map();
|
||||
const objectPattern =
|
||||
/export (?:type|interface) (GameDistribution\w+|AdminGameReview\w*)(?: =)? \{([\s\S]*?)\n\};?/g;
|
||||
/export (?:type|interface) (GameDistribution\w+|AdminGameReview\w*|Creator\w+)(?: =)? \{([\s\S]*?)\n\};?/g;
|
||||
let match;
|
||||
while ((match = objectPattern.exec(source))) {
|
||||
const members = [];
|
||||
@@ -182,7 +190,7 @@ function tsDefinitions(source) {
|
||||
result.set(match[1], { kind: 'struct', members, required });
|
||||
}
|
||||
const unionPattern =
|
||||
/export type (GameDistribution\w+|AdminGameReview\w*) =\s*([^;]+);/g;
|
||||
/export type (GameDistribution\w+|AdminGameReview\w*|Creator\w+) =\s*([^;]+);/g;
|
||||
while ((match = unionPattern.exec(source))) {
|
||||
if (result.has(match[1])) continue;
|
||||
result.set(match[1], {
|
||||
@@ -347,12 +355,12 @@ function insertedKeys(body) {
|
||||
const rust = rustDefinitions(
|
||||
fs.readFileSync(RUST_FILE, 'utf8') +
|
||||
'\n' +
|
||||
fs.readFileSync(ADMIN_RUST_FILE, 'utf8'),
|
||||
fs.readFileSync(ADMIN_RUST_FILE, 'utf8') + '\n' + fs.readFileSync(CREATOR_RUST_FILE, 'utf8'),
|
||||
);
|
||||
const ts = tsDefinitions(
|
||||
fs.readFileSync(TS_FILE, 'utf8') +
|
||||
'\n' +
|
||||
fs.readFileSync(ADMIN_TS_FILE, 'utf8'),
|
||||
fs.readFileSync(ADMIN_TS_FILE, 'utf8') + '\n' + fs.readFileSync(CREATOR_TS_FILE, 'utf8'),
|
||||
);
|
||||
const failures = [];
|
||||
const mappedRust = new Set(PAIRS.map(([rustName]) => rustName));
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
// E2E_ADMIN_USER=... E2E_ADMIN_PASSWORD=... npm run check:game-distribution-ops-rollback-e2e
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import path from 'node:path';
|
||||
|
||||
import JSZip from 'jszip';
|
||||
@@ -99,6 +100,37 @@ async function release(pathname) {
|
||||
return { status: response.status, body, headers: response.headers };
|
||||
}
|
||||
|
||||
/// 原样请求(不自动解压):压缩与条件请求必须看真实线字节,不能让 fetch 帮忙解码。
|
||||
function releaseRaw(pathname, { acceptEncoding, ifNoneMatch } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const target = new URL(`${API}${pathname}`);
|
||||
const headers = {};
|
||||
if (acceptEncoding) headers['accept-encoding'] = acceptEncoding;
|
||||
if (ifNoneMatch) headers['if-none-match'] = ifNoneMatch;
|
||||
const request = http.request(
|
||||
{
|
||||
hostname: target.hostname,
|
||||
port: target.port,
|
||||
path: `${target.pathname}${target.search}`,
|
||||
headers,
|
||||
},
|
||||
(response) => {
|
||||
const chunks = [];
|
||||
response.on('data', (chunk) => chunks.push(chunk));
|
||||
response.on('end', () =>
|
||||
resolve({
|
||||
status: response.statusCode,
|
||||
headers: response.headers,
|
||||
body: Buffer.concat(chunks),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
request.on('error', reject);
|
||||
request.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function adminToken() {
|
||||
const login = await api('/admin/api/login', {
|
||||
method: 'POST',
|
||||
@@ -397,6 +429,47 @@ async function main() {
|
||||
);
|
||||
assertReleaseHeaders('v1 CSS', baselineCss, { html: false });
|
||||
|
||||
// 传输与条件请求契约:引擎包动辄 1 MiB 以上,文本资源必须按 Accept-Encoding 压缩,
|
||||
// 并在 60 秒缓存窗口之后靠 ETag 重验证(304)而不是重下整包。
|
||||
const releasePath = `/api/game-distribution/releases/${gameId}/index.html`;
|
||||
const compressedHtml = await releaseRaw(releasePath, {
|
||||
acceptEncoding: 'gzip',
|
||||
});
|
||||
check(
|
||||
'发行文本资源按 Accept-Encoding 压缩并声明 Vary',
|
||||
compressedHtml.status === 200 &&
|
||||
compressedHtml.headers['content-encoding'] === 'gzip' &&
|
||||
String(compressedHtml.headers.vary ?? '').includes('accept-encoding') &&
|
||||
compressedHtml.body.length < Buffer.byteLength(baselineRelease.body),
|
||||
`encoding=${compressedHtml.headers['content-encoding'] ?? ''} vary=${compressedHtml.headers.vary ?? ''} bytes=${compressedHtml.body.length}/${Buffer.byteLength(baselineRelease.body)}`,
|
||||
);
|
||||
const releaseEtag = baselineRelease.headers.get('etag') ?? '';
|
||||
check(
|
||||
'发行资源下发强 ETag',
|
||||
/^"[0-9a-f]{32}"$/u.test(releaseEtag),
|
||||
`etag=${releaseEtag}`,
|
||||
);
|
||||
const revalidated = await releaseRaw(releasePath, {
|
||||
ifNoneMatch: releaseEtag,
|
||||
});
|
||||
check(
|
||||
'If-None-Match 命中时返回 304 且不带正文',
|
||||
revalidated.status === 304 &&
|
||||
revalidated.body.length === 0 &&
|
||||
revalidated.headers['cache-control'] === RELEASE_CACHE_CONTROL &&
|
||||
revalidated.headers.etag === releaseEtag,
|
||||
`status=${revalidated.status} body=${revalidated.body.length} cache-control=${revalidated.headers['cache-control'] ?? ''}`,
|
||||
);
|
||||
const identityHtml = await releaseRaw(releasePath, {
|
||||
acceptEncoding: 'identity',
|
||||
});
|
||||
check(
|
||||
'客户端不接受 gzip 时不下发压缩体',
|
||||
identityHtml.status === 200 &&
|
||||
identityHtml.headers['content-encoding'] === undefined,
|
||||
`encoding=${identityHtml.headers['content-encoding'] ?? ''}`,
|
||||
);
|
||||
|
||||
const pendingIds = {};
|
||||
for (const marker of ['V2-OK', 'V3-OK']) {
|
||||
const built = await buildPackage(marker);
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
#!/usr/bin/env python3
|
||||
"""创作者关系真实 API / SpacetimeDB 验证,仅允许显式指定的隔离本地库。
|
||||
|
||||
先用仓库 dev 启动器启动全新 creator-hub-validation 库和 API,启用开发密码注册。
|
||||
运行:python3 scripts/test-creator-runtime.py --database creator-hub-validation
|
||||
测试凭据只保存在内存或隔离 data dir,不输出令牌,不触发外部媒体服务。
|
||||
"""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
def request(url, method="GET", body=None, token=None, expected=200):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(url, method=method, data=data, headers=headers)
|
||||
try:
|
||||
response = urllib.request.urlopen(req, timeout=30)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
assert response.status == expected, f"{method} {urllib.parse.urlsplit(url).path}: {response.status} != {expected}"
|
||||
raw = response.read()
|
||||
return (json.loads(raw) if raw else None), response.headers
|
||||
|
||||
|
||||
def option(raw):
|
||||
return raw[1] if raw[0] == 0 else None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--database", required=True)
|
||||
parser.add_argument("--dev-stack", default=".app/dev-stack.json")
|
||||
args = parser.parse_args()
|
||||
state = json.loads(Path(args.dev_stack).read_text())
|
||||
assert args.database == state["database"] == "creator-hub-validation", "只允许专用隔离库"
|
||||
api = state["services"]["api-server"]["url"]
|
||||
server = state["services"]["spacetime"]["url"]
|
||||
for url in [api, server]:
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
assert parsed.scheme == "http" and parsed.hostname in ["127.0.0.1", "localhost", "::1"]
|
||||
data_dir = Path(state["spacetimeDataDir"])
|
||||
service = json.loads((data_dir / "dev-api-identities/local-node.json").read_text())
|
||||
operator_path = data_dir / "creator-test-operator.json"
|
||||
if operator_path.exists():
|
||||
operator = json.loads(operator_path.read_text())
|
||||
else:
|
||||
operator, _ = request(server + "/v1/identity", "POST", {})
|
||||
fd = os.open(operator_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, "w") as file:
|
||||
json.dump(operator, file)
|
||||
scope = hashlib.sha256((server + "\n" + args.database).encode()).hexdigest()
|
||||
secret = json.loads((data_dir / "dev-runtime-service-bootstrap-secrets" / (scope + ".json")).read_text())["secret"]
|
||||
result, _ = request(server + "/v1/database/" + args.database + "/call/authorize_database_migration_operator", "POST", [{"bootstrap_secret": secret, "operator_identity_hex": operator["identity"], "note": "创作者隔离测试夹具"}], operator["token"])
|
||||
assert result[0], "测试迁移身份授权失败"
|
||||
|
||||
def call(name, value, token=operator["token"]):
|
||||
return request(server + "/v1/database/" + args.database + "/call/" + name, "POST", [value], token)[0]
|
||||
|
||||
def export(table):
|
||||
result = call("export_database_migration_to_file", {"include_tables": [table]})
|
||||
assert result[0], option(result[-1])
|
||||
return json.loads(option(result[2]))["tables"][0]["rows"]
|
||||
|
||||
def fixtures(tables):
|
||||
result = call("import_database_migration_incremental_from_file", {"migration_json": json.dumps({"schema_version": 1, "exported_at_micros": int(time.time() * 1e6), "tables": [{"name": k, "rows": v} for k, v in tables.items()]}), "include_tables": list(tables), "replace_existing": False, "dry_run": False})
|
||||
assert result[0], option(result[-1])
|
||||
|
||||
def login(number):
|
||||
value, _ = request(api + "/api/auth/entry", "POST", {"purePhoneNumber": str(13900006000 + number), "password": "Creator-test-2026"})
|
||||
return value["user"]["id"], value["token"]
|
||||
|
||||
def relation(viewer, target):
|
||||
return request(api + "/api/creators/" + target + "/relationship", token=viewer[1])[0]["relationship"]
|
||||
|
||||
def write(viewer, target, method="PUT", remove=False, expected=200):
|
||||
path = "/api/creators/me/followers/" + target if remove else "/api/creators/" + target + "/follow"
|
||||
return request(api + path, method, token=viewer[1], expected=expected)[0]
|
||||
|
||||
def profile(user):
|
||||
value, _ = request(api + "/api/creators/" + user)
|
||||
assert set(value["user"]) == {"id", "publicUserCode", "displayName", "avatarUrl"}
|
||||
return value
|
||||
|
||||
request(api + "/healthz")
|
||||
a, b, c = [login(n) for n in [1, 2, 3]]
|
||||
# 重跑时先清理测试账号的相互出边;不清表或删除已有业务数据。
|
||||
for actor in [a, b, c]:
|
||||
for target in [a, b, c]:
|
||||
if actor != target:
|
||||
write(actor, target[0], "DELETE")
|
||||
assert relation(a, a[0]) == {"isSelf": True, "isFollowing": False, "isFollowedBy": False}
|
||||
for kind in ["following", "followers"]:
|
||||
empty, _ = request(api + f"/api/creators/{c[0]}/{kind}")
|
||||
assert empty == {"items": [], "nextCursor": None, "total": 0}
|
||||
write(a, b[0])
|
||||
first = next(row for row in export("user_follow") if row["follower_user_id"] == a[0] and row["followee_user_id"] == b[0])
|
||||
write(a, b[0])
|
||||
second = next(row for row in export("user_follow") if row["relationship_id"] == first["relationship_id"])
|
||||
assert first == second, "重复关注不能改时间"
|
||||
write(b, a[0])
|
||||
assert relation(a, b[0]) == {"isSelf": False, "isFollowing": True, "isFollowedBy": True}
|
||||
write(a, b[0], "DELETE", remove=True)
|
||||
write(a, b[0], "DELETE", remove=True)
|
||||
assert relation(a, b[0]) == {"isSelf": False, "isFollowing": True, "isFollowedBy": False}
|
||||
write(b, a[0]) # 移除不是拉黑。
|
||||
write(a, b[0], "DELETE")
|
||||
assert not relation(a, b[0])["isFollowing"]
|
||||
write(a, b[0])
|
||||
third = next(row for row in export("user_follow") if row["relationship_id"] == first["relationship_id"])
|
||||
assert third["created_at"] != first["created_at"]
|
||||
write(a, a[0], expected=400)
|
||||
write(a, a[0], "DELETE", expected=400)
|
||||
write(a, a[0], "DELETE", remove=True, expected=400)
|
||||
write(a, "missing-creator", expected=404)
|
||||
request(api + "/api/creators/" + b[0] + "/follow", "PUT", expected=401)
|
||||
request(api + "/api/creators/" + b[0] + "/followers", token="invalid", expected=401)
|
||||
request(api + "/api/creators/" + a[0] + "/followers/" + b[0], "DELETE", token=c[1], expected=404)
|
||||
write(c, b[0], "DELETE", remove=True)
|
||||
assert relation(a, b[0])["isFollowedBy"], "第三方移除不能改变他人入边"
|
||||
stranger, _ = request(server + "/v1/identity", "POST", {})
|
||||
denied = call("follow_creator_and_return", {"actor_id": a[0], "target_id": b[0]}, stranger["token"])
|
||||
assert option(denied[0]) is None and option(denied[1]) == "forbidden"
|
||||
denied = call("list_creator_connections_and_return", {"owner_id": a[0], "viewer_id": [0, a[0]], "kind": "following", "limit": 20, "cursor": None}, stranger["token"])
|
||||
assert option(denied[0]) is None and option(denied[1]) == "forbidden"
|
||||
print("PASS 双向关系、幂等、重新关注、移除粉丝、自操作、认证和越权", flush=True)
|
||||
|
||||
peers = [login(n) for n in range(10, 65)]
|
||||
stamp = {"__timestamp_micros_since_unix_epoch__": 1700000000000000}
|
||||
rows = []
|
||||
for peer, _ in peers:
|
||||
for follower, followee in [(a[0], peer), (peer, a[0])]:
|
||||
rows.append({"relationship_id": f"{len(follower.encode())}:{follower}{followee}", "follower_user_id": follower, "followee_user_id": followee, "created_at": stamp})
|
||||
# 不存在的对端必须同时从计数和列表排除。
|
||||
rows.extend([{"relationship_id": f"{len(x.encode())}:{x}{y}", "follower_user_id": x, "followee_user_id": y, "created_at": stamp} for x, y in [(a[0], "missing-peer"), ("missing-peer", a[0])]])
|
||||
fixtures({"user_follow": rows})
|
||||
for kind, count_key in [("following", "followingCount"), ("followers", "followerCount")]:
|
||||
for viewer in [None, a[1], b[1], c[1]]:
|
||||
seen, cursor, total = [], None, None
|
||||
while True:
|
||||
path = f"/api/creators/{a[0]}/{kind}?limit=20"
|
||||
if cursor:
|
||||
path += "&cursor=" + urllib.parse.quote(cursor)
|
||||
result, headers = request(api + path, token=viewer)
|
||||
total = result["total"]
|
||||
assert headers["Cache-Control"] == "private, no-store"
|
||||
for row in result["items"]:
|
||||
assert (row["relationship"] is not None) == (viewer == a[1])
|
||||
assert set(row["user"]) == {"id", "publicUserCode", "displayName", "avatarUrl"}
|
||||
seen.append(row["user"]["id"])
|
||||
cursor = result["nextCursor"]
|
||||
if not cursor:
|
||||
break
|
||||
request(api + f"/api/creators/{b[0]}/{kind}?cursor=" + cursor, expected=400)
|
||||
other = "followers" if kind == "following" else "following"
|
||||
request(api + f"/api/creators/{a[0]}/{other}?cursor=" + cursor, expected=400)
|
||||
assert len(seen) == len(set(seen)) == total == profile(a[0])[count_key]
|
||||
assert total == 56 and "missing-peer" not in seen
|
||||
before = export("user_follow")
|
||||
a = login(1) # 触发认证快照刷新和持久化。
|
||||
assert export("user_follow") == before
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
list(pool.map(lambda _: write(c, b[0]), range(8)))
|
||||
assert len([row for row in export("user_follow") if row["follower_user_id"] == c[0] and row["followee_user_id"] == b[0]]) == 1
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
list(pool.map(lambda n: write(c, b[0], "PUT" if n % 2 else "DELETE"), range(8)))
|
||||
db_has = any(row["follower_user_id"] == c[0] and row["followee_user_id"] == b[0] for row in export("user_follow"))
|
||||
assert relation(c, b[0])["isFollowing"] == db_has
|
||||
# 丢弃成功回执,模拟调用方不知道写入结果;正式读取决定下一动作。
|
||||
write(c, b[0])
|
||||
assert relation(c, b[0])["isFollowing"]
|
||||
write(c, b[0], "DELETE")
|
||||
assert not relation(c, b[0])["isFollowing"]
|
||||
print("PASS 同时间多页、公开只读、失效用户过滤、认证快照保留、并发及未知结果回读", flush=True)
|
||||
|
||||
none = {"none": []}
|
||||
some = lambda value: {"some": value}
|
||||
games, versions = [], []
|
||||
# 其它作者的更新作品占满旧广场前 48 项,目标作者仍应得到自己的 48 项。
|
||||
for prefix, owner, count in [("target", a[0], 55), ("other", b[0], 55), ("hidden", a[0], 6)]:
|
||||
for n in range(count):
|
||||
game_id = f"creator-web-fixture-{prefix}-{n:03}"
|
||||
version_id = game_id + "-v1"
|
||||
created = {"__timestamp_micros_since_unix_epoch__": 1800000000000000 + (1000 if prefix == "other" else 0) + n}
|
||||
game = dict(game_id=game_id, owner_user_id=owner, title=game_id, summary="测试", description="测试", category="adventure", tags_json="[]", cover_asset_id=none, author_name=none, author_avatar_url=none, device_support_desktop=True, device_support_mobile=True, device_support_touch=True, input_modes_json='["touch"]', orientation="any", publication_revision=1, active_version_id=some(version_id), visibility="published", play_count=0, created_at=created, updated_at=created, local_project_id=none, cover_object_key=none, screenshots_json=none, deleted_at=none)
|
||||
version = dict(version_id=version_id, game_id=game_id, owner_user_id=owner, version_number=1, package_sha256="0" * 64, package_bytes=1, package_file_count=1, package_entry_path="index.html", status="published", review_reason=none, created_at=created, updated_at=created, local_project_id=none, package_object_key=none, package_manifest_json=none, entry_url=some("/games/game_" + hashlib.sha256(game_id.encode()).hexdigest()[:32] + "/"), reviewed_by_user_id=none, uploaded_at=none, submitted_at=none, reviewed_at=none, published_at=some(created), revoked_at=none, last_error_code=none, last_error_message=none, metadata_json=none)
|
||||
if prefix == "hidden":
|
||||
if n == 0: game["visibility"] = "unpublished"
|
||||
if n == 1: game["visibility"] = "suspended"
|
||||
if n == 2: game["deleted_at"] = some(created)
|
||||
if n == 3: game["active_version_id"] = none
|
||||
if n == 4: version["status"] = "pending_review"
|
||||
if n == 5: version["game_id"] = "wrong-game"
|
||||
games.append(game)
|
||||
versions.append(version)
|
||||
fixtures({"game_distribution_game": games, "game_distribution_version": versions})
|
||||
target, _ = request(api + "/api/game-distribution/games?authorId=" + a[0])
|
||||
assert len(target["games"]) == 48 and target["nextCursor"] is None
|
||||
assert all(game["author"]["id"] == a[0] and game["id"].startswith("creator-web-fixture-target-") for game in target["games"])
|
||||
assert [game["id"] for game in target["games"]] == [f"creator-web-fixture-target-{n:03}" for n in range(54, 6, -1)]
|
||||
gallery, _ = request(api + "/api/game-distribution/games")
|
||||
assert len(gallery["games"]) == 48 and gallery["nextCursor"] is None
|
||||
assert all(game["author"]["id"] == b[0] for game in gallery["games"])
|
||||
request(api + "/api/game-distribution/games?authorId=", expected=400)
|
||||
empty, _ = request(api + "/api/game-distribution/games?authorId=" + c[0])
|
||||
assert empty["games"] == []
|
||||
print("PASS 作者过滤先于 48 项截取、公开版本隔离、旧广场上限与空作者校验", flush=True)
|
||||
print("PASS 创作者后端隔离运行时验收", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,258 @@
|
||||
/** 隔离创作者数据库的真实浏览器验收。先运行 test-creator-runtime.py,再启动同库 dev:web。
|
||||
* CREATOR_PLAYWRIGHT_DIR 指向临时安装的 playwright;浏览器、截图与登录信息均不入库。
|
||||
*/
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { createRequire } = require('node:module');
|
||||
const state = JSON.parse(fs.readFileSync('.app/dev-stack.json', 'utf8'));
|
||||
assert.equal(state.database, 'creator-hub-validation');
|
||||
const web = state.services.web.url;
|
||||
const api = state.services['api-server'].url;
|
||||
for (const url of [web, api]) assert.equal(new URL(url).hostname, '127.0.0.1');
|
||||
const runtimeRequire = process.env.CREATOR_PLAYWRIGHT_DIR
|
||||
? createRequire(
|
||||
path.resolve(process.env.CREATOR_PLAYWRIGHT_DIR, 'package.json'),
|
||||
)
|
||||
: require;
|
||||
const { chromium } = runtimeRequire('playwright');
|
||||
async function json(endpoint, token, method = 'GET', body) {
|
||||
const response = await fetch(api + endpoint, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
assert.ok(response.ok, `${method} ${endpoint}: ${response.status}`);
|
||||
const result = await response.json();
|
||||
return result.data ?? result;
|
||||
}
|
||||
async function login(n) {
|
||||
return json('/api/auth/entry', null, 'POST', {
|
||||
purePhoneNumber: String(13900006000 + n),
|
||||
password: 'Creator-test-2026',
|
||||
});
|
||||
}
|
||||
async function waitRows(page, count) {
|
||||
await page.waitForFunction(
|
||||
(n) => document.querySelectorAll('.creator-list > li').length === n,
|
||||
count,
|
||||
);
|
||||
}
|
||||
(async () => {
|
||||
const [a, b] = await Promise.all([login(1), login(2)]);
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const errors = [];
|
||||
try {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: 1280, height: 900 },
|
||||
});
|
||||
await context.addInitScript(
|
||||
(token) =>
|
||||
localStorage.setItem('genarrative.auth.access-token.v1', token),
|
||||
a.token,
|
||||
);
|
||||
const page = await context.newPage();
|
||||
page.on('pageerror', (error) => errors.push(error.message));
|
||||
await page.goto(web + '/creators');
|
||||
await page.locator('.game-card').first().waitFor();
|
||||
assert.equal(await page.locator('.game-card').count(), 48);
|
||||
assert.deepEqual(
|
||||
await page
|
||||
.getByRole('navigation', { name: '平台导航', exact: true })
|
||||
.getByRole('button')
|
||||
.allTextContents(),
|
||||
['创作', '项目', '游戏', '创作者主页', '我的'],
|
||||
);
|
||||
assert.equal(
|
||||
await page
|
||||
.locator('.creator-profile')
|
||||
.getByRole('button', { name: '取消关注' })
|
||||
.count(),
|
||||
0,
|
||||
);
|
||||
await page.screenshot({ path: '/tmp/creator-home-desktop.png' });
|
||||
await page.locator('.game-card').first().click();
|
||||
await page.locator('.game-detail-page').waitFor();
|
||||
await page.locator('.game-detail-page .creator-user-link').click();
|
||||
await page.locator('.creator-counts').waitFor();
|
||||
assert.equal(new URL(page.url()).searchParams.get('id'), a.user.id);
|
||||
await page
|
||||
.getByRole('navigation', { name: '平台导航', exact: true })
|
||||
.getByRole('button', { name: '创作者主页' })
|
||||
.click();
|
||||
assert.equal(new URL(page.url()).search, ''); // 同舞台切回本人,URL 改变也会重绘。
|
||||
await page.locator('.creator-counts a').first().click();
|
||||
await waitRows(page, 20);
|
||||
await page.getByRole('button', { name: '加载更多' }).click();
|
||||
await waitRows(page, 40);
|
||||
await page.locator('.platform-tab-panel').evaluate((el) => {
|
||||
el.scrollTop = 650;
|
||||
});
|
||||
await page.waitForTimeout(100);
|
||||
await page.locator('.creator-list .creator-user-link').nth(7).click();
|
||||
await page.locator('.creator-counts').waitFor();
|
||||
await page.goBack();
|
||||
await waitRows(page, 40);
|
||||
assert.ok(
|
||||
await page
|
||||
.locator('.platform-tab-panel')
|
||||
.evaluate((el) => el.scrollTop > 200),
|
||||
);
|
||||
const first = page.locator('.creator-list > li').first();
|
||||
const target = new URL(
|
||||
await first.locator('a').getAttribute('href'),
|
||||
web,
|
||||
).searchParams.get('id');
|
||||
await first.getByRole('button', { name: '取消关注' }).click();
|
||||
await first.getByRole('button', { name: '重新关注' }).waitFor();
|
||||
await first.getByRole('button', { name: '重新关注' }).click();
|
||||
await first.getByRole('button', { name: '取消关注' }).waitFor();
|
||||
await first.getByRole('button', { name: '取消关注' }).click();
|
||||
await first.getByRole('button', { name: '重新关注' }).waitFor();
|
||||
await page.getByRole('button', { name: '刷新列表' }).click();
|
||||
await page.waitForFunction(
|
||||
(id) =>
|
||||
!document.querySelector(`.creator-list a[href="/creators?id=${id}"]`),
|
||||
target,
|
||||
);
|
||||
await json(`/api/creators/${target}/follow`, a.token, 'PUT');
|
||||
// 同一个列表舞台切换到粉丝,验证双向独立和移除确认。
|
||||
await page
|
||||
.getByRole('navigation', { name: '关系列表' })
|
||||
.getByRole('link', { name: '粉丝', exact: true })
|
||||
.click();
|
||||
await page.getByRole('heading', { name: /我的粉丝/ }).waitFor();
|
||||
await waitRows(page, 20);
|
||||
const fan = page.locator('.creator-list > li').first();
|
||||
const fanId = new URL(
|
||||
await fan.locator('a').getAttribute('href'),
|
||||
web,
|
||||
).searchParams.get('id');
|
||||
await fan.getByRole('button', { name: '取消关注' }).click();
|
||||
await fan.getByRole('button', { name: '回关' }).waitFor();
|
||||
await fan.getByRole('button', { name: '回关' }).click();
|
||||
await fan.getByRole('button', { name: '取消关注' }).waitFor();
|
||||
await fan.getByRole('button', { name: '移除粉丝' }).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await dialog.getByRole('button', { name: '取消', exact: true }).click();
|
||||
await fan.getByRole('button', { name: '移除粉丝' }).click();
|
||||
await dialog.getByRole('button', { name: '移除粉丝', exact: true }).click();
|
||||
await page.waitForFunction(
|
||||
(id) =>
|
||||
!document.querySelector(`.creator-list a[href="/creators?id=${id}"]`),
|
||||
fanId,
|
||||
);
|
||||
const relation = await json(`/api/creators/${fanId}/relationship`, a.token);
|
||||
assert.equal(relation.relationship.isFollowing, true);
|
||||
assert.equal(relation.relationship.isFollowedBy, false);
|
||||
console.log(
|
||||
'PASS desktop: navigation, author/game links, pagination/back/scroll, unfollow retention, follow-back and remove',
|
||||
);
|
||||
// 上一步可能移除了 B 的入边,重建只读列表验收所需的双方关系。
|
||||
await json(`/api/creators/${a.user.id}/follow`, b.token, 'PUT');
|
||||
await json(`/api/creators/${b.user.id}/follow`, a.token, 'PUT');
|
||||
// 他人两类列表只有主页链接,不读取访问者与列表用户的关系。
|
||||
for (const tab of ['following', 'followers']) {
|
||||
const requests = [];
|
||||
const record = (request) => {
|
||||
if (request.url().includes('/relationship'))
|
||||
requests.push(request.url());
|
||||
};
|
||||
page.on('request', record);
|
||||
await page.goto(`${web}/creators/connections?id=${b.user.id}&tab=${tab}`);
|
||||
await page.locator('.creator-list > li').first().waitFor();
|
||||
assert.equal(await page.locator('.creator-list button').count(), 0);
|
||||
assert.equal(requests.length, 0);
|
||||
page.off('request', record);
|
||||
await page.locator('.creator-list a').first().click();
|
||||
await page.locator('.creator-counts').waitFor();
|
||||
}
|
||||
await page.goto(`${web}/creators?id=${b.user.id}`);
|
||||
await page.locator('.creator-relation button').first().waitFor();
|
||||
const follow = page.locator('.creator-relation button').first();
|
||||
await page.waitForFunction(
|
||||
() => !document.querySelector('.creator-relation button')?.disabled,
|
||||
);
|
||||
const oldLabel = await follow.innerText();
|
||||
await follow.click();
|
||||
await page.waitForFunction(
|
||||
(label) =>
|
||||
document.querySelector('.creator-relation button')?.textContent !==
|
||||
label &&
|
||||
!document.querySelector('.creator-relation button')?.disabled,
|
||||
oldLabel,
|
||||
);
|
||||
await follow.click();
|
||||
console.log(
|
||||
'PASS public lists: both read-only, no relationship requests, all users link to creator pages',
|
||||
);
|
||||
await page.setViewportSize({ width: 375, height: 812 });
|
||||
await page.goto(web + '/creators');
|
||||
await page.locator('.creator-profile').waitFor();
|
||||
const welcome = page.getByRole('button', { name: '好', exact: true });
|
||||
if (await welcome.isVisible()) await welcome.click();
|
||||
assert.deepEqual(
|
||||
await page
|
||||
.getByRole('navigation', { name: '移动平台导航' })
|
||||
.getByRole('button')
|
||||
.allTextContents(),
|
||||
['游戏', '创作者主页', '我的'],
|
||||
);
|
||||
assert.ok(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= innerWidth,
|
||||
),
|
||||
);
|
||||
await page.screenshot({ path: '/tmp/creator-home-mobile.png' });
|
||||
await page.locator('.creator-counts a').last().click();
|
||||
await page.locator('.creator-list > li').first().waitFor();
|
||||
assert.ok(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= innerWidth,
|
||||
),
|
||||
);
|
||||
await page.screenshot({ path: '/tmp/creator-followers-mobile.png' });
|
||||
await page.locator('.creator-list a').first().focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await page.locator('.creator-counts').waitFor();
|
||||
const guest = await browser.newContext({
|
||||
viewport: { width: 375, height: 812 },
|
||||
});
|
||||
const guestPage = await guest.newPage();
|
||||
await guestPage.goto(`${web}/creators?id=${b.user.id}`);
|
||||
await guestPage.locator('.creator-profile').waitFor();
|
||||
const guestWelcome = guestPage.getByRole('button', {
|
||||
name: '好',
|
||||
exact: true,
|
||||
});
|
||||
if (await guestWelcome.isVisible()) await guestWelcome.click();
|
||||
for (const tab of ['following', 'followers']) {
|
||||
await guestPage.goto(
|
||||
`${web}/creators/connections?id=${b.user.id}&tab=${tab}`,
|
||||
);
|
||||
await guestPage.locator('.creator-list > li').first().waitFor();
|
||||
if (await guestWelcome.isVisible()) await guestWelcome.click();
|
||||
assert.equal(await guestPage.locator('.creator-list button').count(), 0);
|
||||
await guestPage
|
||||
.getByRole('button', { name: '返回', exact: true })
|
||||
.click();
|
||||
await guestPage.locator('.creator-profile').waitFor();
|
||||
assert.equal(new URL(guestPage.url()).searchParams.get('id'), b.user.id);
|
||||
}
|
||||
await guestPage.getByRole('button', { name: '关注', exact: true }).click();
|
||||
await guestPage.getByRole('dialog').waitFor();
|
||||
assert.equal(new URL(guestPage.url()).searchParams.get('id'), b.user.id);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log(
|
||||
'PASS mobile 375px: three navigation entries, no horizontal overflow, keyboard links, guest login without follow',
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
})().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
Reference in New Issue
Block a user