functional_test.go 48.2 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
			{"LoadImage", validateLoadImage},
131 132 133
		}
		for _, tc := range tests {
			tc := tc
134 135 136 137
			if ctx.Err() == context.DeadlineExceeded {
				t.Fatalf("Unable to run more tests (deadline exceeded)")
			}

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

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

M
Medya Gh 已提交
150
	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 已提交
151
	if err != nil {
M
Medya Gh 已提交
152
		t.Errorf("failed to 'kubectl get nodes' with args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
153 154 155
	}
	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 已提交
156
		if !strings.Contains(rr.Output(), el) {
M
Medya Gh 已提交
157
			t.Errorf("expected to have label %q in node labels but got : %s", el, rr.Output())
M
Medya Gh 已提交
158 159 160 161
		}
	}
}

162 163
// validateLoadImage makes sure that `minikube load image` works as expected
func validateLoadImage(ctx context.Context, t *testing.T, profile string) {
P
Priya Wadhwa 已提交
164 165 166
	if NoneDriver() {
		t.Skip("load image not available on none driver")
	}
167 168 169
	if GithubActionRunner() && runtime.GOOS == "darwin" {
		t.Skip("skipping on github actions and darwin, as this test requires a running docker daemon")
	}
P
Priya Wadhwa 已提交
170
	defer PostMortemLogs(t, profile)
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
	// pull busybox
	busybox := "busybox:latest"
	rr, err := Run(t, exec.CommandContext(ctx, "docker", "pull", busybox))
	if err != nil {
		t.Fatalf("starting minikube: %v\n%s", err, rr.Output())
	}

	// tag busybox
	newImage := fmt.Sprintf("busybox:%s", profile)
	rr, err = Run(t, exec.CommandContext(ctx, "docker", "tag", busybox, newImage))
	if err != nil {
		t.Fatalf("starting minikube: %v\n%s", err, rr.Output())
	}

	// try to load the new image into minikube
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "image", "load", newImage))
	if err != nil {
		t.Fatalf("loading image into minikube: %v\n%s", err, rr.Output())
	}

	// make sure the image was correctly loaded
P
Priya Wadhwa 已提交
192 193 194 195 196 197 198
	var cmd *exec.Cmd
	if ContainerRuntime() == "docker" {
		cmd = exec.CommandContext(ctx, Target(), "ssh", "-p", profile, "--", "docker", "images", "--format", "{{.Repository}}:{{.Tag}}")
	} else {
		cmd = exec.CommandContext(ctx, Target(), "ssh", "-p", profile, "--", "sudo", "ctr", "-n=k8s.io", "image", "ls")
	}
	rr, err = Run(t, cmd)
199 200 201 202 203 204 205 206
	if err != nil {
		t.Fatalf("listing images: %v\n%s", err, rr.Output())
	}
	if !strings.Contains(rr.Output(), newImage) {
		t.Fatalf("expected %s to be loaded into minikube but the image is not there", newImage)
	}
}

207
// check functionality of minikube after evaling docker-env
P
Priya Wadhwa 已提交
208
// TODO: Add validatePodmanEnv for crio runtime: #10231
209
func validateDockerEnv(ctx context.Context, t *testing.T, profile string) {
210 211 212
	if cr := ContainerRuntime(); cr != "docker" {
		t.Skipf("only validate docker env with docker container runtime, currently testing %s", cr)
	}
213
	defer PostMortemLogs(t, profile)
214
	mctx, cancel := context.WithTimeout(ctx, Seconds(120))
215
	defer cancel()
M
Medya Gh 已提交
216 217
	var rr *RunResult
	var err error
M
Medya Gh 已提交
218
	if runtime.GOOS == "windows" {
M
Medya Gh 已提交
219 220
		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 已提交
221 222 223 224 225
	} 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 已提交
226 227
	if mctx.Err() == context.DeadlineExceeded {
		t.Errorf("failed to run the command by deadline. exceeded timeout. %s", rr.Command())
M
Medya Gh 已提交
228
	}
229
	if err != nil {
M
Medya Gh 已提交
230
		t.Fatalf("failed to do status after eval-ing docker-env. error: %v", err)
231 232
	}
	if !strings.Contains(rr.Output(), "Running") {
M
Medya Gh 已提交
233
		t.Fatalf("expected status output to include 'Running' after eval docker-env but got: *%s*", rr.Output())
234 235
	}

236
	mctx, cancel = context.WithTimeout(ctx, Seconds(60))
237 238
	defer cancel()
	// do a eval $(minikube -p profile docker-env) and check if we are point to docker inside minikube
M
Medya Gh 已提交
239
	if runtime.GOOS == "windows" { // testing docker-env eval in powershell
M
Medya Gh 已提交
240 241
		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 已提交
242
	} else {
M
Medya Gh 已提交
243
		c := exec.CommandContext(mctx, "/bin/bash", "-c", "eval $("+Target()+" -p "+profile+" docker-env) && docker images")
M
Medya Gh 已提交
244 245 246
		rr, err = Run(t, c)
	}

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

251
	if err != nil {
M
Medya Gh 已提交
252
		t.Fatalf("failed to run minikube docker-env. args %q : %v ", rr.Command(), err)
253 254 255 256
	}

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

}

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

