functional_test.go 32.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"

M
Medya Gh 已提交
41
	"k8s.io/minikube/pkg/minikube/config"
42 43
	"k8s.io/minikube/pkg/minikube/localpath"

44 45
	"github.com/elazarl/goproxy"
	"github.com/hashicorp/go-retryablehttp"
46
	"github.com/otiai10/copy"
47 48 49
	"github.com/phayes/freeport"
	"github.com/pkg/errors"
	"golang.org/x/build/kubernetes/api"
M
Medya Gh 已提交
50
	"k8s.io/minikube/pkg/minikube/config"
51
	"k8s.io/minikube/pkg/util/retry"
52 53
)

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

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

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

	// Serial tests
	t.Run("serial", func(t *testing.T) {
		tests := []struct {
			name      string
			validator validateFunc
		}{
83 84
			{"CopySyncFile", setupFileSync},                 // Set file for the file sync test case
			{"StartWithProxy", validateStartWithProxy},      // Set everything else up for success
M
Medya Gh 已提交
85
			{"SoftStart", validateSoftStart},                // do a soft start. ensure config didnt change.
86 87 88 89
			{"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
90 91 92 93
		}
		for _, tc := range tests {
			tc := tc
			t.Run(tc.name, func(t *testing.T) {
M
Medya Gh 已提交
94 95 96 97 98 99
				if strings.Contains(tc.name, "StartWithProxy") || strings.Contains(tc.name, "SoftStart") {
					tc.validator(ctx, t, profile, 8441)
				} else {
					tc.validator(ctx, t, profile)
				}

100
			})
M
Medya Gh 已提交
101
		}
102
	})
M
Medya Gh 已提交
103

104 105 106 107 108 109 110 111 112 113 114 115 116
	// Now that we are out of the woods, lets go.
	MaybeParallel(t)

	// Parallelized tests
	t.Run("parallel", func(t *testing.T) {
		tests := []struct {
			name      string
			validator validateFunc
		}{
			{"ComponentHealth", validateComponentHealth},
			{"ConfigCmd", validateConfigCmd},
			{"DashboardCmd", validateDashboardCmd},
			{"DNS", validateDNS},
T
Thomas Stromberg 已提交
117
			{"DryRun", validateDryRun},
J
Josh Woodcock 已提交
118
			{"StatusCmd", validateStatusCmd},
119 120 121
			{"LogsCmd", validateLogsCmd},
			{"MountCmd", validateMountCmd},
			{"ProfileCmd", validateProfileCmd},
122
			{"ServiceCmd", validateServiceCmd},
123
			{"AddonsCmd", validateAddonsCmd},
124 125 126
			{"PersistentVolumeClaim", validatePersistentVolumeClaim},
			{"TunnelCmd", validateTunnelCmd},
			{"SSHCmd", validateSSHCmd},
127
			{"MySQL", validateMySQL},
128
			{"FileSync", validateFileSync},
129
			{"CertSync", validateCertSync},
130
			{"UpdateContextCmd", validateUpdateContextCmd},
131
			{"DockerEnv", validateDockerEnv},
M
Medya Gh 已提交
132
			{"NodeLabels", validateNodeLabels},
133 134 135 136 137 138 139 140
		}
		for _, tc := range tests {
			tc := tc
			t.Run(tc.name, func(t *testing.T) {
				MaybeParallel(t)
				tc.validator(ctx, t, profile)
			})
		}
M
Medya Gh 已提交
141
	})
142 143
}

M
Medya Gh 已提交
144 145
// validateNodeLabels checks if minikube cluster is created with correct kubernetes's node label
func validateNodeLabels(ctx context.Context, t *testing.T, profile string) {
M
Medya Gh 已提交
146
	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 已提交
147
	if err != nil {
M
Medya Gh 已提交
148
		t.Errorf("failed to 'kubectl get nodes' with args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
149 150 151
	}
	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 已提交
152
		if !strings.Contains(rr.Output(), el) {
M
Medya Gh 已提交
153
			t.Errorf("expected to have label %q in node labels but got : %s", el, rr.Output())
M
Medya Gh 已提交
154 155 156 157
		}
	}
}

