Files
mica/tests/test_social.py

119 lines
7.0 KiB
Python

from hashlib import sha256
from io import BytesIO
import json
import os
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest import TestCase
from uuid import uuid4
from mica.gateway import GraphApp
from mica.social import NAMES
class SocialGraph(TestCase):
def setUp(self):
temp = TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.ids = [prefix + uuid4().hex[:12] for prefix in ("a", "b", "c", "d")]
grants = [f"{p}.{mode}" for p in NAMES for mode in ("read", "write")]
self.config = {"name": "one", "key": "one", "database": os.environ.get(
"MICA_SOCIAL_TEST_DB", str(Path(temp.name) / "social.db")),
"callers": [{"subject": i, "sha256": sha256(i.encode()).hexdigest(), "grants": grants}
for i in self.ids]}
self.app = None
self.addCleanup(lambda: self.app and self.app.close())
self.enable(NAMES)
for uid in self.ids:
self.action("user.create", actor=uid, handle="@"+uid, name=uid, avatar="", bio="", profile={})
def enable(self, plugins):
if self.app:
self.app.close()
self.app = GraphApp([{**self.config, "plugins": list(plugins)}])
def request(self, body, actor=None, expected=200):
raw = json.dumps(body).encode()
status = []
env = {"REQUEST_METHOD": "POST", "PATH_INFO": "/v1/graph", "CONTENT_TYPE": "application/json",
"CONTENT_LENGTH": str(len(raw)), "HTTP_X_MICA_SITE_KEY": "one", "wsgi.input": BytesIO(raw),
"HTTP_AUTHORIZATION": "Bearer "+(actor or self.ids[0])}
data = json.loads(b"".join(self.app(env, lambda line, headers: status.append(int(line[:3])))))
self.assertEqual(status, [expected], data)
return data.get("data", data.get("error"))
def action(self, action, actor=None, expected=200, **args):
data = self.request({"mutate": [{"action": action, "args": args}]}, actor, expected)
return data[0] if expected == 200 else data
def query(self, node, id, fields, actor=None, **edges):
return self.request({"query": {"node": node, "id": id, "fields": fields,
"expand": {k: {"fields": v} for k, v in edges.items()}}}, actor)
def test_conversation_graph_and_history(self):
a, b, c, d = self.ids
self.enable(["user", "chat"])
direct = self.action("chat.create", kind="direct", title="", participants=[b])
self.assertEqual(self.action("chat.create", actor=b, kind="direct", title="", participants=[a]), direct)
group = self.action("chat.create", kind="group", title="读书会", participants=[b, c])
self.enable(["user", "chat", "message"])
self.assertNotIn("message.send_rich", self.request({"schema": True})["actions"])
self.assertEqual({r["id"] for r in self.query("user", a, ["id"], chats=["id"])[0]["chats"]}, {direct, group})
self.assertEqual({r["id"] for r in self.query("chat", group, ["id"], members=["id"])[0]["members"]}, {a,b,c})
self.assertEqual(self.query("user", a, ["id"], actor=d, chats=["id"])[0]["chats"], [])
self.action("message.send", actor=d, expected=404, chat_id=group, text="私聊")
self.action("chat.add_member", actor=b, expected=403, chat_id=group, user_id=d)
self.action("chat.add_member", chat_id=group, user_id=d)
msg = self.action("message.send", actor=d, chat_id=group, text="你好")
self.action("chat.remove_member", chat_id=group, user_id=d)
self.assertEqual(self.query("message", msg, ["text"], actor=d), [])
history = self.query("chat", group, ["id"], messages=["kind"])[0]["messages"]
self.assertEqual([r["kind"] for r in history], ["chat.created", "member.added", "message.text", "member.removed"])
self.enable(NAMES)
mark = {"type":"ref","node":"user","id":b,"start":1,"end":2}
msg = self.action("message.send_rich", chat_id=group, text="🙂你", marks=[mark])
self.assertEqual(self.query("message", msg, ["marks"])[0]["marks"], [mark])
def test_publication_graph_and_shared_marks(self):
a,b,_,_ = self.ids
marks = [{"type":"ref","node":"user","id":b,"start":0,"end":1},{"type":"bold","start":0,"end":1}]
post = self.action("post.create_rich", text="你", images=[], marks=marks)
images = [f"https://img.example/{i}.png" for i in range(18)]
note = self.action("note.create_rich", text="你"+"文"*9999, images=images, marks=marks)
self.assertEqual(self.query("note", note, ["images","marks"]), [{"images":images,"marks":marks}])
profile = self.query("user", a, ["handle"], posts=["id"], notes=["id"])[0]
self.assertEqual(profile, {"handle":"@"+a, "posts":[{"id":post}], "notes":[{"id":note}]})
for kind, target in [("post",post),("note",note)]:
reply = self.action("comment.create", actor=b, target=kind, target_id=target, text="好")
self.assertEqual(self.query(kind, target, ["id"], comments=["id"])[0]["comments"], [{"id":reply}])
self.assertEqual(self.query("comment", reply, ["text"], **{kind:["id"]})[0][kind], [{"id":target}])
self.action("comment.create", expected=404, target="note", target_id=post, text="错")
self.action("note.create", expected=400, text="少图", images=[])
self.action("note.create", expected=400, text="多图", images=images+[images[0]])
self.action("post.create", expected=400, text="字"*281, images=[])
self.action("post.create", expected=400, text="图", images=images[:5])
self.action("note.create_rich", expected=404, text="?", images=images[:1], marks=[{**marks[0],"id":"missing"}])
# A caller with comment.read still needs read access to each kind of target.
self.config["callers"][1]["grants"].remove("note.read")
self.enable(NAMES)
visible = self.query("user", b, ["id"], actor=b, comments=["id"])[0]["comments"]
self.assertEqual(len(visible), 1)
self.assertNotEqual(visible[0]["id"], reply)
self.enable(["user","comment","post"])
site = self.request({"schema":True})
self.assertEqual(set(site["nodes"]["user"]["edges"]), {"posts","comments"})
self.assertNotIn("post.create_rich", site["actions"])
self.assertEqual(self.query("user", b, ["id"], comments=["text"])[0]["comments"], [{"text":"好"}])
self.enable(["user"])
self.assertEqual(self.request({"schema":True})["nodes"]["user"]["edges"], {})
def test_profile_and_handle(self):
a,b,_,_ = self.ids
fields = {"name":"甲","avatar":"https://img.example/a.jpg","bio":"介绍","profile":{"city":"上海"}}
self.action("user.update", **fields)
self.assertEqual(self.query("user",a,["handle",*fields]), [{"handle":"@"+a,**fields}])
self.action("user.update", expected=400, handle="@changed", **fields)
self.action("user.update", expected=400, id=b, **fields)
self.action("user.create", expected=409, handle="@another", **fields)
self.assertEqual(self.query("user",a,["handle"]), [{"handle":"@"+a}])