_tmp_integration_test_runner.py
12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#!/usr/bin/env python3
"""Integration test: consecutive same-approver auto-pass. Password restore in finally."""
import json
import sys
import traceback
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone, timedelta
try:
import pymysql
except ImportError:
import subprocess
subprocess.check_call([sys.executable, "-m", "pip", "install", "pymysql", "-q"])
import pymysql
API = "http://127.0.0.1:2015"
MD5_A123456 = "dc483e80a7a0bd9ef71d8cf973673924"
DEFAULT_PWD_HASH = "a5f7932be6f422d774e54560c733dc2b"
FLOW_ID = "806449575979123973"
INITIATOR = "15828667080"
APPROVER = "13608016021"
NODE1 = "QbXlUG3"
NODE2 = "a9ZlUG3"
AUTO_OPINION = "系统自动通过:与上一连续审批节点实际审批人相同"
BACKUP_PATH = "/Users/mr.wang/代码库/绿纤/lvqianmeiye_ERP/ExportFiles/_tmp_pwd_backup_integration.json"
DB = dict(
host="rm-2vccze142rc9a8f58bo.mysql.cn-chengdu.rds.aliyuncs.com",
port=3306,
user="nettest",
password="nettest",
database="lqerp_dev",
charset="utf8mb4",
autocommit=True,
)
RESULT = {"steps": [], "errors": []}
def log(step, detail):
RESULT["steps"].append({"step": step, "detail": detail})
print(f"[{step}] {detail}")
def http(method, url, token=None, data=None, form=None):
headers = {}
if token:
headers["Authorization"] = token
body = None
if form is not None:
body = urllib.parse.urlencode(form).encode()
headers["Content-Type"] = "application/x-www-form-urlencoded"
elif data is not None:
body = json.dumps(data, ensure_ascii=False).encode("utf-8")
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=body, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=120) as resp:
raw = resp.read().decode()
return json.loads(raw) if raw else {}
except urllib.error.HTTPError as e:
raw = e.read().decode()
try:
return json.loads(raw)
except Exception:
return {"code": e.code, "msg": raw}
def login(account):
r = http("POST", f"{API}/api/oauth/Login", form={"account": account, "password": MD5_A123456})
if r.get("code") != 200 or not (r.get("data") or {}).get("token"):
raise RuntimeError(f"login failed {account}: {r.get('msg')}")
return r["data"]["token"]
def db_query(conn, sql, args=None):
with conn.cursor(pymysql.cursors.DictCursor) as cur:
cur.execute(sql, args or ())
return cur.fetchall()
def db_exec(conn, sql, args=None):
with conn.cursor() as cur:
cur.execute(sql, args or ())
return cur.rowcount
def backup_passwords(conn):
rows = db_query(
conn,
"SELECT F_Id, F_Account, F_Password, F_Secretkey FROM BASE_USER WHERE F_Account IN (%s, %s)",
(INITIATOR, APPROVER),
)
backup = {r["F_Account"]: {"F_Id": r["F_Id"], "F_Password": r["F_Password"], "F_Secretkey": r["F_Secretkey"]} for r in rows}
if set(backup) != {INITIATOR, APPROVER}:
raise RuntimeError("backup missing accounts")
with open(BACKUP_PATH, "w") as f:
json.dump({"saved_at": datetime.now().isoformat(), "users": backup}, f)
log("backup", f"saved 2 accounts to backup file (hashes not printed)")
def set_default_passwords(conn):
for acct in (INITIATOR, APPROVER):
n = db_exec(
conn,
"UPDATE BASE_USER SET F_Password=%s WHERE F_Account=%s AND F_Password<>%s",
(DEFAULT_PWD_HASH, acct, DEFAULT_PWD_HASH),
)
log("pwd_reset", f"{acct} rows_updated={n}")
def restore_passwords(conn):
with open(BACKUP_PATH) as f:
backup = json.load(f)["users"]
for acct, row in backup.items():
n = db_exec(
conn,
"UPDATE BASE_USER SET F_Password=%s, F_Secretkey=%s WHERE F_Account=%s",
(row["F_Password"], row["F_Secretkey"], acct),
)
log("pwd_restore", f"{acct} rows_updated={n}")
verify = db_query(
conn,
"SELECT F_Account, F_Password, F_Secretkey FROM BASE_USER WHERE F_Account IN (%s, %s)",
(INITIATOR, APPROVER),
)
ok = True
for r in verify:
b = backup[r["F_Account"]]
if r["F_Password"] != b["F_Password"] or r["F_Secretkey"] != b["F_Secretkey"]:
ok = False
log("pwd_restore_verify", "match_backup=" + str(ok))
return ok
def pick_leave_window():
# 2026-08-18 single day CST -> UTC storage like existing records
start = "2026-08-17T16:00:00.000Z"
end = "2026-08-18T15:59:59.000Z"
return start, end, "2026-08-18"
def run_test(conn):
# conflict check
conflicts = db_query(
conn,
"""
SELECT la.F_Id, la.F_FlowTitle, la.F_LeaveStartTime, ft.F_Status
FROM wform_leaveapply la
JOIN flow_task ft ON ft.F_ProcessId = la.F_Id
WHERE ft.F_CreatorUserId = %s AND la.F_LeaveStartTime >= '2026-08-10'
""",
(INITIATOR,),
)
log("conflict_check", f"future_leaves={len(conflicts)}")
token_i = login(INITIATOR)
log("login_initiator", "ok")
bill_r = http("GET", f"{API}/api/system/BillRule/BillNumber/WF_LeaveApplyNo", token=token_i)
if bill_r.get("code") != 200:
raise RuntimeError(f"BillNumber failed: {bill_r}")
bill_no = bill_r.get("data")
log("bill_no", bill_no)
start, end, local_day = pick_leave_window()
title = "自动化测试-连续同人审批-詹芳英事假"
payload = {
"status": 0,
"flowId": FLOW_ID,
"flowTitle": title,
"flowUrgent": 1,
"billNo": bill_no,
"leaveType": "事假",
"leaveReason": "自动化测试-连续同人审批",
"leaveStartTime": start,
"leaveEndTime": end,
"leaveDayCount": "1",
"leaveHour": "24",
"applyDate": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
"applyUser": f"詹芳英/{INITIATOR}",
"applyDept": "大项目一部",
"applyPost": "",
"fileJson": "",
}
sub = http("POST", f"{API}/api/workflow/Form/LeaveApply", token=token_i, data=payload)
if sub.get("code") != 200:
raise RuntimeError(f"submit failed: {sub}")
log("submit", sub.get("msg", "ok"))
# resolve task/leave id
rows = db_query(
conn,
"""
SELECT la.F_Id AS leave_id, la.F_BillNo, ft.F_Id AS task_id, ft.F_Status, ft.F_ThisStepId
FROM wform_leaveapply la
JOIN flow_task ft ON ft.F_ProcessId = la.F_Id
WHERE la.F_BillNo = %s
ORDER BY ft.F_CreatorTime DESC LIMIT 1
""",
(bill_no,),
)
if not rows:
raise RuntimeError("leave/task not found after submit")
leave_id = rows[0]["leave_id"]
task_id = rows[0]["task_id"]
log("ids", f"leave_id={leave_id} task_id={task_id} billNo={bill_no}")
ops = db_query(
conn,
"""
SELECT fto.F_Id, fto.F_NodeCode, fto.F_HandleId, fto.F_Completion, fto.F_State
FROM flow_taskoperator fto
WHERE fto.F_TaskId = %s AND fto.F_Completion = 0
ORDER BY fto.F_CreatorTime
""",
(task_id,),
)
log("pending_ops", str(ops))
node1_ops = [o for o in ops if o["F_NodeCode"] == NODE1]
if len(node1_ops) != 1 or node1_ops[0]["F_HandleId"] != APPROVER:
raise RuntimeError(f"node1 pending invalid: {node1_ops}")
op1 = node1_ops[0]["F_Id"]
log("node1_verify", f"operatorId={op1} handleId={APPROVER}")
token_a = login(APPROVER)
log("login_approver", "ok")
audit_body = {"handleOpinion": "自动化测试-人工审批通过", "formData": payload}
audit_r = http("POST", f"{API}/api/workflow/Engine/FlowBefore/Audit/{op1}", token=token_a, data=audit_body)
if audit_r.get("code") != 200:
raise RuntimeError(f"audit failed: {audit_r}")
log("audit", audit_r.get("msg", "ok"))
task_after = db_query(conn, "SELECT F_Status, F_ThisStepId FROM flow_task WHERE F_Id=%s", (task_id,))[0]
log("task_after", str(task_after))
records = db_query(
conn,
"""
SELECT F_Id, F_NodeCode, F_NodeName, F_HandleId, F_HandleStatus, F_HandleOpinion, F_HandleTime
FROM flow_taskoperatorrecord
WHERE F_TaskId = %s
ORDER BY F_HandleTime, F_Id
""",
(task_id,),
)
log("records_count", str(len(records)))
manual = [r for r in records if r["F_NodeCode"] == NODE1]
auto = [r for r in records if r["F_NodeCode"] == NODE2 and AUTO_OPINION in (r["F_HandleOpinion"] or "")]
pending2 = db_query(
conn,
"SELECT F_Id FROM flow_taskoperator WHERE F_TaskId=%s AND F_NodeCode=%s AND F_Completion=0",
(task_id, NODE2),
)
RESULT["evidence"] = {
"leave_id": leave_id,
"task_id": task_id,
"bill_no": bill_no,
"operator1": op1,
"task_status": task_after["F_Status"],
"manual_records": manual,
"auto_records": auto,
"node2_pending": pending2,
"all_records": records,
}
if not manual:
raise RuntimeError("missing manual record for node1")
if not auto:
raise RuntimeError("missing auto-pass record for node2")
if auto[0]["F_HandleId"] != APPROVER:
raise RuntimeError("auto record handleId mismatch")
if pending2:
raise RuntimeError(f"node2 pending remains: {pending2}")
if task_after["F_Status"] != 2:
raise RuntimeError(f"expected flow ended status=2, got {task_after['F_Status']}")
# order: manual before auto
t_manual = manual[0]["F_HandleTime"]
t_auto = auto[0]["F_HandleTime"]
if t_auto < t_manual:
raise RuntimeError("auto record before manual record")
# cleanup attendance if synced
att = db_query(
conn,
"""
SELECT F_Id, F_Status, F_Remark, F_AttendanceDate
FROM lq_attendance_record
WHERE F_UserId=%s AND F_AttendanceDate=%s
""",
(INITIATOR, local_day),
)
log("attendance_before_cleanup", str(att))
if att:
cancel = http(
"POST",
f"{API}/api/Extend/LqAttendanceRecord/CancelLeave",
token=token_i,
data={"id": att[0]["F_Id"], "operatorOpinion": "自动化测试-连续同人审批-销假清理", "workflowId": leave_id},
)
log("cancel_leave", str(cancel))
if cancel.get("code") != 200:
raise RuntimeError(f"CancelLeave failed: {cancel}")
att2 = db_query(
conn,
"SELECT F_Id, F_Status, F_Remark FROM lq_attendance_record WHERE F_Id=%s",
(att[0]["F_Id"],),
)
log("attendance_after_cleanup", str(att2))
pending_final = db_query(
conn,
"SELECT F_Id, F_NodeCode, F_HandleId FROM flow_taskoperator WHERE F_TaskId=%s AND F_Completion=0",
(task_id,),
)
log("pending_final", str(pending_final))
RESULT["passed"] = True
def main():
conn = pymysql.connect(**DB)
restored = False
try:
backup_passwords(conn)
set_default_passwords(conn)
# verify temp login works
login(INITIATOR)
login(APPROVER)
log("temp_login_verify", "both ok")
run_test(conn)
except Exception as e:
RESULT["passed"] = False
RESULT["errors"].append({"type": type(e).__name__, "message": str(e), "trace": traceback.format_exc()})
log("ERROR", str(e))
finally:
try:
ok = restore_passwords(conn)
restored = ok
# default pwd should fail after restore
r1 = http("POST", f"{API}/api/oauth/Login", form={"account": INITIATOR, "password": MD5_A123456})
r2 = http("POST", f"{API}/api/oauth/Login", form={"account": APPROVER, "password": MD5_A123456})
RESULT["post_restore_login"] = {
INITIATOR: r1.get("code"),
APPROVER: r2.get("code"),
}
log("post_restore_login", str(RESULT["post_restore_login"]))
except Exception as e2:
RESULT["errors"].append({"type": "restore_failed", "message": str(e2), "trace": traceback.format_exc()})
log("RESTORE_ERROR", str(e2))
conn.close()
out_path = "/Users/mr.wang/代码库/绿纤/lvqianmeiye_ERP/ExportFiles/_tmp_integration_test_result.json"
with open(out_path, "w") as f:
json.dump(RESULT, f, ensure_ascii=False, default=str, indent=2)
print("RESULT_JSON", out_path)
print("PASSED", RESULT.get("passed"), "RESTORED", restored)
return 0 if RESULT.get("passed") and restored else 1
if __name__ == "__main__":
sys.exit(main())