File size: 12,651 Bytes
5fae594
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/*
   Assertion helpers for testing the interface exposed as window.oboe
   
   These assertions mostly rely on everything that sits behind there as well (so they aren't
   true unit testing assertions, more of a suite of component testing helpers).

 */

function givenAnOboeInstance(jsonFileName) {

   function OboeAsserter() {

      var asserter = this,
          oboeInstance,

          expectingErrors = false,
          
          givenErrors = [],
          
          completeJson, // assigned in the requestCompleteCallback

          spiedCallback; //erk: only one callback stub per Asserter right now :-s
          
          
      jsonFileName = jsonFileName || 'invalid://xhr_should_be_stubbed.org/if/not/thats/bad';
       
      function requestComplete(completeJsonFromJsonCompleteCall){
         completeJson = completeJsonFromJsonCompleteCall;
                 
         asserter.isComplete = true;
      } 
       
      oboeInstance = oboe( jsonFileName 
                         ).done(requestComplete);      
                              
      oboeInstance.fail(function(e) {
         // Unless set up to expect them, the test isn't expecting errors.
         // Fail the test on getting an error:
         expect(expectingErrors).toBeTruthy();
      });

      // designed for use with jasmine's waitsFor, ie:
      //    waitsFor(asserter.toComplete())
      this.toComplete = function() {
         return function() {
            return asserter.isComplete;
         }
      }
            
      this.andWeAreListeningForNodes = function(pattern, callback, scope) {
         spiedCallback = callback ? sinon.spy(callback) : sinon.stub();
      
         oboeInstance.node(pattern, argumentClone(spiedCallback), scope);
         return this;
      };

      this.andWeAreListeningForPaths = function(pattern, callback, scope) {
         spiedCallback = callback ? sinon.spy(callback) : sinon.stub();      
      
         oboeInstance.path(pattern, argumentClone(spiedCallback), scope);
         return this;
      };
      
      this.andWeHaveAFaultyCallbackListeningFor = function(pattern) {
         spiedCallback = sinon.stub().throws();      
      
         oboeInstance.path(pattern, argumentClone(spiedCallback));
         return this;
      };      
      
      this.andWeAreExpectingSomeErrors = function() {
         expectingErrors = true;
      
         spiedCallback = sinon.stub();
         
         oboeInstance.fail(argumentClone(spiedCallback));
         return this;
      };
      
      this.andWeAbortTheRequest = function() {    
         oboeInstance.abort();
         return this;
      };      
      
      this.whenGivenInput = function(json) {
         if( typeof json != 'string' ) {
            json = JSON.stringify(json);
         }
        
         // giving the content one char at a time makes debugging easier when
         // wanting to know how much has been written into the stream.
         for( var i = 0; i< json.length; i++) {
            oboeInstance.emit(STREAM_DATA, json.charAt(i) ); 
         }

         return this;
      };
      
      this.whenInputFinishes = function() {
         
         oboeInstance.emit(STREAM_END);                  

         return this;         
      };

      function noop(){}
      
      /**
       * Assert any number of conditions were met on the spied callback
       */
      this.thenTheInstance = function( /* ... functions ... */ ){
      
         if( givenErrors.length > 0 ) {
            throw new Error('error found during previous stages\n' + givenErrors[0].stack);
         }      
      
         for (var i = 0; i < arguments.length; i++) {
            var assertion = arguments[i];
            assertion.testAgainst(spiedCallback, oboeInstance, completeJson);
         }

         return this;
      };
      
      /** sinon stub is only really used to record arguments given.
       *  However, we want to preserve the arguments given at the time of calling, because they might subsequently
       *  be changed inside the parser so everything gets cloned before going to the stub 
       */
      function argumentClone(delegateCallback) {
         return function(){
         
            function clone(original){
               // Note: window.eval being used here instead of JSON.parse because
               // eval can handle 'undefined' in the string but JSON.parse cannot.
               // This isn't wholy ideal since this means we're relying on JSON.
               // stringify to create invalid JSON. But at least there are no
               // security concerns with this being a test. 
               return window.eval( '(' + JSON.stringify( original ) + ')' );
            }
            function toArray(args) {
               return Array.prototype.slice.call(args);
            }
            
            var cloneArguments = toArray(arguments).map(clone);
            
            delegateCallback.apply( this, cloneArguments );
         };
      }      
   }
   return new OboeAsserter();
}


var wasPassedAnErrorObject = {
   testAgainst: function failIfNotPassedAnError(callback, oboeInstance) {
   
      if( !callback.args[0][0] instanceof Error ) {
         throw new Error("Callback should have been given an error but was given" + callback.constructor.name);
      }
      
   }
};


// higher-order function to create assertions. Pass output to Asserter#thenTheInstance.
// test how many matches were found
function foundNMatches(n){
   return {
      testAgainst:
      function(callback, oboeInstance) {
         if( n != callback.callCount ) {
            throw new Error('expected to have been called ' + n + ' times but has been called ' +
               callback.callCount + ' times. \n' +
                   "all calls were with:" +
                   reportArgumentsToCallback(callback.args)
            )
         }
      }
   }
}

// To test the json at oboe#json() is as expected.
function hasRootJson(expected){
   return {
      testAgainst:
      function(callback, oboeInstance) {
      
         expect(oboeInstance.root()).toEqual(expected);
      }
   }
}

// To test the json given as the call .onGet(url, callback(completeJson))
// is correct
function gaveFinalCallbackWithRootJson(expected) {
   return {
      testAgainst:
         function(callback, oboeInstance, completeJson) { 
            expect(completeJson).toEqual(expected);         
         }
   }
}