265 266
	srv, err := startHTTPProxy(t)
	if err != nil {
267
		t.Fatalf("failed to set up the test proxy: %s", err)
268
	}
269 270

	// Use more memory so that we may reliably fit MySQL and nginx
M
Medya Gh 已提交
271
	// changing api server so later in soft start we verify it didn't change
272
	startArgs := append([]string{"start", "-p", profile, "--memory=4000", fmt.Sprintf("--apiserver-port=%d", apiPortTest), "--wait=true"}, StartArgs()...)
273
	c := exec.CommandContext(ctx, Target(), startArgs...)
274 275 276 277 278 279
	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 已提交
280
		t.Errorf("failed minikube start. args %q: %v", rr.Command(), err)
281 282 283 284 285 286 287 288 289 290 291
	}

	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)
	}
292 293 294 295

	t.Run("Audit", func(t *testing.T) {
		got, err := auditContains(profile)
		if err != nil {
296
			t.Fatalf("failed to check audit log: %v", err)
297 298 299 300 301
		}
		if !got {
			t.Errorf("audit.json does not contain the profile %q", profile)
		}
	})
302 303
}

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

M
Medya Gh 已提交
308
	start := time.Now()
M
Medya Gh 已提交
309
	// the test before this had been start with --apiserver-port=8441
M
lint  
Medya Gh 已提交
310 311
	beforeCfg, err := config.LoadProfile(profile)
	if err != nil {
312
		t.Fatalf("error reading cluster config before soft start: %v", err)
M
lint  
Medya Gh 已提交
313
	}
M
Medya Gh 已提交
314 315
	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 已提交
316 317
	}

M
typo  
Medya Gh 已提交
318
	softStartArgs := []string{"start", "-p", profile, "--alsologtostderr", "-v=8"}
M
Medya Gh 已提交
319
	c := exec.CommandContext(ctx, Target(), softStartArgs...)
M
lint  
Medya Gh 已提交
320
	rr, err := Run(t, c)
M
Medya Gh 已提交
321 322 323
	if err != nil {
		t.Errorf("failed to soft start minikube. args %q: %v", rr.Command(), err)
	}
M
Medya Gh 已提交
324
	t.Logf("soft start took %s for %q cluster.", time.Since(start), profile)
M
Medya Gh 已提交
325

M
lint  
Medya Gh 已提交
326 327 328 329 330
	afterCfg, err := config.LoadProfile(profile)
	if err != nil {
		t.Errorf("error reading cluster config after soft start: %v", err)
	}

M
Medya Gh 已提交
331 332
	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 已提交
333
	}
M
Medya Gh 已提交
334

335 336 337
	t.Run("Audit", func(t *testing.T) {
		got, err := auditContains(profile)
		if err != nil {
338
			t.Fatalf("failed to check audit log: %v", err)
339 340 341 342 343
		}
		if !got {
			t.Errorf("audit.json does not contain the profile %q", profile)
		}
	})
M
Medya Gh 已提交
344 345
}

346 347
// validateKubeContext asserts that kubectl is properly configured (race-condition prone!)
func validateKubeContext(ctx context.Context, t *testing.T, profile string) {
348 349
	defer PostMortemLogs(t, profile)

350 351
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "config", "current-context"))
	if err != nil {
M
Medya Gh 已提交
352
		t.Errorf("failed to get current-context. args %q : %v", rr.Command(), err)
353 354
	}
	if !strings.Contains(rr.Stdout.String(), profile) {
355
		t.Errorf("expected current-context = %q, but got *%q*", profile, rr.Stdout.String())
356 357 358
	}
}

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

363
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "po", "-A"))
P
Priya Wadhwa 已提交
364
	if err != nil {
M
Medya Gh 已提交
365
		t.Errorf("failed to get kubectl pods: args %q : %v", rr.Command(), err)
P
Priya Wadhwa 已提交
366
	}
367
	if rr.Stderr.String() != "" {
368
		t.Errorf("expected stderr to be empty but got *%q*: args %q", rr.Stderr, rr.Command())
369
	}
T
Thomas Stromberg 已提交
370
	if !strings.Contains(rr.Stdout.String(), "kube-system") {
371
		t.Errorf("expected stdout to include *kube-system* but got *%q*. args: %q", rr.Stdout, rr.Command())
P
Priya Wadhwa 已提交
372 373 374
	}
}

375 376
// validateMinikubeKubectl validates that the `minikube kubectl` command returns content
func validateMinikubeKubectl(ctx context.Context, t *testing.T, profile string) {
377 378
	defer PostMortemLogs(t, profile)

379 380
	// 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 已提交
381
	rr, err := Run(t, exec.CommandContext(ctx, Target(), kubectlArgs...))
382
	if err != nil {
M
Medya Gh 已提交
383
		t.Fatalf("failed to get pods. args %q: %v", rr.Command(), err)
384 385 386
	}
}

P
Pablo Caderno 已提交
387 388 389 390 391 392 393 394 395 396 397 398
// 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

