All Projects → bahmutov → Lazy Ass

bahmutov / Lazy Ass

Licence: mit
Lazy node assertions without performance penalty

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Lazy Ass

Tester
Tester: enjoyable unit testing in PHP with code coverage reporter. 🍏🍏🍎🍏
Stars: ✭ 281 (+346.03%)
Mutual labels:  assertions
Kotlin Power Assert
Kotlin compiler plugin to enable diagrammed assertions in the Kotlin programming language
Stars: ✭ 370 (+487.3%)
Mutual labels:  assertions
Silk
Markdown based document-driven RESTful API testing.
Stars: ✭ 922 (+1363.49%)
Mutual labels:  assertions
Hamkrest
Hamcrest for Kotlin
Stars: ✭ 317 (+403.17%)
Mutual labels:  assertions
Atrium
A multiplatform assertion library for Kotlin
Stars: ✭ 359 (+469.84%)
Mutual labels:  assertions
Bash unit
bash unit testing enterprise edition framework for professionals
Stars: ✭ 419 (+565.08%)
Mutual labels:  assertions
iutest
c++ testing framework
Stars: ✭ 58 (-7.94%)
Mutual labels:  assertions
Is
Type check values
Stars: ✭ 1,011 (+1504.76%)
Mutual labels:  assertions
Luaunit
LuaUnit is a popular unit-testing framework for Lua, with an interface typical of xUnit libraries (Python unittest, Junit, NUnit, ...). It supports several output formats (Text, TAP, JUnit, ...) to be used directly or work with Continuous Integration platforms (Jenkins, Maven, ...).
Stars: ✭ 362 (+474.6%)
Mutual labels:  assertions
Pandera
A light-weight, flexible, and expressive pandas data validation library
Stars: ✭ 506 (+703.17%)
Mutual labels:  assertions
Sazerac
Data-driven unit testing for Jasmine, Mocha, and Jest
Stars: ✭ 322 (+411.11%)
Mutual labels:  assertions
Assertr
Assertive programming for R analysis pipelines
Stars: ✭ 355 (+463.49%)
Mutual labels:  assertions
Zerocode
A community-developed, free, open source, microservices API automation and load testing framework built using JUnit core runners for Http REST, SOAP, Security, Database, Kafka and much more. Zerocode Open Source enables you to create, change, orchestrate and maintain your automated test cases declaratively with absolute ease.
Stars: ✭ 482 (+665.08%)
Mutual labels:  assertions
Strikt
An assertion library for Kotlin
Stars: ✭ 310 (+392.06%)
Mutual labels:  assertions
Clj Fakes
An isolation framework for Clojure/ClojureScript.
Stars: ✭ 26 (-58.73%)
Mutual labels:  assertions
Kotest
Powerful, elegant and flexible test framework for Kotlin with additional assertions, property testing and data driven testing
Stars: ✭ 3,234 (+5033.33%)
Mutual labels:  assertions
Enzyme
JavaScript Testing utilities for React
Stars: ✭ 19,781 (+31298.41%)
Mutual labels:  assertions
Aws Testing Library
Chai (https://chaijs.com) and Jest (https://jestjs.io/) assertions for testing services built with aws
Stars: ✭ 52 (-17.46%)
Mutual labels:  assertions
Should Enzyme
Useful functions for testing React Components with Enzyme.
Stars: ✭ 41 (-34.92%)
Mutual labels:  assertions
Karate
Test Automation Made Simple
Stars: ✭ 5,497 (+8625.4%)
Mutual labels:  assertions

lazy-ass

Lazy assertions without performance penalty

NPM

Build status manpm dependencies devdependencies

semantic-release Coverage Status Codacy Code Climate

Demo

Note: only tested against Node 4+

Example

Regular assertions evaluate all arguments and concatenate message EVERY time, even if the condition is true.

console.assert(typeof foo === 'object',
  'expected ' + JSON.stringify(foo, null, 2) + ' to be an object');

Lazy assertion function evaluates its arguments and forms a message ONLY IF the condition is false

const {lazyAss} = require('lazy-ass')
lazyAss(typeof foo === 'object', 'expected', foo, 'to be an object');
// shorter version
const {lazyAss: la} = require('lazy-ass')
la(typeof foo === 'object', 'expected', foo, 'to be an object');

Concatenates strings, stringifies objects, calls functions - only if condition is false.

function environment() {
  // returns string
}
var user = {} // an object
lazyAsync(condition, 'something went wrong for', user, 'in', environment);
// throws an error with message equivalent of
// 'something went wrong for ' + JSON.stringify(user) + ' in ' + environment()

Why?

  • Passing an object reference to a function is about 2000-3000 times faster than serializing an object and passing it as a string.
  • Concatenating 2 strings before passing to a function is about 30% slower than passing 2 separate strings.

Install

Node: npm install lazy-ass --save then var la = require('lazy-ass');. You can attach the methods to the global object using require('lazy-ass').globalRegister();.

Browser: bower install lazy-ass --save, include index.js, attaches functions lazyAss and la to window object.

Notes

You can pass as many arguments to lazyAss after the condition. The condition will be evaluated every time (this is required for any assertion). The rest of arguments will be concatenated according to rules

  • string will be left unchanged.
  • function will be called and its output will be concatenated.
  • any array or object will be JSON stringified.

There will be single space between the individual parts.

Lazy async assertions

Sometimes you do not want to throw an error synchronously, breaking the entire execution stack. Instead you can throw an error asynchronously using lazyAssync, which internally implements logic like this:

if (!condition) {
  setTimeout(function () {
    throw new Error('Conditions is false!');
  }, 0);
}

This allows the execution to continue, while your global error handler (like my favorite Sentry) can still forward the error with all specified information to your server.

lazyAss.async(false, 'foo');
console.log('after assync');
// output
after assync
Uncaught Error: foo

In this case, there is no meaningful error stack, so use good message arguments - there is no performance penalty!

Rethrowing errors

If the condition itself is an instance of Error, it is simply rethrown (synchronously or asynchronously).

lazyAss(new Error('foo'));
// Uncaught Error: foo

Useful to make sure errors in the promise chains are not silently ignored.

For example, a rejected promise below this will be ignored.

var p = new Promise(function (resolve, reject) {
  reject(new Error('foo'));
});
p.then(...);

We can catch it and rethrow it synchronously, but it will be ignored too (same way, only one step further)

var p = new Promise(function (resolve, reject) {
  reject(new Error('foo'));
});
p.then(..., lazyAss);

But we can actually trigger global error if we rethrow the error asynchronously

var p = new Promise(function (resolve, reject) {
  reject(new Error('foo'));
});
p.then(..., lazyAssync);
// Uncaught Error: foo

Predicate function as a condition

Typically, JavaScript evaluates the condition expression first, then calls lazyAss. This means the function itself sees only the true / false result, and not the expression itself. This makes makes the error messages cryptic

lazyAss(2 + 2 === 5);
// Error

We usually get around this by giving at least one additional message argument to explain the condition tested

lazyAss(2 + 2 === 5, 'addition')
// Error: addition

lazyAss has a better solution: if you give a function that evaluates the condition expression, if the function returns false, the error message will include the source of the function, making the extra arguments unnecessary

lazyAss(function () { return 2 + 2 === 5; });
// Error: function () { return 2 + 2 === 5; }

The condition function has access to any variables in the scope, making it extremely powerful

var foo = 2, bar = 2;
lazyAss(function () { return foo + bar === 5; });
// Error: function () { return foo + bar === 5; }

In practical terms, I recommend using separate predicates function and passing relevant values to the lazyAss function. Remember, there is no performance penalty!

var foo = 2, bar = 2;
function isValidPair() {
  return foo + bar === 5;
}
lazyAss(isValidPair, 'foo', foo, 'bar', bar);
// Error: function isValidPair() {
//   return foo + bar === 5;
// } foo 2 bar 2

Testing

This library is fully tested under Node and inside browser environment (CasperJs). I described how one can test asynchronous assertion throwing in your own projects using Jasmine in a blog post.

TypeScript

If you use this function from a TypeScript project, we provide ambient type definition file. Because this is CommonJS library, use it like this

import la = require('lazy-ass')
// la should have type signature

Small print

Author: Gleb Bahmutov © 2014

License: MIT - do anything with the code, but don't blame me if it does not work.

Spread the word: tweet, star on github, etc.

Support: if you find any problems with this module, email / tweet / open issue on Github

MIT License

Copyright (c) 2014 Gleb Bahmutov

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].