functional_test.go 45.8 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 167
	if NoneDriver() {
		t.Skip("load image not available on none driver")
	}
	defer PostMortemLogs(t, profile)
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
	// 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 已提交
189 190 191 192 193 194 195
	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)
196 197 198 199 200 201 202 203
	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)
	}
}

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

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

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

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

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

}

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

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

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

	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)
	}
289 290 291 292

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

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

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

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

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

M
Medya Gh 已提交
328 329
	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 已提交
330
	}
M
Medya Gh 已提交
331

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

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

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

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

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

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

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

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

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

}

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

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

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

	for _, i := range cs.Items {
473 474 475 476 477 478 479 480
		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)
				}
481 482
			}
		}
483 484 485 486 487
	}

	for k, v := range found {
		if !v {
			t.Errorf("expected component %q was not found", k)
488 489 490 491
		}
	}
}

J
Josh Woodcock 已提交
492
func validateStatusCmd(ctx context.Context, t *testing.T, profile string) {
493
	defer PostMortemLogs(t, profile)
494
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status"))
J
Josh Woodcock 已提交
495
	if err != nil {
M
Medya Gh 已提交
496
		t.Errorf("failed to run minikube status. args %q : %v", rr.Command(), err)
J
Josh Woodcock 已提交
497 498 499
	}

	// Custom format
500
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-f", "host:{{.Host}},kublet:{{.Kubelet}},apiserver:{{.APIServer}},kubeconfig:{{.Kubeconfig}}"))
J
Josh Woodcock 已提交
501
	if err != nil {
M
Medya Gh 已提交
502
		t.Errorf("failed to run minikube status with custom format: args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
503
	}
504 505
	re := `host:([A-z]+),kublet:([A-z]+),apiserver:([A-z]+),kubeconfig:([A-z]+)`
	match, _ := regexp.MatchString(re, rr.Stdout.String())
J
Josh Woodcock 已提交
506
	if !match {
M
Medya Gh 已提交
507
		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 已提交
508 509 510
	}

	// Json output
511
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-o", "json"))
J
Josh Woodcock 已提交
512
	if err != nil {
M
Medya Gh 已提交
513
		t.Errorf("failed to run minikube status with json output. args %q : %v", rr.Command(), err)
J
Josh Woodcock 已提交
514 515 516 517
	}
	var jsonObject map[string]interface{}
	err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
	if err != nil {
M
Medya Gh 已提交
518
		t.Errorf("failed to decode json from minikube status. args %q. %v", rr.Command(), err)
J
Josh Woodcock 已提交
519 520
	}
	if _, ok := jsonObject["Host"]; !ok {
M
Medya Gh 已提交
521
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Host")
J
Josh Woodcock 已提交
522 523
	}
	if _, ok := jsonObject["Kubelet"]; !ok {
M
Medya Gh 已提交
524
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Kubelet")
J
Josh Woodcock 已提交
525 526
	}
	if _, ok := jsonObject["APIServer"]; !ok {
M
Medya Gh 已提交
527
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "APIServer")
J
Josh Woodcock 已提交
528 529
	}
	if _, ok := jsonObject["Kubeconfig"]; !ok {
M
Medya Gh 已提交
530
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Kubeconfig")
J
Josh Woodcock 已提交
531 532 533
	}
}

534 535
// validateDashboardCmd asserts that the dashboard command works
func validateDashboardCmd(ctx context.Context, t *testing.T, profile string) {
536 537
	defer PostMortemLogs(t, profile)

538 539 540
	args := []string{"dashboard", "--url", "-p", profile, "--alsologtostderr", "-v=1"}
	ss, err := Start(t, exec.CommandContext(ctx, Target(), args...))
	if err != nil {
541
		t.Errorf("failed to run minikube dashboard. args %q : %v", args, err)
542 543 544 545 546 547
	}
	defer func() {
		ss.Stop(t)
	}()

	start := time.Now()
M
Medya Gh 已提交
548
	s, err := ReadLineWithTimeout(ss.Stdout, Seconds(300))
549
	if err != nil {
T
tstromberg 已提交
550 551 552 553
		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)
554 555 556 557 558 559 560 561 562
	}

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

566 567 568
	if resp.StatusCode != http.StatusOK {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
569
			t.Errorf("failed to read http response body from dashboard %q: %v", u.String(), err)
570 571 572 573
		}
		t.Errorf("%s returned status code %d, expected %d.\nbody:\n%s", u, resp.StatusCode, http.StatusOK, body)
	}
}
M
Medya Gh 已提交
574