399
	kubectlArgs := []string{"--context", profile, "get", "pods"}
P
Pablo Caderno 已提交
400 401
	rr, err := Run(t, exec.CommandContext(ctx, dstfn, kubectlArgs...))
	if err != nil {
402
		t.Fatalf("failed to run kubectl directly. args %q: %v", rr.Command(), err)
P
Pablo Caderno 已提交
403 404 405 406
	}

}

407 408 409 410 411
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 已提交
412
	startArgs := []string{"start", "-p", profile, "--extra-config=apiserver.enable-admission-plugins=NamespaceAutoProvision"}
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
	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 已提交
433 434 435
// 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'
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
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)
}

453 454
// validateComponentHealth asserts that all Kubernetes components are healthy
func validateComponentHealth(ctx context.Context, t *testing.T, profile string) {
455 456
	defer PostMortemLogs(t, profile)

457 458 459 460 461 462 463 464 465
	// 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"))
466
	if err != nil {
M
Medya Gh 已提交
467
		t.Fatalf("failed to get components. args %q: %v", rr.Command(), err)
468
	}
469
	cs := api.PodList{}
470 471
	d := json.NewDecoder(bytes.NewReader(rr.Stdout.Bytes()))
	if err := d.Decode(&cs); err != nil {
M
Medya Gh 已提交
472
		t.Fatalf("failed to decode kubectl json output: args %q : %v", rr.Command(), err)
473 474 475
	}

	for _, i := range cs.Items {
476
		for _, l := range i.Labels {
477
			if _, ok := found[l]; ok { // skip irrelevant (eg, repeating/redundant '"tier": "control-plane"') labels
478
				found[l] = true
479 480
				t.Logf("%s phase: %s", l, i.Status.Phase)
				if i.Status.Phase != api.PodRunning {
481
					t.Errorf("%s is not Running: %+v", l, i.Status)
482 483 484 485 486 487 488 489 490 491 492
					continue
				}
				for _, c := range i.Status.Conditions {
					if c.Type == api.PodReady {
						if c.Status != api.ConditionTrue {
							t.Errorf("%s is not Ready: %+v", l, i.Status)
						} else {
							t.Logf("%s status: %s", l, c.Type)
						}
						break
					}
493
				}
494 495
			}
		}
496 497 498 499 500
	}

	for k, v := range found {
		if !v {
			t.Errorf("expected component %q was not found", k)
501 502 503 504
		}
	}
}

J
Josh Woodcock 已提交
505
func validateStatusCmd(ctx context.Context, t *testing.T, profile string) {
506
	defer PostMortemLogs(t, profile)
507
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status"))
J
Josh Woodcock 已提交
508
	if err != nil {
M
Medya Gh 已提交
509
		t.Errorf("failed to run minikube status. args %q : %v", rr.Command(), err)
J
Josh Woodcock 已提交
510 511 512
	}

	// Custom format
513
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-f", "host:{{.Host}},kublet:{{.Kubelet}},apiserver:{{.APIServer}},kubeconfig:{{.Kubeconfig}}"))
J
Josh Woodcock 已提交
514
	if err != nil {
M
Medya Gh 已提交
515
		t.Errorf("failed to run minikube status with custom format: args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
516
	}
517 518
	re := `host:([A-z]+),kublet:([A-z]+),apiserver:([A-z]+),kubeconfig:([A-z]+)`
	match, _ := regexp.MatchString(re, rr.Stdout.String())
J
Josh Woodcock 已提交
519
	if !match {
M
Medya Gh 已提交
520
		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 已提交
521 522 523
	}

	// Json output
524
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-o", "json"))
J
Josh Woodcock 已提交
525
	if err != nil {
M
Medya Gh 已提交
526
		t.Errorf("failed to run minikube status with json output. args %q : %v", rr.Command(), err)
J
Josh Woodcock 已提交
527 528 529 530
	}
	var jsonObject map[string]interface{}
	err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
	if err != nil {
M
Medya Gh 已提交
531
		t.Errorf("failed to decode json from minikube status. args %q. %v", rr.Command(), err)
J
Josh Woodcock 已提交
532 533
	}
	if _, ok := jsonObject["Host"]; !ok {
M
Medya Gh 已提交
534
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Host")
J
Josh Woodcock 已提交
535 536
	}
	if _, ok := jsonObject["Kubelet"]; !ok {
M
Medya Gh 已提交
537
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Kubelet")
J
Josh Woodcock 已提交
538 539
	}
	if _, ok := jsonObject["APIServer"]; !ok {
M
Medya Gh 已提交
540
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "APIServer")
J
Josh Woodcock 已提交
541 542
	}
	if _, ok := jsonObject["Kubeconfig"]; !ok {
M
Medya Gh 已提交
543
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Kubeconfig")
J
Josh Woodcock 已提交
544 545 546
	}
}

