Coder Social home page Coder Social logo

guillaumearm / handle-io Goto Github PK

View Code? Open in Web Editor NEW
4.0 2.0 2.0 8.64 MB

:sparkles: - Wrap side effects, combine them, and make this combination testable

License: MIT License

JavaScript 100.00%
handle-io testing-tools saga-pattern generator testable io-monad

handle-io's Introduction

handle-io ✨

CircleCI branch codecov npm Greenkeeper badge NSP Status dependencies Status devDependencies Status contributions welcome Commitizen friendly Join the chat at https://gitter.im/handle-io/Lobby semantic-release

Highly inspired by funkia/io and redux-saga, this library intends to wrap small pieces of impure code, orchestrates and tests them.

Purpose

Test side effects orchestration without pain

testHandler(logTwice('hello world'))
  .matchIo(log('hello world'))
  .matchIo(log('hello world'))
  .run();

This piece of code is an assertion, an error will be thrown if something goes wrong:

  • wrong io function
  • wrong io arguments
  • too much io ran
  • not enough io ran

Getting started

Install

npm install --save handle-io

IO

io is just a wrapper for functions and arguments. In some way, it transforms impure functions into pure functions.

Conceptually, an io function could just be defined in this way:

const log = (...args) => [console.log, args];

but in handle-io, it isn't.

Create IO functions

You can use io to create one:

const { io } = require('handle-io');
const log = io(console.log);
Run IO functions

Running log with arguments:

log('Hello', 'World').run(); // print Hello World

Running log without arguments:

log().run();
// or
log.run();

Keep in mind: pieces of code using .run() cannot be tested properly.

The idea of this library is to apply an IO function inside a structure called handler.


Handlers

A handler is a wrapped pure generator which just apply some IO function and/or handler.

e.g.

const { io, handler } = require('handle-io');

const log = io(console.log);

const logTwice = handler(function*(...args) {
  yield log(...args);
  yield log(...args);
});

Writing tests for handlers

Writing tests for handlers is very simple (please see the first example above).

What about testing a handler which applies an IO function and returns values ?

There is a very simple way:

  • using the second argument of the .matchIo() method to mock returned values
  • using .shouldReturn() to assert on the final value

e.g.

const { io, handler } = require('handle-io');

const getEnv = io((v) => process.env[v]);

const addValues = handler(function*() {
  const value1 = yield getEnv('VALUE1');
  const value2 = yield getEnv('VALUE2');
  return value1 + value2;
});

testHandler(addValues())
  .matchIo(getEnv('VALUE1'), 32)
  .matchIo(getEnv('VALUE2'), 10)
  .shouldReturn(42)
  .run();

Running handlers

Same as for IO functions, there is a .run() method:

addValues().run(); // => 42
// or
addValue.run();

Likewise, don't use handlers' .run() everywhere in your codebase.

handlers are combinable together: you can yield a handler.


Promise support

handle-io supports promises and allows you to create asynchronous IO.

e.g.

const { io, handler, testHandler } = require('handle-io');

// async io
const sleep = io((ms) => new Promise(resolve => setTimeout(resolve, ms)));

// create an async combination
const sleepSecond = handler(function*(s) {
  yield sleep(s * 1000);
  return s;
});

// test this combination synchronously
testHander(sleepSecond(42))
  .matchIo(sleep(42000))
  .shouldReturn(42)
  .run();

Please note that sleep(n) and sleepSecond(n) will expose .run() methods that return a promise.

e.g.

sleepSecond(1).run().then((n) => {
  console.log(`${n} second(s) waited`);
});

Dealing with errors

using Try/Catch

The simplest way to handle errors with handle-io is to use try/catch blocks.

As you can see in the example below, you can try/catch any errors:

  • inside a handler:
    • thrown error
  • inside an io function:
    • thrown error
    • unhandled promise rejection

e.g.

const { io, handler } = require('handle-io');

const handler1 = handler(function*() {
  throw new Error();
});

// Synchronous IO
const io1 = io(() => { throw new Error() });

// Asynchronous IO
const io2 = io(() => Promise.reject(new Error()));

