1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
16 actionID = "POST /form"
21 oneMinuteFromNow = now.Add(1 * time.Minute)
24 func TestValidToken(t *testing.T) {
25 tok := generateTokenAtTime(key, userID, actionID, now)
26 if !validTokenAtTime(tok, key, userID, actionID, oneMinuteFromNow) {
27 t.Error("One second later: Expected token to be valid")
29 if !validTokenAtTime(tok, key, userID, actionID, now.Add(Timeout-1*time.Nanosecond)) {
30 t.Error("Just before timeout: Expected token to be valid")
32 if !validTokenAtTime(tok, key, userID, actionID, now.Add(-1*time.Minute+1*time.Millisecond)) {
33 t.Error("One minute in the past: Expected token to be valid")
37 // TestSeparatorReplacement tests that separators are being correctly substituted
38 func TestSeparatorReplacement(t *testing.T) {
39 tok := generateTokenAtTime("foo:bar", "baz", "wah", now)
40 tok2 := generateTokenAtTime("foo", "bar:baz", "wah", now)
42 t.Errorf("Expected generated tokens to be different")
46 func TestInvalidToken(t *testing.T) {
47 invalidTokenTests := []struct {
48 name, key, userID, actionID string
51 {"Bad key", "foobar", userID, actionID, oneMinuteFromNow},
52 {"Bad userID", key, "foobar", actionID, oneMinuteFromNow},
53 {"Bad actionID", key, userID, "foobar", oneMinuteFromNow},
54 {"Expired", key, userID, actionID, now.Add(Timeout + 1*time.Millisecond)},
55 {"More than 1 minute from the future", key, userID, actionID, now.Add(-1*time.Nanosecond - 1*time.Minute)},
58 tok := generateTokenAtTime(key, userID, actionID, now)
59 for _, itt := range invalidTokenTests {
60 if validTokenAtTime(tok, itt.key, itt.userID, itt.actionID, itt.t) {
61 t.Errorf("%v: Expected token to be invalid", itt.name)
66 // TestValidateBadData primarily tests that no unexpected panics are triggered
68 func TestValidateBadData(t *testing.T) {
69 badDataTests := []struct {
72 {"Invalid Base64", "ASDab24(@)$*=="},
73 {"No delimiter", base64.URLEncoding.EncodeToString([]byte("foobar12345678"))},
74 {"Invalid time", base64.URLEncoding.EncodeToString([]byte("foobar:foobar"))},
75 {"Wrong length", "1234" + generateTokenAtTime(key, userID, actionID, now)},
78 for _, bdt := range badDataTests {
79 if validTokenAtTime(bdt.tok, key, userID, actionID, oneMinuteFromNow) {
80 t.Errorf("%v: Expected token to be invalid", bdt.name)