Runway 1.0.0
This commit is contained in:
commit
dcf819146b
1372 files changed
+188168
No files matched your search
@@ -0,0 +1,172 @@
|
||||
package mx.quest.runway.spi.testkit;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.SettingsChange;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
import mx.quest.runway.spi.service.ContentChanges;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
|
||||
/**
|
||||
* Delivers SPI change events to a plugin's {@link SiteEventListener}s in the kernel's order, so a plugin test can
|
||||
* exercise its listeners without a kernel — and doubles as the plugin's {@link ContentChanges}, bound to one plugin
|
||||
* id and the source keys it owns.
|
||||
*
|
||||
* <pre>{@code
|
||||
* EventDispatch events = new EventDispatch("blog", Set.of("blog"))
|
||||
* .listener(blogSource) // phase() SOURCE
|
||||
* .listener(blogIndexConsumer); // phase() CONSUMER
|
||||
* events.page("acme", "about", List.of(oldUrl), List.of()); // a deleted page
|
||||
* events.changed("acme", "blog", "hello"); // what the plugin's own code calls
|
||||
* }</pre>
|
||||
*
|
||||
* <h2>The order it applies (the kernel's)</h2>
|
||||
* Every {@code SOURCE}-phase listener, then every {@code CONSUMER}; within a phase, registration order. For one
|
||||
* listener: {@code onSiteLifecycle}, then {@code onSettingsChanged} (only when the settings belong to this dispatch's
|
||||
* plugin), then {@code onCatalogChanged}. {@code SOURCE} listeners receive {@code currentUrls} empty, as on the kernel.
|
||||
* A callback that throws a {@link RuntimeException} or {@link LinkageError} is recorded in {@link #failures()} and the
|
||||
* next one still runs. {@link #changed} is refused from inside a callback, for a source key the plugin does not own,
|
||||
* and for an unsafe site id — the kernel's rules.
|
||||
*
|
||||
* <p>Not thread-safe across concurrent dispatches (tests drive it from one thread).
|
||||
*/
|
||||
public final class EventDispatch implements ContentChanges {
|
||||
|
||||
private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]*");
|
||||
|
||||
private final String pluginId;
|
||||
private final Set<String> ownSourceKeys;
|
||||
private final List<SiteEventListener> listeners = new CopyOnWriteArrayList<>();
|
||||
private final List<Throwable> failures = new CopyOnWriteArrayList<>();
|
||||
private final List<CatalogChange> announced = new CopyOnWriteArrayList<>();
|
||||
private int callbackDepth;
|
||||
|
||||
/**
|
||||
* @param pluginId the plugin under test (its listeners receive its own settings changes)
|
||||
* @param ownSourceKeys the content source keys the plugin contributes ({@link #changed} accepts only these)
|
||||
*/
|
||||
public EventDispatch(String pluginId, Set<String> ownSourceKeys) {
|
||||
this.pluginId = Objects.requireNonNull(pluginId, "pluginId");
|
||||
this.ownSourceKeys = Set.copyOf(ownSourceKeys);
|
||||
}
|
||||
|
||||
/** Registers a listener (registration order is the order within its phase). */
|
||||
public EventDispatch listener(SiteEventListener listener) {
|
||||
listeners.add(Objects.requireNonNull(listener, "listener"));
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Every callback failure so far (the kernel logs and counts them; it never propagates them). */
|
||||
public List<Throwable> failures() {
|
||||
return List.copyOf(failures);
|
||||
}
|
||||
|
||||
/** Every change the plugin announced through {@link #changed}, in order. */
|
||||
public List<CatalogChange> announced() {
|
||||
return List.copyOf(announced);
|
||||
}
|
||||
|
||||
/** Delivers a site lifecycle event (and its {@code SITE} catalog change), local. */
|
||||
public void lifecycle(String siteId, SiteLifecycleEvent.Kind kind, boolean fromBackup) {
|
||||
SiteLifecycleEvent event = new SiteLifecycleEvent(safe(siteId), kind, fromBackup, true);
|
||||
deliver(event, null, new CatalogChange(siteId, CatalogChange.Cause.SITE, null, null, null, null, null, true));
|
||||
}
|
||||
|
||||
/** Delivers a per-site settings save of plugin {@code ofPlugin} (its {@code SETTINGS} catalog change), local. */
|
||||
public void settings(String siteId, String ofPlugin) {
|
||||
SettingsChange settings = new SettingsChange(safe(siteId), ofPlugin, true);
|
||||
deliver(null, settings, new CatalogChange(siteId, CatalogChange.Cause.SETTINGS, null, null, ofPlugin, null,
|
||||
null, true));
|
||||
}
|
||||
|
||||
/** Delivers a page change with the URLs the kernel would report (empty lists for none), local. */
|
||||
public void page(String siteId, String slug, List<LocalizedUrl> previousUrls, List<LocalizedUrl> currentUrls) {
|
||||
deliver(null, null, new CatalogChange(safe(siteId), CatalogChange.Cause.PAGE, "pages", slug, null,
|
||||
previousUrls, currentUrls, true));
|
||||
}
|
||||
|
||||
/** Delivers any catalog change as given (to test a replayed, non-local change, say). */
|
||||
public void catalog(CatalogChange change) {
|
||||
deliver(null, null, change);
|
||||
}
|
||||
|
||||
/**
|
||||
* The plugin's own announcement, as the kernel's {@code ContentChanges} handles it: delivered as a
|
||||
* {@code CONTENT} change attributed to this plugin, with no URLs (a test that needs URLs uses
|
||||
* {@link #catalog}).
|
||||
*/
|
||||
@Override
|
||||
public void changed(String siteId, String sourceKey, String id) {
|
||||
safe(siteId);
|
||||
if (callbackDepth > 0) {
|
||||
throw new IllegalStateException("ContentChanges.changed was called from inside a SiteEventListener "
|
||||
+ "callback");
|
||||
}
|
||||
if (sourceKey == null || !ownSourceKeys.contains(sourceKey)) {
|
||||
throw new IllegalArgumentException("content source '" + sourceKey + "' is not contributed by plugin '"
|
||||
+ pluginId + "'");
|
||||
}
|
||||
CatalogChange change = new CatalogChange(siteId, CatalogChange.Cause.CONTENT, sourceKey, id, pluginId, null,
|
||||
null, true);
|
||||
announced.add(change);
|
||||
deliver(null, null, change);
|
||||
}
|
||||
|
||||
private void deliver(SiteLifecycleEvent lifecycle, SettingsChange settings, CatalogChange change) {
|
||||
List<SiteEventListener> sources = new ArrayList<>();
|
||||
List<SiteEventListener> consumers = new ArrayList<>();
|
||||
for (SiteEventListener listener : listeners) {
|
||||
SiteEventListener.Phase phase;
|
||||
try {
|
||||
phase = listener.phase();
|
||||
} catch (RuntimeException | LinkageError e) {
|
||||
failures.add(e);
|
||||
phase = null;
|
||||
}
|
||||
(phase == SiteEventListener.Phase.SOURCE ? sources : consumers).add(listener);
|
||||
}
|
||||
CatalogChange sourceView = new CatalogChange(change.siteId(), change.cause(), change.sourceKey(),
|
||||
change.id(), change.pluginId(), change.previousUrls(), List.of(), change.local());
|
||||
for (SiteEventListener listener : sources) {
|
||||
invoke(listener, lifecycle, settings, sourceView);
|
||||
}
|
||||
for (SiteEventListener listener : consumers) {
|
||||
invoke(listener, lifecycle, settings, change);
|
||||
}
|
||||
}
|
||||
|
||||
private void invoke(SiteEventListener listener, SiteLifecycleEvent lifecycle, SettingsChange settings,
|
||||
CatalogChange change) {
|
||||
if (lifecycle != null) {
|
||||
guarded(() -> listener.onSiteLifecycle(lifecycle));
|
||||
}
|
||||
if (settings != null && pluginId.equals(settings.pluginId())) {
|
||||
guarded(() -> listener.onSettingsChanged(settings));
|
||||
}
|
||||
guarded(() -> listener.onCatalogChanged(change));
|
||||
}
|
||||
|
||||
private void guarded(Runnable callback) {
|
||||
callbackDepth++;
|
||||
try {
|
||||
callback.run();
|
||||
} catch (RuntimeException | LinkageError e) {
|
||||
failures.add(e);
|
||||
} finally {
|
||||
callbackDepth--;
|
||||
}
|
||||
}
|
||||
|
||||
private static String safe(String siteId) {
|
||||
if (siteId == null || !SAFE_ID.matcher(siteId).matches() || siteId.contains("..")) {
|
||||
throw new IllegalArgumentException("unsafe site id: " + siteId);
|
||||
}
|
||||
return siteId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package mx.quest.runway.spi.testkit;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.service.ContentCatalogView;
|
||||
|
||||
/**
|
||||
* A programmable {@link ContentCatalogView} for plugin tests: the test states what the site's listing holds, which
|
||||
* real pages own which paths, and what indexable text an entry has.
|
||||
*
|
||||
* <pre>{@code
|
||||
* FakeContentCatalog catalog = new FakeContentCatalog()
|
||||
* .site("acme")
|
||||
* .entry("acme", entry) // a CatalogEntry built by the test
|
||||
* .page("acme", "/about", Locale.ENGLISH, "about")
|
||||
* .text("acme", "blog:hello", "<p>Hello</p>");
|
||||
* }</pre>
|
||||
*
|
||||
* The input rules match the kernel's: an unsafe site id throws {@link IllegalArgumentException}; an unknown,
|
||||
* well-formed id answers empty, {@code ""} or {@code false}. {@link #servablePath} applies the kernel's path rule (a
|
||||
* root-relative path with no {@code ..}, {@code //}, {@code |} or control characters) and its reserved surface ({@code /__…}, {@code /actuator},
|
||||
* {@code /error}, {@code /app/…}, {@code /login}, {@code /logout}, {@code /forgot-password}, {@code /reset}) plus any
|
||||
* path the test {@linkplain #route declares as an endpoint route}. {@link #refresh} is counted. Thread-safe.
|
||||
*/
|
||||
public final class FakeContentCatalog implements ContentCatalogView {
|
||||
|
||||
private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]*");
|
||||
private static final List<String> RESERVED_EXACT = List.of("/actuator", "/error", "/login", "/logout",
|
||||
"/forgot-password", "/reset");
|
||||
private static final List<String> RESERVED_PREFIXES = List.of("/__", "/actuator", "/app/");
|
||||
|
||||
private final Set<String> sites = ConcurrentHashMap.newKeySet();
|
||||
private final Map<String, List<CatalogEntry>> entries = new ConcurrentHashMap<>();
|
||||
private final Map<String, String> pages = new ConcurrentHashMap<>();
|
||||
private final Map<String, String> texts = new ConcurrentHashMap<>();
|
||||
private final Set<String> routes = ConcurrentHashMap.newKeySet();
|
||||
private final List<String> refreshed = new CopyOnWriteArrayList<>();
|
||||
|
||||
/** Declares a site that exists (with no entries yet). */
|
||||
public FakeContentCatalog site(String siteId) {
|
||||
sites.add(safe(siteId));
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Adds an entry to the site's listing (declaring the site). */
|
||||
public FakeContentCatalog entry(String siteId, CatalogEntry entry) {
|
||||
site(siteId);
|
||||
entries.computeIfAbsent(siteId, k -> new CopyOnWriteArrayList<>()).add(Objects.requireNonNull(entry));
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Removes every entry of the site (it stays known). */
|
||||
public FakeContentCatalog clear(String siteId) {
|
||||
entries.remove(safe(siteId));
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Declares that the published real page {@code slug} serves {@code path} in {@code locale}. */
|
||||
public FakeContentCatalog page(String siteId, String path, Locale locale, String slug) {
|
||||
site(siteId);
|
||||
pages.put(siteId + "|" + locale.toLanguageTag() + "|" + path, slug);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Sets the indexable text of the entry {@code compositeId} ({@code <sourceKey>:<id>}). */
|
||||
public FakeContentCatalog text(String siteId, String compositeId, String text) {
|
||||
site(siteId);
|
||||
texts.put(siteId + "|" + compositeId, text);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Declares an exact endpoint route ({@code /sitemap.xml}), which {@link #servablePath} then refuses. */
|
||||
public FakeContentCatalog route(String path) {
|
||||
routes.add(path);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** The site ids {@link #refresh} was called with, in order. */
|
||||
public List<String> refreshed() {
|
||||
return List.copyOf(refreshed);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CatalogEntry> entries(String siteId) {
|
||||
safe(siteId);
|
||||
return List.copyOf(entries.getOrDefault(siteId, List.of()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
|
||||
safe(siteId);
|
||||
Objects.requireNonNull(entry, "entry");
|
||||
Objects.requireNonNull(locale, "locale");
|
||||
return texts.getOrDefault(siteId + "|" + entry.compositeId(), "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> pageAt(String siteId, String path, Locale locale) {
|
||||
safe(siteId);
|
||||
return Optional.ofNullable(pages.get(siteId + "|" + locale.toLanguageTag() + "|" + path));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean servablePath(String siteId, String path) {
|
||||
safe(siteId);
|
||||
if (!sites.contains(siteId) || !safePagePath(path) || routes.contains(path)) {
|
||||
return false;
|
||||
}
|
||||
if (RESERVED_EXACT.contains(path)) {
|
||||
return false;
|
||||
}
|
||||
for (String prefix : RESERVED_PREFIXES) {
|
||||
if (path.startsWith(prefix)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refresh(String siteId) {
|
||||
refreshed.add(safe(siteId));
|
||||
}
|
||||
|
||||
/** The kernel's page-path rule: root-relative, no {@code ..}, {@code //}, {@code |} or control characters. */
|
||||
private static boolean safePagePath(String path) {
|
||||
if (path == null || path.isEmpty() || path.charAt(0) != '/') {
|
||||
return false;
|
||||
}
|
||||
if (path.indexOf('|') >= 0 || path.contains("..") || path.contains("//")) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < path.length(); i++) {
|
||||
char c = path.charAt(i);
|
||||
if (c < 0x20 || c == 0x7f) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (String reserved : List.of("/actuator", "/static", "/error")) {
|
||||
if (path.equals(reserved) || path.startsWith(reserved + "/")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static String safe(String siteId) {
|
||||
if (siteId == null || !SAFE_ID.matcher(siteId).matches() || siteId.contains("..")) {
|
||||
throw new IllegalArgumentException("unsafe site id: " + siteId);
|
||||
}
|
||||
return siteId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package mx.quest.runway.spi.testkit;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.model.SettingsView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* An in-memory {@link PluginSettings} for plugin unit tests. Configure declared defaults once and per-site values
|
||||
* per test; {@link #site} answers defaults overlaid by the site's values, exactly like the kernel's (a stored blank
|
||||
* string does not mask a default), and {@link #secret} answers the clear value you set.
|
||||
*
|
||||
* <pre>{@code
|
||||
* FakePluginSettings settings = new FakePluginSettings()
|
||||
* .defaults(Map.of("enabled", true, "limit", 20))
|
||||
* .site("acme", Map.of("limit", 50))
|
||||
* .secret("acme", "smtpPassword", "s3cret");
|
||||
* MyWidget widget = new MyWidget(settings);
|
||||
* }</pre>
|
||||
*
|
||||
* Thread-safe. Like the kernel, an unsafe site id (one that could not be a folder name) throws
|
||||
* {@link IllegalArgumentException}.
|
||||
*/
|
||||
public final class FakePluginSettings implements PluginSettings {
|
||||
|
||||
/** The kernel's site-id rule: a letter or digit, then letters, digits, {@code . _ -}. */
|
||||
private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]*");
|
||||
|
||||
private volatile Map<String, Object> defaults = Map.of();
|
||||
private final Map<String, Map<String, Object>> sites = new ConcurrentHashMap<>();
|
||||
private final Map<String, String> secrets = new ConcurrentHashMap<>();
|
||||
|
||||
/** The declared {@code siteSettings:} defaults (replaces any set before). */
|
||||
public FakePluginSettings defaults(Map<String, ?> declaredDefaults) {
|
||||
this.defaults = Map.copyOf(declaredDefaults);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** The values stored for {@code siteId} (replaces any set before). */
|
||||
public FakePluginSettings site(String siteId, Map<String, ?> stored) {
|
||||
sites.put(requireSafe(siteId), new LinkedHashMap<>(stored));
|
||||
return this;
|
||||
}
|
||||
|
||||
/** A secret's clear value for {@code siteId}. */
|
||||
public FakePluginSettings secret(String siteId, String key, String clearValue) {
|
||||
secrets.put(requireSafe(siteId) + "|" + key, clearValue);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SettingsView site(String siteId) {
|
||||
Map<String, Object> values = new LinkedHashMap<>(defaults);
|
||||
sites.getOrDefault(requireSafe(siteId), Map.of()).forEach((key, value) -> {
|
||||
boolean blankOverDefault = value instanceof String text && text.isBlank() && defaults.containsKey(key);
|
||||
if (value != null && !blankOverDefault) {
|
||||
values.put(key, value);
|
||||
}
|
||||
});
|
||||
return new SettingsView(values);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> secret(String siteId, String key) {
|
||||
String value = secrets.get(requireSafe(siteId) + "|" + key);
|
||||
return value == null || value.isBlank() ? Optional.empty() : Optional.of(value);
|
||||
}
|
||||
|
||||
private static String requireSafe(String siteId) {
|
||||
if (siteId == null || siteId.equals(".") || siteId.equals("..") || !SAFE_ID.matcher(siteId).matches()) {
|
||||
throw new IllegalArgumentException("unsafe site id: " + siteId);
|
||||
}
|
||||
return siteId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package mx.quest.runway.spi.testkit;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.InstallResult;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.model.StarterPage;
|
||||
import mx.quest.runway.spi.service.AccessCheck;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.RequestContext;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
|
||||
/**
|
||||
* One configurable fake for the SPI 0.5.0 kernel singletons a plugin may inject — {@link Sites},
|
||||
* {@link RequestContext}, {@link AccessCheck}, {@link Messages} and {@link SitePages} — so a plugin test sets up "the
|
||||
* kernel" in a few lines and hands this object to whichever constructor parameters need it.
|
||||
*
|
||||
* <pre>{@code
|
||||
* FakeSiteServices kernel = new FakeSiteServices()
|
||||
* .site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test"))
|
||||
* .current("acme")
|
||||
* .grant("contact|settings")
|
||||
* .message("acme", "contact.sent", "Thanks!");
|
||||
* kernel.nextInstall(InstallResult.Outcome.PENDING_REVIEW);
|
||||
* }</pre>
|
||||
*
|
||||
* The input rules match the kernel's: an unsafe site id or slug throws {@link IllegalArgumentException};
|
||||
* {@code may} is fail-closed (only granted keys answer {@code true}); a missing message answers its fallback, or the
|
||||
* code; {@code install} never overwrites a page it has already installed. Thread-safe.
|
||||
*/
|
||||
public final class FakeSiteServices implements Sites, RequestContext, AccessCheck, Messages, SitePages {
|
||||
|
||||
private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]*");
|
||||
|
||||
private final Map<String, SiteView> sites = new ConcurrentHashMap<>();
|
||||
private volatile String current;
|
||||
private final Set<String> granted = ConcurrentHashMap.newKeySet();
|
||||
private final Map<String, String> messages = new ConcurrentHashMap<>();
|
||||
private final Map<String, String> pages = new ConcurrentHashMap<>();
|
||||
private final List<StarterPage> installs = new CopyOnWriteArrayList<>();
|
||||
private volatile InstallResult.Outcome nextOutcome = InstallResult.Outcome.PUBLISHED;
|
||||
private volatile List<Finding> nextBlocking = List.of();
|
||||
|
||||
/** Adds a site {@link #find} knows. */
|
||||
public FakeSiteServices site(SiteView site) {
|
||||
sites.put(Objects.requireNonNull(site, "site").id(), site);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Binds the "current request" to a site added with {@link #site} ({@code null}: off a request / app realm). */
|
||||
public FakeSiteServices current(String siteId) {
|
||||
this.current = siteId;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Grants a permission key to the "current principal". */
|
||||
public FakeSiteServices grant(String permissionKey) {
|
||||
granted.add(permissionKey);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** A message for {@code site(siteId, …)}; {@code siteId} {@code null} defines a console message. */
|
||||
public FakeSiteServices message(String siteId, String code, String text) {
|
||||
messages.put((siteId == null ? "" : siteId) + "|" + code, text);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** An existing page (any state) at {@code path}, as {@link #pathOf} reports it. */
|
||||
public FakeSiteServices page(String siteId, String slug, String path) {
|
||||
pages.put(requireSafe(siteId) + "|" + requireSafe(slug), path);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** What the next {@link #install} of a new page answers (default {@code PUBLISHED}). */
|
||||
public FakeSiteServices nextInstall(InstallResult.Outcome outcome, Finding... blocking) {
|
||||
this.nextOutcome = Objects.requireNonNull(outcome, "outcome");
|
||||
this.nextBlocking = List.of(blocking);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Every starter page {@link #install} was asked to install, in order. */
|
||||
public List<StarterPage> installs() {
|
||||
return List.copyOf(installs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<SiteView> find(String siteId) {
|
||||
return Optional.ofNullable(sites.get(requireSafe(siteId)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<SiteView> site() {
|
||||
String id = current;
|
||||
return id == null ? Optional.empty() : Optional.ofNullable(sites.get(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean may(String permissionKey) {
|
||||
return permissionKey != null && granted.contains(permissionKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String site(String siteId, Locale locale, String code, String fallback, Object... args) {
|
||||
requireSafe(siteId);
|
||||
return format(messages.get(siteId + "|" + code), code, fallback, locale, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String console(String code, String fallback, Object... args) {
|
||||
return format(messages.get("|" + code), code, fallback, Locale.ENGLISH, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> pathOf(String siteId, String slug) {
|
||||
return Optional.ofNullable(pages.get(requireSafe(siteId) + "|" + requireSafe(slug)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public InstallResult install(String siteId, StarterPage page) {
|
||||
Objects.requireNonNull(page, "page");
|
||||
installs.add(page);
|
||||
Optional<String> existing = pathOf(siteId, page.slug());
|
||||
if (existing.isPresent()) {
|
||||
return new InstallResult(InstallResult.Outcome.ALREADY_EXISTS, existing.get(), List.of());
|
||||
}
|
||||
if (!page.path().startsWith("/") || page.path().startsWith("/__")) {
|
||||
throw new IllegalArgumentException("unsafe or reserved page path: " + page.path());
|
||||
}
|
||||
pages.put(siteId + "|" + page.slug(), page.path());
|
||||
InstallResult.Outcome outcome = nextOutcome;
|
||||
return new InstallResult(outcome, page.path(),
|
||||
outcome == InstallResult.Outcome.DRAFT_BLOCKED ? new ArrayList<>(nextBlocking) : List.of());
|
||||
}
|
||||
|
||||
private static String format(String found, String code, String fallback, Locale locale, Object[] args) {
|
||||
String text = found != null ? found : fallback != null ? fallback : code;
|
||||
return (args == null || args.length == 0) ? text : new MessageFormat(text, locale).format(args);
|
||||
}
|
||||
|
||||
private static String requireSafe(String id) {
|
||||
if (id == null || id.equals(".") || id.equals("..") || !SAFE_ID.matcher(id).matches()) {
|
||||
throw new IllegalArgumentException("unsafe identifier: " + id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package mx.quest.runway.spi.testkit;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.SimpleFileVisitor;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.model.FileEntry;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
|
||||
/**
|
||||
* A {@link PluginSiteFiles} over a temporary folder, for plugin unit tests, with the <b>kernel's confinement
|
||||
* rules</b>: the same lexical path rules, the same real-path check against symbolic links (inside the subtree and
|
||||
* for the subtree itself), a link at the leaf reading as absent, {@code deleteTree} never following links, the write
|
||||
* cap, and the 10,000-entry listing cap. A plugin whose tests pass against it behaves the same on the kernel.
|
||||
*
|
||||
* <pre>{@code
|
||||
* @TempDir Path sites;
|
||||
* PluginSiteFiles files = new TempDirSiteFiles(sites, "contact"); // sites/<siteId>/plugins/contact/...
|
||||
* Files.createDirectories(sites.resolve("acme")); // the site must exist to write, as on the kernel
|
||||
* }</pre>
|
||||
*
|
||||
* The layout matches the kernel's: {@code <sitesRoot>/<siteId>/plugins/<pluginId>/}. Thread-safe.
|
||||
*/
|
||||
public final class TempDirSiteFiles implements PluginSiteFiles {
|
||||
|
||||
private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]*");
|
||||
/** The kernel's listing cap. */
|
||||
public static final int MAX_LIST_ENTRIES = 10_000;
|
||||
/** The kernel's default write cap. */
|
||||
public static final long DEFAULT_MAX_WRITE_BYTES = 16L * 1024 * 1024;
|
||||
|
||||
private final Path sitesRoot;
|
||||
private final String pluginId;
|
||||
private final long maxBytes;
|
||||
|
||||
/** With the kernel's default 16 MiB cap. */
|
||||
public TempDirSiteFiles(Path sitesRoot, String pluginId) {
|
||||
this(sitesRoot, pluginId, DEFAULT_MAX_WRITE_BYTES);
|
||||
}
|
||||
|
||||
public TempDirSiteFiles(Path sitesRoot, String pluginId, long maxBytes) {
|
||||
this.sitesRoot = Objects.requireNonNull(sitesRoot, "sitesRoot").toAbsolutePath().normalize();
|
||||
this.pluginId = requireSafe(pluginId, "plugin id");
|
||||
this.maxBytes = Math.min(maxBytes > 0 ? maxBytes : DEFAULT_MAX_WRITE_BYTES, Integer.MAX_VALUE - 16);
|
||||
}
|
||||
|
||||
/** The subtree root for {@code siteId}: where this fake reads and writes. */
|
||||
public Path root(String siteId) {
|
||||
return sitesRoot.resolve(requireSafe(siteId, "site id")).resolve("plugins").resolve(pluginId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> readText(String siteId, String relPath) throws IOException {
|
||||
Path file = resolve(siteId, relPath, false);
|
||||
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (Files.size(file) > maxBytes) {
|
||||
throw new IOException("'" + relPath + "' is larger than the " + maxBytes + "-byte limit");
|
||||
}
|
||||
try (InputStream in = Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS)) {
|
||||
byte[] bytes = in.readNBytes((int) maxBytes + 1);
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new IOException("'" + relPath + "' grew past the limit while being read");
|
||||
}
|
||||
return Optional.of(new String(bytes, StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeText(String siteId, String relPath, String text) throws IOException {
|
||||
Objects.requireNonNull(text, "text");
|
||||
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new IllegalArgumentException("write of " + bytes.length + " bytes is over the " + maxBytes
|
||||
+ "-byte limit");
|
||||
}
|
||||
Path file = resolve(siteId, relPath, false);
|
||||
if (!Files.isDirectory(sitesRoot.resolve(siteId), LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("site '" + siteId + "' does not exist");
|
||||
}
|
||||
if (Files.isDirectory(file, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("'" + relPath + "' is a folder, not a file");
|
||||
}
|
||||
Files.createDirectories(file.getParent());
|
||||
Path tmp = Files.createTempFile(file.getParent(), "." + file.getFileName() + ".", ".tmp");
|
||||
try {
|
||||
Files.write(tmp, bytes);
|
||||
Files.move(tmp, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} finally {
|
||||
Files.deleteIfExists(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean delete(String siteId, String relPath) throws IOException {
|
||||
Path file = resolve(siteId, relPath, false);
|
||||
return Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS) && Files.deleteIfExists(file);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteTree(String siteId, String relDir) throws IOException {
|
||||
Path target = resolve(siteId, relDir, false);
|
||||
if (!Files.exists(target, LinkOption.NOFOLLOW_LINKS) || Files.isSymbolicLink(target)) {
|
||||
return false;
|
||||
}
|
||||
if (!Files.isDirectory(target, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return Files.deleteIfExists(target);
|
||||
}
|
||||
Files.walkFileTree(target, new SimpleFileVisitor<>() {
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
|
||||
Files.deleteIfExists(file);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult postVisitDirectory(Path dir, IOException failure) throws IOException {
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
Files.deleteIfExists(dir);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<FileEntry> list(String siteId, String relDir) throws IOException {
|
||||
Path dir = resolve(siteId, relDir, true);
|
||||
if (!Files.isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return List.of();
|
||||
}
|
||||
List<FileEntry> entries = new ArrayList<>();
|
||||
try (DirectoryStream<Path> children = Files.newDirectoryStream(dir)) {
|
||||
for (Path child : children) {
|
||||
entryOf(child).ifPresent(entries::add);
|
||||
}
|
||||
}
|
||||
entries.sort(Comparator.comparing(FileEntry::name));
|
||||
return List.copyOf(entries.size() > MAX_LIST_ENTRIES ? entries.subList(0, MAX_LIST_ENTRIES) : entries);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<FileEntry> stat(String siteId, String relPath) throws IOException {
|
||||
return entryOf(resolve(siteId, relPath, false));
|
||||
}
|
||||
|
||||
private static Optional<FileEntry> entryOf(Path path) throws IOException {
|
||||
if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
|
||||
if (attrs.isSymbolicLink() || !(attrs.isRegularFile() || attrs.isDirectory())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new FileEntry(path.getFileName().toString(), attrs.isDirectory(), attrs.size(),
|
||||
attrs.lastModifiedTime().toInstant()));
|
||||
}
|
||||
|
||||
private Path resolve(String siteId, String relPath, boolean allowRoot) {
|
||||
Path root = root(siteId);
|
||||
String problem = problemWith(relPath, allowRoot);
|
||||
if (problem != null) {
|
||||
throw new IllegalArgumentException("unsafe plugin file path '" + relPath + "': " + problem);
|
||||
}
|
||||
Path target = relPath.isEmpty() ? root : root.resolve(relPath).normalize();
|
||||
try {
|
||||
Path rootReal = real(root);
|
||||
if (!rootReal.equals(real(sitesRoot.resolve(siteId)).resolve("plugins").resolve(pluginId))) {
|
||||
throw new IllegalArgumentException("plugins/" + pluginId + " (or plugins/) is a symbolic link");
|
||||
}
|
||||
if (!real(target).startsWith(rootReal)) {
|
||||
throw new IllegalArgumentException("'" + relPath + "' leaves the plugin's folder through a link");
|
||||
}
|
||||
} catch (IOException unresolvable) {
|
||||
throw new IllegalArgumentException("could not verify that '" + relPath + "' stays inside", unresolvable);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
private static Path real(Path path) throws IOException {
|
||||
Path normalized = path.toAbsolutePath().normalize();
|
||||
Path existing = normalized;
|
||||
while (existing != null && !Files.exists(existing, LinkOption.NOFOLLOW_LINKS)) {
|
||||
existing = existing.getParent();
|
||||
}
|
||||
if (existing == null) {
|
||||
return normalized;
|
||||
}
|
||||
Path remainder = existing.relativize(normalized);
|
||||
Path realExisting = existing.toRealPath();
|
||||
return remainder.toString().isEmpty() ? realExisting : realExisting.resolve(remainder);
|
||||
}
|
||||
|
||||
private static String problemWith(String relPath, boolean allowRoot) {
|
||||
if (relPath == null) {
|
||||
return "null";
|
||||
}
|
||||
if (relPath.isEmpty()) {
|
||||
return allowRoot ? null : "empty";
|
||||
}
|
||||
if (relPath.startsWith("/")) {
|
||||
return "absolute";
|
||||
}
|
||||
if (relPath.indexOf('\\') >= 0) {
|
||||
return "contains a backslash";
|
||||
}
|
||||
for (int i = 0; i < relPath.length(); i++) {
|
||||
if (relPath.charAt(i) < 0x20 || relPath.charAt(i) == 0x7f) {
|
||||
return "contains a control character";
|
||||
}
|
||||
}
|
||||
for (String segment : relPath.split("/", -1)) {
|
||||
if (segment.isEmpty() || segment.equals(".") || segment.equals("..")) {
|
||||
return "has an empty, '.' or '..' segment";
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String requireSafe(String id, String what) {
|
||||
if (id == null || id.equals(".") || id.equals("..") || !SAFE_ID.matcher(id).matches()) {
|
||||
throw new IllegalArgumentException("unsafe " + what + ": " + id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Test doubles for the SPI service tier, for plugin unit tests ({@code test} scope). A plugin that migrates off
|
||||
* host classes tests against these instead of building real kernel objects.
|
||||
*
|
||||
* <p>It holds a fake for every service that exists in SPI 0.6.0:
|
||||
* {@link mx.quest.runway.spi.testkit.FakePluginSettings} (0.4.0), {@link mx.quest.runway.spi.testkit.TempDirSiteFiles}
|
||||
* (the per-site files over a temporary folder, with the kernel's real path-confinement rules),
|
||||
* {@link mx.quest.runway.spi.testkit.FakeSiteServices} (sites, request context, access check, messages and starter
|
||||
* pages, 0.5.0), {@link mx.quest.runway.spi.testkit.FakeContentCatalog} (the content surface, 0.6.0) and
|
||||
* {@link mx.quest.runway.spi.testkit.EventDispatch} (delivers change events to a plugin's listeners in the kernel's
|
||||
* phase order, and is the plugin's {@code ContentChanges}, 0.6.0); {@link mx.quest.runway.spi.model.PluginInfo} is a
|
||||
* plain record a test constructs directly. Every fake applies the same input rules as the kernel implementation, so
|
||||
* a plugin that passes against the fake behaves the same against the kernel.
|
||||
*/
|
||||
package mx.quest.runway.spi.testkit;
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package mx.quest.runway.spi.testkit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.model.SettingsView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The fake answers like the kernel: defaults, then stored values; secrets in clear; unsafe ids refused. */
|
||||
class FakePluginSettingsTest {
|
||||
|
||||
@Test
|
||||
void defaultsAreOverlaidByTheSitesValuesAndABlankDoesNotMaskADefault() {
|
||||
Map<String, Object> stored = new HashMap<>();
|
||||
stored.put("limit", 50);
|
||||
stored.put("title", " ");
|
||||
stored.put("extra", "kept");
|
||||
stored.put("gone", null);
|
||||
FakePluginSettings settings = new FakePluginSettings()
|
||||
.defaults(Map.of("enabled", true, "limit", 20, "title", "Hello"))
|
||||
.site("acme", stored);
|
||||
SettingsView acme = settings.site("acme");
|
||||
assertTrue(acme.bool("enabled", false));
|
||||
assertEquals(50, acme.integer("limit", 0));
|
||||
assertEquals("Hello", acme.string("title", "x"));
|
||||
assertEquals("kept", acme.string("extra", "x"));
|
||||
assertEquals(20, settings.site("other").integer("limit", 0), "a site with nothing stored gets the defaults");
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretsAreReturnedInClearPerSite() {
|
||||
FakePluginSettings settings = new FakePluginSettings().secret("acme", "smtpPassword", "s3cret");
|
||||
assertEquals(Optional.of("s3cret"), settings.secret("acme", "smtpPassword"));
|
||||
assertEquals(Optional.empty(), settings.secret("other", "smtpPassword"));
|
||||
assertEquals(Optional.empty(), settings.secret("acme", "other"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsafeSiteIdsAreRefusedLikeTheKernelRefusesThem() {
|
||||
FakePluginSettings settings = new FakePluginSettings();
|
||||
for (String bad : new String[] {null, "", "..", "../x", "a/b", "a|b", "-lead"}) {
|
||||
assertThrows(IllegalArgumentException.class, () -> settings.site(bad), "site(" + bad + ")");
|
||||
assertThrows(IllegalArgumentException.class, () -> settings.secret(bad, "k"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package mx.quest.runway.spi.testkit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.InstallResult;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.model.StarterPage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** The SPI 0.5.0 fakes apply the kernel's input rules, so a plugin tested against them behaves the same live. */
|
||||
class K2FakesTest {
|
||||
|
||||
@TempDir
|
||||
Path sites;
|
||||
|
||||
@Test
|
||||
void tempDirSiteFilesWritesUnderTheKernelLayoutAndRefusesEscapes() throws IOException {
|
||||
TempDirSiteFiles files = new TempDirSiteFiles(sites, "contact", 32);
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
Files.writeString(sites.resolve("acme/users.yml"), "SECRET");
|
||||
files.writeText("acme", "submissions.tsv", "row");
|
||||
assertEquals("row", Files.readString(sites.resolve("acme/plugins/contact/submissions.tsv")));
|
||||
assertEquals(Optional.of("row"), files.readText("acme", "submissions.tsv"));
|
||||
assertThrows(IllegalArgumentException.class, () -> files.readText("acme", "../../users.yml"));
|
||||
assertThrows(IllegalArgumentException.class, () -> files.writeText("acme", "big", "x".repeat(33)));
|
||||
assertThrows(IOException.class, () -> files.writeText("nosite", "a", "x"), "the site must exist");
|
||||
Files.createSymbolicLink(files.root("acme").resolve("out"), sites.resolve("acme"));
|
||||
assertThrows(IllegalArgumentException.class, () -> files.readText("acme", "out/users.yml"));
|
||||
assertEquals(List.of("submissions.tsv"), files.list("acme", "").stream().map(e -> e.name()).toList());
|
||||
assertTrue(files.delete("acme", "submissions.tsv"));
|
||||
assertFalse(files.deleteTree("acme", "nothing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fakeSiteServicesBehaveLikeTheKernel() {
|
||||
SiteView acme = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
|
||||
FakeSiteServices kernel = new FakeSiteServices().site(acme).grant("contact|settings")
|
||||
.message("acme", "contact.sent", "Thanks, {0}!").message(null, "contact.title", "Contact");
|
||||
assertEquals(Optional.of(acme), kernel.find("acme"));
|
||||
assertEquals(Optional.empty(), kernel.find("other"));
|
||||
assertThrows(IllegalArgumentException.class, () -> kernel.find("../x"));
|
||||
assertEquals(Optional.empty(), kernel.site(), "off a request until current() is set");
|
||||
assertEquals(Optional.of(acme), kernel.current("acme").site());
|
||||
assertTrue(kernel.may("contact|settings"));
|
||||
assertFalse(kernel.may("EDIT_PAGES"), "fail-closed");
|
||||
assertEquals("Thanks, Ana!", kernel.site("acme", Locale.ENGLISH, "contact.sent", "fb", "Ana"));
|
||||
assertEquals("fb", kernel.site("acme", Locale.ENGLISH, "missing", "fb"));
|
||||
assertEquals("missing", kernel.console("missing", null));
|
||||
assertEquals("Contact", kernel.console("contact.title", "fb"));
|
||||
|
||||
StarterPage page = new StarterPage("contact", "/contact", Map.of("en", "Contact"), "<p/>", null, false);
|
||||
kernel.nextInstall(InstallResult.Outcome.DRAFT_BLOCKED, Finding.error("x", "y"));
|
||||
InstallResult first = kernel.install("acme", page);
|
||||
assertEquals(InstallResult.Outcome.DRAFT_BLOCKED, first.outcome());
|
||||
assertEquals(1, first.blocking().size());
|
||||
assertEquals(InstallResult.Outcome.ALREADY_EXISTS, kernel.install("acme", page).outcome(), "never overwrites");
|
||||
assertEquals(Optional.of("/contact"), kernel.pathOf("acme", "contact"));
|
||||
assertEquals(2, kernel.installs().size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package mx.quest.runway.spi.testkit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.SettingsChange;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The SPI 0.6.0 fakes keep the kernel's rules: input checks, path rules, phase order, isolation, refusals. */
|
||||
class K3FakesTest {
|
||||
|
||||
private static CatalogEntry entry(String id) {
|
||||
ContentRef ref = ContentRef.of(id, "/blog/" + id, Map.of(), List.of(), Map.of(), Map.of(), "__plugin__/b/t",
|
||||
null);
|
||||
return new CatalogEntry("blog", ref, List.of(new LocalizedUrl(Locale.ENGLISH, "/blog/" + id, null)), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCatalogFakeAnswersWhatTheTestDeclared() {
|
||||
FakeContentCatalog catalog = new FakeContentCatalog().entry("acme", entry("hello"))
|
||||
.page("acme", "/about", Locale.ENGLISH, "about").text("acme", "blog:hello", "<p>Hi</p>")
|
||||
.route("/sitemap.xml");
|
||||
assertEquals(List.of("blog:hello"), catalog.entries("acme").stream().map(CatalogEntry::compositeId).toList());
|
||||
assertEquals("<p>Hi</p>", catalog.indexableText("acme", entry("hello"), Locale.ENGLISH));
|
||||
assertEquals("", catalog.indexableText("acme", entry("other"), Locale.ENGLISH));
|
||||
assertEquals(Optional.of("about"), catalog.pageAt("acme", "/about", Locale.ENGLISH));
|
||||
assertEquals(Optional.empty(), catalog.pageAt("acme", "/about", Locale.forLanguageTag("es")));
|
||||
assertEquals(List.of(), catalog.entries("unknown"));
|
||||
catalog.refresh("acme");
|
||||
assertEquals(List.of("acme"), catalog.refreshed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCatalogFakeAppliesTheKernelsPathAndIdRules() {
|
||||
FakeContentCatalog catalog = new FakeContentCatalog().site("acme").route("/sitemap.xml");
|
||||
assertTrue(catalog.servablePath("acme", "/blog"));
|
||||
assertTrue(catalog.servablePath("acme", "/blog/"));
|
||||
for (String bad : new String[] {"/login", "/logout", "/error", "/reset", "/forgot-password", "/__admin",
|
||||
"/actuator/health", "/app/x", "/static/x", "/a/../b", "//x", "x", "/a|b", "/sitemap.xml"}) {
|
||||
assertFalse(catalog.servablePath("acme", bad), bad);
|
||||
}
|
||||
assertFalse(catalog.servablePath("unknown", "/blog"));
|
||||
assertThrows(IllegalArgumentException.class, () -> catalog.entries("../x"));
|
||||
assertThrows(IllegalArgumentException.class, () -> catalog.servablePath(null, "/x"));
|
||||
assertThrows(IllegalArgumentException.class, () -> catalog.refresh("a/b"));
|
||||
}
|
||||
|
||||
private static final class Probe implements SiteEventListener {
|
||||
final String name;
|
||||
final Phase phase;
|
||||
final List<String> log;
|
||||
|
||||
Probe(String name, Phase phase, List<String> log) {
|
||||
this.name = name;
|
||||
this.phase = phase;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Phase phase() {
|
||||
return phase;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSiteLifecycle(SiteLifecycleEvent event) {
|
||||
log.add(name + ":lifecycle");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSettingsChanged(SettingsChange change) {
|
||||
log.add(name + ":settings");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCatalogChanged(CatalogChange change) {
|
||||
log.add(name + ":catalog:" + change.currentUrls().size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDispatchFakeAppliesTheKernelsOrder() {
|
||||
List<String> log = new ArrayList<>();
|
||||
EventDispatch events = new EventDispatch("blog", Set.of("blog"))
|
||||
.listener(new Probe("consumer", SiteEventListener.Phase.CONSUMER, log))
|
||||
.listener(new Probe("source", SiteEventListener.Phase.SOURCE, log));
|
||||
events.lifecycle("acme", SiteLifecycleEvent.Kind.RESTORED, false);
|
||||
events.settings("acme", "blog");
|
||||
events.settings("acme", "other");
|
||||
LocalizedUrl url = new LocalizedUrl(Locale.ENGLISH, "/x", null);
|
||||
events.page("acme", "x", List.of(), List.of(url));
|
||||
assertEquals(List.of(
|
||||
"source:lifecycle", "source:catalog:0", "consumer:lifecycle", "consumer:catalog:0",
|
||||
"source:settings", "source:catalog:0", "consumer:settings", "consumer:catalog:0",
|
||||
"source:catalog:0", "consumer:catalog:0",
|
||||
"source:catalog:0", "consumer:catalog:1"), log,
|
||||
"phases, the per-listener order, own-plugin settings only, no current URLs in the source phase");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDispatchFakeIsolatesAndRefusesLikeTheKernel() {
|
||||
List<String> log = new ArrayList<>();
|
||||
EventDispatch[] self = new EventDispatch[1];
|
||||
List<Throwable> refusals = new ArrayList<>();
|
||||
self[0] = new EventDispatch("blog", Set.of("blog"))
|
||||
.listener(new SiteEventListener() {
|
||||
@Override
|
||||
public void onCatalogChanged(CatalogChange change) {
|
||||
try {
|
||||
self[0].changed("acme", "blog", "y");
|
||||
} catch (IllegalStateException e) {
|
||||
refusals.add(e);
|
||||
}
|
||||
throw new IllegalStateException("boom");
|
||||
}
|
||||
})
|
||||
.listener(new Probe("after", SiteEventListener.Phase.CONSUMER, log));
|
||||
self[0].changed("acme", "blog", "x");
|
||||
assertEquals(1, refusals.size(), "ContentChanges is refused from a callback");
|
||||
assertEquals(1, self[0].failures().size());
|
||||
assertEquals(List.of("after:catalog:0"), log, "the next listener still ran");
|
||||
assertEquals("blog", self[0].announced().get(0).pluginId());
|
||||
assertThrows(IllegalArgumentException.class, () -> self[0].changed("acme", "pages", "x"));
|
||||
assertThrows(IllegalArgumentException.class, () -> self[0].changed("../x", "blog", "x"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user