functional_test.go 31.1 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 41 42
	"github.com/google/go-cmp/cmp"

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

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

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

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

	// Serial tests
	t.Run("serial", func(t *testing.T) {
		tests := []struct {
			name      string
			validator validateFunc
		}{
81 82 83 84 85 86
			{"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
87 88 89 90 91 92
		}
		for _, tc := range tests {
			tc := tc
			t.Run(tc.name, func(t *testing.T) {
				tc.validator(ctx, t, profile)
			})
M
Medya Gh 已提交
93
		}
94
	})
M
Medya Gh 已提交
95

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

M
Medya Gh 已提交
136 137
// 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 已提交
138
	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 已提交
139
	if err != nil {
M
Medya Gh 已提交
140
		t.Errorf("failed to 'kubectl get nodes' with args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
141 142 143
	}
	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 已提交
144 145
		if !strings.Contains(rr.Output(), el) {
			t.Errorf("expected to have label %q in node labels: %q", expectedLabels, rr.Output())
M
Medya Gh 已提交
146 147 148 149
		}
	}
}

150 151
// check functionality of minikube after evaling docker-env
func validateDockerEnv(ctx context.Context, t *testing.T, profile string) {
M
Medya Gh 已提交
152
	mctx, cancel := context.WithTimeout(ctx, Seconds(13))
153 154 155 156 157
	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 {
158
		t.Fatalf("failed to do minikube status after eval-ing docker-env %s", err)
159 160
	}
	if !strings.Contains(rr.Output(), "Running") {
161
		t.Fatalf("expected status output to include 'Running' after eval docker-env but got: *%q*", rr.Output())
162 163
	}

M
Medya Gh 已提交
164
	mctx, cancel = context.WithTimeout(ctx, Seconds(13))
165 166 167 168 169
	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 已提交
170
		t.Fatalf("failed to run minikube docker-env. args %q : %v ", rr.Command(), err)
171 172 173 174
	}

	expectedImgInside := "gcr.io/k8s-minikube/storage-provisioner"
	if !strings.Contains(rr.Output(), expectedImgInside) {
175
		t.Fatalf("expected 'docker images' to have %q inside minikube. but the output is: *%q*", expectedImgInside, rr.Output())
176 177 178 179
	}

}

180 181 182
func validateStartWithProxy(ctx context.Context, t *testing.T, profile string) {
	srv, err := startHTTPProxy(t)
	if err != nil {
183
		t.Fatalf("failed to set up the test proxy: %s", err)
184
	}
185 186

	// Use more memory so that we may reliably fit MySQL and nginx
187
	startArgs := append([]string{"start", "-p", profile, "--wait=true"}, StartArgs()...)
188
	c := exec.CommandContext(ctx, Target(), startArgs...)
189 190 191 192 193 194
	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 已提交
195
		t.Errorf("failed minikube start. args %q: %v", rr.Command(), err)
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
	}

	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 {
M
Medya Gh 已提交
213
		t.Errorf("failed to get current-context. args %q : %v", rr.Command(), err)
214 215
	}
	if !strings.Contains(rr.Stdout.String(), profile) {
216
		t.Errorf("expected current-context = %q, but got *%q*", profile, rr.Stdout.String())
217 218 219
	}
}

P
Priya Wadhwa 已提交
220 221
// validateKubectlGetPods asserts that `kubectl get pod -A` returns non-zero content
func validateKubectlGetPods(ctx context.Context, t *testing.T, profile string) {
222
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "po", "-A"))
P
Priya Wadhwa 已提交
223
	if err != nil {
M
Medya Gh 已提交
224
		t.Errorf("failed to get kubectl pods: args %q : %v", rr.Command(), err)
P
Priya Wadhwa 已提交
225
	}
226
	if rr.Stderr.String() != "" {
227
		t.Errorf("expected stderr to be empty but got *%q*: args %q", rr.Stderr, rr.Command())
228
	}
T
Thomas Stromberg 已提交
229
	if !strings.Contains(rr.Stdout.String(), "kube-system") {
230
		t.Errorf("expected stdout to include *kube-system* but got *%q*. args: %q", rr.Stdout, rr.Command())
P
Priya Wadhwa 已提交
231 232 233
	}
}