158 159
// check functionality of minikube after evaling docker-env
func validateDockerEnv(ctx context.Context, t *testing.T, profile string) {
M
Medya Gh 已提交
160
	mctx, cancel := context.WithTimeout(ctx, Seconds(13))
161 162 163 164 165
	defer cancel()
	// we should be able to get minikube status with a bash which evaled docker-env
	c := exec.CommandContext(mctx, "/bin/bash", "-c", "eval $("+Target()+" -p "+profile+" docker-env) && "+Target()+" status -p "+profile)
	rr, err := Run(t, c)
	if err != nil {
166
		t.Fatalf("failed to do minikube status after eval-ing docker-env %s", err)
167 168
	}
	if !strings.Contains(rr.Output(), "Running") {
M
Medya Gh 已提交
169
		t.Fatalf("expected status output to include 'Running' after eval docker-env but got: *%s*", rr.Output())
170 171
	}

M
Medya Gh 已提交
172
	mctx, cancel = context.WithTimeout(ctx, Seconds(13))
173 174 175 176 177
	defer cancel()
	// do a eval $(minikube -p profile docker-env) and check if we are point to docker inside minikube
	c = exec.CommandContext(mctx, "/bin/bash", "-c", "eval $("+Target()+" -p "+profile+" docker-env) && docker images")
	rr, err = Run(t, c)
	if err != nil {
M
Medya Gh 已提交
178
		t.Fatalf("failed to run minikube docker-env. args %q : %v ", rr.Command(), err)
179 180 181 182
	}

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

}

M
Medya Gh 已提交
188
func validateStartWithProxy(ctx context.Context, t *testing.T, profile string, apiServerPort int) {
189 190
	srv, err := startHTTPProxy(t)
	if err != nil {
191
		t.Fatalf("failed to set up the test proxy: %s", err)
192
	}
193 194

	// Use more memory so that we may reliably fit MySQL and nginx
M
Medya Gh 已提交
195 196
	// changing api server so later in soft start we verify it didn't change
	startArgs := append([]string{"start", "-p", profile, fmt.Sprintf("--apiserver-port=%d", apiServerPort), "--wait=true"}, StartArgs()...)
197
	c := exec.CommandContext(ctx, Target(), startArgs...)
198 199 200 201 202 203
	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 已提交
204
		t.Errorf("failed minikube start. args %q: %v", rr.Command(), err)
205 206 207 208 209 210 211 212 213 214 215 216 217
	}

	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)
	}
}

M
Medya Gh 已提交
218 219
// validateSoftStart validates that after minikube already started, a "minikube start" should not change the configs.
func validateSoftStart(ctx context.Context, t *testing.T, profile string, apiPortBefore int) {
M
Medya Gh 已提交
220
	start := time.Now()
M
Medya Gh 已提交
221 222 223 224 225 226 227 228 229 230 231 232
	// the test before this had been start with api-server
	// before soft start the cluster was started with --apiserver-port=8441
	beforeCfg := config.LoadProfile(profile)
	if beforeCfg.Config.NodePort != apiPortBefore {
		t.Errorf("expected cluster config node port before soft start to be %d but got %s", apiPortBefore, beforeCfg.Config.NodePort)
	}

	softStartArgs := append([]string{"start", "-p", profile})
	c := exec.CommandContext(ctx, Target(), softStartArgs...)
	if err != nil {
		t.Errorf("failed to soft start minikube. args %q: %v", rr.Command(), err)
	}
M
Medya Gh 已提交
233
	t.Logf("soft start took %s for %q cluster.", time.Since(start), profile)
M
Medya Gh 已提交
234 235 236 237 238

	afterCfg := config.LoadProfile(profile)
	if afterCfg.Config.NodePort != apiPortBefore {
		t.Errorf("expected node port in the config not change after soft start. exepceted node port to be %d but got %d.", apiPortBefore, afterCfg.Config.NodePort)
	}
M
Medya Gh 已提交
239

M
Medya Gh 已提交
240 241
}

242 243 244 245
// validateKubeContext asserts that kubectl is properly configured (race-condition prone!)
func validateKubeContext(ctx context.Context, t *testing.T, profile string) {
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "config", "current-context"))
	if err != nil {
M
Medya Gh 已提交
246
		t.Errorf("failed to get current-context. args %q : %v", rr.Command(), err)
247 248
	}
	if !strings.Contains(rr.Stdout.String(), profile) {
249
		t.Errorf("expected current-context = %q, but got *%q*", profile, rr.Stdout.String())
250 251 252
	}
}

P
Priya Wadhwa 已提交
253 254
// validateKubectlGetPods asserts that `kubectl get pod -A` returns non-zero content
func validateKubectlGetPods(ctx context.Context, t *testing.T, profile string) {
255
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "po", "-A"))
P
Priya Wadhwa 已提交
256
	if err != nil {
M
Medya Gh 已提交
257
		t.Errorf("failed to get kubectl pods: args %q : %v", rr.Command(), err)
P
Priya Wadhwa 已提交
258
	}
