Example #1
0
func TestCheckImageExists(t *testing.T) {
	var found bool
	var err error

	dockerClient = &mockClient{waitSleep: 100 * time.Millisecond}

	expected := []string{"latest", "13.2"}
	for _, e := range expected {
		capture.All(func() {
			found, err = checkImageExists("opensuse", e)
		})

		if err != nil {
			t.Fatal("Unexpected error")
		}
		if found != true {
			t.Fatal("The image should have been found")
		}
	}

	not_expected := []string{"unexpected_tag"}
	for _, unexpected := range not_expected {
		capture.All(func() {
			found, err = checkImageExists("opensuse", unexpected)
		})

		if err != nil {
			t.Fatal("Unexpected error")
		}
		if found != false {
			t.Fatal("The image should not have been found")
		}
	}
}
Example #2
0
func TestSetupLoggerHome(t *testing.T) {
	abs, err := filepath.Abs("test")
	if err != nil {
		t.Fatalf("Could not setup the test suite: %v\n", err)
	}
	home := os.Getenv("HOME")
	defer func() {
		_ = os.Setenv("HOME", home)
		_ = os.Remove(filepath.Join(abs, logFileName))
	}()
	_ = os.Setenv("HOME", abs)

	res := capture.All(func() {
		setupLogger(testContext([]string{}, false))
		log.Printf("Test")
	})
	if len(res.Stdout) != 0 {
		t.Fatal("Nothing should've been printed to stdout\n")
	}
	contents, err := ioutil.ReadFile(filepath.Join(abs, logFileName))
	if err != nil {
		t.Fatalf("Could not read contents of the log: %v\n", err)
	}
	if !strings.HasSuffix(string(contents), "Test\n") {
		t.Fatalf("'%v' expected to have logged 'Test'\n", string(contents))
	}
}
Example #3
0
func TestImagesListOk(t *testing.T) {
	dockerClient = &mockClient{waitSleep: 100 * time.Millisecond}
	setupTestExitStatus()

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)

	res := capture.All(func() { imagesCmd(testContext([]string{}, false)) })

	lines := strings.Split(string(res.Stdout), "\n")
	if len(lines) != 7 {
		t.Fatal("Wrong number of lines")
	}
	if !strings.HasPrefix(lines[1], "REPOSITORY") {
		t.Fatal("Wrong contents")
	}
	str := "opensuse            latest              1                   Less than a second ago   254.5 MB"
	if lines[2] != str {
		t.Fatal("Wrong contents")
	}
	str = "opensuse            tag                 1                   Less than a second ago   254.5 MB"
	if lines[3] != str {
		t.Fatal("Wrong contents")
	}
	str = "opensuse            13.2                2                   Less than a second ago   254.5 MB"
	if lines[4] != str {
		t.Fatal("Wrong contents")
	}
	if exitInvocations != 1 && lastCode != 0 {
		t.Fatal("Wrong exit code")
	}
}
Example #4
0
func TestPsCommandMatches(t *testing.T) {
	cacheFile := getCacheFile()
	cacheFile.Outdated = []string{"2"} // this is the Id of the opensuse:13.2 image
	cacheFile.Other = []string{"3"}    // this is the Id of the ubuntu:latest image
	cacheFile.flush()

	setupTestExitStatus()
	safeClient.client = &mockClient{}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)
	rec := capture.All(func() { psCmd(testContext([]string{}, false)) })

	if !strings.Contains(buffer.String(), "Cannot analyze container 4 [foo]") {
		t.Fatal("Wrong message")
	}
	if !strings.Contains(string(rec.Stdout), "Running containers whose images have been updated") {
		t.Fatal("Wrong message")
	}
	if !strings.Contains(string(rec.Stdout), "The following containers have an unknown state") &&
		!strings.Contains(string(rec.Stdout), "busybox") &&
		!strings.Contains(string(rec.Stdout), "foo") {
		t.Fatal("Wrong message")
	}
	if !strings.Contains(string(rec.Stdout), "The following containers have been ignored") &&
		!strings.Contains(string(rec.Stdout), "ubuntu") {
		t.Fatal("Wrong message")
	}
	if exitInvocations != 0 {
		t.Fatalf("Should not have exited with an error")
	}
	if lastCode != 0 {
		t.Fatalf("Exit status should be 1, %v given", lastCode)
	}
}
Example #5
0
func TestPsCommandNoMatches(t *testing.T) {
	cache := os.Getenv("XDG_CACHE_HOME")
	abs, _ := filepath.Abs(".")
	test := filepath.Join(abs, "test")

	defer func() {
		_ = os.Setenv("XDG_CACHE_HOME", cache)
	}()

	_ = os.Setenv("XDG_CACHE_HOME", test)

	setupTestExitStatus()
	dockerClient = &mockClient{}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)
	capture.All(func() { psCmd(testContext([]string{}, false)) })

	if strings.Contains(buffer.String(), "Running containers whose images have been updated") {
		t.Fatal("It should not have found matches")
	}
	if exitInvocations != 0 {
		t.Fatalf("Should not have exited with an error")
	}
}
Example #6
0
func TestImagesListUsingCache(t *testing.T) {
	safeClient.client = &mockClient{waitSleep: 100 * time.Millisecond}
	setupTestExitStatus()

	// Dump some dummy value.
	cd := getCacheFile()
	cd.Suse = []string{"1"}
	cd.Other = []string{"3"}
	cd.flush()

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)

	res := capture.All(func() { imagesCmd(testContext([]string{}, false)) })

	testReaderData(t, bytes.NewBuffer(res.Stdout), []string{
		"REPOSITORY",
		"opensuse            latest              1",
		"opensuse            tag                 1",
		"opensuse            13.2                2",
		"busybox             latest              5",
	})

	if exitInvocations != 1 && lastCode != 0 {
		t.Fatal("Wrong exit code")
	}
}
Example #7
0
func TestHostConfig(t *testing.T) {
	hc := getHostConfig()
	if len(hc.ExtraHosts) != 0 {
		t.Fatalf("Wrong number of extra hosts: %v; Expected: 1", len(hc.ExtraHosts))
	}

	originalArgs := os.Args
	defer func() {
		os.Args = originalArgs
		currentContext = nil
	}()
	os.Args = []string{"exe", "--add-host", "host:ip", "test"}

	app := newApp()
	app.Commands = []cli.Command{{Name: "test", Action: getCmd("test", func(*cli.Context) {})}}
	capture.All(func() { app.RunAndExitOnError() })

	hc = getHostConfig()
	if len(hc.ExtraHosts) != 1 {
		t.Fatalf("Wrong number of extra hosts: %v; Expected: 1", len(hc.ExtraHosts))
	}
	if hc.ExtraHosts[0] != "host:ip" {
		t.Fatalf("Did not expect %v", hc.ExtraHosts[0])
	}
}
Example #8
0
func TestLogAndPrintfAndFatalf(t *testing.T) {
	setupTestExitStatus()
	dm := debugMode

	// Debug mode: false

	debugMode = false

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)

	res := capture.All(func() { logAndFatalf("Here") })

	if !strings.Contains(buffer.String(), "Here") {
		t.Fatalf("Wrong logged value!")
	}
	if !strings.Contains(string(res.Stdout), "Here") {
		t.Fatalf("Wrong logged value!")
	}
	if lastCode != 1 {
		t.Fatalf("It should've failed!")
	}

	// Debug mode: true

	debugMode = true
	lastCode = 0

	buffer = bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)

	res = capture.All(func() { logAndPrintf("Here") })

	if !strings.Contains(buffer.String(), "Here") {
		t.Fatalf("Wrong logged value!")
	}
	if len(res.Stdout) != 0 {
		t.Fatalf("Should've been empty!")
	}
	if lastCode != 0 {
		t.Fatalf("lastCode should've not been changed")
	}

	debugMode = dm
}
Example #9
0
func TestUpdateCommandRunAndCommitFailure(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{startFail: true}

	capture.All(func() { updateCmd(testContext([]string{"ori", "new:1.0.0"}, false)) })

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
}
Example #10
0
func TestUpdateCommandInvalidTargetName(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{}

	capture.All(func() { updateCmd(testContext([]string{"ori", "WRONG"}, false)) })

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
}
Example #11
0
func TestPatchCommandInvalidTargetName(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{}

	capture.All(func() { patchCmd(testPatchContext("ori", "WRONG")) })

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
}
Example #12
0
func TestPatchCommandImageOverwriteDetected(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{listFail: true}

	capture.All(func() { patchCmd(testPatchContext("ori", "new:1.0.0")) })

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
}
Example #13
0
// run the test cases.
func (cases testCases) run(t *testing.T, cmd func(*cli.Context), command, debug string) {
	for _, test := range cases {
		// Skip if this not the one being debugged.
		if debug != "" && debug != test.desc {
			continue
		}

		setupTestExitStatus()
		safeClient.client = test.client

		buffer := bytes.NewBuffer([]byte{})
		log.SetOutput(buffer)
		captured := capture.All(func() { cmd(testContext(test.args, false)) })

		// Exit status code
		if lastCode != test.code {
			t.Fatalf("[%s] Expected to have exited with code %v, %v was received.",
				test.desc, test.code, lastCode)
		}

		// Log
		if test.msg == "" {
			lines := strings.Split(buffer.String(), "\n")
			// The first line might be the cache failing to be loaded.
			if !(len(lines) == 1 || len(lines) == 2) || lines[len(lines)-1] != "" {
				t.Fatalf("Should've loggeed nothing, logged:\n%s\n", buffer.String())
			}
		} else {
			if !strings.Contains(buffer.String(), test.msg) {
				t.Fatalf("[%s] Wrong logged message.\nExpecting:\n%s\n===\nReceived:\n%s\n",
					test.desc, test.msg, buffer.String())
			}
		}

		// Stdout
		if test.logAndStdout {
			test.stdout = test.msg
		}
		if test.stdout != "" {
			if !strings.Contains(string(captured.Stdout), test.stdout) {
				t.Fatalf("[%s] Wrong stdout.\nExpecting:\n%s\n===\nReceived:\n%s\n",
					test.desc, test.stdout, string(captured.Stdout))
			}
		}
		if lastCode == 0 && command != "" {
			if command != testCommand() {
				t.Fatalf("[%s] Wrong command. Expecting '%s', '%s' received.\n",
					test.desc, command, testCommand())
			}
		}
	}
}
Example #14
0
func TestCheckImageListFail(t *testing.T) {
	dockerClient = &mockClient{listFail: true}

	var err error

	capture.All(func() {
		_, err = checkImageExists("opensuse", "bar")
	})

	if err == nil {
		t.Fatal("Error did not occur")
	}
}
Example #15
0
func TestSetupLoggerDebug(t *testing.T) {
	// Set debug mode.
	set := flag.NewFlagSet("test", 0)
	set.Bool("debug", true, "doc")
	c := cli.NewContext(nil, set, nil)

	res := capture.All(func() {
		setupLogger(c)
		log.Printf("Test")
	})
	if !strings.HasSuffix(string(res.Stdout), "Test\n") {
		t.Fatalf("'%v' expected to have logged 'Test'\n", string(res.Stdout))
	}
}
Example #16
0
func TestPatchCheckContainerCheckContainerSuccess(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)

	capture.All(func() {
		patchCheckContainerCmd(testContext([]string{"suse"}, false))
	})

	if exitInvocations != 0 {
		t.Fatalf("Should not have exited with error")
	}
}
Example #17
0
func TestGetCmd(t *testing.T) {
	defer func() {
		currentContext = nil
	}()

	fn1 := getCmd("images", func(ctx *cli.Context) { log.Printf("Hello") })
	fn2 := getCmd("ps", func(ctx *cli.Context) { log.Printf("Hello") })

	set := flag.NewFlagSet("test", 0)
	set.Bool("debug", true, "doc")
	ctx := cli.NewContext(nil, set, nil)

	all := capture.All(func() { fn1(ctx) })
	stdout := string(all.Stdout)
	if !strings.HasPrefix(stdout, "[images]") {
		t.Fatalf("%s: should've started with [images]", stdout)
	}

	all = capture.All(func() { fn2(ctx) })
	stdout = string(all.Stdout)
	if !strings.HasPrefix(stdout, "[ps]") {
		t.Fatalf("%s: should've started with [ps]", stdout)
	}
}
Example #18
0
func TestUpdateCommandWrongInvocation(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)
	capture.All(func() { updateCmd(testContext([]string{}, false)) })

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
	if !strings.Contains(buffer.String(), "Wrong invocation") {
		t.Fatal("It should've logged something\n")
	}
}
Example #19
0
func TestUpdateCommandCommitSuccess(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{listReturnOneImage: true}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)
	capture.All(func() { updateCmd(testContext([]string{"opensuse:13.2", "new:1.0.0"}, false)) })

	if exitInvocations != 0 {
		t.Fatalf("Expected to have exited successfully")
	}
	if !strings.Contains(buffer.String(), "new:1.0.0 successfully created") {
		t.Fatal("It should've logged something\n")
	}
}
Example #20
0
func TestPatchCheckContainerFailure(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{listFail: true}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)

	capture.All(func() {
		patchCheckContainerCmd(testContext([]string{"opensuse:13.2"}, false))
	})

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
}
Example #21
0
func TestPsCommandListContaienrsEmpty(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{listEmpty: true}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)
	capture.All(func() { psCmd(testContext([]string{}, false)) })

	if !strings.Contains(buffer.String(), "There are no running containers") {
		t.Fatal("It should've logged something\n")
	}
	if exitInvocations != 0 {
		t.Fatalf("Should not have exited with an error")
	}
}
Example #22
0
func TestImagesListUsingCache(t *testing.T) {
	dockerClient = &mockClient{waitSleep: 100 * time.Millisecond}
	setupTestExitStatus()

	cache := os.Getenv("XDG_CACHE_HOME")
	abs, _ := filepath.Abs(".")
	test := filepath.Join(abs, "test")

	defer func() {
		_ = os.Setenv("XDG_CACHE_HOME", cache)
	}()
	_ = os.Setenv("XDG_CACHE_HOME", test)

	// Dump some dummy value.
	cd := getCacheFile()
	cd.Suse = []string{"1"}
	cd.Other = []string{"3"}
	cd.flush()

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)

	res := capture.All(func() { imagesCmd(testContext([]string{}, false)) })

	lines := strings.Split(string(res.Stdout), "\n")
	if len(lines) != 7 {
		t.Fatal("Wrong number of lines")
	}
	if !strings.HasPrefix(lines[1], "REPOSITORY") {
		t.Fatal("Wrong contents")
	}
	str := "opensuse            latest              1                   Less than a second ago   254.5 MB"
	if lines[2] != str {
		t.Fatal("Wrong contents")
	}
	str = "opensuse            tag                 1                   Less than a second ago   254.5 MB"
	if lines[3] != str {
		t.Fatal("Wrong contents")
	}
	str = "opensuse            13.2                2                   Less than a second ago   254.5 MB"
	if lines[4] != str {
		t.Fatal("Wrong contents")
	}
	if exitInvocations != 1 && lastCode != 0 {
		t.Fatal("Wrong exit code")
	}
}
Example #23
0
func TestImagesListEmpty(t *testing.T) {
	dockerClient = &mockClient{listEmpty: true}
	setupTestExitStatus()

	res := capture.All(func() { imagesCmd(testContext([]string{}, false)) })

	lines := strings.Split(string(res.Stdout), "\n")
	if len(lines) != 3 {
		t.Fatal("Wrong number of lines")
	}
	if !strings.HasPrefix(lines[1], "REPOSITORY") {
		t.Fatal("Wrong contents")
	}
	if exitInvocations != 1 && lastCode != 0 {
		t.Fatal("Wrong exit code")
	}
}
Example #24
0
func TestCheckImageExistsEmptyList(t *testing.T) {
	var found bool
	var err error

	dockerClient = &mockClient{listEmpty: true}

	capture.All(func() {
		found, err = checkImageExists("suse/sles11sp3", "latest")
	})

	if err != nil {
		t.Fatal("Unexpected error")
	}
	if found == true {
		t.Fatal("The image should not have been found")
	}
}
Example #25
0
func TestRunCommandInContainerCommandFailure(t *testing.T) {
	safeClient.client = &mockClient{commandFail: true}

	var err error

	capture.All(func() {
		_, err = runCommandInContainer("busybox", []string{"zypper"}, false)
	})

	if err == nil {
		t.Fatal("It should've failed\n")
	}

	if err.Error() != "Command exited with status 1" {
		t.Fatal("Wrong type of error received")
	}
}
Example #26
0
func TestPatchCheckOk(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)
	capture.All(func() {
		patchCheckCmd(testContext([]string{"opensuse:13.2"}, false))
	})

	if testCommand() != "zypper pchk" {
		t.Fatalf("Wrong command!")
	}
	if len(strings.Split(buffer.String(), "\n")) != 2 {
		t.Fatalf("Something went wrong")
	}
}
Example #27
0
func TestUpdateCommandCannotUpdateCache(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)
	capture.All(func() { updateCmd(testContext([]string{"ori", "new:1.0.0"}, false)) })

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
	if !strings.Contains(buffer.String(), "new:1.0.0 successfully created") {
		t.Fatal("The new image should have been successfully created\n")
	}
	if !strings.Contains(buffer.String(), "This will break the") {
		t.Fatal("We should warn users zypper-docker ps is not going to work\n")
	}
}
Example #28
0
func TestListUpdatesNoImageSpecified(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)
	capture.All(func() { listUpdatesCmd(testContext([]string{}, false)) })

	if testCommand() != "" {
		t.Fatalf("The command should not have been executed")
	}
	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
	if !strings.Contains(buffer.String(), "Error: no image name specified") {
		t.Fatal("It should've logged something\n")
	}
}
Example #29
0
func TestListUpdatesCommandFailure(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{commandFail: true}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)

	capture.All(func() {
		listUpdatesCmd(testContext([]string{"opensuse:13.2"}, false))
	})

	if !strings.Contains(buffer.String(), "Error: Command exited with status 1") {
		t.Fatal("It should've logged something\n")
	}
	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
}
Example #30
0
func TestRunCommandAndCommitToImageSuccess(t *testing.T) {
	safeClient.client = &mockClient{}
	var err error

	capture.All(func() {
		_, err = runCommandAndCommitToImage(
			"source",
			"new_repo",
			"new_tag",
			"touch foo",
			"comment",
			"author")
	})

	if err != nil {
		t.Fatalf("Unexpected error")
	}
}