234 235
// validateMinikubeKubectl validates that the `minikube kubectl` command returns content
func validateMinikubeKubectl(ctx context.Context, t *testing.T, profile string) {
236 237
	// 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 已提交
238
	rr, err := Run(t, exec.CommandContext(ctx, Target(), kubectlArgs...))
239
	if err != nil {
M
Medya Gh 已提交
240
		t.Fatalf("failed to get pods. args %q: %v", rr.Command(), err)
241 242 243
	}
}

244 245 246 247
// 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 已提交
248
		t.Fatalf("failed to get components. args %q: %v", rr.Command(), err)
249 250 251 252
	}
	cs := api.ComponentStatusList{}
	d := json.NewDecoder(bytes.NewReader(rr.Stdout.Bytes()))
	if err := d.Decode(&cs); err != nil {
M
Medya Gh 已提交
253
		t.Fatalf("failed to decode kubectl json output: args %q : %v", rr.Command(), err)
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
	}

	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 已提交
270
func validateStatusCmd(ctx context.Context, t *testing.T, profile string) {
271
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status"))
J
Josh Woodcock 已提交
272
	if err != nil {
M
Medya Gh 已提交
273
		t.Errorf("failed to run minikube status. args %q : %v", rr.Command(), err)
J
Josh Woodcock 已提交
274 275 276
	}

	// Custom format
277
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-f", "host:{{.Host}},kublet:{{.Kubelet}},apiserver:{{.APIServer}},kubeconfig:{{.Kubeconfig}}"))
J
Josh Woodcock 已提交
278
	if err != nil {
M
Medya Gh 已提交
279
		t.Errorf("failed to run minikube status with custom format: args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
280
	}
281 282
	re := `host:([A-z]+),kublet:([A-z]+),apiserver:([A-z]+),kubeconfig:([A-z]+)`
	match, _ := regexp.MatchString(re, rr.Stdout.String())
J
Josh Woodcock 已提交
283
	if !match {
M
Medya Gh 已提交
284
		t.Errorf("failed to match regex %q for minikube status with custom format. args %q. output %q", re, rr.Command(), rr.Output())
J
Josh Woodcock 已提交
285 286 287
	}

	// Json output
288
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-o", "json"))
J
Josh Woodcock 已提交
289
	if err != nil {
M
Medya Gh 已提交
290
		t.Errorf("failed to run minikube status with json output. args %q : %v", rr.Command(), err)
J
Josh Woodcock 已提交
291 292 293 294
	}
	var jsonObject map[string]interface{}
	err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
	if err != nil {
M
Medya Gh 已提交
295
		t.Errorf("failed to decode json from minikube status. args %q. %v", rr.Command(), err)
J
Josh Woodcock 已提交
296 297
	}
	if _, ok := jsonObject["Host"]; !ok {
M
Medya Gh 已提交
298
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Host")
J
Josh Woodcock 已提交
299 300
	}
	if _, ok := jsonObject["Kubelet"]; !ok {
M
Medya Gh 已提交
301
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Kubelet")
J
Josh Woodcock 已提交
302 303
	}
	if _, ok := jsonObject["APIServer"]; !ok {
M
Medya Gh 已提交
304
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "APIServer")
J
Josh Woodcock 已提交
305 306
	}
	if _, ok := jsonObject["Kubeconfig"]; !ok {
M
Medya Gh 已提交
307
		t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Kubeconfig")
J
Josh Woodcock 已提交
308 309 310
	}
}

311 312 313 314 315
// 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 {
316
		t.Errorf("failed to run minikube dashboard. args %q : %v", args, err)
317 318 319 320 321 322
	}
	defer func() {
		ss.Stop(t)
	}()

	start := time.Now()
M
Medya Gh 已提交
323
	s, err := ReadLineWithTimeout(ss.Stdout, Seconds(300))
324
	if err != nil {
T
tstromberg 已提交
325 326 327 328
		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)
