blob: f33e7189d7410a3bae00bed6ae0788a5419d9161 [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 Duffin80f4cea2021-03-16 14:08:00 +000019 "strings"
Paul Duffin35816122021-02-24 01:49:52 +000020 "testing"
21)
22
23// Provides support for creating test fixtures on which tests can be run. Reduces duplication
24// of test setup by allow tests to easily reuse setup code.
25//
26// Fixture
27// =======
28// These determine the environment within which a test can be run. Fixtures are mutable and are
Paul Duffin4814bb82021-03-29 01:55:10 +010029// created and mutated by FixturePreparer instances. They are created by first creating a base
30// Fixture (which is essentially empty) and then applying FixturePreparer instances to it to modify
31// the environment.
Paul Duffin35816122021-02-24 01:49:52 +000032//
33// FixturePreparer
34// ===============
35// These are responsible for modifying a Fixture in preparation for it to run a test. Preparers are
36// intended to be immutable and able to prepare multiple Fixture objects simultaneously without
37// them sharing any data.
38//
Paul Duffinff2aa692021-03-19 18:20:59 +000039// They provide the basic capabilities for running tests too.
40//
41// FixturePreparers are only ever applied once per test fixture. Prior to application the list of
Paul Duffin35816122021-02-24 01:49:52 +000042// FixturePreparers are flattened and deduped while preserving the order they first appear in the
43// list. This makes it easy to reuse, group and combine FixturePreparers together.
44//
45// Each small self contained piece of test setup should be their own FixturePreparer. e.g.
46// * A group of related modules.
47// * A group of related mutators.
48// * A combination of both.
49// * Configuration.
50//
51// They should not overlap, e.g. the same module type should not be registered by different
52// FixturePreparers as using them both would cause a build error. In that case the preparer should
53// be split into separate parts and combined together using FixturePreparers(...).
54//
55// e.g. attempting to use AllPreparers in preparing a Fixture would break as it would attempt to
56// register module bar twice:
57// var Preparer1 = FixtureRegisterWithContext(RegisterModuleFooAndBar)
58// var Preparer2 = FixtureRegisterWithContext(RegisterModuleBarAndBaz)
Paul Duffina560d5a2021-02-28 01:38:51 +000059// var AllPreparers = GroupFixturePreparers(Preparer1, Preparer2)
Paul Duffin35816122021-02-24 01:49:52 +000060//
61// However, when restructured like this it would work fine:
62// var PreparerFoo = FixtureRegisterWithContext(RegisterModuleFoo)
63// var PreparerBar = FixtureRegisterWithContext(RegisterModuleBar)
64// var PreparerBaz = FixtureRegisterWithContext(RegisterModuleBaz)
Paul Duffina560d5a2021-02-28 01:38:51 +000065// var Preparer1 = GroupFixturePreparers(RegisterModuleFoo, RegisterModuleBar)
66// var Preparer2 = GroupFixturePreparers(RegisterModuleBar, RegisterModuleBaz)
67// var AllPreparers = GroupFixturePreparers(Preparer1, Preparer2)
Paul Duffin35816122021-02-24 01:49:52 +000068//
69// As after deduping and flattening AllPreparers would result in the following preparers being
70// applied:
71// 1. PreparerFoo
72// 2. PreparerBar
73// 3. PreparerBaz
74//
75// Preparers can be used for both integration and unit tests.
76//
77// Integration tests typically use all the module types, mutators and singletons that are available
78// for that package to try and replicate the behavior of the runtime build as closely as possible.
79// However, that realism comes at a cost of increased fragility (as they can be broken by changes in
80// many different parts of the build) and also increased runtime, especially if they use lots of
81// singletons and mutators.
82//
83// Unit tests on the other hand try and minimize the amount of code being tested which makes them
84// less susceptible to changes elsewhere in the build and quick to run but at a cost of potentially
85// not testing realistic scenarios.
86//
87// Supporting unit tests effectively require that preparers are available at the lowest granularity
88// possible. Supporting integration tests effectively require that the preparers are organized into
89// groups that provide all the functionality available.
90//
91// At least in terms of tests that check the behavior of build components via processing
92// `Android.bp` there is no clear separation between a unit test and an integration test. Instead
93// they vary from one end that tests a single module (e.g. filegroup) to the other end that tests a
94// whole system of modules, mutators and singletons (e.g. apex + hiddenapi).
95//
96// TestResult
97// ==========
98// These are created by running tests in a Fixture and provide access to the Config and TestContext
99// in which the tests were run.
100//
101// Example
102// =======
103//
104// An exported preparer for use by other packages that need to use java modules.
105//
106// package java
Paul Duffina560d5a2021-02-28 01:38:51 +0000107// var PrepareForIntegrationTestWithJava = GroupFixturePreparers(
Paul Duffin35816122021-02-24 01:49:52 +0000108// android.PrepareForIntegrationTestWithAndroid,
109// FixtureRegisterWithContext(RegisterAGroupOfRelatedModulesMutatorsAndSingletons),
110// FixtureRegisterWithContext(RegisterAnotherGroupOfRelatedModulesMutatorsAndSingletons),
111// ...
112// )
113//
114// Some files to use in tests in the java package.
115//
116// var javaMockFS = android.MockFS{
Paul Duffinff2aa692021-03-19 18:20:59 +0000117// "api/current.txt": nil,
118// "api/removed.txt": nil,
Paul Duffin35816122021-02-24 01:49:52 +0000119// ...
120// }
121//
Paul Duffinff2aa692021-03-19 18:20:59 +0000122// A package private preparer for use for testing java within the java package.
Paul Duffin35816122021-02-24 01:49:52 +0000123//
Paul Duffinff2aa692021-03-19 18:20:59 +0000124// var prepareForJavaTest = android.GroupFixturePreparers(
125// PrepareForIntegrationTestWithJava,
126// FixtureRegisterWithContext(func(ctx android.RegistrationContext) {
127// ctx.RegisterModuleType("test_module", testModule)
128// }),
129// javaMockFS.AddToFixture(),
130// ...
131// }
132//
133// func TestJavaStuff(t *testing.T) {
Paul Duffin3cb2c062021-03-22 19:24:26 +0000134// result := android.GroupFixturePreparers(
Paul Duffinff2aa692021-03-19 18:20:59 +0000135// prepareForJavaTest,
136// android.FixtureWithRootAndroidBp(`java_library {....}`),
137// android.MockFS{...}.AddToFixture(),
138// ).RunTest(t)
139// ... test result ...
140// }
141//
142// package cc
143// var PrepareForTestWithCC = android.GroupFixturePreparers(
144// android.PrepareForArchMutator,
145// android.prepareForPrebuilts,
146// FixtureRegisterWithContext(RegisterRequiredBuildComponentsForTest),
147// ...
148// )
149//
150// package apex
151//
152// var PrepareForApex = GroupFixturePreparers(
153// ...
154// )
155//
156// Use modules and mutators from java, cc and apex. Any duplicate preparers (like
157// android.PrepareForArchMutator) will be automatically deduped.
158//
159// var prepareForApexTest = android.GroupFixturePreparers(
160// PrepareForJava,
161// PrepareForCC,
162// PrepareForApex,
163// )
164//
Paul Duffin35816122021-02-24 01:49:52 +0000165
166// A set of mock files to add to the mock file system.
167type MockFS map[string][]byte
168
Paul Duffin6e9a4002021-03-11 19:01:26 +0000169// Merge adds the extra entries from the supplied map to this one.
170//
171// Fails if the supplied map files with the same paths are present in both of them.
Paul Duffin35816122021-02-24 01:49:52 +0000172func (fs MockFS) Merge(extra map[string][]byte) {
173 for p, c := range extra {
Paul Duffin80f4cea2021-03-16 14:08:00 +0000174 validateFixtureMockFSPath(p)
Paul Duffin6e9a4002021-03-11 19:01:26 +0000175 if _, ok := fs[p]; ok {
176 panic(fmt.Errorf("attempted to add file %s to the mock filesystem but it already exists", p))
177 }
Paul Duffin35816122021-02-24 01:49:52 +0000178 fs[p] = c
179 }
180}
181
Paul Duffin80f4cea2021-03-16 14:08:00 +0000182// Ensure that tests cannot add paths into the mock file system which would not be allowed in the
183// runtime, e.g. absolute paths, paths relative to the 'out/' directory.
184func validateFixtureMockFSPath(path string) {
185 // This uses validateSafePath rather than validatePath because the latter prevents adding files
186 // that include a $ but there are tests that allow files with a $ to be used, albeit only by
187 // globbing.
188 validatedPath, err := validateSafePath(path)
189 if err != nil {
190 panic(err)
191 }
192
193 // Make sure that the path is canonical.
194 if validatedPath != path {
195 panic(fmt.Errorf("path %q is not a canonical path, use %q instead", path, validatedPath))
196 }
197
198 if path == "out" || strings.HasPrefix(path, "out/") {
199 panic(fmt.Errorf("cannot add output path %q to the mock file system", path))
200 }
201}
202
Paul Duffin35816122021-02-24 01:49:52 +0000203func (fs MockFS) AddToFixture() FixturePreparer {
204 return FixtureMergeMockFs(fs)
205}
206
Paul Duffinae542a52021-03-09 03:15:28 +0000207// FixtureCustomPreparer allows for the modification of any aspect of the fixture.
208//
209// This should only be used if one of the other more specific preparers are not suitable.
210func FixtureCustomPreparer(mutator func(fixture Fixture)) FixturePreparer {
211 return newSimpleFixturePreparer(func(f *fixture) {
212 mutator(f)
213 })
214}
215
Paul Duffin35816122021-02-24 01:49:52 +0000216// Modify the config
217func FixtureModifyConfig(mutator func(config Config)) FixturePreparer {
218 return newSimpleFixturePreparer(func(f *fixture) {
219 mutator(f.config)
220 })
221}
222
223// Modify the config and context
224func FixtureModifyConfigAndContext(mutator func(config Config, ctx *TestContext)) FixturePreparer {
225 return newSimpleFixturePreparer(func(f *fixture) {
226 mutator(f.config, f.ctx)
227 })
228}
229
230// Modify the context
231func FixtureModifyContext(mutator func(ctx *TestContext)) FixturePreparer {
232 return newSimpleFixturePreparer(func(f *fixture) {
233 mutator(f.ctx)
234 })
235}
236
237func FixtureRegisterWithContext(registeringFunc func(ctx RegistrationContext)) FixturePreparer {
238 return FixtureModifyContext(func(ctx *TestContext) { registeringFunc(ctx) })
239}
240
241// Modify the mock filesystem
242func FixtureModifyMockFS(mutator func(fs MockFS)) FixturePreparer {
243 return newSimpleFixturePreparer(func(f *fixture) {
244 mutator(f.mockFS)
Paul Duffin80f4cea2021-03-16 14:08:00 +0000245
246 // Make sure that invalid paths were not added to the mock filesystem.
247 for p, _ := range f.mockFS {
248 validateFixtureMockFSPath(p)
249 }
Paul Duffin35816122021-02-24 01:49:52 +0000250 })
251}
252
253// Merge the supplied file system into the mock filesystem.
254//
255// Paths that already exist in the mock file system are overridden.
256func FixtureMergeMockFs(mockFS MockFS) FixturePreparer {
257 return FixtureModifyMockFS(func(fs MockFS) {
258 fs.Merge(mockFS)
259 })
260}
261
262// Add a file to the mock filesystem
Paul Duffin6e9a4002021-03-11 19:01:26 +0000263//
264// Fail if the filesystem already contains a file with that path, use FixtureOverrideFile instead.
Paul Duffin35816122021-02-24 01:49:52 +0000265func FixtureAddFile(path string, contents []byte) FixturePreparer {
266 return FixtureModifyMockFS(func(fs MockFS) {
Paul Duffin80f4cea2021-03-16 14:08:00 +0000267 validateFixtureMockFSPath(path)
Paul Duffin6e9a4002021-03-11 19:01:26 +0000268 if _, ok := fs[path]; ok {
269 panic(fmt.Errorf("attempted to add file %s to the mock filesystem but it already exists, use FixtureOverride*File instead", path))
270 }
Paul Duffin35816122021-02-24 01:49:52 +0000271 fs[path] = contents
272 })
273}
274
275// Add a text file to the mock filesystem
Paul Duffin6e9a4002021-03-11 19:01:26 +0000276//
277// Fail if the filesystem already contains a file with that path.
Paul Duffin35816122021-02-24 01:49:52 +0000278func FixtureAddTextFile(path string, contents string) FixturePreparer {
279 return FixtureAddFile(path, []byte(contents))
280}
281
Paul Duffin6e9a4002021-03-11 19:01:26 +0000282// Override a file in the mock filesystem
283//
284// If the file does not exist this behaves as FixtureAddFile.
285func FixtureOverrideFile(path string, contents []byte) FixturePreparer {
286 return FixtureModifyMockFS(func(fs MockFS) {
287 fs[path] = contents
288 })
289}
290
291// Override a text file in the mock filesystem
292//
293// If the file does not exist this behaves as FixtureAddTextFile.
294func FixtureOverrideTextFile(path string, contents string) FixturePreparer {
295 return FixtureOverrideFile(path, []byte(contents))
296}
297
Paul Duffin35816122021-02-24 01:49:52 +0000298// Add the root Android.bp file with the supplied contents.
299func FixtureWithRootAndroidBp(contents string) FixturePreparer {
300 return FixtureAddTextFile("Android.bp", contents)
301}
302
Paul Duffinbbccfcf2021-03-03 00:44:00 +0000303// Merge some environment variables into the fixture.
304func FixtureMergeEnv(env map[string]string) FixturePreparer {
305 return FixtureModifyConfig(func(config Config) {
306 for k, v := range env {
307 if k == "PATH" {
308 panic("Cannot set PATH environment variable")
309 }
310 config.env[k] = v
311 }
312 })
313}
314
315// Modify the env.
316//
317// Will panic if the mutator changes the PATH environment variable.
318func FixtureModifyEnv(mutator func(env map[string]string)) FixturePreparer {
319 return FixtureModifyConfig(func(config Config) {
320 oldPath := config.env["PATH"]
321 mutator(config.env)
322 newPath := config.env["PATH"]
323 if newPath != oldPath {
324 panic(fmt.Errorf("Cannot change PATH environment variable from %q to %q", oldPath, newPath))
325 }
326 })
327}
328
Paul Duffin2e0323d2021-03-04 15:11:01 +0000329// Allow access to the product variables when preparing the fixture.
330type FixtureProductVariables struct {
331 *productVariables
332}
333
334// Modify product variables.
335func FixtureModifyProductVariables(mutator func(variables FixtureProductVariables)) FixturePreparer {
336 return FixtureModifyConfig(func(config Config) {
337 productVariables := FixtureProductVariables{&config.productVariables}
338 mutator(productVariables)
339 })
340}
341
Paul Duffin64715ba2021-04-20 22:42:17 +0100342// PrepareForDebug_DO_NOT_SUBMIT puts the fixture into debug which will cause it to output its
343// state before running the test.
344//
345// This must only be added temporarily to a test for local debugging and must be removed from the
346// test before submitting.
347var PrepareForDebug_DO_NOT_SUBMIT = newSimpleFixturePreparer(func(fixture *fixture) {
348 fixture.debug = true
349})
350
Paul Duffina560d5a2021-02-28 01:38:51 +0000351// GroupFixturePreparers creates a composite FixturePreparer that is equivalent to applying each of
352// the supplied FixturePreparer instances in order.
353//
354// Before preparing the fixture the list of preparers is flattened by replacing each
355// instance of GroupFixturePreparers with its contents.
356func GroupFixturePreparers(preparers ...FixturePreparer) FixturePreparer {
Paul Duffinff2aa692021-03-19 18:20:59 +0000357 all := dedupAndFlattenPreparers(nil, preparers)
358 return newFixturePreparer(all)
Paul Duffin35816122021-02-24 01:49:52 +0000359}
360
Paul Duffin50deaae2021-03-16 17:46:12 +0000361// NullFixturePreparer is a preparer that does nothing.
362var NullFixturePreparer = GroupFixturePreparers()
363
364// OptionalFixturePreparer will return the supplied preparer if it is non-nil, otherwise it will
365// return the NullFixturePreparer
366func OptionalFixturePreparer(preparer FixturePreparer) FixturePreparer {
367 if preparer == nil {
368 return NullFixturePreparer
369 } else {
370 return preparer
371 }
372}
373
Paul Duffinff2aa692021-03-19 18:20:59 +0000374// FixturePreparer provides the ability to create, modify and then run tests within a fixture.
Paul Duffin35816122021-02-24 01:49:52 +0000375type FixturePreparer interface {
Paul Duffin4ca67522021-03-20 01:25:12 +0000376 // Return the flattened and deduped list of simpleFixturePreparer pointers.
377 list() []*simpleFixturePreparer
Paul Duffinff2aa692021-03-19 18:20:59 +0000378
Paul Duffinff2aa692021-03-19 18:20:59 +0000379 // Create a Fixture.
Paul Duffin34a7fff2021-03-30 22:11:24 +0100380 Fixture(t *testing.T) Fixture
Paul Duffinff2aa692021-03-19 18:20:59 +0000381
382 // ExtendWithErrorHandler creates a new FixturePreparer that will use the supplied error handler
383 // to check the errors (may be 0) reported by the test.
384 //
385 // The default handlers is FixtureExpectsNoErrors which will fail the go test immediately if any
386 // errors are reported.
387 ExtendWithErrorHandler(errorHandler FixtureErrorHandler) FixturePreparer
388
389 // Run the test, checking any errors reported and returning a TestResult instance.
390 //
Paul Duffin55e740e2021-03-29 02:06:19 +0100391 // Shorthand for Fixture(t).RunTest()
392 RunTest(t *testing.T) *TestResult
Paul Duffinff2aa692021-03-19 18:20:59 +0000393
394 // Run the test with the supplied Android.bp file.
395 //
Paul Duffin55e740e2021-03-29 02:06:19 +0100396 // preparer.RunTestWithBp(t, bp) is shorthand for
397 // android.GroupFixturePreparers(preparer, android.FixtureWithRootAndroidBp(bp)).RunTest(t)
Paul Duffinff2aa692021-03-19 18:20:59 +0000398 RunTestWithBp(t *testing.T, bp string) *TestResult
399
400 // RunTestWithConfig is a temporary method added to help ease the migration of existing tests to
401 // the test fixture.
402 //
403 // In order to allow the Config object to be customized separately to the TestContext a lot of
404 // existing test code has `test...WithConfig` funcs that allow the Config object to be supplied
405 // from the test and then have the TestContext created and configured automatically. e.g.
406 // testCcWithConfig, testCcErrorWithConfig, testJavaWithConfig, etc.
407 //
408 // This method allows those methods to be migrated to use the test fixture pattern without
409 // requiring that every test that uses those methods be migrated at the same time. That allows
410 // those tests to benefit from correctness in the order of registration quickly.
411 //
412 // This method discards the config (along with its mock file system, product variables,
413 // environment, etc.) that may have been set up by FixturePreparers.
414 //
415 // deprecated
416 RunTestWithConfig(t *testing.T, config Config) *TestResult
Paul Duffin35816122021-02-24 01:49:52 +0000417}
418
419// dedupAndFlattenPreparers removes any duplicates and flattens any composite FixturePreparer
420// instances.
421//
422// base - a list of already flattened and deduped preparers that will be applied first before
Colin Crossd079e0b2022-08-16 10:27:33 -0700423//
424// the list of additional preparers. Any duplicates of these in the additional preparers
425// will be ignored.
Paul Duffin35816122021-02-24 01:49:52 +0000426//
427// preparers - a list of additional unflattened, undeduped preparers that will be applied after the
Colin Crossd079e0b2022-08-16 10:27:33 -0700428//
429// base preparers.
Paul Duffin35816122021-02-24 01:49:52 +0000430//
Paul Duffin59251822021-03-15 22:20:12 +0000431// Returns a deduped and flattened list of the preparers starting with the ones in base with any
432// additional ones from the preparers list added afterwards.
Paul Duffin4ca67522021-03-20 01:25:12 +0000433func dedupAndFlattenPreparers(base []*simpleFixturePreparer, preparers []FixturePreparer) []*simpleFixturePreparer {
Paul Duffin59251822021-03-15 22:20:12 +0000434 if len(preparers) == 0 {
435 return base
436 }
437
438 list := make([]*simpleFixturePreparer, len(base))
Paul Duffin35816122021-02-24 01:49:52 +0000439 visited := make(map[*simpleFixturePreparer]struct{})
440
441 // Mark the already flattened and deduped preparers, if any, as having been seen so that
Paul Duffin59251822021-03-15 22:20:12 +0000442 // duplicates of these in the additional preparers will be discarded. Add them to the output
443 // list.
444 for i, s := range base {
Paul Duffin35816122021-02-24 01:49:52 +0000445 visited[s] = struct{}{}
Paul Duffin59251822021-03-15 22:20:12 +0000446 list[i] = s
Paul Duffin35816122021-02-24 01:49:52 +0000447 }
448
Paul Duffin4ca67522021-03-20 01:25:12 +0000449 for _, p := range preparers {
450 for _, s := range p.list() {
451 if _, seen := visited[s]; !seen {
452 visited[s] = struct{}{}
453 list = append(list, s)
454 }
Paul Duffin35816122021-02-24 01:49:52 +0000455 }
Paul Duffin4ca67522021-03-20 01:25:12 +0000456 }
457
Paul Duffin35816122021-02-24 01:49:52 +0000458 return list
459}
460
461// compositeFixturePreparer is a FixturePreparer created from a list of fixture preparers.
462type compositeFixturePreparer struct {
Paul Duffinff2aa692021-03-19 18:20:59 +0000463 baseFixturePreparer
Paul Duffin4ca67522021-03-20 01:25:12 +0000464 // The flattened and deduped list of simpleFixturePreparer pointers encapsulated within this
465 // composite preparer.
Paul Duffin35816122021-02-24 01:49:52 +0000466 preparers []*simpleFixturePreparer
467}
468
Paul Duffin4ca67522021-03-20 01:25:12 +0000469func (c *compositeFixturePreparer) list() []*simpleFixturePreparer {
470 return c.preparers
Paul Duffin35816122021-02-24 01:49:52 +0000471}
472
Paul Duffinff2aa692021-03-19 18:20:59 +0000473func newFixturePreparer(preparers []*simpleFixturePreparer) FixturePreparer {
474 if len(preparers) == 1 {
475 return preparers[0]
476 }
477 p := &compositeFixturePreparer{
478 preparers: preparers,
479 }
480 p.initBaseFixturePreparer(p)
481 return p
482}
483
Paul Duffin35816122021-02-24 01:49:52 +0000484// simpleFixturePreparer is a FixturePreparer that applies a function to a fixture.
485type simpleFixturePreparer struct {
Paul Duffinff2aa692021-03-19 18:20:59 +0000486 baseFixturePreparer
Paul Duffin35816122021-02-24 01:49:52 +0000487 function func(fixture *fixture)
488}
489
Paul Duffin4ca67522021-03-20 01:25:12 +0000490func (s *simpleFixturePreparer) list() []*simpleFixturePreparer {
491 return []*simpleFixturePreparer{s}
Paul Duffin35816122021-02-24 01:49:52 +0000492}
493
494func newSimpleFixturePreparer(preparer func(fixture *fixture)) FixturePreparer {
Paul Duffinff2aa692021-03-19 18:20:59 +0000495 p := &simpleFixturePreparer{function: preparer}
496 p.initBaseFixturePreparer(p)
497 return p
Paul Duffin35816122021-02-24 01:49:52 +0000498}
499
Paul Duffincfd33742021-02-27 11:59:02 +0000500// FixtureErrorHandler determines how to respond to errors reported by the code under test.
501//
502// Some possible responses:
Colin Crossd079e0b2022-08-16 10:27:33 -0700503// - Fail the test if any errors are reported, see FixtureExpectsNoErrors.
504// - Fail the test if at least one error that matches a pattern is not reported see
505// FixtureExpectsAtLeastOneErrorMatchingPattern
506// - Fail the test if any unexpected errors are reported.
Paul Duffincfd33742021-02-27 11:59:02 +0000507//
508// Although at the moment all the error handlers are implemented as simply a wrapper around a
509// function this is defined as an interface to allow future enhancements, e.g. provide different
510// ways other than patterns to match an error and to combine handlers together.
511type FixtureErrorHandler interface {
512 // CheckErrors checks the errors reported.
513 //
514 // The supplied result can be used to access the state of the code under test just as the main
515 // body of the test would but if any errors other than ones expected are reported the state may
516 // be indeterminate.
Paul Duffinc81854a2021-03-12 12:22:27 +0000517 CheckErrors(t *testing.T, result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000518}
519
520type simpleErrorHandler struct {
Paul Duffinc81854a2021-03-12 12:22:27 +0000521 function func(t *testing.T, result *TestResult)
Paul Duffincfd33742021-02-27 11:59:02 +0000522}
523
Paul Duffinc81854a2021-03-12 12:22:27 +0000524func (h simpleErrorHandler) CheckErrors(t *testing.T, result *TestResult) {
525 t.Helper()
526 h.function(t, result)
Paul Duffincfd33742021-02-27 11:59:02 +0000527}
528
529// The default fixture error handler.
530//
531// Will fail the test immediately if any errors are reported.
Paul Duffinea8a3862021-03-04 17:58:33 +0000532//
533// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
534// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000535var FixtureExpectsNoErrors = FixtureCustomErrorHandler(
Paul Duffinc81854a2021-03-12 12:22:27 +0000536 func(t *testing.T, result *TestResult) {
537 t.Helper()
538 FailIfErrored(t, result.Errs)
Paul Duffincfd33742021-02-27 11:59:02 +0000539 },
540)
541
Paul Duffin85034e92021-03-17 00:20:34 +0000542// FixtureIgnoreErrors ignores any errors.
543//
544// If this is used then it is the responsibility of the test to check the TestResult.Errs does not
545// contain any unexpected errors.
546var FixtureIgnoreErrors = FixtureCustomErrorHandler(func(t *testing.T, result *TestResult) {
547 // Ignore the errors
548})
549
Paul Duffincfd33742021-02-27 11:59:02 +0000550// FixtureExpectsAtLeastOneMatchingError returns an error handler that will cause the test to fail
551// if at least one error that matches the regular expression is not found.
552//
553// The test will be failed if:
554// * No errors are reported.
555// * One or more errors are reported but none match the pattern.
556//
557// The test will not fail if:
558// * Multiple errors are reported that do not match the pattern as long as one does match.
Paul Duffinea8a3862021-03-04 17:58:33 +0000559//
560// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
561// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000562func FixtureExpectsAtLeastOneErrorMatchingPattern(pattern string) FixtureErrorHandler {
Paul Duffinc81854a2021-03-12 12:22:27 +0000563 return FixtureCustomErrorHandler(func(t *testing.T, result *TestResult) {
564 t.Helper()
565 if !FailIfNoMatchingErrors(t, pattern, result.Errs) {
566 t.FailNow()
Paul Duffinea8a3862021-03-04 17:58:33 +0000567 }
Paul Duffincfd33742021-02-27 11:59:02 +0000568 })
569}
570
571// FixtureExpectsOneErrorToMatchPerPattern returns an error handler that will cause the test to fail
572// if there are any unexpected errors.
573//
574// The test will be failed if:
575// * The number of errors reported does not exactly match the patterns.
576// * One or more of the reported errors do not match a pattern.
577// * No patterns are provided and one or more errors are reported.
578//
579// The test will not fail if:
580// * One or more of the patterns does not match an error.
Paul Duffinea8a3862021-03-04 17:58:33 +0000581//
582// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
583// which the test is being run which means that the RunTest() method will not return.
Paul Duffincfd33742021-02-27 11:59:02 +0000584func FixtureExpectsAllErrorsToMatchAPattern(patterns []string) FixtureErrorHandler {
Paul Duffinc81854a2021-03-12 12:22:27 +0000585 return FixtureCustomErrorHandler(func(t *testing.T, result *TestResult) {
586 t.Helper()
587 CheckErrorsAgainstExpectations(t, result.Errs, patterns)
Paul Duffincfd33742021-02-27 11:59:02 +0000588 })
589}
590
Paul Duffin0fc6d322021-07-06 22:36:33 +0100591// FixtureExpectsOneErrorPattern returns an error handler that will cause the test to fail
592// if there is more than one error or the error does not match the pattern.
593//
594// If the test fails this handler will call `result.FailNow()` which will exit the goroutine within
595// which the test is being run which means that the RunTest() method will not return.
596func FixtureExpectsOneErrorPattern(pattern string) FixtureErrorHandler {
597 return FixtureCustomErrorHandler(func(t *testing.T, result *TestResult) {
598 t.Helper()
599 CheckErrorsAgainstExpectations(t, result.Errs, []string{pattern})
600 })
601}
602
Paul Duffincfd33742021-02-27 11:59:02 +0000603// FixtureCustomErrorHandler creates a custom error handler
Paul Duffinc81854a2021-03-12 12:22:27 +0000604func FixtureCustomErrorHandler(function func(t *testing.T, result *TestResult)) FixtureErrorHandler {
Paul Duffincfd33742021-02-27 11:59:02 +0000605 return simpleErrorHandler{
606 function: function,
607 }
608}
609
Paul Duffin35816122021-02-24 01:49:52 +0000610// Fixture defines the test environment.
611type Fixture interface {
Paul Duffinae542a52021-03-09 03:15:28 +0000612 // Config returns the fixture's configuration.
613 Config() Config
614
615 // Context returns the fixture's test context.
616 Context() *TestContext
617
618 // MockFS returns the fixture's mock filesystem.
619 MockFS() MockFS
620
Paul Duffincfd33742021-02-27 11:59:02 +0000621 // Run the test, checking any errors reported and returning a TestResult instance.
Paul Duffin35816122021-02-24 01:49:52 +0000622 RunTest() *TestResult
623}
624
Paul Duffin35816122021-02-24 01:49:52 +0000625// Struct to allow TestResult to embed a *TestContext and allow call forwarding to its methods.
626type testContext struct {
627 *TestContext
628}
629
630// The result of running a test.
631type TestResult struct {
Paul Duffin35816122021-02-24 01:49:52 +0000632 testContext
633
634 fixture *fixture
635 Config Config
Paul Duffin942481b2021-03-04 18:58:11 +0000636
637 // The errors that were reported during the test.
638 Errs []error
Paul Duffin78c36212021-03-16 23:57:12 +0000639
640 // The ninja deps is a list of the ninja files dependencies that were added by the modules and
641 // singletons via the *.AddNinjaFileDeps() methods.
642 NinjaDeps []string
Paul Duffin35816122021-02-24 01:49:52 +0000643}
644
Sam Delmerico2351eac2022-05-24 17:10:02 +0000645type TestPathContext struct {
646 *TestResult
647}
648
649var _ PathContext = &TestPathContext{}
650
651func (t *TestPathContext) Config() Config {
652 return t.TestResult.Config
653}
654
655func (t *TestPathContext) AddNinjaFileDeps(deps ...string) {
656 panic("unimplemented")
657}
658
Paul Duffin34a7fff2021-03-30 22:11:24 +0100659func createFixture(t *testing.T, buildDir string, preparers []*simpleFixturePreparer) Fixture {
Paul Duffindff5ff02021-03-15 15:42:40 +0000660 config := TestConfig(buildDir, nil, "", nil)
Paul Duffin35816122021-02-24 01:49:52 +0000661 ctx := NewTestContext(config)
662 fixture := &fixture{
Paul Duffin34a7fff2021-03-30 22:11:24 +0100663 preparers: preparers,
Paul Duffincff464f2021-03-19 18:13:46 +0000664 t: t,
665 config: config,
666 ctx: ctx,
667 mockFS: make(MockFS),
668 // Set the default error handler.
669 errorHandler: FixtureExpectsNoErrors,
Paul Duffin35816122021-02-24 01:49:52 +0000670 }
671
Paul Duffin34a7fff2021-03-30 22:11:24 +0100672 for _, preparer := range preparers {
Paul Duffin35816122021-02-24 01:49:52 +0000673 preparer.function(fixture)
674 }
675
676 return fixture
677}
678
Paul Duffinff2aa692021-03-19 18:20:59 +0000679type baseFixturePreparer struct {
680 self FixturePreparer
681}
682
683func (b *baseFixturePreparer) initBaseFixturePreparer(self FixturePreparer) {
684 b.self = self
685}
686
Paul Duffin34a7fff2021-03-30 22:11:24 +0100687func (b *baseFixturePreparer) Fixture(t *testing.T) Fixture {
688 return createFixture(t, t.TempDir(), b.self.list())
Paul Duffinff2aa692021-03-19 18:20:59 +0000689}
690
691func (b *baseFixturePreparer) ExtendWithErrorHandler(errorHandler FixtureErrorHandler) FixturePreparer {
Paul Duffin79abe572021-03-29 02:16:14 +0100692 return GroupFixturePreparers(b.self, newSimpleFixturePreparer(func(fixture *fixture) {
Paul Duffincff464f2021-03-19 18:13:46 +0000693 fixture.errorHandler = errorHandler
694 }))
Paul Duffincfd33742021-02-27 11:59:02 +0000695}
696
Paul Duffin55e740e2021-03-29 02:06:19 +0100697func (b *baseFixturePreparer) RunTest(t *testing.T) *TestResult {
Paul Duffin35816122021-02-24 01:49:52 +0000698 t.Helper()
Paul Duffin55e740e2021-03-29 02:06:19 +0100699 fixture := b.self.Fixture(t)
Paul Duffin35816122021-02-24 01:49:52 +0000700 return fixture.RunTest()
701}
702
Paul Duffinff2aa692021-03-19 18:20:59 +0000703func (b *baseFixturePreparer) RunTestWithBp(t *testing.T, bp string) *TestResult {
Paul Duffin35816122021-02-24 01:49:52 +0000704 t.Helper()
Paul Duffin55e740e2021-03-29 02:06:19 +0100705 return GroupFixturePreparers(b.self, FixtureWithRootAndroidBp(bp)).RunTest(t)
Paul Duffin35816122021-02-24 01:49:52 +0000706}
707
Paul Duffinff2aa692021-03-19 18:20:59 +0000708func (b *baseFixturePreparer) RunTestWithConfig(t *testing.T, config Config) *TestResult {
Paul Duffin72018ad2021-03-04 19:36:49 +0000709 t.Helper()
710 // Create the fixture as normal.
Paul Duffinff2aa692021-03-19 18:20:59 +0000711 fixture := b.self.Fixture(t).(*fixture)
Paul Duffin72018ad2021-03-04 19:36:49 +0000712
713 // Discard the mock filesystem as otherwise that will override the one in the config.
714 fixture.mockFS = nil
715
716 // Replace the config with the supplied one in the fixture.
717 fixture.config = config
718
719 // Ditto with config derived information in the TestContext.
720 ctx := fixture.ctx
721 ctx.config = config
722 ctx.SetFs(ctx.config.fs)
723 if ctx.config.mockBpList != "" {
724 ctx.SetModuleListFile(ctx.config.mockBpList)
725 }
726
727 return fixture.RunTest()
728}
729
Paul Duffin35816122021-02-24 01:49:52 +0000730type fixture struct {
Paul Duffin59251822021-03-15 22:20:12 +0000731 // The preparers used to create this fixture.
732 preparers []*simpleFixturePreparer
Paul Duffincfd33742021-02-27 11:59:02 +0000733
734 // The gotest state of the go test within which this was created.
735 t *testing.T
736
737 // The configuration prepared for this fixture.
738 config Config
739
740 // The test context prepared for this fixture.
741 ctx *TestContext
742
743 // The mock filesystem prepared for this fixture.
744 mockFS MockFS
745
746 // The error handler used to check the errors, if any, that are reported.
747 errorHandler FixtureErrorHandler
Paul Duffin64715ba2021-04-20 22:42:17 +0100748
749 // Debug mode status
750 debug bool
Paul Duffin35816122021-02-24 01:49:52 +0000751}
752
Paul Duffinae542a52021-03-09 03:15:28 +0000753func (f *fixture) Config() Config {
754 return f.config
755}
756
757func (f *fixture) Context() *TestContext {
758 return f.ctx
759}
760
761func (f *fixture) MockFS() MockFS {
762 return f.mockFS
763}
764
Paul Duffin35816122021-02-24 01:49:52 +0000765func (f *fixture) RunTest() *TestResult {
766 f.t.Helper()
767
Paul Duffin64715ba2021-04-20 22:42:17 +0100768 // If in debug mode output the state of the fixture before running the test.
769 if f.debug {
770 f.outputDebugState()
771 }
772
Paul Duffin35816122021-02-24 01:49:52 +0000773 ctx := f.ctx
774
Paul Duffin72018ad2021-03-04 19:36:49 +0000775 // Do not use the fixture's mockFS to initialize the config's mock file system if it has been
776 // cleared by RunTestWithConfig.
777 if f.mockFS != nil {
778 // The TestConfig() method assumes that the mock filesystem is available when creating so
779 // creates the mock file system immediately. Similarly, the NewTestContext(Config) method
780 // assumes that the supplied Config's FileSystem has been properly initialized before it is
781 // called and so it takes its own reference to the filesystem. However, fixtures create the
782 // Config and TestContext early so they can be modified by preparers at which time the mockFS
783 // has not been populated (because it too is modified by preparers). So, this reinitializes the
784 // Config and TestContext's FileSystem using the now populated mockFS.
785 f.config.mockFileSystem("", f.mockFS)
786
787 ctx.SetFs(ctx.config.fs)
788 if ctx.config.mockBpList != "" {
789 ctx.SetModuleListFile(ctx.config.mockBpList)
790 }
Paul Duffin35816122021-02-24 01:49:52 +0000791 }
792
793 ctx.Register()
Paul Duffin78c36212021-03-16 23:57:12 +0000794 var ninjaDeps []string
795 extraNinjaDeps, errs := ctx.ParseBlueprintsFiles("ignored")
Paul Duffincfd33742021-02-27 11:59:02 +0000796 if len(errs) == 0 {
Paul Duffin78c36212021-03-16 23:57:12 +0000797 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
798 extraNinjaDeps, errs = ctx.PrepareBuildActions(f.config)
799 if len(errs) == 0 {
800 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
801 }
Paul Duffincfd33742021-02-27 11:59:02 +0000802 }
Paul Duffin35816122021-02-24 01:49:52 +0000803
804 result := &TestResult{
Paul Duffin35816122021-02-24 01:49:52 +0000805 testContext: testContext{ctx},
806 fixture: f,
807 Config: f.config,
Paul Duffin942481b2021-03-04 18:58:11 +0000808 Errs: errs,
Paul Duffin78c36212021-03-16 23:57:12 +0000809 NinjaDeps: ninjaDeps,
Paul Duffin35816122021-02-24 01:49:52 +0000810 }
Paul Duffincfd33742021-02-27 11:59:02 +0000811
Paul Duffinc81854a2021-03-12 12:22:27 +0000812 f.errorHandler.CheckErrors(f.t, result)
Paul Duffincfd33742021-02-27 11:59:02 +0000813
Paul Duffin35816122021-02-24 01:49:52 +0000814 return result
815}
816
Paul Duffin64715ba2021-04-20 22:42:17 +0100817func (f *fixture) outputDebugState() {
818 fmt.Printf("Begin Fixture State for %s\n", f.t.Name())
819 if len(f.config.env) == 0 {
820 fmt.Printf(" Fixture Env is empty\n")
821 } else {
822 fmt.Printf(" Begin Env\n")
823 for k, v := range f.config.env {
824 fmt.Printf(" - %s=%s\n", k, v)
825 }
826 fmt.Printf(" End Env\n")
827 }
828 if len(f.mockFS) == 0 {
829 fmt.Printf(" Mock FS is empty\n")
830 } else {
831 fmt.Printf(" Begin Mock FS Contents\n")
832 for p, c := range f.mockFS {
833 if c == nil {
834 fmt.Printf("\n - %s: nil\n", p)
835 } else {
836 contents := string(c)
837 separator := " ========================================================================"
838 fmt.Printf(" - %s\n%s\n", p, separator)
839 for i, line := range strings.Split(contents, "\n") {
840 fmt.Printf(" %6d: %s\n", i+1, line)
841 }
842 fmt.Printf("%s\n", separator)
843 }
844 }
845 fmt.Printf(" End Mock FS Contents\n")
846 }
847 fmt.Printf("End Fixture State for %s\n", f.t.Name())
848}
849
Paul Duffin35816122021-02-24 01:49:52 +0000850// NormalizePathForTesting removes the test invocation specific build directory from the supplied
851// path.
852//
853// If the path is within the build directory (e.g. an OutputPath) then this returns the relative
854// path to avoid tests having to deal with the dynamically generated build directory.
855//
856// Otherwise, this returns the supplied path as it is almost certainly a source path that is
857// relative to the root of the source tree.
858//
859// Even though some information is removed from some paths and not others it should be possible to
860// differentiate between them by the paths themselves, e.g. output paths will likely include
861// ".intermediates" but source paths won't.
862func (r *TestResult) NormalizePathForTesting(path Path) string {
863 pathContext := PathContextForTesting(r.Config)
864 pathAsString := path.String()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200865 if rel, isRel := MaybeRel(pathContext, r.Config.SoongOutDir(), pathAsString); isRel {
Paul Duffin35816122021-02-24 01:49:52 +0000866 return rel
867 }
868 return pathAsString
869}
870
871// NormalizePathsForTesting normalizes each path in the supplied list and returns their normalized
872// forms.
873func (r *TestResult) NormalizePathsForTesting(paths Paths) []string {
874 var result []string
875 for _, path := range paths {
876 result = append(result, r.NormalizePathForTesting(path))
877 }
878 return result
879}
880
Paul Duffin59251822021-03-15 22:20:12 +0000881// Preparer will return a FixturePreparer encapsulating all the preparers used to create the fixture
882// that produced this result.
883//
884// e.g. assuming that this result was created by running:
Colin Crossd079e0b2022-08-16 10:27:33 -0700885//
886// GroupFixturePreparers(preparer1, preparer2, preparer3).RunTest(t)
Paul Duffin59251822021-03-15 22:20:12 +0000887//
888// Then this method will be equivalent to running:
Colin Crossd079e0b2022-08-16 10:27:33 -0700889//
890// GroupFixturePreparers(preparer1, preparer2, preparer3)
Paul Duffin59251822021-03-15 22:20:12 +0000891//
892// This is intended for use by tests whose output is Android.bp files to verify that those files
893// are valid, e.g. tests of the snapshots produced by the sdk module type.
894func (r *TestResult) Preparer() FixturePreparer {
Paul Duffinff2aa692021-03-19 18:20:59 +0000895 return newFixturePreparer(r.fixture.preparers)
Paul Duffin59251822021-03-15 22:20:12 +0000896}
897
Paul Duffin35816122021-02-24 01:49:52 +0000898// Module returns the module with the specific name and of the specified variant.
899func (r *TestResult) Module(name string, variant string) Module {
900 return r.ModuleForTests(name, variant).Module()
901}