Skip to content

Commit

Permalink
add tests and simplify sha1 generation
Browse files Browse the repository at this point in the history
  • Loading branch information
amalfra committed Aug 6, 2017
1 parent d0112f2 commit 3c1c724
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 6 deletions.
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,7 @@ fmt:
vet:
go vet ./...

build: fmt vet
test:
go test -v

build: fmt vet test
6 changes: 1 addition & 5 deletions etag.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,11 @@ package etag

import (
"crypto/sha1"
"encoding/hex"
"fmt"
)

func getHash(str string) string {
h := sha1.New()
h.Write([]byte(str))

return hex.EncodeToString(h.Sum(nil))
return fmt.Sprintf("%x", sha1.Sum([]byte(str)))
}

// Generate an Etag for given sring. Allows specifying whether to generate weak
Expand Down
38 changes: 38 additions & 0 deletions etag_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package etag

import (
"fmt"
"testing"
)

func TestNotWeekEtag(t *testing.T) {
inputStr := `<html>
<head>
<title>test page</title>
</head>
<body>
<p>test page html</p>
</body>
</html>`
expectedOut := fmt.Sprintf("%d-%s", len(inputStr), getHash(inputStr))
generatedOut := Generate(inputStr, false)
if generatedOut != expectedOut {
t.Fatalf("Incorrect Etag generated")
}
}

func TestWeekEtag(t *testing.T) {
inputStr := `<html>
<head>
<title>test page</title>
</head>
<body>
<p>test page html</p>
</body>
</html>`
expectedOut := fmt.Sprintf("W/%d-%s", len(inputStr), getHash(inputStr))
generatedOut := Generate(inputStr, true)
if generatedOut != expectedOut {
t.Fatalf("Incorrect Etag generated")
}
}

0 comments on commit 3c1c724

Please sign in to comment.