329 330 331 332 333 334 335 336 337
	}

	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 {
338
		t.Fatalf("failed to http get %q : %v", u.String(), err)
339 340 341 342
	}
	if resp.StatusCode != http.StatusOK {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
343
			t.Errorf("failed to read http response body from dashboard %q: %v", u.String(), err)
344 345 346 347
		}
		t.Errorf("%s returned status code %d, expected %d.\nbody:\n%s", u, resp.StatusCode, http.StatusOK, body)
	}
}
M
Medya Gh 已提交
348

349 350 351 352
// 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 已提交
353
		t.Fatalf("failed to kubectl replace busybox : args %q: %v", rr.Command(), err)
354 355
	}

M
typo  
Medya Gh 已提交
356
	names, err := PodWait(ctx, t, profile, "default", "integration-test=busybox", Minutes(4))
357
	if err != nil {
358
		t.Fatalf("failed waiting for busybox pod : %v", err)
359 360
	}

361 362 363 364 365 366
	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.
367
	if err = retry.Expo(nslookup, 1*time.Second, Minutes(1)); err != nil {
368
		t.Errorf("failed to do nslookup on kubernetes.default: %v", err)
369 370 371 372
	}

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

T
Thomas Stromberg 已提交
377 378
// validateDryRun asserts that the dry-run mode quickly exits with the right code
func validateDryRun(ctx context.Context, t *testing.T, profile string) {
379
	// dry-run mode should always be able to finish quickly (<5s)
M
Medya Gh 已提交
380
	mctx, cancel := context.WithTimeout(ctx, Seconds(5))
T
Thomas Stromberg 已提交
381 382 383
	defer cancel()

	// Too little memory!
384
	startArgs := append([]string{"start", "-p", profile, "--dry-run", "--memory", "250MB", "--alsologtostderr", "-v=1"}, StartArgs()...)
T
Thomas Stromberg 已提交
385 386 387 388 389 390 391 392
	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 已提交
393
	dctx, cancel := context.WithTimeout(ctx, Seconds(5))
T
Thomas Stromberg 已提交
394
	defer cancel()
395
	startArgs = append([]string{"start", "-p", profile, "--dry-run", "--alsologtostderr", "-v=1"}, StartArgs()...)
T
Thomas Stromberg 已提交
396 397 398 399 400 401 402
	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 已提交
403
// validateCacheCmd tests functionality of cache command (cache add, delete, list)
404 405 406 407
func validateCacheCmd(ctx context.Context, t *testing.T, profile string) {
	if NoneDriver() {
		t.Skipf("skipping: cache unsupported by none")
	}
M
Medya Gh 已提交
408 409
	t.Run("cache", func(t *testing.T) {
		t.Run("add", func(t *testing.T) {
410
			for _, img := range []string{"busybox:latest", "busybox:1.28.4-glibc", "k8s.gcr.io/pause:latest"} {
411
				rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "add", img))
M
Medya Gh 已提交
412
				if err != nil {
M
Medya Gh 已提交
413
					t.Errorf("failed to cache add image %q. args %q err %v", img, rr.Command(), err)
M
Medya Gh 已提交
414 415 416
				}
			}
		})
M
Medya Ghazizadeh 已提交
417
		t.Run("delete_busybox:1.28.4-glibc", func(t *testing.T) {
418
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "delete", "busybox:1.28.4-glibc"))
M
Medya Gh 已提交
419
			if err != nil {
M
Medya Gh 已提交
420
				t.Errorf("failed to delete image busybox:1.28.4-glibc from cache. args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
421 422
			}
		})
M
Medya Gh 已提交
423

M
Medya Gh 已提交
424 425 426
		t.Run("list", func(t *testing.T) {
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "list"))
			if err != nil {
M
Medya Gh 已提交
427
				t.Errorf("failed to do cache list. args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
428 429
			}
			if !strings.Contains(rr.Output(), "k8s.gcr.io/pause") {
430
				t.Errorf("expected 'cache list' output to include 'k8s.gcr.io/pause' but got:\n ***%q***", rr.Output())
M
Medya Gh 已提交
431 432
			}
			if strings.Contains(rr.Output(), "busybox:1.28.4-glibc") {
433
				t.Errorf("expected 'cache list' output not to include busybox:1.28.4-glibc but got:\n ***%q***", rr.Output())
M
Medya Gh 已提交
434 435
			}
		})
