Skip to content

Commit

Permalink
Record a .nock file for each test file
Browse files Browse the repository at this point in the history
  • Loading branch information
exogen committed Nov 14, 2017
1 parent 6ecb300 commit 94efd9a
Show file tree
Hide file tree
Showing 22 changed files with 894 additions and 429 deletions.
10 changes: 10 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"presets": [
["env", {
"targets": {
"node": "6"
}
}]
],
"plugins": ["transform-object-rest-spread"]
}
4 changes: 4 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
/.nyc_output
/coverage
/lib
/fixtures
!.eslintrc.js
14 changes: 4 additions & 10 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
module.exports = {
extends: ["standard", "prettier", "prettier/standard"],
extends: ['standard', 'prettier', 'prettier/standard'],
env: {
es6: true,
node: true
},
plugins: ["prettier"],
plugins: ['prettier'],
rules: {
"prettier/prettier": [
"warn",
{
singleQuote: true,
semi: false
}
]
'prettier/prettier': 'warn'
}
};
}
3 changes: 2 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/lib
/.nyc_output
/coverage
/lib
/fixtures
43 changes: 21 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
# ava-vcr
# ava-nock

```console
$ npm install ava-nock --save-dev
```

```console
$ yarn add ava-nock --dev
```

## Usage

## Modes

| VCR_MODE | Network requests? | Read fixtures? | Write fixtures? |
| :------: | :---------------------: | :---------------------: | :---------------------: |
| live | :ballot_box_with_check: | | |
| preview | :ballot_box_with_check: | :ballot_box_with_check: | |
| record | :ballot_box_with_check: | | :ballot_box_with_check: |
| cache | :ballot_box_with_check: | :ballot_box_with_check: | :ballot_box_with_check: |
| play | | :ballot_box_with_check: | |
| NOCK_MODE | Network requests? | Read fixtures? | Write fixtures? |
| :-------: | :---------------------: | :---------------------: | :---------------------: |
| live | :ballot_box_with_check: | | |
| preview | :ballot_box_with_check: | :ballot_box_with_check: | |
| record | :ballot_box_with_check: | | :ballot_box_with_check: |
| cache | :ballot_box_with_check: | :ballot_box_with_check: | :ballot_box_with_check: |
| play | | :ballot_box_with_check: | |

* **live** will disable replay and recording completely. All requests will hit
the network like normal.
Expand All @@ -17,23 +27,12 @@
and want to make sure they pass before recording them.
* **record** will ignore existing fixtures and record new ones. All requests
will hit the network and be recorded. Note that this might leave you with
fixtures that are no longer used and should be cleaned up.
fixtures that are no longer used and should be cleaned up – you may wish to
delete your fixture directory before running in this mode.
* **cache** will replay existing fixtures and record any other requests from the
network. This is useful if you have written new tests and verified that they
are correct and ready to be recorded.
* **play** will replay existing fixtures and never hit the network. Any requests
that do not have a fixture will result in an error. This is the default
behavior. It is useful if you are done writing tests and want to verify that
they all pass (like you’d do in CI, a pre-commit hook, etc.).

## Configuration

### fixtureDir

```ts
string | (RequestData) => string
```

### requestKey

### requestFixture
they all pass. Use this mode in CI environments.
26 changes: 0 additions & 26 deletions fixtures/f57d63c28c99037c8082337a31b4a9415e9e0f0b.json

This file was deleted.

