luhn_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. package luhn_test
  5. import (
  6. "testing"
  7. "github.com/syncthing/syncthing/internal/luhn"
  8. )
  9. func TestGenerate(t *testing.T) {
  10. // Base 6 Luhn
  11. a := luhn.Alphabet("abcdef")
  12. c, err := a.Generate("abcdef")
  13. if err != nil {
  14. t.Fatal(err)
  15. }
  16. if c != 'e' {
  17. t.Errorf("Incorrect check digit %c != e", c)
  18. }
  19. // Base 10 Luhn
  20. a = luhn.Alphabet("0123456789")
  21. c, err = a.Generate("7992739871")
  22. if err != nil {
  23. t.Fatal(err)
  24. }
  25. if c != '3' {
  26. t.Errorf("Incorrect check digit %c != 3", c)
  27. }
  28. }
  29. func TestInvalidString(t *testing.T) {
  30. a := luhn.Alphabet("ABC")
  31. _, err := a.Generate("7992739871")
  32. t.Log(err)
  33. if err == nil {
  34. t.Error("Unexpected nil error")
  35. }
  36. }
  37. func TestBadAlphabet(t *testing.T) {
  38. a := luhn.Alphabet("01234566789")
  39. _, err := a.Generate("7992739871")
  40. t.Log(err)
  41. if err == nil {
  42. t.Error("Unexpected nil error")
  43. }
  44. }
  45. func TestValidate(t *testing.T) {
  46. a := luhn.Alphabet("abcdef")
  47. if !a.Validate("abcdefe") {
  48. t.Errorf("Incorrect validation response for abcdefe")
  49. }
  50. if a.Validate("abcdefd") {
  51. t.Errorf("Incorrect validation response for abcdefd")
  52. }
  53. }