functional_test.go 27.9 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 31
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
32
	"regexp"
T
tstromberg 已提交
33
	"runtime"
34
	"strings"
35
	"testing"
36 37
	"time"

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

	"k8s.io/minikube/pkg/minikube/localpath"

42 43
	"github.com/elazarl/goproxy"
	"github.com/hashicorp/go-retryablehttp"
44
	"github.com/otiai10/copy"
45 46 47
	"github.com/phayes/freeport"
	"github.com/pkg/errors"
	"golang.org/x/build/kubernetes/api"
48
	"k8s.io/minikube/pkg/util/retry"
49 50
)

51 52 53 54
// 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 已提交
55
func TestFunctional(t *testing.T) {
56 57

	profile := UniqueProfileName("functional")
58
	ctx, cancel := context.WithTimeout(context.Background(), 40*time.Minute)
59 60 61 62 63 64 65
	defer func() {
		p := localSyncTestPath()
		if err := os.Remove(p); err != nil {
			t.Logf("unable to remove %s: %v", p, err)
		}
		CleanupWithLogs(t, profile, cancel)
	}()
66 67 68 69 70 71 72

	// Serial tests
	t.Run("serial", func(t *testing.T) {
		tests := []struct {
			name      string
			validator validateFunc
		}{
73 74 75 76 77 78
			{"CopySyncFile", setupFileSync},                 // Set file for the file sync test case
			{"StartWithProxy", validateStartWithProxy},      // Set everything else up for success
			{"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
79 80 81 82 83 84
		}
		for _, tc := range tests {
			tc := tc
			t.Run(tc.name, func(t *testing.T) {
				tc.validator(ctx, t, profile)
			})
M
Medya Gh 已提交
85
		}
86
	})
M
Medya Gh 已提交
87

88 89 90 91 92 93 94 95 96 97 98 99 100
	// 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 已提交
101
			{"DryRun", validateDryRun},
J
Josh Woodcock 已提交
102
			{"StatusCmd", validateStatusCmd},
103 104 105
			{"LogsCmd", validateLogsCmd},
			{"MountCmd", validateMountCmd},
			{"ProfileCmd", validateProfileCmd},
106
			{"ServiceCmd", validateServiceCmd},
107
			{"AddonsCmd", validateAddonsCmd},
108 109 110
			{"PersistentVolumeClaim", validatePersistentVolumeClaim},
			{"TunnelCmd", validateTunnelCmd},
			{"SSHCmd", validateSSHCmd},
111
			{"MySQL", validateMySQL},
112
			{"FileSync", validateFileSync},
113
			{"UpdateContextCmd", validateUpdateContextCmd},
114
			{"DockerEnv", validateDockerEnv},
M
Medya Gh 已提交
115
			{"NodeLabels", validateNodeLabels},
116 117 118 119 120 121 122 123
		}
		for _, tc := range tests {
			tc := tc
			t.Run(tc.name, func(t *testing.T) {
				MaybeParallel(t)
				tc.validator(ctx, t, profile)
			})
		}
M
Medya Gh 已提交
124
	})
125 126
}

