Files
NeitzelFXDesigner/integration-tests/idea/DocumentTabsTargetProbe.java
T

340 lines
14 KiB
Java

package qualification;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.PixelFormat;
import javafx.stage.*;
import javax.imageio.ImageIO;
import org.w3c.dom.Document;
/**
* Checks the selected product tab, WebKit DOM and actual popup, including a return to the first
* tab.
*/
public final class DocumentTabsTargetProbe {
public static void premain(String dir) {
if (System.getProperty("sun.java.command", "")
.startsWith("de.neitzel.fxdesigner.target.WorkerMain "))
Thread.ofPlatform().daemon().start(() -> Probe.run(Path.of(dir)));
}
static final class Probe {
private static <T> T fx(Callable<T> task) throws Exception {
var future = new FutureTask<>(task);
Platform.runLater(future);
return future.get(10, TimeUnit.SECONDS);
}
private static void await(String description, Callable<Boolean> check) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(45);
while (System.nanoTime() < deadline) {
if (fx(check)) return;
Thread.sleep(100);
}
throw new AssertionError(description);
}
private static void run(Path dir) {
try {
Stage stage = null;
while (stage == null) {
Thread.sleep(120);
try {
stage =
fx(
() ->
Window.getWindows().stream()
.filter(Stage.class::isInstance)
.map(Stage.class::cast)
.filter(
s ->
s.getOpacity() > 0
&& s.getTitle() != null
&& s.getTitle().startsWith("Neitzel preview"))
.findFirst()
.orElse(null));
} catch (IllegalStateException starting) {
/* Waiting for FX startup. */
}
}
final Stage window = stage;
String id = Files.readString(dir.resolve("document-attempt"));
var root = fx(() -> window.getScene().getRoot());
String result;
if (id.equals("archive-window-documents")) {
checkWindow(dir, root);
result =
"Rechnung → Lieferschein → Rechnung: HTML, chips and popup matched each document."
+ " Adding Beleg geprüft affected only Rechnung; removing it restored its"
+ " suggestion.";
} else if (id.startsWith("html-")) {
boolean invoice = id.equals("html-invoice");
String heading = invoice ? "Rechnung RE-042" : "Lieferschein LS-018";
checkHtml(
root, heading, invoice ? "Büromaterial · 48,00 €" : "Wareneingang · 3 Archivkartons");
result = id + ": WebKit displayed " + heading;
} else {
result = checkDetails(dir, root, id);
}
var completed = Files.writeString(dir.resolve("result-" + id + ".tmp"), result);
Files.move(completed, dir.resolve("result-" + id), StandardCopyOption.ATOMIC_MOVE);
} catch (Throwable error) {
var trace = new java.io.StringWriter();
error.printStackTrace(new java.io.PrintWriter(trace));
try {
Files.writeString(dir.resolve("target-error.txt"), trace.toString());
} catch (Exception ignored) {
error.printStackTrace();
}
}
}
private static String checkDetails(Path dir, Node root, String id) throws Exception {
String assigned = id.equals("details-delivery") ? "Beleg geprüft" : "Beleg offen";
String suggestion = id.equals("details-delivery") ? "Beleg offen" : "Beleg geprüft";
boolean readonly = id.equals("details-readonly"), busy = id.equals("details-busy");
var field = fx(() -> (TextField) root.lookup("#tag-input"));
fx(
() -> {
if (!field.getPromptText().equals("Belegtag wählen")
|| field.isDisabled() != (readonly || busy))
throw new AssertionError("Saved prompt or edit state: " + id);
var remove = removeButton(root, assigned);
if (remove.isVisible() == readonly || remove.isDisabled() != busy)
throw new AssertionError("Removal state: " + id);
if (readonly || busy) {
remove.fire();
requireChips(root, assigned);
}
return null;
});
if (!readonly && !busy) popup(field, suggestion, dir.resolve(id + "-tags.png"));
return id
+ ": "
+ assigned
+ (readonly ? ", removal hidden" : busy ? ", removal disabled" : ", Be → " + suggestion);
}
private static void checkWindow(Path dir, Node root) throws Exception {
var group =
fx(
() ->
root.lookupAll(".tab-pane").stream()
.map(TabPane.class::cast)
.filter(
p ->
p.getTabs().stream()
.anyMatch(t -> "Rechnung.html".equals(t.getText())))
.findFirst()
.orElseThrow());
var invoice = select(group, "Rechnung.html");
checkHtml(invoice, "Rechnung RE-042", "Büromaterial · 48,00 €");
var input = fx(() -> (TextField) invoice.lookup("#tag-input"));
fx(
() -> {
requireChips(invoice, "Beleg offen");
save(invoice, dir.resolve("rechnung-tab.png"));
return null;
});
popup(input, "Beleg geprüft", dir.resolve("rechnung-tab-tags.png"));
fx(
() -> {
input.setText("Beleg geprüft");
((Button) invoice.lookup("#add")).fire();
requireChips(invoice, "Beleg offen", "Beleg geprüft");
if (suggestions(input).contains("Beleg geprüft"))
throw new AssertionError("Assigned tag still suggested");
return null;
});
fx(
() -> {
invoice.applyCss();
((javafx.scene.Parent) invoice).layout();
save(invoice, dir.resolve("rechnung-zwei-tags.png"));
return null;
});
var delivery = select(group, "Lieferschein.html");
checkHtml(delivery, "Lieferschein LS-018", "Wareneingang · 3 Archivkartons");
fx(
() -> {
requireChips(delivery, "Beleg geprüft");
save(delivery, dir.resolve("lieferschein-tab.png"));
return null;
});
popup(
fx(() -> (TextField) delivery.lookup("#tag-input")),
"Beleg offen",
dir.resolve("lieferschein-tab-tags.png"));
select(group, "Rechnung.html");
checkHtml(invoice, "Rechnung RE-042", "Büromaterial · 48,00 €");
fx(
() -> {
requireChips(invoice, "Beleg offen", "Beleg geprüft");
removeButton(invoice, "Beleg geprüft").fire();
requireChips(invoice, "Beleg offen");
return null;
});
popup(input, "Beleg geprüft", dir.resolve("rechnung-tab-tags.png"));
}
static Node select(TabPane group, String name) throws Exception {
var tab =
fx(
() -> {
var target =
group.getTabs().stream()
.filter(t -> name.equals(t.getText()))
.findFirst()
.orElseThrow();
group.getSelectionModel().select(target);
return target;
});
await(
"Selected " + name,
() -> group.getSelectionModel().getSelectedItem() == tab && tab.getContent().isVisible());
return fx(tab::getContent);
}
static void checkHtml(Node root, String heading, String text) throws Exception {
await(
heading,
() -> {
var browser = root.lookup("WebView");
if (browser == null) return false;
var engine = browser.getClass().getMethod("getEngine").invoke(browser);
var doc = (Document) engine.getClass().getMethod("getDocument").invoke(engine);
return doc != null
&& doc.getElementsByTagName("h1").getLength() == 1
&& doc.getElementsByTagName("h1").item(0).getTextContent().equals(heading)
&& doc.getDocumentElement().getTextContent().contains(text);
});
}
private static List<?> suggestions(TextField field) throws Exception {
return (List<?>) field.getClass().getMethod("getSuggestionsSource").invoke(field);
}
private static Map<String, Node> chips(Node root) throws Exception {
var named = new TreeMap<String, Node>();
var pane = (javafx.scene.layout.FlowPane) root.lookup("#tags");
for (var row : pane.getChildren()) {
var chip = (javafx.scene.layout.Region) row.lookup(".tag-chip");
String text = (String) chip.getClass().getMethod("getText").invoke(chip);
chip.applyCss();
var fills = chip.getBackground().getFills();
if (fills.stream()
.noneMatch(f -> javafx.scene.paint.Color.web("#f2d58a").equals(f.getFill())))
throw new AssertionError(
"Chip "
+ text
+ " style="
+ chip.getStyle()
+ ", background="
+ fills.stream().map(f -> f.getFill()).toList()
+ ", component="
+ row.getClass().getResource("DocumentTag.fxml"));
if (named.put(text, chip) != null)
throw new AssertionError("Duplicate assigned chip: " + text);
}
return named;
}
static void requireChips(Node root, String... expected) throws Exception {
var actual = chips(root).keySet();
if (!actual.equals(Set.of(expected)))
throw new AssertionError("Assigned tags " + actual + " vs " + Arrays.toString(expected));
}
static Button removeButton(Node root, String text) throws Exception {
return (Button)
Objects.requireNonNull(chips(root).get(text), text).lookup(".tag-chip-remove");
}
private static void popup(TextField field, String suggestion, Path file) throws Exception {
// Each interactive target is a separate macOS app. Keep focus acquisition and typing in
// one FX event so an IDE activation between them cannot suppress the real popup.
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(45);
long activateAfter = 0;
while (System.nanoTime() < deadline) {
if (System.nanoTime() >= activateAfter
&& !fx(() -> field.isFocused() && field.getScene().getWindow().isFocused())
&& System.getProperty("os.name").startsWith("Mac")) {
var desktop = java.awt.Desktop.getDesktop();
if (desktop.isSupported(java.awt.Desktop.Action.APP_REQUEST_FOREGROUND)) {
// Request activation from the preview process itself, which owns the FX stage.
desktop.requestForeground(true);
}
activateAfter = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
}
boolean matched =
fx(
() -> {
var stage = (Stage) field.getScene().getWindow();
if (!stage.isFocused() || !field.isFocused()) {
stage.toFront();
stage.requestFocus();
field.requestFocus();
}
if (!stage.isFocused() || !field.isFocused()) return false;
if (!suggestions(field).contains(suggestion))
throw new AssertionError(
"Missing " + suggestion + " in catalogue " + suggestions(field));
field.setText("");
field.setText("Be");
for (var window : Window.getWindows()) {
if (window instanceof Popup popup
&& popup.isShowing()
&& popup.getOwnerNode() == field
&& popup.getScene().lookup(".list-view") instanceof ListView<?> list) {
if (!list.getItems().equals(List.of(suggestion)))
throw new AssertionError(
"Expected " + suggestion + " but saw " + list.getItems());
save(list, file);
field.setText("");
return true;
}
}
return false;
});
if (matched) return;
Thread.sleep(150);
}
throw new AssertionError(
fx(
() ->
"No popup for "
+ suggestion
+ ", field focused="
+ field.isFocused()
+ ", stage focused="
+ field.getScene().getWindow().isFocused()
+ ", focus owner="
+ field.getScene().getFocusOwner()
+ ", field bounds="
+ field.localToScreen(field.getBoundsInLocal())
+ ", catalogue="
+ suggestions(field)
+ ", windows="
+ Window.getWindows()));
}
private static void save(Node node, Path file) throws Exception {
var image = node.snapshot(null, null);
int width = (int) image.getWidth(), height = (int) image.getHeight();
var pixels = new int[width * height];
image
.getPixelReader()
.getPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), pixels, 0, width);
var png =
new java.awt.image.BufferedImage(
width, height, java.awt.image.BufferedImage.TYPE_INT_ARGB);
png.setRGB(0, 0, width, height, pixels, 0, width);
ImageIO.write(png, "png", file.toFile());
}
}
}