Browse Source

KAFKA-10447: Migrate tools module to JUnit 5 (#9231)

This change sets the groundwork for migrating other modules incrementally.

Main changes:
- Replace `junit` 4.13 with `junit-jupiter` and `junit-vintage` 5.7.0-RC1.
- All modules except for `tools` depend on `junit-vintage`.
- `tools` depends on `junit-jupiter`.
- Convert `tools` tests to JUnit 5.
- Update `PushHttpMetricsReporterTest` to use `mockito` instead of `powermock` and `easymock`
(powermock doesn't seem to work well with JUnit 5 and we don't need it since mockito can mock
static methods).
- Update `mockito` to 3.5.7.
- Update `TestUtils` to use JUnit 5 assertions since `tools` depends on it.

Unrelated clean-ups:
- Remove `unit` from package names in a few `core` tests.
- Replace `try/catch/fail` with `assertThrows` in a number of places.
- Tag `CoordinatorTest` as integration test.
- Remove unnecessary type parameters when invoking methods and constructors.

Tested with IntelliJ and gradle. Verified that the following commands work as expected:
* ./gradlew tools:unitTest
* ./gradlew tools:integrationTest
* ./gradlew tools:test
* ./gradlew core:unitTest
* ./gradlew core:integrationTest
* ./gradlew clients:test

Reviewers: Manikumar Reddy <manikumar.reddy@gmail.com>
pull/10233/head
Ismael Juma 4 years ago committed by GitHub
parent
commit
7d0086e0c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 80
      build.gradle
  2. 27
      clients/src/test/java/org/apache/kafka/test/TestUtils.java
  3. 3
      core/src/test/scala/unit/kafka/cluster/AbstractPartitionTest.scala
  4. 3
      core/src/test/scala/unit/kafka/cluster/AssignmentStateTest.scala
  5. 1
      core/src/test/scala/unit/kafka/cluster/PartitionTest.scala
  6. 3
      core/src/test/scala/unit/kafka/utils/ThrottlerTest.scala
  7. 9
      gradle/dependencies.gradle
  8. 4
      tools/src/main/java/org/apache/kafka/trogdor/fault/Kibosh.java
  9. 233
      tools/src/test/java/org/apache/kafka/tools/PushHttpMetricsReporterTest.java
  10. 51
      tools/src/test/java/org/apache/kafka/trogdor/agent/AgentTest.java
  11. 13
      tools/src/test/java/org/apache/kafka/trogdor/basic/BasicPlatformTest.java
  12. 8
      tools/src/test/java/org/apache/kafka/trogdor/common/JsonSerializationTest.java
  13. 33
      tools/src/test/java/org/apache/kafka/trogdor/common/JsonUtilTest.java
  14. 17
      tools/src/test/java/org/apache/kafka/trogdor/common/StringExpanderTest.java
  15. 16
      tools/src/test/java/org/apache/kafka/trogdor/common/StringFormatterTest.java
  16. 21
      tools/src/test/java/org/apache/kafka/trogdor/common/TopologyTest.java
  17. 30
      tools/src/test/java/org/apache/kafka/trogdor/common/WorkerUtilsTest.java
  18. 15
      tools/src/test/java/org/apache/kafka/trogdor/coordinator/CoordinatorClientTest.java
  19. 40
      tools/src/test/java/org/apache/kafka/trogdor/coordinator/CoordinatorTest.java
  20. 32
      tools/src/test/java/org/apache/kafka/trogdor/rest/RestExceptionMapperTest.java
  21. 20
      tools/src/test/java/org/apache/kafka/trogdor/task/TaskSpecTest.java
  22. 14
      tools/src/test/java/org/apache/kafka/trogdor/workload/ConsumeBenchSpecTest.java
  23. 13
      tools/src/test/java/org/apache/kafka/trogdor/workload/ExternalCommandWorkerTest.java
  24. 39
      tools/src/test/java/org/apache/kafka/trogdor/workload/HistogramTest.java
  25. 41
      tools/src/test/java/org/apache/kafka/trogdor/workload/PayloadGeneratorTest.java
  26. 35
      tools/src/test/java/org/apache/kafka/trogdor/workload/ThrottleTest.java
  27. 6
      tools/src/test/java/org/apache/kafka/trogdor/workload/TimeIntervalTransactionsGeneratorTest.java
  28. 14
      tools/src/test/java/org/apache/kafka/trogdor/workload/TopicsSpecTest.java

80
build.gradle

@ -241,6 +241,7 @@ subprojects { @@ -241,6 +241,7 @@ subprojects {
}
}
def shouldUseJUnit5 = it.project.name == 'tools'
def testLoggingEvents = ["passed", "skipped", "failed"]
def testShowStandardStreams = false
def testExceptionFormat = 'full'
@ -330,6 +331,9 @@ subprojects { @@ -330,6 +331,9 @@ subprojects {
// Gradle will run each test class, so we exclude the suites to avoid redundantly running the tests twice.
exclude '**/*Suite.class'
if (shouldUseJUnit5)
useJUnitPlatform()
retry {
maxRetries = userMaxTestRetries
maxFailures = userMaxTestRetryFailures
@ -355,8 +359,14 @@ subprojects { @@ -355,8 +359,14 @@ subprojects {
// Gradle will run each test class, so we exclude the suites to avoid redundantly running the tests twice.
exclude '**/*Suite.class'
useJUnit {
includeCategories 'org.apache.kafka.test.IntegrationTest'
if (shouldUseJUnit5) {
useJUnitPlatform {
includeTags "integration"
}
} else {
useJUnit {
includeCategories 'org.apache.kafka.test.IntegrationTest'
}
}
retry {
@ -383,9 +393,15 @@ subprojects { @@ -383,9 +393,15 @@ subprojects {
// Gradle will run each test class, so we exclude the suites to avoid redundantly running the tests twice.
exclude '**/*Suite.class'
if (it.project.name != 'generator') {
useJUnit {
excludeCategories 'org.apache.kafka.test.IntegrationTest'
if (shouldUseJUnit5) {
useJUnitPlatform {
excludeTags "integration"
}
} else {
if (it.project.name != 'generator') {
useJUnit {
excludeCategories 'org.apache.kafka.test.IntegrationTest'
}
}
}
@ -761,7 +777,8 @@ project(':core') { @@ -761,7 +777,8 @@ project(':core') {
testCompile libs.apachedsLdifPartition
testCompile libs.apachedsMavibotPartition
testCompile libs.apachedsJdbmPartition
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.scalatest
testCompile libs.slf4jlog4j
testCompile libs.jfreechart
@ -982,7 +999,8 @@ project(':generator') { @@ -982,7 +999,8 @@ project(':generator') {
compile libs.jacksonDatabind
compile libs.jacksonJDK8Datatypes
compile libs.jacksonJaxrsJsonProvider
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
}
integrationTest {
@ -1016,7 +1034,8 @@ project(':clients') { @@ -1016,7 +1034,8 @@ project(':clients') {
jacksonDatabindConfig libs.jacksonDatabind // to publish as provided scope dependency.
testCompile libs.bcpkix
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.mockitoCore
testRuntime libs.slf4jlog4j
@ -1141,11 +1160,9 @@ project(':tools') { @@ -1141,11 +1160,9 @@ project(':tools') {
compile libs.jettyServlets
testCompile project(':clients')
testCompile libs.junit
testCompile libs.junitJupiter
testCompile project(':clients').sourceSets.test.output
testCompile libs.easymock
testCompile libs.powermockJunit4
testCompile libs.powermockEasymock
testCompile libs.mockitoInline // supports mocking static methods, final classes, etc.
testRuntime libs.slf4jlog4j
}
@ -1193,7 +1210,8 @@ project(':streams') { @@ -1193,7 +1210,8 @@ project(':streams') {
testCompile project(':core')
testCompile project(':core').sourceSets.test.output
testCompile libs.log4j
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.easymock
testCompile libs.powermockJunit4
testCompile libs.powermockEasymock
@ -1324,7 +1342,8 @@ project(':streams:streams-scala') { @@ -1324,7 +1342,8 @@ project(':streams:streams-scala') {
testCompile project(':clients').sourceSets.test.output
testCompile project(':streams:test-utils')
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.scalatest
testCompile libs.easymock
testCompile libs.hamcrest
@ -1359,7 +1378,8 @@ project(':streams:test-utils') { @@ -1359,7 +1378,8 @@ project(':streams:test-utils') {
compile project(':clients')
testCompile project(':clients').sourceSets.test.output
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.easymock
testCompile libs.hamcrest
@ -1395,7 +1415,8 @@ project(':streams:examples') { @@ -1395,7 +1415,8 @@ project(':streams:examples') {
testCompile project(':streams:test-utils')
testCompile project(':clients').sourceSets.test.output // for org.apache.kafka.test.IntegrationTest
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
}
javadoc {
@ -1630,7 +1651,8 @@ project(':log4j-appender') { @@ -1630,7 +1651,8 @@ project(':log4j-appender') {
compile libs.slf4jlog4j
testCompile project(':clients').sourceSets.test.output
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.easymock
}
@ -1648,7 +1670,8 @@ project(':connect:api') { @@ -1648,7 +1670,8 @@ project(':connect:api') {
compile libs.slf4jApi
compile libs.jaxrsApi
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testRuntime libs.slf4jlog4j
testCompile project(':clients').sourceSets.test.output
@ -1689,7 +1712,8 @@ project(':connect:transforms') { @@ -1689,7 +1712,8 @@ project(':connect:transforms') {
compile libs.slf4jApi
testCompile libs.easymock
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.powermockJunit4
testCompile libs.powermockEasymock
@ -1729,7 +1753,8 @@ project(':connect:json') { @@ -1729,7 +1753,8 @@ project(':connect:json') {
compile libs.slf4jApi
testCompile libs.easymock
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.powermockJunit4
testCompile libs.powermockEasymock
@ -1785,7 +1810,8 @@ project(':connect:runtime') { @@ -1785,7 +1810,8 @@ project(':connect:runtime') {
testCompile project(':clients').sourceSets.test.output
testCompile libs.easymock
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.powermockJunit4
testCompile libs.powermockEasymock
testCompile libs.mockitoCore
@ -1871,7 +1897,8 @@ project(':connect:file') { @@ -1871,7 +1897,8 @@ project(':connect:file') {
compile libs.slf4jApi
testCompile libs.easymock
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.powermockJunit4
testCompile libs.powermockEasymock
@ -1910,7 +1937,8 @@ project(':connect:basic-auth-extension') { @@ -1910,7 +1937,8 @@ project(':connect:basic-auth-extension') {
testCompile libs.bcpkix
testCompile libs.easymock
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.powermockJunit4
testCompile libs.powermockEasymock
testCompile project(':clients').sourceSets.test.output
@ -1952,7 +1980,8 @@ project(':connect:mirror') { @@ -1952,7 +1980,8 @@ project(':connect:mirror') {
compile libs.argparse4j
compile libs.slf4jApi
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile libs.mockitoCore
testCompile project(':clients').sourceSets.test.output
testCompile project(':connect:runtime').sourceSets.test.output
@ -1992,7 +2021,8 @@ project(':connect:mirror-client') { @@ -1992,7 +2021,8 @@ project(':connect:mirror-client') {
compile project(':clients')
compile libs.slf4jApi
testCompile libs.junit
testCompile libs.junitJupiterApi
testCompile libs.junitVintageEngine
testCompile project(':clients').sourceSets.test.output
testRuntime libs.slf4jlog4j

27
clients/src/test/java/org/apache/kafka/test/TestUtils.java

@ -64,12 +64,11 @@ import java.util.regex.Matcher; @@ -64,12 +64,11 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Helper functions for writing unit tests
@ -98,7 +97,7 @@ public class TestUtils { @@ -98,7 +97,7 @@ public class TestUtils {
}
public static Cluster clusterWith(int nodes) {
return clusterWith(nodes, new HashMap<String, Integer>());
return clusterWith(nodes, new HashMap<>());
}
public static Cluster clusterWith(final int nodes, final Map<String, Integer> topicPartitionCounts) {
@ -398,8 +397,8 @@ public class TestUtils { @@ -398,8 +397,8 @@ public class TestUtils {
retryOnExceptionWithTimeout(maxWaitMs, () -> {
String conditionDetailsSupplied = conditionDetailsSupplier != null ? conditionDetailsSupplier.get() : null;
String conditionDetails = conditionDetailsSupplied != null ? conditionDetailsSupplied : "";
assertThat("Condition not met within timeout " + maxWaitMs + ". " + conditionDetails,
testCondition.conditionMet());
assertTrue(testCondition.conditionMet(),
"Condition not met within timeout " + maxWaitMs + ". " + conditionDetails);
});
}
@ -554,8 +553,8 @@ public class TestUtils { @@ -554,8 +553,8 @@ public class TestUtils {
*/
public static <T extends Throwable> T assertFutureThrows(Future<?> future, Class<T> exceptionCauseClass) {
ExecutionException exception = assertThrows(ExecutionException.class, future::get);
assertTrue("Unexpected exception cause " + exception.getCause(),
exceptionCauseClass.isInstance(exception.getCause()));
assertTrue(exceptionCauseClass.isInstance(exception.getCause()),
"Unexpected exception cause " + exception.getCause());
return exceptionCauseClass.cast(exception.getCause());
}
@ -566,9 +565,9 @@ public class TestUtils { @@ -566,9 +565,9 @@ public class TestUtils {
fail("Expected a " + exceptionClass.getSimpleName() + " exception, but got success.");
} catch (ExecutionException ee) {
Throwable cause = ee.getCause();
assertEquals("Expected a " + exceptionClass.getSimpleName() + " exception, but got " +
cause.getClass().getSimpleName(),
exceptionClass, cause.getClass());
assertEquals(exceptionClass, cause.getClass(),
"Expected a " + exceptionClass.getSimpleName() + " exception, but got " +
cause.getClass().getSimpleName());
}
}

3
core/src/test/scala/unit/kafka/cluster/AbstractPartitionTest.scala

@ -14,13 +14,12 @@ @@ -14,13 +14,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unit.kafka.cluster
package kafka.cluster
import java.io.File
import java.util.Properties
import kafka.api.ApiVersion
import kafka.cluster.{DelayedOperations, Partition, PartitionStateStore}
import kafka.log.{CleanerConfig, LogConfig, LogManager}
import kafka.server.{Defaults, MetadataCache}
import kafka.server.checkpoints.OffsetCheckpoints

3
core/src/test/scala/unit/kafka/cluster/AssignmentStateTest.scala

@ -14,9 +14,8 @@ @@ -14,9 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unit.kafka.cluster
package kafka.cluster
import kafka.cluster.SimpleAssignmentState
import org.apache.kafka.common.message.LeaderAndIsrRequestData.LeaderAndIsrPartitionState
import org.junit.Assert.{assertEquals, assertFalse, assertTrue}
import org.junit.Test

1
core/src/test/scala/unit/kafka/cluster/PartitionTest.scala

@ -42,7 +42,6 @@ import org.mockito.ArgumentMatchers @@ -42,7 +42,6 @@ import org.mockito.ArgumentMatchers
import org.mockito.Mockito._
import org.mockito.invocation.InvocationOnMock
import org.scalatest.Assertions.assertThrows
import unit.kafka.cluster.AbstractPartitionTest
import scala.jdk.CollectionConverters._

3
core/src/test/scala/unit/kafka/utils/ThrottlerTest.scala

@ -15,9 +15,8 @@ @@ -15,9 +15,8 @@
* limitations under the License.
*/
package unit.kafka.utils
package kafka.utils
import kafka.utils.Throttler
import org.apache.kafka.common.utils.MockTime
import org.junit.Test
import org.junit.Assert.{assertTrue, assertEquals}

9
gradle/dependencies.gradle

@ -78,7 +78,7 @@ versions += [ @@ -78,7 +78,7 @@ versions += [
jaxrs: "2.1.1",
jfreechart: "1.0.0",
jopt: "5.0.4",
junit: "4.13",
junit: "5.7.0-RC1",
kafka_0100: "0.10.0.1",
kafka_0101: "0.10.1.1",
kafka_0102: "0.10.2.2",
@ -95,7 +95,7 @@ versions += [ @@ -95,7 +95,7 @@ versions += [
lz4: "1.7.1",
mavenArtifact: "3.6.3",
metrics: "2.2.0",
mockito: "3.4.4",
mockito: "3.5.7",
netty: "4.1.51.Final",
owaspDepCheckPlugin: "5.3.2.1",
powermock: "2.0.7",
@ -151,7 +151,9 @@ libs += [ @@ -151,7 +151,9 @@ libs += [
jmhCoreBenchmarks: "org.openjdk.jmh:jmh-core-benchmarks:$versions.jmh",
jmhGeneratorAnnProcess: "org.openjdk.jmh:jmh-generator-annprocess:$versions.jmh",
joptSimple: "net.sf.jopt-simple:jopt-simple:$versions.jopt",
junit: "junit:junit:$versions.junit",
junitJupiter: "org.junit.jupiter:junit-jupiter:$versions.junit",
junitJupiterApi: "org.junit.jupiter:junit-jupiter-api:$versions.junit",
junitVintageEngine: "org.junit.vintage:junit-vintage-engine:$versions.junit",
hamcrest: "org.hamcrest:hamcrest:$versions.hamcrest",
kafkaStreams_0100: "org.apache.kafka:kafka-streams:$versions.kafka_0100",
kafkaStreams_0101: "org.apache.kafka:kafka-streams:$versions.kafka_0101",
@ -170,6 +172,7 @@ libs += [ @@ -170,6 +172,7 @@ libs += [
lz4: "org.lz4:lz4-java:$versions.lz4",
metrics: "com.yammer.metrics:metrics-core:$versions.metrics",
mockitoCore: "org.mockito:mockito-core:$versions.mockito",
mockitoInline: "org.mockito:mockito-inline:$versions.mockito",
nettyHandler: "io.netty:netty-handler:$versions.netty",
nettyTransportNativeEpoll: "io.netty:netty-transport-native-epoll:$versions.netty",
powermockJunit4: "org.powermock:powermock-module-junit4:$versions.powermock",

4
tools/src/main/java/org/apache/kafka/trogdor/fault/Kibosh.java

@ -124,7 +124,7 @@ public final class Kibosh { @@ -124,7 +124,7 @@ public final class Kibosh {
private final List<KiboshFaultSpec> faults;
public final static KiboshControlFile EMPTY =
new KiboshControlFile(Collections.<KiboshFaultSpec>emptyList());
new KiboshControlFile(Collections.emptyList());
public static KiboshControlFile read(Path controlPath) throws IOException {
byte[] controlFileBytes = Files.readAllBytes(controlPath);
@ -133,7 +133,7 @@ public final class Kibosh { @@ -133,7 +133,7 @@ public final class Kibosh {
@JsonCreator
public KiboshControlFile(@JsonProperty("faults") List<KiboshFaultSpec> faults) {
this.faults = faults == null ? new ArrayList<KiboshFaultSpec>() : faults;
this.faults = faults == null ? new ArrayList<>() : faults;
}
@JsonProperty

233
tools/src/test/java/org/apache/kafka/tools/PushHttpMetricsReporterTest.java

@ -16,8 +16,21 @@ @@ -16,8 +16,21 @@
*/
package org.apache.kafka.tools;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.config.ConfigException;
@ -26,15 +39,6 @@ import org.apache.kafka.common.metrics.KafkaMetric; @@ -26,15 +39,6 @@ import org.apache.kafka.common.metrics.KafkaMetric;
import org.apache.kafka.common.metrics.MetricConfig;
import org.apache.kafka.common.utils.MockTime;
import org.apache.kafka.common.utils.Time;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.api.easymock.annotation.MockStrict;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.InputStream;
import java.io.OutputStream;
@ -49,14 +53,14 @@ import java.util.HashMap; @@ -49,14 +53,14 @@ import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.powermock.api.easymock.PowerMock.replayAll;
import static org.powermock.api.easymock.PowerMock.verifyAll;
@RunWith(PowerMockRunner.class)
@PrepareForTest(PushHttpMetricsReporter.class)
public class PushHttpMetricsReporterTest {
private static final URL URL;
@ -67,64 +71,67 @@ public class PushHttpMetricsReporterTest { @@ -67,64 +71,67 @@ public class PushHttpMetricsReporterTest {
throw new RuntimeException(e);
}
}
private final Time time = new MockTime();
private final ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
private final HttpURLConnection httpReq = mock(HttpURLConnection.class);
private final OutputStream httpOut = mock(OutputStream.class);
private final InputStream httpErr = mock(InputStream.class);
private final ArgumentCaptor<Runnable> reportRunnableCaptor = ArgumentCaptor.forClass(Runnable.class);
private final ArgumentCaptor<byte[]> httpPayloadCaptor = ArgumentCaptor.forClass(byte[].class);
private PushHttpMetricsReporter reporter;
private Time time = new MockTime();
@MockStrict
private ScheduledExecutorService executor;
private Capture<Runnable> reportRunnable = EasyMock.newCapture();
@MockStrict
private HttpURLConnection httpReq;
@MockStrict
private OutputStream httpOut;
private Capture<byte[]> httpPayload = EasyMock.newCapture();
@MockStrict
private InputStream httpErr;
@Before
private MockedStatic<PushHttpMetricsReporter> mockedStaticReporter;
@BeforeEach
public void setUp() {
reporter = new PushHttpMetricsReporter(time, executor);
PowerMock.mockStatic(PushHttpMetricsReporter.class);
mockedStaticReporter = Mockito.mockStatic(PushHttpMetricsReporter.class);
}
@AfterEach
public void tearDown() {
mockedStaticReporter.close();
}
@Test
public void testConfigureClose() throws Exception {
expectConfigure();
expectClose();
replayAll();
whenClose();
configure();
reporter.close();
verifyAll();
verifyConfigure();
verifyClose();
}
@Test(expected = ConfigException.class)
public void testConfigureBadUrl() throws Exception {
@Test
public void testConfigureBadUrl() {
Map<String, String> config = new HashMap<>();
config.put(PushHttpMetricsReporter.METRICS_URL_CONFIG, "malformed;url");
config.put(PushHttpMetricsReporter.METRICS_PERIOD_CONFIG, "5");
reporter.configure(config);
assertThrows(ConfigException.class, () -> reporter.configure(config));
}
@Test(expected = ConfigException.class)
public void testConfigureMissingPeriod() throws Exception {
@Test
public void testConfigureMissingPeriod() {
Map<String, String> config = new HashMap<>();
config.put(PushHttpMetricsReporter.METRICS_URL_CONFIG, URL.toString());
reporter.configure(config);
assertThrows(ConfigException.class, () -> reporter.configure(config));
}
@Test
public void testNoMetrics() throws Exception {
expectConfigure();
expectRequest(200);
expectClose();
replayAll();
whenRequest(200);
configure();
reportRunnable.getValue().run();
JsonNode payload = new ObjectMapper().readTree(httpPayload.getValue());
verifyConfigure();
reportRunnableCaptor.getValue().run();
verifyResponse();
JsonNode payload = new ObjectMapper().readTree(httpPayloadCaptor.getValue());
assertTrue(payload.isObject());
assertPayloadHasClientInfo(payload);
@ -136,52 +143,44 @@ public class PushHttpMetricsReporterTest { @@ -136,52 +143,44 @@ public class PushHttpMetricsReporterTest {
assertEquals(0, metrics.size());
reporter.close();
verifyAll();
verifyClose();
}
// For error conditions, we expect them to come with a response body that we can read & log
@Test
public void testClientError() throws Exception {
expectConfigure();
expectRequest(400, true);
expectClose();
replayAll();
whenRequest(400, true);
configure();
reportRunnable.getValue().run();
verifyConfigure();
reporter.close();
reportRunnableCaptor.getValue().run();
verifyResponse();
verifyAll();
reporter.close();
verifyClose();
}
@Test
public void testServerError() throws Exception {
expectConfigure();
expectRequest(500, true);
expectClose();
replayAll();
whenRequest(500, true);
configure();
reportRunnable.getValue().run();
verifyConfigure();
reporter.close();
reportRunnableCaptor.getValue().run();
verifyResponse();
verifyAll();
reporter.close();
verifyClose();
}
@Test
public void testMetricValues() throws Exception {
expectConfigure();
expectRequest(200);
expectClose();
replayAll();
whenRequest(200);
configure();
verifyConfigure();
KafkaMetric metric1 = new KafkaMetric(
new Object(),
new MetricName("name1", "group1", "desc1", Collections.singletonMap("key1", "value1")),
@ -223,8 +222,10 @@ public class PushHttpMetricsReporterTest { @@ -223,8 +222,10 @@ public class PushHttpMetricsReporterTest {
reporter.metricChange(metric3); // added by change
reporter.metricRemoval(metric2); // added in init, deleted by removal
reportRunnable.getValue().run();
JsonNode payload = new ObjectMapper().readTree(httpPayload.getValue());
reportRunnableCaptor.getValue().run();
verifyResponse();
JsonNode payload = new ObjectMapper().readTree(httpPayloadCaptor.getValue());
assertTrue(payload.isObject());
assertPayloadHasClientInfo(payload);
@ -264,14 +265,7 @@ public class PushHttpMetricsReporterTest { @@ -264,14 +265,7 @@ public class PushHttpMetricsReporterTest {
assertEquals("value4", m4.get("value").textValue());
reporter.close();
verifyAll();
}
private void expectConfigure() {
EasyMock.expect(
executor.scheduleAtFixedRate(EasyMock.capture(reportRunnable), EasyMock.eq(5L), EasyMock.eq(5L), EasyMock.eq(TimeUnit.SECONDS))
).andReturn(null); // return value not expected to be used
verifyClose();
}
private void configure() {
@ -281,42 +275,17 @@ public class PushHttpMetricsReporterTest { @@ -281,42 +275,17 @@ public class PushHttpMetricsReporterTest {
reporter.configure(config);
}
private void expectRequest(int returnStatus) throws Exception {
expectRequest(returnStatus, false);
private void whenRequest(int returnStatus) throws Exception {
whenRequest(returnStatus, false);
}
// Expect that a request is made with the given response code
private void expectRequest(int returnStatus, boolean readResponse) throws Exception {
EasyMock.expect(PushHttpMetricsReporter.newHttpConnection(URL)).andReturn(httpReq);
httpReq.setRequestMethod("POST");
EasyMock.expectLastCall();
httpReq.setDoInput(true);
EasyMock.expectLastCall();
httpReq.setRequestProperty("Content-Type", "application/json");
EasyMock.expectLastCall();
httpReq.setRequestProperty(EasyMock.eq("Content-Length"), EasyMock.anyString());
EasyMock.expectLastCall();
httpReq.setRequestProperty("Accept", "*/*");
EasyMock.expectLastCall();
httpReq.setUseCaches(false);
EasyMock.expectLastCall();
httpReq.setDoOutput(true);
EasyMock.expectLastCall();
EasyMock.expect(httpReq.getOutputStream()).andReturn(httpOut);
httpOut.write(EasyMock.capture(httpPayload));
EasyMock.expectLastCall();
httpOut.flush();
EasyMock.expectLastCall();
httpOut.close();
EasyMock.expectLastCall();
EasyMock.expect(httpReq.getResponseCode()).andReturn(returnStatus);
private void whenRequest(int returnStatus, boolean readResponse) throws Exception {
when(PushHttpMetricsReporter.newHttpConnection(URL)).thenReturn(httpReq);
when(httpReq.getOutputStream()).thenReturn(httpOut);
when(httpReq.getResponseCode()).thenReturn(returnStatus);
if (readResponse)
expectReadResponse();
httpReq.disconnect();
EasyMock.expectLastCall();
whenReadResponse();
}
private void assertPayloadHasClientInfo(JsonNode payload) throws UnknownHostException {
@ -328,15 +297,39 @@ public class PushHttpMetricsReporterTest { @@ -328,15 +297,39 @@ public class PushHttpMetricsReporterTest {
assertEquals(time.milliseconds(), client.get("time").longValue());
}
private void expectReadResponse() throws Exception {
EasyMock.expect(httpReq.getErrorStream()).andReturn(httpErr);
EasyMock.expect(PushHttpMetricsReporter.readResponse(httpErr)).andReturn("error response message");
EasyMock.expectLastCall();
private void whenReadResponse() {
when(httpReq.getErrorStream()).thenReturn(httpErr);
when(PushHttpMetricsReporter.readResponse(httpErr)).thenReturn("error response message");
}
private void whenClose() throws Exception {
when(executor.awaitTermination(anyLong(), any())).thenReturn(true);
}
private void verifyClose() throws InterruptedException {
InOrder inOrder = inOrder(executor);
inOrder.verify(executor).shutdown();
inOrder.verify(executor).awaitTermination(30L, TimeUnit.SECONDS);
}
private void verifyConfigure() {
verify(executor).scheduleAtFixedRate(reportRunnableCaptor.capture(),
eq(5L), eq(5L), eq(TimeUnit.SECONDS));
}
private void expectClose() throws Exception {
executor.shutdown();
EasyMock.expect(executor.awaitTermination(EasyMock.anyLong(), EasyMock.anyObject(TimeUnit.class))).andReturn(true);
private void verifyResponse() throws IOException {
verify(httpReq).setRequestMethod("POST");
verify(httpReq).setDoInput(true);
verify(httpReq).setRequestProperty("Content-Type", "application/json");
verify(httpReq).setRequestProperty(eq("Content-Length"), anyString());
verify(httpReq).setRequestProperty("Accept", "*/*");
verify(httpReq).setUseCaches(false);
verify(httpReq).setDoOutput(true);
verify(httpReq).disconnect();
verify(httpOut).write(httpPayloadCaptor.capture());
verify(httpOut).flush();
verify(httpOut).close();
}
static class ImmutableValue<T> implements Gauge<T> {

51
tools/src/test/java/org/apache/kafka/trogdor/agent/AgentTest.java

@ -17,6 +17,12 @@ @@ -17,6 +17,12 @@
package org.apache.kafka.trogdor.agent;
import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.fasterxml.jackson.databind.node.TextNode;
import org.apache.kafka.common.utils.MockScheduler;
import org.apache.kafka.common.utils.MockTime;
@ -48,10 +54,7 @@ import org.apache.kafka.trogdor.rest.WorkerRunning; @@ -48,10 +54,7 @@ import org.apache.kafka.trogdor.rest.WorkerRunning;
import org.apache.kafka.trogdor.task.NoOpTaskSpec;
import org.apache.kafka.trogdor.task.SampleTaskSpec;
import org.apache.kafka.trogdor.task.TaskSpec;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
@ -60,24 +63,20 @@ import java.io.PrintStream; @@ -60,24 +63,20 @@ import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeMap;
import org.junit.jupiter.api.Timeout;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
@Timeout(value = 120000, unit = MILLISECONDS)
public class AgentTest {
@Rule
final public Timeout globalTimeout = Timeout.millis(120000);
private static BasicPlatform createBasicPlatform(Scheduler scheduler) {
TreeMap<String, Node> nodes = new TreeMap<>();
HashMap<String, String> config = new HashMap<>();
config.put(Platform.Config.TROGDOR_AGENT_PORT, Integer.toString(Agent.DEFAULT_PORT));
nodes.put("node01", new BasicNode("node01", "localhost",
config, Collections.<String>emptySet()));
config, Collections.emptySet()));
BasicTopology topology = new BasicTopology(nodes);
return new BasicPlatform("node01", topology,
scheduler, new BasicPlatform.ShellCommandRunner());
@ -195,16 +194,12 @@ public class AgentTest { @@ -195,16 +194,12 @@ public class AgentTest {
client.createWorker(new CreateWorkerRequest(1, "bar", barSpec));
client.createWorker(new CreateWorkerRequest(1, "bar", barSpec));
try {
client.createWorker(new CreateWorkerRequest(1, "foo", barSpec));
Assert.fail("Expected RequestConflictException when re-creating a request with a different taskId.");
} catch (RequestConflictException exception) {
}
try {
client.createWorker(new CreateWorkerRequest(1, "bar", fooSpec));
Assert.fail("Expected RequestConflictException when re-creating a request with a different spec.");
} catch (RequestConflictException exception) {
}
assertThrows(RequestConflictException.class,
() -> client.createWorker(new CreateWorkerRequest(1, "foo", barSpec)),
"Recreating a request with a different taskId is not allowed");
assertThrows(RequestConflictException.class,
() -> client.createWorker(new CreateWorkerRequest(1, "bar", fooSpec)),
"Recreating a request with a different spec is not allowed");
new ExpectedTasks().
addTask(new ExpectedTaskBuilder("foo").
@ -371,7 +366,7 @@ public class AgentTest { @@ -371,7 +366,7 @@ public class AgentTest {
new ExpectedTasks().waitFor(client);
try (MockKibosh mockKibosh = new MockKibosh()) {
Assert.assertEquals(KiboshControlFile.EMPTY, mockKibosh.read());
assertEquals(KiboshControlFile.EMPTY, mockKibosh.read());
FilesUnreadableFaultSpec fooSpec = new FilesUnreadableFaultSpec(0, 900000,
Collections.singleton("myAgent"), mockKibosh.tempDir.getPath(), "/foo", 123);
client.createWorker(new CreateWorkerRequest(0, "foo", fooSpec));
@ -380,7 +375,7 @@ public class AgentTest { @@ -380,7 +375,7 @@ public class AgentTest {
workerState(new WorkerRunning("foo", fooSpec, 0, new TextNode("Added fault foo"))).
build()).
waitFor(client);
Assert.assertEquals(new KiboshControlFile(Collections.<Kibosh.KiboshFaultSpec>singletonList(
assertEquals(new KiboshControlFile(Collections.singletonList(
new KiboshFilesUnreadableFaultSpec("/foo", 123))), mockKibosh.read());
FilesUnreadableFaultSpec barSpec = new FilesUnreadableFaultSpec(0, 900000,
Collections.singleton("myAgent"), mockKibosh.tempDir.getPath(), "/bar", 456);
@ -391,10 +386,10 @@ public class AgentTest { @@ -391,10 +386,10 @@ public class AgentTest {
addTask(new ExpectedTaskBuilder("bar").
workerState(new WorkerRunning("bar", barSpec, 0, new TextNode("Added fault bar"))).build()).
waitFor(client);
Assert.assertEquals(new KiboshControlFile(new ArrayList<Kibosh.KiboshFaultSpec>() {{
add(new KiboshFilesUnreadableFaultSpec("/foo", 123));
add(new KiboshFilesUnreadableFaultSpec("/bar", 456));
}}), mockKibosh.read());
assertEquals(new KiboshControlFile(asList(
new KiboshFilesUnreadableFaultSpec("/foo", 123),
new KiboshFilesUnreadableFaultSpec("/bar", 456))
), mockKibosh.read());
time.sleep(1);
client.stopWorker(new StopWorkerRequest(0));
new ExpectedTasks().
@ -403,7 +398,7 @@ public class AgentTest { @@ -403,7 +398,7 @@ public class AgentTest {
addTask(new ExpectedTaskBuilder("bar").
workerState(new WorkerRunning("bar", barSpec, 0, new TextNode("Added fault bar"))).build()).
waitFor(client);
Assert.assertEquals(new KiboshControlFile(Collections.<Kibosh.KiboshFaultSpec>singletonList(
assertEquals(new KiboshControlFile(Collections.singletonList(
new KiboshFilesUnreadableFaultSpec("/bar", 456))), mockKibosh.read());
}
}

13
tools/src/test/java/org/apache/kafka/trogdor/basic/BasicPlatformTest.java

@ -17,24 +17,23 @@ @@ -17,24 +17,23 @@
package org.apache.kafka.trogdor.basic;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.test.TestUtils;
import org.apache.kafka.trogdor.common.Platform;
import org.junit.Rule;
import org.junit.rules.Timeout;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import org.junit.jupiter.api.Timeout;
import static org.junit.Assert.assertEquals;
@Timeout(value = 120000, unit = MILLISECONDS)
public class BasicPlatformTest {
@Rule
final public Timeout globalTimeout = Timeout.millis(120000);
@Test
public void testCreateBasicPlatform() throws Exception {

8
tools/src/test/java/org/apache/kafka/trogdor/common/JsonSerializationTest.java

@ -17,6 +17,8 @@ @@ -17,6 +17,8 @@
package org.apache.kafka.trogdor.common;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.apache.kafka.trogdor.fault.FilesUnreadableFaultSpec;
import org.apache.kafka.trogdor.fault.Kibosh;
import org.apache.kafka.trogdor.fault.NetworkPartitionFaultSpec;
@ -30,7 +32,6 @@ import org.apache.kafka.trogdor.workload.PartitionsSpec; @@ -30,7 +32,6 @@ import org.apache.kafka.trogdor.workload.PartitionsSpec;
import org.apache.kafka.trogdor.workload.ProduceBenchSpec;
import org.apache.kafka.trogdor.workload.RoundTripWorkloadSpec;
import org.apache.kafka.trogdor.workload.TopicsSpec;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Arrays;
@ -38,8 +39,7 @@ import java.util.HashMap; @@ -38,8 +39,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertNotNull;
import org.junit.jupiter.api.Test;
public class JsonSerializationTest {
@Test
@ -75,7 +75,7 @@ public class JsonSerializationTest { @@ -75,7 +75,7 @@ public class JsonSerializationTest {
for (Field field : clazz.getDeclaredFields()) {
boolean wasAccessible = field.isAccessible();
field.setAccessible(true);
assertNotNull("Field " + field + " was null.", field.get(val2));
assertNotNull(field.get(val2), "Field " + field + " was null.");
field.setAccessible(wasAccessible);
}
}

33
tools/src/test/java/org/apache/kafka/trogdor/common/JsonUtilTest.java

@ -17,28 +17,23 @@ @@ -17,28 +17,23 @@
package org.apache.kafka.trogdor.common;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.kafka.test.TestUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@Timeout(value = 120000, unit = MILLISECONDS)
public class JsonUtilTest {
private static final Logger log = LoggerFactory.getLogger(JsonUtilTest.class);
@Rule
final public Timeout globalTimeout = Timeout.millis(120000);
@Test
public void testOpenBraceComesFirst() {
@ -62,16 +57,12 @@ public class JsonUtilTest { @@ -62,16 +57,12 @@ public class JsonUtilTest {
@Test
public void testObjectFromCommandLineArgument() throws Exception {
assertEquals(123, JsonUtil.<Foo>
objectFromCommandLineArgument("{\"bar\":123}", Foo.class).bar);
assertEquals(1, JsonUtil.<Foo>
objectFromCommandLineArgument(" {\"bar\": 1} ", Foo.class).bar);
assertEquals(123, JsonUtil.objectFromCommandLineArgument("{\"bar\":123}", Foo.class).bar);
assertEquals(1, JsonUtil.objectFromCommandLineArgument(" {\"bar\": 1} ", Foo.class).bar);
File tempFile = TestUtils.tempFile();
try {
Files.write(tempFile.toPath(),
"{\"bar\": 456}".getBytes(StandardCharsets.UTF_8));
assertEquals(456, JsonUtil.<Foo>
objectFromCommandLineArgument(tempFile.getAbsolutePath(), Foo.class).bar);
Files.write(tempFile.toPath(), "{\"bar\": 456}".getBytes(StandardCharsets.UTF_8));
assertEquals(456, JsonUtil.objectFromCommandLineArgument(tempFile.getAbsolutePath(), Foo.class).bar);
} finally {
Files.delete(tempFile.toPath());
}

17
tools/src/test/java/org/apache/kafka/trogdor/common/StringExpanderTest.java

@ -17,29 +17,28 @@ @@ -17,29 +17,28 @@
package org.apache.kafka.trogdor.common;
import org.junit.Rule;
import org.junit.rules.Timeout;
import org.junit.Test;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import org.junit.jupiter.api.Timeout;
import static org.junit.Assert.assertEquals;
@Timeout(value = 120000, unit = MILLISECONDS)
public class StringExpanderTest {
@Rule
final public Timeout globalTimeout = Timeout.millis(120000);
@Test
public void testNoExpansionNeeded() throws Exception {
public void testNoExpansionNeeded() {
assertEquals(Collections.singleton("foo"), StringExpander.expand("foo"));
assertEquals(Collections.singleton("bar"), StringExpander.expand("bar"));
assertEquals(Collections.singleton(""), StringExpander.expand(""));
}
@Test
public void testExpansions() throws Exception {
public void testExpansions() {
HashSet<String> expected1 = new HashSet<>(Arrays.asList(
"foo1",
"foo2",

16
tools/src/test/java/org/apache/kafka/trogdor/common/StringFormatterTest.java

@ -17,30 +17,26 @@ @@ -17,30 +17,26 @@
package org.apache.kafka.trogdor.common;
import org.junit.Rule;
import org.junit.rules.Timeout;
import org.junit.jupiter.api.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.time.ZoneOffset;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.kafka.trogdor.common.StringFormatter.durationString;
import static org.apache.kafka.trogdor.common.StringFormatter.dateString;
import static org.junit.jupiter.api.Assertions.assertEquals;
@Timeout(value = 120000, unit = MILLISECONDS)
public class StringFormatterTest {
private static final Logger log = LoggerFactory.getLogger(StringFormatterTest.class);
@Rule
final public Timeout globalTimeout = Timeout.millis(120000);
@Test
public void testDateString() {
assertEquals("2019-01-08T20:59:29.85Z",
dateString(1546981169850L, ZoneOffset.UTC));
assertEquals("2019-01-08T20:59:29.85Z", dateString(1546981169850L, ZoneOffset.UTC));
}
@Test

21
tools/src/test/java/org/apache/kafka/trogdor/common/TopologyTest.java

@ -17,29 +17,28 @@ @@ -17,29 +17,28 @@
package org.apache.kafka.trogdor.common;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.kafka.trogdor.agent.Agent;
import org.apache.kafka.trogdor.basic.BasicNode;
import org.apache.kafka.trogdor.basic.BasicTopology;
import org.apache.kafka.trogdor.coordinator.Coordinator;
import org.junit.Rule;
import org.junit.rules.Timeout;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeMap;
import org.junit.jupiter.api.Timeout;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@Timeout(value = 120000, unit = MILLISECONDS)
public class TopologyTest {
@Rule
final public Timeout globalTimeout = Timeout.millis(120000);
@Test
public void testAgentNodeNames() throws Exception {
public void testAgentNodeNames() {
TreeMap<String, Node> nodes = new TreeMap<>();
final int numNodes = 5;
for (int i = 0; i < numNodes; i++) {
@ -52,7 +51,7 @@ public class TopologyTest { @@ -52,7 +51,7 @@ public class TopologyTest {
BasicNode node = new BasicNode(String.format("node%02d", i),
String.format("node%d.example.com", i),
conf,
new HashSet<String>());
new HashSet<>());
nodes.put(node.name(), node);
}
Topology topology = new BasicTopology(nodes);
@ -62,4 +61,4 @@ public class TopologyTest { @@ -62,4 +61,4 @@ public class TopologyTest {
assertTrue(names.contains(String.format("node%02d", i)));
}
}
};
}

30
tools/src/test/java/org/apache/kafka/trogdor/common/WorkerUtilsTest.java

@ -17,7 +17,8 @@ @@ -17,7 +17,8 @@
package org.apache.kafka.trogdor.common;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.apache.kafka.clients.admin.MockAdminClient;
import org.apache.kafka.clients.admin.NewTopic;
@ -29,9 +30,8 @@ import org.apache.kafka.common.TopicPartitionInfo; @@ -29,9 +30,8 @@ import org.apache.kafka.common.TopicPartitionInfo;
import org.apache.kafka.common.errors.TopicExistsException;
import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
import org.apache.kafka.common.utils.Utils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -64,8 +64,8 @@ public class WorkerUtilsTest { @@ -64,8 +64,8 @@ public class WorkerUtilsTest {
private MockAdminClient adminClient;
@Before
public void setUp() throws Exception {
@BeforeEach
public void setUp() {
adminClient = new MockAdminClient(cluster, broker1);
}
@ -108,7 +108,7 @@ public class WorkerUtilsTest { @@ -108,7 +108,7 @@ public class WorkerUtilsTest {
assertEquals(0, adminClient.listTopics().names().get().size());
}
@Test(expected = TopicExistsException.class)
@Test
public void testCreateTopicsFailsIfAtLeastOneTopicExists() throws Throwable {
adminClient.addTopic(
false,
@ -123,10 +123,10 @@ public class WorkerUtilsTest { @@ -123,10 +123,10 @@ public class WorkerUtilsTest {
newTopics.put("one-more-topic",
new NewTopic("one-more-topic", TEST_PARTITIONS, TEST_REPLICATION_FACTOR));
WorkerUtils.createTopics(log, adminClient, newTopics, true);
assertThrows(TopicExistsException.class, () -> WorkerUtils.createTopics(log, adminClient, newTopics, true));
}
@Test(expected = RuntimeException.class)
@Test
public void testExistingTopicsMustHaveRequestedNumberOfPartitions() throws Throwable {
List<TopicPartitionInfo> tpInfo = new ArrayList<>();
tpInfo.add(new TopicPartitionInfo(0, broker1, singleReplica, Collections.<Node>emptyList()));
@ -137,8 +137,8 @@ public class WorkerUtilsTest { @@ -137,8 +137,8 @@ public class WorkerUtilsTest {
tpInfo,
null);
WorkerUtils.createTopics(
log, adminClient, Collections.singletonMap(TEST_TOPIC, NEW_TEST_TOPIC), false);
assertThrows(RuntimeException.class, () -> WorkerUtils.createTopics(
log, adminClient, Collections.singletonMap(TEST_TOPIC, NEW_TEST_TOPIC), false));
}
@Test
@ -325,12 +325,8 @@ public class WorkerUtilsTest { @@ -325,12 +325,8 @@ public class WorkerUtilsTest {
WorkerUtils.verifyTopics(log, adminClient, Collections.singleton(TEST_TOPIC),
Collections.singletonMap(TEST_TOPIC, NEW_TEST_TOPIC), 3, 1);
adminClient.setFetchesRemainingUntilVisible(TEST_TOPIC, 100);
try {
assertThrows(UnknownTopicOrPartitionException.class, () ->
WorkerUtils.verifyTopics(log, adminClient, Collections.singleton(TEST_TOPIC),
Collections.singletonMap(TEST_TOPIC, NEW_TEST_TOPIC), 2, 1);
Assert.fail("expected to get UnknownTopicOrPartitionException");
} catch (UnknownTopicOrPartitionException e) {
// expected
}
Collections.singletonMap(TEST_TOPIC, NEW_TEST_TOPIC), 2, 1));
}
}

15
tools/src/test/java/org/apache/kafka/trogdor/coordinator/CoordinatorClientTest.java

@ -23,21 +23,16 @@ import org.apache.kafka.trogdor.rest.TaskPending; @@ -23,21 +23,16 @@ import org.apache.kafka.trogdor.rest.TaskPending;
import org.apache.kafka.trogdor.rest.TaskRunning;
import org.apache.kafka.trogdor.rest.TaskStopping;
import org.apache.kafka.trogdor.task.NoOpTaskSpec;
import org.junit.Rule;
import org.junit.rules.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.Test;
import java.time.ZoneOffset;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import static org.junit.Assert.assertEquals;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
@Timeout(value = 120000, unit = MILLISECONDS)
public class CoordinatorClientTest {
private static final Logger log = LoggerFactory.getLogger(CoordinatorTest.class);
@Rule
final public Timeout globalTimeout = Timeout.millis(120000);
@Test
public void testPrettyPrintTaskInfo() {

40
tools/src/test/java/org/apache/kafka/trogdor/coordinator/CoordinatorTest.java

@ -49,9 +49,9 @@ import org.apache.kafka.trogdor.rest.WorkerDone; @@ -49,9 +49,9 @@ import org.apache.kafka.trogdor.rest.WorkerDone;
import org.apache.kafka.trogdor.rest.WorkerRunning;
import org.apache.kafka.trogdor.task.NoOpTaskSpec;
import org.apache.kafka.trogdor.task.SampleTaskSpec;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -62,17 +62,18 @@ import java.util.HashMap; @@ -62,17 +62,18 @@ import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Tag("integration")
@Timeout(value = 120000, unit = MILLISECONDS)
public class CoordinatorTest {
private static final Logger log = LoggerFactory.getLogger(CoordinatorTest.class);
@Rule
final public Timeout globalTimeout = Timeout.millis(120000);
private static final Logger log = LoggerFactory.getLogger(CoordinatorTest.class);
@Test
public void testCoordinatorStatus() throws Exception {
@ -125,14 +126,10 @@ public class CoordinatorTest { @@ -125,14 +126,10 @@ public class CoordinatorTest {
new CreateTaskRequest("foo", fooSpec));
// Re-creating a task with different arguments gives a RequestConflictException.
try {
NoOpTaskSpec barSpec = new NoOpTaskSpec(1000, 2000);
cluster.coordinatorClient().createTask(
new CreateTaskRequest("foo", barSpec));
fail("Expected to get an exception when re-creating a task with a " +
"different task spec.");
} catch (RequestConflictException exception) {
}
NoOpTaskSpec barSpec = new NoOpTaskSpec(1000, 2000);
assertThrows(RequestConflictException.class, () -> cluster.coordinatorClient().createTask(
new CreateTaskRequest("foo", barSpec)),
"Recreating task with different task spec is not allowed");
time.sleep(2);
new ExpectedTasks().
@ -647,10 +644,7 @@ public class CoordinatorTest { @@ -647,10 +644,7 @@ public class CoordinatorTest {
waitFor(coordinatorClient).
waitFor(cluster.agentClient("node02"));
try {
coordinatorClient.task(new TaskRequest("non-existent-foo"));
fail("Non existent task request should have raised a NotFoundException");
} catch (NotFoundException ignored) { }
assertThrows(NotFoundException.class, () -> coordinatorClient.task(new TaskRequest("non-existent-foo")));
}
}

32
tools/src/test/java/org/apache/kafka/trogdor/rest/RestExceptionMapperTest.java

@ -16,7 +16,8 @@ @@ -16,7 +16,8 @@
*/
package org.apache.kafka.trogdor.rest;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JavaType;
@ -27,7 +28,7 @@ import javax.ws.rs.core.Response; @@ -27,7 +28,7 @@ import javax.ws.rs.core.Response;
import org.apache.kafka.common.errors.InvalidRequestException;
import org.apache.kafka.common.errors.SerializationException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class RestExceptionMapperTest {
@ -83,23 +84,26 @@ public class RestExceptionMapperTest { @@ -83,23 +84,26 @@ public class RestExceptionMapperTest {
assertEquals(resp.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
@Test(expected = NotFoundException.class)
public void testToExceptionNotFoundException() throws Exception {
RestExceptionMapper.toException(Response.Status.NOT_FOUND.getStatusCode(), "Not Found");
@Test
public void testToExceptionNotFoundException() {
assertThrows(NotFoundException.class,
() -> RestExceptionMapper.toException(Response.Status.NOT_FOUND.getStatusCode(), "Not Found"));
}
@Test(expected = ClassNotFoundException.class)
public void testToExceptionClassNotFoundException() throws Exception {
RestExceptionMapper.toException(Response.Status.NOT_IMPLEMENTED.getStatusCode(), "Not Implemented");
@Test
public void testToExceptionClassNotFoundException() {
assertThrows(ClassNotFoundException.class,
() -> RestExceptionMapper.toException(Response.Status.NOT_IMPLEMENTED.getStatusCode(), "Not Implemented"));
}
@Test(expected = InvalidRequestException.class)
public void testToExceptionSerializationException() throws Exception {
RestExceptionMapper.toException(Response.Status.BAD_REQUEST.getStatusCode(), "Bad Request");
@Test
public void testToExceptionSerializationException() {
assertThrows(InvalidRequestException.class,
() -> RestExceptionMapper.toException(Response.Status.BAD_REQUEST.getStatusCode(), "Bad Request"));
}
@Test(expected = RuntimeException.class)
public void testToExceptionRuntimeException() throws Exception {
RestExceptionMapper.toException(-1, "Unkown status code");
@Test
public void testToExceptionRuntimeException() {
assertThrows(RuntimeException.class, () -> RestExceptionMapper.toException(-1, "Unkown status code"));
}
}

20
tools/src/test/java/org/apache/kafka/trogdor/task/TaskSpecTest.java

@ -19,26 +19,22 @@ package org.apache.kafka.trogdor.task; @@ -19,26 +19,22 @@ package org.apache.kafka.trogdor.task;
import com.fasterxml.jackson.databind.exc.InvalidTypeIdException;
import org.apache.kafka.trogdor.common.JsonUtil;
import org.junit.Rule;
import org.junit.rules.Timeout;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@Timeout(value = 120000, unit = MILLISECONDS)
public class TaskSpecTest {
@Rule
final public Timeout globalTimeout = Timeout.millis(120000);
@Test
public void testTaskSpecSerialization() throws Exception {
try {
assertThrows(InvalidTypeIdException.class, () ->
JsonUtil.JSON_SERDE.readValue(
"{\"startMs\":123,\"durationMs\":456,\"exitMs\":1000,\"error\":\"foo\"}",
SampleTaskSpec.class);
fail("Expected InvalidTypeIdException because type id is missing.");
} catch (InvalidTypeIdException e) {
}
SampleTaskSpec.class), "Missing type id should cause exception to be thrown");
String inputJson = "{\"class\":\"org.apache.kafka.trogdor.task.SampleTaskSpec\"," +
"\"startMs\":123,\"durationMs\":456,\"nodeToExitMs\":{\"node01\":1000},\"error\":\"foo\"}";
SampleTaskSpec spec = JsonUtil.JSON_SERDE.readValue(inputJson, SampleTaskSpec.class);

14
tools/src/test/java/org/apache/kafka/trogdor/workload/ConsumeBenchSpecTest.java

@ -17,8 +17,11 @@ @@ -17,8 +17,11 @@
package org.apache.kafka.trogdor.workload;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.apache.kafka.common.TopicPartition;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.ArrayList;
@ -29,9 +32,6 @@ import java.util.HashMap; @@ -29,9 +32,6 @@ import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class ConsumeBenchSpecTest {
@Test
@ -62,12 +62,8 @@ public class ConsumeBenchSpecTest { @@ -62,12 +62,8 @@ public class ConsumeBenchSpecTest {
@Test
public void testInvalidTopicNameRaisesExceptionInMaterialize() {
for (String invalidName : Arrays.asList("In:valid", "invalid:", ":invalid", "in:valid:1", "invalid:2:2", "invalid::1", "invalid[1-3]:")) {
try {
consumeBenchSpec(Collections.singletonList(invalidName)).materializeTopics();
fail(String.format("Invalid topic name (%s) should have raised an exception.", invalidName));
} catch (IllegalArgumentException ignored) { }
assertThrows(IllegalArgumentException.class, () -> consumeBenchSpec(Collections.singletonList(invalidName)).materializeTopics());
}
}
private ConsumeBenchSpec consumeBenchSpec(List<String> activeTopics) {

13
tools/src/test/java/org/apache/kafka/trogdor/workload/ExternalCommandWorkerTest.java

@ -26,9 +26,6 @@ import org.apache.kafka.common.utils.OperatingSystem; @@ -26,9 +26,6 @@ import org.apache.kafka.common.utils.OperatingSystem;
import org.apache.kafka.test.TestUtils;
import org.apache.kafka.trogdor.task.AgentWorkerStatusTracker;
import org.apache.kafka.trogdor.task.WorkerStatusTracker;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import java.io.File;
import java.io.OutputStream;
@ -37,13 +34,15 @@ import java.nio.file.Files; @@ -37,13 +34,15 @@ import java.nio.file.Files;
import java.util.Arrays;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Timeout(value = 120000, unit = MILLISECONDS)
public class ExternalCommandWorkerTest {
@Rule
final public Timeout globalTimeout = Timeout.millis(120000);
static class ExternalCommandWorkerBuilder {
private final String id;

39
tools/src/test/java/org/apache/kafka/trogdor/workload/HistogramTest.java

@ -17,8 +17,9 @@ @@ -17,8 +17,9 @@
package org.apache.kafka.trogdor.workload;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class HistogramTest {
private static Histogram createHistogram(int maxValue, int... values) {
@ -32,23 +33,23 @@ public class HistogramTest { @@ -32,23 +33,23 @@ public class HistogramTest {
@Test
public void testHistogramAverage() {
Histogram empty = createHistogram(1);
Assert.assertEquals(0, (int) empty.summarize(new float[0]).average());
assertEquals(0, (int) empty.summarize(new float[0]).average());
Histogram histogram = createHistogram(70, 1, 2, 3, 4, 5, 6, 1);
Assert.assertEquals(3, (int) histogram.summarize(new float[0]).average());
assertEquals(3, (int) histogram.summarize(new float[0]).average());
histogram.add(60);
Assert.assertEquals(10, (int) histogram.summarize(new float[0]).average());
assertEquals(10, (int) histogram.summarize(new float[0]).average());
}
@Test
public void testHistogramSamples() {
Histogram empty = createHistogram(100);
Assert.assertEquals(0, empty.summarize(new float[0]).numSamples());
assertEquals(0, empty.summarize(new float[0]).numSamples());
Histogram histogram = createHistogram(100, 4, 8, 2, 4, 1, 100, 150);
Assert.assertEquals(7, histogram.summarize(new float[0]).numSamples());
assertEquals(7, histogram.summarize(new float[0]).numSamples());
histogram.add(60);
Assert.assertEquals(8, histogram.summarize(new float[0]).numSamples());
assertEquals(8, histogram.summarize(new float[0]).numSamples());
}
@Test
@ -56,30 +57,30 @@ public class HistogramTest { @@ -56,30 +57,30 @@ public class HistogramTest {
Histogram histogram = createHistogram(100, 1, 2, 3, 4, 5, 6, 80, 90);
float[] percentiles = new float[] {0.5f, 0.90f, 0.99f, 1f};
Histogram.Summary summary = histogram.summarize(percentiles);
Assert.assertEquals(8, summary.numSamples());
Assert.assertEquals(4, summary.percentiles().get(0).value());
Assert.assertEquals(80, summary.percentiles().get(1).value());
Assert.assertEquals(80, summary.percentiles().get(2).value());
Assert.assertEquals(90, summary.percentiles().get(3).value());
assertEquals(8, summary.numSamples());
assertEquals(4, summary.percentiles().get(0).value());
assertEquals(80, summary.percentiles().get(1).value());
assertEquals(80, summary.percentiles().get(2).value());
assertEquals(90, summary.percentiles().get(3).value());
histogram.add(30);
histogram.add(30);
histogram.add(30);
summary = histogram.summarize(new float[] {0.5f});
Assert.assertEquals(11, summary.numSamples());
Assert.assertEquals(5, summary.percentiles().get(0).value());
assertEquals(11, summary.numSamples());
assertEquals(5, summary.percentiles().get(0).value());
Histogram empty = createHistogram(100);
summary = empty.summarize(new float[] {0.5f});
Assert.assertEquals(0, summary.percentiles().get(0).value());
assertEquals(0, summary.percentiles().get(0).value());
histogram = createHistogram(1000);
histogram.add(100);
histogram.add(200);
summary = histogram.summarize(new float[] {0f, 0.5f, 1.0f});
Assert.assertEquals(0, summary.percentiles().get(0).value());
Assert.assertEquals(100, summary.percentiles().get(1).value());
Assert.assertEquals(200, summary.percentiles().get(2).value());
assertEquals(0, summary.percentiles().get(0).value());
assertEquals(100, summary.percentiles().get(1).value());
assertEquals(200, summary.percentiles().get(2).value());
}
};

41
tools/src/test/java/org/apache/kafka/trogdor/workload/PayloadGeneratorTest.java

@ -17,24 +17,22 @@ @@ -17,24 +17,22 @@
package org.apache.kafka.trogdor.workload;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
@Timeout(value = 120000, unit = MILLISECONDS)
public class PayloadGeneratorTest {
@Rule
final public Timeout globalTimeout = Timeout.millis(120000);
@Test
public void testConstantPayloadGenerator() {
@ -206,16 +204,13 @@ public class PayloadGeneratorTest { @@ -206,16 +204,13 @@ public class PayloadGeneratorTest {
List<RandomComponent> components2 = new ArrayList<>(Arrays.asList(
nullConfig, constantConfig, uniformConfig, nullConfig, uniformConfig, uniformConfig));
assertThrows(IllegalArgumentException.class, () -> {
new PayloadIterator(new RandomComponentPayloadGenerator(1, new ArrayList<>()));
});
assertThrows(IllegalArgumentException.class, () -> {
new PayloadIterator(new RandomComponentPayloadGenerator(13, components2));
});
assertThrows(IllegalArgumentException.class, () -> {
new PayloadIterator(new RandomComponentPayloadGenerator(123, components1));
});
}
assertThrows(IllegalArgumentException.class, () ->
new PayloadIterator(new RandomComponentPayloadGenerator(1, new ArrayList<>())));
assertThrows(IllegalArgumentException.class, () ->
new PayloadIterator(new RandomComponentPayloadGenerator(13, components2)));
assertThrows(IllegalArgumentException.class, () ->
new PayloadIterator(new RandomComponentPayloadGenerator(123, components1)));
}
@Test
public void testPayloadIterator() {
@ -236,8 +231,8 @@ public class PayloadGeneratorTest { @@ -236,8 +231,8 @@ public class PayloadGeneratorTest {
@Test
public void testNullPayloadGenerator() {
NullPayloadGenerator generator = new NullPayloadGenerator();
assertEquals(null, generator.generate(0));
assertEquals(null, generator.generate(1));
assertEquals(null, generator.generate(100));
assertNull(generator.generate(0));
assertNull(generator.generate(1));
assertNull(generator.generate(100));
}
}

35
tools/src/test/java/org/apache/kafka/trogdor/workload/ThrottleTest.java

@ -17,10 +17,13 @@ @@ -17,10 +17,13 @@
package org.apache.kafka.trogdor.workload;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.kafka.common.utils.MockTime;
import org.apache.kafka.common.utils.Time;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class ThrottleTest {
/**
@ -50,21 +53,21 @@ public class ThrottleTest { @@ -50,21 +53,21 @@ public class ThrottleTest {
public void testThrottle() throws Exception {
MockTime time = new MockTime(0, 0, 0);
ThrottleMock throttle = new ThrottleMock(time, 3);
Assert.assertFalse(throttle.increment());
Assert.assertEquals(0, time.milliseconds());
Assert.assertFalse(throttle.increment());
Assert.assertEquals(0, time.milliseconds());
Assert.assertFalse(throttle.increment());
Assert.assertEquals(0, time.milliseconds());
Assert.assertTrue(throttle.increment());
Assert.assertEquals(100, time.milliseconds());
assertFalse(throttle.increment());
assertEquals(0, time.milliseconds());
assertFalse(throttle.increment());
assertEquals(0, time.milliseconds());
assertFalse(throttle.increment());
assertEquals(0, time.milliseconds());
assertTrue(throttle.increment());
assertEquals(100, time.milliseconds());
time.sleep(50);
Assert.assertFalse(throttle.increment());
Assert.assertEquals(150, time.milliseconds());
Assert.assertFalse(throttle.increment());
Assert.assertEquals(150, time.milliseconds());
Assert.assertTrue(throttle.increment());
Assert.assertEquals(200, time.milliseconds());
assertFalse(throttle.increment());
assertEquals(150, time.milliseconds());
assertFalse(throttle.increment());
assertEquals(150, time.milliseconds());
assertTrue(throttle.increment());
assertEquals(200, time.milliseconds());
}
};

6
tools/src/test/java/org/apache/kafka/trogdor/workload/TimeIntervalTransactionsGeneratorTest.java

@ -17,10 +17,10 @@ @@ -17,10 +17,10 @@
package org.apache.kafka.trogdor.workload;
import org.apache.kafka.common.utils.MockTime;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertEquals;
import org.apache.kafka.common.utils.MockTime;
import org.junit.jupiter.api.Test;
public class TimeIntervalTransactionsGeneratorTest {
@Test

14
tools/src/test/java/org/apache/kafka/trogdor/workload/TopicsSpecTest.java

@ -17,9 +17,9 @@ @@ -17,9 +17,9 @@
package org.apache.kafka.trogdor.workload;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.HashMap;
@ -27,13 +27,11 @@ import java.util.List; @@ -27,13 +27,11 @@ import java.util.List;
import java.util.Map;
import org.apache.kafka.trogdor.common.JsonUtil;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@Timeout(value = 120000, unit = MILLISECONDS)
public class TopicsSpecTest {
@Rule
final public Timeout globalTimeout = Timeout.millis(120000);
private final static TopicsSpec FOO;
private final static PartitionsSpec PARTSA;

Loading…
Cancel
Save