+ testkit Add java.time.Duration to testkit's javadsl

This commit is contained in:
虎鸣 2018-03-20 12:48:53 +08:00
parent 3685ce619e
commit e45a638ce0
9 changed files with 311 additions and 22 deletions

View file

@ -33,5 +33,13 @@ object Timeout {
*/
def apply(length: Long, unit: TimeUnit): Timeout = new Timeout(length, unit)
/**
* Create a Timeout from java.time.Duration.
*/
def create(duration: java.time.Duration): Timeout = {
import JavaDurationConverters._
new Timeout(duration.asScala)
}
implicit def durationToTimeout(duration: FiniteDuration): Timeout = new Timeout(duration)
}

View file

@ -741,7 +741,7 @@ public class ActorDocTest extends AbstractJavaTest {
{
watch(b);
system.stop(a);
assertEquals(expectMsgClass(Duration.create(2, TimeUnit.SECONDS), Terminated.class).actor(), b);
assertEquals(expectMsgClass(java.time.Duration.ofSeconds(2), Terminated.class).actor(), b);
}
};
}

View file

@ -16,10 +16,10 @@ import akka.util.Timeout;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import scala.concurrent.duration.Duration;
import scala.concurrent.duration.FiniteDuration;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
@ -147,12 +147,12 @@ public class RecipeGlobalRateLimit extends RecipeTest {
public void work() throws Exception {
new TestKit(system) {
//#global-limiter-flow
public <T> Flow<T, T, NotUsed> limitGlobal(ActorRef limiter, FiniteDuration maxAllowedWait) {
public <T> Flow<T, T, NotUsed> limitGlobal(ActorRef limiter, Duration maxAllowedWait) {
final int parallelism = 4;
final Flow<T, T, NotUsed> f = Flow.create();
return f.mapAsync(parallelism, element -> {
final Timeout triggerTimeout = new Timeout(maxAllowedWait);
final Timeout triggerTimeout = Timeout.create(maxAllowedWait);
final CompletionStage<Object> limiterTriggerFuture =
PatternsCS.ask(limiter, Limiter.WANT_TO_PASS, triggerTimeout);
return limiterTriggerFuture.thenApplyAsync(response -> element, system.dispatcher());
@ -187,7 +187,7 @@ public class RecipeGlobalRateLimit extends RecipeTest {
}
};
final FiniteDuration twoSeconds = (FiniteDuration) dilated(Duration.create(2, TimeUnit.SECONDS));
final java.time.Duration twoSeconds = dilated(java.time.Duration.ofSeconds(2));
final Sink<String, TestSubscriber.Probe<String>> sink = TestSink.probe(system);
final TestSubscriber.Probe<String> probe =

View file

@ -129,7 +129,7 @@ public class TestKitDocTest extends AbstractJavaTest {
//#test-within
new TestKit(system) {{
getRef().tell(42, ActorRef.noSender());
within(Duration.Zero(), Duration.create(1, "second"), () -> {
within(java.time.Duration.ZERO, java.time.Duration.ofSeconds(1), () -> {
assertEquals((Integer) 42, expectMsgClass(Integer.class));
return null;
});
@ -190,7 +190,7 @@ public class TestKitDocTest extends AbstractJavaTest {
//#test-awaitCond
new TestKit(system) {{
getRef().tell(42, ActorRef.noSender());
awaitCond(duration("1 second"), duration("100 millis"), this::msgAvailable);
awaitCond(java.time.Duration.ofSeconds(1), java.time.Duration.ofMillis(100), this::msgAvailable);
}};
//#test-awaitCond
}
@ -260,9 +260,9 @@ public class TestKitDocTest extends AbstractJavaTest {
public void demonstrateDilated() {
//#duration-dilation
new TestKit(system) {{
final FiniteDuration original = duration("1 second");
final Duration stretched = dilated(original);
assertTrue("dilated", stretched.gteq(original));
final java.time.Duration original = java.time.Duration.ofSeconds(1);
final java.time.Duration stretched = dilated(original);
assertTrue("dilated", stretched.compareTo(original) >= 0);
}};
//#duration-dilation
}
@ -399,7 +399,7 @@ public class TestKitDocTest extends AbstractJavaTest {
//#test-within-probe
new TestKit(system) {{
final TestKit probe = new TestKit(system);
within(duration("1 second"), () -> probe.expectMsgEquals("hello"));
within(java.time.Duration.ofSeconds(1), () -> probe.expectMsgEquals("hello"));
}};
//#test-within-probe
} catch (AssertionError e) {

View file

@ -67,10 +67,10 @@ public class TestKitSampleTest extends AbstractJavaTest {
// like a real resource would be passed in production
subject.tell(probe.getRef(), getRef());
// await the correct response
expectMsg(duration("1 second"), "done");
expectMsg(java.time.Duration.ofSeconds(1), "done");
// the run() method needs to finish within 3 seconds
within(duration("3 seconds"), () -> {
within(java.time.Duration.ofSeconds(3), () -> {
subject.tell("hello", getRef());
// This is a demo: would normally use expectMsgEquals().
@ -78,9 +78,9 @@ public class TestKitSampleTest extends AbstractJavaTest {
awaitCond(probe::msgAvailable);
// response must have been enqueued to us before probe
expectMsg(Duration.Zero(), "world");
expectMsg(java.time.Duration.ZERO, "world");
// check that the probe we injected earlier got the msg
probe.expectMsg(Duration.Zero(), "hello");
probe.expectMsg(java.time.Duration.ZERO, "hello");
Assert.assertEquals(getRef(), probe.getLastSender());
// Will wait for the rest of the 3 seconds

View file

@ -203,7 +203,7 @@ public class DeviceGroupQueryTest extends JUnitSuite {
queryActor.tell(new Device.RespondTemperature(0L, Optional.of(1.0)), device1.getRef());
DeviceGroup.RespondAllTemperatures response = requester.expectMsgClass(
FiniteDuration.create(5, TimeUnit.SECONDS),
java.time.Duration.ofSeconds(5),
DeviceGroup.RespondAllTemperatures.class);
assertEquals(1L, response.requestId);

View file

@ -194,7 +194,7 @@ public class DeviceGroupQueryTest extends JUnitSuite {
queryActor.tell(new Device.RespondTemperature(0L, Optional.of(1.0)), device1.getRef());
DeviceGroup.RespondAllTemperatures response = requester.expectMsgClass(
FiniteDuration.create(5, TimeUnit.SECONDS),
java.time.Duration.ofSeconds(5),
DeviceGroup.RespondAllTemperatures.class);
assertEquals(1L, response.requestId);

View file

@ -29,8 +29,8 @@ class EventFilter(clazz: Class[_], system: ActorSystem) {
else
null
private var source: String = null
private var message: String = null
private var source: String = _
private var message: String = _
private var pattern: Boolean = false
private var complete: Boolean = false
private var occurrences: Int = Integer.MAX_VALUE

View file

@ -4,11 +4,12 @@
package akka.testkit.javadsl
import java.util.function.{ Function JFunction, Supplier }
import java.util.function.{ Supplier, Function JFunction }
import java.util.{ List JList }
import akka.actor._
import akka.testkit.{ TestActor, TestDuration, TestProbe }
import akka.util.JavaDurationConverters._
import scala.annotation.varargs
import scala.collection.JavaConverters._
@ -66,8 +67,15 @@ class TestKit(system: ActorSystem) {
/**
* Scale timeouts (durations) during tests with the configured
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def dilated(d: FiniteDuration): FiniteDuration = d.dilated(getSystem)
/**
* Java timeouts (durations) during tests with the configured
*/
def dilated(duration: java.time.Duration): java.time.Duration = dilated(duration.asScala).asJava
/**
* Query queue status.
*/
@ -133,21 +141,47 @@ class TestKit(system: ActorSystem) {
* block or throw an [[AssertionError]] if no `within` block surrounds this
* call.
*/
@Deprecated
@deprecated("Use getRemaining which returns java.time.Duration instead.", since = "2.5.12")
def remaining: FiniteDuration = tp.remaining
/**
* Obtain time remaining for execution of the innermost enclosing `within`
* block or throw an [[AssertionError]] if no `within` block surrounds this
* call.
*/
def getRemaining: java.time.Duration = remaining.asJava
/**
* Obtain time remaining for execution of the innermost enclosing `within`
* block or missing that it returns the given duration.
*/
@Deprecated
@deprecated("Use getRemainingOr which returns java.time.Duration instead.", since = "2.5.12")
def remainingOr(fd: FiniteDuration): FiniteDuration = tp.remainingOr(fd)
/**
* Obtain time remaining for execution of the innermost enclosing `within`
* block or missing that it returns the given duration.
*/
def getRemainingOr(duration: java.time.Duration): java.time.Duration = remainingOr(duration.asScala).asJava
/**
* Obtain time remaining for execution of the innermost enclosing `within`
* block or missing that it returns the properly dilated default for this
* case from settings (key "akka.test.single-expect-default").
*/
@Deprecated
@deprecated("Use getRemainingOrDefault which returns java.time.Duration instead.", since = "2.5.12")
def remainingOrDefault: FiniteDuration = tp.remainingOrDefault
/**
* Obtain time remaining for execution of the innermost enclosing `within`
* block or missing that it returns the properly dilated default for this
* case from settings (key "akka.test.single-expect-default").
*/
def getRemainingOrDefault: java.time.Duration = remainingOrDefault.asJava
/**
* Execute code block while bounding its execution time between `min` and
* `max`. `within` blocks may be nested. All methods in this trait which
@ -166,17 +200,123 @@ class TestKit(system: ActorSystem) {
*
* }}}
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def within[T](min: FiniteDuration, max: FiniteDuration, f: Supplier[T]): T = tp.within(min, max)(f.get)
/**
* Same as calling `within(0 seconds, max, f)`.
* Execute code block while bounding its execution time between `min` and
* `max`. `within` blocks may be nested. All methods in this trait which
* take maximum wait times are available in a version which implicitly uses
* the remaining time governed by the innermost enclosing `within` block.
*
* Note that the timeout is scaled using Duration.dilated, which uses the
* configuration entry "akka.test.timefactor", while the min Duration is not.
*
* {{{
*
* within(java.time.Duration.ofMillis(50), () -> {
* test.tell("ping");
* return expectMsgClass(String.class);
* });
*
* }}}
*/
def within[T](min: java.time.Duration, max: java.time.Duration, f: Supplier[T]): T =
within(min.asScala, max.asScala, f)
/**
* Execute code block while bounding its execution time between `min` and
* `max`. `within` blocks may be nested. All methods in this trait which
* take maximum wait times are available in a version which implicitly uses
* the remaining time governed by the innermost enclosing `within` block.
*
* Note that the timeout is scaled using Duration.dilated, which uses the
* configuration entry "akka.test.timefactor", while the min Duration is not.
*
* {{{
*
* within(duration("50 millis"), () -> {
* test.tell("ping");
* return expectMsgClass(String.class);
* });
*
* }}}
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def within[T](max: FiniteDuration, f: Supplier[T]): T = tp.within(max)(f.get)
/**
* Execute code block while bounding its execution time between `min` and
* `max`. `within` blocks may be nested. All methods in this trait which
* take maximum wait times are available in a version which implicitly uses
* the remaining time governed by the innermost enclosing `within` block.
*
* Note that the timeout is scaled using Duration.dilated, which uses the
* configuration entry "akka.test.timefactor", while the min Duration is not.
*
* {{{
*
* within(java.time.Duration.ofMillis(50), () -> {
* test.tell("ping");
* return expectMsgClass(String.class);
* });
*
* }}}
*/
def within[T](max: java.time.Duration, f: Supplier[T]): T = within(max.asScala, f)
/**
* Await until the given condition evaluates to `true` or the timeout
* expires, whichever comes first.
*
* If no timeout is given, take it from the innermost enclosing `within`
* block.
*
* Note that the timeout is scaled using Duration.dilated,
* which uses the configuration entry "akka.test.timefactor".
*/
def awaitCond(p: Supplier[Boolean]): Unit = tp.awaitCond(p.get)
/**
* Await until the given condition evaluates to `true` or the timeout
* expires, whichever comes first.
*
* If no timeout is given, take it from the innermost enclosing `within`
* block.
*
* Note that the timeout is scaled using Duration.dilated,
* which uses the configuration entry "akka.test.timefactor".
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def awaitCond(max: Duration, p: Supplier[Boolean]): Unit = tp.awaitCond(p.get, max)
/**
* Await until the given condition evaluates to `true` or the timeout
* expires, whichever comes first.
*
* If no timeout is given, take it from the innermost enclosing `within`
* block.
*
* Note that the timeout is scaled using Duration.dilated,
* which uses the configuration entry "akka.test.timefactor".
*/
def awaitCond(max: java.time.Duration, p: Supplier[Boolean]): Unit = awaitCond(max.asScala, p)
/**
* Await until the given condition evaluates to `true` or the timeout
* expires, whichever comes first.
*
* If no timeout is given, take it from the innermost enclosing `within`
* block.
*
* Note that the timeout is scaled using Duration.dilated,
* which uses the configuration entry "akka.test.timefactor".
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def awaitCond(max: Duration, interval: Duration, p: Supplier[Boolean]): Unit =
tp.awaitCond(p.get, max, interval)
@ -184,14 +324,71 @@ class TestKit(system: ActorSystem) {
* Await until the given condition evaluates to `true` or the timeout
* expires, whichever comes first.
*
* If no timeout is given, take it from the innermost enclosing `within`
* block.
*
* Note that the timeout is scaled using Duration.dilated,
* which uses the configuration entry "akka.test.timefactor".
*/
def awaitCond(max: java.time.Duration, interval: java.time.Duration, p: Supplier[Boolean]): Unit =
awaitCond(max.asScala, interval.asScala, p)
/**
* Await until the given condition evaluates to `true` or the timeout
* expires, whichever comes first.
*
* If no timeout is given, take it from the innermost enclosing `within`
* block.
*
* Note that the timeout is scaled using Duration.dilated,
* which uses the configuration entry "akka.test.timefactor".
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def awaitCond(max: Duration, interval: Duration, message: String, p: Supplier[Boolean]): Unit =
tp.awaitCond(p.get, max, interval, message)
/**
* Await until the given condition evaluates to `true` or the timeout
* expires, whichever comes first.
*
* If no timeout is given, take it from the innermost enclosing `within`
* block.
*
* Note that the timeout is scaled using Duration.dilated,
* which uses the configuration entry "akka.test.timefactor".
*/
def awaitCond(max: java.time.Duration, interval: java.time.Duration, message: String, p: Supplier[Boolean]): Unit =
awaitCond(max.asScala, interval.asScala, message, p)
/**
* Evaluate the given assert every `interval` until it does not throw an exception and return the
* result.
*
* If the `max` timeout expires the last exception is thrown.
*
* If no timeout is given, take it from the innermost enclosing `within`
* block.
*
* Note that the timeout is scaled using Duration.dilated,
* which uses the configuration entry "akka.test.timefactor".
*/
def awaitAssert[A](a: Supplier[A]): A = tp.awaitAssert(a.get)
/**
* Evaluate the given assert every `interval` until it does not throw an exception and return the
* result.
*
* If the `max` timeout expires the last exception is thrown.
*
* If no timeout is given, take it from the innermost enclosing `within`
* block.
*
* Note that the timeout is scaled using Duration.dilated,
* which uses the configuration entry "akka.test.timefactor".
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def awaitAssert[A](max: Duration, a: Supplier[A]): A = tp.awaitAssert(a.get, max)
/**
@ -217,8 +414,19 @@ class TestKit(system: ActorSystem) {
*
* @return the received object
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def expectMsgEquals[T](max: FiniteDuration, obj: T): T = tp.expectMsg(max, obj)
/**
* Receive one message from the test actor and assert that it equals the given
* object. Wait time is bounded by the given duration, with an
* AssertionFailure being thrown in case of timeout.
*
* @return the received object
*/
def expectMsgEquals[T](max: java.time.Duration, obj: T): T = expectMsgEquals(max.asScala, obj)
/**
* Same as `expectMsg(remainingOrDefault, obj)`, but correctly treating the timeFactor.
*/
@ -229,6 +437,8 @@ class TestKit(system: ActorSystem) {
* given object. Wait time is bounded by the given duration, with an
* AssertionFailure being thrown in case of timeout.
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def expectMsg[T](max: FiniteDuration, obj: T): T = tp.expectMsg(max, obj)
/**
@ -236,8 +446,24 @@ class TestKit(system: ActorSystem) {
* given object. Wait time is bounded by the given duration, with an
* AssertionFailure being thrown in case of timeout.
*/
def expectMsg[T](max: java.time.Duration, obj: T): T = expectMsg(max.asScala, obj)
/**
* Receive one message from the test actor and assert that it equals the
* given object. Wait time is bounded by the given duration, with an
* AssertionFailure being thrown in case of timeout.
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def expectMsg[T](max: FiniteDuration, obj: T, hint: String): T = tp.expectMsg(max, hint, obj)
/**
* Receive one message from the test actor and assert that it equals the
* given object. Wait time is bounded by the given duration, with an
* AssertionFailure being thrown in case of timeout.
*/
def expectMsg[T](max: java.time.Duration, obj: T, hint: String): T = expectMsg(max.asScala, obj)
/**
* Receive one message from the test actor and assert that the given
* partial function accepts it. Wait time is bounded by the given duration,
@ -278,8 +504,17 @@ class TestKit(system: ActorSystem) {
* the given class. Wait time is bounded by the given duration, with an
* AssertionFailure being thrown in case of timeout.
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def expectMsgClass[T](max: FiniteDuration, c: Class[T]): T = tp.expectMsgClass(max, c)
/**
* Receive one message from the test actor and assert that it conforms to
* the given class. Wait time is bounded by the given duration, with an
* AssertionFailure being thrown in case of timeout.
*/
def expectMsgClass[T](max: java.time.Duration, c: Class[T]): T = expectMsgClass(max.asScala, c)
/**
* Same as `expectMsgAnyOf(remainingOrDefault, obj...)`, but correctly treating the timeFactor.
*/
@ -292,8 +527,17 @@ class TestKit(system: ActorSystem) {
* AssertionFailure being thrown in case of timeout.
*/
@varargs
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def expectMsgAnyOf[T](max: FiniteDuration, objs: T*): T = tp.expectMsgAnyOf(max, objs: _*)
/**
* Receive one message from the test actor and assert that it equals one of
* the given objects. Wait time is bounded by the given duration, with an
* AssertionFailure being thrown in case of timeout.
*/
def expectMsgAnyOf[T](max: java.time.Duration, objs: T*): T = expectMsgAnyOf(max.asScala, objs: _*)
/**
* Same as `expectMsgAllOf(remainingOrDefault, obj...)`, but correctly treating the timeFactor.
*/
@ -308,8 +552,19 @@ class TestKit(system: ActorSystem) {
* given duration, with an AssertionFailure being thrown in case of timeout.
*/
@varargs
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def expectMsgAllOf[T](max: FiniteDuration, objs: T*): JList[T] = tp.expectMsgAllOf(max, objs: _*).asJava
/**
* Receive a number of messages from the test actor matching the given
* number of objects and assert that for each given object one is received
* which equals it and vice versa. This construct is useful when the order in
* which the objects are received is not fixed. Wait time is bounded by the
* given duration, with an AssertionFailure being thrown in case of timeout.
*/
def expectMsgAllOf[T](max: java.time.Duration, objs: T*): JList[T] = expectMsgAllOf(max.asScala, objs: _*)
/**
* Same as `expectMsgAnyClassOf(remainingOrDefault, obj...)`, but correctly treating the timeFactor.
*/
@ -323,7 +578,18 @@ class TestKit(system: ActorSystem) {
* with an AssertionFailure being thrown in case of timeout.
*/
@varargs
def expectMsgAnyClassOf[T](max: FiniteDuration, objs: Class[_]*): T = tp.expectMsgAnyClassOf(max, objs: _*).asInstanceOf[T]
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def expectMsgAnyClassOf[T](max: FiniteDuration, objs: Class[_]*): T =
tp.expectMsgAnyClassOf(max, objs: _*).asInstanceOf[T]
/**
* Receive one message from the test actor and assert that it conforms to
* one of the given classes. Wait time is bounded by the given duration,
* with an AssertionFailure being thrown in case of timeout.
*/
def expectMsgAnyClassOf[T](max: java.time.Duration, objs: Class[_]*): T =
expectMsgAnyClassOf(max.asScala, objs: _*)
/**
* Same as `expectNoMsg(remainingOrDefault)`, but correctly treating the timeFactor.
@ -346,8 +612,16 @@ class TestKit(system: ActorSystem) {
* Assert that no message is received for the specified time.
* Supplied value is not dilated.
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def expectNoMessage(max: FiniteDuration): Unit = tp.expectNoMessage(max)
/**
* Assert that no message is received for the specified time.
* Supplied value is not dilated.
*/
def expectNoMessage(max: java.time.Duration): Unit = expectNoMessage(max.asScala)
/**
* Receive one message from the test actor and assert that it is the Terminated message of the given ActorRef.
* Before calling this method, you have to `watch` the target actor ref.
@ -404,9 +678,16 @@ class TestKit(system: ActorSystem) {
/**
* Receive N messages in a row before the given deadline.
*/
@Deprecated
@deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12")
def receiveN(n: Int, max: FiniteDuration): JList[AnyRef] =
tp.receiveN(n, max).asJava
/**
* Receive N messages in a row before the given deadline.
*/
def receiveN(n: Int, max: java.time.Duration): JList[AnyRef] = receiveN(n, max.asScala)
/**
* Receive one message from the internal queue of the TestActor. If the given
* duration is zero, the queue is polled (non-blocking).