Save system revamp, quality of life.

This commit is contained in:
andrei committed 2026-11-19 09:32:12 +01:00
1 parent 30c6d395ee
commit 8e64749111
44 files changed
+791 -506

No files matched your search

@@ -28,6 +28,11 @@ public class FileNames {
&& filename.endsWith(".yml"); && 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) { public static boolean isStepFile(Path stepFile) {
return "step.yml".equals( stepFile.getFileName().toString() ); return "step.yml".equals( stepFile.getFileName().toString() );
} }
@@ -50,6 +50,8 @@ public class ProjectMonitor extends PathAlterationListener {
Events.emit(new TestCaseEvent(TestCaseEvent.CHANGED, testCaseAndProject(file))); Events.emit(new TestCaseEvent(TestCaseEvent.CHANGED, testCaseAndProject(file)));
else if (isStepResponse(file)) else if (isStepResponse(file))
Events.emit(new ResponseEvent(ResponseEvent.CHANGED, file)); Events.emit(new ResponseEvent(ResponseEvent.CHANGED, file));
else if (isPropertiesFile(file))
Events.emit(new PropertiesEvent(PropertiesEvent.CHANGED, file));
else if (isStepFile(file)) else if (isStepFile(file))
Events.emit(new StepEvent(StepEvent.CHANGED, stepAndProject(file))); Events.emit(new StepEvent(StepEvent.CHANGED, stepAndProject(file)));
else else
@@ -66,6 +68,8 @@ public class ProjectMonitor extends PathAlterationListener {
Events.emit(new TestCaseEvent(TestCaseEvent.ADDED, testCaseAndProject(file))); Events.emit(new TestCaseEvent(TestCaseEvent.ADDED, testCaseAndProject(file)));
else if (isStepResponse(file)) else if (isStepResponse(file))
Events.emit(new ResponseEvent(ResponseEvent.ADDED, file)); Events.emit(new ResponseEvent(ResponseEvent.ADDED, file));
else if (isPropertiesFile(file))
Events.emit(new PropertiesEvent(PropertiesEvent.ADDED, file));
else if (isStepFile(file)) else if (isStepFile(file))
Events.emit(new StepEvent(StepEvent.ADDED, stepAndProject(file))); Events.emit(new StepEvent(StepEvent.ADDED, stepAndProject(file)));
else else
@@ -86,6 +90,8 @@ public class ProjectMonitor extends PathAlterationListener {
Events.emit(new TestCaseEvent(TestCaseEvent.REMOVED, testCaseAndProject(file))); Events.emit(new TestCaseEvent(TestCaseEvent.REMOVED, testCaseAndProject(file)));
else if (isStepResponse(file)) else if (isStepResponse(file))
Events.emit(new ResponseEvent(ResponseEvent.REMOVED, file)); Events.emit(new ResponseEvent(ResponseEvent.REMOVED, file));
else if (isPropertiesFile(file))
Events.emit(new PropertiesEvent(PropertiesEvent.REMOVED, file));
else if (isStepFile(file)) else if (isStepFile(file))
Events.emit(new StepEvent(StepEvent.REMOVED, stepAndProject(file))); Events.emit(new StepEvent(StepEvent.REMOVED, stepAndProject(file)));
else else
@@ -99,7 +105,7 @@ public class ProjectMonitor extends PathAlterationListener {
private boolean isOutsideProjectTree(Path file) { private boolean isOutsideProjectTree(Path file) {
var relative = root.relativize(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)); return ! hasTestCaseFolderName(relative.getName(0));
} }
@@ -10,7 +10,9 @@ public class CallLog {
success, success,
assertionsFailed, assertionsFailed,
extractionsFailed, extractionsFailed,
exception exception,
/** The call could not be made, as when a property is missing: the body says why. */
notCalled
} }
private Path step; private Path step;
@@ -46,6 +46,8 @@ public class Config {
private Double responseHistorySplitPaneDividerPosition = 0.2d; private Double responseHistorySplitPaneDividerPosition = 0.2d;
private Double assertionsExtractionsSplitPaneDividerPosition = 0.5d; private Double assertionsExtractionsSplitPaneDividerPosition = 0.5d;
private Integer callTimeout = 10; private Integer callTimeout = 10;
private Integer maxUndo = 100;
private Integer undoMergeSeconds = 10;
private static Config INSTANCE = null; private static Config INSTANCE = null;
@@ -234,6 +236,24 @@ public class Config {
this.callTimeout = callTimeout; 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() { public Double getAssertionsExtractionsSplitPaneDividerPosition() {
return assertionsExtractionsSplitPaneDividerPosition; return assertionsExtractionsSplitPaneDividerPosition;
} }
@@ -14,7 +14,6 @@ public class Project {
/** By url, in the order they were added. */ /** By url, in the order they were added. */
private Map<String, Endpoint> endpoints = new LinkedHashMap<>(); private Map<String, Endpoint> endpoints = new LinkedHashMap<>();
private Map<String, String> headers = new HashMap<>(); private Map<String, String> headers = new HashMap<>();
private Map<String, String> properties = new HashMap<>();
public Project() {} public Project() {}
@@ -25,10 +24,9 @@ public class Project {
} }
/** Every endpoint is SOAP 1.1. */ /** Every endpoint is SOAP 1.1. */
public Project(String name, List<String> endpoints, Map<String, String> headers, Map<String, String> properties) { public Project(String name, List<String> endpoints, Map<String, String> headers) {
this(name, endpoints); this(name, endpoints);
this.headers = headers; this.headers = headers;
this.properties = properties;
} }
public String getVersion() { public String getVersion() {
@@ -76,12 +74,4 @@ public class Project {
public void setHeaders(Map<String, String> headers) { public void setHeaders(Map<String, String> headers) {
this.headers = headers; this.headers = headers;
} }
public Map<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
} }
@@ -11,7 +11,6 @@ public class TestCase {
private String endpoint = ""; private String endpoint = "";
private String action = ""; private String action = "";
private Map<String, String> headers = new HashMap<>(); private Map<String, String> headers = new HashMap<>();
private Map<String, String> properties = new HashMap<>();
public String filename() { public String filename() {
return name.toLowerCase().replaceAll(" ", "-"); return name.toLowerCase().replaceAll(" ", "-");
@@ -23,13 +22,12 @@ public class TestCase {
this.name = name; this.name = name;
} }
public TestCase(String name, boolean active, String endpoint, String action, Map<String, String> headers, Map<String, String> properties) { public TestCase(String name, boolean active, String endpoint, String action, Map<String, String> headers) {
this.name = name; this.name = name;
this.active = active; this.active = active;
this.endpoint = endpoint; this.endpoint = endpoint;
this.action = action; this.action = action;
this.headers = headers; this.headers = headers;
this.properties = properties;
} }
public String getName() { public String getName() {
@@ -71,12 +69,4 @@ public class TestCase {
public void setHeaders(Map<String, String> headers) { public void setHeaders(Map<String, String> headers) {
this.headers = headers; this.headers = headers;
} }
public Map<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
} }
@@ -62,6 +62,11 @@ public class Yaml {
return Config.HEADER + '\n' + mapper.writeValueAsString(config); 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) { public static String toYaml(CallLog callLog) {
return CallLog.HEADER + '\n' + mapper.writeValueAsString(callLog); return CallLog.HEADER + '\n' + mapper.writeValueAsString(callLog);
} }
@@ -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<Path> {
public static final EventType<PropertiesEvent> ADDED = new EventType<>(Event.ANY, "PROPERTIES_ADDED");
public static final EventType<PropertiesEvent> REMOVED = new EventType<>(Event.ANY, "PROPERTIES_REMOVED");
public static final EventType<PropertiesEvent> CHANGED = new EventType<>(Event.ANY, "PROPERTIES_CHANGED");
public PropertiesEvent(EventType<? extends Event> eventType, Path payload) {
super(eventType, payload);
}
}
@@ -3,18 +3,22 @@ package com.molnarandrei.sopa.project;
import com.molnarandrei.sopa.data.Trash; import com.molnarandrei.sopa.data.Trash;
import com.molnarandrei.sopa.Utils; import com.molnarandrei.sopa.Utils;
import com.molnarandrei.sopa.data.DoesNotExistException; import com.molnarandrei.sopa.data.DoesNotExistException;
import com.molnarandrei.sopa.data.FileNames;
import com.molnarandrei.sopa.data.FileSystemCache; import com.molnarandrei.sopa.data.FileSystemCache;
import com.molnarandrei.sopa.data.EmptyException; import com.molnarandrei.sopa.data.EmptyException;
import com.molnarandrei.sopa.data.ProjectMonitors; import com.molnarandrei.sopa.data.ProjectMonitors;
import com.molnarandrei.sopa.data.RepositoryException; import com.molnarandrei.sopa.data.RepositoryException;
import com.molnarandrei.sopa.data.yaml.*; import com.molnarandrei.sopa.data.yaml.*;
import com.molnarandrei.sopa.data.yaml.Yaml; import com.molnarandrei.sopa.data.yaml.Yaml;
import com.molnarandrei.sopa.testcase.TestCaseRepository;
import tools.jackson.core.JacksonException; import tools.jackson.core.JacksonException;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.List;
import java.util.logging.Logger; 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 { try {
var yaml = Yaml.toYaml(project); var previous = Files.exists(projectPath) ? Files.readString(projectPath) : null;
Files.writeString(projectPath, yaml); if (content.equals(previous)) return null;
Files.writeString(projectPath, content);
FileSystemCache.remove(projectPath); FileSystemCache.remove(projectPath);
ProjectMonitors.trigger(projectPath.getParent()); ProjectMonitors.trigger(projectPath.getParent());
return previous;
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(projectPath, "Cannot write project", 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<Path> getPathsOfContainedSteps(Path projectPath) throws RepositoryException {
List<Path> 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<Path>();
for (var testCase : testCases)
steps.addAll(TestCaseRepository.getPathsOfContainedSteps(testCase));
return steps;
}
public static boolean canHoldNewProject(Path projectDir) { public static boolean canHoldNewProject(Path projectDir) {
var directory = projectDir.toAbsolutePath(); var directory = projectDir.toAbsolutePath();
if (Files.exists(directory)) return isEmptyFolder(directory); if (Files.exists(directory)) return isEmptyFolder(directory);
@@ -2,7 +2,7 @@ package com.molnarandrei.sopa.project;
import java.nio.file.Files; import java.nio.file.Files;
import com.molnarandrei.sopa.data.yaml.Kind; 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.Utils;
import com.molnarandrei.sopa.data.ProjectMonitors; import com.molnarandrei.sopa.data.ProjectMonitors;
import com.molnarandrei.sopa.data.yaml.Project; 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) { public static void write(Path projectPath, Project project) {
removeBlankHeaders(project); removeBlankHeaders(project);
try { try {
ProjectRepository.update(projectPath, project); Undo.modified(Kind.project, projectPath, ProjectRepository.update(projectPath, project));
} catch (RepositoryException cannotWrite) { } catch (RepositoryException cannotWrite) {
log.log(Level.SEVERE, "Cannot write project %s.".formatted(projectPath), cannotWrite); log.log(Level.SEVERE, "Cannot write project %s.".formatted(projectPath), cannotWrite);
Utils.alert( 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) { private static void removeBlankHeaders(Project project) {
project.getHeaders().entrySet().removeIf(entry -> project.getHeaders().entrySet().removeIf(entry ->
entry.getKey() == null || entry.getKey().isBlank() || entry.getKey() == null || entry.getKey().isBlank() ||
@@ -127,12 +145,12 @@ public class ProjectService {
ProjectMonitors.stop(projectPath.getParent()); 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) { public static void delete(Path projectPath) {
log.info("Deleting project %s.".formatted(projectPath)); log.info("Deleting project %s.".formatted(projectPath));
close(projectPath); close(projectPath);
try { try {
TrashService.remember(Kind.project, projectPath, ProjectRepository.trashProject(projectPath)); Undo.deleted(Kind.project, projectPath, ProjectRepository.trashProject(projectPath));
} catch (RepositoryException cannotDeleteAllFiles) { } catch (RepositoryException cannotDeleteAllFiles) {
log.log(Level.WARNING, "Delete project error.", cannotDeleteAllFiles); log.log(Level.WARNING, "Delete project error.", cannotDeleteAllFiles);
Utils.alert( Utils.alert(
@@ -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<String, String> get(Path propertiesPath) throws RepositoryException {
var properties = new HashMap<String, String>();
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<String, String> 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<String, String> 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();
}
}
@@ -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<String, String> 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<String, String> 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()
);
}
}
}
@@ -3,6 +3,7 @@ package com.molnarandrei.sopa.soap;
import com.molnarandrei.sopa.data.RepositoryException; import com.molnarandrei.sopa.data.RepositoryException;
import com.molnarandrei.sopa.data.yaml.Assertion; import com.molnarandrei.sopa.data.yaml.Assertion;
import com.molnarandrei.sopa.project.ProjectRepository; import com.molnarandrei.sopa.project.ProjectRepository;
import com.molnarandrei.sopa.properties.PropertiesRepository;
import com.molnarandrei.sopa.step.StepRepository; import com.molnarandrei.sopa.step.StepRepository;
import com.molnarandrei.sopa.testcase.TestCaseRepository; import com.molnarandrei.sopa.testcase.TestCaseRepository;
@@ -91,11 +92,7 @@ public class SoapCall extends RawSoapCall {
} }
public void applyProperties() throws RepositoryException, PropertyMissingException, MalformedEndpointException { public void applyProperties() throws RepositoryException, PropertyMissingException, MalformedEndpointException {
var testcase = TestCaseRepository.get(testCasePath); properties = PropertiesRepository.merged(projectPath, testCasePath);
var project = ProjectRepository.get(projectPath);
properties = new HashMap<>();
properties.putAll(project.getProperties());
properties.putAll(testcase.getProperties());
endpoint = applyProperties(endpointTemplate); endpoint = applyProperties(endpointTemplate);
payload = applyProperties(payloadTemplate); payload = applyProperties(payloadTemplate);
@@ -8,8 +8,7 @@ import com.molnarandrei.sopa.events.Events;
import com.molnarandrei.sopa.events.SoapCallEvent; import com.molnarandrei.sopa.events.SoapCallEvent;
import com.molnarandrei.sopa.events.SoapJobEvent; import com.molnarandrei.sopa.events.SoapJobEvent;
import com.molnarandrei.sopa.calllog.CallLogService; import com.molnarandrei.sopa.calllog.CallLogService;
import com.molnarandrei.sopa.project.ProjectService; import com.molnarandrei.sopa.properties.PropertiesService;
import com.molnarandrei.sopa.testcase.TestCaseService;
import com.molnarandrei.sopa.data.yaml.Kind; import com.molnarandrei.sopa.data.yaml.Kind;
import com.molnarandrei.sopa.ui.lib.Lineage; import com.molnarandrei.sopa.ui.lib.Lineage;
import com.molnarandrei.sopa.wsdl.WsdlValidations; import com.molnarandrei.sopa.wsdl.WsdlValidations;
@@ -95,7 +94,15 @@ public class SoapJob extends LinkedList<SoapCall> implements Runnable {
private boolean request(SoapCall call) { private boolean request(SoapCall call) {
var stepPath = call.getPath(); 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(); var endpoint = call.getEndpoint();
try { try {
Events.emit(new SoapCallEvent( Events.emit(new SoapCallEvent(
@@ -170,10 +177,11 @@ public class SoapJob extends LinkedList<SoapCall> implements Runnable {
return true; 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 { try {
call.applyProperties(); call.applyProperties();
return true; return null;
} catch (RepositoryException readOrParseErr) { } catch (RepositoryException readOrParseErr) {
log.log(Level.WARNING, "Cannot read properties for step %s".formatted(call.getPath()), readOrParseErr); log.log(Level.WARNING, "Cannot read properties for step %s".formatted(call.getPath()), readOrParseErr);
Utils.alert( Utils.alert(
@@ -182,6 +190,7 @@ public class SoapJob extends LinkedList<SoapCall> implements Runnable {
.formatted(readOrParseErr.getPath()), .formatted(readOrParseErr.getPath()),
readOrParseErr.getMessage() readOrParseErr.getMessage()
); );
return "No se han podido leer las propiedades: %s\n%s".formatted(readOrParseErr.getPath(), readOrParseErr.getMessage());
} catch (PropertyMissingException prop) { } catch (PropertyMissingException prop) {
log.warning("Property %s missing for step %s".formatted(prop.getMissingKey(), call.getPath())); log.warning("Property %s missing for step %s".formatted(prop.getMissingKey(), call.getPath()));
Utils.alert( Utils.alert(
@@ -190,6 +199,7 @@ public class SoapJob extends LinkedList<SoapCall> implements Runnable {
"No podemos realizar la llamada SOAP:\n%s".formatted(Lineage.withPath(Kind.step, call.getPath())), "No podemos realizar la llamada SOAP:\n%s".formatted(Lineage.withPath(Kind.step, call.getPath())),
"Falta la propiedad: %s".formatted(prop.getMissingKey()) "Falta la propiedad: %s".formatted(prop.getMissingKey())
); );
return "Falta la propiedad: %s".formatted(prop.getMissingKey());
} catch (MalformedEndpointException malformed) { } catch (MalformedEndpointException malformed) {
log.warning("Malformed endpoint %s for step %s".formatted(malformed.getEndpoint(), call.getPath())); log.warning("Malformed endpoint %s for step %s".formatted(malformed.getEndpoint(), call.getPath()));
Utils.alert( Utils.alert(
@@ -199,8 +209,8 @@ public class SoapJob extends LinkedList<SoapCall> implements Runnable {
.formatted(malformed.getEndpoint()), .formatted(malformed.getEndpoint()),
malformed.getMessage() 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<String> httpResponse) { private static boolean applyExtractions(SoapCall call, HttpResponse<String> httpResponse) {
@@ -236,12 +246,8 @@ public class SoapJob extends LinkedList<SoapCall> implements Runnable {
} }
log.info("Extraction result: %s".formatted(extracted)); log.info("Extraction result: %s".formatted(extracted));
var testCase = TestCaseService.read(call.getTestCasePath()); var testCaseProperties = PropertiesService.read(call.getTestCasePath());
var project = ProjectService.read(call.getProjectPath()); var projectProperties = PropertiesService.read(call.getProjectPath());
if (testCase == null || project == null) return false;
var testCaseProperties = new HashMap<>(testCase.getProperties());
var projectProperties = new HashMap<>(project.getProperties());
var testCaseUpdated = false; var testCaseUpdated = false;
var projectUpdated = false; var projectUpdated = false;
for (var entry : extracted.entrySet()) { for (var entry : extracted.entrySet()) {
@@ -258,14 +264,8 @@ public class SoapJob extends LinkedList<SoapCall> implements Runnable {
} }
} }
if (testCaseUpdated) { if (testCaseUpdated) PropertiesService.write(call.getTestCasePath(), testCaseProperties);
testCase.setProperties(testCaseProperties); if (projectUpdated) PropertiesService.write(call.getProjectPath(), projectProperties);
TestCaseService.write(call.getTestCasePath(), testCase);
}
if (projectUpdated) {
project.setProperties(projectProperties);
ProjectService.write(call.getProjectPath(), project);
}
return true; return true;
} }
@@ -2,6 +2,7 @@ package com.molnarandrei.sopa.soap;
import com.molnarandrei.sopa.Utils; import com.molnarandrei.sopa.Utils;
import com.molnarandrei.sopa.data.RepositoryException; import com.molnarandrei.sopa.data.RepositoryException;
import com.molnarandrei.sopa.project.ProjectRepository;
import com.molnarandrei.sopa.step.StepRepository; import com.molnarandrei.sopa.step.StepRepository;
import com.molnarandrei.sopa.testcase.TestCaseRepository; import com.molnarandrei.sopa.testcase.TestCaseRepository;
import javafx.scene.control.Alert; 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) { private static void stopJobsOverlapping(SoapJob job) {
for (var call : job) { for (var call : job) {
var running = currentlyRunningJobsByPath.get(call.getPath()); var running = currentlyRunningJobsByPath.get(call.getPath());
@@ -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 { try {
var yaml = Yaml.toYaml(step); var previous = Files.exists(stepPath) ? Files.readString(stepPath) : null;
Files.writeString(stepPath, yaml); if (content.equals(previous)) return null;
Files.writeString(stepPath, content);
FileSystemCache.remove(stepPath); FileSystemCache.remove(stepPath);
ProjectMonitors.trigger(stepPath.getParent().getParent().getParent()); ProjectMonitors.trigger(stepPath.getParent().getParent().getParent());
return previous;
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(stepPath, "Cannot write step", io); throw new RepositoryException(stepPath, "Cannot write step", io);
} }
@@ -2,13 +2,10 @@ package com.molnarandrei.sopa.step;
import com.molnarandrei.sopa.data.yaml.Kind; 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.Utils;
import com.molnarandrei.sopa.data.RepositoryException; import com.molnarandrei.sopa.data.RepositoryException;
import com.molnarandrei.sopa.data.yaml.Step; 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.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@@ -52,13 +49,6 @@ public class StepService {
} }
public static void create(Path testCasePath) { 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"); var stepFolderPath = testCasePath.getParent().resolve("step-1");
if (Files.exists(stepFolderPath)) if (Files.exists(stepFolderPath))
stepFolderPath = renameIndexed(stepFolderPath); stepFolderPath = renameIndexed(stepFolderPath);
@@ -74,7 +64,7 @@ public class StepService {
); );
return; return;
} }
var step = new Step(name); var step = new Step("nuevo paso");
write(stepFolderPath.resolve("step.yml"), step); write(stepFolderPath.resolve("step.yml"), step);
} }
@@ -85,7 +75,7 @@ public class StepService {
entry.getValue() == null || entry.getValue().isBlank() entry.getValue() == null || entry.getValue().isBlank()
); );
try { try {
StepRepository.update(stepPath, step); Undo.modified(Kind.step, stepPath, StepRepository.update(stepPath, step));
return true; return true;
} catch (RepositoryException cannotWrite) { } catch (RepositoryException cannotWrite) {
log.log(Level.SEVERE, "Cannot write step %s.".formatted(stepPath), 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 * 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 * {@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) { public static void delete(Path stepPath) {
log.info("Deleting step %s.".formatted(stepPath)); log.info("Deleting step %s.".formatted(stepPath));
try { try {
TrashService.remember(Kind.step, stepPath, StepRepository.trash(stepPath)); Undo.deleted(Kind.step, stepPath, StepRepository.trash(stepPath));
} catch (RepositoryException readWriteParseError) { } catch (RepositoryException readWriteParseError) {
log.log(Level.SEVERE, "Cannot delete step %s.".formatted(stepPath), readWriteParseError); log.log(Level.SEVERE, "Cannot delete step %s.".formatted(stepPath), readWriteParseError);
Utils.alert( Utils.alert(
@@ -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 { try {
var yaml = Yaml.toYaml(testCase); var previous = Files.exists(testCasePath) ? Files.readString(testCasePath) : null;
Files.writeString(testCasePath, yaml); if (content.equals(previous)) return null;
Files.writeString(testCasePath, content);
FileSystemCache.remove(testCasePath); FileSystemCache.remove(testCasePath);
ProjectMonitors.trigger(testCasePath.getParent().getParent()); ProjectMonitors.trigger(testCasePath.getParent().getParent());
return previous;
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(testCasePath, "Cannot write testcase", io); throw new RepositoryException(testCasePath, "Cannot write testcase", io);
} }
@@ -1,14 +1,11 @@
package com.molnarandrei.sopa.testcase; package com.molnarandrei.sopa.testcase;
import com.molnarandrei.sopa.data.yaml.Kind; 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.step.StepService;
import com.molnarandrei.sopa.Utils; import com.molnarandrei.sopa.Utils;
import com.molnarandrei.sopa.data.RepositoryException; import com.molnarandrei.sopa.data.RepositoryException;
import com.molnarandrei.sopa.data.yaml.TestCase; 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.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@@ -53,13 +50,6 @@ public class TestCaseService {
} }
public static void create(Path projectPath) { 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"); var testCaseDirectory = projectPath.getParent().resolve("testcase-1");
if (Files.exists(testCaseDirectory)) if (Files.exists(testCaseDirectory))
testCaseDirectory = renameIndexed(testCaseDirectory); testCaseDirectory = renameIndexed(testCaseDirectory);
@@ -75,19 +65,19 @@ public class TestCaseService {
); );
return; return;
} }
var testCase = new TestCase(name); var testCase = new TestCase("nuevo caso");
write(testCaseDirectory.resolve("testcase.yml"), testCase); 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) { public static boolean write(Path testCasePath, TestCase testCase) {
testCase.getHeaders().entrySet().removeIf(entry -> testCase.getHeaders().entrySet().removeIf(entry ->
entry.getKey() == null || entry.getKey().isBlank() || entry.getKey() == null || entry.getKey().isBlank() ||
entry.getValue() == null || entry.getValue().isBlank() entry.getValue() == null || entry.getValue().isBlank()
); );
try { try {
TestCaseRepository.update(testCasePath, testCase); Undo.modified(Kind.testcase, testCasePath, TestCaseRepository.update(testCasePath, testCase));
return true; return true;
} catch (RepositoryException cannotWrite) { } catch (RepositoryException cannotWrite) {
log.log(Level.SEVERE, "Cannot write testcase %s.".formatted(testCasePath), 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}, * 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 * 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) { public static void delete(Path testCasePath) {
log.info("Deleting testcase %s.".formatted(testCasePath)); log.info("Deleting testcase %s.".formatted(testCasePath));
try { try {
TrashService.remember(Kind.testcase, testCasePath, TestCaseRepository.trash(testCasePath)); Undo.deleted(Kind.testcase, testCasePath, TestCaseRepository.trash(testCasePath));
} catch (RepositoryException cannotDeleteAllFiles) { } catch (RepositoryException cannotDeleteAllFiles) {
log.log(Level.WARNING, "Delete testcase error %s.".formatted(testCasePath), cannotDeleteAllFiles); log.log(Level.WARNING, "Delete testcase error %s.".formatted(testCasePath), cannotDeleteAllFiles);
Utils.alert( Utils.alert(
@@ -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> 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;
}
}
@@ -4,14 +4,14 @@ import atlantafx.base.controls.Spacer;
import atlantafx.base.theme.Styles; import atlantafx.base.theme.Styles;
import com.molnarandrei.sopa.data.yaml.Config; import com.molnarandrei.sopa.data.yaml.Config;
import com.molnarandrei.sopa.data.yaml.Kind; 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.Events;
import com.molnarandrei.sopa.events.ProjectTreeViewEvent; 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.project.ProjectService;
import com.molnarandrei.sopa.properties.PropertiesService;
import com.molnarandrei.sopa.testcase.TestCaseService; import com.molnarandrei.sopa.testcase.TestCaseService;
import com.molnarandrei.sopa.ui.editor.Destroyable; import com.molnarandrei.sopa.ui.editor.Destroyable;
import com.molnarandrei.sopa.ui.lib.Shortcuts;
import javafx.event.EventHandler; import javafx.event.EventHandler;
import javafx.geometry.Bounds; import javafx.geometry.Bounds;
import javafx.geometry.Insets; import javafx.geometry.Insets;
@@ -50,9 +50,10 @@ public class PropertiesDialog extends Stage implements Destroyable {
private Kind kind; private Kind kind;
private Path projectPath; private Path projectPath;
private Project project; private Map<String, String> projectProperties;
/** Null without a testcase. */
private Path testCasePath; private Path testCasePath;
private TestCase testCase; private Map<String, String> testCaseProperties;
private final Label title; private final Label title;
private final GridPane grid; 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 record Row(TextField key, TextField value, Button remove) {}
private final EventHandler<ProjectTreeViewEvent> selectionHandler = this::onSelection; private final EventHandler<ProjectTreeViewEvent> selectionHandler = this::onSelection;
private final EventHandler<SoapCallEvent> callFinishedHandler = this::onCallFinished; private final EventHandler<PropertiesEvent> propertiesHandler = this::onPropertiesFile;
/** /**
* @param owner main window, the dialog floats above it. * @param owner main window, the dialog floats above it.
@@ -113,6 +114,7 @@ public class PropertiesDialog extends Stage implements Destroyable {
root.setCenter(scroll); root.setCenter(scroll);
root.setBottom(bottom); root.setBottom(bottom);
BorderPane.setMargin(bottom, new Insets(8, 0, 0, 0)); BorderPane.setMargin(bottom, new Insets(8, 0, 0, 0));
Shortcuts.on(root, Shortcuts.SAVE, this::save);
var config = Config.get(); var config = Config.get();
var width = config.getPropertiesDialogWidth() != null ? config.getPropertiesDialogWidth() : DEFAULT_WIDTH; 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(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); reload(initialPath, initialKind);
} }
@@ -165,8 +169,12 @@ public class PropertiesDialog extends Stage implements Destroyable {
reload(identity.path(), identity.kind()); reload(identity.path(), identity.kind());
} }
private void onCallFinished(SoapCallEvent event) { /** The properties files live next to the yml of their project or testcase. */
reload(null, null); 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; if (kind != null) this.kind = kind;
projectPath = null; projectPath = null;
project = null; projectProperties = null;
testCasePath = null; testCasePath = null;
testCase = null; testCaseProperties = null;
if (this.path == null || this.kind == null) { if (this.path == null || this.kind == null) {
title.setText("Selecciona un proyecto, caso o paso"); title.setText("Selecciona un proyecto, caso o paso");
@@ -200,22 +208,15 @@ public class PropertiesDialog extends Stage implements Destroyable {
} }
} }
project = ProjectService.read(projectPath); projectProperties = PropertiesService.read(projectPath);
if (testCasePath != null) var properties = new HashMap<>(projectProperties);
testCase = TestCaseService.read(testCasePath); if (testCasePath != null) {
testCaseProperties = PropertiesService.read(testCasePath);
properties.putAll(testCaseProperties);
}
var properties = new HashMap<String, String>(); var name = testCasePath != null ? TestCaseService.nameOf(testCasePath) : ProjectService.nameOf(projectPath);
if (project != null && project.getProperties() != null) title.setText("Propiedades de %s".formatted(name));
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");
showProperties(properties); showProperties(properties);
} }
@@ -224,7 +225,7 @@ public class PropertiesDialog extends Stage implements Destroyable {
grid.getChildren().clear(); grid.getChildren().clear();
rows.clear(); rows.clear();
new TreeMap<>(properties).forEach(this::addRow); new TreeMap<>(properties).forEach(this::addRow);
var editable = project != null; var editable = projectPath != null;
addBtn.setDisable(!editable); addBtn.setDisable(!editable);
saveBtn.setDisable(!editable); saveBtn.setDisable(!editable);
} }
@@ -242,6 +243,7 @@ public class PropertiesDialog extends Stage implements Destroyable {
removeBtn.setOnAction(e -> { removeBtn.setOnAction(e -> {
rows.remove(row); rows.remove(row);
grid.getChildren().removeAll(keyField, valueField, removeBtn); grid.getChildren().removeAll(keyField, valueField, removeBtn);
save();
}); });
var index = grid.getRowCount(); var index = grid.getRowCount();
@@ -257,7 +259,7 @@ public class PropertiesDialog extends Stage implements Destroyable {
* Removed keys are removed from both. * Removed keys are removed from both.
*/ */
private void save() { private void save() {
if (project == null) return; if (projectPath == null) return;
var edited = new HashMap<String, String>(); var edited = new HashMap<String, String>();
for (var row : rows) { 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()); edited.put(key.strip(), row.value().getText() == null ? "" : row.value().getText());
} }
var projectProperties = project.getProperties();
Map<String, String> testCaseProperties = testCase == null ? null : testCase.getProperties();
if (testCase != null && testCaseProperties == null) {
testCaseProperties = new HashMap<>();
testCase.setProperties(testCaseProperties);
}
var newProject = new HashMap<String, String>(); var newProject = new HashMap<String, String>();
var newTestCase = new HashMap<String, String>(); var newTestCase = new HashMap<String, String>();
for (var entry : edited.entrySet()) { for (var entry : edited.entrySet()) {
@@ -294,15 +289,8 @@ public class PropertiesDialog extends Stage implements Destroyable {
newProject.put(entry.getKey(), entry.getValue()); newProject.put(entry.getKey(), entry.getValue());
log.info("Saving properties of %s and %s.".formatted(projectPath, testCasePath)); log.info("Saving properties of %s and %s.".formatted(projectPath, testCasePath));
projectProperties.clear(); PropertiesService.write(projectPath, newProject);
projectProperties.putAll(newProject); if (testCasePath != null) PropertiesService.write(testCasePath, newTestCase);
ProjectService.write(projectPath, project);
if (testCase != null) {
testCaseProperties.clear();
testCaseProperties.putAll(newTestCase);
TestCaseService.write(testCasePath, testCase);
}
reload(null, null); reload(null, null);
} }
@@ -310,6 +298,8 @@ public class PropertiesDialog extends Stage implements Destroyable {
@Override @Override
public void destroy() { public void destroy() {
Events.removeListener(ProjectTreeViewEvent.SELECTED, selectionHandler); 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);
} }
} }
@@ -6,6 +6,7 @@ import com.molnarandrei.sopa.data.yaml.Config;
import com.molnarandrei.sopa.events.Events; import com.molnarandrei.sopa.events.Events;
import com.molnarandrei.sopa.events.ProjectTreeViewEvent; import com.molnarandrei.sopa.events.ProjectTreeViewEvent;
import com.molnarandrei.sopa.ui.editor.EditorPane; 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.menu.TopMenu;
import com.molnarandrei.sopa.ui.navpane.ProjectPane; import com.molnarandrei.sopa.ui.navpane.ProjectPane;
import javafx.application.Application; import javafx.application.Application;
@@ -48,6 +49,7 @@ public class SopaApplication extends Application {
root.setTop(new TopMenu()); root.setTop(new TopMenu());
root.setCenter(split); root.setCenter(split);
Shortcuts.on(root, Shortcuts.NEW, left::createInSelected);
var scene = new Scene(root, 800, 500); var scene = new Scene(root, 800, 500);
stage.setTitle("Sopa"); stage.setTitle("Sopa");
stage.setScene(scene); stage.setScene(scene);
@@ -2,18 +2,11 @@ package com.molnarandrei.sopa.ui.create;
import atlantafx.base.controls.Spacer; import atlantafx.base.controls.Spacer;
import atlantafx.base.theme.Styles; import atlantafx.base.theme.Styles;
import com.molnarandrei.sopa.data.yaml.Config;
import com.molnarandrei.sopa.data.yaml.Project; import com.molnarandrei.sopa.data.yaml.Project;
import com.molnarandrei.sopa.project.ProjectRepository; import com.molnarandrei.sopa.project.ProjectRepository;
import com.molnarandrei.sopa.project.ProjectService; 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 com.molnarandrei.sopa.ui.lib.Packing;
import javafx.application.Platform;
import javafx.geometry.Insets; import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene; import javafx.scene.Scene;
import javafx.scene.control.*; import javafx.scene.control.*;
import javafx.scene.layout.*; import javafx.scene.layout.*;
@@ -22,37 +15,24 @@ import javafx.stage.Modality;
import javafx.stage.Stage; import javafx.stage.Stage;
import javafx.stage.Window; import javafx.stage.Window;
import org.kordamp.ikonli.javafx.FontIcon; import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.materialdesign2.MaterialDesignD;
import org.kordamp.ikonli.materialdesign2.MaterialDesignF; import org.kordamp.ikonli.materialdesign2.MaterialDesignF;
import java.nio.file.InvalidPathException; import java.nio.file.InvalidPathException;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.logging.Logger; 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 { public class CreateProjectDialog extends Stage {
private static final Logger log = Logger.getLogger(CreateProjectDialog.class.getName()); 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 TextField pathField = new TextField();
private final Label pathError = new Label("No es una carpeta vacia"); 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<String, String> headers = new HashMap<>();
private final Label status = new Label();
private WsdlRemote.Download wsdlOfCurrentEndpoint = null;
private boolean creating = false;
public CreateProjectDialog(Window owner) { public CreateProjectDialog(Window owner) {
initOwner(owner); initOwner(owner);
initModality(Modality.WINDOW_MODAL); initModality(Modality.WINDOW_MODAL);
setTitle("Crear proyecto"); setTitle("Crear proyecto");
setOnCloseRequest(e -> { if (creating) e.consume(); });
var title = new Label("Crear proyecto"); var title = new Label("Crear proyecto");
Styles.addStyleClass(title, Styles.TITLE_1); Styles.addStyleClass(title, Styles.TITLE_1);
@@ -63,7 +43,6 @@ public class CreateProjectDialog extends Stage {
var fieldColumn = new ColumnConstraints(); var fieldColumn = new ColumnConstraints();
fieldColumn.setHgrow(Priority.ALWAYS); fieldColumn.setHgrow(Priority.ALWAYS);
fields.getColumnConstraints().addAll(new ColumnConstraints(), fieldColumn, new ColumnConstraints()); fields.getColumnConstraints().addAll(new ColumnConstraints(), fieldColumn, new ColumnConstraints());
var row = 0;
pathField.setText(Path.of(System.getProperty("user.dir")).toString()); pathField.setText(Path.of(System.getProperty("user.dir")).toString());
pathField.textProperty().addListener((obs, old, value) -> showPathError(false)); pathField.textProperty().addListener((obs, old, value) -> showPathError(false));
@@ -74,65 +53,24 @@ public class CreateProjectDialog extends Stage {
pathField.setOnAction(e -> create()); pathField.setOnAction(e -> create());
var choosePath = new Button("", FontIcon.of(MaterialDesignF.FOLDER_OPEN)); var choosePath = new Button("", FontIcon.of(MaterialDesignF.FOLDER_OPEN));
choosePath.setOnAction(e -> choosePath()); choosePath.setOnAction(e -> choosePath());
fields.add(new Label("Carpeta:"), 0, row); fields.add(new Label("Carpeta:"), 0, 0);
fields.add(pathField, 1, row); fields.add(pathField, 1, 0);
fields.add(choosePath, 2, row); fields.add(choosePath, 2, 0);
row++;
Styles.addStyleClass(pathError, Styles.DANGER); Styles.addStyleClass(pathError, Styles.DANGER);
pathError.managedProperty().bind(pathError.visibleProperty()); pathError.managedProperty().bind(pathError.visibleProperty());
pathError.setVisible(false); pathError.setVisible(false);
fields.add(pathError, 1, row, 2, 1); fields.add(pathError, 1, 1, 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());
var create = new Button("Crear proyecto", FontIcon.of(MaterialDesignF.FOLDER_PLUS)); var create = new Button("Crear proyecto", FontIcon.of(MaterialDesignF.FOLDER_PLUS));
Styles.addStyleClass(create, Styles.ACCENT); Styles.addStyleClass(create, Styles.ACCENT);
create.disableProperty().bind(nameField.textProperty().isEmpty()); create.disableProperty().bind(pathField.textProperty().isEmpty());
create.setOnAction(e -> create()); create.setOnAction(e -> create());
status.setWrapText(true); var form = new VBox(8, title, fields, new Separator(), new HBox(8, new Spacer(), create));
var actions = new HBox(8, new Spacer(), testDownloadWsdl, create);
form.setPadding(new Insets(16)); 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); form.setPrefWidth(600);
var scene = new Scene(form); var scene = new Scene(form);
if (owner != null && owner.getScene() != null) if (owner != null && owner.getScene() != null)
scene.getStylesheets().addAll(owner.getScene().getStylesheets()); scene.getStylesheets().addAll(owner.getScene().getStylesheets());
@@ -147,8 +85,7 @@ public class CreateProjectDialog extends Stage {
if (chosen == null) return; if (chosen == null) return;
pathField.setText(chosen.toPath().toString()); pathField.setText(chosen.toPath().toString());
if (checkPath() && nameField.getText().isBlank()) checkPath();
nameField.setText(chosen.getName().replaceAll("_", " ").replaceAll("-", " "));
} }
private boolean checkPath() { private boolean checkPath() {
@@ -168,101 +105,11 @@ public class CreateProjectDialog extends Stage {
pathError.setVisible(error); 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() { private void create() {
if (nameField.getText().isBlank() || ! checkPath()) return; if (! checkPath()) return;
var directory = Path.of(pathField.getText().strip()).toAbsolutePath(); var directory = Path.of(pathField.getText().strip()).toAbsolutePath();
var endpoint = endpointField.getText(); if (ProjectService.create(directory, new Project(directory.getFileName().toString(), List.of()), true))
var held = wsdlOfCurrentEndpoint; close();
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);
} }
} }
@@ -1,6 +1,7 @@
package com.molnarandrei.sopa.ui.editor; package com.molnarandrei.sopa.ui.editor;
import com.molnarandrei.sopa.data.yaml.Kind; import com.molnarandrei.sopa.data.yaml.Kind;
import com.molnarandrei.sopa.data.yaml.Yaml;
import com.molnarandrei.sopa.events.*; import com.molnarandrei.sopa.events.*;
import com.molnarandrei.sopa.project.ProjectService; import com.molnarandrei.sopa.project.ProjectService;
import com.molnarandrei.sopa.step.StepService; import com.molnarandrei.sopa.step.StepService;
@@ -25,6 +26,8 @@ public class EditorPane extends StackPane {
private Kind activeKind; private Kind activeKind;
private Path activePath; private Path activePath;
/** The project, testcase or step the editor edits. */
private Object shown;
private final ScrollPane scrollPane; private final ScrollPane scrollPane;
private double lastScrollPosition = 0; private double lastScrollPosition = 0;
@@ -62,11 +65,22 @@ public class EditorPane extends StackPane {
private void onChanged(Path changed) { private void onChanged(Path changed) {
if (activePath == null) return; 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(); var folder = Files.isDirectory(changed) ? changed : changed.getParent();
if (activePath.startsWith(folder)) if (activePath.startsWith(folder))
load(activeKind, activePath); 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) { private void onSelectionChanged(ProjectTreeViewEvent event) {
clear(); clear();
activeKind = event.get().kind(); activeKind = event.get().kind();
@@ -123,6 +137,7 @@ public class EditorPane extends StackPane {
private void loadProject(Path projectPath) { private void loadProject(Path projectPath) {
var project = ProjectService.read(projectPath); var project = ProjectService.read(projectPath);
if (project == null) return; if (project == null) return;
shown = project;
var editor = new ProjectEditorPane(projectPath, project); var editor = new ProjectEditorPane(projectPath, project);
setContent(editor); setContent(editor);
} }
@@ -131,6 +146,7 @@ public class EditorPane extends StackPane {
private void loadTestCase(Path testCasePath) { private void loadTestCase(Path testCasePath) {
var testCase = TestCaseService.read(testCasePath); var testCase = TestCaseService.read(testCasePath);
if (testCase == null) return; if (testCase == null) return;
shown = testCase;
var editor = new TestCaseEditorPane(testCasePath, testCase); var editor = new TestCaseEditorPane(testCasePath, testCase);
setContent(editor); setContent(editor);
} }
@@ -139,6 +155,7 @@ public class EditorPane extends StackPane {
private void loadStep(Path stepPath) { private void loadStep(Path stepPath) {
var step = StepService.read(stepPath); var step = StepService.read(stepPath);
if (step == null) return; if (step == null) return;
shown = step;
var editor = new StepEditorPane(stepPath, step); var editor = new StepEditorPane(stepPath, step);
setContent(editor); setContent(editor);
} }
@@ -1,5 +1,6 @@
package com.molnarandrei.sopa.ui.editor; package com.molnarandrei.sopa.ui.editor;
import com.molnarandrei.sopa.ui.lib.Commit;
import atlantafx.base.theme.Styles; import atlantafx.base.theme.Styles;
import com.molnarandrei.sopa.data.yaml.Endpoint; import com.molnarandrei.sopa.data.yaml.Endpoint;
import com.molnarandrei.sopa.soap.SoapVersion; 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 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<String, Endpoint> endpoints, Runnable onSubmit) { public EndpointsPane(Path projectPath, Map<String, Endpoint> endpoints, Runnable onSubmit) {
this.projectPath = projectPath; this.projectPath = projectPath;
@@ -92,7 +93,7 @@ public class EndpointsPane extends GridPane {
var row = endpointsGrid.getRowCount(); var row = endpointsGrid.getRowCount();
var field = new TextField(endpoint); var field = new TextField(endpoint);
field.setPromptText("http://host/servicio"); field.setPromptText("http://host/servicio");
field.setOnAction(e -> onSubmit.run()); Commit.onCommit(field, onSubmit);
field.textProperty().addListener((obs, old, value) -> sync()); field.textProperty().addListener((obs, old, value) -> sync());
var wsdl = new EndpointWsdl(projectPath, null, field); var wsdl = new EndpointWsdl(projectPath, null, field);
@@ -124,6 +125,7 @@ public class EndpointsPane extends GridPane {
endpointsGrid.getChildren().removeAll(cells); endpointsGrid.getChildren().removeAll(cells);
rows.remove(current); rows.remove(current);
sync(); sync();
onSubmit.run();
}); });
return field; return field;
} }
@@ -1,5 +1,6 @@
package com.molnarandrei.sopa.ui.editor; package com.molnarandrei.sopa.ui.editor;
import com.molnarandrei.sopa.ui.lib.Commit;
import atlantafx.base.theme.Styles; import atlantafx.base.theme.Styles;
import javafx.geometry.HPos; import javafx.geometry.HPos;
import javafx.geometry.Insets; import javafx.geometry.Insets;
@@ -24,7 +25,7 @@ public class HeadersPane extends GridPane {
private final Runnable onSubmit; 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<String, String> headers, Runnable onSubmit) { public HeadersPane(Map<String, String> headers, Runnable onSubmit) {
this.headers = headers; this.headers = headers;
@@ -87,8 +88,8 @@ public class HeadersPane extends GridPane {
keyField.setPromptText("llave"); keyField.setPromptText("llave");
valueField.setPromptText("valor"); valueField.setPromptText("valor");
keyField.setOnAction(e -> onSubmit.run()); Commit.onCommit(keyField, onSubmit);
valueField.setOnAction(e -> onSubmit.run()); Commit.onCommit(valueField, onSubmit);
headersGrid.add(keyField, 0, row); headersGrid.add(keyField, 0, row);
headersGrid.add(valueField, 1, row); headersGrid.add(valueField, 1, row);
@@ -103,6 +104,7 @@ public class HeadersPane extends GridPane {
removeBtn.setOnAction(e->{ removeBtn.setOnAction(e->{
headers.remove(keyField.getText()); headers.remove(keyField.getText());
headersGrid.getChildren().removeAll(keyField, valueField, removeBtn); headersGrid.getChildren().removeAll(keyField, valueField, removeBtn);
onSubmit.run();
}); });
row++; row++;
@@ -117,8 +119,8 @@ public class HeadersPane extends GridPane {
keyField.setPromptText("llave"); keyField.setPromptText("llave");
valueField.setPromptText("valor"); valueField.setPromptText("valor");
keyField.setOnAction(e -> onSubmit.run()); Commit.onCommit(keyField, onSubmit);
valueField.setOnAction(e -> onSubmit.run()); Commit.onCommit(valueField, onSubmit);
headersGrid.add(keyField, 0, row); headersGrid.add(keyField, 0, row);
headersGrid.add(valueField, 1, row); headersGrid.add(valueField, 1, row);
@@ -133,6 +135,7 @@ public class HeadersPane extends GridPane {
removeBtn.setOnAction(e->{ removeBtn.setOnAction(e->{
headers.remove(keyField.getText()); headers.remove(keyField.getText());
headersGrid.getChildren().removeAll(keyField, valueField, removeBtn); headersGrid.getChildren().removeAll(keyField, valueField, removeBtn);
onSubmit.run();
}); });
} }
@@ -1,14 +1,13 @@
package com.molnarandrei.sopa.ui.editor; package com.molnarandrei.sopa.ui.editor;
import atlantafx.base.controls.Spacer; import com.molnarandrei.sopa.ui.lib.Commit;
import atlantafx.base.theme.Styles; import atlantafx.base.theme.Styles;
import com.molnarandrei.sopa.data.yaml.Project; import com.molnarandrei.sopa.data.yaml.Project;
import com.molnarandrei.sopa.project.ProjectService; import com.molnarandrei.sopa.project.ProjectService;
import com.molnarandrei.sopa.ui.lib.Shortcuts;
import javafx.geometry.Insets; import javafx.geometry.Insets;
import javafx.scene.control.*; import javafx.scene.control.*;
import javafx.scene.layout.*; import javafx.scene.layout.*;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.materialdesign2.*;
import java.nio.file.Path; import java.nio.file.Path;
@@ -21,6 +20,7 @@ public class ProjectEditorPane extends BorderPane implements Destroyable {
public ProjectEditorPane(Path projectPath, Project project) { public ProjectEditorPane(Path projectPath, Project project) {
Runnable submit = ()-> ProjectService.write(projectPath, project); Runnable submit = ()-> ProjectService.write(projectPath, project);
Shortcuts.on(this, Shortcuts.SAVE, submit);
var top = new VBox(8); var top = new VBox(8);
setTop(top); setTop(top);
@@ -39,8 +39,11 @@ public class ProjectEditorPane extends BorderPane implements Destroyable {
var row = 0; var row = 0;
nameField = new TextField(""); nameField = new TextField("");
nameField.textProperty().addListener((obs, old, value) -> project.setName(value)); nameField.textProperty().addListener((obs, old, value) -> {
nameField.setOnAction(e -> submit.run()); project.setName(value);
title.setText("Proyecto %s".formatted(value));
});
Commit.onCommit(nameField, submit);
fields.add(new Label("Nombre:"), 0, row); fields.add(new Label("Nombre:"), 0, row);
fields.add(nameField, 1, row); fields.add(nameField, 1, row);
row++; row++;
@@ -53,18 +56,6 @@ public class ProjectEditorPane extends BorderPane implements Destroyable {
setMargin(headersPane, new Insets(8, 0, 8, 0)); setMargin(headersPane, new Insets(8, 0, 8, 0));
setCenter(headersPane); 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); loadProject(project);
} }
@@ -1,6 +1,6 @@
package com.molnarandrei.sopa.ui.editor; 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.controls.ToggleSwitch;
import atlantafx.base.theme.Styles; import atlantafx.base.theme.Styles;
import com.molnarandrei.sopa.data.yaml.TestCase; 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.events.UiEvent;
import com.molnarandrei.sopa.project.ProjectService; import com.molnarandrei.sopa.project.ProjectService;
import com.molnarandrei.sopa.testcase.TestCaseService; import com.molnarandrei.sopa.testcase.TestCaseService;
import com.molnarandrei.sopa.ui.lib.Shortcuts;
import javafx.geometry.Insets; import javafx.geometry.Insets;
import javafx.scene.control.*; import javafx.scene.control.*;
import javafx.scene.layout.*; import javafx.scene.layout.*;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.materialdesign2.MaterialDesignC;
import java.nio.file.Path; import java.nio.file.Path;
@@ -31,6 +30,7 @@ public class TestCaseEditorPane extends BorderPane implements Destroyable {
public TestCaseEditorPane(Path testCasePath, TestCase testCase) { public TestCaseEditorPane(Path testCasePath, TestCase testCase) {
Runnable submit = ()-> TestCaseService.write(testCasePath, testCase); Runnable submit = ()-> TestCaseService.write(testCasePath, testCase);
Shortcuts.on(this, Shortcuts.SAVE, submit);
var projectPath = testCasePath.getParent().getParent().resolve("project.yml"); var projectPath = testCasePath.getParent().getParent().resolve("project.yml");
var top = new VBox(8); var top = new VBox(8);
@@ -51,15 +51,18 @@ public class TestCaseEditorPane extends BorderPane implements Destroyable {
fields.add(new Label("Nombre:"), 0, row); fields.add(new Label("Nombre:"), 0, row);
nameField = new TextField(""); nameField = new TextField("");
nameField.textProperty().addListener((obs, old, value) -> testCase.setName(value)); nameField.textProperty().addListener((obs, old, value) -> {
nameField.setOnAction(e -> submit.run()); testCase.setName(value);
title.setText("Caso %s".formatted(value));
});
Commit.onCommit(nameField, submit);
fields.add(nameField, 1, row); fields.add(nameField, 1, row);
row++; row++;
fields.add(new Label("Endpoint:"), 0, row); fields.add(new Label("Endpoint:"), 0, row);
endpointField = new TextField(""); endpointField = new TextField("");
endpointField.textProperty().addListener((obs, old, value) -> testCase.setEndpoint(value)); endpointField.textProperty().addListener((obs, old, value) -> testCase.setEndpoint(value));
endpointField.setOnAction(e -> submit.run()); Commit.onCommit(endpointField, submit);
fields.add(endpointField, 1, row); fields.add(endpointField, 1, row);
wsdl = new EndpointWsdl(projectPath, testCasePath, endpointField); wsdl = new EndpointWsdl(projectPath, testCasePath, endpointField);
fields.add(wsdl.selectEndpointButton(), 2, row); fields.add(wsdl.selectEndpointButton(), 2, row);
@@ -68,7 +71,7 @@ public class TestCaseEditorPane extends BorderPane implements Destroyable {
fields.add(new Label("Accion:"), 0, row); fields.add(new Label("Accion:"), 0, row);
actionField = new TextField(""); actionField = new TextField("");
actionField.textProperty().addListener((obs, old, value) -> testCase.setAction(value)); 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(actionField, 1, row);
fields.add(wsdl.selectActionButton(testCasePath), 2, row); fields.add(wsdl.selectActionButton(testCasePath), 2, row);
row++; row++;
@@ -93,12 +96,6 @@ public class TestCaseEditorPane extends BorderPane implements Destroyable {
}); });
actions.getChildren().add(activeToggle); 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); loadTestCase(testCase);
loadParent(projectPath); loadParent(projectPath);
@@ -1,5 +1,6 @@
package com.molnarandrei.sopa.ui.editor.step; 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.data.yaml.Step;
import com.molnarandrei.sopa.events.EventListeners; import com.molnarandrei.sopa.events.EventListeners;
import com.molnarandrei.sopa.events.SopaEvent; import com.molnarandrei.sopa.events.SopaEvent;
@@ -39,14 +40,14 @@ public class CallDetailsPane extends GridPane implements Destroyable {
add(new Label("Nombre:"), 0, row); add(new Label("Nombre:"), 0, row);
nameField = new TextField(""); nameField = new TextField("");
nameField.textProperty().addListener((obs, old, value) -> step.setName(value)); nameField.textProperty().addListener((obs, old, value) -> step.setName(value));
nameField.setOnAction(e -> onSubmit.run()); Commit.onCommit(nameField, onSubmit);
add(nameField, 1, row, 2, 1); add(nameField, 1, row, 2, 1);
row++; row++;
add(new Label("Endpoint:"), 0, row); add(new Label("Endpoint:"), 0, row);
endpointField = new TextField(""); endpointField = new TextField("");
endpointField.textProperty().addListener((obs, old, value) -> step.setEndpoint(value)); endpointField.textProperty().addListener((obs, old, value) -> step.setEndpoint(value));
endpointField.setOnAction(e -> onSubmit.run()); Commit.onCommit(endpointField, onSubmit);
add(endpointField, 1, row); add(endpointField, 1, row);
var projectPath = stepPath.getParent().getParent().getParent().resolve("project.yml"); var projectPath = stepPath.getParent().getParent().getParent().resolve("project.yml");
var testCasePath = stepPath.getParent().getParent().resolve("testcase.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); add(new Label("Accion:"), 0, row);
actionField = new TextField(""); actionField = new TextField("");
actionField.textProperty().addListener((obs, old, value) -> step.setAction(value)); actionField.textProperty().addListener((obs, old, value) -> step.setAction(value));
actionField.setOnAction(e -> onSubmit.run()); Commit.onCommit(actionField, onSubmit);
add(actionField, 1, row); add(actionField, 1, row);
add(wsdl.selectActionButton(stepPath), 2, row); add(wsdl.selectActionButton(stepPath), 2, row);
row++; row++;
@@ -1,5 +1,6 @@
package com.molnarandrei.sopa.ui.editor.step; package com.molnarandrei.sopa.ui.editor.step;
import com.molnarandrei.sopa.ui.lib.Commit;
import atlantafx.base.controls.Spacer; import atlantafx.base.controls.Spacer;
import atlantafx.base.theme.Styles; import atlantafx.base.theme.Styles;
import com.molnarandrei.sopa.data.yaml.Assertion; import com.molnarandrei.sopa.data.yaml.Assertion;
@@ -119,7 +120,7 @@ public class StepAssertionsExtractionsPane extends SplitPane {
expressionField.setPromptText("expresión"); expressionField.setPromptText("expresión");
expressionField.setDisable(WITHOUT_EXPRESSION.contains(assertion.getType())); expressionField.setDisable(WITHOUT_EXPRESSION.contains(assertion.getType()));
expressionField.textProperty().addListener((obs, old, value) -> assertion.setExpression(value)); expressionField.textProperty().addListener((obs, old, value) -> assertion.setExpression(value));
expressionField.setOnAction(e -> save()); Commit.onCommit(expressionField, this::save);
typeBox.valueProperty().addListener((obs, old, value) -> { typeBox.valueProperty().addListener((obs, old, value) -> {
assertion.setType(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.setPromptText(assertion.getType() == Assertion.Type.soapFault ? "código (opcional)" : "valor");
valueField.setDisable(WITHOUT_VALUE.contains(assertion.getType())); valueField.setDisable(WITHOUT_VALUE.contains(assertion.getType()));
valueField.textProperty().addListener((obs, old, value) -> assertion.setValue(value)); 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)); var removeBtn = new Button("", FontIcon.of(MaterialDesignD.DELETE));
removeBtn.setOnAction(e -> { removeBtn.setOnAction(e -> {
step.getAssertions().remove(assertion); step.getAssertions().remove(assertion);
assertionsGrid.getChildren().removeAll(typeBox, expressionField, valueField, removeBtn); assertionsGrid.getChildren().removeAll(typeBox, expressionField, valueField, removeBtn);
save();
}); });
var index = assertionsGrid.getRowCount(); var index = assertionsGrid.getRowCount();
@@ -150,12 +152,12 @@ public class StepAssertionsExtractionsPane extends SplitPane {
var nameField = new TextField(name); var nameField = new TextField(name);
nameField.setPromptText("propiedad"); nameField.setPromptText("propiedad");
nameField.textProperty().addListener((obs, old, value) -> rebuildExtractionsFromRows()); nameField.textProperty().addListener((obs, old, value) -> rebuildExtractionsFromRows());
nameField.setOnAction(e -> save()); Commit.onCommit(nameField, this::save);
var xPathField = new TextField(xPath); var xPathField = new TextField(xPath);
xPathField.setPromptText("xpath"); xPathField.setPromptText("xpath");
xPathField.textProperty().addListener((obs, old, value) -> rebuildExtractionsFromRows()); 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 removeBtn = new Button("", FontIcon.of(MaterialDesignD.DELETE));
var row = new ExtractionRow(nameField, xPathField); var row = new ExtractionRow(nameField, xPathField);
@@ -163,6 +165,7 @@ public class StepAssertionsExtractionsPane extends SplitPane {
extractionRows.remove(row); extractionRows.remove(row);
extractionsGrid.getChildren().removeAll(nameField, xPathField, removeBtn); extractionsGrid.getChildren().removeAll(nameField, xPathField, removeBtn);
rebuildExtractionsFromRows(); rebuildExtractionsFromRows();
save();
}); });
var index = extractionsGrid.getRowCount(); var index = extractionsGrid.getRowCount();
@@ -14,13 +14,13 @@ import com.molnarandrei.sopa.step.StepService;
import com.molnarandrei.sopa.soap.SoapService; import com.molnarandrei.sopa.soap.SoapService;
import com.molnarandrei.sopa.wsdl.WsdlService; import com.molnarandrei.sopa.wsdl.WsdlService;
import com.molnarandrei.sopa.ui.editor.Destroyable; import com.molnarandrei.sopa.ui.editor.Destroyable;
import com.molnarandrei.sopa.ui.lib.Shortcuts;
import com.molnarandrei.sopa.ui.lib.XmlArea; import com.molnarandrei.sopa.ui.lib.XmlArea;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.geometry.Insets; import javafx.geometry.Insets;
import javafx.scene.control.*; import javafx.scene.control.*;
import javafx.scene.layout.*; import javafx.scene.layout.*;
import org.kordamp.ikonli.javafx.FontIcon; import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.materialdesign2.MaterialDesignC;
import org.kordamp.ikonli.materialdesign2.MaterialDesignS; import org.kordamp.ikonli.materialdesign2.MaterialDesignS;
import java.nio.file.Path; import java.nio.file.Path;
@@ -43,6 +43,9 @@ public class StepEditorPane extends BorderPane implements Destroyable {
private final EventListeners listeners = new EventListeners(); private final EventListeners listeners = new EventListeners();
public StepEditorPane(Path stepPath, Step step) { public StepEditorPane(Path stepPath, Step step) {
Runnable submit = ()-> StepService.write(stepPath, step);
Shortcuts.on(this, Shortcuts.SAVE, submit);
var top = new VBox(); var top = new VBox();
setTop(top); setTop(top);
@@ -59,8 +62,9 @@ public class StepEditorPane extends BorderPane implements Destroyable {
); );
top.getChildren().add(detailsTitledPane); top.getChildren().add(detailsTitledPane);
details = new CallDetailsPane(stepPath, step, ()-> StepService.write(stepPath, step)); details = new CallDetailsPane(stepPath, step, submit);
detailsTitledPane.setContent(details); detailsTitledPane.setContent(details);
details.nameField.textProperty().addListener((obs, old, value)-> title.setText("Paso %s".formatted(value)));
var assertionsExtractionsTitledPane = new TitledPane(); var assertionsExtractionsTitledPane = new TitledPane();
assertionsExtractionsTitledPane.setText("Aserciones y Extracciones"); assertionsExtractionsTitledPane.setText("Aserciones y Extracciones");
@@ -79,6 +83,9 @@ public class StepEditorPane extends BorderPane implements Destroyable {
payload.setMinWidth(200d); payload.setMinWidth(200d);
payload.setXml(""); payload.setXml("");
payload.textProperty().addListener((obs, old, value)-> step.setPayload(value)); payload.textProperty().addListener((obs, old, value)-> step.setPayload(value));
payload.focusedProperty().addListener((obs, old, focused)-> {
if (! focused) submit.run();
});
responses = new CallLogPane(stepPath); 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. // Listener added after the initial value, so opening the editor does not save.
activeToggle.selectedProperty().addListener((obs, old, value)-> { activeToggle.selectedProperty().addListener((obs, old, value)-> {
step.setActive(value); step.setActive(value);
StepService.write(stepPath, step); submit.run();
}); });
bottom.getChildren().add(activeToggle); bottom.getChildren().add(activeToggle);
bottom.getChildren().add(new Spacer()); 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)); var execute = new Button("Ejecutar", FontIcon.of(MaterialDesignS.SEND));
execute.setOnAction(e-> { execute.setOnAction(e-> {
StepService.write(stepPath, step); submit.run();
SoapService.createAndStartCallForStep(stepPath); SoapService.createAndStartCallForStep(stepPath);
}); });
Styles.addStyleClass(execute, Styles.ACCENT); Styles.addStyleClass(execute, Styles.ACCENT);
@@ -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();
});
}
}
@@ -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();
});
}
}
@@ -35,7 +35,7 @@ public enum FlightState {
return switch (callLog.getResult()) { return switch (callLog.getResult()) {
case success -> success; case success -> success;
case exception -> exception; case exception -> exception;
case assertionsFailed, extractionsFailed -> failed; case assertionsFailed, extractionsFailed, notCalled -> failed;
}; };
} }
} }
@@ -3,7 +3,10 @@ package com.molnarandrei.sopa.ui.navpane;
import com.molnarandrei.sopa.data.yaml.Kind; import com.molnarandrei.sopa.data.yaml.Kind;
import com.molnarandrei.sopa.events.*; import com.molnarandrei.sopa.events.*;
import com.molnarandrei.sopa.calllog.CallLogService; 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.Tooltip;
import javafx.scene.control.TreeItem; import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView; import javafx.scene.control.TreeView;
@@ -72,8 +75,25 @@ public class ProjectPane extends StackPane {
treeView.addEventHandler(KeyEvent.KEY_PRESSED, this::onKeyPressed); treeView.addEventHandler(KeyEvent.KEY_PRESSED, this::onKeyPressed);
listeners.addAll(); 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() { public void destroy() {
@@ -82,7 +102,7 @@ public class ProjectPane extends StackPane {
private void onKeyPressed(KeyEvent event) { private void onKeyPressed(KeyEvent event) {
if (UNDO.match(event)) { if (UNDO.match(event)) {
TrashService.undo(); Undo.undo();
event.consume(); event.consume();
return; return;
} }
@@ -5,6 +5,7 @@ import com.molnarandrei.sopa.data.yaml.Kind;
import com.molnarandrei.sopa.ui.navpane.TreeIdentity; import com.molnarandrei.sopa.ui.navpane.TreeIdentity;
import com.molnarandrei.sopa.project.ProjectService; import com.molnarandrei.sopa.project.ProjectService;
import com.molnarandrei.sopa.soap.SoapService;
import com.molnarandrei.sopa.step.StepService; import com.molnarandrei.sopa.step.StepService;
import com.molnarandrei.sopa.testcase.TestCaseService; import com.molnarandrei.sopa.testcase.TestCaseService;
import javafx.scene.control.ContextMenu; import javafx.scene.control.ContextMenu;
@@ -23,9 +24,7 @@ public class ProjectContextMenu extends ContextMenu {
var run = new MenuItem( var run = new MenuItem(
"ejecutar todos los casos", "ejecutar todos los casos",
FontIcon.of(MaterialDesignS.SEND)); FontIcon.of(MaterialDesignS.SEND));
run.setOnAction(e->{ run.setOnAction(e-> SoapService.createAndStartCallsForProject(projectPath));
// TODO
});
var createCase = new MenuItem( var createCase = new MenuItem(
"crear caso de prueba", "crear caso de prueba",
@@ -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<Change> 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;
}
}
@@ -1,12 +1,12 @@
package com.molnarandrei.sopa.wsdl; package com.molnarandrei.sopa.wsdl;
import com.molnarandrei.sopa.properties.PropertiesRepository;
import com.molnarandrei.sopa.Utils; import com.molnarandrei.sopa.Utils;
import com.molnarandrei.sopa.data.RepositoryException; import com.molnarandrei.sopa.data.RepositoryException;
import com.molnarandrei.sopa.project.ProjectRepository; import com.molnarandrei.sopa.project.ProjectRepository;
import com.molnarandrei.sopa.soap.PropertyMissingException; import com.molnarandrei.sopa.soap.PropertyMissingException;
import com.molnarandrei.sopa.soap.SoapCall; import com.molnarandrei.sopa.soap.SoapCall;
import com.molnarandrei.sopa.soap.SoapJob; import com.molnarandrei.sopa.soap.SoapJob;
import com.molnarandrei.sopa.testcase.TestCaseRepository;
import com.molnarandrei.sopa.soap.SoapVersion; import com.molnarandrei.sopa.soap.SoapVersion;
import javafx.scene.control.Alert; import javafx.scene.control.Alert;
import org.apache.xmlbeans.SchemaTypeSystem; import org.apache.xmlbeans.SchemaTypeSystem;
@@ -53,7 +53,7 @@ public class WsdlService {
public static boolean download(Path projectPath, Path testCasePath, String endpoint, int timeoutSeconds) { public static boolean download(Path projectPath, Path testCasePath, String endpoint, int timeoutSeconds) {
String url; String url;
try { try {
url = SoapCall.applyProperties(endpoint, propertiesOf(projectPath, testCasePath)); url = SoapCall.applyProperties(endpoint, PropertiesRepository.merged(projectPath, testCasePath));
} catch (RepositoryException cannotRead) { } catch (RepositoryException cannotRead) {
log.log(Level.WARNING, "Cannot read properties for %s.".formatted(endpoint), cannotRead); log.log(Level.WARNING, "Cannot read properties for %s.".formatted(endpoint), cannotRead);
Utils.alert( Utils.alert(
@@ -75,13 +75,6 @@ public class WsdlService {
return download(projectPath, endpoint, url, timeoutSeconds); return download(projectPath, endpoint, url, timeoutSeconds);
} }
private static Map<String, String> 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) { private static boolean download(Path projectPath, String endpoint, String url, int timeoutSeconds) {
try { try {
var wsdl = WsdlRemote.download(url, timeoutSeconds); var wsdl = WsdlRemote.download(url, timeoutSeconds);
@@ -178,7 +171,7 @@ public class WsdlService {
*/ */
public static SoapVersion detectVersion(Path projectPath, Path testCasePath, String endpoint) { public static SoapVersion detectVersion(Path projectPath, Path testCasePath, String endpoint) {
try { 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); return detectVersion(WsdlRepository.get(projectPath, endpoint).wsdl(), url);
} catch (RepositoryException | PropertyMissingException cannotDetect) { } catch (RepositoryException | PropertyMissingException cannotDetect) {
log.log(Level.INFO, "Cannot detect SOAP version of %s.".formatted(endpoint), cannotDetect); log.log(Level.INFO, "Cannot detect SOAP version of %s.".formatted(endpoint), cannotDetect);
+2 -3
View File
@@ -32,7 +32,6 @@ endpoints:
version: 1.1 # or 1.2 version: 1.1 # or 1.2
headers: {} headers: {}
name: Test Project name: Test Project
properties: {}
``` ```
testcase.yml testcase.yml
@@ -43,7 +42,6 @@ active: true
endpoint: "" endpoint: ""
headers: {} headers: {}
name: Alumni name: Alumni
properties: {}
``` ```
step.yml 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`. - 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. - Inherit: blank endpoint step > testcase. Blank action step > testcase. Both blank endpoint stops run.
- Merge, lower wins: headers project < testcase < step. properties project < testcase. - 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. - `{prop}` substituted in endpoint, payload, header values, assertion expression and value.
- Not substituted: action, extraction XPath. - Not substituted: action, extraction XPath.
- Missing prop stops run. Any `{...}` counts as prop. Only regex expression keeps `{2}`, `{2,3}`. - 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. - 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. - Run: active steps in order. First failed assertion stops rest of steps.
- `active: false` skip step. On testcase, skip all its steps. - `active: false` skip step. On testcase, skip all its steps.
- Prefer `local-name()` XPath: namespace free. - Prefer `local-name()` XPath: namespace free.
@@ -47,4 +47,22 @@ public class ProjectFolderTest {
ProjectRepository.writeAgentsFile(folder); ProjectRepository.writeAgentsFile(folder);
assertTrue(Files.readString(folder.resolve("AGENTS.md")).startsWith("# Sopa")); 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);
}
} }
@@ -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());
}
}
@@ -5,12 +5,15 @@ import com.molnarandrei.sopa.data.yaml.Project;
import com.molnarandrei.sopa.data.yaml.Step; import com.molnarandrei.sopa.data.yaml.Step;
import com.molnarandrei.sopa.data.yaml.TestCase; import com.molnarandrei.sopa.data.yaml.TestCase;
import com.molnarandrei.sopa.project.ProjectRepository; import com.molnarandrei.sopa.project.ProjectRepository;
import com.molnarandrei.sopa.properties.PropertiesRepository;
import com.molnarandrei.sopa.step.StepRepository; import com.molnarandrei.sopa.step.StepRepository;
import com.molnarandrei.sopa.testcase.TestCaseRepository; import com.molnarandrei.sopa.testcase.TestCaseRepository;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito; import org.mockito.Mockito;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -19,6 +22,16 @@ import static org.mockito.ArgumentMatchers.eq;
public class SoapCallTest { public class SoapCallTest {
/** The properties files of the project and testcase hold {@code project} and {@code testCase}. */
private static MockedStatic<PropertiesRepository> properties(
Path projectPath, Map<String, String> project, Path testCasePath, Map<String, String> 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 @Test
public void simpleCallWithoutOverwrites() throws Exception { public void simpleCallWithoutOverwrites() throws Exception {
var stepPath = Path.of("/proj/case/step-1/step.yml"); var stepPath = Path.of("/proj/case/step-1/step.yml");
@@ -29,13 +42,11 @@ public class SoapCallTest {
var project = new Project( var project = new Project(
"Demo Project", "Demo Project",
List.of("http://project.example/soap"), List.of("http://project.example/soap"),
Map.of("X-Project", "p"), Map.of("X-Project", "p")
Map.of("user", "alice")
); );
var testcase = new TestCase( var testcase = new TestCase(
"Demo Case", true, "http://example.com/soap", "urn:simpleAction", "Demo Case", true, "http://example.com/soap", "urn:simpleAction",
Map.of("X-Case", "c"), Map.of("X-Case", "c")
Map.of()
); );
var step = new Step("Demo Step"); var step = new Step("Demo Step");
step.setEndpoint(""); step.setEndpoint("");
@@ -46,7 +57,8 @@ public class SoapCallTest {
try ( try (
var stepMock = Mockito.mockStatic(StepRepository.class); var stepMock = Mockito.mockStatic(StepRepository.class);
var caseMock = Mockito.mockStatic(TestCaseRepository.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); stepMock.when(() -> StepRepository.get(eq(stepPath))).thenReturn(step);
caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase); caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase);
@@ -80,10 +92,6 @@ public class SoapCallTest {
Map.of( Map.of(
"X-Shared", "project-header", "X-Shared", "project-header",
"X-Project", "project-header" "X-Project", "project-header"
),
Map.of(
"shared", "project-value",
"projectOnly", "project-value"
) )
); );
var testcase = new TestCase( var testcase = new TestCase(
@@ -93,10 +101,6 @@ public class SoapCallTest {
Map.of( Map.of(
"X-Shared", "case-header", "X-Shared", "case-header",
"X-Case", "case-header" "X-Case", "case-header"
),
Map.of(
"shared", "case-value",
"caseOnly", "case-value"
) )
); );
var step = new Step("S"); var step = new Step("S");
@@ -109,7 +113,8 @@ public class SoapCallTest {
try ( try (
var stepMock = Mockito.mockStatic(StepRepository.class); var stepMock = Mockito.mockStatic(StepRepository.class);
var caseMock = Mockito.mockStatic(TestCaseRepository.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); stepMock.when(() -> StepRepository.get(eq(stepPath))).thenReturn(step);
caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase); caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase);
@@ -153,8 +158,8 @@ public class SoapCallTest {
var testcasePath = testCaseFolderPath.resolve("testcase.yml"); var testcasePath = testCaseFolderPath.resolve("testcase.yml");
var projectPath = testCaseFolderPath.getParent().resolve("project.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 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(), Map.of("alumnusId", "17")); var testcase = new TestCase("C", true, "http://example.com/soap", "urn:a", Map.of());
var step = new Step("S"); var step = new Step("S");
step.setPayload("<request/>"); step.setPayload("<request/>");
step.getAssertions().add(new Assertion(Assertion.Type.xPath, "{alumnusId}", "//*[local-name()='{element}']")); step.getAssertions().add(new Assertion(Assertion.Type.xPath, "{alumnusId}", "//*[local-name()='{element}']"));
@@ -164,7 +169,8 @@ public class SoapCallTest {
try ( try (
var stepMock = Mockito.mockStatic(StepRepository.class); var stepMock = Mockito.mockStatic(StepRepository.class);
var caseMock = Mockito.mockStatic(TestCaseRepository.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); stepMock.when(() -> StepRepository.get(eq(stepPath))).thenReturn(step);
caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase); caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase);
@@ -192,8 +198,8 @@ public class SoapCallTest {
var testcasePath = testCaseFolderPath.resolve("testcase.yml"); var testcasePath = testCaseFolderPath.resolve("testcase.yml");
var projectPath = testCaseFolderPath.getParent().resolve("project.yml"); var projectPath = testCaseFolderPath.getParent().resolve("project.yml");
var project = new Project("P", List.of("http://example.com/soap"), 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(), Map.of()); var testcase = new TestCase("C", true, "http://example.com/soap", "urn:a", Map.of());
var step = new Step("S"); var step = new Step("S");
step.setPayload("<request/>"); step.setPayload("<request/>");
step.getAssertions().add(new Assertion(Assertion.Type.xPath, "{nope}", "//id")); step.getAssertions().add(new Assertion(Assertion.Type.xPath, "{nope}", "//id"));
@@ -222,7 +228,7 @@ public class SoapCallTest {
var project = new Project("P", List.of()); var project = new Project("P", List.of());
project.putEndpoint("http://{host}/v11", SoapVersion.ONE_ONE); project.putEndpoint("http://{host}/v11", SoapVersion.ONE_ONE);
project.putEndpoint("http://{host}/v12", SoapVersion.ONE_TWO); 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"); var step = new Step("S");
step.setPayload("<request/>"); step.setPayload("<request/>");
@@ -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));
}
}
@@ -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);
}
}
}