Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: Add mocking #9

Merged
merged 6 commits into from Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 8 additions & 2 deletions tools/cli/Makefile
Expand Up @@ -24,15 +24,16 @@ deps: ## Download go module dependencies
.PHONY: devtools
devtools: ## Install dev tools
@echo "==> Installing dev tools..."
go install go.uber.org/mock/mockgen@latest
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(shell go env GOPATH)/bin $(GOLANGCI_VERSION)

.PHONY: setup
setup: deps devtools ## Set up dev env

.PHONY: fmt
fmt: ### Format all go files with goimports and gofmt
find . -name "*.go" -exec gofmt -w "{}" \;
find . -name "*.go" -exec goimports -l -w "{}" \;
find . -name "*.go" -not -path "./internal/mocks" -exec gofmt -w "{}" \;
find . -name "*.go" -not -path "./internal/mocks" -exec goimports -l -w "{}" \;
andreaangiolillo marked this conversation as resolved.
Show resolved Hide resolved

.PHONY: build
build:
Expand All @@ -57,6 +58,11 @@ fix-lint: ## Fix linting errors
list: ## List all make targets
@${MAKE} -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | egrep -v -e '^[^[:alnum:]]' -e '^$@$$' | sort

.PHONY: gen-mocks
gen-mocks: ## Generate mocks
@echo "==> Generating mocks"
rm -rf ./internal/mocks
go generate ./internal...

.PHONY: help
.DEFAULT_GOAL := help
Expand Down
1 change: 1 addition & 0 deletions tools/cli/go.mod
Expand Up @@ -7,6 +7,7 @@ require (
github.com/spf13/cobra v1.8.0
github.com/stretchr/testify v1.9.0
github.com/tufin/oasdiff v1.10.11
go.uber.org/mock v0.4.0
)

