snapshot.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import _extends from "@babel/runtime/helpers/extends";
  2. import _defineProperty from "@babel/runtime/helpers/defineProperty";
  3. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
  4. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
  5. /**
  6. * This file contains helper methods to create expected snapshot structures
  7. * of both instance and ES6 exports.
  8. *
  9. * The files are located here and not under /test or /tools so it's transpiled
  10. * into ES5 code under /lib and can be used straight by node.js
  11. */
  12. import assert from 'assert';
  13. import * as allIsFunctions from './is.js';
  14. import { create } from '../core/create.js';
  15. import { endsWith } from './string.js';
  16. export var validateTypeOf = allIsFunctions.typeOf;
  17. export function validateBundle(expectedBundleStructure, bundle) {
  18. var originalWarn = console.warn;
  19. console.warn = function () {
  20. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  21. args[_key] = arguments[_key];
  22. }
  23. if (args.join(' ').indexOf('is moved to') !== -1 && args.join(' ').indexOf('Please use the new location instead') !== -1) {
  24. // Ignore warnings like:
  25. // Warning: math.type.isNumber is moved to math.isNumber in v6.0.0. Please use the new location instead.
  26. return;
  27. }
  28. originalWarn.apply(console, args);
  29. };
  30. try {
  31. var issues = [];
  32. // see whether all expected functions and objects are there
  33. traverse(expectedBundleStructure, (expectedType, path) => {
  34. var actualValue = get(bundle, path);
  35. var actualType = validateTypeOf(actualValue);
  36. var message = actualType === 'undefined' ? 'Missing entry in bundle. ' + "Path: ".concat(JSON.stringify(path), ", expected type: ").concat(expectedType, ", actual type: ").concat(actualType) : 'Unexpected entry type in bundle. ' + "Path: ".concat(JSON.stringify(path), ", expected type: ").concat(expectedType, ", actual type: ").concat(actualType);
  37. if (actualType !== expectedType) {
  38. issues.push({
  39. actualType,
  40. expectedType,
  41. message
  42. });
  43. console.warn(message);
  44. }
  45. });
  46. // see whether there are any functions or objects that shouldn't be there
  47. traverse(bundle, (actualValue, path) => {
  48. var actualType = validateTypeOf(actualValue);
  49. var expectedType = get(expectedBundleStructure, path) || 'undefined';
  50. // FIXME: ugly to have these special cases
  51. if (path.join('.').indexOf('docs.') !== -1) {
  52. // ignore the contents of docs
  53. return;
  54. }
  55. if (path.join('.').indexOf('all.') !== -1) {
  56. // ignore the contents of all dependencies
  57. return;
  58. }
  59. var message = expectedType === 'undefined' ? 'Unknown entry in bundle. ' + 'Is there a new function added which is missing in this snapshot test? ' + "Path: ".concat(JSON.stringify(path), ", expected type: ").concat(expectedType, ", actual type: ").concat(actualType) : 'Unexpected entry type in bundle. ' + "Path: ".concat(JSON.stringify(path), ", expected type: ").concat(expectedType, ", actual type: ").concat(actualType);
  60. if (actualType !== expectedType) {
  61. issues.push({
  62. actualType,
  63. expectedType,
  64. message
  65. });
  66. console.warn(message);
  67. }
  68. });
  69. // assert on the first issue (if any)
  70. if (issues.length > 0) {
  71. var {
  72. actualType,
  73. expectedType,
  74. message
  75. } = issues[0];
  76. console.warn("".concat(issues.length, " bundle issues found"));
  77. assert.strictEqual(actualType, expectedType, message);
  78. }
  79. } finally {
  80. console.warn = originalWarn;
  81. }
  82. }
  83. /**
  84. * Based on an object with factory functions, create the expected
  85. * structures for ES6 export and a mathjs instance.
  86. * @param {Object} factories
  87. * @return {{expectedInstanceStructure: Object, expectedES6Structure: Object}}
  88. */
  89. export function createSnapshotFromFactories(factories) {
  90. var math = create(factories);
  91. var allFactoryFunctions = {};
  92. var allFunctionsConstantsClasses = {};
  93. var allFunctionsConstants = {};
  94. var allTransformFunctions = {};
  95. var allDependencyCollections = {};
  96. var allClasses = {};
  97. var allNodeClasses = {};
  98. Object.keys(factories).forEach(factoryName => {
  99. var factory = factories[factoryName];
  100. var name = factory.fn;
  101. var isTransformFunction = factory.meta && factory.meta.isTransformFunction;
  102. var isClass = !isLowerCase(name[0]) && validateTypeOf(math[name]) === 'function';
  103. var dependenciesName = factory.fn + (isTransformFunction ? 'Transform' : '') + 'Dependencies';
  104. allFactoryFunctions[factoryName] = 'function';
  105. allFunctionsConstantsClasses[name] = validateTypeOf(math[name]);
  106. allDependencyCollections[dependenciesName] = 'Object';
  107. if (isTransformFunction) {
  108. allTransformFunctions[name] = 'function';
  109. }
  110. if (isClass) {
  111. if (endsWith(name, 'Node')) {
  112. allNodeClasses[name] = 'function';
  113. } else {
  114. allClasses[name] = 'function';
  115. }
  116. } else {
  117. allFunctionsConstants[name] = validateTypeOf(math[name]);
  118. }
  119. });
  120. var embeddedDocs = {};
  121. Object.keys(factories).forEach(factoryName => {
  122. var factory = factories[factoryName];
  123. var name = factory.fn;
  124. if (isLowerCase(factory.fn[0])) {
  125. // ignore class names starting with upper case
  126. embeddedDocs[name] = 'Object';
  127. }
  128. });
  129. embeddedDocs = exclude(embeddedDocs, ['equalScalar', 'apply', 'addScalar', 'multiplyScalar', 'print', 'divideScalar', 'parse', 'compile', 'parser', 'chain', 'reviver', 'replacer']);
  130. var allTypeChecks = {};
  131. Object.keys(allIsFunctions).forEach(name => {
  132. if (name.indexOf('is') === 0) {
  133. allTypeChecks[name] = 'function';
  134. }
  135. });
  136. var allErrorClasses = {
  137. ArgumentsError: 'function',
  138. DimensionError: 'function',
  139. IndexError: 'function'
  140. };
  141. var expectedInstanceStructure = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, allFunctionsConstantsClasses), {}, {
  142. on: 'function',
  143. off: 'function',
  144. once: 'function',
  145. emit: 'function',
  146. import: 'function',
  147. config: 'function',
  148. create: 'function',
  149. factory: 'function'
  150. }, allTypeChecks), allErrorClasses), {}, {
  151. expression: {
  152. transform: _objectSpread({}, allTransformFunctions),
  153. mathWithTransform: _objectSpread(_objectSpread({}, exclude(allFunctionsConstants, ['chain'])), {}, {
  154. config: 'function'
  155. })
  156. }
  157. });
  158. var expectedES6Structure = _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({}, exclude(allFunctionsConstantsClasses, ['E', 'false', 'Infinity', 'NaN', 'null', 'PI', 'true'])), {}, {
  159. create: 'function',
  160. config: 'function',
  161. factory: 'function',
  162. _true: 'boolean',
  163. _false: 'boolean',
  164. _null: 'null',
  165. _Infinity: 'number',
  166. _NaN: 'number'
  167. }, allTypeChecks), allErrorClasses), allDependencyCollections), allFactoryFunctions), {}, {
  168. docs: embeddedDocs
  169. });
  170. return {
  171. expectedInstanceStructure,
  172. expectedES6Structure
  173. };
  174. }
  175. function traverse(obj) {
  176. var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (value, path) => {};
  177. var path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  178. // FIXME: ugly to have these special cases
  179. if (path.length > 0 && path[0].indexOf('Dependencies') !== -1) {
  180. // special case for objects holding a collection of dependencies
  181. callback(obj, path);
  182. } else if (validateTypeOf(obj) === 'Array') {
  183. obj.map((item, index) => traverse(item, callback, path.concat(index)));
  184. } else if (validateTypeOf(obj) === 'Object') {
  185. Object.keys(obj).forEach(key => {
  186. // FIXME: ugly to have these special cases
  187. // ignore special case of deprecated docs
  188. if (key === 'docs' && path.join('.') === 'expression') {
  189. return;
  190. }
  191. traverse(obj[key], callback, path.concat(key));
  192. });
  193. } else {
  194. callback(obj, path);
  195. }
  196. }
  197. function get(object, path) {
  198. var child = object;
  199. for (var i = 0; i < path.length; i++) {
  200. var key = path[i];
  201. child = child ? child[key] : undefined;
  202. }
  203. return child;
  204. }
  205. /**
  206. * Create a copy of the provided `object` and delete
  207. * all properties listed in `excludedProperties`
  208. * @param {Object} object
  209. * @param {string[]} excludedProperties
  210. * @return {Object}
  211. */
  212. function exclude(object, excludedProperties) {
  213. var strippedObject = _extends({}, object);
  214. excludedProperties.forEach(excludedProperty => {
  215. delete strippedObject[excludedProperty];
  216. });
  217. return strippedObject;
  218. }
  219. function isLowerCase(text) {
  220. return typeof text === 'string' && text.toLowerCase() === text;
  221. }