├── .gitignore ├── .gitmodules ├── Gruntfile.js ├── LICENSE ├── README.md ├── bower.json ├── dist ├── browserify-eventsource.js ├── eventsource.js └── eventsource.min.js ├── javascript ├── SpecConcurrentRunner.html ├── SpecRunner.html ├── lib │ └── jasmine-2.0.0 │ │ ├── boot.js │ │ ├── console.js │ │ ├── jasmine-html.js │ │ ├── jasmine.css │ │ ├── jasmine.js │ │ └── jasmine_favicon.png ├── spec │ ├── concurrentSpec.js │ └── eventsourceSpec.js └── src │ ├── browserify-eventsource.js │ └── eventsource.js ├── package.json └── test_server ├── etc ├── nginx │ └── evs_tests.conf └── supervisor │ └── evs_test_server.conf ├── evsutils ├── __init__.py ├── log.py ├── protocol.py └── utils.py ├── requirements.txt └── twisted └── plugins └── test_eventsource.py /.gitignore: -------------------------------------------------------------------------------- 1 | # vim swp files 2 | *.swp 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | bin/ 15 | build/ 16 | develop-eggs/ 17 | eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # Twisted plugins cache 28 | test_server/twisted/plugins/dropin.cache 29 | 30 | # local node_modules 31 | node_modules/ 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | 45 | # Translations 46 | *.mo 47 | 48 | # Mr Developer 49 | .mr.developer.cfg 50 | .project 51 | .pydevproject 52 | 53 | # Rope 54 | .ropeproject 55 | 56 | # Django stuff: 57 | *.log 58 | *.pot 59 | 60 | # Sphinx documentation 61 | docs/_build/ 62 | 63 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "docs"] 2 | path = docs 3 | url = git@github.com:amvtek/EventSource.wiki.git 4 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | module.exports = function(grunt) { 2 | 3 | "use strict"; 4 | 5 | grunt.initConfig({ 6 | 7 | pkg: grunt.file.readJSON('package.json'), 8 | 9 | 'string-replace': { 10 | dist: { 11 | options: { 12 | replacements: [ 13 | {pattern: /{{VERSION}}/g, replacement: '<%= pkg.version %>'} 14 | ] 15 | }, 16 | files: { 17 | 'dist/eventsource.js': ['javascript/src/eventsource.js'], 18 | 'dist/browserify-eventsource.js': ['javascript/src/browserify-eventsource.js'] 19 | } 20 | } 21 | }, 22 | 23 | uglify: { 24 | dist: { 25 | files: { 26 | 'dist/eventsource.min.js': ['dist/eventsource.js'] 27 | } 28 | } 29 | }, 30 | 31 | 32 | }); 33 | grunt.loadNpmTasks('grunt-string-replace'); 34 | grunt.loadNpmTasks('grunt-contrib-uglify'); 35 | grunt.registerTask('default', ['string-replace', 'uglify']); 36 | }; 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 AmvTek 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | EventSource Polyfill 2 | ==================== 3 | 4 | Provide polyfill to support EventSource in browser where it is not available. 5 | 6 | > - Used in production 7 | > - Tested in Internet Explorer 8 + 8 | > - Tested in Android browser 2.1 + 9 | > - [Documented][] 10 | > - Run the [Browser test suite][] 11 | 12 | Installing 13 | ---------- 14 | 15 | ### from source 16 | 17 | Download suitable project archive (zip or tar.gz) from [release page][] 18 | 19 | Include in your html documents one of the following javascript file: 20 | 21 | > - *dist/eventsource.js* 22 | > - *dist/eventsource.min.js* (minified version) 23 | 24 | ### Using bower package manager 25 | 26 | To install package from **bower registry**, type : 27 | 28 | bower install eventsource-polyfill 29 | 30 | Include in your html documents one of the following javascript file: 31 | 32 | > - *bower\_components/eventsource-polyfill/dist/eventsource.js* 33 | > - *bower\_components/eventsource-polyfill/dist/eventsource.min.js* (minified version) 34 | 35 | ### Using npm package manager 36 | 37 | To install package from **npm registry**, type : 38 | 39 | npm install eventsource-polyfill 40 | 41 | Note that this package may only be used with in **browser application**. 42 | 43 | If you are using [browserify][] , you just have to require this package in your main module… 44 | 45 | ``` sourceCode 46 | // load (Polyfill) EventSource, in case browser does not support it... 47 | require('eventsource-polyfill'); 48 | ``` 49 | 50 | Run the tests now 51 | ----------------- 52 | 53 | With your web browser visit this [test site][Browser test suite] 54 | 55 | Allow **sufficient time** ( ~ 5 minutes) for the full Test Suite to run… 56 | 57 | Project content 58 | --------------- 59 | 60 | dist/ 61 | built version of javascript modules 62 | 63 | javascript/ 64 | Contains polyfill module and related unit tests 65 | 66 | test_server/ 67 | python server which generates *easy to test* **event stream** 68 | 69 | docs/ 70 | documentation wiki 71 | 72 | [Documented]: https://github.com/amvtek/EventSource/wiki 73 | [Browser test suite]: http://testevs.amvtek.com/ 74 | [release page]: https://github.com/amvtek/EventSource/releases/latest 75 | [browserify]: http://browserify.org 76 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "eventsource-polyfill", 3 | "homepage": "https://github.com/amvtek/EventSource", 4 | "authors": [ 5 | "amvtek " 6 | ], 7 | "description": "A polyfill for http://www.w3.org/TR/eventsource/", 8 | "main": ["javascript/src/eventsource.js", "eventsource.min.js", "README.rst"], 9 | "keywords": [ 10 | "sse", 11 | "server sent events", 12 | "eventsource", 13 | "event-source", 14 | "polyfill" 15 | ], 16 | "license": "MIT", 17 | "ignore": [ 18 | "**/.*", 19 | "javascript", 20 | "test_server", 21 | "Gruntfile.js", 22 | "package.json", 23 | "node_modules", 24 | "bower_components", 25 | "test", 26 | "tests", 27 | "docs" 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /dist/browserify-eventsource.js: -------------------------------------------------------------------------------- 1 | /* 2 | * CommonJS module that exports EventSource polyfill version 0.9.7 3 | * This module is intended for browser side use 4 | * ===================================================================== 5 | * THIS IS A POLYFILL MODULE, SO IT HAS SIDE EFFECTS 6 | * IT AUTOMATICALLY CHECKS IF window OBJECT DEFINES EventSource 7 | * AND ADD THE EXPORTED ONE IN CASE IT IS UNDEFINED 8 | * ===================================================================== 9 | * Supported by sc AmvTek srl 10 | * :email: devel@amvtek.com 11 | */ 12 | 13 | 14 | var PolyfillEventSource = require('./eventsource.js').EventSource; 15 | module.exports = PolyfillEventSource; 16 | 17 | // Add EventSource to window if it is missing... 18 | if (window && !window.EventSource){ 19 | window.EventSource = PolyfillEventSource; 20 | if (console){ 21 | console.log("polyfill-eventsource added missing EventSource to window"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /dist/eventsource.js: -------------------------------------------------------------------------------- 1 | /* 2 | * EventSource polyfill version 0.9.7 3 | * Supported by sc AmvTek srl 4 | * :email: devel@amvtek.com 5 | */ 6 | ;(function (global) { 7 | 8 | if (global.EventSource && !global._eventSourceImportPrefix){ 9 | return; 10 | } 11 | 12 | var evsImportName = (global._eventSourceImportPrefix||'')+"EventSource"; 13 | 14 | var EventSource = function (url, options) { 15 | 16 | if (!url || typeof url != 'string') { 17 | throw new SyntaxError('Not enough arguments'); 18 | } 19 | 20 | this.URL = url; 21 | this.setOptions(options); 22 | var evs = this; 23 | setTimeout(function(){evs.poll()}, 0); 24 | }; 25 | 26 | EventSource.prototype = { 27 | 28 | CONNECTING: 0, 29 | 30 | OPEN: 1, 31 | 32 | CLOSED: 2, 33 | 34 | defaultOptions: { 35 | 36 | loggingEnabled: false, 37 | 38 | loggingPrefix: "eventsource", 39 | 40 | interval: 500, // milliseconds 41 | 42 | bufferSizeLimit: 256*1024, // bytes 43 | 44 | silentTimeout: 300000, // milliseconds 45 | 46 | getArgs:{ 47 | 'evs_buffer_size_limit': 256*1024 48 | }, 49 | 50 | xhrHeaders:{ 51 | 'Accept': 'text/event-stream', 52 | 'Cache-Control': 'no-cache', 53 | 'X-Requested-With': 'XMLHttpRequest' 54 | } 55 | }, 56 | 57 | setOptions: function(options){ 58 | 59 | var defaults = this.defaultOptions; 60 | var option; 61 | 62 | // set all default options... 63 | for (option in defaults){ 64 | 65 | if ( defaults.hasOwnProperty(option) ){ 66 | this[option] = defaults[option]; 67 | } 68 | } 69 | 70 | // override with what is in options 71 | for (option in options){ 72 | 73 | if (option in defaults && options.hasOwnProperty(option)){ 74 | this[option] = options[option]; 75 | } 76 | } 77 | 78 | // if getArgs option is enabled 79 | // ensure evs_buffer_size_limit corresponds to bufferSizeLimit 80 | if (this.getArgs && this.bufferSizeLimit) { 81 | 82 | this.getArgs['evs_buffer_size_limit'] = this.bufferSizeLimit; 83 | } 84 | 85 | // if console is not available, force loggingEnabled to false 86 | if (typeof console === "undefined" || typeof console.log === "undefined") { 87 | 88 | this.loggingEnabled = false; 89 | } 90 | }, 91 | 92 | log: function(message) { 93 | 94 | if (this.loggingEnabled) { 95 | 96 | console.log("[" + this.loggingPrefix +"]:" + message) 97 | } 98 | }, 99 | 100 | poll: function() { 101 | 102 | try { 103 | 104 | if (this.readyState == this.CLOSED) { 105 | return; 106 | } 107 | 108 | this.cleanup(); 109 | this.readyState = this.CONNECTING; 110 | this.cursor = 0; 111 | this.cache = ''; 112 | this._xhr = new this.XHR(this); 113 | this.resetNoActivityTimer(); 114 | 115 | } 116 | catch (e) { 117 | 118 | // in an attempt to silence the errors 119 | this.log('There were errors inside the pool try-catch'); 120 | this.dispatchEvent('error', { type: 'error', data: e.message }); 121 | } 122 | }, 123 | 124 | pollAgain: function (interval) { 125 | 126 | // schedule poll to be called after interval milliseconds 127 | var evs = this; 128 | evs.readyState = evs.CONNECTING; 129 | evs.dispatchEvent('error', { 130 | type: 'error', 131 | data: "Reconnecting " 132 | }); 133 | this._pollTimer = setTimeout(function(){evs.poll()}, interval||0); 134 | }, 135 | 136 | 137 | cleanup: function() { 138 | 139 | this.log('evs cleaning up') 140 | 141 | if (this._pollTimer){ 142 | clearInterval(this._pollTimer); 143 | this._pollTimer = null; 144 | } 145 | 146 | if (this._noActivityTimer){ 147 | clearInterval(this._noActivityTimer); 148 | this._noActivityTimer = null; 149 | } 150 | 151 | if (this._xhr){ 152 | this._xhr.abort(); 153 | this._xhr = null; 154 | } 155 | }, 156 | 157 | resetNoActivityTimer: function(){ 158 | 159 | if (this.silentTimeout){ 160 | 161 | if (this._noActivityTimer){ 162 | clearInterval(this._noActivityTimer); 163 | } 164 | var evs = this; 165 | this._noActivityTimer = setTimeout( 166 | function(){ evs.log('Timeout! silentTImeout:'+evs.silentTimeout); evs.pollAgain(); }, 167 | this.silentTimeout 168 | ); 169 | } 170 | }, 171 | 172 | close: function () { 173 | 174 | this.readyState = this.CLOSED; 175 | this.log('Closing connection. readyState: '+this.readyState); 176 | this.cleanup(); 177 | }, 178 | 179 | _onxhrdata: function() { 180 | 181 | var request = this._xhr; 182 | 183 | if (request.isReady() && !request.hasError() ) { 184 | // reset the timer, as we have activity 185 | this.resetNoActivityTimer(); 186 | 187 | // move this EventSource to OPEN state... 188 | if (this.readyState == this.CONNECTING) { 189 | this.readyState = this.OPEN; 190 | this.dispatchEvent('open', { type: 'open' }); 191 | } 192 | 193 | var buffer = request.getBuffer(); 194 | 195 | if (buffer.length > this.bufferSizeLimit) { 196 | this.log('buffer.length > this.bufferSizeLimit'); 197 | this.pollAgain(); 198 | } 199 | 200 | if (this.cursor == 0 && buffer.length > 0){ 201 | 202 | // skip byte order mark \uFEFF character if it starts the stream 203 | if (buffer.substring(0,1) == '\uFEFF'){ 204 | this.cursor = 1; 205 | } 206 | } 207 | 208 | var lastMessageIndex = this.lastMessageIndex(buffer); 209 | if (lastMessageIndex[0] >= this.cursor){ 210 | 211 | var newcursor = lastMessageIndex[1]; 212 | var toparse = buffer.substring(this.cursor, newcursor); 213 | this.parseStream(toparse); 214 | this.cursor = newcursor; 215 | } 216 | 217 | // if request is finished, reopen the connection 218 | if (request.isDone()) { 219 | this.log('request.isDone(). reopening the connection'); 220 | this.pollAgain(this.interval); 221 | } 222 | } 223 | else if (this.readyState !== this.CLOSED) { 224 | 225 | this.log('this.readyState !== this.CLOSED'); 226 | this.pollAgain(this.interval); 227 | 228 | //MV: Unsure why an error was previously dispatched 229 | } 230 | }, 231 | 232 | parseStream: function(chunk) { 233 | 234 | // normalize line separators (\r\n,\r,\n) to \n 235 | // remove white spaces that may precede \n 236 | chunk = this.cache + this.normalizeToLF(chunk); 237 | 238 | var events = chunk.split('\n\n'); 239 | 240 | var i, j, eventType, datas, line, retry; 241 | 242 | for (i=0; i < (events.length - 1); i++) { 243 | 244 | eventType = 'message'; 245 | datas = []; 246 | parts = events[i].split('\n'); 247 | 248 | for (j=0; j < parts.length; j++) { 249 | 250 | line = this.trimWhiteSpace(parts[j]); 251 | 252 | if (line.indexOf('event') == 0) { 253 | 254 | eventType = line.replace(/event:?\s*/, ''); 255 | } 256 | else if (line.indexOf('retry') == 0) { 257 | 258 | retry = parseInt(line.replace(/retry:?\s*/, '')); 259 | if(!isNaN(retry)) { 260 | this.interval = retry; 261 | } 262 | } 263 | else if (line.indexOf('data') == 0) { 264 | 265 | datas.push(line.replace(/data:?\s*/, '')); 266 | } 267 | else if (line.indexOf('id:') == 0) { 268 | 269 | this.lastEventId = line.replace(/id:?\s*/, ''); 270 | } 271 | else if (line.indexOf('id') == 0) { // this resets the id 272 | 273 | this.lastEventId = null; 274 | } 275 | } 276 | 277 | if (datas.length) { 278 | // dispatch a new event 279 | var event = new MessageEvent(eventType, datas.join('\n'), window.location.origin, this.lastEventId); 280 | this.dispatchEvent(eventType, event); 281 | } 282 | } 283 | 284 | this.cache = events[events.length - 1]; 285 | }, 286 | 287 | dispatchEvent: function (type, event) { 288 | var handlers = this['_' + type + 'Handlers']; 289 | 290 | if (handlers) { 291 | 292 | for (var i = 0; i < handlers.length; i++) { 293 | handlers[i].call(this, event); 294 | } 295 | } 296 | 297 | if (this['on' + type]) { 298 | this['on' + type].call(this, event); 299 | } 300 | 301 | }, 302 | 303 | addEventListener: function (type, handler) { 304 | if (!this['_' + type + 'Handlers']) { 305 | this['_' + type + 'Handlers'] = []; 306 | } 307 | 308 | this['_' + type + 'Handlers'].push(handler); 309 | }, 310 | 311 | removeEventListener: function (type, handler) { 312 | var handlers = this['_' + type + 'Handlers']; 313 | if (!handlers) { 314 | return; 315 | } 316 | for (var i = handlers.length - 1; i >= 0; --i) { 317 | if (handlers[i] === handler) { 318 | handlers.splice(i, 1); 319 | break; 320 | } 321 | } 322 | }, 323 | 324 | _pollTimer: null, 325 | 326 | _noactivityTimer: null, 327 | 328 | _xhr: null, 329 | 330 | lastEventId: null, 331 | 332 | cache: '', 333 | 334 | cursor: 0, 335 | 336 | onerror: null, 337 | 338 | onmessage: null, 339 | 340 | onopen: null, 341 | 342 | readyState: 0, 343 | 344 | // =================================================================== 345 | // helpers functions 346 | // those are attached to prototype to ease reuse and testing... 347 | 348 | urlWithParams: function (baseURL, params) { 349 | 350 | var encodedArgs = []; 351 | 352 | if (params){ 353 | 354 | var key, urlarg; 355 | var urlize = encodeURIComponent; 356 | 357 | for (key in params){ 358 | if (params.hasOwnProperty(key)) { 359 | urlarg = urlize(key)+'='+urlize(params[key]); 360 | encodedArgs.push(urlarg); 361 | } 362 | } 363 | } 364 | 365 | if (encodedArgs.length > 0){ 366 | 367 | if (baseURL.indexOf('?') == -1) 368 | return baseURL + '?' + encodedArgs.join('&'); 369 | return baseURL + '&' + encodedArgs.join('&'); 370 | } 371 | return baseURL; 372 | }, 373 | 374 | lastMessageIndex: function(text) { 375 | 376 | var ln2 =text.lastIndexOf('\n\n'); 377 | var lr2 = text.lastIndexOf('\r\r'); 378 | var lrln2 = text.lastIndexOf('\r\n\r\n'); 379 | 380 | if (lrln2 > Math.max(ln2, lr2)) { 381 | return [lrln2, lrln2+4]; 382 | } 383 | return [Math.max(ln2, lr2), Math.max(ln2, lr2) + 2] 384 | }, 385 | 386 | trimWhiteSpace: function(str) { 387 | // to remove whitespaces left and right of string 388 | 389 | var reTrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g; 390 | return str.replace(reTrim, ''); 391 | }, 392 | 393 | normalizeToLF: function(str) { 394 | 395 | // replace \r and \r\n with \n 396 | return str.replace(/\r\n|\r/g, '\n'); 397 | } 398 | 399 | }; 400 | 401 | if (!isOldIE()){ 402 | 403 | EventSource.isPolyfill = "XHR"; 404 | 405 | // EventSource will send request using XMLHttpRequest 406 | EventSource.prototype.XHR = function(evs) { 407 | 408 | request = new XMLHttpRequest(); 409 | this._request = request; 410 | evs._xhr = this; 411 | 412 | // set handlers 413 | request.onreadystatechange = function(){ 414 | if (request.readyState > 1 && evs.readyState != evs.CLOSED) { 415 | if (request.status == 200 || (request.status>=300 && request.status<400)){ 416 | evs._onxhrdata(); 417 | } 418 | else { 419 | request._failed = true; 420 | evs.readyState = evs.CLOSED; 421 | evs.dispatchEvent('error', { 422 | type: 'error', 423 | data: "The server responded with "+request.status 424 | }); 425 | evs.close(); 426 | } 427 | } 428 | }; 429 | 430 | request.onprogress = function () { 431 | }; 432 | 433 | request.open('GET', evs.urlWithParams(evs.URL, evs.getArgs), true); 434 | 435 | var headers = evs.xhrHeaders; // maybe null 436 | for (var header in headers) { 437 | if (headers.hasOwnProperty(header)){ 438 | request.setRequestHeader(header, headers[header]); 439 | } 440 | } 441 | if (evs.lastEventId) { 442 | request.setRequestHeader('Last-Event-Id', evs.lastEventId); 443 | } 444 | 445 | request.send(); 446 | }; 447 | 448 | EventSource.prototype.XHR.prototype = { 449 | 450 | useXDomainRequest: false, 451 | 452 | _request: null, 453 | 454 | _failed: false, // true if we have had errors... 455 | 456 | isReady: function() { 457 | 458 | 459 | return this._request.readyState >= 2; 460 | }, 461 | 462 | isDone: function() { 463 | 464 | return (this._request.readyState == 4); 465 | }, 466 | 467 | hasError: function() { 468 | 469 | return (this._failed || (this._request.status >= 400)); 470 | }, 471 | 472 | getBuffer: function() { 473 | 474 | var rv = ''; 475 | try { 476 | rv = this._request.responseText || ''; 477 | } 478 | catch (e){} 479 | return rv; 480 | }, 481 | 482 | abort: function() { 483 | 484 | if ( this._request ) { 485 | this._request.abort(); 486 | } 487 | } 488 | }; 489 | } 490 | else { 491 | 492 | EventSource.isPolyfill = "IE_8-9"; 493 | 494 | // patch EventSource defaultOptions 495 | var defaults = EventSource.prototype.defaultOptions; 496 | defaults.xhrHeaders = null; // no headers will be sent 497 | defaults.getArgs['evs_preamble'] = 2048 + 8; 498 | 499 | // EventSource will send request using Internet Explorer XDomainRequest 500 | EventSource.prototype.XHR = function(evs) { 501 | 502 | request = new XDomainRequest(); 503 | this._request = request; 504 | 505 | // set handlers 506 | request.onprogress = function(){ 507 | request._ready = true; 508 | evs._onxhrdata(); 509 | }; 510 | 511 | request.onload = function(){ 512 | this._loaded = true; 513 | evs._onxhrdata(); 514 | }; 515 | 516 | request.onerror = function(){ 517 | this._failed = true; 518 | evs.readyState = evs.CLOSED; 519 | evs.dispatchEvent('error', { 520 | type: 'error', 521 | data: "XDomainRequest error" 522 | }); 523 | }; 524 | 525 | request.ontimeout = function(){ 526 | this._failed = true; 527 | evs.readyState = evs.CLOSED; 528 | evs.dispatchEvent('error', { 529 | type: 'error', 530 | data: "XDomainRequest timed out" 531 | }); 532 | }; 533 | 534 | // XDomainRequest does not allow setting custom headers 535 | // If EventSource has enabled the use of GET arguments 536 | // we add parameters to URL so that server can adapt the stream... 537 | var reqGetArgs = {}; 538 | if (evs.getArgs) { 539 | 540 | // copy evs.getArgs in reqGetArgs 541 | var defaultArgs = evs.getArgs; 542 | for (var key in defaultArgs) { 543 | if (defaultArgs.hasOwnProperty(key)){ 544 | reqGetArgs[key] = defaultArgs[key]; 545 | } 546 | } 547 | if (evs.lastEventId){ 548 | reqGetArgs['evs_last_event_id'] = evs.lastEventId; 549 | } 550 | } 551 | // send the request 552 | 553 | request.open('GET', evs.urlWithParams(evs.URL,reqGetArgs)); 554 | request.send(); 555 | }; 556 | 557 | EventSource.prototype.XHR.prototype = { 558 | 559 | useXDomainRequest: true, 560 | 561 | _request: null, 562 | 563 | _ready: false, // true when progress events are dispatched 564 | 565 | _loaded: false, // true when request has been loaded 566 | 567 | _failed: false, // true if when request is in error 568 | 569 | isReady: function() { 570 | 571 | return this._request._ready; 572 | }, 573 | 574 | isDone: function() { 575 | 576 | return this._request._loaded; 577 | }, 578 | 579 | hasError: function() { 580 | 581 | return this._request._failed; 582 | }, 583 | 584 | getBuffer: function() { 585 | 586 | var rv = ''; 587 | try { 588 | rv = this._request.responseText || ''; 589 | } 590 | catch (e){} 591 | return rv; 592 | }, 593 | 594 | abort: function() { 595 | 596 | if ( this._request){ 597 | this._request.abort(); 598 | } 599 | } 600 | }; 601 | } 602 | 603 | function MessageEvent(type, data, origin, lastEventId) { 604 | 605 | this.bubbles = false; 606 | this.cancelBubble = false; 607 | this.cancelable = false; 608 | this.data = data || null; 609 | this.origin = origin || ''; 610 | this.lastEventId = lastEventId || ''; 611 | this.type = type || 'message'; 612 | } 613 | 614 | function isOldIE () { 615 | 616 | //return true if we are in IE8 or IE9 617 | return (window.XDomainRequest && (window.XMLHttpRequest && new XMLHttpRequest().responseType === undefined)) ? true : false; 618 | } 619 | 620 | global[evsImportName] = EventSource; 621 | })(this); 622 | -------------------------------------------------------------------------------- /dist/eventsource.min.js: -------------------------------------------------------------------------------- 1 | !function(a){function b(a,b,c,d){this.bubbles=!1,this.cancelBubble=!1,this.cancelable=!1,this.data=b||null,this.origin=c||"",this.lastEventId=d||"",this.type=a||"message"}function c(){return window.XDomainRequest&&window.XMLHttpRequest&&void 0===(new XMLHttpRequest).responseType?!0:!1}if(!a.EventSource||a._eventSourceImportPrefix){var d=(a._eventSourceImportPrefix||"")+"EventSource",e=function(a,b){if(!a||"string"!=typeof a)throw new SyntaxError("Not enough arguments");this.URL=a,this.setOptions(b);var c=this;setTimeout(function(){c.poll()},0)};if(e.prototype={CONNECTING:0,OPEN:1,CLOSED:2,defaultOptions:{loggingEnabled:!1,loggingPrefix:"eventsource",interval:500,bufferSizeLimit:262144,silentTimeout:3e5,getArgs:{evs_buffer_size_limit:262144},xhrHeaders:{Accept:"text/event-stream","Cache-Control":"no-cache","X-Requested-With":"XMLHttpRequest"}},setOptions:function(a){var b,c=this.defaultOptions;for(b in c)c.hasOwnProperty(b)&&(this[b]=c[b]);for(b in a)b in c&&a.hasOwnProperty(b)&&(this[b]=a[b]);this.getArgs&&this.bufferSizeLimit&&(this.getArgs.evs_buffer_size_limit=this.bufferSizeLimit),("undefined"==typeof console||"undefined"==typeof console.log)&&(this.loggingEnabled=!1)},log:function(a){this.loggingEnabled&&console.log("["+this.loggingPrefix+"]:"+a)},poll:function(){try{if(this.readyState==this.CLOSED)return;this.cleanup(),this.readyState=this.CONNECTING,this.cursor=0,this.cache="",this._xhr=new this.XHR(this),this.resetNoActivityTimer()}catch(a){this.log("There were errors inside the pool try-catch"),this.dispatchEvent("error",{type:"error",data:a.message})}},pollAgain:function(a){var b=this;b.readyState=b.CONNECTING,b.dispatchEvent("error",{type:"error",data:"Reconnecting "}),this._pollTimer=setTimeout(function(){b.poll()},a||0)},cleanup:function(){this.log("evs cleaning up"),this._pollTimer&&(clearInterval(this._pollTimer),this._pollTimer=null),this._noActivityTimer&&(clearInterval(this._noActivityTimer),this._noActivityTimer=null),this._xhr&&(this._xhr.abort(),this._xhr=null)},resetNoActivityTimer:function(){if(this.silentTimeout){this._noActivityTimer&&clearInterval(this._noActivityTimer);var a=this;this._noActivityTimer=setTimeout(function(){a.log("Timeout! silentTImeout:"+a.silentTimeout),a.pollAgain()},this.silentTimeout)}},close:function(){this.readyState=this.CLOSED,this.log("Closing connection. readyState: "+this.readyState),this.cleanup()},_onxhrdata:function(){var a=this._xhr;if(a.isReady()&&!a.hasError()){this.resetNoActivityTimer(),this.readyState==this.CONNECTING&&(this.readyState=this.OPEN,this.dispatchEvent("open",{type:"open"}));var b=a.getBuffer();b.length>this.bufferSizeLimit&&(this.log("buffer.length > this.bufferSizeLimit"),this.pollAgain()),0==this.cursor&&b.length>0&&""==b.substring(0,1)&&(this.cursor=1);var c=this.lastMessageIndex(b);if(c[0]>=this.cursor){var d=c[1],e=b.substring(this.cursor,d);this.parseStream(e),this.cursor=d}a.isDone()&&(this.log("request.isDone(). reopening the connection"),this.pollAgain(this.interval))}else this.readyState!==this.CLOSED&&(this.log("this.readyState !== this.CLOSED"),this.pollAgain(this.interval))},parseStream:function(a){a=this.cache+this.normalizeToLF(a);var c,d,e,f,g,h,i=a.split("\n\n");for(c=0;c=0;--d)if(c[d]===b){c.splice(d,1);break}},_pollTimer:null,_noactivityTimer:null,_xhr:null,lastEventId:null,cache:"",cursor:0,onerror:null,onmessage:null,onopen:null,readyState:0,urlWithParams:function(a,b){var c=[];if(b){var d,e,f=encodeURIComponent;for(d in b)b.hasOwnProperty(d)&&(e=f(d)+"="+f(b[d]),c.push(e))}return c.length>0?-1==a.indexOf("?")?a+"?"+c.join("&"):a+"&"+c.join("&"):a},lastMessageIndex:function(a){var b=a.lastIndexOf("\n\n"),c=a.lastIndexOf("\r\r"),d=a.lastIndexOf("\r\n\r\n");return d>Math.max(b,c)?[d,d+4]:[Math.max(b,c),Math.max(b,c)+2]},trimWhiteSpace:function(a){var b=/^(\s|\u00A0)+|(\s|\u00A0)+$/g;return a.replace(b,"")},normalizeToLF:function(a){return a.replace(/\r\n|\r/g,"\n")}},c()){e.isPolyfill="IE_8-9";var f=e.prototype.defaultOptions;f.xhrHeaders=null,f.getArgs.evs_preamble=2056,e.prototype.XHR=function(a){request=new XDomainRequest,this._request=request,request.onprogress=function(){request._ready=!0,a._onxhrdata()},request.onload=function(){this._loaded=!0,a._onxhrdata()},request.onerror=function(){this._failed=!0,a.readyState=a.CLOSED,a.dispatchEvent("error",{type:"error",data:"XDomainRequest error"})},request.ontimeout=function(){this._failed=!0,a.readyState=a.CLOSED,a.dispatchEvent("error",{type:"error",data:"XDomainRequest timed out"})};var b={};if(a.getArgs){var c=a.getArgs;for(var d in c)c.hasOwnProperty(d)&&(b[d]=c[d]);a.lastEventId&&(b.evs_last_event_id=a.lastEventId)}request.open("GET",a.urlWithParams(a.URL,b)),request.send()},e.prototype.XHR.prototype={useXDomainRequest:!0,_request:null,_ready:!1,_loaded:!1,_failed:!1,isReady:function(){return this._request._ready},isDone:function(){return this._request._loaded},hasError:function(){return this._request._failed},getBuffer:function(){var a="";try{a=this._request.responseText||""}catch(b){}return a},abort:function(){this._request&&this._request.abort()}}}else e.isPolyfill="XHR",e.prototype.XHR=function(a){request=new XMLHttpRequest,this._request=request,a._xhr=this,request.onreadystatechange=function(){request.readyState>1&&a.readyState!=a.CLOSED&&(200==request.status||request.status>=300&&request.status<400?a._onxhrdata():(request._failed=!0,a.readyState=a.CLOSED,a.dispatchEvent("error",{type:"error",data:"The server responded with "+request.status}),a.close()))},request.onprogress=function(){},request.open("GET",a.urlWithParams(a.URL,a.getArgs),!0);var b=a.xhrHeaders;for(var c in b)b.hasOwnProperty(c)&&request.setRequestHeader(c,b[c]);a.lastEventId&&request.setRequestHeader("Last-Event-Id",a.lastEventId),request.send()},e.prototype.XHR.prototype={useXDomainRequest:!1,_request:null,_failed:!1,isReady:function(){return this._request.readyState>=2},isDone:function(){return 4==this._request.readyState},hasError:function(){return this._failed||this._request.status>=400},getBuffer:function(){var a="";try{a=this._request.responseText||""}catch(b){}return a},abort:function(){this._request&&this._request.abort()}};a[d]=e}}(this); -------------------------------------------------------------------------------- /javascript/SpecConcurrentRunner.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Polyfill EventSource Test Suite 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |

