Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor refactoring #2718

Merged
merged 1 commit into from
Jan 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 14 additions & 22 deletions testng-collections/src/main/java/org/testng/util/Strings.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package org.testng.util;

import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.testng.collections.Maps;

public final class Strings {
Expand All @@ -13,29 +15,29 @@ private Strings() {
// because now this method is present in JDK11 as part of the JDK itself.
// See
// https://hg.openjdk.java.net/jdk/jdk/file/fc16b5f193c7/src/java.base/share/classes/java/lang/String.java#l2984
/** @deprecated - This method stands deprecated as of TestNG <code>7.6.0</code> */
@Deprecated
public static String repeat(String text, int count) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++) {
builder.append(text);
}
return builder.toString();
return text.repeat(count);
}

public static boolean isNullOrEmpty(String string) {
return string == null || string.trim().isEmpty();
return Optional.ofNullable(string).orElse("").trim().isEmpty();
}

public static boolean isNotNullAndNotEmpty(String string) {
return !(isNullOrEmpty(string));
return !isNullOrEmpty(string);
}

/**
* @param string - The input String.
* @return - Returns an empty string if the input String is <code>null</code> (or) empty, else it
* returns back the input string.
* @deprecated - This method stands deprecated as of TestNG <code>7.6.0</code>
*/
@Deprecated
public static String getValueOrEmpty(String string) {
return isNotNullAndNotEmpty(string) ? string : "";
return Optional.ofNullable(string).orElse("");
}

private static final Map<String, String> ESCAPE_HTML_MAP = Maps.newLinkedHashMap();
Expand All @@ -55,22 +57,12 @@ public static String escapeHtml(String text) {
}

public static String valueOf(Map<?, ?> m) {
StringBuilder result = new StringBuilder();
for (Object o : m.values()) {
result.append(o).append(" ");
}

return result.toString();
return m.values().stream().map(Object::toString).collect(Collectors.joining(" "));
}

/** @deprecated - This is deprecated of TestNG <code>7.6.0</code> */
@Deprecated
public static String join(String delimiter, String[] parts) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parts.length - 1; i++) {
sb.append(parts[i]).append(delimiter);
}
if (parts.length > 0) {
sb.append(parts[parts.length - 1]);
}
return sb.toString();
return String.join(delimiter, parts);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Properties;
import javax.annotation.Nullable;
import org.testng.util.Strings;

