blob: 0bff99593b0f3a7d0a07590aa51192abbce65d39 [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
509// FixtureExpectsAtLeastOneMatchingError returns an error handler that will cause the test to fail
510// if at least one error that matches the regular expression is not found.
511//
512// The test will be failed if:
513// * No errors are reported.
514// * One or more errors are reported but none match the pattern.
515//
516// The test will not fail if:
517// * Multiple errors are reported that do not match the pattern as long as one does match.
Paul Duffinea8a3862021-03-04 17:58:33 +0000518//
519// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
520// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000521func FixtureExpectsAtLeastOneErrorMatchingPattern(pattern string) FixtureErrorHandler {
Paul Duffinc81854a2021-03-12 12:22:27 +0000522 return FixtureCustomErrorHandler(func(t *testing.T, result *TestResult) {
523 t.Helper()
524 if !FailIfNoMatchingErrors(t, pattern, result.Errs) {
525 t.FailNow()
Paul Duffinea8a3862021-03-04 17:58:33 +0000526 }
Paul Duffincfd33742021-02-27 11:59:02 +0000527 })
528}
529
530// FixtureExpectsOneErrorToMatchPerPattern returns an error handler that will cause the test to fail
531// if there are any unexpected errors.
532//
533// The test will be failed if:
534// * The number of errors reported does not exactly match the patterns.
535// * One or more of the reported errors do not match a pattern.
536// * No patterns are provided and one or more errors are reported.
537//
538// The test will not fail if:
539// * One or more of the patterns does not match an error.
Paul Duffinea8a3862021-03-04 17:58:33 +0000540//
541// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
542// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000543func FixtureExpectsAllErrorsToMatchAPattern(patterns []string) FixtureErrorHandler {
Paul Duffinc81854a2021-03-12 12:22:27 +0000544 return FixtureCustomErrorHandler(func(t *testing.T, result *TestResult) {
545 t.Helper()
546 CheckErrorsAgainstExpectations(t, result.Errs, patterns)
Paul Duffincfd33742021-02-27 11:59:02 +0000547 })
548}
549
550// FixtureCustomErrorHandler creates a custom error handler
Paul Duffinc81854a2021-03-12 12:22:27 +0000551func FixtureCustomErrorHandler(function func(t *testing.T, result *TestResult)) FixtureErrorHandler {
Paul Duffincfd33742021-02-27 11:59:02 +0000552 return simpleErrorHandler{
553 function: function,
554 }
555}
556
Paul Duffin35816122021-02-24 01:49:52 +0000557// Fixture defines the test environment.
558type Fixture interface {
Paul Duffincfd33742021-02-27 11:59:02 +0000559 // Run the test, checking any errors reported and returning a TestResult instance.
Paul Duffin35816122021-02-24 01:49:52 +0000560 RunTest() *TestResult
561}
562
Paul Duffin35816122021-02-24 01:49:52 +0000563// Struct to allow TestResult to embed a *TestContext and allow call forwarding to its methods.
564type testContext struct {
565 *TestContext
566}
567
568// The result of running a test.
569type TestResult struct {
Paul Duffin35816122021-02-24 01:49:52 +0000570 testContext
571
572 fixture *fixture
573 Config Config
Paul Duffin942481b2021-03-04 18:58:11 +0000574
575 // The errors that were reported during the test.
576 Errs []error
Paul Duffin35816122021-02-24 01:49:52 +0000577}
578
579var _ FixtureFactory = (*fixtureFactory)(nil)
580
581type fixtureFactory struct {
582 buildDirSupplier *string
583 preparers []*simpleFixturePreparer
Paul Duffincfd33742021-02-27 11:59:02 +0000584 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000585}
586
587func (f *fixtureFactory) Extend(preparers ...FixturePreparer) FixtureFactory {
Paul Duffinfa298852021-03-08 15:05:24 +0000588 // Create a new slice to avoid accidentally sharing the preparers slice from this factory with
589 // the extending factories.
590 var all []*simpleFixturePreparer
591 all = append(all, f.preparers...)
592 all = append(all, dedupAndFlattenPreparers(f.preparers, preparers)...)
Paul Duffincfd33742021-02-27 11:59:02 +0000593 // Copy the existing factory.
594 extendedFactory := &fixtureFactory{}
595 *extendedFactory = *f
596 // Use the extended list of preparers.
597 extendedFactory.preparers = all
598 return extendedFactory
Paul Duffin35816122021-02-24 01:49:52 +0000599}
600
601func (f *fixtureFactory) Fixture(t *testing.T, preparers ...FixturePreparer) Fixture {
Paul Duffindff5ff02021-03-15 15:42:40 +0000602 var buildDir string
603 if f.buildDirSupplier == nil {
604 // Create a new temporary directory for this run. It will be automatically cleaned up when the
605 // test finishes.
606 buildDir = t.TempDir()
607 } else {
608 // Retrieve the buildDir from the supplier.
609 buildDir = *f.buildDirSupplier
610 }
611 config := TestConfig(buildDir, nil, "", nil)
Paul Duffin35816122021-02-24 01:49:52 +0000612 ctx := NewTestContext(config)
613 fixture := &fixture{
Paul Duffincfd33742021-02-27 11:59:02 +0000614 factory: f,
615 t: t,
616 config: config,
617 ctx: ctx,
618 mockFS: make(MockFS),
619 errorHandler: f.errorHandler,
Paul Duffin35816122021-02-24 01:49:52 +0000620 }
621
622 for _, preparer := range f.preparers {
623 preparer.function(fixture)
624 }
625
626 for _, preparer := range dedupAndFlattenPreparers(f.preparers, preparers) {
627 preparer.function(fixture)
628 }
629
630 return fixture
631}
632
Paul Duffin46e37742021-03-09 11:55:20 +0000633func (f *fixtureFactory) ExtendWithErrorHandler(errorHandler FixtureErrorHandler) FixtureFactory {
Paul Duffin52323b52021-03-04 19:15:47 +0000634 newFactory := &fixtureFactory{}
635 *newFactory = *f
636 newFactory.errorHandler = errorHandler
637 return newFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000638}
639
Paul Duffin35816122021-02-24 01:49:52 +0000640func (f *fixtureFactory) RunTest(t *testing.T, preparers ...FixturePreparer) *TestResult {
641 t.Helper()
642 fixture := f.Fixture(t, preparers...)
643 return fixture.RunTest()
644}
645
646func (f *fixtureFactory) RunTestWithBp(t *testing.T, bp string) *TestResult {
647 t.Helper()
648 return f.RunTest(t, FixtureWithRootAndroidBp(bp))
649}
650
Paul Duffin72018ad2021-03-04 19:36:49 +0000651func (f *fixtureFactory) RunTestWithConfig(t *testing.T, config Config) *TestResult {
652 t.Helper()
653 // Create the fixture as normal.
654 fixture := f.Fixture(t).(*fixture)
655
656 // Discard the mock filesystem as otherwise that will override the one in the config.
657 fixture.mockFS = nil
658
659 // Replace the config with the supplied one in the fixture.
660 fixture.config = config
661
662 // Ditto with config derived information in the TestContext.
663 ctx := fixture.ctx
664 ctx.config = config
665 ctx.SetFs(ctx.config.fs)
666 if ctx.config.mockBpList != "" {
667 ctx.SetModuleListFile(ctx.config.mockBpList)
668 }
669
670 return fixture.RunTest()
671}
672
Paul Duffin35816122021-02-24 01:49:52 +0000673type fixture struct {
Paul Duffincfd33742021-02-27 11:59:02 +0000674 // The factory used to create this fixture.
Paul Duffin35816122021-02-24 01:49:52 +0000675 factory *fixtureFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000676
677 // The gotest state of the go test within which this was created.
678 t *testing.T
679
680 // The configuration prepared for this fixture.
681 config Config
682
683 // The test context prepared for this fixture.
684 ctx *TestContext
685
686 // The mock filesystem prepared for this fixture.
687 mockFS MockFS
688
689 // The error handler used to check the errors, if any, that are reported.
690 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000691}
692
693func (f *fixture) RunTest() *TestResult {
694 f.t.Helper()
695
696 ctx := f.ctx
697
Paul Duffin72018ad2021-03-04 19:36:49 +0000698 // Do not use the fixture's mockFS to initialize the config's mock file system if it has been
699 // cleared by RunTestWithConfig.
700 if f.mockFS != nil {
701 // The TestConfig() method assumes that the mock filesystem is available when creating so
702 // creates the mock file system immediately. Similarly, the NewTestContext(Config) method
703 // assumes that the supplied Config's FileSystem has been properly initialized before it is
704 // called and so it takes its own reference to the filesystem. However, fixtures create the
705 // Config and TestContext early so they can be modified by preparers at which time the mockFS
706 // has not been populated (because it too is modified by preparers). So, this reinitializes the
707 // Config and TestContext's FileSystem using the now populated mockFS.
708 f.config.mockFileSystem("", f.mockFS)
709
710 ctx.SetFs(ctx.config.fs)
711 if ctx.config.mockBpList != "" {
712 ctx.SetModuleListFile(ctx.config.mockBpList)
713 }
Paul Duffin35816122021-02-24 01:49:52 +0000714 }
715
716 ctx.Register()
717 _, errs := ctx.ParseBlueprintsFiles("ignored")
Paul Duffincfd33742021-02-27 11:59:02 +0000718 if len(errs) == 0 {
719 _, errs = ctx.PrepareBuildActions(f.config)
720 }
Paul Duffin35816122021-02-24 01:49:52 +0000721
722 result := &TestResult{
Paul Duffin35816122021-02-24 01:49:52 +0000723 testContext: testContext{ctx},
724 fixture: f,
725 Config: f.config,
Paul Duffin942481b2021-03-04 18:58:11 +0000726 Errs: errs,
Paul Duffin35816122021-02-24 01:49:52 +0000727 }
Paul Duffincfd33742021-02-27 11:59:02 +0000728
Paul Duffinc81854a2021-03-12 12:22:27 +0000729 f.errorHandler.CheckErrors(f.t, result)
Paul Duffincfd33742021-02-27 11:59:02 +0000730
Paul Duffin35816122021-02-24 01:49:52 +0000731 return result
732}
733
734// NormalizePathForTesting removes the test invocation specific build directory from the supplied
735// path.
736//
737// If the path is within the build directory (e.g. an OutputPath) then this returns the relative
738// path to avoid tests having to deal with the dynamically generated build directory.
739//
740// Otherwise, this returns the supplied path as it is almost certainly a source path that is
741// relative to the root of the source tree.
742//
743// Even though some information is removed from some paths and not others it should be possible to
744// differentiate between them by the paths themselves, e.g. output paths will likely include
745// ".intermediates" but source paths won't.
746func (r *TestResult) NormalizePathForTesting(path Path) string {
747 pathContext := PathContextForTesting(r.Config)
748 pathAsString := path.String()
749 if rel, isRel := MaybeRel(pathContext, r.Config.BuildDir(), pathAsString); isRel {
750 return rel
751 }
752 return pathAsString
753}
754
755// NormalizePathsForTesting normalizes each path in the supplied list and returns their normalized
756// forms.
757func (r *TestResult) NormalizePathsForTesting(paths Paths) []string {
758 var result []string
759 for _, path := range paths {
760 result = append(result, r.NormalizePathForTesting(path))
761 }
762 return result
763}
764
Paul Duffin35816122021-02-24 01:49:52 +0000765// Module returns the module with the specific name and of the specified variant.
766func (r *TestResult) Module(name string, variant string) Module {
767 return r.ModuleForTests(name, variant).Module()
768}