Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 17 additions & 63 deletions cmd/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,71 +52,14 @@ func NewImportCommand(globalClientOpts *connectors.ClientOptions) *cobra.Command

specificationFiles := args[0]

// Initialize config from command options.
config.InsecureTLS = globalClientOpts.InsecureTLS
config.CaCertPaths = globalClientOpts.CaCertPaths
config.Verbose = globalClientOpts.Verbose

// Read local config file in case we need some context info.
localConfig, err := config.ReadLocalConfig(globalClientOpts.ConfigPath)
mc, serverAddr, err := newCommandClient(globalClientOpts)
if err != nil {
return errors.Wrap(errors.KindEnvironment, err)
return err
}

// Prepare Microcks client.
var mc connectors.MicrocksClient

if globalClientOpts.ServerAddr != "" && globalClientOpts.ClientId != "" && globalClientOpts.ClientSecret != "" {
// Create client with server address.
var err error
mc, err = connectors.NewMicrocksClient(globalClientOpts.ServerAddr)
if err != nil {
return err
}

keycloakURL, err := mc.GetKeycloakURL()
if err != nil {
return err
}

oauthToken := "unauthenticated-token"
if keycloakURL != "null" {
// If Keycloak is enabled, retrieve an OAuth token using Keycloak Client.
kc, err := connectors.NewKeycloakClient(keycloakURL, globalClientOpts.ClientId, globalClientOpts.ClientSecret)
if err != nil {
return err
}

oauthToken, err = kc.ConnectAndGetToken()
if err != nil {
return err
}
}

// Set Auth token.
mc.SetOAuthToken(oauthToken)

// If no context provided use current one from config file or client server address.
// So that watch config can be updated properly, referencing the right context.
if globalClientOpts.Context == "" {
if (localConfig != nil) && (localConfig.CurrentContext != "") {
globalClientOpts.Context = localConfig.CurrentContext
} else {
globalClientOpts.Context = globalClientOpts.ServerAddr
}
}

} else {
// Create client from config file and using the current or provided context.
if localConfig == nil {
return errors.Wrapf(errors.KindUsage, "please login to perform this operation")
}

if globalClientOpts.Context == "" {
globalClientOpts.Context = localConfig.CurrentContext
}

mc, err = connectors.NewClient(*globalClientOpts)
watchContext := globalClientOpts.Context
if watch && watchContext == "" {
watchContext, err = defaultImportWatchContext(globalClientOpts.ConfigPath, serverAddr)
if err != nil {
return err
}
Expand Down Expand Up @@ -180,7 +123,7 @@ func NewImportCommand(globalClientOpts *connectors.ClientOptions) *cobra.Command
// Upsert entry.
watchCfg.UpsertEntry(config.WatchEntry{
FilePath: f,
Context: []string{globalClientOpts.Context},
Context: []string{watchContext},
MainArtifact: mainArtifact,
})

Expand Down Expand Up @@ -220,6 +163,17 @@ func NewImportCommand(globalClientOpts *connectors.ClientOptions) *cobra.Command
return importCmd
}

func defaultImportWatchContext(configPath, serverAddr string) (string, error) {
localConfig, err := config.ReadLocalConfig(configPath)
if err != nil {
return "", errors.Wrap(errors.KindEnvironment, err)
}
if localConfig != nil && localConfig.CurrentContext != "" {
return localConfig.CurrentContext, nil
}
return serverAddr, nil
}

type artifactImportResult struct {
File string `json:"file"`
ID string `json:"id"`
Expand Down
66 changes: 66 additions & 0 deletions cmd/import_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Copyright The Microcks Authors.
*
* 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 cmd

import (
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)

func TestImportCommandUsesMicrocksURLWithoutLocalConfig(t *testing.T) {
artifact := t.TempDir() + "/openapi.yaml"
if err := os.WriteFile(artifact, []byte("openapi: 3.0.0\ninfo:\n title: Demo\n version: 1.0.0\npaths: {}\n"), 0o644); err != nil {
t.Fatalf("failed to write artifact: %v", err)
}

called := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
if r.URL.Path != "/api/artifact/upload" {
t.Fatalf("unexpected path: %s", r.URL.Path)
}
if r.Method != http.MethodPost {
t.Fatalf("unexpected method: %s", r.Method)
}
if err := r.ParseMultipartForm(1 << 20); err != nil {
t.Fatalf("failed to parse multipart form: %v", err)
}
if got := r.MultipartForm.Value["mainArtifact"]; len(got) != 1 || got[0] != "true" {
t.Fatalf("unexpected mainArtifact: %v", got)
}
w.WriteHeader(http.StatusCreated)
if _, err := w.Write([]byte("Demo:1.0.0")); err != nil {
t.Fatalf("failed to write response: %v", err)
}

}))
defer server.Close()

out, err := executeCLIForTest(t, "import", artifact, "--microcksURL", server.URL, "--config", t.TempDir()+"/config")
if err != nil {
t.Fatalf("command returned error: %v", err)
}
if !called {
t.Fatal("expected import command to call Microcks upload endpoint")
}
if !strings.Contains(out, "Microcks has discovered 'Demo:1.0.0'") {
t.Fatalf("unexpected output: %s", out)
}
}