Git Product home page Git Product logo

spyfs's Introduction

spyfs npm-img

Spy on filesystem calls. Create file system mocks. Use for testing.

Install:

npm install --save spyfs

Create a new file system that spies:

import * as fs from 'fs';
import {spy} from 'spyfs';

const sfs = spy(fs);

Now you can use sfs for all your filesystem operations.

const data = sfs.readFileSync('./package.json').toString();

Subscribe to all actions happening on that filesystem:

sfs.subscribe(action => {
    // ...
});

Every time somebody uses sfs, the subscription callback will be called. You will receive a single argument: an action which is a Promise object containing all the information about the performed filesystem operation and its result.

You can also subscribe by providing a listener at creation:

const sfs = spy(fs, action => {
    // ...
});

Want to spy on real filesystem?

Overwrite the real fs module using fs-monkey to spy on all filesystem calls:

import {patchFs} from 'fs-monkey';

patchFs(sfs);

Use async/await

spyfs returns actions which are instances of the Promise constructor, so you can use asynchronous functions for convenience:

const sfs = spy(fs, async function(action) {
    console.log(await action); // prints directory files...
});

sfs.readdir('/', () => {});

Use with memfs

You can use spyfs with any fs-like object, including memfs:

import {fs} from 'memfs';
import {spy} from 'spyfs';

const sfs = spy(fs, async function(action) {
    console.log(await action); // bar
});

sfs.writeFile('/foo', 'bar', () => {});
sfs.readFile('/foo', 'utf8', () => {});

Action properties

spyfs actions have extra properties that tell you more about the action being executed:

  • action.method (string) - name of filesystem method called.
  • action.isAsync (boolean) - whether the filesystem method called was asynchronous.
  • action.args (Array) - list of arguments with which the method was called (sans callback).
const sfs = spy(fs, action => {
    console.log(action.method); // readdir, readdirSync
    console.log(action.isAsync); // true, false
    console.log(action.args); // [ '/' ], [ '/' ]
});

sfs.readdir('/', () => {});
sfs.readdirSync('/');

Subscribe to events

The returned filesystem object is also an event emitter, you can subscribe to specific filesystem actions using the .on() method, in that case you will receive only actions for that method:

sfs.on('readdirSync', async function(action) {
    console.log(action.args, await action);
});

sfs.readdirSync('/');

Listening for action event is equivalent to subscribing using .subscribe().

sfs.on('action', listener);
sfs.subscribe(listener);

Mock responses

You can overwrite what is returned by the filesystem call at runtime or even throw your custom errors, this way you can mock any filesystem call:

For example, prohibit readFileSync for /usr/foo/.bashrc file:

sfs.on('readFileSync', ({args, reject}) => {
    if(args[0] === '/usr/foo/.bashrc')
        reject(new Error("Cant't touch this!"));
});

Sync mocking

action.resolve(result)

Returns to the user result as successfully executed action, below all operations readFileSync will return '123':

sfs.on('readFileSync', action => {
    action.resolve('123');
});

action.reject(error)

Throws error:

sfs.on('statSync', action => {
    action.reject(new Error('This filesystem does not support stat'));
});

action.exec()

Executes an action user was intended to perform and returns back result only to you. This method can throw.

sfs.on('readFileSync', action => {
    const result = action.exec();
    if(result.length > 100) action.reject(new Error('File too long'));
});

action.result

result is a reference to the action for your convenience:

Async mocking

Just like sync mocking actions support resolve, reject and exec methods, but, in addition, async mocking also has pause and unpause methods.

action.resolve(results)

Successfully executes user's filesystem call. results is an array, because some Node's async filesystem calls return more than one result.

sfs.on('readFile', ({resolve}) => {
    resolve(['123']);
});

action.reject(error)

Fails filesystem call and returns your specified error.

sfs.on('readFile', ({reject}) => {
    reject(new Error('You cannot touch this file!'));
});

action.pause()

Pauses the async filesystem call until you un-pause it.

sfs.on('readFile', ({pause}) => {
    pause();
    // The readFile operation will never end,
    // if you don't unpause it.
});

Pausing is useful if you want to perform some other async IO before yielding back to the original filesystem operation.

action.unpause()

Un-pauses previously pauses filesystem operation:

sfs.on('readFile', ({pause, unpause}) => {
    // This effectively does nothing:
    pause();
    unpause();
});

action.exec()

Executes user's intended filesystem call and returns the result only to you. Unlike the sync version exec, async exec returns a promise.

You should use it together with pause() and unpause().

sfs.on('readFile', ({exec, pause, unpause, reject}) => {
    pause();
    exec().then(result => {
        if(result.length < 100) {
            reject(new Error('File too small'));
        } else {
            unpause();
        }
    });
});

Use async/await with exec():

sfs.on('readFile', async function({exec, pause, unpause, reject}) {
    pause();
    let result = await exec();
    if(result.length < 100) {
        reject(new Error('File too small'));
    } else {
        unpause();
    }
});

action.result

result is a reference to the action for your convenience:

Spy constructor

Create spying filesystems manually:

import {Spy} from 'spyfs';

new Spy(fs[, listener])

fs is the file system to spy on. Note that Spy will not overwrite or in any way modify your original filesystem, but rather it will create a new object for you.

listener is an optional callback that will be set using the .subscribe() method, see below.

sfs.subscribe(listener)

Subscribe to all filesystem actions:

