summaryrefslogtreecommitdiff
path: root/integrationtests/commons.go
blob: 64229491badafd7335521b38c2bace86f7bfc2f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package integrationtests

import (
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"strings"
	"testing"
)

func runCommand(t *testing.T, cmd string, args []string, stdoutFile string) error {
	if _, err := os.Stat(cmd); err != nil {
		return fmt.Errorf("No such binary %s, please compile first (%v)", cmd, err)
	}

	t.Log("Executing command:", cmd, strings.Join(args, " "))
	bytes, err := exec.Command(cmd, args...).Output()
	if err != nil {
		return err
	}

	t.Log("Writing stdout to file", stdoutFile)
	fd, err := os.Create(stdoutFile)
	if err != nil {
		return err
	}
	fd.Write(bytes)
	fd.Close()

	return nil
}

func compareFiles(t *testing.T, fileA, fileB string) error {
	t.Log("Comparing files", fileA, fileB)
	shaFileA := shaOfFile(t, fileA)
	shaFileB := shaOfFile(t, fileB)

	if shaFileA != shaFileB {
		t.Errorf("Expected SHA %s but got %s", shaFileA, shaFileB)
		if bytes, err := exec.Command("diff", "-u", fileA, fileB).Output(); err != nil {
			return fmt.Errorf(string(bytes))
		}
	}

	return nil
}

func shaOfFile(t *testing.T, file string) string {
	bytes, err := ioutil.ReadFile(file)
	if err != nil {
		t.Error(err)
	}
	hasher := sha256.New()
	hasher.Write(bytes)
	sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
	t.Log("SHA", file, sha)
	return sha
}