1 |
|
2 | debug = require('debug')('fbp-spec:expectation')
|
3 | chai = require 'chai'
|
4 | JSONPath = require 'JSONPath'
|
5 |
|
6 | common = require './common'
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | operators =
|
13 | 'type': (actual, expected) ->
|
14 | chai.expect(actual).to.be.a expected
|
15 | 'equals': (actual, expected) ->
|
16 | chai.expect(actual).to.eql expected
|
17 | 'above': (actual, expected) ->
|
18 | chai.expect(actual).to.be.above expected
|
19 | 'below': (actual, expected) ->
|
20 | chai.expect(actual).to.be.below expected
|
21 | 'haveKeys': (actual, expected) ->
|
22 | chai.expect(actual).to.have.keys expected
|
23 | 'includeKeys': (actual, expected) ->
|
24 | chai.expect(actual).to.include.keys expected
|
25 | 'contains': (actual, expected) ->
|
26 | chai.expect(actual).to.contain expected
|
27 | 'noterror': (actual, expected) ->
|
28 | throw actual if actual?.message
|
29 |
|
30 |
|
31 |
|
32 | findOperator = (expectation) ->
|
33 | for opname, expectValue of expectation
|
34 | continue if opname is 'path'
|
35 | op = operators[opname]
|
36 | if op
|
37 | predicate = (data) ->
|
38 | op data, expectValue
|
39 | predicate.toString = () -> return "#{opname} #{expectValue}"
|
40 | return predicate
|
41 |
|
42 | throw new Error "fbp-spec: No operator matching #{Object.keys(expectation)}. Available: #{Object.keys(operators)}"
|
43 |
|
44 | extractMatches = (expectation, data) ->
|
45 | options =
|
46 | flatten: true
|
47 | if expectation.path
|
48 | debug 'extracting JSONPath from', expectation.path, data
|
49 | matches = JSONPath.eval data, expectation.path, options
|
50 | throw new Error("expected JSONPath '#{expectation.path}' to match data in #{JSON.stringify(data)}") if not matches.length
|
51 | else
|
52 | matches = [ data ]
|
53 | debug 'matching against', matches
|
54 | return matches
|
55 |
|
56 | exports.expect = (expects, portsdata) ->
|
57 |
|
58 |
|
59 | expects = [ expects ] if not common.isArray expects
|
60 |
|
61 | for e in expects
|
62 |
|
63 | for port, exp of e
|
64 |
|
65 |
|
66 | expectations = exp
|
67 | expectations = [ expectations ] if not common.isArray expectations
|
68 | for expectation in expectations
|
69 | debug 'checking port for expectation', port, expectation
|
70 | data = portsdata[port]
|
71 | if typeof data == 'undefined'
|
72 | throw new Error "No data received on port #{port}"
|
73 | predicate = findOperator expectation
|
74 | matches = extractMatches expectation, data
|
75 | for m in matches
|
76 | debug 'checking against predicate', m, predicate.toString()
|
77 | predicate m
|
78 |
|
79 | exports.noError = (maybeErr) ->
|
80 | chai.expect(maybeErr).to.not.exist
|
81 |
|