require (
Expand Down
2 changes: 2 additions & 0 deletions tools/cli/go.sum
Expand Up @@ -48,6 +48,8 @@ github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4d
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/yargevad/filepathx v1.0.0 h1:SYcT+N3tYGi+NvazubCNlvgIPbzAk7i7y2dwg3I5FYc=
github.com/yargevad/filepathx v1.0.0/go.mod h1:BprfX/gpYNJHJfc35GjRRpVcwWXS89gGulUIU5tK3tA=
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
golang.org/x/exp v0.0.0-20240119083558-1b970713d09a h1:Q8/wZp0KX97QFTc2ywcOE0YRjZPVIx+MXInMzdvQqcA=
golang.org/x/exp v0.0.0-20240119083558-1b970713d09a/go.mod h1:idGWGoKP1toJGkd5/ig9ZLuPcZBC3ewk7SzmH0uou08=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
12 changes: 8 additions & 4 deletions tools/cli/internal/cli/merge/merge.go
Expand Up @@ -29,14 +29,18 @@ const (
DefaultOutputFileName = "FOAS.json"
)

// writeToFileFunc is a variable that holds the function used to write files.
// It can be overridden in tests.
var writeToFileFunc = os.WriteFile
andreaangiolillo marked this conversation as resolved.
Show resolved Hide resolved

type Opts struct {
Merger openapi.Merger
basePath string
outputPath string
externalPaths []string
}

func (o *Opts) Run(_ []string) error {
func (o *Opts) Run() error {
federated, err := o.Merger.MergeOpenAPISpecs(o.externalPaths)
if err != nil {
return err
Expand Down Expand Up @@ -65,7 +69,7 @@ func (o *Opts) PreRunE(_ []string) error {
}

func (o *Opts) saveFile(data []byte) error {
if err := os.WriteFile(o.outputPath, data, 0o600); err != nil {
if err := writeToFileFunc(o.outputPath, data, 0o600); err != nil {
return err
}

Expand All @@ -85,8 +89,8 @@ func Builder() *cobra.Command {
PreRunE: func(_ *cobra.Command, args []string) error {
return opts.PreRunE(args)
},
RunE: func(_ *cobra.Command, args []string) error {
return opts.Run(args)
RunE: func(_ *cobra.Command, _ []string) error {
return opts.Run()
},
}

Expand Down
44 changes: 44 additions & 0 deletions tools/cli/internal/cli/merge/merge_test.go
Expand Up @@ -12,15 +12,52 @@
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build unit
andreaangiolillo marked this conversation as resolved.
Show resolved Hide resolved

package merge

import (
"os"
"testing"

"github.com/getkin/kin-openapi/openapi3"
"github.com/mongodb/openapi/tools/cli/internal/cli/flag"
"github.com/mongodb/openapi/tools/cli/internal/cli/validator"
"github.com/mongodb/openapi/tools/cli/internal/mocks"
"github.com/tufin/oasdiff/load"
"go.uber.org/mock/gomock"
)

func TestSuccessfulMerge_Run(t *testing.T) {
setupTest(t)
ctrl := gomock.NewController(t)
mockMergerStore := mocks.NewMockMerger(ctrl)

externalPaths := []string{"external.json"}
opts := &Opts{
Merger: mockMergerStore,
basePath: "base.json",
outputPath: "foas.json",
externalPaths: externalPaths,
}

response := &load.SpecInfo{
Spec: &openapi3.T{},
Url: "test",
Version: "3.0.1",
}

mockMergerStore.
EXPECT().
MergeOpenAPISpecs(opts.externalPaths).
Return(response, nil).
Times(1)

if err := opts.Run(); err != nil {
t.Fatalf("Run() unexpected error: %v", err)
}
}

func TestCreateBuilder(t *testing.T) {
validator.ValidateSubCommandsAndFlags(
t,
Expand All @@ -29,3 +66,10 @@ func TestCreateBuilder(t *testing.T) {
[]string{flag.Base, flag.External, flag.Output},
)
}

func setupTest(t *testing.T) {
t.Helper()
writeToFileFunc = func(_ string, _ []byte, _ os.FileMode) error {
return nil
}
}
93 changes: 93 additions & 0 deletions tools/cli/internal/mocks/mock_openapi.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions tools/cli/internal/openapi/errors/path_conflict_error.go
@@ -1,3 +1,17 @@
// Copyright 2024 MongoDB Inc

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[q] Not strictly related to this PR but was curious if there are alternatives to having a license header placed in all files, such as a LICENSE file at the root of the project.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for apache should be both

//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package errors

import "fmt"
Expand Down
56 changes: 14 additions & 42 deletions tools/cli/internal/openapi/oasdiff.go
@@ -1,8 +1,20 @@
// Copyright 2024 MongoDB Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package openapi

import (
"log"

"github.com/mongodb/openapi/tools/cli/internal/openapi/errors"
"github.com/tufin/oasdiff/diff"
"github.com/tufin/oasdiff/load"
Expand All @@ -16,46 +28,6 @@ type OasDiff struct {
parser Parser
}

func NewOasDiff(base string) (*OasDiff, error) {
parser := NewOpenAPI3()
baseSpec, err := parser.CreateOpenAPISpecFromPath(base)
if err != nil {
return nil, err
}

return &OasDiff{
base: baseSpec,
parser: parser,
config: &diff.Config{
IncludePathParams: true,
},
}, nil
}

func (o *OasDiff) MergeOpenAPISpecs(paths []string) (*load.SpecInfo, error) {
for _, p := range paths {
spec, err := o.parser.CreateOpenAPISpecFromPath(p)
if err != nil {
return nil, err
}

specDiff, err := diff.Get(o.config, o.base.Spec, spec.Spec)
if err != nil {
log.Fatalf("error in calculating the diff of the specs: %s", err)
return nil, err
}

o.specDiff = specDiff
o.external = spec
err = o.mergeSpecIntoBase()
if err != nil {
return nil, err
}
}

return o.base, nil
}

func (o OasDiff) mergeSpecIntoBase() error {
return o.mergePaths()
}
Expand Down