Files
knowledge-governance/scripts/test_pp_client.py
T
姚章浩 0dd4ad2737
build / build (push) Successful in 1m46s
fix(settings): 兼容 PP 目录接口的字符串总数
真实 PP 登录正常,目录接口将 Java Long 总数序列化为十进制字符串;新客户端的纯整数判断误报不兼容。
接受规范的非负十进制字符串,并保留对负数、布尔、小数和非规范字符串的拒绝。

验证:新增用例先复现 invalid_response,再完成 9 项 PP 回归;make verify 退出 0。
候选代码在测试站 API 和 worker 容器中均真实登录并读取目录成功,确认消费同一配置。
2026-11-17 20:01:44 +08:00

72 lines
5.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
import contextlib
import hashlib
import io
import os
from unittest.mock import patch
import pathlib
import tempfile
import threading
import unittest
from http.server import BaseHTTPRequestHandler, HTTPServer
import pp_client
class PPClientTests(unittest.TestCase):
def setUp(self):
self.calls=[];self.login_code=0;self.list_status=200;self.items=[];self.total=None
owner=self
class Handler(BaseHTTPRequestHandler):
def log_message(self,*args):pass
def do_POST(self):
owner.calls.append((self.command,self.path));self.rfile.read(int(self.headers.get('Content-Length','0')))
self.send_response(200);self.end_headers();self.wfile.write(json.dumps({'code':owner.login_code,'data':{'access_token':'example-token'} if owner.login_code==0 else {}}).encode())
def do_GET(self):
owner.calls.append((self.command,self.path))
if self.path=='/file.pdf':
content=b'%PDF-1.4\nExample PP download\n';self.send_response(200);self.send_header('Content-Length',str(len(content)));self.end_headers();self.wfile.write(content);return
self.send_response(owner.list_status);self.end_headers();self.wfile.write(json.dumps({'code':0,'data':{'list':owner.items,'total':len(owner.items) if owner.total is None else owner.total,'hasNextPage':False}}).encode())
self.server=HTTPServer(('127.0.0.1',0),Handler);self.thread=threading.Thread(target=self.server.serve_forever,daemon=True);self.thread.start()
self.client=pp_client.Client({'base_url':'http://127.0.0.1:'+str(self.server.server_port),'username':'example','password':'example-password'},allow_http=True)
def tearDown(self):self.server.shutdown();self.server.server_close();self.thread.join()
def test_check_really_logs_in_and_reads_empty_directory(self):
result=self.client.check();self.assertEqual(result['state'],'valid');self.assertEqual([x[0] for x in self.calls],['POST','GET']);self.assertTrue(self.calls[0][1].endswith('/admin/login/token'));self.assertTrue(self.calls[1][1].startswith('/potal/file/back/page?'))
def test_real_vendor_decimal_string_total_is_readable(self):
for count,items in [('0',[]),('1',[{'id':'example'}])]:
with self.subTest(count=count):
self.total=count;self.items=items
self.assertEqual(self.client.check()['state'],'valid')
inventory=self.client.inventory(self.client.login())
self.assertEqual(inventory['reported_total'],int(count));self.assertEqual(inventory['items'],items)
def test_malformed_vendor_counts_are_not_normalized(self):
for value in ['01',' 1','+1','1.0','-1','١','9'*20,True,1.5,-1]:
with self.subTest(value=value):
self.total=value;self.assertEqual(self.client.check()['state'],'invalid_response')
def test_explicit_rejection_never_reads_catalog(self):
self.login_code=401;result=self.client.check();self.assertEqual(result['state'],'auth_failed');self.assertEqual(len(self.calls),1)
def test_permission_failure_and_transient_remain_distinct(self):
self.list_status=403;self.assertEqual(self.client.check()['state'],'permission_denied');self.list_status=429;self.assertEqual(self.client.check()['state'],'unavailable')
def test_latest_saved_active_config_owns_each_new_task(self):
with tempfile.TemporaryDirectory() as root:
p=pathlib.Path(root)/'settings.json';p.write_text(json.dumps({'active':{'id':'one','base_url':'https://one.example.invalid','username':'example','password':'example-password'}}));p.chmod(0o600)
self.assertEqual(pp_client.load_config(str(p))['id'],'one');p.write_text(json.dumps({'active':{'id':'two','base_url':'https://two.example.invalid','username':'example','password':'example-password'}}));self.assertEqual(pp_client.load_config(str(p))['base_url'],'https://two.example.invalid')
def test_refresh_consumer_uses_the_shared_client(self):
import live_catalog_refresh
with patch('live_catalog_refresh.active_client',return_value=self.client),patch('live_catalog_refresh.build_pp_live_source',side_effect=lambda inventory,manifest:inventory),contextlib.redirect_stdout(io.StringIO()):
result=live_catalog_refresh.refresh_pp()
self.assertEqual(result['items'],[]);self.assertEqual([x[0] for x in self.calls],['POST','GET'])
def test_download_consumer_uses_current_portal_and_real_file_bytes(self):
import artifact_fetch
url=self.client.base+'/file.pdf'
self.items=[{'online':1,'potalGroup':{'groupName':'公开'},'fileUrl':url}]
with patch('pp_client.active_client',return_value=self.client),patch('artifact_fetch.pp_find_entry',return_value=None):
path,size,digest,local=artifact_fetch.pp_download({'locator_hash':hashlib.sha256(url.encode()).hexdigest(),'name':'example.pdf'},1024)
try:
self.assertFalse(local);self.assertGreater(size,0);self.assertEqual(hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest(),digest)
self.assertEqual([x[0] for x in self.calls],['POST','GET','GET'])
finally:os.unlink(path)
def test_missing_state_never_implicitly_reuses_legacy_credentials(self):
fake=json.dumps({'username':'example','password':'synthetic-'+'fixture'})
with patch.dict(os.environ,{'PP_LEGACY_CREDENTIALS_FILE':''}),patch('pathlib.Path.exists',return_value=False),patch('pathlib.Path.read_text',return_value=fake):
with self.assertRaises(pp_client.PPError):pp_client.load_config('/example-missing/settings.json')
if __name__=='__main__':unittest.main()