T
Thomas Stromberg 已提交
575 576
// validateDryRun asserts that the dry-run mode quickly exits with the right code
func validateDryRun(ctx context.Context, t *testing.T, profile string) {
577
	// dry-run mode should always be able to finish quickly (<5s)
M
Medya Gh 已提交
578
	mctx, cancel := context.WithTimeout(ctx, Seconds(5))
T
Thomas Stromberg 已提交
579 580 581
	defer cancel()

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

586
	wantCode := reason.ExInsufficientMemory
T
Thomas Stromberg 已提交
587 588 589 590
	if rr.ExitCode != wantCode {
		t.Errorf("dry-run(250MB) exit code = %d, wanted = %d: %v", rr.ExitCode, wantCode, err)
	}

M
Medya Gh 已提交
591
	dctx, cancel := context.WithTimeout(ctx, Seconds(5))
T
Thomas Stromberg 已提交
592
	defer cancel()
593
	startArgs = append([]string{"start", "-p", profile, "--dry-run", "--alsologtostderr", "-v=1"}, StartArgs()...)
T
Thomas Stromberg 已提交
594 595 596 597 598 599 600
	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 已提交
601
// validateCacheCmd tests functionality of cache command (cache add, delete, list)
602
func validateCacheCmd(ctx context.Context, t *testing.T, profile string) {
603 604
	defer PostMortemLogs(t, profile)

605 606 607
	if NoneDriver() {
		t.Skipf("skipping: cache unsupported by none")
	}
608

M
Medya Gh 已提交
609
	t.Run("cache", func(t *testing.T) {
M
Medya Gh 已提交
610
		t.Run("add_remote", func(t *testing.T) {
S
Sharif Elgamal 已提交
611
			for _, img := range []string{"k8s.gcr.io/pause:3.1", "k8s.gcr.io/pause:3.3", "k8s.gcr.io/pause:latest"} {
612
				rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "add", img))
M
Medya Gh 已提交
613
				if err != nil {
M
Medya Gh 已提交
614
					t.Errorf("failed to 'cache add' remote image %q. args %q err %v", img, rr.Command(), err)
M
Medya Gh 已提交
615 616 617
				}
			}
		})
618 619

		t.Run("add_local", func(t *testing.T) {
620 621
			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 已提交
622
			}
623

S
Sharif Elgamal 已提交
624 625 626
			_, err := exec.LookPath(oci.Docker)
			if err != nil {
				t.Skipf("docker is not installed, skipping local image test")
627 628
			}

629 630 631 632 633 634 635 636
			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 已提交
637
				t.Fatalf("unable to write Dockerfile: %v", err)
638 639 640
			}

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

T
Thomas Stromberg 已提交
646
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "add", img))
647
			if err != nil {
M
Medya Gh 已提交
648
				t.Errorf("failed to 'cache add' local image %q. args %q err %v", img, rr.Command(), err)
649 650 651
			}
		})

M
Medya Gh 已提交
652 653
		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 已提交
654
			if err != nil {
M
Medya Gh 已提交
655
				t.Errorf("failed to delete image k8s.gcr.io/pause:3.3 from cache. args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
656 657
			}
		})
M
Medya Gh 已提交
658

M
Medya Gh 已提交
659 660 661
		t.Run("list", func(t *testing.T) {
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "list"))
			if err != nil {
M
Medya Gh 已提交
662
				t.Errorf("failed to do cache list. args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
663 664
			}
			if !strings.Contains(rr.Output(), "k8s.gcr.io/pause") {
M
Medya Gh 已提交
665
				t.Errorf("expected 'cache list' output to include 'k8s.gcr.io/pause' but got: ***%s***", rr.Output())
M
Medya Gh 已提交
666
			}
M
Medya Gh 已提交
667 668
			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 已提交
669 670
			}
		})
M
Medya Gh 已提交
671

M
Medya Ghazizadeh 已提交
672
		t.Run("verify_cache_inside_node", func(t *testing.T) {
M
Medya Gh 已提交
673
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "images"))
M
Medya Gh 已提交
674
			if err != nil {
M
Medya Gh 已提交
675
				t.Errorf("failed to get images by %q ssh %v", rr.Command(), err)
M
Medya Gh 已提交
676
			}
677
			pauseID := imageID("pause")