M
Medya Gh 已提交
436

M
Medya Ghazizadeh 已提交
437
		t.Run("verify_cache_inside_node", func(t *testing.T) {
M
Medya Gh 已提交
438
			rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "images"))
M
Medya Gh 已提交
439
			if err != nil {
M
Medya Gh 已提交
440
				t.Errorf("failed to get images by %q ssh %v", rr.Command(), err)
M
Medya Gh 已提交
441
			}
M
Medya Gh 已提交
442
			if !strings.Contains(rr.Output(), "1.28.4-glibc") {
443
				t.Errorf("expected '1.28.4-glibc' to be in the output but got %q", rr.Output())
M
Medya Gh 已提交
444 445 446
			}

		})
M
Medya Gh 已提交
447

M
Medya Ghazizadeh 已提交
448
		t.Run("cache_reload", func(t *testing.T) { // deleting image inside minikube node manually and expecting reload to bring it back
M
Medya Gh 已提交
449 450
			img := "busybox:latest"
			// deleting image inside minikube node manually
M
Medya Gh 已提交
451
			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 已提交
452 453 454 455 456 457
			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 {
458
				t.Errorf("expected an error. because image should not exist. but got *nil error* ! cmd: %q", rr.Command())
M
Medya Gh 已提交
459
			}
M
Medya Gh 已提交
460
			// minikube cache reload.
M
Medya Gh 已提交
461 462
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "reload"))
			if err != nil {
463
				t.Errorf("expected %q to run successfully but got error: %v", rr.Command(), err)
M
Medya Gh 已提交
464
			}
M
Medya Gh 已提交
465
			// make sure 'cache reload' brought back the manually deleted image.
M
Medya Gh 已提交
466 467
			rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "inspecti", img))
			if err != nil {
468
				t.Errorf("expected %q to run successfully but got error: %v", rr.Command(), err)
M
Medya Gh 已提交
469 470 471
			}
		})

M
Medya Gh 已提交
472
	})
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
}

// 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 == "" {
M
Medya Gh 已提交
494
			t.Errorf("failed to config minikube. args %q : %v", rr.Command(), err)
495 496 497 498
		}

		got := strings.TrimSpace(rr.Stdout.String())
		if got != tc.wantOut {
499
			t.Errorf("expected config output for %q to be -%q- but got *%q*", rr.Command(), tc.wantOut, got)
500 501 502
		}
		got = strings.TrimSpace(rr.Stderr.String())
		if got != tc.wantErr {
503
			t.Errorf("expected config error for %q to be -%q- but got *%q*", rr.Command(), tc.wantErr, got)
504 505 506 507 508 509 510 511
		}
	}
}

// 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 已提交
512
		t.Errorf("%s failed: %v", rr.Command(), err)
513 514 515
	}
	for _, word := range []string{"Docker", "apiserver", "Linux", "kubelet"} {
		if !strings.Contains(rr.Stdout.String(), word) {
516
			t.Errorf("excpeted minikube logs to include word: -%q- but got \n***%q***\n", word, rr.Output())
517 518 519 520
		}
	}
}

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

M
Medya Gh 已提交
549 550
	t.Run("profile_list", func(t *testing.T) {
		// List profiles
M
lint  
Medya Gh 已提交
551
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list"))
M
Medya Gh 已提交
552
		if err != nil {
M
Medya Gh 已提交
553
			t.Errorf("failed to list profiles: args %q : %v", rr.Command(), err)
M
Medya Gh 已提交
554
		}
J
Josh Woodcock 已提交
555

M
Medya Gh 已提交
556 557 558 559 560 561 562 563 564 565 566
		// 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 已提交
567
			t.Errorf("expected 'profile list' output to include %q but got *%q*. args: %q", profile, rr.Stdout.String(), rr.Command())
J
Josh Woodcock 已提交
568
		}
M
Medya Gh 已提交
569 570 571 572
	})

	t.Run("profile_json_output", func(t *testing.T) {
		// Json output
M
lint  
Medya Gh 已提交
573
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "--output", "json"))
M
Medya Gh 已提交
574
		if err != nil {
M
Medya Gh 已提交
575
			t.Errorf("failed to list profiles with json format. args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
576
		}
M
Medya Gh 已提交
577 578 579
		var jsonObject map[string][]map[string]interface{}
		err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
		if err != nil {
M
Medya Gh 已提交
580
			t.Errorf("failed to decode json from profile list: args %q: %v", rr.Command(), err)
M
Medya Gh 已提交
581 582
		}
		validProfiles := jsonObject["valid"]
M
lint  
Medya Gh 已提交
583
		profileExists := false
M
Medya Gh 已提交
584 585 586 587 588 589 590
		for _, profileObject := range validProfiles {
			if profileObject["Name"] == profile {
				profileExists = true
				break
			}
		}
		if !profileExists {
M
Medya Gh 已提交
591
			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 已提交
592 593 594
		}

	})
