test.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. "use strict";
  2. var test = require("tape");
  3. var truncate = require("./");
  4. var browserTruncate = require("./browser");
  5. function isHighSurrogate(codePoint) {
  6. return codePoint >= 0xd800 && codePoint <= 0xdbff;
  7. }
  8. function repeat(string, times) {
  9. return new Array(times + 1).join(string);
  10. }
  11. function assertLengths(t, string, charLength, byteLength) {
  12. t.equal(string.length, charLength);
  13. t.equal(Buffer.byteLength(string), byteLength);
  14. }
  15. // Test writing files to the fs
  16. //
  17. try {
  18. var blns = require("./vendor/big-list-of-naughty-strings/blns.json");
  19. }
  20. catch (err) {
  21. console.error("Error: Cannot load file './vendor/big-list-of-naughty-strings/blns.json'");
  22. console.error();
  23. console.error("Make sure you've initialized git submodules by running");
  24. console.error();
  25. console.error(" git submodule update --init");
  26. console.error();
  27. process.exit(1);
  28. }
  29. // Run tests against both implementations
  30. [truncate, browserTruncate].forEach(function(truncate) {
  31. test("strings", function(t) {
  32. assertLengths(t, truncate("a☃", 2), 1, 1);
  33. assertLengths(t, truncate(repeat("a", 250) + '\uD800\uDC00', 255), 252, 254);
  34. assertLengths(t, truncate(repeat("a", 251) + '\uD800\uDC00', 255), 253, 255);
  35. assertLengths(t, truncate(repeat("a", 252) + '\uD800\uDC00', 255), 252, 252);
  36. assertLengths(t, truncate(repeat("a", 253) + '\uD800\uDC00', 255), 253, 253);
  37. assertLengths(t, truncate(repeat("a", 254) + '\uD800\uDC00', 255), 254, 254);
  38. assertLengths(t, truncate(repeat("a", 255) + '\uD800\uDC00', 255), 255, 255);
  39. t.end();
  40. });
  41. // Truncate various strings
  42. [].concat(
  43. [
  44. repeat("a", 300),
  45. repeat("a", 252) + '\uD800\uDC00',
  46. repeat("a", 251) + '\uD800\uDC00',
  47. repeat("a", 253) + '\uD800\uDC00',
  48. ],
  49. blns
  50. ).forEach(function(str) {
  51. test(JSON.stringify(str), function(t) {
  52. var i = 0;
  53. t.equals(truncate(str, 0), "");
  54. // Truncate string one byte at a time
  55. while (true) {
  56. var truncated = truncate(str, i);
  57. t.ok(Buffer.byteLength(truncated) <= i);
  58. t.ok( ! isHighSurrogate(truncated[truncated.length - 1]));
  59. if (truncated === str) {
  60. break;
  61. }
  62. i += 1;
  63. }
  64. t.end();
  65. });
  66. });
  67. });