547 548
// validateDashboardCmd asserts that the dashboard command works
func validateDashboardCmd(ctx context.Context, t *testing.T, profile string) {
549 550
	defer PostMortemLogs(t, profile)

551 552 553
	args := []string{"dashboard", "--url", "-p", profile, "--alsologtostderr", "-v=1"}
	ss, err := Start(t, exec.CommandContext(ctx, Target(), args...))
	if err != nil {
554
		t.Errorf("failed to run minikube dashboard. args %q : %v", args, err)
555 556 557 558 559 560
	}
	defer func() {
		ss.Stop(t)
	}()

	start := time.Now()
M
Medya Gh 已提交
561
	s, err := ReadLineWithTimeout(ss.Stdout, Seconds(300))
562
	if err != nil {
T
tstromberg 已提交
563 564 565 566
		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)
567 568 569 570 571 572 573 574 575
	}

	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 {
576
		t.Fatalf("failed to http get %q: %v\nresponse: %+v", u.String(), err, resp)
577
	}
578

579 580 581
	if resp.StatusCode != http.StatusOK {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
582
			t.Errorf("failed to read http response body from dashboard %q: %v", u.String(), err)
583 584 585 586
		}
		t.Errorf("%s returned status code %d, expected %d.\nbody:\n%s", u, resp.StatusCode, http.StatusOK, body)
	}
}
M
Medya Gh 已提交
587

T
Thomas Stromberg 已提交
588 589
// validateDryRun asserts that the dry-run mode quickly exits with the right code
func validateDryRun(ctx context.Context, t *testing.T, profile string) {
590
	// dry-run mode should always be able to finish quickly (<5s)
M
Medya Gh 已提交
591
	mctx, cancel := context.WithTimeout(ctx, Seconds(5))
T
Thomas Stromberg 已提交
592 593 594
	defer cancel()

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

599
	wantCode := reason.ExInsufficientMemory
T
Thomas Stromberg 已提交
600 601 602 603
	if rr.ExitCode != wantCode {
		t.Errorf("dry-run(250MB) exit code = %d, wanted = %d: %v", rr.ExitCode, wantCode, err)
	}

M
Medya Gh 已提交
604
	dctx, cancel := context.WithTimeout(ctx, Seconds(5))
T
Thomas Stromberg 已提交
605
	defer cancel()
606
	startArgs = append([]string{"start", "-p", profile, "--dry-run", "--alsologtostderr", "-v=1"}, StartArgs()...)
T
Thomas Stromberg 已提交
607 608 609 610 611 612 613
	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 已提交
614
// validateCacheCmd tests functionality of cache command (cache add, delete, list)
615
func validateCacheCmd(ctx context.Context, t *testing.T, profile string) {
616 617
	defer PostMortemLogs(t, profile)

618 619 620
	if NoneDriver() {
		t.Skipf("skipping: cache unsupported by none")
	}
621

M
Medya Gh 已提交
622
	t.Run("cache", func(t *testing.T) {
M
Medya Gh 已提交
623
		t.Run("add_remote", func(t *testing.T) {
S
Sharif Elgamal 已提交
624
			for _, img := range []string{"k8s.gcr.io/pause:3.1", "k8s.gcr.io/pause:3.3", "k8s.gcr.io/pause:latest"} {
625
				rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "add", img))
M
Medya Gh 已提交
626
				if err != nil {
M
Medya Gh 已提交
627
					t.Errorf("failed to 'cache add' remote image %q. args %q err %v", img, rr.Command(), err)
M
Medya Gh 已提交
628 629 630
				}
			}
		})
631 632

		t.Run("add_local", func(t *testing.T) {
633 634
			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 已提交
635
			}
636

S
Sharif Elgamal 已提交
637 638 639
			_, err := exec.LookPath(oci.Docker)
			if err != nil {
				t.Skipf("docker is not installed, skipping local image test")
640 641
			}

642 643 644 645 646 647 648 649
			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 已提交
650
				t.Fatalf("unable to write Dockerfile: %v", err)
651 652 653
			}

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

T
Thomas Stromberg 已提交
659
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "add", img))
660
			if err != nil {
M
Medya Gh 已提交
661
				t.Errorf("failed to 'cache add' local image %q. args %q err %v", img, rr.Command(), err)
662 663 664
			}
		})

M
Medya Gh 已提交
665 666
		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 已提交
667
			if err != nil {
M
Medya Gh 已提交
668
				t.Errorf("failed to delete image k8s.gcr.io/pause:3.3 from cache. args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
669 670
			}
		})
M
Medya Gh 已提交
671

M
Medya Gh 已提交
672 673 674
		t.Run("list", func(t *testing.T) {
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "list"))
			if err != nil {
M
Medya Gh 已提交
675
				t.Errorf("failed to do cache list. args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
676 677
			}
			if !strings.Contains(rr.Output(), "k8s.gcr.io/pause") {
M
Medya Gh 已提交
678
				t.Errorf("expected 'cache list' output to include 'k8s.gcr.io/pause' but got: ***%s***", rr.Output())
M
Medya Gh 已提交
679
			}
M
Medya Gh 已提交
680 681
			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 已提交
682 683
			}
		})
M
Medya Gh 已提交
684

