assert.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // Licensed to the Software Freedom Conservancy (SFC) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The SFC licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. /**
  18. * @fileoverview Defines a library that simplifies writing assertions against
  19. * promised values.
  20. *
  21. * > <hr>
  22. * > __NOTE:__ This module is considered experimental and is subject to
  23. * > change, or removal, at any time!
  24. * > <hr>
  25. *
  26. * Sample usage:
  27. *
  28. * var driver = new webdriver.Builder().build();
  29. * driver.get('http://www.google.com');
  30. *
  31. * assert(driver.getTitle()).equalTo('Google');
  32. */
  33. 'use strict';
  34. const assert = require('assert');
  35. function trueType(v) {
  36. if (v === null) {
  37. return 'null';
  38. }
  39. let type = typeof v;
  40. if (type === 'object') {
  41. if (Array.isArray(v)) {
  42. type = 'array';
  43. }
  44. }
  45. return type;
  46. }
  47. function checkType(v, want) {
  48. let got = trueType(v);
  49. if (got !== want) {
  50. throw new TypeError('require ' + want + ', but got ' + got);
  51. }
  52. return v;
  53. }
  54. const checkNumber = v => checkType(v, 'number');
  55. const checkFunction = v => checkType(v, 'function');
  56. const checkString = v => checkType(v, 'string');
  57. const isFunction = v => trueType(v) === 'function';
  58. const isNumber = v => trueType(v) === 'number';
  59. const isObject = v => trueType(v) === 'object';
  60. const isString = v => trueType(v) === 'string';
  61. function describe(value) {
  62. let ret;
  63. try {
  64. ret = `<${String(value)}>`;
  65. } catch (e) {
  66. ret = `<toString failed: ${e.message}>`;
  67. }
  68. if (null !== value && void(0) !== value) {
  69. ret += ` (${trueType(value)})`;
  70. }
  71. return ret;
  72. }
  73. function evaluate(value, predicate) {
  74. if (isObject(value) && isFunction(value.then)) {
  75. return value.then(predicate);
  76. }
  77. predicate(value);
  78. }
  79. /**
  80. * @private
  81. */
  82. class Assertion {
  83. /**
  84. * @param {?} subject The subject of this assertion.
  85. * @param {boolean=} opt_invert Whether to invert any assertions performed by
  86. * this instance.
  87. */
  88. constructor(subject, opt_invert) {
  89. /** @private {?} */
  90. this.subject_ = subject;
  91. /** @private {boolean} */
  92. this.invert_ = !!opt_invert;
  93. }
  94. /**
  95. * @param {number} expected The minimum permissible value (inclusive).
  96. * @param {string=} opt_message An optional failure message.
  97. * @return {(Promise|undefined)} The result of this assertion, if the subject
  98. * is a promised-value. Otherwise, the assertion is performed immediately
  99. * and nothing is returned.
  100. */
  101. atLeast(expected, opt_message) {
  102. checkNumber(expected);
  103. return evaluate(this.subject_, function(actual) {
  104. if (!isNumber(actual) || actual < expected) {
  105. assert.fail(actual, expected, opt_message, '>=');
  106. }
  107. });
  108. }
  109. /**
  110. * @param {number} expected The maximum permissible value (inclusive).
  111. * @param {string=} opt_message An optional failure message.
  112. * @return {(Promise|undefined)} The result of this assertion, if the subject
  113. * is a promised-value. Otherwise, the assertion is performed immediately
  114. * and nothing is returned.
  115. */
  116. atMost(expected, opt_message) {
  117. checkNumber(expected);
  118. return evaluate(this.subject_, function (actual) {
  119. if (!isNumber(actual) || actual > expected) {
  120. assert.fail(actual, expected, opt_message, '<=');
  121. }
  122. });
  123. }
  124. /**
  125. * @param {number} expected The maximum permissible value (exclusive).
  126. * @param {string=} opt_message An optional failure message.
  127. * @return {(Promise|undefined)} The result of this assertion, if the subject
  128. * is a promised-value. Otherwise, the assertion is performed immediately
  129. * and nothing is returned.
  130. */
  131. greaterThan(expected, opt_message) {
  132. checkNumber(expected);
  133. return evaluate(this.subject_, function(actual) {
  134. if (!isNumber(actual) || actual <= expected) {
  135. assert.fail(actual, expected, opt_message, '>');
  136. }
  137. });
  138. }
  139. /**
  140. * @param {number} expected The minimum permissible value (exclusive).
  141. * @param {string=} opt_message An optional failure message.
  142. * @return {(Promise|undefined)} The result of this assertion, if the subject
  143. * is a promised-value. Otherwise, the assertion is performed immediately
  144. * and nothing is returned.
  145. */
  146. lessThan(expected, opt_message) {
  147. checkNumber(expected);
  148. return evaluate(this.subject_, function (actual) {
  149. if (!isNumber(actual) || actual >= expected) {
  150. assert.fail(actual, expected, opt_message, '<');
  151. }
  152. });
  153. }
  154. /**
  155. * @param {number} expected The desired value.
  156. * @param {number} epsilon The maximum distance from the desired value.
  157. * @param {string=} opt_message An optional failure message.
  158. * @return {(Promise|undefined)} The result of this assertion, if the subject
  159. * is a promised-value. Otherwise, the assertion is performed immediately
  160. * and nothing is returned.
  161. */
  162. closeTo(expected, epsilon, opt_message) {
  163. checkNumber(expected);
  164. checkNumber(epsilon);
  165. return evaluate(this.subject_, function(actual) {
  166. checkNumber(actual);
  167. if (Math.abs(expected - actual) > epsilon) {
  168. assert.fail(opt_message || `${actual} === ${expected} (± ${epsilon})`);
  169. }
  170. });
  171. }
  172. /**
  173. * @param {function(new: ?)} ctor The exptected type's constructor.
  174. * @param {string=} opt_message An optional failure message.
  175. * @return {(Promise|undefined)} The result of this assertion, if the subject
  176. * is a promised-value. Otherwise, the assertion is performed immediately
  177. * and nothing is returned.
  178. */
  179. instanceOf(ctor, opt_message) {
  180. checkFunction(ctor);
  181. return evaluate(this.subject_, function(actual) {
  182. if (!(actual instanceof ctor)) {
  183. assert.fail(
  184. opt_message
  185. || `${describe(actual)} instanceof ${ctor.name || ctor}`);
  186. }
  187. });
  188. }
  189. /**
  190. * @param {string=} opt_message An optional failure message.
  191. * @return {(Promise|undefined)} The result of this assertion, if the subject
  192. * is a promised-value. Otherwise, the assertion is performed immediately
  193. * and nothing is returned.
  194. */
  195. isNull(opt_message) {
  196. return this.isEqualTo(null);
  197. }
  198. /**
  199. * @param {string=} opt_message An optional failure message.
  200. * @return {(Promise|undefined)} The result of this assertion, if the subject
  201. * is a promised-value. Otherwise, the assertion is performed immediately
  202. * and nothing is returned.
  203. */
  204. isUndefined(opt_message) {
  205. return this.isEqualTo(void(0));
  206. }
  207. /**
  208. * Ensures the subject of this assertion is either a string or array
  209. * containing the given `value`.
  210. *
  211. * @param {?} value The value expected to be contained within the subject.
  212. * @param {string=} opt_message An optional failure message.
  213. * @return {(Promise|undefined)} The result of this assertion, if the subject
  214. * is a promised-value. Otherwise, the assertion is performed immediately
  215. * and nothing is returned.
  216. */
  217. contains(value, opt_message) {
  218. return evaluate(this.subject_, function(actual) {
  219. if (actual instanceof Map || actual instanceof Set) {
  220. assert.ok(actual.has(value), opt_message || `${actual}.has(${value})`);
  221. } else if (Array.isArray(actual) || isString(actual)) {
  222. assert.ok(
  223. actual.indexOf(value) !== -1,
  224. opt_message || `${actual}.indexOf(${value}) !== -1`);
  225. } else {
  226. assert.fail(
  227. `Expected an array, map, set, or string: got ${describe(actual)}`);
  228. }
  229. });
  230. }
  231. /**
  232. * @param {string} str The expected suffix.
  233. * @param {string=} opt_message An optional failure message.
  234. * @return {(Promise|undefined)} The result of this assertion, if the subject
  235. * is a promised-value. Otherwise, the assertion is performed immediately
  236. * and nothing is returned.
  237. */
  238. endsWith(str, opt_message) {
  239. checkString(str);
  240. return evaluate(this.subject_, function(actual) {
  241. if (!isString(actual) || !actual.endsWith(str)) {
  242. assert.fail(actual, str, 'ends with');
  243. }
  244. });
  245. }
  246. /**
  247. * @param {string} str The expected prefix.
  248. * @param {string=} opt_message An optional failure message.
  249. * @return {(Promise|undefined)} The result of this assertion, if the subject
  250. * is a promised-value. Otherwise, the assertion is performed immediately
  251. * and nothing is returned.
  252. */
  253. startsWith(str, opt_message) {
  254. checkString(str);
  255. return evaluate(this.subject_, function(actual) {
  256. if (!isString(actual) || !actual.startsWith(str)) {
  257. assert.fail(actual, str, 'starts with');
  258. }
  259. });
  260. }
  261. /**
  262. * @param {!RegExp} regex The regex the subject is expected to match.
  263. * @param {string=} opt_message An optional failure message.
  264. * @return {(Promise|undefined)} The result of this assertion, if the subject
  265. * is a promised-value. Otherwise, the assertion is performed immediately
  266. * and nothing is returned.
  267. */
  268. matches(regex, opt_message) {
  269. if (!(regex instanceof RegExp)) {
  270. throw TypeError(`Not a RegExp: ${describe(regex)}`);
  271. }
  272. return evaluate(this.subject_, function(actual) {
  273. if (!isString(actual) || !regex.test(actual)) {
  274. let message = opt_message
  275. || `Expected a string matching ${regex}, got ${describe(actual)}`;
  276. assert.fail(actual, regex, message);
  277. }
  278. });
  279. }
  280. /**
  281. * @param {?} value The unexpected value.
  282. * @param {string=} opt_message An optional failure message.
  283. * @return {(Promise|undefined)} The result of this assertion, if the subject
  284. * is a promised-value. Otherwise, the assertion is performed immediately
  285. * and nothing is returned.
  286. */
  287. notEqualTo(value, opt_message) {
  288. return evaluate(this.subject_, function(actual) {
  289. assert.notStrictEqual(actual, value, opt_message);
  290. });
  291. }
  292. /** An alias for {@link #isEqualTo}. */
  293. equalTo(value, opt_message) {
  294. return this.isEqualTo(value, opt_message);
  295. }
  296. /** An alias for {@link #isEqualTo}. */
  297. equals(value, opt_message) {
  298. return this.isEqualTo(value, opt_message);
  299. }
  300. /**
  301. * @param {?} value The expected value.
  302. * @param {string=} opt_message An optional failure message.
  303. * @return {(Promise|undefined)} The result of this assertion, if the subject
  304. * is a promised-value. Otherwise, the assertion is performed immediately
  305. * and nothing is returned.
  306. */
  307. isEqualTo(value, opt_message) {
  308. return evaluate(this.subject_, function(actual) {
  309. assert.strictEqual(actual, value, opt_message);
  310. });
  311. }
  312. /**
  313. * @param {string=} opt_message An optional failure message.
  314. * @return {(Promise|undefined)} The result of this assertion, if the subject
  315. * is a promised-value. Otherwise, the assertion is performed immediately
  316. * and nothing is returned.
  317. */
  318. isTrue(opt_message) {
  319. return this.isEqualTo(true, opt_message);
  320. }
  321. /**
  322. * @param {string=} opt_message An optional failure message.
  323. * @return {(Promise|undefined)} The result of this assertion, if the subject
  324. * is a promised-value. Otherwise, the assertion is performed immediately
  325. * and nothing is returned.
  326. */
  327. isFalse(opt_message) {
  328. return this.isEqualTo(false, opt_message);
  329. }
  330. }
  331. // PUBLIC API
  332. /**
  333. * Creates an assertion about the given `value`.
  334. * @return {!Assertion} the new assertion.
  335. */
  336. module.exports = function assertThat(value) {
  337. return new Assertion(value);
  338. };
  339. module.exports.Assertion = Assertion; // Exported to help generated docs