47 changes: 34 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,43 +1,64 @@
{
"name": "ava-vcr",
"name": "ava-nock",
"version": "0.0.0",
"description": "",
"keywords": ["testing", "http", "mocking", "vcr", "record", "playback"],
"keywords": [
"ava",
"testing",
"http",
"nock",
"mocking",
"vcr",
"record",
"playback"
],
"author": "Brian Beck <[email protected]>",
"license": "MIT",
"main": "index.js",
"main": "lib/index.js",
"files": ["lib", "yarn.lock"],
"scripts": {
"build": "npm run build:lib",
"build:lib": "babel --out-dir lib src",
"build:lib": "babel src --out-dir lib --ignore \"**/*.test.js\"",
"clean": "rimraf lib",
"format": "npm run format:js && npm run format:other",
"format:js": "npm run lint:fix || true",
"format:other": "prettier --write \"**/*.{json,md}\"",
"format:other": "prettier --write \"*.md\" \"**/*.json\"",
"lint": "eslint .",
"lint:fix": "eslint --fix .",
"prepare": "npm run clean && npm run build",
"test": "npm run lint && npm run test:coverage",
"test:cache": "VCR_MODE=cache ava",
"test:cache": "NOCK_MODE=cache ava",
"test:coverage": "nyc ava",
"test:live": "VCR_MODE=live ava",
"test:live": "NOCK_MODE=live ava",
"test:only": "ava",
"test:play": "VCR_MODE=play ava",
"test:preview": "VCR_MODE=preview ava",
"test:record": "VCR_MODE=record ava"
"test:play": "NOCK_MODE=play ava",
"test:preview": "NOCK_MODE=preview ava",
"test:record": "NOCK_MODE=record ava"
},
"ava": {
"require": ["./src/index"],
"require": ["babel-register"],
"files": ["src/**/*.test.js", "test"]
},
"prettier": {
"semi": false,
"singleQuote": true
},
"peerDependencies": {
"ava": "^0.23.0"
},
"dependencies": {
"debug": "^3.1.0",
"fs-extra": "^4.0.2",
"http-proxy": "^1.16.2",
"json-parse-better-errors": "^1.0.1",
"json-stable-stringify": "^1.0.1",
"nock": "^9.1.0",
"object-hash": "^1.2.0",
"replay": "^2.1.4",
"request": "^2.83.0",
"temp-write": "^3.3.0"
"temp-write": "^3.3.0",
"tempy": "^0.2.1",
"uuid": "^3.1.0"
},
"devDependencies": {
"ava": "^0.23.0",
Expand All @@ -46,7 +67,7 @@
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-register": "^6.26.0",
"eslint": "^4.10.0",
"eslint": "^4.11.0",
"eslint-config-prettier": "^2.7.0",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.8.0",
Expand Down
60 changes: 60 additions & 0 deletions src/encoding.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import zlib from 'zlib'
import createLogger from 'debug'

const debug = createLogger('ava-nock:encoding')
const decoders = new Map([['gzip', zlib.gunzip], ['deflate', zlib.inflate]])

function findLastEncoding(headers) {
const reversedHeaders = headers.slice().reverse()
const index = reversedHeaders.findIndex(
(header, index) => header.toLowerCase() === 'content-encoding' && index % 2
)
return index === -1 ? -1 : headers.length - index - 1
}

export function decodeResponse(call) {
if (Array.isArray(call.response)) {
// Reverse the headers array, because Content-Encoding can appear multiple
// times and we need to decode the response in the opposite order that it
// was encoded.
const encodingIndex = findLastEncoding(call.rawHeaders)
if (encodingIndex !== -1) {
const encodingValue = call.rawHeaders[encodingIndex + 1]
if (decoders.has(encodingValue)) {
debug(`Found encoding: ${encodingValue}, attempting to decode.`)
const decode = decoders.get(encodingValue)
const buffer = Buffer.concat(
call.response.map(hexString => Buffer.from(hexString, 'hex'))
)
return new Promise((resolve, reject) => {
decode(buffer, (err, outputBuffer) => {
if (err) {
reject(err)
} else {
// Remove the Content-Encoding that was processed.
const headers = call.rawHeaders.slice()
headers.splice(encodingIndex, 2)
const hasEncoding = findLastEncoding(headers) !== -1
// If there's another Content-Encoding, leave the response as an
// array of hex-encoded buffers and call this function again.
// Otherwise, convert it to a string.
const outputCall = {
...call,
rawHeaders: headers,
response: hasEncoding
? [outputBuffer.toString('hex')]
: outputBuffer.toString()
}
if (hasEncoding) {
decodeResponse(outputCall).then(resolve, reject)
} else {
resolve(outputCall)
}
}
})
})
}
}
}
return Promise.resolve(call)
}
45 changes: 0 additions & 45 deletions src/filter.js

This file was deleted.

39 changes: 39 additions & 0 deletions src/fixtures.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import fs from 'fs'
import path from 'path'
import parseJSON from 'json-parse-better-errors'
import stringifyJSON from 'json-stable-stringify'
import { ensureDir, move } from 'fs-extra'
import tempWrite from 'temp-write'
import createLogger from 'debug'

const debug = createLogger('ava-nock:fixtures')

export function readFixture(filename) {
filename = path.relative(process.cwd(), filename)
return new Promise((resolve, reject) => {
debug(`Reading fixture: ${filename}`)
fs.readFile(filename, 'utf8', (err, data) => {
if (err) {
reject(err)
} else {
resolve(parseJSON(data))
}
})
})
}

export function writeFixture(filename, data, options) {
filename = path.relative(process.cwd(), filename)
const output = stringifyJSON(data, { space: 2 }) + '\n'
debug(`Writing fixture to temporary file.`)
return tempWrite(output)
.then(tempFile => {
const dirname = path.dirname(filename)
debug(`Ensuring fixture directory exists: ${dirname}`)
return ensureDir(dirname).then(() => tempFile)
})
.then(tempFile => {
debug(`Moving fixture into place: ${filename}`)
return move(tempFile, filename, options)
})
}
Loading

0 comments on commit 94efd9a

Please sign in to comment.