sha1.test.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { expect } from 'chai'
  2. import { generateSHA1Hash } from '../../../../frontend/js/shared/utils/sha1'
  3. import crypto from 'node:crypto'
  4. function generateSHA1HashNode(content) {
  5. return crypto.createHash('sha1').update(content, 'utf8').digest('hex')
  6. }
  7. function generateRandomUnicodeString(length) {
  8. let result = ''
  9. for (let i = 0; i < length; i++) {
  10. const range = [0x0000, 0x10ffff]
  11. const codePoint =
  12. Math.floor(Math.random() * (range[1] - range[0] + 1)) + range[0]
  13. result += String.fromCharCode(codePoint)
  14. }
  15. return result
  16. }
  17. function generateMultipleRandomStrings(numStrings, maxLength) {
  18. const randomStrings = []
  19. for (let i = 0; i < numStrings; i++) {
  20. const length = Math.floor(Math.random() * maxLength)
  21. randomStrings.push(generateRandomUnicodeString(length))
  22. }
  23. return [...new Set(randomStrings)]
  24. }
  25. describe('sha1', function () {
  26. describe('generateSHA1Hash', function () {
  27. const randomStrings = generateMultipleRandomStrings(100, 1000)
  28. it('verify 100 random strings', function () {
  29. for (const str of randomStrings) {
  30. expect(generateSHA1Hash(str)).to.equal(generateSHA1HashNode(str))
  31. }
  32. })
  33. it('sample string 1', function () {
  34. expect(generateSHA1Hash('sample string 1')).to.equal(
  35. '135028161629af5901ea2f15554730dc0de38a01'
  36. )
  37. })
  38. it('sample string 2', function () {
  39. expect(generateSHA1Hash('sample string 2')).to.equal(
  40. 'db9460374e49a7c737b609c2fb37302381f345d6'
  41. )
  42. })
  43. it('abc', function () {
  44. expect(generateSHA1Hash('abc')).to.equal(
  45. 'a9993e364706816aba3e25717850c26c9cd0d89d'
  46. )
  47. })
  48. it('generates a sha1 for an empty string', function () {
  49. expect(generateSHA1Hash('')).to.equal(
  50. 'da39a3ee5e6b4b0d3255bfef95601890afd80709'
  51. )
  52. })
  53. it('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', function () {
  54. expect(
  55. generateSHA1Hash(
  56. 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'
  57. )
  58. ).to.equal('84983e441c3bd26ebaae4aa1f95129e5e54670f1')
  59. })
  60. it('abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', function () {
  61. expect(
  62. generateSHA1Hash(
  63. 'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu'
  64. )
  65. ).to.equal('a49b2446a02c645bf419f995b67091253a04a259')
  66. })
  67. })
  68. })