Giter Site home page Giter Site logo

mock-couch's Introduction

The Mock Couch

Build Status

Mock a CouchDB server for your unit tests.

A photo of a Mock Couch

Mock Couch will create an HTTP server that emulates the responses of a real CouchDB server. Since it is an actual HTTP server, no matter if you use libraries like cradle and nano, your code should work out of the box.

Mock Couch emit events, so you can listen to them to see the result of your test.

Installation

npm install --save-dev mock-couch

Changelog

  • 0.1.10
  • Updated restify version (credits to @gamegee)
  • 0.1.9
  • Specify the version of dependencies with npm-shrinkwrap.json
  • 0.1.8
  • Fix: _all_docs must return { key : thekey, error : "not_found" } for each missing key
  • Fix: _bulk_docs didn't converted the functions of the passed design docs.
  • 0.1.7
  • Fix: Do not preserve preserve any properties of the old document when updating (Credits to @reederz)
  • New feature: Now is possible to PUT/POST design documents (Credits to @dermidgen)
  • 0.1.6
  • Fix on instance_start_time (Credits to @Dainis)
  • Fix issue when calling addDB multiple times. (Credits to @Troy Cochran)
  • 0.1.5
  • Add support for a show function (Credits to @tekdel)
  • 0.1.4
  • The required minimal version of node is now 0.12
  • Support for the built-in _sum and _count reduce functions.
  • Now, mock-couch uses the Views Collation rules of CouchDB, by using couch-viewkey-compare. (Thanks to @monowerker for this module).
  • GET _uuids (Credits to @watchforstock)
  • Several fixes (Credits to @monowerkerds and @reederz)
  • 0.1.3
  • Several fixes (Thanks to @monowerker and @alexjeffburke)
  • Rewriting a lot of the code using Ramda (to make it more functional)
  • Support for linked documents in views (Credits to @monowerker)
  • Implementation of _changes (Credits to @conor-mac-aoidh)
  • 0.1.2
  • Added HEAD requests. (Credits to @davidwood)
  • Added option to prevent keep-alive connections. (Credits to @davidwood)
  • Now is possible to use the query option key on views.
  • Other fixes.
  • 0.1.1
  • The emitted events are now standarized. Read about the events on the documentation.
  • 0.1.0
  • Support for views (map and reduce functions). Create a _design/ document to use them. Read more about them here.
  • Documentation available on http://chris-l.github.io/mock-couch/
  • Added addDoc method to add a document from the node.js side. Contrary to adding a document with a PUT, this is sync and allows you to specify the _rev

Documentation

Visit the Mock Couch website.

Features

  • Implemented with restify.
  • Uses simple JavaScript objects as documents.
  • It emit events, so the tests can listen to them.
  • The mock_couch object has a databases public property, to examine how the databases are in any moment.
  • Several of the CouchDB REST methods. Right now it has:
  • GET one document
  • GET _all_docs, including:
    • include_docs=true
    • descending=true
    • startkey
    • endkey
    • also, using _all_docs with POST to specify the desired keys
  • GET the information of a database
  • GET _all_dbs
  • GET _uuids
  • GET views (like http://localhost:5984/database/_design/myviews/_view/someview/)
  • PUT one document
  • PUT a database
  • POST one document
  • POST to _bulk_docs multiple documents
  • DELETE one document
  • DELETE a database

Not yet implemented

  • deleting by setting the _deleted member
  • Attachment support
  • And a lot of other things!

Keep in mind that Mock Couch is not attempting to fully implement CouchDB, but only the features necessary for unit testing CouchDB based apps.

However, if there is a feature you need for your tests, feel free to add a feature request in the issues section!

Usage

Here is an example:

var mockCouch = require('mock-couch');

// myfun is the function that we want to test.
// It uses couchdb, either by using cradle, nano, or direct http requests
// This function takes an object as parameter, maybe runs some validations
// and if everything is ok, then save it on couchdb.
var myfun = require('somefunc');


describe('myfun', function() {

  beforeEach(function() {
    // Starting the server
    var couchdb = mockCouch.createServer();

    // Make sure you are either executing this test under a machine that does not have couchdb installed/enabled,
    // or that you are using a different port!
    // (which may require that you are able to specify the couchdb port on the function you are about to test)
    couchdb.listen(5984);

    // This creates a db for Mock Couch. The db is nothing but an array of objects.
    // If we provide an object with an _id property, it will use it. Otherwise, it will create a random one.
    couchdb.addDB('people', [ { name : 'one name', lastname : 'one lastname' }, { _id : '4568797890', name : 'second name', lastname : 'other lastname' } ]);
  });


  // Here is the test
  it('must add a person to couchdb', function(done) {

    // Now we add a listener that is expecting the data we are about to send.
    couchdb.on('POST', function(data) {
      expect(data.doc.name).toBe('reimu');
      expect(data.doc.lastname).toBe('hakurei');
      done();
    });

    // And here we are finally calling the function
    myfun({ name : 'reimu', lastname : 'hakurei' });

  });
});

If your testing requires the frequent setup and teardown of the mock server, it may be beneficial to prevent keep-alive connections. The server will always return a Connection: close header if constructed with a keepAlive option set to false.

var couchdb = mockCouch.createServer({ keepAlive: false });

Status

In this moment I think it could be considered beta; I don't expect any breaking changes.

License

MIT license

Contribution

Your feedback, pull requests, etc are welcomed! :)

