From 5512ea1af52c8b13fc07d9291f1c3f66d9c9b835 Mon Sep 17 00:00:00 2001 From: Christian Femers Date: Fri, 1 Apr 2022 02:25:14 +0200 Subject: [PATCH] Refactor localization and simplify throwing localized assertion failures --- .../de/tum/in/test/api/dynamic/Check.java | 17 ++- .../tum/in/test/api/dynamic/DynamicClass.java | 17 ++- .../test/api/dynamic/DynamicConstructor.java | 14 +-- .../tum/in/test/api/dynamic/DynamicField.java | 24 ++-- .../in/test/api/dynamic/DynamicMethod.java | 22 ++-- .../in/test/api/internal/ReportingUtils.java | 6 +- .../in/test/api/internal/TestGuardUtils.java | 21 ++-- .../in/test/api/internal/TimeoutUtils.java | 4 +- .../sanitization/SanitizationException.java | 4 +- .../de/tum/in/test/api/io/AbstractLine.java | 8 +- .../java/de/tum/in/test/api/io/IOTester.java | 4 +- .../de/tum/in/test/api/io/InputTester.java | 4 +- .../de/tum/in/test/api/io/TestOutStream.java | 6 +- .../in/test/api/localization/Messages.java | 20 ++-- .../api/security/ArtemisSecurityManager.java | 26 ++--- .../api/structural/AttributeTestProvider.java | 16 +-- .../api/structural/ClassTestProvider.java | 18 ++- .../structural/ConstructorTestProvider.java | 8 +- .../api/structural/MethodTestProvider.java | 12 +- .../structural/StructuralTestProvider.java | 4 +- .../testutils/ClassNameScanner.java | 22 ++-- .../in/test/api/util/ReflectionTestUtils.java | 110 +++++++++--------- .../test/integration/testuser/LocaleUser.java | 2 +- 23 files changed, 186 insertions(+), 203 deletions(-) diff --git a/src/main/java/de/tum/in/test/api/dynamic/Check.java b/src/main/java/de/tum/in/test/api/dynamic/Check.java index 9c00bb10..6d6a1eb2 100644 --- a/src/main/java/de/tum/in/test/api/dynamic/Check.java +++ b/src/main/java/de/tum/in/test/api/dynamic/Check.java @@ -1,7 +1,6 @@ package de.tum.in.test.api.dynamic; -import static de.tum.in.test.api.localization.Messages.formatLocalized; -import static org.junit.jupiter.api.Assertions.fail; +import static de.tum.in.test.api.localization.Messages.localizedFailure; import java.lang.reflect.Modifier; import java.util.function.Supplier; @@ -16,49 +15,49 @@ public enum Check { @Override void checkModifiers(int modifiers, Supplier desc) { if (!Modifier.isStatic(modifiers)) - fail(formatLocalized("dynamics.check.not_static", desc.get())); //$NON-NLS-1$ + throw localizedFailure("dynamics.check.not_static", desc.get()); //$NON-NLS-1$ } }, NOT_STATIC { @Override void checkModifiers(int modifiers, Supplier desc) { if (Modifier.isStatic(modifiers)) - fail(formatLocalized("dynamics.check.static", desc.get())); //$NON-NLS-1$ + throw localizedFailure("dynamics.check.static", desc.get()); //$NON-NLS-1$ } }, FINAL { @Override void checkModifiers(int modifiers, Supplier desc) { if (!Modifier.isFinal(modifiers)) - fail(formatLocalized("dynamics.check.not_final", desc.get())); //$NON-NLS-1$ + throw localizedFailure("dynamics.check.not_final", desc.get()); //$NON-NLS-1$ } }, NOT_FINAL { @Override void checkModifiers(int modifiers, Supplier desc) { if (Modifier.isFinal(modifiers)) - fail(formatLocalized("dynamics.check.final", desc.get())); //$NON-NLS-1$ + throw localizedFailure("dynamics.check.final", desc.get()); //$NON-NLS-1$ } }, PUBLIC { @Override void checkModifiers(int modifiers, Supplier desc) { if (!Modifier.isPublic(modifiers)) - fail(formatLocalized("dynamics.check.not_public", desc.get())); //$NON-NLS-1$ + throw localizedFailure("dynamics.check.not_public", desc.get()); //$NON-NLS-1$ } }, NOT_PUBLIC { @Override void checkModifiers(int modifiers, Supplier desc) { if (Modifier.isPublic(modifiers)) - fail(formatLocalized("dynamics.check.public", desc.get())); //$NON-NLS-1$ + throw localizedFailure("dynamics.check.public", desc.get()); //$NON-NLS-1$ } }, PACKAGE_PRIVATE { @Override void checkModifiers(int modifiers, Supplier desc) { if (Modifier.isPublic(modifiers) || Modifier.isPrivate(modifiers) || Modifier.isProtected(modifiers)) - fail(formatLocalized("dynamics.check.not_package", desc.get())); //$NON-NLS-1$ + throw localizedFailure("dynamics.check.not_package", desc.get()); //$NON-NLS-1$ } }; diff --git a/src/main/java/de/tum/in/test/api/dynamic/DynamicClass.java b/src/main/java/de/tum/in/test/api/dynamic/DynamicClass.java index 8194928c..0c7cc591 100644 --- a/src/main/java/de/tum/in/test/api/dynamic/DynamicClass.java +++ b/src/main/java/de/tum/in/test/api/dynamic/DynamicClass.java @@ -1,7 +1,6 @@ package de.tum.in.test.api.dynamic; -import static de.tum.in.test.api.localization.Messages.formatLocalized; -import static org.junit.jupiter.api.Assertions.fail; +import static de.tum.in.test.api.localization.Messages.*; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -45,7 +44,7 @@ public Class toClass() { try { clazz = (Class) Class.forName(name); } catch (ClassNotFoundException e) { - fail(formatLocalized("dynamics.class.not_found", name), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.class.not_found", name); //$NON-NLS-1$ } } return clazz; @@ -87,7 +86,7 @@ public T cast(Object obj) { return null; if (rClass.isPrimitive()) { if (obj == null) - throw new NullPointerException(formatLocalized("dynamics.class.null", getName())); //$NON-NLS-1$ + throw new NullPointerException(localized("dynamics.class.null", getName())); //$NON-NLS-1$ Class objClass = obj.getClass(); Class wrapper = primitiveWrappers.get(rClass); if (objClass.equals(wrapper)) @@ -160,7 +159,7 @@ public void check(Check... checks) { toClass(); int modifiers = toClass().getModifiers(); for (Check check : checks) - check.checkModifiers(modifiers, () -> formatLocalized("dynamics.class.name", this)); //$NON-NLS-1$ + check.checkModifiers(modifiers, () -> localized("dynamics.class.name", this)); //$NON-NLS-1$ } public int checkForPublicOrProtectedMethods(DynamicMethod... exceptions) { @@ -178,12 +177,12 @@ public int checkForPublicOrProtectedMethods(List> exceptions) { String sig = DynamicMethod.signatureOf(m); if (!"main(java.lang.String[])".endsWith(sig) && !publicMethods.contains(sig) //$NON-NLS-1$ && !objectMethods.contains(sig)) - fail(formatLocalized("dynamics.class.method_public", sig)); //$NON-NLS-1$ + throw localizedFailure("dynamics.class.method_public", sig); //$NON-NLS-1$ } if (Modifier.isProtected(m.getModifiers())) { String sig = DynamicMethod.signatureOf(m); if (!objectMethods.contains(sig)) - fail(formatLocalized("dynamics.class.method_protected", sig)); //$NON-NLS-1$ + throw localizedFailure("dynamics.class.method_protected", sig); //$NON-NLS-1$ } checked++; } @@ -196,7 +195,7 @@ public int checkForNonPrivateFields() { if (f.isSynthetic()) continue; if (!Modifier.isPrivate(f.getModifiers())) - fail(formatLocalized("dynamics.class.field_private", f)); //$NON-NLS-1$ + throw localizedFailure("dynamics.class.field_private", f); //$NON-NLS-1$ checked++; } return checked; @@ -208,7 +207,7 @@ public int checkForNonFinalFields() { if (f.isSynthetic()) continue; if (!Modifier.isFinal(f.getModifiers())) - fail(formatLocalized("dynamics.class.field_final", f)); //$NON-NLS-1$ + throw localizedFailure("dynamics.class.field_final", f); //$NON-NLS-1$ checked++; } return checked; diff --git a/src/main/java/de/tum/in/test/api/dynamic/DynamicConstructor.java b/src/main/java/de/tum/in/test/api/dynamic/DynamicConstructor.java index 71e6135e..1d239a60 100644 --- a/src/main/java/de/tum/in/test/api/dynamic/DynamicConstructor.java +++ b/src/main/java/de/tum/in/test/api/dynamic/DynamicConstructor.java @@ -1,8 +1,7 @@ package de.tum.in.test.api.dynamic; import static de.tum.in.test.api.dynamic.DynamicMethod.*; -import static de.tum.in.test.api.localization.Messages.formatLocalized; -import static org.junit.jupiter.api.Assertions.fail; +import static de.tum.in.test.api.localization.Messages.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -31,7 +30,7 @@ public Constructor toConstructor() { constructor = owner.toClass().getDeclaredConstructor(DynamicClass.resolveAll(parameters)); constructor.trySetAccessible(); } catch (NoSuchMethodException e) { - fail(formatLocalized("dynamics.constructor.not_found", owner, descParams(this.parameters)), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.constructor.not_found", owner, descParams(this.parameters)); //$NON-NLS-1$ } } return constructor; @@ -54,17 +53,16 @@ public T newInstance(Object... params) { try { return toConstructor().newInstance(params); } catch (InstantiationException e) { - fail(formatLocalized("dynamics.constructor.abstract", owner), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.constructor.abstract", owner); //$NON-NLS-1$ } catch (IllegalAccessException e) { - fail(formatLocalized("dynamics.constructor.access", this), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.constructor.access", this); //$NON-NLS-1$ } catch (IllegalArgumentException e) { - fail(formatLocalized("dynamics.constructor.arguments", this, descArgs(params)), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.constructor.arguments", this, descArgs(params)); //$NON-NLS-1$ } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) throw (RuntimeException) e.getTargetException(); throw UnexpectedExceptionError.wrap(e.getTargetException()); } - return null; // unreachable } @Override @@ -77,6 +75,6 @@ public void check(Check... checks) { toConstructor(); int modifiers = toConstructor().getModifiers(); for (Check check : checks) - check.checkModifiers(modifiers, () -> formatLocalized("dynamics.constructor.name", this)); //$NON-NLS-1$ + check.checkModifiers(modifiers, () -> localized("dynamics.constructor.name", this)); //$NON-NLS-1$ } } diff --git a/src/main/java/de/tum/in/test/api/dynamic/DynamicField.java b/src/main/java/de/tum/in/test/api/dynamic/DynamicField.java index f5cc801b..16f94924 100644 --- a/src/main/java/de/tum/in/test/api/dynamic/DynamicField.java +++ b/src/main/java/de/tum/in/test/api/dynamic/DynamicField.java @@ -1,7 +1,6 @@ package de.tum.in.test.api.dynamic; -import static de.tum.in.test.api.localization.Messages.formatLocalized; -import static org.junit.jupiter.api.Assertions.fail; +import static de.tum.in.test.api.localization.Messages.*; import java.lang.reflect.Field; import java.util.ArrayList; @@ -40,12 +39,11 @@ public DynamicField(DynamicClass dClass, DynamicClass fType, boolean ignor public Field toField() { if (field == null) { var of = findField(owner.toClass()); - if (of.isPresent()) { - field = of.get(); - field.trySetAccessible(); - } else { - fail(formatLocalized("dynamics.field.not_found", name)); //$NON-NLS-1$ + if (!of.isPresent()) { + throw localizedFailure("dynamics.field.not_found", name); //$NON-NLS-1$ } + field = of.get(); + field.trySetAccessible(); } return field; } @@ -67,22 +65,20 @@ public T getOf(Object o) { try { return type.cast(toField().get(o)); } catch (IllegalAccessException e) { - fail(formatLocalized("dynamics.field.access", name, owner), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.field.access", name, owner); //$NON-NLS-1$ } catch (IllegalArgumentException e) { - fail(formatLocalized("dynamics.field.target", name, owner), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.field.target", name, owner); //$NON-NLS-1$ } catch (ClassCastException e) { - fail(formatLocalized("dynamics.field.cast", name, owner, type.getName()), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.field.cast", name, owner, type.getName()); //$NON-NLS-1$ } - return null; // unreachable } public T getStatic() { try { return getOf(null); } catch (NullPointerException e) { - fail(formatLocalized("dynamics.field.static", name, owner), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.field.static", name, owner); //$NON-NLS-1$ } - return null; // unreachable } private Optional findField(Class c) { @@ -111,6 +107,6 @@ public String toString() { public void check(Check... checks) { int modifiers = toField().getModifiers(); for (Check check : checks) - check.checkModifiers(modifiers, () -> formatLocalized("dynamics.field.name", this)); //$NON-NLS-1$ + check.checkModifiers(modifiers, () -> localized("dynamics.field.name", this)); //$NON-NLS-1$ } } diff --git a/src/main/java/de/tum/in/test/api/dynamic/DynamicMethod.java b/src/main/java/de/tum/in/test/api/dynamic/DynamicMethod.java index 3d52981a..46ae5db3 100644 --- a/src/main/java/de/tum/in/test/api/dynamic/DynamicMethod.java +++ b/src/main/java/de/tum/in/test/api/dynamic/DynamicMethod.java @@ -1,7 +1,6 @@ package de.tum.in.test.api.dynamic; -import static de.tum.in.test.api.localization.Messages.formatLocalized; -import static org.junit.jupiter.api.Assertions.fail; +import static de.tum.in.test.api.localization.Messages.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -47,9 +46,9 @@ public Method toMethod() { m = owner.toClass().getDeclaredMethod(name, DynamicClass.resolveAll(parameters)); m.trySetAccessible(); if (!returnType.toClass().isAssignableFrom(m.getReturnType())) - fail(formatLocalized("dynamics.method.return", this, returnType)); //$NON-NLS-1$ + throw localizedFailure("dynamics.method.return", this, returnType); //$NON-NLS-1$ } catch (NoSuchMethodException e) { - fail(formatLocalized("dynamics.method.not_found", returnType, this), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.method.not_found", returnType, this); //$NON-NLS-1$ } } return m; @@ -74,25 +73,24 @@ public T invokeOn(Object o, Object... params) { try { return returnType.cast(toMethod().invoke(o, params)); } catch (NullPointerException e) { - fail(formatLocalized("dynamics.method.null", this), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.method.null", this); //$NON-NLS-1$ } catch (IllegalAccessException e) { - fail(formatLocalized("dynamics.method.access", this), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.method.access", this); //$NON-NLS-1$ } catch (IllegalArgumentException e) { - fail(formatLocalized("dynamics.method.arguments", this, descArgs(params), o.getClass().getCanonicalName()), //$NON-NLS-1$ - e); + throw localizedFailure(e, "dynamics.method.arguments", this, descArgs(params), //$NON-NLS-1$ + o.getClass().getCanonicalName()); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) throw (RuntimeException) e.getTargetException(); throw UnexpectedExceptionError.wrap(e.getTargetException()); } catch (ClassCastException e) { - fail(formatLocalized("dynamics.method.cast", this, returnType), e); //$NON-NLS-1$ + throw localizedFailure(e, "dynamics.method.cast", this, returnType); //$NON-NLS-1$ } - return null; // unreachable } public T invokeStatic(Object... params) { if (!Modifier.isStatic(toMethod().getModifiers())) - fail(formatLocalized("dynamics.method.static", this)); //$NON-NLS-1$ + throw localizedFailure("dynamics.method.static", this); //$NON-NLS-1$ return invokeOn(null, params); } @@ -137,6 +135,6 @@ public static String descParams(DynamicClass... params) { public void check(Check... checks) { int modifiers = toMethod().getModifiers(); for (Check check : checks) - check.checkModifiers(modifiers, () -> formatLocalized("dynamics.method.name", this)); //$NON-NLS-1$ + check.checkModifiers(modifiers, () -> localized("dynamics.method.name", this)); //$NON-NLS-1$ } } diff --git a/src/main/java/de/tum/in/test/api/internal/ReportingUtils.java b/src/main/java/de/tum/in/test/api/internal/ReportingUtils.java index ed890832..3c784cce 100644 --- a/src/main/java/de/tum/in/test/api/internal/ReportingUtils.java +++ b/src/main/java/de/tum/in/test/api/internal/ReportingUtils.java @@ -1,6 +1,6 @@ package de.tum.in.test.api.internal; -import static de.tum.in.test.api.localization.Messages.formatLocalized; +import static de.tum.in.test.api.localization.Messages.localized; import java.util.Objects; import java.util.Optional; @@ -79,7 +79,7 @@ private static String transformMessage(ThrowableInfo info) { private static Throwable handleSanitizationFailure(String name, Throwable error) { var info = BlacklistedInvoker.invokeOrElse(error::toString, () -> error.getClass().toString()); LOG.error("Sanitization failed for {} with error {}", name, info); //$NON-NLS-1$ - return new SecurityException(formatLocalized("sanitization.sanitization_failure", name, info)); //$NON-NLS-1$ + return new SecurityException(localized("sanitization.sanitization_failure", name, info)); //$NON-NLS-1$ } private static void addStackframeInfoToMessage(ThrowableInfo info) { @@ -88,7 +88,7 @@ private static void addStackframeInfoToMessage(ThrowableInfo info) { if (first.isPresent()) { var call = first.get().toString(); info.setMessage(Objects.toString(info.getMessage(), "") + "\n" //$NON-NLS-1$ //$NON-NLS-2$ - + formatLocalized("reporting.problem_location_hint", call)); //$NON-NLS-1$ + + localized("reporting.problem_location_hint", call)); //$NON-NLS-1$ } } } diff --git a/src/main/java/de/tum/in/test/api/internal/TestGuardUtils.java b/src/main/java/de/tum/in/test/api/internal/TestGuardUtils.java index 98bcd232..9d4a2c5a 100644 --- a/src/main/java/de/tum/in/test/api/internal/TestGuardUtils.java +++ b/src/main/java/de/tum/in/test/api/internal/TestGuardUtils.java @@ -1,7 +1,6 @@ package de.tum.in.test.api.internal; import static de.tum.in.test.api.localization.Messages.*; -import static org.junit.jupiter.api.Assertions.fail; import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation; import java.lang.annotation.Annotation; @@ -53,7 +52,7 @@ public static void checkForHidden(TestContext context) { // check if there are both, that would be a mistake if (hasAnnotationType(context, TestType.PUBLIC)) throw new AnnotationFormatError( - formatLocalized("test_guard.test_cannot_be_public_and_hidden", context.displayName())); //$NON-NLS-1$ + localized("test_guard.test_cannot_be_public_and_hidden", context.displayName())); //$NON-NLS-1$ var now = ZonedDateTime.now(); var finalDeadline = extractDeadline(context); @@ -64,10 +63,11 @@ public static void checkForHidden(TestContext context) { Optional activationBefore = extractActivationBefore(context); if (activationBefore.map(now::isBefore).orElse(false)) return; - fail(localized("test_guard.hidden_test_before_deadline_message")); //$NON-NLS-1$ - } else if (hasAnnotation(context, Deadline.class) || hasAnnotation(context, ExtendedDeadline.class)) { + throw localizedFailure("test_guard.hidden_test_before_deadline_message"); //$NON-NLS-1$ + } + if (hasAnnotation(context, Deadline.class) || hasAnnotation(context, ExtendedDeadline.class)) { throw new AnnotationFormatError( - formatLocalized("test_guard.public_test_cannot_have_deadline", context.displayName())); //$NON-NLS-1$ + localized("test_guard.public_test_cannot_have_deadline", context.displayName())); //$NON-NLS-1$ } } @@ -84,8 +84,7 @@ public static ZonedDateTime extractDeadline(TestContext context) { var deadline = extractDeadline(context.testClass(), context.testMethod()); if (deadline.isPresent()) return deadline.get(); - throw new AnnotationFormatError( - formatLocalized("test_guard.hidden_test_missing_deadline", context.displayName())); //$NON-NLS-1$ + throw new AnnotationFormatError(localized("test_guard.hidden_test_missing_deadline", context.displayName())); //$NON-NLS-1$ } public static Optional extractDeadline(Optional> testClass, Optional testMethod) { @@ -147,7 +146,7 @@ public static ZonedDateTime parseDeadline(String deadlineString) { } return dateTime.atZone(zone); } catch (DateTimeParseException e) { - throw new AnnotationFormatError(formatLocalized("test_guard.invalid_deadline_format", deadlineString), //$NON-NLS-1$ + throw new AnnotationFormatError(localized("test_guard.invalid_deadline_format", deadlineString), //$NON-NLS-1$ e); } } @@ -187,15 +186,13 @@ private static String[] splitIntoDateTimeAndZone(String deadlineString) { public static Duration parseDuration(String durationString) { var matcher = DURATION_PATTERN.matcher(durationString); if (!matcher.matches()) - throw new AnnotationFormatError( - formatLocalized("test_guard.invalid_extended_deadline_format", durationString)); //$NON-NLS-1$ + throw new AnnotationFormatError(localized("test_guard.invalid_extended_deadline_format", durationString)); //$NON-NLS-1$ int d = Optional.ofNullable(matcher.group("d")).map(Integer::parseInt).orElse(0); //$NON-NLS-1$ int h = Optional.ofNullable(matcher.group("h")).map(Integer::parseInt).orElse(0); //$NON-NLS-1$ int m = Optional.ofNullable(matcher.group("m")).map(Integer::parseInt).orElse(0); //$NON-NLS-1$ var duration = Duration.ofDays(d).plusHours(h).plusMinutes(m); if (duration.isZero() || duration.isNegative()) - throw new AnnotationFormatError( - formatLocalized("test_guard.extended_deadline_zero_or_negative", durationString)); //$NON-NLS-1$ + throw new AnnotationFormatError(localized("test_guard.extended_deadline_zero_or_negative", durationString)); //$NON-NLS-1$ return duration; } } diff --git a/src/main/java/de/tum/in/test/api/internal/TimeoutUtils.java b/src/main/java/de/tum/in/test/api/internal/TimeoutUtils.java index 6f57e968..0efd103a 100644 --- a/src/main/java/de/tum/in/test/api/internal/TimeoutUtils.java +++ b/src/main/java/de/tum/in/test/api/internal/TimeoutUtils.java @@ -1,7 +1,7 @@ package de.tum.in.test.api.internal; import static de.tum.in.test.api.internal.BlacklistedInvoker.invokeChecked; -import static de.tum.in.test.api.localization.Messages.formatLocalized; +import static de.tum.in.test.api.localization.Messages.localizedFailure; import java.time.Duration; import java.util.ArrayList; @@ -86,7 +86,7 @@ private static T executeWithTimeout(Duration timeout, Callable action, Te } private static AssertionFailedError generateTimeoutFailure(Duration timeout, TestContext context) { - var failure = new AssertionFailedError(formatLocalized("timeout.failure_message", formatDuration(timeout))); //$NON-NLS-1$ + var failure = localizedFailure("timeout.failure_message", formatDuration(timeout)); //$NON-NLS-1$ if (TestContextUtils.findAnnotationIn(context, PrivilegedExceptionsOnly.class).isPresent()) throw new PrivilegedException(failure); return failure; diff --git a/src/main/java/de/tum/in/test/api/internal/sanitization/SanitizationException.java b/src/main/java/de/tum/in/test/api/internal/sanitization/SanitizationException.java index d71ff6e6..fbb303e0 100644 --- a/src/main/java/de/tum/in/test/api/internal/sanitization/SanitizationException.java +++ b/src/main/java/de/tum/in/test/api/internal/sanitization/SanitizationException.java @@ -1,6 +1,6 @@ package de.tum.in.test.api.internal.sanitization; -import static de.tum.in.test.api.localization.Messages.formatLocalized; +import static de.tum.in.test.api.localization.Messages.localized; import java.util.Objects; @@ -32,7 +32,7 @@ public Throwable getUnsafeCause() { } private static String generateMessage(Class originClass, Throwable cause) { - return formatLocalized("sanitization.sanitization_exception_message", originClass.toString(), //$NON-NLS-1$ + return localized("sanitization.sanitization_exception_message", originClass.toString(), //$NON-NLS-1$ BlacklistedInvoker.invoke(cause::toString)); } diff --git a/src/main/java/de/tum/in/test/api/io/AbstractLine.java b/src/main/java/de/tum/in/test/api/io/AbstractLine.java index 65513124..3461519c 100644 --- a/src/main/java/de/tum/in/test/api/io/AbstractLine.java +++ b/src/main/java/de/tum/in/test/api/io/AbstractLine.java @@ -1,12 +1,12 @@ package de.tum.in.test.api.io; +import static de.tum.in.test.api.localization.Messages.localized; + import java.util.Objects; import org.apiguardian.api.API; import org.apiguardian.api.API.Status; -import de.tum.in.test.api.localization.Messages; - @API(status = Status.MAINTAINED) public abstract class AbstractLine implements Line { @@ -14,8 +14,8 @@ public abstract class AbstractLine implements Line { @Override public String toString() { - return lineNumber == -1 ? Messages.formatLocalized("abstract_line.plain_line", text()) //$NON-NLS-1$ - : Messages.formatLocalized("abstract_line.numbered_line", lineNumber, text()); //$NON-NLS-1$ + return lineNumber == -1 ? localized("abstract_line.plain_line", text()) //$NON-NLS-1$ + : localized("abstract_line.numbered_line", lineNumber, text()); //$NON-NLS-1$ } @Override diff --git a/src/main/java/de/tum/in/test/api/io/IOTester.java b/src/main/java/de/tum/in/test/api/io/IOTester.java index 94b02e7b..d468a8a2 100644 --- a/src/main/java/de/tum/in/test/api/io/IOTester.java +++ b/src/main/java/de/tum/in/test/api/io/IOTester.java @@ -1,6 +1,6 @@ package de.tum.in.test.api.io; -import static de.tum.in.test.api.localization.Messages.*; +import static de.tum.in.test.api.localization.Messages.localized; import java.io.InputStream; import java.io.PrintStream; @@ -222,7 +222,7 @@ public static synchronized void uninstallCurrent() { private static void checkEncoding() { Charset cs = Charset.defaultCharset(); if (!"UTF-8".equals(cs.name())) { //$NON-NLS-1$ - String message = formatLocalized("io_tester.default_not_utf8", cs); //$NON-NLS-1$ + String message = localized("io_tester.default_not_utf8", cs); //$NON-NLS-1$ System.err.println(message); // this is more noticeable in maven build log throw new IllegalStateException(message); } diff --git a/src/main/java/de/tum/in/test/api/io/InputTester.java b/src/main/java/de/tum/in/test/api/io/InputTester.java index 24a40ca1..90b1b5e4 100644 --- a/src/main/java/de/tum/in/test/api/io/InputTester.java +++ b/src/main/java/de/tum/in/test/api/io/InputTester.java @@ -1,6 +1,6 @@ package de.tum.in.test.api.io; -import static de.tum.in.test.api.localization.Messages.*; +import static de.tum.in.test.api.localization.Messages.localized; import java.util.ArrayList; import java.util.Arrays; @@ -30,7 +30,7 @@ public Line getNextLine() { return expectedInput.get(position++); if (expectedInput.isEmpty()) throw new IllegalStateException(localized("input_tester.no_input_expected")); //$NON-NLS-1$ - throw new IllegalStateException(formatLocalized("input_tester.no_more_input_expected", getCurrentLine())); //$NON-NLS-1$ + throw new IllegalStateException(localized("input_tester.no_more_input_expected", getCurrentLine())); //$NON-NLS-1$ } Line getCurrentLine() { diff --git a/src/main/java/de/tum/in/test/api/io/TestOutStream.java b/src/main/java/de/tum/in/test/api/io/TestOutStream.java index 5e86eb53..6b33e7a3 100644 --- a/src/main/java/de/tum/in/test/api/io/TestOutStream.java +++ b/src/main/java/de/tum/in/test/api/io/TestOutStream.java @@ -1,6 +1,6 @@ package de.tum.in.test.api.io; -import static de.tum.in.test.api.localization.Messages.*; +import static de.tum.in.test.api.localization.Messages.localized; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -68,7 +68,7 @@ public void flush() throws IOException { result = decoder.decode(bytes); } catch (CharacterCodingException e) { var problemString = new String(bytes.array(), decoder.charset()); - throw new IllegalArgumentException(formatLocalized("output_tester.output_is_invalid_utf8", problemString), //$NON-NLS-1$ + throw new IllegalArgumentException(localized("output_tester.output_is_invalid_utf8", problemString), //$NON-NLS-1$ e); } outputAcceptor.acceptOutput(result); @@ -92,6 +92,6 @@ private void checkCharCount(int newChars) throws IOException { throw new IOException(localized("output_tester.output_closed")); //$NON-NLS-1$ charCount += newChars; if (charCount > maxChars) - throw new SecurityException(formatLocalized("output_tester.output_maxExceeded", charCount)); //$NON-NLS-1$ + throw new SecurityException(localized("output_tester.output_maxExceeded", charCount)); //$NON-NLS-1$ } } diff --git a/src/main/java/de/tum/in/test/api/localization/Messages.java b/src/main/java/de/tum/in/test/api/localization/Messages.java index d5e722be..9fe80def 100644 --- a/src/main/java/de/tum/in/test/api/localization/Messages.java +++ b/src/main/java/de/tum/in/test/api/localization/Messages.java @@ -9,6 +9,7 @@ import org.apiguardian.api.API; import org.apiguardian.api.API.Status; +import org.opentest4j.AssertionFailedError; import de.tum.in.test.api.util.LruCache; @@ -22,20 +23,23 @@ public final class Messages { private Messages() { } - public static String localized(String key) { + public static String localized(String key, Object... args) { try { - return getBundleForCurrentLocale().getString(key); + String localizedText = getBundleForCurrentLocale().getString(key); + if (args.length == 0) + return localizedText; + return String.format(localizedText, args); } catch (@SuppressWarnings("unused") MissingResourceException e) { return '!' + key + '!'; } } - public static String formatLocalized(String key, Object... args) { - try { - return String.format(getBundleForCurrentLocale().getString(key), args); - } catch (@SuppressWarnings("unused") MissingResourceException e) { - return '!' + key + '!'; - } + public static AssertionFailedError localizedFailure(String key, Object... args) { + return new AssertionFailedError(localized(key, args)); + } + + public static AssertionFailedError localizedFailure(Throwable cause, String key, Object... args) { + return new AssertionFailedError(localized(key, args), cause); } private static ResourceBundle getBundleForCurrentLocale() { diff --git a/src/main/java/de/tum/in/test/api/security/ArtemisSecurityManager.java b/src/main/java/de/tum/in/test/api/security/ArtemisSecurityManager.java index 2e7526be..e67965e6 100644 --- a/src/main/java/de/tum/in/test/api/security/ArtemisSecurityManager.java +++ b/src/main/java/de/tum/in/test/api/security/ArtemisSecurityManager.java @@ -1,6 +1,6 @@ package de.tum.in.test.api.security; -import static de.tum.in.test.api.localization.Messages.*; +import static de.tum.in.test.api.localization.Messages.localized; import java.awt.AWTPermission; import java.io.FilePermission; @@ -173,7 +173,7 @@ public void checkAccept(String host, int port) { return; if (isConnectionAllowed(host, port)) return; - throw new SecurityException(formatLocalized("security.error_network_accept", host, port)); //$NON-NLS-1$ + throw new SecurityException(localized("security.error_network_accept", host, port)); //$NON-NLS-1$ } finally { exitPublicInterface(); } @@ -186,7 +186,7 @@ public void checkConnect(String host, int port) { return; if (isConnectionAllowed(host, port)) return; - throw new SecurityException(formatLocalized("security.error_network_connect", host, port)); //$NON-NLS-1$ + throw new SecurityException(localized("security.error_network_connect", host, port)); //$NON-NLS-1$ } finally { exitPublicInterface(); } @@ -199,7 +199,7 @@ public void checkConnect(String host, int port, Object context) { return; if (isConnectionAllowed(host, port)) return; - throw new SecurityException(formatLocalized("security.error_network_connect_with_context", host, port)); //$NON-NLS-1$ + throw new SecurityException(localized("security.error_network_connect_with_context", host, port)); //$NON-NLS-1$ } finally { exitPublicInterface(); } @@ -212,7 +212,7 @@ public void checkListen(int port) { return; if (isConnectionAllowed(LOCALHOST, port)) return; - throw new SecurityException(formatLocalized("security.error_network_listen", port)); //$NON-NLS-1$ + throw new SecurityException(localized("security.error_network_listen", port)); //$NON-NLS-1$ } finally { exitPublicInterface(); } @@ -309,7 +309,7 @@ public void checkPackageDefinition(String pkg) { LOG.info("PKG-DEF: {}", pkg); //$NON-NLS-1$ super.checkPackageDefinition(pkg); if (SecurityConstants.STACK_WHITELIST.stream().anyMatch(pkg::startsWith)) - throw new SecurityException(formatLocalized("security.error_package_definition", pkg)); //$NON-NLS-1$ + throw new SecurityException(localized("security.error_package_definition", pkg)); //$NON-NLS-1$ } finally { exitPublicInterface(); } @@ -402,7 +402,7 @@ private void checkPathAccess(String path, PathActionLevel pathActionLevel) { */ checkForNonWhitelistedStackFrames(() -> { LOG.warn(message); - return formatLocalized("security.error_path_access", path); //$NON-NLS-1$ + return localized("security.error_path_access", path); //$NON-NLS-1$ }); } else { /* @@ -412,7 +412,7 @@ private void checkPathAccess(String path, PathActionLevel pathActionLevel) { */ checkForNonWhitelistedStackFrames(() -> { LOG.warn(message); - return formatLocalized("security.error_path_access", path); //$NON-NLS-1$ + return localized("security.error_path_access", path); //$NON-NLS-1$ }, IGNORE_ACCESS_PRIVILEGED); } } @@ -450,7 +450,7 @@ public void checkPackageAccess(String pkg) { checkForNonWhitelistedStackFrames(() -> { LOG.warn("BAD PACKAGE ACCESS: {} (BL:{}, WL:{})", pkg, isPackageBlacklisted(pkg), //$NON-NLS-1$ isPackageWhitelisted(pkg)); - return formatLocalized("security.error_disallowed_package", pkg); //$NON-NLS-1$ + return localized("security.error_disallowed_package", pkg); //$NON-NLS-1$ }, IGNORE_ACCESS_PRIVILEGED); } } finally { @@ -489,7 +489,7 @@ private static void throwSecurityExceptionIfNonWhitelistedFound(Supplier if (!nonWhitelisted.isEmpty()) { LOG.warn("NWSFs ==> {}", nonWhitelisted); //$NON-NLS-1$ var first = nonWhitelisted.get(0); - throw new SecurityException(formatLocalized("security.stackframe_add_info", message.get(), //$NON-NLS-1$ + throw new SecurityException(localized("security.stackframe_add_info", message.get(), //$NON-NLS-1$ first.getLineNumber(), first.getFileName())); } } @@ -624,7 +624,7 @@ private Thread[] checkThreadGroup() { return new Thread[0]; // try forceful shutdown var securityException = new SecurityException( - formatLocalized("security.error_threads_not_stoppable", Arrays.toString(threads))); //$NON-NLS-1$ + localized("security.error_threads_not_stoppable", Arrays.toString(threads))); //$NON-NLS-1$ int alive = threads.length; TRIES: for (var i = 0; i < 50 && alive > 0; i++) { alive = 0; @@ -710,7 +710,7 @@ private void checkThreadCreation() { var current = testThreadGroup.activeCount(); var max = configuration.allowedThreadCount().getAsInt(); if (max < current) - checkForNonWhitelistedStackFrames(() -> formatLocalized("security.error_thread_maxExceeded", current, max)); //$NON-NLS-1$ + checkForNonWhitelistedStackFrames(() -> localized("security.error_thread_maxExceeded", current, max)); //$NON-NLS-1$ } /** @@ -816,7 +816,7 @@ public static synchronized void uninstall(String accessToken) { } if (activeThreads.length > 0) throw new IllegalStateException( - formatLocalized("security.error_threads_still_active", Arrays.toString(activeThreads))); //$NON-NLS-1$ + localized("security.error_threads_still_active", Arrays.toString(activeThreads))); //$NON-NLS-1$ } public static synchronized void configure(String accessToken, AresSecurityConfiguration configuration) { diff --git a/src/main/java/de/tum/in/test/api/structural/AttributeTestProvider.java b/src/main/java/de/tum/in/test/api/structural/AttributeTestProvider.java index 1506a727..41428214 100644 --- a/src/main/java/de/tum/in/test/api/structural/AttributeTestProvider.java +++ b/src/main/java/de/tum/in/test/api/structural/AttributeTestProvider.java @@ -1,6 +1,6 @@ package de.tum.in.test.api.structural; -import static de.tum.in.test.api.localization.Messages.formatLocalized; +import static de.tum.in.test.api.localization.Messages.*; import static java.util.function.Predicate.not; import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.DynamicContainer.dynamicContainer; @@ -143,13 +143,13 @@ protected static void checkAttributes(String expectedClassName, Class observe private static void checkAttributeCorrectness(boolean nameIsCorrect, boolean typeIsCorrect, boolean modifiersAreCorrect, boolean annotationsAreCorrect, String expectedName, String expectedClassName) { if (!nameIsCorrect) - throw failure(formatLocalized("structural.attribute.name", expectedName, expectedClassName)); //$NON-NLS-1$ + throw localizedFailure("structural.attribute.name", expectedName, expectedClassName); //$NON-NLS-1$ if (!typeIsCorrect) - throw failure(formatLocalized("structural.attribute.type", expectedName, expectedClassName)); //$NON-NLS-1$ + throw localizedFailure("structural.attribute.type", expectedName, expectedClassName); //$NON-NLS-1$ if (!modifiersAreCorrect) - throw failure(formatLocalized("structural.attribute.modifiers", expectedName, expectedClassName)); //$NON-NLS-1$ + throw localizedFailure("structural.attribute.modifiers", expectedName, expectedClassName); //$NON-NLS-1$ if (!annotationsAreCorrect) - throw failure(formatLocalized("structural.attribute.annotations", expectedName, expectedClassName)); //$NON-NLS-1$ + throw localizedFailure("structural.attribute.annotations", expectedName, expectedClassName); //$NON-NLS-1$ } /** @@ -167,7 +167,7 @@ private static void checkAttributeCorrectness(boolean nameIsCorrect, boolean typ protected static void checkEnumValues(String expectedClassName, Class observedClass, JSONArray expectedEnumValues) { if (!observedClass.isEnum()) - throw failure(formatLocalized("structural.attribute.noEnumConstants", expectedClassName)); //$NON-NLS-1$ + throw localizedFailure("structural.attribute.noEnumConstants", expectedClassName); //$NON-NLS-1$ @SuppressWarnings("unchecked") var observedEnumValues = ((Class>) observedClass).getEnumConstants(); var observedEnumNames = Stream.of(observedEnumValues).map(Enum::name).collect(Collectors.toSet()); @@ -175,9 +175,9 @@ protected static void checkEnumValues(String expectedClassName, Class observe .collect(Collectors.toSet()); var missing = expectedEnumNames.stream().filter(not(observedEnumNames::contains)).findFirst(); missing.ifPresent(missingName -> fail( - formatLocalized("structural.attribute.missingEnumConstants", expectedClassName, missingName))); //$NON-NLS-1$ + localized("structural.attribute.missingEnumConstants", expectedClassName, missingName))); //$NON-NLS-1$ var unexpected = observedEnumNames.stream().filter(not(expectedEnumNames::contains)).findFirst(); unexpected.ifPresent(unexpectedName -> fail( - formatLocalized("structural.attribute.unexpectedEnumConstants", expectedClassName, unexpectedName))); //$NON-NLS-1$ + localized("structural.attribute.unexpectedEnumConstants", expectedClassName, unexpectedName))); //$NON-NLS-1$ } } diff --git a/src/main/java/de/tum/in/test/api/structural/ClassTestProvider.java b/src/main/java/de/tum/in/test/api/structural/ClassTestProvider.java index 2917058c..1d1a038a 100644 --- a/src/main/java/de/tum/in/test/api/structural/ClassTestProvider.java +++ b/src/main/java/de/tum/in/test/api/structural/ClassTestProvider.java @@ -1,6 +1,6 @@ package de.tum.in.test.api.structural; -import static de.tum.in.test.api.localization.Messages.formatLocalized; +import static de.tum.in.test.api.localization.Messages.localizedFailure; import static org.junit.jupiter.api.DynamicContainer.dynamicContainer; import static org.junit.jupiter.api.DynamicTest.dynamicTest; @@ -99,18 +99,18 @@ private static void checkBasicClassProperties(String expectedClassName, Class JSONObject expectedClassPropertiesJSON) { if (checkBooleanOf(expectedClassPropertiesJSON, "isAbstract") //$NON-NLS-1$ && !Modifier.isAbstract(observedClass.getModifiers())) - throw failure(formatLocalized("structural.class.abstract", expectedClassName)); //$NON-NLS-1$ + throw localizedFailure("structural.class.abstract", expectedClassName); //$NON-NLS-1$ if (checkBooleanOf(expectedClassPropertiesJSON, "isEnum") && !observedClass.isEnum()) //$NON-NLS-1$ - throw failure(formatLocalized("structural.class.enum", expectedClassName)); //$NON-NLS-1$ + throw localizedFailure("structural.class.enum", expectedClassName); //$NON-NLS-1$ if (checkBooleanOf(expectedClassPropertiesJSON, "isInterface") //$NON-NLS-1$ && !Modifier.isInterface(observedClass.getModifiers())) - throw failure(formatLocalized("structural.class.interface", expectedClassName)); //$NON-NLS-1$ + throw localizedFailure("structural.class.interface", expectedClassName); //$NON-NLS-1$ if (expectedClassPropertiesJSON.has(JSON_PROPERTY_MODIFIERS)) { var expectedModifiers = getExpectedJsonProperty(expectedClassPropertiesJSON, JSON_PROPERTY_MODIFIERS); var modifiersAreCorrect = checkModifiers(Modifier.toString(observedClass.getModifiers()).split(" "), //$NON-NLS-1$ expectedModifiers); if (!modifiersAreCorrect) - throw failure(formatLocalized("structural.class.modifiers", expectedClassName)); //$NON-NLS-1$ + throw localizedFailure("structural.class.modifiers", expectedClassName); //$NON-NLS-1$ } } @@ -127,9 +127,7 @@ private static void checkSuperclass(String expectedClassName, Class observedC var expectedSuperClassName = expectedClassPropertiesJSON.getString(JSON_PROPERTY_SUPERCLASS); if (!checkExpectedType(observedClass.getSuperclass(), observedClass.getGenericSuperclass(), expectedSuperClassName)) { - var failMessage = formatLocalized("structural.class.extends", expectedClassName, //$NON-NLS-1$ - expectedSuperClassName); - throw failure(failMessage); + throw localizedFailure("structural.class.extends", expectedClassName, expectedSuperClassName); //$NON-NLS-1$ } } } @@ -152,7 +150,7 @@ private static void checkInterfaces(String expectedClassName, Class observedC } } if (!implementsInterface) - throw failure(formatLocalized("structural.class.implements", expectedClassName, expectedInterface)); //$NON-NLS-1$ + throw localizedFailure("structural.class.implements", expectedClassName, expectedInterface); //$NON-NLS-1$ } } } @@ -164,7 +162,7 @@ private static void checkAnnotations(String expectedClassName, Class observed var observedAnnotations = observedClass.getAnnotations(); var annotationsAreRight = checkAnnotations(observedAnnotations, expectedAnnotations); if (!annotationsAreRight) - throw failure(formatLocalized("structural.class.annotations", expectedClassName)); //$NON-NLS-1$ + throw localizedFailure("structural.class.annotations", expectedClassName); //$NON-NLS-1$ } } } diff --git a/src/main/java/de/tum/in/test/api/structural/ConstructorTestProvider.java b/src/main/java/de/tum/in/test/api/structural/ConstructorTestProvider.java index 149e3d19..f94b5282 100644 --- a/src/main/java/de/tum/in/test/api/structural/ConstructorTestProvider.java +++ b/src/main/java/de/tum/in/test/api/structural/ConstructorTestProvider.java @@ -1,6 +1,6 @@ package de.tum.in.test.api.structural; -import static de.tum.in.test.api.localization.Messages.formatLocalized; +import static de.tum.in.test.api.localization.Messages.localizedFailure; import static org.junit.jupiter.api.DynamicContainer.dynamicContainer; import static org.junit.jupiter.api.DynamicTest.dynamicTest; @@ -132,10 +132,10 @@ private static void checkConstructorCorrectness(String expectedClassName, JSONAr boolean parametersAreCorrect, boolean modifiersAreCorrect, boolean annotationsAreCorrect) { String parameters = describeParameters(expectedParameters); if (!parametersAreCorrect) - throw failure(formatLocalized("structural.constructor.parameters", expectedClassName, parameters)); //$NON-NLS-1$ + throw localizedFailure("structural.constructor.parameters", expectedClassName, parameters); //$NON-NLS-1$ if (!modifiersAreCorrect) - throw failure(formatLocalized("structural.constructor.modifiers", expectedClassName, parameters)); //$NON-NLS-1$ + throw localizedFailure("structural.constructor.modifiers", expectedClassName, parameters); //$NON-NLS-1$ if (!annotationsAreCorrect) - throw failure(formatLocalized("structural.constructor.annotations", expectedClassName, parameters)); //$NON-NLS-1$ + throw localizedFailure("structural.constructor.annotations", expectedClassName, parameters); //$NON-NLS-1$ } } diff --git a/src/main/java/de/tum/in/test/api/structural/MethodTestProvider.java b/src/main/java/de/tum/in/test/api/structural/MethodTestProvider.java index 707d44db..7bb50aa9 100644 --- a/src/main/java/de/tum/in/test/api/structural/MethodTestProvider.java +++ b/src/main/java/de/tum/in/test/api/structural/MethodTestProvider.java @@ -1,6 +1,6 @@ package de.tum.in.test.api.structural; -import static de.tum.in.test.api.localization.Messages.formatLocalized; +import static de.tum.in.test.api.localization.Messages.localizedFailure; import static org.junit.jupiter.api.DynamicContainer.dynamicContainer; import static org.junit.jupiter.api.DynamicTest.dynamicTest; @@ -137,15 +137,15 @@ private static void checkMethodCorrectness(String expectedClassName, String expe JSONArray expectedParameters, MethodChecks methodChecks) { String parameters = StructuralTestProvider.describeParameters(expectedParameters); if (!methodChecks.name) - throw failure(formatLocalized("structural.method.name", expectedName, expectedClassName, parameters)); //$NON-NLS-1$ + throw localizedFailure("structural.method.name", expectedName, expectedClassName, parameters); //$NON-NLS-1$ if (!methodChecks.parameters) - throw failure(formatLocalized("structural.method.parameters", expectedName, expectedClassName, parameters)); //$NON-NLS-1$ + throw localizedFailure("structural.method.parameters", expectedName, expectedClassName, parameters); //$NON-NLS-1$ if (!methodChecks.modifiers) - throw failure(formatLocalized("structural.method.modifiers", expectedName, expectedClassName, parameters)); //$NON-NLS-1$ + throw localizedFailure("structural.method.modifiers", expectedName, expectedClassName, parameters); //$NON-NLS-1$ if (!methodChecks.annotations) - throw failure(formatLocalized("structural.method.annoations", expectedName, expectedClassName, parameters)); //$NON-NLS-1$ + throw localizedFailure("structural.method.annoations", expectedName, expectedClassName, parameters); //$NON-NLS-1$ if (!methodChecks.returnType) - throw failure(formatLocalized("structural.method.return", expectedName, expectedClassName, parameters)); //$NON-NLS-1$ + throw localizedFailure("structural.method.return", expectedName, expectedClassName, parameters); //$NON-NLS-1$ } private static class MethodChecks { diff --git a/src/main/java/de/tum/in/test/api/structural/StructuralTestProvider.java b/src/main/java/de/tum/in/test/api/structural/StructuralTestProvider.java index 6fb76514..fca9f321 100644 --- a/src/main/java/de/tum/in/test/api/structural/StructuralTestProvider.java +++ b/src/main/java/de/tum/in/test/api/structural/StructuralTestProvider.java @@ -120,7 +120,7 @@ protected static Class findClassForTestType(ExpectedClassStructure expectedCl // Note: this error happens when the ClassNameScanner finds the correct file, // e.g. 'Course.java', but the class 'Course' was not yet created correctly in // this file. - throw failure(formatLocalized("structural.common.classLoadFailed", typeOfTest, classNameScanMessage)); //$NON-NLS-1$ + throw localizedFailure("structural.common.classLoadFailed", typeOfTest, classNameScanMessage); //$NON-NLS-1$ } } @@ -301,7 +301,7 @@ protected static boolean checkParameters(Class[] observedParameters, JSONArra */ protected static String describeParameters(JSONArray expectedParameters) { return expectedParameters.isEmpty() ? localized("structural.common.noParams") //$NON-NLS-1$ - : formatLocalized("structural.common.withParams", expectedParameters); //$NON-NLS-1$ + : localized("structural.common.withParams", expectedParameters); //$NON-NLS-1$ } /** diff --git a/src/main/java/de/tum/in/test/api/structural/testutils/ClassNameScanner.java b/src/main/java/de/tum/in/test/api/structural/testutils/ClassNameScanner.java index b1b5188f..0c7aa691 100644 --- a/src/main/java/de/tum/in/test/api/structural/testutils/ClassNameScanner.java +++ b/src/main/java/de/tum/in/test/api/structural/testutils/ClassNameScanner.java @@ -1,6 +1,6 @@ package de.tum.in.test.api.structural.testutils; -import static de.tum.in.test.api.localization.Messages.*; +import static de.tum.in.test.api.localization.Messages.localized; import static de.tum.in.test.api.structural.testutils.ScanResultType.*; import java.io.File; @@ -197,29 +197,29 @@ private String createScanResultMessage(ScanResultType scanResultType, String fou String foundPackageName) { switch (scanResultType) { case CORRECT_NAME_CORRECT_PLACE: - return formatLocalized("structural.scan.correctNameCorrectPlace", foundClassName); //$NON-NLS-1$ + return localized("structural.scan.correctNameCorrectPlace", foundClassName); //$NON-NLS-1$ case CORRECT_NAME_MISPLACED: - return formatLocalized("structural.scan.correctNameMisplaced", foundClassName, foundPackageName); //$NON-NLS-1$ + return localized("structural.scan.correctNameMisplaced", foundClassName, foundPackageName); //$NON-NLS-1$ case CORRECT_NAME_MULTIPLE: - return formatLocalized("structural.scan.correctNameMultiple", foundClassName, foundPackageName); //$NON-NLS-1$ + return localized("structural.scan.correctNameMultiple", foundClassName, foundPackageName); //$NON-NLS-1$ case WRONG_CASE_CORRECT_PLACE: - return formatLocalized("structural.scan.wrongCaseCorrectPlace", expectedClassName, foundClassName); //$NON-NLS-1$ + return localized("structural.scan.wrongCaseCorrectPlace", expectedClassName, foundClassName); //$NON-NLS-1$ case WRONG_CASE_MISPLACED: - return formatLocalized("structural.scan.wrongCaseMisplaced", expectedClassName, expectedPackageName, //$NON-NLS-1$ + return localized("structural.scan.wrongCaseMisplaced", expectedClassName, expectedPackageName, //$NON-NLS-1$ foundClassName, foundPackageName); case WRONG_CASE_MULTIPLE: - return formatLocalized("structural.scan.wrongCaseMultiple", expectedClassName, expectedPackageName, //$NON-NLS-1$ + return localized("structural.scan.wrongCaseMultiple", expectedClassName, expectedPackageName, //$NON-NLS-1$ foundClassName, foundPackageName); case TYPOS_CORRECT_PLACE: - return formatLocalized("structural.scan.typosCorrectPlace", expectedClassName, foundClassName); //$NON-NLS-1$ + return localized("structural.scan.typosCorrectPlace", expectedClassName, foundClassName); //$NON-NLS-1$ case TYPOS_MISPLACED: - return formatLocalized("structural.scan.typosMisplaced", expectedClassName, expectedPackageName, //$NON-NLS-1$ + return localized("structural.scan.typosMisplaced", expectedClassName, expectedPackageName, //$NON-NLS-1$ foundClassName, foundPackageName); case TYPOS_MULTIPLE: - return formatLocalized("structural.scan.typosMultiple", expectedClassName, expectedPackageName, //$NON-NLS-1$ + return localized("structural.scan.typosMultiple", expectedClassName, expectedPackageName, //$NON-NLS-1$ foundClassName, observedClasses.get(foundClassName).toString()); case NOTFOUND: - return formatLocalized("structural.scan.notFound", expectedClassName, expectedPackageName); //$NON-NLS-1$ + return localized("structural.scan.notFound", expectedClassName, expectedPackageName); //$NON-NLS-1$ default: return localized("structural.scan.default"); //$NON-NLS-1$ } diff --git a/src/main/java/de/tum/in/test/api/util/ReflectionTestUtils.java b/src/main/java/de/tum/in/test/api/util/ReflectionTestUtils.java index 9307aa6a..68cc0594 100644 --- a/src/main/java/de/tum/in/test/api/util/ReflectionTestUtils.java +++ b/src/main/java/de/tum/in/test/api/util/ReflectionTestUtils.java @@ -7,7 +7,6 @@ import java.lang.reflect.Method; import java.util.Arrays; import java.util.StringJoiner; -import java.util.function.Supplier; import org.apiguardian.api.API; import org.apiguardian.api.API.Status; @@ -56,9 +55,9 @@ public static Class getClazz(String qualifiedClassName) { try { return Class.forName(qualifiedClassName); } catch (@SuppressWarnings("unused") ClassNotFoundException e) { - throw failure(formatLocalized("reflection_test_utils.class_not_found", className)); //$NON-NLS-1$ + throw localizedFailure("reflection_test_utils.class_not_found", className); //$NON-NLS-1$ } catch (@SuppressWarnings("unused") ExceptionInInitializerError e) { - throw failure(formatLocalized("reflection_test_utils.class_initialization", className)); //$NON-NLS-1$ + throw localizedFailure("reflection_test_utils.class_initialization", className); //$NON-NLS-1$ } } @@ -98,15 +97,14 @@ public static Object newInstance(String qualifiedClassName, Object... constructo * @return The instance of this class. */ public static Object newInstance(Class clazz, Object... constructorArgs) { - var constructorArgTypes = getParameterTypes( - () -> formatLocalized("reflection_test_utils.constructor_null_args", clazz.getSimpleName()), //$NON-NLS-1$ - constructorArgs); + var constructorArgTypes = getParameterTypes(constructorArgs, "reflection_test_utils.constructor_null_args", //$NON-NLS-1$ + clazz.getSimpleName()); try { Constructor constructor = clazz.getDeclaredConstructor(constructorArgTypes); return newInstance(constructor, constructorArgs); } catch (@SuppressWarnings("unused") NoSuchMethodException nsme) { - throw failure(formatLocalized("reflection_test_utils.constructor_not_found_args", clazz.getSimpleName(), //$NON-NLS-1$ - getParameterTypesAsString(constructorArgTypes))); + throw localizedFailure("reflection_test_utils.constructor_not_found_args", clazz.getSimpleName(), //$NON-NLS-1$ + getParameterTypesAsString(constructorArgTypes)); } } @@ -125,22 +123,22 @@ public static Object newInstance(Constructor constructor, Object... construct try { return constructor.newInstance(constructorArgs); } catch (@SuppressWarnings("unused") IllegalAccessException iae) { - throw failure(formatLocalized("reflection_test_utils.constructor_access", //$NON-NLS-1$ + throw localizedFailure("reflection_test_utils.constructor_access", //$NON-NLS-1$ constructor.getDeclaringClass().getSimpleName(), - getParameterTypesAsString(constructor.getParameterTypes()))); + getParameterTypesAsString(constructor.getParameterTypes())); } catch (@SuppressWarnings("unused") IllegalArgumentException iae) { - throw failure(formatLocalized("reflection_test_utils.constructor_arguments", //$NON-NLS-1$ + throw localizedFailure("reflection_test_utils.constructor_arguments", //$NON-NLS-1$ constructor.getDeclaringClass().getSimpleName(), - getParameterTypesAsString(constructor.getParameterTypes()))); + getParameterTypesAsString(constructor.getParameterTypes())); } catch (@SuppressWarnings("unused") InstantiationException ie) { - throw failure(formatLocalized("reflection_test_utils.constructor_abstract_class", //$NON-NLS-1$ - constructor.getDeclaringClass().getSimpleName())); + throw localizedFailure("reflection_test_utils.constructor_abstract_class", //$NON-NLS-1$ + constructor.getDeclaringClass().getSimpleName()); } catch (@SuppressWarnings("unused") InvocationTargetException ite) { - throw failure(formatLocalized("reflection_test_utils.constructor_internal_exception", //$NON-NLS-1$ - constructor.getDeclaringClass().getSimpleName(), constructorArgs.length)); + throw localizedFailure("reflection_test_utils.constructor_internal_exception", //$NON-NLS-1$ + constructor.getDeclaringClass().getSimpleName(), constructorArgs.length); } catch (@SuppressWarnings("unused") ExceptionInInitializerError eiie) { - throw failure(formatLocalized("reflection_test_utils.constructor_class_init", //$NON-NLS-1$ - constructor.getDeclaringClass().getSimpleName(), constructorArgs.length)); + throw localizedFailure("reflection_test_utils.constructor_class_init", //$NON-NLS-1$ + constructor.getDeclaringClass().getSimpleName(), constructorArgs.length); } } @@ -155,15 +153,15 @@ public static Object newInstance(Constructor constructor, Object... construct * @return The instance of the attribute with the wanted value. */ public static Object valueForAttribute(Object object, String attributeName) { - requireNonNull(object, () -> formatLocalized("reflection_test_utils.attribute_null", attributeName)); //$NON-NLS-1$ + requireNonNull(object, "reflection_test_utils.attribute_null", attributeName); //$NON-NLS-1$ try { return object.getClass().getDeclaredField(attributeName).get(object); } catch (@SuppressWarnings("unused") NoSuchFieldException nsfe) { - throw failure(formatLocalized("reflection_test_utils.attribute_not_found", attributeName, //$NON-NLS-1$ - object.getClass().getSimpleName())); + throw localizedFailure("reflection_test_utils.attribute_not_found", attributeName, //$NON-NLS-1$ + object.getClass().getSimpleName()); } catch (@SuppressWarnings("unused") IllegalAccessException iae) { - throw failure(formatLocalized("reflection_test_utils.attribute_access", attributeName, //$NON-NLS-1$ - object.getClass().getSimpleName())); + throw localizedFailure("reflection_test_utils.attribute_access", attributeName, //$NON-NLS-1$ + object.getClass().getSimpleName()); } } @@ -178,7 +176,7 @@ public static Object valueForAttribute(Object object, String attributeName) { * @return The wanted method. */ public static Method getMethod(Object object, String methodName, Class... parameterTypes) { - requireNonNull(object, () -> formatLocalized("reflection_test_utils.method_null_target", methodName)); //$NON-NLS-1$ + requireNonNull(object, "reflection_test_utils.method_null_target", methodName); //$NON-NLS-1$ return getMethod(object.getClass(), methodName, parameterTypes); } @@ -195,11 +193,11 @@ public static Method getMethod(Class declaringClass, String methodName, Class try { return declaringClass.getMethod(methodName, parameterTypes); } catch (@SuppressWarnings("unused") NoSuchMethodException nsme) { - throw failure(formatLocalized("reflection_test_utils.method_not_found", methodName, //$NON-NLS-1$ - describeParameters(parameterTypes), declaringClass.getSimpleName())); + throw localizedFailure("reflection_test_utils.method_not_found", methodName, //$NON-NLS-1$ + describeParameters(parameterTypes), declaringClass.getSimpleName()); } catch (@SuppressWarnings("unused") NullPointerException npe) { - throw failure(formatLocalized("reflection_test_utils.method_name_null", methodName, //$NON-NLS-1$ - describeParameters(parameterTypes), declaringClass.getSimpleName())); + throw localizedFailure("reflection_test_utils.method_name_null", methodName, //$NON-NLS-1$ + describeParameters(parameterTypes), declaringClass.getSimpleName()); } } @@ -219,8 +217,7 @@ public static Method getMethod(Class declaringClass, String methodName, Class * @return The return value of the method. */ public static Object invokeMethod(Object object, String methodName, Object... params) { - var parameterTypes = getParameterTypes( - () -> formatLocalized("reflection_test_utils.method_null_args", methodName), params); //$NON-NLS-1$ + var parameterTypes = getParameterTypes(params, "reflection_test_utils.method_null_args", methodName); //$NON-NLS-1$ var method = getMethod(object, methodName, parameterTypes); return invokeMethod(object, method, params); } @@ -242,8 +239,8 @@ public static Object invokeMethod(Object object, Method method, Object... params } catch (AssertionFailedError e) { throw e; } catch (Throwable e) { - throw failure(formatLocalized("reflection_test_utils.method_internal_exception", method.getName(), //$NON-NLS-1$ - method.getDeclaringClass().getSimpleName(), e)); + throw localizedFailure("reflection_test_utils.method_internal_exception", method.getName(), //$NON-NLS-1$ + method.getDeclaringClass().getSimpleName(), e); } } @@ -263,17 +260,17 @@ public static Object invokeMethodRethrowing(Object object, Method method, Object try { return method.invoke(object, params); } catch (@SuppressWarnings("unused") IllegalAccessException iae) { - throw failure(formatLocalized("reflection_test_utils.method_access", method.getName(), //$NON-NLS-1$ - method.getDeclaringClass().getSimpleName())); + throw localizedFailure("reflection_test_utils.method_access", method.getName(), //$NON-NLS-1$ + method.getDeclaringClass().getSimpleName()); } catch (@SuppressWarnings("unused") IllegalArgumentException iae) { - throw failure(formatLocalized("reflection_test_utils.method_parameters", method.getName(), //$NON-NLS-1$ - method.getDeclaringClass().getSimpleName())); + throw localizedFailure("reflection_test_utils.method_parameters", method.getName(), //$NON-NLS-1$ + method.getDeclaringClass().getSimpleName()); } catch (@SuppressWarnings("unused") NullPointerException e) { - throw failure(formatLocalized("reflection_test_utils.method_null_target_instance", method.getName(), //$NON-NLS-1$ - method.getDeclaringClass().getSimpleName())); + throw localizedFailure("reflection_test_utils.method_null_target_instance", method.getName(), //$NON-NLS-1$ + method.getDeclaringClass().getSimpleName()); } catch (@SuppressWarnings("unused") ExceptionInInitializerError e) { - throw failure(formatLocalized("reflection_test_utils.method_class_init", method.getName(), //$NON-NLS-1$ - method.getDeclaringClass().getSimpleName())); + throw localizedFailure("reflection_test_utils.method_class_init", method.getName(), //$NON-NLS-1$ + method.getDeclaringClass().getSimpleName()); } catch (InvocationTargetException e) { throw e.getCause(); } @@ -292,26 +289,27 @@ public static Constructor getConstructor(Class declaringClass, Class... parameterTypes) { if (parameterTypes.length == 0) return localized("reflection_test_utils.no_parameters"); //$NON-NLS-1$ - return formatLocalized("reflection_test_utils.with_parameters", getParameterTypesAsString(parameterTypes)); //$NON-NLS-1$ + return localized("reflection_test_utils.with_parameters", getParameterTypesAsString(parameterTypes)); //$NON-NLS-1$ } /** * Retrieves the parameters types of a given collection of parameter instances. * - * @param failMessage The message of the failure if one of params is null + * @param key The key for the localized exception message. + * @param messageArgs The arguments for the formatted localized message. * @param params The instances of the parameters. * @return The parameter types of the instances as an array. */ - private static Class[] getParameterTypes(Supplier messageSuppier, Object... params) { - return Arrays.stream(params).map(it -> requireNonNull(it, messageSuppier)).map(Object::getClass) + private static Class[] getParameterTypes(Object[] params, String key, Object... messageArgs) { + return Arrays.stream(params).map(it -> requireNonNull(it, key, messageArgs)).map(Object::getClass) .toArray(Class[]::new); } @@ -324,28 +322,24 @@ private static Class[] getParameterTypes(Supplier messageSuppier, Obj private static String getParameterTypesAsString(Class... parameterTypes) { var joiner = new StringJoiner(", ", "[ ", " ]"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ joiner.setEmptyValue("none"); //$NON-NLS-1$ - Arrays.stream(parameterTypes).map(type -> requireNonNull(type, () -> "One of the supplied types was null.")) //$NON-NLS-1$ + Arrays.stream(parameterTypes).map(type -> requireNonNull(type, "One of the supplied types was null.")) //$NON-NLS-1$ .map(Class::getSimpleName).forEach(joiner::add); return joiner.toString(); } /** * Throws an {@link AssertionFailedError} if the given object is null using the - * provided message supplier. + * provided localized message. * - * @param The type of the object that should be checked. - * @param object The object to check for null. - * @param messageSuppier The message supplier to generate failure messages - * lazily + * @param The type of the object that should be checked. + * @param object The object to check for null. + * @param key The key for the localized exception message. + * @param messageArgs The arguments for the formatted localized message. * @return the same, unchanged object in case it was not null */ - private static T requireNonNull(T object, Supplier messageSuppier) { + private static T requireNonNull(T object, String key, Object... messageArgs) { if (object == null) - throw failure(messageSuppier.get()); + throw localizedFailure(key, messageArgs); return object; } - - private static AssertionFailedError failure(String failureMessage) { - return new AssertionFailedError(failureMessage); - } } diff --git a/src/test/java/de/tum/in/test/integration/testuser/LocaleUser.java b/src/test/java/de/tum/in/test/integration/testuser/LocaleUser.java index b94f6260..ea06ffbf 100644 --- a/src/test/java/de/tum/in/test/integration/testuser/LocaleUser.java +++ b/src/test/java/de/tum/in/test/integration/testuser/LocaleUser.java @@ -44,7 +44,7 @@ void testLocaleDe() { @Test void testUnknownFormatted() { - assertThat(Messages.formatLocalized("_unknown_%s_", "x")).isEqualTo("!_unknown_%s_!"); + assertThat(Messages.localized("_unknown_%s_", "x")).isEqualTo("!_unknown_%s_!"); } @Test