M
Medya Gh 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
// validateNodeLabels checks if minikube cluster is created with correct kubernetes's node label
func validateNodeLabels(ctx context.Context, t *testing.T, profile string) {
	mctx, cancel := context.WithTimeout(ctx, 13*time.Second)
	defer cancel()
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "nodes", "--output", "jsonpath={.items[0].metadata.labels}"))
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}

	// json output would look like this
	// [beta.kubernetes.io/arch:amd64 beta.kubernetes.io/os:linux minikube.k8s.io/commit:aa91f39ffbcf27dcbb93c4ff3f457c54e585cf4a-dirty minikube.k8s.io/name:p1 minikube.k8s.io/updated_at:2020_02_20T12_05_35_0700 minikube.k8s.io/version:v1.7.3 kubernetes.io/arch:amd64 kubernetes.io/hostname:p1 kubernetes.io/os:linux node-role.kubernetes.io/master:]

	var labels []string
	err = json.Unmarshal(rr.Stdout.Bytes(), &labels)
	if err != nil {
		t.Errorf("%s umarshaling node label from json failed: %v", rr.Args, err)
	}

	expectedLabels := []string{"minikube.k8s.io/commit", "minikube.k8s.io/version", "minikube.k8s.io/updated_at", "minikube.k8s.io/name"}
	for _, el := range expectedLabels {
		found := false
		for _, l := range labels {
			if strings.Contains(l, el) {
				found = true
				break
			}
		}
		if !found {
			t.Errorf("Failed to have label %q in node labels %+v", expectedLabels, labels)
		}
	}
}

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
// check functionality of minikube after evaling docker-env
func validateDockerEnv(ctx context.Context, t *testing.T, profile string) {
	mctx, cancel := context.WithTimeout(ctx, 13*time.Second)
	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 {
		t.Fatalf("Failed to do minikube status after eval-ing docker-env %s", err)
	}
	if !strings.Contains(rr.Output(), "Running") {
		t.Fatalf("Expected status output to include 'Running' after eval docker-env but got \n%s", rr.Output())
	}

	mctx, cancel = context.WithTimeout(ctx, 13*time.Second)
	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 {
		t.Fatalf("Failed to test eval docker-evn %s", err)
	}

	expectedImgInside := "gcr.io/k8s-minikube/storage-provisioner"
	if !strings.Contains(rr.Output(), expectedImgInside) {
		t.Fatalf("Expected 'docker ps' to have %q from docker-daemon inside minikube. the docker ps output is:\n%q\n", expectedImgInside, rr.Output())
	}

}

190 191 192 193 194
func validateStartWithProxy(ctx context.Context, t *testing.T, profile string) {
	srv, err := startHTTPProxy(t)
	if err != nil {
		t.Fatalf("Failed to set up the test proxy: %s", err)
	}
195 196

	// Use more memory so that we may reliably fit MySQL and nginx
197
	startArgs := append([]string{"start", "-p", profile, "--wait=true", "--memory", "2500MB"}, StartArgs()...)
198
	c := exec.CommandContext(ctx, Target(), startArgs...)
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
	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 {
		t.Errorf("%s failed: %v", rr.Args, err)
	}

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

// 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 {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
	if !strings.Contains(rr.Stdout.String(), profile) {
		t.Errorf("current-context = %q, want %q", rr.Stdout.String(), profile)
	}
}

P
Priya Wadhwa 已提交
230 231
// validateKubectlGetPods asserts that `kubectl get pod -A` returns non-zero content
func validateKubectlGetPods(ctx context.Context, t *testing.T, profile string) {
232
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "po", "-A"))
P
Priya Wadhwa 已提交
233 234 235
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
236 237 238
	if rr.Stderr.String() != "" {
		t.Errorf("%s: got unexpected stderr: %s", rr.Command(), rr.Stderr)
	}
T
Thomas Stromberg 已提交
239
	if !strings.Contains(rr.Stdout.String(), "kube-system") {
240
		t.Errorf("%s = %q, want *kube-system*", rr.Command(), rr.Stdout)
P
Priya Wadhwa 已提交
241 242 243
	}
}

244 245 246
// validateMinikubeKubectl validates that the `minikube kubectl` command returns content
func validateMinikubeKubectl(ctx context.Context, t *testing.T, profile string) {
	kubectlArgs := []string{"kubectl", "--", "get", "pods"}
P
Priya Wadhwa 已提交
247
	rr, err := Run(t, exec.CommandContext(ctx, Target(), kubectlArgs...))
248 249 250 251 252
	if err != nil {
		t.Fatalf("%s failed: %v", rr.Args, err)
	}
}

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
// 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 {
		t.Fatalf("%s failed: %v", rr.Args, err)
	}
	cs := api.ComponentStatusList{}
	d := json.NewDecoder(bytes.NewReader(rr.Stdout.Bytes()))
	if err := d.Decode(&cs); err != nil {
		t.Fatalf("decode: %v", err)
	}

	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 已提交
279
func validateStatusCmd(ctx context.Context, t *testing.T, profile string) {
280
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status"))
J
Josh Woodcock 已提交
281 282 283 284 285
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}

	// Custom format
