summaryrefslogtreecommitdiff
path: root/app/utilities_test.go
blob: 1865c61ccb9e68273ce5123e35178dda62b1d98b (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// +build all general

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestHttpGet(t *testing.T) {
	answer := "Fake webpage here."
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		fmt.Fprintln(w, answer)
	}))
	defer ts.Close()

	fakeUrl := ts.URL

	resp, content, err := HttpGet(fakeUrl)
	if err != nil {
		t.Fatal("Error getting web page.")
	}
	if resp.StatusCode != 200 {
		t.Fatal("Expecting 200 as status code.")
	}
	if strings.TrimSpace(content) != answer {
		t.Log("We got this: ", content)
		t.Log("We expected this: ", answer)
		t.Fatal("Webpage returned wrong answer.")
	}
}

func TestMd5Hash(t *testing.T) {
	hash := "f9d08276bc85d30d578e8883f3c7e843"
	testHash := Md5Hash("md5hash")

	if hash != testHash {
		t.Fatal("Expected %s as hash. Got %s.", hash, testHash)
	}
}

func TestRandomKey(t *testing.T) {
	m := map[string]bool{}
	var key string
	for i := 0; i < 100; i++ {
		key = RandomKey()
		t.Log(key) // Uncomment to see every generated key.
		if m[key] {
			t.Fatal("Key not random.")
		} else {
			m[key] = true
		}
		if len(key) != 40 {
			t.Fatal("Expected a key with length of 40. Got %s.", key)
		}
	}
}

func TestPassword(t *testing.T) {

	testHash, err := HashPassword("password")
	if err != nil {
		t.Fatal("Hashing password failed.")
	}
	verify := VerifyPassword("password", testHash)
	if !verify {
		t.Fatal("Verifying password failed.")
	}

	testHash, err = HashPassword("")
	if err == nil {
		t.Fatal("Accepting empty password.")
	}
	verify = VerifyPassword("", testHash)
	if verify {
		t.Fatal("Verifying empty password.")
	}
}

func BenchmarkMd5Hash(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Md5Hash("md5hash")
	}
}

func BenchmarkRandomKey(b *testing.B) {
	for i := 0; i < b.N; i++ {
		RandomKey()
	}
}

func BenchmarkHashPassword(b *testing.B) {
	for i := 0; i < b.N; i++ {
		HashPassword("password")
	}
}

func BenchmarkVerifyPassword(b *testing.B) {
	for i := 0; i < b.N; i++ {
		VerifyPassword("password", "$2a$10$OnsbG0Obaz2af3UkoQ9Jaeky3zfRi.0ZHCJC8DlWnbqbpaXEhWqYe")
	}
}