forked from shoenig/bcrypt-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
98 lines (83 loc) · 2.32 KB
/
Copy pathmain_test.go
File metadata and controls
98 lines (83 loc) · 2.32 KB
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
package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
var binaryPath string
func TestMain(m *testing.M) {
dir, err := os.MkdirTemp("", "bcrypt-tool-test")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
binaryPath = filepath.Join(dir, "bcrypt-tool")
cmd := exec.Command("go", "build", "-o", binaryPath)
if out, err := cmd.CombinedOutput(); err != nil {
panic("failed to build binary: " + string(out))
}
os.Exit(m.Run())
}
func runTool(t *testing.T, args ...string) (string, int) {
t.Helper()
cmd := exec.Command(binaryPath, args...)
out, err := cmd.CombinedOutput()
exitCode := 0
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode = exitErr.ExitCode()
} else {
t.Fatalf("unexpected error running bcrypt-tool: %v", err)
}
}
return strings.TrimSpace(string(out)), exitCode
}
func TestHashAndMatch(t *testing.T) {
password := "testpassword123"
hash, code := runTool(t, "hash", password)
if code != 0 {
t.Fatalf("expected exit code 0, got %d", code)
}
if !strings.HasPrefix(hash, "$2a$") {
t.Fatalf("expected hash to start with $2a$, got %q", hash)
}
// Verify the generated hash matches the original password
out, code := runTool(t, "match", password, hash)
if code != 0 || out != "yes" {
t.Fatalf("expected match to return 'yes' (exit 0), got %q (exit %d)", out, code)
}
// Verify a wrong password does not match
out, code = runTool(t, "match", "wrongpassword", hash)
if code != 1 || out != "no" {
t.Fatalf("expected mismatch to return 'no' (exit 1), got %q (exit %d)", out, code)
}
}
func TestHashWithCost(t *testing.T) {
password := "costtest"
costVal := "4"
hash, code := runTool(t, "hash", password, costVal)
if code != 0 {
t.Fatalf("expected exit code 0, got %d", code)
}
// Verify cost is reported correctly
out, code := runTool(t, "cost", hash)
if code != 0 {
t.Fatalf("expected exit code 0, got %d", code)
}
if out != costVal {
t.Fatalf("expected cost %q, got %q", costVal, out)
}
// Verify the hash still matches
out, code = runTool(t, "match", password, hash)
if code != 0 || out != "yes" {
t.Fatalf("expected match to return 'yes' (exit 0), got %q (exit %d)", out, code)
}
}
func TestNoArgs(t *testing.T) {
_, code := runTool(t, "hash")
if code != 2 {
t.Fatalf("expected exit code 2 for missing args, got %d", code)
}
}