feat: 同步 LightCore 应用后台 CLI

This commit is contained in:
2026-11-20 04:02:32 +08:00
parent 3eb720cfbd
commit c19c26ec2c
12 changed files with 5477 additions and 45 deletions
+245
View File
@@ -0,0 +1,245 @@
import argparse
from contextlib import redirect_stdout
from hashlib import sha256
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import io
import json
from pathlib import Path
import re
from tempfile import TemporaryDirectory
from threading import Thread
import time
import unittest
from unittest.mock import Mock, patch
from lightcore_cli.application_commands import APPLICATIONS
from lightcore_cli.cli import main, parser
from lightcore_cli.shop_visual import render
from lightcore_cli.transport import ClientError
BACKEND = Path(__file__).resolve().parents[1] / "../../backend"
class ApplicationRouteTests(unittest.TestCase):
def test_registered_routes_and_offline_schemas(self):
cli = parser()
for app, (_, groups) in APPLICATIONS.items():
controllers = BACKEND / "application" / app / "interfaces/admin/controllers"
registered = set()
for file in controllers.glob("*.go"):
if file.stem.endswith("_test"):
continue
source = file.read_text(encoding="utf-8")
registered.update(re.findall(r'\.Handle\("POST",\s*"([^"]+)"', source))
base = re.search(r'\bbase\s*:=\s*"([^"]+)"', source)
if base:
registered.update(base[1] + suffix for suffix in re.findall(r'\.Handle\("POST",\s*base\s*\+\s*"([^"]+)"', source))
if file.name == "product.go" and app == "shop":
registered.update(re.findall(r'\{"(/mall/product/[^" ]+)", t\.', source))
commands = set()
for group, operations in groups.items():
for name, (path, _, _) in operations.items():
with self.subTest(app=app, group=group, command=name):
for flag in ("--schema", "--example"):
output = io.StringIO()
with redirect_stdout(output), self.assertRaises(SystemExit) as error:
cli.parse_args([app, *group.split(), name, flag])
self.assertEqual(error.exception.code, 0)
body = json.loads(output.getvalue())
if flag == "--schema":
self.assertEqual(body["type"], "object")
commands.add(path)
if app == "shop":
if controllers.is_dir():
self.assertEqual(commands - registered, set())
old_leaves = Path(__file__).with_name("shop_command_inventory.txt")
self.assertEqual(
{f"{group} {name}" for group, operations in groups.items() for name in operations},
set(old_leaves.read_text(encoding="utf-8").splitlines()),
)
else:
commands.add(cli.parse_args([app, "login"]).endpoint)
if app != "gysmart":
commands.update(cli.parse_args([app, action]).endpoint for action in ("refresh", "logout"))
if controllers.is_dir():
self.assertEqual(commands, registered)
class AdminHTTP(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def reply(self, data, *, code=200, message="", attachment=False):
raw = data if attachment else json.dumps({"code": code, "msg": message, "data": data}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream" if attachment else "application/json")
self.send_header("Content-Length", str(len(raw)))
self.send_header("X-Request-ID", "test-trace")
if attachment:
self.send_header("Content-Disposition", "attachment; filename=private.bin")
self.end_headers()
self.wfile.write(raw)
def do_POST(self):
raw = self.rfile.read(int(self.headers["Content-Length"]))
token = self.headers.get("Authorization")
multipart = self.headers.get_content_type() == "multipart/form-data"
data = raw if multipart else json.loads(raw)
self.server.requests.append((self.path, token, data))
app = self.path.split("/")[2]
if self.path.endswith(("/auth/login", "/auth/refresh")):
expires = int(time.time()) + 600
auth = {"accessToken": f"synthetic-{app}-token", "accessTokenExpiresAt": expires}
if app != "gysmart":
auth.update(refreshToken=f"synthetic-{app}-refresh", refreshTokenExpiresAt=expires)
return self.reply(auth)
if token != f"Bearer synthetic-{app}-token":
return self.reply(None, code=1001)
if self.path.endswith("/downloadAttachment"):
if data.get("workspaceKey") != "allowed":
return self.reply(None, code=403, message="scope denied")
return self.reply(b"private test data", attachment=True)
if self.path.endswith("/article/create") and data.get("title") == "duplicate":
return self.reply(None, code=400, message="同标题文章已存在")
if self.path.endswith("/workspaceAgent/saveFact"):
self.close_connection = True
return
if self.path.endswith("/getProviderStatus"):
return self.reply({"lastEvent": "delivered"})
self.reply({"received": True})
class ApplicationHTTPTests(unittest.TestCase):
def setUp(self):
directory = TemporaryDirectory()
self.addCleanup(directory.cleanup)
self.folder = Path(directory.name)
self.server = self.start_server()
def start_server(self):
server = ThreadingHTTPServer(("127.0.0.1", 0), AdminHTTP)
server.requests = []
server.address = f"http://127.0.0.1:{server.server_port}"
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
Thread(target=server.serve_forever, daemon=True).start()
return server
def call(self, app, *args, session=None):
with redirect_stdout(io.StringIO()) as stream, patch.dict("os.environ", {"LIGHTCORE_API_BASE_URL": ""}):
status = main([app, "--env-file", str(session or self.folder / f"{app}.env"), *args])
self.assertNotIn("synthetic-", stream.getvalue())
return status, json.loads(stream.getvalue())
def login(self, app, server=None, session=None):
with patch("builtins.input", return_value="tester"), patch("getpass.getpass", return_value="test-password"):
return self.call(app, "login", "--base-url", (server or self.server).address, session=session)
def test_app_and_target_sessions_are_isolated(self):
self.assertEqual(self.login("fangyus")[0], 0)
self.assertEqual(self.login("hengde")[0], 0)
self.assertEqual(self.login("gysmart")[0], 0)
self.assertEqual(self.call("hengde", "refresh")[0], 0)
self.assertEqual(self.server.requests[-1][2], {"refreshToken": "synthetic-hengde-refresh"})
before = len(self.server.requests)
self.assertEqual(self.call("hengde", "refresh", session=self.folder / "fangyus.env")[0], 1)
self.assertEqual(len(self.server.requests), before)
other = self.start_server()
self.assertEqual(self.login("fangyus", other)[0], 1)
self.assertEqual(other.requests, [])
self.assertEqual(self.login("fangyus", other, self.folder / "fangyus-other.env")[0], 0)
self.assertEqual(self.call("gysmart", "email", "get-provider-status", "--id", "email-1")[1]["body"]["data"],
{"lastEvent": "delivered"})
self.assertEqual(self.call("hengde", "logout")[0], 0)
self.assertEqual(self.call("hengde", "refresh")[0], 1)
def test_fangyus_preflight_and_business_error(self):
self.assertEqual(self.login("fangyus")[0], 0)
body = self.folder / "article.json"
body.write_text('{"category":"news","title":"duplicate","contentHtml":"<p>Example</p>"}', encoding="utf-8")
code, result = self.call("fangyus", "article", "create", "--body-file", str(body), "--dry-run")
self.assertEqual(code, 1)
self.assertEqual(result["traceId"], "test-trace")
self.assertEqual(result["body"]["msg"], "同标题文章已存在")
self.assertTrue(self.server.requests[-1][2]["dryRun"])
before = len(self.server.requests)
body.write_text('{"title":"first","title":"second"}', encoding="utf-8")
self.assertEqual(self.call("fangyus", "article", "create", "--body-file", str(body))[0], 1)
self.assertEqual(len(self.server.requests), before)
def test_shop_plan_apply_defaults_and_private_file(self):
self.assertEqual(self.login("shop")[0], 0)
self.assertEqual(self.server.requests[-1][2]["identifier"], "tester")
self.assertEqual(self.call("shop", "douyin-local-life", "validate")[0], 0)
self.assertEqual(self.server.requests[-1][2], {"profile": "official"})
body = self.folder / "request.json"
for action, fields in (
("product-plan", {"manifest": {"productId": 27, "expectedRevision": 4}}),
("product-apply", {"manifest": {"productId": 27, "expectedRevision": 4}, "planHash": "a" * 64,
"requestId": "0198d956-1111-4444-8888-111111111111"}),
):
body.write_text(json.dumps(fields), encoding="utf-8")
self.assertEqual(self.call("shop", "mall", action, "--body-file", str(body))[0], 0)
self.assertEqual(self.server.requests[-1][2], fields)
target = self.folder / "file.bin"
args = ("content", "attachment-download", "--attachment-key", "fixture", "--output", str(target))
self.assertEqual(self.call("shop", *args, "--workspace-key", "denied")[0], 1)
self.assertFalse(target.exists())
code, result = self.call("shop", *args, "--workspace-key", "allowed")
self.assertEqual(code, 0)
self.assertEqual(result["sha256"], sha256(b"private test data").hexdigest())
self.assertEqual(target.read_bytes(), b"private test data")
self.assertEqual(self.call("shop", *args, "--workspace-key", "allowed")[0], 1)
def test_shop_upload_and_unknown_result(self):
self.assertEqual(self.login("shop")[0], 0)
file = self.folder / "fixture.png"
file.write_bytes(b"fixture image")
body = self.folder / "request.json"
body.write_text('{"purpose":"mall/product/image","requestId":"upload-id"}', encoding="utf-8")
self.assertEqual(self.call("shop", "file", "upload", "--file", str(file), "--body-file", str(body))[0], 0)
self.assertIn(b"name=\"requestId\"\r\n\r\nupload-id", self.server.requests[-1][2])
self.assertIn(b"fixture image", self.server.requests[-1][2])
body.write_text('{"meta":{"requestId":"fact-write-id"}}', encoding="utf-8")
code, result = self.call("shop", "content", "fact-save", "--body-file", str(body))
self.assertEqual(code, 1)
self.assertEqual(result["requestId"], "fact-write-id")
class ShopRenderProtocolTests(unittest.TestCase):
def test_commit_requires_current_snapshot(self):
prepare = {"render": {"HTML": "<html/>"}, "metadata": {}, "snapshot": {"id": 5}}
for current in (False, True):
with self.subTest(current=current), TemporaryDirectory() as directory:
result = {"httpStatus": 200, "code": 200, "traceId": "render-test"}
client = Mock()
client.success.return_value = True
client.exchange.side_effect = [{**result, "json": {"data": prepare}}, {**result, "json": {"data": current}}]
child = Mock()
child.stdin = io.BytesIO()
child.stdout = io.BytesIO(b'{"rendered":true}\n')
child.returncode = 0
child.poll.return_value = None if not current else 0
child.communicate.return_value = (b'{"productId":5}', b"")
args = argparse.Namespace(output=Path(directory) / "bundle", endpoint="/mall/productAgent/getRenderInput")
with patch("lightcore_cli.shop_visual.local_binary", return_value="light"), patch(
"lightcore_cli.shop_visual.subprocess.Popen", return_value=Mock(**{
"__enter__": Mock(return_value=child), "__exit__": Mock(return_value=False)
})
):
if current:
self.assertEqual(render(client, args, {"id": 5})["body"], {"productId": 5})
child.communicate.assert_called_once_with(b'{"commit":true}\n', timeout=120)
else:
with self.assertRaisesRegex(ClientError, "快照复核未通过"):
render(client, args, {"id": 5})
child.communicate.assert_not_called()
self.assertTrue(child.stdin.closed)
self.assertEqual(client.exchange.call_args.args,
("/mall/productAgent/validateRenderInput", b'{"id":5}'))
self.assertFalse(args.output.exists())
if __name__ == "__main__":
unittest.main()