blob: edad2c1631f3cfdb5af5937ad47c60992211c12f [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 "reflect"
20 "strings"
21 "testing"
22)
23
24// Provides support for creating test fixtures on which tests can be run. Reduces duplication
25// of test setup by allow tests to easily reuse setup code.
26//
27// Fixture
28// =======
29// These determine the environment within which a test can be run. Fixtures are mutable and are
30// created by FixtureFactory instances and mutated by FixturePreparer instances. They are created by
31// first creating a base Fixture (which is essentially empty) and then applying FixturePreparer
32// instances to it to modify the environment.
33//
34// FixtureFactory
35// ==============
36// These are responsible for creating fixtures. Factories are immutable and are intended to be
37// initialized once and reused to create multiple fixtures. Each factory has a list of fixture
38// preparers that prepare a fixture for running a test. Factories can also be used to create other
39// factories by extending them with additional fixture preparers.
40//
41// FixturePreparer
42// ===============
43// These are responsible for modifying a Fixture in preparation for it to run a test. Preparers are
44// intended to be immutable and able to prepare multiple Fixture objects simultaneously without
45// them sharing any data.
46//
47// FixturePreparers are only ever invoked once per test fixture. Prior to invocation the list of
48// FixturePreparers are flattened and deduped while preserving the order they first appear in the
49// list. This makes it easy to reuse, group and combine FixturePreparers together.
50//
51// Each small self contained piece of test setup should be their own FixturePreparer. e.g.
52// * A group of related modules.
53// * A group of related mutators.
54// * A combination of both.
55// * Configuration.
56//
57// They should not overlap, e.g. the same module type should not be registered by different
58// FixturePreparers as using them both would cause a build error. In that case the preparer should
59// be split into separate parts and combined together using FixturePreparers(...).
60//
61// e.g. attempting to use AllPreparers in preparing a Fixture would break as it would attempt to
62// register module bar twice:
63// var Preparer1 = FixtureRegisterWithContext(RegisterModuleFooAndBar)
64// var Preparer2 = FixtureRegisterWithContext(RegisterModuleBarAndBaz)
Paul Duffina560d5a2021-02-28 01:38:51 +000065// var AllPreparers = GroupFixturePreparers(Preparer1, Preparer2)
Paul Duffin35816122021-02-24 01:49:52 +000066//
67// However, when restructured like this it would work fine:
68// var PreparerFoo = FixtureRegisterWithContext(RegisterModuleFoo)
69// var PreparerBar = FixtureRegisterWithContext(RegisterModuleBar)
70// var PreparerBaz = FixtureRegisterWithContext(RegisterModuleBaz)
Paul Duffina560d5a2021-02-28 01:38:51 +000071// var Preparer1 = GroupFixturePreparers(RegisterModuleFoo, RegisterModuleBar)
72// var Preparer2 = GroupFixturePreparers(RegisterModuleBar, RegisterModuleBaz)
73// var AllPreparers = GroupFixturePreparers(Preparer1, Preparer2)
Paul Duffin35816122021-02-24 01:49:52 +000074//
75// As after deduping and flattening AllPreparers would result in the following preparers being
76// applied:
77// 1. PreparerFoo
78// 2. PreparerBar
79// 3. PreparerBaz
80//
81// Preparers can be used for both integration and unit tests.
82//
83// Integration tests typically use all the module types, mutators and singletons that are available
84// for that package to try and replicate the behavior of the runtime build as closely as possible.
85// However, that realism comes at a cost of increased fragility (as they can be broken by changes in
86// many different parts of the build) and also increased runtime, especially if they use lots of
87// singletons and mutators.
88//
89// Unit tests on the other hand try and minimize the amount of code being tested which makes them
90// less susceptible to changes elsewhere in the build and quick to run but at a cost of potentially
91// not testing realistic scenarios.
92//
93// Supporting unit tests effectively require that preparers are available at the lowest granularity
94// possible. Supporting integration tests effectively require that the preparers are organized into
95// groups that provide all the functionality available.
96//
97// At least in terms of tests that check the behavior of build components via processing
98// `Android.bp` there is no clear separation between a unit test and an integration test. Instead
99// they vary from one end that tests a single module (e.g. filegroup) to the other end that tests a
100// whole system of modules, mutators and singletons (e.g. apex + hiddenapi).
101//
102// TestResult
103// ==========
104// These are created by running tests in a Fixture and provide access to the Config and TestContext
105// in which the tests were run.
106//
107// Example
108// =======
109//
110// An exported preparer for use by other packages that need to use java modules.
111//
112// package java
Paul Duffina560d5a2021-02-28 01:38:51 +0000113// var PrepareForIntegrationTestWithJava = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +0000114// android.PrepareForIntegrationTestWithAndroid,
115// FixtureRegisterWithContext(RegisterAGroupOfRelatedModulesMutatorsAndSingletons),
116// FixtureRegisterWithContext(RegisterAnotherGroupOfRelatedModulesMutatorsAndSingletons),
117// ...
118// )
119//
120// Some files to use in tests in the java package.
121//
122// var javaMockFS = android.MockFS{
123// "api/current.txt": nil,
124// "api/removed.txt": nil,
125// ...
126// }
127//
128// A package private factory for use for testing java within the java package.
129//
130// var javaFixtureFactory = NewFixtureFactory(
131// PrepareForIntegrationTestWithJava,
132// FixtureRegisterWithContext(func(ctx android.RegistrationContext) {
133// ctx.RegisterModuleType("test_module", testModule)
134// }),
135// javaMockFS.AddToFixture(),
136// ...
137// }
138//
139// func TestJavaStuff(t *testing.T) {
140// result := javaFixtureFactory.RunTest(t,
141// android.FixtureWithRootAndroidBp(`java_library {....}`),
142// android.MockFS{...}.AddToFixture(),
143// )
144// ... test result ...
145// }
146//
147// package cc
Paul Duffina560d5a2021-02-28 01:38:51 +0000148// var PrepareForTestWithCC = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +0000149// android.PrepareForArchMutator,
150// android.prepareForPrebuilts,
151// FixtureRegisterWithContext(RegisterRequiredBuildComponentsForTest),
152// ...
153// )
154//
155// package apex
156//
Paul Duffina560d5a2021-02-28 01:38:51 +0000157// var PrepareForApex = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +0000158// ...
159// )
160//
161// Use modules and mutators from java, cc and apex. Any duplicate preparers (like
162// android.PrepareForArchMutator) will be automatically deduped.
163//
164// var apexFixtureFactory = android.NewFixtureFactory(
165// PrepareForJava,
166// PrepareForCC,
167// PrepareForApex,
168// )
169
170// Factory for Fixture objects.
171//
172// This is configured with a set of FixturePreparer objects that are used to
173// initialize each Fixture instance this creates.
174type FixtureFactory interface {
175
176 // Creates a copy of this instance and adds some additional preparers.
177 //
178 // Before the preparers are used they are combined with the preparers provided when the factory
179 // was created, any groups of preparers are flattened, and the list is deduped so that each
180 // preparer is only used once. See the file documentation in android/fixture.go for more details.
181 Extend(preparers ...FixturePreparer) FixtureFactory
182
183 // Create a Fixture.
184 Fixture(t *testing.T, preparers ...FixturePreparer) Fixture
185
Paul Duffin52323b52021-03-04 19:15:47 +0000186 // SetErrorHandler creates a new FixtureFactory that will use the supplied error handler to check
187 // the errors (may be 0) reported by the test.
Paul Duffincfd33742021-02-27 11:59:02 +0000188 //
189 // The default handlers is FixtureExpectsNoErrors which will fail the go test immediately if any
190 // errors are reported.
191 SetErrorHandler(errorHandler FixtureErrorHandler) FixtureFactory
192
193 // Run the test, checking any errors reported and returning a TestResult instance.
Paul Duffin35816122021-02-24 01:49:52 +0000194 //
195 // Shorthand for Fixture(t, preparers...).RunTest()
196 RunTest(t *testing.T, preparers ...FixturePreparer) *TestResult
197
198 // Run the test with the supplied Android.bp file.
199 //
200 // Shorthand for RunTest(t, android.FixtureWithRootAndroidBp(bp))
201 RunTestWithBp(t *testing.T, bp string) *TestResult
202}
203
204// Create a new FixtureFactory that will apply the supplied preparers.
205//
206// The buildDirSupplier is a pointer to the package level buildDir variable that is initialized by
207// the package level setUp method. It has to be a pointer to the variable as the variable will not
208// have been initialized at the time the factory is created.
209func NewFixtureFactory(buildDirSupplier *string, preparers ...FixturePreparer) FixtureFactory {
210 return &fixtureFactory{
211 buildDirSupplier: buildDirSupplier,
212 preparers: dedupAndFlattenPreparers(nil, preparers),
Paul Duffincfd33742021-02-27 11:59:02 +0000213
214 // Set the default error handler.
215 errorHandler: FixtureExpectsNoErrors,
Paul Duffin35816122021-02-24 01:49:52 +0000216 }
217}
218
219// A set of mock files to add to the mock file system.
220type MockFS map[string][]byte
221
222func (fs MockFS) Merge(extra map[string][]byte) {
223 for p, c := range extra {
224 fs[p] = c
225 }
226}
227
228func (fs MockFS) AddToFixture() FixturePreparer {
229 return FixtureMergeMockFs(fs)
230}
231
232// Modify the config
233func FixtureModifyConfig(mutator func(config Config)) FixturePreparer {
234 return newSimpleFixturePreparer(func(f *fixture) {
235 mutator(f.config)
236 })
237}
238
239// Modify the config and context
240func FixtureModifyConfigAndContext(mutator func(config Config, ctx *TestContext)) FixturePreparer {
241 return newSimpleFixturePreparer(func(f *fixture) {
242 mutator(f.config, f.ctx)
243 })
244}
245
246// Modify the context
247func FixtureModifyContext(mutator func(ctx *TestContext)) FixturePreparer {
248 return newSimpleFixturePreparer(func(f *fixture) {
249 mutator(f.ctx)
250 })
251}
252
253func FixtureRegisterWithContext(registeringFunc func(ctx RegistrationContext)) FixturePreparer {
254 return FixtureModifyContext(func(ctx *TestContext) { registeringFunc(ctx) })
255}
256
257// Modify the mock filesystem
258func FixtureModifyMockFS(mutator func(fs MockFS)) FixturePreparer {
259 return newSimpleFixturePreparer(func(f *fixture) {
260 mutator(f.mockFS)
261 })
262}
263
264// Merge the supplied file system into the mock filesystem.
265//
266// Paths that already exist in the mock file system are overridden.
267func FixtureMergeMockFs(mockFS MockFS) FixturePreparer {
268 return FixtureModifyMockFS(func(fs MockFS) {
269 fs.Merge(mockFS)
270 })
271}
272
273// Add a file to the mock filesystem
274func FixtureAddFile(path string, contents []byte) FixturePreparer {
275 return FixtureModifyMockFS(func(fs MockFS) {
276 fs[path] = contents
277 })
278}
279
280// Add a text file to the mock filesystem
281func FixtureAddTextFile(path string, contents string) FixturePreparer {
282 return FixtureAddFile(path, []byte(contents))
283}
284
285// Add the root Android.bp file with the supplied contents.
286func FixtureWithRootAndroidBp(contents string) FixturePreparer {
287 return FixtureAddTextFile("Android.bp", contents)
288}
289
Paul Duffinbbccfcf2021-03-03 00:44:00 +0000290// Merge some environment variables into the fixture.
291func FixtureMergeEnv(env map[string]string) FixturePreparer {
292 return FixtureModifyConfig(func(config Config) {
293 for k, v := range env {
294 if k == "PATH" {
295 panic("Cannot set PATH environment variable")
296 }
297 config.env[k] = v
298 }
299 })
300}
301
302// Modify the env.
303//
304// Will panic if the mutator changes the PATH environment variable.
305func FixtureModifyEnv(mutator func(env map[string]string)) FixturePreparer {
306 return FixtureModifyConfig(func(config Config) {
307 oldPath := config.env["PATH"]
308 mutator(config.env)
309 newPath := config.env["PATH"]
310 if newPath != oldPath {
311 panic(fmt.Errorf("Cannot change PATH environment variable from %q to %q", oldPath, newPath))
312 }
313 })
314}
315
Paul Duffin2e0323d2021-03-04 15:11:01 +0000316// Allow access to the product variables when preparing the fixture.
317type FixtureProductVariables struct {
318 *productVariables
319}
320
321// Modify product variables.
322func FixtureModifyProductVariables(mutator func(variables FixtureProductVariables)) FixturePreparer {
323 return FixtureModifyConfig(func(config Config) {
324 productVariables := FixtureProductVariables{&config.productVariables}
325 mutator(productVariables)
326 })
327}
328
Paul Duffina560d5a2021-02-28 01:38:51 +0000329// GroupFixturePreparers creates a composite FixturePreparer that is equivalent to applying each of
330// the supplied FixturePreparer instances in order.
331//
332// Before preparing the fixture the list of preparers is flattened by replacing each
333// instance of GroupFixturePreparers with its contents.
334func GroupFixturePreparers(preparers ...FixturePreparer) FixturePreparer {
Paul Duffin35816122021-02-24 01:49:52 +0000335 return &compositeFixturePreparer{dedupAndFlattenPreparers(nil, preparers)}
336}
337
338type simpleFixturePreparerVisitor func(preparer *simpleFixturePreparer)
339
340// FixturePreparer is an opaque interface that can change a fixture.
341type FixturePreparer interface {
342 // visit calls the supplied visitor with each *simpleFixturePreparer instances in this preparer,
343 visit(simpleFixturePreparerVisitor)
344}
345
346type fixturePreparers []FixturePreparer
347
348func (f fixturePreparers) visit(visitor simpleFixturePreparerVisitor) {
349 for _, p := range f {
350 p.visit(visitor)
351 }
352}
353
354// dedupAndFlattenPreparers removes any duplicates and flattens any composite FixturePreparer
355// instances.
356//
357// base - a list of already flattened and deduped preparers that will be applied first before
358// the list of additional preparers. Any duplicates of these in the additional preparers
359// will be ignored.
360//
361// preparers - a list of additional unflattened, undeduped preparers that will be applied after the
362// base preparers.
363//
364// Returns a deduped and flattened list of the preparers minus any that exist in the base preparers.
365func dedupAndFlattenPreparers(base []*simpleFixturePreparer, preparers fixturePreparers) []*simpleFixturePreparer {
366 var list []*simpleFixturePreparer
367 visited := make(map[*simpleFixturePreparer]struct{})
368
369 // Mark the already flattened and deduped preparers, if any, as having been seen so that
370 // duplicates of these in the additional preparers will be discarded.
371 for _, s := range base {
372 visited[s] = struct{}{}
373 }
374
375 preparers.visit(func(preparer *simpleFixturePreparer) {
376 if _, seen := visited[preparer]; !seen {
377 visited[preparer] = struct{}{}
378 list = append(list, preparer)
379 }
380 })
381 return list
382}
383
384// compositeFixturePreparer is a FixturePreparer created from a list of fixture preparers.
385type compositeFixturePreparer struct {
386 preparers []*simpleFixturePreparer
387}
388
389func (c *compositeFixturePreparer) visit(visitor simpleFixturePreparerVisitor) {
390 for _, p := range c.preparers {
391 p.visit(visitor)
392 }
393}
394
395// simpleFixturePreparer is a FixturePreparer that applies a function to a fixture.
396type simpleFixturePreparer struct {
397 function func(fixture *fixture)
398}
399
400func (s *simpleFixturePreparer) visit(visitor simpleFixturePreparerVisitor) {
401 visitor(s)
402}
403
404func newSimpleFixturePreparer(preparer func(fixture *fixture)) FixturePreparer {
405 return &simpleFixturePreparer{function: preparer}
406}
407
Paul Duffincfd33742021-02-27 11:59:02 +0000408// FixtureErrorHandler determines how to respond to errors reported by the code under test.
409//
410// Some possible responses:
411// * Fail the test if any errors are reported, see FixtureExpectsNoErrors.
412// * Fail the test if at least one error that matches a pattern is not reported see
413// FixtureExpectsAtLeastOneErrorMatchingPattern
414// * Fail the test if any unexpected errors are reported.
415//
416// Although at the moment all the error handlers are implemented as simply a wrapper around a
417// function this is defined as an interface to allow future enhancements, e.g. provide different
418// ways other than patterns to match an error and to combine handlers together.
419type FixtureErrorHandler interface {
420 // CheckErrors checks the errors reported.
421 //
422 // The supplied result can be used to access the state of the code under test just as the main
423 // body of the test would but if any errors other than ones expected are reported the state may
424 // be indeterminate.
Paul Duffin942481b2021-03-04 18:58:11 +0000425 CheckErrors(result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000426}
427
428type simpleErrorHandler struct {
Paul Duffin942481b2021-03-04 18:58:11 +0000429 function func(result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000430}
431
Paul Duffin942481b2021-03-04 18:58:11 +0000432func (h simpleErrorHandler) CheckErrors(result *TestResult) {
433 result.Helper()
434 h.function(result)
Paul Duffincfd33742021-02-27 11:59:02 +0000435}
436
437// The default fixture error handler.
438//
439// Will fail the test immediately if any errors are reported.
Paul Duffinea8a3862021-03-04 17:58:33 +0000440//
441// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
442// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000443var FixtureExpectsNoErrors = FixtureCustomErrorHandler(
Paul Duffin942481b2021-03-04 18:58:11 +0000444 func(result *TestResult) {
445 result.Helper()
446 FailIfErrored(result.T, result.Errs)
Paul Duffincfd33742021-02-27 11:59:02 +0000447 },
448)
449
450// FixtureExpectsAtLeastOneMatchingError returns an error handler that will cause the test to fail
451// if at least one error that matches the regular expression is not found.
452//
453// The test will be failed if:
454// * No errors are reported.
455// * One or more errors are reported but none match the pattern.
456//
457// The test will not fail if:
458// * Multiple errors are reported that do not match the pattern as long as one does match.
Paul Duffinea8a3862021-03-04 17:58:33 +0000459//
460// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
461// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000462func FixtureExpectsAtLeastOneErrorMatchingPattern(pattern string) FixtureErrorHandler {
Paul Duffin942481b2021-03-04 18:58:11 +0000463 return FixtureCustomErrorHandler(func(result *TestResult) {
464 result.Helper()
465 if !FailIfNoMatchingErrors(result.T, pattern, result.Errs) {
Paul Duffinea8a3862021-03-04 17:58:33 +0000466 result.FailNow()
467 }
Paul Duffincfd33742021-02-27 11:59:02 +0000468 })
469}
470
471// FixtureExpectsOneErrorToMatchPerPattern returns an error handler that will cause the test to fail
472// if there are any unexpected errors.
473//
474// The test will be failed if:
475// * The number of errors reported does not exactly match the patterns.
476// * One or more of the reported errors do not match a pattern.
477// * No patterns are provided and one or more errors are reported.
478//
479// The test will not fail if:
480// * One or more of the patterns does not match an error.
Paul Duffinea8a3862021-03-04 17:58:33 +0000481//
482// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
483// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000484func FixtureExpectsAllErrorsToMatchAPattern(patterns []string) FixtureErrorHandler {
Paul Duffin942481b2021-03-04 18:58:11 +0000485 return FixtureCustomErrorHandler(func(result *TestResult) {
486 result.Helper()
487 CheckErrorsAgainstExpectations(result.T, result.Errs, patterns)
Paul Duffincfd33742021-02-27 11:59:02 +0000488 })
489}
490
491// FixtureCustomErrorHandler creates a custom error handler
Paul Duffin942481b2021-03-04 18:58:11 +0000492func FixtureCustomErrorHandler(function func(result *TestResult)) FixtureErrorHandler {
Paul Duffincfd33742021-02-27 11:59:02 +0000493 return simpleErrorHandler{
494 function: function,
495 }
496}
497
Paul Duffin35816122021-02-24 01:49:52 +0000498// Fixture defines the test environment.
499type Fixture interface {
Paul Duffincfd33742021-02-27 11:59:02 +0000500 // Run the test, checking any errors reported and returning a TestResult instance.
Paul Duffin35816122021-02-24 01:49:52 +0000501 RunTest() *TestResult
502}
503
504// Provides general test support.
505type TestHelper struct {
506 *testing.T
507}
508
509// AssertBoolEquals checks if the expected and actual values are equal and if they are not then it
510// reports an error prefixed with the supplied message and including a reason for why it failed.
511func (h *TestHelper) AssertBoolEquals(message string, expected bool, actual bool) {
512 h.Helper()
513 if actual != expected {
514 h.Errorf("%s: expected %t, actual %t", message, expected, actual)
515 }
516}
517
518// AssertStringEquals checks if the expected and actual values are equal and if they are not then
519// it reports an error prefixed with the supplied message and including a reason for why it failed.
520func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
521 h.Helper()
522 if actual != expected {
523 h.Errorf("%s: expected %s, actual %s", message, expected, actual)
524 }
525}
526
527// AssertTrimmedStringEquals checks if the expected and actual values are the same after trimming
528// leading and trailing spaces from them both. If they are not then it reports an error prefixed
529// with the supplied message and including a reason for why it failed.
530func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
531 h.Helper()
532 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
533}
534
535// AssertStringDoesContain checks if the string contains the expected substring. If it does not
536// then it reports an error prefixed with the supplied message and including a reason for why it
537// failed.
538func (h *TestHelper) AssertStringDoesContain(message string, s string, expectedSubstring string) {
539 h.Helper()
540 if !strings.Contains(s, expectedSubstring) {
541 h.Errorf("%s: could not find %q within %q", message, expectedSubstring, s)
542 }
543}
544
545// AssertStringDoesNotContain checks if the string contains the expected substring. If it does then
546// it reports an error prefixed with the supplied message and including a reason for why it failed.
547func (h *TestHelper) AssertStringDoesNotContain(message string, s string, unexpectedSubstring string) {
548 h.Helper()
549 if strings.Contains(s, unexpectedSubstring) {
550 h.Errorf("%s: unexpectedly found %q within %q", message, unexpectedSubstring, s)
551 }
552}
553
554// AssertArrayString checks if the expected and actual values are equal and if they are not then it
555// reports an error prefixed with the supplied message and including a reason for why it failed.
556func (h *TestHelper) AssertArrayString(message string, expected, actual []string) {
557 h.Helper()
558 if len(actual) != len(expected) {
559 h.Errorf("%s: expected %d (%q), actual (%d) %q", message, len(expected), expected, len(actual), actual)
560 return
561 }
562 for i := range actual {
563 if actual[i] != expected[i] {
564 h.Errorf("%s: expected %d-th, %q (%q), actual %q (%q)",
565 message, i, expected[i], expected, actual[i], actual)
566 return
567 }
568 }
569}
570
571// AssertArrayString checks if the expected and actual values are equal using reflect.DeepEqual and
572// if they are not then it reports an error prefixed with the supplied message and including a
573// reason for why it failed.
574func (h *TestHelper) AssertDeepEquals(message string, expected interface{}, actual interface{}) {
575 h.Helper()
576 if !reflect.DeepEqual(actual, expected) {
577 h.Errorf("%s: expected:\n %#v\n got:\n %#v", message, expected, actual)
578 }
579}
580
581// Struct to allow TestResult to embed a *TestContext and allow call forwarding to its methods.
582type testContext struct {
583 *TestContext
584}
585
586// The result of running a test.
587type TestResult struct {
588 TestHelper
589 testContext
590
591 fixture *fixture
592 Config Config
Paul Duffin942481b2021-03-04 18:58:11 +0000593
594 // The errors that were reported during the test.
595 Errs []error
Paul Duffin35816122021-02-24 01:49:52 +0000596}
597
598var _ FixtureFactory = (*fixtureFactory)(nil)
599
600type fixtureFactory struct {
601 buildDirSupplier *string
602 preparers []*simpleFixturePreparer
Paul Duffincfd33742021-02-27 11:59:02 +0000603 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000604}
605
606func (f *fixtureFactory) Extend(preparers ...FixturePreparer) FixtureFactory {
Paul Duffinfa298852021-03-08 15:05:24 +0000607 // Create a new slice to avoid accidentally sharing the preparers slice from this factory with
608 // the extending factories.
609 var all []*simpleFixturePreparer
610 all = append(all, f.preparers...)
611 all = append(all, dedupAndFlattenPreparers(f.preparers, preparers)...)
Paul Duffincfd33742021-02-27 11:59:02 +0000612 // Copy the existing factory.
613 extendedFactory := &fixtureFactory{}
614 *extendedFactory = *f
615 // Use the extended list of preparers.
616 extendedFactory.preparers = all
617 return extendedFactory
Paul Duffin35816122021-02-24 01:49:52 +0000618}
619
620func (f *fixtureFactory) Fixture(t *testing.T, preparers ...FixturePreparer) Fixture {
621 config := TestConfig(*f.buildDirSupplier, nil, "", nil)
622 ctx := NewTestContext(config)
623 fixture := &fixture{
Paul Duffincfd33742021-02-27 11:59:02 +0000624 factory: f,
625 t: t,
626 config: config,
627 ctx: ctx,
628 mockFS: make(MockFS),
629 errorHandler: f.errorHandler,
Paul Duffin35816122021-02-24 01:49:52 +0000630 }
631
632 for _, preparer := range f.preparers {
633 preparer.function(fixture)
634 }
635
636 for _, preparer := range dedupAndFlattenPreparers(f.preparers, preparers) {
637 preparer.function(fixture)
638 }
639
640 return fixture
641}
642
Paul Duffincfd33742021-02-27 11:59:02 +0000643func (f *fixtureFactory) SetErrorHandler(errorHandler FixtureErrorHandler) FixtureFactory {
Paul Duffin52323b52021-03-04 19:15:47 +0000644 newFactory := &fixtureFactory{}
645 *newFactory = *f
646 newFactory.errorHandler = errorHandler
647 return newFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000648}
649
Paul Duffin35816122021-02-24 01:49:52 +0000650func (f *fixtureFactory) RunTest(t *testing.T, preparers ...FixturePreparer) *TestResult {
651 t.Helper()
652 fixture := f.Fixture(t, preparers...)
653 return fixture.RunTest()
654}
655
656func (f *fixtureFactory) RunTestWithBp(t *testing.T, bp string) *TestResult {
657 t.Helper()
658 return f.RunTest(t, FixtureWithRootAndroidBp(bp))
659}
660
661type fixture struct {
Paul Duffincfd33742021-02-27 11:59:02 +0000662 // The factory used to create this fixture.
Paul Duffin35816122021-02-24 01:49:52 +0000663 factory *fixtureFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000664
665 // The gotest state of the go test within which this was created.
666 t *testing.T
667
668 // The configuration prepared for this fixture.
669 config Config
670
671 // The test context prepared for this fixture.
672 ctx *TestContext
673
674 // The mock filesystem prepared for this fixture.
675 mockFS MockFS
676
677 // The error handler used to check the errors, if any, that are reported.
678 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000679}
680
681func (f *fixture) RunTest() *TestResult {
682 f.t.Helper()
683
684 ctx := f.ctx
685
686 // The TestConfig() method assumes that the mock filesystem is available when creating so creates
687 // the mock file system immediately. Similarly, the NewTestContext(Config) method assumes that the
688 // supplied Config's FileSystem has been properly initialized before it is called and so it takes
689 // its own reference to the filesystem. However, fixtures create the Config and TestContext early
690 // so they can be modified by preparers at which time the mockFS has not been populated (because
691 // it too is modified by preparers). So, this reinitializes the Config and TestContext's
692 // FileSystem using the now populated mockFS.
693 f.config.mockFileSystem("", f.mockFS)
694 ctx.SetFs(ctx.config.fs)
695 if ctx.config.mockBpList != "" {
696 ctx.SetModuleListFile(ctx.config.mockBpList)
697 }
698
699 ctx.Register()
700 _, errs := ctx.ParseBlueprintsFiles("ignored")
Paul Duffincfd33742021-02-27 11:59:02 +0000701 if len(errs) == 0 {
702 _, errs = ctx.PrepareBuildActions(f.config)
703 }
Paul Duffin35816122021-02-24 01:49:52 +0000704
705 result := &TestResult{
706 TestHelper: TestHelper{T: f.t},
707 testContext: testContext{ctx},
708 fixture: f,
709 Config: f.config,
Paul Duffin942481b2021-03-04 18:58:11 +0000710 Errs: errs,
Paul Duffin35816122021-02-24 01:49:52 +0000711 }
Paul Duffincfd33742021-02-27 11:59:02 +0000712
Paul Duffin942481b2021-03-04 18:58:11 +0000713 f.errorHandler.CheckErrors(result)
Paul Duffincfd33742021-02-27 11:59:02 +0000714
Paul Duffin35816122021-02-24 01:49:52 +0000715 return result
716}
717
718// NormalizePathForTesting removes the test invocation specific build directory from the supplied
719// path.
720//
721// If the path is within the build directory (e.g. an OutputPath) then this returns the relative
722// path to avoid tests having to deal with the dynamically generated build directory.
723//
724// Otherwise, this returns the supplied path as it is almost certainly a source path that is
725// relative to the root of the source tree.
726//
727// Even though some information is removed from some paths and not others it should be possible to
728// differentiate between them by the paths themselves, e.g. output paths will likely include
729// ".intermediates" but source paths won't.
730func (r *TestResult) NormalizePathForTesting(path Path) string {
731 pathContext := PathContextForTesting(r.Config)
732 pathAsString := path.String()
733 if rel, isRel := MaybeRel(pathContext, r.Config.BuildDir(), pathAsString); isRel {
734 return rel
735 }
736 return pathAsString
737}
738
739// NormalizePathsForTesting normalizes each path in the supplied list and returns their normalized
740// forms.
741func (r *TestResult) NormalizePathsForTesting(paths Paths) []string {
742 var result []string
743 for _, path := range paths {
744 result = append(result, r.NormalizePathForTesting(path))
745 }
746 return result
747}
748
749// NewFixture creates a new test fixture that is based on the one that created this result. It is
750// intended to test the output of module types that generate content to be processed by the build,
751// e.g. sdk snapshots.
752func (r *TestResult) NewFixture(preparers ...FixturePreparer) Fixture {
753 return r.fixture.factory.Fixture(r.T, preparers...)
754}
755
756// RunTest is shorthand for NewFixture(preparers...).RunTest().
757func (r *TestResult) RunTest(preparers ...FixturePreparer) *TestResult {
758 r.Helper()
759 return r.fixture.factory.Fixture(r.T, preparers...).RunTest()
760}
761
762// Module returns the module with the specific name and of the specified variant.
763func (r *TestResult) Module(name string, variant string) Module {
764 return r.ModuleForTests(name, variant).Module()
765}
766
767// Create a *TestResult object suitable for use within a subtest.
768//
769// This ensures that any errors reported by the TestResult, e.g. from within one of its
770// Assert... methods, will be associated with the sub test and not the main test.
771//
772// result := ....RunTest()
773// t.Run("subtest", func(t *testing.T) {
774// subResult := result.ResultForSubTest(t)
775// subResult.AssertStringEquals("something", ....)
776// })
777func (r *TestResult) ResultForSubTest(t *testing.T) *TestResult {
778 subTestResult := *r
779 r.T = t
780 return &subTestResult
781}