Skip to content

Instantly share code, notes, and snippets.

@nathany nathany/git_test.go
Created Apr 21, 2016

Embed
What would you like to do?
Some nifty test helpers inspired by @mitchellh https://www.youtube.com/watch?v=yszygk1cpEc
package main
import (
"os"
"testing"
)
func TestGetSHA(t *testing.T) {
sha, err := getSHA1()
if err != nil {
t.Fatal(err)
}
const hexDigits = 40 // sha1.Size * 2
if len(sha) != hexDigits {
t.Errorf("Expected SHA to be %d hex digits, was %d", hexDigits, len(sha))
}
}
func TestGitNotInPath(t *testing.T) {
defer changeEnv(t, "PATH", ".")()
_, err := getSHA1()
if err == nil || err.Error() != `exec: "git": executable file not found in $PATH` {
t.Fatalf("Expected error %q, got %v.", "executable file not found", err)
}
}
func TestNotGitDirectory(t *testing.T) {
defer changeDir(t, os.TempDir())()
_, err := getSHA1()
if err == nil || err.Error() != "fatal: Not a git repository (or any of the parent directories): .git" {
t.Fatalf("Expected error %q, got %v.", "Not a git repository", err)
}
}
// changeEnv temporarily changes the environment
func changeEnv(t *testing.T, key, value string) func() {
was := os.Getenv(key)
fatalIfError(t, os.Setenv(key, value))
return func() {
fatalIfError(t, os.Setenv(key, was))
}
}
// changeDir temporarily changes the working directory
func changeDir(t *testing.T, dir string) func() {
wd, err := os.Getwd()
fatalIfError(t, err)
fatalIfError(t, os.Chdir(dir))
return func() {
fatalIfError(t, os.Chdir(wd))
}
}
// fail the tests if an unexpected error occurred
func fatalIfError(t *testing.T, err error) {
if err != nil {
t.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.