const sfs = new Spy(fs);
sfs.subscribe(action => {

});

It is equivalent to calling sfs.on('action', listener).

sfs.unsubscribe(listener)

Unsubscribes your listener. It is equivalent to calling sfs.off('action', listener).

sfs.on(method, listener)

Subscribes to a specific filesystem call.

sfs.on('readFile', listener);

sfs.off(method, listener)

Unsubscribes from a specific filesystem call.

License

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.

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 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.

For more information, please refer to http://unlicense.org/

spyfs's People

Contributors

renovate-bot avatar renovate[bot] avatar streamich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

spyfs's Issues

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (github>whitesource/merge-confidence:beta)

Dependency deprecation warning: babel-preset-es2016 (npm)

On registry https://registry.npmjs.org/, the "latest" version (v6.24.1) of dependency babel-preset-es2016 has the following deprecation notice:

๐Ÿ™Œ Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Affected package file(s): package.json

If you don't care about this, you can close this issue and not be warned about babel-preset-es2016's deprecation again. If you would like to completely disable all future deprecation warnings then add the following to your config:

"suppressNotifications": ["deprecationWarningIssues"]

Dependency deprecation warning: babel-preset-es2017 (nvm)

On registry https://registry.npmjs.org/, the "latest" version (v6.24.1) of dependency babel-preset-es2017 has the following deprecation notice:

๐Ÿ™Œ Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Please take the actions necessary to rename or substitute this deprecated package and commit to your base branch. If you wish to ignore this deprecation warning and continue using babel-preset-es2017 as-is, please add it to your ignoreDeps array in Renovate config before closing this issue, otherwise another issue will be recreated the next time Renovate runs.

Affected package file(s): package.json

Dependency deprecation warning: babel-preset-es2016 (nvm)

On registry https://registry.npmjs.org/, the "latest" version (v6.24.1) of dependency babel-preset-es2016 has the following deprecation notice:

๐Ÿ™Œ Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Please take the actions necessary to rename or substitute this deprecated package and commit to your base branch. If you wish to ignore this deprecation warning and continue using babel-preset-es2016 as-is, please add it to your ignoreDeps array in Renovate config before closing this issue, otherwise another issue will be recreated the next time Renovate runs.

Affected package file(s): package.json

Dependency deprecation warning: babel-preset-es2015 (nvm)

On registry https://registry.npmjs.org/, the "latest" version (v6.24.1) of dependency babel-preset-es2015 has the following deprecation notice:

๐Ÿ™Œ Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Please take the actions necessary to rename or substitute this deprecated package and commit to your base branch. If you wish to ignore this deprecation warning and continue using babel-preset-es2015 as-is, please add it to your ignoreDeps array in Renovate config before closing this issue, otherwise another issue will be recreated the next time Renovate runs.

Affected package file(s): package.json

Request type definitions in package.json or DefinitelyTyped

import { spy } from "spyfs";

Could not find a declaration file for module 'spyfs'. '/home/ajvincent/filesystem/filterfs/node_modules/spyfs/lib/index.js' implicitly has an 'any' type.
Try npm i --save-dev @types/spyfs if it exists or add a new declaration (.d.ts) file containing declare module 'spyfs';ts(7016)

Obviously I can add the declare line, but it would not have any type definition information for me to use...

https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html#handbook-content

Dependency deprecation warning: babel-preset-es2015 (npm)

On registry https://registry.npmjs.org/, the "latest" version (v6.24.1) of dependency babel-preset-es2015 has the following deprecation notice:

๐Ÿ™Œ Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Affected package file(s): package.json

If you don't care about this, you can close this issue and not be warned about babel-preset-es2015's deprecation again. If you would like to completely disable all future deprecation warnings then add the following to your config:

"suppressNotifications": ["deprecationWarningIssues"]

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

npm
package.json
  • fs-monkey 0.4.0
  • mocha 10.4.0
  • chai 5.1.0
  • typescript 5.4.3
  • ts-node 10.9.2
  • babel-cli 6.26.0
  • babel-polyfill 6.26.0
  • babel-preset-stage-0 6.24.1
  • babel-preset-es2015 6.24.1
  • babel-preset-es2016 6.24.1
  • babel-preset-es2017 6.24.1
  • babel-preset-flow 6.23.0
  • gulp 5.0.0
  • gulp-typescript 5.0.1
  • source-map-support 0.5.21
  • nyc 15.1.0
  • watch 1.0.2
  • memfs 4.8.0
nvm
.nvmrc
  • node 8.17.0
travis
.travis.yml
  • node 8
  • node 7
  • node 6
  • node 5

  • Check this box to trigger a request for Renovate to run again on this repository

fs.closeSync error

javascript const spyfs = require( 'spyfs' ); const sfs = spyfs.spy( fs, action => { console.log( action ); } ); const fd = sfs.openSync( __filename, 'r' ); sfs.closeSync( fd ); // error, return undefined

Dependency deprecation warning: babel-preset-es2017 (npm)

On registry https://registry.npmjs.org/, the "latest" version (v6.24.1) of dependency babel-preset-es2017 has the following deprecation notice:

๐Ÿ™Œ Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Affected package file(s): package.json

If you don't care about this, you can close this issue and not be warned about babel-preset-es2017's deprecation again. If you would like to completely disable all future deprecation warnings then add the following to your config:

"suppressNotifications": ["deprecationWarningIssues"]

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.