UNPKG

2.82 kBJavaScriptView Raw
1'use strict'
2
3var request = require('request'),
4 check = require('../check'),
5 async = require('async'),
6 stringify = require('../stringify'),
7 normalizePath = require('path').posix.normalize,
8 parse = require('url').parse,
9 format = require('url').format
10
11/**
12 * @class
13 */
14function Case() {
15 /** @member {string} */
16 this.name = ''
17
18 /** @member {boolean} */
19 this.skip = false
20
21 /** @member {Obj} */
22 this.post = null
23
24 /** @member {string} */
25 this.postUrl = ''
26
27 /* @member {Obj} */
28 this.out = null
29
30 /** @member {number} */
31 this.statusCode = 0
32
33 /** @member {Find[]} */
34 this.finds = []
35}
36
37/**
38 * Run the test case
39 * @param {Object} options
40 * @param {Obejct} options.db
41 * @param {Function} options.it
42 * @param {string} options.baseUrl
43 * @param {Object} options.context
44 * @param {boolean} options.strict
45 * @param {string[]} options.ignoredFindKeys
46 * @param {Buffer} [options.ca]
47 * @param {function(Case,*)} [options.onPost]
48 * @param {function(Case,*)} [options.onOut]
49 * @param {function(Case,Find)} [options.onFind]
50 * @param {string} testName
51 */
52Case.prototype.execute = function (options, testName) {
53 var that = this,
54 it = this.skip ? options.it.skip : options.it
55
56 it(this.name, function (done) {
57 // Prepare context
58 options.context.prev = {
59 post: options.context.post,
60 out: options.context.out
61 }
62 delete options.context.post
63 delete options.context.out
64
65 var post = that.post.execute(options.context, '<post>')
66 options.context.post = post
67 if (options.onPost) {
68 options.onPost(that, post)
69 }
70
71 request({
72 url: normalizeUrl(options.baseUrl + (that.postUrl || testName)),
73 method: 'POST',
74 json: post,
75 agentOptions: {
76 ca: options.ca
77 }
78 }, function (err, res, out) {
79 var expected
80 if (err) {
81 return done(err)
82 }
83 options.context.out = out
84 expected = that.out.execute(options.context, '<out>')
85
86 try {
87 res.statusCode.should.be.equal(that.statusCode)
88 check(out, expected, options.strict)
89 if (options.onOut) {
90 options.onOut(that, out)
91 }
92 } catch (e) {
93 console.log('\n-----\n' +
94 'Request details:\n' +
95 '\x1b[1;32mInput:\x1b[0m\n' +
96 stringify(post, true) + '\n' +
97 '\x1b[1;32mOutput:\x1b[0m\n' +
98 stringify(out, true, e.path) + '\n' +
99 '\x1b[1;32mExpected:\x1b[0m\n' +
100 stringify(expected, true, e.path) + '\n' +
101 '-----\n')
102 throw e
103 }
104 async.each(that.finds, function (find, done) {
105 if (options.onFind) {
106 options.onFind(that, find)
107 }
108 find.execute(options, done)
109 }, done)
110 })
111 })
112}
113
114module.exports = Case
115
116function normalizeUrl(url) {
117 var parsed = parse(url)
118 parsed.pathname = normalizePath(parsed.pathname)
119 return format(parsed)
120}
\No newline at end of file