functional_test.go 44.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// +build integration

/*
Copyright 2016 The Kubernetes Authors All rights reserved.

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 integration

import (
22 23 24 25 26 27 28 29 30
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"os/exec"
31
	"path"
32
	"path/filepath"
33
	"regexp"
T
tstromberg 已提交
34
	"runtime"
35
	"strings"
36
	"testing"
37 38
	"time"

39 40
	"github.com/google/go-cmp/cmp"

S
Sharif Elgamal 已提交
41
	"k8s.io/minikube/pkg/drivers/kic/oci"
M
Medya Gh 已提交
42
	"k8s.io/minikube/pkg/minikube/config"
43
	"k8s.io/minikube/pkg/minikube/localpath"
44
	"k8s.io/minikube/pkg/minikube/reason"
M
lint  
Medya Gh 已提交
45
	"k8s.io/minikube/pkg/util/retry"
46

47 48
	"github.com/elazarl/goproxy"
	"github.com/hashicorp/go-retryablehttp"
49
	"github.com/otiai10/copy"
50 51 52
	"github.com/phayes/freeport"
	"github.com/pkg/errors"
	"golang.org/x/build/kubernetes/api"
53 54
)

55 56 57
// validateFunc are for subtests that share a single setup
type validateFunc func(context.Context, *testing.T, string)

M
Medya Gh 已提交
58 59 60
// used in validateStartWithProxy and validateSoftStart
var apiPortTest = 8441

61
// TestFunctional are functionality tests which can safely share a profile in parallel
N
Nick Kubala 已提交
62
func TestFunctional(t *testing.T) {
63 64

	profile := UniqueProfileName("functional")
M
Medya Gh 已提交
65
	ctx, cancel := context.WithTimeout(context.Background(), Minutes(40))
66
	defer func() {
67 68 69
		if !*cleanup {
			return
		}
70 71
		p := localSyncTestPath()
		if err := os.Remove(p); err != nil {
72
			t.Logf("unable to remove %q: %v", p, err)
73
		}
74

75
		Cleanup(t, profile, cancel)
76
	}()
77 78 79 80 81 82 83

	// Serial tests
	t.Run("serial", func(t *testing.T) {
		tests := []struct {
			name      string
			validator validateFunc
		}{
84 85
			{"CopySyncFile", setupFileSync},                 // Set file for the file sync test case
			{"StartWithProxy", validateStartWithProxy},      // Set everything else up for success
M
Medya Gh 已提交
86
			{"SoftStart", validateSoftStart},                // do a soft start. ensure config didnt change.
87 88 89 90
			{"KubeContext", validateKubeContext},            // Racy: must come immediately after "minikube start"
			{"KubectlGetPods", validateKubectlGetPods},      // Make sure apiserver is up
			{"CacheCmd", validateCacheCmd},                  // Caches images needed for subsequent tests because of proxy
			{"MinikubeKubectlCmd", validateMinikubeKubectl}, // Make sure `minikube kubectl` works
P
Pablo Caderno 已提交
91
			{"MinikubeKubectlCmdDirectly", validateMinikubeKubectlDirectCall},
92
			{"ExtraConfig", validateExtraConfig}, // Ensure extra cmdline config change is saved
93
			{"ComponentHealth", validateComponentHealth},
94 95 96
		}
		for _, tc := range tests {
			tc := tc
97 98 99
			if ctx.Err() == context.DeadlineExceeded {
				t.Fatalf("Unable to run more tests (deadline exceeded)")
			}
100
			t.Run(tc.name, func(t *testing.T) {
M
lint  
Medya Gh 已提交
101
				tc.validator(ctx, t, profile)
102
			})
M
Medya Gh 已提交
103
		}
104
	})
M
Medya Gh 已提交
105

106 107 108 109 110 111
	// Parallelized tests
	t.Run("parallel", func(t *testing.T) {
		tests := []struct {
			name      string
			validator validateFunc
		}{
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
			{"ConfigCmd", validateConfigCmd},
			{"DashboardCmd", validateDashboardCmd},
			{"DryRun", validateDryRun},
			{"StatusCmd", validateStatusCmd},
			{"LogsCmd", validateLogsCmd},
			{"MountCmd", validateMountCmd},
			{"ProfileCmd", validateProfileCmd},
			{"ServiceCmd", validateServiceCmd},
			{"AddonsCmd", validateAddonsCmd},
			{"PersistentVolumeClaim", validatePersistentVolumeClaim},
			{"TunnelCmd", validateTunnelCmd},
			{"SSHCmd", validateSSHCmd},
			{"MySQL", validateMySQL},
			{"FileSync", validateFileSync},
			{"CertSync", validateCertSync},
			{"UpdateContextCmd", validateUpdateContextCmd},
			{"DockerEnv", validateDockerEnv},
			{"NodeLabels", validateNodeLabels},
130 131 132
		}
		for _, tc := range tests {
			tc := tc
133 134 135 136
			if ctx.Err() == context.DeadlineExceeded {
				t.Fatalf("Unable to run more tests (deadline exceeded)")
			}

137 138 139 140 141
			t.Run(tc.name, func(t *testing.T) {
				MaybeParallel(t)
				tc.validator(ctx, t, profile)
			})
		}
M
Medya Gh 已提交
142
	})
143 144
}

M
Medya Gh 已提交
145 146
// validateNodeLabels checks if minikube cluster is created with correct kubernetes's node label
func validateNodeLabels(ctx context.Context, t *testing.T, profile string) {
147 148
	defer PostMortemLogs(t, profile)

M
Medya Gh 已提交
149
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "nodes", "--output=go-template", "--template='{{range $k, $v := (index .items 0).metadata.labels}}{{$k}} {{end}}'"))
M
Medya Gh 已提交
150
	if err != nil {
M
Medya Gh 已提交
151
		t.Errorf("failed to 'kubectl get nodes' with args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
152 153 154
	}
	expectedLabels := []string{"minikube.k8s.io/commit", "minikube.k8s.io/version", "minikube.k8s.io/updated_at", "minikube.k8s.io/name"}
	for _, el := range expectedLabels {
M
Medya Gh 已提交
155
		if !strings.Contains(rr.Output(), el) {
M
Medya Gh 已提交
156
			t.Errorf("expected to have label %q in node labels but got : %s", el, rr.Output())
M
Medya Gh 已提交
157 158 159 160
		}
	}
}

161
// check functionality of minikube after evaling docker-env
P
Priya Wadhwa 已提交
162
// TODO: Add validatePodmanEnv for crio runtime: #10231
163
func validateDockerEnv(ctx context.Context, t *testing.T, profile string) {
164 165 166
	if cr := ContainerRuntime(); cr != "docker" {
		t.Skipf("only validate docker env with docker container runtime, currently testing %s", cr)
	}
167
	defer PostMortemLogs(t, profile)
168
	mctx, cancel := context.WithTimeout(ctx, Seconds(120))
169
	defer cancel()
M
Medya Gh 已提交
170 171
	var rr *RunResult
	var err error
M
Medya Gh 已提交
172
	if runtime.GOOS == "windows" {
M
Medya Gh 已提交
173 174
		c := exec.CommandContext(mctx, "powershell.exe", "-NoProfile", "-NonInteractive", Target()+" -p "+profile+" docker-env | Invoke-Expression ;"+Target()+" status -p "+profile)
		rr, err = Run(t, c)
M
Medya Gh 已提交
175 176 177 178 179
	} else {
		c := exec.CommandContext(mctx, "/bin/bash", "-c", "eval $("+Target()+" -p "+profile+" docker-env) && "+Target()+" status -p "+profile)
		// we should be able to get minikube status with a bash which evaled docker-env
		rr, err = Run(t, c)
	}
M
Medya Gh 已提交
180 181
	if mctx.Err() == context.DeadlineExceeded {
		t.Errorf("failed to run the command by deadline. exceeded timeout. %s", rr.Command())
M
Medya Gh 已提交
182
	}
183
	if err != nil {
M
Medya Gh 已提交
184
		t.Fatalf("failed to do status after eval-ing docker-env. error: %v", err)
185 186
	}
	if !strings.Contains(rr.Output(), "Running") {
M
Medya Gh 已提交
187
		t.Fatalf("expected status output to include 'Running' after eval docker-env but got: *%s*", rr.Output())
188 189
	}

190
	mctx, cancel = context.WithTimeout(ctx, Seconds(60))
191 192
	defer cancel()
	// do a eval $(minikube -p profile docker-env) and check if we are point to docker inside minikube
M
Medya Gh 已提交
193
	if runtime.GOOS == "windows" { // testing docker-env eval in powershell
M
Medya Gh 已提交
194 195
		c := exec.CommandContext(mctx, "powershell.exe", "-NoProfile", "-NonInteractive", Target(), "-p "+profile+" docker-env | Invoke-Expression ; docker images")
		rr, err = Run(t, c)
M
Medya Gh 已提交
196
	} else {
M
Medya Gh 已提交
197
		c := exec.CommandContext(mctx, "/bin/bash", "-c", "eval $("+Target()+" -p "+profile+" docker-env) && docker images")
M
Medya Gh 已提交
198 199 200
		rr, err = Run(t, c)
	}

M
Medya Gh 已提交
201
	if mctx.Err() == context.DeadlineExceeded {
M
try pwd  
Medya Gh 已提交
202
		t.Errorf("failed to run the command in 30 seconds. exceeded 30s timeout. %s", rr.Command())
M
Medya Gh 已提交
203 204
	}

205
	if err != nil {
M
Medya Gh 已提交
206
		t.Fatalf("failed to run minikube docker-env. args %q : %v ", rr.Command(), err)
207 208 209 210
	}

	expectedImgInside := "gcr.io/k8s-minikube/storage-provisioner"
	if !strings.Contains(rr.Output(), expectedImgInside) {
M
Medya Gh 已提交
211
		t.Fatalf("expected 'docker images' to have %q inside minikube. but the output is: *%s*", expectedImgInside, rr.Output())
212 213 214 215
	}

}

M
lint  
Medya Gh 已提交
216
func validateStartWithProxy(ctx context.Context, t *testing.T, profile string) {
217 218
	defer PostMortemLogs(t, profile)

219 220
	srv, err := startHTTPProxy(t)
	if err != nil {
221
		t.Fatalf("failed to set up the test proxy: %s", err)
222
	}
223 224

	// Use more memory so that we may reliably fit MySQL and nginx
M
Medya Gh 已提交
225
	// changing api server so later in soft start we verify it didn't change
226
	startArgs := append([]string{"start", "-p", profile, "--memory=4000", fmt.Sprintf("--apiserver-port=%d", apiPortTest), "--wait=true"}, StartArgs()...)
227
	c := exec.CommandContext(ctx, Target(), startArgs...)
228 229 230 231 232 233
	env := os.Environ()
	env = append(env, fmt.Sprintf("HTTP_PROXY=%s", srv.Addr))
	env = append(env, "NO_PROXY=")
	c.Env = env
	rr, err := Run(t, c)
	if err != nil {
M
Medya Gh 已提交
234
		t.Errorf("failed minikube start. args %q: %v", rr.Command(), err)
235 236 237 238 239 240 241 242 243 244 245
	}

	want := "Found network options:"
	if !strings.Contains(rr.Stdout.String(), want) {
		t.Errorf("start stdout=%s, want: *%s*", rr.Stdout.String(), want)
	}

	want = "You appear to be using a proxy"
	if !strings.Contains(rr.Stderr.String(), want) {
		t.Errorf("start stderr=%s, want: *%s*", rr.Stderr.String(), want)
	}
246 247 248 249

	t.Run("Audit", func(t *testing.T) {
		got, err := auditContains(profile)
		if err != nil {
250
			t.Fatalf("failed to check audit log: %v", err)
251 252 253 254 255
		}
		if !got {
			t.Errorf("audit.json does not contain the profile %q", profile)
		}
	})
256 257
}

M
Medya Gh 已提交
258
// validateSoftStart validates that after minikube already started, a "minikube start" should not change the configs.
M
lint  
Medya Gh 已提交
259
func validateSoftStart(ctx context.Context, t *testing.T, profile string) {
260 261
	defer PostMortemLogs(t, profile)

M
Medya Gh 已提交
262
	start := time.Now()
M
Medya Gh 已提交
263
	// the test before this had been start with --apiserver-port=8441
M
lint  
Medya Gh 已提交
264 265
	beforeCfg, err := config.LoadProfile(profile)
	if err != nil {
266
		t.Fatalf("error reading cluster config before soft start: %v", err)
M
lint  
Medya Gh 已提交
267
	}
M
Medya Gh 已提交
268 269
	if beforeCfg.Config.KubernetesConfig.NodePort != apiPortTest {
		t.Errorf("expected cluster config node port before soft start to be %d but got %d", apiPortTest, beforeCfg.Config.KubernetesConfig.NodePort)
M
Medya Gh 已提交
270 271
	}

M
typo  
Medya Gh 已提交
272
	softStartArgs := []string{"start", "-p", profile, "--alsologtostderr", "-v=8"}
M
Medya Gh 已提交
273
	c := exec.CommandContext(ctx, Target(), softStartArgs...)
M
lint  
Medya Gh 已提交
274
	rr, err := Run(t, c)
M
Medya Gh 已提交
275 276 277
	if err != nil {
		t.Errorf("failed to soft start minikube. args %q: %v", rr.Command(), err)
	}
M
Medya Gh 已提交
278
	t.Logf("soft start took %s for %q cluster.", time.Since(start), profile)
M
Medya Gh 已提交
279

M
lint  
Medya Gh 已提交
280 281 282 283 284
	afterCfg, err := config.LoadProfile(profile)
	if err != nil {
		t.Errorf("error reading cluster config after soft start: %v", err)
	}

M
Medya Gh 已提交
285 286
	if afterCfg.Config.KubernetesConfig.NodePort != apiPortTest {
		t.Errorf("expected node port in the config not change after soft start. exepceted node port to be %d but got %d.", apiPortTest, afterCfg.Config.KubernetesConfig.NodePort)
M
Medya Gh 已提交
287
	}
M
Medya Gh 已提交
288

289 290 291
	t.Run("Audit", func(t *testing.T) {
		got, err := auditContains(profile)
		if err != nil {
292
			t.Fatalf("failed to check audit log: %v", err)
293 294 295 296 297
		}
		if !got {
			t.Errorf("audit.json does not contain the profile %q", profile)
		}
	})
M
Medya Gh 已提交
298 299
}

300 301
// validateKubeContext asserts that kubectl is properly configured (race-condition prone!)
func validateKubeContext(ctx context.Context, t *testing.T, profile string) {
302 303
	defer PostMortemLogs(t, profile)

304 305
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "config", "current-context"))
	if err != nil {
M
Medya Gh 已提交
306
		t.Errorf("failed to get current-context. args %q : %v", rr.Command(), err)
307 308
	}
	if !strings.Contains(rr.Stdout.String(), profile) {
309
		t.Errorf("expected current-context = %q, but got *%q*", profile, rr.Stdout.String())
310 311 312
	}
}

P
Priya Wadhwa 已提交
313 314
// validateKubectlGetPods asserts that `kubectl get pod -A` returns non-zero content
func validateKubectlGetPods(ctx context.Context, t *testing.T, profile string) {
315 316
	defer PostMortemLogs(t, profile)

317
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "po", "-A"))
P
Priya Wadhwa 已提交
318
	if err != nil {
M
Medya Gh 已提交
319
		t.Errorf("failed to get kubectl pods: args %q : %v", rr.Command(), err)
P
Priya Wadhwa 已提交
320
	}
321
	if rr.Stderr.String() != "" {
322
		t.Errorf("expected stderr to be empty but got *%q*: args %q", rr.Stderr, rr.Command())
323
	}
T
Thomas Stromberg 已提交
324
	if !strings.Contains(rr.Stdout.String(), "kube-system") {
325
		t.Errorf("expected stdout to include *kube-system* but got *%q*. args: %q", rr.Stdout, rr.Command())
P
Priya Wadhwa 已提交
326 327 328
	}
}

329 330
// validateMinikubeKubectl validates that the `minikube kubectl` command returns content
func validateMinikubeKubectl(ctx context.Context, t *testing.T, profile string) {
331 332
	defer PostMortemLogs(t, profile)

333 334
	// Must set the profile so that it knows what version of Kubernetes to use
	kubectlArgs := []string{"-p", profile, "kubectl", "--", "--context", profile, "get", "pods"}
P
Priya Wadhwa 已提交
335
	rr, err := Run(t, exec.CommandContext(ctx, Target(), kubectlArgs...))
336
	if err != nil {
M
Medya Gh 已提交
337
		t.Fatalf("failed to get pods. args %q: %v", rr.Command(), err)
338 339 340
	}
}

P
Pablo Caderno 已提交
341 342 343 344 345 346 347 348 349 350 351 352
// validateMinikubeKubectlDirectCall validates that calling minikube's kubectl
func validateMinikubeKubectlDirectCall(ctx context.Context, t *testing.T, profile string) {
	defer PostMortemLogs(t, profile)
	dir := filepath.Dir(Target())
	dstfn := filepath.Join(dir, "kubectl")
	err := os.Link(Target(), dstfn)

	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(dstfn) // clean up

353
	kubectlArgs := []string{"--context", profile, "get", "pods"}
P
Pablo Caderno 已提交
354 355
	rr, err := Run(t, exec.CommandContext(ctx, dstfn, kubectlArgs...))
	if err != nil {
356
		t.Fatalf("failed to run kubectl directly. args %q: %v", rr.Command(), err)
P
Pablo Caderno 已提交
357 358 359 360
	}

}

361 362 363 364 365
func validateExtraConfig(ctx context.Context, t *testing.T, profile string) {
	defer PostMortemLogs(t, profile)

	start := time.Now()
	// The tests before this already created a profile, starting minikube with different --extra-config cmdline option.
Y
Yanshu Zhao 已提交
366
	startArgs := []string{"start", "-p", profile, "--extra-config=apiserver.enable-admission-plugins=NamespaceAutoProvision"}
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
	c := exec.CommandContext(ctx, Target(), startArgs...)
	rr, err := Run(t, c)
	if err != nil {
		t.Errorf("failed to restart minikube. args %q: %v", rr.Command(), err)
	}
	t.Logf("restart took %s for %q cluster.", time.Since(start), profile)

	afterCfg, err := config.LoadProfile(profile)
	if err != nil {
		t.Errorf("error reading cluster config after soft start: %v", err)
	}

	expectedExtraOptions := "apiserver.enable-admission-plugins=NamespaceAutoProvision"

	if !strings.Contains(afterCfg.Config.KubernetesConfig.ExtraOptions.String(), expectedExtraOptions) {
		t.Errorf("expected ExtraOptions to contain %s but got %s", expectedExtraOptions, afterCfg.Config.KubernetesConfig.ExtraOptions.String())
	}

}

I
Ilya Zuyev 已提交
387 388 389
// imageID returns a docker image id for image `image` and current architecture
// 'image' is supposed to be one commonly used in minikube integration tests,
// like k8s 'pause'
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
func imageID(image string) string {
	ids := map[string]map[string]string{
		"pause": {
			"amd64": "0184c1613d929",
			"arm64": "3d18732f8686c",
		},
	}

	if imgIds, ok := ids[image]; ok {
		if id, ok := imgIds[runtime.GOARCH]; ok {
			return id
		}
		panic(fmt.Sprintf("unexpected architecture for image %q: %v", image, runtime.GOARCH))
	}
	panic("unexpected image name: " + image)
}

407 408
// validateComponentHealth asserts that all Kubernetes components are healthy
func validateComponentHealth(ctx context.Context, t *testing.T, profile string) {
409 410
	defer PostMortemLogs(t, profile)

411 412 413 414 415 416 417 418 419
	// The ComponentStatus API is deprecated in v1.19, so do the next closest thing.
	found := map[string]bool{
		"etcd":                    false,
		"kube-apiserver":          false,
		"kube-controller-manager": false,
		"kube-scheduler":          false,
	}

	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "po", "-l", "tier=control-plane", "-n", "kube-system", "-o=json"))
420
	if err != nil {
M
Medya Gh 已提交
421
		t.Fatalf("failed to get components. args %q: %v", rr.Command(), err)
422
	}
423
	cs := api.PodList{}
424 425
	d := json.NewDecoder(bytes.NewReader(rr.Stdout.Bytes()))
	if err := d.Decode(&cs); err != nil {
M
Medya Gh 已提交
426
		t.Fatalf("failed to decode kubectl json output: args %q : %v", rr.Command(), err)
427 428 429
	}

	for _, i := range cs.Items {
430 431 432 433 434 435 436 437
		for _, l := range i.Labels {
			t.Logf("%s phase: %s", l, i.Status.Phase)
			_, ok := found[l]
			if ok {
				found[l] = true
				if i.Status.Phase != "Running" {
					t.Errorf("%s is not Running: %+v", l, i.Status)
				}
438 439
			}
		}
440 441 442 443 444
	}

	for k, v := range found {
		if !v {
			t.Errorf("expected component %q was not found", k)
445 446 447 448
		}
	}
}

J
Josh Woodcock 已提交
449
func validateStatusCmd(ctx context.Context, t *testing.T, profile string) {
450
	defer PostMortemLogs(t, profile)
451
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status"))
J
Josh Woodcock 已提交
452
	if err != nil {
M
Medya Gh 已提交
453
		t.Errorf("failed to run minikube status. args %q : %v", rr.Command(), err)
J
Josh Woodcock 已提交
454 455 456
	}

	// Custom format
457
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-f", "host:{{.Host}},kublet:{{.Kubelet}},apiserver:{{.APIServer}},kubeconfig:{{.Kubeconfig}}"))
J
Josh Woodcock 已提交
458
	if err != nil {
M
Medya Gh 已提交
459
		t.Errorf("failed to run minikube status with custom format: args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
460
	}
461 462
	re := `host:([A-z]+),kublet:([A-z]+),apiserver:([A-z]+),kubeconfig:([A-z]+)`
	match, _ := regexp.MatchString(re, rr.Stdout.String())
J
Josh Woodcock 已提交
463
	if !match {
M
Medya Gh 已提交
464
		t.Errorf("failed to match regex %q for minikube status with custom format. args %q. output: %s", re, rr.Command(), rr.Output())
J
Josh Woodcock 已提交
465 466 467
	}

	// Json output
468
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-o", "json"))
J
Josh Woodcock 已提交
469
	if err != nil {
M
Medya Gh 已提交
470
		t.Errorf("failed to run minikube status with json output. args %q : %v", rr.Command(), err)
J
Josh Woodcock 已提交
471 472 473 474
	}
	var jsonObject map[string]interface{}
	err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
	if err != nil {
M
Medya Gh 已提交
475
		t.Errorf("failed to decode json from minikube status. args %q. %v", rr.Command(), err)
J
Josh Woodcock 已提交
476 477
	}
	if _, ok := jsonObject["Host"]; !ok {
M
Medya Gh 已提交
478
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Host")
J
Josh Woodcock 已提交
479 480
	}
	if _, ok := jsonObject["Kubelet"]; !ok {
M
Medya Gh 已提交
481
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Kubelet")
J
Josh Woodcock 已提交
482 483
	}
	if _, ok := jsonObject["APIServer"]; !ok {
M
Medya Gh 已提交
484
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "APIServer")
J
Josh Woodcock 已提交
485 486
	}
	if _, ok := jsonObject["Kubeconfig"]; !ok {
M
Medya Gh 已提交
487
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Kubeconfig")
J
Josh Woodcock 已提交
488 489 490
	}
}

491 492
// validateDashboardCmd asserts that the dashboard command works
func validateDashboardCmd(ctx context.Context, t *testing.T, profile string) {
493 494
	defer PostMortemLogs(t, profile)

495 496 497
	args := []string{"dashboard", "--url", "-p", profile, "--alsologtostderr", "-v=1"}
	ss, err := Start(t, exec.CommandContext(ctx, Target(), args...))
	if err != nil {
498
		t.Errorf("failed to run minikube dashboard. args %q : %v", args, err)
499 500 501 502 503 504
	}
	defer func() {
		ss.Stop(t)
	}()

	start := time.Now()
M
Medya Gh 已提交
505
	s, err := ReadLineWithTimeout(ss.Stdout, Seconds(300))
506
	if err != nil {
T
tstromberg 已提交
507 508 509 510
		if runtime.GOOS == "windows" {
			t.Skipf("failed to read url within %s: %v\noutput: %q\n", time.Since(start), err, s)
		}
		t.Fatalf("failed to read url within %s: %v\noutput: %q\n", time.Since(start), err, s)
511 512 513 514 515 516 517 518 519
	}

	u, err := url.Parse(strings.TrimSpace(s))
	if err != nil {
		t.Fatalf("failed to parse %q: %v", s, err)
	}

	resp, err := retryablehttp.Get(u.String())
	if err != nil {
520
		t.Fatalf("failed to http get %q: %v\nresponse: %+v", u.String(), err, resp)
521
	}
522

523 524 525
	if resp.StatusCode != http.StatusOK {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
526
			t.Errorf("failed to read http response body from dashboard %q: %v", u.String(), err)
527 528 529 530
		}
		t.Errorf("%s returned status code %d, expected %d.\nbody:\n%s", u, resp.StatusCode, http.StatusOK, body)
	}
}
M
Medya Gh 已提交
531

T
Thomas Stromberg 已提交
532 533
// validateDryRun asserts that the dry-run mode quickly exits with the right code
func validateDryRun(ctx context.Context, t *testing.T, profile string) {
534
	// dry-run mode should always be able to finish quickly (<5s)
M
Medya Gh 已提交
535
	mctx, cancel := context.WithTimeout(ctx, Seconds(5))
T
Thomas Stromberg 已提交
536 537 538
	defer cancel()

	// Too little memory!
539
	startArgs := append([]string{"start", "-p", profile, "--dry-run", "--memory", "250MB", "--alsologtostderr"}, StartArgs()...)
T
Thomas Stromberg 已提交
540 541 542
	c := exec.CommandContext(mctx, Target(), startArgs...)
	rr, err := Run(t, c)

543
	wantCode := reason.ExInsufficientMemory
T
Thomas Stromberg 已提交
544 545 546 547
	if rr.ExitCode != wantCode {
		t.Errorf("dry-run(250MB) exit code = %d, wanted = %d: %v", rr.ExitCode, wantCode, err)
	}

M
Medya Gh 已提交
548
	dctx, cancel := context.WithTimeout(ctx, Seconds(5))
T
Thomas Stromberg 已提交
549
	defer cancel()
550
	startArgs = append([]string{"start", "-p", profile, "--dry-run", "--alsologtostderr", "-v=1"}, StartArgs()...)
T
Thomas Stromberg 已提交
551 552 553 554 555 556 557
	c = exec.CommandContext(dctx, Target(), startArgs...)
	rr, err = Run(t, c)
	if rr.ExitCode != 0 || err != nil {
		t.Errorf("dry-run exit code = %d, wanted = %d: %v", rr.ExitCode, 0, err)
	}
}

M
Medya Gh 已提交
558
// validateCacheCmd tests functionality of cache command (cache add, delete, list)
559
func validateCacheCmd(ctx context.Context, t *testing.T, profile string) {
560 561
	defer PostMortemLogs(t, profile)

562 563 564
	if NoneDriver() {
		t.Skipf("skipping: cache unsupported by none")
	}
565

M
Medya Gh 已提交
566
	t.Run("cache", func(t *testing.T) {
M
Medya Gh 已提交
567
		t.Run("add_remote", func(t *testing.T) {
S
Sharif Elgamal 已提交
568
			for _, img := range []string{"k8s.gcr.io/pause:3.1", "k8s.gcr.io/pause:3.3", "k8s.gcr.io/pause:latest"} {
569
				rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "add", img))
M
Medya Gh 已提交
570
				if err != nil {
M
Medya Gh 已提交
571
					t.Errorf("failed to 'cache add' remote image %q. args %q err %v", img, rr.Command(), err)
M
Medya Gh 已提交
572 573 574
				}
			}
		})
575 576

		t.Run("add_local", func(t *testing.T) {
577 578
			if GithubActionRunner() && runtime.GOOS == "darwin" {
				t.Skipf("skipping this test because Docker can not run in macos on github action free version. https://github.community/t/is-it-possible-to-install-and-configure-docker-on-macos-runner/16981")
S
Sharif Elgamal 已提交
579
			}
580

S
Sharif Elgamal 已提交
581 582 583
			_, err := exec.LookPath(oci.Docker)
			if err != nil {
				t.Skipf("docker is not installed, skipping local image test")
584 585
			}

586 587 588 589 590 591 592 593
			dname, err := ioutil.TempDir("", profile)
			if err != nil {
				t.Fatalf("Cannot create temp dir: %v", err)
			}

			message := []byte("FROM scratch\nADD Dockerfile /x")
			err = ioutil.WriteFile(filepath.Join(dname, "Dockerfile"), message, 0644)
			if err != nil {
M
Medya Gh 已提交
594
				t.Fatalf("unable to write Dockerfile: %v", err)
595 596 597
			}

			img := "minikube-local-cache-test:" + profile
T
Thomas Stromberg 已提交
598
			_, err = Run(t, exec.CommandContext(ctx, "docker", "build", "-t", img, dname))
599
			if err != nil {
S
Sharif Elgamal 已提交
600
				t.Skipf("failed to build docker image, skipping local test: %v", err)
601 602
			}

T
Thomas Stromberg 已提交
603
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "add", img))
604
			if err != nil {
M
Medya Gh 已提交
605
				t.Errorf("failed to 'cache add' local image %q. args %q err %v", img, rr.Command(), err)
606 607 608
			}
		})

M
Medya Gh 已提交
609 610
		t.Run("delete_k8s.gcr.io/pause:3.3", func(t *testing.T) {
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "delete", "k8s.gcr.io/pause:3.3"))
M
Medya Gh 已提交
611
			if err != nil {
M
Medya Gh 已提交
612
				t.Errorf("failed to delete image k8s.gcr.io/pause:3.3 from cache. args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
613 614
			}
		})
M
Medya Gh 已提交
615

M
Medya Gh 已提交
616 617 618
		t.Run("list", func(t *testing.T) {
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "list"))
			if err != nil {
M
Medya Gh 已提交
619
				t.Errorf("failed to do cache list. args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
620 621
			}
			if !strings.Contains(rr.Output(), "k8s.gcr.io/pause") {
M
Medya Gh 已提交
622
				t.Errorf("expected 'cache list' output to include 'k8s.gcr.io/pause' but got: ***%s***", rr.Output())
M
Medya Gh 已提交
623
			}
M
Medya Gh 已提交
624 625
			if strings.Contains(rr.Output(), "k8s.gcr.io/pause:3.3") {
				t.Errorf("expected 'cache list' output not to include k8s.gcr.io/pause:3.3 but got: ***%s***", rr.Output())
M
Medya Gh 已提交
626 627
			}
		})
M
Medya Gh 已提交
628

M
Medya Ghazizadeh 已提交
629
		t.Run("verify_cache_inside_node", func(t *testing.T) {
M
Medya Gh 已提交
630
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "images"))
M
Medya Gh 已提交
631
			if err != nil {
M
Medya Gh 已提交
632
				t.Errorf("failed to get images by %q ssh %v", rr.Command(), err)
M
Medya Gh 已提交
633
			}
634
			pauseID := imageID("pause")
I
Ilya Zuyev 已提交
635
			if !strings.Contains(rr.Output(), pauseID) {
636
				t.Errorf("expected sha for pause:3.3 %q to be in the output but got *%s*", pauseID, rr.Output())
M
Medya Gh 已提交
637 638
			}
		})
M
Medya Gh 已提交
639

M
Medya Ghazizadeh 已提交
640
		t.Run("cache_reload", func(t *testing.T) { // deleting image inside minikube node manually and expecting reload to bring it back
M
Medya Gh 已提交
641
			img := "k8s.gcr.io/pause:latest"
M
Medya Gh 已提交
642
			// deleting image inside minikube node manually
643 644 645 646 647 648 649 650 651 652

			var binary string
			switch ContainerRuntime() {
			case "docker":
				binary = "docker"
			case "containerd", "crio":
				binary = "crictl"
			}

			rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", binary, "rmi", img))
M
Medya Gh 已提交
653

M
Medya Gh 已提交
654
			if err != nil {
M
spell  
Medya Gh 已提交
655
				t.Errorf("failed to manually delete image %q : %v", rr.Command(), err)
M
Medya Gh 已提交
656 657 658 659
			}
			// make sure the image is deleted.
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "inspecti", img))
			if err == nil {
M
Medya Gh 已提交
660
				t.Errorf("expected an error  but got no error. image should not exist. ! cmd: %q", rr.Command())
M
Medya Gh 已提交
661
			}
M
Medya Gh 已提交
662
			// minikube cache reload.
M
Medya Gh 已提交
663 664
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "reload"))
			if err != nil {
665
				t.Errorf("expected %q to run successfully but got error: %v", rr.Command(), err)
M
Medya Gh 已提交
666
			}
M
Medya Gh 已提交
667
			// make sure 'cache reload' brought back the manually deleted image.
M
Medya Gh 已提交
668 669
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "inspecti", img))
			if err != nil {
670
				t.Errorf("expected %q to run successfully but got error: %v", rr.Command(), err)
M
Medya Gh 已提交
671 672 673
			}
		})

M
Medya Gh 已提交
674 675
		// delete will clean up the cached images since they are global and all other tests will load it for no reason
		t.Run("delete", func(t *testing.T) {
S
Sharif Elgamal 已提交
676
			for _, img := range []string{"k8s.gcr.io/pause:3.1", "k8s.gcr.io/pause:latest"} {
M
Medya Gh 已提交
677 678 679 680 681 682
				rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "delete", img))
				if err != nil {
					t.Errorf("failed to delete %s from cache. args %q: %v", img, rr.Command(), err)
				}
			}
		})
M
Medya Gh 已提交
683
	})
684 685 686 687 688 689 690 691 692 693 694
}

// validateConfigCmd asserts basic "config" command functionality
func validateConfigCmd(ctx context.Context, t *testing.T, profile string) {
	tests := []struct {
		args    []string
		wantOut string
		wantErr string
	}{
		{[]string{"unset", "cpus"}, "", ""},
		{[]string{"get", "cpus"}, "", "Error: specified key could not be found in config"},
T
Thomas Stromberg 已提交
695
		{[]string{"set", "cpus", "2"}, "", "! These changes will take effect upon a minikube delete and then a minikube start"},
696 697 698 699 700 701 702 703 704
		{[]string{"get", "cpus"}, "2", ""},
		{[]string{"unset", "cpus"}, "", ""},
		{[]string{"get", "cpus"}, "", "Error: specified key could not be found in config"},
	}

	for _, tc := range tests {
		args := append([]string{"-p", profile, "config"}, tc.args...)
		rr, err := Run(t, exec.CommandContext(ctx, Target(), args...))
		if err != nil && tc.wantErr == "" {
M
Medya Gh 已提交
705
			t.Errorf("failed to config minikube. args %q : %v", rr.Command(), err)
706 707 708 709
		}

		got := strings.TrimSpace(rr.Stdout.String())
		if got != tc.wantOut {
710
			t.Errorf("expected config output for %q to be -%q- but got *%q*", rr.Command(), tc.wantOut, got)
711 712 713
		}
		got = strings.TrimSpace(rr.Stderr.String())
		if got != tc.wantErr {
714
			t.Errorf("expected config error for %q to be -%q- but got *%q*", rr.Command(), tc.wantErr, got)
715 716 717 718 719 720 721 722
		}
	}
}

// validateLogsCmd asserts basic "logs" command functionality
func validateLogsCmd(ctx context.Context, t *testing.T, profile string) {
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "logs"))
	if err != nil {
M
Medya Gh 已提交
723
		t.Errorf("%s failed: %v", rr.Command(), err)
724
	}
725 726 727 728 729 730 731 732 733 734 735
	expectedWords := []string{"apiserver", "Linux", "kubelet"}
	switch ContainerRuntime() {
	case "docker":
		expectedWords = append(expectedWords, "Docker")
	case "containerd":
		expectedWords = append(expectedWords, "containerd")
	case "crio":
		expectedWords = append(expectedWords, "crio")
	}

	for _, word := range expectedWords {
736
		if !strings.Contains(rr.Stdout.String(), word) {
737
			t.Errorf("expected minikube logs to include word: -%q- but got \n***%s***\n", word, rr.Output())
738 739 740 741
		}
	}
}

J
Josh Woodcock 已提交
742
// validateProfileCmd asserts "profile" command functionality
743
func validateProfileCmd(ctx context.Context, t *testing.T, profile string) {
M
Medya Gh 已提交
744 745 746 747 748
	t.Run("profile_not_create", func(t *testing.T) {
		// Profile command should not create a nonexistent profile
		nonexistentProfile := "lis"
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", nonexistentProfile))
		if err != nil {
M
Medya Gh 已提交
749
			t.Errorf("%s failed: %v", rr.Command(), err)
M
Medya Gh 已提交
750 751 752
		}
		rr, err = Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "--output", "json"))
		if err != nil {
M
Medya Gh 已提交
753
			t.Errorf("%s failed: %v", rr.Command(), err)
M
Medya Gh 已提交
754 755 756 757
		}
		var profileJSON map[string][]map[string]interface{}
		err = json.Unmarshal(rr.Stdout.Bytes(), &profileJSON)
		if err != nil {
M
Medya Gh 已提交
758
			t.Errorf("%s failed: %v", rr.Command(), err)
M
Medya Gh 已提交
759 760 761 762 763 764 765
		}
		for profileK := range profileJSON {
			for _, p := range profileJSON[profileK] {
				var name = p["Name"]
				if name == nonexistentProfile {
					t.Errorf("minikube profile %s should not exist", nonexistentProfile)
				}
766
			}
767
		}
M
Medya Gh 已提交
768
	})
769

M
Medya Gh 已提交
770 771
	t.Run("profile_list", func(t *testing.T) {
		// List profiles
M
lint  
Medya Gh 已提交
772
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list"))
M
Medya Gh 已提交
773
		if err != nil {
M
Medya Gh 已提交
774
			t.Errorf("failed to list profiles: args %q : %v", rr.Command(), err)
M
Medya Gh 已提交
775
		}
J
Josh Woodcock 已提交
776

M
Medya Gh 已提交
777 778 779 780 781 782 783 784 785 786 787
		// Table output
		listLines := strings.Split(strings.TrimSpace(rr.Stdout.String()), "\n")
		profileExists := false
		for i := 3; i < (len(listLines) - 1); i++ {
			profileLine := listLines[i]
			if strings.Contains(profileLine, profile) {
				profileExists = true
				break
			}
		}
		if !profileExists {
M
Medya Gh 已提交
788
			t.Errorf("expected 'profile list' output to include %q but got *%q*. args: %q", profile, rr.Stdout.String(), rr.Command())
J
Josh Woodcock 已提交
789
		}
M
Medya Gh 已提交
790 791 792 793
	})

	t.Run("profile_json_output", func(t *testing.T) {
		// Json output
M
lint  
Medya Gh 已提交
794
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "--output", "json"))
M
Medya Gh 已提交
795
		if err != nil {
M
Medya Gh 已提交
796
			t.Errorf("failed to list profiles with json format. args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
797
		}
M
Medya Gh 已提交
798 799 800
		var jsonObject map[string][]map[string]interface{}
		err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
		if err != nil {
M
Medya Gh 已提交
801
			t.Errorf("failed to decode json from profile list: args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
802 803
		}
		validProfiles := jsonObject["valid"]
M
lint  
Medya Gh 已提交
804
		profileExists := false
M
Medya Gh 已提交
805 806 807 808 809 810 811
		for _, profileObject := range validProfiles {
			if profileObject["Name"] == profile {
				profileExists = true
				break
			}
		}
		if !profileExists {
M
Medya Gh 已提交
812
			t.Errorf("expected the json of 'profile list' to include %q but got *%q*. args: %q", profile, rr.Stdout.String(), rr.Command())
M
Medya Gh 已提交
813 814 815
		}

	})
816 817 818
}

// validateServiceCmd asserts basic "service" command functionality
819
func validateServiceCmd(ctx context.Context, t *testing.T, profile string) {
820 821
	defer PostMortemLogs(t, profile)

822 823 824
	defer func() {
		if t.Failed() {
			t.Logf("service test failed - dumping debug information")
825 826 827
			t.Logf("-----------------------service failure post-mortem--------------------------------")
			ctx, cancel := context.WithTimeout(context.Background(), Minutes(2))
			defer cancel()
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
			rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "describe", "po", "hello-node"))
			if err != nil {
				t.Logf("%q failed: %v", rr.Command(), err)
			}
			t.Logf("hello-node pod describe:\n%s", rr.Stdout)

			rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "logs", "-l", "app=hello-node"))
			if err != nil {
				t.Logf("%q failed: %v", rr.Command(), err)
			}
			t.Logf("hello-node logs:\n%s", rr.Stdout)

			rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "describe", "svc", "hello-node"))
			if err != nil {
				t.Logf("%q failed: %v", rr.Command(), err)
			}
			t.Logf("hello-node svc describe:\n%s", rr.Stdout)
		}
	}()

848 849 850
	var rr *RunResult
	var err error
	// k8s.gcr.io/echoserver is not multi-arch
I
Ilya Zuyev 已提交
851
	if arm64Platform() {
852
		rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "create", "deployment", "hello-node", "--image=k8s.gcr.io/echoserver-arm:1.8"))
I
Ilya Zuyev 已提交
853
	} else {
854
		rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "create", "deployment", "hello-node", "--image=k8s.gcr.io/echoserver:1.8"))
I
Ilya Zuyev 已提交
855 856
	}

857
	if err != nil {
858
		t.Fatalf("failed to create hello-node deployment with this command %q: %v.", rr.Command(), err)
859
	}
860
	rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "expose", "deployment", "hello-node", "--type=NodePort", "--port=8080"))
861
	if err != nil {
862
		t.Fatalf("failed to expose hello-node deployment: %q : %v", rr.Command(), err)
863 864
	}

865
	if _, err := PodWait(ctx, t, profile, "default", "app=hello-node", Minutes(10)); err != nil {
866
		t.Fatalf("failed waiting for hello-node pod: %v", err)
867 868
	}

869
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "list"))
870
	if err != nil {
M
Medya Gh 已提交
871
		t.Errorf("failed to do service list. args %q : %v", rr.Command(), err)
872
	}
873
	if !strings.Contains(rr.Stdout.String(), "hello-node") {
874
		t.Errorf("expected 'service list' to contain *hello-node* but got -%q-", rr.Stdout.String())
875 876
	}

877 878 879 880
	if NeedsPortForward() {
		t.Skipf("test is broken for port-forwarded drivers: https://github.com/kubernetes/minikube/issues/7383")
	}

T
Thomas Stromberg 已提交
881
	// Test --https --url mode
882
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "--namespace=default", "--https", "--url", "hello-node"))
883
	if err != nil {
M
Medya Gh 已提交
884
		t.Fatalf("failed to get service url. args %q : %v", rr.Command(), err)
885 886
	}
	if rr.Stderr.String() != "" {
M
Medya Gh 已提交
887
		t.Errorf("expected stderr to be empty but got *%q* . args %q", rr.Stderr, rr.Command())
888
	}
889

T
Thomas Stromberg 已提交
890
	endpoint := strings.TrimSpace(rr.Stdout.String())
891
	t.Logf("found endpoint: %s", endpoint)
T
Thomas Stromberg 已提交
892

893 894
	u, err := url.Parse(endpoint)
	if err != nil {
895
		t.Fatalf("failed to parse service url endpoint %q: %v", endpoint, err)
896 897
	}
	if u.Scheme != "https" {
898
		t.Errorf("expected scheme for %s to be 'https' but got %q", endpoint, u.Scheme)
899 900 901
	}

	// Test --format=IP
902
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "hello-node", "--url", "--format={{.IP}}"))
903
	if err != nil {
M
Medya Gh 已提交
904
		t.Errorf("failed to get service url with custom format. args %q: %v", rr.Command(), err)
905
	}
906
	if strings.TrimSpace(rr.Stdout.String()) != u.Hostname() {
M
Medya Gh 已提交
907
		t.Errorf("expected 'service --format={{.IP}}' output to be -%q- but got *%q* . args %q.", u.Hostname(), rr.Stdout.String(), rr.Command())
908 909
	}

910
	// Test a regular URL
911
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "hello-node", "--url"))
912
	if err != nil {
M
Medya Gh 已提交
913
		t.Errorf("failed to get service url. args: %q: %v", rr.Command(), err)
914
	}
915 916

	endpoint = strings.TrimSpace(rr.Stdout.String())
917 918
	t.Logf("found endpoint for hello-node: %s", endpoint)

919 920 921 922
	u, err = url.Parse(endpoint)
	if err != nil {
		t.Fatalf("failed to parse %q: %v", endpoint, err)
	}
923

924
	if u.Scheme != "http" {
M
lint  
Medya Gh 已提交
925
		t.Fatalf("expected scheme to be -%q- got scheme: *%q*", "http", u.Scheme)
926 927
	}

928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
	t.Logf("Attempting to fetch %s ...", endpoint)

	fetch := func() error {
		resp, err := http.Get(endpoint)
		if err != nil {
			t.Logf("error fetching %s: %v", endpoint, err)
			return err
		}

		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			t.Logf("error reading body from %s: %v", endpoint, err)
			return err
		}
		if resp.StatusCode != http.StatusOK {
			t.Logf("%s: unexpected status code %d - body:\n%s", endpoint, resp.StatusCode, body)
		} else {
			t.Logf("%s: success! body:\n%s", endpoint, body)
		}
		return nil
950
	}
951 952 953

	if err = retry.Expo(fetch, 1*time.Second, Seconds(30)); err != nil {
		t.Errorf("failed to fetch %s: %v", endpoint, err)
954 955 956
	}
}

957 958
// validateAddonsCmd asserts basic "addon" command functionality
func validateAddonsCmd(ctx context.Context, t *testing.T, profile string) {
959 960
	defer PostMortemLogs(t, profile)

M
Medya Gh 已提交
961
	// Table output
962 963
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "addons", "list"))
	if err != nil {
M
Medya Gh 已提交
964
		t.Errorf("failed to do addon list: args %q : %v", rr.Command(), err)
965
	}
M
Medya Gh 已提交
966 967
	for _, a := range []string{"dashboard", "ingress", "ingress-dns"} {
		if !strings.Contains(rr.Output(), a) {
M
Medya Gh 已提交
968
			t.Errorf("expected 'addon list' output to include -%q- but got *%s*", a, rr.Output())
969 970
		}
	}
J
Josh Woodcock 已提交
971 972 973 974

	// Json output
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "addons", "list", "-o", "json"))
	if err != nil {
M
Medya Gh 已提交
975
		t.Errorf("failed to do addon list with json output. args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
976 977 978 979
	}
	var jsonObject map[string]interface{}
	err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
	if err != nil {
980
		t.Errorf("failed to decode addon list json output : %v", err)
J
Josh Woodcock 已提交
981
	}
982 983
}

984 985
// validateSSHCmd asserts basic "ssh" command functionality
func validateSSHCmd(ctx context.Context, t *testing.T, profile string) {
986
	defer PostMortemLogs(t, profile)
987 988 989
	if NoneDriver() {
		t.Skipf("skipping: ssh unsupported by none")
	}
M
Medya Gh 已提交
990 991
	mctx, cancel := context.WithTimeout(ctx, Minutes(1))
	defer cancel()
M
Medya Gh 已提交
992

S
Sharif Elgamal 已提交
993
	want := "hello"
M
Medya Gh 已提交
994

M
Medya Gh 已提交
995 996
	rr, err := Run(t, exec.CommandContext(mctx, Target(), "-p", profile, "ssh", "echo hello"))
	if mctx.Err() == context.DeadlineExceeded {
M
try pwd  
Medya Gh 已提交
997 998 999 1000 1001
		t.Errorf("failed to run command by deadline. exceeded timeout : %s", rr.Command())
	}
	if err != nil {
		t.Errorf("failed to run an ssh command. args %q : %v", rr.Command(), err)
	}
1002
	// trailing whitespace differs between native and external SSH clients, so let's trim it and call it a day
S
Sharif Elgamal 已提交
1003
	if strings.TrimSpace(rr.Stdout.String()) != want {
M
try pwd  
Medya Gh 已提交
1004 1005 1006
		t.Errorf("expected minikube ssh command output to be -%q- but got *%q*. args %q", want, rr.Stdout.String(), rr.Command())
	}

M
Medya Gh 已提交
1007 1008
	// testing hostname as well because testing something like "minikube ssh echo" could be confusing
	// because it  is not clear if echo was run inside minikube on the powershell
M
Medya Gh 已提交
1009
	// so better to test something inside minikube, that is meaningful per profile
M
Medya Gh 已提交
1010
	// in this case /etc/hostname is same as the profile name
1011
	want = profile
M
Medya Gh 已提交
1012
	rr, err = Run(t, exec.CommandContext(mctx, Target(), "-p", profile, "ssh", "cat /etc/hostname"))
M
Medya Gh 已提交
1013
	if mctx.Err() == context.DeadlineExceeded {
M
try pwd  
Medya Gh 已提交
1014
		t.Errorf("failed to run command by deadline. exceeded timeout : %s", rr.Command())
M
Medya Gh 已提交
1015 1016
	}

1017
	if err != nil {
M
Medya Gh 已提交
1018
		t.Errorf("failed to run an ssh command. args %q : %v", rr.Command(), err)
1019
	}
S
Sharif Elgamal 已提交
1020
	// trailing whitespace differs between native and external SSH clients, so let's trim it and call it a day
S
Sharif Elgamal 已提交
1021
	if strings.TrimSpace(rr.Stdout.String()) != want {
M
Medya Gh 已提交
1022
		t.Errorf("expected minikube ssh command output to be -%q- but got *%q*. args %q", want, rr.Stdout.String(), rr.Command())
1023 1024 1025
	}
}

1026 1027
// validateMySQL validates a minimalist MySQL deployment
func validateMySQL(ctx context.Context, t *testing.T, profile string) {
I
Ilya Zuyev 已提交
1028
	if arm64Platform() {
1029
		t.Skip("arm64 is not supported by mysql. Skip the test. See https://github.com/kubernetes/minikube/issues/10144")
I
Ilya Zuyev 已提交
1030 1031
	}

1032 1033
	defer PostMortemLogs(t, profile)

1034 1035
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "replace", "--force", "-f", filepath.Join(*testdataDir, "mysql.yaml")))
	if err != nil {
M
Medya Gh 已提交
1036
		t.Fatalf("failed to kubectl replace mysql: args %q failed: %v", rr.Command(), err)
1037 1038
	}

1039
	names, err := PodWait(ctx, t, profile, "default", "app=mysql", Minutes(10))
1040
	if err != nil {
1041
		t.Fatalf("failed waiting for mysql pod: %v", err)
1042 1043
	}

1044 1045 1046 1047
	// Retry, as mysqld first comes up without users configured. Scan for names in case of a reschedule.
	mysql := func() error {
		rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "exec", names[0], "--", "mysql", "-ppassword", "-e", "show databases;"))
		return err
1048
	}
M
Medya Gh 已提交
1049
	if err = retry.Expo(mysql, 1*time.Second, Minutes(5)); err != nil {
1050
		t.Errorf("failed to exec 'mysql -ppassword -e show databases;': %v", err)
1051 1052 1053
	}
}

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
// vmSyncTestPath is where the test file will be synced into the VM
func vmSyncTestPath() string {
	return fmt.Sprintf("/etc/test/nested/copy/%d/hosts", os.Getpid())
}

// localSyncTestPath is where the test file will be synced into the VM
func localSyncTestPath() string {
	return filepath.Join(localpath.MiniPath(), "/files", vmSyncTestPath())
}

1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
// testCert is name of the test certificate installed
func testCert() string {
	return fmt.Sprintf("%d.pem", os.Getpid())
}

// localTestCertPath is where the test file will be synced into the VM
func localTestCertPath() string {
	return filepath.Join(localpath.MiniPath(), "/certs", testCert())
}

1074 1075 1076 1077 1078
// localEmptyCertPath is where the test file will be synced into the VM
func localEmptyCertPath() string {
	return filepath.Join(localpath.MiniPath(), "/certs", fmt.Sprintf("%d_empty.pem", os.Getpid()))
}

1079 1080
// Copy extra file into minikube home folder for file sync test
func setupFileSync(ctx context.Context, t *testing.T, profile string) {
1081 1082
	p := localSyncTestPath()
	t.Logf("local sync path: %s", p)
1083 1084
	syncFile := filepath.Join(*testdataDir, "sync.test")
	err := copy.Copy(syncFile, p)
1085
	if err != nil {
1086
		t.Fatalf("failed to copy testdata/sync.test: %v", err)
1087
	}
1088

1089
	testPem := filepath.Join(*testdataDir, "minikube_test.pem")
1090

1091 1092 1093
	// Write to a temp file for an atomic write
	tmpPem := localTestCertPath() + ".pem"
	if err := copy.Copy(testPem, tmpPem); err != nil {
1094 1095 1096
		t.Fatalf("failed to copy %s: %v", testPem, err)
	}

1097 1098 1099 1100
	if err := os.Rename(tmpPem, localTestCertPath()); err != nil {
		t.Fatalf("failed to rename %s: %v", tmpPem, err)
	}

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
	want, err := os.Stat(testPem)
	if err != nil {
		t.Fatalf("stat failed: %v", err)
	}

	got, err := os.Stat(localTestCertPath())
	if err != nil {
		t.Fatalf("stat failed: %v", err)
	}

	if want.Size() != got.Size() {
		t.Errorf("%s size=%d, want %d", localTestCertPath(), got.Size(), want.Size())
	}

	// Create an empty file just to mess with people
	if _, err := os.Create(localEmptyCertPath()); err != nil {
		t.Fatalf("create failed: %v", err)
1118
	}
1119 1120 1121 1122
}

// validateFileSync to check existence of the test file
func validateFileSync(ctx context.Context, t *testing.T, profile string) {
1123 1124
	defer PostMortemLogs(t, profile)

1125 1126 1127
	if NoneDriver() {
		t.Skipf("skipping: ssh unsupported by none")
	}
1128 1129 1130

	vp := vmSyncTestPath()
	t.Logf("Checking for existence of %s within VM", vp)
1131
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", fmt.Sprintf("sudo cat %s", vp)))
1132
	if err != nil {
M
Medya Gh 已提交
1133
		t.Errorf("%s failed: %v", rr.Command(), err)
1134
	}
1135 1136
	got := rr.Stdout.String()
	t.Logf("file sync test content: %s", got)
1137

1138 1139
	syncFile := filepath.Join(*testdataDir, "sync.test")
	expected, err := ioutil.ReadFile(syncFile)
1140
	if err != nil {
1141
		t.Errorf("failed to read test file 'testdata/sync.test' : %v", err)
1142 1143
	}

1144
	if diff := cmp.Diff(string(expected), got); diff != "" {
1145 1146 1147 1148
		t.Errorf("/etc/sync.test content mismatch (-want +got):\n%s", diff)
	}
}

1149 1150
// validateCertSync to check existence of the test certificate
func validateCertSync(ctx context.Context, t *testing.T, profile string) {
1151 1152
	defer PostMortemLogs(t, profile)

1153 1154 1155 1156
	if NoneDriver() {
		t.Skipf("skipping: ssh unsupported by none")
	}

1157 1158
	testPem := filepath.Join(*testdataDir, "minikube_test.pem")
	want, err := ioutil.ReadFile(testPem)
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
	if err != nil {
		t.Errorf("test file not found: %v", err)
	}

	// Check both the installed & reference certs (they should be symlinked)
	paths := []string{
		path.Join("/etc/ssl/certs", testCert()),
		path.Join("/usr/share/ca-certificates", testCert()),
		// hashed path generated by: 'openssl x509 -hash -noout -in testCert()'
		"/etc/ssl/certs/51391683.0",
	}
	for _, vp := range paths {
		t.Logf("Checking for existence of %s within VM", vp)
1172
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", fmt.Sprintf("sudo cat %s", vp)))
1173
		if err != nil {
M
Medya Gh 已提交
1174
			t.Errorf("failed to check existence of %q inside minikube. args %q: %v", vp, rr.Command(), err)
1175 1176 1177 1178 1179
		}

		// Strip carriage returned by ssh
		got := strings.Replace(rr.Stdout.String(), "\r", "", -1)
		if diff := cmp.Diff(string(want), got); diff != "" {
1180
			t.Errorf("failed verify pem file. minikube_test.pem -> %s mismatch (-want +got):\n%s", vp, diff)
1181 1182 1183 1184
		}
	}
}

1185 1186
// validateUpdateContextCmd asserts basic "update-context" command functionality
func validateUpdateContextCmd(ctx context.Context, t *testing.T, profile string) {
1187 1188
	defer PostMortemLogs(t, profile)

K
Kazuki Suda 已提交
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
	tests := []struct {
		name       string
		kubeconfig []byte
		want       []byte
	}{
		{
			name:       "no changes",
			kubeconfig: nil,
			want:       []byte("No changes"),
		},
		{
			name: "no minikube cluster",
			kubeconfig: []byte(`
apiVersion: v1
clusters:
- cluster:
    certificate-authority: /home/la-croix/apiserver.crt
    server: 192.168.1.1:8080
  name: la-croix
contexts:
- context:
    cluster: la-croix
    user: la-croix
  name: la-croix
current-context: la-croix
kind: Config
preferences: {}
users:
- name: la-croix
  user:
    client-certificate: /home/la-croix/apiserver.crt
    client-key: /home/la-croix/apiserver.key
`),
			want: []byte("context has been updated"),
		},
		{
			name: "no clusters",
			kubeconfig: []byte(`
apiVersion: v1
clusters:
contexts:
kind: Config
preferences: {}
users:
`),
			want: []byte("context has been updated"),
		},
1236 1237
	}

K
Kazuki Suda 已提交
1238 1239
	for _, tc := range tests {
		tc := tc
1240 1241 1242 1243 1244

		if ctx.Err() == context.DeadlineExceeded {
			t.Fatalf("Unable to run more tests (deadline exceeded)")
		}

K
Kazuki Suda 已提交
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()
			c := exec.CommandContext(ctx, Target(), "-p", profile, "update-context", "--alsologtostderr", "-v=2")
			if tc.kubeconfig != nil {
				tf, err := ioutil.TempFile("", "kubeconfig")
				if err != nil {
					t.Fatal(err)
				}

				if err := ioutil.WriteFile(tf.Name(), tc.kubeconfig, 0644); err != nil {
					t.Fatal(err)
				}

				t.Cleanup(func() {
					os.Remove(tf.Name())
				})

				c.Env = append(os.Environ(), fmt.Sprintf("KUBECONFIG=%s", tf.Name()))
			}

			rr, err := Run(t, c)
			if err != nil {
				t.Errorf("failed to run minikube update-context: args %q: %v", rr.Command(), err)
			}

			if !bytes.Contains(rr.Stdout.Bytes(), tc.want) {
				t.Errorf("update-context: got=%q, want=*%q*", rr.Stdout.Bytes(), tc.want)
			}
		})
1274 1275 1276
	}
}

1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
// startHTTPProxy runs a local http proxy and sets the env vars for it.
func startHTTPProxy(t *testing.T) (*http.Server, error) {
	port, err := freeport.GetFreePort()
	if err != nil {
		return nil, errors.Wrap(err, "Failed to get an open port")
	}

	addr := fmt.Sprintf("localhost:%d", port)
	proxy := goproxy.NewProxyHttpServer()
	srv := &http.Server{Addr: addr, Handler: proxy}
	go func(s *http.Server, t *testing.T) {
		if err := s.ListenAndServe(); err != http.ErrServerClosed {
			t.Errorf("Failed to start http server for proxy mock")
		}
	}(srv, t)
	return srv, nil
1293
}