Skip to content

Commit ca5d4a6

Browse files
committed
lint and tests fixes
1 parent c5bbb5c commit ca5d4a6

File tree

14 files changed

+141
-53
lines changed

14 files changed

+141
-53
lines changed

tools/openapi2crd/cmd/run.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,14 +98,15 @@ func runOpenapi2crd(ctx context.Context, fs afero.Fs, input, output string, over
9898
}
9999

100100
openapiLoader := config.NewKinOpeAPI(fs)
101+
atlasLoader := config.NewAtlas(openapiLoader)
101102

102103
for _, crdConfig := range cfg.Spec.CRDConfig {
103104
pluginSet, err := plugins.GetPluginSet(pluginSets, crdConfig.PluginSet)
104105
if err != nil {
105106
return fmt.Errorf("error getting plugin set %q: %w", crdConfig.PluginSet, err)
106107
}
107108

108-
g := generator.NewGenerator(definitionsMap, pluginSet, openapiLoader)
109+
g := generator.NewGenerator(definitionsMap, pluginSet, openapiLoader, atlasLoader)
109110
crd, err := g.Generate(ctx, &crdConfig)
110111
if err != nil {
111112
return err

tools/openapi2crd/cmd/run_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ spec:
4848
plugins:
4949
- base
5050
- major_version
51-
- parameter
51+
- parameters
5252
- entry
5353
- status
5454
openapi:
Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,38 +13,54 @@
1313
// limitations under the License.
1414
//
1515

16-
package atlas
16+
package config
1717

1818
import (
19+
"context"
20+
"errors"
1921
"fmt"
2022
"os/exec"
2123
"path/filepath"
2224
"strings"
2325

26+
"github.com/getkin/kin-openapi/openapi3"
2427
_ "go.mongodb.org/atlas-sdk/v20250312005/admin"
2528
)
2629

27-
func LoadOpenAPIPath(modulePath string) (string, error) {
28-
path, err := GetGoModulePath(modulePath)
30+
type Atlas struct {
31+
fileLoader Loader
32+
}
33+
34+
func (a *Atlas) Load(ctx context.Context, pkg string) (*openapi3.T, error) {
35+
path, err := getGoModulePath(ctx, pkg)
2936
if err != nil {
30-
return "", fmt.Errorf("failed to load module path: %v", err)
37+
return nil, fmt.Errorf("failed to load module path: %w", err)
3138
}
3239
_ = path
3340

34-
return filepath.Clean(filepath.Join(path, "..", "openapi", "atlas-api-transformed.yaml")), nil
41+
filename := filepath.Clean(filepath.Join(path, "..", "openapi", "atlas-api-transformed.yaml"))
42+
43+
return a.fileLoader.Load(ctx, filename)
44+
}
45+
46+
func NewAtlas(loader Loader) *Atlas {
47+
return &Atlas{
48+
fileLoader: loader,
49+
}
3550
}
3651

37-
func GetGoModulePath(modulePath string) (string, error) {
52+
func getGoModulePath(ctx context.Context, modulePath string) (string, error) {
3853
goCmd, err := exec.LookPath("go")
3954
if err != nil {
4055
return "", fmt.Errorf("go command not found in PATH: %w", err)
4156
}
4257

43-
cmd := exec.Command(goCmd, "list", "-f", "{{.Dir}}", modulePath)
58+
cmd := exec.CommandContext(ctx, goCmd, "list", "-f", "{{.Dir}}", modulePath)
4459
output, err := cmd.Output()
4560
if err != nil {
4661
// Check if the error is due to the module not being found
47-
if exitErr, ok := err.(*exec.ExitError); ok {
62+
var exitErr *exec.ExitError
63+
if errors.As(err, &exitErr) {
4864
stderr := string(exitErr.Stderr)
4965
if strings.Contains(stderr, "not a known module") || strings.Contains(stderr, "cannot find module") {
5066
return "", fmt.Errorf("module '%s' not found or not a dependency of the current project", modulePath)
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package config
2+
3+
import (
4+
"context"
5+
"testing"
6+
7+
"github.com/getkin/kin-openapi/openapi3"
8+
"github.com/stretchr/testify/assert"
9+
"github.com/stretchr/testify/mock"
10+
)
11+
12+
func TestAtlas_Load(t *testing.T) {
13+
tests := map[string]struct {
14+
pkg string
15+
expectedSchema *openapi3.T
16+
expectedErrMsg string
17+
}{
18+
"valid package": {
19+
pkg: "go.mongodb.org/atlas-sdk/v20250312005/admin",
20+
expectedSchema: &openapi3.T{},
21+
},
22+
"invalid package": {
23+
pkg: "invalid/package/name",
24+
expectedErrMsg: "failed to load module path: failed to run 'go list' for module 'invalid/package/name'",
25+
},
26+
}
27+
for name, tt := range tests {
28+
t.Run(name, func(t *testing.T) {
29+
openapiLoader := NewLoaderMock(t)
30+
if tt.expectedErrMsg == "" {
31+
openapiLoader.EXPECT().Load(context.Background(), mock.AnythingOfType("string")).Return(&openapi3.T{}, nil)
32+
}
33+
34+
a := NewAtlas(openapiLoader)
35+
schema, err := a.Load(context.Background(), tt.pkg)
36+
if err != nil {
37+
assert.ErrorContains(t, err, tt.expectedErrMsg)
38+
}
39+
assert.Equal(t, tt.expectedSchema, schema)
40+
})
41+
}
42+
}

tools/openapi2crd/pkg/config/openapi.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ limitations under the License.
3030
package config
3131

3232
import (
33+
"context"
3334
"fmt"
3435
"net/url"
3536
"path/filepath"
@@ -40,7 +41,7 @@ import (
4041
)
4142

4243
type Loader interface {
43-
Load(path string) (*openapi3.T, error)
44+
Load(ctx context.Context, path string) (*openapi3.T, error)
4445
}
4546

4647
type KinOpeAPI struct {
@@ -53,7 +54,7 @@ func NewKinOpeAPI(fs afero.Fs) *KinOpeAPI {
5354
}
5455
}
5556

56-
func (a *KinOpeAPI) Load(path string) (*openapi3.T, error) {
57+
func (a *KinOpeAPI) Load(_ context.Context, path string) (*openapi3.T, error) {
5758
loader := &openapi3.Loader{
5859
IsExternalRefsAllowed: true,
5960
}

tools/openapi2crd/pkg/config/openapi_mock.go

Lines changed: 22 additions & 14 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tools/openapi2crd/pkg/config/openapi_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ paths:
5959
tt.expectedOpenAPI.Paths.Extensions = map[string]any{}
6060

6161
loader := NewKinOpeAPI(fs)
62-
openapi, err := loader.Load(tt.filePath)
62+
openapi, err := loader.Load(nil, tt.filePath)
6363
assert.Equal(t, tt.expectError, err)
6464
assert.Equal(t, tt.expectedOpenAPI, openapi)
6565
})

tools/openapi2crd/pkg/generator/converter.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,12 @@ func (g *Generator) Convert(input converter.PropertyConvertInput) *apiextensions
131131
ExtensionsSchema: extensionSchemaRef,
132132
Path: input.Path,
133133
}
134-
p.Process(req)
134+
err := p.Process(req)
135+
// Currently, property plugins are not expected to return an error.
136+
// If an error case is introduced in the future, we should handle it appropriately.
137+
if err != nil {
138+
return nil
139+
}
135140

136141
if req.Property == nil {
137142
return nil
@@ -201,7 +206,12 @@ func (g *Generator) convertPropertyOrArray(input converter.PropertyConvertInput)
201206
}
202207

203208
func (g *Generator) convertPropertySlice(schemas openapi3.SchemaRefs, input converter.PropertyConvertInput) []apiextensions.JSONSchemaProps {
204-
var s []apiextensions.JSONSchemaProps
209+
if len(schemas) == 0 {
210+
return nil
211+
}
212+
213+
s := make([]apiextensions.JSONSchemaProps, 0, len(schemas))
214+
205215
for _, schema := range schemas {
206216
input.Depth++
207217
result := g.Convert(
@@ -218,6 +228,7 @@ func (g *Generator) convertPropertySlice(schemas openapi3.SchemaRefs, input conv
218228
}
219229
s = append(s, *result)
220230
}
231+
221232
return s
222233
}
223234

tools/openapi2crd/pkg/generator/generator.go

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ import (
3939
"sigs.k8s.io/yaml"
4040

4141
"tools/openapi2crd/pkg/apis/config/v1alpha1"
42-
"tools/openapi2crd/pkg/atlas"
4342
"tools/openapi2crd/pkg/config"
4443
"tools/openapi2crd/pkg/plugins"
4544
)
@@ -48,13 +47,20 @@ type Generator struct {
4847
definitions map[string]v1alpha1.OpenAPIDefinition
4948
pluginSet *plugins.Set
5049
openapiLoader config.Loader
50+
atlasLoader config.Loader
5151
}
5252

53-
func NewGenerator(openAPIDefinitions map[string]v1alpha1.OpenAPIDefinition, pluginSet *plugins.Set, openapiLoader config.Loader) *Generator {
53+
func NewGenerator(
54+
openAPIDefinitions map[string]v1alpha1.OpenAPIDefinition,
55+
pluginSet *plugins.Set,
56+
openapiLoader config.Loader,
57+
atlasLoader config.Loader,
58+
) *Generator {
5459
return &Generator{
5560
definitions: openAPIDefinitions,
5661
pluginSet: pluginSet,
5762
openapiLoader: openapiLoader,
63+
atlasLoader: atlasLoader,
5864
}
5965
}
6066

@@ -81,19 +87,19 @@ func (g *Generator) Generate(ctx context.Context, crdConfig *v1alpha1.CRDConfig)
8187
}
8288

8389
var openApiSpec *openapi3.T
90+
var err error
8491

85-
path := def.Path
86-
if path == "" {
87-
var err error
88-
path, err = atlas.LoadOpenAPIPath(def.Package)
92+
switch def.Path {
93+
case "":
94+
openApiSpec, err = g.atlasLoader.Load(ctx, def.Package)
8995
if err != nil {
90-
return nil, fmt.Errorf("error loading OpenAPI package %q: %w", def.Package, err)
96+
return nil, fmt.Errorf("error loading Atlas OpenAPI package %q: %w", def.Package, err)
97+
}
98+
default:
99+
openApiSpec, err = g.openapiLoader.Load(ctx, def.Path)
100+
if err != nil {
101+
return nil, fmt.Errorf("error loading spec: %w", err)
91102
}
92-
}
93-
94-
openApiSpec, err = g.openapiLoader.Load(path)
95-
if err != nil {
96-
return nil, fmt.Errorf("error loading spec: %w", err)
97103
}
98104

99105
for _, p := range g.pluginSet.Mapping {
@@ -145,7 +151,7 @@ func (g *Generator) Generate(ctx context.Context, crdConfig *v1alpha1.CRDConfig)
145151
}
146152

147153
func (g *Generator) majorVersions(config v1alpha1.CRDConfig) []string {
148-
var result []string
154+
result := make([]string, 0, len(config.Mappings))
149155
for _, m := range config.Mappings {
150156
result = append(result, "- "+m.MajorVersion)
151157
}

tools/openapi2crd/pkg/generator/generator_test.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -221,8 +221,10 @@ func TestGeneratorGenerate(t *testing.T) {
221221
}
222222
for name, tt := range tests {
223223
t.Run(name, func(t *testing.T) {
224-
loader := config.NewLoaderMock(t)
225-
loader.EXPECT().Load("testdata/openapi.yaml").Return(&openapi3.T{}, nil)
224+
openapiLoader := config.NewLoaderMock(t)
225+
openapiLoader.EXPECT().Load(context.Background(), "testdata/openapi.yaml").Return(&openapi3.T{}, nil)
226+
227+
atlasLoader := config.NewLoaderMock(t)
226228

227229
crdPlugin := plugins.NewCRDPluginMock(t)
228230
crdPlugin.EXPECT().Process(mock.AnythingOfType("*plugins.CRDProcessorRequest")).
@@ -250,7 +252,8 @@ func TestGeneratorGenerate(t *testing.T) {
250252
Mapping: []plugins.MappingPlugin{mappingPlugin},
251253
Extension: []plugins.ExtensionPlugin{extensionPlugin},
252254
},
253-
openapiLoader: loader,
255+
openapiLoader: openapiLoader,
256+
atlasLoader: atlasLoader,
254257
}
255258
result, err := g.Generate(context.Background(), tt.config)
256259
if tt.expectError {

0 commit comments

Comments
 (0)