286
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-f", "host:{{.Host}},kublet:{{.Kubelet}},apiserver:{{.APIServer}},kubeconfig:{{.Kubeconfig}}"))
J
Josh Woodcock 已提交
287 288 289
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
290
	match, _ := regexp.MatchString(`host:([A-z]+),kublet:([A-z]+),apiserver:([A-z]+),kubeconfig:([A-z]+)`, rr.Stdout.String())
J
Josh Woodcock 已提交
291 292 293 294 295
	if !match {
		t.Errorf("%s failed: %v. Output for custom format did not match", rr.Args, err)
	}

	// Json output
296
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-o", "json"))
J
Josh Woodcock 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
	var jsonObject map[string]interface{}
	err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
	if _, ok := jsonObject["Host"]; !ok {
		t.Errorf("%s failed: %v. Missing key %s in json object", rr.Args, err, "Host")
	}
	if _, ok := jsonObject["Kubelet"]; !ok {
		t.Errorf("%s failed: %v. Missing key %s in json object", rr.Args, err, "Kubelet")
	}
	if _, ok := jsonObject["APIServer"]; !ok {
		t.Errorf("%s failed: %v. Missing key %s in json object", rr.Args, err, "APIServer")
	}
	if _, ok := jsonObject["Kubeconfig"]; !ok {
		t.Errorf("%s failed: %v. Missing key %s in json object", rr.Args, err, "Kubeconfig")
	}
}

319 320 321 322 323 324 325 326 327 328 329 330 331 332
// 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 {
		t.Errorf("%s failed: %v", args, err)
	}
	defer func() {
		ss.Stop(t)
	}()

	start := time.Now()
	s, err := ReadLineWithTimeout(ss.Stdout, 300*time.Second)
	if err != nil {
T
tstromberg 已提交
333 334 335 336
		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)
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
	}

	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 {
		t.Errorf("failed get: %v", err)
	}
	if resp.StatusCode != http.StatusOK {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			t.Errorf("Unable to read http response body: %v", err)
		}
		t.Errorf("%s returned status code %d, expected %d.\nbody:\n%s", u, resp.StatusCode, http.StatusOK, body)
	}
}
M
Medya Gh 已提交
356

357 358 359 360 361 362 363
// 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 {
		t.Fatalf("%s failed: %v", rr.Args, err)
	}

364
	names, err := PodWait(ctx, t, profile, "default", "integration-test=busybox", 5*time.Minute)
365 366 367 368
	if err != nil {
		t.Fatalf("wait: %v", err)
	}

369 370 371 372 373 374 375 376
	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.
	if err = retry.Expo(nslookup, 1*time.Second, 1*time.Minute); err != nil {
		t.Errorf("nslookup failing: %v", err)
377 378 379 380 381 382 383 384
	}

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

T
Thomas Stromberg 已提交
385 386
// validateDryRun asserts that the dry-run mode quickly exits with the right code
func validateDryRun(ctx context.Context, t *testing.T, profile string) {
387
	// dry-run mode should always be able to finish quickly (<5s)
T
tstromberg 已提交
388
	mctx, cancel := context.WithTimeout(ctx, 5*time.Second)
T
Thomas Stromberg 已提交
389 390 391
	defer cancel()

	// Too little memory!
392
	startArgs := append([]string{"start", "-p", profile, "--dry-run", "--memory", "250MB", "--alsologtostderr", "-v=1"}, StartArgs()...)
T
Thomas Stromberg 已提交
393 394 395 396 397 398 399 400
	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)
	}

T
tstromberg 已提交
401
	dctx, cancel := context.WithTimeout(ctx, 5*time.Second)
T
Thomas Stromberg 已提交
402
	defer cancel()
403
	startArgs = append([]string{"start", "-p", profile, "--dry-run", "--alsologtostderr", "-v=1"}, StartArgs()...)
T
Thomas Stromberg 已提交
404 405 406 407 408 409 410
	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 已提交
