blob: 9d2d92af79ae0ec770eba678e249d5e1ecc66579 [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
224// have been initialized at the time the factory is created.
225func NewFixtureFactory(buildDirSupplier *string, preparers ...FixturePreparer) FixtureFactory {
226 return &fixtureFactory{
227 buildDirSupplier: buildDirSupplier,
228 preparers: dedupAndFlattenPreparers(nil, preparers),
Paul Duffincfd33742021-02-27 11:59:02 +0000229
230 // Set the default error handler.
231 errorHandler: FixtureExpectsNoErrors,
Paul Duffin35816122021-02-24 01:49:52 +0000232 }
233}
234
235// A set of mock files to add to the mock file system.
236type MockFS map[string][]byte
237
Paul Duffin6e9a4002021-03-11 19:01:26 +0000238// Merge adds the extra entries from the supplied map to this one.
239//
240// Fails if the supplied map files with the same paths are present in both of them.
Paul Duffin35816122021-02-24 01:49:52 +0000241func (fs MockFS) Merge(extra map[string][]byte) {
242 for p, c := range extra {
Paul Duffin6e9a4002021-03-11 19:01:26 +0000243 if _, ok := fs[p]; ok {
244 panic(fmt.Errorf("attempted to add file %s to the mock filesystem but it already exists", p))
245 }
Paul Duffin35816122021-02-24 01:49:52 +0000246 fs[p] = c
247 }
248}
249
250func (fs MockFS) AddToFixture() FixturePreparer {
251 return FixtureMergeMockFs(fs)
252}
253
254// Modify the config
255func FixtureModifyConfig(mutator func(config Config)) FixturePreparer {
256 return newSimpleFixturePreparer(func(f *fixture) {
257 mutator(f.config)
258 })
259}
260
261// Modify the config and context
262func FixtureModifyConfigAndContext(mutator func(config Config, ctx *TestContext)) FixturePreparer {
263 return newSimpleFixturePreparer(func(f *fixture) {
264 mutator(f.config, f.ctx)
265 })
266}
267
268// Modify the context
269func FixtureModifyContext(mutator func(ctx *TestContext)) FixturePreparer {
270 return newSimpleFixturePreparer(func(f *fixture) {
271 mutator(f.ctx)
272 })
273}
274
275func FixtureRegisterWithContext(registeringFunc func(ctx RegistrationContext)) FixturePreparer {
276 return FixtureModifyContext(func(ctx *TestContext) { registeringFunc(ctx) })
277}
278
279// Modify the mock filesystem
280func FixtureModifyMockFS(mutator func(fs MockFS)) FixturePreparer {
281 return newSimpleFixturePreparer(func(f *fixture) {
282 mutator(f.mockFS)
283 })
284}
285
286// Merge the supplied file system into the mock filesystem.
287//
288// Paths that already exist in the mock file system are overridden.
289func FixtureMergeMockFs(mockFS MockFS) FixturePreparer {
290 return FixtureModifyMockFS(func(fs MockFS) {
291 fs.Merge(mockFS)
292 })
293}
294
295// Add a file to the mock filesystem
Paul Duffin6e9a4002021-03-11 19:01:26 +0000296//
297// Fail if the filesystem already contains a file with that path, use FixtureOverrideFile instead.
Paul Duffin35816122021-02-24 01:49:52 +0000298func FixtureAddFile(path string, contents []byte) FixturePreparer {
299 return FixtureModifyMockFS(func(fs MockFS) {
Paul Duffin6e9a4002021-03-11 19:01:26 +0000300 if _, ok := fs[path]; ok {
301 panic(fmt.Errorf("attempted to add file %s to the mock filesystem but it already exists, use FixtureOverride*File instead", path))
302 }
Paul Duffin35816122021-02-24 01:49:52 +0000303 fs[path] = contents
304 })
305}
306
307// Add a text file to the mock filesystem
Paul Duffin6e9a4002021-03-11 19:01:26 +0000308//
309// Fail if the filesystem already contains a file with that path.
Paul Duffin35816122021-02-24 01:49:52 +0000310func FixtureAddTextFile(path string, contents string) FixturePreparer {
311 return FixtureAddFile(path, []byte(contents))
312}
313
Paul Duffin6e9a4002021-03-11 19:01:26 +0000314// Override a file in the mock filesystem
315//
316// If the file does not exist this behaves as FixtureAddFile.
317func FixtureOverrideFile(path string, contents []byte) FixturePreparer {
318 return FixtureModifyMockFS(func(fs MockFS) {
319 fs[path] = contents
320 })
321}
322
323// Override a text file in the mock filesystem
324//
325// If the file does not exist this behaves as FixtureAddTextFile.
326func FixtureOverrideTextFile(path string, contents string) FixturePreparer {
327 return FixtureOverrideFile(path, []byte(contents))
328}
329
Paul Duffin35816122021-02-24 01:49:52 +0000330// Add the root Android.bp file with the supplied contents.
331func FixtureWithRootAndroidBp(contents string) FixturePreparer {
332 return FixtureAddTextFile("Android.bp", contents)
333}
334
Paul Duffinbbccfcf2021-03-03 00:44:00 +0000335// Merge some environment variables into the fixture.
336func FixtureMergeEnv(env map[string]string) FixturePreparer {
337 return FixtureModifyConfig(func(config Config) {
338 for k, v := range env {
339 if k == "PATH" {
340 panic("Cannot set PATH environment variable")
341 }
342 config.env[k] = v
343 }
344 })
345}
346
347// Modify the env.
348//
349// Will panic if the mutator changes the PATH environment variable.
350func FixtureModifyEnv(mutator func(env map[string]string)) FixturePreparer {
351 return FixtureModifyConfig(func(config Config) {
352 oldPath := config.env["PATH"]
353 mutator(config.env)
354 newPath := config.env["PATH"]
355 if newPath != oldPath {
356 panic(fmt.Errorf("Cannot change PATH environment variable from %q to %q", oldPath, newPath))
357 }
358 })
359}
360
Paul Duffin2e0323d2021-03-04 15:11:01 +0000361// Allow access to the product variables when preparing the fixture.
362type FixtureProductVariables struct {
363 *productVariables
364}
365
366// Modify product variables.
367func FixtureModifyProductVariables(mutator func(variables FixtureProductVariables)) FixturePreparer {
368 return FixtureModifyConfig(func(config Config) {
369 productVariables := FixtureProductVariables{&config.productVariables}
370 mutator(productVariables)
371 })
372}
373
Paul Duffina560d5a2021-02-28 01:38:51 +0000374// GroupFixturePreparers creates a composite FixturePreparer that is equivalent to applying each of
375// the supplied FixturePreparer instances in order.
376//
377// Before preparing the fixture the list of preparers is flattened by replacing each
378// instance of GroupFixturePreparers with its contents.
379func GroupFixturePreparers(preparers ...FixturePreparer) FixturePreparer {
Paul Duffin35816122021-02-24 01:49:52 +0000380 return &compositeFixturePreparer{dedupAndFlattenPreparers(nil, preparers)}
381}
382
383type simpleFixturePreparerVisitor func(preparer *simpleFixturePreparer)
384
385// FixturePreparer is an opaque interface that can change a fixture.
386type FixturePreparer interface {
387 // visit calls the supplied visitor with each *simpleFixturePreparer instances in this preparer,
388 visit(simpleFixturePreparerVisitor)
389}
390
391type fixturePreparers []FixturePreparer
392
393func (f fixturePreparers) visit(visitor simpleFixturePreparerVisitor) {
394 for _, p := range f {
395 p.visit(visitor)
396 }
397}
398
399// dedupAndFlattenPreparers removes any duplicates and flattens any composite FixturePreparer
400// instances.
401//
402// base - a list of already flattened and deduped preparers that will be applied first before
403// the list of additional preparers. Any duplicates of these in the additional preparers
404// will be ignored.
405//
406// preparers - a list of additional unflattened, undeduped preparers that will be applied after the
407// base preparers.
408//
409// Returns a deduped and flattened list of the preparers minus any that exist in the base preparers.
410func dedupAndFlattenPreparers(base []*simpleFixturePreparer, preparers fixturePreparers) []*simpleFixturePreparer {
411 var list []*simpleFixturePreparer
412 visited := make(map[*simpleFixturePreparer]struct{})
413
414 // Mark the already flattened and deduped preparers, if any, as having been seen so that
415 // duplicates of these in the additional preparers will be discarded.
416 for _, s := range base {
417 visited[s] = struct{}{}
418 }
419
420 preparers.visit(func(preparer *simpleFixturePreparer) {
421 if _, seen := visited[preparer]; !seen {
422 visited[preparer] = struct{}{}
423 list = append(list, preparer)
424 }
425 })
426 return list
427}
428
429// compositeFixturePreparer is a FixturePreparer created from a list of fixture preparers.
430type compositeFixturePreparer struct {
431 preparers []*simpleFixturePreparer
432}
433
434func (c *compositeFixturePreparer) visit(visitor simpleFixturePreparerVisitor) {
435 for _, p := range c.preparers {
436 p.visit(visitor)
437 }
438}
439
440// simpleFixturePreparer is a FixturePreparer that applies a function to a fixture.
441type simpleFixturePreparer struct {
442 function func(fixture *fixture)
443}
444
445func (s *simpleFixturePreparer) visit(visitor simpleFixturePreparerVisitor) {
446 visitor(s)
447}
448
449func newSimpleFixturePreparer(preparer func(fixture *fixture)) FixturePreparer {
450 return &simpleFixturePreparer{function: preparer}
451}
452
Paul Duffincfd33742021-02-27 11:59:02 +0000453// FixtureErrorHandler determines how to respond to errors reported by the code under test.
454//
455// Some possible responses:
456// * Fail the test if any errors are reported, see FixtureExpectsNoErrors.
457// * Fail the test if at least one error that matches a pattern is not reported see
458// FixtureExpectsAtLeastOneErrorMatchingPattern
459// * Fail the test if any unexpected errors are reported.
460//
461// Although at the moment all the error handlers are implemented as simply a wrapper around a
462// function this is defined as an interface to allow future enhancements, e.g. provide different
463// ways other than patterns to match an error and to combine handlers together.
464type FixtureErrorHandler interface {
465 // CheckErrors checks the errors reported.
466 //
467 // The supplied result can be used to access the state of the code under test just as the main
468 // body of the test would but if any errors other than ones expected are reported the state may
469 // be indeterminate.
Paul Duffin942481b2021-03-04 18:58:11 +0000470 CheckErrors(result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000471}
472
473type simpleErrorHandler struct {
Paul Duffin942481b2021-03-04 18:58:11 +0000474 function func(result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000475}
476
Paul Duffin942481b2021-03-04 18:58:11 +0000477func (h simpleErrorHandler) CheckErrors(result *TestResult) {
478 result.Helper()
479 h.function(result)
Paul Duffincfd33742021-02-27 11:59:02 +0000480}
481
482// The default fixture error handler.
483//
484// Will fail the test immediately if any errors are reported.
Paul Duffinea8a3862021-03-04 17:58:33 +0000485//
486// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
487// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000488var FixtureExpectsNoErrors = FixtureCustomErrorHandler(
Paul Duffin942481b2021-03-04 18:58:11 +0000489 func(result *TestResult) {
490 result.Helper()
491 FailIfErrored(result.T, result.Errs)
Paul Duffincfd33742021-02-27 11:59:02 +0000492 },
493)
494
495// FixtureExpectsAtLeastOneMatchingError returns an error handler that will cause the test to fail
496// if at least one error that matches the regular expression is not found.
497//
498// The test will be failed if:
499// * No errors are reported.
500// * One or more errors are reported but none match the pattern.
501//
502// The test will not fail if:
503// * Multiple errors are reported that do not match the pattern as long as one does match.
Paul Duffinea8a3862021-03-04 17:58:33 +0000504//
505// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
506// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000507func FixtureExpectsAtLeastOneErrorMatchingPattern(pattern string) FixtureErrorHandler {
Paul Duffin942481b2021-03-04 18:58:11 +0000508 return FixtureCustomErrorHandler(func(result *TestResult) {
509 result.Helper()
510 if !FailIfNoMatchingErrors(result.T, pattern, result.Errs) {
Paul Duffinea8a3862021-03-04 17:58:33 +0000511 result.FailNow()
512 }
Paul Duffincfd33742021-02-27 11:59:02 +0000513 })
514}
515
516// FixtureExpectsOneErrorToMatchPerPattern returns an error handler that will cause the test to fail
517// if there are any unexpected errors.
518//
519// The test will be failed if:
520// * The number of errors reported does not exactly match the patterns.
521// * One or more of the reported errors do not match a pattern.
522// * No patterns are provided and one or more errors are reported.
523//
524// The test will not fail if:
525// * One or more of the patterns does not match an error.
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 FixtureExpectsAllErrorsToMatchAPattern(patterns []string) FixtureErrorHandler {
Paul Duffin942481b2021-03-04 18:58:11 +0000530 return FixtureCustomErrorHandler(func(result *TestResult) {
531 result.Helper()
532 CheckErrorsAgainstExpectations(result.T, result.Errs, patterns)
Paul Duffincfd33742021-02-27 11:59:02 +0000533 })
534}
535
536// FixtureCustomErrorHandler creates a custom error handler
Paul Duffin942481b2021-03-04 18:58:11 +0000537func FixtureCustomErrorHandler(function func(result *TestResult)) FixtureErrorHandler {
Paul Duffincfd33742021-02-27 11:59:02 +0000538 return simpleErrorHandler{
539 function: function,
540 }
541}
542
Paul Duffin35816122021-02-24 01:49:52 +0000543// Fixture defines the test environment.
544type Fixture interface {
Paul Duffincfd33742021-02-27 11:59:02 +0000545 // Run the test, checking any errors reported and returning a TestResult instance.
Paul Duffin35816122021-02-24 01:49:52 +0000546 RunTest() *TestResult
547}
548
Paul Duffin35816122021-02-24 01:49:52 +0000549// Struct to allow TestResult to embed a *TestContext and allow call forwarding to its methods.
550type testContext struct {
551 *TestContext
552}
553
554// The result of running a test.
555type TestResult struct {
556 TestHelper
557 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 {
589 config := TestConfig(*f.buildDirSupplier, nil, "", nil)
590 ctx := NewTestContext(config)
591 fixture := &fixture{
Paul Duffincfd33742021-02-27 11:59:02 +0000592 factory: f,
593 t: t,
594 config: config,
595 ctx: ctx,
596 mockFS: make(MockFS),
597 errorHandler: f.errorHandler,
Paul Duffin35816122021-02-24 01:49:52 +0000598 }
599
600 for _, preparer := range f.preparers {
601 preparer.function(fixture)
602 }
603
604 for _, preparer := range dedupAndFlattenPreparers(f.preparers, preparers) {
605 preparer.function(fixture)
606 }
607
608 return fixture
609}
610
Paul Duffin46e37742021-03-09 11:55:20 +0000611func (f *fixtureFactory) ExtendWithErrorHandler(errorHandler FixtureErrorHandler) FixtureFactory {
Paul Duffin52323b52021-03-04 19:15:47 +0000612 newFactory := &fixtureFactory{}
613 *newFactory = *f
614 newFactory.errorHandler = errorHandler
615 return newFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000616}
617
Paul Duffin35816122021-02-24 01:49:52 +0000618func (f *fixtureFactory) RunTest(t *testing.T, preparers ...FixturePreparer) *TestResult {
619 t.Helper()
620 fixture := f.Fixture(t, preparers...)
621 return fixture.RunTest()
622}
623
624func (f *fixtureFactory) RunTestWithBp(t *testing.T, bp string) *TestResult {
625 t.Helper()
626 return f.RunTest(t, FixtureWithRootAndroidBp(bp))
627}
628
Paul Duffin72018ad2021-03-04 19:36:49 +0000629func (f *fixtureFactory) RunTestWithConfig(t *testing.T, config Config) *TestResult {
630 t.Helper()
631 // Create the fixture as normal.
632 fixture := f.Fixture(t).(*fixture)
633
634 // Discard the mock filesystem as otherwise that will override the one in the config.
635 fixture.mockFS = nil
636
637 // Replace the config with the supplied one in the fixture.
638 fixture.config = config
639
640 // Ditto with config derived information in the TestContext.
641 ctx := fixture.ctx
642 ctx.config = config
643 ctx.SetFs(ctx.config.fs)
644 if ctx.config.mockBpList != "" {
645 ctx.SetModuleListFile(ctx.config.mockBpList)
646 }
647
648 return fixture.RunTest()
649}
650
Paul Duffin35816122021-02-24 01:49:52 +0000651type fixture struct {
Paul Duffincfd33742021-02-27 11:59:02 +0000652 // The factory used to create this fixture.
Paul Duffin35816122021-02-24 01:49:52 +0000653 factory *fixtureFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000654
655 // The gotest state of the go test within which this was created.
656 t *testing.T
657
658 // The configuration prepared for this fixture.
659 config Config
660
661 // The test context prepared for this fixture.
662 ctx *TestContext
663
664 // The mock filesystem prepared for this fixture.
665 mockFS MockFS
666
667 // The error handler used to check the errors, if any, that are reported.
668 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000669}
670
671func (f *fixture) RunTest() *TestResult {
672 f.t.Helper()
673
674 ctx := f.ctx
675
Paul Duffin72018ad2021-03-04 19:36:49 +0000676 // Do not use the fixture's mockFS to initialize the config's mock file system if it has been
677 // cleared by RunTestWithConfig.
678 if f.mockFS != nil {
679 // The TestConfig() method assumes that the mock filesystem is available when creating so
680 // creates the mock file system immediately. Similarly, the NewTestContext(Config) method
681 // assumes that the supplied Config's FileSystem has been properly initialized before it is
682 // called and so it takes its own reference to the filesystem. However, fixtures create the
683 // Config and TestContext early so they can be modified by preparers at which time the mockFS
684 // has not been populated (because it too is modified by preparers). So, this reinitializes the
685 // Config and TestContext's FileSystem using the now populated mockFS.
686 f.config.mockFileSystem("", f.mockFS)
687
688 ctx.SetFs(ctx.config.fs)
689 if ctx.config.mockBpList != "" {
690 ctx.SetModuleListFile(ctx.config.mockBpList)
691 }
Paul Duffin35816122021-02-24 01:49:52 +0000692 }
693
694 ctx.Register()
695 _, errs := ctx.ParseBlueprintsFiles("ignored")
Paul Duffincfd33742021-02-27 11:59:02 +0000696 if len(errs) == 0 {
697 _, errs = ctx.PrepareBuildActions(f.config)
698 }
Paul Duffin35816122021-02-24 01:49:52 +0000699
700 result := &TestResult{
701 TestHelper: TestHelper{T: f.t},
702 testContext: testContext{ctx},
703 fixture: f,
704 Config: f.config,
Paul Duffin942481b2021-03-04 18:58:11 +0000705 Errs: errs,
Paul Duffin35816122021-02-24 01:49:52 +0000706 }
Paul Duffincfd33742021-02-27 11:59:02 +0000707
Paul Duffin942481b2021-03-04 18:58:11 +0000708 f.errorHandler.CheckErrors(result)
Paul Duffincfd33742021-02-27 11:59:02 +0000709
Paul Duffin35816122021-02-24 01:49:52 +0000710 return result
711}
712
713// NormalizePathForTesting removes the test invocation specific build directory from the supplied
714// path.
715//
716// If the path is within the build directory (e.g. an OutputPath) then this returns the relative
717// path to avoid tests having to deal with the dynamically generated build directory.
718//
719// Otherwise, this returns the supplied path as it is almost certainly a source path that is
720// relative to the root of the source tree.
721//
722// Even though some information is removed from some paths and not others it should be possible to
723// differentiate between them by the paths themselves, e.g. output paths will likely include
724// ".intermediates" but source paths won't.
725func (r *TestResult) NormalizePathForTesting(path Path) string {
726 pathContext := PathContextForTesting(r.Config)
727 pathAsString := path.String()
728 if rel, isRel := MaybeRel(pathContext, r.Config.BuildDir(), pathAsString); isRel {
729 return rel
730 }
731 return pathAsString
732}
733
734// NormalizePathsForTesting normalizes each path in the supplied list and returns their normalized
735// forms.
736func (r *TestResult) NormalizePathsForTesting(paths Paths) []string {
737 var result []string
738 for _, path := range paths {
739 result = append(result, r.NormalizePathForTesting(path))
740 }
741 return result
742}
743
Paul Duffin35816122021-02-24 01:49:52 +0000744// Module returns the module with the specific name and of the specified variant.
745func (r *TestResult) Module(name string, variant string) Module {
746 return r.ModuleForTests(name, variant).Module()
747}