From 7bb966367b43e63e3b02bf0b1b442992e4711ced Mon Sep 17 00:00:00 2001 From: Alexey Kardapoltsev Date: Wed, 20 Feb 2019 12:05:26 +0700 Subject: [PATCH 01/11] specs2 -> scalatest --- build.sbt | 4 +- src/test/scala/redis/ConverterSpec.scala | 27 +- src/test/scala/redis/RedisClusterTest.scala | 93 +++-- src/test/scala/redis/RedisPoolSpec.scala | 27 +- src/test/scala/redis/RedisPubSubSpec.scala | 21 +- src/test/scala/redis/RedisSpec.scala | 33 +- src/test/scala/redis/RedisTest.scala | 25 +- src/test/scala/redis/SentinelPoolSpec.scala | 79 ++-- src/test/scala/redis/SentinelSpec.scala | 78 ++-- src/test/scala/redis/TestBase.scala | 28 ++ .../redis/actors/RedisClientActorSpec.scala | 113 +++--- .../redis/actors/RedisReplyDecoderSpec.scala | 68 ++-- .../actors/RedisSubscriberActorSpec.scala | 22 +- .../redis/actors/RedisWorkerIOSpec.scala | 124 +++--- .../scala/redis/commands/BListsSpec.scala | 180 ++++----- .../scala/redis/commands/ConnectionSpec.scala | 20 +- src/test/scala/redis/commands/GeoSpec.scala | 17 +- .../scala/redis/commands/HashesSpec.scala | 56 +-- .../redis/commands/HyperLogLogSpec.scala | 11 +- src/test/scala/redis/commands/KeysSpec.scala | 159 ++++---- src/test/scala/redis/commands/ListsSpec.scala | 78 ++-- .../scala/redis/commands/ScriptingSpec.scala | 44 ++- .../scala/redis/commands/ServerSpec.scala | 70 ++-- src/test/scala/redis/commands/SetsSpec.scala | 62 +-- .../scala/redis/commands/SortedSetsSpec.scala | 158 ++++---- .../scala/redis/commands/StringsSpec.scala | 362 ++++++++++-------- .../redis/commands/TransactionsSpec.scala | 30 +- .../redis/protocol/ParseNumberSpec.scala | 41 +- .../scala/redis/protocol/ParseParse.scala | 24 +- .../protocol/RedisProtocolReplySpec.scala | 38 +- .../protocol/RedisProtocolRequestSpec.scala | 8 +- 31 files changed, 1100 insertions(+), 1000 deletions(-) create mode 100644 src/test/scala/redis/TestBase.scala diff --git a/build.sbt b/build.sbt index ddcadd87..3f9c9485 100644 --- a/build.sbt +++ b/build.sbt @@ -31,7 +31,7 @@ lazy val common = Seq( "-encoding", "UTF-8", "-Xlint", "-deprecation", - "-Xfatal-warnings", +// "-Xfatal-warnings", "-feature", "-language:postfixOps", "-unchecked" @@ -43,7 +43,7 @@ lazy val common = Seq( Seq( "com.typesafe.akka" %% "akka-actor" % akkaVersion, "com.typesafe.akka" %% "akka-testkit" % akkaVersion % Test, - "org.specs2" %% "specs2-core" % "4.3.6" % Test, + "org.scalatest" %% "scalatest" % "3.0.5" % Test, "org.scala-stm" %% "scala-stm" % "0.9", "org.scalacheck" %% "scalacheck" % "1.14.0" % Test ) diff --git a/src/test/scala/redis/ConverterSpec.scala b/src/test/scala/redis/ConverterSpec.scala index 80288f9f..7f7415ce 100644 --- a/src/test/scala/redis/ConverterSpec.scala +++ b/src/test/scala/redis/ConverterSpec.scala @@ -1,6 +1,5 @@ package redis -import org.specs2.mutable.Specification import akka.util.ByteString import redis.protocol.{Bulk, RedisReply} @@ -25,49 +24,49 @@ object DumbClass { } } -class ConverterSpec extends Specification { +class ConverterSpec extends TestBase { import redis.ByteStringSerializer._ "ByteStringSerializer" should { "String" in { - String.serialize("super string !") mustEqual ByteString("super string !") + String.serialize("super string !") shouldBe ByteString("super string !") } "Short" in { - ShortConverter.serialize(123) mustEqual ByteString("123") + ShortConverter.serialize(123) shouldBe ByteString("123") } "Int" in { - IntConverter.serialize(123) mustEqual ByteString("123") + IntConverter.serialize(123) shouldBe ByteString("123") } "Long" in { - LongConverter.serialize(123) mustEqual ByteString("123") + LongConverter.serialize(123) shouldBe ByteString("123") } "Float" in { - FloatConverter.serialize(123.123f) mustEqual ByteString("123.123") + FloatConverter.serialize(123.123f) shouldBe ByteString("123.123") } "Double" in { - DoubleConverter.serialize(123.123456) mustEqual ByteString("123.123456") + DoubleConverter.serialize(123.123456) shouldBe ByteString("123.123456") } "Char" in { - CharConverter.serialize('a') mustEqual ByteString('a') + CharConverter.serialize('a') shouldBe ByteString('a') } "Byte" in { - ByteConverter.serialize(123) mustEqual ByteString(123) + ByteConverter.serialize(123) shouldBe ByteString(123) } "ArrayByte" in { - ArrayByteConverter.serialize(Array[Byte](1, 2, 3)) mustEqual ByteString(Array[Byte](1, 2, 3)) + ArrayByteConverter.serialize(Array[Byte](1, 2, 3)) shouldBe ByteString(Array[Byte](1, 2, 3)) } "ByteString" in { - ByteStringConverter.serialize(ByteString("stupid")) mustEqual ByteString("stupid") + ByteStringConverter.serialize(ByteString("stupid")) shouldBe ByteString("stupid") } } @@ -77,8 +76,8 @@ class ConverterSpec extends Specification { val formatter = implicitly[ByteStringFormatter[DumbClass]] - formatter.serialize(dumb) mustEqual ByteString("aa|bb") - formatter.deserialize(ByteString("aa|bb")) mustEqual dumb + formatter.serialize(dumb) shouldBe ByteString("aa|bb") + formatter.deserialize(ByteString("aa|bb")) shouldBe dumb } } diff --git a/src/test/scala/redis/RedisClusterTest.scala b/src/test/scala/redis/RedisClusterTest.scala index a2776168..15d15e0f 100644 --- a/src/test/scala/redis/RedisClusterTest.scala +++ b/src/test/scala/redis/RedisClusterTest.scala @@ -1,8 +1,6 @@ package redis - import akka.util.ByteString -import org.specs2.execute.Result import redis.api.clusters.ClusterSlots import redis.protocol._ @@ -13,30 +11,28 @@ import scala.concurrent.Await */ class RedisClusterTest extends RedisClusterClients { - - var redisCluster:RedisCluster = null + var redisCluster: RedisCluster = null override def setup(): Unit = { super.setup() - redisCluster = RedisCluster(nodePorts.map(p=>RedisServer("127.0.0.1",p))) + redisCluster = RedisCluster(nodePorts.map(p => RedisServer("127.0.0.1", p))) } - sequential - "RedisComputeSlot" should { "simple" in { - RedisComputeSlot.hashSlot("foo") mustEqual 12182 - RedisComputeSlot.hashSlot("somekey") mustEqual 11058 - RedisComputeSlot.hashSlot("somekey3452345325453532452345") mustEqual 15278 - RedisComputeSlot.hashSlot("rzarzaZERAZERfqsfsdQSFD") mustEqual 14258 - RedisComputeSlot.hashSlot("{foo}46546546546") mustEqual 12182 - RedisComputeSlot.hashSlot("foo_312312") mustEqual 5839 - RedisComputeSlot.hashSlot("aazaza{aa") mustEqual 11473 + RedisComputeSlot.hashSlot("foo") shouldBe 12182 + RedisComputeSlot.hashSlot("somekey") shouldBe 11058 + RedisComputeSlot.hashSlot("somekey3452345325453532452345") shouldBe 15278 + RedisComputeSlot.hashSlot("rzarzaZERAZERfqsfsdQSFD") shouldBe 14258 + RedisComputeSlot.hashSlot("{foo}46546546546") shouldBe 12182 + RedisComputeSlot.hashSlot("foo_312312") shouldBe 5839 + RedisComputeSlot.hashSlot("aazaza{aa") shouldBe 11473 } } "clusterSlots" should { "encoding" in { - val clusterSlotsAsByteString = ByteString(new sun.misc.BASE64Decoder().decodeBuffer("KjMNCio0DQo6MA0KOjU0NjANCiozDQokOQ0KMTI3LjAuMC4xDQo6NzAwMA0KJDQwDQplNDM1OTlkZmY2ZTNhN2I5ZWQ1M2IxY2EwZGI0YmQwMDlhODUwYmE1DQoqMw0KJDkNCjEyNy4wLjAuMQ0KOjcwMDMNCiQ0MA0KYzBmNmYzOWI2NDg4MTVhMTllNDlkYzQ1MzZkMmExM2IxNDdhOWY1MA0KKjQNCjoxMDkyMw0KOjE2MzgzDQoqMw0KJDkNCjEyNy4wLjAuMQ0KOjcwMDINCiQ0MA0KNDhkMzcxMjBmMjEzNTc4Y2IxZWFjMzhlNWYyYmY1ODlkY2RhNGEwYg0KKjMNCiQ5DQoxMjcuMC4wLjENCjo3MDA1DQokNDANCjE0Zjc2OWVlNmU1YWY2MmZiMTc5NjZlZDRlZWRmMTIxOWNjYjE1OTINCio0DQo6NTQ2MQ0KOjEwOTIyDQoqMw0KJDkNCjEyNy4wLjAuMQ0KOjcwMDENCiQ0MA0KYzhlYzM5MmMyMjY5NGQ1ODlhNjRhMjA5OTliNGRkNWNiNDBlNDIwMQ0KKjMNCiQ5DQoxMjcuMC4wLjENCjo3MDA0DQokNDANCmVmYThmZDc0MDQxYTNhOGQ3YWYyNWY3MDkwM2I5ZTFmNGMwNjRhMjENCg==")) + val clusterSlotsAsByteString = ByteString(new sun.misc.BASE64Decoder().decodeBuffer( + "KjMNCio0DQo6MA0KOjU0NjANCiozDQokOQ0KMTI3LjAuMC4xDQo6NzAwMA0KJDQwDQplNDM1OTlkZmY2ZTNhN2I5ZWQ1M2IxY2EwZGI0YmQwMDlhODUwYmE1DQoqMw0KJDkNCjEyNy4wLjAuMQ0KOjcwMDMNCiQ0MA0KYzBmNmYzOWI2NDg4MTVhMTllNDlkYzQ1MzZkMmExM2IxNDdhOWY1MA0KKjQNCjoxMDkyMw0KOjE2MzgzDQoqMw0KJDkNCjEyNy4wLjAuMQ0KOjcwMDINCiQ0MA0KNDhkMzcxMjBmMjEzNTc4Y2IxZWFjMzhlNWYyYmY1ODlkY2RhNGEwYg0KKjMNCiQ5DQoxMjcuMC4wLjENCjo3MDA1DQokNDANCjE0Zjc2OWVlNmU1YWY2MmZiMTc5NjZlZDRlZWRmMTIxOWNjYjE1OTINCio0DQo6NTQ2MQ0KOjEwOTIyDQoqMw0KJDkNCjEyNy4wLjAuMQ0KOjcwMDENCiQ0MA0KYzhlYzM5MmMyMjY5NGQ1ODlhNjRhMjA5OTliNGRkNWNiNDBlNDIwMQ0KKjMNCiQ5DQoxMjcuMC4wLjENCjo3MDA0DQokNDANCmVmYThmZDc0MDQxYTNhOGQ3YWYyNWY3MDkwM2I5ZTFmNGMwNjRhMjENCg==")) val clusterSlotsAsBulk: DecodeResult[RedisReply] = RedisProtocolReply.decodeReply(clusterSlotsAsByteString) val dr: DecodeResult[String] = clusterSlotsAsBulk.map({ case a: MultiBulk => @@ -44,13 +40,13 @@ class RedisClusterTest extends RedisClusterClients { case _ => "fail" }) + val r = dr match { + case FullyDecoded(decodeValue, _) => + decodeValue shouldBe "Vector(ClusterSlot(0,5460,ClusterNode(127.0.0.1,7000,e43599dff6e3a7b9ed53b1ca0db4bd009a850ba5),Stream(ClusterNode(127.0.0.1,7003,c0f6f39b648815a19e49dc4536d2a13b147a9f50), ?)), " + + "ClusterSlot(10923,16383,ClusterNode(127.0.0.1,7002,48d37120f213578cb1eac38e5f2bf589dcda4a0b),Stream(ClusterNode(127.0.0.1,7005,14f769ee6e5af62fb17966ed4eedf1219ccb1592), ?)), " + + "ClusterSlot(5461,10922,ClusterNode(127.0.0.1,7001,c8ec392c22694d589a64a20999b4dd5cb40e4201),Stream(ClusterNode(127.0.0.1,7004,efa8fd74041a3a8d7af25f70903b9e1f4c064a21), ?)))" - val r: Result = dr match { - case FullyDecoded(decodeValue, _) => decodeValue mustEqual "Vector(ClusterSlot(0,5460,ClusterNode(127.0.0.1,7000,e43599dff6e3a7b9ed53b1ca0db4bd009a850ba5),Stream(ClusterNode(127.0.0.1,7003,c0f6f39b648815a19e49dc4536d2a13b147a9f50), ?)), " + - "ClusterSlot(10923,16383,ClusterNode(127.0.0.1,7002,48d37120f213578cb1eac38e5f2bf589dcda4a0b),Stream(ClusterNode(127.0.0.1,7005,14f769ee6e5af62fb17966ed4eedf1219ccb1592), ?)), " + - "ClusterSlot(5461,10922,ClusterNode(127.0.0.1,7001,c8ec392c22694d589a64a20999b4dd5cb40e4201),Stream(ClusterNode(127.0.0.1,7004,efa8fd74041a3a8d7af25f70903b9e1f4c064a21), ?)))" - - case _ => failure + case _ => fail() } r @@ -61,86 +57,87 @@ class RedisClusterTest extends RedisClusterClients { "Strings" should { "set-get" in { println("set") - Await.result(redisCluster.set[String]("foo","FOO"), timeOut) + Await.result(redisCluster.set[String]("foo", "FOO"), timeOut) println("exists") - Await.result(redisCluster.exists("foo"), timeOut) mustEqual(true) + Await.result(redisCluster.exists("foo"), timeOut) shouldBe (true) println("get") - Await.result(redisCluster.get[String]("foo"), timeOut) mustEqual Some("FOO") + Await.result(redisCluster.get[String]("foo"), timeOut) shouldBe Some("FOO") println("del") - Await.result(redisCluster.del("foo","foo"), timeOut) + Await.result(redisCluster.del("foo", "foo"), timeOut) println("exists") - Await.result(redisCluster.exists("foo"), timeOut) mustEqual(false) + Await.result(redisCluster.exists("foo"), timeOut) shouldBe (false) } "mset-mget" in { println("mset") - Await.result(redisCluster.mset[String](Map("{foo}1"->"FOO1","{foo}2"->"FOO2")), timeOut) + Await.result(redisCluster.mset[String](Map("{foo}1" -> "FOO1", "{foo}2" -> "FOO2")), timeOut) println("exists") - Await.result(redisCluster.exists("{foo}1"), timeOut) mustEqual(true) - Await.result(redisCluster.exists("{foo}2"), timeOut) mustEqual(true) + Await.result(redisCluster.exists("{foo}1"), timeOut) shouldBe (true) + Await.result(redisCluster.exists("{foo}2"), timeOut) shouldBe (true) println("mget") - Await.result(redisCluster.mget[String]("{foo}1","{foo}2"), timeOut) mustEqual Seq(Some("FOO1"),Some("FOO2")) + Await.result(redisCluster.mget[String]("{foo}1", "{foo}2"), timeOut) shouldBe Seq(Some("FOO1"), Some("FOO2")) println("del") - Await.result(redisCluster.del("{foo}1","{foo}2"), timeOut) + Await.result(redisCluster.del("{foo}1", "{foo}2"), timeOut) println("exists") - Await.result(redisCluster.exists("{foo}1"), timeOut) mustEqual(false) + Await.result(redisCluster.exists("{foo}1"), timeOut) shouldBe (false) } } "tools" should { "groupby" in { - redisCluster.groupByCluserServer(Seq("{foo1}1","{foo2}1","{foo1}2","{foo2}2")).sortBy(_.head).toList mustEqual( Seq(Seq("{foo2}1","{foo2}2"),Seq("{foo1}1","{foo1}2")).sortBy(_.head) ) + redisCluster + .groupByCluserServer(Seq("{foo1}1", "{foo2}1", "{foo1}2", "{foo2}2")) + .sortBy(_.head) + .toList shouldBe (Seq(Seq("{foo2}1", "{foo2}2"), Seq("{foo1}1", "{foo1}2")).sortBy(_.head)) } } - "long run" should { "wait" in { - println("set "+ redisCluster.getClusterAndConnection(RedisComputeSlot.hashSlot("foo1")).get._1.master.toString) - Await.result(redisCluster.set[String]("foo1","FOO"), timeOut) + println("set " + redisCluster.getClusterAndConnection(RedisComputeSlot.hashSlot("foo1")).get._1.master.toString) + Await.result(redisCluster.set[String]("foo1", "FOO"), timeOut) Await.result(redisCluster.get[String]("foo1"), timeOut) println("wait...") - // Thread.sleep(15000) + // Thread.sleep(15000) println("get") - Await.result(redisCluster.get[String]("foo1"), timeOut) mustEqual Some("FOO") + Await.result(redisCluster.get[String]("foo1"), timeOut) shouldBe Some("FOO") } - } "clusterInfo" should { "just work" in { val res = Await.result(redisCluster.clusterInfo(), timeOut) - res must not be empty + res should not be empty for (v <- res) { println(s"Key ${v._1} value ${v._2}") } - res("cluster_state") mustEqual "ok" - res("cluster_slots_ok") mustEqual "16384" - res("cluster_known_nodes") mustEqual "6" - res("cluster_size") mustEqual "3" + res("cluster_state") shouldBe "ok" + res("cluster_slots_ok") shouldBe "16384" + res("cluster_known_nodes") shouldBe "6" + res("cluster_size") shouldBe "3" } } "clusterNodes" should { "just work" in { val res = Await.result(redisCluster.clusterNodes(), timeOut) - res must not be empty + res should not be empty for (m <- res) { println(m.toString) } - res.size mustEqual 6 - res.count(_.master != "-") mustEqual 3 - res.count(_.link_state == "connected") mustEqual 6 + res.size shouldBe 6 + res.count(_.master != "-") shouldBe 3 + res.count(_.link_state == "connected") shouldBe 6 } } } diff --git a/src/test/scala/redis/RedisPoolSpec.scala b/src/test/scala/redis/RedisPoolSpec.scala index 93aec549..e5d91f2c 100644 --- a/src/test/scala/redis/RedisPoolSpec.scala +++ b/src/test/scala/redis/RedisPoolSpec.scala @@ -6,7 +6,6 @@ import scala.concurrent._ import scala.concurrent.duration._ class RedisPoolSpec extends RedisStandaloneServer { - sequential "basic pool test" should { "ok" in { @@ -22,13 +21,13 @@ class RedisPoolSpec extends RedisStandaloneServer { getKey2 <- redisPool.get[String](key) getKey0 <- redisPool.get[String](key) } yield { - getDb1 must beNone - getDb2 must beNone - getDb0 must beSome("0") - select mustEqual Seq(true, true, true) - getKey1 must beSome("0") - getKey2 must beSome("0") - getKey0 must beSome("0") + getDb1 shouldBe empty + getDb2 shouldBe empty + getDb0 shouldBe Some("0") + select shouldBe Seq(true, true, true) + getKey1 shouldBe Some("0") + getKey2 shouldBe Some("0") + getKey0 shouldBe Some("0") } Await.result(r, timeOut) } @@ -37,7 +36,7 @@ class RedisPoolSpec extends RedisStandaloneServer { val redisPool = RedisClientPool(Seq(RedisServer( port = port,db = Some(0)), RedisServer( port = port,db = Some(1)), RedisServer(port = 3333,db = Some(3)))) val key = "keyPoolDb0" - awaitAssert(redisPool.redisConnectionPool.size mustEqual 2,20 second) + awaitAssert(redisPool.redisConnectionPool.size shouldBe 2,20 second) redisPool.set(key, 0) val r = for { getDb1 <- redisPool.get(key) @@ -46,11 +45,11 @@ class RedisPoolSpec extends RedisStandaloneServer { getKey1 <- redisPool.get[String](key) getKey0 <- redisPool.get[String](key) } yield { - getDb1 must beNone - getDb0 must beSome("0") - select mustEqual Seq(true, true) - getKey1 must beSome("0") - getKey0 must beSome("0") + getDb1 shouldBe empty + getDb0 shouldBe Some("0") + select shouldBe Seq(true, true) + getKey1 shouldBe Some("0") + getKey0 shouldBe Some("0") } Await.result(r, timeOut) diff --git a/src/test/scala/redis/RedisPubSubSpec.scala b/src/test/scala/redis/RedisPubSubSpec.scala index 4ebdb1d5..548b7e00 100644 --- a/src/test/scala/redis/RedisPubSubSpec.scala +++ b/src/test/scala/redis/RedisPubSubSpec.scala @@ -10,7 +10,6 @@ import akka.util.ByteString class RedisPubSubSpec extends RedisStandaloneServer { - sequential "PubSub test" should { "ok (client + callback)" in { @@ -33,14 +32,14 @@ class RedisPubSubSpec extends RedisStandaloneServer { val p = redis.publish("chan1", "nextChan") val noListener = redis.publish("noListenerChan", "message") - Await.result(p, timeOut) mustEqual 2 - Await.result(noListener, timeOut) mustEqual 0 + Await.result(p, timeOut) shouldBe 2 + Await.result(noListener, timeOut) shouldBe 0 Thread.sleep(2000) val nextChan = redis.publish("nextChan", "message") val p2 = redis.publish("chan1", "nextChan") - Await.result(p2, timeOut) mustEqual 0 - Await.result(nextChan, timeOut) mustEqual 2 + Await.result(p2, timeOut) shouldBe 0 + Await.result(nextChan, timeOut) shouldBe 2 } "ok (actor)" in { @@ -58,11 +57,11 @@ class RedisPubSubSpec extends RedisStandaloneServer { system.scheduler.scheduleOnce(2 seconds)(redis.publish("channel", "value")) - probeMock.expectMsgType[Message](5 seconds) mustEqual Message("channel", ByteString("value")) + probeMock.expectMsgType[Message](5 seconds) shouldBe Message("channel", ByteString("value")) redis.publish("pattern.1", "value") - probeMock.expectMsgType[PMessage] mustEqual PMessage("pattern.*", "pattern.1", ByteString("value")) + probeMock.expectMsgType[PMessage] shouldBe PMessage("pattern.*", "pattern.1", ByteString("value")) subscriberActor.underlyingActor.subscribe("channel2") subscriberActor.underlyingActor.unsubscribe("channel") @@ -71,7 +70,7 @@ class RedisPubSubSpec extends RedisStandaloneServer { redis.publish("channel", "value") redis.publish("channel2", "value") }) - probeMock.expectMsgType[Message](5 seconds) mustEqual Message("channel2", ByteString("value")) + probeMock.expectMsgType[Message](5 seconds) shouldBe Message("channel2", ByteString("value")) subscriberActor.underlyingActor.unsubscribe("channel2") system.scheduler.scheduleOnce(1 second)({ @@ -83,7 +82,7 @@ class RedisPubSubSpec extends RedisStandaloneServer { system.scheduler.scheduleOnce(1 second)({ redis.publish("channel2", ByteString("value")) }) - probeMock.expectMsgType[Message](5 seconds) mustEqual Message("channel2", ByteString("value")) + probeMock.expectMsgType[Message](5 seconds) shouldBe Message("channel2", ByteString("value")) subscriberActor.underlyingActor.psubscribe("pattern2.*") subscriberActor.underlyingActor.punsubscribe("pattern.*") @@ -92,7 +91,7 @@ class RedisPubSubSpec extends RedisStandaloneServer { redis.publish("pattern2.match", ByteString("value")) redis.publish("pattern.*", ByteString("value")) }) - probeMock.expectMsgType[PMessage](5 seconds) mustEqual PMessage("pattern2.*", "pattern2.match", ByteString("value")) + probeMock.expectMsgType[PMessage](5 seconds) shouldBe PMessage("pattern2.*", "pattern2.match", ByteString("value")) subscriberActor.underlyingActor.punsubscribe("pattern2.*") system.scheduler.scheduleOnce(2 seconds)({ @@ -104,7 +103,7 @@ class RedisPubSubSpec extends RedisStandaloneServer { system.scheduler.scheduleOnce(2 seconds)({ redis.publish("pattern.*", ByteString("value")) }) - probeMock.expectMsgType[PMessage](5 seconds) mustEqual PMessage("pattern.*", "pattern.*", ByteString("value")) + probeMock.expectMsgType[PMessage](5 seconds) shouldBe PMessage("pattern.*", "pattern.*", ByteString("value")) } } diff --git a/src/test/scala/redis/RedisSpec.scala b/src/test/scala/redis/RedisSpec.scala index 035e1300..87c69e20 100644 --- a/src/test/scala/redis/RedisSpec.scala +++ b/src/test/scala/redis/RedisSpec.scala @@ -8,9 +8,8 @@ import java.util.concurrent.atomic.AtomicInteger import akka.actor.ActorSystem import akka.testkit.TestKit import akka.util.Timeout -import org.specs2.concurrent.FutureAwait -import org.specs2.mutable.SpecificationLike -import org.specs2.specification.core.Fragments +import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpec, WordSpecLike} +import org.scalatest.concurrent.{Eventually, ScalaFutures} import scala.collection.JavaConverters._ import scala.concurrent.Future @@ -35,8 +34,8 @@ object RedisServerHelper { abstract class RedisHelper extends TestKit(ActorSystem()) - with SpecificationLike - with FutureAwait { + with TestBase + with BeforeAndAfterAll { import scala.concurrent.duration._ @@ -47,15 +46,24 @@ abstract class RedisHelper val timeOut = 10 seconds val longTimeOut = 100 seconds - override def map(fs: => Fragments) = { + + override protected def beforeAll(): Unit = { setup() - fs ^ - step({ - TestKit.shutdownActorSystem(system) - cleanup() - }) } + override protected def afterAll(): Unit = { + TestKit.shutdownActorSystem(system) + cleanup() + } +// override def map(fs: => Fragments) = { +// setup() +// fs ^ +// step({ +// TestKit.shutdownActorSystem(system) +// cleanup() +// }) +// } + def setup() def cleanup() @@ -225,7 +233,8 @@ abstract class RedisClusterClients() extends RedisHelper { Thread.sleep(2000) val nodes = nodePorts.map(s => redisHost + ":" + s).mkString(" ") - val createClusterCmd = s"$redisCliCmd --cluster create --cluster-replicas 1 ${nodes}" + val createClusterCmd = + s"$redisCliCmd --cluster create --cluster-replicas 1 ${nodes}" println(createClusterCmd) Process(createClusterCmd) .run( diff --git a/src/test/scala/redis/RedisTest.scala b/src/test/scala/redis/RedisTest.scala index db1ae082..e31a9246 100644 --- a/src/test/scala/redis/RedisTest.scala +++ b/src/test/scala/redis/RedisTest.scala @@ -7,23 +7,21 @@ import akka.util.ByteString class RedisTest extends RedisStandaloneServer { - sequential - "basic test" should { "ping" in { - Await.result(redis.ping, timeOut) mustEqual "PONG" + Await.result(redis.ping, timeOut) shouldBe "PONG" } "set" in { - Await.result(redis.set("key", "value"), timeOut) mustEqual true + Await.result(redis.set("key", "value"), timeOut) shouldBe true } "get" in { - Await.result(redis.get("key"), timeOut) mustEqual Some(ByteString("value")) + Await.result(redis.get("key"), timeOut) shouldBe Some(ByteString("value")) } "del" in { - Await.result(redis.del("key"), timeOut) mustEqual 1 + Await.result(redis.del("key"), timeOut) shouldBe 1 } "get not found" in { - Await.result(redis.get("key"), timeOut) mustEqual None + Await.result(redis.get("key"), timeOut) shouldBe None } } @@ -37,17 +35,18 @@ class RedisTest extends RedisStandaloneServer { _ <- redis.set("keyDbSelect", "2") } yield { val redis = RedisClient(port = port, password = Some("password"), db = Some(2)) - Await.result(redis.get[String]("keyDbSelect"), timeOut) must beSome("2") + Await.result(redis.get[String]("keyDbSelect"), timeOut) shouldBe Some("2") } Await.result(r, timeOut) }) } "use custom dispatcher" in { - def test() = withRedisServer(port => { - implicit val redisDispatcher = RedisDispatcher("no-this-dispatcher") - RedisClient(port = port) - }) - test must throwA[ConfigurationException] + a[ConfigurationException] shouldBe thrownBy { + withRedisServer(port => { + implicit val redisDispatcher = RedisDispatcher("no-this-dispatcher") + RedisClient(port = port) + }) + } } } diff --git a/src/test/scala/redis/SentinelPoolSpec.scala b/src/test/scala/redis/SentinelPoolSpec.scala index 59b70805..29f83791 100644 --- a/src/test/scala/redis/SentinelPoolSpec.scala +++ b/src/test/scala/redis/SentinelPoolSpec.scala @@ -2,90 +2,87 @@ package redis import redis.RedisServerHelper.redisHost -import scala.concurrent._ import scala.concurrent.duration._ class SentinelMutablePoolSpec extends RedisSentinelClients("SentinelMutablePoolSpec") { - sequential - - var redisPool:RedisClientMutablePool = null + var redisPool: RedisClientMutablePool = null override def setup(): Unit = { super.setup() - redisPool = RedisClientMutablePool(Seq(RedisServer(redisHost, slavePort1)),masterName) + redisPool = RedisClientMutablePool(Seq(RedisServer(redisHost, slavePort1)), masterName) } "mutable pool" should { "add remove" in { Thread.sleep(1000) - redisPool.redisConnectionPool.size mustEqual 1 + redisPool.redisConnectionPool.size shouldBe 1 - redisPool.addServer(RedisServer(redisHost,slavePort2)) - redisPool.addServer(RedisServer(redisHost,slavePort2)) + redisPool.addServer(RedisServer(redisHost, slavePort2)) + redisPool.addServer(RedisServer(redisHost, slavePort2)) Thread.sleep(5000) - redisPool.redisConnectionPool.size mustEqual 2 + redisPool.redisConnectionPool.size shouldBe 2 val key = "keyPoolDb0" - val r = redisClient.set(key, "hello") + redisClient.set(key, "hello").futureValue - Await.result(r, timeOut) - within(500 millisecond) { - Await.result(redisPool.get[String](key), timeOut) must beSome("hello") - Await.result(redisPool.get[String](key), timeOut) must beSome("hello") - } + redisPool.get[String](key).futureValue shouldBe Some("hello") + redisPool.get[String](key).futureValue shouldBe Some("hello") within(1 second) { redisPool.removeServer(RedisServer(redisHost, slavePort2)) } + eventually { + redisPool.redisConnectionPool.size shouldBe 1 + } - awaitAssert(redisPool.redisConnectionPool.size mustEqual 1,5 second) - - - Await.result(redisPool.get[String](key), timeOut) must beSome("hello") - Await.result(redisPool.get[String](key), timeOut) must beSome("hello") + redisPool.get[String](key).futureValue shouldBe Some("hello") + redisPool.get[String](key).futureValue shouldBe Some("hello") } } } -class SentinelMonitoredRedisClientMasterSlavesSpec extends RedisSentinelClients("SentinelMonitoredRedisClientMasterSlavesSpec") { +class SentinelMonitoredRedisClientMasterSlavesSpec + extends RedisSentinelClients("SentinelMonitoredRedisClientMasterSlavesSpec") { -sequential -lazy val redisMasterSlavesPool = - SentinelMonitoredRedisClientMasterSlaves( master = masterName, - sentinels = sentinelPorts.map((redisHost, _))) - "sentinel slave pool" should { + lazy val redisMasterSlavesPool = + SentinelMonitoredRedisClientMasterSlaves(master = masterName, sentinels = sentinelPorts.map((redisHost, _))) + "sentinel slave pool" should { "add and remove" in { Thread.sleep(10000) - Await.result(redisMasterSlavesPool.set("test", "value"), timeOut) - awaitAssert(redisMasterSlavesPool.slavesClients.redisConnectionPool.size mustEqual 2,60 second) + redisMasterSlavesPool.set("test", "value").futureValue + eventually { + redisMasterSlavesPool.slavesClients.redisConnectionPool.size shouldBe 2 + } - val newSlave = newSlaveProcess() + val newSlave = newSlaveProcess() - awaitAssert(redisMasterSlavesPool.slavesClients.redisConnectionPool.size mustEqual 3,20 second) + eventually { + redisMasterSlavesPool.slavesClients.redisConnectionPool.size shouldBe 3 + } newSlave.stop() - Await.result(redisMasterSlavesPool.get[String]("test"),timeOut) mustEqual Some("value") + redisMasterSlavesPool.get[String]("test").futureValue shouldBe Some("value") slave1.stop() slave2.stop() - awaitAssert( redisMasterSlavesPool.slavesClients.redisConnectionPool.size mustEqual 0,20 second) - Await.result(redisMasterSlavesPool.get[String]("test"), timeOut) mustEqual Some("value") + awaitAssert(redisMasterSlavesPool.slavesClients.redisConnectionPool.size shouldBe 0, 20 second) + redisMasterSlavesPool.get[String]("test").futureValue shouldBe Some("value") newSlaveProcess() //println("************************** newSlaveProcess "+RedisServerHelper.portNumber.get()) - //within(30 second) { - awaitAssert( redisMasterSlavesPool.slavesClients.redisConnectionPool.size mustEqual 1,20 second) - redisMasterSlavesPool.slavesClients.redisConnectionPool.size mustEqual 1 - //} + eventually { + redisMasterSlavesPool.slavesClients.redisConnectionPool.size shouldBe 1 + } + redisMasterSlavesPool.slavesClients.redisConnectionPool.size shouldBe 1 } -/* + /* "changemaster" in { - Try(Await.result(redisMasterSlavesPool.masterClient.shutdown(), timeOut)) - awaitAssert( redisMasterSlavesPool.slavesClients.redisConnectionPool.size mustEqual 0, 20 second ) - Await.result(redisMasterSlavesPool.get[String]("test"), timeOut) mustEqual Some("value") + Try(redisMasterSlavesPool.masterClient.shutdown(), timeOut)) + awaitAssert( redisMasterSlavesPool.slavesClients.redisConnectionPool.size shouldBe 0, 20 second ) + redisMasterSlavesPool.get[String]("test"), timeOut) shouldBe Some("value") }*/ } diff --git a/src/test/scala/redis/SentinelSpec.scala b/src/test/scala/redis/SentinelSpec.scala index 894156cb..da0a4e38 100644 --- a/src/test/scala/redis/SentinelSpec.scala +++ b/src/test/scala/redis/SentinelSpec.scala @@ -1,86 +1,72 @@ package redis -import scala.concurrent._ -import scala.concurrent.duration._ -import akka.testkit._ -import org.specs2.concurrent.ExecutionEnv - -class SentinelSpec(implicit ee: ExecutionEnv) extends RedisSentinelClients("SentinelSpec") { - - sequential +class SentinelSpec extends RedisSentinelClients("SentinelSpec") { "sentinel monitored test" should { - "master auto failover" in { val port = sentinelMonitoredRedisClient.redisClient.port - awaitAssert({ - Await.result(sentinelMonitoredRedisClient.ping(), timeOut) mustEqual "PONG" - sentinelClient.failover(masterName) must beTrue.await - }, 30.seconds.dilated) + sentinelMonitoredRedisClient.ping().futureValue shouldBe "PONG" + sentinelClient.failover(masterName).futureValue shouldBe true - awaitAssert({ - Await.result(sentinelMonitoredRedisClient.ping(), timeOut) mustEqual "PONG" - sentinelMonitoredRedisClient.redisClient.port must beOneOf(slavePort1, slavePort2, port) - }, 30.seconds.dilated) + sentinelMonitoredRedisClient.ping().futureValue shouldBe "PONG" + Seq(slavePort1, slavePort2, port) should contain(sentinelMonitoredRedisClient.redisClient.port) - awaitAssert({ - Await.result(sentinelClient.failover(masterName), timeOut) must beTrue - }, 30.seconds.dilated) - - awaitAssert({ - Await.result(sentinelMonitoredRedisClient.ping(), timeOut) mustEqual "PONG" - }, 30.seconds.dilated) - sentinelMonitoredRedisClient.redisClient.port must beOneOf(slavePort1, slavePort2, masterPort, port) + sentinelMonitoredRedisClient.ping().futureValue shouldBe "PONG" + Seq(slavePort1, slavePort2, masterPort, port) should contain(sentinelMonitoredRedisClient.redisClient.port) } "ping" in { - Await.result(sentinelMonitoredRedisClient.ping(), timeOut) mustEqual "PONG" - Await.result(redisClient.ping(), timeOut) mustEqual "PONG" + sentinelMonitoredRedisClient.ping().futureValue shouldBe "PONG" + redisClient.ping().futureValue shouldBe "PONG" } "sentinel nodes auto discovery" in { val sentinelCount = sentinelMonitoredRedisClient.sentinelClients.size val sentinel = newSentinelProcess() - awaitAssert(sentinelMonitoredRedisClient.sentinelClients.size mustEqual sentinelCount + 1, 10 second) - + eventually { + sentinelMonitoredRedisClient.sentinelClients.size shouldBe sentinelCount + 1 + } sentinel.stop() - awaitAssert({ - sentinelMonitoredRedisClient.sentinelClients.size mustEqual sentinelCount - }, 10 seconds) - success + eventually { + sentinelMonitoredRedisClient.sentinelClients.size shouldBe sentinelCount + } } } "sentinel test" should { "masters" in { - val r = Await.result(sentinelClient.masters(), timeOut) - r(0)("name") mustEqual masterName - r(0)("flags").startsWith("master") mustEqual true + val r = sentinelClient.masters().futureValue + r(0)("name") shouldBe masterName + r(0)("flags").startsWith("master") shouldBe true } "no such master" in { - val opt = Await.result(sentinelClient.getMasterAddr("no-such-master"), timeOut) - opt must beNone.setMessage(s"unexpected: master with name '$masterName' was not supposed to be found") + val opt = sentinelClient.getMasterAddr("no-such-master").futureValue + withClue(s"unexpected: master with name '$masterName' was not supposed to be found") { + opt shouldBe empty + } } "unknown master state" in { - val opt = Await.result(sentinelClient.isMasterDown("no-such-master"), timeOut) - opt must beNone.setMessage("unexpected: master state should be unknown") + val opt = sentinelClient.isMasterDown("no-such-master").futureValue + withClue("unexpected: master state should be unknown") { opt shouldBe empty } } "master ok" in { - Await.result(sentinelClient.isMasterDown(masterName), timeOut) must beSome(false).setMessage(s"unexpected: master with name '$masterName' was not found") + withClue(s"unexpected: master with name '$masterName' was not found") { + sentinelClient.isMasterDown(masterName).futureValue shouldBe Some(false) + } } "slaves" in { - val r = Await.result(sentinelClient.slaves(masterName), timeOut) - r must not be empty - r(0)("flags").startsWith("slave") mustEqual true + val r = sentinelClient.slaves(masterName).futureValue + r should not be empty + r(0)("flags").startsWith("slave") shouldBe true } "reset bogus master" in { - !Await.result(sentinelClient.resetMaster("no-such-master"), timeOut) + sentinelClient.resetMaster("no-such-master").futureValue shouldBe false } "reset master" in { - Await.result(sentinelClient.resetMaster(masterName), timeOut) + sentinelClient.resetMaster(masterName).futureValue shouldBe true } } diff --git a/src/test/scala/redis/TestBase.scala b/src/test/scala/redis/TestBase.scala new file mode 100644 index 00000000..95170df1 --- /dev/null +++ b/src/test/scala/redis/TestBase.scala @@ -0,0 +1,28 @@ +package redis + +import org.scalactic.Prettifier +import org.scalatest.concurrent.{Eventually, ScalaFutures} +import org.scalatest.matchers.{MatchResult, Matcher} +import org.scalatest.{Matchers, WordSpecLike} + +trait TestBase extends WordSpecLike with Matchers with ScalaFutures with Eventually { + import org.scalatest.time.{Millis, Seconds, Span} + implicit protected val defaultPatience = + PatienceConfig(timeout = Span(10, Seconds), interval = Span(20, Millis)) + + def beBetween[T: Ordering](right: (T, T)): Matcher[T] = + new Matcher[T] { + def apply(left: T): MatchResult = { + val (from, to) = right + val ordering = implicitly[Ordering[T]] + val isBetween = ordering.lteq(from, left) && ordering.gteq(to, left) + MatchResult( + isBetween, + s"$left wasn't in range $right", + s"$left was in range $right", + Vector(left, right) + ) + } + override def toString: String = "be between " + Prettifier.default(right) + } +} diff --git a/src/test/scala/redis/actors/RedisClientActorSpec.scala b/src/test/scala/redis/actors/RedisClientActorSpec.scala index 5ec75fb5..bd91b483 100644 --- a/src/test/scala/redis/actors/RedisClientActorSpec.scala +++ b/src/test/scala/redis/actors/RedisClientActorSpec.scala @@ -5,15 +5,14 @@ import java.net.InetSocketAddress import akka.actor._ import akka.testkit._ import akka.util.ByteString -import org.specs2.mutable.SpecificationLike import redis.api.connection.Ping import redis.api.strings.Get -import redis.{Operation, Redis} +import redis.{Operation, Redis, TestBase} import scala.collection.mutable import scala.concurrent.{Await, Promise} -class RedisClientActorSpec extends TestKit(ActorSystem()) with SpecificationLike with ImplicitSender { +class RedisClientActorSpec extends TestKit(ActorSystem()) with TestBase with ImplicitSender { import scala.concurrent.duration._ @@ -23,117 +22,141 @@ class RedisClientActorSpec extends TestKit(ActorSystem()) with SpecificationLike val timeout = 120.seconds dilated - val onConnectStatus: (Boolean) => Unit = (status:Boolean) => {} + val onConnectStatus: (Boolean) => Unit = (status: Boolean) => {} "RedisClientActor" should { - "ok" in within(timeout){ + "ok" in within(timeout) { val probeReplyDecoder = TestProbe() - val probeMock = TestProbe() - + val probeMock = TestProbe() val promiseConnect1 = Promise[String]() - val opConnectPing = Operation(Ping, promiseConnect1) + val opConnectPing = Operation(Ping, promiseConnect1) val promiseConnect2 = Promise[Option[ByteString]]() - val getCmd = Get("key") - val opConnectGet = Operation(getCmd, promiseConnect2) + val getCmd = Get("key") + val opConnectGet = Operation(getCmd, promiseConnect2) val getConnectOperations: () => Seq[Operation[_, _]] = () => { Seq(opConnectPing, opConnectGet) } - - val redisClientActor = TestActorRef[RedisClientActorMock](Props(classOf[RedisClientActorMock], probeReplyDecoder.ref, probeMock.ref, getConnectOperations, onConnectStatus) - .withDispatcher(Redis.dispatcher.name)) + val redisClientActor = TestActorRef[RedisClientActorMock]( + Props( + classOf[RedisClientActorMock], + probeReplyDecoder.ref, + probeMock.ref, + getConnectOperations, + onConnectStatus) + .withDispatcher(Redis.dispatcher.name)) val promise = Promise[String]() - val op1 = Operation(Ping, promise) + val op1 = Operation(Ping, promise) redisClientActor ! op1 val promise2 = Promise[String]() - val op2 = Operation(Ping, promise2) + val op2 = Operation(Ping, promise2) redisClientActor ! op2 - probeMock.expectMsg(WriteMock) mustEqual WriteMock - awaitAssert(redisClientActor.underlyingActor.queuePromises.length mustEqual 2) + probeMock.expectMsg(WriteMock) shouldBe WriteMock + awaitAssert(redisClientActor.underlyingActor.queuePromises.length shouldBe 2) //onConnectWrite redisClientActor.underlyingActor.onConnectWrite() - awaitAssert(redisClientActor.underlyingActor.queuePromises.result() mustEqual Seq(opConnectPing, opConnectGet, op1, op2)) - awaitAssert(redisClientActor.underlyingActor.queuePromises.length mustEqual 4) + awaitAssert( + redisClientActor.underlyingActor.queuePromises.result() shouldBe Seq(opConnectPing, opConnectGet, op1, op2)) + awaitAssert(redisClientActor.underlyingActor.queuePromises.length shouldBe 4) //onWriteSent redisClientActor.underlyingActor.onWriteSent() - probeReplyDecoder.expectMsgType[QueuePromises] mustEqual QueuePromises(mutable.Queue(opConnectPing, opConnectGet, op1, op2)) - awaitAssert(redisClientActor.underlyingActor.queuePromises must beEmpty) + probeReplyDecoder.expectMsgType[QueuePromises] shouldBe QueuePromises( + mutable.Queue(opConnectPing, opConnectGet, op1, op2)) + awaitAssert(redisClientActor.underlyingActor.queuePromises shouldBe empty) //onDataReceived awaitAssert(redisClientActor.underlyingActor.onDataReceived(ByteString.empty)) - probeReplyDecoder.expectMsgType[ByteString] mustEqual ByteString.empty + probeReplyDecoder.expectMsgType[ByteString] shouldBe ByteString.empty awaitAssert(redisClientActor.underlyingActor.onDataReceived(ByteString("bytestring"))) - probeReplyDecoder.expectMsgType[ByteString] mustEqual ByteString("bytestring") + probeReplyDecoder.expectMsgType[ByteString] shouldBe ByteString("bytestring") //onConnectionClosed val deathWatcher = TestProbe() deathWatcher.watch(probeReplyDecoder.ref) redisClientActor.underlyingActor.onConnectionClosed() - deathWatcher.expectTerminated(probeReplyDecoder.ref, 30 seconds) must beAnInstanceOf[Terminated] + deathWatcher.expectTerminated(probeReplyDecoder.ref, 30 seconds) shouldBe a[Terminated] } "onConnectionClosed with promises queued" in { val probeReplyDecoder = TestProbe() - val probeMock = TestProbe() + val probeMock = TestProbe() - val redisClientActor = TestActorRef[RedisClientActorMock](Props(classOf[RedisClientActorMock], probeReplyDecoder.ref, probeMock.ref, getConnectOperations, onConnectStatus) - .withDispatcher(Redis.dispatcher.name)) - .underlyingActor + val redisClientActor = TestActorRef[RedisClientActorMock]( + Props( + classOf[RedisClientActorMock], + probeReplyDecoder.ref, + probeMock.ref, + getConnectOperations, + onConnectStatus) + .withDispatcher(Redis.dispatcher.name)).underlyingActor val promise3 = Promise[String]() redisClientActor.receive(Operation(Ping, promise3)) - redisClientActor.queuePromises.length mustEqual 1 + redisClientActor.queuePromises.length shouldBe 1 val deathWatcher = TestProbe() deathWatcher.watch(probeReplyDecoder.ref) redisClientActor.onConnectionClosed() - deathWatcher.expectTerminated(probeReplyDecoder.ref, 30 seconds) must beAnInstanceOf[Terminated] - Await.result(promise3.future, 10 seconds) must throwA(NoConnectionException) + deathWatcher.expectTerminated(probeReplyDecoder.ref, 30 seconds) shouldBe a[Terminated] + a[NoConnectionException.type] should be thrownBy Await.result(promise3.future, 10 seconds) } "replyDecoder died -> reset connection" in { val probeReplyDecoder = TestProbe() - val probeMock = TestProbe() - - val redisClientActorRef = TestActorRef[RedisClientActorMock](Props(classOf[RedisClientActorMock], probeReplyDecoder.ref, probeMock.ref, getConnectOperations, onConnectStatus) - .withDispatcher(Redis.dispatcher.name)) + val probeMock = TestProbe() + + val redisClientActorRef = TestActorRef[RedisClientActorMock]( + Props( + classOf[RedisClientActorMock], + probeReplyDecoder.ref, + probeMock.ref, + getConnectOperations, + onConnectStatus) + .withDispatcher(Redis.dispatcher.name)) val redisClientActor = redisClientActorRef.underlyingActor - val promiseSent = Promise[String]() + val promiseSent = Promise[String]() val promiseNotSent = Promise[String]() - val operation = Operation(Ping, promiseSent) + val operation = Operation(Ping, promiseSent) redisClientActor.receive(operation) - redisClientActor.queuePromises.length mustEqual 1 + redisClientActor.queuePromises.length shouldBe 1 redisClientActor.onWriteSent() - redisClientActor.queuePromises must beEmpty - probeReplyDecoder.expectMsgType[QueuePromises] mustEqual QueuePromises(mutable.Queue(operation)) + redisClientActor.queuePromises shouldBe empty + probeReplyDecoder.expectMsgType[QueuePromises] shouldBe QueuePromises(mutable.Queue(operation)) redisClientActor.receive(Operation(Ping, promiseNotSent)) - redisClientActor.queuePromises.length mustEqual 1 + redisClientActor.queuePromises.length shouldBe 1 val deathWatcher = TestProbe() deathWatcher.watch(probeReplyDecoder.ref) deathWatcher.watch(redisClientActorRef) probeReplyDecoder.ref ! Kill - deathWatcher.expectTerminated(probeReplyDecoder.ref) must beAnInstanceOf[Terminated] - redisClientActor.queuePromises.length mustEqual 1 + deathWatcher.expectTerminated(probeReplyDecoder.ref) shouldBe a[Terminated] + redisClientActor.queuePromises.length shouldBe 1 } } } -class RedisClientActorMock(probeReplyDecoder: ActorRef, probeMock: ActorRef, getConnectOperations: () => Seq[Operation[_, _]], onConnectStatus: Boolean => Unit ) - extends RedisClientActor(new InetSocketAddress("localhost", 6379), getConnectOperations, onConnectStatus, Redis.dispatcher.name) { +class RedisClientActorMock(probeReplyDecoder: ActorRef, + probeMock: ActorRef, + getConnectOperations: () => Seq[Operation[_, _]], + onConnectStatus: Boolean => Unit) + extends RedisClientActor( + new InetSocketAddress("localhost", 6379), + getConnectOperations, + onConnectStatus, + Redis.dispatcher.name) { override def initRepliesDecoder() = probeReplyDecoder override def preStart() { diff --git a/src/test/scala/redis/actors/RedisReplyDecoderSpec.scala b/src/test/scala/redis/actors/RedisReplyDecoderSpec.scala index 6f67d160..c813cced 100644 --- a/src/test/scala/redis/actors/RedisReplyDecoderSpec.scala +++ b/src/test/scala/redis/actors/RedisReplyDecoderSpec.scala @@ -1,25 +1,25 @@ package redis.actors import akka.actor._ -import org.specs2.mutable.SpecificationLike import akka.util.ByteString import redis.api.hashes.Hgetall import redis.protocol.MultiBulk + import scala.concurrent.{Await, Promise} import scala.collection.mutable import java.net.InetSocketAddress + import com.typesafe.config.ConfigFactory -import redis.{Redis, Operation} +import redis.{Operation, Redis, TestBase} import redis.api.connection.Ping import akka.testkit._ class RedisReplyDecoderSpec extends TestKit(ActorSystem("testsystem", ConfigFactory.parseString( """akka.loggers = ["akka.testkit.TestEventListener"]"""))) - with SpecificationLike with ImplicitSender { + with TestBase with ImplicitSender { import scala.concurrent.duration._ - sequential val timeout = 5.seconds dilated @@ -33,15 +33,15 @@ class RedisReplyDecoderSpec val redisReplyDecoder = TestActorRef[RedisReplyDecoder](Props(classOf[RedisReplyDecoder]) .withDispatcher(Redis.dispatcher.name)) - redisReplyDecoder.underlyingActor.queuePromises must beEmpty + redisReplyDecoder.underlyingActor.queuePromises shouldBe empty redisReplyDecoder ! q - awaitAssert(redisReplyDecoder.underlyingActor.queuePromises.size mustEqual 1) + awaitAssert(redisReplyDecoder.underlyingActor.queuePromises.size shouldBe 1) redisReplyDecoder ! ByteString("+PONG\r\n") - Await.result(promise.future, timeout) mustEqual "PONG" + Await.result(promise.future, timeout) shouldBe "PONG" - awaitAssert(redisReplyDecoder.underlyingActor.queuePromises must beEmpty) + awaitAssert(redisReplyDecoder.underlyingActor.queuePromises shouldBe empty) val promise2 = Promise[String]() val promise3 = Promise[String]() @@ -52,12 +52,12 @@ class RedisReplyDecoderSpec q2.queue.enqueue(op3) redisReplyDecoder ! q2 - awaitAssert(redisReplyDecoder.underlyingActor.queuePromises.size mustEqual 2) + awaitAssert(redisReplyDecoder.underlyingActor.queuePromises.size shouldBe 2) redisReplyDecoder ! ByteString("+PONG\r\n+PONG\r\n") - Await.result(promise2.future, timeout) mustEqual "PONG" - Await.result(promise3.future, timeout) mustEqual "PONG" - redisReplyDecoder.underlyingActor.queuePromises must beEmpty + Await.result(promise2.future, timeout) shouldBe "PONG" + Await.result(promise3.future, timeout) shouldBe "PONG" + redisReplyDecoder.underlyingActor.queuePromises shouldBe empty } "can't decode" in within(timeout){ @@ -68,31 +68,31 @@ class RedisReplyDecoderSpec val promise = Promise[String]() redisClientActor ! Operation(Ping, promise) awaitAssert({ - redisClientActor.underlyingActor.queuePromises.length mustEqual 1 + redisClientActor.underlyingActor.queuePromises.length shouldBe 1 redisClientActor.underlyingActor.onWriteSent() - redisClientActor.underlyingActor.queuePromises must beEmpty + redisClientActor.underlyingActor.queuePromises shouldBe empty }, timeout) EventFilter[Exception](occurrences = 1, start = "Redis Protocol error: Got 110 as initial reply byte").intercept({ redisClientActor.underlyingActor.onDataReceived(ByteString("not valid redis reply")) }) - probeMock.expectMsg("restartConnection") mustEqual "restartConnection" - Await.result(promise.future, timeout) must throwA(InvalidRedisReply) + probeMock.expectMsg("restartConnection") shouldBe "restartConnection" + a[InvalidRedisReply.type] should be thrownBy Await.result(promise.future, timeout) val promise2 = Promise[String]() redisClientActor ! Operation(Ping, promise2) awaitAssert({ - redisClientActor.underlyingActor.queuePromises.length mustEqual 1 + redisClientActor.underlyingActor.queuePromises.length shouldBe 1 redisClientActor.underlyingActor.onWriteSent() - redisClientActor.underlyingActor.queuePromises must beEmpty + redisClientActor.underlyingActor.queuePromises shouldBe empty }, timeout) EventFilter[Exception](occurrences = 1, start = "Redis Protocol error: Got 110 as initial reply byte").intercept({ redisClientActor.underlyingActor.onDataReceived(ByteString("not valid redis reply")) }) - probeMock.expectMsg("restartConnection") mustEqual "restartConnection" - Await.result(promise2.future, timeout) must throwA(InvalidRedisReply) + probeMock.expectMsg("restartConnection") shouldBe "restartConnection" + a[InvalidRedisReply.type] should be thrownBy Await.result(promise2.future, timeout) } "redis reply in many chunks" in within(timeout){ @@ -110,16 +110,16 @@ class RedisReplyDecoderSpec val redisReplyDecoder = TestActorRef[RedisReplyDecoder](Props(classOf[RedisReplyDecoder]) .withDispatcher(Redis.dispatcher.name)) - redisReplyDecoder.underlyingActor.queuePromises must beEmpty + redisReplyDecoder.underlyingActor.queuePromises shouldBe empty redisReplyDecoder ! q awaitAssert({ - redisReplyDecoder.underlyingActor.queuePromises.size mustEqual 3 + redisReplyDecoder.underlyingActor.queuePromises.size shouldBe 3 }, timeout) redisReplyDecoder ! ByteString("+P") awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.rest == ByteString("+P")) - awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.isFullyDecoded should beFalse) + awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.isFullyDecoded shouldBe false) redisReplyDecoder ! ByteString("ONG\r") awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.rest == ByteString("+PONG\r")) @@ -127,37 +127,37 @@ class RedisReplyDecoderSpec redisReplyDecoder ! ByteString("\n+PONG2") awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.rest == ByteString("+PONG2")) - Await.result(promise1.future, timeout) mustEqual "PONG" + Await.result(promise1.future, timeout) shouldBe "PONG" redisReplyDecoder ! ByteString("\r\n") - awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.isFullyDecoded must beTrue) - awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.rest.isEmpty must beTrue) + awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.isFullyDecoded shouldBe true) + awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.rest.isEmpty shouldBe true) - Await.result(promise2.future, timeout) mustEqual "PONG2" + Await.result(promise2.future, timeout) shouldBe "PONG2" - awaitAssert(redisReplyDecoder.underlyingActor.queuePromises.size mustEqual 1) + awaitAssert(redisReplyDecoder.underlyingActor.queuePromises.size shouldBe 1) val multibulkString0 = ByteString() val multibulkString = ByteString("*4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$5\r\nWorld\r\n") val (multibulkStringStart, multibulkStringEnd) = multibulkString.splitAt(multibulkString.length - 1) redisReplyDecoder ! multibulkString0 - awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.isFullyDecoded must beTrue, timeout) + awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.isFullyDecoded shouldBe true, timeout) for { b <- multibulkStringStart } yield { redisReplyDecoder ! ByteString(b) - awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.isFullyDecoded must beFalse, timeout) + awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.isFullyDecoded shouldBe false, timeout) } redisReplyDecoder ! multibulkStringEnd - awaitAssert(redisReplyDecoder.underlyingActor.queuePromises.size mustEqual 0) - awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.isFullyDecoded must beTrue, timeout) + awaitAssert(redisReplyDecoder.underlyingActor.queuePromises.size shouldBe 0) + awaitAssert(redisReplyDecoder.underlyingActor.partiallyDecoded.isFullyDecoded shouldBe true, timeout) - Await.result(promise3.future, timeout) mustEqual Map("foo" -> "bar", "Hello" -> "World") + Await.result(promise3.future, timeout) shouldBe Map("foo" -> "bar", "Hello" -> "World") - redisReplyDecoder.underlyingActor.queuePromises must beEmpty + redisReplyDecoder.underlyingActor.queuePromises shouldBe empty } } } diff --git a/src/test/scala/redis/actors/RedisSubscriberActorSpec.scala b/src/test/scala/redis/actors/RedisSubscriberActorSpec.scala index ed600f05..e8ca8275 100644 --- a/src/test/scala/redis/actors/RedisSubscriberActorSpec.scala +++ b/src/test/scala/redis/actors/RedisSubscriberActorSpec.scala @@ -2,16 +2,16 @@ package redis.actors import akka.testkit._ import akka.actor._ -import org.specs2.mutable.SpecificationLike import java.net.InetSocketAddress + import akka.util.ByteString import redis.protocol.RedisProtocolRequest -import redis.Redis +import redis.{Redis, TestBase} import akka.io.Tcp._ import redis.api.pubsub.Message import redis.api.pubsub.PMessage -class RedisSubscriberActorSpec extends TestKit(ActorSystem()) with SpecificationLike with ImplicitSender { +class RedisSubscriberActorSpec extends TestKit(ActorSystem()) with TestBase with ImplicitSender { import scala.concurrent.duration._ @@ -27,20 +27,20 @@ class RedisSubscriberActorSpec extends TestKit(ActorSystem()) with Specification .withDispatcher(Redis.dispatcher.name)) val connectMsg = probeMock.expectMsgType[Connect] - connectMsg mustEqual Connect(subscriberActor.underlyingActor.address, options = SO.KeepAlive(on = true) :: Nil) + connectMsg shouldBe Connect(subscriberActor.underlyingActor.address, options = SO.KeepAlive(on = true) :: Nil) val probeTcpWorker = TestProbe() probeTcpWorker.send(subscriberActor, Connected(connectMsg.remoteAddress, connectMsg.remoteAddress)) - probeTcpWorker.expectMsgType[Register] mustEqual Register(subscriberActor) + probeTcpWorker.expectMsgType[Register] shouldBe Register(subscriberActor) val bs = RedisProtocolRequest.multiBulk("SUBSCRIBE", channels.map(ByteString(_))) ++ RedisProtocolRequest.multiBulk("PSUBSCRIBE", patterns.map(ByteString(_))) - probeTcpWorker.expectMsgType[Write] mustEqual Write(bs, WriteAck) + probeTcpWorker.expectMsgType[Write] shouldBe Write(bs, WriteAck) probeTcpWorker.reply(WriteAck) val newChannels = channels :+ "channel2" subscriberActor.underlyingActor.subscribe("channel2") awaitAssert({ - subscriberActor.underlyingActor.channelsSubscribed must containTheSameElementsAs(newChannels) + subscriberActor.underlyingActor.channelsSubscribed should contain theSameElementsAs(newChannels) }, 5.seconds dilated) - probeTcpWorker.expectMsgType[Write] mustEqual Write(RedisProtocolRequest.multiBulk("SUBSCRIBE", Seq(ByteString("channel2"))), WriteAck) + probeTcpWorker.expectMsgType[Write] shouldBe Write(RedisProtocolRequest.multiBulk("SUBSCRIBE", Seq(ByteString("channel2"))), WriteAck) probeTcpWorker.reply(WriteAck) // ConnectionClosed @@ -48,15 +48,15 @@ class RedisSubscriberActorSpec extends TestKit(ActorSystem()) with Specification // Reconnect val connectMsg2 = probeMock.expectMsgType[Connect] - connectMsg2 mustEqual Connect(subscriberActor.underlyingActor.address, options = SO.KeepAlive(on = true) :: Nil) + connectMsg2 shouldBe Connect(subscriberActor.underlyingActor.address, options = SO.KeepAlive(on = true) :: Nil) val probeTcpWorker2 = TestProbe() probeTcpWorker2.send(subscriberActor, Connected(connectMsg2.remoteAddress, connectMsg2.remoteAddress)) - probeTcpWorker2.expectMsgType[Register] mustEqual Register(subscriberActor) + probeTcpWorker2.expectMsgType[Register] shouldBe Register(subscriberActor) // check the new Channel is there val bs2 = RedisProtocolRequest.multiBulk("SUBSCRIBE", newChannels.map(ByteString(_))) ++ RedisProtocolRequest.multiBulk("PSUBSCRIBE", patterns.map(ByteString(_))) val m = probeTcpWorker2.expectMsgType[Write] - m mustEqual Write(bs2, WriteAck) + m shouldBe Write(bs2, WriteAck) } } } diff --git a/src/test/scala/redis/actors/RedisWorkerIOSpec.scala b/src/test/scala/redis/actors/RedisWorkerIOSpec.scala index 263b894d..e2df6d25 100644 --- a/src/test/scala/redis/actors/RedisWorkerIOSpec.scala +++ b/src/test/scala/redis/actors/RedisWorkerIOSpec.scala @@ -1,9 +1,9 @@ package redis.actors import akka.testkit._ -import akka.actor.{ActorRef, Props, ActorSystem} -import org.specs2.mutable.SpecificationLike +import akka.actor.{ActorRef, ActorSystem, Props} import java.net.InetSocketAddress + import akka.io.Tcp._ import akka.util.ByteString import akka.io.Tcp.ErrorClosed @@ -11,9 +11,9 @@ import akka.io.Tcp.Connected import akka.io.Tcp.Register import akka.io.Tcp.Connect import akka.io.Tcp.CommandFailed -import redis.Redis +import redis.{Redis, TestBase} -class RedisWorkerIOSpec extends TestKit(ActorSystem()) with SpecificationLike with ImplicitSender { +class RedisWorkerIOSpec extends TestKit(ActorSystem()) with TestBase with ImplicitSender { import scala.concurrent.duration._ @@ -29,20 +29,18 @@ class RedisWorkerIOSpec extends TestKit(ActorSystem()) with SpecificationLike wi val redisWorkerIO = TestActorRef[RedisWorkerIOMock](Props(classOf[RedisWorkerIOMock], probeTcp.ref, address, probeMock.ref, ByteString.empty).withDispatcher(Redis.dispatcher.name)) val connectMsg = probeTcp.expectMsgType[Connect] - connectMsg mustEqual Connect(address, options = SO.KeepAlive(on = true) :: Nil) + connectMsg shouldBe Connect(address, options = SO.KeepAlive(on = true) :: Nil) probeTcp.reply(CommandFailed(connectMsg)) - probeMock.expectMsg(OnConnectionClosed) mustEqual OnConnectionClosed + probeMock.expectMsg(OnConnectionClosed) shouldBe OnConnectionClosed - // should reconnect in 2s - within(1 second, 4 seconds) { + withClue("reconnect") { val connectMsg = probeTcp.expectMsgType[Connect] - connectMsg mustEqual Connect(address, options = SO.KeepAlive(on = true) :: Nil) - connectMsg.remoteAddress must not beTheSameAs(address) + connectMsg shouldBe Connect(address, options = SO.KeepAlive(on = true) :: Nil) val probeTcpWorker = TestProbe() probeTcpWorker.send(redisWorkerIO, Connected(connectMsg.remoteAddress, address)) - probeTcpWorker.expectMsgType[Register] mustEqual Register(redisWorkerIO) + probeTcpWorker.expectMsgType[Register] shouldBe Register(redisWorkerIO) } } @@ -55,26 +53,26 @@ class RedisWorkerIOSpec extends TestKit(ActorSystem()) with SpecificationLike wi redisWorkerIO ! "PING1" val connectMsg = probeTcp.expectMsgType[Connect] - connectMsg mustEqual Connect(address, options = SO.KeepAlive(on = true) :: Nil) + connectMsg shouldBe Connect(address, options = SO.KeepAlive(on = true) :: Nil) val probeTcpWorker = TestProbe() probeTcpWorker.send(redisWorkerIO, Connected(connectMsg.remoteAddress, address)) - probeTcpWorker.expectMsgType[Register] mustEqual Register(redisWorkerIO) + probeTcpWorker.expectMsgType[Register] shouldBe Register(redisWorkerIO) - probeTcpWorker.expectMsgType[Write] mustEqual Write(ByteString("PING1"), WriteAck) - probeMock.expectMsg(WriteSent) mustEqual WriteSent + probeTcpWorker.expectMsgType[Write] shouldBe Write(ByteString("PING1"), WriteAck) + probeMock.expectMsg(WriteSent) shouldBe WriteSent redisWorkerIO ! "PING2" redisWorkerIO ! "PING3" probeTcpWorker.reply(WriteAck) - probeTcpWorker.expectMsgType[Write] mustEqual Write(ByteString("PING2PING3"), WriteAck) - probeMock.expectMsg(WriteSent) mustEqual WriteSent + probeTcpWorker.expectMsgType[Write] shouldBe Write(ByteString("PING2PING3"), WriteAck) + probeMock.expectMsg(WriteSent) shouldBe WriteSent redisWorkerIO ! "PING" probeTcpWorker.expectNoMessage(1 seconds) probeTcpWorker.send(redisWorkerIO, WriteAck) - probeTcpWorker.expectMsgType[Write] mustEqual Write(ByteString("PING"), WriteAck) - probeMock.expectMsg(WriteSent) mustEqual WriteSent + probeTcpWorker.expectMsgType[Write] shouldBe Write(ByteString("PING"), WriteAck) + probeMock.expectMsg(WriteSent) shouldBe WriteSent } "reconnect : connected <-> disconnected" in within(timeout){ @@ -86,32 +84,32 @@ class RedisWorkerIOSpec extends TestKit(ActorSystem()) with SpecificationLike wi redisWorkerIO ! "PING1" val connectMsg = probeTcp.expectMsgType[Connect] - connectMsg mustEqual Connect(address, options = SO.KeepAlive(on = true) :: Nil) + connectMsg shouldBe Connect(address, options = SO.KeepAlive(on = true) :: Nil) val probeTcpWorker = TestProbe() probeTcpWorker.send(redisWorkerIO, Connected(connectMsg.remoteAddress, address)) - probeTcpWorker.expectMsgType[Register] mustEqual Register(redisWorkerIO) + probeTcpWorker.expectMsgType[Register] shouldBe Register(redisWorkerIO) - probeTcpWorker.expectMsgType[Write] mustEqual Write(ByteString("PING1"), WriteAck) - probeMock.expectMsg(WriteSent) mustEqual WriteSent + probeTcpWorker.expectMsgType[Write] shouldBe Write(ByteString("PING1"), WriteAck) + probeMock.expectMsg(WriteSent) shouldBe WriteSent redisWorkerIO ! "PING 2" - awaitAssert(redisWorkerIO.underlyingActor.bufferWrite.result mustEqual ByteString("PING 2")) + awaitAssert(redisWorkerIO.underlyingActor.bufferWrite.result shouldBe ByteString("PING 2")) // ConnectionClosed probeTcpWorker.send(redisWorkerIO, ErrorClosed("test")) - probeMock.expectMsg(OnConnectionClosed) mustEqual OnConnectionClosed - awaitAssert(redisWorkerIO.underlyingActor.bufferWrite.length mustEqual 0) + probeMock.expectMsg(OnConnectionClosed) shouldBe OnConnectionClosed + awaitAssert(redisWorkerIO.underlyingActor.bufferWrite.length shouldBe 0) // Reconnect val connectMsg2 = probeTcp.expectMsgType[Connect] - connectMsg2 mustEqual Connect(address, options = SO.KeepAlive(on = true) :: Nil) + connectMsg2 shouldBe Connect(address, options = SO.KeepAlive(on = true) :: Nil) val probeTcpWorker2 = TestProbe() probeTcpWorker2.send(redisWorkerIO, Connected(connectMsg2.remoteAddress, address)) - probeTcpWorker2.expectMsgType[Register] mustEqual Register(redisWorkerIO) + probeTcpWorker2.expectMsgType[Register] shouldBe Register(redisWorkerIO) redisWorkerIO ! "PING1" - probeTcpWorker2.expectMsgType[Write] mustEqual Write(ByteString("PING1"), WriteAck) - probeMock.expectMsg(WriteSent) mustEqual WriteSent + probeTcpWorker2.expectMsgType[Write] shouldBe Write(ByteString("PING1"), WriteAck) + probeMock.expectMsg(WriteSent) shouldBe WriteSent } "onConnectedCommandFailed" in within(timeout){ @@ -123,18 +121,18 @@ class RedisWorkerIOSpec extends TestKit(ActorSystem()) with SpecificationLike wi redisWorkerIO ! "PING1" val connectMsg = probeTcp.expectMsgType[Connect] - connectMsg mustEqual Connect(address, options = SO.KeepAlive(on = true) :: Nil) + connectMsg shouldBe Connect(address, options = SO.KeepAlive(on = true) :: Nil) val probeTcpWorker = TestProbe() probeTcpWorker.send(redisWorkerIO, Connected(connectMsg.remoteAddress, address)) - probeTcpWorker.expectMsgType[Register] mustEqual Register(redisWorkerIO) + probeTcpWorker.expectMsgType[Register] shouldBe Register(redisWorkerIO) val msg = probeTcpWorker.expectMsgType[Write] - msg mustEqual Write(ByteString("PING1"), WriteAck) + msg shouldBe Write(ByteString("PING1"), WriteAck) probeTcpWorker.reply(CommandFailed(msg)) - probeTcpWorker.expectMsgType[Write] mustEqual Write(ByteString("PING1"), WriteAck) - probeMock.expectMsg(WriteSent) mustEqual WriteSent + probeTcpWorker.expectMsgType[Write] shouldBe Write(ByteString("PING1"), WriteAck) + probeMock.expectMsg(WriteSent) shouldBe WriteSent } "received" in within(timeout){ @@ -146,17 +144,17 @@ class RedisWorkerIOSpec extends TestKit(ActorSystem()) with SpecificationLike wi redisWorkerIO ! "PING1" val connectMsg = probeTcp.expectMsgType[Connect] - connectMsg mustEqual Connect(address, options = SO.KeepAlive(on = true) :: Nil) + connectMsg shouldBe Connect(address, options = SO.KeepAlive(on = true) :: Nil) val probeTcpWorker = TestProbe() probeTcpWorker.send(redisWorkerIO, Connected(connectMsg.remoteAddress, address)) - probeTcpWorker.expectMsgType[Register] mustEqual Register(redisWorkerIO) + probeTcpWorker.expectMsgType[Register] shouldBe Register(redisWorkerIO) - probeTcpWorker.expectMsgType[Write] mustEqual Write(ByteString("PING1"), WriteAck) - probeMock.expectMsg(WriteSent) mustEqual WriteSent + probeTcpWorker.expectMsgType[Write] shouldBe Write(ByteString("PING1"), WriteAck) + probeMock.expectMsg(WriteSent) shouldBe WriteSent probeTcpWorker.send(redisWorkerIO, Received(ByteString("PONG"))) - probeMock.expectMsgType[ByteString] mustEqual ByteString("PONG") + probeMock.expectMsgType[ByteString] shouldBe ByteString("PONG") } "Address Changed" in within(timeout){ @@ -168,47 +166,47 @@ class RedisWorkerIOSpec extends TestKit(ActorSystem()) with SpecificationLike wi redisWorkerIO ! "PING1" val connectMsg = probeTcp.expectMsgType[Connect] - connectMsg mustEqual Connect(address, options = SO.KeepAlive(on = true) :: Nil) + connectMsg shouldBe Connect(address, options = SO.KeepAlive(on = true) :: Nil) val probeTcpWorker = TestProbe() probeTcpWorker.send(redisWorkerIO, Connected(connectMsg.remoteAddress, address)) - probeTcpWorker.expectMsgType[Register] mustEqual Register(redisWorkerIO) + probeTcpWorker.expectMsgType[Register] shouldBe Register(redisWorkerIO) - probeTcpWorker.expectMsgType[Write] mustEqual Write(ByteString("PING1"), WriteAck) - probeMock.expectMsg(WriteSent) mustEqual WriteSent + probeTcpWorker.expectMsgType[Write] shouldBe Write(ByteString("PING1"), WriteAck) + probeMock.expectMsg(WriteSent) shouldBe WriteSent probeTcpWorker.reply(WriteAck) // change adresse val address2 = new InetSocketAddress("localhost", 6380) redisWorkerIO ! address2 - probeMock.expectMsg(OnConnectionClosed) mustEqual OnConnectionClosed + probeMock.expectMsg(OnConnectionClosed) shouldBe OnConnectionClosed redisWorkerIO ! "PING2" val connectMsg2 = probeTcp.expectMsgType[Connect] - connectMsg2 mustEqual Connect(address2, options = SO.KeepAlive(on = true) :: Nil) + connectMsg2 shouldBe Connect(address2, options = SO.KeepAlive(on = true) :: Nil) val probeTcpWorker2 = TestProbe() probeTcpWorker2.send(redisWorkerIO, Connected(connectMsg.remoteAddress, address)) - probeTcpWorker2.expectMsgType[Register] mustEqual Register(redisWorkerIO) + probeTcpWorker2.expectMsgType[Register] shouldBe Register(redisWorkerIO) - probeTcpWorker2.expectMsgType[Write] mustEqual Write(ByteString("PING2"), WriteAck) - probeMock.expectMsg(WriteSent) mustEqual WriteSent + probeTcpWorker2.expectMsgType[Write] shouldBe Write(ByteString("PING2"), WriteAck) + probeMock.expectMsg(WriteSent) shouldBe WriteSent probeTcpWorker2.reply(WriteAck) // receiving data on connection with the sending direction closed probeTcpWorker.send(redisWorkerIO, Received(ByteString("PONG1"))) - probeMock.expectMsg(DataReceivedOnClosingConnection) mustEqual DataReceivedOnClosingConnection + probeMock.expectMsg(DataReceivedOnClosingConnection) shouldBe DataReceivedOnClosingConnection // receiving data on open connection probeTcpWorker2.send(redisWorkerIO, Received(ByteString("PONG2"))) - probeMock.expectMsgType[ByteString] mustEqual ByteString("PONG2") + probeMock.expectMsgType[ByteString] shouldBe ByteString("PONG2") // close connection probeTcpWorker.send(redisWorkerIO, ConfirmedClosed) - probeMock.expectMsg(ClosingConnectionClosed) mustEqual ClosingConnectionClosed + probeMock.expectMsg(ClosingConnectionClosed) shouldBe ClosingConnectionClosed } "on connect write" in within(timeout){ @@ -220,33 +218,33 @@ class RedisWorkerIOSpec extends TestKit(ActorSystem()) with SpecificationLike wi val connectMsg = probeTcp.expectMsgType[Connect] - connectMsg mustEqual Connect(address, options = SO.KeepAlive(on = true) :: Nil) + connectMsg shouldBe Connect(address, options = SO.KeepAlive(on = true) :: Nil) val probeTcpWorker = TestProbe() probeTcpWorker.send(redisWorkerIO, Connected(connectMsg.remoteAddress, address)) - probeTcpWorker.expectMsgType[Register] mustEqual Register(redisWorkerIO) + probeTcpWorker.expectMsgType[Register] shouldBe Register(redisWorkerIO) - probeTcpWorker.expectMsgType[Write] mustEqual Write(onConnectByteString, WriteAck) - probeMock.expectMsg(WriteSent) mustEqual WriteSent + probeTcpWorker.expectMsgType[Write] shouldBe Write(onConnectByteString, WriteAck) + probeMock.expectMsg(WriteSent) shouldBe WriteSent redisWorkerIO ! "PING1" - awaitAssert(redisWorkerIO.underlyingActor.bufferWrite.result mustEqual ByteString("PING1")) + awaitAssert(redisWorkerIO.underlyingActor.bufferWrite.result shouldBe ByteString("PING1")) // ConnectionClosed probeTcpWorker.send(redisWorkerIO, ErrorClosed("test")) - probeMock.expectMsg(OnConnectionClosed) mustEqual OnConnectionClosed + probeMock.expectMsg(OnConnectionClosed) shouldBe OnConnectionClosed - awaitAssert(redisWorkerIO.underlyingActor.bufferWrite.length mustEqual 0) + awaitAssert(redisWorkerIO.underlyingActor.bufferWrite.length shouldBe 0) // Reconnect val connectMsg2 = probeTcp.expectMsgType[Connect] - connectMsg2 mustEqual Connect(address, options = SO.KeepAlive(on = true) :: Nil) + connectMsg2 shouldBe Connect(address, options = SO.KeepAlive(on = true) :: Nil) val probeTcpWorker2 = TestProbe() probeTcpWorker2.send(redisWorkerIO, Connected(connectMsg2.remoteAddress, address)) - probeTcpWorker2.expectMsgType[Register] mustEqual Register(redisWorkerIO) + probeTcpWorker2.expectMsgType[Register] shouldBe Register(redisWorkerIO) - probeTcpWorker2.expectMsgType[Write] mustEqual Write(onConnectByteString, WriteAck) - probeMock.expectMsg(WriteSent) mustEqual WriteSent + probeTcpWorker2.expectMsgType[Write] shouldBe Write(onConnectByteString, WriteAck) + probeMock.expectMsg(WriteSent) shouldBe WriteSent } } } diff --git a/src/test/scala/redis/commands/BListsSpec.scala b/src/test/scala/redis/commands/BListsSpec.scala index ea5f8ce4..0fdc4f09 100644 --- a/src/test/scala/redis/commands/BListsSpec.scala +++ b/src/test/scala/redis/commands/BListsSpec.scala @@ -8,132 +8,140 @@ import scala.concurrent.duration._ class BListsSpec extends RedisStandaloneServer { "Blocking Lists commands" should { - "BLPOP" in { - "already containing elements" in { - val redisB = RedisBlockingClient(port=port) - val r = for { - _ <- redis.del("blpop1", "blpop2") - p <- redis.rpush("blpop1", "a", "b", "c") - b <- redisB.blpop(Seq("blpop1", "blpop2")) - } yield { - b mustEqual Some("blpop1" -> ByteString("a")) - } - val rr = Await.result(r, timeOut) - redisB.stop() - rr + + "BLPOP already containing elements" in { + val redisB = RedisBlockingClient(port = port) + val r = for { + _ <- redis.del("blpop1", "blpop2") + p <- redis.rpush("blpop1", "a", "b", "c") + b <- redisB.blpop(Seq("blpop1", "blpop2")) + } yield { + b shouldBe Some("blpop1" -> ByteString("a")) } + val rr = Await.result(r, timeOut) + redisB.stop() + rr + } - "blocking" in { - val redisB = RedisBlockingClient(port=port) - val rr = within(1.seconds, 10.seconds) { - val r = redis.del("blpopBlock").flatMap(_ => { + "BLPOP blocking" in { + val redisB = RedisBlockingClient(port = port) + val rr = within(1.seconds, 10.seconds) { + val r = redis + .del("blpopBlock") + .flatMap(_ => { val blpop = redisB.blpop(Seq("blpopBlock")) Thread.sleep(1000) redis.rpush("blpopBlock", "a", "b", "c") blpop }) - Await.result(r, timeOut) mustEqual Some("blpopBlock" -> ByteString("a")) - } - redisB.stop() - rr + Await.result(r, timeOut) shouldBe Some("blpopBlock" -> ByteString("a")) } + redisB.stop() + rr + } - "blocking timeout" in { - val redisB = RedisBlockingClient(port=port) - val rr = within(1.seconds, 10.seconds) { - val r = redis.del("blpopBlockTimeout").flatMap(_ => { + "BLPOP blocking timeout" in { + val redisB = RedisBlockingClient(port = port) + val rr = within(1.seconds, 10.seconds) { + val r = redis + .del("blpopBlockTimeout") + .flatMap(_ => { redisB.brpop(Seq("blpopBlockTimeout"), 1.seconds) }) - Await.result(r, timeOut) must beNone - } - redisB.stop() - rr + Await.result(r, timeOut) shouldBe empty } + redisB.stop() + rr } - "BRPOP" in { - "already containing elements" in { - val redisB = RedisBlockingClient(port=port) - val r = for { - _ <- redis.del("brpop1", "brpop2") - p <- redis.rpush("brpop1", "a", "b", "c") - b <- redisB.brpop(Seq("brpop1", "brpop2")) - } yield { - redisB.stop() - b mustEqual Some("brpop1" -> ByteString("c")) - } - Await.result(r, timeOut) + "BRPOP already containing elements" in { + val redisB = RedisBlockingClient(port = port) + val r = for { + _ <- redis.del("brpop1", "brpop2") + p <- redis.rpush("brpop1", "a", "b", "c") + b <- redisB.brpop(Seq("brpop1", "brpop2")) + } yield { + redisB.stop() + b shouldBe Some("brpop1" -> ByteString("c")) } + Await.result(r, timeOut) + } - "blocking" in { - val redisB = RedisBlockingClient(port=port) - val rr = within(1.seconds, 10.seconds) { - val r = redis.del("brpopBlock").flatMap(_ => { + "BRPOP blocking" in { + val redisB = RedisBlockingClient(port = port) + val rr = within(1.seconds, 10.seconds) { + val r = redis + .del("brpopBlock") + .flatMap(_ => { val brpop = redisB.brpop(Seq("brpopBlock")) Thread.sleep(1000) redis.rpush("brpopBlock", "a", "b", "c") brpop }) - Await.result(r, timeOut) mustEqual Some("brpopBlock" -> ByteString("c")) - } - redisB.stop() - rr + Await.result(r, timeOut) shouldBe Some("brpopBlock" -> ByteString("c")) } + redisB.stop() + rr + } - "blocking timeout" in { - val redisB = RedisBlockingClient(port=port) - val rr = within(1.seconds, 10.seconds) { - val r = redis.del("brpopBlockTimeout").flatMap(_ => { + "BRPOP blocking timeout" in { + val redisB = RedisBlockingClient(port = port) + val rr = within(1.seconds, 10.seconds) { + val r = redis + .del("brpopBlockTimeout") + .flatMap(_ => { redisB.brpop(Seq("brpopBlockTimeout"), 1.seconds) }) - Await.result(r, timeOut) must beNone - } - redisB.stop() - rr + Await.result(r, timeOut) shouldBe empty } + redisB.stop() + rr } - "BRPOPLPUSH" in { - "already containing elements" in { - val redisB = RedisBlockingClient(port=port) - val r = for { - _ <- redis.del("brpopplush1", "brpopplush2") - p <- redis.rpush("brpopplush1", "a", "b", "c") - b <- redisB.brpoplpush("brpopplush1", "brpopplush2") - } yield { - b mustEqual Some(ByteString("c")) - } - val rr = Await.result(r, timeOut) - redisB.stop() - rr + "BRPOPLPUSH already containing elements" in { + val redisB = RedisBlockingClient(port = port) + val r = for { + _ <- redis.del("brpopplush1", "brpopplush2") + p <- redis.rpush("brpopplush1", "a", "b", "c") + b <- redisB.brpoplpush("brpopplush1", "brpopplush2") + } yield { + b shouldBe Some(ByteString("c")) } + val rr = Await.result(r, timeOut) + redisB.stop() + rr + } - "blocking" in { - val redisB = RedisBlockingClient(port=port) - val rr = within(1.seconds, 10.seconds) { - val r = redis.del("brpopplushBlock1", "brpopplushBlock2").flatMap(_ => { + "BRPOPLPUSH blocking" in { + val redisB = RedisBlockingClient(port = port) + val rr = within(1.seconds, 10.seconds) { + val r = redis + .del("brpopplushBlock1", "brpopplushBlock2") + .flatMap(_ => { val brpopplush = redisB.brpoplpush("brpopplushBlock1", "brpopplushBlock2") Thread.sleep(1000) redis.rpush("brpopplushBlock1", "a", "b", "c") brpopplush }) - Await.result(r, timeOut) mustEqual Some(ByteString("c")) - } - redisB.stop() - rr + Await.result(r, timeOut) shouldBe Some(ByteString("c")) } + redisB.stop() + rr + } - "blocking timeout" in { - val redisB = RedisBlockingClient(port=port) - val rr = within(1.seconds, 10.seconds) { - val r = redis.del("brpopplushBlockTimeout1", "brpopplushBlockTimeout2").flatMap(_ => { + "BRPOPLPUSH blocking timeout" in { + val redisB = RedisBlockingClient(port = port) + val rr = within(1.seconds, 10.seconds) { + val r = redis + .del("brpopplushBlockTimeout1", "brpopplushBlockTimeout2") + .flatMap(_ => { redisB.brpoplpush("brpopplushBlockTimeout1", "brpopplushBlockTimeout2", 1.seconds) }) - Await.result(r, timeOut) must beNone - } - redisB.stop() - rr + Await.result(r, timeOut) shouldBe empty } + redisB.stop() + rr } + } } diff --git a/src/test/scala/redis/commands/ConnectionSpec.scala b/src/test/scala/redis/commands/ConnectionSpec.scala index 103c28ba..56eb9875 100644 --- a/src/test/scala/redis/commands/ConnectionSpec.scala +++ b/src/test/scala/redis/commands/ConnectionSpec.scala @@ -7,32 +7,30 @@ import redis.actors.ReplyErrorException class ConnectionSpec extends RedisStandaloneServer { - sequential - "Connection commands" should { "AUTH" in { - Await.result(redis.auth("no password"), timeOut) must throwA[ReplyErrorException]("ERR Client sent AUTH, but no password is set") + a[ReplyErrorException] should be thrownBy Await.result(redis.auth("no password"), timeOut) } "ECHO" in { val hello = "Hello World!" - Await.result(redis.echo(hello), timeOut) mustEqual Some(ByteString(hello)) + Await.result(redis.echo(hello), timeOut) shouldBe Some(ByteString(hello)) } "PING" in { - Await.result(redis.ping(), timeOut) mustEqual "PONG" + Await.result(redis.ping(), timeOut) shouldBe "PONG" } "QUIT" in { // todo test that the TCP connection is reset. val f = redis.quit() Thread.sleep(1000) val ping = redis.ping() - Await.result(f, timeOut) mustEqual true - Await.result(ping, timeOut) mustEqual "PONG" + Await.result(f, timeOut) shouldBe true + Await.result(ping, timeOut) shouldBe "PONG" } "SELECT" in { - Await.result(redis.select(1), timeOut) mustEqual true - Await.result(redis.select(0), timeOut) mustEqual true - Await.result(redis.select(-1), timeOut) must throwA[ReplyErrorException]("ERR DB index is out of range") - Await.result(redis.select(1000), timeOut) must throwA[ReplyErrorException]("ERR DB index is out of range") + Await.result(redis.select(1), timeOut) shouldBe true + Await.result(redis.select(0), timeOut) shouldBe true + a[ReplyErrorException] should be thrownBy Await.result(redis.select(-1), timeOut) + a[ReplyErrorException] should be thrownBy Await.result(redis.select(1000), timeOut) } } } diff --git a/src/test/scala/redis/commands/GeoSpec.scala b/src/test/scala/redis/commands/GeoSpec.scala index 1efa07ab..31556491 100644 --- a/src/test/scala/redis/commands/GeoSpec.scala +++ b/src/test/scala/redis/commands/GeoSpec.scala @@ -4,7 +4,7 @@ import redis._ import redis.api.geo.DistUnits._ import scala.concurrent.Await -class GeoSpec extends RedisStandaloneServer { +class GeoSpec extends RedisStandaloneServer { import concurrent.duration._ val testKey = "Sicily" @@ -19,20 +19,21 @@ class GeoSpec extends RedisStandaloneServer { "Geo commands " should { "GEOADD add key member" in { - val res = Await.result(redis.geoAdd(testKey, 23.361389, 48.115556, "SomePlace"), 2 second) + val res = Await.result(redis.geoAdd(testKey, 23.361389, 48.115556, "SomePlace"), 2 second) res shouldEqual 1 } - "GEORADIUS By Member" in { + "GEORADIUS" in { addPlaces() - val res = Await.result(redis.geoRadius(testKey,15 , 37, 200, Kilometer), 2 second) - res shouldEqual Vector("Agrigento","Catania") + redis.geoRadius(testKey, 15, 37, 200, Kilometer).futureValue shouldEqual Vector("Agrigento", "Catania") } "GEORADIUS By Member" in { addPlaces() - val res = Await.result(redis.geoRadiusByMember(testKey, "Catania", 500, Kilometer), 2 second) - res shouldEqual Vector("Agrigento" ,"Palermo","Catania") + redis.geoRadiusByMember(testKey, "Catania", 500, Kilometer).futureValue shouldEqual Vector( + "Agrigento", + "Palermo", + "Catania") } "GEORADIUS By Member with opt" in { @@ -74,7 +75,7 @@ class GeoSpec extends RedisStandaloneServer { "GEOPOS " in { addPlaces() val res = Await.result(redis.geoPos(testKey, "Palermo", "Catania"), 2 seconds) - res shouldNotEqual Nil + res should not be empty } } } diff --git a/src/test/scala/redis/commands/HashesSpec.scala b/src/test/scala/redis/commands/HashesSpec.scala index 822a8f6c..6ce832e8 100644 --- a/src/test/scala/redis/commands/HashesSpec.scala +++ b/src/test/scala/redis/commands/HashesSpec.scala @@ -12,7 +12,7 @@ class HashesSpec extends RedisStandaloneServer { _ <- redis.hset("hdelKey", "field", "value") d <- redis.hdel("hdelKey", "field", "fieldNonexisting") } yield { - d mustEqual 1 + d shouldBe 1 } Await.result(r, timeOut) } @@ -23,8 +23,8 @@ class HashesSpec extends RedisStandaloneServer { exist <- redis.hexists("hexistsKey", "field") notExist <- redis.hexists("hexistsKey", "fieldNotExisting") } yield { - exist mustEqual true - notExist mustEqual false + exist shouldBe true + notExist shouldBe false } Await.result(r, timeOut) } @@ -35,8 +35,8 @@ class HashesSpec extends RedisStandaloneServer { get <- redis.hget("hgetKey", "field") get2 <- redis.hget("hgetKey", "fieldNotExisting") } yield { - get mustEqual Some(ByteString("value")) - get2 mustEqual None + get shouldBe Some(ByteString("value")) + get2 shouldBe None } Await.result(r, timeOut) } @@ -47,8 +47,8 @@ class HashesSpec extends RedisStandaloneServer { get <- redis.hgetall("hgetallKey") get2 <- redis.hgetall("hgetallKeyNotExisting") } yield { - get mustEqual Map("field" -> ByteString("value")) - get2 mustEqual Map.empty + get shouldBe Map("field" -> ByteString("value")) + get2 shouldBe Map.empty } Await.result(r, timeOut) } @@ -59,8 +59,8 @@ class HashesSpec extends RedisStandaloneServer { i <- redis.hincrby("hincrbyKey", "field", 1) ii <- redis.hincrby("hincrbyKey", "field", -1) } yield { - i mustEqual 11 - ii mustEqual 10 + i shouldBe 11 + ii shouldBe 10 } Await.result(r, timeOut) } @@ -71,8 +71,8 @@ class HashesSpec extends RedisStandaloneServer { i <- redis.hincrbyfloat("hincrbyfloatKey", "field", 0.1) ii <- redis.hincrbyfloat("hincrbyfloatKey", "field", -1.1) } yield { - i mustEqual 10.6 - ii mustEqual 9.5 + i shouldBe 10.6 + ii shouldBe 9.5 } Await.result(r, timeOut) } @@ -82,7 +82,7 @@ class HashesSpec extends RedisStandaloneServer { _ <- redis.hset("hkeysKey", "field", "value") keys <- redis.hkeys("hkeysKey") } yield { - keys mustEqual Seq("field") + keys shouldBe Seq("field") } Await.result(r, timeOut) } @@ -92,7 +92,7 @@ class HashesSpec extends RedisStandaloneServer { _ <- redis.hset("hlenKey", "field", "value") hLength <- redis.hlen("hlenKey") } yield { - hLength mustEqual 1 + hLength shouldBe 1 } Await.result(r, timeOut) } @@ -102,7 +102,7 @@ class HashesSpec extends RedisStandaloneServer { _ <- redis.hset("hmgetKey", "field", "value") hmget <- redis.hmget("hmgetKey", "field", "nofield") } yield { - hmget mustEqual Seq(Some(ByteString("value")), None) + hmget shouldBe Seq(Some(ByteString("value")), None) } Await.result(r, timeOut) } @@ -113,22 +113,22 @@ class HashesSpec extends RedisStandaloneServer { v1 <- redis.hget("hmsetKey", "field") v2 <- redis.hget("hmsetKey", "field2") } yield { - v1 mustEqual Some(ByteString("value1")) - v2 mustEqual Some(ByteString("value2")) + v1 shouldBe Some(ByteString("value1")) + v2 shouldBe Some(ByteString("value2")) } Await.result(r, timeOut) } - "HMSET" in { + "HMSET update" in { val r = for { _ <- redis.hdel("hsetKey", "field") set <- redis.hset("hsetKey", "field", "value") update <- redis.hset("hsetKey", "field", "value2") v1 <- redis.hget("hsetKey", "field") } yield { - set mustEqual true - update mustEqual false - v1 mustEqual Some(ByteString("value2")) + set shouldBe true + update shouldBe false + v1 shouldBe Some(ByteString("value2")) } Await.result(r, timeOut) } @@ -140,9 +140,9 @@ class HashesSpec extends RedisStandaloneServer { doNothing <- redis.hsetnx("hsetnxKey", "field", "value2") v1 <- redis.hget("hsetnxKey", "field") } yield { - set mustEqual true - doNothing mustEqual false - v1 mustEqual Some(ByteString("value")) + set shouldBe true + doNothing shouldBe false + v1 shouldBe Some(ByteString("value")) } Await.result(r, timeOut) } @@ -154,8 +154,8 @@ class HashesSpec extends RedisStandaloneServer { _ <- redis.hmset("hscan", initialData) scanResult <- redis.hscan[String]("hscan", count = Some(300)) } yield { - scanResult.data.values.toList.map(_.toInt).sorted mustEqual (2 to 20 by 2) - scanResult.index mustEqual 0 + scanResult.data.values.toList.map(_.toInt).sorted shouldBe (2 to 20 by 2) + scanResult.index shouldBe 0 } Await.result(r, timeOut) } @@ -163,12 +163,12 @@ class HashesSpec extends RedisStandaloneServer { "HVALS" in { val r = for { _ <- redis.hdel("hvalsKey", "field") - empty <- redis.hvals("hvalsKey") + emp <- redis.hvals("hvalsKey") _ <- redis.hset("hvalsKey", "field", "value") some <- redis.hvals("hvalsKey") } yield { - empty must beEmpty - some mustEqual Seq(ByteString("value")) + emp shouldBe empty + some shouldBe Seq(ByteString("value")) } Await.result(r, timeOut) } diff --git a/src/test/scala/redis/commands/HyperLogLogSpec.scala b/src/test/scala/redis/commands/HyperLogLogSpec.scala index e40d6109..f0a244f9 100644 --- a/src/test/scala/redis/commands/HyperLogLogSpec.scala +++ b/src/test/scala/redis/commands/HyperLogLogSpec.scala @@ -6,39 +6,38 @@ import scala.concurrent.Await class HyperLogLogSpec extends RedisStandaloneServer { - sequential "HyperLogLog commands" should { "PFADD" in { val r = redis.pfadd("hll", "a", "b", "c", "d", "e", "f", "g").flatMap(_ => { redis.pfcount("hll").flatMap(count => { - count mustEqual 7 + count shouldBe 7 redis.pfadd("hll", "h", "i").flatMap(_ ⇒ { redis.pfcount("hll") }) }) }) - Await.result(r, timeOut) mustEqual 9 + Await.result(r, timeOut) shouldBe 9 } "PFCOUNT" in { val r = redis.pfadd("hll2", "a", "b", "c", "d", "e", "f", "g").flatMap(_ => { redis.pfcount("hll2") }) - Await.result(r, timeOut) mustEqual 7 + Await.result(r, timeOut) shouldBe 7 } "PFMERGE" in { val r = redis.pfadd("hll3", "a", "b").flatMap(_ ⇒ { redis.pfadd("hll4", "c", "d").flatMap(_ ⇒ { redis.pfmerge("hll5", "hll4", "hll3").flatMap(merged ⇒ { - merged mustEqual true + merged shouldBe true redis.pfcount("hll5") }) }) }) - Await.result(r, timeOut) mustEqual 4 + Await.result(r, timeOut) shouldBe 4 } } } diff --git a/src/test/scala/redis/commands/KeysSpec.scala b/src/test/scala/redis/commands/KeysSpec.scala index b35c4ba3..13a7092e 100644 --- a/src/test/scala/redis/commands/KeysSpec.scala +++ b/src/test/scala/redis/commands/KeysSpec.scala @@ -16,8 +16,8 @@ class KeysSpec extends RedisStandaloneServer { s <- redis.set("delKey", "value") d <- redis.del("delKey", "delKeyNonexisting") } yield { - s mustEqual true - d mustEqual 1 + s shouldBe true + d shouldBe 1 } Await.result(r, timeOut) } @@ -32,8 +32,8 @@ class KeysSpec extends RedisStandaloneServer { rs <- redis.restore(k, serializedValue = d.get) value <- redis.get[String](k) } yield { - s mustEqual true - rs mustEqual true + s shouldBe true + rs shouldBe true } Await.result(r, timeOut) } @@ -44,9 +44,9 @@ class KeysSpec extends RedisStandaloneServer { e <- redis.exists("existsKey") e2 <- redis.exists("existsKeyNonexisting") } yield { - s mustEqual true - e mustEqual true - e2 mustEqual false + s shouldBe true + e shouldBe true + e2 shouldBe false } Await.result(r, timeOut) } @@ -57,9 +57,9 @@ class KeysSpec extends RedisStandaloneServer { e <- redis.existsMany("existsKey", "existsKeyNonexisting") e2 <- redis.existsMany("existsKeyNonexisting") } yield { - s mustEqual true - e mustEqual 1 - e2 mustEqual 0 + s shouldBe true + e shouldBe 1 + e2 shouldBe 0 } Await.result(r, timeOut) } @@ -74,10 +74,10 @@ class KeysSpec extends RedisStandaloneServer { redis.get("expireKey") } } yield { - s mustEqual true - e mustEqual true - e2 mustEqual false - expired mustEqual None + s shouldBe true + e shouldBe true + e2 shouldBe false + expired shouldBe None } Await.result(r, timeOut) } @@ -88,9 +88,9 @@ class KeysSpec extends RedisStandaloneServer { e <- redis.expireat("expireatKey", System.currentTimeMillis() / 1000) expired <- redis.get("expireatKey") } yield { - s mustEqual true - e mustEqual true - expired mustEqual None + s shouldBe true + e shouldBe true + expired shouldBe None } Await.result(r, timeOut) } @@ -103,9 +103,9 @@ class KeysSpec extends RedisStandaloneServer { k2 <- redis.keys("keysKey?") k3 <- redis.keys("keysKeyNomatch") } yield { - k must containTheSameElementsAs(Seq("keysKey2", "keysKey")) - k2 must containTheSameElementsAs(Seq("keysKey2")) - k3 must beEmpty + k should contain theSameElementsAs(Seq("keysKey2", "keysKey")) + k2 should contain theSameElementsAs(Seq("keysKey2")) + k3 shouldBe empty } Await.result(r, timeOut) } @@ -121,8 +121,8 @@ class KeysSpec extends RedisStandaloneServer { m <- redis.migrate("localhost", port, key, 0, 10 seconds) get <- redisMigrate.get(key) } yield { - m must beTrue - get mustEqual Some(ByteString("value")) + m shouldBe true + get shouldBe Some(ByteString("value")) } Await.result(r, timeOut) }) @@ -139,23 +139,22 @@ class KeysSpec extends RedisStandaloneServer { get <- redisMove.get("moveKey") get2 <- redisMove.get("moveKey2") } yield { - move must beTrue - move2 must beFalse - get mustEqual Some(ByteString("value")) - get2 mustEqual None + move shouldBe true + move2 shouldBe false + get shouldBe Some(ByteString("value")) + get2 shouldBe None } Await.result(r, timeOut) } - "OBJECT" in { "REFCOUNT" in { val r = for { _ <- redis.set("objectRefcount", "objectRefcountValue") ref <- redis.objectRefcount("objectRefcount") refNotFound <- redis.objectRefcount("objectRefcountNotFound") } yield { - ref must beSome(1) - refNotFound must beNone + ref shouldBe Some(1) + refNotFound shouldBe empty } Await.result(r, timeOut) } @@ -165,8 +164,8 @@ class KeysSpec extends RedisStandaloneServer { time <- redis.objectIdletime("objectIdletime") timeNotFound <- redis.objectIdletime("objectIdletimeNotFound") } yield { - time must beSome[Long] - timeNotFound must beNone + time shouldBe defined + timeNotFound shouldBe empty } Await.result(r, timeOut) } @@ -176,12 +175,11 @@ class KeysSpec extends RedisStandaloneServer { encoding <- redis.objectEncoding("objectEncoding") encodingNotFound <- redis.objectEncoding("objectEncodingNotFound") } yield { - encoding must beSome[String] - encodingNotFound must beNone + encoding shouldBe defined + encodingNotFound shouldBe empty } Await.result(r, timeOut) } - } "PERSIST" in { val r = for { @@ -191,11 +189,11 @@ class KeysSpec extends RedisStandaloneServer { p <- redis.persist("persistKey") ttl2 <- redis.ttl("persistKey") } yield { - s mustEqual true - e mustEqual true - ttl.toInt must beBetween(1, 10) - p mustEqual true - ttl2 mustEqual -1 + s shouldBe true + e shouldBe true + ttl.toInt should beBetween(1, 10) + p shouldBe true + ttl2 shouldBe -1 } Await.result(r, timeOut) } @@ -210,10 +208,10 @@ class KeysSpec extends RedisStandaloneServer { redis.get("pexpireKey") } } yield { - s mustEqual true - e mustEqual true - e2 mustEqual false - expired mustEqual None + s shouldBe true + e shouldBe true + e2 shouldBe false + expired shouldBe None } Await.result(r, timeOut) } @@ -224,33 +222,33 @@ class KeysSpec extends RedisStandaloneServer { e <- redis.pexpireat("pexpireatKey", System.currentTimeMillis()) expired <- redis.get("pexpireatKey") } yield { - s mustEqual true - e mustEqual true - expired mustEqual None + s shouldBe true + e shouldBe true + expired shouldBe None } Await.result(r, timeOut) } - "PEXPIREAT" in { + "PEXPIREAT TTL" in { val r = for { s <- redis.set("pttlKey", "value") e <- redis.expire("pttlKey", 1) pttl <- redis.pttl("pttlKey") } yield { - s mustEqual true - e mustEqual true - pttl.toInt must beBetween(1, 1000) + s shouldBe true + e shouldBe true + pttl.toInt should beBetween(1, 1000) } Await.result(r, timeOut) } "RANDOMKEY" in { val r = for { - s <- redis.set("randomKey", "value") // could fail if database was empty + _ <- redis.set("randomKey", "value") // could fail if database was empty s <- redis.randomkey() } yield { - s must beSome + s shouldBe defined } Await.result(r, timeOut) } @@ -262,9 +260,9 @@ class KeysSpec extends RedisStandaloneServer { rename <- redis.rename("renameKey", "renameNewKey") renamedValue <- redis.get("renameNewKey") } yield { - s mustEqual true - rename mustEqual true - renamedValue mustEqual Some(ByteString("value")) + s shouldBe true + rename shouldBe true + renamedValue shouldBe Some(ByteString("value")) } Await.result(r, timeOut) } @@ -279,10 +277,10 @@ class KeysSpec extends RedisStandaloneServer { rename2 <- redis.renamenx("renamenxKey", "renamenxNewKey") renamedValue <- redis.get("renamenxNewKey") } yield { - s mustEqual true - rename mustEqual false - rename2 mustEqual true - renamedValue mustEqual Some(ByteString("value")) + s shouldBe true + rename shouldBe false + rename2 shouldBe true + renamedValue shouldBe Some(ByteString("value")) } Await.result(r, timeOut) } @@ -298,8 +296,8 @@ class KeysSpec extends RedisStandaloneServer { restore <- redis.restore(k, serializedValue = dump.get) restored <- redis.get[String](k) } yield { - restore mustEqual true - restored mustEqual Some(v) + restore shouldBe true + restored shouldBe Some(v) } Await.result(r, timeOut) } @@ -316,8 +314,8 @@ class KeysSpec extends RedisStandaloneServer { _ <- scanRedis.set("scanKey3", "value3") result <- scanRedis.scan(count = Some(1000)) } yield { - result.index mustEqual 0 - result.data.sorted mustEqual Seq("scanKey1", "scanKey2", "scanKey3") + result.index shouldBe 0 + result.data.sorted shouldBe Seq("scanKey1", "scanKey2", "scanKey3") } Await.result(r, timeOut) }) @@ -350,17 +348,17 @@ class KeysSpec extends RedisStandaloneServer { b6 <- redis.sort("bond_ids", Some("bonds|*->bid_price")) b7 <- redis.sortStore("bond_ids", Some("bonds|*->ask_price"), store = "bond_ids_sorted_by_ask_price") } yield { - sort mustEqual Seq(ByteString("1"), ByteString("2")) - sortDesc mustEqual Seq(ByteString("2"), ByteString("1")) - sortAlpha mustEqual Seq(ByteString("abc"), ByteString("xyz")) - sortLimit mustEqual Seq(ByteString("1")) - b1 mustEqual Seq(ByteString("2"), ByteString("1")) - b2 mustEqual Seq(ByteString("95.5"), ByteString("96.01")) - b3 mustEqual Seq(ByteString("95.5"), ByteString("2"), ByteString("96.01"), ByteString("1")) - b4 mustEqual Seq(ByteString("2")) - b5 mustEqual Seq(ByteString("1"), ByteString("2")) - b6 mustEqual Seq(ByteString("2"), ByteString("1")) - b7 mustEqual 2 + sort shouldBe Seq(ByteString("1"), ByteString("2")) + sortDesc shouldBe Seq(ByteString("2"), ByteString("1")) + sortAlpha shouldBe Seq(ByteString("abc"), ByteString("xyz")) + sortLimit shouldBe Seq(ByteString("1")) + b1 shouldBe Seq(ByteString("2"), ByteString("1")) + b2 shouldBe Seq(ByteString("95.5"), ByteString("96.01")) + b3 shouldBe Seq(ByteString("95.5"), ByteString("2"), ByteString("96.01"), ByteString("1")) + b4 shouldBe Seq(ByteString("2")) + b5 shouldBe Seq(ByteString("1"), ByteString("2")) + b6 shouldBe Seq(ByteString("2"), ByteString("1")) + b7 shouldBe 2 } Await.result(r, timeOut) } @@ -371,9 +369,10 @@ class KeysSpec extends RedisStandaloneServer { e <- redis.expire("ttlKey", 10) ttl <- redis.ttl("ttlKey") } yield { - s mustEqual true - e mustEqual true - ttl.toInt must beBetween(1, 10) + s shouldBe true + e shouldBe true + ttl should be >= 1L + ttl.toInt should beBetween(1, 10) } Await.result(r, timeOut) } @@ -384,9 +383,9 @@ class KeysSpec extends RedisStandaloneServer { _type <- redis.`type`("typeKey") _typeNone <- redis.`type`("typeKeyNonExisting") } yield { - s mustEqual true - _type mustEqual "string" - _typeNone mustEqual "none" + s shouldBe true + _type shouldBe "string" + _typeNone shouldBe "none" } Await.result(r, timeOut) } diff --git a/src/test/scala/redis/commands/ListsSpec.scala b/src/test/scala/redis/commands/ListsSpec.scala index 133302c9..8548da6c 100644 --- a/src/test/scala/redis/commands/ListsSpec.scala +++ b/src/test/scala/redis/commands/ListsSpec.scala @@ -17,9 +17,9 @@ class ListsSpec extends RedisStandaloneServer { world <- redis.lindex("lindexKey", 1) none <- redis.lindex("lindexKey", 2) } yield { - hello mustEqual Some(ByteString("Hello")) - world mustEqual Some(ByteString("World")) - none mustEqual None + hello shouldBe Some(ByteString("Hello")) + world shouldBe Some(ByteString("World")) + none shouldBe None } Await.result(r, timeOut) } @@ -33,10 +33,10 @@ class ListsSpec extends RedisStandaloneServer { length4 <- redis.linsertAfter("linsertKey", "World", "!!!") list4 <- redis.lrange("linsertKey", 0, -1) } yield { - length mustEqual 3 - list mustEqual Seq(ByteString("Hello"), ByteString("There"), ByteString("World")) - length4 mustEqual 4 - list4 mustEqual Seq(ByteString("Hello"), ByteString("There"), ByteString("World"), ByteString("!!!")) + length shouldBe 3 + list shouldBe Seq(ByteString("Hello"), ByteString("There"), ByteString("World")) + length4 shouldBe 4 + list4 shouldBe Seq(ByteString("Hello"), ByteString("There"), ByteString("World"), ByteString("!!!")) } Await.result(r, timeOut) } @@ -47,7 +47,7 @@ class ListsSpec extends RedisStandaloneServer { _ <- redis.lpush("llenKey", "World", "Hello") length <- redis.llen("llenKey") } yield { - length mustEqual 2 + length shouldBe 2 } Await.result(r, timeOut) } @@ -58,7 +58,7 @@ class ListsSpec extends RedisStandaloneServer { _ <- redis.rpush("lpopKey", "one", "two", "three") e <- redis.lpop("lpopKey") } yield { - e mustEqual Some(ByteString("one")) + e shouldBe Some(ByteString("one")) } Await.result(r, timeOut) } @@ -69,7 +69,7 @@ class ListsSpec extends RedisStandaloneServer { _ <- redis.lpush("lpushKey", "World", "Hello") list <- redis.lrange("lpushKey", 0, -1) } yield { - list mustEqual Seq(ByteString("Hello"), ByteString("World")) + list shouldBe Seq(ByteString("Hello"), ByteString("World")) } Await.result(r, timeOut) } @@ -84,11 +84,11 @@ class ListsSpec extends RedisStandaloneServer { list <- redis.lrange("lpushxKey", 0, -1) listOther <- redis.lrange("lpushxKeyOther", 0, -1) } yield { - i mustEqual 1 - ii mustEqual 2 - zero mustEqual 0 - list mustEqual Seq(ByteString("hello"), ByteString("world")) - listOther must beEmpty + i shouldBe 1 + ii shouldBe 2 + zero shouldBe 0 + list shouldBe Seq(ByteString("hello"), ByteString("world")) + listOther shouldBe empty } Await.result(r, timeOut) } @@ -102,10 +102,10 @@ class ListsSpec extends RedisStandaloneServer { list3 <- redis.lrange("lrangeKey", 5, 10) nonExisting <- redis.lrange("lrangeKeyNonexisting", 5, 10) } yield { - list mustEqual Seq(ByteString("one")) - list2 mustEqual Seq(ByteString("one"), ByteString("two"), ByteString("three")) - list3 must beEmpty - nonExisting must beEmpty + list shouldBe Seq(ByteString("one")) + list2 shouldBe Seq(ByteString("one"), ByteString("two"), ByteString("three")) + list3 shouldBe empty + nonExisting shouldBe empty } Await.result(r, timeOut) } @@ -117,8 +117,8 @@ class ListsSpec extends RedisStandaloneServer { lrem <- redis.lrem("lremKey", -2, "hello") list2 <- redis.lrange("lremKey", 0, -1) } yield { - lrem mustEqual 2 - list2 mustEqual Seq(ByteString("hello"), ByteString("foo")) + lrem shouldBe 2 + list2 shouldBe Seq(ByteString("hello"), ByteString("foo")) } Await.result(r, timeOut) } @@ -131,9 +131,9 @@ class ListsSpec extends RedisStandaloneServer { lset2 <- redis.lset("lsetKey", -2, "five") list <- redis.lrange("lsetKey", 0, -1) } yield { - lset1 mustEqual true - lset2 mustEqual true - list mustEqual Seq(ByteString("four"), ByteString("five"), ByteString("three")) + lset1 shouldBe true + lset2 shouldBe true + list shouldBe Seq(ByteString("four"), ByteString("five"), ByteString("three")) } Await.result(r, timeOut) } @@ -145,8 +145,8 @@ class ListsSpec extends RedisStandaloneServer { ltrim <- redis.ltrim("ltrimKey", 1, -1) list <- redis.lrange("ltrimKey", 0, -1) } yield { - ltrim mustEqual true - list mustEqual Seq(ByteString("two"), ByteString("three")) + ltrim shouldBe true + list shouldBe Seq(ByteString("two"), ByteString("three")) } Await.result(r, timeOut) } @@ -158,8 +158,8 @@ class ListsSpec extends RedisStandaloneServer { rpop <- redis.rpop("rpopKey") list <- redis.lrange("rpopKey", 0, -1) } yield { - rpop mustEqual Some(ByteString("three")) - list mustEqual Seq(ByteString("one"), ByteString("two")) + rpop shouldBe Some(ByteString("three")) + list shouldBe Seq(ByteString("one"), ByteString("two")) } Await.result(r, timeOut) } @@ -173,9 +173,9 @@ class ListsSpec extends RedisStandaloneServer { list <- redis.lrange("rpoplpushKey", 0, -1) listOther <- redis.lrange("rpoplpushKeyOther", 0, -1) } yield { - rpoplpush mustEqual Some(ByteString("three")) - list mustEqual Seq(ByteString("one"), ByteString("two")) - listOther mustEqual Seq(ByteString("three")) + rpoplpush shouldBe Some(ByteString("three")) + list shouldBe Seq(ByteString("one"), ByteString("two")) + listOther shouldBe Seq(ByteString("three")) } Await.result(r, timeOut) } @@ -187,9 +187,9 @@ class ListsSpec extends RedisStandaloneServer { ii <- redis.rpush("rpushKey", "world") list <- redis.lrange("rpushKey", 0, -1) } yield { - i mustEqual 1 - ii mustEqual 2 - list mustEqual Seq(ByteString("hello"), ByteString("world")) + i shouldBe 1 + ii shouldBe 2 + list shouldBe Seq(ByteString("hello"), ByteString("world")) } Await.result(r, timeOut) } @@ -204,11 +204,11 @@ class ListsSpec extends RedisStandaloneServer { list <- redis.lrange("rpushxKey", 0, -1) listOther <- redis.lrange("rpushxKeyOther", 0, -1) } yield { - i mustEqual 1 - ii mustEqual 2 - zero mustEqual 0 - list mustEqual Seq(ByteString("hello"), ByteString("world")) - listOther must beEmpty + i shouldBe 1 + ii shouldBe 2 + zero shouldBe 0 + list shouldBe Seq(ByteString("hello"), ByteString("world")) + listOther shouldBe empty } Await.result(r, timeOut) } diff --git a/src/test/scala/redis/commands/ScriptingSpec.scala b/src/test/scala/redis/commands/ScriptingSpec.scala index 39a2bd49..5df82071 100644 --- a/src/test/scala/redis/commands/ScriptingSpec.scala +++ b/src/test/scala/redis/commands/ScriptingSpec.scala @@ -6,14 +6,11 @@ import redis._ import scala.concurrent.Await import akka.util.ByteString -import org.specs2.concurrent.ExecutionEnv import redis.protocol.{Bulk, MultiBulk} import redis.actors.ReplyErrorException import redis.api.scripting.RedisScript -class ScriptingSpec(implicit ee: ExecutionEnv) extends RedisStandaloneServer { - - sequential +class ScriptingSpec extends RedisStandaloneServer { "Scripting commands" should { val redisScript = RedisScript("return 'rediscala'") @@ -21,13 +18,13 @@ class ScriptingSpec(implicit ee: ExecutionEnv) extends RedisStandaloneServer { val redisScriptConversionObject = RedisScript("return redis.call('get', 'dumbKey')") "evalshaOrEval (RedisScript)" in { - Await.result(redis.scriptFlush(), timeOut) must beTrue + Await.result(redis.scriptFlush(), timeOut) shouldBe true val r = Await.result(redis.evalshaOrEval(redisScriptKeysArgs, Seq("key"), Seq("arg")), timeOut) - r mustEqual MultiBulk(Some(Vector(Bulk(Some(ByteString("key"))), Bulk(Some(ByteString("arg")))))) + r shouldBe MultiBulk(Some(Vector(Bulk(Some(ByteString("key"))), Bulk(Some(ByteString("arg")))))) } "EVAL" in { - Await.result(redis.eval(redisScript.script), timeOut) mustEqual Bulk(Some(ByteString("rediscala"))) + Await.result(redis.eval(redisScript.script), timeOut) shouldBe Bulk(Some(ByteString("rediscala"))) } "EVAL with type conversion" in { @@ -36,11 +33,11 @@ class ScriptingSpec(implicit ee: ExecutionEnv) extends RedisStandaloneServer { redis.eval[DumbClass](redisScriptConversionObject.script) }) - Await.result(r, timeOut) mustEqual dumbObject + Await.result(r, timeOut) shouldBe dumbObject } "EVALSHA" in { - Await.result(redis.evalsha(redisScript.sha1), timeOut) mustEqual Bulk(Some(ByteString("rediscala"))) + Await.result(redis.evalsha(redisScript.sha1), timeOut) shouldBe Bulk(Some(ByteString("rediscala"))) } "EVALSHA with type conversion" in { @@ -49,22 +46,22 @@ class ScriptingSpec(implicit ee: ExecutionEnv) extends RedisStandaloneServer { redis.evalsha[DumbClass](redisScriptConversionObject.sha1) }) - Await.result(r, timeOut) mustEqual dumbObject + Await.result(r, timeOut) shouldBe dumbObject } "evalshaOrEvalForTypeOf (RedisScript)" in { - Await.result(redis.scriptFlush(), timeOut) must beTrue + Await.result(redis.scriptFlush(), timeOut) shouldBe true val dumbObject = new DumbClass("foo3", "bar3") val r = redis.set("dumbKey", dumbObject).flatMap(_ => { redis.evalshaOrEval[DumbClass](redisScriptConversionObject) }) - Await.result(r, timeOut) mustEqual dumbObject + Await.result(r, timeOut) shouldBe dumbObject } "SCRIPT FLUSH" in { - Await.result(redis.scriptFlush(), timeOut) must beTrue + Await.result(redis.scriptFlush(), timeOut) shouldBe true } "SCRIPT KILL" in { @@ -72,7 +69,9 @@ class ScriptingSpec(implicit ee: ExecutionEnv) extends RedisStandaloneServer { withRedisServer(serverPort => { val redisKiller = RedisClient(port = serverPort) val redisScriptLauncher = RedisClient(port = serverPort) - Await.result(redisKiller.scriptKill(), timeOut) must throwA(ReplyErrorException("NOTBUSY No scripts in execution right now.")) + a[ReplyErrorException] should be thrownBy { + Await.result(redisKiller.scriptKill(), timeOut) + } // infinite script (5 seconds) val infiniteScript = redisScriptLauncher.eval( @@ -83,14 +82,17 @@ class ScriptingSpec(implicit ee: ExecutionEnv) extends RedisStandaloneServer { |return 0 """.stripMargin) Thread.sleep(1000) - redisKiller.scriptKill() must beTrue.await(retries = 3, timeOut) - Await.result(infiniteScript, timeOut) must throwA( - ReplyErrorException("ERR Error running script (call to f_2817d960235dc23d2cea9cc2c716a0b123b56be8): @user_script:3: Script killed by user with SCRIPT KILL... ")) + eventually { + redisKiller.scriptKill().futureValue shouldBe true + } + a[ReplyErrorException] should be thrownBy { + Await.result(infiniteScript, timeOut) + } }) } "SCRIPT LOAD" in { - Await.result(redis.scriptLoad("return 'rediscala'"), timeOut) mustEqual "d4cf7650161a37eb55a7e9325f3534cec6fc3241" + Await.result(redis.scriptLoad("return 'rediscala'"), timeOut) shouldBe "d4cf7650161a37eb55a7e9325f3534cec6fc3241" } "SCRIPT EXISTS" in { @@ -99,18 +101,18 @@ class ScriptingSpec(implicit ee: ExecutionEnv) extends RedisStandaloneServer { val scriptsLoaded = redis.scriptLoad(redisScriptFound.script).flatMap(_ => redis.scriptExists(redisScriptFound.sha1, redisScriptNotFound.sha1) ) - Await.result(scriptsLoaded, timeOut) mustEqual Seq(true, false) + Await.result(scriptsLoaded, timeOut) shouldBe Seq(true, false) } "fromFile" in { val testScriptFile = new File(getClass.getResource("/lua/test.lua").getPath) - RedisScript.fromFile(testScriptFile) mustEqual RedisScript("""return "test"""") + RedisScript.fromFile(testScriptFile) shouldBe RedisScript("""return "test"""") } "fromResource" in { val testScriptPath = "/lua/test.lua" - RedisScript.fromResource(testScriptPath) mustEqual RedisScript("""return "test"""") + RedisScript.fromResource(testScriptPath) shouldBe RedisScript("""return "test"""") } } diff --git a/src/test/scala/redis/commands/ServerSpec.scala b/src/test/scala/redis/commands/ServerSpec.scala index 62461105..e997bf2e 100644 --- a/src/test/scala/redis/commands/ServerSpec.scala +++ b/src/test/scala/redis/commands/ServerSpec.scala @@ -7,121 +7,125 @@ import redis.api.NOSAVE class ServerSpec extends RedisStandaloneServer { - sequential - "Server commands" should { "BGSAVE" in { - Await.result(redis.bgsave(), timeOut) mustEqual "Background saving started" + Await.result(redis.bgsave(), timeOut) shouldBe "Background saving started" } "CLIENT KILL" in { - Await.result(redis.clientKill("8.8.8.8", 53), timeOut) must throwA[ReplyErrorException]("ERR No such client") + the[ReplyErrorException] thrownBy { + Await.result(redis.clientKill("8.8.8.8", 53), timeOut) + } } "CLIENT LIST" in { val list = Await.result(redis.clientList(), timeOut) - list must beAnInstanceOf[Seq[Map[String, String]]] - list must not beEmpty + list shouldBe a[Seq[Map[String, String]]] + list should not be empty } "CLIENT GETNAME" in { - Await.result(redis.clientGetname(), timeOut) mustEqual None + Await.result(redis.clientGetname(), timeOut) shouldBe None } "CLIENT SETNAME" in { - Await.result(redis.clientSetname("rediscala"), timeOut) mustEqual true + Await.result(redis.clientSetname("rediscala"), timeOut) shouldBe true } "CONFIG GET" in { val map = Await.result(redis.configGet("*"), timeOut) - map must beAnInstanceOf[Map[String, String]] - map must not beEmpty + map shouldBe a[Map[String, String]] + map should not be empty } "CONFIG SET" in { val r = for { - set <- redis.configSet("loglevel", "warning") + set <- redis.configSet("loglevel", "warning") loglevel <- redis.configGet("loglevel") } yield { - set must beTrue - loglevel.get("loglevel") must beSome("warning") + set shouldBe true + loglevel.get("loglevel") shouldBe Some("warning") } Await.result(r, timeOut) } "CONFIG RESETSTAT" in { - Await.result(redis.configResetstat(), timeOut) must beTrue + Await.result(redis.configResetstat(), timeOut) shouldBe true } "DBSIZE" in { - Await.result(redis.dbsize(), timeOut) must be_>=(0l) + Await.result(redis.dbsize(), timeOut) should be >= 0L } "DEBUG OBJECT" in { - Await.result(redis.debugObject("serverDebugObj"), timeOut) must throwA[ReplyErrorException]("ERR no such key") + redis.debugObject("serverDebugObj").failed.futureValue shouldBe a[ReplyErrorException] } - "DEBUG SEGFAULT" in { - todo - } + "DEBUG SEGFAULT" ignore {} "FLUSHALL" in { - Await.result(redis.flushall(), timeOut) must beTrue + Await.result(redis.flushall(), timeOut) shouldBe true } "FLUSHDB" in { - Await.result(redis.flushdb(), timeOut) must beTrue + Await.result(redis.flushdb(), timeOut) shouldBe true } "INFO" in { val r = for { - info <- redis.info() + info <- redis.info() infoCpu <- redis.info("cpu") } yield { - info must beAnInstanceOf[String] - infoCpu must beAnInstanceOf[String] + info shouldBe a[String] + infoCpu shouldBe a[String] } Await.result(r, timeOut) } "LASTSAVE" in { - Await.result(redis.lastsave(), timeOut) must be_>=(0l) + Await.result(redis.lastsave(), timeOut) should be >= 0L } "SAVE" in { - Await.result(redis.save(), timeOut) must beTrue or throwA(ReplyErrorException("ERR Background save already in progress")) + val result = try { Await.result(redis.save(), timeOut) } catch { + case ReplyErrorException("ERR Background save already in progress") => true + } + result shouldBe true } "SLAVE OF" in { - Await.result(redis.slaveof("server", 12345), timeOut) must beTrue + Await.result(redis.slaveof("server", 12345), timeOut) shouldBe true } "SLAVE OF NO ONE" in { - Await.result(redis.slaveofNoOne(), timeOut) must beTrue + Await.result(redis.slaveofNoOne(), timeOut) shouldBe true } "TIME" in { val result = Await.result(redis.time(), timeOut) - result must beAnInstanceOf[Tuple2[Long, Long]].setMessage(result.toString()) + withClue(result.toString()) { + + result shouldBe a[Tuple2[Long, Long]] + } } "BGREWRITEAOF" in { // depending on the redis version, this string could vary, redis 2.8.21 says 'scheduled' // but redis 2.8.18 says 'started' val r = Await.result(redis.bgrewriteaof(), timeOut) - (r mustEqual "Background append only file rewriting started") or - (r mustEqual "Background append only file rewriting scheduled") + r should (be("Background append only file rewriting started") or + be("Background append only file rewriting scheduled")) } "SHUTDOWN" in { - Await.result(redis.shutdown(), timeOut) must throwA(InvalidRedisReply) + a[InvalidRedisReply.type] should be thrownBy Await.result(redis.shutdown(), timeOut) } "SHUTDOWN (with modifier)" in { withRedisServer(port => { val redis = RedisClient(port = port) - Await.result(redis.shutdown(NOSAVE), timeOut) must throwA(InvalidRedisReply) + a[InvalidRedisReply.type] should be thrownBy Await.result(redis.shutdown(NOSAVE), timeOut) }) } diff --git a/src/test/scala/redis/commands/SetsSpec.scala b/src/test/scala/redis/commands/SetsSpec.scala index 81926431..a42908e9 100644 --- a/src/test/scala/redis/commands/SetsSpec.scala +++ b/src/test/scala/redis/commands/SetsSpec.scala @@ -15,9 +15,9 @@ class SetsSpec extends RedisStandaloneServer { s2 <- redis.sadd("saddKey", "World") m <- redis.smembers("saddKey") } yield { - s1 mustEqual 2 - s2 mustEqual 0 - m must containTheSameElementsAs(Seq(ByteString("Hello"), ByteString("World"))) + s1 shouldBe 2 + s2 shouldBe 0 + m should contain theSameElementsAs(Seq(ByteString("Hello"), ByteString("World"))) } Await.result(r, timeOut) } @@ -29,8 +29,8 @@ class SetsSpec extends RedisStandaloneServer { _ <- redis.sadd("scardKey", "Hello", "World") c2 <- redis.scard("scardKey") } yield { - c1 mustEqual 0 - c2 mustEqual 2 + c1 shouldBe 0 + c2 shouldBe 2 } Await.result(r, timeOut) } @@ -43,7 +43,7 @@ class SetsSpec extends RedisStandaloneServer { _ <- redis.sadd("sdiffKey2", "c", "d", "e") diff <- redis.sdiff("sdiffKey1", "sdiffKey2") } yield { - diff must containTheSameElementsAs(Seq(ByteString("a"), ByteString("b"))) + diff should contain theSameElementsAs(Seq(ByteString("a"), ByteString("b"))) } Await.result(r, timeOut) } @@ -57,8 +57,8 @@ class SetsSpec extends RedisStandaloneServer { diff <- redis.sdiffstore("sdiffstoreKeyDest", "sdiffstoreKey1", "sdiffstoreKey2") m <- redis.smembers("sdiffstoreKeyDest") } yield { - diff mustEqual 2 - m must containTheSameElementsAs(Seq(ByteString("a"), ByteString("b"))) + diff shouldBe 2 + m should contain theSameElementsAs(Seq(ByteString("a"), ByteString("b"))) } Await.result(r, timeOut) } @@ -71,7 +71,7 @@ class SetsSpec extends RedisStandaloneServer { _ <- redis.sadd("sinterKey2", "c", "d", "e") inter <- redis.sinter("sinterKey1", "sinterKey2") } yield { - inter must containTheSameElementsAs(Seq(ByteString("c"))) + inter should contain theSameElementsAs(Seq(ByteString("c"))) } Await.result(r, timeOut) } @@ -86,8 +86,8 @@ class SetsSpec extends RedisStandaloneServer { inter <- redis.sinterstore("sinterstoreKeyDest", "sinterstoreKey1", "sinterstoreKey2") m <- redis.smembers("sinterstoreKeyDest") } yield { - inter mustEqual 1 - m must containTheSameElementsAs(Seq(ByteString("c"))) + inter shouldBe 1 + m should contain theSameElementsAs(Seq(ByteString("c"))) } Await.result(r, timeOut) } @@ -99,8 +99,8 @@ class SetsSpec extends RedisStandaloneServer { is <- redis.sismember("sismemberKey", "World") isNot <- redis.sismember("sismemberKey", "not member") } yield { - is mustEqual true - isNot mustEqual false + is shouldBe true + isNot shouldBe false } Await.result(r, timeOut) } @@ -111,7 +111,7 @@ class SetsSpec extends RedisStandaloneServer { _ <- redis.sadd("smembersKey", "Hello", "World") m <- redis.smembers("smembersKey") } yield { - m must containTheSameElementsAs(Seq(ByteString("Hello"), ByteString("World"))) + m should contain theSameElementsAs(Seq(ByteString("Hello"), ByteString("World"))) } Await.result(r, timeOut) } @@ -126,9 +126,9 @@ class SetsSpec extends RedisStandaloneServer { isNotMoved <- redis.smove("smoveKey1", "smoveKey2", "non existing") m <- redis.smembers("smoveKey2") } yield { - isMoved mustEqual true - isNotMoved mustEqual false - m must containTheSameElementsAs(Seq(ByteString("three"), ByteString("two"))) + isMoved shouldBe true + isNotMoved shouldBe false + m should contain theSameElementsAs(Seq(ByteString("three"), ByteString("two"))) } Await.result(r, timeOut) } @@ -141,9 +141,9 @@ class SetsSpec extends RedisStandaloneServer { popNone <- redis.spop("spopKeyNonExisting") m <- redis.smembers("spopKey") } yield { - Seq(ByteString("three"), ByteString("two"), ByteString("one")) must contain(equalTo(pop.get)) - popNone must beNone - m must containAnyOf(Seq(ByteString("three"), ByteString("two"), ByteString("one"))) + Seq(ByteString("three"), ByteString("two"), ByteString("one")) should contain(pop.get) + popNone shouldBe empty + m should contain atLeastOneElementOf (Seq(ByteString("three"), ByteString("two"), ByteString("one"))) } Await.result(r, timeOut) } @@ -157,9 +157,9 @@ class SetsSpec extends RedisStandaloneServer { randmemberNonExisting <- redis.srandmember("srandmemberKeyNonExisting", 2) m <- redis.smembers("spopKey") } yield { - Seq(ByteString("three"), ByteString("two"), ByteString("one")) must contain(equalTo(randmember.get)) - randmember2 must have size 2 - randmemberNonExisting must beEmpty + Seq(ByteString("three"), ByteString("two"), ByteString("one")) should contain(randmember.get) + randmember2 should have size 2 + randmemberNonExisting shouldBe empty } Await.result(r, timeOut) } @@ -172,9 +172,9 @@ class SetsSpec extends RedisStandaloneServer { remNothing <- redis.srem("sremKey", "five") m <- redis.smembers("sremKey") } yield { - rem mustEqual 2 - remNothing mustEqual 0 - m must containTheSameElementsAs(Seq(ByteString("three"), ByteString("two"))) + rem shouldBe 2 + remNothing shouldBe 0 + m should contain theSameElementsAs(Seq(ByteString("three"), ByteString("two"))) } Await.result(r, timeOut) } @@ -184,8 +184,8 @@ class SetsSpec extends RedisStandaloneServer { _ <- redis.sadd("sscan", (1 to 20).map(_.toString):_*) scanResult <- redis.sscan[String]("sscan", count = Some(100)) } yield { - scanResult.index mustEqual 0 - scanResult.data.map(_.toInt).sorted mustEqual (1 to 20) + scanResult.index shouldBe 0 + scanResult.data.map(_.toInt).sorted shouldBe (1 to 20) } Await.result(r, timeOut) @@ -199,7 +199,7 @@ class SetsSpec extends RedisStandaloneServer { _ <- redis.sadd("sunionKey2", "c", "d", "e") union <- redis.sunion("sunionKey1", "sunionKey2") } yield { - union must containTheSameElementsAs(Seq(ByteString("a"), ByteString("b"), ByteString("c"), ByteString("d"), ByteString("e"))) + union should contain theSameElementsAs(Seq(ByteString("a"), ByteString("b"), ByteString("c"), ByteString("d"), ByteString("e"))) } Await.result(r, timeOut) } @@ -214,8 +214,8 @@ class SetsSpec extends RedisStandaloneServer { union <- redis.sunionstore("sunionstoreKeyDest", "sunionstoreKey1", "sunionstoreKey2") m <- redis.smembers("sunionstoreKeyDest") } yield { - union mustEqual 5 - m must containTheSameElementsAs(Seq(ByteString("a"), ByteString("b"), ByteString("c"), ByteString("d"), ByteString("e"))) + union shouldBe 5 + m should contain theSameElementsAs(Seq(ByteString("a"), ByteString("b"), ByteString("c"), ByteString("d"), ByteString("e"))) } Await.result(r, timeOut) } diff --git a/src/test/scala/redis/commands/SortedSetsSpec.scala b/src/test/scala/redis/commands/SortedSetsSpec.scala index b1f50961..199b3d7e 100644 --- a/src/test/scala/redis/commands/SortedSetsSpec.scala +++ b/src/test/scala/redis/commands/SortedSetsSpec.scala @@ -22,11 +22,11 @@ class SortedSetsSpec extends RedisStandaloneServer { _ <- redis.zadd("zaddKey", 1.0 -> "one", (4, "three")) zr <- redis.zrangeWithscores("zaddKey", 0, -1) } yield { - z1 mustEqual 3 - z2 mustEqual 0 - z3 mustEqual 1 - z4 mustEqual 1 - zr mustEqual Seq((ByteString("one"), 1.0), (ByteString("uno"), 1), (ByteString("two"), 3), (ByteString("three"), 4)) + z1 shouldBe 3 + z2 shouldBe 0 + z3 shouldBe 1 + z4 shouldBe 1 + zr shouldBe Seq((ByteString("one"), 1.0), (ByteString("uno"), 1), (ByteString("two"), 3), (ByteString("three"), 4)) } Await.result(r, timeOut) } @@ -38,8 +38,8 @@ class SortedSetsSpec extends RedisStandaloneServer { _ <- redis.zadd("zcardKey", 1.0 -> "one", (2, "two")) c2 <- redis.zcard("zcardKey") } yield { - c1 mustEqual 0 - c2 mustEqual 2 + c1 shouldBe 0 + c2 shouldBe 2 } Await.result(r, timeOut) } @@ -52,9 +52,9 @@ class SortedSetsSpec extends RedisStandaloneServer { c2 <- redis.zcount("zcountKey") c3 <- redis.zcount("zcountKey", Limit(1, inclusive = false), Limit(3)) } yield { - c1 mustEqual 0 - c2 mustEqual 3 - c3 mustEqual 2 + c1 shouldBe 0 + c2 shouldBe 3 + c3 shouldBe 2 } Await.result(r, timeOut) } @@ -67,9 +67,9 @@ class SortedSetsSpec extends RedisStandaloneServer { d2 <- redis.zincrby("zincrbyKey", 2.1, "notexisting") zr <- redis.zrangeWithscores("zincrbyKey", 0, -1) } yield { - d mustEqual 3.1 - d2 mustEqual 2.1 - zr mustEqual Seq((ByteString("two"), 2.0), (ByteString("notexisting"), 2.1), (ByteString("one"), 3.1)) + d shouldBe 3.1 + d2 shouldBe 2.1 + zr shouldBe Seq((ByteString("two"), 2.0), (ByteString("notexisting"), 2.1), (ByteString("one"), 3.1)) } Await.result(r, timeOut) } @@ -85,12 +85,12 @@ class SortedSetsSpec extends RedisStandaloneServer { zr <- redis.zrangeWithscores("zinterstoreKeyOut", 0, -1) zrWeighted <- redis.zrangeWithscores("zinterstoreKeyOutWeighted", 0, -1) } yield { - z1 mustEqual 2 - z2 mustEqual 3 - zinterstore mustEqual 2 - zinterstoreWeighted mustEqual 2 - zr mustEqual Seq((ByteString("one"), 2), (ByteString("two"), 4)) - zrWeighted mustEqual Seq((ByteString("one"), 5), (ByteString("two"), 10)) + z1 shouldBe 2 + z2 shouldBe 3 + zinterstore shouldBe 2 + zinterstoreWeighted shouldBe 2 + zr shouldBe Seq((ByteString("one"), 2), (ByteString("two"), 4)) + zrWeighted shouldBe Seq((ByteString("one"), 5), (ByteString("two"), 10)) } Await.result(r, timeOut) } @@ -103,10 +103,10 @@ class SortedSetsSpec extends RedisStandaloneServer { zr2 <- redis.zrange("zrangeKey", 2, 3) zr3 <- redis.zrange("zrangeKey", -2, -1) } yield { - z1 mustEqual 3 - zr1 mustEqual Seq(ByteString("one"), ByteString("two"), ByteString("three")) - zr2 mustEqual Seq(ByteString("three")) - zr3 mustEqual Seq(ByteString("two"), ByteString("three")) + z1 shouldBe 3 + zr1 shouldBe Seq(ByteString("one"), ByteString("two"), ByteString("three")) + zr2 shouldBe Seq(ByteString("three")) + zr3 shouldBe Seq(ByteString("two"), ByteString("three")) } Await.result(r, timeOut) } @@ -122,13 +122,13 @@ class SortedSetsSpec extends RedisStandaloneServer { zr3 <- redis.zrangebyscore("zrangebyscoreKey", Limit(1, inclusive = false), Limit(2)) zr4 <- redis.zrangebyscore("zrangebyscoreKey", Limit(1, inclusive = false), Limit(2, inclusive = false)) } yield { - z1 mustEqual 3 - zr1 mustEqual Seq(ByteString("one"), ByteString("two"), ByteString("three")) - zr1Limit mustEqual Seq(ByteString("two"), ByteString("three")) - zr2 mustEqual Seq(ByteString("one"), ByteString("two")) - zr2WithScores mustEqual Seq((ByteString("one"), 1), (ByteString("two"), 2)) - zr3 mustEqual Seq(ByteString("two")) - zr4 mustEqual Seq() + z1 shouldBe 3 + zr1 shouldBe Seq(ByteString("one"), ByteString("two"), ByteString("three")) + zr1Limit shouldBe Seq(ByteString("two"), ByteString("three")) + zr2 shouldBe Seq(ByteString("one"), ByteString("two")) + zr2WithScores shouldBe Seq((ByteString("one"), 1), (ByteString("two"), 2)) + zr3 shouldBe Seq(ByteString("two")) + zr4 shouldBe Seq() } Await.result(r, timeOut) } @@ -140,9 +140,9 @@ class SortedSetsSpec extends RedisStandaloneServer { zr1 <- redis.zrank("zrankKey", "three") zr2 <- redis.zrank("zrankKey", "four") } yield { - z1 mustEqual 3 - zr1 must beSome(2) - zr2 must beNone + z1 shouldBe 3 + zr1 shouldBe Some(2) + zr2 shouldBe None } Await.result(r, timeOut) } @@ -154,9 +154,9 @@ class SortedSetsSpec extends RedisStandaloneServer { z2 <- redis.zrem("zremKey", "two", "nonexisting") zr <- redis.zrangeWithscores("zremKey", 0, -1) } yield { - z1 mustEqual 3 - z2 mustEqual 1 - zr mustEqual Seq((ByteString("one"), 1), (ByteString("three"), 3)) + z1 shouldBe 3 + z2 shouldBe 1 + zr shouldBe Seq((ByteString("one"), 1), (ByteString("three"), 3)) } Await.result(r, timeOut) } @@ -169,10 +169,10 @@ class SortedSetsSpec extends RedisStandaloneServer { z3 <- redis.zremrangebylex("zremrangebylexKey", "[b", "[d") zrange1 <- redis.zrange("zremrangebylexKey", 0, -1) } yield { - z1 mustEqual 7 - z2 mustEqual 0 - z3 mustEqual 3 - zrange1 mustEqual Seq(ByteString("a"), ByteString("e"), ByteString("f"), ByteString("g")) + z1 shouldBe 7 + z2 shouldBe 0 + z3 shouldBe 3 + zrange1 shouldBe Seq(ByteString("a"), ByteString("e"), ByteString("f"), ByteString("g")) } Await.result(r, timeOut) } @@ -184,9 +184,9 @@ class SortedSetsSpec extends RedisStandaloneServer { z2 <- redis.zremrangebyrank("zremrangebyrankKey", 0, 1) zr <- redis.zrangeWithscores("zremrangebyrankKey", 0, -1) } yield { - z1 mustEqual 3 - z2 mustEqual 2 - zr mustEqual Seq((ByteString("three"), 3)) + z1 shouldBe 3 + z2 shouldBe 2 + zr shouldBe Seq((ByteString("three"), 3)) } Await.result(r, timeOut) } @@ -198,9 +198,9 @@ class SortedSetsSpec extends RedisStandaloneServer { z2 <- redis.zremrangebyscore("zremrangebyscoreKey", Limit(Double.NegativeInfinity), Limit(2, inclusive = false)) zr <- redis.zrangeWithscores("zremrangebyscoreKey", 0, -1) } yield { - z1 mustEqual 3 - z2 mustEqual 1 - zr mustEqual Seq((ByteString("two"), 2), (ByteString("three"), 3)) + z1 shouldBe 3 + z2 shouldBe 1 + zr shouldBe Seq((ByteString("two"), 2), (ByteString("three"), 3)) } Await.result(r, timeOut) } @@ -214,11 +214,11 @@ class SortedSetsSpec extends RedisStandaloneServer { zr3 <- redis.zrevrange("zrevrangeKey", -2, -1) zr3WithScores <- redis.zrevrangeWithscores("zrevrangeKey", -2, -1) } yield { - z1 mustEqual 3 - zr1 mustEqual Seq(ByteString("three"), ByteString("two"), ByteString("one")) - zr2 mustEqual Seq(ByteString("one")) - zr3 mustEqual Seq(ByteString("two"), ByteString("one")) - zr3WithScores mustEqual Seq((ByteString("two"), 2), (ByteString("one"), 1)) + z1 shouldBe 3 + zr1 shouldBe Seq(ByteString("three"), ByteString("two"), ByteString("one")) + zr2 shouldBe Seq(ByteString("one")) + zr3 shouldBe Seq(ByteString("two"), ByteString("one")) + zr3WithScores shouldBe Seq((ByteString("two"), 2), (ByteString("one"), 1)) } Await.result(r, timeOut) } @@ -233,12 +233,12 @@ class SortedSetsSpec extends RedisStandaloneServer { zr3 <- redis.zrevrangebyscore("zrevrangebyscoreKey", Limit(2), Limit(1, inclusive = false)) zr4 <- redis.zrevrangebyscore("zrevrangebyscoreKey", Limit(2, inclusive = false), Limit(1, inclusive = false)) } yield { - z1 mustEqual 3 - zr1 mustEqual Seq(ByteString("three"), ByteString("two"), ByteString("one")) - zr2 mustEqual Seq(ByteString("two"), ByteString("one")) - zr2WithScores mustEqual Seq((ByteString("two"), 2), (ByteString("one"), 1)) - zr3 mustEqual Seq(ByteString("two")) - zr4 mustEqual Seq() + z1 shouldBe 3 + zr1 shouldBe Seq(ByteString("three"), ByteString("two"), ByteString("one")) + zr2 shouldBe Seq(ByteString("two"), ByteString("one")) + zr2WithScores shouldBe Seq((ByteString("two"), 2), (ByteString("one"), 1)) + zr3 shouldBe Seq(ByteString("two")) + zr4 shouldBe Seq() } Await.result(r, timeOut) } @@ -250,9 +250,9 @@ class SortedSetsSpec extends RedisStandaloneServer { zr1 <- redis.zrevrank("zrevrankKey", "one") zr2 <- redis.zrevrank("zrevrankKey", "four") } yield { - z1 mustEqual 3 - zr1 must beSome(2) - zr2 must beNone + z1 shouldBe 3 + zr1 shouldBe Some(2) + zr2 shouldBe None } Await.result(r, timeOut) } @@ -263,8 +263,8 @@ class SortedSetsSpec extends RedisStandaloneServer { _ <- redis.zadd("zscan", (1 to 20).map(x => x.toDouble -> x.toString):_*) scanResult <- redis.zscan[String]("zscan", count = Some(100)) } yield { - scanResult.index mustEqual 0 - scanResult.data mustEqual (1 to 20).map(x => x.toDouble -> x.toString) + scanResult.index shouldBe 0 + scanResult.data shouldBe (1 to 20).map(x => x.toDouble -> x.toString) } Await.result(r, timeOut) @@ -279,11 +279,11 @@ class SortedSetsSpec extends RedisStandaloneServer { zr3 <- redis.zscore("zscoreKey", "positiveinf") zr4 <- redis.zscore("zscoreKey", "negativeinf") } yield { - z1 mustEqual 5 - zr1 mustEqual Some(1.1) - zr2 mustEqual None - zr3 mustEqual Some(Double.PositiveInfinity) - zr4 mustEqual Some(Double.NegativeInfinity) + z1 shouldBe 5 + zr1 shouldBe Some(1.1) + zr2 shouldBe None + zr3 shouldBe Some(Double.PositiveInfinity) + zr4 shouldBe Some(Double.NegativeInfinity) } Await.result(r, timeOut) } @@ -299,12 +299,12 @@ class SortedSetsSpec extends RedisStandaloneServer { zunionstoreWeighted <- redis.zunionstoreWeighted("zunionstoreKeyOutWeighted", Map("zunionstoreKey1" -> 2, "zunionstoreKey2" -> 3)) zrWeighted <- redis.zrangeWithscores("zunionstoreKeyOutWeighted", 0, -1) } yield { - z1 mustEqual 2 - z2 mustEqual 3 - zunionstore mustEqual 3 - zr mustEqual Seq((ByteString("one"), 2), (ByteString("three"), 3), (ByteString("two"), 4)) - zunionstoreWeighted mustEqual 3 - zrWeighted mustEqual Seq((ByteString("one"), 5), (ByteString("three"), 9), (ByteString("two"), 10)) + z1 shouldBe 2 + z2 shouldBe 3 + zunionstore shouldBe 3 + zr shouldBe Seq((ByteString("one"), 2), (ByteString("three"), 3), (ByteString("two"), 4)) + zunionstoreWeighted shouldBe 3 + zrWeighted shouldBe Seq((ByteString("one"), 5), (ByteString("three"), 9), (ByteString("two"), 10)) } Await.result(r, timeOut) } @@ -316,9 +316,9 @@ class SortedSetsSpec extends RedisStandaloneServer { zr1 <- redis.zrangebylex("zrangebylexKey", Some("[lex"), None, None) zr2 <- redis.zrangebylex("zrangebylexKey", Some("[lex"), None, Some((0L, 1L))) } yield { - z1 mustEqual 3 - zr1 mustEqual Seq(ByteString("lexA"), ByteString("lexB"), ByteString("lexC")) - zr2 mustEqual Seq(ByteString("lexA")) + z1 shouldBe 3 + zr1 shouldBe Seq(ByteString("lexA"), ByteString("lexB"), ByteString("lexC")) + zr2 shouldBe Seq(ByteString("lexA")) } Await.result(r, timeOut) } @@ -330,9 +330,9 @@ class SortedSetsSpec extends RedisStandaloneServer { zr1 <- redis.zrevrangebylex("zrevrangebylexKey", None, Some("[lex"), None) zr2 <- redis.zrevrangebylex("zrevrangebylexKey", None, Some("[lex"), Some((0L, 1L))) } yield { - z1 mustEqual 3 - zr1 mustEqual Seq(ByteString("lexC"), ByteString("lexB"), ByteString("lexA")) - zr2 mustEqual Seq(ByteString("lexC")) + z1 shouldBe 3 + zr1 shouldBe Seq(ByteString("lexC"), ByteString("lexB"), ByteString("lexA")) + zr2 shouldBe Seq(ByteString("lexC")) } Await.result(r, timeOut) } diff --git a/src/test/scala/redis/commands/StringsSpec.scala b/src/test/scala/redis/commands/StringsSpec.scala index 63c77a34..d9047de0 100644 --- a/src/test/scala/redis/commands/StringsSpec.scala +++ b/src/test/scala/redis/commands/StringsSpec.scala @@ -8,50 +8,56 @@ import scala.concurrent.{Await, Future} class StringsSpec extends RedisStandaloneServer { - sequential "Strings commands" should { "APPEND" in { - val r = redis.set("appendKey", "Hello").flatMap(_ => { - redis.append("appendKey", " World").flatMap(length => { - length mustEqual "Hello World".length - redis.get("appendKey") + val r = redis + .set("appendKey", "Hello") + .flatMap(_ => { + redis + .append("appendKey", " World") + .flatMap(length => { + length shouldBe "Hello World".length + redis.get("appendKey") + }) }) - }) - Await.result(r, timeOut) mustEqual Some(ByteString("Hello World")) + Await.result(r, timeOut) shouldBe Some(ByteString("Hello World")) } "BITCOUNT" in { - val r = redis.set("bitcountKey", "foobar").flatMap(_ => { - val a = redis.bitcount("bitcountKey") - val b = redis.bitcount("bitcountKey", 0, 0) - val c = redis.bitcount("bitcountKey", 1, 1) - Future.sequence(Seq(a, b, c)) - }) - Await.result(r, timeOut) mustEqual Seq(26, 4, 6) + val r = redis + .set("bitcountKey", "foobar") + .flatMap(_ => { + val a = redis.bitcount("bitcountKey") + val b = redis.bitcount("bitcountKey", 0, 0) + val c = redis.bitcount("bitcountKey", 1, 1) + Future.sequence(Seq(a, b, c)) + }) + Await.result(r, timeOut) shouldBe Seq(26, 4, 6) } "BITOP" in { val s1 = redis.set("bitopKey1", "afoobar a") val s2 = redis.set("bitopKey2", "aabcdef a") val r = for { - _ <- s1 - _ <- s2 + _ <- s1 + _ <- s2 and <- redis.bitopAND("ANDbitopKey", "bitopKey1", "bitopKey2") - or <- redis.bitopOR("ORbitopKey", "bitopKey1", "bitopKey2") + or <- redis.bitopOR("ORbitopKey", "bitopKey1", "bitopKey2") xor <- redis.bitopXOR("XORbitopKey", "bitopKey1", "bitopKey2") not <- redis.bitopNOT("NOTbitopKey", "bitopKey1") } yield { - "AND" in { - Await.result(redis.get("ANDbitopKey"), timeOut) mustEqual Some(ByteString("a`bc`ab a")) + withClue("AND") { + Await.result(redis.get("ANDbitopKey"), timeOut) shouldBe Some(ByteString("a`bc`ab a")) } - "OR" in { - Await.result(redis.get("ORbitopKey"), timeOut) mustEqual Some(ByteString("agoofev a")) + withClue("OR") { + Await.result(redis.get("ORbitopKey"), timeOut) shouldBe Some(ByteString("agoofev a")) } - "XOR" in { - Await.result(redis.get("XORbitopKey"), timeOut) mustEqual Some(ByteString(0, 7, 13, 12, 6, 4, 20, 0, 0)) + withClue("XOR") { + Await.result(redis.get("XORbitopKey"), timeOut) shouldBe Some(ByteString(0, 7, 13, 12, 6, 4, 20, 0, 0)) } - "NOT" in { - Await.result(redis.get("NOTbitopKey"), timeOut) mustEqual Some(ByteString(-98, -103, -112, -112, -99, -98, -115, -33, -98)) + withClue("NOT") { + Await.result(redis.get("NOTbitopKey"), timeOut) shouldBe Some( + ByteString(-98, -103, -112, -112, -99, -98, -115, -33, -98)) } } Await.result(r, timeOut) @@ -66,247 +72,293 @@ class StringsSpec extends RedisStandaloneServer { v4 <- redis.bitpos("bitposKey", 0, 3) v5 <- redis.bitpos("bitposKey", 0, 1, 2) } yield { - s1 mustEqual true - v1 mustEqual 0 - v2 mustEqual 1 - v3 mustEqual 10 - v4 mustEqual -1 - v5 mustEqual 8 + s1 shouldBe true + v1 shouldBe 0 + v2 shouldBe 1 + v3 shouldBe 10 + v4 shouldBe -1 + v5 shouldBe 8 } Await.result(r, timeOut) } "DECR" in { - val r = redis.set("decrKey", "10").flatMap(_ => { - redis.decr("decrKey") - }) - val r2 = redis.set("decrKeyError", "234293482390480948029348230948").flatMap(_ => { - redis.decr("decrKeyError") - }) - Await.result(r, timeOut) mustEqual 9 - Await.result(r2, timeOut) must throwA[ReplyErrorException]("ERR value is not an integer or out of range") + val r = redis + .set("decrKey", "10") + .flatMap(_ => { + redis.decr("decrKey") + }) + val r2 = redis + .set("decrKeyError", "234293482390480948029348230948") + .flatMap(_ => { + redis.decr("decrKeyError") + }) + Await.result(r, timeOut) shouldBe 9 + an[ReplyErrorException] should be thrownBy Await.result(r2, timeOut) } "DECRBY" in { - val r = redis.set("decrbyKey", "10").flatMap(_ => { - redis.decrby("decrbyKey", 5) - }) - Await.result(r, timeOut) mustEqual 5 + val r = redis + .set("decrbyKey", "10") + .flatMap(_ => { + redis.decrby("decrbyKey", 5) + }) + Await.result(r, timeOut) shouldBe 5 } "GET" in { val r = redis.get("getKeyNonexisting") - val r2 = redis.set("getKey", "Hello").flatMap(_ => { - redis.get("getKey") - }) - Await.result(r, timeOut) mustEqual None - Await.result(r2, timeOut) mustEqual Some(ByteString("Hello")) + val r2 = redis + .set("getKey", "Hello") + .flatMap(_ => { + redis.get("getKey") + }) + Await.result(r, timeOut) shouldBe None + Await.result(r2, timeOut) shouldBe Some(ByteString("Hello")) val rrr = for { r3 <- redis.get[String]("getKey") } yield { - r3 must beSome("Hello") + r3 shouldBe Some("Hello") } Await.result(rrr, timeOut) } "GET with conversion" in { val dumbObject = new DumbClass("foo", "bar") - val r = redis.set("getDumbKey", dumbObject).flatMap(_ => { - redis.get[DumbClass]("getDumbKey") - }) - Await.result(r, timeOut) mustEqual Some(dumbObject) + val r = redis + .set("getDumbKey", dumbObject) + .flatMap(_ => { + redis.get[DumbClass]("getDumbKey") + }) + Await.result(r, timeOut) shouldBe Some(dumbObject) } "GETBIT" in { val r = redis.getbit("getbitKeyNonexisting", 0) - val r2 = redis.set("getbitKey", "Hello").flatMap(_ => { - redis.getbit("getbitKey", 1) - }) - Await.result(r, timeOut) mustEqual false - Await.result(r2, timeOut) mustEqual true + val r2 = redis + .set("getbitKey", "Hello") + .flatMap(_ => { + redis.getbit("getbitKey", 1) + }) + Await.result(r, timeOut) shouldBe false + Await.result(r2, timeOut) shouldBe true } "GETRANGE" in { - val r = redis.set("getrangeKey", "This is a string").flatMap(_ => { - Future.sequence(Seq( - redis.getrange("getrangeKey", 0, 3), - redis.getrange("getrangeKey", -3, -1), - redis.getrange("getrangeKey", 0, -1), - redis.getrange("getrangeKey", 10, 100) - ).map(_.map(_.map(_.utf8String).get))) - }) - Await.result(r, timeOut) mustEqual Seq("This", "ing", "This is a string", "string") + val r = redis + .set("getrangeKey", "This is a string") + .flatMap(_ => { + Future.sequence( + Seq( + redis.getrange("getrangeKey", 0, 3), + redis.getrange("getrangeKey", -3, -1), + redis.getrange("getrangeKey", 0, -1), + redis.getrange("getrangeKey", 10, 100) + ).map(_.map(_.map(_.utf8String).get))) + }) + Await.result(r, timeOut) shouldBe Seq("This", "ing", "This is a string", "string") } "GETSET" in { - val r = redis.set("getsetKey", "Hello").flatMap(_ => { - redis.getset("getsetKey", "World").flatMap(hello => { - hello mustEqual Some(ByteString("Hello")) - redis.get("getsetKey") + val r = redis + .set("getsetKey", "Hello") + .flatMap(_ => { + redis + .getset("getsetKey", "World") + .flatMap(hello => { + hello shouldBe Some(ByteString("Hello")) + redis.get("getsetKey") + }) }) - }) - Await.result(r, timeOut) mustEqual Some(ByteString("World")) + Await.result(r, timeOut) shouldBe Some(ByteString("World")) } "INCR" in { - val r = redis.set("incrKey", "10").flatMap(_ => { - redis.incr("incrKey") - }) - Await.result(r, timeOut) mustEqual 11 + val r = redis + .set("incrKey", "10") + .flatMap(_ => { + redis.incr("incrKey") + }) + Await.result(r, timeOut) shouldBe 11 } "INCRBY" in { - val r = redis.set("incrbyKey", "10").flatMap(_ => { - redis.incrby("incrbyKey", 5) - }) - Await.result(r, timeOut) mustEqual 15 + val r = redis + .set("incrbyKey", "10") + .flatMap(_ => { + redis.incrby("incrbyKey", 5) + }) + Await.result(r, timeOut) shouldBe 15 } "INCRBYFLOAT" in { - val r = redis.set("incrbyfloatKey", "10.50").flatMap(_ => { - redis.incrbyfloat("incrbyfloatKey", 0.15) - }) - Await.result(r, timeOut) mustEqual Some(10.65) + val r = redis + .set("incrbyfloatKey", "10.50") + .flatMap(_ => { + redis.incrbyfloat("incrbyfloatKey", 0.15) + }) + Await.result(r, timeOut) shouldBe Some(10.65) } "MGET" in { val s1 = redis.set("mgetKey", "Hello") val s2 = redis.set("mgetKey2", "World") val r = for { - _ <- s1 - _ <- s2 + _ <- s1 + _ <- s2 mget <- redis.mget("mgetKey", "mgetKey2", "mgetKeyNonexisting") } yield { - mget mustEqual Seq(Some(ByteString("Hello")), Some(ByteString("World")), None) + mget shouldBe Seq(Some(ByteString("Hello")), Some(ByteString("World")), None) } Await.result(r, timeOut) } "MSET" in { - val r = redis.mset(Map("msetKey" -> "Hello", "msetKey2" -> "World")).flatMap(ok => { - ok mustEqual true - Future.sequence(Seq( - redis.get("msetKey"), - redis.get("msetKey2") - )) - }) - Await.result(r, timeOut) mustEqual Seq(Some(ByteString("Hello")), Some(ByteString("World"))) + val r = redis + .mset(Map("msetKey" -> "Hello", "msetKey2" -> "World")) + .flatMap(ok => { + ok shouldBe true + Future.sequence( + Seq( + redis.get("msetKey"), + redis.get("msetKey2") + )) + }) + Await.result(r, timeOut) shouldBe Seq(Some(ByteString("Hello")), Some(ByteString("World"))) } "MSETNX" in { val r = for { - _ <- redis.del("msetnxKey", "msetnxKey2") - msetnx <- redis.msetnx(Map("msetnxKey" -> "Hello", "msetnxKey2" -> "World")) + _ <- redis.del("msetnxKey", "msetnxKey2") + msetnx <- redis.msetnx(Map("msetnxKey" -> "Hello", "msetnxKey2" -> "World")) msetnxFalse <- redis.msetnx(Map("msetnxKey3" -> "Hello", "msetnxKey2" -> "already set !!")) } yield { - msetnx mustEqual true - msetnxFalse mustEqual false + msetnx shouldBe true + msetnxFalse shouldBe false } Await.result(r, timeOut) } "PSETEX" in { - val r = redis.psetex("psetexKey", 2000, "temp value").flatMap(x => { - x mustEqual true - redis.get("psetexKey").flatMap(v => { - v mustEqual Some(ByteString("temp value")) - Thread.sleep(2000) - redis.get("psetexKey") + val r = redis + .psetex("psetexKey", 2000, "temp value") + .flatMap(x => { + x shouldBe true + redis + .get("psetexKey") + .flatMap(v => { + v shouldBe Some(ByteString("temp value")) + Thread.sleep(2000) + redis.get("psetexKey") + }) }) - }) - Await.result(r, timeOut) mustEqual None + Await.result(r, timeOut) shouldBe None } "SET" in { val rr = for { - r <- redis.set("setKey", "value") - ex <- redis.set("setKey", "value", exSeconds = Some(2)) - nxex <- redis.set("setKey2", "value", NX = true, exSeconds = Some(60)) + r <- redis.set("setKey", "value") + ex <- redis.set("setKey", "value", exSeconds = Some(2)) + nxex <- redis.set("setKey2", "value", NX = true, exSeconds = Some(60)) ttlnxex <- redis.ttl("setKey2") - xxex <- redis.set("setKey2", "value", XX = true, exSeconds = Some(180)) + xxex <- redis.set("setKey2", "value", XX = true, exSeconds = Some(180)) ttlxxex <- redis.ttl("setKey2") - _ <- redis.del("setKey2") - px <- redis.set("setKey", "value", pxMilliseconds = Some(1)) + _ <- redis.del("setKey2") + px <- redis.set("setKey", "value", pxMilliseconds = Some(1)) nxTrue <- { Thread.sleep(20) redis.set("setKey", "value", NX = true) } - xx <- redis.set("setKey", "value", XX = true) + xx <- redis.set("setKey", "value", XX = true) nxFalse <- redis.set("setKey", "value", NX = true) } yield { - r mustEqual true - ex mustEqual true - nxex must beTrue - ttlnxex must beBetween[Long](0, 60) - xxex must beTrue - ttlxxex must beBetween[Long](60, 180) - px mustEqual true - nxTrue mustEqual true // because pxMilliseconds = 1 millisecond - xx mustEqual true - nxFalse mustEqual false + r shouldBe true + ex shouldBe true + nxex shouldBe true + ttlnxex should be >= 0L + ttlnxex should be <= 60L + xxex shouldBe true + ttlxxex should be >= 60L + ttlxxex should be <= 180L + px shouldBe true + nxTrue shouldBe true // because pxMilliseconds = 1 millisecond + xx shouldBe true + nxFalse shouldBe false } Await.result(rr, timeOut) } "SETBIT" in { val r = for { - _ <- redis.del("setbitKey") - setTrue <- redis.setbit("setbitKey", 1, value = true) - getTrue <- redis.getbit("setbitKey", 1) + _ <- redis.del("setbitKey") + setTrue <- redis.setbit("setbitKey", 1, value = true) + getTrue <- redis.getbit("setbitKey", 1) setFalse <- redis.setbit("setbitKey", 1, value = false) getFalse <- redis.getbit("setbitKey", 1) } yield { - setTrue mustEqual false - getTrue mustEqual true - setFalse mustEqual true - getFalse mustEqual false + setTrue shouldBe false + getTrue shouldBe true + setFalse shouldBe true + getFalse shouldBe false } Await.result(r, timeOut) } "SETEX" in { - val r = redis.setex("setexKey", 1, "temp value").flatMap(x => { - x mustEqual true - redis.get("setexKey").flatMap(v => { - v mustEqual Some(ByteString("temp value")) - Thread.sleep(2000) - redis.get("setexKey") + val r = redis + .setex("setexKey", 1, "temp value") + .flatMap(x => { + x shouldBe true + redis + .get("setexKey") + .flatMap(v => { + v shouldBe Some(ByteString("temp value")) + Thread.sleep(2000) + redis.get("setexKey") + }) }) - }) - Await.result(r, timeOut) mustEqual None + Await.result(r, timeOut) shouldBe None } "SETNX" in { val r = for { - _ <- redis.del("setnxKey") + _ <- redis.del("setnxKey") s1 <- redis.setnx("setnxKey", "Hello") s2 <- redis.setnx("setnxKey", "World") } yield { - s1 mustEqual true - s2 mustEqual false + s1 shouldBe true + s2 shouldBe false } Await.result(r, timeOut) } "SETRANGE" in { - val r = redis.set("setrangeKey", "Hello World").flatMap(d => { - redis.setrange("setrangeKey", 6, "Redis").flatMap(length => { - length mustEqual "Hello Redis".length - redis.get("setrangeKey") + val r = redis + .set("setrangeKey", "Hello World") + .flatMap(d => { + redis + .setrange("setrangeKey", 6, "Redis") + .flatMap(length => { + length shouldBe "Hello Redis".length + redis.get("setrangeKey") + }) }) - }) - Await.result(r, timeOut) mustEqual Some(ByteString("Hello Redis")) + Await.result(r, timeOut) shouldBe Some(ByteString("Hello Redis")) } "STRLEN" in { - val r = redis.set("strlenKey", "Hello World").flatMap(d => { - redis.strlen("strlenKey").flatMap(length => { - length mustEqual "Hello World".length - redis.strlen("strlenKeyNonexisting") + val r = redis + .set("strlenKey", "Hello World") + .flatMap(d => { + redis + .strlen("strlenKey") + .flatMap(length => { + length shouldBe "Hello World".length + redis.strlen("strlenKeyNonexisting") + }) }) - }) - Await.result(r, timeOut) mustEqual 0 + Await.result(r, timeOut) shouldBe 0 } } } diff --git a/src/test/scala/redis/commands/TransactionsSpec.scala b/src/test/scala/redis/commands/TransactionsSpec.scala index 87bdb963..e21e508d 100644 --- a/src/test/scala/redis/commands/TransactionsSpec.scala +++ b/src/test/scala/redis/commands/TransactionsSpec.scala @@ -21,42 +21,44 @@ class TransactionsSpec extends RedisStandaloneServer { s <- set g <- get } yield { - s mustEqual true - g mustEqual Some(ByteString("abc")) + s shouldBe true + g shouldBe Some(ByteString("abc")) + } + the[ReplyErrorException] thrownBy { + Await.result(decr, timeOut) } - Await.result(decr, timeOut) must throwA[ReplyErrorException]("ERR value is not an integer or out of range") Await.result(r, timeOut) } "function api" in { - "empty" in { + withClue("empty") { val empty = redis.multi().exec() - Await.result(empty, timeOut) mustEqual MultiBulk(Some(Vector())) + Await.result(empty, timeOut) shouldBe MultiBulk(Some(Vector())) } val redisTransaction = redis.multi(redis => { redis.set("a", "abc") redis.get("a") }) - val exec = redisTransaction.exec() - "non empty" in { - Await.result(exec, timeOut) mustEqual MultiBulk(Some(Vector(Status(ByteString("OK")), Bulk(Some(ByteString("abc")))))) + withClue("non empty") { + val exec = redisTransaction.exec() + Await.result(exec, timeOut) shouldBe MultiBulk(Some(Vector(Status(ByteString("OK")), Bulk(Some(ByteString("abc")))))) } - "reused" in { + withClue("reused") { redisTransaction.get("transactionUndefinedKey") val exec = redisTransaction.exec() - Await.result(exec, timeOut) mustEqual MultiBulk(Some(Vector(Status(ByteString("OK")), Bulk(Some(ByteString("abc"))), Bulk(None)))) + Await.result(exec, timeOut) shouldBe MultiBulk(Some(Vector(Status(ByteString("OK")), Bulk(Some(ByteString("abc"))), Bulk(None)))) } - "watch" in { + withClue("watch") { val transaction = redis.watch("transactionWatchKey") - transaction.watcher.result() mustEqual Set("transactionWatchKey") + transaction.watcher.result() shouldBe Set("transactionWatchKey") transaction.unwatch() - transaction.watcher.result() must beEmpty + transaction.watcher.result() shouldBe empty val set = transaction.set("transactionWatch", "value") transaction.exec() val r = for { s <- set } yield { - s must beTrue + s shouldBe true } Await.result(r, timeOut) } diff --git a/src/test/scala/redis/protocol/ParseNumberSpec.scala b/src/test/scala/redis/protocol/ParseNumberSpec.scala index d538666f..60e3e1e5 100644 --- a/src/test/scala/redis/protocol/ParseNumberSpec.scala +++ b/src/test/scala/redis/protocol/ParseNumberSpec.scala @@ -1,61 +1,60 @@ package redis.protocol -import org.specs2.mutable._ import akka.util.ByteString +import redis.TestBase -class ParseNumberSpec extends Specification { +class ParseNumberSpec extends TestBase { - import java.lang.Integer "ParseNumber.parseInt" should { "ok" in { - ParseNumber.parseInt(ByteString("0")) mustEqual 0 - ParseNumber.parseInt(ByteString("10")) mustEqual 10 - ParseNumber.parseInt(ByteString("-10")) mustEqual -10 - ParseNumber.parseInt(ByteString("-123456")) mustEqual -123456 - ParseNumber.parseInt(ByteString("1234567890")) mustEqual 1234567890 - ParseNumber.parseInt(ByteString("-1234567890")) mustEqual -1234567890 + ParseNumber.parseInt(ByteString("0")) shouldBe 0 + ParseNumber.parseInt(ByteString("10")) shouldBe 10 + ParseNumber.parseInt(ByteString("-10")) shouldBe -10 + ParseNumber.parseInt(ByteString("-123456")) shouldBe -123456 + ParseNumber.parseInt(ByteString("1234567890")) shouldBe 1234567890 + ParseNumber.parseInt(ByteString("-1234567890")) shouldBe -1234567890 } "null" in { - ParseNumber.parseInt(null) must throwA[NumberFormatException] + a[NumberFormatException] should be thrownBy ParseNumber.parseInt(null) } "lone \"+\" or \"-\"" in { - ParseNumber.parseInt(ByteString("+")) must throwA[NumberFormatException] - ParseNumber.parseInt(ByteString("-")) must throwA[NumberFormatException] + a[NumberFormatException] should be thrownBy ParseNumber.parseInt(ByteString("+")) + a[NumberFormatException] should be thrownBy ParseNumber.parseInt(ByteString("-")) } "invalid first char" in { - ParseNumber.parseInt(ByteString("$")) must throwA[NumberFormatException] + a[NumberFormatException] should be thrownBy ParseNumber.parseInt(ByteString("$")) } "empty" in { - ParseNumber.parseInt(ByteString.empty) must throwA[NumberFormatException] + a[NumberFormatException] should be thrownBy ParseNumber.parseInt(ByteString.empty) } "invalid char" in { - ParseNumber.parseInt(ByteString("?")) must throwA[NumberFormatException] + a[NumberFormatException] should be thrownBy ParseNumber.parseInt(ByteString("?")) } "limit min" in { - val l1 : Long = Integer.MIN_VALUE + val l1 : Long = java.lang.Integer.MIN_VALUE val l = l1 - 1 - ParseNumber.parseInt(ByteString(l.toString)) must throwA[NumberFormatException] + a[NumberFormatException] should be thrownBy ParseNumber.parseInt(ByteString(l.toString)) } "limit max" in { - val l1 : Long = Integer.MAX_VALUE + val l1 : Long = java.lang.Integer.MAX_VALUE val l = l1 + 1 - ParseNumber.parseInt(ByteString(l.toString)) must throwA[NumberFormatException] + a[NumberFormatException] should be thrownBy ParseNumber.parseInt(ByteString(l.toString)) } "not a number" in { - ParseNumber.parseInt(ByteString("not a number")) must throwA[NumberFormatException] + a[NumberFormatException] should be thrownBy ParseNumber.parseInt(ByteString("not a number")) } "launch exception before integer overflow" in { - ParseNumber.parseInt(ByteString("-2147483650")) must throwA[NumberFormatException] + a[NumberFormatException] should be thrownBy ParseNumber.parseInt(ByteString("-2147483650")) } } diff --git a/src/test/scala/redis/protocol/ParseParse.scala b/src/test/scala/redis/protocol/ParseParse.scala index 9af95a24..01c43fa5 100644 --- a/src/test/scala/redis/protocol/ParseParse.scala +++ b/src/test/scala/redis/protocol/ParseParse.scala @@ -1,13 +1,13 @@ package redis.protocol import akka.util.ByteString -import org.specs2.mutable.Specification +import redis.TestBase -class ParseParse extends Specification { +class ParseParse extends TestBase { "parse" should { "integer" in { val int = ByteString("654\r\n") - RedisProtocolReply.decodeInteger(int) mustEqual FullyDecoded(Integer(ByteString("654")), ByteString()) + RedisProtocolReply.decodeInteger(int) shouldBe FullyDecoded(Integer(ByteString("654")), ByteString()) val (intStart, intEnd) = int.splitAt(int.length - 1) @@ -16,17 +16,17 @@ class ParseParse extends Specification { b <- intStart.tail } yield { result = result.run(ByteString(b)) - result.isFullyDecoded should beFalse + result.isFullyDecoded shouldBe false } val decodeResult = result.run(intEnd) - decodeResult.isFullyDecoded should beTrue - decodeResult mustEqual FullyDecoded(Integer(ByteString("654")), ByteString()) + decodeResult.isFullyDecoded shouldBe true + decodeResult shouldBe FullyDecoded(Integer(ByteString("654")), ByteString()) } "decodeBulk" in { val bulk = ByteString("6\r\nfoobar\r\n") - RedisProtocolReply.decodeBulk(bulk) mustEqual FullyDecoded(Bulk(Some(ByteString("foobar"))), ByteString()) + RedisProtocolReply.decodeBulk(bulk) shouldBe FullyDecoded(Bulk(Some(ByteString("foobar"))), ByteString()) val (bulkStart, bulkEnd) = bulk.splitAt(bulk.length - 1) @@ -35,12 +35,12 @@ class ParseParse extends Specification { b <- bulkStart.tail } yield { result = result.run(ByteString(b)) - result.isFullyDecoded should beFalse + result.isFullyDecoded shouldBe false } val decodeResult = result.run(bulkEnd) - decodeResult.isFullyDecoded should beTrue - decodeResult mustEqual FullyDecoded(Bulk(Some(ByteString("foobar"))), ByteString()) + decodeResult.isFullyDecoded shouldBe true + decodeResult shouldBe FullyDecoded(Bulk(Some(ByteString("foobar"))), ByteString()) } "multibulk" in { @@ -54,12 +54,12 @@ class ParseParse extends Specification { b <- multibulkStringStart.tail } yield { r3 = r3.run(ByteString(b)) - r3.isFullyDecoded should beFalse + r3.isFullyDecoded shouldBe false } val nextBS = ByteString("*2\r\n$3\r\none\r\n$3\r\ntwo\r\n") val result = r3.run(multibulkStringEnd ++ nextBS) - result.isFullyDecoded should beTrue + result.isFullyDecoded shouldBe true val multibulk = Some(Vector(Bulk(Some(ByteString("foo"))), Bulk(Some(ByteString("bar"))), Bulk(Some(ByteString("Hello"))), Bulk(Some(ByteString("World"))))) result shouldEqual FullyDecoded(MultiBulk(multibulk), nextBS) diff --git a/src/test/scala/redis/protocol/RedisProtocolReplySpec.scala b/src/test/scala/redis/protocol/RedisProtocolReplySpec.scala index a37cae5f..f2755285 100644 --- a/src/test/scala/redis/protocol/RedisProtocolReplySpec.scala +++ b/src/test/scala/redis/protocol/RedisProtocolReplySpec.scala @@ -1,55 +1,57 @@ package redis.protocol import akka.util.ByteString -import org.specs2.mutable._ +import redis.TestBase -class RedisProtocolReplySpec extends Specification { +class RedisProtocolReplySpec extends TestBase { "Decode reply" should { "fail" in { val bs = ByteString("!!") - RedisProtocolReply.decodeReply(bs) must throwA[Exception] + an[Exception] shouldBe thrownBy { + RedisProtocolReply.decodeReply(bs) + } } } "Decode String" should { "decode simple string" in { val ok = ByteString("OK\r\n") - RedisProtocolReply.decodeString(ok) mustEqual FullyDecoded(ok.dropRight(2), ByteString()) + RedisProtocolReply.decodeString(ok) shouldBe FullyDecoded(ok.dropRight(2), ByteString()) } "wait for more content" in { val waitForMore = ByteString("waiting for more") val r = RedisProtocolReply.decodeString(waitForMore) - r.isFullyDecoded must beFalse - r.rest mustEqual waitForMore + r.isFullyDecoded shouldBe false + r.rest shouldBe waitForMore } "decode and keep the tail" in { val decode = ByteString("decode\r\n") val keepTail = ByteString("keep the tail") - RedisProtocolReply.decodeString(decode ++ keepTail) mustEqual FullyDecoded(decode.dropRight(2), keepTail) + RedisProtocolReply.decodeString(decode ++ keepTail) shouldBe FullyDecoded(decode.dropRight(2), keepTail) } } "Decode integer" should { "decode positive integer" in { val int = ByteString("6\r\n") - RedisProtocolReply.decodeInteger(int) mustEqual FullyDecoded(Integer(ByteString("6")), ByteString()) + RedisProtocolReply.decodeInteger(int) shouldBe FullyDecoded(Integer(ByteString("6")), ByteString()) } "decode negative integer" in { val int = ByteString("-6\r\n") val decoded = RedisProtocolReply.decodeInteger(int) - decoded mustEqual FullyDecoded(Integer(ByteString("-6")), ByteString()) + decoded shouldBe FullyDecoded(Integer(ByteString("-6")), ByteString()) } } "Decode bulk" should { "decode simple bulk" in { val bulk = ByteString("6\r\nfoobar\r\n") - RedisProtocolReply.decodeBulk(bulk) mustEqual FullyDecoded(Bulk(Some(ByteString("foobar"))), ByteString()) + RedisProtocolReply.decodeBulk(bulk) shouldBe FullyDecoded(Bulk(Some(ByteString("foobar"))), ByteString()) } "decode Null Bulk Reply" in { val bulk = ByteString("-1\r\n") - RedisProtocolReply.decodeBulk(bulk) mustEqual FullyDecoded(Bulk(None), ByteString()) + RedisProtocolReply.decodeBulk(bulk) shouldBe FullyDecoded(Bulk(None), ByteString()) } } @@ -57,31 +59,31 @@ class RedisProtocolReplySpec extends Specification { "decode simple" in { val multibulkString = ByteString("4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$5\r\nWorld\r\n") val multibulk = Some(Vector(Bulk(Some(ByteString("foo"))), Bulk(Some(ByteString("bar"))), Bulk(Some(ByteString("Hello"))), Bulk(Some(ByteString("World"))))) - RedisProtocolReply.decodeMultiBulk(multibulkString) mustEqual FullyDecoded(MultiBulk(multibulk), ByteString()) + RedisProtocolReply.decodeMultiBulk(multibulkString) shouldBe FullyDecoded(MultiBulk(multibulk), ByteString()) } "decode waiting" in { val multibulkString = ByteString("4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$50\r\nWaiting ...") val r = RedisProtocolReply.decodeMultiBulk(multibulkString) - r.isFullyDecoded must beFalse - r.rest mustEqual ByteString() + r.isFullyDecoded shouldBe false + r.rest shouldBe ByteString() } "decode Empty Multi Bulk" in { val emptyMultiBulk = ByteString("0\r\n") - RedisProtocolReply.decodeMultiBulk(emptyMultiBulk) mustEqual FullyDecoded(MultiBulk(Some(Vector())), ByteString()) + RedisProtocolReply.decodeMultiBulk(emptyMultiBulk) shouldBe FullyDecoded(MultiBulk(Some(Vector())), ByteString()) } "decode Null Multi Bulk" in { val nullMultiBulk = ByteString("-1\r\n") - RedisProtocolReply.decodeMultiBulk(nullMultiBulk) mustEqual FullyDecoded(MultiBulk(None), ByteString()) + RedisProtocolReply.decodeMultiBulk(nullMultiBulk) shouldBe FullyDecoded(MultiBulk(None), ByteString()) } "decode Null element in Multi Bulk" in { val nullElementInMultiBulk = ByteString("3\r\n$3\r\nfoo\r\n$-1\r\n$3\r\nbar\r\n") val multibulk = Some(Vector(Bulk(Some(ByteString("foo"))), Bulk(None), Bulk(Some(ByteString("bar"))))) - RedisProtocolReply.decodeMultiBulk(nullElementInMultiBulk) mustEqual FullyDecoded(MultiBulk(multibulk), ByteString()) + RedisProtocolReply.decodeMultiBulk(nullElementInMultiBulk) shouldBe FullyDecoded(MultiBulk(multibulk), ByteString()) } "decode different reply type" in { val diff = ByteString("5\r\n:1\r\n:2\r\n:3\r\n:4\r\n$6\r\nfoobar\r\n") val multibulk = Some(Vector(Integer(ByteString("1")), Integer(ByteString("2")), Integer(ByteString("3")), Integer(ByteString("4")), Bulk(Some(ByteString("foobar"))))) - RedisProtocolReply.decodeMultiBulk(diff) mustEqual FullyDecoded(MultiBulk(multibulk), ByteString()) + RedisProtocolReply.decodeMultiBulk(diff) shouldBe FullyDecoded(MultiBulk(multibulk), ByteString()) } } } diff --git a/src/test/scala/redis/protocol/RedisProtocolRequestSpec.scala b/src/test/scala/redis/protocol/RedisProtocolRequestSpec.scala index 892c7364..261b4eb6 100644 --- a/src/test/scala/redis/protocol/RedisProtocolRequestSpec.scala +++ b/src/test/scala/redis/protocol/RedisProtocolRequestSpec.scala @@ -1,17 +1,17 @@ package redis.protocol import akka.util.ByteString -import org.specs2.mutable._ +import redis.TestBase -class RedisProtocolRequestSpec extends Specification { +class RedisProtocolRequestSpec extends TestBase { "Encode request" should { "inline" in { - RedisProtocolRequest.inline("PING") mustEqual ByteString("PING\r\n") + RedisProtocolRequest.inline("PING") shouldBe ByteString("PING\r\n") } "multibulk" in { val encoded = RedisProtocolRequest.multiBulk("SET", Seq(ByteString("mykey"), ByteString("myvalue"))) - encoded mustEqual ByteString("*3\r\n$3\r\nSET\r\n$5\r\nmykey\r\n$7\r\nmyvalue\r\n") + encoded shouldBe ByteString("*3\r\n$3\r\nSET\r\n$5\r\nmykey\r\n$7\r\nmyvalue\r\n") } } From 0e8a0d8a3345e3832e7eba28876199616ad3e596 Mon Sep 17 00:00:00 2001 From: Alexey Kardapoltsev Date: Wed, 20 Feb 2019 12:44:51 +0700 Subject: [PATCH 02/11] Remove Thread.sleep --- build.sbt | 115 +++++------ src/test/resources/application.conf | 4 + src/test/scala/redis/RedisClusterTest.scala | 21 +- src/test/scala/redis/RedisPubSubSpec.scala | 34 ++-- src/test/scala/redis/RedisSpec.scala | 182 ++++++++---------- src/test/scala/redis/SentinelPoolSpec.scala | 30 +-- src/test/scala/redis/TestBase.scala | 34 ++-- .../scala/redis/commands/BListsSpec.scala | 5 +- .../scala/redis/commands/ConnectionSpec.scala | 6 +- src/test/scala/redis/commands/KeysSpec.scala | 129 ++++++------- .../scala/redis/commands/ScriptingSpec.scala | 3 +- .../scala/redis/commands/StringsSpec.scala | 73 ++----- 12 files changed, 277 insertions(+), 359 deletions(-) create mode 100644 src/test/resources/application.conf diff --git a/build.sbt b/build.sbt index 3f9c9485..119502bc 100644 --- a/build.sbt +++ b/build.sbt @@ -1,70 +1,71 @@ lazy val common = Seq( - organization := "com.github.Ma27", - publishTo := { - val nexus = "https://oss.sonatype.org/" - if (isSnapshot.value) - Some("snapshots" at nexus + "content/repositories/snapshots") - else - Some("releases" at nexus + "service/local/staging/deploy/maven2") - }, - - scalaVersion := "2.12.8", - crossScalaVersions := Seq(scalaVersion.value, "2.11.12"), - licenses += ("Apache-2.0", url("http://www.apache.org/licenses/LICENSE-2.0.html")), - homepage := Some(url("https://github.com/Ma27/rediscala")), - scmInfo := Some(ScmInfo(url("https://github.com/Ma27/rediscala"), "scm:git:git@github.com:Ma27/rediscala.git")), - apiURL := Some(url("http://etaty.github.io/rediscala/latest/api/")), - pomExtra := - + organization := "com.github.Ma27", + publishTo := { + val nexus = "https://oss.sonatype.org/" + if (isSnapshot.value) + Some("snapshots" at nexus + "content/repositories/snapshots") + else + Some("releases" at nexus + "service/local/staging/deploy/maven2") + }, + scalaVersion := "2.12.8", + crossScalaVersions := Seq(scalaVersion.value, "2.11.12"), + licenses += ("Apache-2.0", url("http://www.apache.org/licenses/LICENSE-2.0.html")), + homepage := Some(url("https://github.com/Ma27/rediscala")), + scmInfo := Some(ScmInfo(url("https://github.com/Ma27/rediscala"), "scm:git:git@github.com:Ma27/rediscala.git")), + apiURL := Some(url("http://etaty.github.io/rediscala/latest/api/")), + pomExtra := + Ma27 Valerian Barbot, The Rediscala community http://github.com/Ma27/ , - resolvers ++= Seq( - "Typesafe repository snapshots" at "http://repo.typesafe.com/typesafe/snapshots/", - "Typesafe repository releases" at "http://repo.typesafe.com/typesafe/releases/" - ), - publishMavenStyle := true, - scalacOptions ++= Seq( - "-encoding", "UTF-8", - "-Xlint", - "-deprecation", + resolvers ++= Seq( + "Typesafe repository snapshots" at "http://repo.typesafe.com/typesafe/snapshots/", + "Typesafe repository releases" at "http://repo.typesafe.com/typesafe/releases/" + ), + publishMavenStyle := true, + scalacOptions ++= Seq( + "-encoding", + "UTF-8", + "-Xlint", + "-deprecation", // "-Xfatal-warnings", - "-feature", - "-language:postfixOps", - "-unchecked" - ), - - - libraryDependencies ++= { - val akkaVersion = "2.5.19" - Seq( - "com.typesafe.akka" %% "akka-actor" % akkaVersion, - "com.typesafe.akka" %% "akka-testkit" % akkaVersion % Test, - "org.scalatest" %% "scalatest" % "3.0.5" % Test, - "org.scala-stm" %% "scala-stm" % "0.9", - "org.scalacheck" %% "scalacheck" % "1.14.0" % Test - ) - }, - - autoAPIMappings := true, - - // TODO create new github pages target - apiURL := Some(url("http://etaty.github.io/rediscala/")) - ) + "-feature", + "-language:postfixOps", + "-unchecked" + ), + libraryDependencies ++= { + val akkaVersion = "2.5.19" + Seq( + "org.scala-stm" %% "scala-stm" % "0.9", + "com.typesafe.akka" %% "akka-actor" % akkaVersion, + "com.typesafe.akka" %% "akka-testkit" % akkaVersion % Test, + "de.heikoseeberger" %% "akka-log4j" % "1.6.1" % Test, + "org.scalatest" %% "scalatest" % "3.0.5" % Test, + "org.scalacheck" %% "scalacheck" % "1.14.0" % Test, + "org.apache.logging.log4j" % "log4j-api" % "2.11.1" % Test, + "org.apache.logging.log4j" % "log4j-core" % "2.11.1" % Test, + "org.apache.logging.log4j" % "log4j-slf4j-impl" % "2.11.1" % Test, + "org.apache.logging.log4j" %% "log4j-api-scala" % "11.0" % Test, + ) + }, + autoAPIMappings := true, + // TODO create new github pages target + apiURL := Some(url("http://etaty.github.io/rediscala/")) +) lazy val root = (project in file(".")).settings(common, name := "rediscala") lazy val bench = (project in file("src/bench")) .settings( - name := "rediscala-bench", - testFrameworks += new TestFramework("org.scalameter.ScalaMeterFramework"), - parallelExecution in Test := false, - logBuffered := false, - - libraryDependencies ++= Seq( - "com.storm-enroute" %% "scalameter" % "0.9" - ) - ).dependsOn(root) + name := "rediscala-bench", + testFrameworks += new TestFramework("org.scalameter.ScalaMeterFramework"), + parallelExecution in Test := false, + logBuffered := false, + libraryDependencies ++= Seq( + "com.storm-enroute" %% "scalameter" % "0.9" + ) + ) + .dependsOn(root) diff --git a/src/test/resources/application.conf b/src/test/resources/application.conf new file mode 100644 index 00000000..c98b2138 --- /dev/null +++ b/src/test/resources/application.conf @@ -0,0 +1,4 @@ +akka { + loggers = ["de.heikoseeberger.akkalog4j.Log4jLogger"] + loglevel = "DEBUG" +} \ No newline at end of file diff --git a/src/test/scala/redis/RedisClusterTest.scala b/src/test/scala/redis/RedisClusterTest.scala index 15d15e0f..dce2b0a5 100644 --- a/src/test/scala/redis/RedisClusterTest.scala +++ b/src/test/scala/redis/RedisClusterTest.scala @@ -96,22 +96,19 @@ class RedisClusterTest extends RedisClusterClients { redisCluster .groupByCluserServer(Seq("{foo1}1", "{foo2}1", "{foo1}2", "{foo2}2")) .sortBy(_.head) - .toList shouldBe (Seq(Seq("{foo2}1", "{foo2}2"), Seq("{foo1}1", "{foo1}2")).sortBy(_.head)) + .toList shouldBe Seq(Seq("{foo2}1", "{foo2}2"), Seq("{foo1}1", "{foo1}2")).sortBy(_.head) } } "long run" should { "wait" in { - println("set " + redisCluster.getClusterAndConnection(RedisComputeSlot.hashSlot("foo1")).get._1.master.toString) - Await.result(redisCluster.set[String]("foo1", "FOO"), timeOut) - Await.result(redisCluster.get[String]("foo1"), timeOut) - println("wait...") - // Thread.sleep(15000) - println("get") - Await.result(redisCluster.get[String]("foo1"), timeOut) shouldBe Some("FOO") - + log.debug("set " + redisCluster.getClusterAndConnection(RedisComputeSlot.hashSlot("foo1")).get._1.master.toString) + redisCluster.set[String]("foo1", "FOO").futureValue + redisCluster.get[String]("foo1").futureValue + log.debug("wait...") + log.debug("get") + redisCluster.get[String]("foo1").futureValue shouldBe Some("FOO") } - } "clusterInfo" should { @@ -122,9 +119,6 @@ class RedisClusterTest extends RedisClusterClients { println(s"Key ${v._1} value ${v._2}") } res("cluster_state") shouldBe "ok" - res("cluster_slots_ok") shouldBe "16384" - res("cluster_known_nodes") shouldBe "6" - res("cluster_size") shouldBe "3" } } @@ -136,7 +130,6 @@ class RedisClusterTest extends RedisClusterClients { println(m.toString) } res.size shouldBe 6 - res.count(_.master != "-") shouldBe 3 res.count(_.link_state == "connected") shouldBe 6 } } diff --git a/src/test/scala/redis/RedisPubSubSpec.scala b/src/test/scala/redis/RedisPubSubSpec.scala index 548b7e00..1808a40d 100644 --- a/src/test/scala/redis/RedisPubSubSpec.scala +++ b/src/test/scala/redis/RedisPubSubSpec.scala @@ -1,10 +1,11 @@ package redis -import scala.concurrent.Await import redis.api.pubsub._ import redis.actors.RedisSubscriberActor import java.net.InetSocketAddress -import akka.actor.{Props, ActorRef} +import java.util.concurrent.atomic.AtomicInteger + +import akka.actor.{ActorRef, Props} import akka.testkit.{TestActorRef, TestProbe} import akka.util.ByteString @@ -13,33 +14,22 @@ class RedisPubSubSpec extends RedisStandaloneServer { "PubSub test" should { "ok (client + callback)" in { - - var redisPubSub: RedisPubSub = null - - redisPubSub = RedisPubSub( + val receivedMessages = new AtomicInteger() + RedisPubSub( port = port, channels = Seq("chan1", "secondChannel"), patterns = Seq("chan*"), onMessage = (m: Message) => { - redisPubSub.unsubscribe("chan1", "secondChannel") - redisPubSub.punsubscribe("chan*") - redisPubSub.subscribe(m.data.utf8String) - redisPubSub.psubscribe("next*") + log.debug(s"received $m") + receivedMessages.incrementAndGet() } ) - Thread.sleep(2000) - - val p = redis.publish("chan1", "nextChan") - val noListener = redis.publish("noListenerChan", "message") - Await.result(p, timeOut) shouldBe 2 - Await.result(noListener, timeOut) shouldBe 0 - - Thread.sleep(2000) - val nextChan = redis.publish("nextChan", "message") - val p2 = redis.publish("chan1", "nextChan") - Await.result(p2, timeOut) shouldBe 0 - Await.result(nextChan, timeOut) shouldBe 2 + eventually { + redis.publish("chan1", "nextChan").futureValue shouldBe 2 + redis.publish("noListenerChan", "message").futureValue shouldBe 0 + receivedMessages.get() shouldBe 1 + } } "ok (actor)" in { diff --git a/src/test/scala/redis/RedisSpec.scala b/src/test/scala/redis/RedisSpec.scala index 87c69e20..86599cc4 100644 --- a/src/test/scala/redis/RedisSpec.scala +++ b/src/test/scala/redis/RedisSpec.scala @@ -8,8 +8,7 @@ import java.util.concurrent.atomic.AtomicInteger import akka.actor.ActorSystem import akka.testkit.TestKit import akka.util.Timeout -import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpec, WordSpecLike} -import org.scalatest.concurrent.{Eventually, ScalaFutures} +import org.scalatest.{BeforeAndAfterAll} import scala.collection.JavaConverters._ import scala.concurrent.Future @@ -23,8 +22,7 @@ object RedisServerHelper { val redisHost = "127.0.0.1" // remove stacktrace when we stop the process - val processLogger = - ProcessLogger(line => println(line), line => Console.err.println(line)) + val processLogger = ProcessLogger(line => println(line), line => Console.err.println(line)) val redisServerCmd = "redis-server" val redisCliCmd = "redis-cli" val redisServerLogLevel = "" @@ -32,10 +30,7 @@ object RedisServerHelper { val portNumber = new AtomicInteger(10500) } -abstract class RedisHelper - extends TestKit(ActorSystem()) - with TestBase - with BeforeAndAfterAll { +abstract class RedisHelper extends TestKit(ActorSystem()) with TestBase with BeforeAndAfterAll { import scala.concurrent.duration._ @@ -46,7 +41,6 @@ abstract class RedisHelper val timeOut = 10 seconds val longTimeOut = 100 seconds - override protected def beforeAll(): Unit = { setup() } @@ -55,23 +49,52 @@ abstract class RedisHelper TestKit.shutdownActorSystem(system) cleanup() } -// override def map(fs: => Fragments) = { -// setup() -// fs ^ -// step({ -// TestKit.shutdownActorSystem(system) -// cleanup() -// }) -// } def setup() def cleanup() + class RedisManager(implicit system: ActorSystem) { + + import RedisServerHelper._ + + var processes: Seq[RedisProcess] = Seq.empty + + def newSentinelProcess(masterName: String, masterPort: Int, port: Int = portNumber.incrementAndGet()) = { + startProcess(new SentinelProcess(masterName, masterPort, port)) + } + + def newSlaveProcess(masterPort: Int, port: Int = portNumber.incrementAndGet()) = { + startProcess(new SlaveProcess(masterPort, port)) + } + + def newRedisProcess(port: Int = portNumber.incrementAndGet()) = { + startProcess(new RedisProcess(port)) + } + + private def startProcess(process: RedisProcess): RedisProcess = { + process.start() + ensureRedisStarted(redisHost, process.port) + processes = processes :+ process + process + } + + def stopAll() = { + processes.foreach(_.stop()) + } + + } + + protected def ensureRedisStarted(host: String, port: Int): Unit = { + val client = RedisClient(host, port) + eventually { + client.ping().futureValue + } + } + } -case class RedisVersion(major: Int, minor: Int, patch: Int) - extends Ordered[RedisVersion] { +case class RedisVersion(major: Int, minor: Int, patch: Int) extends Ordered[RedisVersion] { import scala.math.Ordered.orderingToOrdered @@ -89,52 +112,46 @@ abstract class RedisStandaloneServer extends RedisHelper { val port = server.port lazy val redis = RedisClient(port = port) - def redisVersion(): Future[Option[RedisVersion]] = redis.info("Server").map { - info => - info - .split("\r\n") - .drop(1) - .flatMap { line => - line.split(":") match { - case Array(key, value) => List(key -> value) - case _ => List.empty - } + def redisVersion(): Future[Option[RedisVersion]] = redis.info("Server").map { info => + info + .split("\r\n") + .drop(1) + .flatMap { line => + line.split(":") match { + case Array(key, value) => List(key -> value) + case _ => List.empty } - .find(_._1 == "redis_version") - .map(_._2.split("\\.") match { - case Array(major, minor, patch) => - RedisVersion(major.toInt, minor.toInt, patch.toInt) - }) + } + .find(_._1 == "redis_version") + .map(_._2.split("\\.") match { + case Array(major, minor, patch) => + RedisVersion(major.toInt, minor.toInt, patch.toInt) + }) } def withRedisServer[T](block: (Int) => T): T = { val serverProcess = redisManager.newRedisProcess() - serverProcess.start() - Thread.sleep(3000) // wait for server start val result = Try(block(serverProcess.port)) serverProcess.stop() result.get } - override def setup() = { - Thread.sleep(3000) - } + override def setup() = {} override def cleanup() = { redisManager.stopAll() } } -abstract class RedisSentinelClients(val masterName: String = "mymaster") - extends RedisHelper { +abstract class RedisSentinelClients(val masterName: String = "mymaster") extends RedisHelper { import RedisServerHelper._ - val masterPort = portNumber.getAndIncrement() - val slavePort1 = portNumber.getAndIncrement() - val slavePort2 = portNumber.getAndIncrement() - val sentinelPort1 = portNumber.getAndIncrement() - val sentinelPort2 = portNumber.getAndIncrement() + val masterPort = portNumber.incrementAndGet() + val slavePort1 = portNumber.incrementAndGet() + val slavePort2 = portNumber.incrementAndGet() + val sentinelPort1 = portNumber.incrementAndGet() + val sentinelPort2 = portNumber.incrementAndGet() val sentinelPorts = Seq(sentinelPort1, sentinelPort2) @@ -148,7 +165,6 @@ abstract class RedisSentinelClients(val masterName: String = "mymaster") val redisManager = new RedisManager() val master = redisManager.newRedisProcess(masterPort) - Thread.sleep(1000) val slave1 = redisManager.newSlaveProcess(masterPort, slavePort1) val slave2 = redisManager.newSlaveProcess(masterPort, slavePort2) @@ -165,9 +181,7 @@ abstract class RedisSentinelClients(val masterName: String = "mymaster") redisManager.newSentinelProcess(masterName, masterPort) } - override def setup() = { - Thread.sleep(10000) - } + override def setup() = {} override def cleanup() = { redisManager.stopAll() @@ -175,62 +189,23 @@ abstract class RedisSentinelClients(val masterName: String = "mymaster") } -class RedisManager { - - import RedisServerHelper._ - - var processes: Seq[RedisProcess] = Seq.empty - - def newSentinelProcess(masterName: String, - masterPort: Int, - port: Int = portNumber.getAndIncrement()) = { - val sentinelProcess = new SentinelProcess(masterName, masterPort, port) - sentinelProcess.start() - processes = processes :+ sentinelProcess - sentinelProcess - } - - def newSlaveProcess(masterPort: Int, - port: Int = portNumber.getAndIncrement()) = { - val slaveProcess = new SlaveProcess(masterPort, port) - slaveProcess.start() - processes = processes :+ slaveProcess - slaveProcess - } - - def newRedisProcess(port: Int = portNumber.getAndIncrement()) = { - val redisProcess = new RedisProcess(port) - redisProcess.start() - processes = processes :+ redisProcess - redisProcess - } - - def stopAll() = { - processes.foreach(_.stop()) - Thread.sleep(5000) - } - -} - abstract class RedisClusterClients() extends RedisHelper { import RedisServerHelper._ var processes: Seq[Process] = Seq.empty - val fileDir = new java.io.File("/tmp/redis" + System.currentTimeMillis()) + protected val fileDir = createTempDirectory().toFile def newNode(port: Int) = s"$redisServerCmd --port $port --cluster-enabled yes --cluster-config-file nodes-${port}.conf --cluster-node-timeout 30000 --appendonly yes --appendfilename appendonly-${port}.aof --dbfilename dump-${port}.rdb --logfile ${port}.log --daemonize yes" - val nodePorts = (0 to 5).map(_ => portNumber.getAndIncrement()) + val nodePorts = (0 to 5).map(_ => portNumber.incrementAndGet()) override def setup() = { println("Setup") fileDir.mkdirs() - processes = - nodePorts.map(s => Process(newNode(s), fileDir).run(processLogger)) - Thread.sleep(2000) + processes = nodePorts.map(s => Process(newNode(s), fileDir).run(processLogger)) val nodes = nodePorts.map(s => redisHost + ":" + s).mkString(" ") val createClusterCmd = @@ -240,8 +215,7 @@ abstract class RedisClusterClients() extends RedisHelper { .run( new ProcessIO( (writeInput: OutputStream) => { - // - Thread.sleep(2000) +// Thread.sleep(2000) println("yes") writeInput.write("yes\n".getBytes) writeInput.flush @@ -260,19 +234,24 @@ abstract class RedisClusterClients() extends RedisHelper { ) ) .exitValue() - Thread.sleep(5000) + val servers = nodePorts.map { port => RedisServer(host = redisHost, port = port)} + val client = RedisCluster(servers) + eventually { + val clusterInfo = client.clusterInfo().futureValue + clusterInfo("cluster_known_nodes") shouldBe nodePorts.length.toString + } + client.stop() } override def cleanup() = { println("Stop begin") - //cluster shutdown - nodePorts.map { port => + + nodePorts foreach { port => val out = new Socket(redisHost, port).getOutputStream out.write("SHUTDOWN NOSAVE\n".getBytes) - out.flush + out.flush() } - Thread.sleep(6000) //Await.ready(RedisClient(port = port).shutdown(redis.api.NOSAVE),timeOut) } processes.foreach(_.destroy()) @@ -307,8 +286,6 @@ class RedisProcess(val port: Int) { out.flush out.close() - Thread.sleep(500) - } catch { case NonFatal(e) => e.printStackTrace() } finally { @@ -320,8 +297,7 @@ class RedisProcess(val port: Int) { } } -class SentinelProcess(masterName: String, masterPort: Int, port: Int) - extends RedisProcess(port) { +class SentinelProcess(masterName: String, masterPort: Int, port: Int) extends RedisProcess(port) { lazy val sentinelConfPath = { val sentinelConf = diff --git a/src/test/scala/redis/SentinelPoolSpec.scala b/src/test/scala/redis/SentinelPoolSpec.scala index 29f83791..09c9f6c6 100644 --- a/src/test/scala/redis/SentinelPoolSpec.scala +++ b/src/test/scala/redis/SentinelPoolSpec.scala @@ -2,7 +2,6 @@ package redis import redis.RedisServerHelper.redisHost -import scala.concurrent.duration._ class SentinelMutablePoolSpec extends RedisSentinelClients("SentinelMutablePoolSpec") { var redisPool: RedisClientMutablePool = null @@ -14,13 +13,15 @@ class SentinelMutablePoolSpec extends RedisSentinelClients("SentinelMutablePoolS "mutable pool" should { "add remove" in { - Thread.sleep(1000) - redisPool.redisConnectionPool.size shouldBe 1 + eventually { + redisPool.redisConnectionPool.size shouldBe 1 + } redisPool.addServer(RedisServer(redisHost, slavePort2)) redisPool.addServer(RedisServer(redisHost, slavePort2)) - Thread.sleep(5000) - redisPool.redisConnectionPool.size shouldBe 2 + eventually { + redisPool.redisConnectionPool.size shouldBe 2 + } val key = "keyPoolDb0" redisClient.set(key, "hello").futureValue @@ -28,9 +29,7 @@ class SentinelMutablePoolSpec extends RedisSentinelClients("SentinelMutablePoolS redisPool.get[String](key).futureValue shouldBe Some("hello") redisPool.get[String](key).futureValue shouldBe Some("hello") - within(1 second) { - redisPool.removeServer(RedisServer(redisHost, slavePort2)) - } + redisPool.removeServer(RedisServer(redisHost, slavePort2)) eventually { redisPool.redisConnectionPool.size shouldBe 1 @@ -38,7 +37,6 @@ class SentinelMutablePoolSpec extends RedisSentinelClients("SentinelMutablePoolS redisPool.get[String](key).futureValue shouldBe Some("hello") redisPool.get[String](key).futureValue shouldBe Some("hello") - } } @@ -51,9 +49,8 @@ class SentinelMonitoredRedisClientMasterSlavesSpec SentinelMonitoredRedisClientMasterSlaves(master = masterName, sentinels = sentinelPorts.map((redisHost, _))) "sentinel slave pool" should { "add and remove" in { - Thread.sleep(10000) - redisMasterSlavesPool.set("test", "value").futureValue eventually { + redisMasterSlavesPool.set("test", "value").futureValue redisMasterSlavesPool.slavesClients.redisConnectionPool.size shouldBe 2 } @@ -64,19 +61,22 @@ class SentinelMonitoredRedisClientMasterSlavesSpec } newSlave.stop() - redisMasterSlavesPool.get[String]("test").futureValue shouldBe Some("value") + eventually { + redisMasterSlavesPool.get[String]("test").futureValue shouldBe Some("value") + } slave1.stop() slave2.stop() - awaitAssert(redisMasterSlavesPool.slavesClients.redisConnectionPool.size shouldBe 0, 20 second) + eventually { + redisMasterSlavesPool.slavesClients.redisConnectionPool.size shouldBe 0 + } + redisMasterSlavesPool.get[String]("test").futureValue shouldBe Some("value") newSlaveProcess() - //println("************************** newSlaveProcess "+RedisServerHelper.portNumber.get()) eventually { redisMasterSlavesPool.slavesClients.redisConnectionPool.size shouldBe 1 } - redisMasterSlavesPool.slavesClients.redisConnectionPool.size shouldBe 1 } /* "changemaster" in { diff --git a/src/test/scala/redis/TestBase.scala b/src/test/scala/redis/TestBase.scala index 95170df1..1ce5175c 100644 --- a/src/test/scala/redis/TestBase.scala +++ b/src/test/scala/redis/TestBase.scala @@ -1,28 +1,40 @@ package redis -import org.scalactic.Prettifier +import java.nio.file.{Files, Path} + +import org.apache.logging.log4j.scala.Logger import org.scalatest.concurrent.{Eventually, ScalaFutures} import org.scalatest.matchers.{MatchResult, Matcher} import org.scalatest.{Matchers, WordSpecLike} trait TestBase extends WordSpecLike with Matchers with ScalaFutures with Eventually { import org.scalatest.time.{Millis, Seconds, Span} - implicit protected val defaultPatience = - PatienceConfig(timeout = Span(10, Seconds), interval = Span(20, Millis)) + implicit protected val defaultPatience = PatienceConfig(timeout = Span(10, Seconds), interval = Span(100, Millis)) + + protected val log = Logger(getClass) + + protected def createTempDirectory(): Path = { + val dir = Files.createTempDirectory("rediscala-test-dir") + dir.toFile.deleteOnExit() + dir + } - def beBetween[T: Ordering](right: (T, T)): Matcher[T] = + protected def beBetween[T: Ordering](from: T, to: T): Matcher[T] = { + val range = s"[$from, $to]" new Matcher[T] { def apply(left: T): MatchResult = { - val (from, to) = right - val ordering = implicitly[Ordering[T]] - val isBetween = ordering.lteq(from, left) && ordering.gteq(to, left) + val ordering = implicitly[Ordering[T]] + val isBetween = ordering.lteq(from, left) && ordering.gteq(to, left) MatchResult( isBetween, - s"$left wasn't in range $right", - s"$left was in range $right", - Vector(left, right) + s"$left wasn't in range $range", + s"$left was in range $range", + Vector(left, from, to) ) } - override def toString: String = "be between " + Prettifier.default(right) + + override def toString: String = "be between " + range } + } + } diff --git a/src/test/scala/redis/commands/BListsSpec.scala b/src/test/scala/redis/commands/BListsSpec.scala index 0fdc4f09..535aaae6 100644 --- a/src/test/scala/redis/commands/BListsSpec.scala +++ b/src/test/scala/redis/commands/BListsSpec.scala @@ -25,12 +25,13 @@ class BListsSpec extends RedisStandaloneServer { "BLPOP blocking" in { val redisB = RedisBlockingClient(port = port) - val rr = within(1.seconds, 10.seconds) { + val blockTime = 1.second + val rr = within(blockTime, blockTime * 2) { val r = redis .del("blpopBlock") .flatMap(_ => { val blpop = redisB.blpop(Seq("blpopBlock")) - Thread.sleep(1000) + Thread.sleep(blockTime.toMillis) redis.rpush("blpopBlock", "a", "b", "c") blpop }) diff --git a/src/test/scala/redis/commands/ConnectionSpec.scala b/src/test/scala/redis/commands/ConnectionSpec.scala index 56eb9875..9a27bab7 100644 --- a/src/test/scala/redis/commands/ConnectionSpec.scala +++ b/src/test/scala/redis/commands/ConnectionSpec.scala @@ -20,11 +20,7 @@ class ConnectionSpec extends RedisStandaloneServer { } "QUIT" in { // todo test that the TCP connection is reset. - val f = redis.quit() - Thread.sleep(1000) - val ping = redis.ping() - Await.result(f, timeOut) shouldBe true - Await.result(ping, timeOut) shouldBe "PONG" + redis.quit().futureValue shouldBe true } "SELECT" in { Await.result(redis.select(1), timeOut) shouldBe true diff --git a/src/test/scala/redis/commands/KeysSpec.scala b/src/test/scala/redis/commands/KeysSpec.scala index 13a7092e..7db161c7 100644 --- a/src/test/scala/redis/commands/KeysSpec.scala +++ b/src/test/scala/redis/commands/KeysSpec.scala @@ -65,21 +65,13 @@ class KeysSpec extends RedisStandaloneServer { } "EXPIRE" in { - val r = for { - s <- redis.set("expireKey", "value") - e <- redis.expire("expireKey", 1) - e2 <- redis.expire("expireKeyNonexisting", 1) - expired <- { - Thread.sleep(1000) - redis.get("expireKey") - } - } yield { - s shouldBe true - e shouldBe true - e2 shouldBe false - expired shouldBe None + redis.set("expireKey", "value").futureValue shouldBe true + redis.expire("expireKey", 1).futureValue shouldBe true + redis.expire("expireKeyNonexisting", 1).futureValue shouldBe false + + eventually { + redis.get("expireKey").futureValue shouldBe empty } - Await.result(r, timeOut) } "EXPIREAT" in { @@ -103,8 +95,8 @@ class KeysSpec extends RedisStandaloneServer { k2 <- redis.keys("keysKey?") k3 <- redis.keys("keysKeyNomatch") } yield { - k should contain theSameElementsAs(Seq("keysKey2", "keysKey")) - k2 should contain theSameElementsAs(Seq("keysKey2")) + k should contain theSameElementsAs (Seq("keysKey2", "keysKey")) + k2 should contain theSameElementsAs (Seq("keysKey2")) k3 shouldBe empty } Await.result(r, timeOut) @@ -129,7 +121,7 @@ class KeysSpec extends RedisStandaloneServer { } "MOVE" in { - val redisMove = RedisClient(port=port) + val redisMove = RedisClient(port = port) val r = for { _ <- redis.set("moveKey", "value") _ <- redisMove.select(1) @@ -147,39 +139,39 @@ class KeysSpec extends RedisStandaloneServer { Await.result(r, timeOut) } - "REFCOUNT" in { - val r = for { - _ <- redis.set("objectRefcount", "objectRefcountValue") - ref <- redis.objectRefcount("objectRefcount") - refNotFound <- redis.objectRefcount("objectRefcountNotFound") - } yield { - ref shouldBe Some(1) - refNotFound shouldBe empty - } - Await.result(r, timeOut) + "REFCOUNT" in { + val r = for { + _ <- redis.set("objectRefcount", "objectRefcountValue") + ref <- redis.objectRefcount("objectRefcount") + refNotFound <- redis.objectRefcount("objectRefcountNotFound") + } yield { + ref shouldBe Some(1) + refNotFound shouldBe empty } - "IDLETIME" in { - val r = for { - _ <- redis.set("objectIdletime", "objectRefcountValue") - time <- redis.objectIdletime("objectIdletime") - timeNotFound <- redis.objectIdletime("objectIdletimeNotFound") - } yield { - time shouldBe defined - timeNotFound shouldBe empty - } - Await.result(r, timeOut) + Await.result(r, timeOut) + } + "IDLETIME" in { + val r = for { + _ <- redis.set("objectIdletime", "objectRefcountValue") + time <- redis.objectIdletime("objectIdletime") + timeNotFound <- redis.objectIdletime("objectIdletimeNotFound") + } yield { + time shouldBe defined + timeNotFound shouldBe empty } - "ENCODING" in { - val r = for { - _ <- redis.set("objectEncoding", "objectRefcountValue") - encoding <- redis.objectEncoding("objectEncoding") - encodingNotFound <- redis.objectEncoding("objectEncodingNotFound") - } yield { - encoding shouldBe defined - encodingNotFound shouldBe empty - } - Await.result(r, timeOut) + Await.result(r, timeOut) + } + "ENCODING" in { + val r = for { + _ <- redis.set("objectEncoding", "objectRefcountValue") + encoding <- redis.objectEncoding("objectEncoding") + encodingNotFound <- redis.objectEncoding("objectEncodingNotFound") + } yield { + encoding shouldBe defined + encodingNotFound shouldBe empty } + Await.result(r, timeOut) + } "PERSIST" in { val r = for { @@ -199,21 +191,12 @@ class KeysSpec extends RedisStandaloneServer { } "PEXPIRE" in { - val r = for { - s <- redis.set("pexpireKey", "value") - e <- redis.pexpire("pexpireKey", 1500) - e2 <- redis.expire("pexpireKeyNonexisting", 1500) - expired <- { - Thread.sleep(1500) - redis.get("pexpireKey") - } - } yield { - s shouldBe true - e shouldBe true - e2 shouldBe false - expired shouldBe None + redis.set("pexpireKey", "value").futureValue shouldBe true + redis.pexpire("pexpireKey", 1000).futureValue shouldBe true + redis.expire("pexpireKeyNonexisting", 1000).futureValue shouldBe false + eventually { + redis.get("pexpireKey").futureValue shouldBe empty } - Await.result(r, timeOut) } "PEXPIREAT" in { @@ -229,7 +212,6 @@ class KeysSpec extends RedisStandaloneServer { Await.result(r, timeOut) } - "PEXPIREAT TTL" in { val r = for { s <- redis.set("pttlKey", "value") @@ -323,17 +305,18 @@ class KeysSpec extends RedisStandaloneServer { // @see https://gist.github.com/jacqui/983051 "SORT" in { - val init = Future.sequence(Seq( - redis.hset("bonds|1", "bid_price", 96.01), - redis.hset("bonds|1", "ask_price", 97.53), - redis.hset("bonds|2", "bid_price", 95.50), - redis.hset("bonds|2", "ask_price", 98.25), - redis.del("bond_ids"), - redis.sadd("bond_ids", 1), - redis.sadd("bond_ids", 2), - redis.del("sortAlpha"), - redis.rpush("sortAlpha", "abc", "xyz") - )) + val init = Future.sequence( + Seq( + redis.hset("bonds|1", "bid_price", 96.01), + redis.hset("bonds|1", "ask_price", 97.53), + redis.hset("bonds|2", "bid_price", 95.50), + redis.hset("bonds|2", "ask_price", 98.25), + redis.del("bond_ids"), + redis.sadd("bond_ids", 1), + redis.sadd("bond_ids", 2), + redis.del("sortAlpha"), + redis.rpush("sortAlpha", "abc", "xyz") + )) val r = for { _ <- init sort <- redis.sort("bond_ids") diff --git a/src/test/scala/redis/commands/ScriptingSpec.scala b/src/test/scala/redis/commands/ScriptingSpec.scala index 5df82071..69976f24 100644 --- a/src/test/scala/redis/commands/ScriptingSpec.scala +++ b/src/test/scala/redis/commands/ScriptingSpec.scala @@ -73,7 +73,6 @@ class ScriptingSpec extends RedisStandaloneServer { Await.result(redisKiller.scriptKill(), timeOut) } - // infinite script (5 seconds) val infiniteScript = redisScriptLauncher.eval( """ |local i = 1 @@ -81,7 +80,7 @@ class ScriptingSpec extends RedisStandaloneServer { |end |return 0 """.stripMargin) - Thread.sleep(1000) + Thread.sleep(500) eventually { redisKiller.scriptKill().futureValue shouldBe true } diff --git a/src/test/scala/redis/commands/StringsSpec.scala b/src/test/scala/redis/commands/StringsSpec.scala index d9047de0..826d57dd 100644 --- a/src/test/scala/redis/commands/StringsSpec.scala +++ b/src/test/scala/redis/commands/StringsSpec.scala @@ -241,52 +241,25 @@ class StringsSpec extends RedisStandaloneServer { } "PSETEX" in { - val r = redis - .psetex("psetexKey", 2000, "temp value") - .flatMap(x => { - x shouldBe true - redis - .get("psetexKey") - .flatMap(v => { - v shouldBe Some(ByteString("temp value")) - Thread.sleep(2000) - redis.get("psetexKey") - }) - }) - Await.result(r, timeOut) shouldBe None + redis.psetex("psetexKey", 1000, "temp value").futureValue shouldBe true + redis.get("psetexKey").futureValue shouldBe Some(ByteString("temp value")) + eventually { redis.get("psetexKey").futureValue shouldBe empty } } "SET" in { - val rr = for { - r <- redis.set("setKey", "value") - ex <- redis.set("setKey", "value", exSeconds = Some(2)) - nxex <- redis.set("setKey2", "value", NX = true, exSeconds = Some(60)) - ttlnxex <- redis.ttl("setKey2") - xxex <- redis.set("setKey2", "value", XX = true, exSeconds = Some(180)) - ttlxxex <- redis.ttl("setKey2") - _ <- redis.del("setKey2") - px <- redis.set("setKey", "value", pxMilliseconds = Some(1)) - nxTrue <- { - Thread.sleep(20) - redis.set("setKey", "value", NX = true) - } - xx <- redis.set("setKey", "value", XX = true) - nxFalse <- redis.set("setKey", "value", NX = true) - } yield { - r shouldBe true - ex shouldBe true - nxex shouldBe true - ttlnxex should be >= 0L - ttlnxex should be <= 60L - xxex shouldBe true - ttlxxex should be >= 60L - ttlxxex should be <= 180L - px shouldBe true - nxTrue shouldBe true // because pxMilliseconds = 1 millisecond - xx shouldBe true - nxFalse shouldBe false + redis.set("setKey", "value").futureValue shouldBe true + redis.set("setKey", "value", exSeconds = Some(2)).futureValue shouldBe true + redis.set("setKey2", "value", NX = true, exSeconds = Some(60)).futureValue shouldBe true + redis.ttl("setKey2").futureValue should beBetween(0L, 60L) + redis.set("setKey2", "value", XX = true, exSeconds = Some(180)).futureValue shouldBe true + redis.ttl("setKey2").futureValue should beBetween(60L, 180L) + redis.del("setKey2").futureValue + redis.set("setKey", "value", pxMilliseconds = Some(1)).futureValue shouldBe true + eventually { + redis.set("setKey", "value", NX = true).futureValue shouldBe true } - Await.result(rr, timeOut) + redis.set("setKey", "value", XX = true).futureValue shouldBe true + redis.set("setKey", "value", NX = true).futureValue shouldBe false } "SETBIT" in { @@ -306,19 +279,9 @@ class StringsSpec extends RedisStandaloneServer { } "SETEX" in { - val r = redis - .setex("setexKey", 1, "temp value") - .flatMap(x => { - x shouldBe true - redis - .get("setexKey") - .flatMap(v => { - v shouldBe Some(ByteString("temp value")) - Thread.sleep(2000) - redis.get("setexKey") - }) - }) - Await.result(r, timeOut) shouldBe None + redis.setex("setexKey", 1, "temp value").futureValue shouldBe true + redis.get("setexKey").futureValue shouldBe Some(ByteString("temp value")) + eventually { redis.get("setexKey").futureValue shouldBe empty } } "SETNX" in { From 35072f4f90267b66076c471667786d70e8981937 Mon Sep 17 00:00:00 2001 From: Alexey Kardapoltsev Date: Fri, 22 Feb 2019 12:01:19 +0700 Subject: [PATCH 03/11] add logger config --- src/test/resources/log4j2.xml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/test/resources/log4j2.xml diff --git a/src/test/resources/log4j2.xml b/src/test/resources/log4j2.xml new file mode 100644 index 00000000..126c95b3 --- /dev/null +++ b/src/test/resources/log4j2.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file From 3615c38b6d5272c9be8fd207d550f1f60746ce80 Mon Sep 17 00:00:00 2001 From: Alexey Kardapoltsev Date: Sat, 23 Feb 2019 09:54:10 +0700 Subject: [PATCH 04/11] Remove warnings --- build.sbt | 2 +- src/test/resources/application.conf | 7 ++++-- src/test/scala/redis/RedisSpec.scala | 22 +++++++++++-------- src/test/scala/redis/TestBase.scala | 3 ++- .../scala/redis/commands/ConnectionSpec.scala | 13 +++++------ .../scala/redis/commands/ServerSpec.scala | 18 ++++----------- 6 files changed, 30 insertions(+), 35 deletions(-) diff --git a/build.sbt b/build.sbt index 119502bc..2557c554 100644 --- a/build.sbt +++ b/build.sbt @@ -31,7 +31,7 @@ lazy val common = Seq( "UTF-8", "-Xlint", "-deprecation", -// "-Xfatal-warnings", + "-Xfatal-warnings", "-feature", "-language:postfixOps", "-unchecked" diff --git a/src/test/resources/application.conf b/src/test/resources/application.conf index c98b2138..39086864 100644 --- a/src/test/resources/application.conf +++ b/src/test/resources/application.conf @@ -1,4 +1,7 @@ akka { loggers = ["de.heikoseeberger.akkalog4j.Log4jLogger"] - loglevel = "DEBUG" -} \ No newline at end of file + loglevel = "INFO" + test { + timefactor = 10.0 + } +} diff --git a/src/test/scala/redis/RedisSpec.scala b/src/test/scala/redis/RedisSpec.scala index 86599cc4..e2245b6e 100644 --- a/src/test/scala/redis/RedisSpec.scala +++ b/src/test/scala/redis/RedisSpec.scala @@ -7,8 +7,8 @@ import java.util.concurrent.atomic.AtomicInteger import akka.actor.ActorSystem import akka.testkit.TestKit -import akka.util.Timeout -import org.scalatest.{BeforeAndAfterAll} +import org.apache.logging.log4j.scala.Logger +import org.scalatest.BeforeAndAfterAll import scala.collection.JavaConverters._ import scala.concurrent.Future @@ -22,7 +22,6 @@ object RedisServerHelper { val redisHost = "127.0.0.1" // remove stacktrace when we stop the process - val processLogger = ProcessLogger(line => println(line), line => Console.err.println(line)) val redisServerCmd = "redis-server" val redisCliCmd = "redis-cli" val redisServerLogLevel = "" @@ -31,15 +30,18 @@ object RedisServerHelper { } abstract class RedisHelper extends TestKit(ActorSystem()) with TestBase with BeforeAndAfterAll { + protected val processLogger = ProcessLogger(line => log.debug(line), line => log.error(line)) import scala.concurrent.duration._ - implicit val executionContext = - system.dispatchers.lookup(Redis.dispatcher.name) + implicit val executionContext = system.dispatchers.lookup(Redis.dispatcher.name) - implicit val timeout = Timeout(10 seconds) - val timeOut = 10 seconds - val longTimeOut = 100 seconds + override def spanScaleFactor: Double = { + testKitSettings.TestTimeFactor + } + + + val timeOut = 10.seconds override protected def beforeAll(): Unit = { setup() @@ -54,7 +56,7 @@ abstract class RedisHelper extends TestKit(ActorSystem()) with TestBase with Bef def cleanup() - class RedisManager(implicit system: ActorSystem) { + class RedisManager { import RedisServerHelper._ @@ -272,6 +274,8 @@ import redis.RedisServerHelper._ class RedisProcess(val port: Int) { var server: Process = null val cmd = s"${redisServerCmd} --port $port ${redisServerLogLevel}" + protected val log = Logger(getClass) + protected val processLogger = ProcessLogger(line => log.debug(line), line => log.error(line)) def start() = { if (server == null) diff --git a/src/test/scala/redis/TestBase.scala b/src/test/scala/redis/TestBase.scala index 1ce5175c..3914aa5c 100644 --- a/src/test/scala/redis/TestBase.scala +++ b/src/test/scala/redis/TestBase.scala @@ -9,7 +9,8 @@ import org.scalatest.{Matchers, WordSpecLike} trait TestBase extends WordSpecLike with Matchers with ScalaFutures with Eventually { import org.scalatest.time.{Millis, Seconds, Span} - implicit protected val defaultPatience = PatienceConfig(timeout = Span(10, Seconds), interval = Span(100, Millis)) + implicit protected val defaultPatience = + PatienceConfig(timeout = scaled(Span(1, Seconds)), interval = scaled(Span(10, Millis))) protected val log = Logger(getClass) diff --git a/src/test/scala/redis/commands/ConnectionSpec.scala b/src/test/scala/redis/commands/ConnectionSpec.scala index 9a27bab7..c4e20fa3 100644 --- a/src/test/scala/redis/commands/ConnectionSpec.scala +++ b/src/test/scala/redis/commands/ConnectionSpec.scala @@ -1,7 +1,6 @@ package redis.commands import redis._ -import scala.concurrent.Await import akka.util.ByteString import redis.actors.ReplyErrorException @@ -9,24 +8,22 @@ class ConnectionSpec extends RedisStandaloneServer { "Connection commands" should { "AUTH" in { - a[ReplyErrorException] should be thrownBy Await.result(redis.auth("no password"), timeOut) + redis.auth("no password").failed.futureValue shouldBe a[ReplyErrorException] } "ECHO" in { val hello = "Hello World!" - Await.result(redis.echo(hello), timeOut) shouldBe Some(ByteString(hello)) + redis.echo(hello).futureValue shouldBe Some(ByteString(hello)) } "PING" in { - Await.result(redis.ping(), timeOut) shouldBe "PONG" + redis.ping().futureValue shouldBe "PONG" } "QUIT" in { // todo test that the TCP connection is reset. redis.quit().futureValue shouldBe true } "SELECT" in { - Await.result(redis.select(1), timeOut) shouldBe true - Await.result(redis.select(0), timeOut) shouldBe true - a[ReplyErrorException] should be thrownBy Await.result(redis.select(-1), timeOut) - a[ReplyErrorException] should be thrownBy Await.result(redis.select(1000), timeOut) + redis.select(0).futureValue shouldBe true + redis.select(-1).failed.futureValue shouldBe a[ReplyErrorException] } } } diff --git a/src/test/scala/redis/commands/ServerSpec.scala b/src/test/scala/redis/commands/ServerSpec.scala index e997bf2e..09fd1258 100644 --- a/src/test/scala/redis/commands/ServerSpec.scala +++ b/src/test/scala/redis/commands/ServerSpec.scala @@ -14,15 +14,11 @@ class ServerSpec extends RedisStandaloneServer { } "CLIENT KILL" in { - the[ReplyErrorException] thrownBy { - Await.result(redis.clientKill("8.8.8.8", 53), timeOut) - } + redis.clientKill("8.8.8.8", 53).failed.futureValue shouldBe a[ReplyErrorException] } "CLIENT LIST" in { - val list = Await.result(redis.clientList(), timeOut) - list shouldBe a[Seq[Map[String, String]]] - list should not be empty + redis.clientList().futureValue should not be empty } "CLIENT GETNAME" in { @@ -34,10 +30,8 @@ class ServerSpec extends RedisStandaloneServer { } "CONFIG GET" in { - val map = Await.result(redis.configGet("*"), timeOut) - map shouldBe a[Map[String, String]] + val map = redis.configGet("*").futureValue map should not be empty - } "CONFIG SET" in { val r = for { @@ -103,11 +97,7 @@ class ServerSpec extends RedisStandaloneServer { } "TIME" in { - val result = Await.result(redis.time(), timeOut) - withClue(result.toString()) { - - result shouldBe a[Tuple2[Long, Long]] - } + redis.time().futureValue } "BGREWRITEAOF" in { From 9c8e182b569761e11f8df7579da0ecc12b8fc9ef Mon Sep 17 00:00:00 2001 From: Alexey Kardapoltsev Date: Sat, 23 Feb 2019 12:57:24 +0700 Subject: [PATCH 05/11] increase test timeout --- src/test/resources/application.conf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/resources/application.conf b/src/test/resources/application.conf index 39086864..05a682e4 100644 --- a/src/test/resources/application.conf +++ b/src/test/resources/application.conf @@ -2,6 +2,6 @@ akka { loggers = ["de.heikoseeberger.akkalog4j.Log4jLogger"] loglevel = "INFO" test { - timefactor = 10.0 + timefactor = 50.0 } } From 492d520f8eb2b4c37fc075e37da70fe8fce3f4e0 Mon Sep 17 00:00:00 2001 From: Alexey Kardapoltsev Date: Sun, 24 Feb 2019 11:27:50 +0700 Subject: [PATCH 06/11] custom time factor for travis --- .travis.yml | 2 + src/test/resources/application.conf | 3 +- ...onitoredRedisClientMasterSlavesSpec.scala} | 40 ----------------- .../scala/redis/SentinelMutablePoolSpec.scala | 45 +++++++++++++++++++ 4 files changed, 49 insertions(+), 41 deletions(-) rename src/test/scala/redis/{SentinelPoolSpec.scala => SentinelMonitoredRedisClientMasterSlavesSpec.scala} (57%) create mode 100644 src/test/scala/redis/SentinelMutablePoolSpec.scala diff --git a/.travis.yml b/.travis.yml index 400055b4..1c6e1a98 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,5 @@ +env: + TEST_TIME_FACTOR=50 dist: xenial language: scala diff --git a/src/test/resources/application.conf b/src/test/resources/application.conf index 05a682e4..ef37354f 100644 --- a/src/test/resources/application.conf +++ b/src/test/resources/application.conf @@ -2,6 +2,7 @@ akka { loggers = ["de.heikoseeberger.akkalog4j.Log4jLogger"] loglevel = "INFO" test { - timefactor = 50.0 + timefactor = 10 + timefactor = ${?TEST_TIME_FACTOR} } } diff --git a/src/test/scala/redis/SentinelPoolSpec.scala b/src/test/scala/redis/SentinelMonitoredRedisClientMasterSlavesSpec.scala similarity index 57% rename from src/test/scala/redis/SentinelPoolSpec.scala rename to src/test/scala/redis/SentinelMonitoredRedisClientMasterSlavesSpec.scala index 09c9f6c6..3503a10e 100644 --- a/src/test/scala/redis/SentinelPoolSpec.scala +++ b/src/test/scala/redis/SentinelMonitoredRedisClientMasterSlavesSpec.scala @@ -2,46 +2,6 @@ package redis import redis.RedisServerHelper.redisHost -class SentinelMutablePoolSpec extends RedisSentinelClients("SentinelMutablePoolSpec") { - - var redisPool: RedisClientMutablePool = null - - override def setup(): Unit = { - super.setup() - redisPool = RedisClientMutablePool(Seq(RedisServer(redisHost, slavePort1)), masterName) - } - - "mutable pool" should { - "add remove" in { - eventually { - redisPool.redisConnectionPool.size shouldBe 1 - } - - redisPool.addServer(RedisServer(redisHost, slavePort2)) - redisPool.addServer(RedisServer(redisHost, slavePort2)) - eventually { - redisPool.redisConnectionPool.size shouldBe 2 - } - - val key = "keyPoolDb0" - redisClient.set(key, "hello").futureValue - - redisPool.get[String](key).futureValue shouldBe Some("hello") - redisPool.get[String](key).futureValue shouldBe Some("hello") - - redisPool.removeServer(RedisServer(redisHost, slavePort2)) - - eventually { - redisPool.redisConnectionPool.size shouldBe 1 - } - - redisPool.get[String](key).futureValue shouldBe Some("hello") - redisPool.get[String](key).futureValue shouldBe Some("hello") - } - } - -} - class SentinelMonitoredRedisClientMasterSlavesSpec extends RedisSentinelClients("SentinelMonitoredRedisClientMasterSlavesSpec") { diff --git a/src/test/scala/redis/SentinelMutablePoolSpec.scala b/src/test/scala/redis/SentinelMutablePoolSpec.scala new file mode 100644 index 00000000..7b579f83 --- /dev/null +++ b/src/test/scala/redis/SentinelMutablePoolSpec.scala @@ -0,0 +1,45 @@ +package redis + +import redis.RedisServerHelper.redisHost + +class SentinelMutablePoolSpec extends RedisSentinelClients("SentinelMutablePoolSpec") { + + var redisPool: RedisClientMutablePool = null + + override def setup(): Unit = { + super.setup() + redisPool = RedisClientMutablePool(Seq(RedisServer(redisHost, slavePort1)), masterName) + } + + "mutable pool" should { + "add remove" in { + eventually { + redisPool.redisConnectionPool.size shouldBe 1 + } + + redisPool.addServer(RedisServer(redisHost, slavePort2)) + redisPool.addServer(RedisServer(redisHost, slavePort2)) + eventually { + redisPool.redisConnectionPool.size shouldBe 2 + } + + val key = "keyPoolDb0" + redisClient.set(key, "hello").futureValue + + redisPool.get[String](key).futureValue shouldBe Some("hello") + redisPool.get[String](key).futureValue shouldBe Some("hello") + + redisPool.removeServer(RedisServer(redisHost, slavePort2)) + + eventually { + redisPool.redisConnectionPool.size shouldBe 1 + } + + redisPool.get[String](key).futureValue shouldBe Some("hello") + redisPool.get[String](key).futureValue shouldBe Some("hello") + } + } + +} + + From 69338dbbadd285d6da184493441405804b4b0a44 Mon Sep 17 00:00:00 2001 From: Alexey Kardapoltsev Date: Sun, 24 Feb 2019 11:57:19 +0700 Subject: [PATCH 07/11] Remove Await from tests --- .travis.yml | 2 +- src/test/scala/redis/RedisClusterTest.scala | 28 +++--- src/test/scala/redis/RedisPoolSpec.scala | 4 +- src/test/scala/redis/RedisSpec.scala | 4 +- src/test/scala/redis/RedisTest.scala | 15 ++-- .../scala/redis/commands/BListsSpec.scala | 20 ++--- src/test/scala/redis/commands/GeoSpec.scala | 25 +++--- .../scala/redis/commands/HashesSpec.scala | 30 +++---- .../redis/commands/HyperLogLogSpec.scala | 8 +- src/test/scala/redis/commands/KeysSpec.scala | 46 +++++----- src/test/scala/redis/commands/ListsSpec.scala | 30 +++---- .../scala/redis/commands/ScriptingSpec.scala | 72 +++++++-------- .../scala/redis/commands/ServerSpec.scala | 34 +++---- src/test/scala/redis/commands/SetsSpec.scala | 32 +++---- .../scala/redis/commands/SortedSetsSpec.scala | 42 ++++----- .../scala/redis/commands/StringsSpec.scala | 89 ++++++++----------- .../redis/commands/TransactionsSpec.scala | 16 ++-- 17 files changed, 238 insertions(+), 259 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1c6e1a98..9f50128f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ env: - TEST_TIME_FACTOR=50 + TEST_TIME_FACTOR=500 dist: xenial language: scala diff --git a/src/test/scala/redis/RedisClusterTest.scala b/src/test/scala/redis/RedisClusterTest.scala index dce2b0a5..c990d164 100644 --- a/src/test/scala/redis/RedisClusterTest.scala +++ b/src/test/scala/redis/RedisClusterTest.scala @@ -4,7 +4,7 @@ import akka.util.ByteString import redis.api.clusters.ClusterSlots import redis.protocol._ -import scala.concurrent.Await + /** * Created by npeters on 20/05/16. @@ -57,36 +57,36 @@ class RedisClusterTest extends RedisClusterClients { "Strings" should { "set-get" in { println("set") - Await.result(redisCluster.set[String]("foo", "FOO"), timeOut) + redisCluster.set[String]("foo", "FOO").futureValue println("exists") - Await.result(redisCluster.exists("foo"), timeOut) shouldBe (true) + redisCluster.exists("foo").futureValue shouldBe (true) println("get") - Await.result(redisCluster.get[String]("foo"), timeOut) shouldBe Some("FOO") + redisCluster.get[String]("foo").futureValue shouldBe Some("FOO") println("del") - Await.result(redisCluster.del("foo", "foo"), timeOut) + redisCluster.del("foo", "foo").futureValue println("exists") - Await.result(redisCluster.exists("foo"), timeOut) shouldBe (false) + redisCluster.exists("foo").futureValue shouldBe (false) } "mset-mget" in { println("mset") - Await.result(redisCluster.mset[String](Map("{foo}1" -> "FOO1", "{foo}2" -> "FOO2")), timeOut) + redisCluster.mset[String](Map("{foo}1" -> "FOO1", "{foo}2" -> "FOO2")).futureValue println("exists") - Await.result(redisCluster.exists("{foo}1"), timeOut) shouldBe (true) - Await.result(redisCluster.exists("{foo}2"), timeOut) shouldBe (true) + redisCluster.exists("{foo}1").futureValue shouldBe (true) + redisCluster.exists("{foo}2").futureValue shouldBe (true) println("mget") - Await.result(redisCluster.mget[String]("{foo}1", "{foo}2"), timeOut) shouldBe Seq(Some("FOO1"), Some("FOO2")) + redisCluster.mget[String]("{foo}1", "{foo}2").futureValue shouldBe Seq(Some("FOO1"), Some("FOO2")) println("del") - Await.result(redisCluster.del("{foo}1", "{foo}2"), timeOut) + redisCluster.del("{foo}1", "{foo}2").futureValue println("exists") - Await.result(redisCluster.exists("{foo}1"), timeOut) shouldBe (false) + redisCluster.exists("{foo}1").futureValue shouldBe (false) } } @@ -113,7 +113,7 @@ class RedisClusterTest extends RedisClusterClients { "clusterInfo" should { "just work" in { - val res = Await.result(redisCluster.clusterInfo(), timeOut) + val res = redisCluster.clusterInfo().futureValue res should not be empty for (v <- res) { println(s"Key ${v._1} value ${v._2}") @@ -124,7 +124,7 @@ class RedisClusterTest extends RedisClusterClients { "clusterNodes" should { "just work" in { - val res = Await.result(redisCluster.clusterNodes(), timeOut) + val res = redisCluster.clusterNodes().futureValue res should not be empty for (m <- res) { println(m.toString) diff --git a/src/test/scala/redis/RedisPoolSpec.scala b/src/test/scala/redis/RedisPoolSpec.scala index e5d91f2c..504f8d1e 100644 --- a/src/test/scala/redis/RedisPoolSpec.scala +++ b/src/test/scala/redis/RedisPoolSpec.scala @@ -29,7 +29,7 @@ class RedisPoolSpec extends RedisStandaloneServer { getKey2 shouldBe Some("0") getKey0 shouldBe Some("0") } - Await.result(r, timeOut) + r.futureValue } "check status" in { @@ -51,7 +51,7 @@ class RedisPoolSpec extends RedisStandaloneServer { getKey1 shouldBe Some("0") getKey0 shouldBe Some("0") } - Await.result(r, timeOut) + r.futureValue } } diff --git a/src/test/scala/redis/RedisSpec.scala b/src/test/scala/redis/RedisSpec.scala index e2245b6e..b641b51f 100644 --- a/src/test/scala/redis/RedisSpec.scala +++ b/src/test/scala/redis/RedisSpec.scala @@ -32,7 +32,6 @@ object RedisServerHelper { abstract class RedisHelper extends TestKit(ActorSystem()) with TestBase with BeforeAndAfterAll { protected val processLogger = ProcessLogger(line => log.debug(line), line => log.error(line)) - import scala.concurrent.duration._ implicit val executionContext = system.dispatchers.lookup(Redis.dispatcher.name) @@ -41,7 +40,8 @@ abstract class RedisHelper extends TestKit(ActorSystem()) with TestBase with Bef } - val timeOut = 10.seconds +// import scala.concurrent.duration._ +// val timeOut = 10.seconds override protected def beforeAll(): Unit = { setup() diff --git a/src/test/scala/redis/RedisTest.scala b/src/test/scala/redis/RedisTest.scala index e31a9246..fffcb198 100644 --- a/src/test/scala/redis/RedisTest.scala +++ b/src/test/scala/redis/RedisTest.scala @@ -2,26 +2,25 @@ package redis import akka.ConfigurationException -import scala.concurrent._ import akka.util.ByteString class RedisTest extends RedisStandaloneServer { "basic test" should { "ping" in { - Await.result(redis.ping, timeOut) shouldBe "PONG" + redis.ping.futureValue shouldBe "PONG" } "set" in { - Await.result(redis.set("key", "value"), timeOut) shouldBe true + redis.set("key", "value").futureValue shouldBe true } "get" in { - Await.result(redis.get("key"), timeOut) shouldBe Some(ByteString("value")) + redis.get("key").futureValue shouldBe Some(ByteString("value")) } "del" in { - Await.result(redis.del("key"), timeOut) shouldBe 1 + redis.del("key").futureValue shouldBe 1 } "get not found" in { - Await.result(redis.get("key"), timeOut) shouldBe None + redis.get("key").futureValue shouldBe None } } @@ -35,9 +34,9 @@ class RedisTest extends RedisStandaloneServer { _ <- redis.set("keyDbSelect", "2") } yield { val redis = RedisClient(port = port, password = Some("password"), db = Some(2)) - Await.result(redis.get[String]("keyDbSelect"), timeOut) shouldBe Some("2") + redis.get[String]("keyDbSelect").futureValue shouldBe Some("2") } - Await.result(r, timeOut) + r.futureValue }) } "use custom dispatcher" in { diff --git a/src/test/scala/redis/commands/BListsSpec.scala b/src/test/scala/redis/commands/BListsSpec.scala index 535aaae6..e81ca864 100644 --- a/src/test/scala/redis/commands/BListsSpec.scala +++ b/src/test/scala/redis/commands/BListsSpec.scala @@ -1,7 +1,7 @@ package redis.commands import redis._ -import scala.concurrent.Await + import akka.util.ByteString import scala.concurrent.duration._ @@ -18,7 +18,7 @@ class BListsSpec extends RedisStandaloneServer { } yield { b shouldBe Some("blpop1" -> ByteString("a")) } - val rr = Await.result(r, timeOut) + val rr = r.futureValue redisB.stop() rr } @@ -35,7 +35,7 @@ class BListsSpec extends RedisStandaloneServer { redis.rpush("blpopBlock", "a", "b", "c") blpop }) - Await.result(r, timeOut) shouldBe Some("blpopBlock" -> ByteString("a")) + r.futureValue shouldBe Some("blpopBlock" -> ByteString("a")) } redisB.stop() rr @@ -49,7 +49,7 @@ class BListsSpec extends RedisStandaloneServer { .flatMap(_ => { redisB.brpop(Seq("blpopBlockTimeout"), 1.seconds) }) - Await.result(r, timeOut) shouldBe empty + r.futureValue shouldBe empty } redisB.stop() rr @@ -65,7 +65,7 @@ class BListsSpec extends RedisStandaloneServer { redisB.stop() b shouldBe Some("brpop1" -> ByteString("c")) } - Await.result(r, timeOut) + r.futureValue } "BRPOP blocking" in { @@ -79,7 +79,7 @@ class BListsSpec extends RedisStandaloneServer { redis.rpush("brpopBlock", "a", "b", "c") brpop }) - Await.result(r, timeOut) shouldBe Some("brpopBlock" -> ByteString("c")) + r.futureValue shouldBe Some("brpopBlock" -> ByteString("c")) } redisB.stop() rr @@ -93,7 +93,7 @@ class BListsSpec extends RedisStandaloneServer { .flatMap(_ => { redisB.brpop(Seq("brpopBlockTimeout"), 1.seconds) }) - Await.result(r, timeOut) shouldBe empty + r.futureValue shouldBe empty } redisB.stop() rr @@ -108,7 +108,7 @@ class BListsSpec extends RedisStandaloneServer { } yield { b shouldBe Some(ByteString("c")) } - val rr = Await.result(r, timeOut) + val rr = r.futureValue redisB.stop() rr } @@ -124,7 +124,7 @@ class BListsSpec extends RedisStandaloneServer { redis.rpush("brpopplushBlock1", "a", "b", "c") brpopplush }) - Await.result(r, timeOut) shouldBe Some(ByteString("c")) + r.futureValue shouldBe Some(ByteString("c")) } redisB.stop() rr @@ -138,7 +138,7 @@ class BListsSpec extends RedisStandaloneServer { .flatMap(_ => { redisB.brpoplpush("brpopplushBlockTimeout1", "brpopplushBlockTimeout2", 1.seconds) }) - Await.result(r, timeOut) shouldBe empty + r.futureValue shouldBe empty } redisB.stop() rr diff --git a/src/test/scala/redis/commands/GeoSpec.scala b/src/test/scala/redis/commands/GeoSpec.scala index 31556491..7b49e1b2 100644 --- a/src/test/scala/redis/commands/GeoSpec.scala +++ b/src/test/scala/redis/commands/GeoSpec.scala @@ -2,24 +2,23 @@ package redis.commands import redis._ import redis.api.geo.DistUnits._ -import scala.concurrent.Await + class GeoSpec extends RedisStandaloneServer { - import concurrent.duration._ val testKey = "Sicily" def addPlaces() = { - Await.result(redis.geoAdd(testKey, 13.361389, 38.115556, "Palermo"), 2 second) - Await.result(redis.geoAdd(testKey, 15.087269, 37.502669, "Catania"), 2 second) - Await.result(redis.geoAdd(testKey, 13.583333, 37.316667, "Agrigento"), 2 second) + redis.geoAdd(testKey, 13.361389, 38.115556, "Palermo").futureValue + redis.geoAdd(testKey, 15.087269, 37.502669, "Catania").futureValue + redis.geoAdd(testKey, 13.583333, 37.316667, "Agrigento").futureValue } "Geo commands " should { "GEOADD add key member" in { - val res = Await.result(redis.geoAdd(testKey, 23.361389, 48.115556, "SomePlace"), 2 second) + val res = redis.geoAdd(testKey, 23.361389, 48.115556, "SomePlace").futureValue res shouldEqual 1 } @@ -38,43 +37,43 @@ class GeoSpec extends RedisStandaloneServer { "GEORADIUS By Member with opt" in { addPlaces() - val res = Await.result(redis.geoRadiusByMemberWithOpt(testKey, "Agrigento", 100, Kilometer), 2 second) + val res = redis.geoRadiusByMemberWithOpt(testKey, "Agrigento", 100, Kilometer).futureValue res shouldEqual Vector("Agrigento", "0.0000", "Palermo", "89.8694") } "GEODIST with default unit" in { addPlaces() - val res = Await.result(redis.geoDist(testKey, "Palermo", "Catania"), 2 seconds) + val res = redis.geoDist(testKey, "Palermo", "Catania").futureValue res shouldEqual 203017.1901 } "GEODIST in km" in { addPlaces() - val res = Await.result(redis.geoDist(testKey, "Palermo", "Catania", Kilometer), 2 seconds) + val res = redis.geoDist(testKey, "Palermo", "Catania", Kilometer).futureValue res shouldEqual 203.0172 } "GEODIST in mile" in { addPlaces() - val res = Await.result(redis.geoDist(testKey, "Palermo", "Catania", Mile), 2 seconds) + val res = redis.geoDist(testKey, "Palermo", "Catania", Mile).futureValue res shouldEqual 126.1493 } "GEODIST in feet" in { addPlaces() - val res = Await.result(redis.geoDist(testKey, "Palermo", "Catania", Feet), 2 seconds) + val res = redis.geoDist(testKey, "Palermo", "Catania", Feet).futureValue res shouldEqual 666066.8965 } "GEOHASH " in { addPlaces() - val res = Await.result(redis.geoHash(testKey, "Palermo", "Catania"), 2 seconds) + val res = redis.geoHash(testKey, "Palermo", "Catania").futureValue res shouldEqual Vector("sfdtv6s9ew0", "sf7h526gsz0") } "GEOPOS " in { addPlaces() - val res = Await.result(redis.geoPos(testKey, "Palermo", "Catania"), 2 seconds) + val res = redis.geoPos(testKey, "Palermo", "Catania").futureValue res should not be empty } } diff --git a/src/test/scala/redis/commands/HashesSpec.scala b/src/test/scala/redis/commands/HashesSpec.scala index 6ce832e8..8d85145f 100644 --- a/src/test/scala/redis/commands/HashesSpec.scala +++ b/src/test/scala/redis/commands/HashesSpec.scala @@ -1,7 +1,7 @@ package redis.commands import redis._ -import scala.concurrent.Await + import akka.util.ByteString class HashesSpec extends RedisStandaloneServer { @@ -14,7 +14,7 @@ class HashesSpec extends RedisStandaloneServer { } yield { d shouldBe 1 } - Await.result(r, timeOut) + r.futureValue } "HEXISTS" in { @@ -26,7 +26,7 @@ class HashesSpec extends RedisStandaloneServer { exist shouldBe true notExist shouldBe false } - Await.result(r, timeOut) + r.futureValue } "HGET" in { @@ -38,7 +38,7 @@ class HashesSpec extends RedisStandaloneServer { get shouldBe Some(ByteString("value")) get2 shouldBe None } - Await.result(r, timeOut) + r.futureValue } "HGETALL" in { @@ -50,7 +50,7 @@ class HashesSpec extends RedisStandaloneServer { get shouldBe Map("field" -> ByteString("value")) get2 shouldBe Map.empty } - Await.result(r, timeOut) + r.futureValue } "HINCRBY" in { @@ -62,7 +62,7 @@ class HashesSpec extends RedisStandaloneServer { i shouldBe 11 ii shouldBe 10 } - Await.result(r, timeOut) + r.futureValue } "HINCRBYFLOAT" in { @@ -74,7 +74,7 @@ class HashesSpec extends RedisStandaloneServer { i shouldBe 10.6 ii shouldBe 9.5 } - Await.result(r, timeOut) + r.futureValue } "HKEYS" in { @@ -84,7 +84,7 @@ class HashesSpec extends RedisStandaloneServer { } yield { keys shouldBe Seq("field") } - Await.result(r, timeOut) + r.futureValue } "HLEN" in { @@ -94,7 +94,7 @@ class HashesSpec extends RedisStandaloneServer { } yield { hLength shouldBe 1 } - Await.result(r, timeOut) + r.futureValue } "HMGET" in { @@ -104,7 +104,7 @@ class HashesSpec extends RedisStandaloneServer { } yield { hmget shouldBe Seq(Some(ByteString("value")), None) } - Await.result(r, timeOut) + r.futureValue } "HMSET" in { @@ -116,7 +116,7 @@ class HashesSpec extends RedisStandaloneServer { v1 shouldBe Some(ByteString("value1")) v2 shouldBe Some(ByteString("value2")) } - Await.result(r, timeOut) + r.futureValue } "HMSET update" in { @@ -130,7 +130,7 @@ class HashesSpec extends RedisStandaloneServer { update shouldBe false v1 shouldBe Some(ByteString("value2")) } - Await.result(r, timeOut) + r.futureValue } "HMSETNX" in { @@ -144,7 +144,7 @@ class HashesSpec extends RedisStandaloneServer { doNothing shouldBe false v1 shouldBe Some(ByteString("value")) } - Await.result(r, timeOut) + r.futureValue } "HSCAN" in { @@ -157,7 +157,7 @@ class HashesSpec extends RedisStandaloneServer { scanResult.data.values.toList.map(_.toInt).sorted shouldBe (2 to 20 by 2) scanResult.index shouldBe 0 } - Await.result(r, timeOut) + r.futureValue } "HVALS" in { @@ -170,7 +170,7 @@ class HashesSpec extends RedisStandaloneServer { emp shouldBe empty some shouldBe Seq(ByteString("value")) } - Await.result(r, timeOut) + r.futureValue } } } diff --git a/src/test/scala/redis/commands/HyperLogLogSpec.scala b/src/test/scala/redis/commands/HyperLogLogSpec.scala index f0a244f9..9737a321 100644 --- a/src/test/scala/redis/commands/HyperLogLogSpec.scala +++ b/src/test/scala/redis/commands/HyperLogLogSpec.scala @@ -2,7 +2,7 @@ package redis.commands import redis.RedisStandaloneServer -import scala.concurrent.Await + class HyperLogLogSpec extends RedisStandaloneServer { @@ -17,14 +17,14 @@ class HyperLogLogSpec extends RedisStandaloneServer { }) }) }) - Await.result(r, timeOut) shouldBe 9 + r.futureValue shouldBe 9 } "PFCOUNT" in { val r = redis.pfadd("hll2", "a", "b", "c", "d", "e", "f", "g").flatMap(_ => { redis.pfcount("hll2") }) - Await.result(r, timeOut) shouldBe 7 + r.futureValue shouldBe 7 } "PFMERGE" in { @@ -37,7 +37,7 @@ class HyperLogLogSpec extends RedisStandaloneServer { }) }) - Await.result(r, timeOut) shouldBe 4 + r.futureValue shouldBe 4 } } } diff --git a/src/test/scala/redis/commands/KeysSpec.scala b/src/test/scala/redis/commands/KeysSpec.scala index 7db161c7..0574f6d0 100644 --- a/src/test/scala/redis/commands/KeysSpec.scala +++ b/src/test/scala/redis/commands/KeysSpec.scala @@ -4,7 +4,7 @@ import akka.util.ByteString import redis._ import redis.api._ -import scala.concurrent.{Await, Future} +import scala.concurrent.Future import java.io.File @@ -19,7 +19,7 @@ class KeysSpec extends RedisStandaloneServer { s shouldBe true d shouldBe 1 } - Await.result(r, timeOut) + r.futureValue } "DUMP" in { val k = "dumpKey" @@ -35,7 +35,7 @@ class KeysSpec extends RedisStandaloneServer { s shouldBe true rs shouldBe true } - Await.result(r, timeOut) + r.futureValue } "EXISTS" in { @@ -48,7 +48,7 @@ class KeysSpec extends RedisStandaloneServer { e shouldBe true e2 shouldBe false } - Await.result(r, timeOut) + r.futureValue } "EXISTS variadic" in { @@ -61,7 +61,7 @@ class KeysSpec extends RedisStandaloneServer { e shouldBe 1 e2 shouldBe 0 } - Await.result(r, timeOut) + r.futureValue } "EXPIRE" in { @@ -84,7 +84,7 @@ class KeysSpec extends RedisStandaloneServer { e shouldBe true expired shouldBe None } - Await.result(r, timeOut) + r.futureValue } "KEYS" in { @@ -99,7 +99,7 @@ class KeysSpec extends RedisStandaloneServer { k2 should contain theSameElementsAs (Seq("keysKey2")) k3 shouldBe empty } - Await.result(r, timeOut) + r.futureValue } "MIGRATE" in { @@ -116,7 +116,7 @@ class KeysSpec extends RedisStandaloneServer { m shouldBe true get shouldBe Some(ByteString("value")) } - Await.result(r, timeOut) + r.futureValue }) } @@ -136,7 +136,7 @@ class KeysSpec extends RedisStandaloneServer { get shouldBe Some(ByteString("value")) get2 shouldBe None } - Await.result(r, timeOut) + r.futureValue } "REFCOUNT" in { @@ -148,7 +148,7 @@ class KeysSpec extends RedisStandaloneServer { ref shouldBe Some(1) refNotFound shouldBe empty } - Await.result(r, timeOut) + r.futureValue } "IDLETIME" in { val r = for { @@ -159,7 +159,7 @@ class KeysSpec extends RedisStandaloneServer { time shouldBe defined timeNotFound shouldBe empty } - Await.result(r, timeOut) + r.futureValue } "ENCODING" in { val r = for { @@ -170,7 +170,7 @@ class KeysSpec extends RedisStandaloneServer { encoding shouldBe defined encodingNotFound shouldBe empty } - Await.result(r, timeOut) + r.futureValue } "PERSIST" in { @@ -187,7 +187,7 @@ class KeysSpec extends RedisStandaloneServer { p shouldBe true ttl2 shouldBe -1 } - Await.result(r, timeOut) + r.futureValue } "PEXPIRE" in { @@ -209,7 +209,7 @@ class KeysSpec extends RedisStandaloneServer { e shouldBe true expired shouldBe None } - Await.result(r, timeOut) + r.futureValue } "PEXPIREAT TTL" in { @@ -222,7 +222,7 @@ class KeysSpec extends RedisStandaloneServer { e shouldBe true pttl.toInt should beBetween(1, 1000) } - Await.result(r, timeOut) + r.futureValue } "RANDOMKEY" in { @@ -232,7 +232,7 @@ class KeysSpec extends RedisStandaloneServer { } yield { s shouldBe defined } - Await.result(r, timeOut) + r.futureValue } "RENAME" in { @@ -246,7 +246,7 @@ class KeysSpec extends RedisStandaloneServer { rename shouldBe true renamedValue shouldBe Some(ByteString("value")) } - Await.result(r, timeOut) + r.futureValue } "RENAMENX" in { @@ -264,7 +264,7 @@ class KeysSpec extends RedisStandaloneServer { rename2 shouldBe true renamedValue shouldBe Some(ByteString("value")) } - Await.result(r, timeOut) + r.futureValue } "RESTORE" in { @@ -281,7 +281,7 @@ class KeysSpec extends RedisStandaloneServer { restore shouldBe true restored shouldBe Some(v) } - Await.result(r, timeOut) + r.futureValue } "SCAN" in { @@ -299,7 +299,7 @@ class KeysSpec extends RedisStandaloneServer { result.index shouldBe 0 result.data.sorted shouldBe Seq("scanKey1", "scanKey2", "scanKey3") } - Await.result(r, timeOut) + r.futureValue }) } @@ -343,7 +343,7 @@ class KeysSpec extends RedisStandaloneServer { b6 shouldBe Seq(ByteString("2"), ByteString("1")) b7 shouldBe 2 } - Await.result(r, timeOut) + r.futureValue } "TTL" in { @@ -357,7 +357,7 @@ class KeysSpec extends RedisStandaloneServer { ttl should be >= 1L ttl.toInt should beBetween(1, 10) } - Await.result(r, timeOut) + r.futureValue } "TYPE" in { @@ -370,7 +370,7 @@ class KeysSpec extends RedisStandaloneServer { _type shouldBe "string" _typeNone shouldBe "none" } - Await.result(r, timeOut) + r.futureValue } } diff --git a/src/test/scala/redis/commands/ListsSpec.scala b/src/test/scala/redis/commands/ListsSpec.scala index 8548da6c..7e3b3276 100644 --- a/src/test/scala/redis/commands/ListsSpec.scala +++ b/src/test/scala/redis/commands/ListsSpec.scala @@ -3,7 +3,7 @@ package redis.commands import akka.util.ByteString import redis._ -import scala.concurrent.Await + class ListsSpec extends RedisStandaloneServer { @@ -21,7 +21,7 @@ class ListsSpec extends RedisStandaloneServer { world shouldBe Some(ByteString("World")) none shouldBe None } - Await.result(r, timeOut) + r.futureValue } "LINSERT" in { @@ -38,7 +38,7 @@ class ListsSpec extends RedisStandaloneServer { length4 shouldBe 4 list4 shouldBe Seq(ByteString("Hello"), ByteString("There"), ByteString("World"), ByteString("!!!")) } - Await.result(r, timeOut) + r.futureValue } "LLEN" in { @@ -49,7 +49,7 @@ class ListsSpec extends RedisStandaloneServer { } yield { length shouldBe 2 } - Await.result(r, timeOut) + r.futureValue } "LPOP" in { @@ -60,7 +60,7 @@ class ListsSpec extends RedisStandaloneServer { } yield { e shouldBe Some(ByteString("one")) } - Await.result(r, timeOut) + r.futureValue } "LPUSH" in { @@ -71,7 +71,7 @@ class ListsSpec extends RedisStandaloneServer { } yield { list shouldBe Seq(ByteString("Hello"), ByteString("World")) } - Await.result(r, timeOut) + r.futureValue } "LPUSHX" in { @@ -90,7 +90,7 @@ class ListsSpec extends RedisStandaloneServer { list shouldBe Seq(ByteString("hello"), ByteString("world")) listOther shouldBe empty } - Await.result(r, timeOut) + r.futureValue } "LRANGE" in { @@ -107,7 +107,7 @@ class ListsSpec extends RedisStandaloneServer { list3 shouldBe empty nonExisting shouldBe empty } - Await.result(r, timeOut) + r.futureValue } "LREM" in { @@ -120,7 +120,7 @@ class ListsSpec extends RedisStandaloneServer { lrem shouldBe 2 list2 shouldBe Seq(ByteString("hello"), ByteString("foo")) } - Await.result(r, timeOut) + r.futureValue } "LSET" in { @@ -135,7 +135,7 @@ class ListsSpec extends RedisStandaloneServer { lset2 shouldBe true list shouldBe Seq(ByteString("four"), ByteString("five"), ByteString("three")) } - Await.result(r, timeOut) + r.futureValue } "LTRIM" in { @@ -148,7 +148,7 @@ class ListsSpec extends RedisStandaloneServer { ltrim shouldBe true list shouldBe Seq(ByteString("two"), ByteString("three")) } - Await.result(r, timeOut) + r.futureValue } "RPOP" in { @@ -161,7 +161,7 @@ class ListsSpec extends RedisStandaloneServer { rpop shouldBe Some(ByteString("three")) list shouldBe Seq(ByteString("one"), ByteString("two")) } - Await.result(r, timeOut) + r.futureValue } "RPOPLPUSH" in { @@ -177,7 +177,7 @@ class ListsSpec extends RedisStandaloneServer { list shouldBe Seq(ByteString("one"), ByteString("two")) listOther shouldBe Seq(ByteString("three")) } - Await.result(r, timeOut) + r.futureValue } "RPUSH" in { @@ -191,7 +191,7 @@ class ListsSpec extends RedisStandaloneServer { ii shouldBe 2 list shouldBe Seq(ByteString("hello"), ByteString("world")) } - Await.result(r, timeOut) + r.futureValue } "RPUSHX" in { @@ -210,7 +210,7 @@ class ListsSpec extends RedisStandaloneServer { list shouldBe Seq(ByteString("hello"), ByteString("world")) listOther shouldBe empty } - Await.result(r, timeOut) + r.futureValue } } } diff --git a/src/test/scala/redis/commands/ScriptingSpec.scala b/src/test/scala/redis/commands/ScriptingSpec.scala index 69976f24..e1a4bb6d 100644 --- a/src/test/scala/redis/commands/ScriptingSpec.scala +++ b/src/test/scala/redis/commands/ScriptingSpec.scala @@ -4,7 +4,6 @@ import java.io.File import redis._ -import scala.concurrent.Await import akka.util.ByteString import redis.protocol.{Bulk, MultiBulk} import redis.actors.ReplyErrorException @@ -13,68 +12,71 @@ import redis.api.scripting.RedisScript class ScriptingSpec extends RedisStandaloneServer { "Scripting commands" should { - val redisScript = RedisScript("return 'rediscala'") - val redisScriptKeysArgs = RedisScript("return {KEYS[1],ARGV[1]}") + val redisScript = RedisScript("return 'rediscala'") + val redisScriptKeysArgs = RedisScript("return {KEYS[1],ARGV[1]}") val redisScriptConversionObject = RedisScript("return redis.call('get', 'dumbKey')") "evalshaOrEval (RedisScript)" in { - Await.result(redis.scriptFlush(), timeOut) shouldBe true - val r = Await.result(redis.evalshaOrEval(redisScriptKeysArgs, Seq("key"), Seq("arg")), timeOut) + redis.scriptFlush().futureValue shouldBe true + val r = redis.evalshaOrEval(redisScriptKeysArgs, Seq("key"), Seq("arg")).futureValue r shouldBe MultiBulk(Some(Vector(Bulk(Some(ByteString("key"))), Bulk(Some(ByteString("arg")))))) } "EVAL" in { - Await.result(redis.eval(redisScript.script), timeOut) shouldBe Bulk(Some(ByteString("rediscala"))) + redis.eval(redisScript.script).futureValue shouldBe Bulk(Some(ByteString("rediscala"))) } "EVAL with type conversion" in { val dumbObject = new DumbClass("foo", "bar") - val r = redis.set("dumbKey", dumbObject).flatMap(_ => { - redis.eval[DumbClass](redisScriptConversionObject.script) - }) + val r = redis + .set("dumbKey", dumbObject) + .flatMap(_ => { + redis.eval[DumbClass](redisScriptConversionObject.script) + }) - Await.result(r, timeOut) shouldBe dumbObject + r.futureValue shouldBe dumbObject } "EVALSHA" in { - Await.result(redis.evalsha(redisScript.sha1), timeOut) shouldBe Bulk(Some(ByteString("rediscala"))) + redis.evalsha(redisScript.sha1).futureValue shouldBe Bulk(Some(ByteString("rediscala"))) } "EVALSHA with type conversion" in { val dumbObject = new DumbClass("foo2", "bar2") - val r = redis.set("dumbKey", dumbObject).flatMap(_ => { - redis.evalsha[DumbClass](redisScriptConversionObject.sha1) - }) + val r = redis + .set("dumbKey", dumbObject) + .flatMap(_ => { + redis.evalsha[DumbClass](redisScriptConversionObject.sha1) + }) - Await.result(r, timeOut) shouldBe dumbObject + r.futureValue shouldBe dumbObject } "evalshaOrEvalForTypeOf (RedisScript)" in { - Await.result(redis.scriptFlush(), timeOut) shouldBe true + redis.scriptFlush().futureValue shouldBe true val dumbObject = new DumbClass("foo3", "bar3") - val r = redis.set("dumbKey", dumbObject).flatMap(_ => { - redis.evalshaOrEval[DumbClass](redisScriptConversionObject) - }) + val r = redis + .set("dumbKey", dumbObject) + .flatMap(_ => { + redis.evalshaOrEval[DumbClass](redisScriptConversionObject) + }) - Await.result(r, timeOut) shouldBe dumbObject + r.futureValue shouldBe dumbObject } "SCRIPT FLUSH" in { - Await.result(redis.scriptFlush(), timeOut) shouldBe true + redis.scriptFlush().futureValue shouldBe true } "SCRIPT KILL" in { withRedisServer(serverPort => { - val redisKiller = RedisClient(port = serverPort) + val redisKiller = RedisClient(port = serverPort) val redisScriptLauncher = RedisClient(port = serverPort) - a[ReplyErrorException] should be thrownBy { - Await.result(redisKiller.scriptKill(), timeOut) - } + redisKiller.scriptKill().failed.futureValue shouldBe a[ReplyErrorException] - val infiniteScript = redisScriptLauncher.eval( - """ + val infiniteScript = redisScriptLauncher.eval(""" |local i = 1 |while(i > 0) do |end @@ -84,23 +86,21 @@ class ScriptingSpec extends RedisStandaloneServer { eventually { redisKiller.scriptKill().futureValue shouldBe true } - a[ReplyErrorException] should be thrownBy { - Await.result(infiniteScript, timeOut) - } + infiniteScript.failed.futureValue }) } "SCRIPT LOAD" in { - Await.result(redis.scriptLoad("return 'rediscala'"), timeOut) shouldBe "d4cf7650161a37eb55a7e9325f3534cec6fc3241" + redis.scriptLoad("return 'rediscala'").futureValue shouldBe "d4cf7650161a37eb55a7e9325f3534cec6fc3241" } "SCRIPT EXISTS" in { val redisScriptNotFound = RedisScript("return 'SCRIPT EXISTS not found'") - val redisScriptFound = RedisScript("return 'SCRIPT EXISTS found'") - val scriptsLoaded = redis.scriptLoad(redisScriptFound.script).flatMap(_ => - redis.scriptExists(redisScriptFound.sha1, redisScriptNotFound.sha1) - ) - Await.result(scriptsLoaded, timeOut) shouldBe Seq(true, false) + val redisScriptFound = RedisScript("return 'SCRIPT EXISTS found'") + val scriptsLoaded = redis + .scriptLoad(redisScriptFound.script) + .flatMap(_ => redis.scriptExists(redisScriptFound.sha1, redisScriptNotFound.sha1)) + scriptsLoaded.futureValue shouldBe Seq(true, false) } diff --git a/src/test/scala/redis/commands/ServerSpec.scala b/src/test/scala/redis/commands/ServerSpec.scala index 09fd1258..3b3a997c 100644 --- a/src/test/scala/redis/commands/ServerSpec.scala +++ b/src/test/scala/redis/commands/ServerSpec.scala @@ -1,7 +1,7 @@ package redis.commands import redis._ -import scala.concurrent.Await + import redis.actors.{InvalidRedisReply, ReplyErrorException} import redis.api.NOSAVE @@ -10,7 +10,7 @@ class ServerSpec extends RedisStandaloneServer { "Server commands" should { "BGSAVE" in { - Await.result(redis.bgsave(), timeOut) shouldBe "Background saving started" + redis.bgsave().futureValue shouldBe "Background saving started" } "CLIENT KILL" in { @@ -22,11 +22,11 @@ class ServerSpec extends RedisStandaloneServer { } "CLIENT GETNAME" in { - Await.result(redis.clientGetname(), timeOut) shouldBe None + redis.clientGetname().futureValue shouldBe None } "CLIENT SETNAME" in { - Await.result(redis.clientSetname("rediscala"), timeOut) shouldBe true + redis.clientSetname("rediscala").futureValue shouldBe true } "CONFIG GET" in { @@ -41,15 +41,15 @@ class ServerSpec extends RedisStandaloneServer { set shouldBe true loglevel.get("loglevel") shouldBe Some("warning") } - Await.result(r, timeOut) + r.futureValue } "CONFIG RESETSTAT" in { - Await.result(redis.configResetstat(), timeOut) shouldBe true + redis.configResetstat().futureValue shouldBe true } "DBSIZE" in { - Await.result(redis.dbsize(), timeOut) should be >= 0L + redis.dbsize().futureValue should be >= 0L } "DEBUG OBJECT" in { @@ -59,11 +59,11 @@ class ServerSpec extends RedisStandaloneServer { "DEBUG SEGFAULT" ignore {} "FLUSHALL" in { - Await.result(redis.flushall(), timeOut) shouldBe true + redis.flushall().futureValue shouldBe true } "FLUSHDB" in { - Await.result(redis.flushdb(), timeOut) shouldBe true + redis.flushdb().futureValue shouldBe true } "INFO" in { @@ -74,26 +74,26 @@ class ServerSpec extends RedisStandaloneServer { info shouldBe a[String] infoCpu shouldBe a[String] } - Await.result(r, timeOut) + r.futureValue } "LASTSAVE" in { - Await.result(redis.lastsave(), timeOut) should be >= 0L + redis.lastsave().futureValue should be >= 0L } "SAVE" in { - val result = try { Await.result(redis.save(), timeOut) } catch { + val result = try { redis.save().futureValue } catch { case ReplyErrorException("ERR Background save already in progress") => true } result shouldBe true } "SLAVE OF" in { - Await.result(redis.slaveof("server", 12345), timeOut) shouldBe true + redis.slaveof("server", 12345).futureValue shouldBe true } "SLAVE OF NO ONE" in { - Await.result(redis.slaveofNoOne(), timeOut) shouldBe true + redis.slaveofNoOne().futureValue shouldBe true } "TIME" in { @@ -103,19 +103,19 @@ class ServerSpec extends RedisStandaloneServer { "BGREWRITEAOF" in { // depending on the redis version, this string could vary, redis 2.8.21 says 'scheduled' // but redis 2.8.18 says 'started' - val r = Await.result(redis.bgrewriteaof(), timeOut) + val r = redis.bgrewriteaof().futureValue r should (be("Background append only file rewriting started") or be("Background append only file rewriting scheduled")) } "SHUTDOWN" in { - a[InvalidRedisReply.type] should be thrownBy Await.result(redis.shutdown(), timeOut) + redis.shutdown().failed.futureValue shouldBe InvalidRedisReply } "SHUTDOWN (with modifier)" in { withRedisServer(port => { val redis = RedisClient(port = port) - a[InvalidRedisReply.type] should be thrownBy Await.result(redis.shutdown(NOSAVE), timeOut) + redis.shutdown(NOSAVE).failed.futureValue shouldBe InvalidRedisReply }) } diff --git a/src/test/scala/redis/commands/SetsSpec.scala b/src/test/scala/redis/commands/SetsSpec.scala index a42908e9..2d24b992 100644 --- a/src/test/scala/redis/commands/SetsSpec.scala +++ b/src/test/scala/redis/commands/SetsSpec.scala @@ -3,7 +3,7 @@ package redis.commands import akka.util.ByteString import redis._ -import scala.concurrent.Await + class SetsSpec extends RedisStandaloneServer { @@ -19,7 +19,7 @@ class SetsSpec extends RedisStandaloneServer { s2 shouldBe 0 m should contain theSameElementsAs(Seq(ByteString("Hello"), ByteString("World"))) } - Await.result(r, timeOut) + r.futureValue } "SCARD" in { @@ -32,7 +32,7 @@ class SetsSpec extends RedisStandaloneServer { c1 shouldBe 0 c2 shouldBe 2 } - Await.result(r, timeOut) + r.futureValue } "SDIFF" in { @@ -45,7 +45,7 @@ class SetsSpec extends RedisStandaloneServer { } yield { diff should contain theSameElementsAs(Seq(ByteString("a"), ByteString("b"))) } - Await.result(r, timeOut) + r.futureValue } "SDIFFSTORE" in { @@ -60,7 +60,7 @@ class SetsSpec extends RedisStandaloneServer { diff shouldBe 2 m should contain theSameElementsAs(Seq(ByteString("a"), ByteString("b"))) } - Await.result(r, timeOut) + r.futureValue } "SINTER" in { @@ -73,7 +73,7 @@ class SetsSpec extends RedisStandaloneServer { } yield { inter should contain theSameElementsAs(Seq(ByteString("c"))) } - Await.result(r, timeOut) + r.futureValue } @@ -89,7 +89,7 @@ class SetsSpec extends RedisStandaloneServer { inter shouldBe 1 m should contain theSameElementsAs(Seq(ByteString("c"))) } - Await.result(r, timeOut) + r.futureValue } "SISMEMBER" in { @@ -102,7 +102,7 @@ class SetsSpec extends RedisStandaloneServer { is shouldBe true isNot shouldBe false } - Await.result(r, timeOut) + r.futureValue } "SMEMBERS" in { @@ -113,7 +113,7 @@ class SetsSpec extends RedisStandaloneServer { } yield { m should contain theSameElementsAs(Seq(ByteString("Hello"), ByteString("World"))) } - Await.result(r, timeOut) + r.futureValue } "SMOVE" in { @@ -130,7 +130,7 @@ class SetsSpec extends RedisStandaloneServer { isNotMoved shouldBe false m should contain theSameElementsAs(Seq(ByteString("three"), ByteString("two"))) } - Await.result(r, timeOut) + r.futureValue } "SPOP" in { @@ -145,7 +145,7 @@ class SetsSpec extends RedisStandaloneServer { popNone shouldBe empty m should contain atLeastOneElementOf (Seq(ByteString("three"), ByteString("two"), ByteString("one"))) } - Await.result(r, timeOut) + r.futureValue } "SRANDMEMBER" in { @@ -161,7 +161,7 @@ class SetsSpec extends RedisStandaloneServer { randmember2 should have size 2 randmemberNonExisting shouldBe empty } - Await.result(r, timeOut) + r.futureValue } "SREM" in { @@ -176,7 +176,7 @@ class SetsSpec extends RedisStandaloneServer { remNothing shouldBe 0 m should contain theSameElementsAs(Seq(ByteString("three"), ByteString("two"))) } - Await.result(r, timeOut) + r.futureValue } "SSCAN" in { @@ -188,7 +188,7 @@ class SetsSpec extends RedisStandaloneServer { scanResult.data.map(_.toInt).sorted shouldBe (1 to 20) } - Await.result(r, timeOut) + r.futureValue } "SUNION" in { @@ -201,7 +201,7 @@ class SetsSpec extends RedisStandaloneServer { } yield { union should contain theSameElementsAs(Seq(ByteString("a"), ByteString("b"), ByteString("c"), ByteString("d"), ByteString("e"))) } - Await.result(r, timeOut) + r.futureValue } @@ -217,7 +217,7 @@ class SetsSpec extends RedisStandaloneServer { union shouldBe 5 m should contain theSameElementsAs(Seq(ByteString("a"), ByteString("b"), ByteString("c"), ByteString("d"), ByteString("e"))) } - Await.result(r, timeOut) + r.futureValue } } } diff --git a/src/test/scala/redis/commands/SortedSetsSpec.scala b/src/test/scala/redis/commands/SortedSetsSpec.scala index 199b3d7e..3933628e 100644 --- a/src/test/scala/redis/commands/SortedSetsSpec.scala +++ b/src/test/scala/redis/commands/SortedSetsSpec.scala @@ -4,7 +4,7 @@ import redis._ import redis.api._ import redis.api.ZaddOption.{CH, NX, XX} -import scala.concurrent.{Await, Future} +import scala.concurrent.Future import akka.util.ByteString class SortedSetsSpec extends RedisStandaloneServer { @@ -28,7 +28,7 @@ class SortedSetsSpec extends RedisStandaloneServer { z4 shouldBe 1 zr shouldBe Seq((ByteString("one"), 1.0), (ByteString("uno"), 1), (ByteString("two"), 3), (ByteString("three"), 4)) } - Await.result(r, timeOut) + r.futureValue } "ZCARD" in { @@ -41,7 +41,7 @@ class SortedSetsSpec extends RedisStandaloneServer { c1 shouldBe 0 c2 shouldBe 2 } - Await.result(r, timeOut) + r.futureValue } "ZCOUNT" in { @@ -56,7 +56,7 @@ class SortedSetsSpec extends RedisStandaloneServer { c2 shouldBe 3 c3 shouldBe 2 } - Await.result(r, timeOut) + r.futureValue } "ZINCRBY" in { @@ -71,7 +71,7 @@ class SortedSetsSpec extends RedisStandaloneServer { d2 shouldBe 2.1 zr shouldBe Seq((ByteString("two"), 2.0), (ByteString("notexisting"), 2.1), (ByteString("one"), 3.1)) } - Await.result(r, timeOut) + r.futureValue } "ZINTERSTORE" in { @@ -92,7 +92,7 @@ class SortedSetsSpec extends RedisStandaloneServer { zr shouldBe Seq((ByteString("one"), 2), (ByteString("two"), 4)) zrWeighted shouldBe Seq((ByteString("one"), 5), (ByteString("two"), 10)) } - Await.result(r, timeOut) + r.futureValue } "ZRANGE" in { @@ -108,7 +108,7 @@ class SortedSetsSpec extends RedisStandaloneServer { zr2 shouldBe Seq(ByteString("three")) zr3 shouldBe Seq(ByteString("two"), ByteString("three")) } - Await.result(r, timeOut) + r.futureValue } "ZRANGEBYSCORE" in { @@ -130,7 +130,7 @@ class SortedSetsSpec extends RedisStandaloneServer { zr3 shouldBe Seq(ByteString("two")) zr4 shouldBe Seq() } - Await.result(r, timeOut) + r.futureValue } "ZRANK" in { @@ -144,7 +144,7 @@ class SortedSetsSpec extends RedisStandaloneServer { zr1 shouldBe Some(2) zr2 shouldBe None } - Await.result(r, timeOut) + r.futureValue } "ZREM" in { @@ -158,7 +158,7 @@ class SortedSetsSpec extends RedisStandaloneServer { z2 shouldBe 1 zr shouldBe Seq((ByteString("one"), 1), (ByteString("three"), 3)) } - Await.result(r, timeOut) + r.futureValue } "ZREMRANGEBYLEX" in { @@ -174,7 +174,7 @@ class SortedSetsSpec extends RedisStandaloneServer { z3 shouldBe 3 zrange1 shouldBe Seq(ByteString("a"), ByteString("e"), ByteString("f"), ByteString("g")) } - Await.result(r, timeOut) + r.futureValue } "ZREMRANGEBYRANK" in { @@ -188,7 +188,7 @@ class SortedSetsSpec extends RedisStandaloneServer { z2 shouldBe 2 zr shouldBe Seq((ByteString("three"), 3)) } - Await.result(r, timeOut) + r.futureValue } "ZREMRANGEBYSCORE" in { @@ -202,7 +202,7 @@ class SortedSetsSpec extends RedisStandaloneServer { z2 shouldBe 1 zr shouldBe Seq((ByteString("two"), 2), (ByteString("three"), 3)) } - Await.result(r, timeOut) + r.futureValue } "ZREVRANGE" in { @@ -220,7 +220,7 @@ class SortedSetsSpec extends RedisStandaloneServer { zr3 shouldBe Seq(ByteString("two"), ByteString("one")) zr3WithScores shouldBe Seq((ByteString("two"), 2), (ByteString("one"), 1)) } - Await.result(r, timeOut) + r.futureValue } "ZREVRANGEBYSCORE" in { @@ -240,7 +240,7 @@ class SortedSetsSpec extends RedisStandaloneServer { zr3 shouldBe Seq(ByteString("two")) zr4 shouldBe Seq() } - Await.result(r, timeOut) + r.futureValue } "ZREVRANK" in { @@ -254,7 +254,7 @@ class SortedSetsSpec extends RedisStandaloneServer { zr1 shouldBe Some(2) zr2 shouldBe None } - Await.result(r, timeOut) + r.futureValue } "ZSCAN" in { @@ -267,7 +267,7 @@ class SortedSetsSpec extends RedisStandaloneServer { scanResult.data shouldBe (1 to 20).map(x => x.toDouble -> x.toString) } - Await.result(r, timeOut) + r.futureValue } "ZSCORE" in { @@ -285,7 +285,7 @@ class SortedSetsSpec extends RedisStandaloneServer { zr3 shouldBe Some(Double.PositiveInfinity) zr4 shouldBe Some(Double.NegativeInfinity) } - Await.result(r, timeOut) + r.futureValue } "ZUNIONSTORE" in { @@ -306,7 +306,7 @@ class SortedSetsSpec extends RedisStandaloneServer { zunionstoreWeighted shouldBe 3 zrWeighted shouldBe Seq((ByteString("one"), 5), (ByteString("three"), 9), (ByteString("two"), 10)) } - Await.result(r, timeOut) + r.futureValue } "ZRANGEBYLEX" in { @@ -320,7 +320,7 @@ class SortedSetsSpec extends RedisStandaloneServer { zr1 shouldBe Seq(ByteString("lexA"), ByteString("lexB"), ByteString("lexC")) zr2 shouldBe Seq(ByteString("lexA")) } - Await.result(r, timeOut) + r.futureValue } "ZREVRANGEBYLEX" in { @@ -334,7 +334,7 @@ class SortedSetsSpec extends RedisStandaloneServer { zr1 shouldBe Seq(ByteString("lexC"), ByteString("lexB"), ByteString("lexA")) zr2 shouldBe Seq(ByteString("lexC")) } - Await.result(r, timeOut) + r.futureValue } } } diff --git a/src/test/scala/redis/commands/StringsSpec.scala b/src/test/scala/redis/commands/StringsSpec.scala index 826d57dd..7f7ad215 100644 --- a/src/test/scala/redis/commands/StringsSpec.scala +++ b/src/test/scala/redis/commands/StringsSpec.scala @@ -4,7 +4,7 @@ import akka.util.ByteString import redis._ import redis.actors.ReplyErrorException -import scala.concurrent.{Await, Future} +import scala.concurrent.Future class StringsSpec extends RedisStandaloneServer { @@ -20,7 +20,7 @@ class StringsSpec extends RedisStandaloneServer { redis.get("appendKey") }) }) - Await.result(r, timeOut) shouldBe Some(ByteString("Hello World")) + r.futureValue shouldBe Some(ByteString("Hello World")) } "BITCOUNT" in { @@ -32,7 +32,7 @@ class StringsSpec extends RedisStandaloneServer { val c = redis.bitcount("bitcountKey", 1, 1) Future.sequence(Seq(a, b, c)) }) - Await.result(r, timeOut) shouldBe Seq(26, 4, 6) + r.futureValue shouldBe Seq(26, 4, 6) } "BITOP" in { @@ -47,20 +47,20 @@ class StringsSpec extends RedisStandaloneServer { not <- redis.bitopNOT("NOTbitopKey", "bitopKey1") } yield { withClue("AND") { - Await.result(redis.get("ANDbitopKey"), timeOut) shouldBe Some(ByteString("a`bc`ab a")) + redis.get("ANDbitopKey").futureValue shouldBe Some(ByteString("a`bc`ab a")) } withClue("OR") { - Await.result(redis.get("ORbitopKey"), timeOut) shouldBe Some(ByteString("agoofev a")) + redis.get("ORbitopKey").futureValue shouldBe Some(ByteString("agoofev a")) } withClue("XOR") { - Await.result(redis.get("XORbitopKey"), timeOut) shouldBe Some(ByteString(0, 7, 13, 12, 6, 4, 20, 0, 0)) + redis.get("XORbitopKey").futureValue shouldBe Some(ByteString(0, 7, 13, 12, 6, 4, 20, 0, 0)) } withClue("NOT") { - Await.result(redis.get("NOTbitopKey"), timeOut) shouldBe Some( + redis.get("NOTbitopKey").futureValue shouldBe Some( ByteString(-98, -103, -112, -112, -99, -98, -115, -33, -98)) } } - Await.result(r, timeOut) + r.futureValue } "BITPOS" in { @@ -79,22 +79,14 @@ class StringsSpec extends RedisStandaloneServer { v4 shouldBe -1 v5 shouldBe 8 } - Await.result(r, timeOut) + r.futureValue } "DECR" in { - val r = redis - .set("decrKey", "10") - .flatMap(_ => { - redis.decr("decrKey") - }) - val r2 = redis - .set("decrKeyError", "234293482390480948029348230948") - .flatMap(_ => { - redis.decr("decrKeyError") - }) - Await.result(r, timeOut) shouldBe 9 - an[ReplyErrorException] should be thrownBy Await.result(r2, timeOut) + redis.set("decrKey", "10").futureValue shouldBe true + redis.decr("decrKey").futureValue shouldBe 9 + redis.set("decrKeyError", "non-int").futureValue + redis.decr("decrKeyError").failed.futureValue shouldBe a[ReplyErrorException] } "DECRBY" in { @@ -103,7 +95,7 @@ class StringsSpec extends RedisStandaloneServer { .flatMap(_ => { redis.decrby("decrbyKey", 5) }) - Await.result(r, timeOut) shouldBe 5 + r.futureValue shouldBe 5 } "GET" in { @@ -113,15 +105,15 @@ class StringsSpec extends RedisStandaloneServer { .flatMap(_ => { redis.get("getKey") }) - Await.result(r, timeOut) shouldBe None - Await.result(r2, timeOut) shouldBe Some(ByteString("Hello")) + r.futureValue shouldBe None + r2.futureValue shouldBe Some(ByteString("Hello")) val rrr = for { r3 <- redis.get[String]("getKey") } yield { r3 shouldBe Some("Hello") } - Await.result(rrr, timeOut) + rrr.futureValue } "GET with conversion" in { @@ -131,7 +123,7 @@ class StringsSpec extends RedisStandaloneServer { .flatMap(_ => { redis.get[DumbClass]("getDumbKey") }) - Await.result(r, timeOut) shouldBe Some(dumbObject) + r.futureValue shouldBe Some(dumbObject) } "GETBIT" in { @@ -141,8 +133,8 @@ class StringsSpec extends RedisStandaloneServer { .flatMap(_ => { redis.getbit("getbitKey", 1) }) - Await.result(r, timeOut) shouldBe false - Await.result(r2, timeOut) shouldBe true + r.futureValue shouldBe false + r2.futureValue shouldBe true } "GETRANGE" in { @@ -157,7 +149,7 @@ class StringsSpec extends RedisStandaloneServer { redis.getrange("getrangeKey", 10, 100) ).map(_.map(_.map(_.utf8String).get))) }) - Await.result(r, timeOut) shouldBe Seq("This", "ing", "This is a string", "string") + r.futureValue shouldBe Seq("This", "ing", "This is a string", "string") } "GETSET" in { @@ -171,7 +163,7 @@ class StringsSpec extends RedisStandaloneServer { redis.get("getsetKey") }) }) - Await.result(r, timeOut) shouldBe Some(ByteString("World")) + r.futureValue shouldBe Some(ByteString("World")) } "INCR" in { @@ -180,7 +172,7 @@ class StringsSpec extends RedisStandaloneServer { .flatMap(_ => { redis.incr("incrKey") }) - Await.result(r, timeOut) shouldBe 11 + r.futureValue shouldBe 11 } "INCRBY" in { @@ -189,7 +181,7 @@ class StringsSpec extends RedisStandaloneServer { .flatMap(_ => { redis.incrby("incrbyKey", 5) }) - Await.result(r, timeOut) shouldBe 15 + r.futureValue shouldBe 15 } "INCRBYFLOAT" in { @@ -198,7 +190,7 @@ class StringsSpec extends RedisStandaloneServer { .flatMap(_ => { redis.incrbyfloat("incrbyfloatKey", 0.15) }) - Await.result(r, timeOut) shouldBe Some(10.65) + r.futureValue shouldBe Some(10.65) } "MGET" in { @@ -211,21 +203,13 @@ class StringsSpec extends RedisStandaloneServer { } yield { mget shouldBe Seq(Some(ByteString("Hello")), Some(ByteString("World")), None) } - Await.result(r, timeOut) + r.futureValue } "MSET" in { - val r = redis - .mset(Map("msetKey" -> "Hello", "msetKey2" -> "World")) - .flatMap(ok => { - ok shouldBe true - Future.sequence( - Seq( - redis.get("msetKey"), - redis.get("msetKey2") - )) - }) - Await.result(r, timeOut) shouldBe Seq(Some(ByteString("Hello")), Some(ByteString("World"))) + redis.mset(Map("msetKey" -> "Hello", "msetKey2" -> "World")).futureValue shouldBe true + redis.get("msetKey").futureValue shouldBe Some(ByteString("Hello")) + redis.get("msetKey2").futureValue shouldBe Some(ByteString("World")) } "MSETNX" in { @@ -237,12 +221,11 @@ class StringsSpec extends RedisStandaloneServer { msetnx shouldBe true msetnxFalse shouldBe false } - Await.result(r, timeOut) + r.futureValue } "PSETEX" in { redis.psetex("psetexKey", 1000, "temp value").futureValue shouldBe true - redis.get("psetexKey").futureValue shouldBe Some(ByteString("temp value")) eventually { redis.get("psetexKey").futureValue shouldBe empty } } @@ -275,12 +258,12 @@ class StringsSpec extends RedisStandaloneServer { setFalse shouldBe true getFalse shouldBe false } - Await.result(r, timeOut) + r.futureValue } "SETEX" in { - redis.setex("setexKey", 1, "temp value").futureValue shouldBe true - redis.get("setexKey").futureValue shouldBe Some(ByteString("temp value")) + val ttl = 1 + redis.setex("setexKey", ttl, "temp value").futureValue shouldBe true eventually { redis.get("setexKey").futureValue shouldBe empty } } @@ -293,7 +276,7 @@ class StringsSpec extends RedisStandaloneServer { s1 shouldBe true s2 shouldBe false } - Await.result(r, timeOut) + r.futureValue } "SETRANGE" in { @@ -307,7 +290,7 @@ class StringsSpec extends RedisStandaloneServer { redis.get("setrangeKey") }) }) - Await.result(r, timeOut) shouldBe Some(ByteString("Hello Redis")) + r.futureValue shouldBe Some(ByteString("Hello Redis")) } "STRLEN" in { @@ -321,7 +304,7 @@ class StringsSpec extends RedisStandaloneServer { redis.strlen("strlenKeyNonexisting") }) }) - Await.result(r, timeOut) shouldBe 0 + r.futureValue shouldBe 0 } } } diff --git a/src/test/scala/redis/commands/TransactionsSpec.scala b/src/test/scala/redis/commands/TransactionsSpec.scala index e21e508d..bf1c16c4 100644 --- a/src/test/scala/redis/commands/TransactionsSpec.scala +++ b/src/test/scala/redis/commands/TransactionsSpec.scala @@ -1,7 +1,7 @@ package redis.commands import redis._ -import scala.concurrent.Await + import akka.util.ByteString import redis.actors.ReplyErrorException import redis.protocol.{Bulk, Status, MultiBulk} @@ -24,16 +24,14 @@ class TransactionsSpec extends RedisStandaloneServer { s shouldBe true g shouldBe Some(ByteString("abc")) } - the[ReplyErrorException] thrownBy { - Await.result(decr, timeOut) - } - Await.result(r, timeOut) + decr.failed.futureValue shouldBe a[ReplyErrorException] + r.futureValue } "function api" in { withClue("empty") { val empty = redis.multi().exec() - Await.result(empty, timeOut) shouldBe MultiBulk(Some(Vector())) + empty.futureValue shouldBe MultiBulk(Some(Vector())) } val redisTransaction = redis.multi(redis => { redis.set("a", "abc") @@ -41,12 +39,12 @@ class TransactionsSpec extends RedisStandaloneServer { }) withClue("non empty") { val exec = redisTransaction.exec() - Await.result(exec, timeOut) shouldBe MultiBulk(Some(Vector(Status(ByteString("OK")), Bulk(Some(ByteString("abc")))))) + exec.futureValue shouldBe MultiBulk(Some(Vector(Status(ByteString("OK")), Bulk(Some(ByteString("abc")))))) } withClue("reused") { redisTransaction.get("transactionUndefinedKey") val exec = redisTransaction.exec() - Await.result(exec, timeOut) shouldBe MultiBulk(Some(Vector(Status(ByteString("OK")), Bulk(Some(ByteString("abc"))), Bulk(None)))) + exec.futureValue shouldBe MultiBulk(Some(Vector(Status(ByteString("OK")), Bulk(Some(ByteString("abc"))), Bulk(None)))) } withClue("watch") { val transaction = redis.watch("transactionWatchKey") @@ -60,7 +58,7 @@ class TransactionsSpec extends RedisStandaloneServer { } yield { s shouldBe true } - Await.result(r, timeOut) + r.futureValue } } From e2ea5365c32f3a8457247b2d81b8b0ac34fcc50d Mon Sep 17 00:00:00 2001 From: Alexey Kardapoltsev Date: Sun, 24 Feb 2019 21:23:14 +0700 Subject: [PATCH 08/11] add debug logs --- src/test/resources/log4j2.xml | 2 +- src/test/scala/redis/RedisSpec.scala | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/test/resources/log4j2.xml b/src/test/resources/log4j2.xml index 126c95b3..111be68c 100644 --- a/src/test/resources/log4j2.xml +++ b/src/test/resources/log4j2.xml @@ -7,7 +7,7 @@ - + diff --git a/src/test/scala/redis/RedisSpec.scala b/src/test/scala/redis/RedisSpec.scala index b641b51f..80f281b4 100644 --- a/src/test/scala/redis/RedisSpec.scala +++ b/src/test/scala/redis/RedisSpec.scala @@ -75,6 +75,7 @@ abstract class RedisHelper extends TestKit(ActorSystem()) with TestBase with Bef } private def startProcess(process: RedisProcess): RedisProcess = { + log.debug(s"starting redis process on ${process.port}") process.start() ensureRedisStarted(redisHost, process.port) processes = processes :+ process @@ -92,6 +93,7 @@ abstract class RedisHelper extends TestKit(ActorSystem()) with TestBase with Bef eventually { client.ping().futureValue } + log.debug(s"redis was started on $port") } } From 919a01cd32d0f816f7144490d282dcd399df798c Mon Sep 17 00:00:00 2001 From: Alexey Kardapoltsev Date: Sun, 24 Feb 2019 21:43:48 +0700 Subject: [PATCH 09/11] change travis time factor --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 9f50128f..58828e80 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ env: - TEST_TIME_FACTOR=500 + TEST_TIME_FACTOR=100 dist: xenial language: scala From 1e4572adb6edf3e33f87864253c7c622ef066b25 Mon Sep 17 00:00:00 2001 From: Alexey Kardapoltsev Date: Sun, 24 Feb 2019 22:13:43 +0700 Subject: [PATCH 10/11] more debug logs --- build.sbt | 6 ++- src/test/scala/redis/RedisSpec.scala | 58 ++++++++++++++-------------- 2 files changed, 34 insertions(+), 30 deletions(-) diff --git a/build.sbt b/build.sbt index 2557c554..dd383ba4 100644 --- a/build.sbt +++ b/build.sbt @@ -56,7 +56,11 @@ lazy val common = Seq( apiURL := Some(url("http://etaty.github.io/rediscala/")) ) -lazy val root = (project in file(".")).settings(common, name := "rediscala") +lazy val root = (project in file(".")).settings( + common, + name := "rediscala", + logBuffered in Test := false +) lazy val bench = (project in file("src/bench")) .settings( diff --git a/src/test/scala/redis/RedisSpec.scala b/src/test/scala/redis/RedisSpec.scala index 80f281b4..911669ff 100644 --- a/src/test/scala/redis/RedisSpec.scala +++ b/src/test/scala/redis/RedisSpec.scala @@ -22,8 +22,8 @@ object RedisServerHelper { val redisHost = "127.0.0.1" // remove stacktrace when we stop the process - val redisServerCmd = "redis-server" - val redisCliCmd = "redis-cli" + val redisServerCmd = "redis-server" + val redisCliCmd = "redis-cli" val redisServerLogLevel = "" val portNumber = new AtomicInteger(10500) @@ -32,14 +32,12 @@ object RedisServerHelper { abstract class RedisHelper extends TestKit(ActorSystem()) with TestBase with BeforeAndAfterAll { protected val processLogger = ProcessLogger(line => log.debug(line), line => log.error(line)) - implicit val executionContext = system.dispatchers.lookup(Redis.dispatcher.name) override def spanScaleFactor: Double = { testKitSettings.TestTimeFactor } - // import scala.concurrent.duration._ // val timeOut = 10.seconds @@ -113,7 +111,7 @@ abstract class RedisStandaloneServer extends RedisHelper { val server = redisManager.newRedisProcess() - val port = server.port + val port = server.port lazy val redis = RedisClient(port = port) def redisVersion(): Future[Option[RedisVersion]] = redis.info("Server").map { info => @@ -135,7 +133,7 @@ abstract class RedisStandaloneServer extends RedisHelper { def withRedisServer[T](block: (Int) => T): T = { val serverProcess = redisManager.newRedisProcess() - val result = Try(block(serverProcess.port)) + val result = Try(block(serverProcess.port)) serverProcess.stop() result.get } @@ -151,15 +149,16 @@ abstract class RedisSentinelClients(val masterName: String = "mymaster") extends import RedisServerHelper._ - val masterPort = portNumber.incrementAndGet() - val slavePort1 = portNumber.incrementAndGet() - val slavePort2 = portNumber.incrementAndGet() + val masterPort = portNumber.incrementAndGet() + val slavePort1 = portNumber.incrementAndGet() + val slavePort2 = portNumber.incrementAndGet() val sentinelPort1 = portNumber.incrementAndGet() val sentinelPort2 = portNumber.incrementAndGet() + log.debug(s"starting sentinel clients with master port $masterPort, slave1 $slavePort1, slave2 $slavePort2") val sentinelPorts = Seq(sentinelPort1, sentinelPort2) - lazy val redisClient = RedisClient(port = masterPort) + lazy val redisClient = RedisClient(port = masterPort) lazy val sentinelClient = SentinelClient(port = sentinelPort1) lazy val sentinelMonitoredRedisClient = SentinelMonitoredRedisClient( @@ -172,10 +171,8 @@ abstract class RedisSentinelClients(val masterName: String = "mymaster") extends val slave1 = redisManager.newSlaveProcess(masterPort, slavePort1) val slave2 = redisManager.newSlaveProcess(masterPort, slavePort2) - val sentinel1 = - redisManager.newSentinelProcess(masterName, masterPort, sentinelPort1) - val sentinel2 = - redisManager.newSentinelProcess(masterName, masterPort, sentinelPort2) + val sentinel1 = redisManager.newSentinelProcess(masterName, masterPort, sentinelPort1) + val sentinel2 = redisManager.newSentinelProcess(masterName, masterPort, sentinelPort2) def newSlaveProcess() = { redisManager.newSlaveProcess(masterPort) @@ -198,7 +195,7 @@ abstract class RedisClusterClients() extends RedisHelper { import RedisServerHelper._ var processes: Seq[Process] = Seq.empty - protected val fileDir = createTempDirectory().toFile + protected val fileDir = createTempDirectory().toFile def newNode(port: Int) = s"$redisServerCmd --port $port --cluster-enabled yes --cluster-config-file nodes-${port}.conf --cluster-node-timeout 30000 --appendonly yes --appendfilename appendonly-${port}.aof --dbfilename dump-${port}.rdb --logfile ${port}.log --daemonize yes" @@ -239,7 +236,9 @@ abstract class RedisClusterClients() extends RedisHelper { ) .exitValue() - val servers = nodePorts.map { port => RedisServer(host = redisHost, port = port)} + val servers = nodePorts.map { port => + RedisServer(host = redisHost, port = port) + } val client = RedisCluster(servers) eventually { val clusterInfo = client.clusterInfo().futureValue @@ -274,38 +273,40 @@ abstract class RedisClusterClients() extends RedisHelper { import redis.RedisServerHelper._ class RedisProcess(val port: Int) { - var server: Process = null - val cmd = s"${redisServerCmd} --port $port ${redisServerLogLevel}" - protected val log = Logger(getClass) + var server: Process = null + val cmd = s"${redisServerCmd} --port $port ${redisServerLogLevel}" + protected val log = Logger(getClass) protected val processLogger = ProcessLogger(line => log.debug(line), line => log.error(line)) def start() = { + log.debug(s"starting $this") if (server == null) server = Process(cmd).run(processLogger) } def stop() = { + log.debug(s"stopping $this") if (server != null) { try { val out = new Socket(redisHost, port).getOutputStream out.write("SHUTDOWN NOSAVE\n".getBytes) - out.flush + out.flush() out.close() - } catch { - case NonFatal(e) => e.printStackTrace() + case NonFatal(e) => log.error(s"couldn't stop $this", e) } finally { server.destroy() server = null } } - } + + override def toString: String = s"RedisProcess($port)" } class SentinelProcess(masterName: String, masterPort: Int, port: Int) extends RedisProcess(port) { - - lazy val sentinelConfPath = { + log.debug(s"starting sentinel process with master post $masterPort on $port") + val sentinelConfPath = { val sentinelConf = s""" |sentinel monitor $masterName $redisHost $masterPort 2 @@ -319,11 +320,10 @@ class SentinelProcess(masterName: String, masterPort: Int, port: Int) extends Re sentinelConfFile.path } - override val cmd = - s"${redisServerCmd} $sentinelConfPath --port $port --sentinel $redisServerLogLevel" + override val cmd = s"${redisServerCmd} $sentinelConfPath --port $port --sentinel $redisServerLogLevel" } class SlaveProcess(masterPort: Int, port: Int) extends RedisProcess(port) { - override val cmd = - s"$redisServerCmd --port $port --slaveof $redisHost $masterPort $redisServerLogLevel" + log.debug(s"starting slave process with master post $masterPort on $port") + override val cmd = s"$redisServerCmd --port $port --slaveof $redisHost $masterPort $redisServerLogLevel" } From 209cc631f5c2b14d8fe4edb6eb1dd9689afb7b30 Mon Sep 17 00:00:00 2001 From: Alexey Kardapoltsev Date: Sun, 24 Feb 2019 22:58:06 +0700 Subject: [PATCH 11/11] small cleanup --- src/main/scala/redis/RedisPool.scala | 106 +++++++++--------- src/test/scala/redis/RedisClusterTest.scala | 4 +- src/test/scala/redis/RedisSpec.scala | 54 +++------ ...MonitoredRedisClientMasterSlavesSpec.scala | 1 + .../scala/redis/SentinelMutablePoolSpec.scala | 4 +- src/test/scala/redis/TestBase.scala | 2 +- 6 files changed, 80 insertions(+), 91 deletions(-) diff --git a/src/main/scala/redis/RedisPool.scala b/src/main/scala/redis/RedisPool.scala index 21eaaadd..a9218cdf 100644 --- a/src/main/scala/redis/RedisPool.scala +++ b/src/main/scala/redis/RedisPool.scala @@ -15,10 +15,9 @@ case class RedisServer(host: String = "localhost", password: Option[String] = None, db: Option[Int] = None) - case class RedisConnection(actor: ActorRef, active: Ref[Boolean] = Ref(false)) -abstract class RedisClientPoolLike(system: ActorSystem, redisDispatcher: RedisDispatcher) { +abstract class RedisClientPoolLike(system: ActorSystem, redisDispatcher: RedisDispatcher) { def redisServerConnections: scala.collection.Map[RedisServer, RedisConnection] @@ -26,6 +25,7 @@ abstract class RedisClientPoolLike(system: ActorSystem, redisDispatcher: RedisDi implicit val executionContext = system.dispatchers.lookup(redisDispatcher.name) private val redisConnectionRef: Ref[Seq[ActorRef]] = Ref(Seq.empty) + /** * * @param redisCommand @@ -55,12 +55,12 @@ abstract class RedisClientPoolLike(system: ActorSystem, redisDispatcher: RedisDi server.db.foreach(redis.select) } - def onConnectStatus(server: RedisServer, active: Ref[Boolean]): (Boolean) => Unit = { - (status: Boolean) => { - if (active.single.compareAndSet(!status, status)) { - refreshConnections() - } + def onConnectStatus(server: RedisServer, active: Ref[Boolean]): (Boolean) => Unit = { (status: Boolean) => + { + if (active.single.compareAndSet(!status, status)) { + refreshConnections() } + } } def refreshConnections() = { @@ -78,8 +78,8 @@ abstract class RedisClientPoolLike(system: ActorSystem, redisDispatcher: RedisDi } /** - * Disconnect from the server (stop the actor) - */ + * Disconnect from the server (stop the actor) + */ def stop() { redisConnectionPool.foreach { redisConnection => system stop redisConnection @@ -92,23 +92,31 @@ abstract class RedisClientPoolLike(system: ActorSystem, redisDispatcher: RedisDi } def makeRedisClientActor(server: RedisServer, active: Ref[Boolean]): ActorRef = { - system.actorOf(RedisClientActor.props(new InetSocketAddress(server.host, server.port), - getConnectOperations(server), onConnectStatus(server, active), redisDispatcher.name) - .withDispatcher(redisDispatcher.name), + system.actorOf( + RedisClientActor + .props( + new InetSocketAddress(server.host, server.port), + getConnectOperations(server), + onConnectStatus(server, active), + redisDispatcher.name) + .withDispatcher(redisDispatcher.name), name + '-' + Redis.tempName() ) } } -case class RedisClientMutablePool(redisServers: Seq[RedisServer], - name: String = "RedisClientPool") - (implicit system: ActorSystem, - redisDispatcher: RedisDispatcher = Redis.dispatcher - ) extends RedisClientPoolLike (system, redisDispatcher) with RoundRobinPoolRequest with RedisCommands { +case class RedisClientMutablePool(redisServers: Seq[RedisServer], name: String = "RedisClientPool")( + implicit system: ActorSystem, + redisDispatcher: RedisDispatcher = Redis.dispatcher) + extends RedisClientPoolLike(system, redisDispatcher) + with RoundRobinPoolRequest + with RedisCommands { override val redisServerConnections = { - val m = redisServers map { server => makeRedisConnection(server) } + val m = redisServers map { server => + makeRedisConnection(server) + } collection.mutable.Map(m: _*) } @@ -134,14 +142,14 @@ case class RedisClientMutablePool(redisServers: Seq[RedisServer], } } - } -case class RedisClientPool(redisServers: Seq[RedisServer], - name: String = "RedisClientPool") - (implicit _system: ActorSystem, - redisDispatcher: RedisDispatcher = Redis.dispatcher - ) extends RedisClientPoolLike(_system, redisDispatcher) with RoundRobinPoolRequest with RedisCommands { +case class RedisClientPool(redisServers: Seq[RedisServer], name: String = "RedisClientPool")( + implicit _system: ActorSystem, + redisDispatcher: RedisDispatcher = Redis.dispatcher) + extends RedisClientPoolLike(_system, redisDispatcher) + with RoundRobinPoolRequest + with RedisCommands { override val redisServerConnections = { redisServers.map { server => @@ -153,11 +161,11 @@ case class RedisClientPool(redisServers: Seq[RedisServer], } -case class RedisClientMasterSlaves(master: RedisServer, - slaves: Seq[RedisServer]) - (implicit _system: ActorSystem, - redisDispatcher: RedisDispatcher = Redis.dispatcher) - extends RedisCommands with Transactions { +case class RedisClientMasterSlaves(master: RedisServer, slaves: Seq[RedisServer])(implicit _system: ActorSystem, + redisDispatcher: RedisDispatcher = + Redis.dispatcher) + extends RedisCommands + with Transactions { implicit val executionContext = _system.dispatchers.lookup(redisDispatcher.name) val masterClient = RedisClient(master.host, master.port, master.password, master.db) @@ -175,26 +183,24 @@ case class RedisClientMasterSlaves(master: RedisServer, def redisConnection: ActorRef = masterClient.redisConnection } - case class SentinelMonitoredRedisClientMasterSlaves( - sentinels: Seq[(String, Int)] = Seq(("localhost", 26379)), master: String) - (implicit _system: ActorSystem, redisDispatcher: RedisDispatcher = Redis.dispatcher) - extends SentinelMonitored(_system, redisDispatcher) with ActorRequest with RedisCommands with Transactions { - - val masterClient: RedisClient = withMasterAddr( - (ip, port) => { - new RedisClient(ip, port, name = "SMRedisClient") - }) - - val slavesClients: RedisClientMutablePool = withSlavesAddr( - slavesHostPort => { - val slaves = slavesHostPort.map { - case (ip, port) => - new RedisServer(ip, port) - } - new RedisClientMutablePool(slaves, name = "SMRedisClient") - }) - + sentinels: Seq[(String, Int)] = Seq(("localhost", 26379)), + master: String)(implicit _system: ActorSystem, redisDispatcher: RedisDispatcher = Redis.dispatcher) + extends SentinelMonitored(_system, redisDispatcher) + with ActorRequest + with RedisCommands + with Transactions { + + val masterClient: RedisClient = withMasterAddr((ip, port) => { + new RedisClient(ip, port, name = "SMRedisClient") + }) + + val slavesClients: RedisClientMutablePool = withSlavesAddr(slavesHostPort => { + val slaves = slavesHostPort.map { + case (ip, port) => RedisServer(ip, port) + } + RedisClientMutablePool(slaves, name = "SMRedisClient") + }) val onNewSlave = (ip: String, port: Int) => { log.info(s"onNewSlave $ip:$port") @@ -212,8 +218,8 @@ case class SentinelMonitoredRedisClientMasterSlaves( } /** - * Disconnect from the server (stop the actors) - */ + * Disconnect from the server (stop the actors) + */ def stop() = { masterClient.stop() slavesClients.stop() diff --git a/src/test/scala/redis/RedisClusterTest.scala b/src/test/scala/redis/RedisClusterTest.scala index c990d164..428ab774 100644 --- a/src/test/scala/redis/RedisClusterTest.scala +++ b/src/test/scala/redis/RedisClusterTest.scala @@ -12,8 +12,8 @@ import redis.protocol._ class RedisClusterTest extends RedisClusterClients { var redisCluster: RedisCluster = null - override def setup(): Unit = { - super.setup() + override def beforeAll(): Unit = { + super.beforeAll() redisCluster = RedisCluster(nodePorts.map(p => RedisServer("127.0.0.1", p))) } diff --git a/src/test/scala/redis/RedisSpec.scala b/src/test/scala/redis/RedisSpec.scala index 911669ff..df5d5310 100644 --- a/src/test/scala/redis/RedisSpec.scala +++ b/src/test/scala/redis/RedisSpec.scala @@ -20,12 +20,9 @@ import scala.util.control.NonFatal object RedisServerHelper { val redisHost = "127.0.0.1" - - // remove stacktrace when we stop the process val redisServerCmd = "redis-server" val redisCliCmd = "redis-cli" val redisServerLogLevel = "" - val portNumber = new AtomicInteger(10500) } @@ -38,22 +35,10 @@ abstract class RedisHelper extends TestKit(ActorSystem()) with TestBase with Bef testKitSettings.TestTimeFactor } -// import scala.concurrent.duration._ -// val timeOut = 10.seconds - - override protected def beforeAll(): Unit = { - setup() - } - override protected def afterAll(): Unit = { TestKit.shutdownActorSystem(system) - cleanup() } - def setup() - - def cleanup() - class RedisManager { import RedisServerHelper._ @@ -138,9 +123,8 @@ abstract class RedisStandaloneServer extends RedisHelper { result.get } - override def setup() = {} - - override def cleanup() = { + override def afterAll() = { + super.afterAll() redisManager.stopAll() } } @@ -182,9 +166,8 @@ abstract class RedisSentinelClients(val masterName: String = "mymaster") extends redisManager.newSentinelProcess(masterName, masterPort) } - override def setup() = {} - - override def cleanup() = { + override def afterAll() = { + super.afterAll() redisManager.stopAll() } @@ -202,16 +185,15 @@ abstract class RedisClusterClients() extends RedisHelper { val nodePorts = (0 to 5).map(_ => portNumber.incrementAndGet()) - override def setup() = { - println("Setup") + override def beforeAll() = { + log.debug(s"Starting Redis cluster with $nodePorts") fileDir.mkdirs() processes = nodePorts.map(s => Process(newNode(s), fileDir).run(processLogger)) val nodes = nodePorts.map(s => redisHost + ":" + s).mkString(" ") - val createClusterCmd = - s"$redisCliCmd --cluster create --cluster-replicas 1 ${nodes}" - println(createClusterCmd) + val createClusterCmd = s"$redisCliCmd --cluster create --cluster-replicas 1 ${nodes}" + log.debug(createClusterCmd) Process(createClusterCmd) .run( new ProcessIO( @@ -219,16 +201,16 @@ abstract class RedisClusterClients() extends RedisHelper { // Thread.sleep(2000) println("yes") writeInput.write("yes\n".getBytes) - writeInput.flush + writeInput.flush() }, (processOutput: InputStream) => { Source.fromInputStream(processOutput).getLines().foreach { l => - println(l) + log.debug(l) } }, (processError: InputStream) => { Source.fromInputStream(processError).getLines().foreach { l => - println(l) + log.error(l) } }, daemonizeThreads = false @@ -245,10 +227,12 @@ abstract class RedisClusterClients() extends RedisHelper { clusterInfo("cluster_known_nodes") shouldBe nodePorts.length.toString } client.stop() + log.debug(s"RedisCluster started on $nodePorts") } - override def cleanup() = { - println("Stop begin") + override def afterAll() = { + super.afterAll() + log.debug("Stop begin") nodePorts foreach { port => val out = new Socket(redisHost, port).getOutputStream @@ -260,7 +244,7 @@ abstract class RedisClusterClients() extends RedisHelper { //deleteDirectory() - println("Stop end") + log.debug("Stop end") } def deleteDirectory(): Unit = { @@ -278,13 +262,13 @@ class RedisProcess(val port: Int) { protected val log = Logger(getClass) protected val processLogger = ProcessLogger(line => log.debug(line), line => log.error(line)) - def start() = { + def start(): Unit = { log.debug(s"starting $this") if (server == null) server = Process(cmd).run(processLogger) } - def stop() = { + def stop(): Unit = { log.debug(s"stopping $this") if (server != null) { try { @@ -305,7 +289,6 @@ class RedisProcess(val port: Int) { } class SentinelProcess(masterName: String, masterPort: Int, port: Int) extends RedisProcess(port) { - log.debug(s"starting sentinel process with master post $masterPort on $port") val sentinelConfPath = { val sentinelConf = s""" @@ -324,6 +307,5 @@ class SentinelProcess(masterName: String, masterPort: Int, port: Int) extends Re } class SlaveProcess(masterPort: Int, port: Int) extends RedisProcess(port) { - log.debug(s"starting slave process with master post $masterPort on $port") override val cmd = s"$redisServerCmd --port $port --slaveof $redisHost $masterPort $redisServerLogLevel" } diff --git a/src/test/scala/redis/SentinelMonitoredRedisClientMasterSlavesSpec.scala b/src/test/scala/redis/SentinelMonitoredRedisClientMasterSlavesSpec.scala index 3503a10e..b609a511 100644 --- a/src/test/scala/redis/SentinelMonitoredRedisClientMasterSlavesSpec.scala +++ b/src/test/scala/redis/SentinelMonitoredRedisClientMasterSlavesSpec.scala @@ -7,6 +7,7 @@ class SentinelMonitoredRedisClientMasterSlavesSpec lazy val redisMasterSlavesPool = SentinelMonitoredRedisClientMasterSlaves(master = masterName, sentinels = sentinelPorts.map((redisHost, _))) + "sentinel slave pool" should { "add and remove" in { eventually { diff --git a/src/test/scala/redis/SentinelMutablePoolSpec.scala b/src/test/scala/redis/SentinelMutablePoolSpec.scala index 7b579f83..938c5608 100644 --- a/src/test/scala/redis/SentinelMutablePoolSpec.scala +++ b/src/test/scala/redis/SentinelMutablePoolSpec.scala @@ -6,8 +6,8 @@ class SentinelMutablePoolSpec extends RedisSentinelClients("SentinelMutablePoolS var redisPool: RedisClientMutablePool = null - override def setup(): Unit = { - super.setup() + override def beforeAll(): Unit = { + super.beforeAll() redisPool = RedisClientMutablePool(Seq(RedisServer(redisHost, slavePort1)), masterName) } diff --git a/src/test/scala/redis/TestBase.scala b/src/test/scala/redis/TestBase.scala index 3914aa5c..8572c237 100644 --- a/src/test/scala/redis/TestBase.scala +++ b/src/test/scala/redis/TestBase.scala @@ -10,7 +10,7 @@ import org.scalatest.{Matchers, WordSpecLike} trait TestBase extends WordSpecLike with Matchers with ScalaFutures with Eventually { import org.scalatest.time.{Millis, Seconds, Span} implicit protected val defaultPatience = - PatienceConfig(timeout = scaled(Span(1, Seconds)), interval = scaled(Span(10, Millis))) + PatienceConfig(timeout = scaled(Span(1, Seconds)), interval = Span(100, Millis)) protected val log = Logger(getClass)