bpmax-cli 0.2.1-beta.29 → 0.2.1-beta.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bpmax-cli",
3
- "version": "0.2.1-beta.29",
3
+ "version": "0.2.1-beta.30",
4
4
  "description": "CLI for BPMAX environments with multi-profile config and local login callback flow",
5
5
  "type": "module",
6
6
  "bin": {
@@ -69,6 +69,13 @@ bpmax-cli project create --profile <profile> --flow-type <matrix_flow_type> --js
69
69
 
70
70
  5. Verification:
71
71
 
72
+ Submit 前先做分层 lint/readback:
73
+
74
+ ```bash
75
+ bpmax-cli matrix app inspect --flow-type <matrix_flow_type> --workspace <workspace> --profile <profile> --format json
76
+ bpmax-cli matrix consumer lint --flow-type <business_flow_type> --node <node_id> --profile <profile> --format json
77
+ ```
78
+
72
79
  - Matrix app is visible in the target workspace.
73
80
  - Matrix rule project exists online with real approver fields.
74
81
  - Business flow create/submit reaches the matrix-owned step.
@@ -79,7 +86,21 @@ bpmax-cli project create --profile <profile> --flow-type <matrix_flow_type> --js
79
86
  bpmax-cli matrix owner-resolve --profile <profile> --flow-type <business_flow_type> --node <node_id> --project-id <project_id> --format json
80
87
  ```
81
88
 
82
- The diagnostic only reports node-side `matrix_owner` config paths and project form context. It does not create matrix rule records and does not replace browser/runtime E2E verification.
89
+ `owner-resolve` 必须调用平台 `/project/predicted_path`,不再只做静态配置解析。它会返回指定节点的 `predicted_owners`,但仍不代替真实多用户页面验收。
90
+
91
+ 最终聚合 gate 必须一次对账矩阵应用、表单/列表/筛选模板、workspace 绑定、线上规则记录、审批人有效状态、消费节点和 owner resolver:
92
+
93
+ ```bash
94
+ bpmax-cli matrix verify \
95
+ --matrix-flow-type <matrix_flow_type> \
96
+ --consumer-flow-type <business_flow_type> \
97
+ --node <node_id> --project-id <project_id> \
98
+ --approver-field <owner_field> \
99
+ --workspace <workspace> \
100
+ --profile <profile> --format json
101
+ ```
102
+
103
+ 任一层缺失都不得宣称“审批矩阵已可用”。
83
104
 
84
105
  ## Stop Conditions
85
106
 
@@ -24,6 +24,7 @@ description: "用于在 BPMAX 中做全链路流程测试、场景回归、前
24
24
  - Chrome DevTools MCP 出现 `Network.enable timed out`、快照不可用或页面通道挂住时,允许切换到 AppleScript;AppleScript 只能做 DOM 读取、按钮点击、输入、截图和页面提交,不得改用接口直调替代页面动作。
25
25
  - H5 测试必须打开 `/m/#/...`,页面 viewport 设为 `412x844`;只调 viewport,不调浏览器外层窗口尺寸。
26
26
  - 多角色页面测试使用 [$bpmax-user-mock-operator](../bpmax-user-mock-operator/SKILL.md),只用于浏览器页面测试,不用于 API Key impersonation 或 CLI 业务命令身份切换;结束前必须 unmock 并验证恢复。
27
+ - 多角色用例的身份步骤必须使用 `bpmax-cli e2e identity mock|status|unmock`,并与当前 execution manifest/case step 绑定。不得再运行 Skill 内的旧 Python Cookie 脚本作为正式主路。
27
28
 
28
29
  ## 重复操作加速模式
29
30
  - E2E 加速分两层:`bpmax-cli e2e` 提供稳定、可复用、可审计的执行能力;本 skill 负责把这些能力编排成标准打法。
@@ -79,6 +79,37 @@ CLI 返回 `handoff: true` 时,回复用户前必须全部满足:
79
79
  - `--unsafe-direct-create` 只允许本地专家调试旧行为;OpenClaw/Agent/BBS 永远不要使用
80
80
  - 表单校验失败时修正字段 key/type/选项值,不要绕过校验重试
81
81
 
82
+ ## 环节关联项目表单预填 handoff
83
+
84
+ 当用户要为当前待办环节中展示的“关联项目表单”准备预填值时,只使用 typed 命令生成 handoff:
85
+
86
+ ```bash
87
+ bpmax-cli project handoff step-form \
88
+ --project-id <project_id> \
89
+ --step-id <step_id> \
90
+ --json '{"form":{"<field_key>":"<value>"}}' \
91
+ --format json
92
+ ```
93
+
94
+ 硬门禁:
95
+
96
+ - 该能力只适用于当前用户尚未处理、仍可编辑,且流程节点开启 `enable_relate_project_form` 的环节。
97
+ - 必须使用表单模板内真实 field key;CLI 会读取关联项目表单 schema 并拒绝不存在或不兼容的字段。
98
+ - 禁止手写 `/projectContinue` URL、`prefill_token`、`target` 或直接调用 `/project_staging/prefill`。
99
+ - 最终回复只逐字使用 CLI 输出的 `reply_markdown`;没有该字段时才使用完整 `url`,不得截断、重组或删除查询参数。
100
+ - CLI 返回 `browser_prefill_verified: false` 或 `prefill_verification_required: true` 时,必须打开真实环节页确认可见项目表单控件已经带值;token 可读不等于页面预填成功。
101
+ - 该命令只预填关联项目表单,不提交表单、不完成环节,也不得声称环节已处理。
102
+ - 检查 token 状态时必须显式使用 step capability:
103
+
104
+ ```bash
105
+ bpmax-cli project handoff status \
106
+ --prefill-token <token> \
107
+ --step-form \
108
+ --format json
109
+ ```
110
+
111
+ - 状态查询固定走 query 参数协议;不要把 token 放到 URL path 上。
112
+
82
113
  ## 查询与链接命令
83
114
 
84
115
  ```bash
@@ -90,6 +121,7 @@ bpmax-cli project my-step --key-of-flow-node 'flow802926525::1776572829122' --fo
90
121
  bpmax-cli project my-step --workspace store_mgr --flow-type flow802926525 --format json
91
122
  bpmax-cli project approval-context 1001 --step-id 2002 --format json
92
123
  bpmax-cli project handoff status --prefill-token <token> --format json
124
+ bpmax-cli project handoff status --prefill-token <token> --step-form --format json
93
125
  bpmax-cli project search --body @project-search-query.json --page 1 --page-size 20 --format json
94
126
  bpmax-cli es project-search --body @project-search-query.json --page 1 --page-size 20 --format json
95
127
  bpmax-cli step get 2002 --format json
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: bpmax-user
3
3
  version: 1.0.0
4
- description: Use when the user needs to confirm the current BPMAX identity or inspect the authenticated current-user payload through bpmax-cli.
4
+ description: Use when the user needs to confirm the current BPMAX identity, search organization users, resolve an exact person, or verify active user status through typed bpmax-cli commands.
5
5
  metadata:
6
6
  requires:
7
7
  bins: ["bpmax-cli"]
@@ -16,6 +16,9 @@ metadata:
16
16
 
17
17
  ```bash
18
18
  bpmax-cli user current --format json
19
+ bpmax-cli user search --query "<姓名或工号>" --active-only --profile <profile> --format json
20
+ bpmax-cli user resolve --name "<姓名>" --employee-no "<工号>" --profile <profile> --format json
21
+ bpmax-cli user readback --id <user_id> --profile <profile> --format json
19
22
  ```
20
23
 
21
24
  ## 何时使用
@@ -23,9 +26,13 @@ bpmax-cli user current --format json
23
26
  - 用户想确认当前登录账号
24
27
  - 要在执行其他 BPMAX 操作前验证身份
25
28
  - 要检查某个 profile 实际连到哪个环境、哪个用户
29
+ - WEWF 迁移、固定审批人或矩阵规则需要将姓名/工号精确绑定到 BPMAX 用户 ID
30
+ - 需要确认用户未删除且处于有效在职状态
26
31
 
27
32
  ## 规则
28
33
 
29
34
  - 默认优先 `--format json`
30
35
  - 若只是判断登录是否生效,`user current` 比原始 `api GET /user/current` 更优先
31
36
  - 若用户明确指定环境,显式加 `--profile <name>`
37
+ - 固定人绑定优先同时提供姓名和工号。`user resolve` 匹配多人、未匹配或用户失效时必须停止,不得凭姓名选第一个。
38
+ - typed 输出只保留 ID、姓名、工号、组织、状态和角色摘要,不应默认输出手机号或头像 URL。
@@ -8,7 +8,7 @@ description: "用于 BPMAX E2E 测试中的用户身份切换。只要用户提
8
8
  ## 使用范围
9
9
  - 本 skill 只用于“浏览器 E2E 测试中的用户身份切换”。
10
10
  - 目标是让同一浏览器会话在完整页面链路中切到发起人、审批人、查看人等角色,验证真实 UI 可见性、按钮、表单和流转。
11
- - 不用于普通 CLI API 调用身份切换,不用于 API Key impersonation,不新增 `bpmax-cli user mock` typed command。
11
+ - 不用于普通 CLI API 调用身份切换,不用于 API Key impersonation。只使用 `bpmax-cli e2e identity mock|unmock|status` 操作当前浏览器会话。
12
12
  - 不修改 BPMAX 平台权限、角色配置、本地 `think_*` 镜像或配置提交体。
13
13
 
14
14
  ## 何时使用
@@ -19,7 +19,7 @@ description: "用于 BPMAX E2E 测试中的用户身份切换。只要用户提
19
19
 
20
20
  ## 前置条件
21
21
  - 浏览器里已有可用 BPMAX 登录态。
22
- - 当前账号具备平台已有的用户模拟权限。
22
+ - 原始账号必须具备专用权限点 `user.mock`(超管兼容);普通 `organization.admin` 不再自动获得模拟身份权限。
23
23
  - 已确认 workspace、目标用户 `user_id`、目标测试角色。
24
24
  - 默认页面为 `.../w:<workspace>/userManagement`;如果测试页不是这个路由,可以传 `--href-path` 覆盖。
25
25
 
@@ -35,69 +35,41 @@ description: "用于 BPMAX E2E 测试中的用户身份切换。只要用户提
35
35
  - 某类角色切换后的页面权限验证方式
36
36
  - 不要写入 Cookie、Authorization、API Key、手机号、验证码、密码或完整接口响应。
37
37
 
38
- ## 核心接口
39
- - 进入模拟:`PUT /api/user/<user_id>`,body `{"mock": 1}`
40
- - 退出模拟:`PUT /api/user/<user_id>`,body `{"unmock": 1}`
41
- - query 需要带 `$workspace=<workspace>&$language=<language>`
42
- - 请求头复用当前浏览器登录态:
43
- - `Cookie`
44
- - `Origin`
45
- - `Referer`
46
- - `x-href`
47
- - `Content-Type: application/json`
38
+ ## 受控命令
48
39
 
49
- ## 操作命令
50
-
51
- ### 进入目标用户身份
40
+ 浏览器 Cookie 只能通过环境变量 `BPMAX_COOKIE_HEADER` 传入,不得出现在命令行、报告或证据文件中。正式 E2E 必须带本轮 execution manifest 和当前 case step:
52
41
 
53
42
  ```bash
54
- PYTHON_BIN=./venv/bin/python
55
- [[ -x "$PYTHON_BIN" ]] || PYTHON_BIN=./.venv/bin/python
56
- [[ -x "$PYTHON_BIN" ]] || PYTHON_BIN=python3
57
-
58
- "$PYTHON_BIN" .codex/skills/bpmax-user-mock-operator/scripts/switch_user_identity.py \
59
- --action mock \
43
+ bpmax-cli e2e identity mock \
60
44
  --user-id <target_user_id> \
61
- --workspace <workspace> \
62
- --base-url <bpmax_origin> \
63
- --cookie-header "$BPMAX_COOKIE_HEADER"
64
- ```
45
+ --execution-manifest <file> --case-id <case_id> --case-step-id <step_id> \
46
+ --evidence-dir <current_run_dir> --profile <profile> --format json
65
47
 
66
- ### 退出模拟身份
48
+ bpmax-cli e2e identity status \
49
+ --execution-manifest <file> --case-id <case_id> --case-step-id <step_id> \
50
+ --evidence-dir <current_run_dir> --profile <profile> --format json
67
51
 
68
- ```bash
69
- "$PYTHON_BIN" .codex/skills/bpmax-user-mock-operator/scripts/switch_user_identity.py \
70
- --action unmock \
71
- --user-id <target_user_id> \
72
- --workspace <workspace> \
73
- --base-url <bpmax_origin> \
74
- --cookie-header "$BPMAX_COOKIE_HEADER"
52
+ bpmax-cli e2e identity unmock \
53
+ --execution-manifest <file> --case-id <case_id> --case-step-id <step_id> \
54
+ --evidence-dir <current_run_dir> --profile <profile> --format json
75
55
  ```
76
56
 
77
- ## 参数说明
78
- - `--action`:只能是 `mock` 或 `unmock`。
79
- - `--user-id`:目标用户 id,必须是正整数。
80
- - `--workspace`:工作区 key;也可用 `BPMAX_WORKSPACE` 环境变量。
81
- - `--base-url`:BPMAX 页面 origin;也可用 `BPMAX_BASE_URL` 环境变量。
82
- - `--cookie-header`:当前浏览器页面有效 Cookie 串;也可用 `BPMAX_COOKIE_HEADER` 环境变量。
83
- - `--href-path`:覆盖默认 `/w:<workspace>/userManagement` 的 `x-href` / `Referer` 口径。
84
- - `--language`:默认 `zhCN`。
85
- - `--insecure`:仅用于证书异常的临时排障。
86
-
87
57
  ## 浏览器 E2E 工作流
88
58
  1. 记录原始管理账号、workspace、当前页面和目标测试角色。
89
- 2. 从当前浏览器页面提取 Cookie,设置 `BPMAX_COOKIE_HEADER`。
90
- 3. 用本 skill 执行 `mock`。
91
- 4. 刷新或打开待测页面,通过 `/api/user/current` 或页面头像/用户名/权限入口确认当前身份已经切到目标用户。
59
+ 2. 使用 `bpmax-cli user resolve` 精确解析目标用户,不得凭姓名猜 ID。
60
+ 3. 将当前浏览器会话 Cookie 仅放入 `BPMAX_COOKIE_HEADER`,执行当前用例步骤对应的 `e2e identity mock`。
61
+ 4. CLI 必须回读 `current_user.mock=true` 且 ID 与目标用户一致;然后刷新待测页面,再从可见用户名和权限入口确认身份。
92
62
  5. 在浏览器中执行该角色的真实动作:发起、填写、提交、审批、驳回、查看或权限验证。
93
63
  6. 记录截图、项目 ID、step ID、当前角色、目标用户 id 和结论。
94
- 7. 执行 `unmock`,刷新页面并确认已恢复原管理账号身份。
64
+ 7. 执行 `e2e identity unmock`;只有 `readback_confirmed=true` 且页面刷新后恢复原账号,才能结束多角色测试。
95
65
 
96
66
  ## 硬门禁
97
67
  - 没有确认当前浏览器身份前,不得声称该角色浏览器 E2E 已通过。
98
68
  - 没有执行 unmock 和恢复验证前,不得结束多角色测试。
99
69
  - 不得把 mock 后的 Cookie/API 响应用作普通 API Key 或 CLI 业务命令身份。
100
70
  - 不得把浏览器抓包中的 Cookie 或 Authorization 写入报告、memory、AGENTS.md 或 git。
71
+ - 正式用例缺少 execution manifest/case step 时必须在远程 mock 前硬阻断。`--diagnostic` 只能排障,不能记为 pass evidence。
72
+ - 每次 mock/unmock 由平台写入审计日志;目标用户必须与原始操作人同组织。
101
73
 
102
74
  ## 常见问题
103
75
  - 401/403:先确认 Cookie 是否过期,再确认原始管理账号是否具备模拟用户权限。
@@ -1,37 +0,0 @@
1
- #!/usr/bin/env python3
2
- from __future__ import annotations
3
-
4
- import argparse
5
- import json
6
-
7
- from user_mock_operator_common import build_client, default_href_path
8
-
9
-
10
- def build_parser() -> argparse.ArgumentParser:
11
- parser = argparse.ArgumentParser(
12
- description="Switch a BPMAX browser E2E session into or out of simulated identity mode via /api/user/:id."
13
- )
14
- parser.add_argument("--action", choices=("mock", "unmock"), required=True)
15
- parser.add_argument("--user-id", type=int, required=True)
16
- parser.add_argument("--workspace")
17
- parser.add_argument("--base-url")
18
- parser.add_argument("--language", default="zhCN")
19
- parser.add_argument("--cookie-header")
20
- parser.add_argument("--href-path")
21
- parser.add_argument("--timeout", type=float, default=30)
22
- parser.add_argument("--insecure", action="store_true")
23
- return parser
24
-
25
-
26
- def main() -> int:
27
- args = build_parser().parse_args()
28
- client = build_client(args)
29
- workspace = args.workspace or client.workspace
30
- href_path = args.href_path or default_href_path(workspace)
31
- payload = client.switch_user_identity(args.user_id, args.action, href_path)
32
- print(json.dumps(payload, ensure_ascii=False))
33
- return 0
34
-
35
-
36
- if __name__ == "__main__":
37
- raise SystemExit(main())
@@ -1,136 +0,0 @@
1
- #!/usr/bin/env python3
2
- from __future__ import annotations
3
-
4
- import json
5
- import os
6
- import ssl
7
- import sys
8
- import urllib.error
9
- import urllib.parse
10
- import urllib.request
11
- from dataclasses import dataclass
12
- from pathlib import Path
13
- from typing import Any, Optional
14
-
15
-
16
- SHARED_SKILL_ROOT = Path(__file__).resolve().parents[2] / "bpmax-builder-shared"
17
- if str(SHARED_SKILL_ROOT) not in sys.path:
18
- sys.path.insert(0, str(SHARED_SKILL_ROOT))
19
-
20
- from base_url import DEFAULT_BASE_URL, resolve_base_url
21
-
22
-
23
- DEFAULT_LANGUAGE = "zhCN"
24
-
25
-
26
- def resolve_cookie_header(value: Optional[str]) -> str:
27
- cookie = value or os.environ.get("BPMAX_COOKIE_HEADER", "")
28
- if not cookie:
29
- raise SystemExit("missing cookie header: pass --cookie-header or set BPMAX_COOKIE_HEADER")
30
- return cookie
31
-
32
-
33
- def resolve_workspace(value: Optional[str]) -> str:
34
- workspace = value or os.environ.get("BPMAX_WORKSPACE", "")
35
- if not workspace:
36
- raise SystemExit("missing workspace: pass --workspace or set BPMAX_WORKSPACE")
37
- return workspace
38
-
39
-
40
- def default_href_path(workspace: str) -> str:
41
- return f"/w:{workspace}/userManagement"
42
-
43
-
44
- def encode_x_href(href_path: str) -> str:
45
- return urllib.parse.quote(href_path, safe="")
46
-
47
-
48
- def normalize_href_path(href_path: Optional[str], workspace: str) -> str:
49
- candidate = (href_path or "").strip() or default_href_path(workspace)
50
- if candidate.startswith("http://") or candidate.startswith("https://"):
51
- parsed = urllib.parse.urlparse(candidate)
52
- candidate = parsed.path or default_href_path(workspace)
53
- if parsed.query:
54
- candidate = f"{candidate}?{parsed.query}"
55
- if not candidate.startswith("/"):
56
- raise SystemExit("href path must start with '/' or be an absolute BPMAX page URL")
57
- return candidate
58
-
59
-
60
- def build_action_body(action: str) -> dict:
61
- if action == "mock":
62
- return {"mock": 1}
63
- if action == "unmock":
64
- return {"unmock": 1}
65
- raise SystemExit(f"unsupported action: {action}")
66
-
67
-
68
- @dataclass
69
- class ApiClient:
70
- base_url: str
71
- workspace: str
72
- language: str
73
- cookie_header: str
74
- timeout: float
75
- insecure: bool = False
76
-
77
- def _build_url(self, path: str) -> str:
78
- joiner = "&" if "?" in path else "?"
79
- suffix = f"$workspace={urllib.parse.quote(self.workspace)}&$language={urllib.parse.quote(self.language)}"
80
- return self.base_url.rstrip("/") + path + joiner + suffix
81
-
82
- def _build_headers(self, href_path: str) -> dict[str, str]:
83
- normalized_href = normalize_href_path(href_path, self.workspace)
84
- return {
85
- "accept": "application/json, text/plain, */*",
86
- "accept-language": "zh-CN,zh;q=0.9",
87
- "content-type": "application/json",
88
- "cookie": self.cookie_header,
89
- "origin": self.base_url.rstrip("/"),
90
- "referer": f"{self.base_url.rstrip('/')}{normalized_href}",
91
- "x-href": encode_x_href(normalized_href),
92
- }
93
-
94
- def request(self, method: str, path: str, body: Optional[dict] = None, *, href_path: Optional[str] = None) -> dict:
95
- href = normalize_href_path(href_path, self.workspace)
96
- headers = self._build_headers(href)
97
- data = None if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
98
- request = urllib.request.Request(self._build_url(path), data=data, headers=headers, method=method.upper())
99
- context = ssl._create_unverified_context() if self.insecure else None
100
- try:
101
- with urllib.request.urlopen(request, timeout=self.timeout, context=context) as response:
102
- raw = response.read().decode("utf-8", "replace")
103
- except urllib.error.HTTPError as err:
104
- raw = err.read().decode("utf-8", "replace")
105
- raise SystemExit(f"HTTP {err.code} {path}: {raw}") from err
106
- except urllib.error.URLError as err:
107
- raise SystemExit(f"Request failed {path}: {err}") from err
108
-
109
- try:
110
- payload = json.loads(raw)
111
- except json.JSONDecodeError as err:
112
- raise SystemExit(f"Non-JSON response from {path}: {raw}") from err
113
- if isinstance(payload, dict) and payload.get("code") not in (None, 0):
114
- raise SystemExit(f"API error {path}: {payload}")
115
- return payload
116
-
117
- def switch_user_identity(self, user_id: int, action: str, href_path: Optional[str] = None) -> dict:
118
- if user_id <= 0:
119
- raise SystemExit("user id must be positive")
120
- return self.request(
121
- "PUT",
122
- f"/api/user/{user_id}",
123
- build_action_body(action),
124
- href_path=href_path,
125
- )
126
-
127
-
128
- def build_client(args: Any) -> ApiClient:
129
- return ApiClient(
130
- base_url=resolve_base_url(getattr(args, "base_url", None)),
131
- workspace=resolve_workspace(getattr(args, "workspace", None)),
132
- language=getattr(args, "language", DEFAULT_LANGUAGE),
133
- cookie_header=resolve_cookie_header(getattr(args, "cookie_header", None)),
134
- timeout=float(getattr(args, "timeout", 30)),
135
- insecure=bool(getattr(args, "insecure", False)),
136
- )
@@ -1,138 +0,0 @@
1
- import io
2
- import json
3
- import os
4
- import sys
5
- import unittest
6
- from contextlib import redirect_stdout
7
- from pathlib import Path
8
- from unittest import mock
9
-
10
-
11
- SCRIPT_DIR = Path(__file__).resolve().parents[1] / "scripts"
12
- if str(SCRIPT_DIR) not in sys.path:
13
- sys.path.insert(0, str(SCRIPT_DIR))
14
-
15
- import switch_user_identity as cli # noqa: E402
16
- from user_mock_operator_common import ( # noqa: E402
17
- DEFAULT_BASE_URL,
18
- ApiClient,
19
- build_action_body,
20
- build_client,
21
- default_href_path,
22
- encode_x_href,
23
- )
24
-
25
-
26
- class FakeResponse:
27
- def __init__(self, body: bytes, status: int = 200) -> None:
28
- self._body = body
29
- self.status = status
30
-
31
- def __enter__(self) -> "FakeResponse":
32
- return self
33
-
34
- def __exit__(self, exc_type, exc, tb) -> None:
35
- return None
36
-
37
- def read(self) -> bytes:
38
- return self._body
39
-
40
-
41
- class UserMockOperatorTests(unittest.TestCase):
42
- def test_default_base_url_is_empty_until_runtime_configured(self) -> None:
43
- self.assertEqual(DEFAULT_BASE_URL, "")
44
-
45
- def test_build_action_body_maps_mock_and_unmock(self) -> None:
46
- self.assertEqual(build_action_body("mock"), {"mock": 1})
47
- self.assertEqual(build_action_body("unmock"), {"unmock": 1})
48
-
49
- def test_default_href_path_and_encoding_follow_user_management_route(self) -> None:
50
- href = default_href_path("store_mgr")
51
- self.assertEqual(href, "/w:store_mgr/userManagement")
52
- self.assertEqual(encode_x_href(href), "%2Fw%3Astore_mgr%2FuserManagement")
53
-
54
- def test_build_client_uses_environment_origin_without_api_suffix(self) -> None:
55
- args = type(
56
- "Args",
57
- (),
58
- {
59
- "base_url": None,
60
- "workspace": "store_mgr",
61
- "language": "zhCN",
62
- "cookie_header": "token=demo",
63
- "timeout": 30,
64
- "insecure": False,
65
- },
66
- )()
67
- with mock.patch.dict(os.environ, {"BPMAX_BASE_URL": "https://bpmax.example.com/api/"}, clear=False):
68
- client = build_client(args)
69
- self.assertEqual(
70
- client._build_url("/api/user/995920025"),
71
- "https://bpmax.example.com/api/user/995920025?$workspace=store_mgr&$language=zhCN",
72
- )
73
-
74
- def test_client_builds_expected_headers_for_user_management_page(self) -> None:
75
- client = ApiClient(
76
- base_url="https://bpmax.example.com",
77
- workspace="store_mgr",
78
- language="zhCN",
79
- cookie_header="token=demo",
80
- timeout=30,
81
- )
82
- headers = client._build_headers(default_href_path("store_mgr"))
83
- self.assertEqual(headers["origin"], "https://bpmax.example.com")
84
- self.assertEqual(headers["referer"], "https://bpmax.example.com/w:store_mgr/userManagement")
85
- self.assertEqual(headers["x-href"], "%2Fw%3Astore_mgr%2FuserManagement")
86
- self.assertEqual(headers["cookie"], "token=demo")
87
-
88
- def test_switch_user_identity_sends_put_with_expected_body(self) -> None:
89
- client = ApiClient(
90
- base_url="https://bpmax.example.com",
91
- workspace="store_mgr",
92
- language="zhCN",
93
- cookie_header="token=demo",
94
- timeout=30,
95
- )
96
- captured = {}
97
-
98
- def fake_urlopen(req, timeout, context=None):
99
- captured["url"] = req.full_url
100
- captured["method"] = req.get_method()
101
- captured["data"] = req.data.decode("utf-8")
102
- captured["headers"] = {k.lower(): v for k, v in req.header_items()}
103
- return FakeResponse(b'{"code":0,"data":{"ok":true}}')
104
-
105
- with mock.patch.object(
106
- __import__("user_mock_operator_common").urllib.request,
107
- "urlopen",
108
- side_effect=fake_urlopen,
109
- ):
110
- payload = client.switch_user_identity(995920025, "mock", default_href_path("store_mgr"))
111
-
112
- self.assertTrue(payload["data"]["ok"])
113
- self.assertEqual(captured["method"], "PUT")
114
- self.assertEqual(json.loads(captured["data"]), {"mock": 1})
115
- self.assertEqual(
116
- captured["url"],
117
- "https://bpmax.example.com/api/user/995920025?$workspace=store_mgr&$language=zhCN",
118
- )
119
- self.assertEqual(captured["headers"]["x-href"], "%2Fw%3Astore_mgr%2FuserManagement")
120
-
121
- def test_cli_dispatches_selected_action_and_prints_json(self) -> None:
122
- client = mock.Mock()
123
- client.switch_user_identity.return_value = {"code": 0, "data": {"userId": 995920025, "mocked": False}}
124
- output = io.StringIO()
125
- with mock.patch.object(cli, "build_client", return_value=client), mock.patch.object(
126
- sys,
127
- "argv",
128
- ["switch_user_identity.py", "--action", "unmock", "--user-id", "995920025", "--workspace", "store_mgr"],
129
- ), redirect_stdout(output):
130
- result = cli.main()
131
-
132
- self.assertEqual(result, 0)
133
- client.switch_user_identity.assert_called_once_with(995920025, "unmock", "/w:store_mgr/userManagement")
134
- self.assertEqual(json.loads(output.getvalue()), {"code": 0, "data": {"userId": 995920025, "mocked": False}})
135
-
136
-
137
- if __name__ == "__main__":
138
- unittest.main()