145 lines
5.8 KiB
Python
145 lines
5.8 KiB
Python
from concurrent.futures import ThreadPoolExecutor
|
|
import os
|
|
from pathlib import Path
|
|
import sqlite3
|
|
from tempfile import TemporaryDirectory
|
|
from threading import Barrier
|
|
from uuid import uuid4
|
|
from unittest import TestCase
|
|
from unittest.mock import Mock, patch
|
|
|
|
from sqlalchemy import Column, Integer, MetaData, String, Table, inspect, select, text
|
|
|
|
from sqlalchemy.orm import registry
|
|
|
|
from mica.core import Plugin, Registry, Runtime, Snippet
|
|
from mica.publishing import bundled_plugins
|
|
|
|
|
|
def counter_plugins(name, extra=()):
|
|
table = Table(name, MetaData(), Column("id", Integer, primary_key=True),
|
|
Column("label", String(50), nullable=False), *extra)
|
|
|
|
class Counter:
|
|
pass
|
|
|
|
registry().map_imperatively(Counter, table)
|
|
|
|
def write(call, label):
|
|
call.session.add(Counter(label=label))
|
|
|
|
def relay(call, label, fail=False):
|
|
call.call("counter.write", label=label)
|
|
if fail:
|
|
raise ValueError("rollback")
|
|
|
|
storage = Plugin("storage", (Snippet("counter", {"write": write}, (Counter,)),))
|
|
actions = Plugin("actions", (Snippet("relay", {"run": relay}),), requires=("counter",))
|
|
return storage, actions
|
|
|
|
|
|
class RegistryTest(TestCase):
|
|
def test_entry_point_selection_and_dependencies(self):
|
|
plugin, relay = counter_plugins("counter_rows")
|
|
entry = Mock()
|
|
entry.name = plugin.name
|
|
entry.load.return_value = plugin
|
|
with patch("mica.plugins.entry_points", return_value=[entry]):
|
|
self.assertFalse(Registry.load(enabled=[]).plugins)
|
|
entry.load.assert_not_called()
|
|
self.assertIn("relay.run", Registry.load([relay]).operations)
|
|
with self.assertRaisesRegex(ValueError, "unknown plugins"):
|
|
Registry.load(enabled=["absent"])
|
|
with self.assertRaisesRegex(ValueError, "requires missing"):
|
|
Registry([relay])
|
|
with self.assertRaisesRegex(ValueError, "duplicate plugin"):
|
|
Registry([plugin, plugin])
|
|
with self.assertRaisesRegex(ValueError, "duplicate snippet"):
|
|
Registry([plugin, Plugin("second", plugin.snippets)])
|
|
|
|
def test_existing_sqlite_content(self):
|
|
with TemporaryDirectory() as path:
|
|
database = Path(path) / "legacy.sqlite3"
|
|
db = sqlite3.connect(database)
|
|
db.executescript("""
|
|
CREATE TABLE content (id TEXT PRIMARY KEY, type TEXT NOT NULL,
|
|
fields TEXT NOT NULL, published_at TEXT);
|
|
CREATE INDEX public_content ON content (published_at DESC, id DESC)
|
|
WHERE published_at IS NOT NULL;
|
|
INSERT INTO content VALUES ('old', 'posts', '{"body":"旧数据"}', NULL);
|
|
""")
|
|
db.close()
|
|
runtime = Runtime(database, bundled_plugins())
|
|
try:
|
|
row = runtime.call("content.publish", identifier="old")
|
|
self.assertEqual(row["fields"], {"body": "旧数据"})
|
|
finally:
|
|
runtime.close()
|
|
|
|
|
|
class DatabaseContract(TestCase):
|
|
"""Optional server URLs must identify dedicated, disposable test databases."""
|
|
|
|
def exercise(self, url):
|
|
name = "counter_" + uuid4().hex[:12]
|
|
plugins = counter_plugins(name)
|
|
barrier = Barrier(2)
|
|
def start_worker():
|
|
barrier.wait(timeout=10)
|
|
Runtime(url, plugins).close()
|
|
|
|
with ThreadPoolExecutor(max_workers=2) as workers:
|
|
futures = [workers.submit(start_worker) for _ in range(2)]
|
|
for future in futures:
|
|
future.result(timeout=45)
|
|
runtime = Runtime(url, plugins)
|
|
try:
|
|
runtime.call("relay.run", label="一次写入")
|
|
with self.assertRaisesRegex(ValueError, "rollback"):
|
|
runtime.call("relay.run", label="rolled back", fail=True)
|
|
with runtime.engine.connect() as db:
|
|
self.assertEqual(db.scalars(select(plugins[0].snippets[0].tables[0].c.label)).all(),
|
|
["一次写入"])
|
|
self.assertIn("relay", str(db.scalar(text(
|
|
"SELECT description FROM mica_plugins WHERE name = 'actions'"))))
|
|
finally:
|
|
runtime.close()
|
|
|
|
updated = counter_plugins(name, [Column("note", String(80))])
|
|
for _ in range(2):
|
|
runtime = Runtime(url, updated)
|
|
try:
|
|
with runtime.engine.connect() as db:
|
|
self.assertEqual(db.execute(select(updated[0].snippets[0].tables[0].c.note)).all(),
|
|
[(None,)])
|
|
self.assertIn("note", [c["name"] for c in inspect(db).get_columns(name)])
|
|
finally:
|
|
runtime.close()
|
|
with self.assertRaisesRegex(ValueError, "explicit schema migration"):
|
|
Runtime(url, plugins)
|
|
runtime = Runtime(url, bundled_plugins())
|
|
try:
|
|
row = runtime.call("content.draft", kind="articles", fields={"title": "标题", "body": "文"})
|
|
self.assertIsNone(runtime.call("content.get", identifier=row["id"]))
|
|
published = runtime.call("content.publish", identifier=row["id"])
|
|
self.assertEqual(published, runtime.call("content.publish", identifier=row["id"]))
|
|
finally:
|
|
runtime.close()
|
|
Runtime(url, bundled_plugins()).close()
|
|
|
|
def test_sqlite(self):
|
|
with TemporaryDirectory() as directory:
|
|
self.exercise(Path(directory) / "mica.sqlite3")
|
|
|
|
def test_postgresql(self):
|
|
url = os.getenv("MICA_TEST_POSTGRESQL")
|
|
if not url:
|
|
self.skipTest("set MICA_TEST_POSTGRESQL to a disposable database")
|
|
self.exercise(url)
|
|
|
|
def test_mysql(self):
|
|
url = os.getenv("MICA_TEST_MYSQL")
|
|
if not url:
|
|
self.skipTest("set MICA_TEST_MYSQL to a disposable database")
|
|
self.exercise(url)
|