259
	if rr.Stderr.String() != "" {
260
		t.Errorf("expected stderr to be empty but got *%q*: args %q", rr.Stderr, rr.Command())
261
	}
T
Thomas Stromberg 已提交
262
	if !strings.Contains(rr.Stdout.String(), "kube-system") {
263
		t.Errorf("expected stdout to include *kube-system* but got *%q*. args: %q", rr.Stdout, rr.Command())
P
Priya Wadhwa 已提交
264 265 266
	}
}

267 268
// validateMinikubeKubectl validates that the `minikube kubectl` command returns content
func validateMinikubeKubectl(ctx context.Context, t *testing.T, profile string) {
269 270
	// 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 已提交
271
	rr, err := Run(t, exec.CommandContext(ctx, Target(), kubectlArgs...))
272
	if err != nil {
M
Medya Gh 已提交
273
		t.Fatalf("failed to get pods. args %q: %v", rr.Command(), err)
274 275 276
	}
}

277 278 279 280
// validateComponentHealth asserts that all Kubernetes components are healthy
func validateComponentHealth(ctx context.Context, t *testing.T, profile string) {
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "cs", "-o=json"))
	if err != nil {
M
Medya Gh 已提交
281
		t.Fatalf("failed to get components. args %q: %v", rr.Command(), err)
282 283 284 285
	}
	cs := api.ComponentStatusList{}
	d := json.NewDecoder(bytes.NewReader(rr.Stdout.Bytes()))
	if err := d.Decode(&cs); err != nil {
M
Medya Gh 已提交
286
		t.Fatalf("failed to decode kubectl json output: args %q : %v", rr.Command(), err)
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
	}

	for _, i := range cs.Items {
		status := api.ConditionFalse
		for _, c := range i.Conditions {
			if c.Type != api.ComponentHealthy {
				continue
			}
			status = c.Status
		}
		if status != api.ConditionTrue {
			t.Errorf("unexpected status: %v - item: %+v", status, i)
		}
	}
}

J
Josh Woodcock 已提交
303
func validateStatusCmd(ctx context.Context, t *testing.T, profile string) {
304
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status"))
J
Josh Woodcock 已提交
305
	if err != nil {
M
Medya Gh 已提交
306
		t.Errorf("failed to run minikube status. args %q : %v", rr.Command(), err)
J
Josh Woodcock 已提交
307 308 309
	}

	// Custom format
310
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-f", "host:{{.Host}},kublet:{{.Kubelet}},apiserver:{{.APIServer}},kubeconfig:{{.Kubeconfig}}"))
J
Josh Woodcock 已提交
311
	if err != nil {
M
Medya Gh 已提交
312
		t.Errorf("failed to run minikube status with custom format: args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
313
	}
314 315
	re := `host:([A-z]+),kublet:([A-z]+),apiserver:([A-z]+),kubeconfig:([A-z]+)`
	match, _ := regexp.MatchString(re, rr.Stdout.String())
J
Josh Woodcock 已提交
316
	if !match {
M
Medya Gh 已提交
317
		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 已提交
318 319 320
	}

	// Json output
321
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-o", "json"))
J
Josh Woodcock 已提交
322
	if err != nil {
M
Medya Gh 已提交
323
		t.Errorf("failed to run minikube status with json output. args %q : %v", rr.Command(), err)
J
Josh Woodcock 已提交
324 325 326 327
	}
	var jsonObject map[string]interface{}
	err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
	if err != nil {
M
Medya Gh 已提交
328
		t.Errorf("failed to decode json from minikube status. args %q. %v", rr.Command(), err)
J
Josh Woodcock 已提交
329 330
	}
	if _, ok := jsonObject["Host"]; !ok {
M
Medya Gh 已提交
331
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Host")
J
Josh Woodcock 已提交
332 333
	}
	if _, ok := jsonObject["Kubelet"]; !ok {
M
Medya Gh 已提交
334
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Kubelet")
J
Josh Woodcock 已提交
335 336
	}
	if _, ok := jsonObject["APIServer"]; !ok {
M
Medya Gh 已提交
337
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "APIServer")
J
Josh Woodcock 已提交
338 339
	}
	if _, ok := jsonObject["Kubeconfig"]; !ok {
M
Medya Gh 已提交
340
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Kubeconfig")
J
Josh Woodcock 已提交
341 342 343
	}
}

