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