M
Medya Ghazizadeh 已提交
685
		t.Run("verify_cache_inside_node", func(t *testing.T) {
M
Medya Gh 已提交
686
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "images"))
M
Medya Gh 已提交
687
			if err != nil {
M
Medya Gh 已提交
688
				t.Errorf("failed to get images by %q ssh %v", rr.Command(), err)
M
Medya Gh 已提交
689
			}
690
			pauseID := imageID("pause")
I
Ilya Zuyev 已提交
691
			if !strings.Contains(rr.Output(), pauseID) {
692
				t.Errorf("expected sha for pause:3.3 %q to be in the output but got *%s*", pauseID, rr.Output())
M
Medya Gh 已提交
693 694
			}
		})
M
Medya Gh 已提交
695

M
Medya Ghazizadeh 已提交
696
		t.Run("cache_reload", func(t *testing.T) { // deleting image inside minikube node manually and expecting reload to bring it back
M
Medya Gh 已提交
697
			img := "k8s.gcr.io/pause:latest"
M
Medya Gh 已提交
698
			// deleting image inside minikube node manually
699 700 701 702 703 704 705 706 707 708

			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 已提交
709

M
Medya Gh 已提交
710
			if err != nil {
M
spell  
Medya Gh 已提交
711
				t.Errorf("failed to manually delete image %q : %v", rr.Command(), err)
M
Medya Gh 已提交
712 713 714 715
			}
			// 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 已提交
716
				t.Errorf("expected an error  but got no error. image should not exist. ! cmd: %q", rr.Command())
M
Medya Gh 已提交
717
			}
M
Medya Gh 已提交
718
			// minikube cache reload.
M
Medya Gh 已提交
719 720
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "reload"))
			if err != nil {
721
				t.Errorf("expected %q to run successfully but got error: %v", rr.Command(), err)
M
Medya Gh 已提交
722
			}
M
Medya Gh 已提交
723
			// make sure 'cache reload' brought back the manually deleted image.
M
Medya Gh 已提交
724 725
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "inspecti", img))
			if err != nil {
726
				t.Errorf("expected %q to run successfully but got error: %v", rr.Command(), err)
M
Medya Gh 已提交
727 728 729
			}
		})

M
Medya Gh 已提交
730 731
		// 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 已提交
732
			for _, img := range []string{"k8s.gcr.io/pause:3.1", "k8s.gcr.io/pause:latest"} {
M
Medya Gh 已提交
733 734 735 736 737 738
				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 已提交
739
	})
740 741 742 743 744 745 746 747 748 749 750
}

// 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 已提交
751
		{[]string{"set", "cpus", "2"}, "", "! These changes will take effect upon a minikube delete and then a minikube start"},
752 753 754 755 756 757 758 759 760
		{[]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 已提交
761
			t.Errorf("failed to config minikube. args %q : %v", rr.Command(), err)
762 763 764 765
		}

		got := strings.TrimSpace(rr.Stdout.String())
		if got != tc.wantOut {
766
			t.Errorf("expected config output for %q to be -%q- but got *%q*", rr.Command(), tc.wantOut, got)
767 768 769
		}
		got = strings.TrimSpace(rr.Stderr.String())
		if got != tc.wantErr {
770
			t.Errorf("expected config error for %q to be -%q- but got *%q*", rr.Command(), tc.wantErr, got)
771 772 773 774 775 776 777 778
		}
	}
}

// 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 已提交
779
		t.Errorf("%s failed: %v", rr.Command(), err)
780
	}
781 782 783 784 785 786 787 788 789 790 791
	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 {
792
		if !strings.Contains(rr.Stdout.String(), word) {
793
			t.Errorf("expected minikube logs to include word: -%q- but got \n***%s***\n", word, rr.Output())
794 795 796 797
		}
	}
}

J
Josh Woodcock 已提交
798
// validateProfileCmd asserts "profile" command functionality
799
func validateProfileCmd(ctx context.Context, t *testing.T, profile string) {
M
Medya Gh 已提交
800 801 802 803 804
	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 已提交
805
			t.Errorf("%s failed: %v", rr.Command(), err)
M
Medya Gh 已提交
806 807 808
		}
		rr, err = Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "--output", "json"))
		if err != nil {
M
Medya Gh 已提交
809
			t.Errorf("%s failed: %v", rr.Command(), err)
M
Medya Gh 已提交
810 811 812 813
		}
		var profileJSON map[string][]map[string]interface{}
		err = json.Unmarshal(rr.Stdout.Bytes(), &profileJSON)
		if err != nil {
M
Medya Gh 已提交
814
			t.Errorf("%s failed: %v", rr.Command(), err)
M
Medya Gh 已提交
815 816 817 818 819 820 821
		}
		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)
				}
822
			}
823
		}
M
Medya Gh 已提交
824
	})
825