344 345 346 347 348
// validateDashboardCmd asserts that the dashboard command works
func validateDashboardCmd(ctx context.Context, t *testing.T, profile string) {
	args := []string{"dashboard", "--url", "-p", profile, "--alsologtostderr", "-v=1"}
	ss, err := Start(t, exec.CommandContext(ctx, Target(), args...))
	if err != nil {
349
		t.Errorf("failed to run minikube dashboard. args %q : %v", args, err)
350 351 352 353 354 355
	}
	defer func() {
		ss.Stop(t)
	}()

	start := time.Now()
M
Medya Gh 已提交
356
	s, err := ReadLineWithTimeout(ss.Stdout, Seconds(300))
357
	if err != nil {
T
tstromberg 已提交
358 359 360 361
		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)
362 363 364 365 366 367 368 369 370
	}

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

374 375 376
	if resp.StatusCode != http.StatusOK {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
377
			t.Errorf("failed to read http response body from dashboard %q: %v", u.String(), err)
378 379 380 381
		}
		t.Errorf("%s returned status code %d, expected %d.\nbody:\n%s", u, resp.StatusCode, http.StatusOK, body)
	}
}
M
Medya Gh 已提交
382

383 384 385 386
// validateDNS asserts that all Kubernetes DNS is healthy
func validateDNS(ctx context.Context, t *testing.T, profile string) {
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "replace", "--force", "-f", filepath.Join(*testdataDir, "busybox.yaml")))
	if err != nil {
M
Medya Gh 已提交
387
		t.Fatalf("failed to kubectl replace busybox : args %q: %v", rr.Command(), err)
388 389
	}

M
typo  
Medya Gh 已提交
390
	names, err := PodWait(ctx, t, profile, "default", "integration-test=busybox", Minutes(4))
391
	if err != nil {
392
		t.Fatalf("failed waiting for busybox pod : %v", err)
393 394
	}

395 396 397 398 399 400
	nslookup := func() error {
		rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "exec", names[0], "nslookup", "kubernetes.default"))
		return err
	}

	// If the coredns process was stable, this retry wouldn't be necessary.
401
	if err = retry.Expo(nslookup, 1*time.Second, Minutes(1)); err != nil {
402
		t.Errorf("failed to do nslookup on kubernetes.default: %v", err)
403 404 405 406
	}

	want := []byte("10.96.0.1")
	if !bytes.Contains(rr.Stdout.Bytes(), want) {
407
		t.Errorf("failed nslookup: got=%q, want=*%q*", rr.Stdout.Bytes(), want)
408 409 410
	}
}

T
Thomas Stromberg 已提交
411 412
// validateDryRun asserts that the dry-run mode quickly exits with the right code
func validateDryRun(ctx context.Context, t *testing.T, profile string) {
413
	// dry-run mode should always be able to finish quickly (<5s)
M
Medya Gh 已提交
414
	mctx, cancel := context.WithTimeout(ctx, Seconds(5))
T
Thomas Stromberg 已提交
415 416 417
	defer cancel()

	// Too little memory!
418
	startArgs := append([]string{"start", "-p", profile, "--dry-run", "--memory", "250MB", "--alsologtostderr", "-v=1"}, StartArgs()...)
T
Thomas Stromberg 已提交
419 420 421 422 423 424 425 426
	c := exec.CommandContext(mctx, Target(), startArgs...)
	rr, err := Run(t, c)

	wantCode := 78 // exit.Config
	if rr.ExitCode != wantCode {
		t.Errorf("dry-run(250MB) exit code = %d, wanted = %d: %v", rr.ExitCode, wantCode, err)
	}

M
Medya Gh 已提交
427
	dctx, cancel := context.WithTimeout(ctx, Seconds(5))
T
Thomas Stromberg 已提交
428
	defer cancel()
429
	startArgs = append([]string{"start", "-p", profile, "--dry-run", "--alsologtostderr", "-v=1"}, StartArgs()...)
T
Thomas Stromberg 已提交
430 431 432 433 434 435 436
	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 已提交
437
// validateCacheCmd tests functionality of cache command (cache add, delete, list)
438 439 440 441
func validateCacheCmd(ctx context.Context, t *testing.T, profile string) {
	if NoneDriver() {
		t.Skipf("skipping: cache unsupported by none")
	}
M
Medya Gh 已提交
442 443
	t.Run("cache", func(t *testing.T) {
		t.Run("add", func(t *testing.T) {
444
			for _, img := range []string{"busybox:latest", "busybox:1.28.4-glibc", "k8s.gcr.io/pause:latest"} {
445
				rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "add", img))
M
Medya Gh 已提交
446
				if err != nil {
M
Medya Gh 已提交
447
					t.Errorf("failed to cache add image %q. args %q err %v", img, rr.Command(), err)
M
Medya Gh 已提交
448 449 450
				}
			}
		})
M
Medya Ghazizadeh 已提交
451
		t.Run("delete_busybox:1.28.4-glibc", func(t *testing.T) {
452
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "delete", "busybox:1.28.4-glibc"))
M
Medya Gh 已提交
453
			if err != nil {
M
Medya Gh 已提交
454
				t.Errorf("failed to delete image busybox:1.28.4-glibc from cache. args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
455 456
			}
		})
M
Medya Gh 已提交
457

M
Medya Gh 已提交
458 459 460
		t.Run("list", func(t *testing.T) {
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "list"))
			if err != nil {
M
Medya Gh 已提交
461
				t.Errorf("failed to do cache list. args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
462 463
			}
			if !strings.Contains(rr.Output(), "k8s.gcr.io/pause") {
M
Medya Gh 已提交
464
				t.Errorf("expected 'cache list' output to include 'k8s.gcr.io/pause' but got:\n ***%s***", rr.Output())
M
Medya Gh 已提交
465 466
			}
			if strings.Contains(rr.Output(), "busybox:1.28.4-glibc") {
M
Medya Gh 已提交
467
				t.Errorf("expected 'cache list' output not to include busybox:1.28.4-glibc but got:\n ***%s***", rr.Output())
M
Medya Gh 已提交
468 469
			}
		})