var foundOneMatch = foundNMatches(1),
    calledCallbackOnce = foundNMatches(1),    
    foundNoMatches = foundNMatches(0);

function wasCalledbackWithContext(callbackScope) {
   return { 
      testAgainst:
      function(callbackStub, oboeInstance) {
         if(!callbackStub.calledOn(callbackScope)){
         
            if( !callbackStub.called ) {
               throw new Error('Expected to be called with context ' + callbackScope + ' but has not been called at all');
            }
         
            throw new Error('was not called in the expected context. Expected ' + callbackScope + ' but got ' + 
               callbackStub.getCall(0).thisValue);
         }   
      }
   };
}

function wasGivenTheOboeAsContext() {
   return { 
      testAgainst:
      function(callbackStub, oboeInstance) {
         return wasCalledbackWithContext(oboeInstance).testAgainst(callbackStub, oboeInstance);   
      }
   };
}

function lastOf(array){
   return array[array.length-1];
}
function penultimateOf(array){
   return array[array.length-2];
}
function prepenultimateOf(array){
   return array[array.length-3];
}

/**
 * Make a string version of the callback arguments given from oboe
 * @param {[[*]]} callbackArgs
 */
function reportArgumentsToCallback(callbackArgs) {

   return "\n" + callbackArgs.map( function( args, i ){

      var ancestors = args[2];
      
      return "Call number " + i + " was: \n" + 
               "\tnode:         " + JSON.stringify( args[0] ) + "\n" + 
               "\tpath:         " + JSON.stringify( args[1] ) + "\n" +
               "\tparent:       " + JSON.stringify( lastOf(ancestors) ) + "\n" +
               "\tgrandparent:  " + JSON.stringify( penultimateOf(ancestors) ) + "\n" +
               "\tancestors:    " + JSON.stringify( ancestors );
   
   }).join("\n\n");
         
}

// higher-level function to create assertions which will be used by the asserter.
function matched(obj) {

   return {   
      testAgainst: function assertMatchedRightObject( callbackStub ) {
      
         if(!callbackStub.calledWith(obj)) {

            var objectPassedToCall = function(callArgs){return callArgs[0]};
            
            throw new Error( "was not called with the object " +  JSON.stringify(obj) + "\n" +
                "objects that I got are:" +
                JSON.stringify(callbackStub.args.map(objectPassedToCall) ) + "\n" +
                "all calls were with:" +
                reportArgumentsToCallback(callbackStub.args));
   
         }
      }
   
   ,  atPath: function assertAtRightPath(path) {
         var oldAssertion = this.testAgainst;
         
         this.testAgainst = function( callbackStub ){
            oldAssertion.apply(this, arguments);
            
            if(!callbackStub.calledWithMatch(sinon.match.any, path)) {
               throw new Error( "was not called with the path " +  JSON.stringify(path) + "\n" +
                   "paths that I have are:\n" +
                   callbackStub.args.map(function(callArgs){
                     return "\t" + JSON.stringify(callArgs[1]) + "\n";
                   }) + "\n" +
                   "all calls were with:" +
                   reportArgumentsToCallback(callbackStub.args));
            }            
         };
         
         return this;   
      }
      
   ,  withParent: function( expectedParent ) {
         var oldAssertion = this.testAgainst;
         
         this.testAgainst = function( callbackStub ){
            oldAssertion.apply(this, arguments);
            
            var parentMatcher = sinon.match(function (array) {

               var foundParent = penultimateOf(array);
                  
               // since this is a matcher, we can't ues expect().toEqual()
               // because then the test would fail on the first non-match
               // under jasmine. Using stringify is slightly brittle and 
               // if this breaks we need to work out how to plug into Jasmine's
               // inner equals(a,b) function
                            
               return JSON.stringify(foundParent) == JSON.stringify(expectedParent)
               
            }, "had the right parent");
            
            if(!callbackStub.calledWithMatch(obj, sinon.match.any, parentMatcher)) {
               throw new Error( "was not called with the object" + JSON.stringify(obj) + 
                        " and parent object " +  JSON.stringify(expectedParent) +
                        "all calls were with:" +
                        reportArgumentsToCallback(callbackStub.args));
            }            
         };
         
         return this;
      }
      
   ,  withGrandparent: function( expectedGrandparent ) {
         var oldAssertion = this.testAgainst;
         
         this.testAgainst = function( callbackStub ){
            oldAssertion.apply(this, arguments);
            
            var grandparentMatcher = sinon.match(function (array) {

               // since this is a matcher, we can't ues expect().toEqual()
               // because then the test would fail on the first non-match
               // under jasmine. Using stringify is slightly brittle and 
               // if this breaks we need to work out how to plug into Jasmine's
               // inner equals(a,b) function

               var foundGrandparent = prepenultimateOf(array);                
               
               return JSON.stringify(foundGrandparent) == JSON.stringify(expectedGrandparent);
               
            }, "had the right grandparent");
            
            if(!callbackStub.calledWithMatch(obj, sinon.match.any, grandparentMatcher)) {
               throw new Error( "was not called with the object" + JSON.stringify(obj) + 
                        " and garndparent object " +  JSON.stringify(expectedGrandparent) +
                        "all calls were with:" +
                        reportArgumentsToCallback(callbackStub.args));
            }            
         };
         
         return this;
      }                  
      
   ,  atRootOfJson: function assertAtRootOfJson() {
         this.atPath([]);
         return this;
      }
   };
}