I
Ilya Zuyev 已提交
678
			if !strings.Contains(rr.Output(), pauseID) {
679
				t.Errorf("expected sha for pause:3.3 %q to be in the output but got *%s*", pauseID, rr.Output())
M
Medya Gh 已提交
680 681
			}
		})
M
Medya Gh 已提交
682

M
Medya Ghazizadeh 已提交
683
		t.Run("cache_reload", func(t *testing.T) { // deleting image inside minikube node manually and expecting reload to bring it back
M
Medya Gh 已提交
684
			img := "k8s.gcr.io/pause:latest"
M
Medya Gh 已提交
685
			// deleting image inside minikube node manually
686 687 688 689 690 691 692 693 694 695

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

M
Medya Gh 已提交
697
			if err != nil {
M
spell  
Medya Gh 已提交
698
				t.Errorf("failed to manually delete image %q : %v", rr.Command(), err)
M
Medya Gh 已提交
699 700 701 702
			}
			// 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 已提交
703
				t.Errorf("expected an error  but got no error. image should not exist. ! cmd: %q", rr.Command())
M
Medya Gh 已提交
704
			}
M
Medya Gh 已提交
705
			// minikube cache reload.
M
Medya Gh 已提交
706 707
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "reload"))
			if err != nil {
708
				t.Errorf("expected %q to run successfully but got error: %v", rr.Command(), err)
M
Medya Gh 已提交
709
			}
M
Medya Gh 已提交
710
			// make sure 'cache reload' brought back the manually deleted image.
M
Medya Gh 已提交
711 712
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "inspecti", img))
			if err != nil {
713
				t.Errorf("expected %q to run successfully but got error: %v", rr.Command(), err)
M
Medya Gh 已提交
714 715 716
			}
		})

M
Medya Gh 已提交
717 718
		// 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 已提交
719
			for _, img := range []string{"k8s.gcr.io/pause:3.1", "k8s.gcr.io/pause:latest"} {
M
Medya Gh 已提交
720 721 722 723 724 725
				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 已提交
726
	})
727 728 729 730 731 732 733 734 735 736 737
}

// 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 已提交
738
		{[]string{"set", "cpus", "2"}, "", "! These changes will take effect upon a minikube delete and then a minikube start"},
739 740 741 742 743 744 745 746 747
		{[]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 已提交
748
			t.Errorf("failed to config minikube. args %q : %v", rr.Command(), err)
749 750 751 752
		}

		got := strings.TrimSpace(rr.Stdout.String())
		if got != tc.wantOut {
753
			t.Errorf("expected config output for %q to be -%q- but got *%q*", rr.Command(), tc.wantOut, got)
754 755 756
		}
		got = strings.TrimSpace(rr.Stderr.String())
		if got != tc.wantErr {
757
			t.Errorf("expected config error for %q to be -%q- but got *%q*", rr.Command(), tc.wantErr, got)
758 759 760 761 762 763 764 765
		}
	}
}

// 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 已提交
766
		t.Errorf("%s failed: %v", rr.Command(), err)
767
	}
768 769 770 771 772 773 774 775 776 777 778
	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 {
779
		if !strings.Contains(rr.Stdout.String(), word) {
780
			t.Errorf("expected minikube logs to include word: -%q- but got \n***%s***\n", word, rr.Output())
781 782 783 784
		}
	}
}

J
Josh Woodcock 已提交
785
// validateProfileCmd asserts "profile" command functionality
786
func validateProfileCmd(ctx context.Context, t *testing.T, profile string) {
M
Medya Gh 已提交
787 788 789 790 791
	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 已提交
792
			t.Errorf("%s failed: %v", rr.Command(), err)
M
Medya Gh 已提交
793 794 795
		}
		rr, err = Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "--output", "json"))
		if err != nil {
M
Medya Gh 已提交
796
			t.Errorf("%s failed: %v", rr.Command(), err)
M
Medya Gh 已提交
797 798 799 800
		}
		var profileJSON map[string][]map[string]interface{}
		err = json.Unmarshal(rr.Stdout.Bytes(), &profileJSON)
		if err != nil {
M
Medya Gh 已提交
801
			t.Errorf("%s failed: %v", rr.Command(), err)
M
Medya Gh 已提交
802 803 804 805 806 807 808
		}
		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)
				}
809
			}
810
		}
M
Medya Gh 已提交
811
	})
812

