blob: 928967d8cd79ac69ea6f97e406f535128da047e6 [file] [log] [blame]
Paul Duffin35816122021-02-24 01:49:52 +00001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
Paul Duffinbbccfcf2021-03-03 00:44:00 +000018 "fmt"
Paul Duffin35816122021-02-24 01:49:52 +000019 "testing"
20)
21
22// Provides support for creating test fixtures on which tests can be run. Reduces duplication
23// of test setup by allow tests to easily reuse setup code.
24//
25// Fixture
26// =======
27// These determine the environment within which a test can be run. Fixtures are mutable and are
28// created by FixtureFactory instances and mutated by FixturePreparer instances. They are created by
29// first creating a base Fixture (which is essentially empty) and then applying FixturePreparer
30// instances to it to modify the environment.
31//
32// FixtureFactory
33// ==============
34// These are responsible for creating fixtures. Factories are immutable and are intended to be
35// initialized once and reused to create multiple fixtures. Each factory has a list of fixture
36// preparers that prepare a fixture for running a test. Factories can also be used to create other
37// factories by extending them with additional fixture preparers.
38//
39// FixturePreparer
40// ===============
41// These are responsible for modifying a Fixture in preparation for it to run a test. Preparers are
42// intended to be immutable and able to prepare multiple Fixture objects simultaneously without
43// them sharing any data.
44//
45// FixturePreparers are only ever invoked once per test fixture. Prior to invocation the list of
46// FixturePreparers are flattened and deduped while preserving the order they first appear in the
47// list. This makes it easy to reuse, group and combine FixturePreparers together.
48//
49// Each small self contained piece of test setup should be their own FixturePreparer. e.g.
50// * A group of related modules.
51// * A group of related mutators.
52// * A combination of both.
53// * Configuration.
54//
55// They should not overlap, e.g. the same module type should not be registered by different
56// FixturePreparers as using them both would cause a build error. In that case the preparer should
57// be split into separate parts and combined together using FixturePreparers(...).
58//
59// e.g. attempting to use AllPreparers in preparing a Fixture would break as it would attempt to
60// register module bar twice:
61// var Preparer1 = FixtureRegisterWithContext(RegisterModuleFooAndBar)
62// var Preparer2 = FixtureRegisterWithContext(RegisterModuleBarAndBaz)
Paul Duffina560d5a2021-02-28 01:38:51 +000063// var AllPreparers = GroupFixturePreparers(Preparer1, Preparer2)
Paul Duffin35816122021-02-24 01:49:52 +000064//
65// However, when restructured like this it would work fine:
66// var PreparerFoo = FixtureRegisterWithContext(RegisterModuleFoo)
67// var PreparerBar = FixtureRegisterWithContext(RegisterModuleBar)
68// var PreparerBaz = FixtureRegisterWithContext(RegisterModuleBaz)
Paul Duffina560d5a2021-02-28 01:38:51 +000069// var Preparer1 = GroupFixturePreparers(RegisterModuleFoo, RegisterModuleBar)
70// var Preparer2 = GroupFixturePreparers(RegisterModuleBar, RegisterModuleBaz)
71// var AllPreparers = GroupFixturePreparers(Preparer1, Preparer2)
Paul Duffin35816122021-02-24 01:49:52 +000072//
73// As after deduping and flattening AllPreparers would result in the following preparers being
74// applied:
75// 1. PreparerFoo
76// 2. PreparerBar
77// 3. PreparerBaz
78//
79// Preparers can be used for both integration and unit tests.
80//
81// Integration tests typically use all the module types, mutators and singletons that are available
82// for that package to try and replicate the behavior of the runtime build as closely as possible.
83// However, that realism comes at a cost of increased fragility (as they can be broken by changes in
84// many different parts of the build) and also increased runtime, especially if they use lots of
85// singletons and mutators.
86//
87// Unit tests on the other hand try and minimize the amount of code being tested which makes them
88// less susceptible to changes elsewhere in the build and quick to run but at a cost of potentially
89// not testing realistic scenarios.
90//
91// Supporting unit tests effectively require that preparers are available at the lowest granularity
92// possible. Supporting integration tests effectively require that the preparers are organized into
93// groups that provide all the functionality available.
94//
95// At least in terms of tests that check the behavior of build components via processing
96// `Android.bp` there is no clear separation between a unit test and an integration test. Instead
97// they vary from one end that tests a single module (e.g. filegroup) to the other end that tests a
98// whole system of modules, mutators and singletons (e.g. apex + hiddenapi).
99//
100// TestResult
101// ==========
102// These are created by running tests in a Fixture and provide access to the Config and TestContext
103// in which the tests were run.
104//
105// Example
106// =======
107//
108// An exported preparer for use by other packages that need to use java modules.
109//
110// package java
Paul Duffina560d5a2021-02-28 01:38:51 +0000111// var PrepareForIntegrationTestWithJava = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +0000112// android.PrepareForIntegrationTestWithAndroid,
113// FixtureRegisterWithContext(RegisterAGroupOfRelatedModulesMutatorsAndSingletons),
114// FixtureRegisterWithContext(RegisterAnotherGroupOfRelatedModulesMutatorsAndSingletons),
115// ...
116// )
117//
118// Some files to use in tests in the java package.
119//
120// var javaMockFS = android.MockFS{
121// "api/current.txt": nil,
122// "api/removed.txt": nil,
123// ...
124// }
125//
126// A package private factory for use for testing java within the java package.
127//
128// var javaFixtureFactory = NewFixtureFactory(
129// PrepareForIntegrationTestWithJava,
130// FixtureRegisterWithContext(func(ctx android.RegistrationContext) {
131// ctx.RegisterModuleType("test_module", testModule)
132// }),
133// javaMockFS.AddToFixture(),
134// ...
135// }
136//
137// func TestJavaStuff(t *testing.T) {
138// result := javaFixtureFactory.RunTest(t,
139// android.FixtureWithRootAndroidBp(`java_library {....}`),
140// android.MockFS{...}.AddToFixture(),
141// )
142// ... test result ...
143// }
144//
145// package cc
Paul Duffina560d5a2021-02-28 01:38:51 +0000146// var PrepareForTestWithCC = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +0000147// android.PrepareForArchMutator,
148// android.prepareForPrebuilts,
149// FixtureRegisterWithContext(RegisterRequiredBuildComponentsForTest),
150// ...
151// )
152//
153// package apex
154//
Paul Duffina560d5a2021-02-28 01:38:51 +0000155// var PrepareForApex = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +0000156// ...
157// )
158//
159// Use modules and mutators from java, cc and apex. Any duplicate preparers (like
160// android.PrepareForArchMutator) will be automatically deduped.
161//
162// var apexFixtureFactory = android.NewFixtureFactory(
163// PrepareForJava,
164// PrepareForCC,
165// PrepareForApex,
166// )
167
168// Factory for Fixture objects.
169//
170// This is configured with a set of FixturePreparer objects that are used to
171// initialize each Fixture instance this creates.
172type FixtureFactory interface {
173
174 // Creates a copy of this instance and adds some additional preparers.
175 //
176 // Before the preparers are used they are combined with the preparers provided when the factory
177 // was created, any groups of preparers are flattened, and the list is deduped so that each
178 // preparer is only used once. See the file documentation in android/fixture.go for more details.
179 Extend(preparers ...FixturePreparer) FixtureFactory
180
181 // Create a Fixture.
182 Fixture(t *testing.T, preparers ...FixturePreparer) Fixture
183
Paul Duffin46e37742021-03-09 11:55:20 +0000184 // ExtendWithErrorHandler creates a new FixtureFactory that will use the supplied error handler
185 // to check the errors (may be 0) reported by the test.
Paul Duffincfd33742021-02-27 11:59:02 +0000186 //
187 // The default handlers is FixtureExpectsNoErrors which will fail the go test immediately if any
188 // errors are reported.
Paul Duffin46e37742021-03-09 11:55:20 +0000189 ExtendWithErrorHandler(errorHandler FixtureErrorHandler) FixtureFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000190
191 // Run the test, checking any errors reported and returning a TestResult instance.
Paul Duffin35816122021-02-24 01:49:52 +0000192 //
193 // Shorthand for Fixture(t, preparers...).RunTest()
194 RunTest(t *testing.T, preparers ...FixturePreparer) *TestResult
195
196 // Run the test with the supplied Android.bp file.
197 //
198 // Shorthand for RunTest(t, android.FixtureWithRootAndroidBp(bp))
199 RunTestWithBp(t *testing.T, bp string) *TestResult
Paul Duffin72018ad2021-03-04 19:36:49 +0000200
201 // RunTestWithConfig is a temporary method added to help ease the migration of existing tests to
202 // the test fixture.
203 //
204 // In order to allow the Config object to be customized separately to the TestContext a lot of
205 // existing test code has `test...WithConfig` funcs that allow the Config object to be supplied
206 // from the test and then have the TestContext created and configured automatically. e.g.
207 // testCcWithConfig, testCcErrorWithConfig, testJavaWithConfig, etc.
208 //
209 // This method allows those methods to be migrated to use the test fixture pattern without
210 // requiring that every test that uses those methods be migrated at the same time. That allows
211 // those tests to benefit from correctness in the order of registration quickly.
212 //
213 // This method discards the config (along with its mock file system, product variables,
214 // environment, etc.) that may have been set up by FixturePreparers.
215 //
216 // deprecated
217 RunTestWithConfig(t *testing.T, config Config) *TestResult
Paul Duffin35816122021-02-24 01:49:52 +0000218}
219
220// Create a new FixtureFactory that will apply the supplied preparers.
221//
222// The buildDirSupplier is a pointer to the package level buildDir variable that is initialized by
223// the package level setUp method. It has to be a pointer to the variable as the variable will not
Paul Duffindff5ff02021-03-15 15:42:40 +0000224// have been initialized at the time the factory is created. If it is nil then a test specific
225// temporary directory will be created instead.
Paul Duffin35816122021-02-24 01:49:52 +0000226func NewFixtureFactory(buildDirSupplier *string, preparers ...FixturePreparer) FixtureFactory {
227 return &fixtureFactory{
228 buildDirSupplier: buildDirSupplier,
229 preparers: dedupAndFlattenPreparers(nil, preparers),
Paul Duffincfd33742021-02-27 11:59:02 +0000230
231 // Set the default error handler.
232 errorHandler: FixtureExpectsNoErrors,
Paul Duffin35816122021-02-24 01:49:52 +0000233 }
234}
235
236// A set of mock files to add to the mock file system.
237type MockFS map[string][]byte
238
Paul Duffin6e9a4002021-03-11 19:01:26 +0000239// Merge adds the extra entries from the supplied map to this one.
240//
241// Fails if the supplied map files with the same paths are present in both of them.
Paul Duffin35816122021-02-24 01:49:52 +0000242func (fs MockFS) Merge(extra map[string][]byte) {
243 for p, c := range extra {
Paul Duffin6e9a4002021-03-11 19:01:26 +0000244 if _, ok := fs[p]; ok {
245 panic(fmt.Errorf("attempted to add file %s to the mock filesystem but it already exists", p))
246 }
Paul Duffin35816122021-02-24 01:49:52 +0000247 fs[p] = c
248 }
249}
250
251func (fs MockFS) AddToFixture() FixturePreparer {
252 return FixtureMergeMockFs(fs)
253}
254
255// Modify the config
256func FixtureModifyConfig(mutator func(config Config)) FixturePreparer {
257 return newSimpleFixturePreparer(func(f *fixture) {
258 mutator(f.config)
259 })
260}
261
262// Modify the config and context
263func FixtureModifyConfigAndContext(mutator func(config Config, ctx *TestContext)) FixturePreparer {
264 return newSimpleFixturePreparer(func(f *fixture) {
265 mutator(f.config, f.ctx)
266 })
267}
268
269// Modify the context
270func FixtureModifyContext(mutator func(ctx *TestContext)) FixturePreparer {
271 return newSimpleFixturePreparer(func(f *fixture) {
272 mutator(f.ctx)
273 })
274}
275
276func FixtureRegisterWithContext(registeringFunc func(ctx RegistrationContext)) FixturePreparer {
277 return FixtureModifyContext(func(ctx *TestContext) { registeringFunc(ctx) })
278}
279
280// Modify the mock filesystem
281func FixtureModifyMockFS(mutator func(fs MockFS)) FixturePreparer {
282 return newSimpleFixturePreparer(func(f *fixture) {
283 mutator(f.mockFS)
284 })
285}
286
287// Merge the supplied file system into the mock filesystem.
288//
289// Paths that already exist in the mock file system are overridden.
290func FixtureMergeMockFs(mockFS MockFS) FixturePreparer {
291 return FixtureModifyMockFS(func(fs MockFS) {
292 fs.Merge(mockFS)
293 })
294}
295
296// Add a file to the mock filesystem
Paul Duffin6e9a4002021-03-11 19:01:26 +0000297//
298// Fail if the filesystem already contains a file with that path, use FixtureOverrideFile instead.
Paul Duffin35816122021-02-24 01:49:52 +0000299func FixtureAddFile(path string, contents []byte) FixturePreparer {
300 return FixtureModifyMockFS(func(fs MockFS) {
Paul Duffin6e9a4002021-03-11 19:01:26 +0000301 if _, ok := fs[path]; ok {
302 panic(fmt.Errorf("attempted to add file %s to the mock filesystem but it already exists, use FixtureOverride*File instead", path))
303 }
Paul Duffin35816122021-02-24 01:49:52 +0000304 fs[path] = contents
305 })
306}
307
308// Add a text file to the mock filesystem
Paul Duffin6e9a4002021-03-11 19:01:26 +0000309//
310// Fail if the filesystem already contains a file with that path.
Paul Duffin35816122021-02-24 01:49:52 +0000311func FixtureAddTextFile(path string, contents string) FixturePreparer {
312 return FixtureAddFile(path, []byte(contents))
313}
314
Paul Duffin6e9a4002021-03-11 19:01:26 +0000315// Override a file in the mock filesystem
316//
317// If the file does not exist this behaves as FixtureAddFile.
318func FixtureOverrideFile(path string, contents []byte) FixturePreparer {
319 return FixtureModifyMockFS(func(fs MockFS) {
320 fs[path] = contents
321 })
322}
323
324// Override a text file in the mock filesystem
325//
326// If the file does not exist this behaves as FixtureAddTextFile.
327func FixtureOverrideTextFile(path string, contents string) FixturePreparer {
328 return FixtureOverrideFile(path, []byte(contents))
329}
330
Paul Duffin35816122021-02-24 01:49:52 +0000331// Add the root Android.bp file with the supplied contents.
332func FixtureWithRootAndroidBp(contents string) FixturePreparer {
333 return FixtureAddTextFile("Android.bp", contents)
334}
335
Paul Duffinbbccfcf2021-03-03 00:44:00 +0000336// Merge some environment variables into the fixture.
337func FixtureMergeEnv(env map[string]string) FixturePreparer {
338 return FixtureModifyConfig(func(config Config) {
339 for k, v := range env {
340 if k == "PATH" {
341 panic("Cannot set PATH environment variable")
342 }
343 config.env[k] = v
344 }
345 })
346}
347
348// Modify the env.
349//
350// Will panic if the mutator changes the PATH environment variable.
351func FixtureModifyEnv(mutator func(env map[string]string)) FixturePreparer {
352 return FixtureModifyConfig(func(config Config) {
353 oldPath := config.env["PATH"]
354 mutator(config.env)
355 newPath := config.env["PATH"]
356 if newPath != oldPath {
357 panic(fmt.Errorf("Cannot change PATH environment variable from %q to %q", oldPath, newPath))
358 }
359 })
360}
361
Paul Duffin2e0323d2021-03-04 15:11:01 +0000362// Allow access to the product variables when preparing the fixture.
363type FixtureProductVariables struct {
364 *productVariables
365}
366
367// Modify product variables.
368func FixtureModifyProductVariables(mutator func(variables FixtureProductVariables)) FixturePreparer {
369 return FixtureModifyConfig(func(config Config) {
370 productVariables := FixtureProductVariables{&config.productVariables}
371 mutator(productVariables)
372 })
373}
374
Paul Duffina560d5a2021-02-28 01:38:51 +0000375// GroupFixturePreparers creates a composite FixturePreparer that is equivalent to applying each of
376// the supplied FixturePreparer instances in order.
377//
378// Before preparing the fixture the list of preparers is flattened by replacing each
379// instance of GroupFixturePreparers with its contents.
380func GroupFixturePreparers(preparers ...FixturePreparer) FixturePreparer {
Paul Duffin35816122021-02-24 01:49:52 +0000381 return &compositeFixturePreparer{dedupAndFlattenPreparers(nil, preparers)}
382}
383
384type simpleFixturePreparerVisitor func(preparer *simpleFixturePreparer)
385
386// FixturePreparer is an opaque interface that can change a fixture.
387type FixturePreparer interface {
388 // visit calls the supplied visitor with each *simpleFixturePreparer instances in this preparer,
389 visit(simpleFixturePreparerVisitor)
390}
391
392type fixturePreparers []FixturePreparer
393
394func (f fixturePreparers) visit(visitor simpleFixturePreparerVisitor) {
395 for _, p := range f {
396 p.visit(visitor)
397 }
398}
399
400// dedupAndFlattenPreparers removes any duplicates and flattens any composite FixturePreparer
401// instances.
402//
403// base - a list of already flattened and deduped preparers that will be applied first before
404// the list of additional preparers. Any duplicates of these in the additional preparers
405// will be ignored.
406//
407// preparers - a list of additional unflattened, undeduped preparers that will be applied after the
408// base preparers.
409//
410// Returns a deduped and flattened list of the preparers minus any that exist in the base preparers.
411func dedupAndFlattenPreparers(base []*simpleFixturePreparer, preparers fixturePreparers) []*simpleFixturePreparer {
412 var list []*simpleFixturePreparer
413 visited := make(map[*simpleFixturePreparer]struct{})
414
415 // Mark the already flattened and deduped preparers, if any, as having been seen so that
416 // duplicates of these in the additional preparers will be discarded.
417 for _, s := range base {
418 visited[s] = struct{}{}
419 }
420
421 preparers.visit(func(preparer *simpleFixturePreparer) {
422 if _, seen := visited[preparer]; !seen {
423 visited[preparer] = struct{}{}
424 list = append(list, preparer)
425 }
426 })
427 return list
428}
429
430// compositeFixturePreparer is a FixturePreparer created from a list of fixture preparers.
431type compositeFixturePreparer struct {
432 preparers []*simpleFixturePreparer
433}
434
435func (c *compositeFixturePreparer) visit(visitor simpleFixturePreparerVisitor) {
436 for _, p := range c.preparers {
437 p.visit(visitor)
438 }
439}
440
441// simpleFixturePreparer is a FixturePreparer that applies a function to a fixture.
442type simpleFixturePreparer struct {
443 function func(fixture *fixture)
444}
445
446func (s *simpleFixturePreparer) visit(visitor simpleFixturePreparerVisitor) {
447 visitor(s)
448}
449
450func newSimpleFixturePreparer(preparer func(fixture *fixture)) FixturePreparer {
451 return &simpleFixturePreparer{function: preparer}
452}
453
Paul Duffincfd33742021-02-27 11:59:02 +0000454// FixtureErrorHandler determines how to respond to errors reported by the code under test.
455//
456// Some possible responses:
457// * Fail the test if any errors are reported, see FixtureExpectsNoErrors.
458// * Fail the test if at least one error that matches a pattern is not reported see
459// FixtureExpectsAtLeastOneErrorMatchingPattern
460// * Fail the test if any unexpected errors are reported.
461//
462// Although at the moment all the error handlers are implemented as simply a wrapper around a
463// function this is defined as an interface to allow future enhancements, e.g. provide different
464// ways other than patterns to match an error and to combine handlers together.
465type FixtureErrorHandler interface {
466 // CheckErrors checks the errors reported.
467 //
468 // The supplied result can be used to access the state of the code under test just as the main
469 // body of the test would but if any errors other than ones expected are reported the state may
470 // be indeterminate.
Paul Duffinc81854a2021-03-12 12:22:27 +0000471 CheckErrors(t *testing.T, result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000472}
473
474type simpleErrorHandler struct {
Paul Duffinc81854a2021-03-12 12:22:27 +0000475 function func(t *testing.T, result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000476}
477
Paul Duffinc81854a2021-03-12 12:22:27 +0000478func (h simpleErrorHandler) CheckErrors(t *testing.T, result *TestResult) {
479 t.Helper()
480 h.function(t, result)
Paul Duffincfd33742021-02-27 11:59:02 +0000481}
482
483// The default fixture error handler.
484//
485// Will fail the test immediately if any errors are reported.
Paul Duffinea8a3862021-03-04 17:58:33 +0000486//
487// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
488// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000489var FixtureExpectsNoErrors = FixtureCustomErrorHandler(
Paul Duffinc81854a2021-03-12 12:22:27 +0000490 func(t *testing.T, result *TestResult) {
491 t.Helper()
492 FailIfErrored(t, result.Errs)
Paul Duffincfd33742021-02-27 11:59:02 +0000493 },
494)
495
496// FixtureExpectsAtLeastOneMatchingError returns an error handler that will cause the test to fail
497// if at least one error that matches the regular expression is not found.
498//
499// The test will be failed if:
500// * No errors are reported.
501// * One or more errors are reported but none match the pattern.
502//
503// The test will not fail if:
504// * Multiple errors are reported that do not match the pattern as long as one does match.
Paul Duffinea8a3862021-03-04 17:58:33 +0000505//
506// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
507// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000508func FixtureExpectsAtLeastOneErrorMatchingPattern(pattern string) FixtureErrorHandler {
Paul Duffinc81854a2021-03-12 12:22:27 +0000509 return FixtureCustomErrorHandler(func(t *testing.T, result *TestResult) {
510 t.Helper()
511 if !FailIfNoMatchingErrors(t, pattern, result.Errs) {
512 t.FailNow()
Paul Duffinea8a3862021-03-04 17:58:33 +0000513 }
Paul Duffincfd33742021-02-27 11:59:02 +0000514 })
515}
516
517// FixtureExpectsOneErrorToMatchPerPattern returns an error handler that will cause the test to fail
518// if there are any unexpected errors.
519//
520// The test will be failed if:
521// * The number of errors reported does not exactly match the patterns.
522// * One or more of the reported errors do not match a pattern.
523// * No patterns are provided and one or more errors are reported.
524//
525// The test will not fail if:
526// * One or more of the patterns does not match an error.
Paul Duffinea8a3862021-03-04 17:58:33 +0000527//
528// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
529// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000530func FixtureExpectsAllErrorsToMatchAPattern(patterns []string) FixtureErrorHandler {
Paul Duffinc81854a2021-03-12 12:22:27 +0000531 return FixtureCustomErrorHandler(func(t *testing.T, result *TestResult) {
532 t.Helper()
533 CheckErrorsAgainstExpectations(t, result.Errs, patterns)
Paul Duffincfd33742021-02-27 11:59:02 +0000534 })
535}
536
537// FixtureCustomErrorHandler creates a custom error handler
Paul Duffinc81854a2021-03-12 12:22:27 +0000538func FixtureCustomErrorHandler(function func(t *testing.T, result *TestResult)) FixtureErrorHandler {
Paul Duffincfd33742021-02-27 11:59:02 +0000539 return simpleErrorHandler{
540 function: function,
541 }
542}
543
Paul Duffin35816122021-02-24 01:49:52 +0000544// Fixture defines the test environment.
545type Fixture interface {
Paul Duffincfd33742021-02-27 11:59:02 +0000546 // Run the test, checking any errors reported and returning a TestResult instance.
Paul Duffin35816122021-02-24 01:49:52 +0000547 RunTest() *TestResult
548}
549
Paul Duffin35816122021-02-24 01:49:52 +0000550// Struct to allow TestResult to embed a *TestContext and allow call forwarding to its methods.
551type testContext struct {
552 *TestContext
553}
554
555// The result of running a test.
556type TestResult struct {
Paul Duffin35816122021-02-24 01:49:52 +0000557 testContext
558
559 fixture *fixture
560 Config Config
Paul Duffin942481b2021-03-04 18:58:11 +0000561
562 // The errors that were reported during the test.
563 Errs []error
Paul Duffin35816122021-02-24 01:49:52 +0000564}
565
566var _ FixtureFactory = (*fixtureFactory)(nil)
567
568type fixtureFactory struct {
569 buildDirSupplier *string
570 preparers []*simpleFixturePreparer
Paul Duffincfd33742021-02-27 11:59:02 +0000571 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000572}
573
574func (f *fixtureFactory) Extend(preparers ...FixturePreparer) FixtureFactory {
Paul Duffinfa298852021-03-08 15:05:24 +0000575 // Create a new slice to avoid accidentally sharing the preparers slice from this factory with
576 // the extending factories.
577 var all []*simpleFixturePreparer
578 all = append(all, f.preparers...)
579 all = append(all, dedupAndFlattenPreparers(f.preparers, preparers)...)
Paul Duffincfd33742021-02-27 11:59:02 +0000580 // Copy the existing factory.
581 extendedFactory := &fixtureFactory{}
582 *extendedFactory = *f
583 // Use the extended list of preparers.
584 extendedFactory.preparers = all
585 return extendedFactory
Paul Duffin35816122021-02-24 01:49:52 +0000586}
587
588func (f *fixtureFactory) Fixture(t *testing.T, preparers ...FixturePreparer) Fixture {
Paul Duffindff5ff02021-03-15 15:42:40 +0000589 var buildDir string
590 if f.buildDirSupplier == nil {
591 // Create a new temporary directory for this run. It will be automatically cleaned up when the
592 // test finishes.
593 buildDir = t.TempDir()
594 } else {
595 // Retrieve the buildDir from the supplier.
596 buildDir = *f.buildDirSupplier
597 }
598 config := TestConfig(buildDir, nil, "", nil)
Paul Duffin35816122021-02-24 01:49:52 +0000599 ctx := NewTestContext(config)
600 fixture := &fixture{
Paul Duffincfd33742021-02-27 11:59:02 +0000601 factory: f,
602 t: t,
603 config: config,
604 ctx: ctx,
605 mockFS: make(MockFS),
606 errorHandler: f.errorHandler,
Paul Duffin35816122021-02-24 01:49:52 +0000607 }
608
609 for _, preparer := range f.preparers {
610 preparer.function(fixture)
611 }
612
613 for _, preparer := range dedupAndFlattenPreparers(f.preparers, preparers) {
614 preparer.function(fixture)
615 }
616
617 return fixture
618}
619
Paul Duffin46e37742021-03-09 11:55:20 +0000620func (f *fixtureFactory) ExtendWithErrorHandler(errorHandler FixtureErrorHandler) FixtureFactory {
Paul Duffin52323b52021-03-04 19:15:47 +0000621 newFactory := &fixtureFactory{}
622 *newFactory = *f
623 newFactory.errorHandler = errorHandler
624 return newFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000625}
626
Paul Duffin35816122021-02-24 01:49:52 +0000627func (f *fixtureFactory) RunTest(t *testing.T, preparers ...FixturePreparer) *TestResult {
628 t.Helper()
629 fixture := f.Fixture(t, preparers...)
630 return fixture.RunTest()
631}
632
633func (f *fixtureFactory) RunTestWithBp(t *testing.T, bp string) *TestResult {
634 t.Helper()
635 return f.RunTest(t, FixtureWithRootAndroidBp(bp))
636}
637
Paul Duffin72018ad2021-03-04 19:36:49 +0000638func (f *fixtureFactory) RunTestWithConfig(t *testing.T, config Config) *TestResult {
639 t.Helper()
640 // Create the fixture as normal.
641 fixture := f.Fixture(t).(*fixture)
642
643 // Discard the mock filesystem as otherwise that will override the one in the config.
644 fixture.mockFS = nil
645
646 // Replace the config with the supplied one in the fixture.
647 fixture.config = config
648
649 // Ditto with config derived information in the TestContext.
650 ctx := fixture.ctx
651 ctx.config = config
652 ctx.SetFs(ctx.config.fs)
653 if ctx.config.mockBpList != "" {
654 ctx.SetModuleListFile(ctx.config.mockBpList)
655 }
656
657 return fixture.RunTest()
658}
659
Paul Duffin35816122021-02-24 01:49:52 +0000660type fixture struct {
Paul Duffincfd33742021-02-27 11:59:02 +0000661 // The factory used to create this fixture.
Paul Duffin35816122021-02-24 01:49:52 +0000662 factory *fixtureFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000663
664 // The gotest state of the go test within which this was created.
665 t *testing.T
666
667 // The configuration prepared for this fixture.
668 config Config
669
670 // The test context prepared for this fixture.
671 ctx *TestContext
672
673 // The mock filesystem prepared for this fixture.
674 mockFS MockFS
675
676 // The error handler used to check the errors, if any, that are reported.
677 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000678}
679
680func (f *fixture) RunTest() *TestResult {
681 f.t.Helper()
682
683 ctx := f.ctx
684
Paul Duffin72018ad2021-03-04 19:36:49 +0000685 // Do not use the fixture's mockFS to initialize the config's mock file system if it has been
686 // cleared by RunTestWithConfig.
687 if f.mockFS != nil {
688 // The TestConfig() method assumes that the mock filesystem is available when creating so
689 // creates the mock file system immediately. Similarly, the NewTestContext(Config) method
690 // assumes that the supplied Config's FileSystem has been properly initialized before it is
691 // called and so it takes its own reference to the filesystem. However, fixtures create the
692 // Config and TestContext early so they can be modified by preparers at which time the mockFS
693 // has not been populated (because it too is modified by preparers). So, this reinitializes the
694 // Config and TestContext's FileSystem using the now populated mockFS.
695 f.config.mockFileSystem("", f.mockFS)
696
697 ctx.SetFs(ctx.config.fs)
698 if ctx.config.mockBpList != "" {
699 ctx.SetModuleListFile(ctx.config.mockBpList)
700 }
Paul Duffin35816122021-02-24 01:49:52 +0000701 }
702
703 ctx.Register()
704 _, errs := ctx.ParseBlueprintsFiles("ignored")
Paul Duffincfd33742021-02-27 11:59:02 +0000705 if len(errs) == 0 {
706 _, errs = ctx.PrepareBuildActions(f.config)
707 }
Paul Duffin35816122021-02-24 01:49:52 +0000708
709 result := &TestResult{
Paul Duffin35816122021-02-24 01:49:52 +0000710 testContext: testContext{ctx},
711 fixture: f,
712 Config: f.config,
Paul Duffin942481b2021-03-04 18:58:11 +0000713 Errs: errs,
Paul Duffin35816122021-02-24 01:49:52 +0000714 }
Paul Duffincfd33742021-02-27 11:59:02 +0000715
Paul Duffinc81854a2021-03-12 12:22:27 +0000716 f.errorHandler.CheckErrors(f.t, result)
Paul Duffincfd33742021-02-27 11:59:02 +0000717
Paul Duffin35816122021-02-24 01:49:52 +0000718 return result
719}
720
721// NormalizePathForTesting removes the test invocation specific build directory from the supplied
722// path.
723//
724// If the path is within the build directory (e.g. an OutputPath) then this returns the relative
725// path to avoid tests having to deal with the dynamically generated build directory.
726//
727// Otherwise, this returns the supplied path as it is almost certainly a source path that is
728// relative to the root of the source tree.
729//
730// Even though some information is removed from some paths and not others it should be possible to
731// differentiate between them by the paths themselves, e.g. output paths will likely include
732// ".intermediates" but source paths won't.
733func (r *TestResult) NormalizePathForTesting(path Path) string {
734 pathContext := PathContextForTesting(r.Config)
735 pathAsString := path.String()
736 if rel, isRel := MaybeRel(pathContext, r.Config.BuildDir(), pathAsString); isRel {
737 return rel
738 }
739 return pathAsString
740}
741
742// NormalizePathsForTesting normalizes each path in the supplied list and returns their normalized
743// forms.
744func (r *TestResult) NormalizePathsForTesting(paths Paths) []string {
745 var result []string
746 for _, path := range paths {
747 result = append(result, r.NormalizePathForTesting(path))
748 }
749 return result
750}
751
Paul Duffin35816122021-02-24 01:49:52 +0000752// Module returns the module with the specific name and of the specified variant.
753func (r *TestResult) Module(name string, variant string) Module {
754 return r.ModuleForTests(name, variant).Module()
755}