blob: 447ffd6d4aada002d055bf6aceed5b4940c57c04 [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"
Jeff Gastondea7e4d2017-11-17 13:29:40 -080019 "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 Crossf8b860a2019-04-16 14:43:28 -070040 ctx.preArch = append(ctx.preArch, registerLoadHookMutator)
41
Colin Cross1b488422019-03-04 22:33:56 -080042 ctx.postDeps = append(ctx.postDeps, registerPathDepsMutator)
43
Jeff Gaston088e29e2017-11-29 16:47:17 -080044 return ctx
Colin Crosscec81712017-07-13 14:43:27 -070045}
46
Colin Crossae4c6182017-09-15 17:33:55 -070047func NewTestArchContext() *TestContext {
48 ctx := NewTestContext()
49 ctx.preDeps = append(ctx.preDeps, registerArchMutator)
50 return ctx
51}
52
Colin Crosscec81712017-07-13 14:43:27 -070053type TestContext struct {
Colin Cross4c83e5c2019-02-25 14:54:28 -080054 *Context
Colin Crosscec81712017-07-13 14:43:27 -070055 preArch, preDeps, postDeps []RegisterMutatorFunc
Jeff Gastonb274ed32017-12-01 17:10:33 -080056 NameResolver *NameResolver
Colin Crosscec81712017-07-13 14:43:27 -070057}
58
59func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) {
60 ctx.preArch = append(ctx.preArch, f)
61}
62
63func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) {
64 ctx.preDeps = append(ctx.preDeps, f)
65}
66
67func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) {
68 ctx.postDeps = append(ctx.postDeps, f)
69}
70
71func (ctx *TestContext) Register() {
Colin Cross4c83e5c2019-02-25 14:54:28 -080072 registerMutators(ctx.Context.Context, ctx.preArch, ctx.preDeps, ctx.postDeps)
Colin Crosscec81712017-07-13 14:43:27 -070073
Colin Cross54855dd2017-11-28 23:55:23 -080074 ctx.RegisterSingletonType("env", SingletonFactoryAdaptor(EnvSingleton))
Colin Crosscec81712017-07-13 14:43:27 -070075}
76
77func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
78 var module Module
79 ctx.VisitAllModules(func(m blueprint.Module) {
80 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant {
81 module = m.(Module)
82 }
83 })
84
85 if module == nil {
Jeff Gaston294356f2017-09-27 17:05:30 -070086 // find all the modules that do exist
87 allModuleNames := []string{}
88 ctx.VisitAllModules(func(m blueprint.Module) {
89 allModuleNames = append(allModuleNames, m.(Module).Name()+"("+ctx.ModuleSubDir(m)+")")
90 })
91
92 panic(fmt.Errorf("failed to find module %q variant %q."+
93 "\nall modules: %v", name, variant, allModuleNames))
Colin Crosscec81712017-07-13 14:43:27 -070094 }
95
96 return TestingModule{module}
97}
98
Jiyong Park37b25202018-07-11 10:49:27 +090099func (ctx *TestContext) ModuleVariantsForTests(name string) []string {
100 var variants []string
101 ctx.VisitAllModules(func(m blueprint.Module) {
102 if ctx.ModuleName(m) == name {
103 variants = append(variants, ctx.ModuleSubDir(m))
104 }
105 })
106 return variants
107}
108
Colin Cross4c83e5c2019-02-25 14:54:28 -0800109// SingletonForTests returns a TestingSingleton for the singleton registered with the given name.
110func (ctx *TestContext) SingletonForTests(name string) TestingSingleton {
111 allSingletonNames := []string{}
112 for _, s := range ctx.Singletons() {
113 n := ctx.SingletonName(s)
114 if n == name {
115 return TestingSingleton{
116 singleton: s.(*singletonAdaptor).Singleton,
117 provider: s.(testBuildProvider),
118 }
119 }
120 allSingletonNames = append(allSingletonNames, n)
121 }
122
123 panic(fmt.Errorf("failed to find singleton %q."+
124 "\nall singletons: %v", name, allSingletonNames))
125}
126
Jeff Gastondea7e4d2017-11-17 13:29:40 -0800127// MockFileSystem causes the Context to replace all reads with accesses to the provided map of
128// filenames to contents stored as a byte slice.
129func (ctx *TestContext) MockFileSystem(files map[string][]byte) {
130 // no module list file specified; find every file named Blueprints or Android.bp
131 pathsToParse := []string{}
132 for candidate := range files {
133 base := filepath.Base(candidate)
134 if base == "Blueprints" || base == "Android.bp" {
135 pathsToParse = append(pathsToParse, candidate)
136 }
137 }
138 if len(pathsToParse) < 1 {
139 panic(fmt.Sprintf("No Blueprint or Android.bp files found in mock filesystem: %v\n", files))
140 }
141 files[blueprint.MockModuleListFile] = []byte(strings.Join(pathsToParse, "\n"))
142
143 ctx.Context.MockFileSystem(files)
144}
145
Colin Cross4c83e5c2019-02-25 14:54:28 -0800146type testBuildProvider interface {
147 BuildParamsForTests() []BuildParams
148 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
149}
150
151type TestingBuildParams struct {
152 BuildParams
153 RuleParams blueprint.RuleParams
154}
155
156func newTestingBuildParams(provider testBuildProvider, bparams BuildParams) TestingBuildParams {
157 return TestingBuildParams{
158 BuildParams: bparams,
159 RuleParams: provider.RuleParamsForTests()[bparams.Rule],
160 }
161}
162
163func maybeBuildParamsFromRule(provider testBuildProvider, rule string) TestingBuildParams {
164 for _, p := range provider.BuildParamsForTests() {
165 if strings.Contains(p.Rule.String(), rule) {
166 return newTestingBuildParams(provider, p)
167 }
168 }
169 return TestingBuildParams{}
170}
171
172func buildParamsFromRule(provider testBuildProvider, rule string) TestingBuildParams {
173 p := maybeBuildParamsFromRule(provider, rule)
174 if p.Rule == nil {
175 panic(fmt.Errorf("couldn't find rule %q", rule))
176 }
177 return p
178}
179
180func maybeBuildParamsFromDescription(provider testBuildProvider, desc string) TestingBuildParams {
181 for _, p := range provider.BuildParamsForTests() {
Colin Crossb88b3c52019-06-10 15:15:17 -0700182 if strings.Contains(p.Description, desc) {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800183 return newTestingBuildParams(provider, p)
184 }
185 }
186 return TestingBuildParams{}
187}
188
189func buildParamsFromDescription(provider testBuildProvider, desc string) TestingBuildParams {
190 p := maybeBuildParamsFromDescription(provider, desc)
191 if p.Rule == nil {
192 panic(fmt.Errorf("couldn't find description %q", desc))
193 }
194 return p
195}
196
197func maybeBuildParamsFromOutput(provider testBuildProvider, file string) (TestingBuildParams, []string) {
198 var searchedOutputs []string
199 for _, p := range provider.BuildParamsForTests() {
200 outputs := append(WritablePaths(nil), p.Outputs...)
Colin Cross1d2cf042019-03-29 15:33:06 -0700201 outputs = append(outputs, p.ImplicitOutputs...)
Colin Cross4c83e5c2019-02-25 14:54:28 -0800202 if p.Output != nil {
203 outputs = append(outputs, p.Output)
204 }
205 for _, f := range outputs {
206 if f.String() == file || f.Rel() == file {
207 return newTestingBuildParams(provider, p), nil
208 }
209 searchedOutputs = append(searchedOutputs, f.Rel())
210 }
211 }
212 return TestingBuildParams{}, searchedOutputs
213}
214
215func buildParamsFromOutput(provider testBuildProvider, file string) TestingBuildParams {
216 p, searchedOutputs := maybeBuildParamsFromOutput(provider, file)
217 if p.Rule == nil {
218 panic(fmt.Errorf("couldn't find output %q.\nall outputs: %v",
219 file, searchedOutputs))
220 }
221 return p
222}
223
224func allOutputs(provider testBuildProvider) []string {
225 var outputFullPaths []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 outputFullPaths = append(outputFullPaths, outputs.Strings()...)
233 }
234 return outputFullPaths
235}
236
Colin Crossb77ffc42019-01-05 22:09:19 -0800237// TestingModule is wrapper around an android.Module that provides methods to find information about individual
238// ctx.Build parameters for verification in tests.
Colin Crosscec81712017-07-13 14:43:27 -0700239type TestingModule struct {
240 module Module
241}
242
Colin Crossb77ffc42019-01-05 22:09:19 -0800243// Module returns the Module wrapped by the TestingModule.
Colin Crosscec81712017-07-13 14:43:27 -0700244func (m TestingModule) Module() Module {
245 return m.module
246}
247
Colin Crossb77ffc42019-01-05 22:09:19 -0800248// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
249// BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800250func (m TestingModule) MaybeRule(rule string) TestingBuildParams {
251 return maybeBuildParamsFromRule(m.module, rule)
Colin Crosscec81712017-07-13 14:43:27 -0700252}
253
Colin Crossb77ffc42019-01-05 22:09:19 -0800254// 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 -0800255func (m TestingModule) Rule(rule string) TestingBuildParams {
256 return buildParamsFromRule(m.module, rule)
Colin Crossb77ffc42019-01-05 22:09:19 -0800257}
258
259// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
260// BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800261func (m TestingModule) MaybeDescription(desc string) TestingBuildParams {
262 return maybeBuildParamsFromDescription(m.module, desc)
Nan Zhanged19fc32017-10-19 13:06:22 -0700263}
264
Colin Crossb77ffc42019-01-05 22:09:19 -0800265// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
266// found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800267func (m TestingModule) Description(desc string) TestingBuildParams {
268 return buildParamsFromDescription(m.module, desc)
Colin Crossb77ffc42019-01-05 22:09:19 -0800269}
270
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800271// 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 -0800272// value matches the provided string. Returns an empty BuildParams if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800273func (m TestingModule) MaybeOutput(file string) TestingBuildParams {
274 p, _ := maybeBuildParamsFromOutput(m.module, file)
Colin Crossb77ffc42019-01-05 22:09:19 -0800275 return p
276}
277
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800278// 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 -0800279// value matches the provided string. Panics if no rule is found.
Colin Cross4c83e5c2019-02-25 14:54:28 -0800280func (m TestingModule) Output(file string) TestingBuildParams {
281 return buildParamsFromOutput(m.module, file)
Colin Crosscec81712017-07-13 14:43:27 -0700282}
Logan Chien42039712018-03-12 16:29:17 +0800283
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800284// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
285func (m TestingModule) AllOutputs() []string {
Colin Cross4c83e5c2019-02-25 14:54:28 -0800286 return allOutputs(m.module)
287}
288
289// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual
290// ctx.Build parameters for verification in tests.
291type TestingSingleton struct {
292 singleton Singleton
293 provider testBuildProvider
294}
295
296// Singleton returns the Singleton wrapped by the TestingSingleton.
297func (s TestingSingleton) Singleton() Singleton {
298 return s.singleton
299}
300
301// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty
302// BuildParams if no rule is found.
303func (s TestingSingleton) MaybeRule(rule string) TestingBuildParams {
304 return maybeBuildParamsFromRule(s.provider, rule)
305}
306
307// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found.
308func (s TestingSingleton) Rule(rule string) TestingBuildParams {
309 return buildParamsFromRule(s.provider, rule)
310}
311
312// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty
313// BuildParams if no rule is found.
314func (s TestingSingleton) MaybeDescription(desc string) TestingBuildParams {
315 return maybeBuildParamsFromDescription(s.provider, desc)
316}
317
318// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is
319// found.
320func (s TestingSingleton) Description(desc string) TestingBuildParams {
321 return buildParamsFromDescription(s.provider, desc)
322}
323
324// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
325// value matches the provided string. Returns an empty BuildParams if no rule is found.
326func (s TestingSingleton) MaybeOutput(file string) TestingBuildParams {
327 p, _ := maybeBuildParamsFromOutput(s.provider, file)
328 return p
329}
330
331// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel()
332// value matches the provided string. Panics if no rule is found.
333func (s TestingSingleton) Output(file string) TestingBuildParams {
334 return buildParamsFromOutput(s.provider, file)
335}
336
337// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms.
338func (s TestingSingleton) AllOutputs() []string {
339 return allOutputs(s.provider)
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800340}
341
Logan Chien42039712018-03-12 16:29:17 +0800342func FailIfErrored(t *testing.T, errs []error) {
343 t.Helper()
344 if len(errs) > 0 {
345 for _, err := range errs {
346 t.Error(err)
347 }
348 t.FailNow()
349 }
350}
Logan Chienee97c3e2018-03-12 16:34:26 +0800351
352func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) {
353 t.Helper()
354
355 matcher, err := regexp.Compile(pattern)
356 if err != nil {
357 t.Errorf("failed to compile regular expression %q because %s", pattern, err)
358 }
359
360 found := false
361 for _, err := range errs {
362 if matcher.FindStringIndex(err.Error()) != nil {
363 found = true
364 break
365 }
366 }
367 if !found {
368 t.Errorf("missing the expected error %q (checked %d error(s))", pattern, len(errs))
369 for i, err := range errs {
370 t.Errorf("errs[%d] = %s", i, err)
371 }
372 }
373}
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700374
Paul Duffin91e38192019-08-05 15:07:57 +0100375func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) {
376 t.Helper()
377
378 if expectedErrorPatterns == nil {
379 FailIfErrored(t, errs)
380 } else {
381 for _, expectedError := range expectedErrorPatterns {
382 FailIfNoMatchingErrors(t, expectedError, errs)
383 }
384 if len(errs) > len(expectedErrorPatterns) {
385 t.Errorf("additional errors found, expected %d, found %d",
386 len(expectedErrorPatterns), len(errs))
387 for i, expectedError := range expectedErrorPatterns {
388 t.Errorf("expectedErrors[%d] = %s", i, expectedError)
389 }
390 for i, err := range errs {
391 t.Errorf("errs[%d] = %s", i, err)
392 }
393 }
394 }
395
396}
397
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700398func AndroidMkEntriesForTest(t *testing.T, config Config, bpPath string, mod blueprint.Module) AndroidMkEntries {
399 var p AndroidMkEntriesProvider
400 var ok bool
401 if p, ok = mod.(AndroidMkEntriesProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +0100402 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name())
Jaewoong Jung9aa3ab12019-04-03 15:47:29 -0700403 }
404 entries := p.AndroidMkEntries()
405 entries.fillInEntries(config, bpPath, mod)
406 return entries
407}
Jooyung Han12df5fb2019-07-11 16:18:47 +0900408
409func AndroidMkDataForTest(t *testing.T, config Config, bpPath string, mod blueprint.Module) AndroidMkData {
410 var p AndroidMkDataProvider
411 var ok bool
412 if p, ok = mod.(AndroidMkDataProvider); !ok {
Roland Levillaindfe75b32019-07-23 16:53:32 +0100413 t.Errorf("module does not implement AndroidMkDataProvider: " + mod.Name())
Jooyung Han12df5fb2019-07-11 16:18:47 +0900414 }
415 data := p.AndroidMk()
416 data.fillInData(config, bpPath, mod)
417 return data
418}