blob: 607b5bd39f3905cdc4ec9b624648ccb9f05d14bd [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 Duffina560d5a2021-02-28 01:38:51 +0000316// GroupFixturePreparers creates a composite FixturePreparer that is equivalent to applying each of
317// the supplied FixturePreparer instances in order.
318//
319// Before preparing the fixture the list of preparers is flattened by replacing each
320// instance of GroupFixturePreparers with its contents.
321func GroupFixturePreparers(preparers ...FixturePreparer) FixturePreparer {
Paul Duffin35816122021-02-24 01:49:52 +0000322 return &compositeFixturePreparer{dedupAndFlattenPreparers(nil, preparers)}
323}
324
325type simpleFixturePreparerVisitor func(preparer *simpleFixturePreparer)
326
327// FixturePreparer is an opaque interface that can change a fixture.
328type FixturePreparer interface {
329 // visit calls the supplied visitor with each *simpleFixturePreparer instances in this preparer,
330 visit(simpleFixturePreparerVisitor)
331}
332
333type fixturePreparers []FixturePreparer
334
335func (f fixturePreparers) visit(visitor simpleFixturePreparerVisitor) {
336 for _, p := range f {
337 p.visit(visitor)
338 }
339}
340
341// dedupAndFlattenPreparers removes any duplicates and flattens any composite FixturePreparer
342// instances.
343//
344// base - a list of already flattened and deduped preparers that will be applied first before
345// the list of additional preparers. Any duplicates of these in the additional preparers
346// will be ignored.
347//
348// preparers - a list of additional unflattened, undeduped preparers that will be applied after the
349// base preparers.
350//
351// Returns a deduped and flattened list of the preparers minus any that exist in the base preparers.
352func dedupAndFlattenPreparers(base []*simpleFixturePreparer, preparers fixturePreparers) []*simpleFixturePreparer {
353 var list []*simpleFixturePreparer
354 visited := make(map[*simpleFixturePreparer]struct{})
355
356 // Mark the already flattened and deduped preparers, if any, as having been seen so that
357 // duplicates of these in the additional preparers will be discarded.
358 for _, s := range base {
359 visited[s] = struct{}{}
360 }
361
362 preparers.visit(func(preparer *simpleFixturePreparer) {
363 if _, seen := visited[preparer]; !seen {
364 visited[preparer] = struct{}{}
365 list = append(list, preparer)
366 }
367 })
368 return list
369}
370
371// compositeFixturePreparer is a FixturePreparer created from a list of fixture preparers.
372type compositeFixturePreparer struct {
373 preparers []*simpleFixturePreparer
374}
375
376func (c *compositeFixturePreparer) visit(visitor simpleFixturePreparerVisitor) {
377 for _, p := range c.preparers {
378 p.visit(visitor)
379 }
380}
381
382// simpleFixturePreparer is a FixturePreparer that applies a function to a fixture.
383type simpleFixturePreparer struct {
384 function func(fixture *fixture)
385}
386
387func (s *simpleFixturePreparer) visit(visitor simpleFixturePreparerVisitor) {
388 visitor(s)
389}
390
391func newSimpleFixturePreparer(preparer func(fixture *fixture)) FixturePreparer {
392 return &simpleFixturePreparer{function: preparer}
393}
394
Paul Duffincfd33742021-02-27 11:59:02 +0000395// FixtureErrorHandler determines how to respond to errors reported by the code under test.
396//
397// Some possible responses:
398// * Fail the test if any errors are reported, see FixtureExpectsNoErrors.
399// * Fail the test if at least one error that matches a pattern is not reported see
400// FixtureExpectsAtLeastOneErrorMatchingPattern
401// * Fail the test if any unexpected errors are reported.
402//
403// Although at the moment all the error handlers are implemented as simply a wrapper around a
404// function this is defined as an interface to allow future enhancements, e.g. provide different
405// ways other than patterns to match an error and to combine handlers together.
406type FixtureErrorHandler interface {
407 // CheckErrors checks the errors reported.
408 //
409 // The supplied result can be used to access the state of the code under test just as the main
410 // body of the test would but if any errors other than ones expected are reported the state may
411 // be indeterminate.
Paul Duffin942481b2021-03-04 18:58:11 +0000412 CheckErrors(result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000413}
414
415type simpleErrorHandler struct {
Paul Duffin942481b2021-03-04 18:58:11 +0000416 function func(result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000417}
418
Paul Duffin942481b2021-03-04 18:58:11 +0000419func (h simpleErrorHandler) CheckErrors(result *TestResult) {
420 result.Helper()
421 h.function(result)
Paul Duffincfd33742021-02-27 11:59:02 +0000422}
423
424// The default fixture error handler.
425//
426// Will fail the test immediately if any errors are reported.
Paul Duffinea8a3862021-03-04 17:58:33 +0000427//
428// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
429// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000430var FixtureExpectsNoErrors = FixtureCustomErrorHandler(
Paul Duffin942481b2021-03-04 18:58:11 +0000431 func(result *TestResult) {
432 result.Helper()
433 FailIfErrored(result.T, result.Errs)
Paul Duffincfd33742021-02-27 11:59:02 +0000434 },
435)
436
437// FixtureExpectsAtLeastOneMatchingError returns an error handler that will cause the test to fail
438// if at least one error that matches the regular expression is not found.
439//
440// The test will be failed if:
441// * No errors are reported.
442// * One or more errors are reported but none match the pattern.
443//
444// The test will not fail if:
445// * Multiple errors are reported that do not match the pattern as long as one does match.
Paul Duffinea8a3862021-03-04 17:58:33 +0000446//
447// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
448// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000449func FixtureExpectsAtLeastOneErrorMatchingPattern(pattern string) FixtureErrorHandler {
Paul Duffin942481b2021-03-04 18:58:11 +0000450 return FixtureCustomErrorHandler(func(result *TestResult) {
451 result.Helper()
452 if !FailIfNoMatchingErrors(result.T, pattern, result.Errs) {
Paul Duffinea8a3862021-03-04 17:58:33 +0000453 result.FailNow()
454 }
Paul Duffincfd33742021-02-27 11:59:02 +0000455 })
456}
457
458// FixtureExpectsOneErrorToMatchPerPattern returns an error handler that will cause the test to fail
459// if there are any unexpected errors.
460//
461// The test will be failed if:
462// * The number of errors reported does not exactly match the patterns.
463// * One or more of the reported errors do not match a pattern.
464// * No patterns are provided and one or more errors are reported.
465//
466// The test will not fail if:
467// * One or more of the patterns does not match an error.
Paul Duffinea8a3862021-03-04 17:58:33 +0000468//
469// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
470// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000471func FixtureExpectsAllErrorsToMatchAPattern(patterns []string) FixtureErrorHandler {
Paul Duffin942481b2021-03-04 18:58:11 +0000472 return FixtureCustomErrorHandler(func(result *TestResult) {
473 result.Helper()
474 CheckErrorsAgainstExpectations(result.T, result.Errs, patterns)
Paul Duffincfd33742021-02-27 11:59:02 +0000475 })
476}
477
478// FixtureCustomErrorHandler creates a custom error handler
Paul Duffin942481b2021-03-04 18:58:11 +0000479func FixtureCustomErrorHandler(function func(result *TestResult)) FixtureErrorHandler {
Paul Duffincfd33742021-02-27 11:59:02 +0000480 return simpleErrorHandler{
481 function: function,
482 }
483}
484
Paul Duffin35816122021-02-24 01:49:52 +0000485// Fixture defines the test environment.
486type Fixture interface {
Paul Duffincfd33742021-02-27 11:59:02 +0000487 // Run the test, checking any errors reported and returning a TestResult instance.
Paul Duffin35816122021-02-24 01:49:52 +0000488 RunTest() *TestResult
489}
490
491// Provides general test support.
492type TestHelper struct {
493 *testing.T
494}
495
496// AssertBoolEquals checks if the expected and actual values are equal and if they are not then it
497// reports an error prefixed with the supplied message and including a reason for why it failed.
498func (h *TestHelper) AssertBoolEquals(message string, expected bool, actual bool) {
499 h.Helper()
500 if actual != expected {
501 h.Errorf("%s: expected %t, actual %t", message, expected, actual)
502 }
503}
504
505// AssertStringEquals checks if the expected and actual values are equal and if they are not then
506// it reports an error prefixed with the supplied message and including a reason for why it failed.
507func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
508 h.Helper()
509 if actual != expected {
510 h.Errorf("%s: expected %s, actual %s", message, expected, actual)
511 }
512}
513
514// AssertTrimmedStringEquals checks if the expected and actual values are the same after trimming
515// leading and trailing spaces from them both. If they are not then it reports an error prefixed
516// with the supplied message and including a reason for why it failed.
517func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
518 h.Helper()
519 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
520}
521
522// AssertStringDoesContain checks if the string contains the expected substring. If it does not
523// then it reports an error prefixed with the supplied message and including a reason for why it
524// failed.
525func (h *TestHelper) AssertStringDoesContain(message string, s string, expectedSubstring string) {
526 h.Helper()
527 if !strings.Contains(s, expectedSubstring) {
528 h.Errorf("%s: could not find %q within %q", message, expectedSubstring, s)
529 }
530}
531
532// AssertStringDoesNotContain checks if the string contains the expected substring. If it does then
533// it reports an error prefixed with the supplied message and including a reason for why it failed.
534func (h *TestHelper) AssertStringDoesNotContain(message string, s string, unexpectedSubstring string) {
535 h.Helper()
536 if strings.Contains(s, unexpectedSubstring) {
537 h.Errorf("%s: unexpectedly found %q within %q", message, unexpectedSubstring, s)
538 }
539}
540
541// AssertArrayString checks if the expected and actual values are equal and if they are not then it
542// reports an error prefixed with the supplied message and including a reason for why it failed.
543func (h *TestHelper) AssertArrayString(message string, expected, actual []string) {
544 h.Helper()
545 if len(actual) != len(expected) {
546 h.Errorf("%s: expected %d (%q), actual (%d) %q", message, len(expected), expected, len(actual), actual)
547 return
548 }
549 for i := range actual {
550 if actual[i] != expected[i] {
551 h.Errorf("%s: expected %d-th, %q (%q), actual %q (%q)",
552 message, i, expected[i], expected, actual[i], actual)
553 return
554 }
555 }
556}
557
558// AssertArrayString checks if the expected and actual values are equal using reflect.DeepEqual and
559// if they are not then it reports an error prefixed with the supplied message and including a
560// reason for why it failed.
561func (h *TestHelper) AssertDeepEquals(message string, expected interface{}, actual interface{}) {
562 h.Helper()
563 if !reflect.DeepEqual(actual, expected) {
564 h.Errorf("%s: expected:\n %#v\n got:\n %#v", message, expected, actual)
565 }
566}
567
568// Struct to allow TestResult to embed a *TestContext and allow call forwarding to its methods.
569type testContext struct {
570 *TestContext
571}
572
573// The result of running a test.
574type TestResult struct {
575 TestHelper
576 testContext
577
578 fixture *fixture
579 Config Config
Paul Duffin942481b2021-03-04 18:58:11 +0000580
581 // The errors that were reported during the test.
582 Errs []error
Paul Duffin35816122021-02-24 01:49:52 +0000583}
584
585var _ FixtureFactory = (*fixtureFactory)(nil)
586
587type fixtureFactory struct {
588 buildDirSupplier *string
589 preparers []*simpleFixturePreparer
Paul Duffincfd33742021-02-27 11:59:02 +0000590 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000591}
592
593func (f *fixtureFactory) Extend(preparers ...FixturePreparer) FixtureFactory {
Paul Duffinfa298852021-03-08 15:05:24 +0000594 // Create a new slice to avoid accidentally sharing the preparers slice from this factory with
595 // the extending factories.
596 var all []*simpleFixturePreparer
597 all = append(all, f.preparers...)
598 all = append(all, dedupAndFlattenPreparers(f.preparers, preparers)...)
Paul Duffincfd33742021-02-27 11:59:02 +0000599 // Copy the existing factory.
600 extendedFactory := &fixtureFactory{}
601 *extendedFactory = *f
602 // Use the extended list of preparers.
603 extendedFactory.preparers = all
604 return extendedFactory
Paul Duffin35816122021-02-24 01:49:52 +0000605}
606
607func (f *fixtureFactory) Fixture(t *testing.T, preparers ...FixturePreparer) Fixture {
608 config := TestConfig(*f.buildDirSupplier, nil, "", nil)
609 ctx := NewTestContext(config)
610 fixture := &fixture{
Paul Duffincfd33742021-02-27 11:59:02 +0000611 factory: f,
612 t: t,
613 config: config,
614 ctx: ctx,
615 mockFS: make(MockFS),
616 errorHandler: f.errorHandler,
Paul Duffin35816122021-02-24 01:49:52 +0000617 }
618
619 for _, preparer := range f.preparers {
620 preparer.function(fixture)
621 }
622
623 for _, preparer := range dedupAndFlattenPreparers(f.preparers, preparers) {
624 preparer.function(fixture)
625 }
626
627 return fixture
628}
629
Paul Duffincfd33742021-02-27 11:59:02 +0000630func (f *fixtureFactory) SetErrorHandler(errorHandler FixtureErrorHandler) FixtureFactory {
Paul Duffin52323b52021-03-04 19:15:47 +0000631 newFactory := &fixtureFactory{}
632 *newFactory = *f
633 newFactory.errorHandler = errorHandler
634 return newFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000635}
636
Paul Duffin35816122021-02-24 01:49:52 +0000637func (f *fixtureFactory) RunTest(t *testing.T, preparers ...FixturePreparer) *TestResult {
638 t.Helper()
639 fixture := f.Fixture(t, preparers...)
640 return fixture.RunTest()
641}
642
643func (f *fixtureFactory) RunTestWithBp(t *testing.T, bp string) *TestResult {
644 t.Helper()
645 return f.RunTest(t, FixtureWithRootAndroidBp(bp))
646}
647
648type fixture struct {
Paul Duffincfd33742021-02-27 11:59:02 +0000649 // The factory used to create this fixture.
Paul Duffin35816122021-02-24 01:49:52 +0000650 factory *fixtureFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000651
652 // The gotest state of the go test within which this was created.
653 t *testing.T
654
655 // The configuration prepared for this fixture.
656 config Config
657
658 // The test context prepared for this fixture.
659 ctx *TestContext
660
661 // The mock filesystem prepared for this fixture.
662 mockFS MockFS
663
664 // The error handler used to check the errors, if any, that are reported.
665 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000666}
667
668func (f *fixture) RunTest() *TestResult {
669 f.t.Helper()
670
671 ctx := f.ctx
672
673 // The TestConfig() method assumes that the mock filesystem is available when creating so creates
674 // the mock file system immediately. Similarly, the NewTestContext(Config) method assumes that the
675 // supplied Config's FileSystem has been properly initialized before it is called and so it takes
676 // its own reference to the filesystem. However, fixtures create the Config and TestContext early
677 // so they can be modified by preparers at which time the mockFS has not been populated (because
678 // it too is modified by preparers). So, this reinitializes the Config and TestContext's
679 // FileSystem using the now populated mockFS.
680 f.config.mockFileSystem("", f.mockFS)
681 ctx.SetFs(ctx.config.fs)
682 if ctx.config.mockBpList != "" {
683 ctx.SetModuleListFile(ctx.config.mockBpList)
684 }
685
686 ctx.Register()
687 _, errs := ctx.ParseBlueprintsFiles("ignored")
Paul Duffincfd33742021-02-27 11:59:02 +0000688 if len(errs) == 0 {
689 _, errs = ctx.PrepareBuildActions(f.config)
690 }
Paul Duffin35816122021-02-24 01:49:52 +0000691
692 result := &TestResult{
693 TestHelper: TestHelper{T: f.t},
694 testContext: testContext{ctx},
695 fixture: f,
696 Config: f.config,
Paul Duffin942481b2021-03-04 18:58:11 +0000697 Errs: errs,
Paul Duffin35816122021-02-24 01:49:52 +0000698 }
Paul Duffincfd33742021-02-27 11:59:02 +0000699
Paul Duffin942481b2021-03-04 18:58:11 +0000700 f.errorHandler.CheckErrors(result)
Paul Duffincfd33742021-02-27 11:59:02 +0000701
Paul Duffin35816122021-02-24 01:49:52 +0000702 return result
703}
704
705// NormalizePathForTesting removes the test invocation specific build directory from the supplied
706// path.
707//
708// If the path is within the build directory (e.g. an OutputPath) then this returns the relative
709// path to avoid tests having to deal with the dynamically generated build directory.
710//
711// Otherwise, this returns the supplied path as it is almost certainly a source path that is
712// relative to the root of the source tree.
713//
714// Even though some information is removed from some paths and not others it should be possible to
715// differentiate between them by the paths themselves, e.g. output paths will likely include
716// ".intermediates" but source paths won't.
717func (r *TestResult) NormalizePathForTesting(path Path) string {
718 pathContext := PathContextForTesting(r.Config)
719 pathAsString := path.String()
720 if rel, isRel := MaybeRel(pathContext, r.Config.BuildDir(), pathAsString); isRel {
721 return rel
722 }
723 return pathAsString
724}
725
726// NormalizePathsForTesting normalizes each path in the supplied list and returns their normalized
727// forms.
728func (r *TestResult) NormalizePathsForTesting(paths Paths) []string {
729 var result []string
730 for _, path := range paths {
731 result = append(result, r.NormalizePathForTesting(path))
732 }
733 return result
734}
735
736// NewFixture creates a new test fixture that is based on the one that created this result. It is
737// intended to test the output of module types that generate content to be processed by the build,
738// e.g. sdk snapshots.
739func (r *TestResult) NewFixture(preparers ...FixturePreparer) Fixture {
740 return r.fixture.factory.Fixture(r.T, preparers...)
741}
742
743// RunTest is shorthand for NewFixture(preparers...).RunTest().
744func (r *TestResult) RunTest(preparers ...FixturePreparer) *TestResult {
745 r.Helper()
746 return r.fixture.factory.Fixture(r.T, preparers...).RunTest()
747}
748
749// Module returns the module with the specific name and of the specified variant.
750func (r *TestResult) Module(name string, variant string) Module {
751 return r.ModuleForTests(name, variant).Module()
752}
753
754// Create a *TestResult object suitable for use within a subtest.
755//
756// This ensures that any errors reported by the TestResult, e.g. from within one of its
757// Assert... methods, will be associated with the sub test and not the main test.
758//
759// result := ....RunTest()
760// t.Run("subtest", func(t *testing.T) {
761// subResult := result.ResultForSubTest(t)
762// subResult.AssertStringEquals("something", ....)
763// })
764func (r *TestResult) ResultForSubTest(t *testing.T) *TestResult {
765 subTestResult := *r
766 r.T = t
767 return &subTestResult
768}