feat: 同步 LightCore 应用后台 CLI
This commit is contained in:
@@ -0,0 +1,241 @@
|
||||
content attachment-download
|
||||
content attachment-get
|
||||
content attachment-import
|
||||
content attachment-list
|
||||
content attachment-set-validity
|
||||
content attachment-update
|
||||
content attachment-upload
|
||||
content cms article-apply
|
||||
content cms article-archive
|
||||
content cms article-check
|
||||
content cms article-get
|
||||
content cms article-list
|
||||
content cms article-plan
|
||||
content cms article-publish
|
||||
content cms article-restore-apply
|
||||
content cms article-restore-plan
|
||||
content cms article-revision-get
|
||||
content cms article-revision-list
|
||||
content cms article-withdraw
|
||||
content cms attachment-copy
|
||||
content cms case-apply
|
||||
content cms case-archive
|
||||
content cms case-check
|
||||
content cms case-get
|
||||
content cms case-list
|
||||
content cms case-plan
|
||||
content cms case-publish
|
||||
content cms case-restore-apply
|
||||
content cms case-restore-plan
|
||||
content cms case-revision-get
|
||||
content cms case-revision-list
|
||||
content cms case-withdraw
|
||||
content cms category-create
|
||||
content cms category-delete
|
||||
content cms category-get
|
||||
content cms category-list
|
||||
content cms category-update
|
||||
content cms category-update-status
|
||||
content context-get
|
||||
content document-export
|
||||
content document-get
|
||||
content document-list
|
||||
content document-restore-apply
|
||||
content document-restore-plan
|
||||
content document-review
|
||||
content document-review-check
|
||||
content document-review-get
|
||||
content document-revision-get
|
||||
content document-revision-list
|
||||
content document-save
|
||||
content document-set-validity
|
||||
content fact-get
|
||||
content fact-list
|
||||
content fact-restore-apply
|
||||
content fact-restore-plan
|
||||
content fact-revision-get
|
||||
content fact-revision-list
|
||||
content fact-save
|
||||
content fact-set-validity
|
||||
content operation-get
|
||||
content operation-list
|
||||
content review-rule-get
|
||||
content review-rule-list
|
||||
content review-rule-restore-apply
|
||||
content review-rule-restore-plan
|
||||
content review-rule-revision-get
|
||||
content review-rule-revision-list
|
||||
content review-rule-save
|
||||
content review-rule-set-validity
|
||||
content run-finish
|
||||
content run-get
|
||||
content run-list
|
||||
content run-start
|
||||
content source-get
|
||||
content source-list
|
||||
content source-restore-apply
|
||||
content source-restore-plan
|
||||
content source-revision-get
|
||||
content source-revision-list
|
||||
content source-save
|
||||
content source-set-validity
|
||||
content website article-apply
|
||||
content website article-archive
|
||||
content website article-check
|
||||
content website article-get
|
||||
content website article-list
|
||||
content website article-plan
|
||||
content website article-publish
|
||||
content website article-withdraw
|
||||
content website attachment-copy
|
||||
content website category-create
|
||||
content website category-delete
|
||||
content website category-get
|
||||
content website category-list
|
||||
content website category-update
|
||||
content website category-update-status
|
||||
content website restore-apply
|
||||
content website restore-plan
|
||||
content website revision-get
|
||||
content website revision-list
|
||||
content workspace-create
|
||||
content workspace-get
|
||||
content workspace-list
|
||||
content workspace-restore-apply
|
||||
content workspace-restore-plan
|
||||
content workspace-revision-get
|
||||
content workspace-revision-list
|
||||
content workspace-set-validity
|
||||
content workspace-update
|
||||
crm artifact get
|
||||
crm artifact list
|
||||
crm catalog brand create
|
||||
crm catalog brand delete
|
||||
crm catalog brand delete-preview
|
||||
crm catalog brand get
|
||||
crm catalog brand list
|
||||
crm catalog brand update
|
||||
crm catalog brand update-status
|
||||
crm catalog category create
|
||||
crm catalog category delete
|
||||
crm catalog category delete-preview
|
||||
crm catalog category get
|
||||
crm catalog category list
|
||||
crm catalog category tree
|
||||
crm catalog category update
|
||||
crm catalog category update-status
|
||||
crm catalog operation get
|
||||
crm catalog operation list
|
||||
crm catalog product apply
|
||||
crm catalog product delete
|
||||
crm catalog product delete-preview
|
||||
crm catalog product get
|
||||
crm catalog product list
|
||||
crm catalog product plan
|
||||
crm catalog product update-status
|
||||
crm catalog quotation-category create
|
||||
crm catalog quotation-category delete
|
||||
crm catalog quotation-category delete-preview
|
||||
crm catalog quotation-category get
|
||||
crm catalog quotation-category list
|
||||
crm catalog quotation-category update
|
||||
crm catalog quotation-category update-status
|
||||
crm customer get
|
||||
crm customer list
|
||||
crm fund-ledger account get
|
||||
crm fund-ledger account list
|
||||
crm fund-ledger balance-check
|
||||
crm fund-ledger daily-summary
|
||||
crm fund-ledger overview
|
||||
crm fund-ledger record get
|
||||
crm fund-ledger record list
|
||||
crm project file download
|
||||
crm project file get
|
||||
crm project file list
|
||||
crm project get
|
||||
crm project list
|
||||
douyin-local-life validate
|
||||
file convert-pdf-to-images
|
||||
file download
|
||||
file get
|
||||
file image variant
|
||||
file import
|
||||
file list
|
||||
file operation get
|
||||
file operation list
|
||||
file purpose get
|
||||
file purpose list
|
||||
file rename
|
||||
file upload
|
||||
mall brand-create
|
||||
mall brand-delete
|
||||
mall brand-get
|
||||
mall brand-list
|
||||
mall brand-update
|
||||
mall brand-update-status
|
||||
mall category-create
|
||||
mall category-delete
|
||||
mall category-get
|
||||
mall category-list
|
||||
mall category-tree
|
||||
mall category-update
|
||||
mall category-update-status
|
||||
mall deal-apply
|
||||
mall deal-check
|
||||
mall deal-get
|
||||
mall deal-list
|
||||
mall deal-operation-get
|
||||
mall deal-operation-list
|
||||
mall deal-plan
|
||||
mall deal-publish-apply
|
||||
mall deal-publish-plan
|
||||
mall deal-render
|
||||
mall deal-status-apply
|
||||
mall deal-status-plan
|
||||
mall deal-version-get
|
||||
mall deal-version-list
|
||||
mall operation-get
|
||||
mall operation-list
|
||||
mall product-ai-apply
|
||||
mall product-ai-plan
|
||||
mall product-ai-version-diff
|
||||
mall product-ai-version-get
|
||||
mall product-ai-version-list
|
||||
mall product-apply
|
||||
mall product-audit
|
||||
mall product-check
|
||||
mall product-context-apply
|
||||
mall product-context-get
|
||||
mall product-context-plan
|
||||
mall product-context-revision-diff
|
||||
mall product-context-revision-get
|
||||
mall product-context-revision-list
|
||||
mall product-get
|
||||
mall product-inventory-apply
|
||||
mall product-inventory-get
|
||||
mall product-inventory-ledger-list
|
||||
mall product-inventory-plan
|
||||
mall product-list
|
||||
mall product-plan
|
||||
mall product-render
|
||||
mall product-restore-apply
|
||||
mall product-restore-plan
|
||||
mall product-revision-diff
|
||||
mall product-revision-get
|
||||
mall product-revision-list
|
||||
mall product-sort-apply
|
||||
mall product-sort-list
|
||||
mall product-sort-plan
|
||||
mall product-status-apply
|
||||
mall product-status-plan
|
||||
mall shipping-template-list
|
||||
mall supplier-create
|
||||
mall supplier-delete
|
||||
mall supplier-get
|
||||
mall supplier-list
|
||||
mall supplier-update
|
||||
showroom create
|
||||
showroom get
|
||||
showroom list
|
||||
showroom update
|
||||
showroom update-status
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user