Testing providers and wrappers¶
Testkit tests your application. This page is for code next to the SDK: a FeatureProvider you wrote, a
wrapper around one, or a custom FlagType. The tools live in the same zio-openfeature-testkit module.
| You wrote | Check it with |
|---|---|
| a provider that must survive hangs, errors and slow calls | FaultyProvider |
a FlagType |
FlagTypeLaws |
| a provider wrapper | WrapperLaws |
| a provider, to compare with the test provider | DifferentialLaws |
Inject faults into a provider¶
FaultyProvider wraps a provider and makes it misbehave on demand: an initialize() that never returns, a hanging
shutdown(), an error event during startup, a failure on the first call only.
val faultInjection = suite("when the provider itself misbehaves")(
test("an initialize() that never returns fails the layer at the init timeout") {
for
faulty <- FaultyProvider.scoped(Map("flag" -> true)) // the scope releases any hang left parked
_ <- faulty.script(Op.Initialize, Fault.HangUntilReleased) // ignores shutdown(), like a stuck SDK
error <- FeatureFlags.fromProvider(faulty, FeatureFlagsConfig.default.withInitTimeout(200.millis)).build.flip
yield assertTrue(error.isInstanceOf[java.util.concurrent.TimeoutException])
},
test("the first evaluation fails, the ones after it succeed") {
for
faulty <- FaultyProvider.scoped(Map("flag" -> true))
_ <- faulty.script(Op.EvaluateBoolean, Fault.Throw(new RuntimeException("timeout")), Fault.Succeed)
both <- (FeatureFlags.boolean("flag", default = false).either <*> FeatureFlags.boolean("flag", default = false))
.provide(FeatureFlags.fromProvider(faulty))
calls <- faulty.calls(Op.EvaluateBoolean)
yield assertTrue(both._1.isLeft, both._2, calls.size == 2)
}
) @@ TestAspect.withLiveClock
script(op, faults*) gives one Op a sequence of faults, one per call; the last repeats. An unscripted op calls the
wrapped provider, and script(op) with no faults clears the script.
flowchart LR
c1["call 1"] --> f1["Throw(e)"]
c2["call 2"] --> f2["Succeed"]
c3["call 3, 4, ..."] --> f2
f2 --> p["wrapped provider"]
The diagram is script(Op.EvaluateBoolean, Fault.Throw(e), Fault.Succeed).
Fault |
Effect |
|---|---|
Succeed |
call the wrapped provider |
Throw(error) |
throw error without calling it |
Delay(d, andThen) |
block the calling thread for d, then apply andThen (default Succeed) |
HangUntilReleased |
block until release (not shutdown()) |
HangUntilShutdown |
block until shutdown() or release |
Emit(event, details, andThen) |
emit an OpenFeature event (e.g. PROVIDER_ERROR inside initialize()), then apply andThen |
Answer(shape) |
an evaluation op only: return a malformed answer instead of the provider's (AnswerShape) |
MetadataAnswer(shape) |
GetMetadata only: return null or a nameless Metadata (MetadataShape) |
AnswerShape is NullValue (no value, no error code), WrongBox (an Integer from the boolean, string, long and
double getters, a Boolean from the integer getter, a String from the object getter), ErrorCodeWithValue,
NullReason or NullEvaluation (the getter returns null).
There is an Op for every FeatureProvider method: Initialize (both overloads), Shutdown, GetMetadata,
GetProviderHooks, GetState, IsDomainScoped, Track, and EvaluateBoolean to EvaluateObject.
| Factory | Wraps |
|---|---|
FaultyProvider.scoped(flags, name) |
a fresh TestFeatureProvider; closing the scope releases parked hangs |
FaultyProvider.make(flags, name) |
the same, without the finalizer |
FaultyProvider.wrapScoped(provider, name), wrap(provider, name) |
any provider |
Prefer the scoped factories: a failing test then still frees parked threads. delegate is the wrapped provider (for
make and scoped, the TestFeatureProvider, so setFlag works).
| Observe | Returns |
|---|---|
calls, calls(op) |
every completed call, in completion order; a hung call appears once it is released |
entered(op) |
how many calls of op have started, including ones still parked |
awaitEntered(op, n) |
waits until n calls (default 1) have started; a release after it reaches them |
release |
unparks every call that entered before it, even one not yet parked; later calls park again |
Each Call has op, flagKey (the event name for track), thread, startedAt, outcome (Outcome.Returned or
Outcome.Threw(error)) and arguments.
The wrapped provider's events do not reach FeatureFlags: use Fault.Emit or the wrapper's emit.
Hostile providers¶
HostileProvider generates whole scripts of wrong answers for property tests: a Script maps each Op to its
faults, and HostileProvider.scripted(script, flags) is a FaultyProvider.scoped with the script applied.
evaluationScripts gives every evaluation op a malformed answer or a thrown exception from throwables (a checked
exception, an unchecked one and a non-fatal Error: only what ZIO does not treat as fatal), and getMetadata a
malformed answer or its own. scripts adds a hostile initialize() (a READY emitted from inside it, or one that
returns only at shutdown) and a shutdown() that throws; build over those with a short init timeout, or each
never-returning start waits out the default one. Run them against what you build on a provider, and assert that
nothing dies. FeatureFlags and the extras wrappers also absorb a provider's StackOverflowError; a library that
hands a provider call to ZIO itself must guard against it, or ZIO exits the JVM:
check(HostileProvider.evaluationScripts) { script =>
ZIO.scoped {
for {
provider <- HostileProvider.scripted(script, Map("flag" -> true))
result <- yourLibrary(provider).exit
} yield assertTrue(!result.causeOption.exists(_.isDie))
}
}
A FaultyProvider records every call, so a test can also check its end state: calls(Op.Shutdown) after
calls(Op.Initialize) tells whether shutdown() reached it twice in one initialization cycle. The library's own
lifecycle specs check that after every test.
The library's own sweep, HostileProviderSweepSpec, runs the typed getters, value[A], the *Details getters,
*OrDefault and resolveOrDefault of FeatureFlags this way and pins the outcome of each shape.
Check a custom FlagType¶
Check a hand-written FlagType with FlagTypeLaws and a Gen for your type:
final case class Celsius(degrees: Int)
object Celsius:
given FlagType[Celsius] = FlagType.mapped[Celsius, Int]("Celsius", Celsius(0))(Celsius(_), _.degrees)
val celsiusLaws = FlagTypeLaws.all(Gen.int(-100, 100).map(Celsius(_)))
celsiusLaws is a Spec; put it in a suite. all runs two laws:
| Law | Checks |
|---|---|
roundTrip |
decode(encode(a)) == Right(a) |
throughValueBridge |
the same, after a trip through the OpenFeature SDK's Value type |
The second finds the real problems: every number comes back as a Double (a Long beyond 2^53 as that exact Long),
and structure members the SDK cannot represent are dropped. Object-backed types always take that path. Both laws work
on Scala 2.13 too.
Check a wrapper passes every call on¶
The OpenFeature SDK adds FeatureProvider methods with default bodies, so an older wrapper keeps compiling but answers
them itself instead of asking the wrapped provider: track events vanish, or a Long evaluation goes through
getDoubleEvaluation. WrapperLaws.delegation catches this. Give it a name and a function that builds your wrapper
around a provider:
val countingDelegates = WrapperLaws.delegation("CountingProvider")(
inner => new CountingProvider(inner),
handledByWrapper = Map(Op.GetMetadata -> "reports its own name")
)
The result is a suite with one test per Op. Each builds your wrapper around a fresh FaultyProvider, calls one method
with distinctive arguments, and checks the wrapped provider received the same call with equal arguments (contexts and
tracking details compared by content), both initialize overloads included. It does not look at the results.
handledByWrapper lists the ops your wrapper answers itself, each with a reason that becomes part of the test name. For
those, the test checks the call does not reach the wrapped provider, and fails with "allow-list entry no longer needed"
if it does. The law runs on Scala 2.13 and 3; the library's own wrappers are checked with it.
Compare a provider with the testkit¶
DifferentialLaws checks the test provider's answers against a real provider. It generates flag sets over every wire
type, puts each into TestFeatureProvider and your provider, reads every key (and AbsentKey) through every typed
accessor, and compares what FeatureFlags returns: value, reason class (Served, Default or Error) and error code,
each an Observed.
List each intended difference as a Deviation with its reason; any other difference fails the test. Here an
environment variable holds text, so a read of another type parses it:
def environment(flags: FlagSet): Map[String, String] =
flags.flags.map((key, value) => s"FF_${EnvVarProvider.defaultKeyTransform(key)}" -> value.toString)
def mismatchedInTestkit(testkit: Observed) = testkit.errorCode.contains(ErrorCode.TypeMismatch)
val envVarAgrees = DifferentialLaws.agreesWithTestkit("env-var")(
seed = flags => ZIO.succeed(EnvVarProvider.withLookup(environment(flags).get)),
deviations = List(
Deviation(
"env-var",
(_, _, testkit, env) => mismatchedInTestkit(testkit) && env.reasonClass == ReasonClass.Served,
"an env var is text: a read of another type is served when the text parses"
),
Deviation(
"env-var",
(_, _, testkit, env) => mismatchedInTestkit(testkit) && env.errorCode.contains(ErrorCode.ParseError),
"an env var is text: text that does not parse is PARSE_ERROR, not TYPE_MISMATCH"
)
),
flagSets = DifferentialLaws.scalarFlagSets, // an env var cannot hold a long or an object
corpus = DifferentialLaws.scalarCorpus
)
seedbuilds your provider holding the generated flags.- A
Disagreementis one request where the two differ. A deviation's predicate gets the flag set, theRequestand bothObservedanswers;sameValueis the strict equality used (1is not1L,-0.0is not0.0,NaNequalsNaN). - A deviation that matched nothing fails as stale, and one filed under another oracle's name fails as misfiled, so the
list cannot outlive the behaviour it excuses.
Deviationtakes an optionalissuereference for failure output. - Each run checks 50 random flag sets (
samples) plus a fixedcorpusof edge cases (NaN, -0.0,Longs beyondInt, text that looks like a number). zio-test seeds the randomness, so failures reproduce. flagSetsandcorpuscover every wire type;scalarFlagSetsandscalarCorpusonly booleans, strings, ints and doubles. The generators are public (flagKey,hostileString,hostileDouble,anyInt,anyLong,objectValue,anyValue), as isrequestsFor(flagSet).comparetakes the same arguments and returns aReportinstead of a test:passed,problemsand per-deviation counts.
This repository runs it for HoconProvider, EnvVarProvider and the OFREP provider.
Absent keys are not found¶
absentKeysAreNotFound(oracleName)(seed) is a second law, for a provider that answers locally. For each key in
adversarialKeys that the provider does not hold (the empty key, every HOCON path character, leading, trailing and
doubled dots, a path-like a.b.c, a character outside the BMP, control characters, a 10 kB key, and include,
null and true), every typed getter must fail with FlagNotFound, never another error or a defect, and the total
tier must serve the default with FLAG_NOT_FOUND. adversarialKey draws one of them; absentKeyViolations returns
the violations instead of a test. Pass ctx with a targeting key for a provider that checks it before the flag key:
DifferentialLaws.absentKeysAreNotFound("hocon")(flags =>
ZIO.succeed(HoconProvider.fromConfig(ConfigFactory.parseString(render(flags))))
)
flagKey stays path-safe: it generates keys for flags that exist, which every oracle has to accept. The repository
applies the law to TestFeatureProvider, CachingReasonProvider, HoconProvider, EnvVarProvider, both extras
wrappers and a ready Optimizely provider. Not to OFREP: the key goes to the server, which decides.
Run a scenario matrix with zio-bdd¶
zio-bdd can run one scenario against several flag configurations, one
FeatureFlags layer per @flags(...) tag. Override flagLayer in your ZIOSteps suite; tag values arrive as
strings:
override def flagLayer(meta: ScenarioMetadata, flags: Map[String, String]): ZLayer[Any, Throwable, FeatureFlags] =
TestFeatureProvider.layer(Map("new-greeting" -> flags.get("greeting").contains("new")))
@flags(greeting=new, plan=pro) runs the scenario once with both keys; two @flags(...) tags on separate lines run it
once per tag. Coarser hooks: scenarioLayer(meta), featureLayer and globalLayer. This block is not a compiled snippet:
zio-bdd is a dependency of the conformance-zio-bdd module only.
CachingReasonProvider
CachingReasonProvider reports the CACHED reason from the second evaluation of a key on; it always calls the
wrapped provider and caches nothing (see CachingProvider). It exists so the conformance suite can run
the spec's CACHED scenario.