Skip to content

Instantly share code, notes, and snippets.

@nathany
Created April 21, 2016 19:19
Show Gist options
  • Save nathany/0279c2c3a8d03945ea09042c5b289044 to your computer and use it in GitHub Desktop.
Save nathany/0279c2c3a8d03945ea09042c5b289044 to your computer and use it in GitHub Desktop.
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