mock-couch's People

Contributors

alexjeffburke avatar chris-l avatar dainis avatar davidwood avatar dermidgen avatar mactroyibm avatar monowerker avatar reederz avatar watchforstock 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  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  avatar  avatar  avatar  avatar

mock-couch's Issues

CouchDB 2.0

Are you planing to support CouchDB 2.* as well?

Allow '/' in database names

{"statusCode":400,"error":"Bad Request","message":"Name: 'm/6f23be18595c4164a575d768b2121043'. Only lowercase characters (a-z), digits (0-9), and any of the characters _, $, (, ), +, -, and / are allowed. Must begin with a letter."}

Getting 405 PUT is not allowed when trying to insert a _design doc with nano

I seem to be getting a 405 PUT not allowed error when trying to insert a design document;

{ [Error: PUT is not allowed]
  name: 'Error',
  statusCode: 405,
  body: { code: 'MethodNotAllowedError', message: 'PUT is not allowed' },
  scope: 'couch',
  request: 
   { method: 'PUT',
     headers: 
      { 'content-type': 'application/json',
        accept: 'application/json' },
[...]

I'm simply doing the following with nano after creating a database:

var design = {
  "views": {
    "all": {
      map: function(doc) {
        if (doc._id) emit(doc._id, doc);
      }
    }
  }
};

db.insert(design, '_design/tweets', function(err, res) {
  if (err) return console.log(err);
  console.log('Inserted!');
});

This gives the correct response when using a real couchdb database, but seems to fail when using mock-couch.

crash on require('mock-couch')

I'm having a problem with node crashing when I require mock-couch.

  • macOS 10.13.4
  • node v8.9.1
  • npm v6.1.0

package.json

{
  "dependencies": {
    "mock-couch": "0.1.10"
  }
}

test.js

require('mock-couch');
bash> node test.js


#
# Fatal error in ../deps/v8/src/api.cc, line 1248
# Check failed: !value_obj->IsJSReceiver() || value_obj->IsTemplateInfo().
#
Illegal instruction: 4
bash> npm list
/Users/chris/projects/rmc/test
└─┬ [email protected]
  ├── [email protected] extraneous
  ├── [email protected]
  ├── [email protected] extraneous
  ├── [email protected] extraneous
  ├── [email protected] extraneous
  ├── [email protected]
  ├─┬ [email protected] invalid
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ ├── [email protected] extraneous
  │ └── [email protected] extraneous
  └── [email protected]

npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/color-convert
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/grunt
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/grunt-jasmine-nodejs
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/grunt-jslint
npm ERR! invalid: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/restify
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/assert-plus
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/backoff
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/bunyan
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/csv
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/deep-equal
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/dtrace-provider
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/escape-regexp-component
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/formidable
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/http-signature
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/keep-alive-agent
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/lru-cache
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/mime
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/negotiator
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/node-uuid
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/once
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/qs
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/semver
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/spdy
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/tunnel-agent
npm ERR! extraneous: [email protected] /Users/chris/projects/rmc/test/node_modules/mock-couch/node_modules/verror

I wonder if the problem is related to [email protected] invalid? I'm not sure what that means.

_changes mock

Just came across this project, I am so glad this exists. Anything that requires having more than one couch becomes real annoying to test. Specifically I've been wanting something like this in order to write some tests for overwatch. I'd love to help out with a basic _changes implementation when I have some bandwidth. Let me know if this interests you :).

Support for design document update handlers?

Thanks for the great library. I've been looking for something like this for a while!

The docs clearly show that views are supported using addDoc, but it doesn't appear that updates functions are supported when I add design docs that have update handlers in them. We use update handlers to add simple timestamps to our docs. Am I doing something wrong, or is this feature just not supported yet.

Are update handlers a feature that you'd consider supporting, if they don't work already?

The super constructor to "inherits" must not be null or undefined

Weird error when I execute test with gulp or npm:

Here the sample of code from my test:

const mockCouch = require('mock-couch');
let couchdbMock;

describe('TEST', function() {
    before(function() {
        couchdbMock = mockCouch.createServer();
        couchdbMock.listen(5985);
    });

  // unit tests

I got this error comming from the line of code: couchdbMock = mockCouch.createServer();:

TypeError: The super constructor to "inherits" must not be null or undefined
      at Object.exports.inherits (util.js:989:11)
      at Object.<anonymous> (node_modules/spdy/lib/spdy/connection.js:86:6)
      at require (internal/module.js:20:19)
      at Object.<anonymous> (node_modules/spdy/lib/spdy.js:20:19)
      at require (internal/module.js:20:19)
      at Object.<anonymous> (node_modules/restify/lib/server.js:13:12)
      at require (internal/module.js:20:19)
      at Object.createServer (node_modules/restify/lib/index.js:95:18)
      at node_modules/mock-couch/index.js:122:25
      at Object.createServer (node_modules/mock-couch/index.js:158:6)
      at Context.<anonymous> (server/dao/dao.couchdb.spec.js:18:33)

The weird thing is I get this error when I execute the test with Gulp or npm, but I do not get any errors when I use mocha commands directly.

View collation bug with array keys

Edit: The first two comments are more me trying to figure out what's happening. It's good reading, but I think I've come closer to nailing down part of the problem in the third post (as well as the referenced commit to my fork just above it)

Having a bit of a problem with the order some documents are spit out versus what they do on a real couch-db instance. It's going to not look super clear, but I hope to illustrate the issue I'm having. I can try to provide sample data tomorrow if necessary. Here is the map function:

function (doc) {
          if (doc.docType === 'foo') {
            key = [];
            key.push(doc._id);
            emit(key);
          }
          if (doc.docType === 'rel:bar') {
            key = [];
            key.push(doc.fooId);
            key.push(doc.barId);
            emit(key, { _id: doc.barId });
          }
          if ((doc.docType === 'rel:baz') && (doc.path.length === 2)) {
            key = [];
            key.push(doc.fooId);
            key.push(doc.barId);
            key.push(doc.path);
            emit(key, { _id: doc.bazId });
          }
 }

What this effectively does is spit out a three level hierarchy of some documents we have.

What I want, and what seems to work very consistently on our real instance, is:

foo
bar
baz

foo
bar
baz
bar
baz

etc.

However, in test, foo does not come first. Therefore when we try to construct this hierarchy in flat, descending order, it fails because there was no foo before bar, or baz. It appears the foos come last. I've tried messing with the descending order flags on a view with no luck.

Like I said, it works on our real instance, but now that it doesn't work in our unit tests I'm second guessing the whole thing :/

Fix in 'Add put/post for design docs #42' Wasn't Delivered into NPM Package

Hi there,
Can somebody publish the fix in 'Add put/post for design docs #42' to npm package?
The latest 0.1.6 version of npm package was published 6 month ago and doesn't have this fix.

Really look forward to seeing the npm package include this fix, rather than install from git for the specific version.

Thanks very much.

New databases created via HTTP don't get a changes list

After creating a new database via HTTP save_doc throws an exception when trying to save a new document into it.

TypeError: Cannot read property 'push' of undefined
    at Server.<anonymous> (.../node_modules/mock-couch/lib/save_doc.js:43:29)

I get this error when running my simple tests: The super constructor to inherits must not be null or undefined

This issue might not be related to mock-couch but I would appreciate some help. I am getting this error when running a simple test (let me know if you need the complete log):

TypeError: The super constructor to "inherits" must not be null or undefined
  at Object.inherits (util.js:971:11)
  at Object.<anonymous> (node_modules\mock-couch\node_modules\spdy\lib\spdy\connection.js:86:6)

This is my simple test (I have deleted some lines; mockedUsers is a simple JSON object):

(function mockConnection(module, require) {
  'use strict';

  const path = require('path');
  const root = path.resolve('./');
  const mockedUsers = require(`${root}/mocks/users`);

  const should = require('should');
  const mock = require('mock-couch');

  describe('Mock couch connection', function mockCouchConnection() {
    let Users;
    let mockCouch;
    const port = 5984;
    const uid = '[email protected]';

    beforeEach(function beforeEach() {
      mockCouch = mock.createServer({ keepAlive: false, });
      mockCouch.listen(port, function mockCouchListen() {
        // does nothing... yet!
      });
      // This creates a db for Mock Couch. The db is nothing but an array of objects.
      // If we provide an object with an _id property, it will use it. Otherwise, it will create a random one.
      Users = mockCouch.addDB('users', mockedUsers);
    });

    it(`user ${uid} must exist`, function userMustExists(done) {
      // TODO: validate that user actually exists.
      done();
    });
  });
}(module, require));

The error happens at this line mockCouch = mock.createServer({ keepAlive: false, });. I have run the code in different Nodejs versions, including 8.4.0, 8.8.0, 7.10.0.

Thanks!

Doesn't seem to work with yarn

Thanks! this is something I really needed today, but unfortunately couldn't make it work with yarn (not that I tried npm actually)

This is the error I am getting when I require the modue:

{ Error: Cannot find module './build/Release/DTraceProviderBindings'
    at Function.Module._resolveFilename (module.js:489:15)
    at Function.Module._load (module.js:439:25)
    at Module.require (module.js:517:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/z/dev/x/node_modules/bunyan/node_modules/dtrace-provider/dtrace-provider.js:18:23)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3) code: 'MODULE_NOT_FOUND' }
TAP version 13
# deploy
util.js:988
    throw new TypeError('The super constructor to "inherits" must not ' +
    ^

TypeError: The super constructor to "inherits" must not be null or undefined
    at Object.inherits (util.js:988:11)
    at Object.<anonymous> (/Users/z/dev/x/node_modules/spdy/lib/spdy/connection.js:86:6)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Module.require (module.js:517:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/z/dev/x/node_modules/spdy/lib/spdy.js:20:19)

Fix PUT db

After e67a594, you get {"statusCode":404,"error":"Not Found","message":"no_db_file"} when trying to PUT a new database.

There'd need to be some kind of request injection for the project to be able to catch this with a test.

Bulk attachment upload support

I need to fill CouchDB mock database with documents with attachments
Is there possible to upload attachment in batch mode?
Have methods addDB and addDoc support?
If not: have you plan/time to implement this feature?

Alternative: Is there possible to use couch-push with together with mock-couch?

Getting some errors with node v5.9.0

I seem to be getting the following errors when trying to create a new mockCouch server.

var mockCouch = require('mock-couch');
var couchdb = mockCouch.createServer();
{ [Error: Cannot find module './build/Release/DTraceProviderBindings'] code: 'MODULE_NOT_FOUND' }
{ [Error: Cannot find module './build/default/DTraceProviderBindings'] code: 'MODULE_NOT_FOUND' }
{ [Error: Cannot find module './build/Debug/DTraceProviderBindings'] code: 'MODULE_NOT_FOUND' }

Any ideas what would be causing this?

TypeError [ERR_INVALID_ARG_TYPE]: The "superCtor" argument must be of type Function. Received type undefined

let mockCouch = mock.createServer();
TypeError [ERR_INVALID_ARG_TYPE]: The "superCtor" argument must be of type Function. Received type undefined
at Object.inherits (util.js:1203:11)
at Object. (C:\Users\TEJINDERSINGH\Projects\isc-common-configstore\configstorev1\node_modules\mock-couch\node_modules\spdy\lib\spdy\connection.js:86:6)
at Module._compile (internal/modules/cjs/loader.js:702:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Module.require (internal/modules/cjs/loader.js:650:17)
at require (internal/modules/cjs/helpers.js:20:18)

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.