luhn_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package luhn_test
  16. import (
  17. "testing"
  18. "github.com/syncthing/syncthing/internal/luhn"
  19. )
  20. func TestGenerate(t *testing.T) {
  21. // Base 6 Luhn
  22. a := luhn.Alphabet("abcdef")
  23. c, err := a.Generate("abcdef")
  24. if err != nil {
  25. t.Fatal(err)
  26. }
  27. if c != 'e' {
  28. t.Errorf("Incorrect check digit %c != e", c)
  29. }
  30. // Base 10 Luhn
  31. a = luhn.Alphabet("0123456789")
  32. c, err = a.Generate("7992739871")
  33. if err != nil {
  34. t.Fatal(err)
  35. }
  36. if c != '3' {
  37. t.Errorf("Incorrect check digit %c != 3", c)
  38. }
  39. }
  40. func TestInvalidString(t *testing.T) {
  41. a := luhn.Alphabet("ABC")
  42. _, err := a.Generate("7992739871")
  43. t.Log(err)
  44. if err == nil {
  45. t.Error("Unexpected nil error")
  46. }
  47. }
  48. func TestBadAlphabet(t *testing.T) {
  49. a := luhn.Alphabet("01234566789")
  50. _, err := a.Generate("7992739871")
  51. t.Log(err)
  52. if err == nil {
  53. t.Error("Unexpected nil error")
  54. }
  55. }
  56. func TestValidate(t *testing.T) {
  57. a := luhn.Alphabet("abcdef")
  58. if !a.Validate("abcdefe") {
  59. t.Errorf("Incorrect validation response for abcdefe")
  60. }
  61. if a.Validate("abcdefd") {
  62. t.Errorf("Incorrect validation response for abcdefd")
  63. }
  64. }