M
Medya Gh 已提交
813 814
	t.Run("profile_list", func(t *testing.T) {
		// List profiles
M
lint  
Medya Gh 已提交
815
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list"))
M
Medya Gh 已提交
816
		if err != nil {
M
Medya Gh 已提交
817
			t.Errorf("failed to list profiles: args %q : %v", rr.Command(), err)
M
Medya Gh 已提交
818
		}
J
Josh Woodcock 已提交
819

M
Medya Gh 已提交
820 821 822 823 824 825 826 827 828 829 830
		// 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 已提交
831
			t.Errorf("expected 'profile list' output to include %q but got *%q*. args: %q", profile, rr.Stdout.String(), rr.Command())
J
Josh Woodcock 已提交
832
		}
M
Medya Gh 已提交
833 834 835 836
	})

	t.Run("profile_json_output", func(t *testing.T) {
		// Json output
M
lint  
Medya Gh 已提交
837
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "--output", "json"))
M
Medya Gh 已提交
838
		if err != nil {
M
Medya Gh 已提交
839
			t.Errorf("failed to list profiles with json format. args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
840
		}
M
Medya Gh 已提交
841 842 843
		var jsonObject map[string][]map[string]interface{}
		err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
		if err != nil {
M
Medya Gh 已提交
844
			t.Errorf("failed to decode json from profile list: args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
845 846
		}
		validProfiles := jsonObject["valid"]
M
lint  
Medya Gh 已提交
847
		profileExists := false
M
Medya Gh 已提交
848 849 850 851 852 853 854
		for _, profileObject := range validProfiles {
			if profileObject["Name"] == profile {
				profileExists = true
				break
			}
		}
		if !profileExists {
M
Medya Gh 已提交
855
			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 已提交
856 857 858
		}

	})
859 860 861
}

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

865 866 867
	defer func() {
		if t.Failed() {
			t.Logf("service test failed - dumping debug information")
868 869 870
			t.Logf("-----------------------service failure post-mortem--------------------------------")
			ctx, cancel := context.WithTimeout(context.Background(), Minutes(2))
			defer cancel()
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
			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)
		}
	}()

891 892 893
	var rr *RunResult
	var err error
	// k8s.gcr.io/echoserver is not multi-arch
I
Ilya Zuyev 已提交
894
	if arm64Platform() {
895
		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 已提交
896
	} else {
897
		rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "create", "deployment", "hello-node", "--image=k8s.gcr.io/echoserver:1.8"))
I
Ilya Zuyev 已提交
898 899
	}

900
	if err != nil {
901
		t.Fatalf("failed to create hello-node deployment with this command %q: %v.", rr.Command(), err)
902
	}
903
	rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "expose", "deployment", "hello-node", "--type=NodePort", "--port=8080"))
904
	if err != nil {
905
		t.Fatalf("failed to expose hello-node deployment: %q : %v", rr.Command(), err)
906 907
	}

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

912
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "list"))
913
	if err != nil {
M
Medya Gh 已提交
914
		t.Errorf("failed to do service list. args %q : %v", rr.Command(), err)
915
	}
916
	if !strings.Contains(rr.Stdout.String(), "hello-node") {
917
		t.Errorf("expected 'service list' to contain *hello-node* but got -%q-", rr.Stdout.String())
918 919
	}

920 921 922 923
	if NeedsPortForward() {
		t.Skipf("test is broken for port-forwarded drivers: https://github.com/kubernetes/minikube/issues/7383")
	}

T
Thomas Stromberg 已提交
924
	// Test --https --url mode
925
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "--namespace=default", "--https", "--url", "hello-node"))
926
	if err != nil {
M
Medya Gh 已提交
927
		t.Fatalf("failed to get service url. args %q : %v", rr.Command(), err)
928 929
	}
	if rr.Stderr.String() != "" {
M
Medya Gh 已提交
930
		t.Errorf("expected stderr to be empty but got *%q* . args %q", rr.Stderr, rr.Command())
931
	}
932

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

936 937
	u, err := url.Parse(endpoint)
	if err != nil {
938
		t.Fatalf("failed to parse service url endpoint %q: %v", endpoint, err)
939 940
	}
	if u.Scheme != "https" {
941
		t.Errorf("expected scheme for %s to be 'https' but got %q", endpoint, u.Scheme)
942 943 944
	}

	// Test --format=IP