M
Medya Gh 已提交
470

M
Medya Ghazizadeh 已提交
471
		t.Run("verify_cache_inside_node", func(t *testing.T) {
M
Medya Gh 已提交
472
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "images"))
M
Medya Gh 已提交
473
			if err != nil {
M
Medya Gh 已提交
474
				t.Errorf("failed to get images by %q ssh %v", rr.Command(), err)
M
Medya Gh 已提交
475
			}
M
Medya Gh 已提交
476
			if !strings.Contains(rr.Output(), "1.28.4-glibc") {
M
Medya Gh 已提交
477
				t.Errorf("expected '1.28.4-glibc' to be in the output but got *%s*", rr.Output())
M
Medya Gh 已提交
478 479 480
			}

		})
M
Medya Gh 已提交
481

M
Medya Ghazizadeh 已提交
482
		t.Run("cache_reload", func(t *testing.T) { // deleting image inside minikube node manually and expecting reload to bring it back
M
Medya Gh 已提交
483 484
			img := "busybox:latest"
			// deleting image inside minikube node manually
M
Medya Gh 已提交
485
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "docker", "rmi", img)) // for some reason crictl rmi doesn't work
M
Medya Gh 已提交
486 487 488 489 490 491
			if err != nil {
				t.Errorf("failed to delete inside the node %q : %v", rr.Command(), err)
			}
			// make sure the image is deleted.
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "inspecti", img))
			if err == nil {
492
				t.Errorf("expected an error. because image should not exist. but got *nil error* ! cmd: %q", rr.Command())
M
Medya Gh 已提交
493
			}
M
Medya Gh 已提交
494
			// minikube cache reload.
M
Medya Gh 已提交
495 496
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "reload"))
			if err != nil {
497
				t.Errorf("expected %q to run successfully but got error: %v", rr.Command(), err)
M
Medya Gh 已提交
498
			}
M
Medya Gh 已提交
499
			// make sure 'cache reload' brought back the manually deleted image.
M
Medya Gh 已提交
500 501
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "inspecti", img))
			if err != nil {
502
				t.Errorf("expected %q to run successfully but got error: %v", rr.Command(), err)
M
Medya Gh 已提交
503 504 505
			}
		})

M
Medya Gh 已提交
506
	})
507 508 509 510 511 512 513 514 515 516 517
}

// 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 已提交
518
		{[]string{"set", "cpus", "2"}, "", "! These changes will take effect upon a minikube delete and then a minikube start"},
