api_tests.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import json, urllib.request, urllib.error
  2. BASE = 'http://localhost:8980/js/a'
  3. def call(m, p, b=None, t=None):
  4. d = json.dumps(b).encode() if b is not None else None
  5. r = urllib.request.Request(BASE + p, data=d, method=m)
  6. r.add_header('Content-Type', 'application/json')
  7. if t:
  8. r.add_header('x-token', t)
  9. try:
  10. with urllib.request.urlopen(r, timeout=30) as x:
  11. return json.loads(x.read().decode())
  12. except urllib.error.HTTPError as e:
  13. return {'http': e.code, 'body': e.read().decode()[:300]}
  14. def login(u, p):
  15. return call('POST', '/auth/login', {'username': u, 'password': p, 'force': True})['data']['token']
  16. T = {
  17. 'admin': login('admin', 'admin123'),
  18. 'A': login('vsuserA', 'Vs1118pass'),
  19. 'B': login('vsuserB', 'Vs1118pass'),
  20. 'C': login('vsuserC', 'Vs1118pass'),
  21. }
  22. D1 = '2123022706158374913'
  23. D2 = '2123022706573611010'
  24. ids = {
  25. 'expert_pub': '2123022764635361281', 'expert_dept': '2123022766514409473',
  26. 'expert_self': '2123022768359903234',
  27. 'skill_pub': '2123022765163843585', 'skill_dept': '2123022767038697473',
  28. 'skill_self': '2123022768850636802',
  29. 'pack_pub': '2123022765524553730', 'pack_dept': '2123022767378436098',
  30. 'pack_self': '2123022769240707074',
  31. 'kb_pub': '2123022766036258817', 'kb_dept': '2123022767873363969',
  32. 'kb_self': '2123022769697886209',
  33. }
  34. results = []
  35. def check(name, cond, detail=''):
  36. results.append({'case': name, 'pass': bool(cond), 'detail': detail})
  37. print(('PASS' if cond else 'FAIL'), name, str(detail)[:300])
  38. def list_rows(path, t):
  39. r = call('GET', path, t=t)
  40. return r, (r.get('data') or {}).get('rows') or []
  41. # T1/T2 scope options
  42. r = call('GET', '/ai/agent/scope-options', t=T['admin'])
  43. check('T1 admin scope-options superAdmin=true + depts',
  44. r.get('code') == 200 and r['data']['superAdmin'] is True and len(r['data']['depts']) > 0,
  45. json.dumps(r, ensure_ascii=False)[:200])
  46. r = call('GET', '/ai/agent/scope-options', t=T['A'])
  47. check('T2 normal scope-options superAdmin=false + depts',
  48. r.get('code') == 200 and r['data']['superAdmin'] is False and len(r['data']['depts']) > 0,
  49. json.dumps(r, ensure_ascii=False)[:200])
  50. # T3 list visibility counts
  51. for kind, path in [('expert', '/ai/agent/list?pageSize=100'), ('skill', '/ai/skill/list?pageSize=100'),
  52. ('pack', '/ai/pack/list?pageSize=100'), ('kb', '/ai/kb/list?pageSize=100')]:
  53. for u, exp in [('A', 3), ('B', 2), ('C', 1), ('admin', 3)]:
  54. r, rows = list_rows(path, T[u])
  55. names = [x.get('agentName') or x.get('name') or x.get('packName') or x.get('kbName') for x in rows]
  56. check(f'T3 {kind} list {u} total={exp}', r.get('code') == 200 and len(rows) == exp, 'names=' + ','.join(names))
  57. # T4 canManage flags
  58. _, rows = list_rows('/ai/agent/list?pageSize=100', T['B'])
  59. by = {x['agentCode']: x for x in rows}
  60. check('T4 B cannot manage A dept expert', by['vs_expert_dept']['canManage'] is False, str(by['vs_expert_dept'].get('canManage')))
  61. check('T4 B cannot manage admin public expert', by['vs_expert_pub']['canManage'] is False, str(by['vs_expert_pub'].get('canManage')))
  62. _, rows = list_rows('/ai/agent/list?pageSize=100', T['A'])
  63. byA = {x['agentCode']: x for x in rows}
  64. check('T4 A can manage own dept/self expert',
  65. byA['vs_expert_dept']['canManage'] is True and byA['vs_expert_self']['canManage'] is True, '')
  66. check('T4 A cannot manage admin public expert', byA['vs_expert_pub']['canManage'] is False, '')
  67. # T5 detail visibility
  68. for key, path in [('expert_self', '/ai/agent/'), ('skill_self', '/ai/skill/'),
  69. ('pack_self', '/ai/pack/'), ('kb_self', '/ai/kb/')]:
  70. r = call('GET', path + ids[key], t=T['B'])
  71. check(f'T5 B cannot view A self {key}', r.get('code') == 500, json.dumps(r, ensure_ascii=False)[:160])
  72. for key, path in [('expert_dept', '/ai/agent/'), ('skill_dept', '/ai/skill/'),
  73. ('pack_dept', '/ai/pack/'), ('kb_dept', '/ai/kb/')]:
  74. r = call('GET', path + ids[key], t=T['B'])
  75. check(f'T5 B can view dept {key}', r.get('code') == 200 and r['data'] is not None, str(r.get('code')))
  76. for key, path in [('expert_dept', '/ai/agent/'), ('skill_dept', '/ai/skill/'),
  77. ('pack_dept', '/ai/pack/'), ('kb_dept', '/ai/kb/')]:
  78. r = call('GET', path + ids[key], t=T['C'])
  79. check(f'T5 C(D2) cannot view D1 dept {key}', r.get('code') == 500, json.dumps(r, ensure_ascii=False)[:160])
  80. for key, path in [('expert_pub', '/ai/agent/'), ('skill_pub', '/ai/skill/'),
  81. ('pack_pub', '/ai/pack/'), ('kb_pub', '/ai/kb/')]:
  82. r = call('GET', path + ids[key], t=T['C'])
  83. check(f'T5 C can view public {key}', r.get('code') == 200, str(r.get('code')))
  84. # T6 update authorization
  85. expert_body = lambda scope, oid=None: {
  86. 'id': ids['expert_dept'], 'agentName': 'VS部门专家', 'agentCode': 'vs_expert_dept',
  87. 'modelId': 1761400000000020400, 'visibleScope': scope, 'ownerDeptId': oid}
  88. r = call('PUT', '/ai/agent', expert_body('1', D1), T['B'])
  89. check('T6 B update A dept expert rejected',
  90. r.get('code') == 500 and '仅创建人或超级管理员' in (r.get('message') or ''),
  91. json.dumps(r, ensure_ascii=False)[:200])
  92. r = call('PUT', '/ai/agent', expert_body('1', D1), T['C'])
  93. check('T6 C update A dept expert rejected', r.get('code') == 500, json.dumps(r, ensure_ascii=False)[:200])
  94. r = call('PUT', '/ai/agent', expert_body('1', D1), T['admin'])
  95. check('T6 admin update A dept expert allowed', r.get('code') == 200, json.dumps(r, ensure_ascii=False)[:200])
  96. r = call('PUT', '/ai/agent', expert_body('2', None), T['A'])
  97. check('T6 A update own expert allowed', r.get('code') == 200, json.dumps(r, ensure_ascii=False)[:200])
  98. # T7 normal user cannot set 0 on own record; invalid rejected; blank inherits
  99. r = call('PUT', '/ai/agent', {'id': ids['expert_self'], 'agentName': 'VS自建专家',
  100. 'agentCode': 'vs_expert_self', 'modelId': 1761400000000020400,
  101. 'visibleScope': '0'}, T['A'])
  102. check('T7 A set own expert scope=0 rejected',
  103. r.get('code') == 500 and '普通用户不能设置全员/公开可见' in (r.get('message') or ''),
  104. json.dumps(r, ensure_ascii=False)[:200])
  105. r = call('PUT', '/ai/agent', {'id': ids['expert_self'], 'agentName': 'VS自建专家',
  106. 'agentCode': 'vs_expert_self', 'modelId': 1761400000000020400,
  107. 'visibleScope': '9'}, T['A'])
  108. check('T7 A set invalid scope=9 rejected', r.get('code') != 200, json.dumps(r, ensure_ascii=False)[:200])
  109. r = call('PUT', '/ai/agent', {'id': ids['expert_self'], 'agentName': 'VS自建专家',
  110. 'agentCode': 'vs_expert_self', 'modelId': 1761400000000020400}, T['A'])
  111. check('T7 A blank scope inherits 2', r.get('code') == 200, json.dumps(r, ensure_ascii=False)[:200])
  112. r = call('GET', '/ai/agent/' + ids['expert_self'], t=T['A'])
  113. check('T7 self expert scope still 2', r.get('code') == 200 and r['data']['visibleScope'] == '2',
  114. str((r.get('data') or {}).get('visibleScope')))
  115. # T8 workbench options filtered
  116. for path, label in [('/ai/agent/experts', 'visible experts'),
  117. ('/ai/agent/experts/candidates', 'candidates'),
  118. ('/ai/skill/visible-options', 'skill options'),
  119. ('/ai/pack/options', 'pack options'),
  120. ('/ai/kb/visible-options', 'kb options')]:
  121. for u, exp in [('A', 3), ('B', 2), ('C', 1), ('admin', 3)]:
  122. r = call('GET', path, t=T[u])
  123. n = len(r.get('data') or [])
  124. check(f'T8 {label} {u} count={exp}', r.get('code') == 200 and n == exp, f'n={n}')
  125. r = call('GET', '/ai/kb/options', t=T['C'])
  126. check('T8 kb full options 3 for C', r.get('code') == 200 and len(r.get('data') or []) == 3,
  127. f"n={len(r.get('data') or [])}")
  128. # T9 doc list filtering
  129. r = call('GET', f'/ai/kb/doc/list?kbId={ids["kb_dept"]}&pageSize=20', t=T['B'])
  130. check('T9 B doc list dept kb allowed(empty ok)',
  131. r.get('code') == 200 and len((r.get('data') or {}).get('rows') or []) == 0,
  132. json.dumps(r, ensure_ascii=False)[:200])
  133. r = call('GET', f'/ai/kb/doc/list?kbId={ids["kb_dept"]}&pageSize=20', t=T['C'])
  134. check('T9 C doc list dept kb returns empty',
  135. r.get('code') == 200 and len((r.get('data') or {}).get('rows') or []) == 0,
  136. json.dumps(r, ensure_ascii=False)[:200])
  137. r = call('GET', f'/ai/kb/doc/list?kbId={ids["kb_self"]}&pageSize=20', t=T['B'])
  138. check('T9 B doc list A self kb empty',
  139. r.get('code') == 200 and len((r.get('data') or {}).get('rows') or []) == 0,
  140. json.dumps(r, ensure_ascii=False)[:200])
  141. # T10 entry behavior
  142. r = call('GET', '/ai/agent/entry', t=T['admin'])
  143. entry = r.get('data') or {}
  144. check('T10 entry readable', r.get('code') == 200 and entry.get('id'), str(entry.get('id')))
  145. def entry_body(scope, oid):
  146. return {'id': entry['id'], 'agentName': entry['agentName'], 'agentCode': entry['agentCode'],
  147. 'modelId': entry['modelId'], 'visibleScope': scope, 'ownerDeptId': oid}
  148. r = call('PUT', '/ai/agent/entry', entry_body('1', D1), T['admin'])
  149. check('T10 admin save entry scope=1', r.get('code') == 200, json.dumps(r, ensure_ascii=False)[:200])
  150. r = call('GET', '/ai/agent/entry', t=T['B'])
  151. e2 = r.get('data') or {}
  152. check('T10 entry scope persisted=1',
  153. e2.get('visibleScope') == '1' and str(e2.get('ownerDeptId')) == D1,
  154. f"{e2.get('visibleScope')}/{e2.get('ownerDeptId')}")
  155. r = call('GET', '/ai/agent/options', t=T['B'])
  156. names = [x.get('agentCode') for x in (r.get('data') or [])]
  157. check('T10 entry still offered to B despite dept scope', 'entry_agent' in names, str(names))
  158. r = call('PUT', '/ai/agent/entry', entry_body('2', None), T['A'])
  159. check('T10 normal user A can save entry (no creator check)', r.get('code') == 200,
  160. json.dumps(r, ensure_ascii=False)[:200])
  161. r = call('PUT', '/ai/agent/entry', entry_body('0', None), T['admin'])
  162. check('T10 admin restore entry scope=0', r.get('code') == 200, json.dumps(r, ensure_ascii=False)[:200])
  163. # T11 admin dept record visible only to target dept
  164. r = call('POST', '/ai/agent', {'agentName': 'VS跨部门专家', 'agentCode': 'vs_expert_d2',
  165. 'description': 'admin d2', 'modelId': 1761400000000020400, 'status': '0',
  166. 'visibleScope': '1', 'ownerDeptId': D2, 'autoRoute': '1',
  167. 'memoryEnabled': '0', 'expertWriteEnabled': '1'}, T['admin'])
  168. check('T11 create admin record ownerDept=D2', r.get('code') == 200, json.dumps(r, ensure_ascii=False)[:200])
  169. _, rows = list_rows('/ai/agent/list?pageSize=100', T['A'])
  170. nA = len(rows)
  171. _, rows = list_rows('/ai/agent/list?pageSize=100', T['C'])
  172. codesC = [x['agentCode'] for x in rows]
  173. check('T11 D2 record hidden from A(D1)', nA == 3, f'nA={nA}')
  174. check('T11 D2 record visible to C(D2)', 'vs_expert_d2' in codesC, str(codesC))
  175. # T12 default scope for normal user when omitted
  176. r = call('POST', '/ai/skill', {'name': 'vs_skill_default', 'description': 'default scope test', 'status': '0'}, T['A'])
  177. check('T12 create skill without scope ok', r.get('code') == 200, json.dumps(r, ensure_ascii=False)[:200])
  178. _, rows = list_rows('/ai/skill/list?pageSize=100', T['A'])
  179. row = [x for x in rows if x['name'] == 'vs_skill_default']
  180. check('T12 default scope=2 for normal user', bool(row) and row[0]['visibleScope'] == '2',
  181. str(row[0]['visibleScope'] if row else None))
  182. if row:
  183. ids['skill_default'] = row[0]['id']
  184. # T13 delete authorization
  185. r = call('POST', '/ai/skill', {'name': 'vs_skill_del', 'description': 'delete test', 'status': '0',
  186. 'visibleScope': '1', 'ownerDeptId': D1}, T['A'])
  187. check('T13 create temp skill', r.get('code') == 200, '')
  188. _, rows = list_rows('/ai/skill/list?pageSize=100', T['A'])
  189. row = [x for x in rows if x['name'] == 'vs_skill_del']
  190. delid = row[0]['id'] if row else None
  191. r = call('DELETE', '/ai/skill/' + str(delid), t=T['B'])
  192. check('T13 B delete A skill rejected', r.get('code') == 500, json.dumps(r, ensure_ascii=False)[:200])
  193. r = call('DELETE', '/ai/skill/' + str(delid), t=T['C'])
  194. check('T13 C delete A skill rejected', r.get('code') == 500, json.dumps(r, ensure_ascii=False)[:200])
  195. r = call('DELETE', '/ai/skill/' + str(delid), t=T['A'])
  196. check('T13 A delete own skill allowed', r.get('code') == 200, json.dumps(r, ensure_ascii=False)[:200])
  197. if ids.get('skill_default'):
  198. r = call('DELETE', '/ai/skill/' + str(ids['skill_default']), t=T['A'])
  199. check('T13 cleanup default skill', r.get('code') == 200, '')
  200. _, rows = list_rows('/ai/agent/list?pageSize=100', T['admin'])
  201. row = [x for x in rows if x['agentCode'] == 'vs_expert_d2']
  202. if row:
  203. r = call('DELETE', '/ai/agent/' + row[0]['id'], t=T['admin'])
  204. check('T13 cleanup d2 expert', r.get('code') == 200, '')
  205. json.dump(results, open('api_results.json', 'w'), ensure_ascii=False, indent=2)
  206. print('TOTAL', len(results), 'PASS', sum(1 for x in results if x['pass']), 'FAIL', sum(1 for x in results if not x['pass']))