cryptotest.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var proxyquire = require('proxyquire');
  2. var assert = require("assert");
  3. var Module = require("module");
  4. describe("Crypto API Test", function() {
  5. var crypto_stub = {};
  6. var original = Math.random;
  7. var rng, r;
  8. // Load seedrandom in absence of any crypto package.
  9. it("should be able to seed without crypto", function() {
  10. var noncrypto_sr = proxyquire('../seedrandom', { crypto: null });
  11. rng = noncrypto_sr('hello.');
  12. assert.equal(typeof(rng), 'function', "Should return a function.");
  13. r = rng();
  14. assert.equal(r, 0.9282578795792454, "Should be 'hello.'#1");
  15. assert(original === Math.random, "Should not change Math.random.");
  16. assert(original !== rng, "PRNG should not be Math.random.");
  17. var noncrypto_sr = proxyquire('../seedrandom', { crypto: null });
  18. result = noncrypto_sr();
  19. assert.equal(typeof(result), 'function', "Should return function.");
  20. assert(original === Math.random, "Should not change Math.random.");
  21. r = result();
  22. assert(r != 0.9282578795792454, "Should not be 'hello.'#1");
  23. assert(r != 0.7316977468919549, "Should not be 'hello.'#3");
  24. assert(r != 0.23144008215179881, "Should not be '\\0'#1");
  25. assert(r != 0.7220382488550928, "Should not be '\\1'#1");
  26. // Recache original seedrandom.
  27. proxyquire('../seedrandom', {});
  28. });
  29. // Load seedrandom with zeroed-out crypto package.
  30. it("should be able to seed ('hello.') with zero crypto", function() {
  31. var zerocrypto_sr = proxyquire('../seedrandom', {
  32. crypto: { randomBytes: function(n) {
  33. result = []; while (n-- > 0) { result.push(1); } return result; } }
  34. });
  35. rng = zerocrypto_sr('hello.');
  36. assert.equal(typeof(rng), 'function', "Should return a function.");
  37. r = rng();
  38. assert.equal(r, 0.9282578795792454 , "Should be 'hello.'#1");
  39. assert(original === Math.random, "Should not change Math.random.");
  40. assert(original !== rng, "PRNG should not be Math.random.");
  41. rng = zerocrypto_sr();
  42. assert.equal(typeof(rng), 'function', "Should return function.");
  43. assert(original === Math.random, "Should not change Math.random.");
  44. r = rng();
  45. assert.equal(r, 0.7220382488550928, "Should be '\\1'#1");
  46. r = rng();
  47. assert.equal(r, 0.0259971860493045, "Should be '\\1'#2");
  48. // Recache original seedrandom.
  49. proxyquire('../seedrandom', {});
  50. });
  51. });