M
Medya Gh 已提交
826
	t.Run("profile_list", func(t *testing.T) {
827 828 829 830 831 832 833 834 835 836 837 838
		// helper function to run command then, return target profile line from table output.
		extractrofileListFunc := func(rr *RunResult) string {
			listLines := strings.Split(strings.TrimSpace(rr.Stdout.String()), "\n")
			for i := 3; i < (len(listLines) - 1); i++ {
				profileLine := listLines[i]
				if strings.Contains(profileLine, profile) {
					return profileLine
				}
			}
			return ""
		}

M
Medya Gh 已提交
839
		// List profiles
840
		start := time.Now()
M
lint  
Medya Gh 已提交
841
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list"))
842
		elapsed := time.Since(start)
M
Medya Gh 已提交
843
		if err != nil {
M
Medya Gh 已提交
844
			t.Errorf("failed to list profiles: args %q : %v", rr.Command(), err)
M
Medya Gh 已提交
845
		}
846
		t.Logf("Took %q to run %q", elapsed, rr.Command())
J
Josh Woodcock 已提交
847

848 849
		profileLine := extractrofileListFunc(rr)
		if profileLine == "" {
M
Medya Gh 已提交
850
			t.Errorf("expected 'profile list' output to include %q but got *%q*. args: %q", profile, rr.Stdout.String(), rr.Command())
J
Josh Woodcock 已提交
851
		}
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869

		// List profiles with light option.
		start = time.Now()
		lrr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "-l"))
		lightElapsed := time.Since(start)
		if err != nil {
			t.Errorf("failed to list profiles: args %q : %v", lrr.Command(), err)
		}
		t.Logf("Took %q to run %q", lightElapsed, lrr.Command())

		profileLine = extractrofileListFunc(lrr)
		if profileLine == "" || !strings.Contains(profileLine, "Skipped") {
			t.Errorf("expected 'profile list' output to include %q with 'Skipped' status but got *%q*. args: %q", profile, rr.Stdout.String(), rr.Command())
		}

		if lightElapsed > 3*time.Second {
			t.Errorf("expected running time of '%q' is less than 3 seconds. Took %q ", lrr.Command(), lightElapsed)
		}
M
Medya Gh 已提交
870 871 872
	})

	t.Run("profile_json_output", func(t *testing.T) {
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
		// helper function to run command then, return target profile object from json output.
		extractProfileObjFunc := func(rr *RunResult) *config.Profile {
			var jsonObject map[string][]config.Profile
			err := json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
			if err != nil {
				t.Errorf("failed to decode json from profile list: args %q: %v", rr.Command(), err)
				return nil
			}

			for _, profileObject := range jsonObject["valid"] {
				if profileObject.Name == profile {
					return &profileObject
				}
			}
			return nil
		}

		start := time.Now()
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "-o", "json"))
		elapsed := time.Since(start)
M
Medya Gh 已提交
893
		if err != nil {
M
Medya Gh 已提交
894
			t.Errorf("failed to list profiles with json format. args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
895
		}
896 897 898 899 900 901 902 903 904 905
		t.Logf("Took %q to run %q", elapsed, rr.Command())

		pr := extractProfileObjFunc(rr)
		if pr == nil {
			t.Errorf("expected the json of 'profile list' to include %q but got *%q*. args: %q", profile, rr.Stdout.String(), rr.Command())
		}

		start = time.Now()
		lrr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "-o", "json", "--light"))
		lightElapsed := time.Since(start)
M
Medya Gh 已提交
906
		if err != nil {
907
			t.Errorf("failed to list profiles with json format. args %q: %v", lrr.Command(), err)
M
Medya Gh 已提交
908
		}
909 910 911 912 913
		t.Logf("Took %q to run %q", lightElapsed, lrr.Command())

		pr = extractProfileObjFunc(lrr)
		if pr == nil || pr.Status != "Skipped" {
			t.Errorf("expected the json of 'profile list' to include 'Skipped' status for %q but got *%q*. args: %q", profile, lrr.Stdout.String(), lrr.Command())
M
Medya Gh 已提交
914 915
		}

916 917 918
		if lightElapsed > 3*time.Second {
			t.Errorf("expected running time of '%q' is less than 3 seconds. Took %q ", lrr.Command(), lightElapsed)
		}
M
Medya Gh 已提交
919
	})
920 921 922
}

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

926 927 928
	defer func() {
		if t.Failed() {
			t.Logf("service test failed - dumping debug information")
929 930 931
			t.Logf("-----------------------service failure post-mortem--------------------------------")
			ctx, cancel := context.WithTimeout(context.Background(), Minutes(2))
			defer cancel()
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
			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)
		}
	}()

952 953 954
	var rr *RunResult
	var err error
	// k8s.gcr.io/echoserver is not multi-arch
I
Ilya Zuyev 已提交
955
	if arm64Platform() {
956
		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 已提交
957
	} else {
958
		rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "create", "deployment", "hello-node", "--image=k8s.gcr.io/echoserver:1.8"))
I
Ilya Zuyev 已提交
959 960
	}

961
	if err != nil {
962
		t.Fatalf("failed to create hello-node deployment with this command %q: %v.", rr.Command(), err)
963
	}
964
	rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "expose", "deployment", "hello-node", "--type=NodePort", "--port=8080"))
965
	if err != nil {
966
		t.Fatalf("failed to expose hello-node deployment: %q : %v", rr.Command(), err)
967 968
	}

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

973
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "list"))
974
	if err != nil {
M
Medya Gh 已提交
975
		t.Errorf("failed to do service list. args %q : %v", rr.Command(), err)
976
	}