// handler2 is safe, it can't throw because it handles errors
const handler2 = handler(function*() {
  try {
    yield io1();
    yield io2();
    yield handler1();
  } catch (e) {
    console.error(e);
  }
});

using catchError helper

A functional helper exits to avoid try/catchs block, it allows to easily ignore errors and/or results.

Under the hood, catchError uses a try/catch block and works similarly.

e.g.

const { io, handler, catchError } = require('handle-io');

const ioError = io((e) => { throw new Error(e) });

const myHandler = handler(function*() {
  const [res, err] = yield catchError(ioError('error'));
  if (err) {
    yield log(err);
  }
  return res;
});

How to test errors

By default, no mocked IO throws any error.

It's possible to simulate throws with testHandler using the simulateThrow test utility.

Writing tests for myHandler means two cases need to be handled:

  • when ioError throws:
testHandler(myHandler())
  .matchIo(ioError('error'), simulateThrow('error'))
  .matchIo(log('error'))
  .shouldReturn(undefined)
  .run();
  • when ioError doesn't throw:
testHandler(myHandler())
  .matchIo(ioError('error'), 42)
  .shouldReturn(42)
  .run();

Custom testHandler

A custom testHandler can be created using createTestHandler.

e.g.

import { io, createTestHandler } from 'handle-io';


const createCustomTestHandler = (h, mockedIOs = [], expectedRetValue, assertRet = false, constructor = createCustomTestHandler) => {
  return {
    ...createTestHandler(h, mockedIOs, expectedRetValue, assertRet, constructor),
    matchLog: (arg, ret) => constructor(
      h,
      [...mockedIOs, [io(console.log)(arg), ret]],
      expectedRetValue,
      assertRet,
      constructor,
    ),
  };
};

const customTestHandler = h => createCustomTestHandler(h);

const log = io(console.log);
const myHandler = handler(function*(value) {
  yield log(value);
  yield log(value);
  return 42;
});

customTestHandler(myHandler('hello world'))
  .shouldReturn(42)
  .matchLog('hello world')
  .matchLog('hello world')
  .run()

Use with Redux

There is a way to use handler as redux middleware.

Please take a look to redux-fun Handlers.

License

MIT

handle-io's People

Contributors

fossabot avatar greenkeeper[bot] avatar greenkeeperio-bot avatar guillaumearm avatar semantic-release-bot avatar shakadak avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

fossabot shakadak

handle-io's Issues

add io.Lazy

Non-blocking asynchronous flow

io.Lazy allows handlers to have more control on asynchronous flow.

yield an io.Lazy in an handler allow to get promise instead of value, this promise must be yield to be resolved.

e.g.

const { io, handler } = require('handle-io');

const sleep = io(ms => new Promise(resolve => setTimeout(resolve, ms)));

const myHandler = handler(function*() {
  const sleepPromise1 = yield io.Lazy(sleep(1000));
  const sleepPromise2 = yield io.Lazy(sleep(2000));
  const sleepPromise3 = yield io.Lazy(sleep(3000));

  // at this point, all sleep IOs are ran in parallel

  yield sleepPromise1; // waiting for first sleep
  yield sleepPromise2; // waiting for second sleep
  yield sleepPromise3; // waiting for third sleep
});

The important point to note here is that yield sleep(1000) is blocking while yield io.lazy(sleep(1000)) is non-blocking.


Related to #138.

Refactor internal

  • move createTestRunner code from internal/runners.js into testHandler.js
  • rename internal/runners.js into internal/ioRunner.js and change named export by default export

Write api documentation

  • Install jsdoc
  • write documentation for all exposed functions :
    • io
    • handler
    • testHandler
    • catchError
    • simulateError
  • Configure circleci to automatically generate api documentation

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Replaced the old Node.js version in your .nvmrc with the new one
  • The new Node.js version is in-range for the engines in 1 of your package.json files, so that was left alone

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Integrate browser tests

  • Using testem and phantomjs. Check out if puppettier works with testem.
  • Check if HandleIO is exposed in window object (umd build)

add fallback to "npm ci" in install job

npm ci || npm install

This is for greenkeeper lockfile update.

npm ci
npm ERR! cipm can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file with `npm install` before continuing.
npm ERR! 
npm ERR! 
npm ERR! Invalid: lock file's [email protected] does not satisfy [email protected]
npm ERR! 

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/circleci/.npm/_logs/2018-03-17T19_00_56_092Z-debug.log
Exited with code 1

