luhn_test.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright (C) 2014 Jakob Borg
  2. package luhn_test
  3. import (
  4. "testing"
  5. "github.com/calmh/luhn"
  6. )
  7. func TestGenerate(t *testing.T) {
  8. // Base 6 Luhn
  9. a := luhn.Alphabet("abcdef")
  10. c, err := a.Generate("abcdef")
  11. if err != nil {
  12. t.Fatal(err)
  13. }
  14. if c != 'e' {
  15. t.Errorf("Incorrect check digit %c != e", c)
  16. }
  17. // Base 10 Luhn
  18. a = luhn.Alphabet("0123456789")
  19. c, err = a.Generate("7992739871")
  20. if err != nil {
  21. t.Fatal(err)
  22. }
  23. if c != '3' {
  24. t.Errorf("Incorrect check digit %c != 3", c)
  25. }
  26. }
  27. func TestInvalidString(t *testing.T) {
  28. a := luhn.Alphabet("ABC")
  29. _, err := a.Generate("7992739871")
  30. t.Log(err)
  31. if err == nil {
  32. t.Error("Unexpected nil error")
  33. }
  34. }
  35. func TestBadAlphabet(t *testing.T) {
  36. a := luhn.Alphabet("01234566789")
  37. _, err := a.Generate("7992739871")
  38. t.Log(err)
  39. if err == nil {
  40. t.Error("Unexpected nil error")
  41. }
  42. }
  43. func TestValidate(t *testing.T) {
  44. a := luhn.Alphabet("abcdef")
  45. if !a.Validate("abcdefe") {
  46. t.Errorf("Incorrect validation response for abcdefe")
  47. }
  48. if a.Validate("abcdefd") {
  49. t.Errorf("Incorrect validation response for abcdefd")
  50. }
  51. }