519 520 521 522 523 524 525 526 527
		{[]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 已提交
528
			t.Errorf("failed to config minikube. args %q : %v", rr.Command(), err)
529 530 531 532
		}

		got := strings.TrimSpace(rr.Stdout.String())
		if got != tc.wantOut {
533
			t.Errorf("expected config output for %q to be -%q- but got *%q*", rr.Command(), tc.wantOut, got)
534 535 536
		}
		got = strings.TrimSpace(rr.Stderr.String())
		if got != tc.wantErr {
537
			t.Errorf("expected config error for %q to be -%q- but got *%q*", rr.Command(), tc.wantErr, got)
538 539 540 541 542 543 544 545
		}
	}
}

// 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 已提交
546
		t.Errorf("%s failed: %v", rr.Command(), err)
547 548 549
	}
	for _, word := range []string{"Docker", "apiserver", "Linux", "kubelet"} {
		if !strings.Contains(rr.Stdout.String(), word) {
M
Medya Gh 已提交
550
			t.Errorf("excpeted minikube logs to include word: -%q- but got \n***%s***\n", word, rr.Output())
551 552 553 554
		}
	}
}

J
Josh Woodcock 已提交
555
// validateProfileCmd asserts "profile" command functionality
556
func validateProfileCmd(ctx context.Context, t *testing.T, profile string) {
M
Medya Gh 已提交
557 558 559 560 561
	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 已提交
562
			t.Errorf("%s failed: %v", rr.Command(), err)
M
Medya Gh 已提交
563 564 565
		}
		rr, err = Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "--output", "json"))
		if err != nil {
M
Medya Gh 已提交
566
			t.Errorf("%s failed: %v", rr.Command(), err)
M
Medya Gh 已提交
567 568 569 570
		}
		var profileJSON map[string][]map[string]interface{}
		err = json.Unmarshal(rr.Stdout.Bytes(), &profileJSON)
		if err != nil {
M
Medya Gh 已提交
571
			t.Errorf("%s failed: %v", rr.Command(), err)
M
Medya Gh 已提交
572 573 574 575 576 577 578
		}
		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)
				}
579
			}
580
		}
M
Medya Gh 已提交
581
	})
582

M
Medya Gh 已提交
583 584
	t.Run("profile_list", func(t *testing.T) {
		// List profiles
M
lint  
Medya Gh 已提交
585
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list"))
M
Medya Gh 已提交
586
		if err != nil {
M
Medya Gh 已提交
587
			t.Errorf("failed to list profiles: args %q : %v", rr.Command(), err)
M
Medya Gh 已提交
588
		}
J
Josh Woodcock 已提交
589

M
Medya Gh 已提交
590 591 592 593 594 595 596 597 598 599 600
		// 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 已提交
601
			t.Errorf("expected 'profile list' output to include %q but got *%q*. args: %q", profile, rr.Stdout.String(), rr.Command())
J
Josh Woodcock 已提交
602
		}
M
Medya Gh 已提交
603 604 605 606
	})

	t.Run("profile_json_output", func(t *testing.T) {
		// Json output
M
lint  
Medya Gh 已提交
607
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "--output", "json"))
M
Medya Gh 已提交
608
		if err != nil {
M
Medya Gh 已提交
609
			t.Errorf("failed to list profiles with json format. args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
610
		}
M
Medya Gh 已提交
611 612 613
		var jsonObject map[string][]map[string]interface{}
		err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
		if err != nil {
M
Medya Gh 已提交
614
			t.Errorf("failed to decode json from profile list: args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
615 616
		}
		validProfiles := jsonObject["valid"]
M
lint  
Medya Gh 已提交
617
		profileExists := false
M
Medya Gh 已提交
618 619 620 621 622 623 624
		for _, profileObject := range validProfiles {
			if profileObject["Name"] == profile {
				profileExists = true
				break
			}
		}
		if !profileExists {
M
Medya Gh 已提交
625
			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 已提交
626 627 628
		}

	})
629 630 631
}

// validateServiceCmd asserts basic "service" command functionality
632
func validateServiceCmd(ctx context.Context, t *testing.T, profile string) {
633
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "create", "deployment", "hello-node", "--image=gcr.io/hello-minikube-zero-install/hello-node"))
634
	if err != nil {
M
Medya Gh 已提交
635
		t.Logf("%q failed: %v (may not be an error).", rr.Command(), err)
636
	}
637
	rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "expose", "deployment", "hello-node", "--type=NodePort", "--port=8080"))
638
	if err != nil {
M
Medya Gh 已提交
639
		t.Logf("%q failed: %v (may not be an error)", rr.Command(), err)
640 641
	}

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

646
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "list"))
647
	if err != nil {
M
Medya Gh 已提交
648
		t.Errorf("failed to do service list. args %q : %v", rr.Command(), err)
649
	}