977
	if !strings.Contains(rr.Stdout.String(), "hello-node") {
978
		t.Errorf("expected 'service list' to contain *hello-node* but got -%q-", rr.Stdout.String())
979 980
	}

981 982 983 984
	if NeedsPortForward() {
		t.Skipf("test is broken for port-forwarded drivers: https://github.com/kubernetes/minikube/issues/7383")
	}

T
Thomas Stromberg 已提交
985
	// Test --https --url mode
986
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "--namespace=default", "--https", "--url", "hello-node"))
987
	if err != nil {
M
Medya Gh 已提交
988
		t.Fatalf("failed to get service url. args %q : %v", rr.Command(), err)
989 990
	}
	if rr.Stderr.String() != "" {
M
Medya Gh 已提交
991
		t.Errorf("expected stderr to be empty but got *%q* . args %q", rr.Stderr, rr.Command())
992
	}
993

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

997 998
	u, err := url.Parse(endpoint)
	if err != nil {
999
		t.Fatalf("failed to parse service url endpoint %q: %v", endpoint, err)
1000 1001
	}
	if u.Scheme != "https" {
1002
		t.Errorf("expected scheme for %s to be 'https' but got %q", endpoint, u.Scheme)
1003 1004 1005
	}

	// Test --format=IP
1006
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "hello-node", "--url", "--format={{.IP}}"))
1007
	if err != nil {
M
Medya Gh 已提交
1008
		t.Errorf("failed to get service url with custom format. args %q: %v", rr.Command(), err)
1009
	}
1010
	if strings.TrimSpace(rr.Stdout.String()) != u.Hostname() {
M
Medya Gh 已提交
1011
		t.Errorf("expected 'service --format={{.IP}}' output to be -%q- but got *%q* . args %q.", u.Hostname(), rr.Stdout.String(), rr.Command())
1012 1013
	}

1014
	// Test a regular URL
1015
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "hello-node", "--url"))
1016
	if err != nil {
M
Medya Gh 已提交
1017
		t.Errorf("failed to get service url. args: %q: %v", rr.Command(), err)
1018
	}
1019 1020

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

1023 1024 1025 1026
	u, err = url.Parse(endpoint)
	if err != nil {
		t.Fatalf("failed to parse %q: %v", endpoint, err)
	}
1027

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

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
	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
1054
	}
1055 1056 1057

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

1061 1062
// validateAddonsCmd asserts basic "addon" command functionality
func validateAddonsCmd(ctx context.Context, t *testing.T, profile string) {
1063 1064
	defer PostMortemLogs(t, profile)

M
Medya Gh 已提交
1065
	// Table output
1066 1067
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "addons", "list"))
	if err != nil {
M
Medya Gh 已提交
1068
		t.Errorf("failed to do addon list: args %q : %v", rr.Command(), err)
1069
	}
M
Medya Gh 已提交
1070 1071
	for _, a := range []string{"dashboard", "ingress", "ingress-dns"} {
		if !strings.Contains(rr.Output(), a) {
M
Medya Gh 已提交
1072
			t.Errorf("expected 'addon list' output to include -%q- but got *%s*", a, rr.Output())
1073 1074
		}
	}
J
Josh Woodcock 已提交
1075 1076 1077 1078

	// Json output
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "addons", "list", "-o", "json"))
	if err != nil {
M
Medya Gh 已提交
1079
		t.Errorf("failed to do addon list with json output. args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
1080 1081 1082 1083
	}
	var jsonObject map[string]interface{}
	err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
	if err != nil {
1084
		t.Errorf("failed to decode addon list json output : %v", err)
J
Josh Woodcock 已提交
1085
	}
1086 1087
}

1088 1089
// validateSSHCmd asserts basic "ssh" command functionality
func validateSSHCmd(ctx context.Context, t *testing.T, profile string) {
1090
	defer PostMortemLogs(t, profile)
1091 1092 1093
	if NoneDriver() {
		t.Skipf("skipping: ssh unsupported by none")
	}
M
Medya Gh 已提交
1094 1095
	mctx, cancel := context.WithTimeout(ctx, Minutes(1))
	defer cancel()
M
Medya Gh 已提交
1096

S
Sharif Elgamal 已提交
1097
	want := "hello"
M
Medya Gh 已提交
1098

M
Medya Gh 已提交
1099 1100
	rr, err := Run(t, exec.CommandContext(mctx, Target(), "-p", profile, "ssh", "echo hello"))
	if mctx.Err() == context.DeadlineExceeded {
M
try pwd  
Medya Gh 已提交
1101 1102 1103 1104 1105
		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)
	}
1106
	// trailing whitespace differs between native and external SSH clients, so let's trim it and call it a day
S
Sharif Elgamal 已提交
1107
	if strings.TrimSpace(rr.Stdout.String()) != want {
M
try pwd  
Medya Gh 已提交
1108 1109 1110
		t.Errorf("expected minikube ssh command output to be -%q- but got *%q*. args %q", want, rr.Stdout.String(), rr.Command())
	}

M
Medya Gh 已提交
1111 1112
	// 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 已提交