945
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "hello-node", "--url", "--format={{.IP}}"))
946
	if err != nil {
M
Medya Gh 已提交
947
		t.Errorf("failed to get service url with custom format. args %q: %v", rr.Command(), err)
948
	}
949
	if strings.TrimSpace(rr.Stdout.String()) != u.Hostname() {
M
Medya Gh 已提交
950
		t.Errorf("expected 'service --format={{.IP}}' output to be -%q- but got *%q* . args %q.", u.Hostname(), rr.Stdout.String(), rr.Command())
951 952
	}

953
	// Test a regular URL
954
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "hello-node", "--url"))
955
	if err != nil {
M
Medya Gh 已提交
956
		t.Errorf("failed to get service url. args: %q: %v", rr.Command(), err)
957
	}
958 959

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

962 963 964 965
	u, err = url.Parse(endpoint)
	if err != nil {
		t.Fatalf("failed to parse %q: %v", endpoint, err)
	}
966

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

971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
	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
993
	}
994 995 996

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

1000 1001
// validateAddonsCmd asserts basic "addon" command functionality
func validateAddonsCmd(ctx context.Context, t *testing.T, profile string) {
1002 1003
	defer PostMortemLogs(t, profile)

M
Medya Gh 已提交
1004
	// Table output
1005 1006
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "addons", "list"))
	if err != nil {
M
Medya Gh 已提交
1007
		t.Errorf("failed to do addon list: args %q : %v", rr.Command(), err)
1008
	}
M
Medya Gh 已提交
1009 1010
	for _, a := range []string{"dashboard", "ingress", "ingress-dns"} {
		if !strings.Contains(rr.Output(), a) {
M
Medya Gh 已提交
1011
			t.Errorf("expected 'addon list' output to include -%q- but got *%s*", a, rr.Output())
1012 1013
		}
	}
J
Josh Woodcock 已提交
1014 1015 1016 1017

	// Json output
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "addons", "list", "-o", "json"))
	if err != nil {
M
Medya Gh 已提交
1018
		t.Errorf("failed to do addon list with json output. args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
1019 1020 1021 1022
	}
	var jsonObject map[string]interface{}
	err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
	if err != nil {
1023
		t.Errorf("failed to decode addon list json output : %v", err)
J
Josh Woodcock 已提交
1024
	}
1025 1026
}

1027 1028
// validateSSHCmd asserts basic "ssh" command functionality
func validateSSHCmd(ctx context.Context, t *testing.T, profile string) {
1029
	defer PostMortemLogs(t, profile)
1030 1031 1032
	if NoneDriver() {
		t.Skipf("skipping: ssh unsupported by none")
	}
M
Medya Gh 已提交
1033 1034
	mctx, cancel := context.WithTimeout(ctx, Minutes(1))
	defer cancel()
M
Medya Gh 已提交
1035

S
Sharif Elgamal 已提交
1036
	want := "hello"
M
Medya Gh 已提交
1037

M
Medya Gh 已提交
1038 1039
	rr, err := Run(t, exec.CommandContext(mctx, Target(), "-p", profile, "ssh", "echo hello"))
	if mctx.Err() == context.DeadlineExceeded {
M
try pwd  
Medya Gh 已提交
1040 1041 1042 1043 1044
		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)
	}
1045
	// trailing whitespace differs between native and external SSH clients, so let's trim it and call it a day
S
Sharif Elgamal 已提交
1046
	if strings.TrimSpace(rr.Stdout.String()) != want {
M
try pwd  
Medya Gh 已提交
1047 1048 1049
		t.Errorf("expected minikube ssh command output to be -%q- but got *%q*. args %q", want, rr.Stdout.String(), rr.Command())
	}

M
Medya Gh 已提交
1050 1051
	// 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 已提交
1052
	// so better to test something inside minikube, that is meaningful per profile
M
Medya Gh 已提交
1053
	// in this case /etc/hostname is same as the profile name
1054
	want = profile
M
Medya Gh 已提交
1055
	rr, err = Run(t, exec.CommandContext(mctx, Target(), "-p", profile, "ssh", "cat /etc/hostname"))
M
Medya Gh 已提交
1056
	if mctx.Err() == context.DeadlineExceeded {
M
try pwd  
Medya Gh 已提交
1057
		t.Errorf("failed to run command by deadline. exceeded timeout : %s", rr.Command())
M
Medya Gh 已提交
1058 1059
	}

1060
	if err != nil {
M
Medya Gh 已提交
1061
		t.Errorf("failed to run an ssh command. args %q : %v", rr.Command(), err)
1062
	}
