Testing
Testing is an integral part of every software development process as such Apache Flink comes with tooling to test your application code on multiple levels of the testing pyramid.
Testing User-Defined Functions
Usually, one can assume that Flink produces correct results outside of a user-defined function. Therefore, it is recommended to test those classes that contain the main business logic with unit tests as much as possible.
Unit Testing Stateless, Timeless UDFs
For example, let’s take the following stateless MapFunction.
Java
public class IncrementMapFunction implements MapFunction<Long, Long> {@Overridepublic Long map(Long record) throws Exception {return record + 1;}}
Scala
class IncrementMapFunction extends MapFunction[Long, Long] {override def map(record: Long): Long = {record + 1}}
It is very easy to unit test such a function with your favorite testing framework by passing suitable arguments and verifying the output.
Java
public class IncrementMapFunctionTest {@Testpublic void testIncrement() throws Exception {// instantiate your functionIncrementMapFunction incrementer = new IncrementMapFunction();// call the methods that you have implementedassertEquals(3L, incrementer.map(2L));}}
Scala
class IncrementMapFunctionTest extends FlatSpec with Matchers {"IncrementMapFunction" should "increment values" in {// instantiate your functionval incrementer: IncrementMapFunction = new IncrementMapFunction()// call the methods that you have implementedincremeter.map(2) should be (3)}}
Similarly, a user-defined function which uses an org.apache.flink.util.Collector (e.g. a FlatMapFunction or ProcessFunction) can be easily tested by providing a mock object instead of a real collector. A FlatMapFunction with the same functionality as the IncrementMapFunction could be unit tested as follows.
Java
public class IncrementFlatMapFunctionTest {@Testpublic void testIncrement() throws Exception {// instantiate your functionIncrementFlatMapFunction incrementer = new IncrementFlatMapFunction();Collector<Integer> collector = mock(Collector.class);// call the methods that you have implementedincrementer.flatMap(2L, collector);//verify collector was called with the right outputMockito.verify(collector, times(1)).collect(3L);}}
Scala
class IncrementFlatMapFunctionTest extends FlatSpec with MockFactory {"IncrementFlatMapFunction" should "increment values" in {// instantiate your functionval incrementer : IncrementFlatMapFunction = new IncrementFlatMapFunction()val collector = mock[Collector[Integer]]//verify collector was called with the right output(collector.collect _).expects(3)// call the methods that you have implementedflattenFunction.flatMap(2, collector)}}
Unit Testing Stateful or Timely UDFs & Custom Operators
Testing the functionality of a user-defined function, which makes use of managed state or timers is more difficult because it involves testing the interaction between the user code and Flink’s runtime. For this Flink comes with a collection of so called test harnesses, which can be used to test such user-defined functions as well as custom operators:
OneInputStreamOperatorTestHarness(for operators onDataStreams)KeyedOneInputStreamOperatorTestHarness(for operators onKeyedStreams)TwoInputStreamOperatorTestHarness(for operators ofConnectedStreamsof twoDataStreams)KeyedTwoInputStreamOperatorTestHarness(for operators onConnectedStreamsof twoKeyedStreams)
To use the test harnesses a set of additional dependencies is needed. Refer to the configuration section for more detail.
Now, the test harnesses can be used to push records and watermarks into your user-defined functions or custom operators, control processing time and finally assert on the output of the operator (including side outputs).
Java
public class StatefulFlatMapTest {private OneInputStreamOperatorTestHarness<Long, Long> testHarness;private StatefulFlatMap statefulFlatMapFunction;@Beforepublic void setupTestHarness() throws Exception {//instantiate user-defined functionstatefulFlatMapFunction = new StatefulFlatMapFunction();// wrap user defined function into a the corresponding operatortestHarness = new OneInputStreamOperatorTestHarness<>(new StreamFlatMap<>(statefulFlatMapFunction));// optionally configured the execution environmenttestHarness.getExecutionConfig().setAutoWatermarkInterval(50);// open the test harness (will also call open() on RichFunctions)testHarness.open();}@Testpublic void testingStatefulFlatMapFunction() throws Exception {//push (timestamped) elements into the operator (and hence user defined function)testHarness.processElement(2L, 100L);//trigger event time timers by advancing the event time of the operator with a watermarktestHarness.processWatermark(100L);//trigger processing time timers by advancing the processing time of the operator directlytestHarness.setProcessingTime(100L);//retrieve list of emitted records for assertionsassertThat(testHarness.getOutput(), containsInExactlyThisOrder(3L));//retrieve list of records emitted to a specific side output for assertions (ProcessFunction only)//assertThat(testHarness.getSideOutput(new OutputTag<>("invalidRecords")), hasSize(0))}}
Scala
class StatefulFlatMapFunctionTest extends FlatSpec with Matchers with BeforeAndAfter {private var testHarness: OneInputStreamOperatorTestHarness[Long, Long] = nullprivate var statefulFlatMap: StatefulFlatMapFunction = nullbefore {//instantiate user-defined functionstatefulFlatMap = new StatefulFlatMap// wrap user defined function into a the corresponding operatortestHarness = new OneInputStreamOperatorTestHarness[Long, Long](new StreamFlatMap(statefulFlatMap))// optionally configured the execution environmenttestHarness.getExecutionConfig().setAutoWatermarkInterval(50)// open the test harness (will also call open() on RichFunctions)testHarness.open()}"StatefulFlatMap" should "do some fancy stuff with timers and state" in {//push (timestamped) elements into the operator (and hence user defined function)testHarness.processElement(2, 100)//trigger event time timers by advancing the event time of the operator with a watermarktestHarness.processWatermark(100)//trigger proccesign time timers by advancing the processing time of the operator directlytestHarness.setProcessingTime(100)//retrieve list of emitted records for assertionstestHarness.getOutput should contain (3)//retrieve list of records emitted to a specific side output for assertions (ProcessFunction only)//testHarness.getSideOutput(new OutputTag[Int]("invalidRecords")) should have size 0}}
KeyedOneInputStreamOperatorTestHarness and KeyedTwoInputStreamOperatorTestHarness are instantiated by additionally providing a KeySelector including TypeInformation for the class of the key.
Java
public class StatefulFlatMapFunctionTest {private OneInputStreamOperatorTestHarness<String, Long, Long> testHarness;private StatefulFlatMap statefulFlatMapFunction;@Beforepublic void setupTestHarness() throws Exception {//instantiate user-defined functionstatefulFlatMapFunction = new StatefulFlatMapFunction();// wrap user defined function into a the corresponding operatortestHarness = new KeyedOneInputStreamOperatorTestHarness<>(new StreamFlatMap<>(statefulFlatMapFunction), new MyStringKeySelector(), Types.STRING);// open the test harness (will also call open() on RichFunctions)testHarness.open();}//tests}
Scala
class StatefulFlatMapTest extends FlatSpec with Matchers with BeforeAndAfter {private var testHarness: OneInputStreamOperatorTestHarness[String, Long, Long] = nullprivate var statefulFlatMapFunction: FlattenFunction = nullbefore {//instantiate user-defined functionstatefulFlatMapFunction = new StateFulFlatMap// wrap user defined function into a the corresponding operatortestHarness = new KeyedOneInputStreamOperatorTestHarness(new StreamFlatMap(statefulFlatMapFunction),new MyStringKeySelector(), Types.STRING())// open the test harness (will also call open() on RichFunctions)testHarness.open()}//tests}
Many more examples for the usage of these test harnesses can be found in the Flink code base, e.g.:
org.apache.flink.streaming.runtime.operators.windowing.WindowOperatorTestis a good example for testing operators and user-defined functions, which depend on processing or event time.
Note Be aware that AbstractStreamOperatorTestHarness and its derived classes are currently not part of the public API and can be subject to change.
Unit Testing ProcessFunction
Given its importance, in addition to the previous test harnesses that can be used directly to test a ProcessFunction, Flink provides a test harness factory named ProcessFunctionTestHarnesses that allows for easier test harness instantiation. Considering this example:
Note Be aware that to use this test harness, you also need to introduce the dependencies mentioned in the last section.
Java
public static class PassThroughProcessFunction extends ProcessFunction<Integer, Integer> {@Overridepublic void processElement(Integer value, Context ctx, Collector<Integer> out) throws Exception {out.collect(value);}}
Scala
class PassThroughProcessFunction extends ProcessFunction[Integer, Integer] {@throws[Exception]override def processElement(value: Integer, ctx: ProcessFunction[Integer, Integer]#Context, out: Collector[Integer]): Unit = {out.collect(value)}}
It is very easy to unit test such a function with ProcessFunctionTestHarnesses by passing suitable arguments and verifying the output.
Java
public class PassThroughProcessFunctionTest {@Testpublic void testPassThrough() throws Exception {//instantiate user-defined functionPassThroughProcessFunction processFunction = new PassThroughProcessFunction();// wrap user defined function into a the corresponding operatorOneInputStreamOperatorTestHarness<Integer, Integer> harness = ProcessFunctionTestHarnesses.forProcessFunction(processFunction);//push (timestamped) elements into the operator (and hence user defined function)harness.processElement(1, 10);//retrieve list of emitted records for assertionsassertEquals(harness.extractOutputValues(), Collections.singletonList(1));}}
Scala
class PassThroughProcessFunctionTest extends FlatSpec with Matchers {"PassThroughProcessFunction" should "forward values" in {//instantiate user-defined functionval processFunction = new PassThroughProcessFunction// wrap user defined function into a the corresponding operatorval harness = ProcessFunctionTestHarnesses.forProcessFunction(processFunction)//push (timestamped) elements into the operator (and hence user defined function)harness.processElement(1, 10)//retrieve list of emitted records for assertionsharness.extractOutputValues() should contain (1)}}
For more examples on how to use the ProcessFunctionTestHarnesses in order to test the different flavours of the ProcessFunction, e.g. KeyedProcessFunction, KeyedCoProcessFunction, BroadcastProcessFunction, etc, the user is encouraged to look at the ProcessFunctionTestHarnessesTest.
Testing Flink Jobs
JUnit Rule MiniClusterWithClientResource
Apache Flink provides a JUnit rule called MiniClusterWithClientResource for testing complete jobs against a local, embedded mini cluster. called MiniClusterWithClientResource.
To use MiniClusterWithClientResource one additional dependency (test scoped) is needed.
<dependency><groupId>org.apache.flink</groupId><artifactId>flink-test-utils</artifactId><version>1.16.0</version><scope>test</scope></dependency>
Copied to clipboard!
Let us take the same simple MapFunction as in the previous sections.
Java
public class IncrementMapFunction implements MapFunction<Long, Long> {@Overridepublic Long map(Long record) throws Exception {return record + 1;}}
Scala
class IncrementMapFunction extends MapFunction[Long, Long] {override def map(record: Long): Long = {record + 1}}
A simple pipeline using this MapFunction can now be tested in a local Flink cluster as follows.
Java
public class ExampleIntegrationTest {@ClassRulepublic static MiniClusterWithClientResource flinkCluster =new MiniClusterWithClientResource(new MiniClusterResourceConfiguration.Builder().setNumberSlotsPerTaskManager(2).setNumberTaskManagers(1).build());@Testpublic void testIncrementPipeline() throws Exception {StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();// configure your test environmentenv.setParallelism(2);// values are collected in a static variableCollectSink.values.clear();// create a stream of custom elements and apply transformationsenv.fromElements(1L, 21L, 22L).map(new IncrementMapFunction()).addSink(new CollectSink());// executeenv.execute();// verify your resultsassertTrue(CollectSink.values.containsAll(2L, 22L, 23L));}// create a testing sinkprivate static class CollectSink implements SinkFunction<Long> {// must be staticpublic static final List<Long> values = Collections.synchronizedList(new ArrayList<>());@Overridepublic void invoke(Long value, SinkFunction.Context context) throws Exception {values.add(value);}}}
Scala
class StreamingJobIntegrationTest extends FlatSpec with Matchers with BeforeAndAfter {val flinkCluster = new MiniClusterWithClientResource(new MiniClusterResourceConfiguration.Builder().setNumberSlotsPerTaskManager(2).setNumberTaskManagers(1).build)before {flinkCluster.before()}after {flinkCluster.after()}"IncrementFlatMapFunction pipeline" should "incrementValues" in {val env = StreamExecutionEnvironment.getExecutionEnvironment// configure your test environmentenv.setParallelism(2)// values are collected in a static variableCollectSink.values.clear()// create a stream of custom elements and apply transformationsenv.fromElements(1L, 21L, 22L).map(new IncrementMapFunction()).addSink(new CollectSink())// executeenv.execute()// verify your resultsCollectSink.values should contain allOf (2, 22, 23)}}// create a testing sinkclass CollectSink extends SinkFunction[Long] {override def invoke(value: Long, context: SinkFunction.Context): Unit = {CollectSink.values.add(value)}}object CollectSink {// must be staticval values: util.List[Long] = Collections.synchronizedList(new util.ArrayList())}
A few remarks on integration testing with MiniClusterWithClientResource:
In order not to copy your whole pipeline code from production to test, make sources and sinks pluggable in your production code and inject special test sources and test sinks in your tests.
The static variable in
CollectSinkis used here because Flink serializes all operators before distributing them across a cluster. Communicating with operators instantiated by a local Flink mini cluster via static variables is one way around this issue. Alternatively, you could write the data to files in a temporary directory with your test sink.You can implement a custom parallel source function for emitting watermarks if your job uses event time timers.
It is recommended to always test your pipelines locally with a parallelism > 1 to identify bugs which only surface for the pipelines executed in parallel.
Prefer
@ClassRuleover@Ruleso that multiple tests can share the same Flink cluster. Doing so saves a significant amount of time since the startup and shutdown of Flink clusters usually dominate the execution time of the actual tests.If your pipeline contains custom state handling, you can test its correctness by enabling checkpointing and restarting the job within the mini cluster. For this, you need to trigger a failure by throwing an exception from (a test-only) user-defined function in your pipeline.