test.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. if (!this.uuid) {
  2. // node.js
  3. uuid = require('../uuid');
  4. }
  5. //
  6. // x-platform log/assert shims
  7. //
  8. function _log(msg, type) {
  9. type = type || 'log';
  10. if (typeof(document) != 'undefined') {
  11. document.write('<div class="' + type + '">' + msg.replace(/\n/g, '<br />') + '</div>');
  12. }
  13. if (typeof(console) != 'undefined') {
  14. var color = {
  15. log: '\033[39m',
  16. warn: '\033[33m',
  17. error: '\033[31m'
  18. };
  19. console[type](color[type] + msg + color.log);
  20. }
  21. }
  22. function log(msg) {_log(msg, 'log');}
  23. function warn(msg) {_log(msg, 'warn');}
  24. function error(msg) {_log(msg, 'error');}
  25. function assert(res, msg) {
  26. if (!res) {
  27. error('FAIL: ' + msg);
  28. } else {
  29. log('Pass: ' + msg);
  30. }
  31. }
  32. //
  33. // Unit tests
  34. //
  35. // Verify ordering of v1 ids created with explicit times
  36. var TIME = 1321644961388; // 2011-11-18 11:36:01.388-08:00
  37. function compare(name, ids) {
  38. ids = ids.map(function(id) {
  39. return id.split('-').reverse().join('-');
  40. }).sort();
  41. var sorted = ([].concat(ids)).sort();
  42. assert(sorted.toString() == ids.toString(), name + ' have expected order');
  43. }
  44. // Verify ordering of v1 ids created using default behavior
  45. compare('uuids with current time', [
  46. uuid.v1(),
  47. uuid.v1(),
  48. uuid.v1(),
  49. uuid.v1(),
  50. uuid.v1()
  51. ]);
  52. // Verify ordering of v1 ids created with explicit times
  53. compare('uuids with time option', [
  54. uuid.v1({msecs: TIME - 10*3600*1000}),
  55. uuid.v1({msecs: TIME - 1}),
  56. uuid.v1({msecs: TIME}),
  57. uuid.v1({msecs: TIME + 1}),
  58. uuid.v1({msecs: TIME + 28*24*3600*1000})
  59. ]);
  60. assert(
  61. uuid.v1({msecs: TIME}) != uuid.v1({msecs: TIME}),
  62. 'IDs created at same msec are different'
  63. );
  64. // Verify throw if too many ids created
  65. var thrown = false;
  66. try {
  67. uuid.v1({msecs: TIME, nsecs: 10000});
  68. } catch (e) {
  69. thrown = true;
  70. }
  71. assert(thrown, 'Exception thrown when > 10K ids created in 1 ms');
  72. // Verify clock regression bumps clockseq
  73. var uidt = uuid.v1({msecs: TIME});
  74. var uidtb = uuid.v1({msecs: TIME - 1});
  75. assert(
  76. parseInt(uidtb.split('-')[3], 16) - parseInt(uidt.split('-')[3], 16) === 1,
  77. 'Clock regression by msec increments the clockseq'
  78. );
  79. // Verify clock regression bumps clockseq
  80. var uidtn = uuid.v1({msecs: TIME, nsecs: 10});
  81. var uidtnb = uuid.v1({msecs: TIME, nsecs: 9});
  82. assert(
  83. parseInt(uidtnb.split('-')[3], 16) - parseInt(uidtn.split('-')[3], 16) === 1,
  84. 'Clock regression by nsec increments the clockseq'
  85. );
  86. // Verify explicit options produce expected id
  87. var id = uuid.v1({
  88. msecs: 1321651533573,
  89. nsecs: 5432,
  90. clockseq: 0x385c,
  91. node: [ 0x61, 0xcd, 0x3c, 0xbb, 0x32, 0x10 ]
  92. });
  93. assert(id == 'd9428888-122b-11e1-b85c-61cd3cbb3210', 'Explicit options produce expected id');
  94. // Verify adjacent ids across a msec boundary are 1 time unit apart
  95. var u0 = uuid.v1({msecs: TIME, nsecs: 9999});
  96. var u1 = uuid.v1({msecs: TIME + 1, nsecs: 0});
  97. var before = u0.split('-')[0], after = u1.split('-')[0];
  98. var dt = parseInt(after, 16) - parseInt(before, 16);
  99. assert(dt === 1, 'Ids spanning 1ms boundary are 100ns apart');
  100. //
  101. // Test parse/unparse
  102. //
  103. id = '00112233445566778899aabbccddeeff';
  104. assert(uuid.unparse(uuid.parse(id.substr(0,10))) ==
  105. '00112233-4400-0000-0000-000000000000', 'Short parse');
  106. assert(uuid.unparse(uuid.parse('(this is the uuid -> ' + id + id)) ==
  107. '00112233-4455-6677-8899-aabbccddeeff', 'Dirty parse');
  108. //
  109. // Perf tests
  110. //
  111. var generators = {
  112. v1: uuid.v1,
  113. v4: uuid.v4
  114. };
  115. var UUID_FORMAT = {
  116. v1: /[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i,
  117. v4: /[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i
  118. };
  119. var N = 1e4;
  120. // Get %'age an actual value differs from the ideal value
  121. function divergence(actual, ideal) {
  122. return Math.round(100*100*(actual - ideal)/ideal)/100;
  123. }
  124. function rate(msg, t) {
  125. log(msg + ': ' + (N / (Date.now() - t) * 1e3 | 0) + ' uuids\/second');
  126. }
  127. for (var version in generators) {
  128. var counts = {}, max = 0;
  129. var generator = generators[version];
  130. var format = UUID_FORMAT[version];
  131. log('\nSanity check ' + N + ' ' + version + ' uuids');
  132. for (var i = 0, ok = 0; i < N; i++) {
  133. id = generator();
  134. if (!format.test(id)) {
  135. throw Error(id + ' is not a valid UUID string');
  136. }
  137. if (id != uuid.unparse(uuid.parse(id))) {
  138. assert(fail, id + ' is not a valid id');
  139. }
  140. // Count digits for our randomness check
  141. if (version == 'v4') {
  142. var digits = id.replace(/-/g, '').split('');
  143. for (var j = digits.length-1; j >= 0; j--) {
  144. var c = digits[j];
  145. max = Math.max(max, counts[c] = (counts[c] || 0) + 1);
  146. }
  147. }
  148. }
  149. // Check randomness for v4 UUIDs
  150. if (version == 'v4') {
  151. // Limit that we get worried about randomness. (Purely empirical choice, this!)
  152. var limit = 2*100*Math.sqrt(1/N);
  153. log('\nChecking v4 randomness. Distribution of Hex Digits (% deviation from ideal)');
  154. for (var i = 0; i < 16; i++) {
  155. var c = i.toString(16);
  156. var bar = '', n = counts[c], p = Math.round(n/max*100|0);
  157. // 1-3,5-8, and D-F: 1:16 odds over 30 digits
  158. var ideal = N*30/16;
  159. if (i == 4) {
  160. // 4: 1:1 odds on 1 digit, plus 1:16 odds on 30 digits
  161. ideal = N*(1 + 30/16);
  162. } else if (i >= 8 && i <= 11) {
  163. // 8-B: 1:4 odds on 1 digit, plus 1:16 odds on 30 digits
  164. ideal = N*(1/4 + 30/16);
  165. } else {
  166. // Otherwise: 1:16 odds on 30 digits
  167. ideal = N*30/16;
  168. }
  169. var d = divergence(n, ideal);
  170. // Draw bar using UTF squares (just for grins)
  171. var s = n/max*50 | 0;
  172. while (s--) bar += '=';
  173. assert(Math.abs(d) < limit, c + ' |' + bar + '| ' + counts[c] + ' (' + d + '% < ' + limit + '%)');
  174. }
  175. }
  176. }
  177. // Perf tests
  178. for (var version in generators) {
  179. log('\nPerformance testing ' + version + ' UUIDs');
  180. var generator = generators[version];
  181. var buf = new uuid.BufferClass(16);
  182. for (var i = 0, t = Date.now(); i < N; i++) generator();
  183. rate('uuid.' + version + '()', t);
  184. for (var i = 0, t = Date.now(); i < N; i++) generator('binary');
  185. rate('uuid.' + version + '(\'binary\')', t);
  186. for (var i = 0, t = Date.now(); i < N; i++) generator('binary', buf);
  187. rate('uuid.' + version + '(\'binary\', buffer)', t);
  188. }