blob: f32d745c2bff8ba28ea6ef4bf9143e4990824b7a [file] [log] [blame]
Colin Crosscec81712017-07-13 14:43:27 -07001// Copyright 2017 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 "fmt"
Paul Duffin9b478b02019-12-10 13:41:51 +000019 "path/filepath"
Logan Chienee97c3e2018-03-12 16:34:26 +080020 "regexp"
Martin Stjernholm4c021242020-05-13 01:13:50 +010021 "sort"
Colin Crosscec81712017-07-13 14:43:27 -070022 "strings"
Logan Chien42039712018-03-12 16:29:17 +080023 "testing"
Colin Crosscec81712017-07-13 14:43:27 -070024
25 "github.com/google/blueprint"
26)
27
28func NewTestContext() *TestContext {
Jeff Gaston088e29e2017-11-29 16:47:17 -080029 namespaceExportFilter := func(namespace *Namespace) bool {
30 return true
31 }
Jeff Gastonb274ed32017-12-01 17:10:33 -080032
33 nameResolver := NewNameResolver(namespaceExportFilter)
34 ctx := &TestContext{
Colin Cross4c83e5c2019-02-25 14:54:28 -080035 Context: &Context{blueprint.NewContext()},
Jeff Gastonb274ed32017-12-01 17:10:33 -080036 NameResolver: nameResolver,
37 }
38
39 ctx.SetNameInterface(nameResolver)
Jeff Gaston088e29e2017-11-29 16:47:17 -080040
Colin Cross1b488422019-03-04 22:33:56 -080041 ctx.postDeps = append(ctx.postDeps, registerPathDepsMutator)
42
Jeff Gaston088e29e2017-11-29 16:47:17 -080043 return ctx
Colin Crosscec81712017-07-13 14:43:27 -070044}
45
Colin Crossae4c6182017-09-15 17:33:55 -070046func NewTestArchContext() *TestContext {
47 ctx := NewTestContext()
48 ctx.preDeps = append(ctx.preDeps, registerArchMutator)
49 return ctx
50}
51
Colin Crosscec81712017-07-13 14:43:27 -070052type TestContext struct {
Colin Cross4c83e5c2019-02-25 14:54:28 -080053 *Context
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000054 preArch, preDeps, postDeps, finalDeps []RegisterMutatorFunc
55 NameResolver *NameResolver
56 config Config
Colin Crosscec81712017-07-13 14:43:27 -070057}
58
59func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
60 ctx.preArch = append(ctx.preArch, f)
61}
62
Paul Duffina80ef842020-01-14 12:09:36 +000063func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
64 // Register mutator function as normal for testing.
65 ctx.PreArchMutators(f)
66}
67
Colin Crosscec81712017-07-13 14:43:27 -070068func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
69 ctx.preDeps = append(ctx.preDeps, f)
70}
71
72func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
73 ctx.postDeps = append(ctx.postDeps, f)
74}
75
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000076func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) {
77 ctx.finalDeps = append(ctx.finalDeps, f)
78}
79
Colin Cross98be1bb2019-12-13 20:41:13 -080080func (ctx *TestContext) Register(config Config) {
81 ctx.SetFs(config.fs)
82 if config.mockBpList != "" {
83 ctx.SetModuleListFile(config.mockBpList)
84 }
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000085 registerMutators(ctx.Context.Context, ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.finalDeps)
Colin Crosscec81712017-07-13 14:43:27 -070086
Colin Cross4b49b762019-11-22 15:25:03 -080087 ctx.RegisterSingletonType("env", EnvSingleton)
Colin Cross31a738b2019-12-30 18:45:15 -080088
89 ctx.config = config
90}
91
92func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) {
93 // This function adapts the old style ParseFileList calls that are spread throughout the tests
94 // to the new style that takes a config.
95 return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config)
96}
97
98func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) {
99 // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the
100 // tests to the new style that takes a config.
101 return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config)
Colin Cross4b49b762019-11-22 15:25:03 -0800102}
103
104func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
105 ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
106}
107
108func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
109 ctx.Context.RegisterSingletonType(name, SingletonFactoryAdaptor(factory))
Colin Crosscec81712017-07-13 14:43:27 -0700110}
111
112func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
113 var module Module
114 ctx.VisitAllModules(func(m blueprint.Module) {
115 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
116 module = m.(Module)
117 }
118 })
119
120 if module == nil {
Jeff Gaston294356f2017-09-27 17:05:30 -0700121 // find all the modules that do exist
Colin Crossbeae6ec2020-08-11 12:02:11 -0700122 var allModuleNames []string
123 var allVariants []string
Jeff Gaston294356f2017-09-27 17:05:30 -0700124 ctx.VisitAllModules(func(m blueprint.Module) {
Colin Crossbeae6ec2020-08-11 12:02:11 -0700125 allModuleNames = append(allModuleNames, ctx.ModuleName(m))
126 if ctx.ModuleName(m) == name {
127 allVariants = append(allVariants, ctx.ModuleSubDir(m))
128 }
Jeff Gaston294356f2017-09-27 17:05:30 -0700129 })
Martin Stjernholm4c021242020-05-13 01:13:50 +0100130 sort.Strings(allModuleNames)
Colin Crossbeae6ec2020-08-11 12:02:11 -0700131 sort.Strings(allVariants)
Jeff Gaston294356f2017-09-27 17:05:30 -0700132
Colin Crossbeae6ec2020-08-11 12:02:11 -0700133 if len(allVariants) == 0 {
134 panic(fmt.Errorf("failed to find module %q. All modules:\n %s",
135 name, strings.Join(allModuleNames, "\n ")))
136 } else {
137 panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s",
138 name, variant, strings.Join(allVariants, "\n ")))
139 }
Colin Crosscec81712017-07-13 14:43:27 -0700140 }
141
142 return TestingModule{module}
143}
144
Jiyong Park37b25202018-07-11 10:49:27 +0900145func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
146 var variants []string
147 ctx.VisitAllModules(func(m blueprint.Module) {
148 if ctx.ModuleName(m) == name {
149 variants = append(variants, ctx.ModuleSubDir(m))
150 }
151 })
152 return variants
153}
154
Colin Cross4c83e5c2019-02-25 14:54:28 -0800155// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
156func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
157 allSingletonNames := []string{}
158 for _, s := range ctx.Singletons() {
159 n := ctx.SingletonName(s)
160 if n == name {
161 return TestingSingleton{
162 singleton: s.(*singletonAdaptor).Singleton,
163 provider: s.(testBuildProvider),
164 }
165 }
166 allSingletonNames = append(allSingletonNames, n)
167 }
168
169 panic(fmt.Errorf("failed to find singleton %q."+
170 "\nall singletons: %v", name, allSingletonNames))
171}
172
Colin Cross4c83e5c2019-02-25 14:54:28 -0800173type testBuildProvider interface {
174 BuildParamsForTests() []BuildParams
175 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
176}
177
178type TestingBuildParams struct {
179 BuildParams
180 RuleParams blueprint.RuleParams
181}
182
183func newTestingBuildParams(provider testBuildProvider, bparams BuildParams) TestingBuildParams {
184 return TestingBuildParams{
185 BuildParams: bparams,
186 RuleParams: provider.RuleParamsForTests()[bparams.Rule],
187 }
188}
189
190func maybeBuildParamsFromRule(provider testBuildProvider, rule string) TestingBuildParams {
191 for _, p := range provider.BuildParamsForTests() {
192 if strings.Contains(p.Rule.String(), rule) {
193 return newTestingBuildParams(provider, p)
194 }
195 }
196 return TestingBuildParams{}
197}
198
199func buildParamsFromRule(provider testBuildProvider, rule string) TestingBuildParams {
200 p := maybeBuildParamsFromRule(provider, rule)
201 if p.Rule == nil {
202 panic(fmt.Errorf("couldn't find rule %q", rule))
203 }
204 return p
205}
206
207func maybeBuildParamsFromDescription(provider testBuildProvider, desc string) TestingBuildParams {
208 for _, p := range provider.BuildParamsForTests() {
Colin Crossb88b3c52019-06-10 15:15:17 -0700209 if strings.Contains(p.Description, desc) {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800210 return newTestingBuildParams(provider, p)
211 }
212 }
213 return TestingBuildParams{}
214}
215
216func buildParamsFromDescription(provider testBuildProvider, desc string) TestingBuildParams {
217 p := maybeBuildParamsFromDescription(provider, desc)
218 if p.Rule == nil {
219 panic(fmt.Errorf("couldn't find description %q", desc))
220 }
221 return p
222}
223
224func maybeBuildParamsFromOutput(provider testBuildProvider, file string) (TestingBuildParams, []string) {
225 var searchedOutputs []string
226 for _, p := range provider.BuildParamsForTests() {
227 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700228 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800229 if p.Output != nil {
230 outputs = append(outputs, p.Output)
231 }
232 for _, f := range outputs {
233 if f.String() == file || f.Rel() == file {
234 return newTestingBuildParams(provider, p), nil
235 }
236 searchedOutputs = append(searchedOutputs, f.Rel())
237 }
238 }
239 return TestingBuildParams{}, searchedOutputs
240}
241
242func buildParamsFromOutput(provider testBuildProvider, file string) TestingBuildParams {
243 p, searchedOutputs := maybeBuildParamsFromOutput(provider, file)
244 if p.Rule == nil {
245 panic(fmt.Errorf("couldn't find output %q.\nall outputs: %v",
246 file, searchedOutputs))
247 }
248 return p
249}
250
251func allOutputs(provider testBuildProvider) []string {
252 var outputFullPaths []string
253 for _, p := range provider.BuildParamsForTests() {
254 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700255 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800256 if p.Output != nil {
257 outputs = append(outputs, p.Output)
258 }
259 outputFullPaths = append(outputFullPaths, outputs.Strings()...)
260 }
261 return outputFullPaths
262}
263
Colin Crossb77ffc42019-01-05 22:09:19 -0800264// TestingModule is wrapper around an android.Module that provides methods to find information about individual
265// ctx.Build parameters for verification in tests.
Colin Crosscec81712017-07-13 14:43:27 -0700266type TestingModule struct {
267 module Module
268}
269
Colin Crossb77ffc42019-01-05 22:09:19 -0800270// Module returns the Module wrapped by the TestingModule.
Colin Crosscec81712017-07-13 14:43:27 -0700271func (m TestingModule) Module() Module {
272 return m.module
273}
274
Colin Crossb77ffc42019-01-05 22:09:19 -0800275// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
276// BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800277func (m TestingModule) MaybeRule(rule string) TestingBuildParams {
278 return maybeBuildParamsFromRule(m.module, rule)
Colin Crosscec81712017-07-13 14:43:27 -0700279}
280
Colin Crossb77ffc42019-01-05 22:09:19 -0800281// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800282func (m TestingModule) Rule(rule string) TestingBuildParams {
283 return buildParamsFromRule(m.module, rule)
Colin Crossb77ffc42019-01-05 22:09:19 -0800284}
285
286// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
287// BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800288func (m TestingModule) MaybeDescription(desc string) TestingBuildParams {
289 return maybeBuildParamsFromDescription(m.module, desc)
Nan Zhanged19fc32017-10-19 13:06:22 -0700290}
291
Colin Crossb77ffc42019-01-05 22:09:19 -0800292// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
293// found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800294func (m TestingModule) Description(desc string) TestingBuildParams {
295 return buildParamsFromDescription(m.module, desc)
Colin Crossb77ffc42019-01-05 22:09:19 -0800296}
297
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800298// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
Colin Crossb77ffc42019-01-05 22:09:19 -0800299// value matches the provided string. Returns an empty BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800300func (m TestingModule) MaybeOutput(file string) TestingBuildParams {
301 p, _ := maybeBuildParamsFromOutput(m.module, file)
Colin Crossb77ffc42019-01-05 22:09:19 -0800302 return p
303}
304
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800305// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
Colin Crossb77ffc42019-01-05 22:09:19 -0800306// value matches the provided string. Panics if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800307func (m TestingModule) Output(file string) TestingBuildParams {
308 return buildParamsFromOutput(m.module, file)
Colin Crosscec81712017-07-13 14:43:27 -0700309}
Logan Chien42039712018-03-12 16:29:17 +0800310
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800311// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
312func (m TestingModule) AllOutputs() []string {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800313 return allOutputs(m.module)
314}
315
316// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
317// ctx.Build parameters for verification in tests.
318type TestingSingleton struct {
319 singleton Singleton
320 provider testBuildProvider
321}
322
323// Singleton returns the Singleton wrapped by the TestingSingleton.
324func (s TestingSingleton) Singleton() Singleton {
325 return s.singleton
326}
327
328// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
329// BuildParams if no rule is found.
330func (s TestingSingleton) MaybeRule(rule string) TestingBuildParams {
331 return maybeBuildParamsFromRule(s.provider, rule)
332}
333
334// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
335func (s TestingSingleton) Rule(rule string) TestingBuildParams {
336 return buildParamsFromRule(s.provider, rule)
337}
338
339// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
340// BuildParams if no rule is found.
341func (s TestingSingleton) MaybeDescription(desc string) TestingBuildParams {
342 return maybeBuildParamsFromDescription(s.provider, desc)
343}
344
345// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
346// found.
347func (s TestingSingleton) Description(desc string) TestingBuildParams {
348 return buildParamsFromDescription(s.provider, desc)
349}
350
351// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
352// value matches the provided string. Returns an empty BuildParams if no rule is found.
353func (s TestingSingleton) MaybeOutput(file string) TestingBuildParams {
354 p, _ := maybeBuildParamsFromOutput(s.provider, file)
355 return p
356}
357
358// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
359// value matches the provided string. Panics if no rule is found.
360func (s TestingSingleton) Output(file string) TestingBuildParams {
361 return buildParamsFromOutput(s.provider, file)
362}
363
364// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
365func (s TestingSingleton) AllOutputs() []string {
366 return allOutputs(s.provider)
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800367}
368
Logan Chien42039712018-03-12 16:29:17 +0800369func FailIfErrored(t *testing.T, errs []error) {
370 t.Helper()
371 if len(errs) > 0 {
372 for _, err := range errs {
373 t.Error(err)
374 }
375 t.FailNow()
376 }
377}
Logan Chienee97c3e2018-03-12 16:34:26 +0800378
379func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) {
380 t.Helper()
381
382 matcher, err := regexp.Compile(pattern)
383 if err != nil {
384 t.Errorf("failed to compile regular expression %q because %s", pattern, err)
385 }
386
387 found := false
388 for _, err := range errs {
389 if matcher.FindStringIndex(err.Error()) != nil {
390 found = true
391 break
392 }
393 }
394 if !found {
395 t.Errorf("missing the expected error %q (checked %d error(s))", pattern, len(errs))
396 for i, err := range errs {
397 t.Errorf("errs[%d] = %s", i, err)
398 }
399 }
400}
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700401
Paul Duffin91e38192019-08-05 15:07:57 +0100402func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
403 t.Helper()
404
405 if expectedErrorPatterns == nil {
406 FailIfErrored(t, errs)
407 } else {
408 for _, expectedError := range expectedErrorPatterns {
409 FailIfNoMatchingErrors(t, expectedError, errs)
410 }
411 if len(errs) > len(expectedErrorPatterns) {
412 t.Errorf("additional errors found, expected %d, found %d",
413 len(expectedErrorPatterns), len(errs))
414 for i, expectedError := range expectedErrorPatterns {
415 t.Errorf("expectedErrors[%d] = %s", i, expectedError)
416 }
417 for i, err := range errs {
418 t.Errorf("errs[%d] = %s", i, err)
419 }
420 }
421 }
422
423}
424
Paul Duffin8c3fec42020-03-04 20:15:08 +0000425func SetInMakeForTests(config Config) {
426 config.inMake = true
427}
428
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900429func AndroidMkEntriesForTest(t *testing.T, config Config, bpPath string, mod blueprint.Module) []AndroidMkEntries {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700430 var p AndroidMkEntriesProvider
431 var ok bool
432 if p, ok = mod.(AndroidMkEntriesProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +0100433 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700434 }
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900435
436 entriesList := p.AndroidMkEntries()
437 for i, _ := range entriesList {
438 entriesList[i].fillInEntries(config, bpPath, mod)
439 }
440 return entriesList
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700441}
Jooyung Han12df5fb2019-07-11 16:18:47 +0900442
443func AndroidMkDataForTest(t *testing.T, config Config, bpPath string, mod blueprint.Module) AndroidMkData {
444 var p AndroidMkDataProvider
445 var ok bool
446 if p, ok = mod.(AndroidMkDataProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +0100447 t.Errorf("module does not implement AndroidMkDataProvider: " + mod.Name())
Jooyung Han12df5fb2019-07-11 16:18:47 +0900448 }
449 data := p.AndroidMk()
450 data.fillInData(config, bpPath, mod)
451 return data
452}
Paul Duffin9b478b02019-12-10 13:41:51 +0000453
454// Normalize the path for testing.
455//
456// If the path is relative to the build directory then return the relative path
457// to avoid tests having to deal with the dynamically generated build directory.
458//
459// Otherwise, return the supplied path as it is almost certainly a source path
460// that is relative to the root of the source tree.
461//
462// The build and source paths should be distinguishable based on their contents.
463func NormalizePathForTesting(path Path) string {
464 p := path.String()
465 if w, ok := path.(WritablePath); ok {
466 rel, err := filepath.Rel(w.buildDir(), p)
467 if err != nil {
468 panic(err)
469 }
470 return rel
471 }
472 return p
473}
474
475func NormalizePathsForTesting(paths Paths) []string {
476 var result []string
477 for _, path := range paths {
478 relative := NormalizePathForTesting(path)
479 result = append(result, relative)
480 }
481 return result
482}