Skip to content

Commit

Permalink
fix: Assert.assertThrows() should check result of exceptionConsumer (#…
Browse files Browse the repository at this point in the history
…135)

* fix: Assert.assertThrows() should check result of exceptionConsumer

* fix some warnings

* remove assertThrowsFuture() from Assert
  • Loading branch information
javeme authored Nov 30, 2023
1 parent 5ad55fb commit 8c93652
Show file tree
Hide file tree
Showing 8 changed files with 121 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
import java.util.List;
import java.util.Map;

import org.apache.hugegraph.util.E;
import org.apache.hugegraph.util.Log;
import javax.annotation.Nullable;

import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.FileBasedConfiguration;
import org.apache.commons.configuration2.PropertiesConfiguration;
Expand All @@ -35,10 +35,10 @@
import org.apache.commons.configuration2.io.FileHandler;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hugegraph.util.E;
import org.apache.hugegraph.util.Log;
import org.slf4j.Logger;

import javax.annotation.Nullable;

public class HugeConfig extends PropertiesConfiguration {

private static final Logger LOG = Log.logger(HugeConfig.class);
Expand Down Expand Up @@ -117,7 +117,7 @@ public void addPropertyDirect(String key, Object value) {
value = this.validateOption(key, value);
}
if (this.containsKey(key) && value instanceof List) {
for (Object item : (List<Object>) value) {
for (Object item : (List<?>) value) {
super.addPropertyDirect(key, item);
}
} else {
Expand All @@ -137,7 +137,7 @@ private Object validateOption(String key, Object value) {
return option.parseConvert((String) value);
}

Class dataType = option.dataType();
Class<?> dataType = option.dataType();
if (dataType.isInstance(value)) {
return value;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@ public long preventOptimizePadding() {
}
}

public static final class LocalStack<E> {
public static final class LocalStack<T> {

private final Object[] elementData;
private int elementCount;
Expand All @@ -574,27 +574,27 @@ boolean empty() {
return this.elementCount == 0;
}

public void push(E elem) {
public void push(T elem) {
this.elementData[this.elementCount++] = elem;
}

public E pop() {
public T pop() {
if (this.elementCount == 0) {
throw new EmptyStackException();
}
this.elementCount--;
@SuppressWarnings("unchecked")
E elem = (E) this.elementData[this.elementCount];
T elem = (T) this.elementData[this.elementCount];
this.elementData[this.elementCount] = null;
return elem;
}

public E peek() {
public T peek() {
if (this.elementCount == 0) {
throw new EmptyStackException();
}
@SuppressWarnings("unchecked")
E elem = (E) this.elementData[this.elementCount - 1];
T elem = (T) this.elementData[this.elementCount - 1];
return elem;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
@Builder
@Getter
@Setter
@SuppressWarnings("unused")
public class RestClientConfig {

private String user;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

package org.apache.hugegraph.testutil;

import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;

Expand All @@ -37,43 +36,36 @@ public interface ThrowableConsumer<T> {
void accept(T t) throws Throwable;
}

public static void assertThrows(Class<? extends Throwable> throwable,
ThrowableRunnable runnable) {
CompletableFuture<?> future = assertThrowsFuture(throwable, runnable);
future.thenAccept(System.err::println);
}

public static void assertThrows(Class<? extends Throwable> throwable,
public static void assertThrows(Class<? extends Throwable> clazz,
ThrowableRunnable runnable,
Consumer<Throwable> exceptionConsumer) {
CompletableFuture<Throwable> future = assertThrowsFuture(throwable,
runnable);
future.thenAccept(exceptionConsumer);
Throwable expectedException = assertThrows(clazz, runnable);
assert expectedException != null;
exceptionConsumer.accept(expectedException);
}

public static CompletableFuture<Throwable> assertThrowsFuture(
Class<? extends Throwable> clazz,
ThrowableRunnable runnable) {
CompletableFuture<Throwable> future = new CompletableFuture<>();
boolean fail = false;
public static Throwable assertThrows(Class<? extends Throwable> clazz,
ThrowableRunnable runnable) {
try {
// expect throwing here
runnable.run();
fail = true;
} catch (Throwable e) {
if (!clazz.isInstance(e)) {
Assert.fail(String.format(
"Bad exception type %s(expected %s)",
e.getClass().getName(), clazz.getName()));
// exception type not matched
Assert.fail(String.format("Bad exception type %s(expected %s)",
e.getClass().getName(), clazz.getName()));
}
future.complete(e);
}
if (fail) {
String msg = String.format("No exception was thrown(expected %s)",
clazz.getName());
future.completeExceptionally(new AssertionError(msg));
Assert.fail(msg);

return e;
}
return future;

// no exception
Assert.fail(String.format("No exception was thrown(expected %s)",
clazz.getName()));

// unavailable
assert false;
return null;
}

public static void assertEquals(byte expected, Object actual) {
Expand Down Expand Up @@ -104,34 +96,40 @@ public static void assertEquals(double expected, Object actual) {
org.junit.Assert.assertEquals(expected, actual);
}

@SuppressWarnings("deprecation")
public static void assertGt(Number expected, Object actual) {
org.junit.Assert.assertThat(actual, new NumberMatcher(expected, cmp -> {
return cmp > 0;
}, ">"));
}

@SuppressWarnings("deprecation")
public static void assertGte(Number expected, Object actual) {
org.junit.Assert.assertThat(actual, new NumberMatcher(expected, cmp -> {
return cmp >= 0;
}, ">="));
}

@SuppressWarnings("deprecation")
public static void assertLt(Number expected, Object actual) {
org.junit.Assert.assertThat(actual, new NumberMatcher(expected, cmp -> {
return cmp < 0;
}, "<"));
}

@SuppressWarnings("deprecation")
public static void assertLte(Number expected, Object actual) {
org.junit.Assert.assertThat(actual, new NumberMatcher(expected, cmp -> {
return cmp <= 0;
}, "<="));
}

@SuppressWarnings("deprecation")
public static void assertContains(String sub, String actual) {
org.junit.Assert.assertThat(actual, CoreMatchers.containsString(sub));
}

@SuppressWarnings("deprecation")
public static void assertInstanceOf(Class<?> clazz, Object object) {
org.junit.Assert.assertThat(object, CoreMatchers.instanceOf(clazz));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package org.apache.hugegraph.util;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public final class ExceptionUtil {

public static Throwable rootCause(Throwable e) {
Throwable cause = e;
while (cause.getCause() != null) {
cause = cause.getCause();
}
return cause;
}

public static RuntimeException transToRuntimeException(Throwable e) {
if (e instanceof RuntimeException) {
return (RuntimeException) e;
}
return new RuntimeException(rootCause(e).getMessage(), e);
}

public static <T> T futureGet(Future<T> future) {
try {
return future.get();
} catch (InterruptedException e) {
throw ExceptionUtil.transToRuntimeException(e);
} catch (ExecutionException e) {
throw ExceptionUtil.transToRuntimeException(e.getCause());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@

package org.apache.hugegraph.testutil;

import org.junit.Test;

import org.apache.hugegraph.unit.BaseUnitTest;
import org.junit.Test;

public class AssertTest extends BaseUnitTest {

Expand Down Expand Up @@ -175,6 +174,12 @@ public void testAssertThrows() {
throw new RuntimeException();
});

Throwable exception = Assert.assertThrows(RuntimeException.class, () -> {
throw new RuntimeException("fake-error");
});
Assert.assertInstanceOf(RuntimeException.class, exception);
Assert.assertEquals("fake-error", exception.getMessage());

Assert.assertThrows(RuntimeException.class, () -> {
throw new RuntimeException("fake-error");
}, e -> {
Expand All @@ -183,7 +188,7 @@ public void testAssertThrows() {
}

@Test
public void testAssertThrowsWithError() {
public void testAssertThrowsWithTypeError() {
try {
Assert.assertThrows(NullPointerException.class, () -> {
// pass
Expand All @@ -204,6 +209,21 @@ public void testAssertThrowsWithError() {
}
}

@Test
public void testAssertThrowsWithMessageError() {
try {
Assert.assertThrows(RuntimeException.class, () -> {
throw new RuntimeException("fake-error");
}, e -> {
Assert.assertEquals("fake-error-typo", e.getMessage());
});
Assert.fail("Expect error");
} catch (AssertionError e) {
Assert.assertContains("expected:<fake-error[-typo]> but was:<fake-error[]>",
e.getMessage());
}
}

@Test
public void testAssertGt() {
Assert.assertGt((byte) 1, Byte.valueOf("2"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.io.FileUtils;
import org.apache.hugegraph.util.ExceptionUtil;
import org.apache.hugegraph.util.TimeUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
Expand All @@ -51,11 +51,7 @@ protected static void runWithThreads(int threads, Runnable task) {
futures.add(executor.submit(task));
}
for (Future<?> future : futures) {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
ExceptionUtil.futureGet(future);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,19 @@
import java.util.Comparator;
import java.util.List;

import org.junit.Test;

import org.apache.commons.collections.IteratorUtils;
import org.apache.hugegraph.perf.PerfUtil;
import org.apache.hugegraph.testutil.Assert;
import org.apache.hugegraph.unit.BaseUnitTest;
import org.apache.hugegraph.unit.perf.testclass.TestClass;
import org.apache.hugegraph.unit.perf.testclass.TestClass.Bar;
import org.apache.hugegraph.unit.perf.testclass.TestClass.Base;
import org.apache.hugegraph.unit.perf.testclass.TestClass.Foo;
import org.apache.hugegraph.unit.perf.testclass.TestClass.ManuallyProfile;
import org.apache.hugegraph.unit.perf.testclass.TestClass.Sub;
import org.apache.hugegraph.perf.PerfUtil;
import org.apache.hugegraph.unit.BaseUnitTest;
import org.apache.hugegraph.util.ReflectionUtil;
import org.apache.commons.collections.IteratorUtils;
import org.junit.Test;

import com.google.common.reflect.ClassPath.ClassInfo;

import javassist.NotFoundException;
Expand Down Expand Up @@ -94,16 +94,16 @@ public void testClasses() throws IOException {
@SuppressWarnings("unchecked")
List<ClassInfo> classes = IteratorUtils.toList(ReflectionUtil.classes(
"org.apache.hugegraph.util"));
Assert.assertEquals(18, classes.size());
Assert.assertEquals(19, classes.size());
classes.sort(Comparator.comparing(ClassInfo::getName));
Assert.assertEquals("org.apache.hugegraph.util.Bytes",
classes.get(0).getName());
Assert.assertEquals("org.apache.hugegraph.util.CheckSocket",
classes.get(1).getName());
Assert.assertEquals("org.apache.hugegraph.util.CollectionUtil",
classes.get(2).getName());
Assert.assertEquals("org.apache.hugegraph.util.VersionUtil",
classes.get(17).getName());
Assert.assertEquals("org.apache.hugegraph.util.DateUtil",
classes.get(3).getName());
}

@Test
Expand Down

0 comments on commit 8c93652

Please sign in to comment.