Merge branch 'develop' into feature/new-hub-keyloading

# Conflicts:
#	src/main/java/org/cryptomator/ui/keyloading/hub/CreateDeviceDto.java
#	src/main/java/org/cryptomator/ui/keyloading/hub/RegisterDeviceController.java
This commit is contained in:
Sebastian Stenzel
2023-06-30 16:20:59 +02:00
88 changed files with 1653 additions and 1420 deletions
@@ -13,6 +13,7 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
@DisplayName("Environment Variables Test")
public class EnvironmentTest {
@@ -22,41 +23,7 @@ public class EnvironmentTest {
@BeforeEach
public void init() {
env = Mockito.spy(Environment.getInstance());
Mockito.when(env.getHomeDir()).thenReturn(Path.of("/home/testuser"));
}
@Test
@DisplayName("cryptomator.settingsPath=~/.config/Cryptomator/settings.json:~/.Cryptomator/settings.json")
public void testSettingsPath() {
System.setProperty("cryptomator.settingsPath", "~/.config/Cryptomator/settings.json:~/.Cryptomator/settings.json");
List<Path> result = env.getSettingsPath().toList();
MatcherAssert.assertThat(result, Matchers.hasSize(2));
MatcherAssert.assertThat(result, Matchers.contains(Paths.get("/home/testuser/.config/Cryptomator/settings.json"), //
Paths.get("/home/testuser/.Cryptomator/settings.json")));
}
@Test
@DisplayName("cryptomator.ipcSocketPath=~/.config/Cryptomator/ipc.socket:~/.Cryptomator/ipc.socket")
public void testIpcSocketPath() {
System.setProperty("cryptomator.ipcSocketPath", "~/.config/Cryptomator/ipc.socket:~/.Cryptomator/ipc.socket");
List<Path> result = env.ipcSocketPath().toList();
MatcherAssert.assertThat(result, Matchers.hasSize(2));
MatcherAssert.assertThat(result, Matchers.contains(Paths.get("/home/testuser/.config/Cryptomator/ipc.socket"), //
Paths.get("/home/testuser/.Cryptomator/ipc.socket")));
}
@Test
@DisplayName("cryptomator.integrationsWin.keychainPaths=~/AppData/Roaming/Cryptomator/keychain.json")
public void testKeychainPath() {
System.setProperty("cryptomator.integrationsWin.keychainPaths", "~/AppData/Roaming/Cryptomator/keychain.json");
List<Path> result = env.getKeychainPath().toList();
MatcherAssert.assertThat(result, Matchers.hasSize(1));
MatcherAssert.assertThat(result, Matchers.contains(Paths.get("/home/testuser/AppData/Roaming/Cryptomator/keychain.json")));
}
@Test
@DisplayName("cryptomator.logDir=/foo/bar")
public void testAbsoluteLogDir() {
@@ -67,20 +34,9 @@ public class EnvironmentTest {
Assertions.assertTrue(logDir.isPresent());
}
@Test
@DisplayName("cryptomator.logDir=~/foo/bar")
public void testRelativeLogDir() {
System.setProperty("cryptomator.logDir", "~/foo/bar");
Optional<Path> logDir = env.getLogDir();
Assertions.assertTrue(logDir.isPresent());
Assertions.assertEquals(Paths.get("/home/testuser/foo/bar"), logDir.get());
}
@Nested
@DisplayName("Path Lists")
public class SettingsPath {
@DisplayName("Testing parsing path lists")
public class PathLists {
@Test
@DisplayName("test.path.property=")
@@ -93,7 +49,7 @@ public class EnvironmentTest {
@Test
@DisplayName("test.path.property=/foo/bar/test")
public void testSingleAbsolutePath() {
public void testSinglePath() {
System.setProperty("test.path.property", "/foo/bar/test");
List<Path> result = env.getPaths("test.path.property").toList();
@@ -102,27 +58,44 @@ public class EnvironmentTest {
}
@Test
@DisplayName("test.path.property=~/test")
public void testSingleHomeRelativePath() {
System.setProperty("test.path.property", "~/test");
@DisplayName("test.path.property=/foo/bar/test:/bar/nez/tost")
public void testTwoPaths() {
System.setProperty("test.path.property", "/foo/bar/test:bar/nez/tost");
List<Path> result = env.getPaths("test.path.property").toList();
MatcherAssert.assertThat(result, Matchers.hasSize(1));
MatcherAssert.assertThat(result, Matchers.hasItem(Paths.get("/home/testuser/test")));
}
@Test
@DisplayName("test.path.property=~/test:~/test2:/foo/bar/test")
public void testMultiplePaths() {
System.setProperty("test.path.property", "~/test:~/test2:/foo/bar/test");
List<Path> result = env.getPaths("test.path.property").toList();
MatcherAssert.assertThat(result, Matchers.hasSize(3));
MatcherAssert.assertThat(result, Matchers.contains(Paths.get("/home/testuser/test"), //
Paths.get("/home/testuser/test2"), //
Paths.get("/foo/bar/test")));
MatcherAssert.assertThat(result, Matchers.hasSize(2));
MatcherAssert.assertThat(result, Matchers.hasItems(Path.of("/foo/bar/test"), Path.of("bar/nez/tost")));
}
}
@Nested
public class VariablesContainingPathLists {
@Test
public void testSettingsPath() {
Mockito.doReturn(Stream.of()).when(env).getPaths(Mockito.anyString());
env.getSettingsPath();
Mockito.verify(env).getPaths("cryptomator.settingsPath");
}
@Test
public void testP12Path() {
Mockito.doReturn(Stream.of()).when(env).getPaths(Mockito.anyString());
env.getP12Path();
Mockito.verify(env).getPaths("cryptomator.p12Path");
}
@Test
public void testIpcSocketPath() {
Mockito.doReturn(Stream.of()).when(env).getPaths(Mockito.anyString());
env.getIpcSocketPath();
Mockito.verify(env).getPaths("cryptomator.ipcSocketPath");
}
@Test
public void testKeychainPath() {
Mockito.doReturn(Stream.of()).when(env).getPaths(Mockito.anyString());
env.getKeychainPath();
Mockito.verify(env).getPaths("cryptomator.integrationsWin.keychainPaths");
}
}
}
@@ -0,0 +1,151 @@
package org.cryptomator.common;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mockito;
import java.util.Map;
import java.util.Properties;
public class SubstitutingPropertiesTest {
SubstitutingProperties inTest;
@Nested
public class Processing {
@ParameterizedTest
@DisplayName("Test template replacement")
@CsvSource(textBlock = """
unknown.@{testToken}.test, unknown.@{testToken}.test
@{only*words*digits*under_score},@{only*words*digits*under_score}
C:\\Users\\@{appdir}\\dir, C:\\Users\\foobar\\dir
@{@{appdir}},@{foobar}
Replacing several @{appdir} with @{appdir}., Replacing several foobar with foobar.""")
public void test(String propertyValue, String expected) {
SubstitutingProperties inTest = new SubstitutingProperties(Mockito.mock(Properties.class), Map.of("APPDIR", "foobar"));
var result = inTest.process(propertyValue);
Assertions.assertEquals(expected, result);
}
@Test
@DisplayName("@{userhome} is replaced with the user home directory")
public void testPropSubstitutions() {
var props = new Properties();
props.setProperty("user.home", "OneUponABit");
inTest = new SubstitutingProperties(props, Map.of());
var result = inTest.process("@{userhome}");
Assertions.assertEquals("OneUponABit", result);
}
@DisplayName("Other keywords are replaced accordingly")
@ParameterizedTest(name = "Token \"{0}\" replaced with content of {1}")
@CsvSource(value = {"appdir, APPDIR, foobar", "appdata, APPDATA, bazbaz", "localappdata, LOCALAPPDATA, boboAlice"})
public void testEnvSubstitutions(String token, String envName, String expected) {
inTest = new SubstitutingProperties(new Properties(), Map.of(envName, expected));
var result = inTest.process("@{" + token + "}");
Assertions.assertEquals(expected, result);
}
}
@Nested
public class GetProperty {
@Test
@DisplayName("Undefined properties are not processed")
public void testNoProcessingOnNull() {
inTest = Mockito.spy(new SubstitutingProperties(new Properties(), Map.of()));
var result = inTest.getProperty("some.prop");
Assertions.assertNull(result);
Mockito.verify(inTest, Mockito.never()).process(Mockito.anyString());
}
@ParameterizedTest
@DisplayName("Properties not starting with \"cryptomator.\" are not processed")
@ValueSource(strings = {"example.foo", "cryptomatorSomething.foo", "org.cryptomator.foo", "cryPtoMAtor.foo"})
public void testNoProcessingOnNotCryptomator(String propKey) {
var props = new Properties();
props.setProperty(propKey, "someValue");
inTest = Mockito.spy(new SubstitutingProperties(props, Map.of()));
var result = inTest.getProperty("some.prop");
Assertions.assertNull(result);
Mockito.verify(inTest, Mockito.never()).process(Mockito.anyString());
}
@Test
@DisplayName("Non-null property starting with \"cryptomator.\" is processed")
public void testProcessing() {
var props = new Properties();
props.setProperty("cryptomator.prop", "someValue");
inTest = Mockito.spy(new SubstitutingProperties(props, Map.of()));
Mockito.doReturn("someValue").when(inTest).process(Mockito.anyString());
inTest.getProperty("cryptomator.prop");
Mockito.verify(inTest).process("someValue");
}
@Test
@DisplayName("Default value is not processed")
public void testNoProcessingDefault() {
var props = Mockito.mock(Properties.class);
Mockito.when(props.getProperty("cryptomator.prop")).thenReturn(null);
inTest = Mockito.spy(new SubstitutingProperties(props, Map.of()));
Mockito.doReturn("someValue").when(inTest).process(Mockito.anyString());
var result = inTest.getProperty("cryptomator.prop", "a default");
Assertions.assertEquals("a default", result);
Mockito.verify(inTest, Mockito.never()).process(Mockito.any());
}
}
@ParameterizedTest(name = "{0}={1} -> {0}={2}")
@DisplayName("Replace @{userhome} during getProperty()")
@CsvSource(quoteCharacter = '"', textBlock = """
cryptomator.settingsPath, "@{userhome}/.config/Cryptomator/settings.json:@{userhome}/.Cryptomator/settings.json", "/home/.config/Cryptomator/settings.json:/home/.Cryptomator/settings.json"
cryptomator.ipcSocketPath, "@{userhome}/.config/Cryptomator/ipc.socket:@{userhome}/.Cryptomator/ipc.socket", "/home/.config/Cryptomator/ipc.socket:/home/.Cryptomator/ipc.socket"
not.cryptomator.not.substituted, "@{userhome}/foo", "@{userhome}/foo"
cryptomator.no.placeholder.found, "foo/bar", "foo/bar"
""")
public void testEndToEndPropsSource(String key, String raw, String substituted) {
var delegate = Mockito.mock(Properties.class);
Mockito.doReturn("/home").when(delegate).getProperty("user.home");
Mockito.doReturn(raw).when(delegate).getProperty(key);
var inTest = new SubstitutingProperties(delegate, Map.of());
var result = inTest.getProperty(key);
Assertions.assertEquals(substituted, result);
}
@ParameterizedTest(name = "{0}={1} -> {0}={2}")
@DisplayName("Replace appdata,localappdata or appdir during getProperty()")
@CsvSource(quoteCharacter = '"', textBlock = """
cryptomator.settingsPath, "@{appdata}/Cryptomator/settings.json", "C:\\Users\\JimFang\\AppData\\Roaming/Cryptomator/settings.json"
cryptomator.ipcSocketPath, "@{localappdata}/Cryptomator/ipc.socket", "C:\\Users\\JimFang\\AppData\\Local/Cryptomator/ipc.socket"
cryptomator.integrationsLinux.trayIconsDir, "@{appdir}/hicolor", "/squashfs1337/usr/hicolor"
not.cryptomator.not.substituted, "@{appdir}/foo", "@{appdir}/foo"
cryptomator.no.placeholder.found, "foo/bar", "foo/bar"
""")
public void testEndToEndEnvSource(String key, String raw, String substituted) {
var delegate = Mockito.mock(Properties.class);
Mockito.doReturn(raw).when(delegate).getProperty(key);
var env = Map.of("APPDATA", "C:\\Users\\JimFang\\AppData\\Roaming", //
"LOCALAPPDATA", "C:\\Users\\JimFang\\AppData\\Local", //
"APPDIR", "/squashfs1337/usr");
var inTest = new SubstitutingProperties(delegate, env);
var result = inTest.getProperty(key);
Assertions.assertEquals(substituted, result);
}
}
@@ -1,61 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 Skymatic UG (haftungsbeschränkt).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the accompanying LICENSE file.
*******************************************************************************/
package org.cryptomator.common.settings;
import org.cryptomator.common.Environment;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mockito;
import java.io.IOException;
public class SettingsJsonAdapterTest {
private final Environment env = Mockito.mock(Environment.class);
private final SettingsJsonAdapter adapter = new SettingsJsonAdapter(env);
@Test
public void testDeserialize() throws IOException {
String json = """
{
"directories": [
{"id": "1", "path": "/vault1", "mountName": "vault1", "winDriveLetter": "X"},
{"id": "2", "path": "/vault2", "mountName": "vault2", "winDriveLetter": "Y"}
],
"autoCloseVaults" : true,
"checkForUpdatesEnabled": true,
"port": 8080,
"language": "de-DE",
"numTrayNotifications": 42
}
""";
Settings settings = adapter.fromJson(json);
Assertions.assertTrue(settings.checkForUpdates().get());
Assertions.assertEquals(2, settings.getDirectories().size());
Assertions.assertEquals(8080, settings.port().get());
Assertions.assertEquals(true, settings.autoCloseVaults().get());
Assertions.assertEquals("de-DE", settings.languageProperty().get());
Assertions.assertEquals(42, settings.numTrayNotifications().get());
}
@SuppressWarnings("SpellCheckingInspection")
@ParameterizedTest(name = "fromJson() should throw IOException for input: {0}")
@ValueSource(strings = { //
"", //
"<html>", //
"{invalidjson}" //
})
public void testDeserializeMalformed(String input) {
Assertions.assertThrows(IOException.class, () -> {
adapter.fromJson(input);
});
}
}
@@ -0,0 +1,79 @@
package org.cryptomator.common.settings;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.IOException;
import java.util.List;
import static org.hamcrest.CoreMatchers.containsString;
public class SettingsJsonTest {
@Test
public void testDeserialize() throws IOException {
String jsonStr = """
{
"directories": [
{"id": "1", "path": "/vault1", "mountName": "vault1", "winDriveLetter": "X", "shouldBeIgnored": true},
{"id": "2", "path": "/vault2", "mountName": "vault2", "winDriveLetter": "Y", "mountFlags":"--foo --bar"}
],
"autoCloseVaults" : true,
"checkForUpdatesEnabled": true,
"port": 8080,
"language": "de-DE",
"numTrayNotifications": 42
}
""";
var jsonObj = new ObjectMapper().reader().readValue(jsonStr, SettingsJson.class);
Assertions.assertTrue(jsonObj.checkForUpdatesEnabled);
Assertions.assertEquals(2, jsonObj.directories.size());
Assertions.assertEquals("/vault1", jsonObj.directories.get(0).path);
Assertions.assertEquals("/vault2", jsonObj.directories.get(1).path);
Assertions.assertEquals("--foo --bar", jsonObj.directories.get(1).mountFlags);
Assertions.assertEquals(8080, jsonObj.port);
Assertions.assertTrue(jsonObj.autoCloseVaults);
Assertions.assertEquals("de-DE", jsonObj.language);
Assertions.assertEquals(42, jsonObj.numTrayNotifications);
}
@SuppressWarnings("SpellCheckingInspection")
@ParameterizedTest(name = "throw JacksonException for input: {0}")
@ValueSource(strings = { //
"", //
"<html>", //
"{invalidjson}" //
})
public void testDeserializeMalformed(String input) {
var objectMapper = new ObjectMapper().reader();
Assertions.assertThrows(JacksonException.class, () -> {
objectMapper.readValue(input, SettingsJson.class);
});
}
@Test
public void testSerialize() throws JsonProcessingException {
var jsonObj = new SettingsJson();
jsonObj.directories = List.of(new VaultSettingsJson(), new VaultSettingsJson());
jsonObj.directories.get(0).id = "test";
jsonObj.theme = UiTheme.DARK;
jsonObj.showTrayIcon = false;
var jsonStr = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(jsonObj);
MatcherAssert.assertThat(jsonStr, containsString("\"theme\" : \"DARK\""));
MatcherAssert.assertThat(jsonStr, containsString("\"showTrayIcon\" : false"));
MatcherAssert.assertThat(jsonStr, containsString("\"useKeychain\" : true"));
MatcherAssert.assertThat(jsonStr, containsString("\"actionAfterUnlock\" : \"ASK\""));
}
}
@@ -18,21 +18,21 @@ public class SettingsTest {
Environment env = Mockito.mock(Environment.class);
@SuppressWarnings("unchecked") Consumer<Settings> changeListener = Mockito.mock(Consumer.class);
Settings settings = new Settings(env);
Settings settings = Settings.create(env);
settings.setSaveCmd(changeListener);
VaultSettings vaultSettings = VaultSettings.withRandomId();
Mockito.verify(changeListener, Mockito.times(0)).accept(settings);
// first change (to property):
settings.port().set(42428);
settings.port.set(42428);
Mockito.verify(changeListener, Mockito.times(1)).accept(settings);
// second change (to list):
settings.getDirectories().add(vaultSettings);
settings.directories.add(vaultSettings);
Mockito.verify(changeListener, Mockito.times(2)).accept(settings);
// third change (to property of list item):
vaultSettings.displayName().set("asd");
vaultSettings.displayName.set("asd");
Mockito.verify(changeListener, Mockito.times(3)).accept(settings);
}
@@ -1,67 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 Skymatic UG (haftungsbeschränkt).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the accompanying LICENSE file.
*******************************************************************************/
package org.cryptomator.common.settings;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.file.Paths;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class VaultSettingsJsonAdapterTest {
private final VaultSettingsJsonAdapter adapter = new VaultSettingsJsonAdapter();
@Test
public void testDeserialize() throws IOException {
String json = "{\"id\": \"foo\", \"path\": \"/foo/bar\", \"displayName\": \"test\", \"winDriveLetter\": \"X\", \"shouldBeIgnored\": true, \"individualMountPath\": \"/home/test/crypto\", \"mountFlags\":\"--foo --bar\"}";
JsonReader jsonReader = new JsonReader(new StringReader(json));
VaultSettings vaultSettings = adapter.read(jsonReader);
assertAll(
() -> assertEquals("foo", vaultSettings.getId()),
() -> assertEquals(Paths.get("/foo/bar"), vaultSettings.path().get()),
() -> assertEquals("test", vaultSettings.displayName().get()),
() -> assertEquals("--foo --bar", vaultSettings.mountFlags().get())
);
}
@SuppressWarnings("SpellCheckingInspection")
@Test
public void testSerialize() throws IOException {
VaultSettings vaultSettings = new VaultSettings("test");
vaultSettings.path().set(Paths.get("/foo/bar"));
vaultSettings.displayName().set("mountyMcMountFace");
vaultSettings.mountFlags().set("--foo --bar");
StringWriter buf = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(buf);
adapter.write(jsonWriter, vaultSettings);
String result = buf.toString();
assertAll(
() -> assertThat(result, containsString("\"id\":\"test\"")),
() -> {
if (System.getProperty("os.name").contains("Windows")) {
assertThat(result, containsString("\"path\":\"\\\\foo\\\\bar\""));
} else {
assertThat(result, containsString("\"path\":\"/foo/bar\""));
}
},
() -> assertThat(result, containsString("\"displayName\":\"mountyMcMountFace\"")),
() -> assertThat(result, containsString("\"mountFlags\":\"--foo --bar\""))
);
}
}
@@ -1,29 +0,0 @@
package org.cryptomator.common.vaults;
import org.cryptomator.common.settings.Settings;
import org.cryptomator.common.settings.VaultSettings;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import java.nio.file.Path;
public class VaultModuleTest {
private final Settings settings = Mockito.mock(Settings.class);
private final VaultSettings vaultSettings = Mockito.mock(VaultSettings.class);
private final VaultModule module = new VaultModule();
@BeforeEach
public void setup(@TempDir Path tmpDir) {
Mockito.when(vaultSettings.mountName()).thenReturn(Bindings.createStringBinding(() -> "TEST"));
Mockito.when(vaultSettings.usesReadOnlyMode()).thenReturn(new SimpleBooleanProperty(true));
Mockito.when(vaultSettings.displayName()).thenReturn(new SimpleStringProperty("Vault"));
System.setProperty("user.home", tmpDir.toString());
}
}
@@ -0,0 +1,145 @@
package org.cryptomator.ui.error;
import org.cryptomator.common.Environment;
import org.cryptomator.common.ErrorCode;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.Mockito;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.util.concurrent.ExecutorService;
class ErrorControllerTest {
Application application;
String stackTrace;
ErrorCode errorCode;
Scene previousScene;
Stage window;
Environment environment;
ExecutorService executorService;
ErrorController errorController;
@BeforeEach
public void beforeEach() {
application = Mockito.mock(Application.class);
stackTrace = "This is a stackTrace mock";
errorCode = Mockito.mock(ErrorCode.class);
previousScene = Mockito.mock(Scene.class);
window = Mockito.mock(Stage.class);
environment = Mockito.mock(Environment.class);
executorService = Mockito.mock(ExecutorService.class);
errorController = new ErrorController(application, stackTrace, errorCode, previousScene, window, environment, executorService);
}
private ErrorDiscussion createErrorDiscussion(String title, int upvoteCount, ErrorDiscussion.Answer answer) {
ErrorDiscussion ed = new ErrorDiscussion();
ed.title = title;
ed.upvoteCount = upvoteCount;
ed.answer = answer;
return ed;
}
@DisplayName("compare error discussions by upvote count")
@ParameterizedTest
@CsvSource(textBlock = """
10, <, 5
8, >, 15
10, =, 10
""")
public void testCompareUpvoteCount(int leftUpvoteCount, char expected, int rightUpvoteCount) {
int expectedResult = switch (expected) {
case '<' -> -1;
case '>' -> +1;
default -> 0;
};
var left = createErrorDiscussion("", leftUpvoteCount, null);
var right = createErrorDiscussion("", rightUpvoteCount, null);
int result = errorController.compareUpvoteCount(left, right);
Assertions.assertEquals(expectedResult, Integer.signum(result));
}
@DisplayName("compare error discussions by existence of an answer")
@ParameterizedTest
@CsvSource(textBlock = """
false, =, false
true, =, true
true, <, false
false, >, true
""")
public void testCompareIsAnswered(boolean leftIsAnswered, char expected, boolean rightIsAnswered) {
var answer = new ErrorDiscussion.Answer();
int expectedResult = switch (expected) {
case '<' -> -1;
case '>' -> +1;
default -> 0;
};
var left = createErrorDiscussion("", 0, leftIsAnswered ? answer : null);
var right = createErrorDiscussion("", 0, rightIsAnswered ? answer : null);
int result = errorController.compareIsAnswered(left, right);
Assertions.assertEquals(expectedResult, result);
}
@DisplayName("compare error codes by full error code")
@ParameterizedTest
@CsvSource(textBlock = """
Error 0000:0000:0000, =, Error 0000:0000:0000
Error 6HU1:12H1:HU7J, <, Error 0000:0000:0000
Error 0000:0000:0000, >, Error 6HU1:12H1:HU7J
""")
public void testCompareByFullErrorCode(String leftTitle, char expected, String rightTitle) {
Mockito.when(errorCode.toString()).thenReturn("6HU1:12H1:HU7J");
int expectedResult = switch (expected) {
case '<' -> -1;
case '>' -> +1;
default -> 0;
};
var left = createErrorDiscussion(leftTitle, 0, null);
var right = createErrorDiscussion(rightTitle, 0, null);
int result = errorController.compareByFullErrorCode(left, right);
Assertions.assertEquals(expectedResult, result);
}
@DisplayName("compare error codes by root cause")
@ParameterizedTest
@CsvSource(textBlock = """
Error 6HU1:12H1:0000, =, Error 6HU1:12H1:0000
Error 6HU1:12H1:0007, =, Error 6HU1:12H1:0042
Error 0000:0000:0000, =, Error 0000:0000:0000
Error 6HU1:12H1:0000, <, Error 0000:0000:0000
Error 6HU1:12H1:0000, <, Error 6HU1:0000:0000
Error 0000:0000:0000, >, Error 6HU1:12H1:0000
Error 6HU1:0000:0000, >, Error 6HU1:12H1:0000
""")
public void testCompareByRootCauseCode(String leftTitle, char expected, String rightTitle) {
Mockito.when(errorCode.methodCode()).thenReturn("6HU1");
Mockito.when(errorCode.rootCauseCode()).thenReturn("12H1");
int expectedResult = switch (expected) {
case '<' -> -1;
case '>' -> +1;
default -> 0;
};
var left = createErrorDiscussion(leftTitle, 0, null);
var right = createErrorDiscussion(rightTitle, 0, null);
int result = errorController.compareByRootCauseCode(left, right);
Assertions.assertEquals(expectedResult, result);
}
@DisplayName("check if the error code contains the method code")
@ParameterizedTest
@CsvSource(textBlock = """
Error 6HU1:0000:0000, true
Error 0000:0000:0000, false
""")
public void testContainsMethodCode(String title, boolean expectedResult) {
Mockito.when(errorCode.methodCode()).thenReturn("6HU1");
var ed = createErrorDiscussion(title, 0, null);
boolean result = errorController.containsMethodCode(ed);
Assertions.assertEquals(expectedResult, result);
}
}
@@ -0,0 +1,19 @@
package org.cryptomator.ui.keyloading.hub;
import com.auth0.jwt.JWT;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class HubConfigTest {
@Test
@DisplayName("can parse JWT with unknown fields in header claim \"hub\"")
public void testParseJWTWithUnknownFields() {
var jwt = JWT.decode("eyJraWQiOiIxMjMiLCJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiIsImh1YiI6eyJ1bmtub3duRmllbGQiOjQyLCJjbGllbnRJZCI6ImNyeXB0b21hdG9yIn19.eyJqdGkiOiI0NTYifQ.e1CStFf5fdh9ofX_6O8_LfbHfHEJZqUpuYNWz9xZp0I");
var claim = jwt.getHeaderClaim("hub");
var hubConfig = Assertions.assertDoesNotThrow(() -> claim.as(HubConfig.class));
Assertions.assertEquals("cryptomator", hubConfig.clientId);
}
}