411
// validateCacheCmd tests functionality of cache command (cache add, delete, list)
412 413 414 415
func validateCacheCmd(ctx context.Context, t *testing.T, profile string) {
	if NoneDriver() {
		t.Skipf("skipping: cache unsupported by none")
	}
M
Medya Gh 已提交
416 417
	t.Run("cache", func(t *testing.T) {
		t.Run("add", func(t *testing.T) {
418
			for _, img := range []string{"busybox:latest", "busybox:1.28.4-glibc", "k8s.gcr.io/pause:latest"} {
M
Medya Gh 已提交
419 420 421 422 423 424
				_, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "add", img))
				if err != nil {
					t.Errorf("Failed to cache image %q", img)
				}
			}
		})
M
Medya Ghazizadeh 已提交
425
		t.Run("delete_busybox:1.28.4-glibc", func(t *testing.T) {
M
Medya Gh 已提交
426 427 428 429 430
			_, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "delete", "busybox:1.28.4-glibc"))
			if err != nil {
				t.Errorf("failed to delete image busybox:1.28.4-glibc from cache: %v", err)
			}
		})
M
Medya Gh 已提交
431

M
Medya Gh 已提交
432 433 434 435 436 437 438 439 440 441 442 443
		t.Run("list", func(t *testing.T) {
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "list"))
			if err != nil {
				t.Errorf("cache list failed: %v", err)
			}
			if !strings.Contains(rr.Output(), "k8s.gcr.io/pause") {
				t.Errorf("cache list did not include k8s.gcr.io/pause")
			}
			if strings.Contains(rr.Output(), "busybox:1.28.4-glibc") {
				t.Errorf("cache list should not include busybox:1.28.4-glibc")
			}
		})
M
Medya Gh 已提交
444

M
Medya Ghazizadeh 已提交
445
		t.Run("verify_cache_inside_node", func(t *testing.T) {
M
Medya Gh 已提交
446
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "images"))
M
Medya Gh 已提交
447
			if err != nil {
M
Medya Gh 已提交
448
				t.Errorf("failed to get images by %q ssh %v", rr.Command(), err)
M
Medya Gh 已提交
449
			}
M
Medya Gh 已提交
450 451
			if !strings.Contains(rr.Output(), "1.28.4-glibc") {
				t.Errorf("expected '1.28.4-glibc' to be in the output: %s", rr.Output())
M
Medya Gh 已提交
452 453 454
			}

		})
M
Medya Gh 已提交
455

M
Medya Ghazizadeh 已提交
456
		t.Run("cache_reload", func(t *testing.T) { // deleting image inside minikube node manually and expecting reload to bring it back
M
Medya Gh 已提交
457 458
			img := "busybox:latest"
			// deleting image inside minikube node manually
M
Medya Gh 已提交
459
			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 已提交
460 461 462 463 464 465 466 467
			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 {
				t.Errorf("expected the image be deleted and get  error but got nil error ! cmd: %q", rr.Command())
			}
M
Medya Gh 已提交
468
			// minikube cache reload.
M
Medya Gh 已提交
469 470
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "reload"))
			if err != nil {
M
Medya Gh 已提交
471
				t.Errorf("expected %q to run successfully but got error %v", rr.Command(), err)
M
Medya Gh 已提交
472
			}
M
Medya Gh 已提交
473
			// make sure 'cache reload' brought back the manually deleted image.
M
Medya Gh 已提交
474 475 476 477 478 479
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "inspecti", img))
			if err != nil {
				t.Errorf("expected to get no error for %q but got %v", rr.Command(), err)
			}
		})

M
Medya Gh 已提交
480
	})
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
}

// 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"},
		{[]string{"set", "cpus", "2"}, "! These changes will take effect upon a minikube delete and then a minikube start", ""},
		{[]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 == "" {
			t.Errorf("unexpected failure: %s failed: %v", rr.Args, err)
		}

		got := strings.TrimSpace(rr.Stdout.String())
		if got != tc.wantOut {
			t.Errorf("%s stdout got: %q, want: %q", rr.Command(), got, tc.wantOut)
		}
		got = strings.TrimSpace(rr.Stderr.String())
		if got != tc.wantErr {
			t.Errorf("%s stderr got: %q, want: %q", rr.Command(), got, tc.wantErr)
		}
	}
}

// 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 {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
	for _, word := range []string{"Docker", "apiserver", "Linux", "kubelet"} {
		if !strings.Contains(rr.Stdout.String(), word) {
			t.Errorf("minikube logs missing expected word: %q", word)
		}
	}
}

