Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(168)

Side by Side Diff: third_party/pkg/angular/lib/mock/http_backend.dart

Issue 124053002: Adding Angular and dependent packages for testing (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 6 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 part of angular.mock;
2
3 class _MockXhr {
4 var $$method, $$url, $$async, $$reqHeaders, $$respHeaders;
5
6 open(method, url, async) {
7 $$method = method;
8 $$url = url;
9 $$async = async;
10 $$reqHeaders = {};
11 $$respHeaders = {};
12 }
13
14 var $$data;
15
16 send(data) {
17 $$data = data;
18 }
19
20 setRequestHeader(key, value) {
21 $$reqHeaders[key] = value;
22 }
23
24 getResponseHeader(name) {
25 // the lookup must be case insensitive, that's why we try two quick lookups and full scan at last
26 if ($$respHeaders.containsKey(name)) {
27 return $$respHeaders[name];
28 }
29
30 name = name.toLowerCase();
31 if ($$respHeaders.containsKey(name)) {
32 return $$respHeaders[name];
33 }
34
35 String header = null;
36 $$respHeaders.forEach((headerName, headerVal) {
37 if (header != null) return;
38 if (headerName.toLowerCase()) header = headerVal;
39 });
40 return header;
41 }
42
43 getAllResponseHeaders() {
44 if ($$respHeaders == null) return '';
45
46 var lines = [];
47
48 $$respHeaders.forEach((key, value) {
49 lines.add("$key: $value");
50 });
51 return lines.join('\n');
52 }
53
54 // noop
55 abort() {}
56 }
57
58 /**
59 * An internal class used by [MockHttpBackend].
60 */
61 class MockHttpExpectation {
62
63 var method, url, data, headers;
64
65 var response;
66
67 MockHttpExpectation(this.method, this.url, [this.data, this.headers]);
68
69 match(m, u, [d, h]) {
70 if (method != m) return false;
71 if (!matchUrl(u)) return false;
72 if (d != null && !matchData(d)) return false;
73 if (h != null && !matchHeaders(h)) return false;
74 return true;
75 }
76
77 matchUrl(u) {
78 if (url == null) return true;
79 if (url is RegExp) return url.hasMatch(u);
80 return url == u;
81 }
82
83 matchHeaders(h) {
84 if (headers == null) return true;
85 if (headers is Function) return headers(h);
86 return "$headers" == "$h";
87 }
88
89 matchData(d) {
90 if (data == null) return true;
91 if (d == null) return false; // data is not null, but d is.
92 if (data is File) return data == d;
93 assert(d is String);
94 if (data is RegExp) return data.hasMatch(d);
95 return JSON.encode(data) == JSON.encode(d);
96 }
97
98 toString() {
99 return "$method $url";
100 }
101 }
102
103
104 class _Chain {
105 var _respondFn;
106 _Chain({respond}) {
107 _respondFn = respond;
108 }
109 respond([x,y,z]) => _respondFn(x,y,z);
110 }
111
112 /**
113 * A mock implementation of [HttpBackend], used in tests.
114 */
115 class MockHttpBackend implements HttpBackend {
116 var definitions = [],
117 expectations = [],
118 responses = [];
119
120 /**
121 * This function is called from [Http] and designed to mimic the Dart APIs.
122 */
123 dart_async.Future request(String url,
124 {String method, bool withCredentials, String responseType,
125 String mimeType, Map<String, String> requestHeaders, sendData,
126 void onProgress(ProgressEvent e)}) {
127 dart_async.Completer c = new dart_async.Completer();
128 var callback = (status, data, headers) {
129 if (status >= 200 && status < 300) {
130 c.complete(new MockHttpRequest(status, data, headers));
131 } else {
132 c.completeError(
133 new MockProgressEvent(
134 new MockHttpRequest(status, data, headers)));
135 }
136 };
137 call(method == null ? 'GET' : method, url, sendData, callback, requestHeader s);
138 return c.future;
139 }
140
141 _createResponse(status, data, headers) {
142 if (status is Function) return status;
143
144 return ([a,b,c,d,e]) {
145 return status is num
146 ? [status, data, headers]
147 : [200, status, data];
148 };
149 }
150
151
152 /**
153 * A callback oriented API. This function takes a callback with
154 * will be called with (status, data, headers)
155 */
156 call(method, [url, data, callback, headers, timeout]) {
157 var xhr = new _MockXhr(),
158 expectation = expectations.isEmpty ? null : expectations[0],
159 wasExpected = false;
160
161 var prettyPrint = (data) {
162 return (data is String || data is Function || data is RegExp)
163 ? data
164 : JSON.encode(data);
165 };
166
167 var wrapResponse = (wrapped) {
168 var handleResponse = () {
169 var response = wrapped.response(method, url, data, headers);
170 xhr.$$respHeaders = response[2];
171 utils.relaxFnApply(callback, [response[0], response[1], xhr.getAllRespon seHeaders()]);
172 };
173
174 var handleTimeout = () {
175 for (var i = 0, ii = responses.length; i < ii; i++) {
176 if (identical(responses[i], handleResponse)) {
177 responses.removeAt(i);
178 callback(-1, null, '');
179 break;
180 }
181 }
182 };
183
184 if (timeout != null) timeout.then(handleTimeout);
185 return handleResponse;
186 };
187
188 if (expectation != null && expectation.match(method, url)) {
189 if (!expectation.matchData(data))
190 throw ['Expected $expectation with different data\n' +
191 'EXPECTED: ${prettyPrint(expectation.data)}\nGOT: $data'];
192
193 if (!expectation.matchHeaders(headers))
194 throw ['Expected $expectation with different headers\n' +
195 'EXPECTED: ${prettyPrint(expectation.headers)}\nGOT: ${prettyPr int(headers)}'];
196
197 expectations.removeAt(0);
198
199 if (expectation.response != null) {
200 responses.add(wrapResponse(expectation));
201 return;
202 }
203 wasExpected = true;
204 }
205
206 for (var definition in definitions) {
207 if (definition.match(method, url, data, headers != null ? headers : {})) {
208 if (definition.response != null) {
209 // if $browser specified, we do auto flush all requests
210 responses.add(wrapResponse(definition));
211 } else throw ['No response defined !'];
212 return;
213 }
214 }
215 throw wasExpected ?
216 ['No response defined !'] :
217 ['Unexpected request: $method $url\n' +
218 (expectation != null ? 'Expected $expectation' : 'No more requests e xpected')];
219 }
220
221 /**
222 * Creates a new backend definition.
223 *
224 * @param {string} method HTTP method.
225 * @param {string|RegExp} url HTTP url.
226 * @param {(string|RegExp)=} data HTTP request body.
227 * @param {(Object|function(Object))=} headers HTTP headers or function that r eceives http header
228 * object and returns true if the headers match the current definition.
229 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
230 * request is handled.
231 *
232 * - respond – `{function([status,] data[, headers])|function(function(method , url, data, headers)}`
233 * – The respond method takes a set of static data to be returned or a func tion that can return
234 * an array containing response status (number), response data (string) and response headers
235 * (Object).
236 */
237 when(method, [url, data, headers]) {
238 var definition = new MockHttpExpectation(method, url, data, headers),
239 chain = new _Chain(respond: (status, data, headers) {
240 definition.response = _createResponse(status, data, headers);
241 });
242
243 definitions.add(definition);
244 return chain;
245 }
246
247 /**
248 * @ngdoc method
249 * @name ngMock.$httpBackend#whenGET
250 * @methodOf ngMock.$httpBackend
251 * @description
252 * Creates a new backend definition for GET requests. For more info see `when( )`.
253 *
254 * @param {string|RegExp} url HTTP url.
255 * @param {(Object|function(Object))=} headers HTTP headers.
256 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
257 * request is handled.
258 */
259
260
261 whenGET(url, [headers]) =>
262 when('GET', url, null, headers);
263 whenDELETE(url, [headers]) =>
264 when('DELETE', url, null, headers);
265 whenJSONP(url, [headers]) =>
266 when('JSONP', url, null, headers);
267
268 whenPUT(url, [data, headers]) =>
269 when('PUT', url, data, headers);
270 whenPOST(url, [data, headers]) =>
271 when('POST', url, data, headers);
272 whenPATCH(url, [data, headers]) =>
273 when('PATCH', url, data, headers);
274
275 /**
276 * @ngdoc method
277 * @name ngMock.$httpBackend#whenHEAD
278 * @methodOf ngMock.$httpBackend
279 * @description
280 * Creates a new backend definition for HEAD requests. For more info see `when ()`.
281 *
282 * @param {string|RegExp} url HTTP url.
283 * @param {(Object|function(Object))=} headers HTTP headers.
284 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
285 * request is handled.
286 */
287
288 /**
289 * @ngdoc method
290 * @name ngMock.$httpBackend#whenDELETE
291 * @methodOf ngMock.$httpBackend
292 * @description
293 * Creates a new backend definition for DELETE requests. For more info see `wh en()`.
294 *
295 * @param {string|RegExp} url HTTP url.
296 * @param {(Object|function(Object))=} headers HTTP headers.
297 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
298 * request is handled.
299 */
300
301 /**
302 * @ngdoc method
303 * @name ngMock.$httpBackend#whenPOST
304 * @methodOf ngMock.$httpBackend
305 * @description
306 * Creates a new backend definition for POST requests. For more info see `when ()`.
307 *
308 * @param {string|RegExp} url HTTP url.
309 * @param {(string|RegExp)=} data HTTP request body.
310 * @param {(Object|function(Object))=} headers HTTP headers.
311 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
312 * request is handled.
313 */
314
315 /**
316 * @ngdoc method
317 * @name ngMock.$httpBackend#whenPUT
318 * @methodOf ngMock.$httpBackend
319 * @description
320 * Creates a new backend definition for PUT requests. For more info see `when ()`.
321 *
322 * @param {string|RegExp} url HTTP url.
323 * @param {(string|RegExp)=} data HTTP request body.
324 * @param {(Object|function(Object))=} headers HTTP headers.
325 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
326 * request is handled.
327 */
328
329 /**
330 * @ngdoc method
331 * @name ngMock.$httpBackend#whenJSONP
332 * @methodOf ngMock.$httpBackend
333 * @description
334 * Creates a new backend definition for JSONP requests. For more info see `whe n()`.
335 *
336 * @param {string|RegExp} url HTTP url.
337 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
338 * request is handled.
339 */
340 //createShortMethods('when');
341
342
343 /**
344 * @ngdoc method
345 * @name ngMock.$httpBackend#expect
346 * @methodOf ngMock.$httpBackend
347 * @description
348 * Creates a new request expectation.
349 *
350 * @param {string} method HTTP method.
351 * @param {string|RegExp} url HTTP url.
352 * @param {(string|RegExp)=} data HTTP request body.
353 * @param {(Object|function(Object))=} headers HTTP headers or function that r eceives http header
354 * object and returns true if the headers match the current expectation.
355 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
356 * request is handled.
357 *
358 * - respond – `{function([status,] data[, headers])|function(function(method , url, data, headers)}`
359 * – The respond method takes a set of static data to be returned or a func tion that can return
360 * an array containing response status (number), response data (string) and response headers
361 * (Object).
362 */
363 expect(method, [url, data, headers]) {
364 var expectation = new MockHttpExpectation(method, url, data, headers);
365 expectations.add(expectation);
366 return new _Chain(respond: (status, data, headers) {
367 expectation.response = _createResponse(status, data, headers);
368 });
369 }
370
371
372 /**
373 * @ngdoc method
374 * @name ngMock.$httpBackend#expectGET
375 * @methodOf ngMock.$httpBackend
376 * @description
377 * Creates a new request expectation for GET requests. For more info see `expe ct()`.
378 *
379 * @param {string|RegExp} url HTTP url.
380 * @param {Object=} headers HTTP headers.
381 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
382 * request is handled. See #expect for more info.
383 */
384 expectGET(url, [headers]) =>
385 expect('GET', url, null, headers);
386 expectDELETE(url, [headers]) =>
387 expect('DELETE', url, null, headers);
388 expectJSONP(url, [headers]) =>
389 expect('JSONP', url, null, headers);
390
391 expectPUT(url, [data, headers]) =>
392 expect('PUT', url, data, headers);
393 expectPOST(url, [data, headers]) =>
394 expect('POST', url, data, headers);
395 expectPATCH(url, [data, headers]) =>
396 expect('PATCH', url, data, headers);
397
398 /**
399 * @ngdoc method
400 * @name ngMock.$httpBackend#expectHEAD
401 * @methodOf ngMock.$httpBackend
402 * @description
403 * Creates a new request expectation for HEAD requests. For more info see `exp ect()`.
404 *
405 * @param {string|RegExp} url HTTP url.
406 * @param {Object=} headers HTTP headers.
407 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
408 * request is handled.
409 */
410
411 /**
412 * @ngdoc method
413 * @name ngMock.$httpBackend#expectDELETE
414 * @methodOf ngMock.$httpBackend
415 * @description
416 * Creates a new request expectation for DELETE requests. For more info see `e xpect()`.
417 *
418 * @param {string|RegExp} url HTTP url.
419 * @param {Object=} headers HTTP headers.
420 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
421 * request is handled.
422 */
423
424 /**
425 * @ngdoc method
426 * @name ngMock.$httpBackend#expectPOST
427 * @methodOf ngMock.$httpBackend
428 * @description
429 * Creates a new request expectation for POST requests. For more info see `exp ect()`.
430 *
431 * @param {string|RegExp} url HTTP url.
432 * @param {(string|RegExp)=} data HTTP request body.
433 * @param {Object=} headers HTTP headers.
434 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
435 * request is handled.
436 */
437
438 /**
439 * @ngdoc method
440 * @name ngMock.$httpBackend#expectPUT
441 * @methodOf ngMock.$httpBackend
442 * @description
443 * Creates a new request expectation for PUT requests. For more info see `expe ct()`.
444 *
445 * @param {string|RegExp} url HTTP url.
446 * @param {(string|RegExp)=} data HTTP request body.
447 * @param {Object=} headers HTTP headers.
448 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
449 * request is handled.
450 */
451
452 /**
453 * @ngdoc method
454 * @name ngMock.$httpBackend#expectPATCH
455 * @methodOf ngMock.$httpBackend
456 * @description
457 * Creates a new request expectation for PATCH requests. For more info see `ex pect()`.
458 *
459 * @param {string|RegExp} url HTTP url.
460 * @param {(string|RegExp)=} data HTTP request body.
461 * @param {Object=} headers HTTP headers.
462 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
463 * request is handled.
464 */
465
466 /**
467 * @ngdoc method
468 * @name ngMock.$httpBackend#expectJSONP
469 * @methodOf ngMock.$httpBackend
470 * @description
471 * Creates a new request expectation for JSONP requests. For more info see `ex pect()`.
472 *
473 * @param {string|RegExp} url HTTP url.
474 * @returns {requestHandler} Returns an object with `respond` method that cont rol how a matched
475 * request is handled.
476 */
477 //createShortMethods('expect');
478
479
480 /**
481 * @ngdoc method
482 * @name ngMock.$httpBackend#flush
483 * @methodOf ngMock.$httpBackend
484 * @description
485 * Flushes all pending requests using the trained responses.
486 *
487 * @param {number=} count Number of responses to flush (in the order they arri ved). If undefined,
488 * all pending requests will be flushed. If there are no pending requests wh en the flush method
489 * is called an exception is thrown (as this typically a sign of programming error).
490 */
491 flush([count]) {
492 if (responses.isEmpty) throw ['No pending request to flush !'];
493
494 if (count != null) {
495 while (count-- > 0) {
496 if (responses.isEmpty) throw ['No more pending request to flush !'];
497 responses.removeAt(0)();
498 }
499 } else {
500 while (!responses.isEmpty) {
501 responses.removeAt(0)();
502 }
503 }
504 verifyNoOutstandingExpectation();
505 }
506
507
508 /**
509 * @ngdoc method
510 * @name ngMock.$httpBackend#verifyNoOutstandingExpectation
511 * @methodOf ngMock.$httpBackend
512 * @description
513 * Verifies that all of the requests defined via the `expect` api were made. I f any of the
514 * requests were not made, verifyNoOutstandingExpectation throws an exception.
515 *
516 * Typically, you would call this method following each test case that asserts requests using an
517 * "afterEach" clause.
518 *
519 * <pre>
520 * afterEach($httpBackend.verifyNoOutstandingExpectation);
521 * </pre>
522 */
523 verifyNoOutstandingExpectation() {
524 if (!expectations.isEmpty) {
525 throw ['Unsatisfied requests: ${expectations.join(', ')}'];
526 }
527 }
528
529
530 /**
531 * @ngdoc method
532 * @name ngMock.$httpBackend#verifyNoOutstandingRequest
533 * @methodOf ngMock.$httpBackend
534 * @description
535 * Verifies that there are no outstanding requests that need to be flushed.
536 *
537 * Typically, you would call this method following each test case that asserts requests using an
538 * "afterEach" clause.
539 *
540 * <pre>
541 * afterEach($httpBackend.verifyNoOutstandingRequest);
542 * </pre>
543 */
544 verifyNoOutstandingRequest() {
545 if (!responses.isEmpty) {
546 throw ['Unflushed requests: ${responses.length}'];
547 }
548 }
549
550
551 /**
552 * @ngdoc method
553 * @name ngMock.$httpBackend#resetExpectations
554 * @methodOf ngMock.$httpBackend
555 * @description
556 * Resets all request expectations, but preserves all backend definitions. Typ ically, you would
557 * call resetExpectations during a multiple-phase test when you want to reuse the same instance of
558 * $httpBackend mock.
559 */
560 resetExpectations() {
561 expectations.length = 0;
562 responses.length = 0;
563 }
564 }
565
566 /**
567 * Mock implementation of the [HttpRequest] object returned from the HttpBackend .
568 */
569 class MockHttpRequest implements HttpRequest {
570 final bool supportsCrossOrigin = false;
571 final bool supportsLoadEndEvent = false;
572 final bool supportsOverrideMimeType = false;
573 final bool supportsProgressEvent = false;
574 final Events on = null;
575
576 final dart_async.Stream<ProgressEvent> onAbort = null;
577 final dart_async.Stream<ProgressEvent> onError = null;
578 final dart_async.Stream<ProgressEvent> onLoad = null;
579 final dart_async.Stream<ProgressEvent> onLoadEnd = null;
580 final dart_async.Stream<ProgressEvent> onLoadStart = null;
581 final dart_async.Stream<ProgressEvent> onProgress = null;
582 final dart_async.Stream<ProgressEvent> onReadyStateChange = null;
583
584 final dart_async.Stream<ProgressEvent> onTimeout = null;
585 final int readyState = 0;
586
587 get responseText => response == null ? null : "$response";
588 Map<String, String> get responseHeaders => null;
589 final responseXml = null;
590 final String statusText = null;
591 final HttpRequestUpload upload = null;
592
593 String responseType = null;
594 int timeout = 0;
595 bool withCredentials;
596
597 final int status;
598 final response;
599 final String headers;
600
601 MockHttpRequest(this.status, this.response, [this.headers]);
602
603 void abort() {}
604 bool dispatchEvent(Event event) => false;
605 String getAllResponseHeaders() {
606 if (headers == null) return null;
607 return headers;
608 }
609 String getResponseHeader(String header) => null;
610
611 void open(String method, String url, {bool async, String user, String password }) {}
612 void overrideMimeType(String override) {}
613 void send([data]) {}
614 void setRequestHeader(String header, String value) {}
615 void addEventListener(String type, EventListener listener, [bool useCapture]) {}
616 void removeEventListener(String type, EventListener listener, [bool useCapture ]) {}
617 }
618
619 class MockProgressEvent implements ProgressEvent {
620 final bool bubbles = false;
621 final bool cancelable = false;
622 final DataTransfer clipboardData = null;
623 final EventTarget currentTarget;
624 final Element matchingTarget = null;
625 final bool defaultPrevented = false;
626 final int eventPhase = 0;
627 final bool lengthComputable = false;
628 final int loaded = 0;
629 final List<Node> path = null;
630 final int position = 0;
631 final Type runtimeType = null;
632 final EventTarget target = null;
633 final int timeStamp = 0;
634 final int total = 0;
635 final int totalSize = 0;
636 final String type = null;
637
638 bool cancelBubble = false;
639
640 MockProgressEvent(MockHttpRequest this.currentTarget);
641
642 void preventDefault() {}
643 void stopImmediatePropagation() {}
644 void stopPropagation() {}
645 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698