blob: 552c8f569c916f97d7e9acd0ccdc238a325a0d72 [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 Duffin46e37742021-03-09 11:55:20 +0000186 // ExtendWithErrorHandler creates a new FixtureFactory that will use the supplied error handler
187 // to check 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.
Paul Duffin46e37742021-03-09 11:55:20 +0000191 ExtendWithErrorHandler(errorHandler FixtureErrorHandler) FixtureFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000192
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
Paul Duffin72018ad2021-03-04 19:36:49 +0000202
203 // RunTestWithConfig is a temporary method added to help ease the migration of existing tests to
204 // the test fixture.
205 //
206 // In order to allow the Config object to be customized separately to the TestContext a lot of
207 // existing test code has `test...WithConfig` funcs that allow the Config object to be supplied
208 // from the test and then have the TestContext created and configured automatically. e.g.
209 // testCcWithConfig, testCcErrorWithConfig, testJavaWithConfig, etc.
210 //
211 // This method allows those methods to be migrated to use the test fixture pattern without
212 // requiring that every test that uses those methods be migrated at the same time. That allows
213 // those tests to benefit from correctness in the order of registration quickly.
214 //
215 // This method discards the config (along with its mock file system, product variables,
216 // environment, etc.) that may have been set up by FixturePreparers.
217 //
218 // deprecated
219 RunTestWithConfig(t *testing.T, config Config) *TestResult
Paul Duffin35816122021-02-24 01:49:52 +0000220}
221
222// Create a new FixtureFactory that will apply the supplied preparers.
223//
224// The buildDirSupplier is a pointer to the package level buildDir variable that is initialized by
225// the package level setUp method. It has to be a pointer to the variable as the variable will not
226// have been initialized at the time the factory is created.
227func NewFixtureFactory(buildDirSupplier *string, preparers ...FixturePreparer) FixtureFactory {
228 return &fixtureFactory{
229 buildDirSupplier: buildDirSupplier,
230 preparers: dedupAndFlattenPreparers(nil, preparers),
Paul Duffincfd33742021-02-27 11:59:02 +0000231
232 // Set the default error handler.
233 errorHandler: FixtureExpectsNoErrors,
Paul Duffin35816122021-02-24 01:49:52 +0000234 }
235}
236
237// A set of mock files to add to the mock file system.
238type MockFS map[string][]byte
239
240func (fs MockFS) Merge(extra map[string][]byte) {
241 for p, c := range extra {
242 fs[p] = c
243 }
244}
245
246func (fs MockFS) AddToFixture() FixturePreparer {
247 return FixtureMergeMockFs(fs)
248}
249
250// Modify the config
251func FixtureModifyConfig(mutator func(config Config)) FixturePreparer {
252 return newSimpleFixturePreparer(func(f *fixture) {
253 mutator(f.config)
254 })
255}
256
257// Modify the config and context
258func FixtureModifyConfigAndContext(mutator func(config Config, ctx *TestContext)) FixturePreparer {
259 return newSimpleFixturePreparer(func(f *fixture) {
260 mutator(f.config, f.ctx)
261 })
262}
263
264// Modify the context
265func FixtureModifyContext(mutator func(ctx *TestContext)) FixturePreparer {
266 return newSimpleFixturePreparer(func(f *fixture) {
267 mutator(f.ctx)
268 })
269}
270
271func FixtureRegisterWithContext(registeringFunc func(ctx RegistrationContext)) FixturePreparer {
272 return FixtureModifyContext(func(ctx *TestContext) { registeringFunc(ctx) })
273}
274
275// Modify the mock filesystem
276func FixtureModifyMockFS(mutator func(fs MockFS)) FixturePreparer {
277 return newSimpleFixturePreparer(func(f *fixture) {
278 mutator(f.mockFS)
279 })
280}
281
282// Merge the supplied file system into the mock filesystem.
283//
284// Paths that already exist in the mock file system are overridden.
285func FixtureMergeMockFs(mockFS MockFS) FixturePreparer {
286 return FixtureModifyMockFS(func(fs MockFS) {
287 fs.Merge(mockFS)
288 })
289}
290
291// Add a file to the mock filesystem
292func FixtureAddFile(path string, contents []byte) FixturePreparer {
293 return FixtureModifyMockFS(func(fs MockFS) {
294 fs[path] = contents
295 })
296}
297
298// Add a text file to the mock filesystem
299func FixtureAddTextFile(path string, contents string) FixturePreparer {
300 return FixtureAddFile(path, []byte(contents))
301}
302
303// Add the root Android.bp file with the supplied contents.
304func FixtureWithRootAndroidBp(contents string) FixturePreparer {
305 return FixtureAddTextFile("Android.bp", contents)
306}
307
Paul Duffinbbccfcf2021-03-03 00:44:00 +0000308// Merge some environment variables into the fixture.
309func FixtureMergeEnv(env map[string]string) FixturePreparer {
310 return FixtureModifyConfig(func(config Config) {
311 for k, v := range env {
312 if k == "PATH" {
313 panic("Cannot set PATH environment variable")
314 }
315 config.env[k] = v
316 }
317 })
318}
319
320// Modify the env.
321//
322// Will panic if the mutator changes the PATH environment variable.
323func FixtureModifyEnv(mutator func(env map[string]string)) FixturePreparer {
324 return FixtureModifyConfig(func(config Config) {
325 oldPath := config.env["PATH"]
326 mutator(config.env)
327 newPath := config.env["PATH"]
328 if newPath != oldPath {
329 panic(fmt.Errorf("Cannot change PATH environment variable from %q to %q", oldPath, newPath))
330 }
331 })
332}
333
Paul Duffin2e0323d2021-03-04 15:11:01 +0000334// Allow access to the product variables when preparing the fixture.
335type FixtureProductVariables struct {
336 *productVariables
337}
338
339// Modify product variables.
340func FixtureModifyProductVariables(mutator func(variables FixtureProductVariables)) FixturePreparer {
341 return FixtureModifyConfig(func(config Config) {
342 productVariables := FixtureProductVariables{&config.productVariables}
343 mutator(productVariables)
344 })
345}
346
Paul Duffina560d5a2021-02-28 01:38:51 +0000347// GroupFixturePreparers creates a composite FixturePreparer that is equivalent to applying each of
348// the supplied FixturePreparer instances in order.
349//
350// Before preparing the fixture the list of preparers is flattened by replacing each
351// instance of GroupFixturePreparers with its contents.
352func GroupFixturePreparers(preparers ...FixturePreparer) FixturePreparer {
Paul Duffin35816122021-02-24 01:49:52 +0000353 return &compositeFixturePreparer{dedupAndFlattenPreparers(nil, preparers)}
354}
355
356type simpleFixturePreparerVisitor func(preparer *simpleFixturePreparer)
357
358// FixturePreparer is an opaque interface that can change a fixture.
359type FixturePreparer interface {
360 // visit calls the supplied visitor with each *simpleFixturePreparer instances in this preparer,
361 visit(simpleFixturePreparerVisitor)
362}
363
364type fixturePreparers []FixturePreparer
365
366func (f fixturePreparers) visit(visitor simpleFixturePreparerVisitor) {
367 for _, p := range f {
368 p.visit(visitor)
369 }
370}
371
372// dedupAndFlattenPreparers removes any duplicates and flattens any composite FixturePreparer
373// instances.
374//
375// base - a list of already flattened and deduped preparers that will be applied first before
376// the list of additional preparers. Any duplicates of these in the additional preparers
377// will be ignored.
378//
379// preparers - a list of additional unflattened, undeduped preparers that will be applied after the
380// base preparers.
381//
382// Returns a deduped and flattened list of the preparers minus any that exist in the base preparers.
383func dedupAndFlattenPreparers(base []*simpleFixturePreparer, preparers fixturePreparers) []*simpleFixturePreparer {
384 var list []*simpleFixturePreparer
385 visited := make(map[*simpleFixturePreparer]struct{})
386
387 // Mark the already flattened and deduped preparers, if any, as having been seen so that
388 // duplicates of these in the additional preparers will be discarded.
389 for _, s := range base {
390 visited[s] = struct{}{}
391 }
392
393 preparers.visit(func(preparer *simpleFixturePreparer) {
394 if _, seen := visited[preparer]; !seen {
395 visited[preparer] = struct{}{}
396 list = append(list, preparer)
397 }
398 })
399 return list
400}
401
402// compositeFixturePreparer is a FixturePreparer created from a list of fixture preparers.
403type compositeFixturePreparer struct {
404 preparers []*simpleFixturePreparer
405}
406
407func (c *compositeFixturePreparer) visit(visitor simpleFixturePreparerVisitor) {
408 for _, p := range c.preparers {
409 p.visit(visitor)
410 }
411}
412
413// simpleFixturePreparer is a FixturePreparer that applies a function to a fixture.
414type simpleFixturePreparer struct {
415 function func(fixture *fixture)
416}
417
418func (s *simpleFixturePreparer) visit(visitor simpleFixturePreparerVisitor) {
419 visitor(s)
420}
421
422func newSimpleFixturePreparer(preparer func(fixture *fixture)) FixturePreparer {
423 return &simpleFixturePreparer{function: preparer}
424}
425
Paul Duffincfd33742021-02-27 11:59:02 +0000426// FixtureErrorHandler determines how to respond to errors reported by the code under test.
427//
428// Some possible responses:
429// * Fail the test if any errors are reported, see FixtureExpectsNoErrors.
430// * Fail the test if at least one error that matches a pattern is not reported see
431// FixtureExpectsAtLeastOneErrorMatchingPattern
432// * Fail the test if any unexpected errors are reported.
433//
434// Although at the moment all the error handlers are implemented as simply a wrapper around a
435// function this is defined as an interface to allow future enhancements, e.g. provide different
436// ways other than patterns to match an error and to combine handlers together.
437type FixtureErrorHandler interface {
438 // CheckErrors checks the errors reported.
439 //
440 // The supplied result can be used to access the state of the code under test just as the main
441 // body of the test would but if any errors other than ones expected are reported the state may
442 // be indeterminate.
Paul Duffin942481b2021-03-04 18:58:11 +0000443 CheckErrors(result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000444}
445
446type simpleErrorHandler struct {
Paul Duffin942481b2021-03-04 18:58:11 +0000447 function func(result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000448}
449
Paul Duffin942481b2021-03-04 18:58:11 +0000450func (h simpleErrorHandler) CheckErrors(result *TestResult) {
451 result.Helper()
452 h.function(result)
Paul Duffincfd33742021-02-27 11:59:02 +0000453}
454
455// The default fixture error handler.
456//
457// Will fail the test immediately if any errors are reported.
Paul Duffinea8a3862021-03-04 17:58:33 +0000458//
459// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
460// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000461var FixtureExpectsNoErrors = FixtureCustomErrorHandler(
Paul Duffin942481b2021-03-04 18:58:11 +0000462 func(result *TestResult) {
463 result.Helper()
464 FailIfErrored(result.T, result.Errs)
Paul Duffincfd33742021-02-27 11:59:02 +0000465 },
466)
467
468// FixtureExpectsAtLeastOneMatchingError returns an error handler that will cause the test to fail
469// if at least one error that matches the regular expression is not found.
470//
471// The test will be failed if:
472// * No errors are reported.
473// * One or more errors are reported but none match the pattern.
474//
475// The test will not fail if:
476// * Multiple errors are reported that do not match the pattern as long as one does match.
Paul Duffinea8a3862021-03-04 17:58:33 +0000477//
478// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
479// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000480func FixtureExpectsAtLeastOneErrorMatchingPattern(pattern string) FixtureErrorHandler {
Paul Duffin942481b2021-03-04 18:58:11 +0000481 return FixtureCustomErrorHandler(func(result *TestResult) {
482 result.Helper()
483 if !FailIfNoMatchingErrors(result.T, pattern, result.Errs) {
Paul Duffinea8a3862021-03-04 17:58:33 +0000484 result.FailNow()
485 }
Paul Duffincfd33742021-02-27 11:59:02 +0000486 })
487}
488
489// FixtureExpectsOneErrorToMatchPerPattern returns an error handler that will cause the test to fail
490// if there are any unexpected errors.
491//
492// The test will be failed if:
493// * The number of errors reported does not exactly match the patterns.
494// * One or more of the reported errors do not match a pattern.
495// * No patterns are provided and one or more errors are reported.
496//
497// The test will not fail if:
498// * One or more of the patterns does not match an error.
Paul Duffinea8a3862021-03-04 17:58:33 +0000499//
500// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
501// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000502func FixtureExpectsAllErrorsToMatchAPattern(patterns []string) FixtureErrorHandler {
Paul Duffin942481b2021-03-04 18:58:11 +0000503 return FixtureCustomErrorHandler(func(result *TestResult) {
504 result.Helper()
505 CheckErrorsAgainstExpectations(result.T, result.Errs, patterns)
Paul Duffincfd33742021-02-27 11:59:02 +0000506 })
507}
508
509// FixtureCustomErrorHandler creates a custom error handler
Paul Duffin942481b2021-03-04 18:58:11 +0000510func FixtureCustomErrorHandler(function func(result *TestResult)) FixtureErrorHandler {
Paul Duffincfd33742021-02-27 11:59:02 +0000511 return simpleErrorHandler{
512 function: function,
513 }
514}
515
Paul Duffin35816122021-02-24 01:49:52 +0000516// Fixture defines the test environment.
517type Fixture interface {
Paul Duffincfd33742021-02-27 11:59:02 +0000518 // Run the test, checking any errors reported and returning a TestResult instance.
Paul Duffin35816122021-02-24 01:49:52 +0000519 RunTest() *TestResult
520}
521
522// Provides general test support.
523type TestHelper struct {
524 *testing.T
525}
526
527// AssertBoolEquals checks if the expected and actual values are equal and if they are not then it
528// reports an error prefixed with the supplied message and including a reason for why it failed.
529func (h *TestHelper) AssertBoolEquals(message string, expected bool, actual bool) {
530 h.Helper()
531 if actual != expected {
532 h.Errorf("%s: expected %t, actual %t", message, expected, actual)
533 }
534}
535
536// AssertStringEquals checks if the expected and actual values are equal and if they are not then
537// it reports an error prefixed with the supplied message and including a reason for why it failed.
538func (h *TestHelper) AssertStringEquals(message string, expected string, actual string) {
539 h.Helper()
540 if actual != expected {
541 h.Errorf("%s: expected %s, actual %s", message, expected, actual)
542 }
543}
544
Paul Duffina3cb2b32021-03-10 09:15:22 +0000545// AssertErrorMessageEquals checks if the error is not nil and has the expected message. If it does
546// not then this reports an error prefixed with the supplied message and including a reason for why
547// it failed.
548func (h *TestHelper) AssertErrorMessageEquals(message string, expected string, actual error) {
549 h.Helper()
550 if actual == nil {
551 h.Errorf("Expected error but was nil")
552 } else if actual.Error() != expected {
553 h.Errorf("%s: expected %s, actual %s", message, expected, actual.Error())
554 }
555}
556
Paul Duffin35816122021-02-24 01:49:52 +0000557// AssertTrimmedStringEquals checks if the expected and actual values are the same after trimming
558// leading and trailing spaces from them both. If they are not then it reports an error prefixed
559// with the supplied message and including a reason for why it failed.
560func (h *TestHelper) AssertTrimmedStringEquals(message string, expected string, actual string) {
561 h.Helper()
562 h.AssertStringEquals(message, strings.TrimSpace(expected), strings.TrimSpace(actual))
563}
564
565// AssertStringDoesContain checks if the string contains the expected substring. If it does not
566// then it reports an error prefixed with the supplied message and including a reason for why it
567// failed.
568func (h *TestHelper) AssertStringDoesContain(message string, s string, expectedSubstring string) {
569 h.Helper()
570 if !strings.Contains(s, expectedSubstring) {
571 h.Errorf("%s: could not find %q within %q", message, expectedSubstring, s)
572 }
573}
574
575// AssertStringDoesNotContain checks if the string contains the expected substring. If it does then
576// it reports an error prefixed with the supplied message and including a reason for why it failed.
577func (h *TestHelper) AssertStringDoesNotContain(message string, s string, unexpectedSubstring string) {
578 h.Helper()
579 if strings.Contains(s, unexpectedSubstring) {
580 h.Errorf("%s: unexpectedly found %q within %q", message, unexpectedSubstring, s)
581 }
582}
583
Paul Duffin93706ae2021-03-07 15:48:27 +0000584// AssertStringListContains checks if the list of strings contains the expected string. If it does
585// not then it reports an error prefixed with the supplied message and including a reason for why it
586// failed.
587func (h *TestHelper) AssertStringListContains(message string, list []string, expected string) {
588 h.Helper()
589 if !InList(expected, list) {
590 h.Errorf("%s: could not find %q within %q", message, expected, list)
591 }
592}
593
Paul Duffin35816122021-02-24 01:49:52 +0000594// AssertArrayString checks if the expected and actual values are equal and if they are not then it
595// reports an error prefixed with the supplied message and including a reason for why it failed.
596func (h *TestHelper) AssertArrayString(message string, expected, actual []string) {
597 h.Helper()
598 if len(actual) != len(expected) {
599 h.Errorf("%s: expected %d (%q), actual (%d) %q", message, len(expected), expected, len(actual), actual)
600 return
601 }
602 for i := range actual {
603 if actual[i] != expected[i] {
604 h.Errorf("%s: expected %d-th, %q (%q), actual %q (%q)",
605 message, i, expected[i], expected, actual[i], actual)
606 return
607 }
608 }
609}
610
Paul Duffin1ef166e2021-03-11 14:08:57 +0000611// AssertDeepEquals checks if the expected and actual values are equal using reflect.DeepEqual and
Paul Duffin35816122021-02-24 01:49:52 +0000612// if they are not then it reports an error prefixed with the supplied message and including a
613// reason for why it failed.
614func (h *TestHelper) AssertDeepEquals(message string, expected interface{}, actual interface{}) {
615 h.Helper()
616 if !reflect.DeepEqual(actual, expected) {
617 h.Errorf("%s: expected:\n %#v\n got:\n %#v", message, expected, actual)
618 }
619}
620
Paul Duffina3cb2b32021-03-10 09:15:22 +0000621// AssertPanic checks that the supplied function panics as expected.
622func (h *TestHelper) AssertPanic(message string, funcThatShouldPanic func()) {
623 h.Helper()
624 panicked := false
625 func() {
626 defer func() {
627 if x := recover(); x != nil {
628 panicked = true
629 }
630 }()
631 funcThatShouldPanic()
632 }()
633 if !panicked {
634 h.Error(message)
635 }
636}
637
Paul Duffin35816122021-02-24 01:49:52 +0000638// Struct to allow TestResult to embed a *TestContext and allow call forwarding to its methods.
639type testContext struct {
640 *TestContext
641}
642
643// The result of running a test.
644type TestResult struct {
645 TestHelper
646 testContext
647
648 fixture *fixture
649 Config Config
Paul Duffin942481b2021-03-04 18:58:11 +0000650
651 // The errors that were reported during the test.
652 Errs []error
Paul Duffin35816122021-02-24 01:49:52 +0000653}
654
655var _ FixtureFactory = (*fixtureFactory)(nil)
656
657type fixtureFactory struct {
658 buildDirSupplier *string
659 preparers []*simpleFixturePreparer
Paul Duffincfd33742021-02-27 11:59:02 +0000660 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000661}
662
663func (f *fixtureFactory) Extend(preparers ...FixturePreparer) FixtureFactory {
Paul Duffinfa298852021-03-08 15:05:24 +0000664 // Create a new slice to avoid accidentally sharing the preparers slice from this factory with
665 // the extending factories.
666 var all []*simpleFixturePreparer
667 all = append(all, f.preparers...)
668 all = append(all, dedupAndFlattenPreparers(f.preparers, preparers)...)
Paul Duffincfd33742021-02-27 11:59:02 +0000669 // Copy the existing factory.
670 extendedFactory := &fixtureFactory{}
671 *extendedFactory = *f
672 // Use the extended list of preparers.
673 extendedFactory.preparers = all
674 return extendedFactory
Paul Duffin35816122021-02-24 01:49:52 +0000675}
676
677func (f *fixtureFactory) Fixture(t *testing.T, preparers ...FixturePreparer) Fixture {
678 config := TestConfig(*f.buildDirSupplier, nil, "", nil)
679 ctx := NewTestContext(config)
680 fixture := &fixture{
Paul Duffincfd33742021-02-27 11:59:02 +0000681 factory: f,
682 t: t,
683 config: config,
684 ctx: ctx,
685 mockFS: make(MockFS),
686 errorHandler: f.errorHandler,
Paul Duffin35816122021-02-24 01:49:52 +0000687 }
688
689 for _, preparer := range f.preparers {
690 preparer.function(fixture)
691 }
692
693 for _, preparer := range dedupAndFlattenPreparers(f.preparers, preparers) {
694 preparer.function(fixture)
695 }
696
697 return fixture
698}
699
Paul Duffin46e37742021-03-09 11:55:20 +0000700func (f *fixtureFactory) ExtendWithErrorHandler(errorHandler FixtureErrorHandler) FixtureFactory {
Paul Duffin52323b52021-03-04 19:15:47 +0000701 newFactory := &fixtureFactory{}
702 *newFactory = *f
703 newFactory.errorHandler = errorHandler
704 return newFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000705}
706
Paul Duffin35816122021-02-24 01:49:52 +0000707func (f *fixtureFactory) RunTest(t *testing.T, preparers ...FixturePreparer) *TestResult {
708 t.Helper()
709 fixture := f.Fixture(t, preparers...)
710 return fixture.RunTest()
711}
712
713func (f *fixtureFactory) RunTestWithBp(t *testing.T, bp string) *TestResult {
714 t.Helper()
715 return f.RunTest(t, FixtureWithRootAndroidBp(bp))
716}
717
Paul Duffin72018ad2021-03-04 19:36:49 +0000718func (f *fixtureFactory) RunTestWithConfig(t *testing.T, config Config) *TestResult {
719 t.Helper()
720 // Create the fixture as normal.
721 fixture := f.Fixture(t).(*fixture)
722
723 // Discard the mock filesystem as otherwise that will override the one in the config.
724 fixture.mockFS = nil
725
726 // Replace the config with the supplied one in the fixture.
727 fixture.config = config
728
729 // Ditto with config derived information in the TestContext.
730 ctx := fixture.ctx
731 ctx.config = config
732 ctx.SetFs(ctx.config.fs)
733 if ctx.config.mockBpList != "" {
734 ctx.SetModuleListFile(ctx.config.mockBpList)
735 }
736
737 return fixture.RunTest()
738}
739
Paul Duffin35816122021-02-24 01:49:52 +0000740type fixture struct {
Paul Duffincfd33742021-02-27 11:59:02 +0000741 // The factory used to create this fixture.
Paul Duffin35816122021-02-24 01:49:52 +0000742 factory *fixtureFactory
Paul Duffincfd33742021-02-27 11:59:02 +0000743
744 // The gotest state of the go test within which this was created.
745 t *testing.T
746
747 // The configuration prepared for this fixture.
748 config Config
749
750 // The test context prepared for this fixture.
751 ctx *TestContext
752
753 // The mock filesystem prepared for this fixture.
754 mockFS MockFS
755
756 // The error handler used to check the errors, if any, that are reported.
757 errorHandler FixtureErrorHandler
Paul Duffin35816122021-02-24 01:49:52 +0000758}
759
760func (f *fixture) RunTest() *TestResult {
761 f.t.Helper()
762
763 ctx := f.ctx
764
Paul Duffin72018ad2021-03-04 19:36:49 +0000765 // Do not use the fixture's mockFS to initialize the config's mock file system if it has been
766 // cleared by RunTestWithConfig.
767 if f.mockFS != nil {
768 // The TestConfig() method assumes that the mock filesystem is available when creating so
769 // creates the mock file system immediately. Similarly, the NewTestContext(Config) method
770 // assumes that the supplied Config's FileSystem has been properly initialized before it is
771 // called and so it takes its own reference to the filesystem. However, fixtures create the
772 // Config and TestContext early so they can be modified by preparers at which time the mockFS
773 // has not been populated (because it too is modified by preparers). So, this reinitializes the
774 // Config and TestContext's FileSystem using the now populated mockFS.
775 f.config.mockFileSystem("", f.mockFS)
776
777 ctx.SetFs(ctx.config.fs)
778 if ctx.config.mockBpList != "" {
779 ctx.SetModuleListFile(ctx.config.mockBpList)
780 }
Paul Duffin35816122021-02-24 01:49:52 +0000781 }
782
783 ctx.Register()
784 _, errs := ctx.ParseBlueprintsFiles("ignored")
Paul Duffincfd33742021-02-27 11:59:02 +0000785 if len(errs) == 0 {
786 _, errs = ctx.PrepareBuildActions(f.config)
787 }
Paul Duffin35816122021-02-24 01:49:52 +0000788
789 result := &TestResult{
790 TestHelper: TestHelper{T: f.t},
791 testContext: testContext{ctx},
792 fixture: f,
793 Config: f.config,
Paul Duffin942481b2021-03-04 18:58:11 +0000794 Errs: errs,
Paul Duffin35816122021-02-24 01:49:52 +0000795 }
Paul Duffincfd33742021-02-27 11:59:02 +0000796
Paul Duffin942481b2021-03-04 18:58:11 +0000797 f.errorHandler.CheckErrors(result)
Paul Duffincfd33742021-02-27 11:59:02 +0000798
Paul Duffin35816122021-02-24 01:49:52 +0000799 return result
800}
801
802// NormalizePathForTesting removes the test invocation specific build directory from the supplied
803// path.
804//
805// If the path is within the build directory (e.g. an OutputPath) then this returns the relative
806// path to avoid tests having to deal with the dynamically generated build directory.
807//
808// Otherwise, this returns the supplied path as it is almost certainly a source path that is
809// relative to the root of the source tree.
810//
811// Even though some information is removed from some paths and not others it should be possible to
812// differentiate between them by the paths themselves, e.g. output paths will likely include
813// ".intermediates" but source paths won't.
814func (r *TestResult) NormalizePathForTesting(path Path) string {
815 pathContext := PathContextForTesting(r.Config)
816 pathAsString := path.String()
817 if rel, isRel := MaybeRel(pathContext, r.Config.BuildDir(), pathAsString); isRel {
818 return rel
819 }
820 return pathAsString
821}
822
823// NormalizePathsForTesting normalizes each path in the supplied list and returns their normalized
824// forms.
825func (r *TestResult) NormalizePathsForTesting(paths Paths) []string {
826 var result []string
827 for _, path := range paths {
828 result = append(result, r.NormalizePathForTesting(path))
829 }
830 return result
831}
832
833// NewFixture creates a new test fixture that is based on the one that created this result. It is
834// intended to test the output of module types that generate content to be processed by the build,
835// e.g. sdk snapshots.
836func (r *TestResult) NewFixture(preparers ...FixturePreparer) Fixture {
837 return r.fixture.factory.Fixture(r.T, preparers...)
838}
839
840// RunTest is shorthand for NewFixture(preparers...).RunTest().
841func (r *TestResult) RunTest(preparers ...FixturePreparer) *TestResult {
842 r.Helper()
843 return r.fixture.factory.Fixture(r.T, preparers...).RunTest()
844}
845
846// Module returns the module with the specific name and of the specified variant.
847func (r *TestResult) Module(name string, variant string) Module {
848 return r.ModuleForTests(name, variant).Module()
849}
850
851// Create a *TestResult object suitable for use within a subtest.
852//
853// This ensures that any errors reported by the TestResult, e.g. from within one of its
854// Assert... methods, will be associated with the sub test and not the main test.
855//
856// result := ....RunTest()
857// t.Run("subtest", func(t *testing.T) {
858// subResult := result.ResultForSubTest(t)
859// subResult.AssertStringEquals("something", ....)
860// })
861func (r *TestResult) ResultForSubTest(t *testing.T) *TestResult {
862 subTestResult := *r
863 r.T = t
864 return &subTestResult
865}