595 596 597
}

// validateServiceCmd asserts basic "service" command functionality
598
func validateServiceCmd(ctx context.Context, t *testing.T, profile string) {
599
	rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "create", "deployment", "hello-node", "--image=gcr.io/hello-minikube-zero-install/hello-node"))
600
	if err != nil {
M
Medya Gh 已提交
601
		t.Logf("%q failed: %v (may not be an error).", rr.Command(), err)
602
	}
603
	rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "expose", "deployment", "hello-node", "--type=NodePort", "--port=8080"))
604
	if err != nil {
M
Medya Gh 已提交
605
		t.Logf("%q failed: %v (may not be an error)", rr.Command(), err)
606 607
	}

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

612
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "list"))
613
	if err != nil {
M
Medya Gh 已提交
614
		t.Errorf("failed to do service list. args %q : %v", rr.Command(), err)
615
	}
616
	if !strings.Contains(rr.Stdout.String(), "hello-node") {
617
		t.Errorf("expected 'service list' to contain *hello-node* but got -%q-", rr.Stdout.String())
618 619 620
	}

	// Test --https --url mode
621
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "--namespace=default", "--https", "--url", "hello-node"))
622
	if err != nil {
M
Medya Gh 已提交
623
		t.Fatalf("failed to get service url. args %q : %v", rr.Command(), err)
624 625
	}
	if rr.Stderr.String() != "" {
626
		t.Errorf("expected stderr to be empty but got *%q*", rr.Stderr)
627
	}
628 629

	endpoint := strings.TrimSpace(rr.Stdout.String())
630 631
	u, err := url.Parse(endpoint)
	if err != nil {
632
		t.Fatalf("failed to parse service url endpoint %q: %v", endpoint, err)
633 634
	}
	if u.Scheme != "https" {
635
		t.Errorf("expected scheme to be 'https' but got %q", u.Scheme)
636 637 638
	}

	// Test --format=IP
639
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "hello-node", "--url", "--format={{.IP}}"))
640
	if err != nil {
M
Medya Gh 已提交
641
		t.Errorf("failed to get service url with custom format. args %q: %v", rr.Command(), err)
642
	}
643
	if strings.TrimSpace(rr.Stdout.String()) != u.Hostname() {
M
Medya Gh 已提交
644
		t.Errorf("expected 'service --format={{.IP}}' output to be -%q- but got *%q* . args %q.", u.Hostname(), rr.Stdout.String(), rr.Command())
645 646
	}

647 648
	// Test a regular URLminikube
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "hello-node", "--url"))
649
	if err != nil {
M
Medya Gh 已提交
650
		t.Errorf("failed to get service url. args: %q: %v", rr.Command(), err)
651
	}
652 653 654 655 656 657 658

	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 已提交
659
		t.Fatalf("expected scheme to be -%q- got scheme: *%q*", "http", u.Scheme)
660 661 662 663
	}

	t.Logf("url: %s", endpoint)
	resp, err := retryablehttp.Get(endpoint)
664
	if err != nil {
665
		t.Fatalf("get failed: %v\nresp: %v", err, resp)
666 667
	}
	if resp.StatusCode != http.StatusOK {
M
lint  
Medya Gh 已提交
668
		t.Fatalf("expected status code for %q to be -%q- but got *%q*", endpoint, http.StatusOK, resp.StatusCode)
669 670 671
	}
}