Concurrent polyfill EventSource Test Suite

31 | 32 |
33 |

34 | Be patient, those tests need a few minutes to complete. 35 |

36 | 37 | 45 |
46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /javascript/SpecRunner.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Polyfill EventSource Test Suite 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |

Polyfill EventSource Test Suite

31 | 32 |
33 |

34 | Be patient, those tests need a few minutes to complete. 35 |

36 | 37 | 45 |
46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /javascript/lib/jasmine-2.0.0/boot.js: -------------------------------------------------------------------------------- 1 | /** 2 | Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. 3 | 4 | If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. 5 | 6 | The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. 7 | 8 | [jasmine-gem]: http://github.com/pivotal/jasmine-gem 9 | */ 10 | 11 | (function() { 12 | 13 | /** 14 | * ## Require & Instantiate 15 | * 16 | * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. 17 | */ 18 | window.jasmine = jasmineRequire.core(jasmineRequire); 19 | 20 | /** 21 | * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. 22 | */ 23 | jasmineRequire.html(jasmine); 24 | 25 | /** 26 | * Create the Jasmine environment. This is used to run all specs in a project. 27 | */ 28 | var env = jasmine.getEnv(); 29 | 30 | /** 31 | * ## The Global Interface 32 | * 33 | * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. 34 | */ 35 | var jasmineInterface = { 36 | describe: function(description, specDefinitions) { 37 | return env.describe(description, specDefinitions); 38 | }, 39 | 40 | xdescribe: function(description, specDefinitions) { 41 | return env.xdescribe(description, specDefinitions); 42 | }, 43 | 44 | it: function(desc, func) { 45 | return env.it(desc, func); 46 | }, 47 | 48 | xit: function(desc, func) { 49 | return env.xit(desc, func); 50 | }, 51 | 52 | beforeEach: function(beforeEachFunction) { 53 | return env.beforeEach(beforeEachFunction); 54 | }, 55 | 56 | afterEach: function(afterEachFunction) { 57 | return env.afterEach(afterEachFunction); 58 | }, 59 | 60 | expect: function(actual) { 61 | return env.expect(actual); 62 | }, 63 | 64 | pending: function() { 65 | return env.pending(); 66 | }, 67 | 68 | spyOn: function(obj, methodName) { 69 | return env.spyOn(obj, methodName); 70 | }, 71 | 72 | jsApiReporter: new jasmine.JsApiReporter({ 73 | timer: new jasmine.Timer() 74 | }) 75 | }; 76 | 77 | /** 78 | * Add all of the Jasmine global/public interface to the proper global, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. 79 | */ 80 | if (typeof window == "undefined" && typeof exports == "object") { 81 | extend(exports, jasmineInterface); 82 | } else { 83 | extend(window, jasmineInterface); 84 | } 85 | 86 | /** 87 | * Expose the interface for adding custom equality testers. 88 | */ 89 | jasmine.addCustomEqualityTester = function(tester) { 90 | env.addCustomEqualityTester(tester); 91 | }; 92 | 93 | /** 94 | * Expose the interface for adding custom expectation matchers 95 | */ 96 | jasmine.addMatchers = function(matchers) { 97 | return env.addMatchers(matchers); 98 | }; 99 | 100 | /** 101 | * Expose the mock interface for the JavaScript timeout functions 102 | */ 103 | jasmine.clock = function() { 104 | return env.clock; 105 | }; 106 | 107 | /** 108 | * ## Runner Parameters 109 | * 110 | * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. 111 | */ 112 | 113 | var queryString = new jasmine.QueryString({ 114 | getWindowLocation: function() { return window.location; } 115 | }); 116 | 117 | var catchingExceptions = queryString.getParam("catch"); 118 | env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions); 119 | 120 | /** 121 | * ## Reporters 122 | * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). 123 | */ 124 | var htmlReporter = new jasmine.HtmlReporter({ 125 | env: env, 126 | onRaiseExceptionsClick: function() { queryString.setParam("catch", !env.catchingExceptions()); }, 127 | getContainer: function() { return document.body; }, 128 | createElement: function() { return document.createElement.apply(document, arguments); }, 129 | createTextNode: function() { return document.createTextNode.apply(document, arguments); }, 130 | timer: new jasmine.Timer() 131 | }); 132 | 133 | /** 134 | * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. 135 | */ 136 | env.addReporter(jasmineInterface.jsApiReporter); 137 | env.addReporter(htmlReporter); 138 | 139 | /** 140 | * Filter which specs will be run by matching the start of the full name against the `spec` query param. 141 | */ 142 | var specFilter = new jasmine.HtmlSpecFilter({ 143 | filterString: function() { return queryString.getParam("spec"); } 144 | }); 145 | 146 | env.specFilter = function(spec) { 147 | return specFilter.matches(spec.getFullName()); 148 | }; 149 | 150 | /** 151 | * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. 152 | */ 153 | window.setTimeout = window.setTimeout; 154 | window.setInterval = window.setInterval; 155 | window.clearTimeout = window.clearTimeout; 156 | window.clearInterval = window.clearInterval; 157 | 158 | /** 159 | * ## Execution 160 | * 161 | * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. 162 | */ 163 | var currentWindowOnload = window.onload; 164 | 165 | window.onload = function() { 166 | if (currentWindowOnload) { 167 | currentWindowOnload(); 168 | } 169 | htmlReporter.initialize(); 170 | env.execute(); 171 | }; 172 | 173 | /** 174 | * Helper function for readability above. 175 | */ 176 | function extend(destination, source) { 177 | for (var property in source) destination[property] = source[property]; 178 | return destination; 179 | } 180 | 181 | }()); 182 | -------------------------------------------------------------------------------- /javascript/lib/jasmine-2.0.0/console.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2008-2013 Pivotal Labs 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining 5 | a copy of this software and associated documentation files (the 6 | "Software"), to deal in the Software without restriction, including 7 | without limitation the rights to use, copy, modify, merge, publish, 8 | distribute, sublicense, and/or sell copies of the Software, and to 9 | permit persons to whom the Software is furnished to do so, subject to 10 | the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 19 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 20 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 21 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 | */ 23 | function getJasmineRequireObj() { 24 | if (typeof module !== "undefined" && module.exports) { 25 | return exports; 26 | } else { 27 | window.jasmineRequire = window.jasmineRequire || {}; 28 | return window.jasmineRequire; 29 | } 30 | } 31 | 32 | getJasmineRequireObj().console = function(jRequire, j$) { 33 | j$.ConsoleReporter = jRequire.ConsoleReporter(); 34 | }; 35 | 36 | getJasmineRequireObj().ConsoleReporter = function() { 37 | 38 | var noopTimer = { 39 | start: function(){}, 40 | elapsed: function(){ return 0; } 41 | }; 42 | 43 | function ConsoleReporter(options) { 44 | var print = options.print, 45 | showColors = options.showColors || false, 46 | onComplete = options.onComplete || function() {}, 47 | timer = options.timer || noopTimer, 48 | specCount, 49 | failureCount, 50 | failedSpecs = [], 51 | pendingCount, 52 | ansi = { 53 | green: '\x1B[32m', 54 | red: '\x1B[31m', 55 | yellow: '\x1B[33m', 56 | none: '\x1B[0m' 57 | }; 58 | 59 | this.jasmineStarted = function() { 60 | specCount = 0; 61 | failureCount = 0; 62 | pendingCount = 0; 63 | print("Started"); 64 | printNewline(); 65 | timer.start(); 66 | }; 67 | 68 | this.jasmineDone = function() { 69 | printNewline(); 70 | for (var i = 0; i < failedSpecs.length; i++) { 71 | specFailureDetails(failedSpecs[i]); 72 | } 73 | 74 | printNewline(); 75 | var specCounts = specCount + " " + plural("spec", specCount) + ", " + 76 | failureCount + " " + plural("failure", failureCount); 77 | 78 | if (pendingCount) { 79 | specCounts += ", " + pendingCount + " pending " + plural("spec", pendingCount); 80 | } 81 | 82 | print(specCounts); 83 | 84 | printNewline(); 85 | var seconds = timer.elapsed() / 1000; 86 | print("Finished in " + seconds + " " + plural("second", seconds)); 87 | 88 | printNewline(); 89 | 90 | onComplete(failureCount === 0); 91 | }; 92 | 93 | this.specDone = function(result) { 94 | specCount++; 95 | 96 | if (result.status == "pending") { 97 | pendingCount++; 98 | print(colored("yellow", "*")); 99 | return; 100 | } 101 | 102 | if (result.status == "passed") { 103 | print(colored("green", '.')); 104 | return; 105 | } 106 | 107 | if (result.status == "failed") { 108 | failureCount++; 109 | failedSpecs.push(result); 110 | print(colored("red", 'F')); 111 | } 112 | }; 113 | 114 | return this; 115 | 116 | function printNewline() { 117 | print("\n"); 118 | } 119 | 120 | function colored(color, str) { 121 | return showColors ? (ansi[color] + str + ansi.none) : str; 122 | } 123 | 124 | function plural(str, count) { 125 | return count == 1 ? str : str + "s"; 126 | } 127 | 128 | function repeat(thing, times) { 129 | var arr = []; 130 | for (var i = 0; i < times; i++) { 131 | arr.push(thing); 132 | } 133 | return arr; 134 | } 135 | 136 | function indent(str, spaces) { 137 | var lines = (str || '').split("\n"); 138 | var newArr = []; 139 | for (var i = 0; i < lines.length; i++) { 140 | newArr.push(repeat(" ", spaces).join("") + lines[i]); 141 | } 142 | return newArr.join("\n"); 143 | } 144 | 145 | function specFailureDetails(result) { 146 | printNewline(); 147 | print(result.fullName); 148 | 149 | for (var i = 0; i < result.failedExpectations.length; i++) { 150 | var failedExpectation = result.failedExpectations[i]; 151 | printNewline(); 152 | print(indent(failedExpectation.stack, 2)); 153 | } 154 | 155 | printNewline(); 156 | } 157 | } 158 | 159 | return ConsoleReporter; 160 | }; 161 | -------------------------------------------------------------------------------- /javascript/lib/jasmine-2.0.0/jasmine-html.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2008-2013 Pivotal Labs 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining 5 | a copy of this software and associated documentation files (the 6 | "Software"), to deal in the Software without restriction, including 7 | without limitation the rights to use, copy, modify, merge, publish, 8 | distribute, sublicense, and/or sell copies of the Software, and to 9 | permit persons to whom the Software is furnished to do so, subject to 10 | the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 19 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 20 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 21 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 | */ 23 | jasmineRequire.html = function(j$) { 24 | j$.ResultsNode = jasmineRequire.ResultsNode(); 25 | j$.HtmlReporter = jasmineRequire.HtmlReporter(j$); 26 | j$.QueryString = jasmineRequire.QueryString(); 27 | j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter(); 28 | }; 29 | 30 | jasmineRequire.HtmlReporter = function(j$) { 31 | 32 | var noopTimer = { 33 | start: function() {}, 34 | elapsed: function() { return 0; } 35 | }; 36 | 37 | function HtmlReporter(options) { 38 | var env = options.env || {}, 39 | getContainer = options.getContainer, 40 | createElement = options.createElement, 41 | createTextNode = options.createTextNode, 42 | onRaiseExceptionsClick = options.onRaiseExceptionsClick || function() {}, 43 | timer = options.timer || noopTimer, 44 | results = [], 45 | specsExecuted = 0, 46 | failureCount = 0, 47 | pendingSpecCount = 0, 48 | htmlReporterMain, 49 | symbols; 50 | 51 | this.initialize = function() { 52 | htmlReporterMain = createDom("div", {className: "html-reporter"}, 53 | createDom("div", {className: "banner"}, 54 | createDom("span", {className: "title"}, "Jasmine"), 55 | createDom("span", {className: "version"}, j$.version) 56 | ), 57 | createDom("ul", {className: "symbol-summary"}), 58 | createDom("div", {className: "alert"}), 59 | createDom("div", {className: "results"}, 60 | createDom("div", {className: "failures"}) 61 | ) 62 | ); 63 | getContainer().appendChild(htmlReporterMain); 64 | 65 | symbols = find(".symbol-summary"); 66 | }; 67 | 68 | var totalSpecsDefined; 69 | this.jasmineStarted = function(options) { 70 | totalSpecsDefined = options.totalSpecsDefined || 0; 71 | timer.start(); 72 | }; 73 | 74 | var summary = createDom("div", {className: "summary"}); 75 | 76 | var topResults = new j$.ResultsNode({}, "", null), 77 | currentParent = topResults; 78 | 79 | this.suiteStarted = function(result) { 80 | currentParent.addChild(result, "suite"); 81 | currentParent = currentParent.last(); 82 | }; 83 | 84 | this.suiteDone = function(result) { 85 | if (currentParent == topResults) { 86 | return; 87 | } 88 | 89 | currentParent = currentParent.parent; 90 | }; 91 | 92 | this.specStarted = function(result) { 93 | currentParent.addChild(result, "spec"); 94 | }; 95 | 96 | var failures = []; 97 | this.specDone = function(result) { 98 | if (result.status != "disabled") { 99 | specsExecuted++; 100 | } 101 | 102 | symbols.appendChild(createDom("li", { 103 | className: result.status, 104 | id: "spec_" + result.id, 105 | title: result.fullName 106 | } 107 | )); 108 | 109 | if (result.status == "failed") { 110 | failureCount++; 111 | 112 | var failure = 113 | createDom("div", {className: "spec-detail failed"}, 114 | createDom("div", {className: "description"}, 115 | createDom("a", {title: result.fullName, href: specHref(result)}, result.fullName) 116 | ), 117 | createDom("div", {className: "messages"}) 118 | ); 119 | var messages = failure.childNodes[1]; 120 | 121 | for (var i = 0; i < result.failedExpectations.length; i++) { 122 | var expectation = result.failedExpectations[i]; 123 | messages.appendChild(createDom("div", {className: "result-message"}, expectation.message)); 124 | messages.appendChild(createDom("div", {className: "stack-trace"}, expectation.stack)); 125 | } 126 | 127 | failures.push(failure); 128 | } 129 | 130 | if (result.status == "pending") { 131 | pendingSpecCount++; 132 | } 133 | }; 134 | 135 | this.jasmineDone = function() { 136 | var banner = find(".banner"); 137 | banner.appendChild(createDom("span", {className: "duration"}, "finished in " + timer.elapsed() / 1000 + "s")); 138 | 139 | var alert = find(".alert"); 140 | 141 | alert.appendChild(createDom("span", { className: "exceptions" }, 142 | createDom("label", { className: "label", 'for': "raise-exceptions" }, "raise exceptions"), 143 | createDom("input", { 144 | className: "raise", 145 | id: "raise-exceptions", 146 | type: "checkbox" 147 | }) 148 | )); 149 | var checkbox = find("input"); 150 | 151 | checkbox.checked = !env.catchingExceptions(); 152 | checkbox.onclick = onRaiseExceptionsClick; 153 | 154 | if (specsExecuted < totalSpecsDefined) { 155 | var skippedMessage = "Ran " + specsExecuted + " of " + totalSpecsDefined + " specs - run all"; 156 | alert.appendChild( 157 | createDom("span", {className: "bar skipped"}, 158 | createDom("a", {href: "?", title: "Run all specs"}, skippedMessage) 159 | ) 160 | ); 161 | } 162 | var statusBarMessage = "" + pluralize("spec", specsExecuted) + ", " + pluralize("failure", failureCount); 163 | if (pendingSpecCount) { statusBarMessage += ", " + pluralize("pending spec", pendingSpecCount); } 164 | 165 | var statusBarClassName = "bar " + ((failureCount > 0) ? "failed" : "passed"); 166 | alert.appendChild(createDom("span", {className: statusBarClassName}, statusBarMessage)); 167 | 168 | var results = find(".results"); 169 | results.appendChild(summary); 170 | 171 | summaryList(topResults, summary); 172 | 173 | function summaryList(resultsTree, domParent) { 174 | var specListNode; 175 | for (var i = 0; i < resultsTree.children.length; i++) { 176 | var resultNode = resultsTree.children[i]; 177 | if (resultNode.type == "suite") { 178 | var suiteListNode = createDom("ul", {className: "suite", id: "suite-" + resultNode.result.id}, 179 | createDom("li", {className: "suite-detail"}, 180 | createDom("a", {href: specHref(resultNode.result)}, resultNode.result.description) 181 | ) 182 | ); 183 | 184 | summaryList(resultNode, suiteListNode); 185 | domParent.appendChild(suiteListNode); 186 | } 187 | if (resultNode.type == "spec") { 188 | if (domParent.getAttribute("class") != "specs") { 189 | specListNode = createDom("ul", {className: "specs"}); 190 | domParent.appendChild(specListNode); 191 | } 192 | specListNode.appendChild( 193 | createDom("li", { 194 | className: resultNode.result.status, 195 | id: "spec-" + resultNode.result.id 196 | }, 197 | createDom("a", {href: specHref(resultNode.result)}, resultNode.result.description) 198 | ) 199 | ); 200 | } 201 | } 202 | } 203 | 204 | if (failures.length) { 205 | alert.appendChild( 206 | createDom('span', {className: "menu bar spec-list"}, 207 | createDom("span", {}, "Spec List | "), 208 | createDom('a', {className: "failures-menu", href: "#"}, "Failures"))); 209 | alert.appendChild( 210 | createDom('span', {className: "menu bar failure-list"}, 211 | createDom('a', {className: "spec-list-menu", href: "#"}, "Spec List"), 212 | createDom("span", {}, " | Failures "))); 213 | 214 | find(".failures-menu").onclick = function() { 215 | setMenuModeTo('failure-list'); 216 | }; 217 | find(".spec-list-menu").onclick = function() { 218 | setMenuModeTo('spec-list'); 219 | }; 220 | 221 | setMenuModeTo('failure-list'); 222 | 223 | var failureNode = find(".failures"); 224 | for (var i = 0; i < failures.length; i++) { 225 | failureNode.appendChild(failures[i]); 226 | } 227 | } 228 | }; 229 | 230 | return this; 231 | 232 | function find(selector) { 233 | return getContainer().querySelector(selector); 234 | } 235 | 236 | function createDom(type, attrs, childrenVarArgs) { 237 | var el = createElement(type); 238 | 239 | for (var i = 2; i < arguments.length; i++) { 240 | var child = arguments[i]; 241 | 242 | if (typeof child === 'string') { 243 | el.appendChild(createTextNode(child)); 244 | } else { 245 | if (child) { 246 | el.appendChild(child); 247 | } 248 | } 249 | } 250 | 251 | for (var attr in attrs) { 252 | if (attr == "className") { 253 | el[attr] = attrs[attr]; 254 | } else { 255 | el.setAttribute(attr, attrs[attr]); 256 | } 257 | } 258 | 259 | return el; 260 | } 261 | 262 | function pluralize(singular, count) { 263 | var word = (count == 1 ? singular : singular + "s"); 264 | 265 | return "" + count + " " + word; 266 | } 267 | 268 | function specHref(result) { 269 | return "?spec=" + encodeURIComponent(result.fullName); 270 | } 271 | 272 | function setMenuModeTo(mode) { 273 | htmlReporterMain.setAttribute("class", "html-reporter " + mode); 274 | } 275 | } 276 | 277 | return HtmlReporter; 278 | }; 279 | 280 | jasmineRequire.HtmlSpecFilter = function() { 281 | function HtmlSpecFilter(options) { 282 | var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); 283 | var filterPattern = new RegExp(filterString); 284 | 285 | this.matches = function(specName) { 286 | return filterPattern.test(specName); 287 | }; 288 | } 289 | 290 | return HtmlSpecFilter; 291 | }; 292 | 293 | jasmineRequire.ResultsNode = function() { 294 | function ResultsNode(result, type, parent) { 295 | this.result = result; 296 | this.type = type; 297 | this.parent = parent; 298 | 299 | this.children = []; 300 | 301 | this.addChild = function(result, type) { 302 | this.children.push(new ResultsNode(result, type, this)); 303 | }; 304 | 305 | this.last = function() { 306 | return this.children[this.children.length - 1]; 307 | }; 308 | } 309 | 310 | return ResultsNode; 311 | }; 312 | 313 | jasmineRequire.QueryString = function() { 314 | function QueryString(options) { 315 | 316 | this.setParam = function(key, value) { 317 | var paramMap = queryStringToParamMap(); 318 | paramMap[key] = value; 319 | options.getWindowLocation().search = toQueryString(paramMap); 320 | }; 321 | 322 | this.getParam = function(key) { 323 | return queryStringToParamMap()[key]; 324 | }; 325 | 326 | return this; 327 | 328 | function toQueryString(paramMap) { 329 | var qStrPairs = []; 330 | for (var prop in paramMap) { 331 | qStrPairs.push(encodeURIComponent(prop) + "=" + encodeURIComponent(paramMap[prop])); 332 | } 333 | return "?" + qStrPairs.join('&'); 334 | } 335 | 336 | function queryStringToParamMap() { 337 | var paramStr = options.getWindowLocation().search.substring(1), 338 | params = [], 339 | paramMap = {}; 340 | 341 | if (paramStr.length > 0) { 342 | params = paramStr.split('&'); 343 | for (var i = 0; i < params.length; i++) { 344 | var p = params[i].split('='); 345 | var value = decodeURIComponent(p[1]); 346 | if (value === "true" || value === "false") { 347 | value = JSON.parse(value); 348 | } 349 | paramMap[decodeURIComponent(p[0])] = value; 350 | } 351 | } 352 | 353 | return paramMap; 354 | } 355 | 356 | } 357 | 358 | return QueryString; 359 | }; 360 | -------------------------------------------------------------------------------- /javascript/lib/jasmine-2.0.0/jasmine.css: -------------------------------------------------------------------------------- 1 | body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; } 2 | 3 | .html-reporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; } 4 | .html-reporter a { text-decoration: none; } 5 | .html-reporter a:hover { text-decoration: underline; } 6 | .html-reporter p, .html-reporter h1, .html-reporter h2, .html-reporter h3, .html-reporter h4, .html-reporter h5, .html-reporter h6 { margin: 0; line-height: 14px; } 7 | .html-reporter .banner, .html-reporter .symbol-summary, .html-reporter .summary, .html-reporter .result-message, .html-reporter .spec .description, .html-reporter .spec-detail .description, .html-reporter .alert .bar, .html-reporter .stack-trace { padding-left: 9px; padding-right: 9px; } 8 | .html-reporter .banner .version { margin-left: 14px; } 9 | .html-reporter #jasmine_content { position: fixed; right: 100%; } 10 | .html-reporter .version { color: #aaaaaa; } 11 | .html-reporter .banner { margin-top: 14px; } 12 | .html-reporter .duration { color: #aaaaaa; float: right; } 13 | .html-reporter .symbol-summary { overflow: hidden; *zoom: 1; margin: 14px 0; } 14 | .html-reporter .symbol-summary li { display: inline-block; height: 8px; width: 14px; font-size: 16px; } 15 | .html-reporter .symbol-summary li.passed { font-size: 14px; } 16 | .html-reporter .symbol-summary li.passed:before { color: #5e7d00; content: "\02022"; } 17 | .html-reporter .symbol-summary li.failed { line-height: 9px; } 18 | .html-reporter .symbol-summary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; } 19 | .html-reporter .symbol-summary li.disabled { font-size: 14px; } 20 | .html-reporter .symbol-summary li.disabled:before { color: #bababa; content: "\02022"; } 21 | .html-reporter .symbol-summary li.pending { line-height: 17px; } 22 | .html-reporter .symbol-summary li.pending:before { color: #ba9d37; content: "*"; } 23 | .html-reporter .exceptions { color: #fff; float: right; margin-top: 5px; margin-right: 5px; } 24 | .html-reporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; } 25 | .html-reporter .bar.failed { background-color: #b03911; } 26 | .html-reporter .bar.passed { background-color: #a6b779; } 27 | .html-reporter .bar.skipped { background-color: #bababa; } 28 | .html-reporter .bar.menu { background-color: #fff; color: #aaaaaa; } 29 | .html-reporter .bar.menu a { color: #333333; } 30 | .html-reporter .bar a { color: white; } 31 | .html-reporter.spec-list .bar.menu.failure-list, .html-reporter.spec-list .results .failures { display: none; } 32 | .html-reporter.failure-list .bar.menu.spec-list, .html-reporter.failure-list .summary { display: none; } 33 | .html-reporter .running-alert { background-color: #666666; } 34 | .html-reporter .results { margin-top: 14px; } 35 | .html-reporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; } 36 | .html-reporter.showDetails .summaryMenuItem:hover { text-decoration: underline; } 37 | .html-reporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; } 38 | .html-reporter.showDetails .summary { display: none; } 39 | .html-reporter.showDetails #details { display: block; } 40 | .html-reporter .summaryMenuItem { font-weight: bold; text-decoration: underline; } 41 | .html-reporter .summary { margin-top: 14px; } 42 | .html-reporter .summary ul { list-style-type: none; margin-left: 14px; padding-top: 0; padding-left: 0; } 43 | .html-reporter .summary ul.suite { margin-top: 7px; margin-bottom: 7px; } 44 | .html-reporter .summary li.passed a { color: #5e7d00; } 45 | .html-reporter .summary li.failed a { color: #b03911; } 46 | .html-reporter .summary li.pending a { color: #ba9d37; } 47 | .html-reporter .description + .suite { margin-top: 0; } 48 | .html-reporter .suite { margin-top: 14px; } 49 | .html-reporter .suite a { color: #333333; } 50 | .html-reporter .failures .spec-detail { margin-bottom: 28px; } 51 | .html-reporter .failures .spec-detail .description { background-color: #b03911; } 52 | .html-reporter .failures .spec-detail .description a { color: white; } 53 | .html-reporter .result-message { padding-top: 14px; color: #333333; white-space: pre; } 54 | .html-reporter .result-message span.result { display: block; } 55 | .html-reporter .stack-trace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; } 56 | -------------------------------------------------------------------------------- /javascript/lib/jasmine-2.0.0/jasmine.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2008-2013 Pivotal Labs 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining 5 | a copy of this software and associated documentation files (the 6 | "Software"), to deal in the Software without restriction, including 7 | without limitation the rights to use, copy, modify, merge, publish, 8 | distribute, sublicense, and/or sell copies of the Software, and to 9 | permit persons to whom the Software is furnished to do so, subject to 10 | the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 19 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 20 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 21 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 | */ 23 | function getJasmineRequireObj() { 24 | if (typeof module !== "undefined" && module.exports) { 25 | return exports; 26 | } else { 27 | window.jasmineRequire = window.jasmineRequire || {}; 28 | return window.jasmineRequire; 29 | } 30 | } 31 | 32 | getJasmineRequireObj().core = function(jRequire) { 33 | var j$ = {}; 34 | 35 | jRequire.base(j$); 36 | j$.util = jRequire.util(); 37 | j$.Any = jRequire.Any(); 38 | j$.CallTracker = jRequire.CallTracker(); 39 | j$.Clock = jRequire.Clock(); 40 | j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler(); 41 | j$.Env = jRequire.Env(j$); 42 | j$.ExceptionFormatter = jRequire.ExceptionFormatter(); 43 | j$.Expectation = jRequire.Expectation(); 44 | j$.buildExpectationResult = jRequire.buildExpectationResult(); 45 | j$.JsApiReporter = jRequire.JsApiReporter(); 46 | j$.matchersUtil = jRequire.matchersUtil(j$); 47 | j$.ObjectContaining = jRequire.ObjectContaining(j$); 48 | j$.pp = jRequire.pp(j$); 49 | j$.QueueRunner = jRequire.QueueRunner(); 50 | j$.ReportDispatcher = jRequire.ReportDispatcher(); 51 | j$.Spec = jRequire.Spec(j$); 52 | j$.SpyStrategy = jRequire.SpyStrategy(); 53 | j$.Suite = jRequire.Suite(); 54 | j$.Timer = jRequire.Timer(); 55 | j$.version = jRequire.version(); 56 | 57 | j$.matchers = jRequire.requireMatchers(jRequire, j$); 58 | 59 | return j$; 60 | }; 61 | 62 | getJasmineRequireObj().requireMatchers = function(jRequire, j$) { 63 | var availableMatchers = [ 64 | "toBe", 65 | "toBeCloseTo", 66 | "toBeDefined", 67 | "toBeFalsy", 68 | "toBeGreaterThan", 69 | "toBeLessThan", 70 | "toBeNaN", 71 | "toBeNull", 72 | "toBeTruthy", 73 | "toBeUndefined", 74 | "toContain", 75 | "toEqual", 76 | "toHaveBeenCalled", 77 | "toHaveBeenCalledWith", 78 | "toMatch", 79 | "toThrow", 80 | "toThrowError" 81 | ], 82 | matchers = {}; 83 | 84 | for (var i = 0; i < availableMatchers.length; i++) { 85 | var name = availableMatchers[i]; 86 | matchers[name] = jRequire[name](j$); 87 | } 88 | 89 | return matchers; 90 | }; 91 | 92 | getJasmineRequireObj().base = function(j$) { 93 | j$.unimplementedMethod_ = function() { 94 | throw new Error("unimplemented method"); 95 | }; 96 | 97 | j$.MAX_PRETTY_PRINT_DEPTH = 40; 98 | j$.DEFAULT_TIMEOUT_INTERVAL = 50000; 99 | 100 | j$.getGlobal = (function() { 101 | var jasmineGlobal = eval.call(null, "this"); 102 | return function() { 103 | return jasmineGlobal; 104 | }; 105 | })(); 106 | 107 | j$.getEnv = function(options) { 108 | var env = j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options); 109 | //jasmine. singletons in here (setTimeout blah blah). 110 | return env; 111 | }; 112 | 113 | j$.isArray_ = function(value) { 114 | return j$.isA_("Array", value); 115 | }; 116 | 117 | j$.isString_ = function(value) { 118 | return j$.isA_("String", value); 119 | }; 120 | 121 | j$.isNumber_ = function(value) { 122 | return j$.isA_("Number", value); 123 | }; 124 | 125 | j$.isA_ = function(typeName, value) { 126 | return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; 127 | }; 128 | 129 | j$.isDomNode = function(obj) { 130 | return obj.nodeType > 0; 131 | }; 132 | 133 | j$.any = function(clazz) { 134 | return new j$.Any(clazz); 135 | }; 136 | 137 | j$.objectContaining = function(sample) { 138 | return new j$.ObjectContaining(sample); 139 | }; 140 | 141 | j$.createSpy = function(name, originalFn) { 142 | 143 | var spyStrategy = new j$.SpyStrategy({ 144 | name: name, 145 | fn: originalFn, 146 | getSpy: function() { return spy; } 147 | }), 148 | callTracker = new j$.CallTracker(), 149 | spy = function() { 150 | callTracker.track({ 151 | object: this, 152 | args: Array.prototype.slice.apply(arguments) 153 | }); 154 | return spyStrategy.exec.apply(this, arguments); 155 | }; 156 | 157 | for (var prop in originalFn) { 158 | if (prop === 'and' || prop === 'calls') { 159 | throw new Error("Jasmine spies would overwrite the 'and' and 'calls' properties on the object being spied upon"); 160 | } 161 | 162 | spy[prop] = originalFn[prop]; 163 | } 164 | 165 | spy.and = spyStrategy; 166 | spy.calls = callTracker; 167 | 168 | return spy; 169 | }; 170 | 171 | j$.isSpy = function(putativeSpy) { 172 | if (!putativeSpy) { 173 | return false; 174 | } 175 | return putativeSpy.and instanceof j$.SpyStrategy && 176 | putativeSpy.calls instanceof j$.CallTracker; 177 | }; 178 | 179 | j$.createSpyObj = function(baseName, methodNames) { 180 | if (!j$.isArray_(methodNames) || methodNames.length === 0) { 181 | throw "createSpyObj requires a non-empty array of method names to create spies for"; 182 | } 183 | var obj = {}; 184 | for (var i = 0; i < methodNames.length; i++) { 185 | obj[methodNames[i]] = j$.createSpy(baseName + '.' + methodNames[i]); 186 | } 187 | return obj; 188 | }; 189 | }; 190 | 191 | getJasmineRequireObj().util = function() { 192 | 193 | var util = {}; 194 | 195 | util.inherit = function(childClass, parentClass) { 196 | var Subclass = function() { 197 | }; 198 | Subclass.prototype = parentClass.prototype; 199 | childClass.prototype = new Subclass(); 200 | }; 201 | 202 | util.htmlEscape = function(str) { 203 | if (!str) { 204 | return str; 205 | } 206 | return str.replace(/&/g, '&') 207 | .replace(//g, '>'); 209 | }; 210 | 211 | util.argsToArray = function(args) { 212 | var arrayOfArgs = []; 213 | for (var i = 0; i < args.length; i++) { 214 | arrayOfArgs.push(args[i]); 215 | } 216 | return arrayOfArgs; 217 | }; 218 | 219 | util.isUndefined = function(obj) { 220 | return obj === void 0; 221 | }; 222 | 223 | return util; 224 | }; 225 | 226 | getJasmineRequireObj().Spec = function(j$) { 227 | function Spec(attrs) { 228 | this.expectationFactory = attrs.expectationFactory; 229 | this.resultCallback = attrs.resultCallback || function() {}; 230 | this.id = attrs.id; 231 | this.description = attrs.description || ''; 232 | this.fn = attrs.fn; 233 | this.beforeFns = attrs.beforeFns || function() { return []; }; 234 | this.afterFns = attrs.afterFns || function() { return []; }; 235 | this.onStart = attrs.onStart || function() {}; 236 | this.exceptionFormatter = attrs.exceptionFormatter || function() {}; 237 | this.getSpecName = attrs.getSpecName || function() { return ''; }; 238 | this.expectationResultFactory = attrs.expectationResultFactory || function() { }; 239 | this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; 240 | this.catchingExceptions = attrs.catchingExceptions || function() { return true; }; 241 | 242 | this.timer = attrs.timer || {setTimeout: setTimeout, clearTimeout: clearTimeout}; 243 | 244 | if (!this.fn) { 245 | this.pend(); 246 | } 247 | 248 | this.result = { 249 | id: this.id, 250 | description: this.description, 251 | fullName: this.getFullName(), 252 | failedExpectations: [] 253 | }; 254 | } 255 | 256 | Spec.prototype.addExpectationResult = function(passed, data) { 257 | if (passed) { 258 | return; 259 | } 260 | this.result.failedExpectations.push(this.expectationResultFactory(data)); 261 | }; 262 | 263 | Spec.prototype.expect = function(actual) { 264 | return this.expectationFactory(actual, this); 265 | }; 266 | 267 | Spec.prototype.execute = function(onComplete) { 268 | var self = this, 269 | timeout; 270 | 271 | this.onStart(this); 272 | 273 | if (this.markedPending || this.disabled) { 274 | complete(); 275 | return; 276 | } 277 | 278 | function timeoutable(fn) { 279 | return function(done) { 280 | timeout = Function.prototype.apply.apply(self.timer.setTimeout, [j$.getGlobal(), [function() { 281 | onException(new Error('Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.')); 282 | done(); 283 | }, j$.DEFAULT_TIMEOUT_INTERVAL]]); 284 | 285 | var callDone = function() { 286 | clearTimeoutable(); 287 | done(); 288 | }; 289 | 290 | fn.call(this, callDone); //TODO: do we care about more than 1 arg? 291 | }; 292 | } 293 | 294 | function clearTimeoutable() { 295 | Function.prototype.apply.apply(self.timer.clearTimeout, [j$.getGlobal(), [timeout]]); 296 | timeout = void 0; 297 | } 298 | 299 | var allFns = this.beforeFns().concat(this.fn).concat(this.afterFns()), 300 | allTimeoutableFns = []; 301 | for (var i = 0; i < allFns.length; i++) { 302 | var fn = allFns[i]; 303 | allTimeoutableFns.push(fn.length > 0 ? timeoutable(fn) : fn); 304 | } 305 | 306 | this.queueRunnerFactory({ 307 | fns: allTimeoutableFns, 308 | onException: onException, 309 | onComplete: complete 310 | }); 311 | 312 | function onException(e) { 313 | clearTimeoutable(); 314 | if (Spec.isPendingSpecException(e)) { 315 | self.pend(); 316 | return; 317 | } 318 | 319 | self.addExpectationResult(false, { 320 | matcherName: "", 321 | passed: false, 322 | expected: "", 323 | actual: "", 324 | error: e 325 | }); 326 | } 327 | 328 | function complete() { 329 | self.result.status = self.status(); 330 | self.resultCallback(self.result); 331 | 332 | if (onComplete) { 333 | onComplete(); 334 | } 335 | } 336 | }; 337 | 338 | Spec.prototype.disable = function() { 339 | this.disabled = true; 340 | }; 341 | 342 | Spec.prototype.pend = function() { 343 | this.markedPending = true; 344 | }; 345 | 346 | Spec.prototype.status = function() { 347 | if (this.disabled) { 348 | return 'disabled'; 349 | } 350 | 351 | if (this.markedPending) { 352 | return 'pending'; 353 | } 354 | 355 | if (this.result.failedExpectations.length > 0) { 356 | return 'failed'; 357 | } else { 358 | return 'passed'; 359 | } 360 | }; 361 | 362 | Spec.prototype.getFullName = function() { 363 | return this.getSpecName(this); 364 | }; 365 | 366 | Spec.pendingSpecExceptionMessage = "=> marked Pending"; 367 | 368 | Spec.isPendingSpecException = function(e) { 369 | return e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1; 370 | }; 371 | 372 | return Spec; 373 | }; 374 | 375 | if (typeof window == void 0 && typeof exports == "object") { 376 | exports.Spec = jasmineRequire.Spec; 377 | } 378 | 379 | getJasmineRequireObj().Env = function(j$) { 380 | function Env(options) { 381 | options = options || {}; 382 | 383 | var self = this; 384 | var global = options.global || j$.getGlobal(); 385 | 386 | var totalSpecsDefined = 0; 387 | 388 | var catchExceptions = true; 389 | 390 | var realSetTimeout = j$.getGlobal().setTimeout; 391 | var realClearTimeout = j$.getGlobal().clearTimeout; 392 | this.clock = new j$.Clock(global, new j$.DelayedFunctionScheduler()); 393 | 394 | var runnableLookupTable = {}; 395 | 396 | var spies = []; 397 | 398 | var currentSpec = null; 399 | var currentSuite = null; 400 | 401 | var reporter = new j$.ReportDispatcher([ 402 | "jasmineStarted", 403 | "jasmineDone", 404 | "suiteStarted", 405 | "suiteDone", 406 | "specStarted", 407 | "specDone" 408 | ]); 409 | 410 | this.specFilter = function() { 411 | return true; 412 | }; 413 | 414 | var equalityTesters = []; 415 | 416 | var customEqualityTesters = []; 417 | this.addCustomEqualityTester = function(tester) { 418 | customEqualityTesters.push(tester); 419 | }; 420 | 421 | j$.Expectation.addCoreMatchers(j$.matchers); 422 | 423 | var nextSpecId = 0; 424 | var getNextSpecId = function() { 425 | return 'spec' + nextSpecId++; 426 | }; 427 | 428 | var nextSuiteId = 0; 429 | var getNextSuiteId = function() { 430 | return 'suite' + nextSuiteId++; 431 | }; 432 | 433 | var expectationFactory = function(actual, spec) { 434 | return j$.Expectation.Factory({ 435 | util: j$.matchersUtil, 436 | customEqualityTesters: customEqualityTesters, 437 | actual: actual, 438 | addExpectationResult: addExpectationResult 439 | }); 440 | 441 | function addExpectationResult(passed, result) { 442 | return spec.addExpectationResult(passed, result); 443 | } 444 | }; 445 | 446 | var specStarted = function(spec) { 447 | currentSpec = spec; 448 | reporter.specStarted(spec.result); 449 | }; 450 | 451 | var beforeFns = function(suite) { 452 | return function() { 453 | var befores = []; 454 | while(suite) { 455 | befores = befores.concat(suite.beforeFns); 456 | suite = suite.parentSuite; 457 | } 458 | return befores.reverse(); 459 | }; 460 | }; 461 | 462 | var afterFns = function(suite) { 463 | return function() { 464 | var afters = []; 465 | while(suite) { 466 | afters = afters.concat(suite.afterFns); 467 | suite = suite.parentSuite; 468 | } 469 | return afters; 470 | }; 471 | }; 472 | 473 | var getSpecName = function(spec, suite) { 474 | return suite.getFullName() + ' ' + spec.description; 475 | }; 476 | 477 | // TODO: we may just be able to pass in the fn instead of wrapping here 478 | var buildExpectationResult = j$.buildExpectationResult, 479 | exceptionFormatter = new j$.ExceptionFormatter(), 480 | expectationResultFactory = function(attrs) { 481 | attrs.messageFormatter = exceptionFormatter.message; 482 | attrs.stackFormatter = exceptionFormatter.stack; 483 | 484 | return buildExpectationResult(attrs); 485 | }; 486 | 487 | // TODO: fix this naming, and here's where the value comes in 488 | this.catchExceptions = function(value) { 489 | catchExceptions = !!value; 490 | return catchExceptions; 491 | }; 492 | 493 | this.catchingExceptions = function() { 494 | return catchExceptions; 495 | }; 496 | 497 | var maximumSpecCallbackDepth = 20; 498 | var currentSpecCallbackDepth = 0; 499 | 500 | function clearStack(fn) { 501 | currentSpecCallbackDepth++; 502 | if (currentSpecCallbackDepth >= maximumSpecCallbackDepth) { 503 | currentSpecCallbackDepth = 0; 504 | realSetTimeout(fn, 0); 505 | } else { 506 | fn(); 507 | } 508 | } 509 | 510 | var catchException = function(e) { 511 | return j$.Spec.isPendingSpecException(e) || catchExceptions; 512 | }; 513 | 514 | var queueRunnerFactory = function(options) { 515 | options.catchException = catchException; 516 | options.clearStack = options.clearStack || clearStack; 517 | 518 | new j$.QueueRunner(options).execute(); 519 | }; 520 | 521 | var topSuite = new j$.Suite({ 522 | env: this, 523 | id: getNextSuiteId(), 524 | description: 'Jasmine__TopLevel__Suite', 525 | queueRunner: queueRunnerFactory, 526 | resultCallback: function() {} // TODO - hook this up 527 | }); 528 | runnableLookupTable[topSuite.id] = topSuite; 529 | currentSuite = topSuite; 530 | 531 | this.topSuite = function() { 532 | return topSuite; 533 | }; 534 | 535 | this.execute = function(runnablesToRun) { 536 | runnablesToRun = runnablesToRun || [topSuite.id]; 537 | 538 | var allFns = []; 539 | for(var i = 0; i < runnablesToRun.length; i++) { 540 | var runnable = runnableLookupTable[runnablesToRun[i]]; 541 | allFns.push((function(runnable) { return function(done) { runnable.execute(done); }; })(runnable)); 542 | } 543 | 544 | reporter.jasmineStarted({ 545 | totalSpecsDefined: totalSpecsDefined 546 | }); 547 | 548 | queueRunnerFactory({fns: allFns, onComplete: reporter.jasmineDone}); 549 | }; 550 | 551 | this.addReporter = function(reporterToAdd) { 552 | reporter.addReporter(reporterToAdd); 553 | }; 554 | 555 | this.addMatchers = function(matchersToAdd) { 556 | j$.Expectation.addMatchers(matchersToAdd); 557 | }; 558 | 559 | this.spyOn = function(obj, methodName) { 560 | if (j$.util.isUndefined(obj)) { 561 | throw new Error("spyOn could not find an object to spy upon for " + methodName + "()"); 562 | } 563 | 564 | if (j$.util.isUndefined(obj[methodName])) { 565 | throw new Error(methodName + '() method does not exist'); 566 | } 567 | 568 | if (obj[methodName] && j$.isSpy(obj[methodName])) { 569 | //TODO?: should this return the current spy? Downside: may cause user confusion about spy state 570 | throw new Error(methodName + ' has already been spied upon'); 571 | } 572 | 573 | var spy = j$.createSpy(methodName, obj[methodName]); 574 | 575 | spies.push({ 576 | spy: spy, 577 | baseObj: obj, 578 | methodName: methodName, 579 | originalValue: obj[methodName] 580 | }); 581 | 582 | obj[methodName] = spy; 583 | 584 | return spy; 585 | }; 586 | 587 | var suiteFactory = function(description) { 588 | var suite = new j$.Suite({ 589 | env: self, 590 | id: getNextSuiteId(), 591 | description: description, 592 | parentSuite: currentSuite, 593 | queueRunner: queueRunnerFactory, 594 | onStart: suiteStarted, 595 | resultCallback: function(attrs) { 596 | reporter.suiteDone(attrs); 597 | } 598 | }); 599 | 600 | runnableLookupTable[suite.id] = suite; 601 | return suite; 602 | }; 603 | 604 | this.describe = function(description, specDefinitions) { 605 | var suite = suiteFactory(description); 606 | 607 | var parentSuite = currentSuite; 608 | parentSuite.addChild(suite); 609 | currentSuite = suite; 610 | 611 | var declarationError = null; 612 | try { 613 | specDefinitions.call(suite); 614 | } catch (e) { 615 | declarationError = e; 616 | } 617 | 618 | if (declarationError) { 619 | this.it("encountered a declaration exception", function() { 620 | throw declarationError; 621 | }); 622 | } 623 | 624 | currentSuite = parentSuite; 625 | 626 | return suite; 627 | }; 628 | 629 | this.xdescribe = function(description, specDefinitions) { 630 | var suite = this.describe(description, specDefinitions); 631 | suite.disable(); 632 | return suite; 633 | }; 634 | 635 | var specFactory = function(description, fn, suite) { 636 | totalSpecsDefined++; 637 | 638 | var spec = new j$.Spec({ 639 | id: getNextSpecId(), 640 | beforeFns: beforeFns(suite), 641 | afterFns: afterFns(suite), 642 | expectationFactory: expectationFactory, 643 | exceptionFormatter: exceptionFormatter, 644 | resultCallback: specResultCallback, 645 | getSpecName: function(spec) { 646 | return getSpecName(spec, suite); 647 | }, 648 | onStart: specStarted, 649 | description: description, 650 | expectationResultFactory: expectationResultFactory, 651 | queueRunnerFactory: queueRunnerFactory, 652 | fn: fn, 653 | timer: {setTimeout: realSetTimeout, clearTimeout: realClearTimeout} 654 | }); 655 | 656 | runnableLookupTable[spec.id] = spec; 657 | 658 | if (!self.specFilter(spec)) { 659 | spec.disable(); 660 | } 661 | 662 | return spec; 663 | 664 | function removeAllSpies() { 665 | for (var i = 0; i < spies.length; i++) { 666 | var spyEntry = spies[i]; 667 | spyEntry.baseObj[spyEntry.methodName] = spyEntry.originalValue; 668 | } 669 | spies = []; 670 | } 671 | 672 | function specResultCallback(result) { 673 | removeAllSpies(); 674 | j$.Expectation.resetMatchers(); 675 | customEqualityTesters = []; 676 | currentSpec = null; 677 | reporter.specDone(result); 678 | } 679 | }; 680 | 681 | var suiteStarted = function(suite) { 682 | reporter.suiteStarted(suite.result); 683 | }; 684 | 685 | this.it = function(description, fn) { 686 | var spec = specFactory(description, fn, currentSuite); 687 | currentSuite.addChild(spec); 688 | return spec; 689 | }; 690 | 691 | this.xit = function(description, fn) { 692 | var spec = this.it(description, fn); 693 | spec.pend(); 694 | return spec; 695 | }; 696 | 697 | this.expect = function(actual) { 698 | return currentSpec.expect(actual); 699 | }; 700 | 701 | this.beforeEach = function(beforeEachFunction) { 702 | currentSuite.beforeEach(beforeEachFunction); 703 | }; 704 | 705 | this.afterEach = function(afterEachFunction) { 706 | currentSuite.afterEach(afterEachFunction); 707 | }; 708 | 709 | this.pending = function() { 710 | throw j$.Spec.pendingSpecExceptionMessage; 711 | }; 712 | } 713 | 714 | return Env; 715 | }; 716 | 717 | getJasmineRequireObj().JsApiReporter = function() { 718 | 719 | var noopTimer = { 720 | start: function(){}, 721 | elapsed: function(){ return 0; } 722 | }; 723 | 724 | function JsApiReporter(options) { 725 | var timer = options.timer || noopTimer, 726 | status = "loaded"; 727 | 728 | this.started = false; 729 | this.finished = false; 730 | 731 | this.jasmineStarted = function() { 732 | this.started = true; 733 | status = 'started'; 734 | timer.start(); 735 | }; 736 | 737 | var executionTime; 738 | 739 | this.jasmineDone = function() { 740 | this.finished = true; 741 | executionTime = timer.elapsed(); 742 | status = 'done'; 743 | }; 744 | 745 | this.status = function() { 746 | return status; 747 | }; 748 | 749 | var suites = {}; 750 | 751 | this.suiteStarted = function(result) { 752 | storeSuite(result); 753 | }; 754 | 755 | this.suiteDone = function(result) { 756 | storeSuite(result); 757 | }; 758 | 759 | function storeSuite(result) { 760 | suites[result.id] = result; 761 | } 762 | 763 | this.suites = function() { 764 | return suites; 765 | }; 766 | 767 | var specs = []; 768 | this.specStarted = function(result) { }; 769 | 770 | this.specDone = function(result) { 771 | specs.push(result); 772 | }; 773 | 774 | this.specResults = function(index, length) { 775 | return specs.slice(index, index + length); 776 | }; 777 | 778 | this.specs = function() { 779 | return specs; 780 | }; 781 | 782 | this.executionTime = function() { 783 | return executionTime; 784 | }; 785 | 786 | } 787 | 788 | return JsApiReporter; 789 | }; 790 | 791 | getJasmineRequireObj().Any = function() { 792 | 793 | function Any(expectedObject) { 794 | this.expectedObject = expectedObject; 795 | } 796 | 797 | Any.prototype.jasmineMatches = function(other) { 798 | if (this.expectedObject == String) { 799 | return typeof other == 'string' || other instanceof String; 800 | } 801 | 802 | if (this.expectedObject == Number) { 803 | return typeof other == 'number' || other instanceof Number; 804 | } 805 | 806 | if (this.expectedObject == Function) { 807 | return typeof other == 'function' || other instanceof Function; 808 | } 809 | 810 | if (this.expectedObject == Object) { 811 | return typeof other == 'object'; 812 | } 813 | 814 | if (this.expectedObject == Boolean) { 815 | return typeof other == 'boolean'; 816 | } 817 | 818 | return other instanceof this.expectedObject; 819 | }; 820 | 821 | Any.prototype.jasmineToString = function() { 822 | return ''; 823 | }; 824 | 825 | return Any; 826 | }; 827 | 828 | getJasmineRequireObj().CallTracker = function() { 829 | 830 | function CallTracker() { 831 | var calls = []; 832 | 833 | this.track = function(context) { 834 | calls.push(context); 835 | }; 836 | 837 | this.any = function() { 838 | return !!calls.length; 839 | }; 840 | 841 | this.count = function() { 842 | return calls.length; 843 | }; 844 | 845 | this.argsFor = function(index) { 846 | var call = calls[index]; 847 | return call ? call.args : []; 848 | }; 849 | 850 | this.all = function() { 851 | return calls; 852 | }; 853 | 854 | this.allArgs = function() { 855 | var callArgs = []; 856 | for(var i = 0; i < calls.length; i++){ 857 | callArgs.push(calls[i].args); 858 | } 859 | 860 | return callArgs; 861 | }; 862 | 863 | this.first = function() { 864 | return calls[0]; 865 | }; 866 | 867 | this.mostRecent = function() { 868 | return calls[calls.length - 1]; 869 | }; 870 | 871 | this.reset = function() { 872 | calls = []; 873 | }; 874 | } 875 | 876 | return CallTracker; 877 | }; 878 | 879 | getJasmineRequireObj().Clock = function() { 880 | function Clock(global, delayedFunctionScheduler) { 881 | var self = this, 882 | realTimingFunctions = { 883 | setTimeout: global.setTimeout, 884 | clearTimeout: global.clearTimeout, 885 | setInterval: global.setInterval, 886 | clearInterval: global.clearInterval 887 | }, 888 | fakeTimingFunctions = { 889 | setTimeout: setTimeout, 890 | clearTimeout: clearTimeout, 891 | setInterval: setInterval, 892 | clearInterval: clearInterval 893 | }, 894 | installed = false, 895 | timer; 896 | 897 | self.install = function() { 898 | replace(global, fakeTimingFunctions); 899 | timer = fakeTimingFunctions; 900 | installed = true; 901 | }; 902 | 903 | self.uninstall = function() { 904 | delayedFunctionScheduler.reset(); 905 | replace(global, realTimingFunctions); 906 | timer = realTimingFunctions; 907 | installed = false; 908 | }; 909 | 910 | self.setTimeout = function(fn, delay, params) { 911 | if (legacyIE()) { 912 | if (arguments.length > 2) { 913 | throw new Error("IE < 9 cannot support extra params to setTimeout without a polyfill"); 914 | } 915 | return timer.setTimeout(fn, delay); 916 | } 917 | return Function.prototype.apply.apply(timer.setTimeout, [global, arguments]); 918 | }; 919 | 920 | self.setInterval = function(fn, delay, params) { 921 | if (legacyIE()) { 922 | if (arguments.length > 2) { 923 | throw new Error("IE < 9 cannot support extra params to setInterval without a polyfill"); 924 | } 925 | return timer.setInterval(fn, delay); 926 | } 927 | return Function.prototype.apply.apply(timer.setInterval, [global, arguments]); 928 | }; 929 | 930 | self.clearTimeout = function(id) { 931 | return Function.prototype.call.apply(timer.clearTimeout, [global, id]); 932 | }; 933 | 934 | self.clearInterval = function(id) { 935 | return Function.prototype.call.apply(timer.clearInterval, [global, id]); 936 | }; 937 | 938 | self.tick = function(millis) { 939 | if (installed) { 940 | delayedFunctionScheduler.tick(millis); 941 | } else { 942 | throw new Error("Mock clock is not installed, use jasmine.clock().install()"); 943 | } 944 | }; 945 | 946 | return self; 947 | 948 | function legacyIE() { 949 | //if these methods are polyfilled, apply will be present 950 | return !(realTimingFunctions.setTimeout || realTimingFunctions.setInterval).apply; 951 | } 952 | 953 | function replace(dest, source) { 954 | for (var prop in source) { 955 | dest[prop] = source[prop]; 956 | } 957 | } 958 | 959 | function setTimeout(fn, delay) { 960 | return delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2)); 961 | } 962 | 963 | function clearTimeout(id) { 964 | return delayedFunctionScheduler.removeFunctionWithId(id); 965 | } 966 | 967 | function setInterval(fn, interval) { 968 | return delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true); 969 | } 970 | 971 | function clearInterval(id) { 972 | return delayedFunctionScheduler.removeFunctionWithId(id); 973 | } 974 | 975 | function argSlice(argsObj, n) { 976 | return Array.prototype.slice.call(argsObj, 2); 977 | } 978 | } 979 | 980 | return Clock; 981 | }; 982 | 983 | getJasmineRequireObj().DelayedFunctionScheduler = function() { 984 | function DelayedFunctionScheduler() { 985 | var self = this; 986 | var scheduledLookup = []; 987 | var scheduledFunctions = {}; 988 | var currentTime = 0; 989 | var delayedFnCount = 0; 990 | 991 | self.tick = function(millis) { 992 | millis = millis || 0; 993 | var endTime = currentTime + millis; 994 | 995 | runScheduledFunctions(endTime); 996 | currentTime = endTime; 997 | }; 998 | 999 | self.scheduleFunction = function(funcToCall, millis, params, recurring, timeoutKey, runAtMillis) { 1000 | var f; 1001 | if (typeof(funcToCall) === 'string') { 1002 | /* jshint evil: true */ 1003 | f = function() { return eval(funcToCall); }; 1004 | /* jshint evil: false */ 1005 | } else { 1006 | f = funcToCall; 1007 | } 1008 | 1009 | millis = millis || 0; 1010 | timeoutKey = timeoutKey || ++delayedFnCount; 1011 | runAtMillis = runAtMillis || (currentTime + millis); 1012 | 1013 | var funcToSchedule = { 1014 | runAtMillis: runAtMillis, 1015 | funcToCall: f, 1016 | recurring: recurring, 1017 | params: params, 1018 | timeoutKey: timeoutKey, 1019 | millis: millis 1020 | }; 1021 | 1022 | if (runAtMillis in scheduledFunctions) { 1023 | scheduledFunctions[runAtMillis].push(funcToSchedule); 1024 | } else { 1025 | scheduledFunctions[runAtMillis] = [funcToSchedule]; 1026 | scheduledLookup.push(runAtMillis); 1027 | scheduledLookup.sort(function (a, b) { 1028 | return a - b; 1029 | }); 1030 | } 1031 | 1032 | return timeoutKey; 1033 | }; 1034 | 1035 | self.removeFunctionWithId = function(timeoutKey) { 1036 | for (var runAtMillis in scheduledFunctions) { 1037 | var funcs = scheduledFunctions[runAtMillis]; 1038 | var i = indexOfFirstToPass(funcs, function (func) { 1039 | return func.timeoutKey === timeoutKey; 1040 | }); 1041 | 1042 | if (i > -1) { 1043 | if (funcs.length === 1) { 1044 | delete scheduledFunctions[runAtMillis]; 1045 | deleteFromLookup(runAtMillis); 1046 | } else { 1047 | funcs.splice(i, 1); 1048 | } 1049 | 1050 | // intervals get rescheduled when executed, so there's never more 1051 | // than a single scheduled function with a given timeoutKey 1052 | break; 1053 | } 1054 | } 1055 | }; 1056 | 1057 | self.reset = function() { 1058 | currentTime = 0; 1059 | scheduledLookup = []; 1060 | scheduledFunctions = {}; 1061 | delayedFnCount = 0; 1062 | }; 1063 | 1064 | return self; 1065 | 1066 | function indexOfFirstToPass(array, testFn) { 1067 | var index = -1; 1068 | 1069 | for (var i = 0; i < array.length; ++i) { 1070 | if (testFn(array[i])) { 1071 | index = i; 1072 | break; 1073 | } 1074 | } 1075 | 1076 | return index; 1077 | } 1078 | 1079 | function deleteFromLookup(key) { 1080 | var value = Number(key); 1081 | var i = indexOfFirstToPass(scheduledLookup, function (millis) { 1082 | return millis === value; 1083 | }); 1084 | 1085 | if (i > -1) { 1086 | scheduledLookup.splice(i, 1); 1087 | } 1088 | } 1089 | 1090 | function reschedule(scheduledFn) { 1091 | self.scheduleFunction(scheduledFn.funcToCall, 1092 | scheduledFn.millis, 1093 | scheduledFn.params, 1094 | true, 1095 | scheduledFn.timeoutKey, 1096 | scheduledFn.runAtMillis + scheduledFn.millis); 1097 | } 1098 | 1099 | function runScheduledFunctions(endTime) { 1100 | if (scheduledLookup.length === 0 || scheduledLookup[0] > endTime) { 1101 | return; 1102 | } 1103 | 1104 | do { 1105 | currentTime = scheduledLookup.shift(); 1106 | 1107 | var funcsToRun = scheduledFunctions[currentTime]; 1108 | delete scheduledFunctions[currentTime]; 1109 | 1110 | for (var i = 0; i < funcsToRun.length; ++i) { 1111 | var funcToRun = funcsToRun[i]; 1112 | funcToRun.funcToCall.apply(null, funcToRun.params || []); 1113 | 1114 | if (funcToRun.recurring) { 1115 | reschedule(funcToRun); 1116 | } 1117 | } 1118 | } while (scheduledLookup.length > 0 && 1119 | // checking first if we're out of time prevents setTimeout(0) 1120 | // scheduled in a funcToRun from forcing an extra iteration 1121 | currentTime !== endTime && 1122 | scheduledLookup[0] <= endTime); 1123 | } 1124 | } 1125 | 1126 | return DelayedFunctionScheduler; 1127 | }; 1128 | 1129 | getJasmineRequireObj().ExceptionFormatter = function() { 1130 | function ExceptionFormatter() { 1131 | this.message = function(error) { 1132 | var message = error.name + 1133 | ': ' + 1134 | error.message; 1135 | 1136 | if (error.fileName || error.sourceURL) { 1137 | message += " in " + (error.fileName || error.sourceURL); 1138 | } 1139 | 1140 | if (error.line || error.lineNumber) { 1141 | message += " (line " + (error.line || error.lineNumber) + ")"; 1142 | } 1143 | 1144 | return message; 1145 | }; 1146 | 1147 | this.stack = function(error) { 1148 | return error ? error.stack : null; 1149 | }; 1150 | } 1151 | 1152 | return ExceptionFormatter; 1153 | }; 1154 | 1155 | getJasmineRequireObj().Expectation = function() { 1156 | 1157 | var matchers = {}; 1158 | 1159 | function Expectation(options) { 1160 | this.util = options.util || { buildFailureMessage: function() {} }; 1161 | this.customEqualityTesters = options.customEqualityTesters || []; 1162 | this.actual = options.actual; 1163 | this.addExpectationResult = options.addExpectationResult || function(){}; 1164 | this.isNot = options.isNot; 1165 | 1166 | for (var matcherName in matchers) { 1167 | this[matcherName] = matchers[matcherName]; 1168 | } 1169 | } 1170 | 1171 | Expectation.prototype.wrapCompare = function(name, matcherFactory) { 1172 | return function() { 1173 | var args = Array.prototype.slice.call(arguments, 0), 1174 | expected = args.slice(0), 1175 | message = ""; 1176 | 1177 | args.unshift(this.actual); 1178 | 1179 | var matcher = matcherFactory(this.util, this.customEqualityTesters), 1180 | matcherCompare = matcher.compare; 1181 | 1182 | function defaultNegativeCompare() { 1183 | var result = matcher.compare.apply(null, args); 1184 | result.pass = !result.pass; 1185 | return result; 1186 | } 1187 | 1188 | if (this.isNot) { 1189 | matcherCompare = matcher.negativeCompare || defaultNegativeCompare; 1190 | } 1191 | 1192 | var result = matcherCompare.apply(null, args); 1193 | 1194 | if (!result.pass) { 1195 | if (!result.message) { 1196 | args.unshift(this.isNot); 1197 | args.unshift(name); 1198 | message = this.util.buildFailureMessage.apply(null, args); 1199 | } else { 1200 | message = result.message; 1201 | } 1202 | } 1203 | 1204 | if (expected.length == 1) { 1205 | expected = expected[0]; 1206 | } 1207 | 1208 | // TODO: how many of these params are needed? 1209 | this.addExpectationResult( 1210 | result.pass, 1211 | { 1212 | matcherName: name, 1213 | passed: result.pass, 1214 | message: message, 1215 | actual: this.actual, 1216 | expected: expected // TODO: this may need to be arrayified/sliced 1217 | } 1218 | ); 1219 | }; 1220 | }; 1221 | 1222 | Expectation.addCoreMatchers = function(matchers) { 1223 | var prototype = Expectation.prototype; 1224 | for (var matcherName in matchers) { 1225 | var matcher = matchers[matcherName]; 1226 | prototype[matcherName] = prototype.wrapCompare(matcherName, matcher); 1227 | } 1228 | }; 1229 | 1230 | Expectation.addMatchers = function(matchersToAdd) { 1231 | for (var name in matchersToAdd) { 1232 | var matcher = matchersToAdd[name]; 1233 | matchers[name] = Expectation.prototype.wrapCompare(name, matcher); 1234 | } 1235 | }; 1236 | 1237 | Expectation.resetMatchers = function() { 1238 | for (var name in matchers) { 1239 | delete matchers[name]; 1240 | } 1241 | }; 1242 | 1243 | Expectation.Factory = function(options) { 1244 | options = options || {}; 1245 | 1246 | var expect = new Expectation(options); 1247 | 1248 | // TODO: this would be nice as its own Object - NegativeExpectation 1249 | // TODO: copy instead of mutate options 1250 | options.isNot = true; 1251 | expect.not = new Expectation(options); 1252 | 1253 | return expect; 1254 | }; 1255 | 1256 | return Expectation; 1257 | }; 1258 | 1259 | //TODO: expectation result may make more sense as a presentation of an expectation. 1260 | getJasmineRequireObj().buildExpectationResult = function() { 1261 | function buildExpectationResult(options) { 1262 | var messageFormatter = options.messageFormatter || function() {}, 1263 | stackFormatter = options.stackFormatter || function() {}; 1264 | 1265 | return { 1266 | matcherName: options.matcherName, 1267 | expected: options.expected, 1268 | actual: options.actual, 1269 | message: message(), 1270 | stack: stack(), 1271 | passed: options.passed 1272 | }; 1273 | 1274 | function message() { 1275 | if (options.passed) { 1276 | return "Passed."; 1277 | } else if (options.message) { 1278 | return options.message; 1279 | } else if (options.error) { 1280 | return messageFormatter(options.error); 1281 | } 1282 | return ""; 1283 | } 1284 | 1285 | function stack() { 1286 | if (options.passed) { 1287 | return ""; 1288 | } 1289 | 1290 | var error = options.error; 1291 | if (!error) { 1292 | try { 1293 | throw new Error(message()); 1294 | } catch (e) { 1295 | error = e; 1296 | } 1297 | } 1298 | return stackFormatter(error); 1299 | } 1300 | } 1301 | 1302 | return buildExpectationResult; 1303 | }; 1304 | 1305 | getJasmineRequireObj().ObjectContaining = function(j$) { 1306 | 1307 | function ObjectContaining(sample) { 1308 | this.sample = sample; 1309 | } 1310 | 1311 | ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) { 1312 | if (typeof(this.sample) !== "object") { throw new Error("You must provide an object to objectContaining, not '"+this.sample+"'."); } 1313 | 1314 | mismatchKeys = mismatchKeys || []; 1315 | mismatchValues = mismatchValues || []; 1316 | 1317 | var hasKey = function(obj, keyName) { 1318 | return obj !== null && !j$.util.isUndefined(obj[keyName]); 1319 | }; 1320 | 1321 | for (var property in this.sample) { 1322 | if (!hasKey(other, property) && hasKey(this.sample, property)) { 1323 | mismatchKeys.push("expected has key '" + property + "', but missing from actual."); 1324 | } 1325 | else if (!j$.matchersUtil.equals(this.sample[property], other[property])) { 1326 | mismatchValues.push("'" + property + "' was '" + (other[property] ? j$.util.htmlEscape(other[property].toString()) : other[property]) + "' in actual, but was '" + (this.sample[property] ? j$.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in expected."); 1327 | } 1328 | } 1329 | 1330 | return (mismatchKeys.length === 0 && mismatchValues.length === 0); 1331 | }; 1332 | 1333 | ObjectContaining.prototype.jasmineToString = function() { 1334 | return ""; 1335 | }; 1336 | 1337 | return ObjectContaining; 1338 | }; 1339 | 1340 | getJasmineRequireObj().pp = function(j$) { 1341 | 1342 | function PrettyPrinter() { 1343 | this.ppNestLevel_ = 0; 1344 | } 1345 | 1346 | PrettyPrinter.prototype.format = function(value) { 1347 | this.ppNestLevel_++; 1348 | try { 1349 | if (j$.util.isUndefined(value)) { 1350 | this.emitScalar('undefined'); 1351 | } else if (value === null) { 1352 | this.emitScalar('null'); 1353 | } else if (value === j$.getGlobal()) { 1354 | this.emitScalar(''); 1355 | } else if (value.jasmineToString) { 1356 | this.emitScalar(value.jasmineToString()); 1357 | } else if (typeof value === 'string') { 1358 | this.emitString(value); 1359 | } else if (j$.isSpy(value)) { 1360 | this.emitScalar("spy on " + value.and.identity()); 1361 | } else if (value instanceof RegExp) { 1362 | this.emitScalar(value.toString()); 1363 | } else if (typeof value === 'function') { 1364 | this.emitScalar('Function'); 1365 | } else if (typeof value.nodeType === 'number') { 1366 | this.emitScalar('HTMLNode'); 1367 | } else if (value instanceof Date) { 1368 | this.emitScalar('Date(' + value + ')'); 1369 | } else if (value.__Jasmine_been_here_before__) { 1370 | this.emitScalar(''); 1371 | } else if (j$.isArray_(value) || j$.isA_('Object', value)) { 1372 | value.__Jasmine_been_here_before__ = true; 1373 | if (j$.isArray_(value)) { 1374 | this.emitArray(value); 1375 | } else { 1376 | this.emitObject(value); 1377 | } 1378 | delete value.__Jasmine_been_here_before__; 1379 | } else { 1380 | this.emitScalar(value.toString()); 1381 | } 1382 | } finally { 1383 | this.ppNestLevel_--; 1384 | } 1385 | }; 1386 | 1387 | PrettyPrinter.prototype.iterateObject = function(obj, fn) { 1388 | for (var property in obj) { 1389 | if (!obj.hasOwnProperty(property)) { continue; } 1390 | if (property == '__Jasmine_been_here_before__') { continue; } 1391 | fn(property, obj.__lookupGetter__ ? (!j$.util.isUndefined(obj.__lookupGetter__(property)) && 1392 | obj.__lookupGetter__(property) !== null) : false); 1393 | } 1394 | }; 1395 | 1396 | PrettyPrinter.prototype.emitArray = j$.unimplementedMethod_; 1397 | PrettyPrinter.prototype.emitObject = j$.unimplementedMethod_; 1398 | PrettyPrinter.prototype.emitScalar = j$.unimplementedMethod_; 1399 | PrettyPrinter.prototype.emitString = j$.unimplementedMethod_; 1400 | 1401 | function StringPrettyPrinter() { 1402 | PrettyPrinter.call(this); 1403 | 1404 | this.string = ''; 1405 | } 1406 | 1407 | j$.util.inherit(StringPrettyPrinter, PrettyPrinter); 1408 | 1409 | StringPrettyPrinter.prototype.emitScalar = function(value) { 1410 | this.append(value); 1411 | }; 1412 | 1413 | StringPrettyPrinter.prototype.emitString = function(value) { 1414 | this.append("'" + value + "'"); 1415 | }; 1416 | 1417 | StringPrettyPrinter.prototype.emitArray = function(array) { 1418 | if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { 1419 | this.append("Array"); 1420 | return; 1421 | } 1422 | 1423 | this.append('[ '); 1424 | for (var i = 0; i < array.length; i++) { 1425 | if (i > 0) { 1426 | this.append(', '); 1427 | } 1428 | this.format(array[i]); 1429 | } 1430 | this.append(' ]'); 1431 | }; 1432 | 1433 | StringPrettyPrinter.prototype.emitObject = function(obj) { 1434 | if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { 1435 | this.append("Object"); 1436 | return; 1437 | } 1438 | 1439 | var self = this; 1440 | this.append('{ '); 1441 | var first = true; 1442 | 1443 | this.iterateObject(obj, function(property, isGetter) { 1444 | if (first) { 1445 | first = false; 1446 | } else { 1447 | self.append(', '); 1448 | } 1449 | 1450 | self.append(property); 1451 | self.append(' : '); 1452 | if (isGetter) { 1453 | self.append(''); 1454 | } else { 1455 | self.format(obj[property]); 1456 | } 1457 | }); 1458 | 1459 | this.append(' }'); 1460 | }; 1461 | 1462 | StringPrettyPrinter.prototype.append = function(value) { 1463 | this.string += value; 1464 | }; 1465 | 1466 | return function(value) { 1467 | var stringPrettyPrinter = new StringPrettyPrinter(); 1468 | stringPrettyPrinter.format(value); 1469 | return stringPrettyPrinter.string; 1470 | }; 1471 | }; 1472 | 1473 | getJasmineRequireObj().QueueRunner = function() { 1474 | 1475 | function QueueRunner(attrs) { 1476 | this.fns = attrs.fns || []; 1477 | this.onComplete = attrs.onComplete || function() {}; 1478 | this.clearStack = attrs.clearStack || function(fn) {fn();}; 1479 | this.onException = attrs.onException || function() {}; 1480 | this.catchException = attrs.catchException || function() { return true; }; 1481 | this.userContext = {}; 1482 | } 1483 | 1484 | QueueRunner.prototype.execute = function() { 1485 | this.run(this.fns, 0); 1486 | }; 1487 | 1488 | QueueRunner.prototype.run = function(fns, recursiveIndex) { 1489 | var length = fns.length, 1490 | self = this, 1491 | iterativeIndex; 1492 | 1493 | for(iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex++) { 1494 | var fn = fns[iterativeIndex]; 1495 | if (fn.length > 0) { 1496 | return attemptAsync(fn); 1497 | } else { 1498 | attemptSync(fn); 1499 | } 1500 | } 1501 | 1502 | var runnerDone = iterativeIndex >= length; 1503 | 1504 | if (runnerDone) { 1505 | this.clearStack(this.onComplete); 1506 | } 1507 | 1508 | function attemptSync(fn) { 1509 | try { 1510 | fn.call(self.userContext); 1511 | } catch (e) { 1512 | handleException(e); 1513 | } 1514 | } 1515 | 1516 | function attemptAsync(fn) { 1517 | var next = function () { self.run(fns, iterativeIndex + 1); }; 1518 | 1519 | try { 1520 | fn.call(self.userContext, next); 1521 | } catch (e) { 1522 | handleException(e); 1523 | next(); 1524 | } 1525 | } 1526 | 1527 | function handleException(e) { 1528 | self.onException(e); 1529 | if (!self.catchException(e)) { 1530 | //TODO: set a var when we catch an exception and 1531 | //use a finally block to close the loop in a nice way.. 1532 | throw e; 1533 | } 1534 | } 1535 | }; 1536 | 1537 | return QueueRunner; 1538 | }; 1539 | 1540 | getJasmineRequireObj().ReportDispatcher = function() { 1541 | function ReportDispatcher(methods) { 1542 | 1543 | var dispatchedMethods = methods || []; 1544 | 1545 | for (var i = 0; i < dispatchedMethods.length; i++) { 1546 | var method = dispatchedMethods[i]; 1547 | this[method] = (function(m) { 1548 | return function() { 1549 | dispatch(m, arguments); 1550 | }; 1551 | }(method)); 1552 | } 1553 | 1554 | var reporters = []; 1555 | 1556 | this.addReporter = function(reporter) { 1557 | reporters.push(reporter); 1558 | }; 1559 | 1560 | return this; 1561 | 1562 | function dispatch(method, args) { 1563 | for (var i = 0; i < reporters.length; i++) { 1564 | var reporter = reporters[i]; 1565 | if (reporter[method]) { 1566 | reporter[method].apply(reporter, args); 1567 | } 1568 | } 1569 | } 1570 | } 1571 | 1572 | return ReportDispatcher; 1573 | }; 1574 | 1575 | 1576 | getJasmineRequireObj().SpyStrategy = function() { 1577 | 1578 | function SpyStrategy(options) { 1579 | options = options || {}; 1580 | 1581 | var identity = options.name || "unknown", 1582 | originalFn = options.fn || function() {}, 1583 | getSpy = options.getSpy || function() {}, 1584 | plan = function() {}; 1585 | 1586 | this.identity = function() { 1587 | return identity; 1588 | }; 1589 | 1590 | this.exec = function() { 1591 | return plan.apply(this, arguments); 1592 | }; 1593 | 1594 | this.callThrough = function() { 1595 | plan = originalFn; 1596 | return getSpy(); 1597 | }; 1598 | 1599 | this.returnValue = function(value) { 1600 | plan = function() { 1601 | return value; 1602 | }; 1603 | return getSpy(); 1604 | }; 1605 | 1606 | this.throwError = function(something) { 1607 | var error = (something instanceof Error) ? something : new Error(something); 1608 | plan = function() { 1609 | throw error; 1610 | }; 1611 | return getSpy(); 1612 | }; 1613 | 1614 | this.callFake = function(fn) { 1615 | plan = fn; 1616 | return getSpy(); 1617 | }; 1618 | 1619 | this.stub = function(fn) { 1620 | plan = function() {}; 1621 | return getSpy(); 1622 | }; 1623 | } 1624 | 1625 | return SpyStrategy; 1626 | }; 1627 | 1628 | getJasmineRequireObj().Suite = function() { 1629 | function Suite(attrs) { 1630 | this.env = attrs.env; 1631 | this.id = attrs.id; 1632 | this.parentSuite = attrs.parentSuite; 1633 | this.description = attrs.description; 1634 | this.onStart = attrs.onStart || function() {}; 1635 | this.resultCallback = attrs.resultCallback || function() {}; 1636 | this.clearStack = attrs.clearStack || function(fn) {fn();}; 1637 | 1638 | this.beforeFns = []; 1639 | this.afterFns = []; 1640 | this.queueRunner = attrs.queueRunner || function() {}; 1641 | this.disabled = false; 1642 | 1643 | this.children = []; 1644 | 1645 | this.result = { 1646 | id: this.id, 1647 | status: this.disabled ? 'disabled' : '', 1648 | description: this.description, 1649 | fullName: this.getFullName() 1650 | }; 1651 | } 1652 | 1653 | Suite.prototype.getFullName = function() { 1654 | var fullName = this.description; 1655 | for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { 1656 | if (parentSuite.parentSuite) { 1657 | fullName = parentSuite.description + ' ' + fullName; 1658 | } 1659 | } 1660 | return fullName; 1661 | }; 1662 | 1663 | Suite.prototype.disable = function() { 1664 | this.disabled = true; 1665 | }; 1666 | 1667 | Suite.prototype.beforeEach = function(fn) { 1668 | this.beforeFns.unshift(fn); 1669 | }; 1670 | 1671 | Suite.prototype.afterEach = function(fn) { 1672 | this.afterFns.unshift(fn); 1673 | }; 1674 | 1675 | Suite.prototype.addChild = function(child) { 1676 | this.children.push(child); 1677 | }; 1678 | 1679 | Suite.prototype.execute = function(onComplete) { 1680 | var self = this; 1681 | if (this.disabled) { 1682 | complete(); 1683 | return; 1684 | } 1685 | 1686 | var allFns = []; 1687 | 1688 | for (var i = 0; i < this.children.length; i++) { 1689 | allFns.push(wrapChildAsAsync(this.children[i])); 1690 | } 1691 | 1692 | this.onStart(this); 1693 | 1694 | this.queueRunner({ 1695 | fns: allFns, 1696 | onComplete: complete 1697 | }); 1698 | 1699 | function complete() { 1700 | self.resultCallback(self.result); 1701 | 1702 | if (onComplete) { 1703 | onComplete(); 1704 | } 1705 | } 1706 | 1707 | function wrapChildAsAsync(child) { 1708 | return function(done) { child.execute(done); }; 1709 | } 1710 | }; 1711 | 1712 | return Suite; 1713 | }; 1714 | 1715 | if (typeof window == void 0 && typeof exports == "object") { 1716 | exports.Suite = jasmineRequire.Suite; 1717 | } 1718 | 1719 | getJasmineRequireObj().Timer = function() { 1720 | function Timer(options) { 1721 | options = options || {}; 1722 | 1723 | var now = options.now || function() { return new Date().getTime(); }, 1724 | startTime; 1725 | 1726 | this.start = function() { 1727 | startTime = now(); 1728 | }; 1729 | 1730 | this.elapsed = function() { 1731 | return now() - startTime; 1732 | }; 1733 | } 1734 | 1735 | return Timer; 1736 | }; 1737 | 1738 | getJasmineRequireObj().matchersUtil = function(j$) { 1739 | // TODO: what to do about jasmine.pp not being inject? move to JSON.stringify? gut PrettyPrinter? 1740 | 1741 | return { 1742 | equals: function(a, b, customTesters) { 1743 | customTesters = customTesters || []; 1744 | 1745 | return eq(a, b, [], [], customTesters); 1746 | }, 1747 | 1748 | contains: function(haystack, needle, customTesters) { 1749 | customTesters = customTesters || []; 1750 | 1751 | if (Object.prototype.toString.apply(haystack) === "[object Array]") { 1752 | for (var i = 0; i < haystack.length; i++) { 1753 | if (eq(haystack[i], needle, [], [], customTesters)) { 1754 | return true; 1755 | } 1756 | } 1757 | return false; 1758 | } 1759 | return haystack.indexOf(needle) >= 0; 1760 | }, 1761 | 1762 | buildFailureMessage: function() { 1763 | var args = Array.prototype.slice.call(arguments, 0), 1764 | matcherName = args[0], 1765 | isNot = args[1], 1766 | actual = args[2], 1767 | expected = args.slice(3), 1768 | englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); 1769 | 1770 | var message = "Expected " + 1771 | j$.pp(actual) + 1772 | (isNot ? " not " : " ") + 1773 | englishyPredicate; 1774 | 1775 | if (expected.length > 0) { 1776 | for (var i = 0; i < expected.length; i++) { 1777 | if (i > 0) { 1778 | message += ","; 1779 | } 1780 | message += " " + j$.pp(expected[i]); 1781 | } 1782 | } 1783 | 1784 | return message + "."; 1785 | } 1786 | }; 1787 | 1788 | // Equality function lovingly adapted from isEqual in 1789 | // [Underscore](http://underscorejs.org) 1790 | function eq(a, b, aStack, bStack, customTesters) { 1791 | var result = true; 1792 | 1793 | for (var i = 0; i < customTesters.length; i++) { 1794 | var customTesterResult = customTesters[i](a, b); 1795 | if (!j$.util.isUndefined(customTesterResult)) { 1796 | return customTesterResult; 1797 | } 1798 | } 1799 | 1800 | if (a instanceof j$.Any) { 1801 | result = a.jasmineMatches(b); 1802 | if (result) { 1803 | return true; 1804 | } 1805 | } 1806 | 1807 | if (b instanceof j$.Any) { 1808 | result = b.jasmineMatches(a); 1809 | if (result) { 1810 | return true; 1811 | } 1812 | } 1813 | 1814 | if (b instanceof j$.ObjectContaining) { 1815 | result = b.jasmineMatches(a); 1816 | if (result) { 1817 | return true; 1818 | } 1819 | } 1820 | 1821 | if (a instanceof Error && b instanceof Error) { 1822 | return a.message == b.message; 1823 | } 1824 | 1825 | // Identical objects are equal. `0 === -0`, but they aren't identical. 1826 | // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). 1827 | if (a === b) { return a !== 0 || 1 / a == 1 / b; } 1828 | // A strict comparison is necessary because `null == undefined`. 1829 | if (a === null || b === null) { return a === b; } 1830 | var className = Object.prototype.toString.call(a); 1831 | if (className != Object.prototype.toString.call(b)) { return false; } 1832 | switch (className) { 1833 | // Strings, numbers, dates, and booleans are compared by value. 1834 | case '[object String]': 1835 | // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is 1836 | // equivalent to `new String("5")`. 1837 | return a == String(b); 1838 | case '[object Number]': 1839 | // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for 1840 | // other numeric values. 1841 | return a != +a ? b != +b : (a === 0 ? 1 / a == 1 / b : a == +b); 1842 | case '[object Date]': 1843 | case '[object Boolean]': 1844 | // Coerce dates and booleans to numeric primitive values. Dates are compared by their 1845 | // millisecond representations. Note that invalid dates with millisecond representations 1846 | // of `NaN` are not equivalent. 1847 | return +a == +b; 1848 | // RegExps are compared by their source patterns and flags. 1849 | case '[object RegExp]': 1850 | return a.source == b.source && 1851 | a.global == b.global && 1852 | a.multiline == b.multiline && 1853 | a.ignoreCase == b.ignoreCase; 1854 | } 1855 | if (typeof a != 'object' || typeof b != 'object') { return false; } 1856 | // Assume equality for cyclic structures. The algorithm for detecting cyclic 1857 | // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. 1858 | var length = aStack.length; 1859 | while (length--) { 1860 | // Linear search. Performance is inversely proportional to the number of 1861 | // unique nested structures. 1862 | if (aStack[length] == a) { return bStack[length] == b; } 1863 | } 1864 | // Add the first object to the stack of traversed objects. 1865 | aStack.push(a); 1866 | bStack.push(b); 1867 | var size = 0; 1868 | // Recursively compare objects and arrays. 1869 | if (className == '[object Array]') { 1870 | // Compare array lengths to determine if a deep comparison is necessary. 1871 | size = a.length; 1872 | result = size == b.length; 1873 | if (result) { 1874 | // Deep compare the contents, ignoring non-numeric properties. 1875 | while (size--) { 1876 | if (!(result = eq(a[size], b[size], aStack, bStack, customTesters))) { break; } 1877 | } 1878 | } 1879 | } else { 1880 | // Objects with different constructors are not equivalent, but `Object`s 1881 | // from different frames are. 1882 | var aCtor = a.constructor, bCtor = b.constructor; 1883 | if (aCtor !== bCtor && !(isFunction(aCtor) && (aCtor instanceof aCtor) && 1884 | isFunction(bCtor) && (bCtor instanceof bCtor))) { 1885 | return false; 1886 | } 1887 | // Deep compare objects. 1888 | for (var key in a) { 1889 | if (has(a, key)) { 1890 | // Count the expected number of properties. 1891 | size++; 1892 | // Deep compare each member. 1893 | if (!(result = has(b, key) && eq(a[key], b[key], aStack, bStack, customTesters))) { break; } 1894 | } 1895 | } 1896 | // Ensure that both objects contain the same number of properties. 1897 | if (result) { 1898 | for (key in b) { 1899 | if (has(b, key) && !(size--)) { break; } 1900 | } 1901 | result = !size; 1902 | } 1903 | } 1904 | // Remove the first object from the stack of traversed objects. 1905 | aStack.pop(); 1906 | bStack.pop(); 1907 | 1908 | return result; 1909 | 1910 | function has(obj, key) { 1911 | return obj.hasOwnProperty(key); 1912 | } 1913 | 1914 | function isFunction(obj) { 1915 | return typeof obj === 'function'; 1916 | } 1917 | } 1918 | }; 1919 | 1920 | getJasmineRequireObj().toBe = function() { 1921 | function toBe() { 1922 | return { 1923 | compare: function(actual, expected) { 1924 | return { 1925 | pass: actual === expected 1926 | }; 1927 | } 1928 | }; 1929 | } 1930 | 1931 | return toBe; 1932 | }; 1933 | 1934 | getJasmineRequireObj().toBeCloseTo = function() { 1935 | 1936 | function toBeCloseTo() { 1937 | return { 1938 | compare: function(actual, expected, precision) { 1939 | if (precision !== 0) { 1940 | precision = precision || 2; 1941 | } 1942 | 1943 | return { 1944 | pass: Math.abs(expected - actual) < (Math.pow(10, -precision) / 2) 1945 | }; 1946 | } 1947 | }; 1948 | } 1949 | 1950 | return toBeCloseTo; 1951 | }; 1952 | 1953 | getJasmineRequireObj().toBeDefined = function() { 1954 | function toBeDefined() { 1955 | return { 1956 | compare: function(actual) { 1957 | return { 1958 | pass: (void 0 !== actual) 1959 | }; 1960 | } 1961 | }; 1962 | } 1963 | 1964 | return toBeDefined; 1965 | }; 1966 | 1967 | getJasmineRequireObj().toBeFalsy = function() { 1968 | function toBeFalsy() { 1969 | return { 1970 | compare: function(actual) { 1971 | return { 1972 | pass: !!!actual 1973 | }; 1974 | } 1975 | }; 1976 | } 1977 | 1978 | return toBeFalsy; 1979 | }; 1980 | 1981 | getJasmineRequireObj().toBeGreaterThan = function() { 1982 | 1983 | function toBeGreaterThan() { 1984 | return { 1985 | compare: function(actual, expected) { 1986 | return { 1987 | pass: actual > expected 1988 | }; 1989 | } 1990 | }; 1991 | } 1992 | 1993 | return toBeGreaterThan; 1994 | }; 1995 | 1996 | 1997 | getJasmineRequireObj().toBeLessThan = function() { 1998 | function toBeLessThan() { 1999 | return { 2000 | 2001 | compare: function(actual, expected) { 2002 | return { 2003 | pass: actual < expected 2004 | }; 2005 | } 2006 | }; 2007 | } 2008 | 2009 | return toBeLessThan; 2010 | }; 2011 | getJasmineRequireObj().toBeNaN = function(j$) { 2012 | 2013 | function toBeNaN() { 2014 | return { 2015 | compare: function(actual) { 2016 | var result = { 2017 | pass: (actual !== actual) 2018 | }; 2019 | 2020 | if (result.pass) { 2021 | result.message = "Expected actual not to be NaN."; 2022 | } else { 2023 | result.message = "Expected " + j$.pp(actual) + " to be NaN."; 2024 | } 2025 | 2026 | return result; 2027 | } 2028 | }; 2029 | } 2030 | 2031 | return toBeNaN; 2032 | }; 2033 | 2034 | getJasmineRequireObj().toBeNull = function() { 2035 | 2036 | function toBeNull() { 2037 | return { 2038 | compare: function(actual) { 2039 | return { 2040 | pass: actual === null 2041 | }; 2042 | } 2043 | }; 2044 | } 2045 | 2046 | return toBeNull; 2047 | }; 2048 | 2049 | getJasmineRequireObj().toBeTruthy = function() { 2050 | 2051 | function toBeTruthy() { 2052 | return { 2053 | compare: function(actual) { 2054 | return { 2055 | pass: !!actual 2056 | }; 2057 | } 2058 | }; 2059 | } 2060 | 2061 | return toBeTruthy; 2062 | }; 2063 | 2064 | getJasmineRequireObj().toBeUndefined = function() { 2065 | 2066 | function toBeUndefined() { 2067 | return { 2068 | compare: function(actual) { 2069 | return { 2070 | pass: void 0 === actual 2071 | }; 2072 | } 2073 | }; 2074 | } 2075 | 2076 | return toBeUndefined; 2077 | }; 2078 | 2079 | getJasmineRequireObj().toContain = function() { 2080 | function toContain(util, customEqualityTesters) { 2081 | customEqualityTesters = customEqualityTesters || []; 2082 | 2083 | return { 2084 | compare: function(actual, expected) { 2085 | 2086 | return { 2087 | pass: util.contains(actual, expected, customEqualityTesters) 2088 | }; 2089 | } 2090 | }; 2091 | } 2092 | 2093 | return toContain; 2094 | }; 2095 | 2096 | getJasmineRequireObj().toEqual = function() { 2097 | 2098 | function toEqual(util, customEqualityTesters) { 2099 | customEqualityTesters = customEqualityTesters || []; 2100 | 2101 | return { 2102 | compare: function(actual, expected) { 2103 | var result = { 2104 | pass: false 2105 | }; 2106 | 2107 | result.pass = util.equals(actual, expected, customEqualityTesters); 2108 | 2109 | return result; 2110 | } 2111 | }; 2112 | } 2113 | 2114 | return toEqual; 2115 | }; 2116 | 2117 | getJasmineRequireObj().toHaveBeenCalled = function(j$) { 2118 | 2119 | function toHaveBeenCalled() { 2120 | return { 2121 | compare: function(actual) { 2122 | var result = {}; 2123 | 2124 | if (!j$.isSpy(actual)) { 2125 | throw new Error('Expected a spy, but got ' + j$.pp(actual) + '.'); 2126 | } 2127 | 2128 | if (arguments.length > 1) { 2129 | throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); 2130 | } 2131 | 2132 | result.pass = actual.calls.any(); 2133 | 2134 | result.message = result.pass ? 2135 | "Expected spy " + actual.and.identity() + " not to have been called." : 2136 | "Expected spy " + actual.and.identity() + " to have been called."; 2137 | 2138 | return result; 2139 | } 2140 | }; 2141 | } 2142 | 2143 | return toHaveBeenCalled; 2144 | }; 2145 | 2146 | getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { 2147 | 2148 | function toHaveBeenCalledWith(util) { 2149 | return { 2150 | compare: function() { 2151 | var args = Array.prototype.slice.call(arguments, 0), 2152 | actual = args[0], 2153 | expectedArgs = args.slice(1), 2154 | result = { pass: false }; 2155 | 2156 | if (!j$.isSpy(actual)) { 2157 | throw new Error('Expected a spy, but got ' + j$.pp(actual) + '.'); 2158 | } 2159 | 2160 | if (!actual.calls.any()) { 2161 | result.message = "Expected spy " + actual.and.identity() + " to have been called with " + j$.pp(expectedArgs) + " but it was never called."; 2162 | return result; 2163 | } 2164 | 2165 | if (util.contains(actual.calls.allArgs(), expectedArgs)) { 2166 | result.pass = true; 2167 | result.message = "Expected spy " + actual.and.identity() + " not to have been called with " + j$.pp(expectedArgs) + " but it was."; 2168 | } else { 2169 | result.message = "Expected spy " + actual.and.identity() + " to have been called with " + j$.pp(expectedArgs) + " but actual calls were " + j$.pp(actual.calls.allArgs()).replace(/^\[ | \]$/g, '') + "."; 2170 | } 2171 | 2172 | return result; 2173 | } 2174 | }; 2175 | } 2176 | 2177 | return toHaveBeenCalledWith; 2178 | }; 2179 | 2180 | getJasmineRequireObj().toMatch = function() { 2181 | 2182 | function toMatch() { 2183 | return { 2184 | compare: function(actual, expected) { 2185 | var regexp = new RegExp(expected); 2186 | 2187 | return { 2188 | pass: regexp.test(actual) 2189 | }; 2190 | } 2191 | }; 2192 | } 2193 | 2194 | return toMatch; 2195 | }; 2196 | 2197 | getJasmineRequireObj().toThrow = function(j$) { 2198 | 2199 | function toThrow(util) { 2200 | return { 2201 | compare: function(actual, expected) { 2202 | var result = { pass: false }, 2203 | threw = false, 2204 | thrown; 2205 | 2206 | if (typeof actual != "function") { 2207 | throw new Error("Actual is not a Function"); 2208 | } 2209 | 2210 | try { 2211 | actual(); 2212 | } catch (e) { 2213 | threw = true; 2214 | thrown = e; 2215 | } 2216 | 2217 | if (!threw) { 2218 | result.message = "Expected function to throw an exception."; 2219 | return result; 2220 | } 2221 | 2222 | if (arguments.length == 1) { 2223 | result.pass = true; 2224 | result.message = "Expected function not to throw, but it threw " + j$.pp(thrown) + "."; 2225 | 2226 | return result; 2227 | } 2228 | 2229 | if (util.equals(thrown, expected)) { 2230 | result.pass = true; 2231 | result.message = "Expected function not to throw " + j$.pp(expected) + "."; 2232 | } else { 2233 | result.message = "Expected function to throw " + j$.pp(expected) + ", but it threw " + j$.pp(thrown) + "."; 2234 | } 2235 | 2236 | return result; 2237 | } 2238 | }; 2239 | } 2240 | 2241 | return toThrow; 2242 | }; 2243 | 2244 | getJasmineRequireObj().toThrowError = function(j$) { 2245 | function toThrowError (util) { 2246 | return { 2247 | compare: function(actual) { 2248 | var threw = false, 2249 | thrown, 2250 | errorType, 2251 | message, 2252 | regexp, 2253 | name, 2254 | constructorName; 2255 | 2256 | if (typeof actual != "function") { 2257 | throw new Error("Actual is not a Function"); 2258 | } 2259 | 2260 | extractExpectedParams.apply(null, arguments); 2261 | 2262 | try { 2263 | actual(); 2264 | } catch (e) { 2265 | threw = true; 2266 | thrown = e; 2267 | } 2268 | 2269 | if (!threw) { 2270 | return fail("Expected function to throw an Error."); 2271 | } 2272 | 2273 | if (!(thrown instanceof Error)) { 2274 | return fail("Expected function to throw an Error, but it threw " + thrown + "."); 2275 | } 2276 | 2277 | if (arguments.length == 1) { 2278 | return pass("Expected function not to throw an Error, but it threw " + fnNameFor(thrown) + "."); 2279 | } 2280 | 2281 | if (errorType) { 2282 | name = fnNameFor(errorType); 2283 | constructorName = fnNameFor(thrown.constructor); 2284 | } 2285 | 2286 | if (errorType && message) { 2287 | if (thrown.constructor == errorType && util.equals(thrown.message, message)) { 2288 | return pass("Expected function not to throw " + name + " with message \"" + message + "\"."); 2289 | } else { 2290 | return fail("Expected function to throw " + name + " with message \"" + message + 2291 | "\", but it threw " + constructorName + " with message \"" + thrown.message + "\"."); 2292 | } 2293 | } 2294 | 2295 | if (errorType && regexp) { 2296 | if (thrown.constructor == errorType && regexp.test(thrown.message)) { 2297 | return pass("Expected function not to throw " + name + " with message matching " + regexp + "."); 2298 | } else { 2299 | return fail("Expected function to throw " + name + " with message matching " + regexp + 2300 | ", but it threw " + constructorName + " with message \"" + thrown.message + "\"."); 2301 | } 2302 | } 2303 | 2304 | if (errorType) { 2305 | if (thrown.constructor == errorType) { 2306 | return pass("Expected function not to throw " + name + "."); 2307 | } else { 2308 | return fail("Expected function to throw " + name + ", but it threw " + constructorName + "."); 2309 | } 2310 | } 2311 | 2312 | if (message) { 2313 | if (thrown.message == message) { 2314 | return pass("Expected function not to throw an exception with message " + j$.pp(message) + "."); 2315 | } else { 2316 | return fail("Expected function to throw an exception with message " + j$.pp(message) + 2317 | ", but it threw an exception with message " + j$.pp(thrown.message) + "."); 2318 | } 2319 | } 2320 | 2321 | if (regexp) { 2322 | if (regexp.test(thrown.message)) { 2323 | return pass("Expected function not to throw an exception with a message matching " + j$.pp(regexp) + "."); 2324 | } else { 2325 | return fail("Expected function to throw an exception with a message matching " + j$.pp(regexp) + 2326 | ", but it threw an exception with message " + j$.pp(thrown.message) + "."); 2327 | } 2328 | } 2329 | 2330 | function fnNameFor(func) { 2331 | return func.name || func.toString().match(/^\s*function\s*(\w*)\s*\(/)[1]; 2332 | } 2333 | 2334 | function pass(notMessage) { 2335 | return { 2336 | pass: true, 2337 | message: notMessage 2338 | }; 2339 | } 2340 | 2341 | function fail(message) { 2342 | return { 2343 | pass: false, 2344 | message: message 2345 | }; 2346 | } 2347 | 2348 | function extractExpectedParams() { 2349 | if (arguments.length == 1) { 2350 | return; 2351 | } 2352 | 2353 | if (arguments.length == 2) { 2354 | var expected = arguments[1]; 2355 | 2356 | if (expected instanceof RegExp) { 2357 | regexp = expected; 2358 | } else if (typeof expected == "string") { 2359 | message = expected; 2360 | } else if (checkForAnErrorType(expected)) { 2361 | errorType = expected; 2362 | } 2363 | 2364 | if (!(errorType || message || regexp)) { 2365 | throw new Error("Expected is not an Error, string, or RegExp."); 2366 | } 2367 | } else { 2368 | if (checkForAnErrorType(arguments[1])) { 2369 | errorType = arguments[1]; 2370 | } else { 2371 | throw new Error("Expected error type is not an Error."); 2372 | } 2373 | 2374 | if (arguments[2] instanceof RegExp) { 2375 | regexp = arguments[2]; 2376 | } else if (typeof arguments[2] == "string") { 2377 | message = arguments[2]; 2378 | } else { 2379 | throw new Error("Expected error message is not a string or RegExp."); 2380 | } 2381 | } 2382 | } 2383 | 2384 | function checkForAnErrorType(type) { 2385 | if (typeof type !== "function") { 2386 | return false; 2387 | } 2388 | 2389 | var Surrogate = function() {}; 2390 | Surrogate.prototype = type.prototype; 2391 | return (new Surrogate()) instanceof Error; 2392 | } 2393 | } 2394 | }; 2395 | } 2396 | 2397 | return toThrowError; 2398 | }; 2399 | 2400 | getJasmineRequireObj().version = function() { 2401 | return "2.0.0"; 2402 | }; 2403 | -------------------------------------------------------------------------------- /javascript/lib/jasmine-2.0.0/jasmine_favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amvtek/EventSource/2ced4fad8755c8f1e90600fc12af508dd7315004/javascript/lib/jasmine-2.0.0/jasmine_favicon.png -------------------------------------------------------------------------------- /javascript/spec/concurrentSpec.js: -------------------------------------------------------------------------------- 1 | 2 | describe('Test concurrent operation of various EventSource against real stream', function(){ 3 | 4 | var polyfillEventSource = window['TestEventSource']; 5 | 6 | var nativeEventSource = window['EventSource']; 7 | 8 | var TEST_SOURCE_URLS = [ 9 | "/test/eventsource/4-messages-with-seed-01", 10 | "/test/eventsource/6-messages-with-seed-02", 11 | "/test/eventsource/8-messages-closeat-4-with-seed-03", 12 | "/test/eventsource/16-messages-closeat-5-with-seed-04", 13 | ]; 14 | 15 | 16 | jasmine.DEFAULT_TIMEOUT_INTERVAL = 300000; 17 | 18 | var WM = function (EventSourceFactory, EventSourceName, sourceUrls){ 19 | 20 | var self = {}; 21 | 22 | var _count = sourceUrls.length; 23 | 24 | self.setdonecb = function(donefunc){ 25 | 26 | if (_count <= 0 && donefunc ){ 27 | donefunc(); 28 | } 29 | self.donecallback = donefunc; 30 | }; 31 | 32 | self.complete = function(){ 33 | 34 | --_count; 35 | if (_count <= 0 && self.donecallback){ 36 | self.donecallback(); 37 | } 38 | }; 39 | 40 | function EVS(srcUrl){ 41 | 42 | var evs = new EventSourceFactory(srcUrl); 43 | var ctx = this; 44 | 45 | ctx.eventsource = evs; 46 | 47 | ctx.msgEvents = []; 48 | evs.addEventListener('message', function (e) { 49 | if (e.data) {ctx.msgEvents.push(e.data);} 50 | }, false); 51 | 52 | ctx.openEvents = []; 53 | evs.addEventListener('open', function (e) { 54 | ctx.openEvents.push(e.type); 55 | }, false); 56 | 57 | ctx.errorEvents = []; 58 | evs.addEventListener('error', function (e) { 59 | ctx.errorEvents.push(e.type); 60 | }, false); 61 | 62 | ctx.testmetaEvents = []; 63 | evs.addEventListener('testmeta', function (e) { 64 | ctx.testmetaEvents = JSON.parse(e.data); 65 | }, false); 66 | 67 | ctx.testendEvents = []; 68 | evs.addEventListener('testend', function (e) { 69 | ctx.testendEvents.push(e.type); 70 | self.complete(); 71 | evs.close(); 72 | }, false); 73 | }; 74 | 75 | // create one EventSource for each url in sourceUrls 76 | self.sources = []; 77 | for (var i=0; i < sourceUrls.length; i++){ 78 | 79 | console.log("creating new "+EventSourceName+" on "+sourceUrls[i]); 80 | self.sources.push(new EVS(sourceUrls[i])); 81 | } 82 | 83 | return self; 84 | }; 85 | 86 | 87 | describe("consume 4 sources concurrently", function(){ 88 | 89 | describe('using polyfill eventsource', function () { 90 | 91 | var wm = WM(polyfillEventSource,"polyfill EventSource", TEST_SOURCE_URLS); 92 | 93 | beforeEach(function (done) { 94 | 95 | this.sources = wm.sources; 96 | wm.setdonecb(done); 97 | }); 98 | 99 | afterEach(function (done){ 100 | 101 | console.log("polyfill EventSource SPEC OVER..."); 102 | done(); 103 | }); 104 | 105 | 106 | it("sources.length shall be equal to TEST_SOURCE_URLS.length", function (){ 107 | 108 | expect(this.sources.length).toEqual(TEST_SOURCE_URLS.length); 109 | }); 110 | 111 | it("data in testmeta event should match all incoming messages data", function () { 112 | 113 | var result; 114 | for (var i=0; i < this.sources.length; i++){ 115 | 116 | result = this.sources[i]; 117 | expect(result.testmetaEvents).toEqual(result.msgEvents); 118 | }; 119 | }); 120 | 121 | it("testend event was received", function () { 122 | 123 | var result; 124 | for (var i=0; i < this.sources.length; i++){ 125 | 126 | result = this.sources[i]; 127 | expect(result.testendEvents.length).toEqual(1); 128 | }; 129 | }); 130 | }); 131 | 132 | if (nativeEventSource){ 133 | 134 | describe('using native eventsource', function () { 135 | 136 | var wm = WM(nativeEventSource,"native EventSource", TEST_SOURCE_URLS); 137 | 138 | beforeEach(function (done) { 139 | this.sources = wm.sources; 140 | wm.setdonecb(done); 141 | }); 142 | 143 | afterEach(function (done){ 144 | 145 | console.log("native EventSource SPEC OVER..."); 146 | done(); 147 | }); 148 | 149 | it("sources.length shall be equal to TEST_SOURCE_URLS.length", function (){ 150 | 151 | expect(this.sources.length).toEqual(TEST_SOURCE_URLS.length); 152 | }); 153 | 154 | it("data in testmeta event should match all incoming messages data", function () { 155 | 156 | var result; 157 | for (var i=0; i < this.sources.length; i++){ 158 | 159 | result = this.sources[i]; 160 | expect(result.testmetaEvents).toEqual(result.msgEvents); 161 | }; 162 | }); 163 | 164 | it("testend event was received", function () { 165 | 166 | var result; 167 | for (var i=0; i < this.sources.length; i++){ 168 | 169 | result = this.sources[i]; 170 | expect(result.testendEvents.length).toEqual(1); 171 | }; 172 | }); 173 | }); 174 | }; 175 | }); 176 | }); 177 | -------------------------------------------------------------------------------- /javascript/spec/eventsourceSpec.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by vasi on 4/8/14. 3 | */ 4 | 5 | var evsName = "EventSource", 6 | evsImportName = (window._eventSourceImportPrefix || '') + evsName, 7 | isEventSourceSupported = (window["EventSource"] != undefined); 8 | 9 | describe("Testing EventSource polyfill with MockupXHR", function() { 10 | 11 | var previousXHR; 12 | 13 | beforeEach(function() { 14 | 15 | var mockupXHR = function(evs) { 16 | 17 | this.responseText = ''; 18 | this.evs = evs; 19 | }; 20 | 21 | mockupXHR.prototype = { 22 | 23 | useXDomaineRequest: false, 24 | 25 | _request: null, 26 | 27 | _failed: false, 28 | 29 | isReady: function() { 30 | 31 | return true; 32 | }, 33 | 34 | isDone: function() { 35 | 36 | return false; 37 | }, 38 | 39 | hasError: function() { 40 | 41 | return (this._failed); 42 | }, 43 | 44 | getBuffer: function() { 45 | 46 | return this.responseText; 47 | }, 48 | 49 | abort: function() { 50 | 51 | this.responseText = ''; 52 | }, 53 | 54 | sendData: function(str) { 55 | 56 | this.responseText += str; 57 | this.evs._onxhrdata(); 58 | } 59 | }; 60 | 61 | this.eventSource = window[evsImportName]; 62 | previousXHR = this.eventSource.prototype.XHR; 63 | this.eventSource.prototype.XHR = mockupXHR; 64 | }); 65 | 66 | afterEach(function () { 67 | this.eventSource.prototype.XHR = previousXHR; 68 | }); 69 | 70 | describe("Provide MockupXHR class to ease testing the EventSource class", function() { 71 | var evs; 72 | 73 | beforeEach(function (done) { 74 | 75 | evs = new this.eventSource('http://exampleLoadMockupXHR.com'); 76 | setTimeout(function () { 77 | done(); 78 | }, 0); 79 | }); 80 | 81 | afterEach(function (){ 82 | 83 | evs.close(); 84 | }); 85 | 86 | it("should load mockupXHR instead of native XHR", function() { 87 | // the prefix is set in SpecRunner.html 88 | 89 | expect(evs._xhr.sendData).toBeDefined(); 90 | }); 91 | }); 92 | 93 | describe("Setting up the polyfill EventSource for it to be available alongside browser native EventSource", function() { 94 | 95 | it("When no options object is passed to the EventSource constructor, all option in EventSource.prototype.defaultOptions are set.", function() { 96 | // the prefix is set in SpecRunner.html 97 | 98 | var evs = new this.eventSource('http://example.com'); 99 | var expected = evs.defaultOptions; // in this test we expect all options to be the default ones 100 | 101 | var actual = { 102 | loggingEnabled: evs.loggingEnabled, 103 | loggingPrefix: evs.loggingPrefix, 104 | interval: evs.interval, 105 | bufferSizeLimit: evs.bufferSizeLimit, // bytes 106 | silentTimeout: evs.silentTimeout, // milliseconds 107 | getArgs: evs.getArgs, 108 | xhrHeaders: evs.xhrHeaders 109 | }; 110 | 111 | expect(actual).toEqual(expected); 112 | 113 | evs.close(); 114 | }); 115 | 116 | it("When options is passed to constructor, all option not defined in defaultOptions are ignored.", function() { 117 | // the prefix is set in SpecRunner.html 118 | 119 | var extraOptions = { 120 | extraOption: 1000 121 | }; 122 | var evs = new this.eventSource('http://example.com', extraOptions); 123 | 124 | expect(evs.extraOption).toBeUndefined(); 125 | 126 | evs.close(); 127 | }); 128 | 129 | it("When options is passed to constructor, option defined in defaultOptions are over written.", function() { 130 | // the prefix is set in SpecRunner.html 131 | 132 | var options = { 133 | interval: 1000, 134 | bufferSizeLimit: 256*1024 // bytes 135 | }; 136 | 137 | var evs = new this.eventSource('http://example.com', options); 138 | var defaults = evs.defaultOptions; 139 | 140 | var expected = { 141 | interval: options.interval, 142 | bufferSizeLimit: options.bufferSizeLimit, 143 | silentTimeout: defaults.silentTimeout, // milliseconds 144 | getArgs: defaults.getArgs, 145 | xhrHeaders: defaults.xhrHeaders 146 | }; 147 | 148 | var actual = { 149 | interval: evs.interval, 150 | bufferSizeLimit: evs.bufferSizeLimit, // bytes 151 | silentTimeout: evs.silentTimeout, // milliseconds 152 | getArgs: evs.getArgs, 153 | xhrHeaders: evs.xhrHeaders 154 | }; 155 | 156 | expect(actual).toEqual(expected); 157 | 158 | evs.close(); 159 | }); 160 | }); 161 | 162 | describe("tests for urlWithParams", function() { 163 | 164 | it("When the baseURL already contains arguments, the rest of evs arguments are appended.", function() { 165 | 166 | var params = { 167 | a: 1, 168 | b: 2 169 | }; 170 | var evs = new this.eventSource('http://example.com?ciao=ola'); 171 | var urlWithParams = evs.urlWithParams; 172 | expect(urlWithParams('http://example.com?ciao=ola', params)).toBe('http://example.com?ciao=ola&a=1&b=2'); 173 | }) 174 | 175 | it("When called with a null or undefined params, baseUrl is returned.", function() { 176 | // the prefix is set in SpecRunner.html 177 | 178 | var evs = new this.eventSource('http://exampleurlWithParams.com'); 179 | var urlWithParams = evs.urlWithParams; 180 | expect(urlWithParams('http://example.com')).toBe('http://example.com'); 181 | }); 182 | 183 | it("When called with a params object that contains no attribute but has a prototype with attributes, baseUrl is returned.", function() { 184 | // the prefix is set in SpecRunner.html 185 | 186 | var Params = function () {}; 187 | Params.prototype = { 188 | 'a': 1, 189 | 'b': 2 190 | }; 191 | var evs = new this.eventSource('http://exampleurlWithParams.com'); 192 | var urlWithParams = evs.urlWithParams; 193 | expect(urlWithParams('http://example.com', new Params())).toBe('http://example.com'); 194 | }); 195 | 196 | it("When called with a params that define arguments, those are added to the url", function() { 197 | // the prefix is set in SpecRunner.html 198 | 199 | var params = { 200 | a: 1, 201 | b: 2 202 | }; 203 | var evs = new this.eventSource('http://exampleurlWithParams.com'); 204 | var urlWithParams = evs.urlWithParams; 205 | expect(urlWithParams('http://example.com', params)).toBe('http://example.com?a=1&b=2'); 206 | }); 207 | }); 208 | 209 | describe("tests for lastLineIndex", function() { 210 | 211 | it("returns correct lastMessageIndex in case of \\n\\n", function() { 212 | // the prefix is set in SpecRunner.html 213 | 214 | var evs = new this.eventSource('http://exampleurlWithParams.com'); 215 | var lastLineIndex = evs.lastMessageIndex; 216 | expect(lastLineIndex("0123\r\r678\n\n9")).toEqual([9, 11]); 217 | }); 218 | 219 | it("returns correct lastLineIndex in case of \\r\\r", function() { 220 | // the prefix is set in SpecRunner.html 221 | 222 | var evs = new this.eventSource('http://exampleurlWithParams.com'); 223 | var lastLineIndex = evs.lastMessageIndex; 224 | expect(lastLineIndex("0123\n\n678\r\r")).toEqual([9, 11]); 225 | }); 226 | 227 | it("returns correct lastLineIndex in case of \\r\\n\\r\\n", function() { 228 | // the prefix is set in SpecRunner.html 229 | 230 | var evs = new this.eventSource('http://exampleurlWithParams.com'); 231 | var lastLineIndex = evs.lastMessageIndex; 232 | expect(lastLineIndex("0123\n\n67\r\n\r\n")).toEqual([8, 12]); 233 | }); 234 | }); 235 | 236 | describe("tests for trimWhiteSpace", function() { 237 | 238 | it("should remove whitespace left and right of the string", function () { 239 | // the prefix is set in SpecRunner.html 240 | 241 | var evs = new this.eventSource('http://exampleurlWithParams.com'); 242 | var trimWhiteSpace = evs.trimWhiteSpace; 243 | expect(trimWhiteSpace(" text between spaces ")).toBe('text between spaces'); 244 | }); 245 | }); 246 | 247 | describe("tests for normalizeToLF", function() { 248 | 249 | it("should replace CR and CRLF with LF(\\n) inside a string", function () { 250 | // the prefix is set in SpecRunner.html 251 | 252 | var evs = new this.eventSource('http://example.com'); 253 | var normalizeToLF = evs.normalizeToLF; 254 | 255 | var str = "LF:\n. CR:\r. CRLF:\r\n. and again LF:\n. CR:\r. CRLF:\r\n. Double CR:\r\r. Double CRLF:\r\n\r\n"; 256 | var expectedStr = "LF:\n. CR:\n. CRLF:\n. and again LF:\n. CR:\n. CRLF:\n. Double CR:\n\n. Double CRLF:\n\n"; 257 | var actualStr = normalizeToLF(str); 258 | 259 | expect(actualStr).toBe(expectedStr); 260 | 261 | evs.close(); 262 | }); 263 | }); 264 | 265 | describe("Simulates EventSource stream using MockupXHR", function() { 266 | 267 | var evs, receivedMessageEvents, receivedOpenEvents, receivedErrorEvents; 268 | 269 | beforeEach(function (done) { 270 | 271 | evs = new this.eventSource('http://exampleSimulatesEventSourceWithMockupXHR.com'); 272 | receivedMessageEvents = []; 273 | receivedOpenEvents = []; 274 | receivedErrorEvents = []; 275 | evs.addEventListener('message', function(e) { 276 | receivedMessageEvents.push(e.data); 277 | }, false); 278 | evs.addEventListener('open', function(e) { 279 | receivedOpenEvents.push(e.type); 280 | }, false); 281 | evs.addEventListener('error', function(e) { 282 | receivedErrorEvents.push(e.type); 283 | }, false); 284 | 285 | setTimeout(function () { 286 | done(); 287 | }, 0) 288 | }); 289 | 290 | afterEach(function (done) { 291 | evs.close(); 292 | done(); 293 | }); 294 | 295 | it("check that Mockup XHR is used", function () { 296 | 297 | expect(evs._xhr.sendData).toBeDefined(); 298 | }); 299 | 300 | it("Initial BOM mark is skipped", function () { 301 | 302 | evs._xhr.sendData('\ufeffdata: "First line of data."\r\r'); 303 | var expectedEvents = ['"First line of data."']; 304 | expect(receivedMessageEvents).toEqual(expectedEvents); 305 | }); 306 | 307 | it("Multiline message are properly reassembled", function () { 308 | 309 | evs._xhr.sendData('data: "First line of data."\ndata: "Second line of data."\r\r'); 310 | var expectedEvents = ['"First line of data."\n"Second line of data."']; 311 | expect(receivedMessageEvents).toEqual(expectedEvents); 312 | }); 313 | 314 | it("Chunky transmissions are properly buffered", function () { 315 | 316 | evs._xhr.sendData('data: "First line of data."\ndata: "Second line of data."\n\ndata: "First part of broken message.'); 317 | evs._xhr.sendData('Second part of broken message."\n\n'); 318 | var expectedEvents = ['"First line of data."\n"Second line of data."', '"First part of broken message.Second part of broken message."']; 319 | expect(receivedMessageEvents).toEqual(expectedEvents); 320 | }); 321 | 322 | it("id lines are properly processed", function () { 323 | 324 | var expectedEventId = '1983'; 325 | evs._xhr.sendData('data: "First line of data."\ndata: "Second line of data."\n\ndata: "First part of broken message.'); 326 | evs._xhr.sendData('Second part of broken message."\n\nid: '+expectedEventId+'\ndata: "Message with new id"\n\n'); 327 | expect(evs.lastEventId).toEqual(expectedEventId); 328 | }); 329 | 330 | it("option bufferSizeLimit is taken into account", function () { 331 | 332 | evs.bufferSizeLimit = 100; 333 | evs._xhr.sendData('data: "First line of data."\ndata: "Second line of data."\n\ndata: "First part of broken message.'); 334 | evs._xhr.sendData('Second part of broken message."\n\nid: 1983\rdata: "Message with new id"\n\n'); 335 | evs._xhr.sendData('data: "Message to force dispatching the open event"\n\n'); 336 | var expectedOpenEvents = ["open", "open"]; 337 | expect(receivedOpenEvents).toEqual(expectedOpenEvents); 338 | }); 339 | 340 | describe("Manually ticking the Jasmine Clock to produce a sleep until events are fired:", function () { 341 | 342 | var previous = 0; 343 | 344 | beforeEach(function() { 345 | 346 | previous = evs.silentTimeout; 347 | jasmine.clock().install(); 348 | }); 349 | 350 | afterEach(function(done) { 351 | 352 | evs.silentTimeout = previous; 353 | jasmine.clock().uninstall(); 354 | 355 | done(); 356 | }); 357 | 358 | it("option silentTimeout is taken into account", function () { 359 | 360 | evs.silentTimeout = 1000; 361 | evs._xhr.sendData('data: "First line of data."\ndata: "Second line of data."\n\r\ndata: "First part of broken message.'); 362 | evs._xhr.sendData('Second part of broken message."\n\r\nid: 1983\rdata: "Message with new id"\n\n'); 363 | 364 | setTimeout(function() { 365 | }, 1100); 366 | jasmine.clock().tick(1101); 367 | 368 | evs._xhr.sendData('data: "Message to force dispatching the open event"\n\n'); 369 | var expectedOpenEvents = ["open", "open"]; 370 | var expectedErrorEvents = ["error"]; 371 | 372 | expect(receivedOpenEvents).toEqual(expectedOpenEvents); 373 | expect(receivedErrorEvents).toEqual(expectedErrorEvents); 374 | }); 375 | }); 376 | }); 377 | }); 378 | 379 | describe("Evaluating EventSource 'time to attach listener' doubt", function() { 380 | 381 | var evs, previousXHR, 382 | receivedMessageEvents = [], 383 | receivedOpenEvents = [], 384 | receivedErrorEvents = []; 385 | 386 | beforeEach(function (done) { 387 | 388 | var mockupXHR = function (evs) { 389 | 390 | this.responseText = ''; 391 | this.evs = evs; 392 | evs._xhr = this; 393 | 394 | // send data right away to stress the events 395 | this.sendData(this.initialData || ''); 396 | }; 397 | 398 | mockupXHR.prototype = { 399 | 400 | initialData: 'data: "I will fire very quick"\n\n', 401 | 402 | useXDomaineRequest: false, 403 | 404 | _request: null, 405 | 406 | _failed: false, 407 | 408 | isReady: function () { 409 | 410 | return true; 411 | }, 412 | 413 | isDone: function () { 414 | 415 | return false; 416 | }, 417 | 418 | hasError: function () { 419 | 420 | return (this._failed); 421 | }, 422 | 423 | getBuffer: function () { 424 | 425 | return this.responseText; 426 | }, 427 | 428 | abort: function () { 429 | 430 | }, 431 | 432 | sendData: function (str) { 433 | 434 | evs = this.evs; 435 | this.responseText += str; 436 | evs._onxhrdata(); 437 | } 438 | }; 439 | 440 | this.eventSource = window[evsImportName]; 441 | previousXHR = this.eventSource.prototype.XHR; 442 | this.eventSource.prototype.XHR = mockupXHR; 443 | 444 | evs = new this.eventSource('http://exampleTimeToAttachDoubt.com'); 445 | 446 | evs.addEventListener('message', function(e) { 447 | receivedMessageEvents.push(e.data); 448 | }, false); 449 | evs.addEventListener('open', function(e) { 450 | receivedOpenEvents.push(e.type); 451 | }, false); 452 | evs.addEventListener('error', function(e) { 453 | receivedErrorEvents.push(e.data); 454 | }, false); 455 | setTimeout(function () { 456 | done(); 457 | }, 0); 458 | }); 459 | 460 | afterEach(function (done) { 461 | evs.close(); 462 | this.eventSource.prototype.XHR = previousXHR; 463 | done(); 464 | }); 465 | 466 | it("should catch initial message sent", function (done) { 467 | 468 | var expectedMessageEvents = ['"I will fire very quick"']; 469 | expect(receivedMessageEvents).toEqual(expectedMessageEvents); 470 | done(); 471 | }) 472 | }); 473 | 474 | describe('Failed XHR request(invalid url) shall trigger EventSource to close and "error" event to be dispatched', function() { 475 | 476 | var evs, 477 | receivedMessageEvents = [], 478 | receivedOpenEvents = [], 479 | receivedErrorEvents = []; 480 | 481 | beforeEach(function (done) { 482 | 483 | this.eventSource = window[evsImportName]; 484 | 485 | // sending to wrong url 486 | evs = new this.eventSource('http://exampleFailedXHRequest'); 487 | 488 | evs.addEventListener('message', function (e) { 489 | receivedMessageEvents.push(e.data); 490 | }, false); 491 | evs.addEventListener('open', function (e) { 492 | receivedOpenEvents.push(e.type); 493 | }, false); 494 | evs.addEventListener('error', function (e) { 495 | receivedErrorEvents.push(e.type); 496 | done(); 497 | }, false); 498 | }); 499 | 500 | afterEach(function (done) { 501 | 502 | evs.close(); 503 | receivedErrorEvents = []; 504 | done(); 505 | }); 506 | 507 | it("should send error event", function (done) { 508 | 509 | expect(receivedErrorEvents.length).toBe(1); 510 | done(); 511 | }); 512 | }); 513 | 514 | describe('Failed XHR request(missing-code 404) shall trigger EventSource to close and "error" event to be dispatched', function() { 515 | 516 | var evs, 517 | receivedMessageEvents = [], 518 | receivedOpenEvents = [], 519 | receivedErrorEvents = []; 520 | 521 | beforeEach(function (done) { 522 | 523 | this.eventSource = window[evsImportName]; 524 | 525 | // sending to wrong url 526 | evs = new this.eventSource('/missing'); 527 | 528 | evs.addEventListener('message', function (e) { 529 | receivedMessageEvents.push(e.data); 530 | }, false); 531 | evs.addEventListener('open', function (e) { 532 | receivedOpenEvents.push(e.type); 533 | }, false); 534 | evs.addEventListener('error', function (e) { 535 | receivedErrorEvents.push(e.type); 536 | done(); 537 | }, false); 538 | }); 539 | 540 | afterEach(function () { 541 | 542 | evs.close() 543 | }); 544 | 545 | it("should send error event", function (done) { 546 | 547 | expect(receivedErrorEvents.length).toBe(1); 548 | done(); 549 | }); 550 | }); 551 | 552 | describe('Tests with twisted server:', function() { 553 | 554 | 555 | var evs, 556 | receivedMessageEvents = [], 557 | receivedOpenEvents = [], 558 | receivedErrorEvents = [], 559 | receivedTestMetaEvents = [], 560 | receivedTestEndEvents = []; 561 | 562 | function addEventListeners(evs, done) { 563 | 564 | evs.addEventListener('message', function (e) { 565 | // if (e.lastEventId) {console.log(e.lastEventId);} 566 | // console.log('message: ' + e.type + ":" + e.data) 567 | // console.log(e) 568 | if (e.data) {receivedMessageEvents.push(e.data);} 569 | }, false); 570 | evs.addEventListener('open', function (e) { 571 | receivedOpenEvents.push(e.type); 572 | }, false); 573 | evs.addEventListener('error', function (e) { 574 | receivedErrorEvents.push(e.type); 575 | }, false); 576 | evs.addEventListener('testmeta', function (e) { 577 | // console.log("received testmeta:" + e.type + "["+ evs.id +"]: "+ e.data); 578 | // console.log(e) 579 | receivedTestMetaEvents = JSON.parse(e.data); 580 | }, false); 581 | evs.addEventListener('testend', function (e) { 582 | receivedTestEndEvents.push(e.type); 583 | // console.log('received tesend' + e.type + ":" + e.data + "end"); 584 | // console.log(e) 585 | done(); 586 | }, false); 587 | } 588 | 589 | afterEach(function (done) { 590 | 591 | evs.close(); 592 | receivedErrorEvents = []; 593 | receivedMessageEvents = []; 594 | receivedTestEndEvents = []; 595 | receivedTestMetaEvents = []; 596 | receivedOpenEvents = []; 597 | done(); 598 | }); 599 | 600 | describe('4-messages-with-seed-01', function() { 601 | 602 | var twistedUrl = '/test/eventsource/4-messages-with-seed-01'; 603 | 604 | describe('using polyfill eventsource', function () { 605 | 606 | beforeEach(function (done) { 607 | 608 | var eventSource = window[evsImportName]; 609 | 610 | evs = new eventSource(twistedUrl); 611 | addEventListeners(evs, done); 612 | }); 613 | 614 | describe ('after a complete run until testend:', function() { 615 | 616 | it("data in testmeta event should match all incoming messages data", function () { 617 | 618 | expect(receivedTestMetaEvents).toEqual(receivedMessageEvents); 619 | }); 620 | 621 | it("testend event is received", function () { 622 | 623 | expect(receivedTestEndEvents.length).toEqual(1); 624 | }) 625 | }); 626 | }); 627 | 628 | if (isEventSourceSupported) { 629 | 630 | describe('using native eventsource', function () { 631 | 632 | beforeEach(function (done) { 633 | 634 | var eventSource = window[evsName]; 635 | 636 | evs = new eventSource(twistedUrl); 637 | addEventListeners(evs, done); 638 | }); 639 | 640 | describe ('after a complete run until testend:', function() { 641 | 642 | it("data in testmeta event should match all incoming messages data", function () { 643 | 644 | expect(receivedTestMetaEvents).toEqual(receivedMessageEvents); 645 | }); 646 | 647 | it("testend event is received", function () { 648 | 649 | expect(receivedTestEndEvents.length).toEqual(1); 650 | }) 651 | }); 652 | }) 653 | } 654 | }); 655 | 656 | describe('6-messages-with-seed-02', function() { 657 | 658 | var twistedUrl = '/test/eventsource/6-messages-with-seed-02'; 659 | 660 | describe('using polyfill eventsource', function () { 661 | 662 | beforeEach(function (done) { 663 | 664 | var eventSource = window[evsImportName]; 665 | 666 | evs = new eventSource(twistedUrl); 667 | addEventListeners(evs, done); 668 | }); 669 | 670 | describe ('after a complete run until testend:', function() { 671 | 672 | it("data in testmeta event should match all incoming messages data", function () { 673 | 674 | expect(receivedTestMetaEvents).toEqual(receivedMessageEvents); 675 | }); 676 | 677 | it("testend event is received", function () { 678 | 679 | expect(receivedTestEndEvents.length).toEqual(1); 680 | }) 681 | }); 682 | }); 683 | 684 | if (isEventSourceSupported) { 685 | 686 | describe('using native eventsource', function () { 687 | 688 | beforeEach(function (done) { 689 | 690 | var eventSource = window[evsName]; 691 | 692 | evs = new eventSource(twistedUrl); 693 | addEventListeners(evs, done); 694 | }); 695 | 696 | describe ('after a complete run until testend:', function() { 697 | 698 | it("data in testmeta event should match all incoming messages data", function () { 699 | 700 | expect(receivedTestMetaEvents).toEqual(receivedMessageEvents); 701 | }); 702 | 703 | it("testend event is received", function () { 704 | 705 | expect(receivedTestEndEvents.length).toEqual(1); 706 | }) 707 | }); 708 | }) 709 | } 710 | }); 711 | 712 | describe('8-messages-closeat-4-with-seed-03', function() { 713 | 714 | var twistedUrl = '/test/eventsource/8-messages-closeat-4-with-seed-03'; 715 | 716 | describe('using polyfill eventsource', function () { 717 | 718 | beforeEach(function (done) { 719 | 720 | var eventSource = window[evsImportName]; 721 | 722 | evs = new eventSource(twistedUrl); 723 | addEventListeners(evs, done); 724 | }); 725 | 726 | describe ('after a complete run until testend:', function() { 727 | 728 | it("data in testmeta event should match all incoming messages data", function () { 729 | 730 | expect(receivedTestMetaEvents).toEqual(receivedMessageEvents); 731 | }); 732 | 733 | it("testend event is received", function () { 734 | 735 | expect(receivedTestEndEvents.length).toBe(1); 736 | }); 737 | 738 | it("at least 1 error message are received, meaning 1 reconnection", function () { 739 | 740 | expect(receivedErrorEvents.length).toBeGreaterThan(0); // we expect at least 1 741 | }); 742 | }); 743 | }); 744 | 745 | if (isEventSourceSupported) { 746 | 747 | describe('using native eventsource', function () { 748 | 749 | beforeEach(function (done) { 750 | 751 | var eventSource = window[evsName]; 752 | 753 | evs = new eventSource(twistedUrl); 754 | addEventListeners(evs, done); 755 | }); 756 | 757 | describe ('after a complete run until testend:', function() { 758 | 759 | it("data in testmeta event should match all incoming messages data", function () { 760 | 761 | expect(receivedTestMetaEvents).toEqual(receivedMessageEvents); 762 | }); 763 | 764 | it("testend event is received", function () { 765 | 766 | expect(receivedTestEndEvents.length).toBe(1); 767 | }); 768 | 769 | it("at least 1 error messages are received, meaning 1 reconnection", function () { 770 | 771 | expect(receivedErrorEvents.length).toBeGreaterThan(0); 772 | }); 773 | }); 774 | }) 775 | } 776 | }); 777 | 778 | describe('16-messages-closeat-5-with-seed-04', function() { 779 | 780 | var twistedUrl = '/test/eventsource/16-messages-closeat-5-with-seed-04'; 781 | 782 | describe('using polyfill eventsource', function () { 783 | 784 | beforeEach(function (done) { 785 | 786 | var eventSource = window[evsImportName]; 787 | 788 | evs = new eventSource(twistedUrl); 789 | addEventListeners(evs, done); 790 | }); 791 | 792 | describe ('after a complete run until testend:', function() { 793 | 794 | it("data in testmeta event should match all incoming messages data", function () { 795 | 796 | expect(receivedTestMetaEvents).toEqual(receivedMessageEvents); 797 | }); 798 | 799 | it("testend event is received", function () { 800 | 801 | expect(receivedTestEndEvents.length).toBe(1); 802 | }); 803 | 804 | it("3 error messages are received, meaning 3 reconnections", function () { 805 | 806 | expect(receivedErrorEvents.length).toBeGreaterThan(1); // we expect at least 3 807 | }); 808 | }); 809 | }); 810 | 811 | if (isEventSourceSupported) { 812 | 813 | describe('using native eventsource', function () { 814 | 815 | beforeEach(function (done) { 816 | 817 | var eventSource = window[evsName]; 818 | 819 | evs = new eventSource(twistedUrl); 820 | addEventListeners(evs, done); 821 | }); 822 | 823 | describe ('after a complete run until testend:', function() { 824 | 825 | it("data in testmeta event should match all incoming messages data", function () { 826 | 827 | expect(receivedTestMetaEvents).toEqual(receivedMessageEvents); 828 | }); 829 | 830 | it("testend event is received", function () { 831 | 832 | expect(receivedTestEndEvents.length).toBe(1); 833 | }); 834 | 835 | it("3 error messages are received, meaning 3 reconnections", function () { 836 | 837 | expect(receivedErrorEvents.length).toBeGreaterThan(1); 838 | }); 839 | }); 840 | }) 841 | } 842 | }); 843 | }); 844 | 845 | -------------------------------------------------------------------------------- /javascript/src/browserify-eventsource.js: -------------------------------------------------------------------------------- 1 | /* 2 | * CommonJS module that exports EventSource polyfill version {{VERSION}} 3 | * This module is intended for browser side use 4 | * ===================================================================== 5 | * THIS IS A POLYFILL MODULE, SO IT HAS SIDE EFFECTS 6 | * IT AUTOMATICALLY CHECKS IF window OBJECT DEFINES EventSource 7 | * AND ADD THE EXPORTED ONE IN CASE IT IS UNDEFINED 8 | * ===================================================================== 9 | * Supported by sc AmvTek srl 10 | * :email: devel@amvtek.com 11 | */ 12 | 13 | 14 | var PolyfillEventSource = require('./eventsource.js').EventSource; 15 | module.exports = PolyfillEventSource; 16 | 17 | // Add EventSource to window if it is missing... 18 | if (window && !window.EventSource){ 19 | window.EventSource = PolyfillEventSource; 20 | // Don't break IE < 10 21 | if (typeof console !== "undefined" && typeof console.log !== "undefined"){ 22 | console.log("polyfill-eventsource added missing EventSource to window"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /javascript/src/eventsource.js: -------------------------------------------------------------------------------- 1 | /* 2 | * EventSource polyfill version {{VERSION}} 3 | * Supported by sc AmvTek srl 4 | * :email: devel@amvtek.com 5 | */ 6 | ;(function (global) { 7 | 8 | if (global.EventSource && !global._eventSourceImportPrefix){ 9 | return; 10 | } 11 | 12 | var evsImportName = (global._eventSourceImportPrefix||'')+"EventSource"; 13 | 14 | var EventSource = function (url, options) { 15 | 16 | if (!url || typeof url != 'string') { 17 | throw new SyntaxError('Not enough arguments'); 18 | } 19 | 20 | this.URL = url; 21 | this.setOptions(options); 22 | var evs = this; 23 | setTimeout(function(){evs.poll()}, 0); 24 | }; 25 | 26 | EventSource.prototype = { 27 | 28 | CONNECTING: 0, 29 | 30 | OPEN: 1, 31 | 32 | CLOSED: 2, 33 | 34 | defaultOptions: { 35 | 36 | loggingEnabled: false, 37 | 38 | loggingPrefix: "eventsource", 39 | 40 | interval: 500, // milliseconds 41 | 42 | bufferSizeLimit: 256*1024, // bytes 43 | 44 | silentTimeout: 300000, // milliseconds 45 | 46 | getArgs:{ 47 | 'evs_buffer_size_limit': 256*1024 48 | }, 49 | 50 | xhrHeaders:{ 51 | 'Accept': 'text/event-stream', 52 | 'Cache-Control': 'no-cache', 53 | 'X-Requested-With': 'XMLHttpRequest' 54 | } 55 | }, 56 | 57 | setOptions: function(options){ 58 | 59 | var defaults = this.defaultOptions; 60 | var option; 61 | 62 | // set all default options... 63 | for (option in defaults){ 64 | 65 | if ( defaults.hasOwnProperty(option) ){ 66 | this[option] = defaults[option]; 67 | } 68 | } 69 | 70 | // override with what is in options 71 | for (option in options){ 72 | 73 | if (option in defaults && options.hasOwnProperty(option)){ 74 | this[option] = options[option]; 75 | } 76 | } 77 | 78 | // if getArgs option is enabled 79 | // ensure evs_buffer_size_limit corresponds to bufferSizeLimit 80 | if (this.getArgs && this.bufferSizeLimit) { 81 | 82 | this.getArgs['evs_buffer_size_limit'] = this.bufferSizeLimit; 83 | } 84 | 85 | // if console is not available, force loggingEnabled to false 86 | if (typeof console === "undefined" || typeof console.log === "undefined") { 87 | 88 | this.loggingEnabled = false; 89 | } 90 | }, 91 | 92 | log: function(message) { 93 | 94 | if (this.loggingEnabled) { 95 | 96 | console.log("[" + this.loggingPrefix +"]:" + message) 97 | } 98 | }, 99 | 100 | poll: function() { 101 | 102 | try { 103 | 104 | if (this.readyState == this.CLOSED) { 105 | return; 106 | } 107 | 108 | this.cleanup(); 109 | this.readyState = this.CONNECTING; 110 | this.cursor = 0; 111 | this.cache = ''; 112 | this._xhr = new this.XHR(this); 113 | this.resetNoActivityTimer(); 114 | 115 | } 116 | catch (e) { 117 | 118 | // in an attempt to silence the errors 119 | this.log('There were errors inside the pool try-catch'); 120 | this.dispatchEvent('error', { type: 'error', data: e.message }); 121 | } 122 | }, 123 | 124 | pollAgain: function (interval) { 125 | 126 | // schedule poll to be called after interval milliseconds 127 | var evs = this; 128 | evs.readyState = evs.CONNECTING; 129 | evs.dispatchEvent('error', { 130 | type: 'error', 131 | data: "Reconnecting " 132 | }); 133 | this._pollTimer = setTimeout(function(){evs.poll()}, interval||0); 134 | }, 135 | 136 | 137 | cleanup: function() { 138 | 139 | this.log('evs cleaning up') 140 | 141 | if (this._pollTimer){ 142 | clearInterval(this._pollTimer); 143 | this._pollTimer = null; 144 | } 145 | 146 | if (this._noActivityTimer){ 147 | clearInterval(this._noActivityTimer); 148 | this._noActivityTimer = null; 149 | } 150 | 151 | if (this._xhr){ 152 | this._xhr.abort(); 153 | this._xhr = null; 154 | } 155 | }, 156 | 157 | resetNoActivityTimer: function(){ 158 | 159 | if (this.silentTimeout){ 160 | 161 | if (this._noActivityTimer){ 162 | clearInterval(this._noActivityTimer); 163 | } 164 | var evs = this; 165 | this._noActivityTimer = setTimeout( 166 | function(){ evs.log('Timeout! silentTImeout:'+evs.silentTimeout); evs.pollAgain(); }, 167 | this.silentTimeout 168 | ); 169 | } 170 | }, 171 | 172 | close: function () { 173 | 174 | this.readyState = this.CLOSED; 175 | this.log('Closing connection. readyState: '+this.readyState); 176 | this.cleanup(); 177 | }, 178 | 179 | _onxhrdata: function() { 180 | 181 | var request = this._xhr; 182 | 183 | if (request.isReady() && !request.hasError() ) { 184 | // reset the timer, as we have activity 185 | this.resetNoActivityTimer(); 186 | 187 | // move this EventSource to OPEN state... 188 | if (this.readyState == this.CONNECTING) { 189 | this.readyState = this.OPEN; 190 | this.dispatchEvent('open', { type: 'open' }); 191 | } 192 | 193 | var buffer = request.getBuffer(); 194 | 195 | if (buffer.length > this.bufferSizeLimit) { 196 | this.log('buffer.length > this.bufferSizeLimit'); 197 | this.pollAgain(); 198 | } 199 | 200 | if (this.cursor == 0 && buffer.length > 0){ 201 | 202 | // skip byte order mark \uFEFF character if it starts the stream 203 | if (buffer.substring(0,1) == '\uFEFF'){ 204 | this.cursor = 1; 205 | } 206 | } 207 | 208 | var lastMessageIndex = this.lastMessageIndex(buffer); 209 | if (lastMessageIndex[0] >= this.cursor){ 210 | 211 | var newcursor = lastMessageIndex[1]; 212 | var toparse = buffer.substring(this.cursor, newcursor); 213 | this.parseStream(toparse); 214 | this.cursor = newcursor; 215 | } 216 | 217 | // if request is finished, reopen the connection 218 | if (request.isDone()) { 219 | this.log('request.isDone(). reopening the connection'); 220 | this.pollAgain(this.interval); 221 | } 222 | } 223 | else if (this.readyState !== this.CLOSED) { 224 | 225 | this.log('this.readyState !== this.CLOSED'); 226 | this.pollAgain(this.interval); 227 | 228 | //MV: Unsure why an error was previously dispatched 229 | } 230 | }, 231 | 232 | parseStream: function(chunk) { 233 | 234 | // normalize line separators (\r\n,\r,\n) to \n 235 | // remove white spaces that may precede \n 236 | chunk = this.cache + this.normalizeToLF(chunk); 237 | 238 | var events = chunk.split('\n\n'); 239 | 240 | var i, j, eventType, datas, line, retry; 241 | 242 | for (i=0; i < (events.length - 1); i++) { 243 | 244 | eventType = 'message'; 245 | datas = []; 246 | parts = events[i].split('\n'); 247 | 248 | for (j=0; j < parts.length; j++) { 249 | 250 | line = this.trimWhiteSpace(parts[j]); 251 | 252 | if (line.indexOf('event') == 0) { 253 | 254 | eventType = line.replace(/event:?\s*/, ''); 255 | } 256 | else if (line.indexOf('retry') == 0) { 257 | 258 | retry = parseInt(line.replace(/retry:?\s*/, '')); 259 | if(!isNaN(retry)) { 260 | this.interval = retry; 261 | } 262 | } 263 | else if (line.indexOf('data') == 0) { 264 | 265 | datas.push(line.replace(/data:?\s*/, '')); 266 | } 267 | else if (line.indexOf('id:') == 0) { 268 | 269 | this.lastEventId = line.replace(/id:?\s*/, ''); 270 | } 271 | else if (line.indexOf('id') == 0) { // this resets the id 272 | 273 | this.lastEventId = null; 274 | } 275 | } 276 | 277 | if (datas.length) { 278 | // dispatch a new event 279 | var event = new MessageEvent(eventType, datas.join('\n'), window.location.origin, this.lastEventId); 280 | this.dispatchEvent(eventType, event); 281 | } 282 | } 283 | 284 | this.cache = events[events.length - 1]; 285 | }, 286 | 287 | dispatchEvent: function (type, event) { 288 | var handlers = this['_' + type + 'Handlers']; 289 | 290 | if (handlers) { 291 | 292 | for (var i = 0; i < handlers.length; i++) { 293 | handlers[i].call(this, event); 294 | } 295 | } 296 | 297 | if (this['on' + type]) { 298 | this['on' + type].call(this, event); 299 | } 300 | 301 | }, 302 | 303 | addEventListener: function (type, handler) { 304 | if (!this['_' + type + 'Handlers']) { 305 | this['_' + type + 'Handlers'] = []; 306 | } 307 | 308 | this['_' + type + 'Handlers'].push(handler); 309 | }, 310 | 311 | removeEventListener: function (type, handler) { 312 | var handlers = this['_' + type + 'Handlers']; 313 | if (!handlers) { 314 | return; 315 | } 316 | for (var i = handlers.length - 1; i >= 0; --i) { 317 | if (handlers[i] === handler) { 318 | handlers.splice(i, 1); 319 | break; 320 | } 321 | } 322 | }, 323 | 324 | _pollTimer: null, 325 | 326 | _noactivityTimer: null, 327 | 328 | _xhr: null, 329 | 330 | lastEventId: null, 331 | 332 | cache: '', 333 | 334 | cursor: 0, 335 | 336 | onerror: null, 337 | 338 | onmessage: null, 339 | 340 | onopen: null, 341 | 342 | readyState: 0, 343 | 344 | // =================================================================== 345 | // helpers functions 346 | // those are attached to prototype to ease reuse and testing... 347 | 348 | urlWithParams: function (baseURL, params) { 349 | 350 | var encodedArgs = []; 351 | 352 | if (params){ 353 | 354 | var key, urlarg; 355 | var urlize = encodeURIComponent; 356 | 357 | for (key in params){ 358 | if (params.hasOwnProperty(key)) { 359 | urlarg = urlize(key)+'='+urlize(params[key]); 360 | encodedArgs.push(urlarg); 361 | } 362 | } 363 | } 364 | 365 | if (encodedArgs.length > 0){ 366 | 367 | if (baseURL.indexOf('?') == -1) 368 | return baseURL + '?' + encodedArgs.join('&'); 369 | return baseURL + '&' + encodedArgs.join('&'); 370 | } 371 | return baseURL; 372 | }, 373 | 374 | lastMessageIndex: function(text) { 375 | 376 | var ln2 =text.lastIndexOf('\n\n'); 377 | var lr2 = text.lastIndexOf('\r\r'); 378 | var lrln2 = text.lastIndexOf('\r\n\r\n'); 379 | 380 | if (lrln2 > Math.max(ln2, lr2)) { 381 | return [lrln2, lrln2+4]; 382 | } 383 | return [Math.max(ln2, lr2), Math.max(ln2, lr2) + 2] 384 | }, 385 | 386 | trimWhiteSpace: function(str) { 387 | // to remove whitespaces left and right of string 388 | 389 | var reTrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g; 390 | return str.replace(reTrim, ''); 391 | }, 392 | 393 | normalizeToLF: function(str) { 394 | 395 | // replace \r and \r\n with \n 396 | return str.replace(/\r\n|\r/g, '\n'); 397 | } 398 | 399 | }; 400 | 401 | if (!isOldIE()){ 402 | 403 | EventSource.isPolyfill = "XHR"; 404 | 405 | // EventSource will send request using XMLHttpRequest 406 | EventSource.prototype.XHR = function(evs) { 407 | 408 | request = new XMLHttpRequest(); 409 | this._request = request; 410 | evs._xhr = this; 411 | 412 | // set handlers 413 | request.onreadystatechange = function(){ 414 | if (request.readyState > 1 && evs.readyState != evs.CLOSED) { 415 | if (request.status == 200 || (request.status>=300 && request.status<400)){ 416 | evs._onxhrdata(); 417 | } 418 | else { 419 | request._failed = true; 420 | evs.readyState = evs.CLOSED; 421 | evs.dispatchEvent('error', { 422 | type: 'error', 423 | data: "The server responded with "+request.status 424 | }); 425 | evs.close(); 426 | } 427 | } 428 | }; 429 | 430 | request.onprogress = function () { 431 | }; 432 | 433 | request.open('GET', evs.urlWithParams(evs.URL, evs.getArgs), true); 434 | 435 | var headers = evs.xhrHeaders; // maybe null 436 | for (var header in headers) { 437 | if (headers.hasOwnProperty(header)){ 438 | request.setRequestHeader(header, headers[header]); 439 | } 440 | } 441 | if (evs.lastEventId) { 442 | request.setRequestHeader('Last-Event-Id', evs.lastEventId); 443 | } 444 | 445 | request.send(); 446 | }; 447 | 448 | EventSource.prototype.XHR.prototype = { 449 | 450 | useXDomainRequest: false, 451 | 452 | _request: null, 453 | 454 | _failed: false, // true if we have had errors... 455 | 456 | isReady: function() { 457 | 458 | 459 | return this._request.readyState >= 2; 460 | }, 461 | 462 | isDone: function() { 463 | 464 | return (this._request.readyState == 4); 465 | }, 466 | 467 | hasError: function() { 468 | 469 | return (this._failed || (this._request.status >= 400)); 470 | }, 471 | 472 | getBuffer: function() { 473 | 474 | var rv = ''; 475 | try { 476 | rv = this._request.responseText || ''; 477 | } 478 | catch (e){} 479 | return rv; 480 | }, 481 | 482 | abort: function() { 483 | 484 | if ( this._request ) { 485 | this._request.abort(); 486 | } 487 | } 488 | }; 489 | } 490 | else { 491 | 492 | EventSource.isPolyfill = "IE_8-9"; 493 | 494 | // patch EventSource defaultOptions 495 | var defaults = EventSource.prototype.defaultOptions; 496 | defaults.xhrHeaders = null; // no headers will be sent 497 | defaults.getArgs['evs_preamble'] = 2048 + 8; 498 | 499 | // EventSource will send request using Internet Explorer XDomainRequest 500 | EventSource.prototype.XHR = function(evs) { 501 | 502 | request = new XDomainRequest(); 503 | this._request = request; 504 | 505 | // set handlers 506 | request.onprogress = function(){ 507 | request._ready = true; 508 | evs._onxhrdata(); 509 | }; 510 | 511 | request.onload = function(){ 512 | this._loaded = true; 513 | evs._onxhrdata(); 514 | }; 515 | 516 | request.onerror = function(){ 517 | this._failed = true; 518 | evs.readyState = evs.CLOSED; 519 | evs.dispatchEvent('error', { 520 | type: 'error', 521 | data: "XDomainRequest error" 522 | }); 523 | }; 524 | 525 | request.ontimeout = function(){ 526 | this._failed = true; 527 | evs.readyState = evs.CLOSED; 528 | evs.dispatchEvent('error', { 529 | type: 'error', 530 | data: "XDomainRequest timed out" 531 | }); 532 | }; 533 | 534 | // XDomainRequest does not allow setting custom headers 535 | // If EventSource has enabled the use of GET arguments 536 | // we add parameters to URL so that server can adapt the stream... 537 | var reqGetArgs = {}; 538 | if (evs.getArgs) { 539 | 540 | // copy evs.getArgs in reqGetArgs 541 | var defaultArgs = evs.getArgs; 542 | for (var key in defaultArgs) { 543 | if (defaultArgs.hasOwnProperty(key)){ 544 | reqGetArgs[key] = defaultArgs[key]; 545 | } 546 | } 547 | if (evs.lastEventId){ 548 | reqGetArgs['evs_last_event_id'] = evs.lastEventId; 549 | } 550 | } 551 | // send the request 552 | 553 | request.open('GET', evs.urlWithParams(evs.URL,reqGetArgs)); 554 | request.send(); 555 | }; 556 | 557 | EventSource.prototype.XHR.prototype = { 558 | 559 | useXDomainRequest: true, 560 | 561 | _request: null, 562 | 563 | _ready: false, // true when progress events are dispatched 564 | 565 | _loaded: false, // true when request has been loaded 566 | 567 | _failed: false, // true if when request is in error 568 | 569 | isReady: function() { 570 | 571 | return this._request._ready; 572 | }, 573 | 574 | isDone: function() { 575 | 576 | return this._request._loaded; 577 | }, 578 | 579 | hasError: function() { 580 | 581 | return this._request._failed; 582 | }, 583 | 584 | getBuffer: function() { 585 | 586 | var rv = ''; 587 | try { 588 | rv = this._request.responseText || ''; 589 | } 590 | catch (e){} 591 | return rv; 592 | }, 593 | 594 | abort: function() { 595 | 596 | if ( this._request){ 597 | this._request.abort(); 598 | } 599 | } 600 | }; 601 | } 602 | 603 | function MessageEvent(type, data, origin, lastEventId) { 604 | 605 | this.bubbles = false; 606 | this.cancelBubble = false; 607 | this.cancelable = false; 608 | this.data = data || null; 609 | this.origin = origin || ''; 610 | this.lastEventId = lastEventId || ''; 611 | this.type = type || 'message'; 612 | } 613 | 614 | function isOldIE () { 615 | 616 | //return true if we are in IE8 or IE9 617 | return (window.XDomainRequest && (window.XMLHttpRequest && new XMLHttpRequest().responseType === undefined)) ? true : false; 618 | } 619 | 620 | global[evsImportName] = EventSource; 621 | })(this); 622 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "eventsource-polyfill", 3 | "version": "0.9.7", 4 | "description": "A browser polyfill for W3C EventSource (http://www.w3.org/TR/eventsource/)", 5 | "main": "dist/browserify-eventsource.js", 6 | "directories": { "doc": "docs" }, 7 | "files": [ 8 | "dist/eventsource.js", 9 | "dist/browserify-eventsource.js" 10 | ], 11 | "scripts": { 12 | "test": "echo \"Error: to run browser tests, visit http://testevs.amvtek.com/\" && exit 1" 13 | }, 14 | "repository": { 15 | "type": "git", 16 | "url": "https://github.com/amvtek/EventSource.git" 17 | }, 18 | "keywords": [ 19 | "sse", 20 | "server sent events", 21 | "eventsource", 22 | "event-source", 23 | "polyfill" 24 | ], 25 | "author": "amvtek ", 26 | "license": "MIT", 27 | "bugs": { 28 | "url": "https://github.com/amvtek/EventSource/issues" 29 | }, 30 | "homepage": "https://github.com/amvtek/EventSource", 31 | "devDependencies": { 32 | "grunt": "^0.4.5", 33 | "grunt-contrib-uglify": "^0.6.0", 34 | "grunt-string-replace": "^1.0.0" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /test_server/etc/nginx/evs_tests.conf: -------------------------------------------------------------------------------- 1 | upstream event_sources { 2 | 3 | # eventsource web server run from command line 4 | server 127.0.0.1:7676; 5 | } 6 | 7 | server{ 8 | 9 | listen 80; # this is for HTTP 10 | server_name testevs.amvtek.com; 11 | root /usr/local/www/testevs.amvtek.com/EventSource/javascript; 12 | index SpecRunner.html; 13 | 14 | location = /favicon.ico { 15 | 16 | return 404; 17 | } 18 | 19 | location = /robots.txt { 20 | 21 | alias /usr/local/www/robots/deny_all.txt; 22 | } 23 | 24 | location = /test/eventsource/4-messages-with-seed-01{ 25 | 26 | chunked_transfer_encoding off; 27 | proxy_http_version 1.1; 28 | proxy_buffering off; 29 | 30 | proxy_set_header Host $host; 31 | proxy_set_header X-Browser-Addr $remote_addr; 32 | proxy_set_header X-EVS-Test-Num-Message 4; 33 | 34 | 35 | proxy_pass http://event_sources; 36 | access_log /var/log/nginx/test_event_source.log time_upstream_fmt; 37 | } 38 | 39 | location = /test/eventsource/6-messages-with-seed-02{ 40 | 41 | chunked_transfer_encoding off; 42 | proxy_http_version 1.1; 43 | proxy_buffering off; 44 | 45 | proxy_set_header Host $host; 46 | proxy_set_header X-Browser-Addr $remote_addr; 47 | proxy_set_header X-EVS-Test-Num-Message 6; 48 | 49 | 50 | proxy_pass http://event_sources; 51 | access_log /var/log/nginx/test_event_source.log time_upstream_fmt; 52 | } 53 | 54 | location = /test/eventsource/8-messages-closeat-4-with-seed-03{ 55 | 56 | chunked_transfer_encoding off; 57 | proxy_http_version 1.1; 58 | proxy_buffering off; 59 | 60 | proxy_set_header Host $host; 61 | proxy_set_header X-Browser-Addr $remote_addr; 62 | proxy_set_header X-EVS-Test-Num-Message 8; 63 | proxy_set_header X-EVS-Test-CloseAt 4; 64 | 65 | 66 | proxy_pass http://event_sources; 67 | access_log /var/log/nginx/test_event_source.log time_upstream_fmt; 68 | } 69 | 70 | location = /test/eventsource/16-messages-closeat-5-with-seed-04{ 71 | 72 | chunked_transfer_encoding off; 73 | proxy_http_version 1.1; 74 | proxy_buffering off; 75 | 76 | proxy_set_header Host $host; 77 | proxy_set_header X-Browser-Addr $remote_addr; 78 | proxy_set_header X-EVS-Test-Num-Message 16; 79 | proxy_set_header X-EVS-Test-CloseAt 5; 80 | 81 | 82 | proxy_pass http://event_sources; 83 | access_log /var/log/nginx/test_event_source.log time_upstream_fmt; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /test_server/etc/supervisor/evs_test_server.conf: -------------------------------------------------------------------------------- 1 | [program:test_eventsource] 2 | command=/usr/local/www/testevs.amvtek.com/bin/twistd 3 | -n --pidfile= 4 | test_eventsource 5 | --host=127.0.0.1 6 | --port=7676 7 | user=eventsource 8 | directory=/usr/local/www/testevs.amvtek.com/EventSource/test_server 9 | process_name=%(program_name)s 10 | num_procs=1 11 | -------------------------------------------------------------------------------- /test_server/evsutils/__init__.py: -------------------------------------------------------------------------------- 1 | # from protocol import * 2 | # from utils import * -------------------------------------------------------------------------------- /test_server/evsutils/log.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | shared.log 4 | ~~~~~~~~~~ 5 | 6 | AmvTek attend to take control of twisted logging 7 | 8 | :copyright: (c) 2012 by sc AmvTek srl 9 | :email: devel@amvtek.com 10 | """ 11 | 12 | import sys 13 | 14 | from logging import DEBUG,INFO,WARNING,ERROR,FATAL 15 | 16 | from zope.interface import implements 17 | from twisted.python import context, log as _log 18 | 19 | 20 | ILogContext = _log.ILogContext 21 | _FileLogObserver = _log.FileLogObserver # local alias 22 | 23 | 24 | class LeveledOnlyFileLogObserver(_FileLogObserver): 25 | """ 26 | FileLogObserver that filters out non 'leveled' log events... 27 | This is our attend to eliminate unwanted twisted log messages... 28 | """ 29 | 30 | def emit(self,eventDict): 31 | """skip logging if eventDict does not contain 'level' key...""" 32 | 33 | if eventDict.get('isError') or eventDict.has_key('level'): 34 | return _FileLogObserver.emit(self, eventDict) 35 | 36 | 37 | def setLeveledLogging(): 38 | """ 39 | monkey patch twisted.python.log.FileLogObserver so that 'unleveled' log 40 | events are ignored... 41 | """ 42 | _log.FileLogObserver = LeveledOnlyFileLogObserver 43 | 44 | 45 | def buildContextAwareLogPrefix(prefix): 46 | """ 47 | return logPrefix callable that : 48 | appends context retrieved 'system' to set prefix 49 | """ 50 | 51 | def logPrefix(): 52 | "logPrefix that adjust to current context" 53 | 54 | logCtx = context.get('system',"-") 55 | if logCtx is not "-": 56 | return "%s,%s"%(logCtx,prefix) 57 | return prefix 58 | 59 | return logPrefix 60 | 61 | 62 | class LogPublisher(object): 63 | 64 | minLevel = DEBUG 65 | 66 | defaultLevel = INFO 67 | 68 | def _msg(self,*args,**kwargs): 69 | "wraps twisted.log.msg..." 70 | 71 | _log.msg(*args,**kwargs) 72 | 73 | def _err(self,_stuff=None,_why=None,**kwargs): 74 | "wraps twisted.log.err..." 75 | 76 | _log.err(_stuff,_why,**kwargs) 77 | 78 | def debug(self,*args,**kwargs): 79 | "bypass twisted log.msg in case DEBUG below minLevel..." 80 | 81 | if DEBUG >= self.minLevel: 82 | kwargs['level'] = DEBUG 83 | self._msg(*args,**kwargs) 84 | 85 | def msg(self,*args,**kwargs): 86 | "bypass twisted log.msg in case level below minLevel..." 87 | 88 | level = kwargs.setdefault('level',self.defaultLevel) 89 | if level >= self.minLevel: 90 | self._msg(*args,**kwargs) 91 | 92 | log = msg 93 | 94 | def err(self,_stuff=None,_why=None,**kwargs): 95 | """ 96 | bypass twisted log.err in case level below minLevel 97 | uses ERROR as default for level 98 | """ 99 | level = kwargs.setdefault('level',ERROR) 100 | if level >= self.minLevel: 101 | self._err(_stuff,_why,**kwargs) 102 | 103 | def getLogger(self,logPrefix): 104 | "return Logger instance" 105 | 106 | logger = Logger() 107 | logger.minLevel = self.minLevel 108 | logger.defaultLevel = self.defaultLevel 109 | if callable(logPrefix): 110 | logger.logPrefix = logPrefix 111 | else: 112 | logger.logPrefix = lambda :logPrefix 113 | return logger 114 | 115 | 116 | class Logger(LogPublisher): 117 | "a Logger which inline 'level aware' debug, msg, err log methods" 118 | 119 | def logPrefix(self): 120 | return "?" 121 | 122 | def _msg(self,*args,**kwargs): 123 | "add 'system' into log 'event dict'..." 124 | 125 | kwargs['system'] = self.logPrefix() 126 | _log.msg(*args,**kwargs) 127 | 128 | def _err(self,_stuff=None,_why=None,**kwargs): 129 | "add 'system' into log 'event dict'..." 130 | 131 | kwargs['system'] = self.logPrefix() 132 | _log.err(_stuff,_why,**kwargs) 133 | 134 | 135 | def setLevel(minLevel,defaultLevel): 136 | "set minimum and default levels for log publishing" 137 | 138 | minLevel = int(minLevel) 139 | defaultLevel = int(defaultLevel) 140 | 141 | # Initializes global publisher 142 | thePublisher.minLevel = minLevel 143 | thePublisher.defaultLevel = defaultLevel 144 | 145 | # Initializes Logger class, this simplify inlining Logger 146 | Logger.minLevel = minLevel 147 | Logger.defaultLevel = defaultLevel 148 | 149 | # Install global LogPublisher 150 | thePublisher = LogPublisher() 151 | debug = thePublisher.debug 152 | msg = thePublisher.msg 153 | err = thePublisher.err 154 | getLogger = thePublisher.getLogger 155 | 156 | # Add globals to ease replacing twisted.python.log with this module 157 | callWithContext = _log.callWithContext 158 | callWithLogger = _log.callWithLogger 159 | 160 | startConsoleLogging = lambda :_log.startLogging(sys.stdout) 161 | -------------------------------------------------------------------------------- /test_server/evsutils/protocol.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import random as RND 3 | 4 | try: 5 | from cStringIO import StringIO 6 | except ImportError: 7 | from StringIO import StringIO 8 | 9 | from zope.interface import implements 10 | from twisted.protocols import basic, policies 11 | from twisted.internet import reactor, protocol, interfaces 12 | from twisted.internet.task import deferLater, cooperate 13 | 14 | import log as customLog 15 | 16 | from utils import SimpleHTTPRequest, encode_http_response, TestSource, split_by 17 | 18 | 19 | class EventSourceRequest(SimpleHTTPRequest): 20 | 21 | ALLOWED_METHODS = frozenset(["GET"]) 22 | 23 | def parse(self, httpMsg): 24 | 25 | super(EventSourceRequest, self).parse(httpMsg) 26 | 27 | if self._error is not None: 28 | return 29 | 30 | self.evsArgs = {} 31 | 32 | # continue parsing to read test parameters 33 | try: 34 | 35 | errReason = "Bad Request" 36 | 37 | # local aliases 38 | path = self.path 39 | reqArgs = self.args 40 | reqHeaders = self.headers 41 | 42 | # read seed 43 | errReason = "Invalid seed" 44 | self.evsArgs['seed'] = hash(path.rsplit('/',1)[-1]) 45 | 46 | # read message sequence length 47 | errReason = "Can not parse sequence length" 48 | seqlength = reqArgs.get('evs_num_messages', None) or \ 49 | reqHeaders.get('X-EVS-Test-Num-Message'.lower(), None) or None 50 | self.evsArgs['length'] = int(seqlength) 51 | 52 | # read closeAt 53 | errReason = "Can not parse closeAt" 54 | closeAt = reqArgs.get('evs_close_at', None) or\ 55 | reqHeaders.get('X-EVS-Test-CloseAt'.lower(), None) 56 | self.evsArgs['closeAt'] = int(closeAt) if closeAt else None 57 | 58 | # read sendPreamble 59 | self.evsArgs['sendPreamble'] = bool(reqArgs.get('evs_preamble')) 60 | 61 | # read Last-Event-Id 62 | errReason = "Invalid Last-Event-Id" 63 | lastEventId = reqArgs.get('evs_last_event_id', None) or\ 64 | reqHeaders.get('Last-Event-Id'.lower(), None) or -1 65 | self.evsLastId = int(lastEventId) 66 | 67 | except ValueError: 68 | 69 | self.set_error(400, errReason) 70 | 71 | except: 72 | 73 | self.set_error(500, "Server side error") 74 | 75 | 76 | class SimpleHTTPServerProtocol(basic.LineReceiver, policies.TimeoutMixin): 77 | 78 | START_EVENT_STREAM = \ 79 | "HTTP/1.1 200 OK\r\n"\ 80 | "Content-Type: text/event-stream\r\n"\ 81 | "Access-Control-Allow-Origin: *\r\n"\ 82 | "Cache-Control: no-cache\r\n"\ 83 | "Transfert-Encoding: identity\r\n"\ 84 | "Connection: close\r\n\r\n" 85 | 86 | MAX_LENGTH_ERROR = encode_http_response(413, 'Request Entity Too Large') 87 | 88 | MAX_REQUEST_TRANSMIT_TIME_ERROR = encode_http_response(408, 'Request Timeout') 89 | 90 | delimiter = "\r\n\r\n" 91 | 92 | request = None 93 | 94 | def __init__(self, maxLength, timeout): 95 | 96 | self.MAX_LENGTH = maxLength 97 | self.MAX_REQUEST_TRANSMIT_TIME = timeout 98 | 99 | def lineLengthExceeded(self, line): 100 | 101 | self.log.msg("request too large, disconnecting") 102 | self.sendError(self.MAX_LENGTH_ERROR) 103 | 104 | def connectionMade(self): 105 | 106 | self.setTimeout(self.MAX_REQUEST_TRANSMIT_TIME) 107 | 108 | self.log = customLog.getLogger(self.transport.logstr) 109 | self.log.msg('connectionMade') 110 | 111 | def timeoutConnection(self): 112 | 113 | self.log.msg("request transmission takes too long, timing out") 114 | self.sendError(self.MAX_REQUEST_TRANSMIT_TIME_ERROR) 115 | 116 | def connectionLost(self, reason=None): 117 | 118 | self.log.msg('Connection closed because %s' % reason) 119 | if hasattr(self, 'producer'): 120 | self.producer.stopProducing() 121 | 122 | def lineReceived(self, line): 123 | """parse incoming http request, and start streaming...""" 124 | 125 | self.log.msg("received HTTP request, attending to parse it") 126 | self.resetTimeout() 127 | 128 | self.request = EventSourceRequest(line) 129 | 130 | if self.request._error is not None: 131 | 132 | self.log.msg("Got HTTP error %(status)s" % self.request._error) 133 | self.sendError(self.request.error) 134 | 135 | else: 136 | 137 | # send response headers 138 | self.startResponse() 139 | 140 | # register EventSource producer 141 | self.producer = CooperativePushProducer(self.buildEventStream()) 142 | self.transport.registerProducer(self.producer, True) 143 | d = self.producer.whenDone() 144 | d.addCallback(lambda _: self.transport.loseConnection()) 145 | 146 | def sendError(self, error): 147 | """send error response and close connection""" 148 | 149 | self.transport.write(error) 150 | self.transport.loseConnection() 151 | 152 | def startResponse(self): 153 | """send response that starts EventSource stream...""" 154 | 155 | self.transport.write(self.START_EVENT_STREAM) 156 | 157 | def buildEventStream(self): 158 | 159 | lastEvtId = self.request.evsLastId 160 | 161 | evtSource = TestSource(messages=self.factory.messages, **self.request.evsArgs) 162 | evtSequence = evtSource.visit_from(lastEvtId+1) 163 | 164 | if lastEvtId > -1: 165 | 166 | self.log.msg("restart streaming from : %d" % lastEvtId) 167 | 168 | else: 169 | 170 | self.log.msg("new eventsource stream...") 171 | 172 | restart = lambda: None 173 | 174 | for message in evtSequence: 175 | 176 | # extract start of message... 177 | msgstart = message[:message.find(":", 0, 8)+12] 178 | self.log.msg("new event line : %s..." % msgstart) 179 | 180 | for part in split_by(message, RND.randint(1, 3)): 181 | self.transport.write(part) 182 | yield deferLater(reactor, RND.uniform(0.05, 0.3), restart) 183 | 184 | 185 | class CooperativePushProducer(object): 186 | 187 | implements(interfaces.IPushProducer) 188 | 189 | def __init__(self, iterator): 190 | 191 | self.task = cooperate(iterator) 192 | 193 | def getTaskState(self): 194 | 195 | return self.task._completionState 196 | 197 | def whenDone(self): 198 | 199 | return self.task.whenDone() 200 | 201 | def pauseProducing(self): 202 | 203 | self.task.pause() 204 | 205 | def resumeProducing(self): 206 | 207 | self.task.resume() 208 | 209 | def stopProducing(self): 210 | 211 | if self.task._completionState is None: 212 | 213 | self.task.stop() 214 | 215 | 216 | class SimpleHTTPServerProtocolFactory(protocol.Factory): 217 | 218 | def __init__(self): 219 | 220 | self.MAX_LENGTH = 100000 221 | self.MAX_REQUEST_TRANSMIT_TIME = 20000 # seconds 222 | self.messages = None 223 | 224 | def buildProtocol(self, addr): 225 | 226 | proto = SimpleHTTPServerProtocol(self.MAX_LENGTH, self.MAX_REQUEST_TRANSMIT_TIME) 227 | proto.factory = self 228 | return proto 229 | 230 | if __name__ == "__main__": 231 | 232 | import doctest 233 | doctest.testmod() 234 | -------------------------------------------------------------------------------- /test_server/evsutils/utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from urlparse import urlparse, parse_qsl 4 | from rfc822 import Message as MimeMessage 5 | import random as RND 6 | import json 7 | 8 | try: 9 | from cStringIO import StringIO 10 | except ImportError: 11 | from StringIO import StringIO 12 | 13 | import log as customLog 14 | 15 | 16 | def encode_http_response( 17 | status, reason, version="HTTP/1.1", 18 | headers=None, entity=None, **kwargs): 19 | """return http message encoding response""" 20 | 21 | buf = [] 22 | 23 | # 'dictify' headers 24 | headers = dict(headers or []) 25 | 26 | # add status line 27 | buf.append("%s %i %s\r\n" % (version, status, reason)) 28 | 29 | # add entity description in headers 30 | if entity: 31 | headers["Content-Length"] = len(entity) 32 | headers.setdefault("Content-Type", "text/plain") 33 | 34 | # render headers 35 | for name, value in headers.items(): 36 | buf.append("%s: %s\r\n" % (name.title(), value)) 37 | 38 | # add empty line 39 | buf.append("\r\n") 40 | 41 | if entity: 42 | buf.append(entity) 43 | 44 | return "".join(buf) 45 | 46 | 47 | class SimpleHTTPRequest(object): 48 | """Simple HTTPRequest object to help parsing HTTP message""" 49 | 50 | ALLOWED_METHODS = frozenset([ 51 | "OPTIONS", "GET", "HEAD", "POST", 52 | "PUT", "DELETE", "TRACE", "CONNECT"]) 53 | 54 | method = None 55 | path = None 56 | headers = {} 57 | version = None 58 | args = None 59 | 60 | _error = None 61 | 62 | def __init__(self, httpMsg): 63 | """ 64 | >>> reqText = "GET /path/to/my/eventsource?arg1=1&arg2=2 HTTP/1.1\\r\\nheader: 3\\r\\n\\r\\n" 65 | >>> req = SimpleHTTPRequest(reqText) 66 | >>> req.path, req.args, req.method, req.version, req.headers 67 | ('/path/to/my/eventsource', {'arg1': '1', 'arg2': '2'}, 'GET', (1, 1), {'header': '3'}) 68 | """ 69 | 70 | self.log = customLog.getLogger('Processing HTTP request') 71 | try: 72 | self.parse(httpMsg) 73 | except: 74 | self.set_error(400, "Bad Request") 75 | 76 | def parse(self, httpMsg): 77 | """parse and validate http request out of httpMsg""" 78 | 79 | f = StringIO(httpMsg) 80 | 81 | # parse request line 82 | reqline = f.readline() 83 | parts = reqline.split() 84 | 85 | if len(parts) == 3: 86 | 87 | method, path, version = parts 88 | 89 | elif len(parts) == 2: 90 | 91 | method, path = parts 92 | version = "HTTP/0.9" 93 | 94 | else: 95 | 96 | return self.set_error(400, "Invalid Request line") 97 | 98 | # validates method 99 | method = method.strip().upper() 100 | if method not in self.ALLOWED_METHODS: 101 | hdrs = {"Allow": ", ".join(self.ALLOWED_METHODS)} 102 | return self.set_error(405, "Method Not Allowed", hdrs) 103 | self.method = method 104 | 105 | # validates path 106 | self.path = urlparse(path).path 107 | self.args = dict(parse_qsl(urlparse(path).query)) 108 | 109 | # validates version 110 | version = version.strip().upper() 111 | if not version.startswith("HTTP/"): 112 | 113 | return self.set_error(400, "Invalid HTTP version") 114 | majmin = version[5:].split(".") 115 | try: 116 | major, minor = [int(v) for v in majmin] 117 | except: 118 | 119 | return self.set_error(400, "Invalid HTTP version") 120 | self.version = (major, minor) 121 | 122 | # parse headers 123 | self.headers = dict(MimeMessage(f)) 124 | self.log.msg('\nFound headers: {}'.format(self.headers)) 125 | 126 | def set_error(self, status, reason, headers=None, entity=None): 127 | """helper method allowing to define 'shortcut' response""" 128 | 129 | status = int(status) 130 | self._error = locals() 131 | 132 | def get_error(self): 133 | """return string encoding error response if any""" 134 | 135 | if self._error: 136 | return encode_http_response(**self._error) 137 | error = property(get_error) 138 | 139 | def has_error(self): 140 | """return True if request is not valid""" 141 | 142 | return bool(self._error) 143 | 144 | 145 | class TestSource(object): 146 | 147 | lineSep = ['\n', '\r', '\r\n'] 148 | 149 | messages = [u'one line. one', 150 | u'two lines. one\ntwo lines. two', 151 | u'three lines. one\nthree lines. two\nthree lines. three', 152 | u'four lines. one\nfour. two\nfour lines. three\nfour lines. four', 153 | u'spam, ham and eggs', 154 | u"spam, șuncă și ouă", 155 | u'spam\nham\neggs', 156 | u'Nobody expects the spanish inquisition', 157 | u"Personne ne s'attend à l'Inquisition espagnole", 158 | u'always look on the bright side of bugs', 159 | u"toujours regarder le côté lumineux de bugs"] 160 | 161 | def __init__(self, seed, length, closeAt=None, 162 | sendPreamble=False, messages=None): 163 | """ 164 | test if we can recreate the exact scenario with the same seed 165 | >>> source1 = TestSource(2014, 2) 166 | >>> source2 = TestSource(2014, 2) 167 | >>> source1.sequence == source2.sequence 168 | True 169 | """ 170 | 171 | RND.seed(seed) 172 | self.sendPreamble = sendPreamble 173 | self.length = int(length) 174 | self.closeAt = closeAt 175 | self.messages = [unicode(mess) for mess in messages or self.messages] 176 | self.chosenLnSep = RND.choice(self.lineSep) 177 | 178 | # self.chosenEvtSep = RND.choice(self.lineSep).rjust(RND.randint(2, 10)) 179 | self.chosenEvtSep = self.chosenLnSep # RND.choice(self.lineSep) 180 | self.sequence = ["Message %02i%s" % 181 | (n, RND.choice(self.messages)) 182 | for n in xrange(self.length)] 183 | self.encoder = EventSourceEncoder(self.chosenLnSep, self.chosenEvtSep) 184 | 185 | def visit_from(self, fromId=0): 186 | """ 187 | generator function, let us iterate sequence from identifier 188 | 189 | helper lambda to simulate event encoding 190 | >>> ev = lambda mylist, sep: ["%s%s" % (el, sep) for el in mylist] 191 | 192 | start from fromId=0 to closeAt=1 193 | >>> source = TestSource(2014, 10, 1) # closeAt is 1 194 | >>> source.sequence = [1, 2, 3] 195 | 196 | >>> actual = list(source.visit_from()) 197 | >>> sep = source.chosenLnSep + source.chosenEvtSep 198 | >>> expected = ev(['event: testmeta\\ndata: [1, 2, 3]', 'data: 1\\nid: 1'], sep) 199 | >>> actual == expected 200 | True 201 | 202 | start from fromId=7 to closeAt=4 203 | >>> source = TestSource(2014, 10, 4) # closeAt is 4 204 | >>> source.sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 205 | 206 | >>> actual = list(source.visit_from(7)) 207 | >>> sep = source.chosenLnSep + source.chosenEvtSep 208 | >>> expected = ev(['data: 7\\nid: 7', 'data: 8\\nid: 8'], sep) 209 | >>> actual == expected 210 | True 211 | 212 | start from fromId=7 to closeAt=10 213 | >>> source = TestSource(2014, 10) # to the end 214 | >>> source.sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 215 | 216 | >>> actual = list(source.visit_from(7)) 217 | >>> sep = source.chosenLnSep + source.chosenEvtSep 218 | >>> expected = ev(['data: 7\\nid: 7', 'data: 8\\nid: 8', 'data: 9\\nid: 9', 'data: 10\\nid: 10', 'event: testend\\ndata: This is the end'], sep) 219 | >>> actual == expected 220 | True 221 | 222 | start from fromId=5 to closeAt=4 223 | >>> source = TestSource(2014, 8, 4) # to the end 224 | >>> source.sequence = [1, 2, 3, 4, 5, 6, 7, 8] 225 | 226 | >>> actual = list(source.visit_from(5)) 227 | >>> sep = source.chosenLnSep + source.chosenEvtSep 228 | >>> expected = ev(['data: 5\\nid: 5', 'data: 6\\nid: 6', 'data: 7\\nid: 7', 'data: 8\\nid: 8', 'event: testend\\ndata: This is the end'], sep) 229 | >>> actual == expected 230 | True 231 | 232 | tart from fromId=5 to closeAt=4 233 | >>> source = TestSource(2014, 16, 4) # to the end 234 | >>> source.sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] 235 | 236 | >>> actual = list(source.visit_from(5)) 237 | >>> sep = source.chosenLnSep + source.chosenEvtSep 238 | >>> expected = ev(['data: 5\\nid: 5', 'data: 6\\nid: 6', 'data: 7\\nid: 7', 'data: 8\\nid: 8'], sep) 239 | >>> actual == expected 240 | True 241 | """ 242 | 243 | fromId = int(fromId) 244 | encoder = self.encoder 245 | sequence = self.sequence 246 | closeAt = self.closeAt 247 | encode = encoder.encode_event 248 | sendPreamble = self.sendPreamble 249 | 250 | events = [encode(message, None, index+1) for index, message in enumerate(sequence)] 251 | events.insert(0, encode(json.dumps(sequence), 'testmeta', 0)) 252 | events.append(encode("This is the end", 'testend')) 253 | 254 | if sendPreamble: 255 | yield encoder.encode_preamble() 256 | 257 | seqEnd = fromId - fromId % closeAt + closeAt + 1 if closeAt else len(events)+1 258 | seqEnd = seqEnd if seqEnd < len(events)-1 else len(events) 259 | 260 | for event in events[fromId:seqEnd]: 261 | yield event 262 | 263 | 264 | class EventSourceEncoder(object): 265 | 266 | preamble = "mypreamble" 267 | 268 | def __init__(self, linesep='\n', eventsep='\n'): 269 | self.linesep = linesep 270 | self.eventsep = eventsep 271 | 272 | def encode_preamble(self, size=2056): 273 | """ 274 | return preamble comment aiming at resetting IE 8 9 XDomainRequest 275 | 276 | >>> EventSourceEncoder().encode_preamble(15) 277 | ':mypreamble \\n' 278 | """ 279 | 280 | return (u"%s%s" % ((":%s" % self.preamble).ljust(size), self.linesep)).encode('utf-8') 281 | 282 | def encode_comment(self, comment): 283 | """ 284 | return comment line 285 | 286 | >>> EventSourceEncoder().encode_comment('spam, ham and eggs') 287 | u': spam, ham and eggs\\n' 288 | """ 289 | 290 | return u": %s%s" % (comment, self.linesep) 291 | 292 | def encode_mark(self, evtId): 293 | """ 294 | return line encoding event id 295 | 296 | >>> EventSourceEncoder().encode_mark(2014) 297 | u'id: 2014\\n' 298 | """ 299 | 300 | return u"id: %s%s" % (evtId, self.linesep) 301 | 302 | def encode_name(self, evtName): 303 | """ 304 | return line encoding event name 305 | 306 | >>> EventSourceEncoder().encode_name('myevent') 307 | u'event: myevent\\n' 308 | """ 309 | return u'event: %s%s' % (evtName, self.linesep) 310 | 311 | def encode_data(self, datas): 312 | ur""" 313 | return lines encoding event data 314 | 315 | >>> datas = 'first data\nsecond data\nthird data' 316 | >>> EventSourceEncoder().encode_data(datas) 317 | u'data: first data\ndata: second data\ndata: third data\n' 318 | 319 | >>> datas = u"toujours regarder le côté lumineux de bugs" 320 | >>> EventSourceEncoder().encode_data(datas) 321 | u'data: toujours regarder le c\xf4t\xe9 lumineux de bugs\n' 322 | """ 323 | 324 | return "data: %s%s" % (("%sdata: " % self.linesep).join(unicode(datas).splitlines()), self.linesep) 325 | 326 | def encode_event(self, datas, evtName=None, evtId=None): 327 | """ 328 | return block encoding event 329 | 330 | >>> datas = 'first data\\nsecond data' 331 | >>> EventSourceEncoder().encode_event(datas, 'myevent', 2014) 332 | 'event: myevent\\ndata: first data\\ndata: second data\\nid: 2014\\n\\n' 333 | 334 | >>> datas = 'only one line of data' 335 | >>> EventSourceEncoder().encode_event(datas) 336 | 'data: only one line of data\\n\\n' 337 | """ 338 | 339 | return (u"%s%s%s%s" % ( 340 | self.encode_name(evtName) if evtName else '', 341 | self.encode_data(datas), 342 | self.encode_mark(evtId) if evtId else '', 343 | self.eventsep 344 | )).encode('utf-8') 345 | 346 | 347 | def split_by(msg, n): 348 | """ 349 | return msg divided in nchunk if msg size allow so... 350 | 351 | >>> split_by('123456789', 3) 352 | ['123', '456', '789'] 353 | 354 | >>> split_by('123456789', 2) 355 | ['1234', '56789'] 356 | 357 | >>> split_by('12345', 2) 358 | ['12', '345'] 359 | 360 | >>> len(split_by('123456789', 4)) 361 | 4 362 | 363 | Generate all randomly(msg, msg length and pieces) 364 | and check if the final length matches 365 | >>> import random,string 366 | >>> pieces = random.randint(1, 20) 367 | >>> len(split_by(''.join(random.choice(string.ascii_uppercase) for i in range(random.randint(1, 100))), pieces)) == pieces 368 | True 369 | """ 370 | 371 | return [(msg[len(msg)*i//n:len(msg)*(i+1)//n]) for i in range(n)] 372 | 373 | 374 | if __name__ == "__main__": 375 | 376 | import doctest 377 | doctest.testmod() 378 | -------------------------------------------------------------------------------- /test_server/requirements.txt: -------------------------------------------------------------------------------- 1 | Twisted==19.7.0 2 | argparse==1.2.1 3 | distribute==0.6.24 4 | wsgiref==0.1.2 5 | zope.interface==4.1.1 6 | -------------------------------------------------------------------------------- /test_server/twisted/plugins/test_eventsource.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from zope.interface import implements 4 | 5 | from twisted.application.service import IServiceMaker 6 | from twisted.application import internet 7 | from twisted.plugin import IPlugin 8 | from twisted.python import usage 9 | 10 | from evsutils.protocol import SimpleHTTPServerProtocolFactory 11 | 12 | 13 | class Options(usage.Options): 14 | 15 | optParameters = [ 16 | ['host', 'h', '0.0.0.0', "host"], 17 | ['port', 'p', 7676, "port"] 18 | ] 19 | 20 | 21 | class TestEventsourceServiceMaker(object): 22 | 23 | implements(IServiceMaker, IPlugin) 24 | tapname = "test_eventsource" 25 | description = "test eventsource" 26 | options = Options 27 | 28 | def makeService(self, options): 29 | 30 | return internet.TCPServer(int(options["port"]), SimpleHTTPServerProtocolFactory()) 31 | 32 | serviceMaker = TestEventsourceServiceMaker() --------------------------------------------------------------------------------