An in-range update of markdownlint-cli is breaking the build 🚨

☝️ Greenkeeper’s updated Terms of Service will come into effect on April 6th, 2018.

Version 0.8.1 of markdownlint-cli was just published.

Branch Build failing 🚨
Dependency markdownlint-cli
Current Version 0.8.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

markdownlint-cli is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: install Your tests passed on CircleCI! Details
  • ci/circleci: node8_bundle_test Your tests failed on CircleCI Details
  • ci/circleci: style_test Your tests failed on CircleCI Details
  • ci/circleci: node7_bundle_test Your tests failed on CircleCI Details
  • ci/circleci: code_coverage Your tests failed on CircleCI Details
  • ci/circleci: unit_test Your tests failed on CircleCI Details
  • ci/circleci: node6_bundle_test Your tests failed on CircleCI Details
  • ci/circleci: node9_bundle_test Your tests failed on CircleCI Details

Release Notes 0.8.1
  • Fix a bug introduced by new --stdin support that could be triggered by some customizations
Commits

The new version differs by 2 commits.

  • 2ba1b66 Bump version 0.8.1
  • bf77d8a Prevent new stdin support from interfering when unused (fixes #35).

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

API changes

  • raname io in IO
  • rename handler in Handler
  • rename .matchIo method in .matchIO
  • impact existing tests
  • impact existing documentation

add simulateThrow test utility

usage:

const { io, handler, testHandler, simulateThrow } = require('handle-io');

const ioError = io((e) => { throw e });

const addValues = handler(function*() {
  try {
    yield ioError('error');
  } catch (e) {
    return 'error';
  }
  return 'result';
});

testHandler(addValues())
  .matchIo(ioError('error'), simulateThrow(new Error())),
  .shouldReturn('error')
  .run()
  • implementation
  • unit tests
  • documentation
  • readme example test (bundle tests)

fix lockfile generation

in circleci install job, npm install again after greenkeeper-update-lockfile in order to sync package.json and package-lock.json

Improve CONTRIBUTING.md

  • Add a "Contributing" part in README.md
  • Add introduction
  • Link url to the CODE_OF_CONDUCT.md
  • add PRs section
  • ...

curried io instances and handler instances

instead of replace arguments when we apply several times an io or a handler instance :

const list = (...args) => args;
io(list)(1, 2, 3)(4, 5, 6)(7)(8)(9).run() // => [1, 2, 3, 4, 5, 6, 7, 8, 9]

Write tests

Unit tests ✅

  • test all exposed functions
    • io
    • handler
    • testHandler
  • test internal functions
    • utils
    • ioRunner

Integration tests (with umd, commonjs and es modules) ✅

  • build
    • umd module
    • commonjs module
    • es module
  • on each modules :
    • check exposed api
    • run readme examples
      • logTwice
      • addValues

improve __bundle_tests__/api test

Replace hardcoded api keys ['io', 'handler', 'testHandler', 'catchError'] by an Object.keys of imported handle-io from src,

in __bundle_tests__/api.js file.

Add catchError io/handler enhancer

implementation :

const catchError = (yieldable) => handler(function*() {
  let res;
  let err;
  try {
    res = yield yieldable;
  } catch (e) {
    err = e;
  }
  return [res, err]
});

usage :

const handler1 = handler(function*() {
  const [res, err] = yield catchError(anyYieldable());
  if (err) {
    yield log(err);
  }
  return res;
})
  • write documentation
  • write implementation
  • write unit tests
  • add __bundle_tests__/example-readme-catchError.js

async handler

  • make handler manage promises
  • write tests for this
  • write documentation for this

Add io.Parallel

waiting for #139

usage:

const { io, handler } = require('handle-io');


const ioFetchAll = io(() => io.Parallel(fetchUser(), fetchData(), fetchMisc()));

const fetchAll = handler(function*() {
  // const [user, data, misc] = yield io.Parallel(fetchUser(), fetchData(), fetchMisc());
  const [user, data, misc] = yield ioFetchAll();
  return { user, data, misc };
})

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.