blob: c07af7f324e9a71d32fc5d5168283e6e6d39b6d6 [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"
Colin Crosscec81712017-07-13 14:43:27 -070021 "strings"
Logan Chien42039712018-03-12 16:29:17 +080022 "testing"
Colin Crosscec81712017-07-13 14:43:27 -070023
24 "github.com/google/blueprint"
25)
26
27func NewTestContext() *TestContext {
Jeff Gaston088e29e2017-11-29 16:47:17 -080028 namespaceExportFilter := func(namespace *Namespace) bool {
29 return true
30 }
Jeff Gastonb274ed32017-12-01 17:10:33 -080031
32 nameResolver := NewNameResolver(namespaceExportFilter)
33 ctx := &TestContext{
Colin Cross4c83e5c2019-02-25 14:54:28 -080034 Context: &Context{blueprint.NewContext()},
Jeff Gastonb274ed32017-12-01 17:10:33 -080035 NameResolver: nameResolver,
36 }
37
38 ctx.SetNameInterface(nameResolver)
Jeff Gaston088e29e2017-11-29 16:47:17 -080039
Colin Cross1b488422019-03-04 22:33:56 -080040 ctx.postDeps = append(ctx.postDeps, registerPathDepsMutator)
41
Jeff Gaston088e29e2017-11-29 16:47:17 -080042 return ctx
Colin Crosscec81712017-07-13 14:43:27 -070043}
44
Colin Crossae4c6182017-09-15 17:33:55 -070045func NewTestArchContext() *TestContext {
46 ctx := NewTestContext()
47 ctx.preDeps = append(ctx.preDeps, registerArchMutator)
48 return ctx
49}
50
Colin Crosscec81712017-07-13 14:43:27 -070051type TestContext struct {
Colin Cross4c83e5c2019-02-25 14:54:28 -080052 *Context
Colin Crosscec81712017-07-13 14:43:27 -070053 preArch, preDeps, postDeps []RegisterMutatorFunc
Jeff Gastonb274ed32017-12-01 17:10:33 -080054 NameResolver *NameResolver
Colin Cross31a738b2019-12-30 18:45:15 -080055 config Config
Colin Crosscec81712017-07-13 14:43:27 -070056}
57
58func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
59 ctx.preArch = append(ctx.preArch, f)
60}
61
Paul Duffina80ef842020-01-14 12:09:36 +000062func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) {
63 // Register mutator function as normal for testing.
64 ctx.PreArchMutators(f)
65}
66
Colin Crosscec81712017-07-13 14:43:27 -070067func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
68 ctx.preDeps = append(ctx.preDeps, f)
69}
70
71func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
72 ctx.postDeps = append(ctx.postDeps, f)
73}
74
Colin Cross98be1bb2019-12-13 20:41:13 -080075func (ctx *TestContext) Register(config Config) {
76 ctx.SetFs(config.fs)
77 if config.mockBpList != "" {
78 ctx.SetModuleListFile(config.mockBpList)
79 }
Colin Cross4c83e5c2019-02-25 14:54:28 -080080 registerMutators(ctx.Context.Context, ctx.preArch, ctx.preDeps, ctx.postDeps)
Colin Crosscec81712017-07-13 14:43:27 -070081
Colin Cross4b49b762019-11-22 15:25:03 -080082 ctx.RegisterSingletonType("env", EnvSingleton)
Colin Cross31a738b2019-12-30 18:45:15 -080083
84 ctx.config = config
85}
86
87func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) {
88 // This function adapts the old style ParseFileList calls that are spread throughout the tests
89 // to the new style that takes a config.
90 return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config)
91}
92
93func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) {
94 // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the
95 // tests to the new style that takes a config.
96 return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config)
Colin Cross4b49b762019-11-22 15:25:03 -080097}
98
99func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
100 ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
101}
102
103func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
104 ctx.Context.RegisterSingletonType(name, SingletonFactoryAdaptor(factory))
Colin Crosscec81712017-07-13 14:43:27 -0700105}
106
107func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
108 var module Module
109 ctx.VisitAllModules(func(m blueprint.Module) {
110 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
111 module = m.(Module)
112 }
113 })
114
115 if module == nil {
Jeff Gaston294356f2017-09-27 17:05:30 -0700116 // find all the modules that do exist
117 allModuleNames := []string{}
118 ctx.VisitAllModules(func(m blueprint.Module) {
119 allModuleNames = append(allModuleNames, m.(Module).Name()+"("+ctx.ModuleSubDir(m)+")")
120 })
121
122 panic(fmt.Errorf("failed to find module %q variant %q."+
123 "\nall modules: %v", name, variant, allModuleNames))
Colin Crosscec81712017-07-13 14:43:27 -0700124 }
125
126 return TestingModule{module}
127}
128
Jiyong Park37b25202018-07-11 10:49:27 +0900129func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
130 var variants []string
131 ctx.VisitAllModules(func(m blueprint.Module) {
132 if ctx.ModuleName(m) == name {
133 variants = append(variants, ctx.ModuleSubDir(m))
134 }
135 })
136 return variants
137}
138
Colin Cross4c83e5c2019-02-25 14:54:28 -0800139// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
140func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
141 allSingletonNames := []string{}
142 for _, s := range ctx.Singletons() {
143 n := ctx.SingletonName(s)
144 if n == name {
145 return TestingSingleton{
146 singleton: s.(*singletonAdaptor).Singleton,
147 provider: s.(testBuildProvider),
148 }
149 }
150 allSingletonNames = append(allSingletonNames, n)
151 }
152
153 panic(fmt.Errorf("failed to find singleton %q."+
154 "\nall singletons: %v", name, allSingletonNames))
155}
156
Colin Cross4c83e5c2019-02-25 14:54:28 -0800157type testBuildProvider interface {
158 BuildParamsForTests() []BuildParams
159 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
160}
161
162type TestingBuildParams struct {
163 BuildParams
164 RuleParams blueprint.RuleParams
165}
166
167func newTestingBuildParams(provider testBuildProvider, bparams BuildParams) TestingBuildParams {
168 return TestingBuildParams{
169 BuildParams: bparams,
170 RuleParams: provider.RuleParamsForTests()[bparams.Rule],
171 }
172}
173
174func maybeBuildParamsFromRule(provider testBuildProvider, rule string) TestingBuildParams {
175 for _, p := range provider.BuildParamsForTests() {
176 if strings.Contains(p.Rule.String(), rule) {
177 return newTestingBuildParams(provider, p)
178 }
179 }
180 return TestingBuildParams{}
181}
182
183func buildParamsFromRule(provider testBuildProvider, rule string) TestingBuildParams {
184 p := maybeBuildParamsFromRule(provider, rule)
185 if p.Rule == nil {
186 panic(fmt.Errorf("couldn't find rule %q", rule))
187 }
188 return p
189}
190
191func maybeBuildParamsFromDescription(provider testBuildProvider, desc string) TestingBuildParams {
192 for _, p := range provider.BuildParamsForTests() {
Colin Crossb88b3c52019-06-10 15:15:17 -0700193 if strings.Contains(p.Description, desc) {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800194 return newTestingBuildParams(provider, p)
195 }
196 }
197 return TestingBuildParams{}
198}
199
200func buildParamsFromDescription(provider testBuildProvider, desc string) TestingBuildParams {
201 p := maybeBuildParamsFromDescription(provider, desc)
202 if p.Rule == nil {
203 panic(fmt.Errorf("couldn't find description %q", desc))
204 }
205 return p
206}
207
208func maybeBuildParamsFromOutput(provider testBuildProvider, file string) (TestingBuildParams, []string) {
209 var searchedOutputs []string
210 for _, p := range provider.BuildParamsForTests() {
211 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700212 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800213 if p.Output != nil {
214 outputs = append(outputs, p.Output)
215 }
216 for _, f := range outputs {
217 if f.String() == file || f.Rel() == file {
218 return newTestingBuildParams(provider, p), nil
219 }
220 searchedOutputs = append(searchedOutputs, f.Rel())
221 }
222 }
223 return TestingBuildParams{}, searchedOutputs
224}
225
226func buildParamsFromOutput(provider testBuildProvider, file string) TestingBuildParams {
227 p, searchedOutputs := maybeBuildParamsFromOutput(provider, file)
228 if p.Rule == nil {
229 panic(fmt.Errorf("couldn't find output %q.\nall outputs: %v",
230 file, searchedOutputs))
231 }
232 return p
233}
234
235func allOutputs(provider testBuildProvider) []string {
236 var outputFullPaths []string
237 for _, p := range provider.BuildParamsForTests() {
238 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700239 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800240 if p.Output != nil {
241 outputs = append(outputs, p.Output)
242 }
243 outputFullPaths = append(outputFullPaths, outputs.Strings()...)
244 }
245 return outputFullPaths
246}
247
Colin Crossb77ffc42019-01-05 22:09:19 -0800248// TestingModule is wrapper around an android.Module that provides methods to find information about individual
249// ctx.Build parameters for verification in tests.
Colin Crosscec81712017-07-13 14:43:27 -0700250type TestingModule struct {
251 module Module
252}
253
Colin Crossb77ffc42019-01-05 22:09:19 -0800254// Module returns the Module wrapped by the TestingModule.
Colin Crosscec81712017-07-13 14:43:27 -0700255func (m TestingModule) Module() Module {
256 return m.module
257}
258
Colin Crossb77ffc42019-01-05 22:09:19 -0800259// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
260// BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800261func (m TestingModule) MaybeRule(rule string) TestingBuildParams {
262 return maybeBuildParamsFromRule(m.module, rule)
Colin Crosscec81712017-07-13 14:43:27 -0700263}
264
Colin Crossb77ffc42019-01-05 22:09:19 -0800265// 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 -0800266func (m TestingModule) Rule(rule string) TestingBuildParams {
267 return buildParamsFromRule(m.module, rule)
Colin Crossb77ffc42019-01-05 22:09:19 -0800268}
269
270// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
271// BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800272func (m TestingModule) MaybeDescription(desc string) TestingBuildParams {
273 return maybeBuildParamsFromDescription(m.module, desc)
Nan Zhanged19fc32017-10-19 13:06:22 -0700274}
275
Colin Crossb77ffc42019-01-05 22:09:19 -0800276// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
277// found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800278func (m TestingModule) Description(desc string) TestingBuildParams {
279 return buildParamsFromDescription(m.module, desc)
Colin Crossb77ffc42019-01-05 22:09:19 -0800280}
281
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800282// 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 -0800283// value matches the provided string. Returns an empty BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800284func (m TestingModule) MaybeOutput(file string) TestingBuildParams {
285 p, _ := maybeBuildParamsFromOutput(m.module, file)
Colin Crossb77ffc42019-01-05 22:09:19 -0800286 return p
287}
288
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800289// 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 -0800290// value matches the provided string. Panics if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800291func (m TestingModule) Output(file string) TestingBuildParams {
292 return buildParamsFromOutput(m.module, file)
Colin Crosscec81712017-07-13 14:43:27 -0700293}
Logan Chien42039712018-03-12 16:29:17 +0800294
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800295// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
296func (m TestingModule) AllOutputs() []string {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800297 return allOutputs(m.module)
298}
299
300// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
301// ctx.Build parameters for verification in tests.
302type TestingSingleton struct {
303 singleton Singleton
304 provider testBuildProvider
305}
306
307// Singleton returns the Singleton wrapped by the TestingSingleton.
308func (s TestingSingleton) Singleton() Singleton {
309 return s.singleton
310}
311
312// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
313// BuildParams if no rule is found.
314func (s TestingSingleton) MaybeRule(rule string) TestingBuildParams {
315 return maybeBuildParamsFromRule(s.provider, rule)
316}
317
318// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
319func (s TestingSingleton) Rule(rule string) TestingBuildParams {
320 return buildParamsFromRule(s.provider, rule)
321}
322
323// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
324// BuildParams if no rule is found.
325func (s TestingSingleton) MaybeDescription(desc string) TestingBuildParams {
326 return maybeBuildParamsFromDescription(s.provider, desc)
327}
328
329// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
330// found.
331func (s TestingSingleton) Description(desc string) TestingBuildParams {
332 return buildParamsFromDescription(s.provider, desc)
333}
334
335// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
336// value matches the provided string. Returns an empty BuildParams if no rule is found.
337func (s TestingSingleton) MaybeOutput(file string) TestingBuildParams {
338 p, _ := maybeBuildParamsFromOutput(s.provider, file)
339 return p
340}
341
342// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
343// value matches the provided string. Panics if no rule is found.
344func (s TestingSingleton) Output(file string) TestingBuildParams {
345 return buildParamsFromOutput(s.provider, file)
346}
347
348// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
349func (s TestingSingleton) AllOutputs() []string {
350 return allOutputs(s.provider)
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800351}
352
Logan Chien42039712018-03-12 16:29:17 +0800353func FailIfErrored(t *testing.T, errs []error) {
354 t.Helper()
355 if len(errs) > 0 {
356 for _, err := range errs {
357 t.Error(err)
358 }
359 t.FailNow()
360 }
361}
Logan Chienee97c3e2018-03-12 16:34:26 +0800362
363func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) {
364 t.Helper()
365
366 matcher, err := regexp.Compile(pattern)
367 if err != nil {
368 t.Errorf("failed to compile regular expression %q because %s", pattern, err)
369 }
370
371 found := false
372 for _, err := range errs {
373 if matcher.FindStringIndex(err.Error()) != nil {
374 found = true
375 break
376 }
377 }
378 if !found {
379 t.Errorf("missing the expected error %q (checked %d error(s))", pattern, len(errs))
380 for i, err := range errs {
381 t.Errorf("errs[%d] = %s", i, err)
382 }
383 }
384}
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700385
Paul Duffin91e38192019-08-05 15:07:57 +0100386func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
387 t.Helper()
388
389 if expectedErrorPatterns == nil {
390 FailIfErrored(t, errs)
391 } else {
392 for _, expectedError := range expectedErrorPatterns {
393 FailIfNoMatchingErrors(t, expectedError, errs)
394 }
395 if len(errs) > len(expectedErrorPatterns) {
396 t.Errorf("additional errors found, expected %d, found %d",
397 len(expectedErrorPatterns), len(errs))
398 for i, expectedError := range expectedErrorPatterns {
399 t.Errorf("expectedErrors[%d] = %s", i, expectedError)
400 }
401 for i, err := range errs {
402 t.Errorf("errs[%d] = %s", i, err)
403 }
404 }
405 }
406
407}
408
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900409func AndroidMkEntriesForTest(t *testing.T, config Config, bpPath string, mod blueprint.Module) []AndroidMkEntries {
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700410 var p AndroidMkEntriesProvider
411 var ok bool
412 if p, ok = mod.(AndroidMkEntriesProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +0100413 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700414 }
Jiyong Park0b0e1b92019-12-03 13:24:29 +0900415
416 entriesList := p.AndroidMkEntries()
417 for i, _ := range entriesList {
418 entriesList[i].fillInEntries(config, bpPath, mod)
419 }
420 return entriesList
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700421}
Jooyung Han12df5fb2019-07-11 16:18:47 +0900422
423func AndroidMkDataForTest(t *testing.T, config Config, bpPath string, mod blueprint.Module) AndroidMkData {
424 var p AndroidMkDataProvider
425 var ok bool
426 if p, ok = mod.(AndroidMkDataProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +0100427 t.Errorf("module does not implement AndroidMkDataProvider: " + mod.Name())
Jooyung Han12df5fb2019-07-11 16:18:47 +0900428 }
429 data := p.AndroidMk()
430 data.fillInData(config, bpPath, mod)
431 return data
432}
Paul Duffin9b478b02019-12-10 13:41:51 +0000433
434// Normalize the path for testing.
435//
436// If the path is relative to the build directory then return the relative path
437// to avoid tests having to deal with the dynamically generated build directory.
438//
439// Otherwise, return the supplied path as it is almost certainly a source path
440// that is relative to the root of the source tree.
441//
442// The build and source paths should be distinguishable based on their contents.
443func NormalizePathForTesting(path Path) string {
444 p := path.String()
445 if w, ok := path.(WritablePath); ok {
446 rel, err := filepath.Rel(w.buildDir(), p)
447 if err != nil {
448 panic(err)
449 }
450 return rel
451 }
452 return p
453}
454
455func NormalizePathsForTesting(paths Paths) []string {
456 var result []string
457 for _, path := range paths {
458 relative := NormalizePathForTesting(path)
459 result = append(result, relative)
460 }
461 return result
462}