S
Sharif Elgamal 已提交
1063
	// trailing whitespace differs between native and external SSH clients, so let's trim it and call it a day
S
Sharif Elgamal 已提交
1064
	if strings.TrimSpace(rr.Stdout.String()) != want {
M
Medya Gh 已提交
1065
		t.Errorf("expected minikube ssh command output to be -%q- but got *%q*. args %q", want, rr.Stdout.String(), rr.Command())
1066 1067 1068
	}
}

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

1075 1076
	defer PostMortemLogs(t, profile)

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

1082
	names, err := PodWait(ctx, t, profile, "default", "app=mysql", Minutes(10))
1083
	if err != nil {
1084
		t.Fatalf("failed waiting for mysql pod: %v", err)
1085 1086
	}

1087 1088 1089 1090
	// 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
1091
	}
M
Medya Gh 已提交
1092
	if err = retry.Expo(mysql, 1*time.Second, Minutes(5)); err != nil {
1093
		t.Errorf("failed to exec 'mysql -ppassword -e show databases;': %v", err)
1094 1095 1096
	}
}

1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
// 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())
}

1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
// 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())
}

1117 1118 1119 1120 1121
// 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()))
}

1122 1123
// Copy extra file into minikube home folder for file sync test
func setupFileSync(ctx context.Context, t *testing.T, profile string) {
1124 1125
	p := localSyncTestPath()
	t.Logf("local sync path: %s", p)
1126 1127
	syncFile := filepath.Join(*testdataDir, "sync.test")
	err := copy.Copy(syncFile, p)
1128
	if err != nil {
1129
		t.Fatalf("failed to copy testdata/sync.test: %v", err)
1130
	}
1131

1132
	testPem := filepath.Join(*testdataDir, "minikube_test.pem")
1133

1134 1135 1136
	// Write to a temp file for an atomic write
	tmpPem := localTestCertPath() + ".pem"
	if err := copy.Copy(testPem, tmpPem); err != nil {
1137 1138 1139
		t.Fatalf("failed to copy %s: %v", testPem, err)
	}

1140 1141 1142 1143
	if err := os.Rename(tmpPem, localTestCertPath()); err != nil {
		t.Fatalf("failed to rename %s: %v", tmpPem, err)
	}

1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
	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)
1161
	}
1162 1163 1164 1165
}

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

1168 1169 1170
	if NoneDriver() {
		t.Skipf("skipping: ssh unsupported by none")
	}
1171 1172 1173

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

1181 1182
	syncFile := filepath.Join(*testdataDir, "sync.test")
	expected, err := ioutil.ReadFile(syncFile)
1183
	if err != nil {
1184
		t.Errorf("failed to read test file 'testdata/sync.test' : %v", err)
1185 1186
	}

1187
	if diff := cmp.Diff(string(expected), got); diff != "" {
1188 1189 1190 1191
		t.Errorf("/etc/sync.test content mismatch (-want +got):\n%s", diff)
	}
}

1192 1193
// validateCertSync to check existence of the test certificate
func validateCertSync(ctx context.Context, t *testing.T, profile string) {
1194 1195
	defer PostMortemLogs(t, profile)

1196 1197 1198 1199
	if NoneDriver() {
		t.Skipf("skipping: ssh unsupported by none")
	}

1200 1201
	testPem := filepath.Join(*testdataDir, "minikube_test.pem")
	want, err := ioutil.ReadFile(testPem)
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
	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)
1215
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", fmt.Sprintf("sudo cat %s", vp)))
1216
		if err != nil {
M
Medya Gh 已提交
1217
			t.Errorf("failed to check existence of %q inside minikube. args %q: %v", vp, rr.Command(), err)
1218 1219 1220 1221 1222
		}

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

1228 1229
// validateUpdateContextCmd asserts basic "update-context" command functionality
func validateUpdateContextCmd(ctx context.Context, t *testing.T, profile string) {
1230 1231
	defer PostMortemLogs(t, profile)

K
Kazuki Suda 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 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 1274 1275 1276 1277 1278
	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"),
		},
1279 1280
	}

K
Kazuki Suda 已提交
1281 1282
	for _, tc := range tests {
		tc := tc
1283 1284 1285 1286 1287

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

K
Kazuki Suda 已提交
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
		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)
			}
		})
1317 1318 1319
	}
}

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
// 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
1336
}