/**
* Static helpers for XML.
Expand Down Expand Up @@ -121,7 +121,7 @@ public static void xmlClose(IBuffer result, String indent, String tag, String co
.append("</")
.append(tag)
.append(">")
.append(Strings.getValueOrEmpty(comment))
.append(Optional.ofNullable(comment).orElse(""))
.append(EOL);
}

Expand Down
3 changes: 1 addition & 2 deletions testng-core/src/main/java/org/testng/internal/Yaml.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import java.util.function.Consumer;
import org.testng.TestNGException;
import org.testng.internal.objects.InstanceCreator;
import org.testng.util.Strings;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlInclude;
import org.testng.xml.XmlPackage;
Expand Down Expand Up @@ -140,7 +139,7 @@ public static StringBuilder toYaml(XmlSuite suite) {

/** Convert a XmlTest into YAML */
private static void toYaml(StringBuilder result, XmlTest t) {
String sp2 = Strings.repeat(" ", 2);
String sp2 = " ".repeat(2);
result.append(" ").append("- name: ").append(t.getName()).append("\n");

maybeAdd(result, sp2, "junit", t.isJUnit(), XmlSuite.DEFAULT_JUNIT);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import org.testng.annotations.ITestAnnotation;
import org.testng.annotations.Ignore;
import org.testng.internal.reflect.ReflectionHelper;
import org.testng.util.Strings;

public class IgnoreListener implements IAnnotationTransformer {

Expand Down Expand Up @@ -77,7 +76,7 @@ private static Ignore findAnnotation(Package testPackage) {
}
String[] parts = testPackage.getName().split("\\.");
String[] parentParts = Arrays.copyOf(parts, parts.length - 1);
String parentPackageName = Strings.join(".", parentParts);
String parentPackageName = String.join(".", parentParts);
if (parentPackageName.isEmpty()) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
Expand All @@ -18,6 +19,7 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import org.testng.IConfigurable;
import org.testng.IConfigureCallBack;
import org.testng.IHookCallBack;
Expand Down Expand Up @@ -309,6 +311,12 @@ private static boolean invokeWithTimeoutWithNoExecutor(
ITestResult testResult,
IHookable hookable) {

Consumer<Throwable> failureMarker =
t -> {
testResult.setThrowable(t);
testResult.setStatus(ITestResult.FAILURE);
};

InvokeMethodRunnable imr =
new InvokeMethodRunnable(tm, instance, parameterValues, hookable, testResult);
long startTime = System.currentTimeMillis();
Expand Down Expand Up @@ -339,29 +347,27 @@ private static boolean invokeWithTimeoutWithNoExecutor(
if (notTimedout) {
testResult.setStatus(ITestResult.SUCCESS);
} else {
testResult.setThrowable(new ThreadTimeoutException(tm, realTimeOut));
testResult.setStatus(ITestResult.FAILURE);
failureMarker.accept(new ThreadTimeoutException(tm, realTimeOut));
}
return wasInvoked;
} catch (TestNotInvokedException e) {
failureMarker.accept(e.getCause());
return wasInvoked;
} catch (Exception ex) {
if (notTimedout && !interruptByMonitor.get()) {
Throwable e = ex.getCause();
Throwable e = ex.getCause();
boolean wasTimedOut = !(notTimedout && !interruptByMonitor.get());
if (wasTimedOut) {
e = new ThreadTimeoutException(tm, realTimeOut);
} else {
if (e instanceof TestNGRuntimeException) {
e = e.getCause();
}
testResult.setThrowable(e);
} else {
if (!(ex instanceof TestNotInvokedException)) {
testResult.setThrowable(new ThreadTimeoutException(tm, realTimeOut));
}
}
testResult.setStatus(ITestResult.FAILURE);
failureMarker.accept(e);
return wasInvoked;
} finally {
finished.set(true);
if (monitorThread != null && monitorThread.isAlive()) {
monitorThread.interrupt();
}
Optional.ofNullable(monitorThread).filter(Thread::isAlive).ifPresent(Thread::interrupt);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.internal.Utils;
import org.testng.util.Strings;
import org.testng.xml.XmlSuite;

public class FailedInformationOnConsoleReporter implements IReporter {
Expand All @@ -35,30 +34,30 @@ private static void generateReport(String name, ISuiteResult suiteResult) {
}

if (hasFailedConfigs) {
System.err.println(Strings.repeat("=", 100));
System.err.println("=".repeat(100));
System.err.println(
"::::::Failed Configurations for Suite ::: ["
+ name
+ "] ::: Test name ["
+ ctx.getName()
+ "]::::::");
System.err.println(Strings.repeat("=", 100));
System.err.println("=".repeat(100));
failedConfigs.getAllResults().forEach(FailedInformationOnConsoleReporter::generateReport);
System.err.println(Strings.repeat("=", 100));
System.err.println("=".repeat(100));
System.err.println("\n\n");
}

if (hasFailedTests) {
System.err.println(Strings.repeat("=", 100));
System.err.println("=".repeat(100));
System.err.println(
"::::::Failed Tests for Suite ::: ["
+ name
+ "] ::: Test name ["
+ ctx.getName()
+ "]::::::");
System.err.println(Strings.repeat("=", 100));
System.err.println("=".repeat(100));
failedTests.getAllResults().forEach(FailedInformationOnConsoleReporter::generateReport);
System.err.println(Strings.repeat("=", 100));
System.err.println("=".repeat(100));
System.err.println("\n\n");
}
}
Expand All @@ -76,6 +75,6 @@ private static void generateReport(ITestResult result) {
builder.append("\nException:\n");
builder.append(Utils.shortStackTrace(throwable, false));
builder.append("\n\n");
System.err.println(builder.toString());
System.err.println(builder);
}
}
26 changes: 14 additions & 12 deletions testng-core/src/test/kotlin/org/testng/util/StringsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,22 @@ import org.testng.annotations.Test

class StringsTest {
@Test
fun joinEmptyArray() {
val emptyArray = arrayOf<String>()
assertThat(Strings.join(",", emptyArray)).isEmpty()
fun testValueOf() {
val input = mapOf(
Pair("skill", "Kung-Fu"),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use "to" keyword instead of Pair()

Pair("expertise-level", "Master"),
Pair("name", "Po")
)
val expected = "Kung-Fu Master Po"
val actual = Strings.valueOf(input)
assertThat(actual).isEqualTo(expected)
}

@Test
fun joinArrayWithOneElement() {
val array = arrayOf("one")
assertThat(Strings.join(",", array)).isEqualTo("one")
}

@Test
fun joinArrayWithTwoElements() {
val array = arrayOf("one", "two")
assertThat(Strings.join(",", array)).isEqualTo("one,two")
fun testEscapeHtml() {
val input = "&<>"
val expected = "&amp;&lt;&gt;"
val actual = Strings.escapeHtml(input)
assertThat(actual).isEqualTo(expected)
}
}