Supplying ScalaTest config map entries via the environment

(, en)

Supplying dynamic config settings to ScalaTest tests can be cumbersome. So how can you supply them via the environment?

The code

Assume you have code that changes behaviour based on feature flags. You want to test the old and the new features. Some features are internal improvements that do not change the API, so also the tests are the same. Still, you want to test it.

Here is a simple withFixture example. You can pull in the feature flags from the configMap construct of ScalaTest.

// src/test/scala/FeatureFlagSpec.scala
package org.bargsten.spielwiese.scala2

import org.scalatest.Outcome
import org.scalatest.flatspec.FixtureAnyFlatSpec
import org.scalatest.matchers.should.Matchers

class FeatureFlagSpec extends FixtureAnyFlatSpec with Matchers {
  case class FixtureParam(flags: Set[FeatureFlag])

  def withFixture(test: OneArgTest): Outcome = {
    println(test.configMap)
    val flags = test.configMap
      .get("featureFlags")
      .map(_.toString)
      .map(_.split(raw"[|,]").map(s => FeatureFlag(s)))
      .fold(Set.empty[FeatureFlag])(_.toSet)
    super.withFixture(test.toNoArgTest(FixtureParam(flags)))
  }

  it should "contain A flag" in { f =>
    println(f.flags)
    f.flags should contain(FeatureFlag("A"))
  }
}

case class FeatureFlag(name: String)

with sbt

// build.sbt
val featureFlagsArg = sys.env
  .get("FEATURE_FLAGS")
  .map(ff => s"-DfeatureFlags=$ff")
  .map(Tests.Argument(TestFrameworks.ScalaTest, _))
Test / testOptions ++= featureFlagsArg

call it with

FEATURE_FLAGS="A,B,C" sbt test

with maven

<!-- pom.xml -->
<!-- ... -->
<plugin>
  <groupId>org.scalatest</groupId>
  <artifactId>scalatest-maven-plugin</artifactId>
  <version>1.0</version>
  <configuration>
    <config>featureFlags=${env.FEATURE_FLAGS}</config>
  </configuration>
  <executions>
    <execution>
      <id>test</id>
      <goals>
        <goal>test</goal>
      </goals>
    </execution>
  </executions>
</plugin>
<!-- ... -->

call it with

FEATURE_FLAGS="A\,B\,C" mvn test

(You need to escape the comma, because the maven plugin config option expects that the list of configMap entries is separated by comma.)

See also