1113
	// so better to test something inside minikube, that is meaningful per profile
M
Medya Gh 已提交
1114
	// in this case /etc/hostname is same as the profile name
1115
	want = profile
M
Medya Gh 已提交
1116
	rr, err = Run(t, exec.CommandContext(mctx, Target(), "-p", profile, "ssh", "cat /etc/hostname"))
M
Medya Gh 已提交
1117
	if mctx.Err() == context.DeadlineExceeded {
M
try pwd  
Medya Gh 已提交
1118
		t.Errorf("failed to run command by deadline. exceeded timeout : %s", rr.Command())
M
Medya Gh 已提交
1119 1120
	}

1121
	if err != nil {
M
Medya Gh 已提交
1122
		t.Errorf("failed to run an ssh command. args %q : %v", rr.Command(), err)
1123
	}
S
Sharif Elgamal 已提交
1124
	// trailing whitespace differs between native and external SSH clients, so let's trim it and call it a day
S
Sharif Elgamal 已提交
1125
	if strings.TrimSpace(rr.Stdout.String()) != want {
M
Medya Gh 已提交
1126
		t.Errorf("expected minikube ssh command output to be -%q- but got *%q*. args %q", want, rr.Stdout.String(), rr.Command())
1127 1128 1129
	}
}

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

1136 1137
	defer PostMortemLogs(t, profile)

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

1143
	names, err := PodWait(ctx, t, profile, "default", "app=mysql", Minutes(10))
1144
	if err != nil {
1145
		t.Fatalf("failed waiting for mysql pod: %v", err)
1146 1147
	}

1148 1149 1150 1151
	// 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
1152
	}
M
Medya Gh 已提交
1153
	if err = retry.Expo(mysql, 1*time.Second, Minutes(5)); err != nil {
1154
		t.Errorf("failed to exec 'mysql -ppassword -e show databases;': %v", err)
1155 1156 1157
	}
}

1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
// 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())
}

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
// 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())
}

1178 1179 1180 1181 1182
// 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()))
}

1183 1184
// Copy extra file into minikube home folder for file sync test
func setupFileSync(ctx context.Context, t *testing.T, profile string) {
1185 1186
	p := localSyncTestPath()
	t.Logf("local sync path: %s", p)
1187 1188
	syncFile := filepath.Join(*testdataDir, "sync.test")
	err := copy.Copy(syncFile, p)
1189
	if err != nil {
1190
		t.Fatalf("failed to copy testdata/sync.test: %v", err)
1191
	}
1192

1193
	testPem := filepath.Join(*testdataDir, "minikube_test.pem")
1194

1195 1196 1197
	// Write to a temp file for an atomic write
	tmpPem := localTestCertPath() + ".pem"
	if err := copy.Copy(testPem, tmpPem); err != nil {
1198 1199 1200
		t.Fatalf("failed to copy %s: %v", testPem, err)
	}

1201 1202 1203 1204
	if err := os.Rename(tmpPem, localTestCertPath()); err != nil {
		t.Fatalf("failed to rename %s: %v", tmpPem, err)
	}

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
	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)
1222
	}
1223 1224 1225 1226
}

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

1229 1230 1231
	if NoneDriver() {
		t.Skipf("skipping: ssh unsupported by none")
	}
1232 1233 1234

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

1242 1243
	syncFile := filepath.Join(*testdataDir, "sync.test")
	expected, err := ioutil.ReadFile(syncFile)
1244
	if err != nil {
1245
		t.Errorf("failed to read test file 'testdata/sync.test' : %v", err)
1246 1247
	}

1248
	if diff := cmp.Diff(string(expected), got); diff != "" {
1249 1250 1251 1252
		t.Errorf("/etc/sync.test content mismatch (-want +got):\n%s", diff)
	}
}

1253 1254
// validateCertSync to check existence of the test certificate
func validateCertSync(ctx context.Context, t *testing.T, profile string) {
1255 1256
	defer PostMortemLogs(t, profile)

1257 1258 1259 1260
	if NoneDriver() {
		t.Skipf("skipping: ssh unsupported by none")
	}

1261 1262
	testPem := filepath.Join(*testdataDir, "minikube_test.pem")
	want, err := ioutil.ReadFile(testPem)
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
	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)
1276
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", fmt.Sprintf("sudo cat %s", vp)))
1277
		if err != nil {
M
Medya Gh 已提交
1278
			t.Errorf("failed to check existence of %q inside minikube. args %q: %v", vp, rr.Command(), err)
1279 1280 1281 1282 1283
		}

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

1289 1290
// validateUpdateContextCmd asserts basic "update-context" command functionality
func validateUpdateContextCmd(ctx context.Context, t *testing.T, profile string) {
1291 1292
	defer PostMortemLogs(t, profile)

K
Kazuki Suda 已提交
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
	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"),
		},
1340 1341
	}

K
Kazuki Suda 已提交
1342 1343
	for _, tc := range tests {
		tc := tc
1344 1345 1346 1347 1348

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

K
Kazuki Suda 已提交
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
		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)
			}
		})
1378 1379 1380
	}
}

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
// 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
1397
}