blob: 6db43e25a579a46012a31f1d99a49f3717aa839f [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
Paul Duffin50deaae2021-03-16 17:46:12 +0000384// NullFixturePreparer is a preparer that does nothing.
385var NullFixturePreparer = GroupFixturePreparers()
386
387// OptionalFixturePreparer will return the supplied preparer if it is non-nil, otherwise it will
388// return the NullFixturePreparer
389func OptionalFixturePreparer(preparer FixturePreparer) FixturePreparer {
390 if preparer == nil {
391 return NullFixturePreparer
392 } else {
393 return preparer
394 }
395}
396
Paul Duffin35816122021-02-24 01:49:52 +0000397type simpleFixturePreparerVisitor func(preparer *simpleFixturePreparer)
398
399// FixturePreparer is an opaque interface that can change a fixture.
400type FixturePreparer interface {
401 // visit calls the supplied visitor with each *simpleFixturePreparer instances in this preparer,
402 visit(simpleFixturePreparerVisitor)
403}
404
405type fixturePreparers []FixturePreparer
406
407func (f fixturePreparers) visit(visitor simpleFixturePreparerVisitor) {
408 for _, p := range f {
409 p.visit(visitor)
410 }
411}
412
413// dedupAndFlattenPreparers removes any duplicates and flattens any composite FixturePreparer
414// instances.
415//
416// base - a list of already flattened and deduped preparers that will be applied first before
417// the list of additional preparers. Any duplicates of these in the additional preparers
418// will be ignored.
419//
420// preparers - a list of additional unflattened, undeduped preparers that will be applied after the
421// base preparers.
422//
423// Returns a deduped and flattened list of the preparers minus any that exist in the base preparers.
424func dedupAndFlattenPreparers(base []*simpleFixturePreparer, preparers fixturePreparers) []*simpleFixturePreparer {
425 var list []*simpleFixturePreparer
426 visited := make(map[*simpleFixturePreparer]struct{})
427
428 // Mark the already flattened and deduped preparers, if any, as having been seen so that
429 // duplicates of these in the additional preparers will be discarded.
430 for _, s := range base {
431 visited[s] = struct{}{}
432 }
433
434 preparers.visit(func(preparer *simpleFixturePreparer) {
435 if _, seen := visited[preparer]; !seen {
436 visited[preparer] = struct{}{}
437 list = append(list, preparer)
438 }
439 })
440 return list
441}
442
443// compositeFixturePreparer is a FixturePreparer created from a list of fixture preparers.
444type compositeFixturePreparer struct {
445 preparers []*simpleFixturePreparer
446}
447
448func (c *compositeFixturePreparer) visit(visitor simpleFixturePreparerVisitor) {
449 for _, p := range c.preparers {
450 p.visit(visitor)
451 }
452}
453
454// simpleFixturePreparer is a FixturePreparer that applies a function to a fixture.
455type simpleFixturePreparer struct {
456 function func(fixture *fixture)
457}
458
459func (s *simpleFixturePreparer) visit(visitor simpleFixturePreparerVisitor) {
460 visitor(s)
461}
462
463func newSimpleFixturePreparer(preparer func(fixture *fixture)) FixturePreparer {
464 return &simpleFixturePreparer{function: preparer}
465}
466
Paul Duffincfd33742021-02-27 11:59:02 +0000467// FixtureErrorHandler determines how to respond to errors reported by the code under test.
468//
469// Some possible responses:
470// * Fail the test if any errors are reported, see FixtureExpectsNoErrors.
471// * Fail the test if at least one error that matches a pattern is not reported see
472// FixtureExpectsAtLeastOneErrorMatchingPattern
473// * Fail the test if any unexpected errors are reported.
474//
475// Although at the moment all the error handlers are implemented as simply a wrapper around a
476// function this is defined as an interface to allow future enhancements, e.g. provide different
477// ways other than patterns to match an error and to combine handlers together.
478type FixtureErrorHandler interface {
479 // CheckErrors checks the errors reported.
480 //
481 // The supplied result can be used to access the state of the code under test just as the main
482 // body of the test would but if any errors other than ones expected are reported the state may
483 // be indeterminate.
Paul Duffinc81854a2021-03-12 12:22:27 +0000484 CheckErrors(t *testing.T, result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000485}
486
487type simpleErrorHandler struct {
Paul Duffinc81854a2021-03-12 12:22:27 +0000488 function func(t *testing.T, result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000489}
490
Paul Duffinc81854a2021-03-12 12:22:27 +0000491func (h simpleErrorHandler) CheckErrors(t *testing.T, result *TestResult) {
492 t.Helper()
493 h.function(t, result)
Paul Duffincfd33742021-02-27 11:59:02 +0000494}
495
496// The default fixture error handler.
497//
498// Will fail the test immediately if any errors are reported.
Paul Duffinea8a3862021-03-04 17:58:33 +0000499//
500// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
501// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000502var FixtureExpectsNoErrors = FixtureCustomErrorHandler(
Paul Duffinc81854a2021-03-12 12:22:27 +0000503 func(t *testing.T, result *TestResult) {
504 t.Helper()
505 FailIfErrored(t, result.Errs)
Paul Duffincfd33742021-02-27 11:59:02 +0000506 },
507)
508
Paul Duffin85034e92021-03-17 00:20:34 +0000509// FixtureIgnoreErrors ignores any errors.
510//
511// If this is used then it is the responsibility of the test to check the TestResult.Errs does not
512// contain any unexpected errors.
513var FixtureIgnoreErrors = FixtureCustomErrorHandler(func(t *testing.T, result *TestResult) {
514 // Ignore the errors
515})
516
Paul Duffincfd33742021-02-27 11:59:02 +0000517// FixtureExpectsAtLeastOneMatchingError returns an error handler that will cause the test to fail
518// if at least one error that matches the regular expression is not found.
519//
520// The test will be failed if:
521// * No errors are reported.
522// * One or more errors are reported but none match the pattern.
523//
524// The test will not fail if:
525// * Multiple errors are reported that do not match the pattern as long as one does match.
Paul Duffinea8a3862021-03-04 17:58:33 +0000526//
527// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
528// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000529func FixtureExpectsAtLeastOneErrorMatchingPattern(pattern string) FixtureErrorHandler {
Paul Duffinc81854a2021-03-12 12:22:27 +0000530 return FixtureCustomErrorHandler(func(t *testing.T, result *TestResult) {
531 t.Helper()
532 if !FailIfNoMatchingErrors(t, pattern, result.Errs) {
533 t.FailNow()
Paul Duffinea8a3862021-03-04 17:58:33 +0000534 }
Paul Duffincfd33742021-02-27 11:59:02 +0000535 })
536}
537
538// FixtureExpectsOneErrorToMatchPerPattern returns an error handler that will cause the test to fail
539// if there are any unexpected errors.
540//
541// The test will be failed if:
542// * The number of errors reported does not exactly match the patterns.
543// * One or more of the reported errors do not match a pattern.
544// * No patterns are provided and one or more errors are reported.
545//
546// The test will not fail if:
547// * One or more of the patterns does not match an error.
Paul Duffinea8a3862021-03-04 17:58:33 +0000548//
549// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
550// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000551func FixtureExpectsAllErrorsToMatchAPattern(patterns []string) FixtureErrorHandler {
Paul Duffinc81854a2021-03-12 12:22:27 +0000552 return FixtureCustomErrorHandler(func(t *testing.T, result *TestResult) {
553 t.Helper()
554 CheckErrorsAgainstExpectations(t, result.Errs, patterns)
Paul Duffincfd33742021-02-27 11:59:02 +0000555 })
556}
557
558// FixtureCustomErrorHandler creates a custom error handler
Paul Duffinc81854a2021-03-12 12:22:27 +0000559func FixtureCustomErrorHandler(function func(t *testing.T, result *TestResult)) FixtureErrorHandler {
Paul Duffincfd33742021-02-27 11:59:02 +0000560 return simpleErrorHandler{
561 function: function,
562 }
563}
564
Paul Duffin35816122021-02-24 01:49:52 +0000565// Fixture defines the test environment.
566type Fixture interface {
Paul Duffincfd33742021-02-27 11:59:02 +0000567 // Run the test, checking any errors reported and returning a TestResult instance.
Paul Duffin35816122021-02-24 01:49:52 +0000568 RunTest() *TestResult
569}
570
Paul Duffin35816122021-02-24 01:49:52 +0000571// Struct to allow TestResult to embed a *TestContext and allow call forwarding to its methods.
572type testContext struct {
573 *TestContext
574}
575
576// The result of running a test.
577type TestResult struct {
Paul Duffin35816122021-02-24 01:49:52 +0000578 testContext
579
580 fixture *fixture
581 Config Config
Paul Duffin942481b2021-03-04 18:58:11 +0000582
583 // The errors that were reported during the test.
584 Errs []error
Paul Duffin35816122021-02-24 01:49:52 +0000585}
586
587var _ FixtureFactory = (*fixtureFactory)(nil)
588
589type fixtureFactory struct {
590 buildDirSupplier *string
591 preparers []*simpleFixturePreparer
Paul Duffincfd33742021-02-27 11:59:02 +0000592 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000593}
594
595func (f *fixtureFactory) Extend(preparers ...FixturePreparer) FixtureFactory {
Paul Duffinfa298852021-03-08 15:05:24 +0000596 // Create a new slice to avoid accidentally sharing the preparers slice from this factory with
597 // the extending factories.
598 var all []*simpleFixturePreparer
599 all = append(all, f.preparers...)
600 all = append(all, dedupAndFlattenPreparers(f.preparers, preparers)...)
Paul Duffincfd33742021-02-27 11:59:02 +0000601 // Copy the existing factory.
602 extendedFactory := &fixtureFactory{}
603 *extendedFactory = *f
604 // Use the extended list of preparers.
605 extendedFactory.preparers = all
606 return extendedFactory
Paul Duffin35816122021-02-24 01:49:52 +0000607}
608
609func (f *fixtureFactory) Fixture(t *testing.T, preparers ...FixturePreparer) Fixture {
Paul Duffindff5ff02021-03-15 15:42:40 +0000610 var buildDir string
611 if f.buildDirSupplier == nil {
612 // Create a new temporary directory for this run. It will be automatically cleaned up when the
613 // test finishes.
614 buildDir = t.TempDir()
615 } else {
616 // Retrieve the buildDir from the supplier.
617 buildDir = *f.buildDirSupplier
618 }
619 config := TestConfig(buildDir, nil, "", nil)
Paul Duffin35816122021-02-24 01:49:52 +0000620 ctx := NewTestContext(config)
621 fixture := &fixture{
Paul Duffincfd33742021-02-27 11:59:02 +0000622 factory: f,
623 t: t,
624 config: config,
625 ctx: ctx,
626 mockFS: make(MockFS),
627 errorHandler: f.errorHandler,
Paul Duffin35816122021-02-24 01:49:52 +0000628 }
629
630 for _, preparer := range f.preparers {
631 preparer.function(fixture)
632 }
633
634 for _, preparer := range dedupAndFlattenPreparers(f.preparers, preparers) {
635 preparer.function(fixture)
636 }
637
638 return fixture
639}
640
Paul Duffin46e37742021-03-09 11:55:20 +0000641func (f *fixtureFactory) ExtendWithErrorHandler(errorHandler FixtureErrorHandler) FixtureFactory {
Paul Duffin52323b52021-03-04 19:15:47 +0000642 newFactory := &fixtureFactory{}
643 *newFactory = *f
644 newFactory.errorHandler = errorHandler
645 return newFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000646}
647
Paul Duffin35816122021-02-24 01:49:52 +0000648func (f *fixtureFactory) RunTest(t *testing.T, preparers ...FixturePreparer) *TestResult {
649 t.Helper()
650 fixture := f.Fixture(t, preparers...)
651 return fixture.RunTest()
652}
653
654func (f *fixtureFactory) RunTestWithBp(t *testing.T, bp string) *TestResult {
655 t.Helper()
656 return f.RunTest(t, FixtureWithRootAndroidBp(bp))
657}
658
Paul Duffin72018ad2021-03-04 19:36:49 +0000659func (f *fixtureFactory) RunTestWithConfig(t *testing.T, config Config) *TestResult {
660 t.Helper()
661 // Create the fixture as normal.
662 fixture := f.Fixture(t).(*fixture)
663
664 // Discard the mock filesystem as otherwise that will override the one in the config.
665 fixture.mockFS = nil
666
667 // Replace the config with the supplied one in the fixture.
668 fixture.config = config
669
670 // Ditto with config derived information in the TestContext.
671 ctx := fixture.ctx
672 ctx.config = config
673 ctx.SetFs(ctx.config.fs)
674 if ctx.config.mockBpList != "" {
675 ctx.SetModuleListFile(ctx.config.mockBpList)
676 }
677
678 return fixture.RunTest()
679}
680
Paul Duffin35816122021-02-24 01:49:52 +0000681type fixture struct {
Paul Duffincfd33742021-02-27 11:59:02 +0000682 // The factory used to create this fixture.
Paul Duffin35816122021-02-24 01:49:52 +0000683 factory *fixtureFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000684
685 // The gotest state of the go test within which this was created.
686 t *testing.T
687
688 // The configuration prepared for this fixture.
689 config Config
690
691 // The test context prepared for this fixture.
692 ctx *TestContext
693
694 // The mock filesystem prepared for this fixture.
695 mockFS MockFS
696
697 // The error handler used to check the errors, if any, that are reported.
698 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000699}
700
701func (f *fixture) RunTest() *TestResult {
702 f.t.Helper()
703
704 ctx := f.ctx
705
Paul Duffin72018ad2021-03-04 19:36:49 +0000706 // Do not use the fixture's mockFS to initialize the config's mock file system if it has been
707 // cleared by RunTestWithConfig.
708 if f.mockFS != nil {
709 // The TestConfig() method assumes that the mock filesystem is available when creating so
710 // creates the mock file system immediately. Similarly, the NewTestContext(Config) method
711 // assumes that the supplied Config's FileSystem has been properly initialized before it is
712 // called and so it takes its own reference to the filesystem. However, fixtures create the
713 // Config and TestContext early so they can be modified by preparers at which time the mockFS
714 // has not been populated (because it too is modified by preparers). So, this reinitializes the
715 // Config and TestContext's FileSystem using the now populated mockFS.
716 f.config.mockFileSystem("", f.mockFS)
717
718 ctx.SetFs(ctx.config.fs)
719 if ctx.config.mockBpList != "" {
720 ctx.SetModuleListFile(ctx.config.mockBpList)
721 }
Paul Duffin35816122021-02-24 01:49:52 +0000722 }
723
724 ctx.Register()
725 _, errs := ctx.ParseBlueprintsFiles("ignored")
Paul Duffincfd33742021-02-27 11:59:02 +0000726 if len(errs) == 0 {
727 _, errs = ctx.PrepareBuildActions(f.config)
728 }
Paul Duffin35816122021-02-24 01:49:52 +0000729
730 result := &TestResult{
Paul Duffin35816122021-02-24 01:49:52 +0000731 testContext: testContext{ctx},
732 fixture: f,
733 Config: f.config,
Paul Duffin942481b2021-03-04 18:58:11 +0000734 Errs: errs,
Paul Duffin35816122021-02-24 01:49:52 +0000735 }
Paul Duffincfd33742021-02-27 11:59:02 +0000736
Paul Duffinc81854a2021-03-12 12:22:27 +0000737 f.errorHandler.CheckErrors(f.t, result)
Paul Duffincfd33742021-02-27 11:59:02 +0000738
Paul Duffin35816122021-02-24 01:49:52 +0000739 return result
740}
741
742// NormalizePathForTesting removes the test invocation specific build directory from the supplied
743// path.
744//
745// If the path is within the build directory (e.g. an OutputPath) then this returns the relative
746// path to avoid tests having to deal with the dynamically generated build directory.
747//
748// Otherwise, this returns the supplied path as it is almost certainly a source path that is
749// relative to the root of the source tree.
750//
751// Even though some information is removed from some paths and not others it should be possible to
752// differentiate between them by the paths themselves, e.g. output paths will likely include
753// ".intermediates" but source paths won't.
754func (r *TestResult) NormalizePathForTesting(path Path) string {
755 pathContext := PathContextForTesting(r.Config)
756 pathAsString := path.String()
757 if rel, isRel := MaybeRel(pathContext, r.Config.BuildDir(), pathAsString); isRel {
758 return rel
759 }
760 return pathAsString
761}
762
763// NormalizePathsForTesting normalizes each path in the supplied list and returns their normalized
764// forms.
765func (r *TestResult) NormalizePathsForTesting(paths Paths) []string {
766 var result []string
767 for _, path := range paths {
768 result = append(result, r.NormalizePathForTesting(path))
769 }
770 return result
771}
772
Paul Duffin35816122021-02-24 01:49:52 +0000773// Module returns the module with the specific name and of the specified variant.
774func (r *TestResult) Module(name string, variant string) Module {
775 return r.ModuleForTests(name, variant).Module()
776}