UNPKG

2.73 kBtext/coffeescriptView Raw
1
2debug = require('debug')('fbp-spec:expectation')
3chai = require 'chai'
4JSONPath = require 'JSONPath'
5
6common = require './common'
7
8## A library of standard expectation operators
9#
10# Should throw AssertionError if expectation is violated,
11# with details about the issue
12operators =
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# returns a predicate function
31# (data) ->
32findOperator = (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
44extractMatches = (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
56exports.expect = (expects, portsdata) ->
57
58 # can have one or more set of expectations of messages
59 expects = [ expects ] if not common.isArray expects
60
61 for e in expects
62 # each message expectation can match on ports
63 for port, exp of e
64
65 # for each matching port, there can be one or more assertions on the value
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
79exports.noError = (maybeErr) ->
80 chai.expect(maybeErr).to.not.exist
81