├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── index.js ├── package.json └── test ├── helpers └── single-instance.js ├── initialize.js ├── multiple-instances ├── instance1.js └── instance2.js ├── not-duplicated.js └── port-offset.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | .db-test-* 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | addons: 4 | apt: 5 | packages: 6 | - rethinkdb 7 | sources: 8 | - sourceline: 'deb http://download.rethinkdb.com/apt precise main' 9 | 10 | node_js: 11 | - 6 12 | - 8 13 | 14 | env: 15 | - AVA_VERSION=0.15.2 16 | - AVA_VERSION=0.21.0 17 | 18 | before_script: 19 | - npm install ava@$AVA_VERSION 20 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | [ava-rethinkdb]: https://github.com/rrdelaney/ava-rethinkdb 3 | [Travis CI]: https://travis-ci.org/ 4 | 5 | ## [Unreleased] 6 | [Unreleased]: https://github.com/rrdelaney/ava-rethinkdb/compare/v0.1.4...HEAD 7 | 8 | ### Added 9 | 10 | - `engines.node = ">=6.0.0"` to formally note which versions of Node are supported. 11 | 12 | ## [0.1.4] - 2017-08-01 13 | 14 | [Code][0.1.4] ([Diff][0.1.4-diff]) | [Changelog][0.1.4-log] 15 | 16 | Updates and Bugfixes 17 | 18 | ### Added 19 | 20 | - [Travis CI][] configuration (#5) 21 | - Tests running [ava-rethinkdb][] from multiple files and directories (#7) 22 | 23 | ### Modified 24 | 25 | - Updated AVA to v0.21.0 (#5) 26 | - Ensured data directories are unique to prevent collisions (#6) 27 | 28 | [0.1.4]: https://github.com/rrdelaney/ava-rethinkdb/tree/v0.1.4 29 | [0.1.4-diff]: https://github.com/rrdelaney/ava-rethinkdb/compare/141c3414bfd8f3b5f73b54e2630d7b25465c2fd8...v0.1.4 30 | [0.1.4-log]: https://github.com/rrdelaney/ava-rethinkdb/blob/master/CHANGELOG.md#014---2017-08-01 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Ryan Delaney 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Testing utilities for RethinkDB and AVA 2 | 3 | [![ava-rethinkdb on NPM](https://img.shields.io/npm/v/ava-rethinkdb.svg)](https://npm.im/ava-rethinkdb) 4 | [![Build Status](https://travis-ci.org/rrdelaney/ava-rethinkdb.svg?branch=master)](https://travis-ci.org/rrdelaney/ava-rethinkdb) 5 | ![See package.json for Node.js Support](https://img.shields.io/node/v/ava-rethinkdb.svg?label=Runs%20on%20Node.js) 6 | 7 | ``` 8 | npm install --save-dev ava-rethinkdb 9 | ``` 10 | 11 | This is a hacky way of using the NodeJS RethinkDB and AVA together. It uses 12 | undocumented features of the RethinkDB driver, and should be considered 13 | experimental. 14 | 15 | # Basic Testing 16 | 17 | By running `init` and `cleanup` you get a fully managed database instance for 18 | your tests! Everything is cleaned up at the end, so there's no leftover fixtures 19 | 20 | ```js 21 | import test from 'ava' 22 | import { init, cleanup } from 'ava-rethinkdb' 23 | 24 | test.before(init()) 25 | test.after.always(cleanup) 26 | 27 | test('I should have a RethinkDB instance', async t => { 28 | let connection = await r.connect({}) 29 | 30 | await r.dbCreate('MyDatabase') 31 | }) 32 | ``` 33 | 34 | # Seeding 35 | 36 | The problem is that if you want to do multiple tests they all happen at the same 37 | time due to the magic of AVA. Luckily you can seed the database with a simple 38 | JSON structure 39 | 40 | ```js 41 | import test from 'ava' 42 | import { init, cleanup } from 'ava-rethinkdb' 43 | 44 | const TEST_DATA = { 45 | my_database: { // The top level is the database to create 46 | my_table: [ // Next is a table in the database. This holds an array of documents to insert 47 | { name: 'A', value: 1}, 48 | { name: 'B', value: 2} 49 | ], 50 | users: [ 51 | { username: 'daniel', email: 'wry@gmail.com' }, 52 | { username: 'heya', email: 'ayeh@outlook.com' } 53 | ] 54 | } 55 | } 56 | 57 | test.before(init(TEST_DATA)) 58 | test.after.always(cleanup) 59 | 60 | test('These documents should exist', async t => { 61 | let conn = await r.connect({ db: 'my_database' }) 62 | let results = await r.table('my_table').run(conn) 63 | let data = await results.toArray() 64 | 65 | console.log(data) 66 | t.truthy(data) 67 | }) 68 | ``` 69 | 70 | # Different Database Instances 71 | 72 | This is where the magic really is. Every single test file is given its own 73 | RethinkDB instance. This makes it perfect for integration tests against 74 | endpoints, because now they can all be used in parallel! The magic comes 75 | from modifying the default port the driver looks at, making it different 76 | in each process, then spinning up a RethinkDB instance at that port. 77 | Check out the `test` directory for a good example. 78 | 79 | ```js 80 | // app.js 81 | 82 | const express = require('express') 83 | const r = require('rethinkdb') 84 | 85 | let app = express() 86 | 87 | app.get('/users', (req, res) => { 88 | r.connect({ db: 'app' }) 89 | .then(conn => r.table('users').run(conn)) 90 | .then(results => results.toArray()) 91 | .then(users => res.status(200).send({ users })) 92 | .catch(e => res.status(500).send(e)) 93 | }) 94 | 95 | module.exports = { app } 96 | ``` 97 | 98 | ```js 99 | // test/integration/users-test-1.js 100 | import test from 'ava' 101 | import request from 'supertest-as-promised' 102 | import { init, cleanup } from 'ava-rethinkdb' 103 | 104 | import { app } from '../../app.js' 105 | 106 | const TEST_DATA = { 107 | app: { 108 | users: [ 109 | { name: 'UserA' }, 110 | { name: 'UserB' } 111 | ] 112 | } 113 | } 114 | 115 | test('Users should be returned from /users', t => { 116 | return request(app) 117 | .get('/users') 118 | .expect(200) 119 | }) 120 | ``` 121 | 122 | ```js 123 | // test/integration/users-test-2.js 124 | import test from 'ava' 125 | import request from 'supertest-as-promised' 126 | import { init, cleanup } from 'ava-rethinkdb' 127 | 128 | import { app } from '../../app.js' 129 | 130 | const TEST_DATA = { 131 | app: { 132 | users: [ 133 | { name: 'UserC' }, 134 | { name: 'UserD' } 135 | ] 136 | } 137 | } 138 | 139 | test('Different users should be returned from /users', t => { 140 | return request(app) 141 | .get('/users') 142 | .expect(200) 143 | }) 144 | ``` 145 | 146 | The `TEST_DATA` contained in each file creates a new database to be used for 147 | each file! 148 | 149 | # Debugging 150 | 151 | To view the output from all the server logs, set the environment variable 152 | `AVA_RETHINKDB_DEBUG=on` 153 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const { spawn } = require('child_process') 4 | const rimraf = require('rimraf') 5 | const mkdirp = require('mkdirp') 6 | 7 | const getPortOffset = pid => { 8 | const maxOffset = 65535 - 28015 9 | return pid - (Math.floor(pid / maxOffset) * maxOffset) 10 | } 11 | 12 | const getStorageDir = (cwd, pid) => `${cwd}/.db-test-${pid}` 13 | 14 | let rethink 15 | 16 | module.exports.init = initialData => t => new Promise((resolve, reject) => { 17 | const offset = getPortOffset(process.pid) 18 | const port = 28015 + offset 19 | const r = require('rethinkdb') 20 | const dir = getStorageDir(process.cwd(), process.pid) 21 | 22 | r.net.Connection.prototype.DEFAULT_PORT = port 23 | mkdirp.sync(dir) 24 | rethink = spawn('rethinkdb', ['-o', `${offset}`, '-d', `${dir}/${port}`]) 25 | 26 | if (process.env.AVA_RETHINKDB_DEBUG) { 27 | console.error(`==> Process ${process.pid} spawning RethinkDB server on port ${port}...`) 28 | } 29 | 30 | rethink.stdout.on('data', chunk => { 31 | if (chunk.toString('utf8').startsWith('Listening for client driver connections')) { 32 | if (initialData) { 33 | importData().then(() => resolve(port)) 34 | } else { 35 | resolve(port) 36 | } 37 | 38 | if (process.env.AVA_RETHINKDB_DEBUG) { 39 | console.error(`==> Process ${process.pid} RethinkDB server booted!`) 40 | } 41 | } 42 | 43 | if (process.env.AVA_RETHINKDB_DEBUG) { 44 | console.error(chunk.toString()) 45 | } 46 | }) 47 | 48 | if (process.env.AVA_RETHINKDB_DEBUG) { 49 | rethink.stderr.on('data', chunk => console.error(chunk.toString())) 50 | } 51 | 52 | rethink.on('error', reject) 53 | 54 | function importData () { 55 | let conn 56 | return r.connect({}).then(_ => { conn = _ }) 57 | .then(() => Promise.all( 58 | Object.keys(initialData).map(db => db !== 'test' && r.dbCreate(db).run(conn)) 59 | )) 60 | .then(() => Promise.all( 61 | collectTables(initialData).map(([db, table]) => r.db(db).tableCreate(table).run(conn)) 62 | )) 63 | .then(() => Promise.all( 64 | collectDocuments(initialData).map(([db, table, doc]) => r.db(db).table(table).insert(doc).run(conn)) 65 | )) 66 | } 67 | }) 68 | 69 | module.exports.cleanup = () => { 70 | if (process.env.AVA_RETHINKDB_DEBUG) { 71 | console.error(`==> Process ${process.pid} killing RethinkDB server...`) 72 | } 73 | 74 | rethink.kill() 75 | 76 | if (process.env.AVA_RETHINKDB_DEBUG) { 77 | console.error(`==> Process ${process.pid} killed RethinkDB server!`) 78 | } 79 | 80 | rimraf.sync(getStorageDir(process.cwd(), process.pid)) 81 | } 82 | 83 | function collectTables (data) { 84 | return Object.keys(data) 85 | .map(db => Object.keys(data[db]).map(table => [db, table])) 86 | .reduce((a, b) => a.concat(b)) 87 | } 88 | 89 | function collectDocuments (data) { 90 | return Object.keys(data) 91 | .map(db => Object.keys(data[db]).map(table => data[db][table].map(doc => [db, table, doc]))) 92 | .reduce((a, b) => a.concat(b)) 93 | .reduce((a, b) => a.concat(b)) 94 | } 95 | 96 | module.exports.getPortOffset = getPortOffset 97 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ava-rethinkdb", 3 | "version": "0.1.4", 4 | "description": "RethinkDB helpers for AVA", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "snazzy && ava" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/rrdelaney/ava-rethinkdb" 12 | }, 13 | "keywords": [ 14 | "ava", 15 | "rethinkdb" 16 | ], 17 | "author": "Ryan Delaney ", 18 | "license": "MIT", 19 | "bugs": { 20 | "url": "https://github.com/rrdelaney/ava-rethinkdb/issues" 21 | }, 22 | "homepage": "https://github.com/rrdelaney/ava-rethinkdb", 23 | "engines": { 24 | "node": ">=6.0.0" 25 | }, 26 | "peerDependencies": { 27 | "ava": "^0.21.0 || <= 0.21.0" 28 | }, 29 | "devDependencies": { 30 | "babel-eslint": "^7.2.3", 31 | "ava": "^0.21.0", 32 | "rethinkdb": "^2.3.2", 33 | "snazzy": "^4.0.0", 34 | "standard": "^7.1.2" 35 | }, 36 | "dependencies": { 37 | "mkdirp": "^0.5.1", 38 | "rimraf": "^2.5.2" 39 | }, 40 | "standard": { 41 | "parser": "babel-eslint" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /test/helpers/single-instance.js: -------------------------------------------------------------------------------- 1 | import test from 'ava' 2 | import r from 'rethinkdb' 3 | import { init, cleanup } from '../../' 4 | 5 | test.before('Initialize DB', init()) 6 | test.after.always('Teardown DB', cleanup) 7 | 8 | test('connects to database', async t => { 9 | let connection = await r.connect({}) 10 | t.true(connection.open) 11 | }) 12 | -------------------------------------------------------------------------------- /test/initialize.js: -------------------------------------------------------------------------------- 1 | import test from 'ava' 2 | import r from 'rethinkdb' 3 | import { init, cleanup } from '../' 4 | 5 | const TEST_DATA = { 6 | fp: { 7 | users: [ 8 | { name: 'UserA' }, 9 | { name: 'UserB' } 10 | ] 11 | }, 12 | meta: { 13 | data: [ 14 | { something: true } 15 | ] 16 | }, 17 | test: { 18 | data: [ 19 | { something: true } 20 | ] 21 | } 22 | } 23 | 24 | test.before('Initialize DB', init(TEST_DATA)) 25 | test.after.always('Teardown DB', cleanup) 26 | 27 | async function shouldDatabaseExist (t, input, expected) { 28 | let conn = await r.connect({}) 29 | let databases = await r.dbList().run(conn) 30 | 31 | if (expected) { 32 | t.true(databases.indexOf(input) !== -1) 33 | } else { 34 | t.true(databases.indexOf(input) === -1) 35 | } 36 | } 37 | 38 | shouldDatabaseExist.title = (_, input, expected) => `Database ${input} should${expected ? '' : "n't"} exist` 39 | 40 | test(shouldDatabaseExist, 'fp', true) 41 | test(shouldDatabaseExist, 'meta', true) 42 | test(shouldDatabaseExist, 'test', true) 43 | test(shouldDatabaseExist, 'sugar', false) 44 | 45 | async function shouldUserExist (t, name, expected) { 46 | let conn = await r.connect({ db: 'fp' }) 47 | let [ user ] = await r.table('users').filter({ name }).run(conn).then(_ => _.toArray()) 48 | 49 | if (expected) { 50 | t.truthy(user, `${name} should exist`) 51 | } else { 52 | t.falsy(user, `${name} should not exist`) 53 | } 54 | } 55 | 56 | shouldUserExist.title = (_, input, expected) => `${input} should${expected ? '' : "n't"} exist` 57 | 58 | test(shouldUserExist, 'UserA', true) 59 | test(shouldUserExist, 'UserB', true) 60 | test(shouldUserExist, 'UserC', false) 61 | test(shouldUserExist, 'UserD', false) 62 | -------------------------------------------------------------------------------- /test/multiple-instances/instance1.js: -------------------------------------------------------------------------------- 1 | import test from 'ava' 2 | import r from 'rethinkdb' 3 | import { init, cleanup } from '../../' 4 | 5 | test.before('Initialize DB', init()) 6 | test.after.always('Teardown DB', cleanup) 7 | 8 | test('connects to database', async t => { 9 | let connection = await r.connect({}) 10 | t.true(connection.open) 11 | }) 12 | -------------------------------------------------------------------------------- /test/multiple-instances/instance2.js: -------------------------------------------------------------------------------- 1 | import test from 'ava' 2 | import r from 'rethinkdb' 3 | import { init, cleanup } from '../../' 4 | 5 | test.before('Initialize DB', init()) 6 | test.after.always('Teardown DB', cleanup) 7 | 8 | test('connects to database', async t => { 9 | let connection = await r.connect({}) 10 | t.true(connection.open) 11 | }) 12 | -------------------------------------------------------------------------------- /test/not-duplicated.js: -------------------------------------------------------------------------------- 1 | import test from 'ava' 2 | import r from 'rethinkdb' 3 | import { init, cleanup } from '../' 4 | 5 | const TEST_DATA = { 6 | fp: { 7 | users: [ 8 | { name: 'UserC' }, 9 | { name: 'UserD' } 10 | ] 11 | } 12 | } 13 | 14 | test.before('Initialize DB', init(TEST_DATA)) 15 | test.after.always('Teardown DB', cleanup) 16 | 17 | async function shouldDatabaseExist (t, input, expected) { 18 | let conn = await r.connect({}) 19 | let databases = await r.dbList().run(conn) 20 | 21 | if (expected) { 22 | t.true(databases.indexOf(input) !== -1) 23 | } else { 24 | t.true(databases.indexOf(input) === -1) 25 | } 26 | } 27 | 28 | shouldDatabaseExist.title = (_, input, expected) => `Database ${input} should${expected ? '' : "n't"} exist` 29 | 30 | test(shouldDatabaseExist, 'fp', true) 31 | test(shouldDatabaseExist, 'meta', false) 32 | test(shouldDatabaseExist, 'sugar', false) 33 | 34 | async function shouldUserExist (t, name, expected) { 35 | let conn = await r.connect({ db: 'fp' }) 36 | let [ user ] = await r.table('users').filter({ name }).run(conn).then(_ => _.toArray()) 37 | 38 | if (expected) { 39 | t.truthy(user, `${name} should exist`) 40 | } else { 41 | t.falsy(user, `${name} should not exist`) 42 | } 43 | } 44 | 45 | shouldUserExist.title = (_, input, expected) => `${input} should${expected ? '' : "n't"} exist` 46 | 47 | test(shouldUserExist, 'UserA', false) 48 | test(shouldUserExist, 'UserB', false) 49 | test(shouldUserExist, 'UserC', true) 50 | test(shouldUserExist, 'UserD', true) 51 | -------------------------------------------------------------------------------- /test/port-offset.js: -------------------------------------------------------------------------------- 1 | import test from 'ava' 2 | import { getPortOffset } from '../' 3 | 4 | test('port offsets shouldn\'t exceed the maximum offset', async t => { 5 | const maxOffset = 65535 - 28015 6 | 7 | t.true(getPortOffset(0) <= maxOffset) 8 | t.true(getPortOffset(10) <= maxOffset) 9 | t.true(getPortOffset(maxOffset / 2) <= maxOffset) 10 | t.true(getPortOffset(maxOffset - 1) <= maxOffset) 11 | t.true(getPortOffset(maxOffset + 1) <= maxOffset) 12 | t.true(getPortOffset(maxOffset) <= maxOffset) 13 | t.true(getPortOffset(maxOffset * 2) <= maxOffset) 14 | t.true(getPortOffset(maxOffset * 2.5) <= maxOffset) 15 | }) 16 | --------------------------------------------------------------------------------