650
	if !strings.Contains(rr.Stdout.String(), "hello-node") {
651
		t.Errorf("expected 'service list' to contain *hello-node* but got -%q-", rr.Stdout.String())
652 653
	}

654 655 656 657
	if NeedsPortForward() {
		t.Skipf("test is broken for port-forwarded drivers: https://github.com/kubernetes/minikube/issues/7383")
	}

658
	// Test --https --url mode
659
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "--namespace=default", "--https", "--url", "hello-node"))
660
	if err != nil {
M
Medya Gh 已提交
661
		t.Fatalf("failed to get service url. args %q : %v", rr.Command(), err)
662 663
	}
	if rr.Stderr.String() != "" {
664
		t.Errorf("expected stderr to be empty but got *%q*", rr.Stderr)
665
	}
666 667

	endpoint := strings.TrimSpace(rr.Stdout.String())
668 669
	u, err := url.Parse(endpoint)
	if err != nil {
670
		t.Fatalf("failed to parse service url endpoint %q: %v", endpoint, err)
671 672
	}
	if u.Scheme != "https" {
673
		t.Errorf("expected scheme to be 'https' but got %q", u.Scheme)
674 675 676
	}

	// Test --format=IP
677
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "hello-node", "--url", "--format={{.IP}}"))
678
	if err != nil {
M
Medya Gh 已提交
679
		t.Errorf("failed to get service url with custom format. args %q: %v", rr.Command(), err)
680
	}
681
	if strings.TrimSpace(rr.Stdout.String()) != u.Hostname() {
M
Medya Gh 已提交
682
		t.Errorf("expected 'service --format={{.IP}}' output to be -%q- but got *%q* . args %q.", u.Hostname(), rr.Stdout.String(), rr.Command())
683 684
	}

685 686
	// Test a regular URLminikube
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "hello-node", "--url"))
687
	if err != nil {
M
Medya Gh 已提交
688
		t.Errorf("failed to get service url. args: %q: %v", rr.Command(), err)
689
	}
690 691 692 693 694 695 696

	endpoint = strings.TrimSpace(rr.Stdout.String())
	u, err = url.Parse(endpoint)
	if err != nil {
		t.Fatalf("failed to parse %q: %v", endpoint, err)
	}
	if u.Scheme != "http" {
M
lint  
Medya Gh 已提交
697
		t.Fatalf("expected scheme to be -%q- got scheme: *%q*", "http", u.Scheme)
698 699 700 701
	}

	t.Logf("url: %s", endpoint)
	resp, err := retryablehttp.Get(endpoint)
702
	if err != nil {
703
		t.Fatalf("get failed: %v\nresp: %v", err, resp)
704 705
	}
	if resp.StatusCode != http.StatusOK {
M
lint  
Medya Gh 已提交
706
		t.Fatalf("expected status code for %q to be -%q- but got *%q*", endpoint, http.StatusOK, resp.StatusCode)
707 708 709
	}
}

710 711
// validateAddonsCmd asserts basic "addon" command functionality
func validateAddonsCmd(ctx context.Context, t *testing.T, profile string) {
M
Medya Gh 已提交
712
	// Table output
713 714
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "addons", "list"))
	if err != nil {
M
Medya Gh 已提交
715
		t.Errorf("failed to do addon list: args %q : %v", rr.Command(), err)
716
	}
M
Medya Gh 已提交
717 718
	for _, a := range []string{"dashboard", "ingress", "ingress-dns"} {
		if !strings.Contains(rr.Output(), a) {
M
Medya Gh 已提交
719
			t.Errorf("expected 'addon list' output to include -%q- but got *%s*", a, rr.Output())
720 721
		}
	}
J
Josh Woodcock 已提交
722 723 724 725

	// Json output
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "addons", "list", "-o", "json"))
	if err != nil {
M
Medya Gh 已提交
726
		t.Errorf("failed to do addon list with json output. args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
727 728 729 730
	}
	var jsonObject map[string]interface{}
	err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
	if err != nil {
731
		t.Errorf("failed to decode addon list json output : %v", err)
J
Josh Woodcock 已提交
732
	}
733 734
}

