Compare commits

...
11 Commits
Author SHA1 Message Date
andrei a785719788 Use gitea actions runner for new releases.
release / release (push) Successful in 14m12s
2026-11-21 09:47:51 +01:00
andrei dfa5380986 Add gitignore. 2026-11-19 10:36:57 +01:00
andrei 7e71de98bd Increase version. 2026-11-19 10:21:28 +01:00
andrei a4993e2d78 Configuration dialog.
+ Help dialog
2026-11-19 10:19:28 +01:00
andrei 8591df9dbd Migration system + separate properties migration. 2026-11-19 09:58:48 +01:00
andrei 8e64749111 Save system revamp, quality of life. 2026-11-19 09:32:12 +01:00
andrei 30c6d395ee Dialog was ugly 2026-11-18 00:20:40 +01:00
andrei a4ac411e56 Deactivated nav items show as greyed out 2026-11-18 00:20:20 +01:00
andrei 6d59ad6805 Refactor 2026-11-17 23:38:32 +01:00
andrei 7c54387191 Add filesystem cache 2026-11-17 23:18:43 +01:00
andrei a7397355ed Informar del lineaje cuando se mostraria tambien el path de un fichero. 2026-11-17 17:03:26 +01:00
60 changed files with 1505 additions and 603 deletions

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
# On every push to master, publish a Gitea release for the pom.xml version if one
# does not exist yet. "Version changed" == "no release tagged v<version> yet", which
# also covers multi-commit pushes, force pushes and re-runs after a failed upload.
#
# Assets: target/sopa-<v>.zip (self-contained distribution) and
# target/sopa-<v>-shaded.jar (fat jar). The plain jar is not uploaded.
name: release
on:
push:
branches: [master]
concurrency:
group: release
cancel-in-progress: false
env:
MAVEN_VERSION: 3.9.11
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
# The automatic token can create releases on current Gitea; set a RELEASE_TOKEN
# secret (PAT with write:repository) if yours refuses it.
TOKEN: ${{ secrets.RELEASE_TOKEN || github.token }}
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
cache: maven
- name: Install Maven
run: |
curl -fsSL "https://archive.apache.org/dist/maven/maven-3/${MAVEN_VERSION}/binaries/apache-maven-${MAVEN_VERSION}-bin.tar.gz" \
| tar -xz -C "$RUNNER_TEMP"
echo "$RUNNER_TEMP/apache-maven-${MAVEN_VERSION}/bin" >> "$GITHUB_PATH"
- name: Check whether this version is already released
id: version
run: |
VERSION=$(mvn -B -q help:evaluate -Dexpression=project.version -DforceStdout)
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
STATUS=$(curl -s -o /dev/null -w '%{http_code}' \
-H "Authorization: token $TOKEN" "$API/releases/tags/v$VERSION")
case "$STATUS" in
404) echo "release=true" >> "$GITHUB_OUTPUT"; echo "v$VERSION is new, releasing." ;;
200) echo "release=false" >> "$GITHUB_OUTPUT"; echo "v$VERSION already released, skipping." ;;
*) echo "Unexpected HTTP $STATUS from release lookup"; exit 1 ;;
esac
# The Liberica JDKs (~700 MB) the pom downloads for jlink.
- name: Cache distribution JDKs
if: steps.version.outputs.release == 'true'
uses: actions/cache@v4
with:
path: .jdks
key: jdks-${{ hashFiles('pom.xml') }}
restore-keys: jdks-
- name: Build
if: steps.version.outputs.release == 'true'
run: mvn -B package
- name: Create release and upload assets
if: steps.version.outputs.release == 'true'
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
ZIP="target/sopa-$VERSION.zip"
JAR="target/sopa-$VERSION-shaded.jar"
test -f "$ZIP" && test -f "$JAR"
BODY=$(jq -n --arg tag "v$VERSION" --arg sha "$GITHUB_SHA" \
'{tag_name: $tag, target_commitish: $sha, name: $tag, draft: false, prerelease: false}')
ID=$(curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d "$BODY" "$API/releases" | jq -r .id)
echo "Created release $ID"
for f in "$ZIP" "$JAR"; do
curl -fsS -X POST -H "Authorization: token $TOKEN" \
-F "attachment=@$f" "$API/releases/$ID/assets?name=$(basename "$f")" > /dev/null
echo "Uploaded $(basename "$f")"
done
+4
View File
@@ -0,0 +1,4 @@
/.jdks/
/.idea/
/target/
/testProject/
-13
View File
@@ -1,13 +0,0 @@
# You can override the included template(s) by including variable overrides
# SAST customization: https://docs.gitlab.com/user/application_security/sast/#available-cicd-variables
# Secret Detection customization: https://docs.gitlab.com/user/application_security/secret_detection/pipeline/configure/
# Dependency Scanning customization: https://docs.gitlab.com/user/application_security/dependency_scanning/dependency_scanning_sbom/#customizing-analyzer-behavior
# Container Scanning customization: https://docs.gitlab.com/user/application_security/container_scanning/#customizing-analyzer-behavior
# Note that environment variables can be set in several places
# See https://docs.gitlab.com/ci/variables/#cicd-variable-precedence
stages:
- test
sast:
stage: test
include:
- template: Security/SAST.gitlab-ci.yml
+1 -1
View File
@@ -6,7 +6,7 @@
<groupId>com.molnarandrei</groupId> <groupId>com.molnarandrei</groupId>
<artifactId>sopa</artifactId> <artifactId>sopa</artifactId>
<version>1.0.2</version> <version>1.0.4</version>
<name>sopa</name> <name>sopa</name>
<packaging>jar</packaging> <packaging>jar</packaging>
@@ -1,6 +1,7 @@
package com.molnarandrei.sopa.calllog; package com.molnarandrei.sopa.calllog;
import com.molnarandrei.sopa.data.DoesNotExistException; import com.molnarandrei.sopa.data.DoesNotExistException;
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;
@@ -75,9 +76,9 @@ public class CallLogRepository {
public static CallLog get(Path responsePath) throws RepositoryException { public static CallLog get(Path responsePath) throws RepositoryException {
if (! Files.isRegularFile(responsePath)) if (! Files.isRegularFile(responsePath))
throw new DoesNotExistException(responsePath, "Unreadable"); throw new DoesNotExistException(responsePath, "Unreadable");
String response = ""; String response;
try { try {
response = Files.readString(responsePath); response = FileSystemCache.read(responsePath);
} catch (IOException raise) { } catch (IOException raise) {
throw new RepositoryException(responsePath, "IO error", raise); throw new RepositoryException(responsePath, "IO error", raise);
} }
@@ -100,6 +101,7 @@ public class CallLogRepository {
var yaml = Yaml.toYaml(callLog); var yaml = Yaml.toYaml(callLog);
try { try {
Files.writeString(responsePath, yaml); Files.writeString(responsePath, yaml);
FileSystemCache.remove(responsePath);
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(responsePath, "Cannot write response history", io); throw new RepositoryException(responsePath, "Cannot write response history", io);
} }
@@ -128,8 +130,10 @@ public class CallLogRepository {
if (Files.isRegularFile(responsePath)) responses.add(responsePath); if (Files.isRegularFile(responsePath)) responses.add(responsePath);
responses.sort(NEWEST_FIRST); responses.sort(NEWEST_FIRST);
for (int index = limit; index < responses.size(); index++) for (int index = limit; index < responses.size(); index++) {
Files.deleteIfExists(responses.get(index)); Files.deleteIfExists(responses.get(index));
FileSystemCache.remove(responses.get(index));
}
} catch (IOException io) { } catch (IOException io) {
log.log(Level.WARNING, "Cannot delete files over limit of %s".formatted(limit), io); log.log(Level.WARNING, "Cannot delete files over limit of %s".formatted(limit), io);
} }
@@ -152,6 +156,7 @@ public class CallLogRepository {
public static void delete(Path responsePath) throws RepositoryException{ public static void delete(Path responsePath) throws RepositoryException{
try { try {
Files.deleteIfExists(responsePath); Files.deleteIfExists(responsePath);
FileSystemCache.remove(responsePath);
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(responsePath, "Cannot delete response log.", io); throw new RepositoryException(responsePath, "Cannot delete response log.", io);
} }
@@ -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() );
} }
@@ -0,0 +1,24 @@
package com.molnarandrei.sopa.data;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class FileSystemCache {
private static final Map<Path, String> files = new ConcurrentHashMap<>();
public static String read(Path path) throws IOException {
var content = files.get(path);
if (content == null) {
content = Files.readString(path);
files.put(path, content);
}
return content;
}
public static void remove(Path path) {
files.keySet().removeIf(cached -> cached.startsWith(path));
}
}
@@ -43,12 +43,15 @@ public class ProjectMonitor extends PathAlterationListener {
public void onFileChange(Path file) { public void onFileChange(Path file) {
if (isOutsideProjectTree(file)) return; if (isOutsideProjectTree(file)) return;
log.info("File changed %s.".formatted(file)); log.info("File changed %s.".formatted(file));
FileSystemCache.remove(file);
if (isProjectFile(file)) if (isProjectFile(file))
Events.emit(new ProjectEvent(ProjectEvent.CHANGED, file)); Events.emit(new ProjectEvent(ProjectEvent.CHANGED, file));
else if (isTestCaseFile(file)) else if (isTestCaseFile(file))
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
@@ -65,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
@@ -78,12 +83,15 @@ public class ProjectMonitor extends PathAlterationListener {
public void onFileDelete(Path file) { public void onFileDelete(Path file) {
if (isOutsideProjectTree(file)) return; if (isOutsideProjectTree(file)) return;
log.info("File deleted: %s.".formatted(file)); log.info("File deleted: %s.".formatted(file));
FileSystemCache.remove(file);
if (isProjectFile(file)) if (isProjectFile(file))
Events.emit(new ProjectEvent(ProjectEvent.REMOVED, file)); Events.emit(new ProjectEvent(ProjectEvent.REMOVED, file));
else if (isTestCaseFile(file)) else if (isTestCaseFile(file))
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
@@ -97,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;
@@ -1,6 +1,7 @@
package com.molnarandrei.sopa.data.yaml; package com.molnarandrei.sopa.data.yaml;
import com.molnarandrei.sopa.migrations.Migration;
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.events.Events; import com.molnarandrei.sopa.events.Events;
@@ -46,6 +47,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;
@@ -128,6 +131,7 @@ public class Config {
// So: iterate a copy, and only start listening once the saved projects are loaded. // So: iterate a copy, and only start listening once the saved projects are loaded.
for (var project : List.copyOf(loadedProjects)) { for (var project : List.copyOf(loadedProjects)) {
try { try {
Migration.migrate(project);
ProjectMonitors.start(project.getParent()); ProjectMonitors.start(project.getParent());
} catch (RepositoryException logAndIgnore) { } catch (RepositoryException logAndIgnore) {
log.log(Level.WARNING, "Cannot load previously loaded project at %s.".formatted(project), logAndIgnore); log.log(Level.WARNING, "Cannot load previously loaded project at %s.".formatted(project), logAndIgnore);
@@ -234,6 +238,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;
} }
@@ -1,5 +1,6 @@
package com.molnarandrei.sopa.data.yaml; package com.molnarandrei.sopa.data.yaml;
import com.molnarandrei.sopa.migrations.Migration;
import com.molnarandrei.sopa.soap.SoapVersion; import com.molnarandrei.sopa.soap.SoapVersion;
import java.util.HashMap; import java.util.HashMap;
@@ -9,12 +10,12 @@ import java.util.Map;
public class Project { public class Project {
public static final String HEADER = "# com.molnarandrei.sopa.Project"; public static final String HEADER = "# com.molnarandrei.sopa.Project";
private String version = "1.0.2"; /** Of the files of the project: {@link Migration} brings older projects to the current one. */
private String version = String.valueOf(Migration.VERSION);
private String name = ""; private String name = "";
/** 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 +26,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 +76,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;
}
} }
@@ -3,6 +3,9 @@ package com.molnarandrei.sopa.data.yaml;
import tools.jackson.core.JacksonException; import tools.jackson.core.JacksonException;
import tools.jackson.dataformat.yaml.YAMLMapper; import tools.jackson.dataformat.yaml.YAMLMapper;
import java.util.LinkedHashMap;
import java.util.Map;
public class Yaml { public class Yaml {
private static final YAMLMapper mapper = HumanComfyYamlMapper.get(); private static final YAMLMapper mapper = HumanComfyYamlMapper.get();
@@ -62,6 +65,22 @@ public class Yaml {
return Config.HEADER + '\n' + mapper.writeValueAsString(config); return Config.HEADER + '\n' + mapper.writeValueAsString(config);
} }
/** Any yml as plain maps, lists and scalars, as migrations read the files of older versions. */
@SuppressWarnings("unchecked")
public static Map<String, Object> toMap(String value) throws JacksonException {
var map = mapper.readValue(value, LinkedHashMap.class);
return map == null ? new LinkedHashMap<>() : map;
}
public static String toYaml(String header, Map<String, Object> map) {
return header + '\n' + mapper.writeValueAsString(map);
}
/** 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);
}
}
@@ -0,0 +1,36 @@
package com.molnarandrei.sopa.migrations;
import com.molnarandrei.sopa.data.FileNames;
import com.molnarandrei.sopa.data.yaml.Yaml;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
/** File helpers for migrations, which read the files of older versions as plain maps rather than as the app objects. */
public class MigrateUtils {
/** The testcase folders in {@code projectFolder}, in no particular order. */
public static List<Path> testCaseFolders(Path projectFolder) throws IOException {
try (var children = Files.list(projectFolder)) {
return children.filter(folder -> Files.isDirectory(folder) && FileNames.hasTestCaseFolderName(folder)).toList();
}
}
/** The step folders in {@code testCaseFolder}, in no particular order. */
public static List<Path> stepFolders(Path testCaseFolder) throws IOException {
try (var children = Files.list(testCaseFolder)) {
return children.filter(FileNames::isStepFolder).toList();
}
}
public static Map<String, Object> readYaml(Path ymlPath) throws IOException {
return Yaml.toMap(Files.readString(ymlPath));
}
public static void writeYaml(Path ymlPath, String header, Map<String, Object> yaml) throws IOException {
Files.writeString(ymlPath, Yaml.toYaml(header, yaml));
}
}
@@ -0,0 +1,84 @@
package com.molnarandrei.sopa.migrations;
import com.molnarandrei.sopa.data.FileSystemCache;
import com.molnarandrei.sopa.data.RepositoryException;
import com.molnarandrei.sopa.data.yaml.Project;
import com.molnarandrei.sopa.data.yaml.TestCase;
import com.molnarandrei.sopa.project.ProjectRepository;
import com.molnarandrei.sopa.properties.PropertiesRepository;
import tools.jackson.core.JacksonException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* Brings the files of a project up to the {@link #VERSION} of this app, one version at a time, before anything else
* reads them. Migration {@code n} takes a project from version {@code n} to {@code n + 1}.
*/
public class Migration {
private static final Logger log = Logger.getLogger(Migration.class.getName());
/** The version of the projects of this app. */
public static final int VERSION = 2;
private Migration() {}
/** Migrates the project of {@code projectPath}, its project.yml, when its version is older. Overwrites its AGENTS.md. */
public static void migrate(Path projectPath) throws RepositoryException {
try {
var version = versionOf(MigrateUtils.readYaml(projectPath));
if (version >= VERSION) return;
var projectFolder = projectPath.getParent();
log.info("Migrating project %s from version %d to %d.".formatted(projectPath, version, VERSION));
for (; version < VERSION; version++)
switch (version) {
case 1 -> migration_1(projectFolder);
default -> throw new IllegalStateException("No migration from version %d".formatted(version));
}
var project = MigrateUtils.readYaml(projectPath);
project.put("version", String.valueOf(VERSION));
MigrateUtils.writeYaml(projectPath, Project.HEADER, project);
ProjectRepository.writeAgentsFile(projectFolder);
FileSystemCache.remove(projectFolder);
} catch (IOException | JacksonException cannotMigrate) {
throw new RepositoryException(projectPath, "Cannot migrate project", cannotMigrate);
}
}
/** The whole number before any dot: "1.0.2" is 1. A project without version is 1. */
static int versionOf(Map<String, Object> project) {
var version = project.get("version");
if (version == null) return 1;
return Integer.parseInt(String.valueOf(version).split("\\.")[0].strip());
}
/** Properties move from the yml of the project and its testcases to their .properties files. */
static void migration_1(Path projectFolder) throws IOException, RepositoryException {
var ymlPaths = new ArrayList<Path>();
ymlPaths.add(projectFolder.resolve("project.yml"));
for (var testCaseFolder : MigrateUtils.testCaseFolders(projectFolder))
ymlPaths.add(testCaseFolder.resolve("testcase.yml"));
for (var ymlPath : ymlPaths) {
if (! Files.exists(ymlPath)) continue;
var yaml = MigrateUtils.readYaml(ymlPath);
if (! (yaml.remove("properties") instanceof Map<?, ?> moved)) continue;
log.info("Moving testcase properties to .properties file %s".formatted(ymlPath));
var properties = new HashMap<String, String>();
moved.forEach((key, value) -> properties.put(String.valueOf(key), value == null ? "" : String.valueOf(value)));
// A properties file already there was written by a newer version: its values win.
var propertiesPath = PropertiesRepository.of(ymlPath);
properties.putAll(PropertiesRepository.get(propertiesPath));
PropertiesRepository.store(propertiesPath, properties);
MigrateUtils.writeYaml(ymlPath, ymlPath.endsWith("project.yml") ? Project.HEADER : TestCase.HEADER, yaml);
}
}
}
@@ -3,32 +3,31 @@ 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.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.Comparator; import java.nio.file.StandardCopyOption;
import java.util.logging.Logger; import java.util.ArrayList;
import java.util.List;
/**
* IO operations belong here.
* Assume the filesystem to be the single source of truth.
* IDEA filelocks?
*/
public class ProjectRepository { public class ProjectRepository {
private static final Logger log = Logger.getLogger(ProjectRepository.class.getName());
public static Project get(Path projectPath) throws RepositoryException { public static Project get(Path projectPath) throws RepositoryException {
if (! Files.isReadable(projectPath)) throw new DoesNotExistException(projectPath, "Unreadable"); if (! Files.isReadable(projectPath)) throw new DoesNotExistException(projectPath, "Unreadable");
try { try {
var project = Files.readString(projectPath); var project = FileSystemCache.read(projectPath);
if (project.isBlank()) if (project.isBlank())
throw new EmptyException(projectPath, "Project file is empty"); throw new EmptyException(projectPath, "Project file is empty");
var obj = Yaml.toProject(project); var obj = Yaml.toProject(project);
@@ -44,20 +43,44 @@ public class ProjectRepository {
} }
} }
public static boolean isProjectFolder(Path projectDir) { /** @return the content it replaced, null when the file was new or already held it. */
return Files.isReadable(projectDir.resolve("project.yml")); public static String update(Path projectPath, Project project) throws RepositoryException {
return overwrite(projectPath, Yaml.toYaml(project));
} }
public static void update(Path projectPath, Project project) throws RepositoryException{ /** 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);
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);
@@ -84,18 +107,20 @@ public class ProjectRepository {
if (Files.size(projectFile) == 0) { if (Files.size(projectFile) == 0) {
var yaml = Yaml.toYaml(project); var yaml = Yaml.toYaml(project);
Files.writeString(projectFile, yaml); Files.writeString(projectFile, yaml);
FileSystemCache.remove(projectFile);
} }
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(projectFile, "Could not create project file", io); throw new RepositoryException(projectFile, "Could not create project file", io);
} }
} }
/** Writes the AGENTS.md of this version of the app, over any there is. */
public static void writeAgentsFile(Path projectDir) throws RepositoryException { public static void writeAgentsFile(Path projectDir) throws RepositoryException {
var agentsFile = projectDir.resolve("AGENTS.md"); var agentsFile = projectDir.resolve("AGENTS.md");
try (var template = ProjectRepository.class.getResourceAsStream("/AGENTS.md")) { try (var template = ProjectRepository.class.getResourceAsStream("/AGENTS.md")) {
if (template == null) if (template == null)
throw new IOException("AGENTS.md is not packaged"); throw new IOException("AGENTS.md is not packaged");
Files.copy(template, agentsFile); Files.copy(template, agentsFile, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(agentsFile, "Could not create agents file", io); throw new RepositoryException(agentsFile, "Could not create agents file", io);
} }
@@ -129,42 +154,14 @@ public class ProjectRepository {
} }
} }
public static void deleteProject(Path projectPath) throws RepositoryException {
if (! Files.exists(projectPath)) {
return;
}
var projectDirectory = projectPath.getParent();
try {
if (! Files.isDirectory(projectDirectory))
return;
try (var walk = Files.walk(projectDirectory)) {
walk.sorted(Comparator.reverseOrder())
.forEach(p -> {
try {
Files.delete(p);
} catch (IOException ignore) {}
});
}
if (Files.exists(projectDirectory))
throw new IOException("Not deleted.");
} catch (IOException io) {
throw new RepositoryException(projectPath, "Could not delete project", io);
} finally {
ProjectMonitors.trigger(projectDirectory);
}
}
/** Moves the folder of a closed project to the {@link Trash}. @return where it is kept. */ /** Moves the folder of a closed project to the {@link Trash}. @return where it is kept. */
public static Path trashProject(Path projectPath) throws RepositoryException { public static Path trashProject(Path projectPath) throws RepositoryException {
try { try {
return Trash.keep(projectPath.getParent()); return Trash.keep(projectPath.getParent());
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(projectPath, "Could not delete project", io); throw new RepositoryException(projectPath, "Could not delete project", io);
} finally {
FileSystemCache.remove(projectPath.getParent());
} }
} }
@@ -2,25 +2,20 @@ 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.migrations.Migration;
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;
import com.molnarandrei.sopa.data.yaml.Step;
import com.molnarandrei.sopa.data.yaml.TestCase;
import com.molnarandrei.sopa.project.ProjectRepository;
import com.molnarandrei.sopa.data.RepositoryException; import com.molnarandrei.sopa.data.RepositoryException;
import com.molnarandrei.sopa.events.Events; import com.molnarandrei.sopa.events.Events;
import com.molnarandrei.sopa.events.ProjectEvent; import com.molnarandrei.sopa.events.ProjectEvent;
import com.molnarandrei.sopa.step.StepRepository;
import com.molnarandrei.sopa.testcase.TestCaseRepository;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import static com.molnarandrei.sopa.Utils.renameIndexed; import static com.molnarandrei.sopa.Utils.renameIndexed;
import static com.molnarandrei.sopa.data.yaml.Kind.project;
/** /**
* All operations over projects at the application level belong here. * All operations over projects at the application level belong here.
@@ -44,10 +39,24 @@ public class ProjectService {
} }
} }
/**
* The name of the project for display, such as in dialogs; its folder name when it cannot be read,
* without alerting: the dialog showing it is not about reading it.
*/
public static String nameOf(Path projectPath) {
try {
return ProjectRepository.get(projectPath).getName();
} catch (RepositoryException unreadable) {
log.log(Level.FINE, "Cannot read name of project %s.".formatted(projectPath), unreadable);
return projectPath.getParent().getFileName().toString();
}
}
/** 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(
@@ -59,6 +68,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() ||
@@ -114,12 +140,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(
@@ -150,8 +176,10 @@ public class ProjectService {
return true; return true;
} }
/** Migrates the project to this version of the app, before anything reads it, and opens it. */
public static void open(Path projectPath) { public static void open(Path projectPath) {
try { try {
Migration.migrate(projectPath);
ProjectRepository.get(projectPath); ProjectRepository.get(projectPath);
ProjectMonitors.start(projectPath.getParent()); ProjectMonitors.start(projectPath.getParent());
} catch (RepositoryException repo) { } catch (RepositoryException repo) {
@@ -0,0 +1,64 @@
package com.molnarandrei.sopa.properties;
import com.molnarandrei.sopa.data.*;
import java.io.*;
import java.nio.file.*;
import java.util.*;
/**
* 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;
store(propertiesPath, properties);
ProjectMonitors.trigger(projectDirectoryOf(propertiesPath));
}
/** Writes {@code properties} without notifying the monitor: for projects not open yet, as when migrating. */
public static void store(Path propertiesPath, Map<String, String> properties) throws RepositoryException {
try {
var stored = new Properties();
stored.putAll(properties);
var text = new StringWriter();
stored.store(text, null);
Files.writeString(propertiesPath, text.toString());
} 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,9 @@ 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.ui.lib.Lineage;
import com.molnarandrei.sopa.wsdl.WsdlValidations; import com.molnarandrei.sopa.wsdl.WsdlValidations;
import javafx.scene.control.Alert; import javafx.scene.control.Alert;
@@ -93,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(
@@ -154,10 +163,13 @@ public class SoapJob extends LinkedList<SoapCall> implements Runnable {
Utils.alert( Utils.alert(
Alert.AlertType.WARNING, Alert.AlertType.WARNING,
"Aserción no cumplida", "Aserción no cumplida",
"La respuesta del paso no cumple la aserción %s:\n%s" "La respuesta no cumple la aserción %s.".formatted(assertion.getType()),
.formatted(assertion.getType(), call.getPath()), "%s\n\nLa respuesta se ha guardado en el historial del paso para revisarla. %s\n\nPaso: %s"
"%s\n\nLa respuesta se ha guardado en el historial del paso para revisarla. %s" .formatted(
.formatted(unmetDetail(call, assertion, httpResponse), REMAINING_SKIPPED) unmetDetail(call, assertion, httpResponse),
REMAINING_SKIPPED,
Lineage.of(Kind.step, call.getPath())
)
); );
return false; return false;
} }
@@ -165,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(
@@ -177,14 +190,16 @@ 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(
Alert.AlertType.WARNING, Alert.AlertType.WARNING,
"Llamada incompleta", "Llamada incompleta",
"No podemos realizar la llamada SOAP:\n%s".formatted(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(
@@ -194,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) {
@@ -231,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()) {
@@ -253,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());
@@ -3,6 +3,7 @@ package com.molnarandrei.sopa.step;
import com.molnarandrei.sopa.data.Trash; import com.molnarandrei.sopa.data.Trash;
import com.molnarandrei.sopa.testcase.TestCaseRepository; import com.molnarandrei.sopa.testcase.TestCaseRepository;
import com.molnarandrei.sopa.data.DoesNotExistException; import com.molnarandrei.sopa.data.DoesNotExistException;
import com.molnarandrei.sopa.data.FileSystemCache;
import com.molnarandrei.sopa.data.EmptyException; import com.molnarandrei.sopa.data.EmptyException;
import com.molnarandrei.sopa.data.FileNames; import com.molnarandrei.sopa.data.FileNames;
import com.molnarandrei.sopa.data.ProjectMonitors; import com.molnarandrei.sopa.data.ProjectMonitors;
@@ -17,10 +18,8 @@ import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.stream.Collectors;
import static com.molnarandrei.sopa.Utils.baseNameOf; import static com.molnarandrei.sopa.Utils.baseNameOf;
import static com.molnarandrei.sopa.Utils.extractNumber; import static com.molnarandrei.sopa.Utils.extractNumber;
@@ -35,7 +34,7 @@ public class StepRepository {
public static Step get(Path stepPath) throws RepositoryException { public static Step get(Path stepPath) throws RepositoryException {
if (! Files.isReadable(stepPath)) throw new DoesNotExistException(stepPath, "Unreadable"); if (! Files.isReadable(stepPath)) throw new DoesNotExistException(stepPath, "Unreadable");
try { try {
var step = Files.readString(stepPath); var step = FileSystemCache.read(stepPath);
if (step.isBlank()) if (step.isBlank())
throw new EmptyException(stepPath, "Step file is empty"); throw new EmptyException(stepPath, "Step file is empty");
var obj = Yaml.toStep(step); var obj = Yaml.toStep(step);
@@ -51,11 +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);
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);
} }
@@ -100,6 +108,7 @@ public class StepRepository {
var destination = renameIndexed(toTestCaseFolderPath.resolve(baseName + "-" + (highestIndex + 1))); var destination = renameIndexed(toTestCaseFolderPath.resolve(baseName + "-" + (highestIndex + 1)));
try { try {
Files.move(fromStepFolderPath, destination); Files.move(fromStepFolderPath, destination);
FileSystemCache.remove(fromStepFolderPath);
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(fromStepPath, "Cannot move step to '%s'".formatted(destination), io); throw new RepositoryException(fromStepPath, "Cannot move step to '%s'".formatted(destination), io);
} }
@@ -138,7 +147,7 @@ public class StepRepository {
throw new RepositoryException(toStepPath, "Step is not part of '%s'".formatted(toTestCaseFolderPath)); throw new RepositoryException(toStepPath, "Step is not part of '%s'".formatted(toTestCaseFolderPath));
var shiftIndex = targetIndex + (putBefore? 0: 1); var shiftIndex = targetIndex + (putBefore? 0: 1);
var orderedSteps = new ArrayList<Path>(allSteps); var orderedSteps = new ArrayList<>(allSteps);
orderedSteps.add(shiftIndex, fromStepPath); orderedSteps.add(shiftIndex, fromStepPath);
var shifting = new LinkedHashMap<Path, Path>(); var shifting = new LinkedHashMap<Path, Path>();
@@ -179,6 +188,7 @@ public class StepRepository {
if (source.equals(destination)) return; if (source.equals(destination)) return;
try { try {
Files.move(source, destination); Files.move(source, destination);
FileSystemCache.remove(source);
} catch (IOException io) { } catch (IOException io) {
log.log(Level.SEVERE, "While reordering, cannot shift step '%s' to '%s'".formatted(source, destination), io); log.log(Level.SEVERE, "While reordering, cannot shift step '%s' to '%s'".formatted(source, destination), io);
throw new RepositoryException(reportedPath, "Cannot shift step to '%s'".formatted(destination), io); throw new RepositoryException(reportedPath, "Cannot shift step to '%s'".formatted(destination), io);
@@ -206,6 +216,7 @@ public class StepRepository {
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(stepPath, "Cannot delete step '%s'".formatted(stepFolderPath), io); throw new RepositoryException(stepPath, "Cannot delete step '%s'".formatted(stepFolderPath), io);
} finally { } finally {
FileSystemCache.remove(stepFolderPath);
ProjectMonitors.trigger(stepPath.getParent().getParent().getParent()); ProjectMonitors.trigger(stepPath.getParent().getParent().getParent());
} }
} }
@@ -217,6 +228,7 @@ public class StepRepository {
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(stepPath, "Cannot delete step '%s'".formatted(stepPath.getParent()), io); throw new RepositoryException(stepPath, "Cannot delete step '%s'".formatted(stepPath.getParent()), io);
} finally { } finally {
FileSystemCache.remove(stepPath.getParent());
ProjectMonitors.trigger(stepPath.getParent().getParent().getParent()); ProjectMonitors.trigger(stepPath.getParent().getParent().getParent());
} }
} }
@@ -2,12 +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.Packing;
import javafx.scene.control.TextInputDialog;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@@ -37,13 +35,20 @@ public class StepService {
} }
} }
public static void create(Path testCasePath) { /**
var input = Packing.pack(new TextInputDialog()); * The name of the step for display, such as in dialogs; its folder name when it cannot be read,
input.setTitle("Crear paso en prueba"); * without alerting: the dialog showing it is not about reading it.
input.setHeaderText("Nombre del paso"); */
var name = input.showAndWait().orElse(""); public static String nameOf(Path stepPath) {
if (name.isBlank()) return; try {
return StepRepository.get(stepPath).getName();
} catch (RepositoryException unreadable) {
log.log(Level.FINE, "Cannot read name of step %s.".formatted(stepPath), unreadable);
return stepPath.getParent().getFileName().toString();
}
}
public static void create(Path testCasePath) {
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);
@@ -59,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);
} }
@@ -70,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);
@@ -84,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
@@ -198,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(
@@ -3,6 +3,7 @@ package com.molnarandrei.sopa.testcase;
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.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;
@@ -27,7 +28,7 @@ public class TestCaseRepository {
public static TestCase get(Path testCasePath) throws RepositoryException { public static TestCase get(Path testCasePath) throws RepositoryException {
if (! Files.isReadable(testCasePath)) throw new DoesNotExistException(testCasePath, "Unreadable"); if (! Files.isReadable(testCasePath)) throw new DoesNotExistException(testCasePath, "Unreadable");
try { try {
var testCase = Files.readString(testCasePath); var testCase = FileSystemCache.read(testCasePath);
if (testCase.isBlank()) if (testCase.isBlank())
throw new EmptyException(testCasePath, "TestCase file is empty"); throw new EmptyException(testCasePath, "TestCase file is empty");
var obj = Yaml.toTestCase(testCase); var obj = Yaml.toTestCase(testCase);
@@ -43,11 +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);
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);
} }
@@ -73,6 +83,7 @@ public class TestCaseRepository {
); );
try { try {
Files.move(fromTestCaseDirectory, destination); Files.move(fromTestCaseDirectory, destination);
FileSystemCache.remove(fromTestCaseDirectory);
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(fromTestCasePath, "Cannot move testcase to '%s'".formatted(destination), io); throw new RepositoryException(fromTestCasePath, "Cannot move testcase to '%s'".formatted(destination), io);
} }
@@ -142,6 +153,7 @@ public class TestCaseRepository {
throw new RepositoryException(testCaseDirectory, "Could not delete testcase", io); throw new RepositoryException(testCaseDirectory, "Could not delete testcase", io);
} finally { } finally {
FileSystemCache.remove(testCaseDirectory);
ProjectMonitors.trigger(testCasePath.getParent().getParent()); ProjectMonitors.trigger(testCasePath.getParent().getParent());
} }
} }
@@ -165,6 +177,7 @@ public class TestCaseRepository {
} catch (IOException io) { } catch (IOException io) {
throw new RepositoryException(testCasePath, "Could not delete testcase", io); throw new RepositoryException(testCasePath, "Could not delete testcase", io);
} finally { } finally {
FileSystemCache.remove(testCasePath.getParent());
ProjectMonitors.trigger(testCasePath.getParent().getParent()); ProjectMonitors.trigger(testCasePath.getParent().getParent());
} }
} }
@@ -1,13 +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.Packing;
import javafx.scene.control.TextInputDialog;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@@ -38,13 +36,20 @@ public class TestCaseService {
} }
} }
public static void create(Path projectPath) { /**
var input = Packing.pack(new TextInputDialog()); * The name of the testcase for display, such as in dialogs; its folder name when it cannot be read,
input.setTitle("Crear caso de prueba"); * without alerting: the dialog showing it is not about reading it.
input.setHeaderText("Nombre del caso"); */
var name = input.showAndWait().orElse(""); public static String nameOf(Path testCasePath) {
if (name.isBlank()) return; try {
return TestCaseRepository.get(testCasePath).getName();
} catch (RepositoryException unreadable) {
log.log(Level.FINE, "Cannot read name of testcase %s.".formatted(testCasePath), unreadable);
return testCasePath.getParent().getFileName().toString();
}
}
public static void create(Path projectPath) {
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);
@@ -60,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);
@@ -86,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
@@ -196,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;
}
}
@@ -0,0 +1,131 @@
package com.molnarandrei.sopa.ui;
import atlantafx.base.controls.Spacer;
import atlantafx.base.theme.Styles;
import com.molnarandrei.sopa.data.yaml.Config;
import com.molnarandrei.sopa.ui.lib.Packing;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.materialdesign2.MaterialDesignC;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
/** Edits the settings of the app; they are saved only with "Guardar cambios". */
public class ConfigDialog extends Stage {
/** A whole number setting, valid from {@code min}. */
private record Setting(TextField field, int min, Consumer<Integer> set) {}
private final List<Setting> settings = new ArrayList<>();
private final GridPane grid = new GridPane();
public ConfigDialog(Window owner) {
initOwner(owner);
initModality(Modality.WINDOW_MODAL);
setTitle("Configuración");
var title = new Label("Configuración");
Styles.addStyleClass(title, Styles.TITLE_1);
grid.setVgap(8);
grid.setHgap(16);
var fieldColumn = new ColumnConstraints();
fieldColumn.setHgrow(Priority.ALWAYS);
grid.getColumnConstraints().addAll(new ColumnConstraints(), fieldColumn);
var config = Config.get();
add("Historial de respuestas:", "Respuestas que se guardan por paso; al superarlas se borran las más antiguas.",
1, config::getResponseHistory, config::setResponseHistory);
add("Tiempo de espera (s):", "Segundos que se espera a conectar con el servidor y a recibir su respuesta antes de dar la llamada por fallida.",
1, config::getCallTimeout, config::setCallTimeout);
add("Cambios a deshacer:", "Eliminaciones y modificaciones que se pueden deshacer con Ctrl+Z; las más antiguas se olvidan.",
1, config::getMaxUndo, config::setMaxUndo);
add("Agrupar ediciones (s):", "Las ediciones de un mismo fichero en estos segundos desde la primera se deshacen juntas. Con 0 se deshacen una a una.",
0, config::getUndoMergeSeconds, config::setUndoMergeSeconds);
var scroll = new ScrollPane(grid);
scroll.setFitToWidth(true);
scroll.setPadding(new Insets(4));
var cancel = new Button("Cancelar");
cancel.setCancelButton(true);
cancel.setOnAction(e -> close());
var save = new Button("Guardar cambios", FontIcon.of(MaterialDesignC.CONTENT_SAVE));
Styles.addStyleClass(save, Styles.ACCENT);
save.setDefaultButton(true);
save.setOnAction(e -> save());
var root = new BorderPane();
root.setPadding(new Insets(16));
root.setTop(title);
BorderPane.setMargin(title, new Insets(0, 0, 8, 0));
root.setCenter(scroll);
root.setBottom(new VBox(8, new Separator(), new HBox(8, new Spacer(), cancel, save)));
BorderPane.setMargin(root.getBottom(), new Insets(8, 0, 0, 0));
root.setPrefWidth(480);
var scene = new Scene(root);
if (owner != null && owner.getScene() != null)
scene.getStylesheets().addAll(owner.getScene().getStylesheets());
setScene(scene);
Packing.pack(this, scene);
}
private void add(String name, String description, int min, Supplier<Integer> get, Consumer<Integer> set) {
var label = new Label(name);
var field = new TextField(String.valueOf(get.get()));
// Only digits can be typed.
field.setTextFormatter(new TextFormatter<String>(change -> change.getControlNewText().matches("\\d*") ? change : null));
field.textProperty().addListener((obs, old, value) -> field.pseudoClassStateChanged(Styles.STATE_DANGER, false));
var tooltip = new Tooltip(description + (min > 0 ? " Mínimo %d.".formatted(min) : ""));
tooltip.setWrapText(true);
tooltip.setMaxWidth(360);
label.setTooltip(tooltip);
field.setTooltip(tooltip);
// Behind the label and the field, so the gaps of the row show the tooltip too.
var background = new Region();
Tooltip.install(background, tooltip);
var row = settings.size();
grid.add(background, 0, row, 2, 1);
grid.add(label, 0, row);
grid.add(field, 1, row);
settings.add(new Setting(field, min, set));
}
/** Saves when every value is valid; else marks the invalid fields and keeps the dialog open. */
private void save() {
var valid = true;
for (var setting : settings) {
var invalid = valueOf(setting) == null;
setting.field().pseudoClassStateChanged(Styles.STATE_DANGER, invalid);
valid &= ! invalid;
}
if (! valid) return;
for (var setting : settings)
setting.set().accept(valueOf(setting));
Config.get().save();
close();
}
/** Null when blank, too big or below the minimum. */
private static Integer valueOf(Setting setting) {
try {
var value = Integer.parseInt(setting.field().getText());
return value < setting.min() ? null : value;
} catch (NumberFormatException blankOrTooBig) {
return null;
}
}
}
@@ -0,0 +1,96 @@
package com.molnarandrei.sopa.ui;
import atlantafx.base.controls.Spacer;
import atlantafx.base.theme.Styles;
import com.molnarandrei.sopa.ui.lib.Packing;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
public class HelpDialog extends Stage {
private static final String[][] SHORTCUTS = {
{"Ctrl+N", "Crea dentro de lo seleccionado en el árbol: un caso en un proyecto, un paso en un caso o en el caso de un paso. Sin selección, un proyecto."},
{"Ctrl+S", "Guarda el editor o las propiedades abiertas."},
{"Enter", "Guarda el campo."},
{"Ctrl+Z", "En el árbol, deshace la última eliminación o modificación. Cada campo se guarda al salir de él, así que cada cambio se puede deshacer; las ediciones de un mismo fichero en 10 s (por defecto, en Configuración) se deshacen juntas."},
{"Ctrl+C / X / V", "En el árbol, copia, corta y pega casos y pasos."},
{"Supr", "En el árbol, elimina lo seleccionado."},
{"Tab / Mayús+Tab", "En el XML, sangra o quita la sangría."},
};
public HelpDialog(Window owner) {
initOwner(owner);
initModality(Modality.WINDOW_MODAL);
setTitle("Ayuda");
var shortcuts = new GridPane();
shortcuts.setHgap(16);
shortcuts.setVgap(8);
var descriptionColumn = new ColumnConstraints();
descriptionColumn.setHgrow(Priority.ALWAYS);
// The keys keep their width, the descriptions wrap in the rest.
var keysColumn = new ColumnConstraints();
keysColumn.setMinWidth(Region.USE_PREF_SIZE);
shortcuts.getColumnConstraints().addAll(keysColumn, descriptionColumn);
for (int row = 0; row < SHORTCUTS.length; row++) {
var keys = new Label(SHORTCUTS[row][0]);
Styles.addStyleClass(keys, Styles.TEXT_BOLD);
keys.setMinWidth(Region.USE_PREF_SIZE);
shortcuts.add(keys, 0, row);
shortcuts.add(text(SHORTCUTS[row][1]), 1, row);
}
var content = new VBox(8,
title("Sopa", Styles.TITLE_1),
text("Sopa prueba servicios SOAP. Un proyecto tiene casos de prueba y cada caso, pasos: llamadas SOAP con "
+ "aserciones y extracciones que guardan propiedades para los pasos siguientes. Ejecutar un caso o un "
+ "proyecto ejecuta sus pasos en orden y se detiene en el primero que falla."),
title("Pensada para agentes", Styles.TITLE_3),
text("Un proyecto son ficheros YAML y .properties legibles en su carpeta, descritos en su AGENTS.md. Tú o un "
+ "agente IA podéis editarlos desde fuera y la app los recarga al momento; lo que cambias en la app se "
+ "escribe en ellos."),
title("Atajos", Styles.TITLE_3),
shortcuts
);
content.setPadding(new Insets(4));
var scroll = new ScrollPane(content);
scroll.setFitToWidth(true);
var close = new Button("Cerrar");
close.setDefaultButton(true);
close.setCancelButton(true);
close.setOnAction(e -> close());
var root = new BorderPane();
root.setPadding(new Insets(16));
root.setCenter(scroll);
root.setBottom(new VBox(8, new Separator(), new HBox(new Spacer(), close)));
BorderPane.setMargin(root.getBottom(), new Insets(8, 0, 0, 0));
root.setPrefSize(560, 520);
var scene = new Scene(root);
if (owner != null && owner.getScene() != null)
scene.getStylesheets().addAll(owner.getScene().getStylesheets());
setScene(scene);
Packing.pack(this, scene);
}
private static Label title(String text, String style) {
var label = new Label(text);
Styles.addStyleClass(label, style);
return label;
}
private static Label text(String text) {
var label = new Label(text);
label.setWrapText(true);
// Else layouts give it the height of one line and it shows as "...".
label.setMinHeight(Region.USE_PREF_SIZE);
return label;
}
}
@@ -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++;
@@ -85,15 +88,14 @@ public class TestCaseEditorPane extends BorderPane implements Destroyable {
bottom.getChildren().add(actions); bottom.getChildren().add(actions);
activeToggle = new ToggleSwitch("Activo"); activeToggle = new ToggleSwitch("Activo");
activeToggle.selectedProperty().addListener((obs, old, value)-> testCase.setActive(value)); activeToggle.setSelected(testCase.isActive());
// Listener added after the initial value, so opening the editor does not save.
activeToggle.selectedProperty().addListener((obs, old, value)-> {
testCase.setActive(value);
submit.run();
});
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);
@@ -108,7 +110,6 @@ public class TestCaseEditorPane extends BorderPane implements Destroyable {
private void loadTestCase(TestCase testCase) { private void loadTestCase(TestCase testCase) {
title.setText("Caso %s".formatted(testCase.getName())); title.setText("Caso %s".formatted(testCase.getName()));
activeToggle.setSelected(testCase.isActive());
nameField.setText(testCase.getName()); nameField.setText(testCase.getName());
endpointField.setText(testCase.getEndpoint()); endpointField.setText(testCase.getEndpoint());
actionField.setText(testCase.getAction()); actionField.setText(testCase.getAction());
@@ -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);
@@ -95,22 +102,19 @@ public class StepEditorPane extends BorderPane implements Destroyable {
setBottom(bottom); setBottom(bottom);
activeToggle = new ToggleSwitch("Activo"); activeToggle = new ToggleSwitch("Activo");
activeToggle.selectedProperty().addListener((obs, old, value)-> step.setActive(value)); activeToggle.setSelected(step.isActive());
// Listener added after the initial value, so opening the editor does not save.
activeToggle.selectedProperty().addListener((obs, old, value)-> {
step.setActive(value);
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);
@@ -156,7 +160,6 @@ public class StepEditorPane extends BorderPane implements Destroyable {
private void loadStep(Step step) { private void loadStep(Step step) {
title.setText("Paso %s".formatted(step.getName())); title.setText("Paso %s".formatted(step.getName()));
activeToggle.setSelected(step.isActive());
payload.setXml(step.getPayload()); payload.setXml(step.getPayload());
} }
} }
@@ -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,34 @@
package com.molnarandrei.sopa.ui.lib;
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;
public final class Lineage {
private static final String SEPARATOR = " > ";
private Lineage() {}
public static String of(Kind kind, Path path) {
return switch (kind) {
case project -> ProjectService.nameOf(path);
case testcase -> of(Kind.project, projectOf(path)) + SEPARATOR + TestCaseService.nameOf(path);
case step -> of(Kind.testcase, testCaseOf(path)) + SEPARATOR + StepService.nameOf(path);
};
}
public static String withPath(Kind kind, Path path) {
return of(kind, path) + "\n" + path.getParent();
}
private static Path projectOf(Path testCasePath) {
return testCasePath.getParent().getParent().resolve("project.yml");
}
private static Path testCaseOf(Path stepPath) {
return stepPath.getParent().getParent().resolve("testcase.yml");
}
}
@@ -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();
});
}
}
@@ -5,6 +5,8 @@ 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.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.ConfigDialog;
import com.molnarandrei.sopa.ui.HelpDialog;
import com.molnarandrei.sopa.ui.PropertiesDialog; import com.molnarandrei.sopa.ui.PropertiesDialog;
import com.molnarandrei.sopa.ui.create.CreateProjectDialog; import com.molnarandrei.sopa.ui.create.CreateProjectDialog;
import javafx.event.EventHandler; import javafx.event.EventHandler;
@@ -17,8 +19,10 @@ import com.molnarandrei.sopa.project.ProjectService;
import javafx.scene.control.*; import javafx.scene.control.*;
import javafx.stage.*; import javafx.stage.*;
import org.kordamp.ikonli.javafx.FontIcon; import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.materialdesign2.MaterialDesignA;
import org.kordamp.ikonli.materialdesign2.MaterialDesignC; import org.kordamp.ikonli.materialdesign2.MaterialDesignC;
import org.kordamp.ikonli.materialdesign2.MaterialDesignF; import org.kordamp.ikonli.materialdesign2.MaterialDesignF;
import org.kordamp.ikonli.materialdesign2.MaterialDesignH;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.HashMap; import java.util.HashMap;
@@ -70,12 +74,20 @@ public class TopMenu extends MenuBar {
propertiesMenu = new Menu(); propertiesMenu = new Menu();
propertiesMenu.setGraphic(propertiesLabel); propertiesMenu.setGraphic(propertiesLabel);
var config = new MenuItem("Configuración", FontIcon.of(MaterialDesignC.COG));
config.setOnAction(e -> new ConfigDialog(getScene().getWindow()).show());
var help = new MenuItem("Ayuda", FontIcon.of(MaterialDesignH.HELP_CIRCLE_OUTLINE));
help.setOnAction(e -> new HelpDialog(getScene().getWindow()).show());
var appMenu = new Menu("Aplicación", FontIcon.of(MaterialDesignA.APPLICATION_COG));
appMenu.getItems().addAll(config, help);
// MenuBar only holds Menus, so the spacer is an empty, disabled Menu whose button grows (see layoutChildren). // MenuBar only holds Menus, so the spacer is an empty, disabled Menu whose button grows (see layoutChildren).
separatorMenu = new Menu(); separatorMenu = new Menu();
separatorMenu.setDisable(true); separatorMenu.setDisable(true);
getMenus().addAll( getMenus().addAll(
projectMenu, projectMenu,
appMenu,
separatorMenu, separatorMenu,
propertiesMenu propertiesMenu
); );
@@ -1,11 +1,9 @@
package com.molnarandrei.sopa.ui.navpane; package com.molnarandrei.sopa.ui.navpane;
import com.molnarandrei.sopa.project.ProjectRepository;
import com.molnarandrei.sopa.project.ProjectService; import com.molnarandrei.sopa.project.ProjectService;
import com.molnarandrei.sopa.step.StepRepository;
import com.molnarandrei.sopa.step.StepService; import com.molnarandrei.sopa.step.StepService;
import com.molnarandrei.sopa.testcase.TestCaseRepository;
import com.molnarandrei.sopa.testcase.TestCaseService; import com.molnarandrei.sopa.testcase.TestCaseService;
import com.molnarandrei.sopa.ui.lib.Lineage;
import com.molnarandrei.sopa.ui.lib.Packing; import com.molnarandrei.sopa.ui.lib.Packing;
import javafx.scene.control.Alert; import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonBar;
@@ -19,8 +17,13 @@ public class DeleteDialog {
public static void confirmAndDelete(TreeIdentity identity) { public static void confirmAndDelete(TreeIdentity identity) {
var alert = Packing.pack(new Alert(Alert.AlertType.CONFIRMATION, "", DELETE, CANCEL)); var alert = Packing.pack(new Alert(Alert.AlertType.CONFIRMATION, "", DELETE, CANCEL));
alert.setTitle("Eliminar"); alert.setTitle("Eliminar");
alert.setHeaderText("Seguro que desea eliminar el %s %s?".formatted(kindName(identity), nameOf(identity))); var name = switch (identity.kind()) {
alert.setContentText(identity.path().getParent().toString()); case project -> ProjectService.nameOf(identity.path());
case testcase -> TestCaseService.nameOf(identity.path());
case step -> StepService.nameOf(identity.path());
};
alert.setHeaderText("Seguro que desea eliminar el %s %s?".formatted(kindName(identity), name));
alert.setContentText(Lineage.withPath(identity.kind(), identity.path()));
// Delete is the default: enter confirms what the delete key started, escape cancels. // Delete is the default: enter confirms what the delete key started, escape cancels.
if (alert.showAndWait().orElse(CANCEL) == DELETE) if (alert.showAndWait().orElse(CANCEL) == DELETE)
switch (identity.kind()) { switch (identity.kind()) {
@@ -37,17 +40,4 @@ public class DeleteDialog {
case step -> "paso"; case step -> "paso";
}; };
} }
private static String nameOf(TreeIdentity identity) {
var path = identity.path();
try {
return switch (identity.kind()) {
case project -> ProjectRepository.get(path).getName();
case testcase -> TestCaseRepository.get(path).getName();
case step -> StepRepository.get(path).getName();
};
} catch (Exception unreadable) {
return path.getParent().getFileName().toString();
}
}
} }
@@ -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;
} }
@@ -125,7 +125,7 @@ public class SopaTreeCell extends TreeCell<TreeIdentity> {
if (empty || item == null) if (empty || item == null)
return; return;
getStyleClass().remove("text-bold"); getStyleClass().removeAll("text-bold", "inactive");
var path = item.path(); var path = item.path();
try { try {
switch (item.kind()) { switch (item.kind()) {
@@ -136,12 +136,16 @@ public class SopaTreeCell extends TreeCell<TreeIdentity> {
getStyleClass().add("text-bold"); getStyleClass().add("text-bold");
break; break;
case testcase: case testcase:
setText(TestCaseRepository.get(path).getName()); var testCase = TestCaseRepository.get(path);
setText(testCase.getName());
if (!testCase.isActive()) getStyleClass().add("inactive");
setGraphic(null); setGraphic(null);
setContextMenu(new TestCaseContextMenu(item.path())); setContextMenu(new TestCaseContextMenu(item.path()));
break; break;
case step: case step:
setText(StepRepository.get(path).getName()); var step = StepRepository.get(path);
setText(step.getName());
if (!step.isActive()) getStyleClass().add("inactive");
setContextMenu(new StepContextMenu(item.path())); setContextMenu(new StepContextMenu(item.path()));
setGraphic(flightIcon(flightStates.apply(path))); setGraphic(flightIcon(flightStates.apply(path)));
break; break;
@@ -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);
+5 -3
View File
@@ -1,3 +1,5 @@
> **Do not modify this file.** Sopa overwrites it whenever it migrates the project to a newer version, so any change here is lost.
# Sopa SOAP test project # Sopa SOAP test project
Plain YAML files. App watches folder, sees edits live. Plain YAML files. App watches folder, sees edits live.
@@ -32,7 +34,7 @@ endpoints:
version: 1.1 # or 1.2 version: 1.1 # or 1.2
headers: {} headers: {}
name: Test Project name: Test Project
properties: {} version: "2" # of the project files, the app migrates older ones: never change it
``` ```
testcase.yml testcase.yml
@@ -43,7 +45,6 @@ active: true
endpoint: "" endpoint: ""
headers: {} headers: {}
name: Alumni name: Alumni
properties: {}
``` ```
step.yml step.yml
@@ -101,11 +102,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.
+5
View File
@@ -43,3 +43,8 @@
.tree-cell .flight-icon.exception { .tree-cell .flight-icon.exception {
-fx-icon-color: -color-danger-fg; -fx-icon-color: -color-danger-fg;
} }
/* Deactivated testcases and steps appear de-emphasized in the project tree. */
.tree-cell.inactive {
-color-cell-fg: -color-fg-muted;
}
@@ -0,0 +1,68 @@
package com.molnarandrei.sopa.migrations;
import com.molnarandrei.sopa.data.yaml.Project;
import com.molnarandrei.sopa.data.yaml.TestCase;
import com.molnarandrei.sopa.project.ProjectRepository;
import com.molnarandrei.sopa.properties.PropertiesRepository;
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 MigrationTest {
@TempDir
Path folder;
@Test
public void versionIsTheWholeNumberBeforeAnyDot() {
assertEquals(1, Migration.versionOf(Map.of("version", "1.0.2")));
assertEquals(1, Migration.versionOf(Map.of("version", 1)));
assertEquals(2, Migration.versionOf(Map.of("version", "2")));
assertEquals(1, Migration.versionOf(Map.of()));
}
@Test
public void propertiesMoveToTheirFilesAndTheProjectIsCurrent() throws Exception {
var projectPath = folder.resolve("project.yml");
Files.writeString(projectPath, Project.HEADER + """
version: 1.0.2
endpoints: {}
headers: {}
name: P
properties:
host: localhost
""");
var testCasePath = folder.resolve("testcase-1").resolve("testcase.yml");
Files.createDirectories(testCasePath.getParent());
Files.writeString(testCasePath, TestCase.HEADER + """
name: C
properties:
alumnusAge: 20
alumnusName: Zoe
""");
// Written by a newer version, so it wins over the yml.
Files.writeString(PropertiesRepository.of(testCasePath), "alumnusName=Ana\n");
Files.writeString(folder.resolve("AGENTS.md"), "edited by the user");
Migration.migrate(projectPath);
assertEquals(String.valueOf(Migration.VERSION), ProjectRepository.get(projectPath).getVersion());
assertEquals(Map.of("host", "localhost"), PropertiesRepository.get(PropertiesRepository.of(projectPath)));
assertEquals(Map.of("alumnusAge", "20", "alumnusName", "Ana"), PropertiesRepository.get(PropertiesRepository.of(testCasePath)));
assertFalse(Files.readString(testCasePath).contains("properties"));
assertEquals("C", TestCaseRepository.get(testCasePath).getName());
assertTrue(Files.readString(folder.resolve("AGENTS.md")).startsWith("> **Do not modify this file.**"));
// A current project is left as it is.
Files.writeString(folder.resolve("AGENTS.md"), "untouched");
Migration.migrate(projectPath);
assertEquals("untouched", Files.readString(folder.resolve("AGENTS.md")));
}
}
@@ -45,6 +45,24 @@ public class ProjectFolderTest {
@Test @Test
public void agentsFileIsWrittenIntoTheProject() throws Exception { public void agentsFileIsWrittenIntoTheProject() throws Exception {
ProjectRepository.writeAgentsFile(folder); ProjectRepository.writeAgentsFile(folder);
assertTrue(Files.readString(folder.resolve("AGENTS.md")).startsWith("# Sopa")); assertTrue(Files.readString(folder.resolve("AGENTS.md")).startsWith("> **Do not modify this file.**"));
}
@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);
}
}
}