J
Josh Woodcock 已提交
529
// validateProfileCmd asserts "profile" command functionality
530
func validateProfileCmd(ctx context.Context, t *testing.T, profile string) {
M
Medya Gh 已提交
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
	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 {
			t.Errorf("%s failed: %v", rr.Args, err)
		}
		rr, err = Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "--output", "json"))
		if err != nil {
			t.Errorf("%s failed: %v", rr.Args, err)
		}
		var profileJSON map[string][]map[string]interface{}
		err = json.Unmarshal(rr.Stdout.Bytes(), &profileJSON)
		if err != nil {
			t.Errorf("%s failed: %v", rr.Args, err)
		}
		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)
				}
553
			}
554
		}
M
Medya Gh 已提交
555
	})
556

M
Medya Gh 已提交
557 558
	t.Run("profile_list", func(t *testing.T) {
		// List profiles
M
lint  
Medya Gh 已提交
559
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list"))
M
Medya Gh 已提交
560 561 562
		if err != nil {
			t.Errorf("%s failed: %v", rr.Args, err)
		}
J
Josh Woodcock 已提交
563

M
Medya Gh 已提交
564 565 566 567 568 569 570 571 572 573 574 575
		// 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 {
			t.Errorf("%s failed: Missing profile '%s'. Got '\n%s\n'", rr.Args, profile, rr.Stdout.String())
J
Josh Woodcock 已提交
576 577
		}

M
Medya Gh 已提交
578 579 580 581
	})

	t.Run("profile_json_output", func(t *testing.T) {
		// Json output
M
lint  
Medya Gh 已提交
582
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "--output", "json"))
M
Medya Gh 已提交
583 584
		if err != nil {
			t.Errorf("%s failed: %v", rr.Args, err)
J
Josh Woodcock 已提交
585
		}
M
Medya Gh 已提交
586 587 588 589 590 591
		var jsonObject map[string][]map[string]interface{}
		err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
		if err != nil {
			t.Errorf("%s failed: %v", rr.Args, err)
		}
		validProfiles := jsonObject["valid"]
M
lint  
Medya Gh 已提交
592
		profileExists := false
M
Medya Gh 已提交
593 594 595 596 597 598 599 600 601 602 603
		for _, profileObject := range validProfiles {
			if profileObject["Name"] == profile {
				profileExists = true
				break
			}
		}
		if !profileExists {
			t.Errorf("%s failed: Missing profile '%s'. Got '\n%s\n'", rr.Args, profile, rr.Stdout.String())
		}

	})
604 605 606
}

// validateServiceCmd asserts basic "service" command functionality
607
func validateServiceCmd(ctx context.Context, t *testing.T, profile string) {
608
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "create", "deployment", "hello-node", "--image=gcr.io/hello-minikube-zero-install/hello-node"))
609 610 611
	if err != nil {
		t.Logf("%s failed: %v (may not be an error)", rr.Args, err)
	}
612
	rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "expose", "deployment", "hello-node", "--type=NodePort", "--port=8080"))
613 614 615 616
	if err != nil {
		t.Logf("%s failed: %v (may not be an error)", rr.Args, err)
	}

617
	if _, err := PodWait(ctx, t, profile, "default", "app=hello-node", 10*time.Minute); err != nil {
618 619 620
		t.Fatalf("wait: %v", err)
	}

621
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "list"))
622 623 624
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
625 626
	if !strings.Contains(rr.Stdout.String(), "hello-node") {
		t.Errorf("service list got %q, wanted *hello-node*", rr.Stdout.String())
627 628 629
	}

	// Test --https --url mode
630
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "--namespace=default", "--https", "--url", "hello-node"))
631
	if err != nil {
632 633 634 635
		t.Fatalf("%s failed: %v", rr.Args, err)
	}
	if rr.Stderr.String() != "" {
		t.Errorf("unexpected stderr output: %s", rr.Stderr)
636
	}
637 638

	endpoint := strings.TrimSpace(rr.Stdout.String())
639 640 641 642 643 644 645 646 647
	u, err := url.Parse(endpoint)
	if err != nil {
		t.Fatalf("failed to parse %q: %v", endpoint, err)
	}
	if u.Scheme != "https" {
		t.Errorf("got scheme: %q, expected: %q", u.Scheme, "https")
	}

	// Test --format=IP
