Skip to content
This repository was archived by the owner on Mar 2, 2022. It is now read-only.

Added implicit Context.getOrNone method #71

Merged
merged 1 commit into from
Jul 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/main/scala/reactor/util/scala/context/SContext.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package reactor.util.scala.context

import reactor.util.context.Context

import scala.reflect.ClassTag

object SContext {
implicit class ContextOps(context: Context) {

/**
* Resolve a value given a key within the [[Context]].
* <p/>
* <b>Important:</b> Unlike the basic Context methods,
* this will actually check the type of the value against the given type parameter,
* and return [[None]] if the value is not of a compatible type.
*
* @param key a lookup key to resolve the value within the context
* @return [[Some]] value for that key,
* or [[None]] if there is no such key (or if its value is the wrong type).
*/
def getOrNone[T](key: Any)(implicit valueType: ClassTag[T]): Option[T] =
context.getOrDefault[Any](key, None) match {
case value:T => Some(value)
case _ => None
}
}
}
46 changes: 46 additions & 0 deletions src/test/scala/reactor/util/scala/context/SContextTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package reactor.util.scala.context

import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import reactor.core.scala.publisher.SMono
import reactor.core.scala.publisher.model.TestSupport
import reactor.test.StepVerifier
import SContext._

class SContextTest extends AnyFreeSpec with Matchers with TestSupport {
"SContext" - {
".getOrNone " - {
"with missing key should return None" in {
StepVerifier.create(
SMono.subscriberContext
.map{ _.getOrNone("BOGUS") }
).expectNext(None)
.verifyComplete()
}
"with value of incompatible type should return None" in {
StepVerifier.create(
SMono.subscriberContext
.map{ _.getOrNone[Sedan]("whatever key") }
.subscriberContext{ _.put("whatever key", Truck(76254))}
).expectNext(None)
.verifyComplete()
}
"with value of exactly the expected type should return Some value" in {
StepVerifier.create(
SMono.subscriberContext
.map{ _.getOrNone[Truck]("whatever key") }
.subscriberContext{ _.put("whatever key", Truck(76254))}
).expectNext(Some(Truck(76254)))
.verifyComplete()
}
"with value of a supertype of the expected type should return Some value" in {
StepVerifier.create(
SMono.subscriberContext
.map{ _.getOrNone[Vehicle](true) }
.subscriberContext{ _.put(true, Truck(76254))}
).expectNext(Some(Truck(76254)))
.verifyComplete()
}
}
}
}