From 8e64749111dea7d4837102d2b3a8f17a08b9c173 Mon Sep 17 00:00:00 2001 From: Andrei Molnar <1995am@pm.me> Date: Thu, 19 Nov 2026 09:31:43 +0100 Subject: [PATCH] Save system revamp, quality of life. --- .../com/molnarandrei/sopa/data/FileNames.java | 5 + .../sopa/data/ProjectMonitor.java | 8 +- .../molnarandrei/sopa/data/yaml/CallLog.java | 4 +- .../molnarandrei/sopa/data/yaml/Config.java | 20 ++ .../molnarandrei/sopa/data/yaml/Project.java | 12 +- .../molnarandrei/sopa/data/yaml/TestCase.java | 12 +- .../com/molnarandrei/sopa/data/yaml/Yaml.java | 5 + .../sopa/events/PropertiesEvent.java | 17 ++ .../sopa/project/ProjectRepository.java | 37 +++- .../sopa/project/ProjectService.java | 26 ++- .../sopa/properties/PropertiesRepository.java | 65 +++++++ .../sopa/properties/PropertiesService.java | 44 +++++ .../com/molnarandrei/sopa/soap/SoapCall.java | 7 +- .../com/molnarandrei/sopa/soap/SoapJob.java | 40 ++-- .../molnarandrei/sopa/soap/SoapService.java | 9 + .../sopa/step/StepRepository.java | 14 +- .../molnarandrei/sopa/step/StepService.java | 37 ++-- .../sopa/testcase/TestCaseRepository.java | 14 +- .../sopa/testcase/TestCaseService.java | 39 ++-- .../molnarandrei/sopa/trash/TrashService.java | 58 ------ .../sopa/ui/PropertiesDialog.java | 80 ++++---- .../molnarandrei/sopa/ui/SopaApplication.java | 2 + .../sopa/ui/create/CreateProjectDialog.java | 177 ++---------------- .../sopa/ui/editor/EditorPane.java | 17 ++ .../sopa/ui/editor/EndpointsPane.java | 6 +- .../sopa/ui/editor/HeadersPane.java | 13 +- .../sopa/ui/editor/ProjectEditorPane.java | 25 +-- .../sopa/ui/editor/TestCaseEditorPane.java | 23 +-- .../sopa/ui/editor/step/CallDetailsPane.java | 7 +- .../step/StepAssertionsExtractionsPane.java | 11 +- .../sopa/ui/editor/step/StepEditorPane.java | 23 ++- .../com/molnarandrei/sopa/ui/lib/Commit.java | 15 ++ .../molnarandrei/sopa/ui/lib/Shortcuts.java | 23 +++ .../sopa/ui/navpane/FlightState.java | 2 +- .../sopa/ui/navpane/ProjectPane.java | 26 ++- .../navpane/context/ProjectContextMenu.java | 5 +- .../java/com/molnarandrei/sopa/undo/Undo.java | 91 +++++++++ .../molnarandrei/sopa/wsdl/WsdlService.java | 13 +- src/main/resources/AGENTS.md | 5 +- .../sopa/project/ProjectFolderTest.java | 18 ++ .../properties/PropertiesRepositoryTest.java | 44 +++++ .../molnarandrei/sopa/soap/SoapCallTest.java | 46 +++-- .../sopa/trash/TrashServiceTest.java | 49 ----- .../com/molnarandrei/sopa/undo/UndoTest.java | 103 ++++++++++ 44 files changed, 791 insertions(+), 506 deletions(-) create mode 100644 src/main/java/com/molnarandrei/sopa/events/PropertiesEvent.java create mode 100644 src/main/java/com/molnarandrei/sopa/properties/PropertiesRepository.java create mode 100644 src/main/java/com/molnarandrei/sopa/properties/PropertiesService.java delete mode 100644 src/main/java/com/molnarandrei/sopa/trash/TrashService.java create mode 100644 src/main/java/com/molnarandrei/sopa/ui/lib/Commit.java create mode 100644 src/main/java/com/molnarandrei/sopa/ui/lib/Shortcuts.java create mode 100644 src/main/java/com/molnarandrei/sopa/undo/Undo.java create mode 100644 src/test/java/com/molnarandrei/sopa/properties/PropertiesRepositoryTest.java delete mode 100644 src/test/java/com/molnarandrei/sopa/trash/TrashServiceTest.java create mode 100644 src/test/java/com/molnarandrei/sopa/undo/UndoTest.java diff --git a/src/main/java/com/molnarandrei/sopa/data/FileNames.java b/src/main/java/com/molnarandrei/sopa/data/FileNames.java index 72160d7..e14f166 100644 --- a/src/main/java/com/molnarandrei/sopa/data/FileNames.java +++ b/src/main/java/com/molnarandrei/sopa/data/FileNames.java @@ -28,6 +28,11 @@ public class FileNames { && filename.endsWith(".yml"); } + public static boolean isPropertiesFile(Path propertiesFile) { + var filename = propertiesFile.getFileName().toString(); + return "project.properties".equals(filename) || "testcase.properties".equals(filename); + } + public static boolean isStepFile(Path stepFile) { return "step.yml".equals( stepFile.getFileName().toString() ); } diff --git a/src/main/java/com/molnarandrei/sopa/data/ProjectMonitor.java b/src/main/java/com/molnarandrei/sopa/data/ProjectMonitor.java index cfe75c1..14abb41 100644 --- a/src/main/java/com/molnarandrei/sopa/data/ProjectMonitor.java +++ b/src/main/java/com/molnarandrei/sopa/data/ProjectMonitor.java @@ -50,6 +50,8 @@ public class ProjectMonitor extends PathAlterationListener { Events.emit(new TestCaseEvent(TestCaseEvent.CHANGED, testCaseAndProject(file))); else if (isStepResponse(file)) Events.emit(new ResponseEvent(ResponseEvent.CHANGED, file)); + else if (isPropertiesFile(file)) + Events.emit(new PropertiesEvent(PropertiesEvent.CHANGED, file)); else if (isStepFile(file)) Events.emit(new StepEvent(StepEvent.CHANGED, stepAndProject(file))); else @@ -66,6 +68,8 @@ public class ProjectMonitor extends PathAlterationListener { Events.emit(new TestCaseEvent(TestCaseEvent.ADDED, testCaseAndProject(file))); else if (isStepResponse(file)) Events.emit(new ResponseEvent(ResponseEvent.ADDED, file)); + else if (isPropertiesFile(file)) + Events.emit(new PropertiesEvent(PropertiesEvent.ADDED, file)); else if (isStepFile(file)) Events.emit(new StepEvent(StepEvent.ADDED, stepAndProject(file))); else @@ -86,6 +90,8 @@ public class ProjectMonitor extends PathAlterationListener { Events.emit(new TestCaseEvent(TestCaseEvent.REMOVED, testCaseAndProject(file))); else if (isStepResponse(file)) Events.emit(new ResponseEvent(ResponseEvent.REMOVED, file)); + else if (isPropertiesFile(file)) + Events.emit(new PropertiesEvent(PropertiesEvent.REMOVED, file)); else if (isStepFile(file)) Events.emit(new StepEvent(StepEvent.REMOVED, stepAndProject(file))); else @@ -99,7 +105,7 @@ public class ProjectMonitor extends PathAlterationListener { private boolean isOutsideProjectTree(Path file) { var relative = root.relativize(file); - if (relative.getNameCount() == 1) return ! isProjectFile(file); + if (relative.getNameCount() == 1) return ! isProjectFile(file) && ! file.endsWith("project.properties"); return ! hasTestCaseFolderName(relative.getName(0)); } diff --git a/src/main/java/com/molnarandrei/sopa/data/yaml/CallLog.java b/src/main/java/com/molnarandrei/sopa/data/yaml/CallLog.java index 6adf6d6..1b2a7ce 100644 --- a/src/main/java/com/molnarandrei/sopa/data/yaml/CallLog.java +++ b/src/main/java/com/molnarandrei/sopa/data/yaml/CallLog.java @@ -10,7 +10,9 @@ public class CallLog { success, assertionsFailed, extractionsFailed, - exception + exception, + /** The call could not be made, as when a property is missing: the body says why. */ + notCalled } private Path step; diff --git a/src/main/java/com/molnarandrei/sopa/data/yaml/Config.java b/src/main/java/com/molnarandrei/sopa/data/yaml/Config.java index eab51fa..b52e643 100644 --- a/src/main/java/com/molnarandrei/sopa/data/yaml/Config.java +++ b/src/main/java/com/molnarandrei/sopa/data/yaml/Config.java @@ -46,6 +46,8 @@ public class Config { private Double responseHistorySplitPaneDividerPosition = 0.2d; private Double assertionsExtractionsSplitPaneDividerPosition = 0.5d; private Integer callTimeout = 10; + private Integer maxUndo = 100; + private Integer undoMergeSeconds = 10; private static Config INSTANCE = null; @@ -234,6 +236,24 @@ public class Config { this.callTimeout = callTimeout; } + /** How many deletions and modifications can be undone. */ + public Integer getMaxUndo() { + return maxUndo; + } + + public void setMaxUndo(Integer maxUndo) { + this.maxUndo = maxUndo; + } + + /** How long after an undoable modification further ones of the same file are undone with it. */ + public Integer getUndoMergeSeconds() { + return undoMergeSeconds; + } + + public void setUndoMergeSeconds(Integer undoMergeSeconds) { + this.undoMergeSeconds = undoMergeSeconds; + } + public Double getAssertionsExtractionsSplitPaneDividerPosition() { return assertionsExtractionsSplitPaneDividerPosition; } diff --git a/src/main/java/com/molnarandrei/sopa/data/yaml/Project.java b/src/main/java/com/molnarandrei/sopa/data/yaml/Project.java index c476264..6b51b66 100644 --- a/src/main/java/com/molnarandrei/sopa/data/yaml/Project.java +++ b/src/main/java/com/molnarandrei/sopa/data/yaml/Project.java @@ -14,7 +14,6 @@ public class Project { /** By url, in the order they were added. */ private Map endpoints = new LinkedHashMap<>(); private Map headers = new HashMap<>(); - private Map properties = new HashMap<>(); public Project() {} @@ -25,10 +24,9 @@ public class Project { } /** Every endpoint is SOAP 1.1. */ - public Project(String name, List endpoints, Map headers, Map properties) { + public Project(String name, List endpoints, Map headers) { this(name, endpoints); this.headers = headers; - this.properties = properties; } public String getVersion() { @@ -76,12 +74,4 @@ public class Project { public void setHeaders(Map headers) { this.headers = headers; } - - public Map getProperties() { - return properties; - } - - public void setProperties(Map properties) { - this.properties = properties; - } } diff --git a/src/main/java/com/molnarandrei/sopa/data/yaml/TestCase.java b/src/main/java/com/molnarandrei/sopa/data/yaml/TestCase.java index 82e51ae..7a25363 100644 --- a/src/main/java/com/molnarandrei/sopa/data/yaml/TestCase.java +++ b/src/main/java/com/molnarandrei/sopa/data/yaml/TestCase.java @@ -11,7 +11,6 @@ public class TestCase { private String endpoint = ""; private String action = ""; private Map headers = new HashMap<>(); - private Map properties = new HashMap<>(); public String filename() { return name.toLowerCase().replaceAll(" ", "-"); @@ -23,13 +22,12 @@ public class TestCase { this.name = name; } - public TestCase(String name, boolean active, String endpoint, String action, Map headers, Map properties) { + public TestCase(String name, boolean active, String endpoint, String action, Map headers) { this.name = name; this.active = active; this.endpoint = endpoint; this.action = action; this.headers = headers; - this.properties = properties; } public String getName() { @@ -71,12 +69,4 @@ public class TestCase { public void setHeaders(Map headers) { this.headers = headers; } - - public Map getProperties() { - return properties; - } - - public void setProperties(Map properties) { - this.properties = properties; - } } diff --git a/src/main/java/com/molnarandrei/sopa/data/yaml/Yaml.java b/src/main/java/com/molnarandrei/sopa/data/yaml/Yaml.java index 3f080fa..ff32730 100644 --- a/src/main/java/com/molnarandrei/sopa/data/yaml/Yaml.java +++ b/src/main/java/com/molnarandrei/sopa/data/yaml/Yaml.java @@ -62,6 +62,11 @@ public class Yaml { return Config.HEADER + '\n' + mapper.writeValueAsString(config); } + /** Whether both would be written the same, whatever the order of their maps. */ + public static boolean sameContent(Object a, Object b) { + return mapper.valueToTree(a).equals(mapper.valueToTree(b)); + } + public static String toYaml(CallLog callLog) { return CallLog.HEADER + '\n' + mapper.writeValueAsString(callLog); } diff --git a/src/main/java/com/molnarandrei/sopa/events/PropertiesEvent.java b/src/main/java/com/molnarandrei/sopa/events/PropertiesEvent.java new file mode 100644 index 0000000..2da9d54 --- /dev/null +++ b/src/main/java/com/molnarandrei/sopa/events/PropertiesEvent.java @@ -0,0 +1,17 @@ +package com.molnarandrei.sopa.events; + +import javafx.event.Event; +import javafx.event.EventType; + +import java.nio.file.Path; + +/** The properties file of a project or testcase, the payload, was added, removed or changed. */ +public class PropertiesEvent extends SopaEvent { + public static final EventType ADDED = new EventType<>(Event.ANY, "PROPERTIES_ADDED"); + public static final EventType REMOVED = new EventType<>(Event.ANY, "PROPERTIES_REMOVED"); + public static final EventType CHANGED = new EventType<>(Event.ANY, "PROPERTIES_CHANGED"); + + public PropertiesEvent(EventType eventType, Path payload) { + super(eventType, payload); + } +} diff --git a/src/main/java/com/molnarandrei/sopa/project/ProjectRepository.java b/src/main/java/com/molnarandrei/sopa/project/ProjectRepository.java index 26a24a7..b3d0f20 100644 --- a/src/main/java/com/molnarandrei/sopa/project/ProjectRepository.java +++ b/src/main/java/com/molnarandrei/sopa/project/ProjectRepository.java @@ -3,18 +3,22 @@ package com.molnarandrei.sopa.project; import com.molnarandrei.sopa.data.Trash; import com.molnarandrei.sopa.Utils; import com.molnarandrei.sopa.data.DoesNotExistException; +import com.molnarandrei.sopa.data.FileNames; import com.molnarandrei.sopa.data.FileSystemCache; import com.molnarandrei.sopa.data.EmptyException; import com.molnarandrei.sopa.data.ProjectMonitors; import com.molnarandrei.sopa.data.RepositoryException; import com.molnarandrei.sopa.data.yaml.*; import com.molnarandrei.sopa.data.yaml.Yaml; +import com.molnarandrei.sopa.testcase.TestCaseRepository; import tools.jackson.core.JacksonException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Comparator; +import java.util.List; import java.util.logging.Logger; @@ -40,17 +44,44 @@ public class ProjectRepository { } } - public static void update(Path projectPath, Project project) throws RepositoryException{ + /** @return the content it replaced, null when the file was new or already held it. */ + public static String update(Path projectPath, Project project) throws RepositoryException { + return overwrite(projectPath, Yaml.toYaml(project)); + } + + /** Writes {@code content} as the project file, unless it already holds it. @return as {@link #update}. */ + public static String overwrite(Path projectPath, String content) throws RepositoryException { try { - var yaml = Yaml.toYaml(project); - Files.writeString(projectPath, yaml); + var previous = Files.exists(projectPath) ? Files.readString(projectPath) : null; + if (content.equals(previous)) return null; + Files.writeString(projectPath, content); FileSystemCache.remove(projectPath); ProjectMonitors.trigger(projectPath.getParent()); + return previous; } catch (IOException io) { throw new RepositoryException(projectPath, "Cannot write project", io); } } + /** The steps of the testcases of the project, testcase by testcase, in the order they run. */ + public static List getPathsOfContainedSteps(Path projectPath) throws RepositoryException { + List testCases; + try (var children = Files.list(projectPath.getParent())) { + testCases = children + .filter(folder -> Files.isDirectory(folder) && FileNames.hasTestCaseFolderName(folder)) + .map(folder -> folder.resolve("testcase.yml")) + .filter(Files::exists) + .sorted(Utils.STEP_ORDER) // by the index of their folder, as steps + .toList(); + } catch (IOException io) { + throw new RepositoryException(projectPath, "Cannot list testcases", io); + } + var steps = new ArrayList(); + for (var testCase : testCases) + steps.addAll(TestCaseRepository.getPathsOfContainedSteps(testCase)); + return steps; + } + public static boolean canHoldNewProject(Path projectDir) { var directory = projectDir.toAbsolutePath(); if (Files.exists(directory)) return isEmptyFolder(directory); diff --git a/src/main/java/com/molnarandrei/sopa/project/ProjectService.java b/src/main/java/com/molnarandrei/sopa/project/ProjectService.java index 9e57ea5..5877e71 100644 --- a/src/main/java/com/molnarandrei/sopa/project/ProjectService.java +++ b/src/main/java/com/molnarandrei/sopa/project/ProjectService.java @@ -2,7 +2,7 @@ package com.molnarandrei.sopa.project; import java.nio.file.Files; import com.molnarandrei.sopa.data.yaml.Kind; -import com.molnarandrei.sopa.trash.TrashService; +import com.molnarandrei.sopa.undo.Undo; import com.molnarandrei.sopa.Utils; import com.molnarandrei.sopa.data.ProjectMonitors; import com.molnarandrei.sopa.data.yaml.Project; @@ -57,10 +57,11 @@ public class ProjectService { } } + /** Writes the project, alerting on failure; {@link Undo#undo()} puts back what it held. */ public static void write(Path projectPath, Project project) { removeBlankHeaders(project); try { - ProjectRepository.update(projectPath, project); + Undo.modified(Kind.project, projectPath, ProjectRepository.update(projectPath, project)); } catch (RepositoryException cannotWrite) { log.log(Level.SEVERE, "Cannot write project %s.".formatted(projectPath), cannotWrite); Utils.alert( @@ -72,6 +73,23 @@ public class ProjectService { } } + /** Puts back what {@code projectPath} held, undoing a {@link #write}. Returns whether it was written. */ + public static boolean overwrite(Path projectPath, String content) { + log.info("Undoing changes to project %s.".formatted(projectPath)); + try { + ProjectRepository.overwrite(projectPath, content); + return true; + } catch (RepositoryException cannotWrite) { + log.log(Level.WARNING, "Cannot undo changes to project %s.".formatted(projectPath), cannotWrite); + Utils.alert( + "No se puede deshacer", + "No se ha podido restaurar el proyecto:\n%s".formatted(projectPath), + cannotWrite.getMessage() + ); + return false; + } + } + private static void removeBlankHeaders(Project project) { project.getHeaders().entrySet().removeIf(entry -> entry.getKey() == null || entry.getKey().isBlank() || @@ -127,12 +145,12 @@ public class ProjectService { ProjectMonitors.stop(projectPath.getParent()); } - /** Closes the project and moves it to the trash: {@link TrashService#undo()} restores and opens it. */ + /** Closes the project and moves it to the trash: {@link Undo#undo()} restores and opens it. */ public static void delete(Path projectPath) { log.info("Deleting project %s.".formatted(projectPath)); close(projectPath); try { - TrashService.remember(Kind.project, projectPath, ProjectRepository.trashProject(projectPath)); + Undo.deleted(Kind.project, projectPath, ProjectRepository.trashProject(projectPath)); } catch (RepositoryException cannotDeleteAllFiles) { log.log(Level.WARNING, "Delete project error.", cannotDeleteAllFiles); Utils.alert( diff --git a/src/main/java/com/molnarandrei/sopa/properties/PropertiesRepository.java b/src/main/java/com/molnarandrei/sopa/properties/PropertiesRepository.java new file mode 100644 index 0000000..5aae0ea --- /dev/null +++ b/src/main/java/com/molnarandrei/sopa/properties/PropertiesRepository.java @@ -0,0 +1,65 @@ +package com.molnarandrei.sopa.properties; + +import com.molnarandrei.sopa.data.ProjectMonitors; +import com.molnarandrei.sopa.data.RepositoryException; + +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * The properties of a project or testcase, in a java .properties file next to its yml: + * project.properties and testcase.properties. A missing file has no properties. + */ +public class PropertiesRepository { + + /** The properties file of the project or testcase whose yml is {@code ymlPath}. */ + public static Path of(Path ymlPath) { + return ymlPath.resolveSibling(ymlPath.getFileName().toString().replace(".yml", ".properties")); + } + + public static Map get(Path propertiesPath) throws RepositoryException { + var properties = new HashMap(); + if (! Files.exists(propertiesPath)) return properties; + try { + var loaded = new Properties(); + loaded.load(new StringReader(Files.readString(propertiesPath))); + loaded.forEach((key, value) -> properties.put((String) key, (String) value)); + return properties; + } catch (IOException | IllegalArgumentException io) { + throw new RepositoryException(propertiesPath, "Cannot read properties", io); + } + } + + /** Those of the project, overridden by those of the testcase when {@code testCasePath} is not null. */ + public static Map merged(Path projectPath, Path testCasePath) throws RepositoryException { + var properties = get(of(projectPath)); + if (testCasePath != null) properties.putAll(get(of(testCasePath))); + return properties; + } + + /** Writes {@code properties}, unless the file already holds them. */ + public static void update(Path propertiesPath, Map properties) throws RepositoryException { + if (get(propertiesPath).equals(properties)) return; + try { + var stored = new Properties(); + stored.putAll(properties); + var text = new StringWriter(); + stored.store(text, null); + Files.writeString(propertiesPath, text.toString()); + ProjectMonitors.trigger(projectDirectoryOf(propertiesPath)); + } catch (IOException io) { + throw new RepositoryException(propertiesPath, "Cannot write properties", io); + } + } + + private static Path projectDirectoryOf(Path propertiesPath) { + var folder = propertiesPath.getParent(); + return propertiesPath.getFileName().toString().equals("project.properties") ? folder : folder.getParent(); + } +} diff --git a/src/main/java/com/molnarandrei/sopa/properties/PropertiesService.java b/src/main/java/com/molnarandrei/sopa/properties/PropertiesService.java new file mode 100644 index 0000000..d569295 --- /dev/null +++ b/src/main/java/com/molnarandrei/sopa/properties/PropertiesService.java @@ -0,0 +1,44 @@ +package com.molnarandrei.sopa.properties; + +import com.molnarandrei.sopa.Utils; +import com.molnarandrei.sopa.data.RepositoryException; + +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** Properties are not undoable: their files are written apart from the yml of their project or testcase. */ +public class PropertiesService { + private static final Logger log = Logger.getLogger(PropertiesService.class.getName()); + + /** The properties of the project or testcase whose yml is {@code ymlPath}; empty and alerting when unreadable. */ + public static Map read(Path ymlPath) { + try { + return PropertiesRepository.get(PropertiesRepository.of(ymlPath)); + } catch (RepositoryException cannotRead) { + log.log(Level.WARNING, "Cannot read properties of %s.".formatted(ymlPath), cannotRead); + Utils.alert( + "Fallo de fichero", + "No se han podido leer las propiedades de:\n%s".formatted(ymlPath), + cannotRead.getMessage() + ); + return new HashMap<>(); + } + } + + /** Writes the properties of the project or testcase whose yml is {@code ymlPath}, alerting on failure. */ + public static void write(Path ymlPath, Map properties) { + try { + PropertiesRepository.update(PropertiesRepository.of(ymlPath), properties); + } catch (RepositoryException cannotWrite) { + log.log(Level.SEVERE, "Cannot write properties of %s.".formatted(ymlPath), cannotWrite); + Utils.alert( + "Fallo de fichero", + "No se han podido guardar las propiedades de:\n%s".formatted(ymlPath), + cannotWrite.getMessage() + ); + } + } +} diff --git a/src/main/java/com/molnarandrei/sopa/soap/SoapCall.java b/src/main/java/com/molnarandrei/sopa/soap/SoapCall.java index 3ccb743..39614c6 100644 --- a/src/main/java/com/molnarandrei/sopa/soap/SoapCall.java +++ b/src/main/java/com/molnarandrei/sopa/soap/SoapCall.java @@ -3,6 +3,7 @@ package com.molnarandrei.sopa.soap; import com.molnarandrei.sopa.data.RepositoryException; import com.molnarandrei.sopa.data.yaml.Assertion; import com.molnarandrei.sopa.project.ProjectRepository; +import com.molnarandrei.sopa.properties.PropertiesRepository; import com.molnarandrei.sopa.step.StepRepository; import com.molnarandrei.sopa.testcase.TestCaseRepository; @@ -91,11 +92,7 @@ public class SoapCall extends RawSoapCall { } public void applyProperties() throws RepositoryException, PropertyMissingException, MalformedEndpointException { - var testcase = TestCaseRepository.get(testCasePath); - var project = ProjectRepository.get(projectPath); - properties = new HashMap<>(); - properties.putAll(project.getProperties()); - properties.putAll(testcase.getProperties()); + properties = PropertiesRepository.merged(projectPath, testCasePath); endpoint = applyProperties(endpointTemplate); payload = applyProperties(payloadTemplate); diff --git a/src/main/java/com/molnarandrei/sopa/soap/SoapJob.java b/src/main/java/com/molnarandrei/sopa/soap/SoapJob.java index 6a7b4e0..d3593be 100644 --- a/src/main/java/com/molnarandrei/sopa/soap/SoapJob.java +++ b/src/main/java/com/molnarandrei/sopa/soap/SoapJob.java @@ -8,8 +8,7 @@ import com.molnarandrei.sopa.events.Events; import com.molnarandrei.sopa.events.SoapCallEvent; import com.molnarandrei.sopa.events.SoapJobEvent; import com.molnarandrei.sopa.calllog.CallLogService; -import com.molnarandrei.sopa.project.ProjectService; -import com.molnarandrei.sopa.testcase.TestCaseService; +import com.molnarandrei.sopa.properties.PropertiesService; import com.molnarandrei.sopa.data.yaml.Kind; import com.molnarandrei.sopa.ui.lib.Lineage; import com.molnarandrei.sopa.wsdl.WsdlValidations; @@ -95,7 +94,15 @@ public class SoapJob extends LinkedList implements Runnable { private boolean request(SoapCall call) { var stepPath = call.getPath(); - if (!applyProperties(call)) return false; + var notCalled = applyProperties(call); + if (notCalled != null) { + CallLogService.save(stepPath, new CallLog(stepPath, notCalled, 0, CallLog.Result.notCalled)); + Events.emit(new SoapCallEvent( + SoapCallEvent.FINISHED, + new SoapCallEvent.StepAndEndpoint(stepPath, call.getEndpoint()) + )); + return false; + } var endpoint = call.getEndpoint(); try { Events.emit(new SoapCallEvent( @@ -170,10 +177,11 @@ public class SoapJob extends LinkedList implements Runnable { return true; } - private static boolean applyProperties(SoapCall call) { + /** @return null when the call can be made, else why not. */ + private static String applyProperties(SoapCall call) { try { call.applyProperties(); - return true; + return null; } catch (RepositoryException readOrParseErr) { log.log(Level.WARNING, "Cannot read properties for step %s".formatted(call.getPath()), readOrParseErr); Utils.alert( @@ -182,6 +190,7 @@ public class SoapJob extends LinkedList implements Runnable { .formatted(readOrParseErr.getPath()), readOrParseErr.getMessage() ); + return "No se han podido leer las propiedades: %s\n%s".formatted(readOrParseErr.getPath(), readOrParseErr.getMessage()); } catch (PropertyMissingException prop) { log.warning("Property %s missing for step %s".formatted(prop.getMissingKey(), call.getPath())); Utils.alert( @@ -190,6 +199,7 @@ public class SoapJob extends LinkedList implements Runnable { "No podemos realizar la llamada SOAP:\n%s".formatted(Lineage.withPath(Kind.step, call.getPath())), "Falta la propiedad: %s".formatted(prop.getMissingKey()) ); + return "Falta la propiedad: %s".formatted(prop.getMissingKey()); } catch (MalformedEndpointException malformed) { log.warning("Malformed endpoint %s for step %s".formatted(malformed.getEndpoint(), call.getPath())); Utils.alert( @@ -199,8 +209,8 @@ public class SoapJob extends LinkedList implements Runnable { .formatted(malformed.getEndpoint()), malformed.getMessage() ); + return "El endpoint no es válido: %s\n%s".formatted(malformed.getEndpoint(), malformed.getMessage()); } - return false; } private static boolean applyExtractions(SoapCall call, HttpResponse httpResponse) { @@ -236,12 +246,8 @@ public class SoapJob extends LinkedList implements Runnable { } log.info("Extraction result: %s".formatted(extracted)); - var testCase = TestCaseService.read(call.getTestCasePath()); - var project = ProjectService.read(call.getProjectPath()); - if (testCase == null || project == null) return false; - - var testCaseProperties = new HashMap<>(testCase.getProperties()); - var projectProperties = new HashMap<>(project.getProperties()); + var testCaseProperties = PropertiesService.read(call.getTestCasePath()); + var projectProperties = PropertiesService.read(call.getProjectPath()); var testCaseUpdated = false; var projectUpdated = false; for (var entry : extracted.entrySet()) { @@ -258,14 +264,8 @@ public class SoapJob extends LinkedList implements Runnable { } } - if (testCaseUpdated) { - testCase.setProperties(testCaseProperties); - TestCaseService.write(call.getTestCasePath(), testCase); - } - if (projectUpdated) { - project.setProperties(projectProperties); - ProjectService.write(call.getProjectPath(), project); - } + if (testCaseUpdated) PropertiesService.write(call.getTestCasePath(), testCaseProperties); + if (projectUpdated) PropertiesService.write(call.getProjectPath(), projectProperties); return true; } diff --git a/src/main/java/com/molnarandrei/sopa/soap/SoapService.java b/src/main/java/com/molnarandrei/sopa/soap/SoapService.java index 2c509d8..ff88040 100644 --- a/src/main/java/com/molnarandrei/sopa/soap/SoapService.java +++ b/src/main/java/com/molnarandrei/sopa/soap/SoapService.java @@ -2,6 +2,7 @@ package com.molnarandrei.sopa.soap; import com.molnarandrei.sopa.Utils; import com.molnarandrei.sopa.data.RepositoryException; +import com.molnarandrei.sopa.project.ProjectRepository; import com.molnarandrei.sopa.step.StepRepository; import com.molnarandrei.sopa.testcase.TestCaseRepository; import javafx.scene.control.Alert; @@ -71,6 +72,14 @@ public class SoapService { } } + public static void createAndStartCallsForProject(Path projectPath) { + try { + createAndStartStepCalls(ProjectRepository.getPathsOfContainedSteps(projectPath)); + } catch (RepositoryException readOrParseErr) { + alert(readOrParseErr); + } + } + private static void stopJobsOverlapping(SoapJob job) { for (var call : job) { var running = currentlyRunningJobsByPath.get(call.getPath()); diff --git a/src/main/java/com/molnarandrei/sopa/step/StepRepository.java b/src/main/java/com/molnarandrei/sopa/step/StepRepository.java index 0abc6f9..987d49e 100644 --- a/src/main/java/com/molnarandrei/sopa/step/StepRepository.java +++ b/src/main/java/com/molnarandrei/sopa/step/StepRepository.java @@ -50,12 +50,20 @@ public class StepRepository { } } - public static void update(Path stepPath, Step step) throws RepositoryException{ + /** @return the content it replaced, null when the file was new or already held it. */ + public static String update(Path stepPath, Step step) throws RepositoryException { + return overwrite(stepPath, Yaml.toYaml(step)); + } + + /** Writes {@code content} as the step file, unless it already holds it. @return as {@link #update}. */ + public static String overwrite(Path stepPath, String content) throws RepositoryException { try { - var yaml = Yaml.toYaml(step); - Files.writeString(stepPath, yaml); + var previous = Files.exists(stepPath) ? Files.readString(stepPath) : null; + if (content.equals(previous)) return null; + Files.writeString(stepPath, content); FileSystemCache.remove(stepPath); ProjectMonitors.trigger(stepPath.getParent().getParent().getParent()); + return previous; } catch (IOException io) { throw new RepositoryException(stepPath, "Cannot write step", io); } diff --git a/src/main/java/com/molnarandrei/sopa/step/StepService.java b/src/main/java/com/molnarandrei/sopa/step/StepService.java index a4321b1..b05aadf 100644 --- a/src/main/java/com/molnarandrei/sopa/step/StepService.java +++ b/src/main/java/com/molnarandrei/sopa/step/StepService.java @@ -2,13 +2,10 @@ package com.molnarandrei.sopa.step; import com.molnarandrei.sopa.data.yaml.Kind; -import com.molnarandrei.sopa.trash.TrashService; +import com.molnarandrei.sopa.undo.Undo; import com.molnarandrei.sopa.Utils; import com.molnarandrei.sopa.data.RepositoryException; import com.molnarandrei.sopa.data.yaml.Step; -import com.molnarandrei.sopa.ui.lib.Lineage; -import com.molnarandrei.sopa.ui.lib.Packing; -import javafx.scene.control.TextInputDialog; import java.io.IOException; import java.nio.file.Files; @@ -52,13 +49,6 @@ public class StepService { } public static void create(Path testCasePath) { - var input = Packing.pack(new TextInputDialog()); - input.setTitle("Crear paso en prueba"); - input.setHeaderText(Lineage.withPath(Kind.testcase, testCasePath)); - input.setContentText("Nombre del paso:"); - var name = input.showAndWait().orElse(""); - if (name.isBlank()) return; - var stepFolderPath = testCasePath.getParent().resolve("step-1"); if (Files.exists(stepFolderPath)) stepFolderPath = renameIndexed(stepFolderPath); @@ -74,7 +64,7 @@ public class StepService { ); return; } - var step = new Step(name); + var step = new Step("nuevo paso"); write(stepFolderPath.resolve("step.yml"), step); } @@ -85,7 +75,7 @@ public class StepService { entry.getValue() == null || entry.getValue().isBlank() ); try { - StepRepository.update(stepPath, step); + Undo.modified(Kind.step, stepPath, StepRepository.update(stepPath, step)); return true; } catch (RepositoryException cannotWrite) { log.log(Level.SEVERE, "Cannot write step %s.".formatted(stepPath), cannotWrite); @@ -99,6 +89,23 @@ public class StepService { } } + /** Puts back what {@code stepPath} held, undoing a {@link #write}. Returns whether it was written. */ + public static boolean overwrite(Path stepPath, String content) { + log.info("Undoing changes to step %s.".formatted(stepPath)); + try { + StepRepository.overwrite(stepPath, content); + return true; + } catch (RepositoryException cannotWrite) { + log.log(Level.WARNING, "Cannot undo changes to step %s.".formatted(stepPath), cannotWrite); + Utils.alert( + "No se puede deshacer", + "No se ha podido restaurar el paso:\n%s".formatted(stepPath), + cannotWrite.getMessage() + ); + return false; + } + } + /** * Writes a new step with the contents of {@code stepPath} after the last step of * {@code toTestCasePath}, its name followed by {@code nameSuffix}. Only the step itself is @@ -213,11 +220,11 @@ public class StepService { } } - /** Moves the step to the trash: {@link TrashService#undo()} restores it. */ + /** Moves the step to the trash: {@link Undo#undo()} restores it. */ public static void delete(Path stepPath) { log.info("Deleting step %s.".formatted(stepPath)); try { - TrashService.remember(Kind.step, stepPath, StepRepository.trash(stepPath)); + Undo.deleted(Kind.step, stepPath, StepRepository.trash(stepPath)); } catch (RepositoryException readWriteParseError) { log.log(Level.SEVERE, "Cannot delete step %s.".formatted(stepPath), readWriteParseError); Utils.alert( diff --git a/src/main/java/com/molnarandrei/sopa/testcase/TestCaseRepository.java b/src/main/java/com/molnarandrei/sopa/testcase/TestCaseRepository.java index 1edaddd..8dcd904 100644 --- a/src/main/java/com/molnarandrei/sopa/testcase/TestCaseRepository.java +++ b/src/main/java/com/molnarandrei/sopa/testcase/TestCaseRepository.java @@ -44,12 +44,20 @@ public class TestCaseRepository { } } - public static void update(Path testCasePath, TestCase testCase) throws RepositoryException { + /** @return the content it replaced, null when the file was new or already held it. */ + public static String update(Path testCasePath, TestCase testCase) throws RepositoryException { + return overwrite(testCasePath, Yaml.toYaml(testCase)); + } + + /** Writes {@code content} as the testcase file, unless it already holds it. @return as {@link #update}. */ + public static String overwrite(Path testCasePath, String content) throws RepositoryException { try { - var yaml = Yaml.toYaml(testCase); - Files.writeString(testCasePath, yaml); + var previous = Files.exists(testCasePath) ? Files.readString(testCasePath) : null; + if (content.equals(previous)) return null; + Files.writeString(testCasePath, content); FileSystemCache.remove(testCasePath); ProjectMonitors.trigger(testCasePath.getParent().getParent()); + return previous; } catch (IOException io) { throw new RepositoryException(testCasePath, "Cannot write testcase", io); } diff --git a/src/main/java/com/molnarandrei/sopa/testcase/TestCaseService.java b/src/main/java/com/molnarandrei/sopa/testcase/TestCaseService.java index 97efaf6..08ecd0a 100644 --- a/src/main/java/com/molnarandrei/sopa/testcase/TestCaseService.java +++ b/src/main/java/com/molnarandrei/sopa/testcase/TestCaseService.java @@ -1,14 +1,11 @@ package com.molnarandrei.sopa.testcase; import com.molnarandrei.sopa.data.yaml.Kind; -import com.molnarandrei.sopa.trash.TrashService; +import com.molnarandrei.sopa.undo.Undo; import com.molnarandrei.sopa.step.StepService; import com.molnarandrei.sopa.Utils; import com.molnarandrei.sopa.data.RepositoryException; import com.molnarandrei.sopa.data.yaml.TestCase; -import com.molnarandrei.sopa.ui.lib.Lineage; -import com.molnarandrei.sopa.ui.lib.Packing; -import javafx.scene.control.TextInputDialog; import java.io.IOException; import java.nio.file.Files; @@ -53,13 +50,6 @@ public class TestCaseService { } public static void create(Path projectPath) { - var input = Packing.pack(new TextInputDialog()); - input.setTitle("Crear caso de prueba"); - input.setHeaderText(Lineage.withPath(Kind.project, projectPath)); - input.setContentText("Nombre del caso:"); - var name = input.showAndWait().orElse(""); - if (name.isBlank()) return; - var testCaseDirectory = projectPath.getParent().resolve("testcase-1"); if (Files.exists(testCaseDirectory)) testCaseDirectory = renameIndexed(testCaseDirectory); @@ -75,19 +65,19 @@ public class TestCaseService { ); return; } - var testCase = new TestCase(name); + var testCase = new TestCase("nuevo caso"); write(testCaseDirectory.resolve("testcase.yml"), testCase); } - /** Writes the testcase, alerting on failure. Returns whether it was written. */ + /** Writes the testcase, alerting on failure; {@link Undo#undo()} puts back what it held. Returns whether it was written. */ public static boolean write(Path testCasePath, TestCase testCase) { testCase.getHeaders().entrySet().removeIf(entry -> entry.getKey() == null || entry.getKey().isBlank() || entry.getValue() == null || entry.getValue().isBlank() ); try { - TestCaseRepository.update(testCasePath, testCase); + Undo.modified(Kind.testcase, testCasePath, TestCaseRepository.update(testCasePath, testCase)); return true; } catch (RepositoryException cannotWrite) { log.log(Level.SEVERE, "Cannot write testcase %s.".formatted(testCasePath), cannotWrite); @@ -101,6 +91,23 @@ public class TestCaseService { } } + /** Puts back what {@code testCasePath} held, undoing a {@link #write}. Returns whether it was written. */ + public static boolean overwrite(Path testCasePath, String content) { + log.info("Undoing changes to testcase %s.".formatted(testCasePath)); + try { + TestCaseRepository.overwrite(testCasePath, content); + return true; + } catch (RepositoryException cannotWrite) { + log.log(Level.WARNING, "Cannot undo changes to testcase %s.".formatted(testCasePath), cannotWrite); + Utils.alert( + "No se puede deshacer", + "No se ha podido restaurar el caso:\n%s".formatted(testCasePath), + cannotWrite.getMessage() + ); + return false; + } + } + /** * Writes a new testcase with the contents of {@code testCasePath} into {@code toProjectPath}, * followed by a copy of each of its steps in the same order. Only the testcase gets @@ -211,11 +218,11 @@ public class TestCaseService { } - /** Moves the testcase, with its steps, to the trash: {@link TrashService#undo()} restores it. */ + /** Moves the testcase, with its steps, to the trash: {@link Undo#undo()} restores it. */ public static void delete(Path testCasePath) { log.info("Deleting testcase %s.".formatted(testCasePath)); try { - TrashService.remember(Kind.testcase, testCasePath, TestCaseRepository.trash(testCasePath)); + Undo.deleted(Kind.testcase, testCasePath, TestCaseRepository.trash(testCasePath)); } catch (RepositoryException cannotDeleteAllFiles) { log.log(Level.WARNING, "Delete testcase error %s.".formatted(testCasePath), cannotDeleteAllFiles); Utils.alert( diff --git a/src/main/java/com/molnarandrei/sopa/trash/TrashService.java b/src/main/java/com/molnarandrei/sopa/trash/TrashService.java deleted file mode 100644 index 6d6df86..0000000 --- a/src/main/java/com/molnarandrei/sopa/trash/TrashService.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.molnarandrei.sopa.trash; - -import com.molnarandrei.sopa.data.yaml.Kind; -import com.molnarandrei.sopa.project.ProjectService; -import com.molnarandrei.sopa.step.StepService; -import com.molnarandrei.sopa.testcase.TestCaseService; - -import java.nio.file.Path; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.logging.Logger; - -/** - * The deletions of this session, to undo them latest first. - * The services of each kind delete into the trash and restore from it. - */ -public class TrashService { - private static final Logger log = Logger.getLogger(TrashService.class.getName()); - - /** - * @param path the yml of the deleted object, where it is restored. - * @param kept the folder of the object inside the trash. - */ - public record Deleted(Kind kind, Path path, Path kept) {} - - private static final Deque deleted = new ArrayDeque<>(); - - /** Called by the services once they moved {@code path} to the trash, kept at {@code kept}. */ - public static synchronized void remember(Kind kind, Path path, Path kept) { - deleted.push(new Deleted(kind, path, kept)); - } - - public static synchronized boolean canUndo() { - return ! deleted.isEmpty(); - } - - /** - * Restores the last deletion through the service of its kind. It stays to undo when it cannot be restored, - * as when its place is taken or its parent is gone. - * - * @return the restored deletion, null when there is none or it could not be restored. - */ - public static synchronized Deleted undo() { - var last = deleted.peek(); - if (last == null) { - log.info("Nothing to undo."); - return null; - } - var restored = switch (last.kind()) { - case project -> ProjectService.restore(last.path(), last.kept()); - case testcase -> TestCaseService.restore(last.path(), last.kept()); - case step -> StepService.restore(last.path(), last.kept()); - }; - if (! restored) return null; - deleted.pop(); - return last; - } -} diff --git a/src/main/java/com/molnarandrei/sopa/ui/PropertiesDialog.java b/src/main/java/com/molnarandrei/sopa/ui/PropertiesDialog.java index 83ce8cd..6bbca6d 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/PropertiesDialog.java +++ b/src/main/java/com/molnarandrei/sopa/ui/PropertiesDialog.java @@ -4,14 +4,14 @@ import atlantafx.base.controls.Spacer; import atlantafx.base.theme.Styles; import com.molnarandrei.sopa.data.yaml.Config; import com.molnarandrei.sopa.data.yaml.Kind; -import com.molnarandrei.sopa.data.yaml.Project; -import com.molnarandrei.sopa.data.yaml.TestCase; import com.molnarandrei.sopa.events.Events; import com.molnarandrei.sopa.events.ProjectTreeViewEvent; -import com.molnarandrei.sopa.events.SoapCallEvent; +import com.molnarandrei.sopa.events.PropertiesEvent; import com.molnarandrei.sopa.project.ProjectService; +import com.molnarandrei.sopa.properties.PropertiesService; import com.molnarandrei.sopa.testcase.TestCaseService; import com.molnarandrei.sopa.ui.editor.Destroyable; +import com.molnarandrei.sopa.ui.lib.Shortcuts; import javafx.event.EventHandler; import javafx.geometry.Bounds; import javafx.geometry.Insets; @@ -50,9 +50,10 @@ public class PropertiesDialog extends Stage implements Destroyable { private Kind kind; private Path projectPath; - private Project project; + private Map projectProperties; + /** Null without a testcase. */ private Path testCasePath; - private TestCase testCase; + private Map testCaseProperties; private final Label title; private final GridPane grid; @@ -63,7 +64,7 @@ public class PropertiesDialog extends Stage implements Destroyable { private record Row(TextField key, TextField value, Button remove) {} private final EventHandler selectionHandler = this::onSelection; - private final EventHandler callFinishedHandler = this::onCallFinished; + private final EventHandler propertiesHandler = this::onPropertiesFile; /** * @param owner main window, the dialog floats above it. @@ -113,6 +114,7 @@ public class PropertiesDialog extends Stage implements Destroyable { root.setCenter(scroll); root.setBottom(bottom); BorderPane.setMargin(bottom, new Insets(8, 0, 0, 0)); + Shortcuts.on(root, Shortcuts.SAVE, this::save); var config = Config.get(); var width = config.getPropertiesDialogWidth() != null ? config.getPropertiesDialogWidth() : DEFAULT_WIDTH; @@ -133,7 +135,9 @@ public class PropertiesDialog extends Stage implements Destroyable { }); Events.addListener(ProjectTreeViewEvent.SELECTED, selectionHandler); - Events.addListener(SoapCallEvent.FINISHED, callFinishedHandler); + Events.addListener(PropertiesEvent.ADDED, propertiesHandler); + Events.addListener(PropertiesEvent.CHANGED, propertiesHandler); + Events.addListener(PropertiesEvent.REMOVED, propertiesHandler); reload(initialPath, initialKind); } @@ -165,8 +169,12 @@ public class PropertiesDialog extends Stage implements Destroyable { reload(identity.path(), identity.kind()); } - private void onCallFinished(SoapCallEvent event) { - reload(null, null); + /** The properties files live next to the yml of their project or testcase. */ + private void onPropertiesFile(PropertiesEvent event) { + var folder = event.get().getParent(); + var shown = (projectPath != null && folder.equals(projectPath.getParent())) + || (testCasePath != null && folder.equals(testCasePath.getParent())); + if (shown) reload(null, null); } /** @@ -178,9 +186,9 @@ public class PropertiesDialog extends Stage implements Destroyable { if (kind != null) this.kind = kind; projectPath = null; - project = null; + projectProperties = null; testCasePath = null; - testCase = null; + testCaseProperties = null; if (this.path == null || this.kind == null) { title.setText("Selecciona un proyecto, caso o paso"); @@ -200,22 +208,15 @@ public class PropertiesDialog extends Stage implements Destroyable { } } - project = ProjectService.read(projectPath); - if (testCasePath != null) - testCase = TestCaseService.read(testCasePath); + projectProperties = PropertiesService.read(projectPath); + var properties = new HashMap<>(projectProperties); + if (testCasePath != null) { + testCaseProperties = PropertiesService.read(testCasePath); + properties.putAll(testCaseProperties); + } - var properties = new HashMap(); - if (project != null && project.getProperties() != null) - properties.putAll(project.getProperties()); - if (testCase != null && testCase.getProperties() != null) - properties.putAll(testCase.getProperties()); - - if (testCase != null) - title.setText("Propiedades de %s".formatted(testCase.getName())); - else if (project != null) - title.setText("Propiedades de %s".formatted(project.getName())); - else - title.setText("Propiedades"); + var name = testCasePath != null ? TestCaseService.nameOf(testCasePath) : ProjectService.nameOf(projectPath); + title.setText("Propiedades de %s".formatted(name)); showProperties(properties); } @@ -224,7 +225,7 @@ public class PropertiesDialog extends Stage implements Destroyable { grid.getChildren().clear(); rows.clear(); new TreeMap<>(properties).forEach(this::addRow); - var editable = project != null; + var editable = projectPath != null; addBtn.setDisable(!editable); saveBtn.setDisable(!editable); } @@ -242,6 +243,7 @@ public class PropertiesDialog extends Stage implements Destroyable { removeBtn.setOnAction(e -> { rows.remove(row); grid.getChildren().removeAll(keyField, valueField, removeBtn); + save(); }); var index = grid.getRowCount(); @@ -257,7 +259,7 @@ public class PropertiesDialog extends Stage implements Destroyable { * Removed keys are removed from both. */ private void save() { - if (project == null) return; + if (projectPath == null) return; var edited = new HashMap(); for (var row : rows) { @@ -266,13 +268,6 @@ public class PropertiesDialog extends Stage implements Destroyable { edited.put(key.strip(), row.value().getText() == null ? "" : row.value().getText()); } - var projectProperties = project.getProperties(); - Map testCaseProperties = testCase == null ? null : testCase.getProperties(); - if (testCase != null && testCaseProperties == null) { - testCaseProperties = new HashMap<>(); - testCase.setProperties(testCaseProperties); - } - var newProject = new HashMap(); var newTestCase = new HashMap(); for (var entry : edited.entrySet()) { @@ -294,15 +289,8 @@ public class PropertiesDialog extends Stage implements Destroyable { newProject.put(entry.getKey(), entry.getValue()); log.info("Saving properties of %s and %s.".formatted(projectPath, testCasePath)); - projectProperties.clear(); - projectProperties.putAll(newProject); - ProjectService.write(projectPath, project); - - if (testCase != null) { - testCaseProperties.clear(); - testCaseProperties.putAll(newTestCase); - TestCaseService.write(testCasePath, testCase); - } + PropertiesService.write(projectPath, newProject); + if (testCasePath != null) PropertiesService.write(testCasePath, newTestCase); reload(null, null); } @@ -310,6 +298,8 @@ public class PropertiesDialog extends Stage implements Destroyable { @Override public void destroy() { Events.removeListener(ProjectTreeViewEvent.SELECTED, selectionHandler); - Events.removeListener(SoapCallEvent.FINISHED, callFinishedHandler); + Events.removeListener(PropertiesEvent.ADDED, propertiesHandler); + Events.removeListener(PropertiesEvent.CHANGED, propertiesHandler); + Events.removeListener(PropertiesEvent.REMOVED, propertiesHandler); } } diff --git a/src/main/java/com/molnarandrei/sopa/ui/SopaApplication.java b/src/main/java/com/molnarandrei/sopa/ui/SopaApplication.java index 7174199..5fa3d50 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/SopaApplication.java +++ b/src/main/java/com/molnarandrei/sopa/ui/SopaApplication.java @@ -6,6 +6,7 @@ import com.molnarandrei.sopa.data.yaml.Config; import com.molnarandrei.sopa.events.Events; import com.molnarandrei.sopa.events.ProjectTreeViewEvent; import com.molnarandrei.sopa.ui.editor.EditorPane; +import com.molnarandrei.sopa.ui.lib.Shortcuts; import com.molnarandrei.sopa.ui.menu.TopMenu; import com.molnarandrei.sopa.ui.navpane.ProjectPane; import javafx.application.Application; @@ -48,6 +49,7 @@ public class SopaApplication extends Application { root.setTop(new TopMenu()); root.setCenter(split); + Shortcuts.on(root, Shortcuts.NEW, left::createInSelected); var scene = new Scene(root, 800, 500); stage.setTitle("Sopa"); stage.setScene(scene); diff --git a/src/main/java/com/molnarandrei/sopa/ui/create/CreateProjectDialog.java b/src/main/java/com/molnarandrei/sopa/ui/create/CreateProjectDialog.java index c5e2848..e62c808 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/create/CreateProjectDialog.java +++ b/src/main/java/com/molnarandrei/sopa/ui/create/CreateProjectDialog.java @@ -2,18 +2,11 @@ package com.molnarandrei.sopa.ui.create; import atlantafx.base.controls.Spacer; import atlantafx.base.theme.Styles; -import com.molnarandrei.sopa.data.yaml.Config; import com.molnarandrei.sopa.data.yaml.Project; import com.molnarandrei.sopa.project.ProjectRepository; import com.molnarandrei.sopa.project.ProjectService; -import com.molnarandrei.sopa.soap.SoapVersion; -import com.molnarandrei.sopa.wsdl.WsdlRemote; -import com.molnarandrei.sopa.wsdl.WsdlService; -import com.molnarandrei.sopa.ui.editor.HeadersPane; import com.molnarandrei.sopa.ui.lib.Packing; -import javafx.application.Platform; import javafx.geometry.Insets; -import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.*; @@ -22,37 +15,24 @@ import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.Window; import org.kordamp.ikonli.javafx.FontIcon; -import org.kordamp.ikonli.materialdesign2.MaterialDesignD; import org.kordamp.ikonli.materialdesign2.MaterialDesignF; import java.nio.file.InvalidPathException; import java.nio.file.Path; -import java.util.HashMap; import java.util.List; import java.util.logging.Logger; +/** Asks for the folder of a new project; everything else is edited afterwards in the project editor. */ public class CreateProjectDialog extends Stage { private static final Logger log = Logger.getLogger(CreateProjectDialog.class.getName()); - private static final int CREATE_WSDL_TIMEOUT_SECONDS = 1; - private final BorderPane form = new BorderPane(); private final TextField pathField = new TextField(); private final Label pathError = new Label("No es una carpeta vacia"); - private final TextField nameField = new TextField(); - private final TextField endpointField = new TextField(); - private final ToggleGroup versionGroup = new ToggleGroup(); - private final CheckBox agentsFileBox = new CheckBox("Crear fichero AGENTS.md para asistencia IA"); - private final HashMap headers = new HashMap<>(); - private final Label status = new Label(); - - private WsdlRemote.Download wsdlOfCurrentEndpoint = null; - private boolean creating = false; public CreateProjectDialog(Window owner) { initOwner(owner); initModality(Modality.WINDOW_MODAL); setTitle("Crear proyecto"); - setOnCloseRequest(e -> { if (creating) e.consume(); }); var title = new Label("Crear proyecto"); Styles.addStyleClass(title, Styles.TITLE_1); @@ -63,7 +43,6 @@ public class CreateProjectDialog extends Stage { var fieldColumn = new ColumnConstraints(); fieldColumn.setHgrow(Priority.ALWAYS); fields.getColumnConstraints().addAll(new ColumnConstraints(), fieldColumn, new ColumnConstraints()); - var row = 0; pathField.setText(Path.of(System.getProperty("user.dir")).toString()); pathField.textProperty().addListener((obs, old, value) -> showPathError(false)); @@ -74,65 +53,24 @@ public class CreateProjectDialog extends Stage { pathField.setOnAction(e -> create()); var choosePath = new Button("", FontIcon.of(MaterialDesignF.FOLDER_OPEN)); choosePath.setOnAction(e -> choosePath()); - fields.add(new Label("Carpeta:"), 0, row); - fields.add(pathField, 1, row); - fields.add(choosePath, 2, row); - row++; + fields.add(new Label("Carpeta:"), 0, 0); + fields.add(pathField, 1, 0); + fields.add(choosePath, 2, 0); Styles.addStyleClass(pathError, Styles.DANGER); pathError.managedProperty().bind(pathError.visibleProperty()); pathError.setVisible(false); - fields.add(pathError, 1, row, 2, 1); - row++; - - nameField.setOnAction(e -> create()); - fields.add(new Label("Nombre:"), 0, row); - fields.add(nameField, 1, row, 2, 1); - row++; - - endpointField.textProperty().addListener((obs, old, value) -> wsdlOfCurrentEndpoint = null); - endpointField.setOnAction(e -> create()); - fields.add(new Label("Endpoint:"), 0, row); - fields.add(endpointField, 1, row, 2, 1); - row++; - - var versions = new HBox(16); - versions.setAlignment(Pos.CENTER_LEFT); - for (var version : SoapVersion.values()) { - var option = new RadioButton("v" + version.getTitle()); - option.setUserData(version); - option.setToggleGroup(versionGroup); - option.setSelected(version == SoapVersion.ONE_ONE); - versions.getChildren().add(option); - } - fields.add(new Label("Versión SOAP:"), 0, row); - fields.add(versions, 1, row, 2, 1); - row++; - - agentsFileBox.setSelected(true); - fields.add(agentsFileBox, 1, row, 2, 1); - - var headersPane = new HeadersPane(headers, this::create); - headersPane.update(); - BorderPane.setMargin(headersPane, new Insets(8, 0, 8, 0)); - - var testDownloadWsdl = new Button("Probar / descargar WSDL", FontIcon.of(MaterialDesignD.DOWNLOAD)); - testDownloadWsdl.setOnAction(e -> testDownloadWsdl()); + fields.add(pathError, 1, 1, 2, 1); var create = new Button("Crear proyecto", FontIcon.of(MaterialDesignF.FOLDER_PLUS)); Styles.addStyleClass(create, Styles.ACCENT); - create.disableProperty().bind(nameField.textProperty().isEmpty()); + create.disableProperty().bind(pathField.textProperty().isEmpty()); create.setOnAction(e -> create()); - status.setWrapText(true); - var actions = new HBox(8, new Spacer(), testDownloadWsdl, create); - + var form = new VBox(8, title, fields, new Separator(), new HBox(8, new Spacer(), create)); form.setPadding(new Insets(16)); - form.setTop(new VBox(8, title, fields)); - form.setCenter(headersPane); - form.setBottom(new VBox(8, new Separator(), status, actions)); - form.setPrefWidth(600); + var scene = new Scene(form); if (owner != null && owner.getScene() != null) scene.getStylesheets().addAll(owner.getScene().getStylesheets()); @@ -147,8 +85,7 @@ public class CreateProjectDialog extends Stage { if (chosen == null) return; pathField.setText(chosen.toPath().toString()); - if (checkPath() && nameField.getText().isBlank()) - nameField.setText(chosen.getName().replaceAll("_", " ").replaceAll("-", " ")); + checkPath(); } private boolean checkPath() { @@ -168,101 +105,11 @@ public class CreateProjectDialog extends Stage { pathError.setVisible(error); } - private void testDownloadWsdl() { - var endpoint = endpointField.getText(); - showStatus("Descargando WSDL...", null); - form.setDisable(true); - Thread.ofVirtual().start(() -> { - WsdlRemote.Download downloaded = null; - String failure = null; - try { - downloaded = WsdlRemote.download(endpoint, Config.get().getCallTimeout()); - } catch (Exception cannotDownload) { - failure = cannotDownload.getMessage() != null ? cannotDownload.getMessage() : cannotDownload.toString(); - } - - var result = downloaded; - var error = failure; - Platform.runLater(() -> { - if (! isShowing()) return; - form.setDisable(false); - if (result == null) { - showStatus("No se ha podido descargar el WSDL: %s".formatted(error), Styles.DANGER); - return; - } - wsdlOfCurrentEndpoint = result; - selectVersion(WsdlService.detectVersion(result.wsdl(), endpoint)); - if (result.failedImports().isEmpty()) - showStatus("WSDL descargado: %s.".formatted(operations(result)), Styles.SUCCESS); - else - showStatus( - "WSDL descargado: %s, pero faltan esquemas importados: %s" - .formatted(operations(result), result.failedImports()), - Styles.WARNING - ); - }); - }); - } - - /** Selects the version the WSDL declares; leaves the selection when it declares none. */ - private void selectVersion(SoapVersion version) { - if (version == null) return; - for (var toggle : versionGroup.getToggles()) - if (toggle.getUserData() == version) versionGroup.selectToggle(toggle); - } - - private static String operations(WsdlRemote.Download download) { - var count = WsdlService.operationCount(download); - return count == 1 ? "1 operación" : "%d operaciones".formatted(count); - } - private void create() { - if (nameField.getText().isBlank() || ! checkPath()) return; + if (! checkPath()) return; var directory = Path.of(pathField.getText().strip()).toAbsolutePath(); - var endpoint = endpointField.getText(); - var held = wsdlOfCurrentEndpoint; - var createAgentsFile = agentsFileBox.isSelected(); - var project = new Project(nameField.getText(), List.of(), headers, new HashMap<>()); - project.putEndpoint(endpoint, (SoapVersion) versionGroup.getSelectedToggle().getUserData()); - - showLoader(); - Thread.ofVirtual().start(() -> { - var download = held != null ? held : downloadIgnoringFailure(endpoint); - // A WSDL tested before creating already selected its version, which may have been changed since. - var detected = held == null && download != null ? WsdlService.detectVersion(download.wsdl(), endpoint) : null; - if (detected != null) project.putEndpoint(endpoint, detected); - var created = ProjectService.create(directory, project, createAgentsFile); - if (created && download != null) - WsdlService.write(directory.resolve("project.yml"), endpoint, download); - - Platform.runLater(() -> { - creating = false; - if (created) close(); - else getScene().setRoot(form); - }); - }); - } - - private static WsdlRemote.Download downloadIgnoringFailure(String endpoint) { - try { - return WsdlRemote.download(endpoint, CREATE_WSDL_TIMEOUT_SECONDS); - } catch (Exception cannotDownload) { - log.info("Creating project without WSDL: %s".formatted(cannotDownload)); - return null; - } - } - - private void showLoader() { - creating = true; - var loader = new StackPane(new ProgressBar(ProgressIndicator.INDETERMINATE_PROGRESS)); - loader.setAlignment(Pos.CENTER); - getScene().setRoot(loader); - } - - private void showStatus(String text, String style) { - status.setText(text); - status.getStyleClass().removeAll(Styles.SUCCESS, Styles.WARNING, Styles.DANGER); - if (style != null) status.getStyleClass().add(style); + if (ProjectService.create(directory, new Project(directory.getFileName().toString(), List.of()), true)) + close(); } } diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/EditorPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/EditorPane.java index b6264b7..8b5df56 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/editor/EditorPane.java +++ b/src/main/java/com/molnarandrei/sopa/ui/editor/EditorPane.java @@ -1,6 +1,7 @@ package com.molnarandrei.sopa.ui.editor; import com.molnarandrei.sopa.data.yaml.Kind; +import com.molnarandrei.sopa.data.yaml.Yaml; import com.molnarandrei.sopa.events.*; import com.molnarandrei.sopa.project.ProjectService; import com.molnarandrei.sopa.step.StepService; @@ -25,6 +26,8 @@ public class EditorPane extends StackPane { private Kind activeKind; private Path activePath; + /** The project, testcase or step the editor edits. */ + private Object shown; private final ScrollPane scrollPane; private double lastScrollPosition = 0; @@ -62,11 +65,22 @@ public class EditorPane extends StackPane { private void onChanged(Path changed) { if (activePath == null) return; + // Its own saves leave the editor as it is: rebuilding it would take the focus from the field being edited. + if (changed.equals(activePath) && showsSaved()) return; var folder = Files.isDirectory(changed) ? changed : changed.getParent(); if (activePath.startsWith(folder)) load(activeKind, activePath); } + private boolean showsSaved() { + Object saved = switch (activeKind) { + case project -> ProjectService.read(activePath); + case testcase -> TestCaseService.read(activePath); + case step -> StepService.read(activePath); + }; + return saved != null && Yaml.sameContent(saved, shown); + } + private void onSelectionChanged(ProjectTreeViewEvent event) { clear(); activeKind = event.get().kind(); @@ -123,6 +137,7 @@ public class EditorPane extends StackPane { private void loadProject(Path projectPath) { var project = ProjectService.read(projectPath); if (project == null) return; + shown = project; var editor = new ProjectEditorPane(projectPath, project); setContent(editor); } @@ -131,6 +146,7 @@ public class EditorPane extends StackPane { private void loadTestCase(Path testCasePath) { var testCase = TestCaseService.read(testCasePath); if (testCase == null) return; + shown = testCase; var editor = new TestCaseEditorPane(testCasePath, testCase); setContent(editor); } @@ -139,6 +155,7 @@ public class EditorPane extends StackPane { private void loadStep(Path stepPath) { var step = StepService.read(stepPath); if (step == null) return; + shown = step; var editor = new StepEditorPane(stepPath, step); setContent(editor); } diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/EndpointsPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/EndpointsPane.java index f86e99f..81ed57c 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/editor/EndpointsPane.java +++ b/src/main/java/com/molnarandrei/sopa/ui/editor/EndpointsPane.java @@ -1,5 +1,6 @@ package com.molnarandrei.sopa.ui.editor; +import com.molnarandrei.sopa.ui.lib.Commit; import atlantafx.base.theme.Styles; import com.molnarandrei.sopa.data.yaml.Endpoint; import com.molnarandrei.sopa.soap.SoapVersion; @@ -49,7 +50,7 @@ public class EndpointsPane extends GridPane { /** * @param endpoints kept equal to the non blank fields, stripped, with the version of their row. - * @param onSubmit called when enter is pressed on any endpoint field, and when a version changes. + * @param onSubmit called when enter is pressed on any endpoint field, when a version changes and when an endpoint is removed. */ public EndpointsPane(Path projectPath, Map endpoints, Runnable onSubmit) { this.projectPath = projectPath; @@ -92,7 +93,7 @@ public class EndpointsPane extends GridPane { var row = endpointsGrid.getRowCount(); var field = new TextField(endpoint); field.setPromptText("http://host/servicio"); - field.setOnAction(e -> onSubmit.run()); + Commit.onCommit(field, onSubmit); field.textProperty().addListener((obs, old, value) -> sync()); var wsdl = new EndpointWsdl(projectPath, null, field); @@ -124,6 +125,7 @@ public class EndpointsPane extends GridPane { endpointsGrid.getChildren().removeAll(cells); rows.remove(current); sync(); + onSubmit.run(); }); return field; } diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/HeadersPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/HeadersPane.java index 476c2b4..9c80995 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/editor/HeadersPane.java +++ b/src/main/java/com/molnarandrei/sopa/ui/editor/HeadersPane.java @@ -1,5 +1,6 @@ package com.molnarandrei.sopa.ui.editor; +import com.molnarandrei.sopa.ui.lib.Commit; import atlantafx.base.theme.Styles; import javafx.geometry.HPos; import javafx.geometry.Insets; @@ -24,7 +25,7 @@ public class HeadersPane extends GridPane { private final Runnable onSubmit; /** - * @param onSubmit called when enter is pressed on any header field. + * @param onSubmit called when enter is pressed on any header field, and when a header is removed. */ public HeadersPane(Map headers, Runnable onSubmit) { this.headers = headers; @@ -87,8 +88,8 @@ public class HeadersPane extends GridPane { keyField.setPromptText("llave"); valueField.setPromptText("valor"); - keyField.setOnAction(e -> onSubmit.run()); - valueField.setOnAction(e -> onSubmit.run()); + Commit.onCommit(keyField, onSubmit); + Commit.onCommit(valueField, onSubmit); headersGrid.add(keyField, 0, row); headersGrid.add(valueField, 1, row); @@ -103,6 +104,7 @@ public class HeadersPane extends GridPane { removeBtn.setOnAction(e->{ headers.remove(keyField.getText()); headersGrid.getChildren().removeAll(keyField, valueField, removeBtn); + onSubmit.run(); }); row++; @@ -117,8 +119,8 @@ public class HeadersPane extends GridPane { keyField.setPromptText("llave"); valueField.setPromptText("valor"); - keyField.setOnAction(e -> onSubmit.run()); - valueField.setOnAction(e -> onSubmit.run()); + Commit.onCommit(keyField, onSubmit); + Commit.onCommit(valueField, onSubmit); headersGrid.add(keyField, 0, row); headersGrid.add(valueField, 1, row); @@ -133,6 +135,7 @@ public class HeadersPane extends GridPane { removeBtn.setOnAction(e->{ headers.remove(keyField.getText()); headersGrid.getChildren().removeAll(keyField, valueField, removeBtn); + onSubmit.run(); }); } diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/ProjectEditorPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/ProjectEditorPane.java index dd2ee54..703c02c 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/editor/ProjectEditorPane.java +++ b/src/main/java/com/molnarandrei/sopa/ui/editor/ProjectEditorPane.java @@ -1,14 +1,13 @@ package com.molnarandrei.sopa.ui.editor; -import atlantafx.base.controls.Spacer; +import com.molnarandrei.sopa.ui.lib.Commit; import atlantafx.base.theme.Styles; import com.molnarandrei.sopa.data.yaml.Project; import com.molnarandrei.sopa.project.ProjectService; +import com.molnarandrei.sopa.ui.lib.Shortcuts; import javafx.geometry.Insets; import javafx.scene.control.*; import javafx.scene.layout.*; -import org.kordamp.ikonli.javafx.FontIcon; -import org.kordamp.ikonli.materialdesign2.*; import java.nio.file.Path; @@ -21,6 +20,7 @@ public class ProjectEditorPane extends BorderPane implements Destroyable { public ProjectEditorPane(Path projectPath, Project project) { Runnable submit = ()-> ProjectService.write(projectPath, project); + Shortcuts.on(this, Shortcuts.SAVE, submit); var top = new VBox(8); setTop(top); @@ -39,8 +39,11 @@ public class ProjectEditorPane extends BorderPane implements Destroyable { var row = 0; nameField = new TextField(""); - nameField.textProperty().addListener((obs, old, value) -> project.setName(value)); - nameField.setOnAction(e -> submit.run()); + nameField.textProperty().addListener((obs, old, value) -> { + project.setName(value); + title.setText("Proyecto %s".formatted(value)); + }); + Commit.onCommit(nameField, submit); fields.add(new Label("Nombre:"), 0, row); fields.add(nameField, 1, row); row++; @@ -53,18 +56,6 @@ public class ProjectEditorPane extends BorderPane implements Destroyable { setMargin(headersPane, new Insets(8, 0, 8, 0)); setCenter(headersPane); - var bottom = new VBox(8); - setBottom(bottom); - bottom.getChildren().add(new Separator()); - - var actions = new HBox(8); - bottom.getChildren().add(actions); - actions.getChildren().add(new Spacer()); - - var save = new Button("Guardar cambios", FontIcon.of(MaterialDesignC.CONTENT_SAVE)); - save.setOnAction(e-> submit.run()); - actions.getChildren().add(save); - loadProject(project); } diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/TestCaseEditorPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/TestCaseEditorPane.java index 73bb239..629ed0c 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/editor/TestCaseEditorPane.java +++ b/src/main/java/com/molnarandrei/sopa/ui/editor/TestCaseEditorPane.java @@ -1,6 +1,6 @@ package com.molnarandrei.sopa.ui.editor; -import atlantafx.base.controls.Spacer; +import com.molnarandrei.sopa.ui.lib.Commit; import atlantafx.base.controls.ToggleSwitch; import atlantafx.base.theme.Styles; import com.molnarandrei.sopa.data.yaml.TestCase; @@ -9,11 +9,10 @@ import com.molnarandrei.sopa.events.SopaEvent; import com.molnarandrei.sopa.events.UiEvent; import com.molnarandrei.sopa.project.ProjectService; import com.molnarandrei.sopa.testcase.TestCaseService; +import com.molnarandrei.sopa.ui.lib.Shortcuts; import javafx.geometry.Insets; import javafx.scene.control.*; import javafx.scene.layout.*; -import org.kordamp.ikonli.javafx.FontIcon; -import org.kordamp.ikonli.materialdesign2.MaterialDesignC; import java.nio.file.Path; @@ -31,6 +30,7 @@ public class TestCaseEditorPane extends BorderPane implements Destroyable { public TestCaseEditorPane(Path testCasePath, TestCase testCase) { Runnable submit = ()-> TestCaseService.write(testCasePath, testCase); + Shortcuts.on(this, Shortcuts.SAVE, submit); var projectPath = testCasePath.getParent().getParent().resolve("project.yml"); var top = new VBox(8); @@ -51,15 +51,18 @@ public class TestCaseEditorPane extends BorderPane implements Destroyable { fields.add(new Label("Nombre:"), 0, row); nameField = new TextField(""); - nameField.textProperty().addListener((obs, old, value) -> testCase.setName(value)); - nameField.setOnAction(e -> submit.run()); + nameField.textProperty().addListener((obs, old, value) -> { + testCase.setName(value); + title.setText("Caso %s".formatted(value)); + }); + Commit.onCommit(nameField, submit); fields.add(nameField, 1, row); row++; fields.add(new Label("Endpoint:"), 0, row); endpointField = new TextField(""); endpointField.textProperty().addListener((obs, old, value) -> testCase.setEndpoint(value)); - endpointField.setOnAction(e -> submit.run()); + Commit.onCommit(endpointField, submit); fields.add(endpointField, 1, row); wsdl = new EndpointWsdl(projectPath, testCasePath, endpointField); fields.add(wsdl.selectEndpointButton(), 2, row); @@ -68,7 +71,7 @@ public class TestCaseEditorPane extends BorderPane implements Destroyable { fields.add(new Label("Accion:"), 0, row); actionField = new TextField(""); actionField.textProperty().addListener((obs, old, value) -> testCase.setAction(value)); - actionField.setOnAction(e -> submit.run()); + Commit.onCommit(actionField, submit); fields.add(actionField, 1, row); fields.add(wsdl.selectActionButton(testCasePath), 2, row); row++; @@ -93,12 +96,6 @@ public class TestCaseEditorPane extends BorderPane implements Destroyable { }); actions.getChildren().add(activeToggle); - actions.getChildren().add(new Spacer()); - - var save = new Button("Guardar cambios", FontIcon.of(MaterialDesignC.CONTENT_SAVE)); - save.setOnAction(e-> submit.run()); - actions.getChildren().add(save); - loadTestCase(testCase); loadParent(projectPath); diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/step/CallDetailsPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/step/CallDetailsPane.java index 40c5242..ba66af7 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/editor/step/CallDetailsPane.java +++ b/src/main/java/com/molnarandrei/sopa/ui/editor/step/CallDetailsPane.java @@ -1,5 +1,6 @@ package com.molnarandrei.sopa.ui.editor.step; +import com.molnarandrei.sopa.ui.lib.Commit; import com.molnarandrei.sopa.data.yaml.Step; import com.molnarandrei.sopa.events.EventListeners; import com.molnarandrei.sopa.events.SopaEvent; @@ -39,14 +40,14 @@ public class CallDetailsPane extends GridPane implements Destroyable { add(new Label("Nombre:"), 0, row); nameField = new TextField(""); nameField.textProperty().addListener((obs, old, value) -> step.setName(value)); - nameField.setOnAction(e -> onSubmit.run()); + Commit.onCommit(nameField, onSubmit); add(nameField, 1, row, 2, 1); row++; add(new Label("Endpoint:"), 0, row); endpointField = new TextField(""); endpointField.textProperty().addListener((obs, old, value) -> step.setEndpoint(value)); - endpointField.setOnAction(e -> onSubmit.run()); + Commit.onCommit(endpointField, onSubmit); add(endpointField, 1, row); var projectPath = stepPath.getParent().getParent().getParent().resolve("project.yml"); var testCasePath = stepPath.getParent().getParent().resolve("testcase.yml"); @@ -57,7 +58,7 @@ public class CallDetailsPane extends GridPane implements Destroyable { add(new Label("Accion:"), 0, row); actionField = new TextField(""); actionField.textProperty().addListener((obs, old, value) -> step.setAction(value)); - actionField.setOnAction(e -> onSubmit.run()); + Commit.onCommit(actionField, onSubmit); add(actionField, 1, row); add(wsdl.selectActionButton(stepPath), 2, row); row++; diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/step/StepAssertionsExtractionsPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/step/StepAssertionsExtractionsPane.java index 5db3443..c8f44a9 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/editor/step/StepAssertionsExtractionsPane.java +++ b/src/main/java/com/molnarandrei/sopa/ui/editor/step/StepAssertionsExtractionsPane.java @@ -1,5 +1,6 @@ package com.molnarandrei.sopa.ui.editor.step; +import com.molnarandrei.sopa.ui.lib.Commit; import atlantafx.base.controls.Spacer; import atlantafx.base.theme.Styles; import com.molnarandrei.sopa.data.yaml.Assertion; @@ -119,7 +120,7 @@ public class StepAssertionsExtractionsPane extends SplitPane { expressionField.setPromptText("expresión"); expressionField.setDisable(WITHOUT_EXPRESSION.contains(assertion.getType())); expressionField.textProperty().addListener((obs, old, value) -> assertion.setExpression(value)); - expressionField.setOnAction(e -> save()); + Commit.onCommit(expressionField, this::save); typeBox.valueProperty().addListener((obs, old, value) -> { assertion.setType(value); @@ -131,12 +132,13 @@ public class StepAssertionsExtractionsPane extends SplitPane { valueField.setPromptText(assertion.getType() == Assertion.Type.soapFault ? "código (opcional)" : "valor"); valueField.setDisable(WITHOUT_VALUE.contains(assertion.getType())); valueField.textProperty().addListener((obs, old, value) -> assertion.setValue(value)); - valueField.setOnAction(e -> save()); + Commit.onCommit(valueField, this::save); var removeBtn = new Button("", FontIcon.of(MaterialDesignD.DELETE)); removeBtn.setOnAction(e -> { step.getAssertions().remove(assertion); assertionsGrid.getChildren().removeAll(typeBox, expressionField, valueField, removeBtn); + save(); }); var index = assertionsGrid.getRowCount(); @@ -150,12 +152,12 @@ public class StepAssertionsExtractionsPane extends SplitPane { var nameField = new TextField(name); nameField.setPromptText("propiedad"); nameField.textProperty().addListener((obs, old, value) -> rebuildExtractionsFromRows()); - nameField.setOnAction(e -> save()); + Commit.onCommit(nameField, this::save); var xPathField = new TextField(xPath); xPathField.setPromptText("xpath"); xPathField.textProperty().addListener((obs, old, value) -> rebuildExtractionsFromRows()); - xPathField.setOnAction(e -> save()); + Commit.onCommit(xPathField, this::save); var removeBtn = new Button("", FontIcon.of(MaterialDesignD.DELETE)); var row = new ExtractionRow(nameField, xPathField); @@ -163,6 +165,7 @@ public class StepAssertionsExtractionsPane extends SplitPane { extractionRows.remove(row); extractionsGrid.getChildren().removeAll(nameField, xPathField, removeBtn); rebuildExtractionsFromRows(); + save(); }); var index = extractionsGrid.getRowCount(); diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/step/StepEditorPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/step/StepEditorPane.java index 61a3ff5..5bdbf6f 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/editor/step/StepEditorPane.java +++ b/src/main/java/com/molnarandrei/sopa/ui/editor/step/StepEditorPane.java @@ -14,13 +14,13 @@ import com.molnarandrei.sopa.step.StepService; import com.molnarandrei.sopa.soap.SoapService; import com.molnarandrei.sopa.wsdl.WsdlService; import com.molnarandrei.sopa.ui.editor.Destroyable; +import com.molnarandrei.sopa.ui.lib.Shortcuts; import com.molnarandrei.sopa.ui.lib.XmlArea; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.scene.control.*; import javafx.scene.layout.*; import org.kordamp.ikonli.javafx.FontIcon; -import org.kordamp.ikonli.materialdesign2.MaterialDesignC; import org.kordamp.ikonli.materialdesign2.MaterialDesignS; import java.nio.file.Path; @@ -43,6 +43,9 @@ public class StepEditorPane extends BorderPane implements Destroyable { private final EventListeners listeners = new EventListeners(); public StepEditorPane(Path stepPath, Step step) { + Runnable submit = ()-> StepService.write(stepPath, step); + Shortcuts.on(this, Shortcuts.SAVE, submit); + var top = new VBox(); setTop(top); @@ -59,8 +62,9 @@ public class StepEditorPane extends BorderPane implements Destroyable { ); top.getChildren().add(detailsTitledPane); - details = new CallDetailsPane(stepPath, step, ()-> StepService.write(stepPath, step)); + details = new CallDetailsPane(stepPath, step, submit); detailsTitledPane.setContent(details); + details.nameField.textProperty().addListener((obs, old, value)-> title.setText("Paso %s".formatted(value))); var assertionsExtractionsTitledPane = new TitledPane(); assertionsExtractionsTitledPane.setText("Aserciones y Extracciones"); @@ -79,6 +83,9 @@ public class StepEditorPane extends BorderPane implements Destroyable { payload.setMinWidth(200d); payload.setXml(""); payload.textProperty().addListener((obs, old, value)-> step.setPayload(value)); + payload.focusedProperty().addListener((obs, old, focused)-> { + if (! focused) submit.run(); + }); responses = new CallLogPane(stepPath); @@ -99,23 +106,15 @@ public class StepEditorPane extends BorderPane implements Destroyable { // Listener added after the initial value, so opening the editor does not save. activeToggle.selectedProperty().addListener((obs, old, value)-> { step.setActive(value); - StepService.write(stepPath, step); + submit.run(); }); bottom.getChildren().add(activeToggle); bottom.getChildren().add(new Spacer()); - var save = new Button("Guardar cambios", FontIcon.of(MaterialDesignC.CONTENT_SAVE)); - save.setOnAction(e-> StepService.write(stepPath, step)); - bottom.getChildren().add(save); - - var separation = new Spacer(); - separation.setMaxWidth(8); - bottom.getChildren().add(separation); - var execute = new Button("Ejecutar", FontIcon.of(MaterialDesignS.SEND)); execute.setOnAction(e-> { - StepService.write(stepPath, step); + submit.run(); SoapService.createAndStartCallForStep(stepPath); }); Styles.addStyleClass(execute, Styles.ACCENT); diff --git a/src/main/java/com/molnarandrei/sopa/ui/lib/Commit.java b/src/main/java/com/molnarandrei/sopa/ui/lib/Commit.java new file mode 100644 index 0000000..9ba58cd --- /dev/null +++ b/src/main/java/com/molnarandrei/sopa/ui/lib/Commit.java @@ -0,0 +1,15 @@ +package com.molnarandrei.sopa.ui.lib; + +import javafx.scene.control.TextField; + +public final class Commit { + private Commit() {} + + /** Runs {@code save} once an edit of {@code field} is done: on enter and when it loses the focus. */ + public static void onCommit(TextField field, Runnable save) { + field.setOnAction(e -> save.run()); + field.focusedProperty().addListener((obs, old, focused) -> { + if (! focused) save.run(); + }); + } +} diff --git a/src/main/java/com/molnarandrei/sopa/ui/lib/Shortcuts.java b/src/main/java/com/molnarandrei/sopa/ui/lib/Shortcuts.java new file mode 100644 index 0000000..16ba8f0 --- /dev/null +++ b/src/main/java/com/molnarandrei/sopa/ui/lib/Shortcuts.java @@ -0,0 +1,23 @@ +package com.molnarandrei.sopa.ui.lib; + +import javafx.scene.Node; +import javafx.scene.input.KeyCode; +import javafx.scene.input.KeyCodeCombination; +import javafx.scene.input.KeyCombination; +import javafx.scene.input.KeyEvent; + +public final class Shortcuts { + public static final KeyCombination SAVE = new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN); + public static final KeyCombination NEW = new KeyCodeCombination(KeyCode.N, KeyCombination.SHORTCUT_DOWN); + + private Shortcuts() {} + + /** Runs {@code action} on {@code keys} pressed anywhere inside {@code node}, whichever descendant has the focus. */ + public static void on(Node node, KeyCombination keys, Runnable action) { + node.addEventFilter(KeyEvent.KEY_PRESSED, event -> { + if (! keys.match(event)) return; + event.consume(); + action.run(); + }); + } +} diff --git a/src/main/java/com/molnarandrei/sopa/ui/navpane/FlightState.java b/src/main/java/com/molnarandrei/sopa/ui/navpane/FlightState.java index 23d6fa5..5da8fed 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/navpane/FlightState.java +++ b/src/main/java/com/molnarandrei/sopa/ui/navpane/FlightState.java @@ -35,7 +35,7 @@ public enum FlightState { return switch (callLog.getResult()) { case success -> success; case exception -> exception; - case assertionsFailed, extractionsFailed -> failed; + case assertionsFailed, extractionsFailed, notCalled -> failed; }; } } diff --git a/src/main/java/com/molnarandrei/sopa/ui/navpane/ProjectPane.java b/src/main/java/com/molnarandrei/sopa/ui/navpane/ProjectPane.java index 031cf18..532c582 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/navpane/ProjectPane.java +++ b/src/main/java/com/molnarandrei/sopa/ui/navpane/ProjectPane.java @@ -3,7 +3,10 @@ package com.molnarandrei.sopa.ui.navpane; import com.molnarandrei.sopa.data.yaml.Kind; import com.molnarandrei.sopa.events.*; import com.molnarandrei.sopa.calllog.CallLogService; -import com.molnarandrei.sopa.trash.TrashService; +import com.molnarandrei.sopa.step.StepService; +import com.molnarandrei.sopa.testcase.TestCaseService; +import com.molnarandrei.sopa.undo.Undo; +import com.molnarandrei.sopa.ui.create.CreateProjectDialog; import javafx.scene.control.Tooltip; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; @@ -72,8 +75,25 @@ public class ProjectPane extends StackPane { treeView.addEventHandler(KeyEvent.KEY_PRESSED, this::onKeyPressed); listeners.addAll(); + } - // TODO when ctrl+n create testcase if project highlighted + /** + * Creates a new item inside the selected one, as the create option of its context menu does: a testcase + * in a project, a step in a testcase, and a step in the testcase of a step. Without a selection it opens + * the dialog to create a project. + */ + public void createInSelected() { + var selectedCell = treeView.getSelectionModel().getSelectedItem(); + if (selectedCell == null || selectedCell.getValue() == null) { + new CreateProjectDialog(getScene().getWindow()).show(); + return; + } + var selected = selectedCell.getValue(); + switch (selected.kind()) { + case project -> TestCaseService.create(selected.path()); + case testcase -> StepService.create(selected.path()); + case step -> StepService.create(selected.path().getParent().getParent().resolve("testcase.yml")); + } } public void destroy() { @@ -82,7 +102,7 @@ public class ProjectPane extends StackPane { private void onKeyPressed(KeyEvent event) { if (UNDO.match(event)) { - TrashService.undo(); + Undo.undo(); event.consume(); return; } diff --git a/src/main/java/com/molnarandrei/sopa/ui/navpane/context/ProjectContextMenu.java b/src/main/java/com/molnarandrei/sopa/ui/navpane/context/ProjectContextMenu.java index bef42b0..c9b8a29 100644 --- a/src/main/java/com/molnarandrei/sopa/ui/navpane/context/ProjectContextMenu.java +++ b/src/main/java/com/molnarandrei/sopa/ui/navpane/context/ProjectContextMenu.java @@ -5,6 +5,7 @@ import com.molnarandrei.sopa.data.yaml.Kind; import com.molnarandrei.sopa.ui.navpane.TreeIdentity; import com.molnarandrei.sopa.project.ProjectService; +import com.molnarandrei.sopa.soap.SoapService; import com.molnarandrei.sopa.step.StepService; import com.molnarandrei.sopa.testcase.TestCaseService; import javafx.scene.control.ContextMenu; @@ -23,9 +24,7 @@ public class ProjectContextMenu extends ContextMenu { var run = new MenuItem( "ejecutar todos los casos", FontIcon.of(MaterialDesignS.SEND)); - run.setOnAction(e->{ - // TODO - }); + run.setOnAction(e-> SoapService.createAndStartCallsForProject(projectPath)); var createCase = new MenuItem( "crear caso de prueba", diff --git a/src/main/java/com/molnarandrei/sopa/undo/Undo.java b/src/main/java/com/molnarandrei/sopa/undo/Undo.java new file mode 100644 index 0000000..5f30135 --- /dev/null +++ b/src/main/java/com/molnarandrei/sopa/undo/Undo.java @@ -0,0 +1,91 @@ +package com.molnarandrei.sopa.undo; + +import com.molnarandrei.sopa.data.yaml.Config; +import com.molnarandrei.sopa.data.yaml.Kind; +import com.molnarandrei.sopa.project.ProjectService; +import com.molnarandrei.sopa.step.StepService; +import com.molnarandrei.sopa.testcase.TestCaseService; + +import java.nio.file.Path; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.logging.Logger; + +/** + * The deletions and modifications of projects, testcases and steps in this session, to undo them latest first. + * The services of each kind remember them and undo them. Only the last {@link Config#getMaxUndo()} are kept. + */ +public class Undo { + private static final Logger log = Logger.getLogger(Undo.class.getName()); + + public sealed interface Change { Kind kind(); Path path(); } + + /** + * @param path the yml of the deleted object, where it is restored. + * @param kept the folder of the object inside the trash. + */ + public record Deleted(Kind kind, Path path, Path kept) implements Change {} + + /** @param content what the yml held before it was written. */ + public record Modified(Kind kind, Path path, String content) implements Change {} + + private static final Deque changes = new ArrayDeque<>(); + /** Unix time in milliseconds of the last change added to the queue. */ + private static long lastAdded = 0; + + /** Called by the services once they moved {@code path} to the trash, kept at {@code kept}. */ + public static void deleted(Kind kind, Path path, Path kept) { + remember(new Deleted(kind, path, kept)); + } + + /** + * Called by the services once they wrote {@code path}; null {@code previous}, for a new or unchanged file, is ignored. + * Consecutive modifications of the same file within {@link Config#getUndoMergeSeconds()} of the first are one + * change: undoing it puts back what the file held before the first. + */ + public static synchronized void modified(Kind kind, Path path, String previous) { + if (previous == null) return; + var recent = System.currentTimeMillis() - lastAdded < Config.get().getUndoMergeSeconds() * 1000L; + if (recent && changes.peek() instanceof Modified last && last.path().equals(path)) return; + remember(new Modified(kind, path, previous)); + } + + private static synchronized void remember(Change change) { + changes.push(change); + lastAdded = System.currentTimeMillis(); + while (changes.size() > Config.get().getMaxUndo()) changes.removeLast(); + } + + public static synchronized boolean canUndo() { + return ! changes.isEmpty(); + } + + /** + * Undoes the last change through the service of its kind. It stays to undo when it cannot be undone, + * as when the place of a deleted object is taken or its parent is gone. + * + * @return the undone change, null when there is none or it could not be undone. + */ + public static synchronized Change undo() { + var last = changes.peek(); + if (last == null) { + log.info("Nothing to undo."); + return null; + } + var undone = switch (last) { + case Deleted d -> switch (d.kind()) { + case project -> ProjectService.restore(d.path(), d.kept()); + case testcase -> TestCaseService.restore(d.path(), d.kept()); + case step -> StepService.restore(d.path(), d.kept()); + }; + case Modified m -> switch (m.kind()) { + case project -> ProjectService.overwrite(m.path(), m.content()); + case testcase -> TestCaseService.overwrite(m.path(), m.content()); + case step -> StepService.overwrite(m.path(), m.content()); + }; + }; + if (! undone) return null; + changes.pop(); + return last; + } +} diff --git a/src/main/java/com/molnarandrei/sopa/wsdl/WsdlService.java b/src/main/java/com/molnarandrei/sopa/wsdl/WsdlService.java index a66c09a..bf791ec 100644 --- a/src/main/java/com/molnarandrei/sopa/wsdl/WsdlService.java +++ b/src/main/java/com/molnarandrei/sopa/wsdl/WsdlService.java @@ -1,12 +1,12 @@ package com.molnarandrei.sopa.wsdl; +import com.molnarandrei.sopa.properties.PropertiesRepository; import com.molnarandrei.sopa.Utils; import com.molnarandrei.sopa.data.RepositoryException; import com.molnarandrei.sopa.project.ProjectRepository; import com.molnarandrei.sopa.soap.PropertyMissingException; import com.molnarandrei.sopa.soap.SoapCall; import com.molnarandrei.sopa.soap.SoapJob; -import com.molnarandrei.sopa.testcase.TestCaseRepository; import com.molnarandrei.sopa.soap.SoapVersion; import javafx.scene.control.Alert; import org.apache.xmlbeans.SchemaTypeSystem; @@ -53,7 +53,7 @@ public class WsdlService { public static boolean download(Path projectPath, Path testCasePath, String endpoint, int timeoutSeconds) { String url; try { - url = SoapCall.applyProperties(endpoint, propertiesOf(projectPath, testCasePath)); + url = SoapCall.applyProperties(endpoint, PropertiesRepository.merged(projectPath, testCasePath)); } catch (RepositoryException cannotRead) { log.log(Level.WARNING, "Cannot read properties for %s.".formatted(endpoint), cannotRead); Utils.alert( @@ -75,13 +75,6 @@ public class WsdlService { return download(projectPath, endpoint, url, timeoutSeconds); } - private static Map propertiesOf(Path projectPath, Path testCasePath) throws RepositoryException { - var properties = new HashMap<>(ProjectRepository.get(projectPath).getProperties()); - if (testCasePath != null) - properties.putAll(TestCaseRepository.get(testCasePath).getProperties()); - return properties; - } - private static boolean download(Path projectPath, String endpoint, String url, int timeoutSeconds) { try { var wsdl = WsdlRemote.download(url, timeoutSeconds); @@ -178,7 +171,7 @@ public class WsdlService { */ public static SoapVersion detectVersion(Path projectPath, Path testCasePath, String endpoint) { try { - var url = SoapCall.applyProperties(endpoint, propertiesOf(projectPath, testCasePath)); + var url = SoapCall.applyProperties(endpoint, PropertiesRepository.merged(projectPath, testCasePath)); return detectVersion(WsdlRepository.get(projectPath, endpoint).wsdl(), url); } catch (RepositoryException | PropertyMissingException cannotDetect) { log.log(Level.INFO, "Cannot detect SOAP version of %s.".formatted(endpoint), cannotDetect); diff --git a/src/main/resources/AGENTS.md b/src/main/resources/AGENTS.md index ead7c2d..66720a2 100644 --- a/src/main/resources/AGENTS.md +++ b/src/main/resources/AGENTS.md @@ -32,7 +32,6 @@ endpoints: version: 1.1 # or 1.2 headers: {} name: Test Project -properties: {} ``` testcase.yml @@ -43,7 +42,6 @@ active: true endpoint: "" headers: {} name: Alumni -properties: {} ``` step.yml @@ -101,11 +99,12 @@ No fault via xPath: `count(//*[local-name()='Fault'])`, value `"0"`. - Version unknown: read endpoint WSDL. Port with `soap12:address` or only `soap12:binding` = `1.2`; `soap:` = `1.1`. - Inherit: blank endpoint step > testcase. Blank action step > testcase. Both blank endpoint stops run. - Merge, lower wins: headers project < testcase < step. properties project < testcase. +- Properties: java `.properties` files next to yml: `project.properties`, `testcase-N/testcase.properties`. Missing file = none. - `{prop}` substituted in endpoint, payload, header values, assertion expression and value. - Not substituted: action, extraction XPath. - Missing prop stops run. Any `{...}` counts as prop. Only regex expression keeps `{2}`, `{2,3}`. - Extraction: `prop: XPath`. Runs after assertions pass. Empty result fails step. -- Extracted value saved to `testcase.yml` properties, or `project.yml` if key only there. No need declare first. +- Extracted value saved to `testcase.properties`, or `project.properties` if key only there. No need declare first. - Run: active steps in order. First failed assertion stops rest of steps. - `active: false` skip step. On testcase, skip all its steps. - Prefer `local-name()` XPath: namespace free. diff --git a/src/test/java/com/molnarandrei/sopa/project/ProjectFolderTest.java b/src/test/java/com/molnarandrei/sopa/project/ProjectFolderTest.java index cfa3124..b886779 100644 --- a/src/test/java/com/molnarandrei/sopa/project/ProjectFolderTest.java +++ b/src/test/java/com/molnarandrei/sopa/project/ProjectFolderTest.java @@ -47,4 +47,22 @@ public class ProjectFolderTest { ProjectRepository.writeAgentsFile(folder); assertTrue(Files.readString(folder.resolve("AGENTS.md")).startsWith("# Sopa")); } + + @Test + public void projectStepsRunTestCaseByTestCaseInIndexOrder() throws Exception { + for (var step : new String[]{"testcase-10/step-1", "testcase-2/step-10", "testcase-2/step-2", "testcase-3/step-1"}) { + var stepPath = folder.resolve(step).resolve("step.yml"); + Files.createDirectories(stepPath.getParent()); + Files.writeString(stepPath, ""); + Files.writeString(stepPath.getParent().getParent().resolve("testcase.yml"), ""); + } + // A testcase folder without its yml is not a testcase. + Files.createDirectories(folder.resolve("testcase-4/step-1")); + Files.writeString(folder.resolve("testcase-4/step-1/step.yml"), ""); + + var steps = ProjectRepository.getPathsOfContainedSteps(folder.resolve("project.yml")).stream() + .map(step -> folder.relativize(step.getParent()).toString().replace('\\', '/')) + .toList(); + assertEquals(java.util.List.of("testcase-2/step-2", "testcase-2/step-10", "testcase-3/step-1", "testcase-10/step-1"), steps); + } } diff --git a/src/test/java/com/molnarandrei/sopa/properties/PropertiesRepositoryTest.java b/src/test/java/com/molnarandrei/sopa/properties/PropertiesRepositoryTest.java new file mode 100644 index 0000000..d482ba4 --- /dev/null +++ b/src/test/java/com/molnarandrei/sopa/properties/PropertiesRepositoryTest.java @@ -0,0 +1,44 @@ +package com.molnarandrei.sopa.properties; + +import com.molnarandrei.sopa.data.yaml.TestCase; +import com.molnarandrei.sopa.testcase.TestCaseRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +public class PropertiesRepositoryTest { + @TempDir + Path folder; + + @Test + public void propertiesAreKeptNextToTheYml() throws Exception { + var projectPath = folder.resolve("project.yml"); + var testCasePath = folder.resolve("testcase-1").resolve("testcase.yml"); + Files.createDirectories(testCasePath.getParent()); + + assertEquals(folder.resolve("project.properties"), PropertiesRepository.of(projectPath)); + assertEquals(Map.of(), PropertiesRepository.merged(projectPath, testCasePath)); + + var project = Map.of("shared", "project", "url", "http://host:80/a b", "ñ", "ü=1"); + PropertiesRepository.update(PropertiesRepository.of(projectPath), project); + PropertiesRepository.update(PropertiesRepository.of(testCasePath), Map.of("shared", "testcase")); + + assertEquals(project, PropertiesRepository.get(PropertiesRepository.of(projectPath))); + var merged = PropertiesRepository.merged(projectPath, testCasePath); + assertEquals("testcase", merged.get("shared")); + assertEquals("ü=1", merged.get("ñ")); + assertEquals("project", PropertiesRepository.merged(projectPath, null).get("shared")); + } + + @Test + public void ymlWithTheFormerPropertiesStillReads() throws Exception { + var testCasePath = folder.resolve("testcase.yml"); + Files.writeString(testCasePath, TestCase.HEADER + "\nname: C\nproperties:\n a: b\n"); + assertEquals("C", TestCaseRepository.get(testCasePath).getName()); + } +} diff --git a/src/test/java/com/molnarandrei/sopa/soap/SoapCallTest.java b/src/test/java/com/molnarandrei/sopa/soap/SoapCallTest.java index 49e0aa9..5a4898a 100644 --- a/src/test/java/com/molnarandrei/sopa/soap/SoapCallTest.java +++ b/src/test/java/com/molnarandrei/sopa/soap/SoapCallTest.java @@ -5,12 +5,15 @@ import com.molnarandrei.sopa.data.yaml.Project; import com.molnarandrei.sopa.data.yaml.Step; import com.molnarandrei.sopa.data.yaml.TestCase; import com.molnarandrei.sopa.project.ProjectRepository; +import com.molnarandrei.sopa.properties.PropertiesRepository; import com.molnarandrei.sopa.step.StepRepository; import com.molnarandrei.sopa.testcase.TestCaseRepository; import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; import org.mockito.Mockito; import java.nio.file.Path; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -19,6 +22,16 @@ import static org.mockito.ArgumentMatchers.eq; public class SoapCallTest { + /** The properties files of the project and testcase hold {@code project} and {@code testCase}. */ + private static MockedStatic properties( + Path projectPath, Map project, Path testCasePath, Map testCase + ) { + var mock = Mockito.mockStatic(PropertiesRepository.class, Mockito.CALLS_REAL_METHODS); + mock.when(() -> PropertiesRepository.get(eq(PropertiesRepository.of(projectPath)))).thenAnswer(i -> new HashMap<>(project)); + mock.when(() -> PropertiesRepository.get(eq(PropertiesRepository.of(testCasePath)))).thenAnswer(i -> new HashMap<>(testCase)); + return mock; + } + @Test public void simpleCallWithoutOverwrites() throws Exception { var stepPath = Path.of("/proj/case/step-1/step.yml"); @@ -29,13 +42,11 @@ public class SoapCallTest { var project = new Project( "Demo Project", List.of("http://project.example/soap"), - Map.of("X-Project", "p"), - Map.of("user", "alice") + Map.of("X-Project", "p") ); var testcase = new TestCase( "Demo Case", true, "http://example.com/soap", "urn:simpleAction", - Map.of("X-Case", "c"), - Map.of() + Map.of("X-Case", "c") ); var step = new Step("Demo Step"); step.setEndpoint(""); @@ -46,7 +57,8 @@ public class SoapCallTest { try ( var stepMock = Mockito.mockStatic(StepRepository.class); var caseMock = Mockito.mockStatic(TestCaseRepository.class); - var projectMock = Mockito.mockStatic(ProjectRepository.class) + var projectMock = Mockito.mockStatic(ProjectRepository.class); + var propertiesMock = properties(projectPath, Map.of("user", "alice"), testcasePath, Map.of()) ) { stepMock.when(() -> StepRepository.get(eq(stepPath))).thenReturn(step); caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase); @@ -80,10 +92,6 @@ public class SoapCallTest { Map.of( "X-Shared", "project-header", "X-Project", "project-header" - ), - Map.of( - "shared", "project-value", - "projectOnly", "project-value" ) ); var testcase = new TestCase( @@ -93,10 +101,6 @@ public class SoapCallTest { Map.of( "X-Shared", "case-header", "X-Case", "case-header" - ), - Map.of( - "shared", "case-value", - "caseOnly", "case-value" ) ); var step = new Step("S"); @@ -109,7 +113,8 @@ public class SoapCallTest { try ( var stepMock = Mockito.mockStatic(StepRepository.class); var caseMock = Mockito.mockStatic(TestCaseRepository.class); - var projectMock = Mockito.mockStatic(ProjectRepository.class) + var projectMock = Mockito.mockStatic(ProjectRepository.class); + var propertiesMock = properties(projectPath, Map.of("shared", "project-value", "projectOnly", "project-value"), testcasePath, Map.of("shared", "case-value", "caseOnly", "case-value")) ) { stepMock.when(() -> StepRepository.get(eq(stepPath))).thenReturn(step); caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase); @@ -153,8 +158,8 @@ public class SoapCallTest { var testcasePath = testCaseFolderPath.resolve("testcase.yml"); var projectPath = testCaseFolderPath.getParent().resolve("project.yml"); - var project = new Project("P", List.of("http://example.com/soap"), Map.of(), Map.of("element", "id")); - var testcase = new TestCase("C", true, "http://example.com/soap", "urn:a", Map.of(), Map.of("alumnusId", "17")); + var project = new Project("P", List.of("http://example.com/soap"), Map.of()); + var testcase = new TestCase("C", true, "http://example.com/soap", "urn:a", Map.of()); var step = new Step("S"); step.setPayload(""); step.getAssertions().add(new Assertion(Assertion.Type.xPath, "{alumnusId}", "//*[local-name()='{element}']")); @@ -164,7 +169,8 @@ public class SoapCallTest { try ( var stepMock = Mockito.mockStatic(StepRepository.class); var caseMock = Mockito.mockStatic(TestCaseRepository.class); - var projectMock = Mockito.mockStatic(ProjectRepository.class) + var projectMock = Mockito.mockStatic(ProjectRepository.class); + var propertiesMock = properties(projectPath, Map.of("element", "id"), testcasePath, Map.of("alumnusId", "17")) ) { stepMock.when(() -> StepRepository.get(eq(stepPath))).thenReturn(step); caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase); @@ -192,8 +198,8 @@ public class SoapCallTest { var testcasePath = testCaseFolderPath.resolve("testcase.yml"); var projectPath = testCaseFolderPath.getParent().resolve("project.yml"); - var project = new Project("P", List.of("http://example.com/soap"), Map.of(), Map.of()); - var testcase = new TestCase("C", true, "http://example.com/soap", "urn:a", Map.of(), Map.of()); + var project = new Project("P", List.of("http://example.com/soap"), Map.of()); + var testcase = new TestCase("C", true, "http://example.com/soap", "urn:a", Map.of()); var step = new Step("S"); step.setPayload(""); step.getAssertions().add(new Assertion(Assertion.Type.xPath, "{nope}", "//id")); @@ -222,7 +228,7 @@ public class SoapCallTest { var project = new Project("P", List.of()); project.putEndpoint("http://{host}/v11", SoapVersion.ONE_ONE); project.putEndpoint("http://{host}/v12", SoapVersion.ONE_TWO); - var testcase = new TestCase("C", true, "http://{host}/v12", "urn:a", Map.of(), Map.of()); + var testcase = new TestCase("C", true, "http://{host}/v12", "urn:a", Map.of()); var step = new Step("S"); step.setPayload(""); diff --git a/src/test/java/com/molnarandrei/sopa/trash/TrashServiceTest.java b/src/test/java/com/molnarandrei/sopa/trash/TrashServiceTest.java deleted file mode 100644 index ba705a4..0000000 --- a/src/test/java/com/molnarandrei/sopa/trash/TrashServiceTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.molnarandrei.sopa.trash; - -import com.molnarandrei.sopa.step.StepService; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.nio.file.Files; -import java.nio.file.Path; - -import static org.junit.jupiter.api.Assertions.*; - -public class TrashServiceTest { - @TempDir - Path folder; - - private Path step(String testCase, String step) throws Exception { - var stepPath = folder.resolve(testCase).resolve(step).resolve("step.yml"); - Files.createDirectories(stepPath.getParent()); - Files.writeString(stepPath, "# step"); - Files.writeString(stepPath.resolveSibling("response-1.yml"), "# log"); - return stepPath; - } - - @Test - public void deletedStepComesBackWithAllItsFiles() throws Exception { - var stepPath = step("testcase-1", "step-1"); - StepService.delete(stepPath); - assertFalse(Files.exists(stepPath.getParent())); - assertTrue(TrashService.canUndo()); - - var restored = TrashService.undo(); - assertEquals(stepPath, restored.path()); - assertEquals("# step", Files.readString(stepPath)); - assertEquals("# log", Files.readString(stepPath.resolveSibling("response-1.yml"))); - } - - @Test - public void undoRestoresTheLatestFirst() throws Exception { - var first = step("testcase-1", "step-1"); - var second = step("testcase-1", "step-2"); - StepService.delete(first); - StepService.delete(second); - - assertEquals(second, TrashService.undo().path()); - assertFalse(Files.exists(first)); - assertEquals(first, TrashService.undo().path()); - assertTrue(Files.exists(first)); - } -} diff --git a/src/test/java/com/molnarandrei/sopa/undo/UndoTest.java b/src/test/java/com/molnarandrei/sopa/undo/UndoTest.java new file mode 100644 index 0000000..71c0717 --- /dev/null +++ b/src/test/java/com/molnarandrei/sopa/undo/UndoTest.java @@ -0,0 +1,103 @@ +package com.molnarandrei.sopa.undo; + +import com.molnarandrei.sopa.data.yaml.Config; +import com.molnarandrei.sopa.data.yaml.Step; +import com.molnarandrei.sopa.step.StepService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.*; + +public class UndoTest { + @TempDir + Path folder; + + private Path step(String testCase, String step) throws Exception { + var stepPath = folder.resolve(testCase).resolve(step).resolve("step.yml"); + Files.createDirectories(stepPath.getParent()); + Files.writeString(stepPath, "# step"); + Files.writeString(stepPath.resolveSibling("response-1.yml"), "# log"); + return stepPath; + } + + @Test + public void deletedStepComesBackWithAllItsFiles() throws Exception { + var stepPath = step("testcase-1", "step-1"); + StepService.delete(stepPath); + assertFalse(Files.exists(stepPath.getParent())); + assertTrue(Undo.canUndo()); + + var restored = Undo.undo(); + assertEquals(stepPath, restored.path()); + assertEquals("# step", Files.readString(stepPath)); + assertEquals("# log", Files.readString(stepPath.resolveSibling("response-1.yml"))); + } + + @Test + public void undoRestoresTheLatestFirst() throws Exception { + var first = step("testcase-1", "step-1"); + var second = step("testcase-1", "step-2"); + StepService.delete(first); + StepService.delete(second); + + assertEquals(second, Undo.undo().path()); + assertFalse(Files.exists(first)); + assertEquals(first, Undo.undo().path()); + assertTrue(Files.exists(first)); + } + + @Test + public void modifiedStepGetsItsPreviousContentBack() throws Exception { + var stepPath = step("testcase-1", "step-1"); + StepService.write(stepPath, new Step("cambiado")); + assertNotEquals("# step", Files.readString(stepPath)); + + var undone = Undo.undo(); + assertInstanceOf(Undo.Modified.class, undone); + assertEquals("# step", Files.readString(stepPath)); + } + + @Test + public void writingTheSameContentIsNotAChange() throws Exception { + var stepPath = step("testcase-1", "step-1"); + var step = new Step("igual"); + StepService.write(stepPath, step); + StepService.write(stepPath, step); + + Undo.undo(); + assertEquals("# step", Files.readString(stepPath)); + } + + @Test + public void consecutiveModificationsOfAFileAreUndoneTogether() throws Exception { + var stepPath = step("testcase-1", "step-1"); + StepService.write(stepPath, new Step("primero")); + StepService.write(stepPath, new Step("segundo")); + + assertInstanceOf(Undo.Modified.class, Undo.undo()); + assertEquals("# step", Files.readString(stepPath)); + assertFalse(Undo.canUndo()); + } + + @Test + public void modificationsAfterTheMergeWindowAreUndoneApart() throws Exception { + var window = Config.get().getUndoMergeSeconds(); + Config.get().setUndoMergeSeconds(0); + try { + var stepPath = step("testcase-1", "step-1"); + StepService.write(stepPath, new Step("primero")); + var first = Files.readString(stepPath); + StepService.write(stepPath, new Step("segundo")); + + Undo.undo(); + assertEquals(first, Files.readString(stepPath)); + Undo.undo(); + assertEquals("# step", Files.readString(stepPath)); + } finally { + Config.get().setUndoMergeSeconds(window); + } + } +}