648
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "hello-node", "--url", "--format={{.IP}}"))
649 650 651
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
652
	if strings.TrimSpace(rr.Stdout.String()) != u.Hostname() {
653 654 655
		t.Errorf("%s = %q, wanted %q", rr.Args, rr.Stdout.String(), u.Hostname())
	}

656 657
	// Test a regular URLminikube
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "hello-node", "--url"))
658 659 660
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
661 662 663 664 665 666 667 668 669 670 671 672

	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" {
		t.Fatalf("got scheme: %q, expected: %q", u.Scheme, "http")
	}

	t.Logf("url: %s", endpoint)
	resp, err := retryablehttp.Get(endpoint)
673
	if err != nil {
674
		t.Fatalf("get failed: %v\nresp: %v", err, resp)
675 676
	}
	if resp.StatusCode != http.StatusOK {
677
		t.Fatalf("%s = status code %d, want %d", u, resp.StatusCode, http.StatusOK)
678 679 680
	}
}

681 682
// validateAddonsCmd asserts basic "addon" command functionality
func validateAddonsCmd(ctx context.Context, t *testing.T, profile string) {
M
Medya Gh 已提交
683
	// Table output
684 685 686 687
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "addons", "list"))
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
M
Medya Gh 已提交
688 689 690
	for _, a := range []string{"dashboard", "ingress", "ingress-dns"} {
		if !strings.Contains(rr.Output(), a) {
			t.Errorf("addon list expected to include %q but didn't output: %q", a, rr.Output())
691 692
		}
	}
J
Josh Woodcock 已提交
693 694 695 696 697 698 699 700 701 702 703

	// Json output
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "addons", "list", "-o", "json"))
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
	var jsonObject map[string]interface{}
	err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
704 705
}

706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
// 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")
	}
	want := "hello\r\n"
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", fmt.Sprintf("echo hello")))
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
	if rr.Stdout.String() != want {
		t.Errorf("%v = %q, want = %q", rr.Args, rr.Stdout.String(), want)
	}
}

721 722 723 724 725 726 727
// 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 {
		t.Fatalf("%s failed: %v", rr.Args, err)
	}

728
	names, err := PodWait(ctx, t, profile, "default", "app=mysql", 10*time.Minute)
729 730 731 732
	if err != nil {
		t.Fatalf("podwait: %v", err)
	}

733 734 735 736
	// 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
737
	}
738
	if err = retry.Expo(mysql, 5*time.Second, 180*time.Second); err != nil {
739
		t.Errorf("mysql failing: %v", err)
740 741 742
	}
}

743 744 745 746 747 748 749 750 751 752
// 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())
}

753 754
// Copy extra file into minikube home folder for file sync test
func setupFileSync(ctx context.Context, t *testing.T, profile string) {
755 756 757
	p := localSyncTestPath()
	t.Logf("local sync path: %s", p)
	err := copy.Copy("./testdata/sync.test", p)
758 759 760 761 762 763 764 765 766 767
	if err != nil {
		t.Fatalf("copy: %v", err)
	}
}

// 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")
	}
768 769 770 771

	vp := vmSyncTestPath()
	t.Logf("Checking for existence of %s within VM", vp)
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", fmt.Sprintf("cat %s", vp)))
772 773 774
	if err != nil {
		t.Errorf("%s failed: %v", rr.Args, err)
	}
775 776
	got := rr.Stdout.String()
	t.Logf("file sync test content: %s", got)
777 778 779 780 781 782

	expected, err := ioutil.ReadFile("./testdata/sync.test")
	if err != nil {
		t.Errorf("test file not found: %v", err)
	}

783
	if diff := cmp.Diff(string(expected), got); diff != "" {
784 785 786 787
		t.Errorf("/etc/sync.test content mismatch (-want +got):\n%s", diff)
	}
}

788 789 790 791 792 793 794 795 796 797 798 799 800
// 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 {
		t.Errorf("%s failed: %v", rr.Args, err)
	}

	want := []byte("IP was already correctly configured")
	if !bytes.Contains(rr.Stdout.Bytes(), want) {
		t.Errorf("update-context: got=%q, want=*%q*", rr.Stdout.Bytes(), want)
	}
}

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
// 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
817
}