| 1 |
/* |
| 2 |
Copyright 2019 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package generator |
| 18 |
|
| 19 |
import ( |
| 20 |
"reflect" |
| 21 |
"testing" |
| 22 |
|
| 23 |
"k8s.io/gengo/v2/types" |
| 24 |
) |
| 25 |
|
| 26 |
func TestNewImportTracker(t *testing.T) { |
| 27 |
tests := []struct { |
| 28 |
name string |
| 29 |
localPackage string |
| 30 |
inputTypes []*types.Type |
| 31 |
expectedImports []string |
| 32 |
}{ |
| 33 |
{ |
| 34 |
name: "empty", |
| 35 |
inputTypes: []*types.Type{}, |
| 36 |
expectedImports: []string{}, |
| 37 |
}, |
| 38 |
{ |
| 39 |
name: "builtin", |
| 40 |
inputTypes: []*types.Type{ |
| 41 |
{Name: types.Name{Package: "net/http"}}, |
| 42 |
}, |
| 43 |
expectedImports: []string{ |
| 44 |
`http "net/http"`, |
| 45 |
}, |
| 46 |
}, |
| 47 |
{ |
| 48 |
name: "sorting", |
| 49 |
inputTypes: []*types.Type{ |
| 50 |
{Name: types.Name{Package: "foo/bar/pkg2"}}, |
| 51 |
{Name: types.Name{Package: "foo/bar/pkg1"}}, |
| 52 |
}, |
| 53 |
expectedImports: []string{ |
| 54 |
`pkg1 "foo/bar/pkg1"`, |
| 55 |
`pkg2 "foo/bar/pkg2"`, |
| 56 |
}, |
| 57 |
}, |
| 58 |
{ |
| 59 |
name: "reserved-keyword", |
| 60 |
inputTypes: []*types.Type{ |
| 61 |
{Name: types.Name{Package: "my/reserved/pkg/struct"}}, |
| 62 |
}, |
| 63 |
expectedImports: []string{ |
| 64 |
`_struct "my/reserved/pkg/struct"`, |
| 65 |
}, |
| 66 |
}, |
| 67 |
{ |
| 68 |
name: "local-symbol", |
| 69 |
localPackage: "bar.com/my/pkg", |
| 70 |
inputTypes: []*types.Type{ |
| 71 |
{Name: types.Name{Package: "bar.com/my/pkg"}}, |
| 72 |
{Name: types.Name{Package: "bar.com/external/pkg"}}, |
| 73 |
}, |
| 74 |
expectedImports: []string{ |
| 75 |
`externalpkg "bar.com/external/pkg"`, |
| 76 |
}, |
| 77 |
}, |
| 78 |
} |
| 79 |
for _, tt := range tests { |
| 80 |
t.Run(tt.name, func(t *testing.T) { |
| 81 |
var actualImports []string |
| 82 |
if len(tt.localPackage) == 0 { |
| 83 |
actualImports = NewImportTracker(tt.inputTypes...).ImportLines() |
| 84 |
} else { |
| 85 |
actualImports = NewImportTrackerForPackage(tt.localPackage, tt.inputTypes...).ImportLines() |
| 86 |
} |
| 87 |
if !reflect.DeepEqual(actualImports, tt.expectedImports) { |
| 88 |
t.Errorf("ImportLines(%v) = %v, want %v", tt.inputTypes, actualImports, tt.expectedImports) |
| 89 |
} |
| 90 |
}) |
| 91 |
} |
| 92 |
} |