test.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. var assert = require('assert');
  2. var Base62 = require('../base62');
  3. describe("encode", function() {
  4. it("should encode a number to a Base62 string", function() {
  5. assert.equal(Base62.encode(0), '0');
  6. assert.equal(Base62.encode(999), 'g7');
  7. assert.equal(Base62.encode(65), '13');
  8. //test big numbers
  9. assert.equal(Base62.encode(10000000000001), "2Q3rKTOF");
  10. assert.equal(Base62.encode(10000000000002), "2Q3rKTOG");
  11. });
  12. });
  13. describe("decode", function() {
  14. it("should decode a number from a Base62 string", function() {
  15. assert.equal(Base62.decode('0'), 0);
  16. assert.equal(Base62.decode('g7'), 999);
  17. assert.equal(Base62.decode('13'), 65);
  18. //zero padded strings
  19. assert.equal(Base62.decode('0013'), 65);
  20. //test big numbers
  21. assert.equal(Base62.decode("2Q3rKTOF"), 10000000000001);
  22. assert.equal(Base62.decode("2Q3rKTOH"), 10000000000003);
  23. });
  24. });
  25. describe("setCharacterSequence", function(){
  26. it("should update the character sequence", function(){
  27. Base62.setCharacterSet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  28. //Test default character set is not intact
  29. assert.notEqual(Base62.encode(999), 'g7');
  30. //Test new character set test cases
  31. var testCases = {
  32. "G7": 999,
  33. "Lxf7": 5234233,
  34. "qx": 3283,
  35. "29": 133,
  36. "1S": 90,
  37. "3k": 232,
  38. "4I": 266,
  39. "2X": 157,
  40. "1E": 76,
  41. "1L": 83
  42. };
  43. Object.keys(testCases).forEach(function(base62String){
  44. assert.equal(Base62.encode(testCases[base62String]), base62String);
  45. assert.equal(Base62.decode(base62String), testCases[base62String]);
  46. });
  47. });
  48. it("should throw exceptions on invalid strings", function(){
  49. var errorCheck = function(err) {
  50. if ( (err instanceof Error) && /value/.test(err) ) {
  51. return true;
  52. }
  53. };
  54. assert.throws(function(){
  55. Base62.setCharacterSet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy");
  56. }, /You must supply 62 characters/);
  57. assert.throws(function(){
  58. Base62.setCharacterSet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz;");
  59. }, /You must supply 62 characters/);
  60. assert.throws(function(){
  61. Base62.setCharacterSet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxzz");
  62. }, /You must use unique characters/);
  63. });
  64. });