Add OptionalFixturePreparer
Sometimes it is necessary to optionally add a preparer. e.g. There are
many parameterized tests where one of the parameters is some additional
test setup but not every test provides it so it will default to the
"zero" value of whatever type is used for the test setup parameter
Migrating those tests to use test fixtures will typically require that
the test setup parameter be changed to a FixturePreparer, which by
default will be nil.
Attempting to use a nil FixturePreparer in the test fixtures will fail
so the OptionalFixturePreparer was added to wrap a possibly nil
FixturePreparer and thereby avoiding complicating each test with
similar logic.
Bug: 182885307
Test: m nothing
Change-Id: Ia12b2af2105fdc69af4e0b909a37a7b86f1af299
diff --git a/android/fixture.go b/android/fixture.go
index 928967d..0bff995 100644
--- a/android/fixture.go
+++ b/android/fixture.go
@@ -381,6 +381,19 @@
return &compositeFixturePreparer{dedupAndFlattenPreparers(nil, preparers)}
}
+// NullFixturePreparer is a preparer that does nothing.
+var NullFixturePreparer = GroupFixturePreparers()
+
+// OptionalFixturePreparer will return the supplied preparer if it is non-nil, otherwise it will
+// return the NullFixturePreparer
+func OptionalFixturePreparer(preparer FixturePreparer) FixturePreparer {
+ if preparer == nil {
+ return NullFixturePreparer
+ } else {
+ return preparer
+ }
+}
+
type simpleFixturePreparerVisitor func(preparer *simpleFixturePreparer)
// FixturePreparer is an opaque interface that can change a fixture.
diff --git a/android/fixture_test.go b/android/fixture_test.go
index a31ef16..0042e5b 100644
--- a/android/fixture_test.go
+++ b/android/fixture_test.go
@@ -30,9 +30,10 @@
preparer1 := appendToList("preparer1")
preparer2 := appendToList("preparer2")
preparer3 := appendToList("preparer3")
- preparer4 := appendToList("preparer4")
+ preparer4 := OptionalFixturePreparer(appendToList("preparer4"))
+ nilPreparer := OptionalFixturePreparer(nil)
- preparer1Then2 := GroupFixturePreparers(preparer1, preparer2)
+ preparer1Then2 := GroupFixturePreparers(preparer1, preparer2, nilPreparer)
preparer2Then1 := GroupFixturePreparers(preparer2, preparer1)