735 736 737 738 739
// validateSSHCmd asserts basic "ssh" command functionality
func validateSSHCmd(ctx context.Context, t *testing.T, profile string) {
	if NoneDriver() {
		t.Skipf("skipping: ssh unsupported by none")
	}
P
Priya Wadhwa 已提交
740
	want := "hello\n"
741 742
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", fmt.Sprintf("echo hello")))
	if err != nil {
M
Medya Gh 已提交
743
		t.Errorf("failed to run an ssh command. args %q : %v", rr.Command(), err)
744 745
	}
	if rr.Stdout.String() != want {
M
Medya Gh 已提交
746
		t.Errorf("expected minikube ssh command output to be -%q- but got *%q*. args %q", want, rr.Stdout.String(), rr.Command())
747 748 749
	}
}

750 751 752 753
// validateMySQL validates a minimalist MySQL deployment
func validateMySQL(ctx context.Context, t *testing.T, profile string) {
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "replace", "--force", "-f", filepath.Join(*testdataDir, "mysql.yaml")))
	if err != nil {
M
Medya Gh 已提交
754
		t.Fatalf("failed to kubectl replace mysql: args %q failed: %v", rr.Command(), err)
755 756
	}

757
	names, err := PodWait(ctx, t, profile, "default", "app=mysql", Minutes(10))
758
	if err != nil {
759
		t.Fatalf("failed waiting for mysql pod: %v", err)
760 761
	}

762 763 764 765
	// 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
766
	}
M
Medya Gh 已提交
767
	if err = retry.Expo(mysql, 1*time.Second, Minutes(5)); err != nil {
768
		t.Errorf("failed to exec 'mysql -ppassword -e show databases;': %v", err)
769 770 771
	}
}

772 773 774 775 776 777 778 779 780 781
// 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())
}

782 783 784 785 786 787 788 789 790 791
// 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())
}

792 793
// Copy extra file into minikube home folder for file sync test
func setupFileSync(ctx context.Context, t *testing.T, profile string) {
794 795 796
	p := localSyncTestPath()
	t.Logf("local sync path: %s", p)
	err := copy.Copy("./testdata/sync.test", p)
797
	if err != nil {
798
		t.Fatalf("failed to copy ./testdata/sync.test : %v", err)
799
	}
800 801 802

	err = copy.Copy("./testdata/minikube_test.pem", localTestCertPath())
	if err != nil {
803
		t.Fatalf("failed to copy ./testdata/minikube_test.pem : %v", err)
804
	}
805 806 807 808 809 810 811
}

// validateFileSync to check existence of the test file
func validateFileSync(ctx context.Context, t *testing.T, profile string) {
	if NoneDriver() {
		t.Skipf("skipping: ssh unsupported by none")
	}
812 813 814

	vp := vmSyncTestPath()
	t.Logf("Checking for existence of %s within VM", vp)
815
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", fmt.Sprintf("sudo cat %s", vp)))
816
	if err != nil {
M
Medya Gh 已提交
817
		t.Errorf("%s failed: %v", rr.Command(), err)
818
	}
819 820
	got := rr.Stdout.String()
	t.Logf("file sync test content: %s", got)
821 822 823

	expected, err := ioutil.ReadFile("./testdata/sync.test")
	if err != nil {
824
		t.Errorf("failed to read test file '/testdata/sync.test' : %v", err)
825 826
	}

827
	if diff := cmp.Diff(string(expected), got); diff != "" {
828 829 830 831
		t.Errorf("/etc/sync.test content mismatch (-want +got):\n%s", diff)
	}
}

832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
// validateCertSync to check existence of the test certificate
func validateCertSync(ctx context.Context, t *testing.T, profile string) {
	if NoneDriver() {
		t.Skipf("skipping: ssh unsupported by none")
	}

	want, err := ioutil.ReadFile("./testdata/minikube_test.pem")
	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)
852
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", fmt.Sprintf("sudo cat %s", vp)))
853
		if err != nil {
M
Medya Gh 已提交
854
			t.Errorf("failed to check existence of %q inside minikube. args %q: %v", vp, rr.Command(), err)
855 856 857 858 859
		}

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

865 866 867 868
// validateUpdateContextCmd asserts basic "update-context" command functionality
func validateUpdateContextCmd(ctx context.Context, t *testing.T, profile string) {
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "update-context", "--alsologtostderr", "-v=2"))
	if err != nil {
M
Medya Gh 已提交
869
		t.Errorf("failed to run minikube update-context: args %q: %v", rr.Command(), err)
870 871
	}

T
Thomas Stromberg 已提交
872
	want := []byte("No changes")
873 874 875 876 877
	if !bytes.Contains(rr.Stdout.Bytes(), want) {
		t.Errorf("update-context: got=%q, want=*%q*", rr.Stdout.Bytes(), want)
	}
}

878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
// 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
894
}