672 673
// validateAddonsCmd asserts basic "addon" command functionality
func validateAddonsCmd(ctx context.Context, t *testing.T, profile string) {
M
Medya Gh 已提交
674
	// Table output
675 676
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "addons", "list"))
	if err != nil {
M
Medya Gh 已提交
677
		t.Errorf("failed to do addon list: args %q : %v", rr.Command(), err)
678
	}
M
Medya Gh 已提交
679 680
	for _, a := range []string{"dashboard", "ingress", "ingress-dns"} {
		if !strings.Contains(rr.Output(), a) {
681
			t.Errorf("expected 'addon list' output to include -%q- but got *%q*", a, rr.Output())
682 683
		}
	}
J
Josh Woodcock 已提交
684 685 686 687

	// Json output
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "addons", "list", "-o", "json"))
	if err != nil {
M
Medya Gh 已提交
688
		t.Errorf("failed to do addon list with json output. args %q: %v", rr.Command(), err)
J
Josh Woodcock 已提交
689 690 691 692
	}
	var jsonObject map[string]interface{}
	err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
	if err != nil {
693
		t.Errorf("failed to decode addon list json output : %v", err)
J
Josh Woodcock 已提交
694
	}
695 696
}

697 698 699 700 701
// 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 已提交
702
	want := "hello\n"
703 704
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", fmt.Sprintf("echo hello")))
	if err != nil {
M
Medya Gh 已提交
705
		t.Errorf("failed to run an ssh command. args %q : %v", rr.Command(), err)
706 707
	}
	if rr.Stdout.String() != want {
M
Medya Gh 已提交
708
		t.Errorf("expected minikube ssh command output to be -%q- but got *%q*. args %q", want, rr.Stdout.String(), rr.Command())
709 710 711
	}
}

712 713 714 715
// 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 已提交
716
		t.Fatalf("failed to kubectl replace mysql: args %q failed: %v", rr.Command(), err)
717 718
	}

719
	names, err := PodWait(ctx, t, profile, "default", "app=mysql", Minutes(10))
720
	if err != nil {
721
		t.Fatalf("failed waiting for mysql pod: %v", err)
722 723
	}

724 725 726 727
	// 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
728
	}
729 730
	if err = retry.Expo(mysql, 1*time.Second, Seconds(200)); err != nil {
		t.Errorf("failed to exec 'mysql -ppassword -e show databases;': %v", err)
731 732 733
	}
}

734 735 736 737 738 739 740 741 742 743
// 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())
}

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

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

	err = copy.Copy("./testdata/minikube_test.pem", localTestCertPath())
	if err != nil {
765
		t.Fatalf("failed to copy ./testdata/minikube_test.pem : %v", err)
766
	}
767 768 769 770 771 772 773
}

// 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")
	}
774 775 776 777

	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)))
778
	if err != nil {
M
Medya Gh 已提交
779
		t.Errorf("%s failed: %v", rr.Command(), err)
780
	}
781 782
	got := rr.Stdout.String()
	t.Logf("file sync test content: %s", got)
783 784 785

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

789
	if diff := cmp.Diff(string(expected), got); diff != "" {
790 791 792 793
		t.Errorf("/etc/sync.test content mismatch (-want +got):\n%s", diff)
	}
}

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
// 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)
		rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", fmt.Sprintf("cat %s", vp)))
		if err != nil {
M
Medya Gh 已提交
816
			t.Errorf("failed to check existence of %q inside minikube. args %q: %v", vp, rr.Command(), err)
817 818 819 820 821
		}

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

827 828 829 830
// 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 已提交
831
		t.Errorf("failed to run minikube update-context: args %q: %v", rr.Command(), err)
832 833
	}

T
Thomas Stromberg 已提交
834
	want := []byte("No changes")
835 836 837 838 839
	if !bytes.Contains(rr.Stdout.Bytes(), want) {
		t.Errorf("update-context: got=%q, want=*%q*", rr.Stdout.Bytes(), want)
	}
}

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
// 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
856
}