├── .gitignore
├── README.md
├── demo
├── css
│ └── vendor
│ │ └── bootstrap.min.css
└── js
│ ├── app.js
│ └── vendor
│ └── angular.min.js
├── docs
├── docs.md
└── get-started.md
├── index.html
├── package.json
├── test
├── SpecRunner.html
├── lib
│ └── jasmine-2.1.3
│ │ ├── boot.js
│ │ ├── console.js
│ │ ├── jasmine-html.js
│ │ ├── jasmine.css
│ │ ├── jasmine.js
│ │ └── jasmine_favicon.png
└── spec
│ ├── LocalStorageHelpersSpec.js
│ ├── LocalStorageSpec.js
│ ├── WebORMHelpersSpec.js
│ ├── WebORMRelationshipSpec.js
│ ├── WebORMSelfRelationshipSpec.js
│ └── WebORMSpec.js
└── weborm.js
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | /node_modules
3 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # WebORM
2 |
3 | ORM-like localStorage.
4 |
5 | Useful for prototyping your application and simulating your API responses.
6 |
7 | ## Docs
8 |
9 | [Get started](/docs/get-started.md) or read [the docs](/docs/docs.md).
10 |
11 | ## Demo App
12 |
13 | See [the code](/demo/js/app.js) or try the [live application](http://rafaeleyng.github.io/weborm/).
14 |
15 | ## License
16 |
17 | MIT
18 |
--------------------------------------------------------------------------------
/demo/js/app.js:
--------------------------------------------------------------------------------
1 | // WebORM
2 | var weborm = (function() {
3 | var schema = {
4 | // common to all entities:
5 | _Base: {
6 | attrs: ['name']
7 | },
8 | // entities:
9 | Country: {
10 | attrs: ['abbr']
11 | },
12 | State: {
13 | attrs: ['abbr'],
14 | relsToOne: ['Country']
15 | },
16 | City: {
17 | relsToOne: ['State']
18 | }
19 | };
20 | var config = {
21 | pluralization: {
22 | Country: 'Countries',
23 | City: 'Cities'
24 | }
25 | };
26 | return new WebORM(schema, config);
27 | })();
28 |
29 | var helpers = {
30 | cleanStorage: function() {
31 | weborm.storage.clean();
32 | console.log(localStorage.length);
33 | },
34 |
35 | insertData: function() {
36 | var br = weborm.save('Country', {name: 'Brazil', abbr: 'BR'});
37 | var rs = weborm.save('State', {name: 'Rio Grande do Sul', abbr: 'RS', _countryId: br.id});
38 | var sc = weborm.save('State', {name: 'Santa Catarina', abbr: 'SC', _countryId: br.id});
39 | var feliz = weborm.save('City', {name: 'Feliz', _stateId: rs.id});
40 | var poa = weborm.save('City', {name: 'Porto Alegre', _stateId: rs.id});
41 | var floripa = weborm.save('City', {name: 'Florianópolis', _stateId: sc.id});
42 | var garopaba = weborm.save('City', {name: 'Garopaba', _stateId: sc.id});
43 |
44 | var us = weborm.save('Country', {name: 'United States', abbr: 'US'});
45 | var ny = weborm.save('State', {name: 'New York', abbr: 'NY', _countryId: us.id});
46 | var ca = weborm.save('State', {name: 'California', abbr: 'CA', _countryId: us.id});
47 | var nyc = weborm.save('City', {name: 'New York', _stateId: ny.id});
48 | var la = weborm.save('City', {name: 'Los Angeles', _stateId: ca.id});
49 | var sf = weborm.save('City', {name: 'San Francisco', _stateId: ca.id});
50 | },
51 | reset: function() {
52 | helpers.cleanStorage();
53 | window.location.reload();
54 | }
55 | };
56 |
57 | if (localStorage.length === 0) {
58 | helpers.insertData();
59 | }
60 |
61 | // AngularJS
62 | var app = angular.module('weborm-demo', []);
63 |
64 | app.service('dataService', function() {
65 | this.getCountries = function() {
66 | // mocked call to your API or whatever
67 | return weborm.all('Country');
68 | };
69 | });
70 |
71 | app.controller('mainCtrl', ['$scope', 'dataService', function($scope, dataService) {
72 |
73 | $scope.nameAndAbbr = function(obj) {
74 | return ':0 (:1)'
75 | .replace(':0', obj.name)
76 | .replace(':1', obj.abbr)
77 | ;
78 | };
79 |
80 | $scope.selectCountry = function(index) {
81 | $scope.selectedCountry = $scope.countries[index];
82 | $scope.selectFirstState();
83 | };
84 |
85 | $scope.selectState = function(index) {
86 | if ($scope.selectedCountry) {
87 | $scope.selectedState = $scope.selectedCountry.States[index];
88 | } else {
89 | $scope.selectedState = undefined;
90 | }
91 | $scope.selectFirstCity();
92 | };
93 |
94 | $scope.selectCity = function(index) {
95 | if ($scope.selectedState) {
96 | $scope.selectedCity = $scope.selectedState.Cities[index];
97 | } else {
98 | $scope.selectedCity = undefined;
99 | }
100 | };
101 |
102 | $scope.selectFirstCountry = function() {
103 | $scope.selectCountry(0);
104 | };
105 |
106 | $scope.selectFirstState = function() {
107 | $scope.selectState(0);
108 | };
109 |
110 | $scope.selectFirstCity = function() {
111 | $scope.selectCity(0);
112 | };
113 |
114 | $scope.selectLastCountry = function() {
115 | $scope.selectCountry($scope.countries.length-1);
116 | };
117 |
118 | $scope.selectLastState = function() {
119 | $scope.selectState($scope.selectedCountry.States.length-1);
120 | };
121 |
122 | $scope.selectLastCity = function() {
123 | $scope.selectCity($scope.selectedState.Cities.length-1);
124 | };
125 |
126 | $scope.changeCountry = function() {
127 | $scope.selectedState = $scope.selectedCountry.States[0];
128 | $scope.changeState();
129 | };
130 |
131 | $scope.changeState = function() {
132 | $scope.selectedCity = $scope.selectedState.Cities[0];
133 | };
134 |
135 | $scope.saveCountry = function() {
136 | $scope.selectedCountry && $scope.selectedCountry.save();
137 | };
138 |
139 | $scope.saveState = function() {
140 | $scope.selectedState && $scope.selectedState.save();
141 | };
142 |
143 | $scope.saveCity = function() {
144 | $scope.selectedCity && $scope.selectedCity.save();
145 | };
146 |
147 | $scope.newCountry = function() {
148 | weborm.save('Country', {name: 'New country ' + weborm.count('Country'), abbr: 'Abbr'});
149 | $scope.loadCountries();
150 | $scope.selectLastCountry();
151 | $scope.newState();
152 | };
153 |
154 | $scope.newState = function() {
155 | weborm.save('State', {name: 'New state ' + weborm.count('State'), abbr: 'Abbr', _countryId: $scope.selectedCountry.id});
156 | $scope.selectLastState();
157 | $scope.newCity();
158 | };
159 |
160 | $scope.newCity = function() {
161 | weborm.save('City', {name: 'New city ' + weborm.count('City'), _stateId: $scope.selectedState.id});
162 | $scope.selectLastCity();
163 | };
164 |
165 | $scope.deleteCountry = function() {
166 | if ($scope.selectedCountry) {
167 | $scope.selectedCountry.delete();
168 | // remove the country from the local array. this is done by weborm in the inverse relationship arrays
169 | $scope.countries.splice($scope.countries.indexOf($scope.selectedCountry), 1);
170 | $scope.selectFirstCountry();
171 | }
172 | };
173 |
174 | $scope.deleteState = function() {
175 | if ($scope.selectedState) {
176 | $scope.selectedState.delete();
177 | $scope.selectFirstState();
178 | }
179 | };
180 |
181 | $scope.deleteCity = function() {
182 | if ($scope.selectedCity) {
183 | $scope.selectedCity.delete();
184 | $scope.selectFirstCity();
185 | }
186 | };
187 |
188 | $scope.loadCountries = function() {
189 | $scope.countries = dataService.getCountries();
190 | }
191 |
192 | var init = function() {
193 | $scope.loadCountries();
194 | $scope.selectFirstCountry();
195 | };
196 |
197 | init();
198 |
199 | }]);
200 |
--------------------------------------------------------------------------------
/docs/docs.md:
--------------------------------------------------------------------------------
1 | # WebORM Docs
2 |
3 | ## WebORM constructor reference
4 |
5 | ### `WebORM(schema, config)`
6 | WebORM constructor.
7 | * `schema`: { }.
8 | * Keys are entity names and values are SchemaEntity objects.
9 | * `config`: { }.
10 | * Valid keys and values:
11 | * `pluralization`: object where keys are entity names and values are how you want them pluralized, if they don't follow the pattern of just adding an 's' at the end of the word.
12 |
13 | **Returns:** The WebORM object.
14 |
15 | ### `WebORM.SchemaEntity(attrs, relsToOne, relsToMany)`
16 | SchemaEntity objects constructor.
17 | * `attrs`: [ String ]. Attributes names for a given entity.
18 | * `relsToOne`: [ String ]. Names of other SchemaEntity to which this entity will have a 'to one' relationship'.
19 | * `relsToMany`: [ String ]. Names of other SchemaEntity to which this entity will have a 'to many' relationship'.
20 |
21 | **Returns:** SchemaEntity object.
22 |
23 |
24 | ## WebORM reference
25 |
26 | ### `weborm.save(entity, data)`
27 | Inserts a record, or update (replace) a record if `data` contains an id of a existing record.
28 | * `entity`: String. Entity name.
29 | * `data`: {} or WebORMEntity object. Data to be stored. Only attributes that match the schema for that entity will be persisted.
30 |
31 | **Returns:** WebORMEntity object.
32 |
33 | ### `weborm.find(entity, id)`
34 | Retrieves a single record by its entity and id.
35 | * `entity`: String. Entity name.
36 | * `id`: Number. Record id.
37 |
38 | **Returns:** WebORMEntity object or `undefined`.
39 |
40 | ### `weborm.all(entity)`
41 | Retrieves all records of an entity.
42 | * `entity`: String. Entity name.
43 |
44 | **Returns:** [ WebORMEntity ].
45 |
46 | ### `weborm.count(entity)`
47 | Counts the number of records of an entity.
48 | * `entity`: String. Entity name.
49 |
50 | **Returns:** Number.
51 |
52 | ### `weborm.first(entity)`
53 | Retrieves the first record of an entity, ordered by id.
54 | * `entity`: String. Entity name.
55 |
56 | **Returns:** WebORMEntity object or `undefined`.
57 |
58 | ### `weborm.last(entity)`
59 | Retrieves the last record of an entity, ordered by id.
60 | * `entity`: String. Entity name.
61 |
62 | **Returns:** WebORMEntity object or `undefined`.
63 |
64 | ### `weborm.page(entity, pageNumber, pageSize)`
65 | Retrieves a page of records of an entity, ordered by id.
66 | * `entity`: String. Entity name.
67 | * `pageNumber`: Number. The number of the desired page.
68 | * `pageSize`: Number. The desired size for the page.
69 |
70 | **Returns:** [ WebORMEntity ].
71 |
72 | ### `weborm.filter(entity, filters)`
73 | Retrieves all records of an entity that match the filter function.
74 | * `entity`: String. Entity name.
75 | * `filters`: Function. Function to filter the records.
76 |
77 | **Returns:** [ WebORMEntity ].
78 |
79 | ### `weborm.delete(entity, id)`
80 | Deletes a single record by its entity and id.
81 | * `entity`: String. Entity name.
82 | * `id`: Number. Record id.
83 |
84 | ### `weborm.addTo(addThis, toObj)`
85 | Adds an object as a `to many` relationship of another object.
86 | * `addThis`: WebORMEntity object. Object to be added as a `to many` relationship.
87 | * `toObj`: WebORMEntity object. Object that will receive `addThis` as a `to many` relationship.
88 |
89 | ### `weborm.removeFrom(removeThis, fromObj)`
90 | Removes an object as a `to many` relationship of another object.
91 | * `removeThis`: WebORMEntity object. Object to be removed as a `to many` relationship.
92 | * `fromObj`: WebORMEntity object. Object that will lose `removeThis` as a `to many` relationship.
93 |
94 | ### `weborm.relatedTo(related, toObj)`
95 | Indicates whether an object is related to another as a `to many` relationship.
96 | * `related`: WebORMEntity object. Object you want to know whether is related to `toObj`.
97 | * `toObj`: WebORMEntity object. Object you want to know whether `related` is related to.
98 |
99 | **Returns:** Boolean.
100 |
101 | ### `weborm.same(obj1, obj2)`
102 | Indicates whether `obj1` and `obj2` refer to the same record of the same entity.
103 | * `obj1`: WebORMEntity object.
104 | * `obj2`: WebORMEntity object.
105 |
106 | **Returns:** Boolean.
107 |
108 | ### `weborm.equals(obj1, obj2)`
109 | Indicates whether `obj1` and `obj2` have the same values for all of its attributes, *not considering* the `id` attribute.
110 | * `obj1`: WebORMEntity object.
111 | * `obj2`: WebORMEntity object.
112 |
113 | **Returns:** Boolean.
114 |
115 |
116 | ## WebORMEntity objects reference
117 |
118 | ### `webormEntity.save()`
119 | Saves an object to the storage. Equivalent to `weborm.save(entity, webormEntity)`. Only makes sense for updates, because requires an already existing WebORMEntity object, which is returned by `weborm.save(...)` or by one of `weborm` retrieval methods.
120 |
121 | ### `webormEntity.delete()`
122 | Deletes an object from the storage. Equivalent to `weborm.delete(entity, webormEntity.id)`. Only makes sense for an already existing WebORMEntity object, which is returned by `weborm.save(...)` or by one of `weborm` retrieval methods.
123 |
--------------------------------------------------------------------------------
/docs/get-started.md:
--------------------------------------------------------------------------------
1 | # Get Started With WebORM
2 |
3 | ## Schema
4 |
5 | You must define a schema in order to work with WebORM. There are 2 ways to define your schema: using a plain JavaScript objects or using the `WebORM.SchemaEntity` constructor.
6 |
7 | Using plain JavaScript objects:
8 |
9 | ```
10 | var schema = {
11 | _Base: {
12 | attrs: ['name'],
13 | },
14 |
15 | Game: {},
16 |
17 | Player: {
18 | attrs: ['score'],
19 | relsToOne: ['Game'],
20 | relsToMany: ['Badge']
21 | },
22 |
23 | Badge: {
24 | attrs: ['description']
25 | }
26 | };
27 | ```
28 |
29 | Using the `WebORM.SchemaEntity` constructor:
30 |
31 |
32 | ```
33 | var schema = {
34 | _Base: new WebORM.SchemaEntity(['name']),
35 | Game: new WebORM.SchemaEntity(),
36 | Player: new WebORM.SchemaEntity(['score'], ['Game'], ['Badge']),
37 | Badge: new WebORM.SchemaEntity(['description'])
38 | };
39 | ```
40 |
41 | The order of the parameters is
42 | ```
43 | WebORM.SchemaEntity(attrs, relsToOne, relsToMany);
44 | ```
45 |
46 |
47 | ## Inheritance
48 |
49 | Every WebORMEntity object inherits attributes from an entity called `_DefaultBase`. Currently, the only inherited attribute is the `id`, which works pretty much as an id in a relational database.
50 |
51 | Additionaly, you can specify a custom base entity, which *must* be called `_Base`. Every WebORMEntity object will inherit the attributes defined in your `_Base`.
52 |
53 | Note that defining a `_Base` won't have any impact on the `_DefaultBase`. So **you don't have to define the `id` attribute** yourself.
54 |
55 |
56 | ## Config
57 |
58 | You can, optionally, pass a configuration object. Currently, there are only one possible configuration:
59 |
60 | * `pluralization`: WebORM pluralizes entity names by just adding an 's' at the end of the word. If you want to have a correct pluralization for your entity names, you should pass everything that doesn't follow this pattern.
61 |
62 | ```
63 | var config = {
64 | pluralization: {
65 | Country: 'Countries',
66 | City: 'Cities'
67 | }
68 | };
69 | ```
70 |
71 |
72 | ## Initializing WebORM
73 |
74 | ```
75 | var weborm = new WebORM(schema, config);
76 | ```
77 |
78 |
79 | ## CRUD
80 |
81 | ### Create
82 |
83 | ```
84 | var rafael = weborm.save('Person', {name: 'Rafael', profession: 'Dev'});`
85 | var id = rafael.id; // generated id
86 | ```
87 |
88 | ### Read
89 |
90 | ```
91 | var rafael = weborm.find('Person', id);
92 | ```
93 |
94 | ### Update
95 |
96 | ```
97 | rafael.name = 'Rafael Eyng';
98 |
99 | rafael.save();
100 | // or
101 | weborm.save('Person', rafael);
102 | ```
103 |
104 | ### Delete
105 |
106 | ```
107 | rafael.delete();
108 | // or
109 | weborm.delete('Person', id);
110 | ```
111 |
112 | ## Other operations
113 |
114 | ### all, count, first, last, page
115 |
116 | ```
117 | var people = weborm.all('Person');
118 | var count = weborm.count('Person');
119 |
120 | var first = weborm.first('Person');
121 | var last = weborm.last('Person');
122 |
123 | var page1 = weborm.page('Person', 0, 10); // page number, page size
124 | ```
125 |
126 | ### filter
127 |
128 | Allows you to perform more complex queries
129 |
130 | ```
131 | var rafaelDev = weborm.filter('Person', function(record) {
132 | return record.name === 'Rafael' && record.profession.toLowerCase() === 'dev';
133 | });
134 | ```
135 |
136 |
137 | ## Relationships
138 |
139 | ### Relationships 'to one'
140 |
141 | You can set a relationship when creating a new object:
142 |
143 | ```
144 | var brazil = weborm.save('Country', {name: 'Brazil'});
145 | var rs = weborm.save('State',
146 | {
147 | name: 'Rio Grande do Sul',
148 | _countryId: brazil.id
149 | }
150 | );
151 |
152 | rs.Country.name; // 'Brazil'
153 | rs.countryId; // 1
154 | ```
155 |
156 | Or later:
157 |
158 | ```
159 | var brazil = weborm.save('Country', {name: 'Brazil'});
160 | var rs = weborm.save('State', {name: 'Rio Grande do Sul'});
161 |
162 | rs.Country = brazil;
163 | // or
164 | rs.countryId = brazil.id;
165 |
166 | rs.save();
167 | ```
168 |
169 | WebORM will handle the inverse relationship:
170 |
171 | ```
172 | var rs = weborm.save('State', {name: 'Rio Grande do Sul'});
173 |
174 | var portoAlegre = weborm.save('City', {name: 'Porto Alegre', _stateId: rs.id});
175 | var feliz = weborm.save('City', {name: 'Feliz', _stateId: rs.id});
176 |
177 | rs.Cities; // [portoAlegre, feliz]
178 | ```
179 |
180 | ### Relationships 'to many'
181 |
182 | You can `add` objects `To`, and `remove` objects `From` a 'to many' relationship
183 |
184 | ```
185 | var bronze = weborm.save('Badge', {name: 'Bronze'});
186 | var silver = weborm.save('Badge', {name: 'Silver'});
187 | var gold = weborm.save('Badge', {name: 'Gold'});
188 |
189 | var player = weborm.save('Player', {
190 | name: 'Bob',
191 | _badgesId: [bronze.id, silver.id]
192 | });
193 |
194 | weborm.addTo(gold, player);
195 |
196 | player.Badges.length; // 3
197 | player.Badges[2].name; // 'Gold'
198 |
199 | weborm.removeFrom(silver, player);
200 |
201 | player.Badges.length; // 2
202 | player.Badges[1].name; // 'Gold'
203 |
204 | ```
205 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | WebORM Demo
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
22 |
23 |
24 |
25 |
26 | GitHub
27 |
28 |
29 | npm
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
WebORM Demo
42 |
Edit, save and reload the page. Everything is stored in your browser!
43 |
This is a sample of how you can use WebORM to work with ORM-like localStorage, to prototype your application while your API is not ready. Check
44 | the docs or
45 | get started .
46 |
47 |
48 |
49 |
50 |
51 |
52 | Countries
53 |
57 |
58 |
59 |
60 |
61 | States
62 |
66 |
67 |
68 |
69 |
70 | Cities
71 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
94 |
Save
95 |
New
96 |
Delete
97 |
98 |
99 |
100 |
112 |
Save
113 |
New
114 |
Delete
115 |
116 |
117 |
118 |
125 |
Save
126 |
New
127 |
Delete
128 |
129 |
130 |
131 |
132 |
133 |
134 | Reset all
135 |
136 |
137 |
138 |
139 |
140 |
The schema used in this sample app is defined by the code:
141 |
142 | var schema = {
143 | _Base: {
144 | attrs: ['name']
145 | },
146 | Country: {
147 | attrs: ['abbr']
148 | },
149 | State: {
150 | attrs: ['abbr'],
151 | relsToOne: ['Country']
152 | },
153 | City: {
154 | relsToOne: ['State']
155 | }
156 | };
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "weborm",
3 | "version": "0.1.0",
4 | "description": "ORM-like localStorage",
5 | "main": "weborm.js",
6 | "directories": {
7 | "test": "test"
8 | },
9 | "dependencies": {
10 | "aws-sdk": "2.1.6"
11 | },
12 | "scripts": {
13 | "test": "mocha test/index.js"
14 | },
15 | "repository": {
16 | "type": "git",
17 | "url": "git+https://github.com/rafaeleyng/weborm.git"
18 | },
19 | "keywords": [
20 | "localStorage",
21 | "orm"
22 | ],
23 | "author": "Rafael Eyng (https://github.com/rafaeleyng)",
24 | "license": "MIT",
25 | "bugs": {
26 | "url": "https://github.com/rafaeleyng/weborm/issues"
27 | },
28 | "homepage": "https://github.com/rafaeleyng/weborm#readme"
29 | }
30 |
--------------------------------------------------------------------------------
/test/SpecRunner.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Jasmine Spec Runner v2.1.3
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/test/lib/jasmine-2.1.3/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` and `jasmine_html.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 = jasmineRequire.interface(jasmine, env);
36 |
37 | /**
38 | * 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`.
39 | */
40 | if (typeof window == "undefined" && typeof exports == "object") {
41 | extend(exports, jasmineInterface);
42 | } else {
43 | extend(window, jasmineInterface);
44 | }
45 |
46 | /**
47 | * ## Runner Parameters
48 | *
49 | * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface.
50 | */
51 |
52 | var queryString = new jasmine.QueryString({
53 | getWindowLocation: function() { return window.location; }
54 | });
55 |
56 | var catchingExceptions = queryString.getParam("catch");
57 | env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions);
58 |
59 | /**
60 | * ## Reporters
61 | * 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).
62 | */
63 | var htmlReporter = new jasmine.HtmlReporter({
64 | env: env,
65 | onRaiseExceptionsClick: function() { queryString.setParam("catch", !env.catchingExceptions()); },
66 | getContainer: function() { return document.body; },
67 | createElement: function() { return document.createElement.apply(document, arguments); },
68 | createTextNode: function() { return document.createTextNode.apply(document, arguments); },
69 | timer: new jasmine.Timer()
70 | });
71 |
72 | /**
73 | * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript.
74 | */
75 | env.addReporter(jasmineInterface.jsApiReporter);
76 | env.addReporter(htmlReporter);
77 |
78 | /**
79 | * Filter which specs will be run by matching the start of the full name against the `spec` query param.
80 | */
81 | var specFilter = new jasmine.HtmlSpecFilter({
82 | filterString: function() { return queryString.getParam("spec"); }
83 | });
84 |
85 | env.specFilter = function(spec) {
86 | return specFilter.matches(spec.getFullName());
87 | };
88 |
89 | /**
90 | * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack.
91 | */
92 | window.setTimeout = window.setTimeout;
93 | window.setInterval = window.setInterval;
94 | window.clearTimeout = window.clearTimeout;
95 | window.clearInterval = window.clearInterval;
96 |
97 | /**
98 | * ## Execution
99 | *
100 | * 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.
101 | */
102 | var currentWindowOnload = window.onload;
103 |
104 | window.onload = function() {
105 | if (currentWindowOnload) {
106 | currentWindowOnload();
107 | }
108 | htmlReporter.initialize();
109 | env.execute();
110 | };
111 |
112 | /**
113 | * Helper function for readability above.
114 | */
115 | function extend(destination, source) {
116 | for (var property in source) destination[property] = source[property];
117 | return destination;
118 | }
119 |
120 | }());
121 |
--------------------------------------------------------------------------------
/test/lib/jasmine-2.1.3/console.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2008-2014 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 | failedSuites = [];
59 |
60 | print('ConsoleReporter is deprecated and will be removed in a future version.');
61 |
62 | this.jasmineStarted = function() {
63 | specCount = 0;
64 | failureCount = 0;
65 | pendingCount = 0;
66 | print('Started');
67 | printNewline();
68 | timer.start();
69 | };
70 |
71 | this.jasmineDone = function() {
72 | printNewline();
73 | for (var i = 0; i < failedSpecs.length; i++) {
74 | specFailureDetails(failedSpecs[i]);
75 | }
76 |
77 | if(specCount > 0) {
78 | printNewline();
79 |
80 | var specCounts = specCount + ' ' + plural('spec', specCount) + ', ' +
81 | failureCount + ' ' + plural('failure', failureCount);
82 |
83 | if (pendingCount) {
84 | specCounts += ', ' + pendingCount + ' pending ' + plural('spec', pendingCount);
85 | }
86 |
87 | print(specCounts);
88 | } else {
89 | print('No specs found');
90 | }
91 |
92 | printNewline();
93 | var seconds = timer.elapsed() / 1000;
94 | print('Finished in ' + seconds + ' ' + plural('second', seconds));
95 | printNewline();
96 |
97 | for(i = 0; i < failedSuites.length; i++) {
98 | suiteFailureDetails(failedSuites[i]);
99 | }
100 |
101 | onComplete(failureCount === 0);
102 | };
103 |
104 | this.specDone = function(result) {
105 | specCount++;
106 |
107 | if (result.status == 'pending') {
108 | pendingCount++;
109 | print(colored('yellow', '*'));
110 | return;
111 | }
112 |
113 | if (result.status == 'passed') {
114 | print(colored('green', '.'));
115 | return;
116 | }
117 |
118 | if (result.status == 'failed') {
119 | failureCount++;
120 | failedSpecs.push(result);
121 | print(colored('red', 'F'));
122 | }
123 | };
124 |
125 | this.suiteDone = function(result) {
126 | if (result.failedExpectations && result.failedExpectations.length > 0) {
127 | failureCount++;
128 | failedSuites.push(result);
129 | }
130 | };
131 |
132 | return this;
133 |
134 | function printNewline() {
135 | print('\n');
136 | }
137 |
138 | function colored(color, str) {
139 | return showColors ? (ansi[color] + str + ansi.none) : str;
140 | }
141 |
142 | function plural(str, count) {
143 | return count == 1 ? str : str + 's';
144 | }
145 |
146 | function repeat(thing, times) {
147 | var arr = [];
148 | for (var i = 0; i < times; i++) {
149 | arr.push(thing);
150 | }
151 | return arr;
152 | }
153 |
154 | function indent(str, spaces) {
155 | var lines = (str || '').split('\n');
156 | var newArr = [];
157 | for (var i = 0; i < lines.length; i++) {
158 | newArr.push(repeat(' ', spaces).join('') + lines[i]);
159 | }
160 | return newArr.join('\n');
161 | }
162 |
163 | function specFailureDetails(result) {
164 | printNewline();
165 | print(result.fullName);
166 |
167 | for (var i = 0; i < result.failedExpectations.length; i++) {
168 | var failedExpectation = result.failedExpectations[i];
169 | printNewline();
170 | print(indent(failedExpectation.message, 2));
171 | print(indent(failedExpectation.stack, 2));
172 | }
173 |
174 | printNewline();
175 | }
176 |
177 | function suiteFailureDetails(result) {
178 | for (var i = 0; i < result.failedExpectations.length; i++) {
179 | printNewline();
180 | print(colored('red', 'An error was thrown in an afterAll'));
181 | printNewline();
182 | print(colored('red', 'AfterAll ' + result.failedExpectations[i].message));
183 |
184 | }
185 | printNewline();
186 | }
187 | }
188 |
189 | return ConsoleReporter;
190 | };
191 |
--------------------------------------------------------------------------------
/test/lib/jasmine-2.1.3/jasmine-html.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2008-2014 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 | failedSuites = [];
51 |
52 | this.initialize = function() {
53 | clearPrior();
54 | htmlReporterMain = createDom('div', {className: 'jasmine_html-reporter'},
55 | createDom('div', {className: 'banner'},
56 | createDom('a', {className: 'title', href: 'http://jasmine.github.io/', target: '_blank'}),
57 | createDom('span', {className: 'version'}, j$.version)
58 | ),
59 | createDom('ul', {className: 'symbol-summary'}),
60 | createDom('div', {className: 'alert'}),
61 | createDom('div', {className: 'results'},
62 | createDom('div', {className: 'failures'})
63 | )
64 | );
65 | getContainer().appendChild(htmlReporterMain);
66 |
67 | symbols = find('.symbol-summary');
68 | };
69 |
70 | var totalSpecsDefined;
71 | this.jasmineStarted = function(options) {
72 | totalSpecsDefined = options.totalSpecsDefined || 0;
73 | timer.start();
74 | };
75 |
76 | var summary = createDom('div', {className: 'summary'});
77 |
78 | var topResults = new j$.ResultsNode({}, '', null),
79 | currentParent = topResults;
80 |
81 | this.suiteStarted = function(result) {
82 | currentParent.addChild(result, 'suite');
83 | currentParent = currentParent.last();
84 | };
85 |
86 | this.suiteDone = function(result) {
87 | if (result.status == 'failed') {
88 | failedSuites.push(result);
89 | }
90 |
91 | if (currentParent == topResults) {
92 | return;
93 | }
94 |
95 | currentParent = currentParent.parent;
96 | };
97 |
98 | this.specStarted = function(result) {
99 | currentParent.addChild(result, 'spec');
100 | };
101 |
102 | var failures = [];
103 | this.specDone = function(result) {
104 | if(noExpectations(result) && typeof console !== 'undefined' && typeof console.error !== 'undefined') {
105 | console.error('Spec \'' + result.fullName + '\' has no expectations.');
106 | }
107 |
108 | if (result.status != 'disabled') {
109 | specsExecuted++;
110 | }
111 |
112 | symbols.appendChild(createDom('li', {
113 | className: noExpectations(result) ? 'empty' : result.status,
114 | id: 'spec_' + result.id,
115 | title: result.fullName
116 | }
117 | ));
118 |
119 | if (result.status == 'failed') {
120 | failureCount++;
121 |
122 | var failure =
123 | createDom('div', {className: 'spec-detail failed'},
124 | createDom('div', {className: 'description'},
125 | createDom('a', {title: result.fullName, href: specHref(result)}, result.fullName)
126 | ),
127 | createDom('div', {className: 'messages'})
128 | );
129 | var messages = failure.childNodes[1];
130 |
131 | for (var i = 0; i < result.failedExpectations.length; i++) {
132 | var expectation = result.failedExpectations[i];
133 | messages.appendChild(createDom('div', {className: 'result-message'}, expectation.message));
134 | messages.appendChild(createDom('div', {className: 'stack-trace'}, expectation.stack));
135 | }
136 |
137 | failures.push(failure);
138 | }
139 |
140 | if (result.status == 'pending') {
141 | pendingSpecCount++;
142 | }
143 | };
144 |
145 | this.jasmineDone = function() {
146 | var banner = find('.banner');
147 | banner.appendChild(createDom('span', {className: 'duration'}, 'finished in ' + timer.elapsed() / 1000 + 's'));
148 |
149 | var alert = find('.alert');
150 |
151 | alert.appendChild(createDom('span', { className: 'exceptions' },
152 | createDom('label', { className: 'label', 'for': 'raise-exceptions' }, 'raise exceptions'),
153 | createDom('input', {
154 | className: 'raise',
155 | id: 'raise-exceptions',
156 | type: 'checkbox'
157 | })
158 | ));
159 | var checkbox = find('#raise-exceptions');
160 |
161 | checkbox.checked = !env.catchingExceptions();
162 | checkbox.onclick = onRaiseExceptionsClick;
163 |
164 | if (specsExecuted < totalSpecsDefined) {
165 | var skippedMessage = 'Ran ' + specsExecuted + ' of ' + totalSpecsDefined + ' specs - run all';
166 | alert.appendChild(
167 | createDom('span', {className: 'bar skipped'},
168 | createDom('a', {href: '?', title: 'Run all specs'}, skippedMessage)
169 | )
170 | );
171 | }
172 | var statusBarMessage = '';
173 | var statusBarClassName = 'bar ';
174 |
175 | if (totalSpecsDefined > 0) {
176 | statusBarMessage += pluralize('spec', specsExecuted) + ', ' + pluralize('failure', failureCount);
177 | if (pendingSpecCount) { statusBarMessage += ', ' + pluralize('pending spec', pendingSpecCount); }
178 | statusBarClassName += (failureCount > 0) ? 'failed' : 'passed';
179 | } else {
180 | statusBarClassName += 'skipped';
181 | statusBarMessage += 'No specs found';
182 | }
183 |
184 | alert.appendChild(createDom('span', {className: statusBarClassName}, statusBarMessage));
185 |
186 | for(i = 0; i < failedSuites.length; i++) {
187 | var failedSuite = failedSuites[i];
188 | for(var j = 0; j < failedSuite.failedExpectations.length; j++) {
189 | var errorBarMessage = 'AfterAll ' + failedSuite.failedExpectations[j].message;
190 | var errorBarClassName = 'bar errored';
191 | alert.appendChild(createDom('span', {className: errorBarClassName}, errorBarMessage));
192 | }
193 | }
194 |
195 | var results = find('.results');
196 | results.appendChild(summary);
197 |
198 | summaryList(topResults, summary);
199 |
200 | function summaryList(resultsTree, domParent) {
201 | var specListNode;
202 | for (var i = 0; i < resultsTree.children.length; i++) {
203 | var resultNode = resultsTree.children[i];
204 | if (resultNode.type == 'suite') {
205 | var suiteListNode = createDom('ul', {className: 'suite', id: 'suite-' + resultNode.result.id},
206 | createDom('li', {className: 'suite-detail'},
207 | createDom('a', {href: specHref(resultNode.result)}, resultNode.result.description)
208 | )
209 | );
210 |
211 | summaryList(resultNode, suiteListNode);
212 | domParent.appendChild(suiteListNode);
213 | }
214 | if (resultNode.type == 'spec') {
215 | if (domParent.getAttribute('class') != 'specs') {
216 | specListNode = createDom('ul', {className: 'specs'});
217 | domParent.appendChild(specListNode);
218 | }
219 | var specDescription = resultNode.result.description;
220 | if(noExpectations(resultNode.result)) {
221 | specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription;
222 | }
223 | specListNode.appendChild(
224 | createDom('li', {
225 | className: resultNode.result.status,
226 | id: 'spec-' + resultNode.result.id
227 | },
228 | createDom('a', {href: specHref(resultNode.result)}, specDescription)
229 | )
230 | );
231 | }
232 | }
233 | }
234 |
235 | if (failures.length) {
236 | alert.appendChild(
237 | createDom('span', {className: 'menu bar spec-list'},
238 | createDom('span', {}, 'Spec List | '),
239 | createDom('a', {className: 'failures-menu', href: '#'}, 'Failures')));
240 | alert.appendChild(
241 | createDom('span', {className: 'menu bar failure-list'},
242 | createDom('a', {className: 'spec-list-menu', href: '#'}, 'Spec List'),
243 | createDom('span', {}, ' | Failures ')));
244 |
245 | find('.failures-menu').onclick = function() {
246 | setMenuModeTo('failure-list');
247 | };
248 | find('.spec-list-menu').onclick = function() {
249 | setMenuModeTo('spec-list');
250 | };
251 |
252 | setMenuModeTo('failure-list');
253 |
254 | var failureNode = find('.failures');
255 | for (var i = 0; i < failures.length; i++) {
256 | failureNode.appendChild(failures[i]);
257 | }
258 | }
259 | };
260 |
261 | return this;
262 |
263 | function find(selector) {
264 | return getContainer().querySelector('.jasmine_html-reporter ' + selector);
265 | }
266 |
267 | function clearPrior() {
268 | // return the reporter
269 | var oldReporter = find('');
270 |
271 | if(oldReporter) {
272 | getContainer().removeChild(oldReporter);
273 | }
274 | }
275 |
276 | function createDom(type, attrs, childrenVarArgs) {
277 | var el = createElement(type);
278 |
279 | for (var i = 2; i < arguments.length; i++) {
280 | var child = arguments[i];
281 |
282 | if (typeof child === 'string') {
283 | el.appendChild(createTextNode(child));
284 | } else {
285 | if (child) {
286 | el.appendChild(child);
287 | }
288 | }
289 | }
290 |
291 | for (var attr in attrs) {
292 | if (attr == 'className') {
293 | el[attr] = attrs[attr];
294 | } else {
295 | el.setAttribute(attr, attrs[attr]);
296 | }
297 | }
298 |
299 | return el;
300 | }
301 |
302 | function pluralize(singular, count) {
303 | var word = (count == 1 ? singular : singular + 's');
304 |
305 | return '' + count + ' ' + word;
306 | }
307 |
308 | function specHref(result) {
309 | return '?spec=' + encodeURIComponent(result.fullName);
310 | }
311 |
312 | function setMenuModeTo(mode) {
313 | htmlReporterMain.setAttribute('class', 'jasmine_html-reporter ' + mode);
314 | }
315 |
316 | function noExpectations(result) {
317 | return (result.failedExpectations.length + result.passedExpectations.length) === 0 &&
318 | result.status === 'passed';
319 | }
320 | }
321 |
322 | return HtmlReporter;
323 | };
324 |
325 | jasmineRequire.HtmlSpecFilter = function() {
326 | function HtmlSpecFilter(options) {
327 | var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
328 | var filterPattern = new RegExp(filterString);
329 |
330 | this.matches = function(specName) {
331 | return filterPattern.test(specName);
332 | };
333 | }
334 |
335 | return HtmlSpecFilter;
336 | };
337 |
338 | jasmineRequire.ResultsNode = function() {
339 | function ResultsNode(result, type, parent) {
340 | this.result = result;
341 | this.type = type;
342 | this.parent = parent;
343 |
344 | this.children = [];
345 |
346 | this.addChild = function(result, type) {
347 | this.children.push(new ResultsNode(result, type, this));
348 | };
349 |
350 | this.last = function() {
351 | return this.children[this.children.length - 1];
352 | };
353 | }
354 |
355 | return ResultsNode;
356 | };
357 |
358 | jasmineRequire.QueryString = function() {
359 | function QueryString(options) {
360 |
361 | this.setParam = function(key, value) {
362 | var paramMap = queryStringToParamMap();
363 | paramMap[key] = value;
364 | options.getWindowLocation().search = toQueryString(paramMap);
365 | };
366 |
367 | this.getParam = function(key) {
368 | return queryStringToParamMap()[key];
369 | };
370 |
371 | return this;
372 |
373 | function toQueryString(paramMap) {
374 | var qStrPairs = [];
375 | for (var prop in paramMap) {
376 | qStrPairs.push(encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop]));
377 | }
378 | return '?' + qStrPairs.join('&');
379 | }
380 |
381 | function queryStringToParamMap() {
382 | var paramStr = options.getWindowLocation().search.substring(1),
383 | params = [],
384 | paramMap = {};
385 |
386 | if (paramStr.length > 0) {
387 | params = paramStr.split('&');
388 | for (var i = 0; i < params.length; i++) {
389 | var p = params[i].split('=');
390 | var value = decodeURIComponent(p[1]);
391 | if (value === 'true' || value === 'false') {
392 | value = JSON.parse(value);
393 | }
394 | paramMap[decodeURIComponent(p[0])] = value;
395 | }
396 | }
397 |
398 | return paramMap;
399 | }
400 |
401 | }
402 |
403 | return QueryString;
404 | };
405 |
--------------------------------------------------------------------------------
/test/lib/jasmine-2.1.3/jasmine.css:
--------------------------------------------------------------------------------
1 | body { overflow-y: scroll; }
2 |
3 | .jasmine_html-reporter { background-color: #eeeeee; padding: 5px; margin: -8px; font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; }
4 | .jasmine_html-reporter a { text-decoration: none; }
5 | .jasmine_html-reporter a:hover { text-decoration: underline; }
6 | .jasmine_html-reporter p, .jasmine_html-reporter h1, .jasmine_html-reporter h2, .jasmine_html-reporter h3, .jasmine_html-reporter h4, .jasmine_html-reporter h5, .jasmine_html-reporter h6 { margin: 0; line-height: 14px; }
7 | .jasmine_html-reporter .banner, .jasmine_html-reporter .symbol-summary, .jasmine_html-reporter .summary, .jasmine_html-reporter .result-message, .jasmine_html-reporter .spec .description, .jasmine_html-reporter .spec-detail .description, .jasmine_html-reporter .alert .bar, .jasmine_html-reporter .stack-trace { padding-left: 9px; padding-right: 9px; }
8 | .jasmine_html-reporter .banner { position: relative; }
9 | .jasmine_html-reporter .banner .title { background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAAAZCAMAAACGusnyAAACdlBMVEX/////AP+AgICqVaqAQICZM5mAVYCSSZKAQICOOY6ATYCLRouAQICJO4mSSYCIRIiPQICHPIeOR4CGQ4aMQICGPYaLRoCFQ4WKQICPPYWJRYCOQoSJQICNPoSIRICMQoSHQICHRICKQoOHQICKPoOJO4OJQYOMQICMQ4CIQYKLQICIPoKLQ4CKQICNPoKJQISMQ4KJQoSLQYKJQISLQ4KIQoSKQYKIQICIQISMQoSKQYKLQIOLQoOJQYGLQIOKQIOMQoGKQYOLQYGKQIOLQoGJQYOJQIOKQYGJQIOKQoGKQIGLQIKLQ4KKQoGLQYKJQIGKQYKJQIGKQIKJQoGKQYKLQIGKQYKLQIOJQoKKQoOJQYKKQIOJQoKKQoOKQIOLQoKKQYOLQYKJQIOKQoKKQYKKQoKJQYOKQYKLQIOKQoKLQYOKQYKLQIOJQoGKQYKJQYGJQoGKQYKLQoGLQYGKQoGJQYKKQYGJQIKKQoGJQYKLQIKKQYGLQYKKQYGKQYGKQYKJQYOKQoKJQYOKQYKLQYOLQYOKQYKLQYOKQoKKQYKKQYOKQYOJQYKKQYKLQYKKQIKKQoKKQYKKQYKKQoKJQIKKQYKLQYKKQYKKQIKKQYKKQYKKQYKKQIKKQYK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gogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA3MTYuMjg5LDM3Ni41OSAzNy42NDA2LDAgMCwxODQuODE2IC0zNy42NDA2LDAgMCwtMTg0LjgxNiB6IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoNTYiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjwvZz48L2c+PC9nPjwvZz48L3N2Zz4=') no-repeat, none; -webkit-background-size: 100%; -moz-background-size: 100%; -o-background-size: 100%; background-size: 100%; display: block; float: left; width: 90px; height: 25px; }
10 | .jasmine_html-reporter .banner .version { margin-left: 14px; position: relative; top: 6px; }
11 | .jasmine_html-reporter .banner .duration { position: absolute; right: 14px; top: 6px; }
12 | .jasmine_html-reporter #jasmine_content { position: fixed; right: 100%; }
13 | .jasmine_html-reporter .version { color: #aaaaaa; }
14 | .jasmine_html-reporter .banner { margin-top: 14px; }
15 | .jasmine_html-reporter .duration { color: #aaaaaa; float: right; }
16 | .jasmine_html-reporter .symbol-summary { overflow: hidden; *zoom: 1; margin: 14px 0; }
17 | .jasmine_html-reporter .symbol-summary li { display: inline-block; height: 8px; width: 14px; font-size: 16px; }
18 | .jasmine_html-reporter .symbol-summary li.passed { font-size: 14px; }
19 | .jasmine_html-reporter .symbol-summary li.passed:before { color: #007069; content: "\02022"; }
20 | .jasmine_html-reporter .symbol-summary li.failed { line-height: 9px; }
21 | .jasmine_html-reporter .symbol-summary li.failed:before { color: #ca3a11; content: "\d7"; font-weight: bold; margin-left: -1px; }
22 | .jasmine_html-reporter .symbol-summary li.disabled { font-size: 14px; }
23 | .jasmine_html-reporter .symbol-summary li.disabled:before { color: #bababa; content: "\02022"; }
24 | .jasmine_html-reporter .symbol-summary li.pending { line-height: 17px; }
25 | .jasmine_html-reporter .symbol-summary li.pending:before { color: #ba9d37; content: "*"; }
26 | .jasmine_html-reporter .symbol-summary li.empty { font-size: 14px; }
27 | .jasmine_html-reporter .symbol-summary li.empty:before { color: #ba9d37; content: "\02022"; }
28 | .jasmine_html-reporter .exceptions { color: #fff; float: right; margin-top: 5px; margin-right: 5px; }
29 | .jasmine_html-reporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; }
30 | .jasmine_html-reporter .bar.failed { background-color: #ca3a11; }
31 | .jasmine_html-reporter .bar.passed { background-color: #007069; }
32 | .jasmine_html-reporter .bar.skipped { background-color: #bababa; }
33 | .jasmine_html-reporter .bar.errored { background-color: #ca3a11; }
34 | .jasmine_html-reporter .bar.menu { background-color: #fff; color: #aaaaaa; }
35 | .jasmine_html-reporter .bar.menu a { color: #333333; }
36 | .jasmine_html-reporter .bar a { color: white; }
37 | .jasmine_html-reporter.spec-list .bar.menu.failure-list, .jasmine_html-reporter.spec-list .results .failures { display: none; }
38 | .jasmine_html-reporter.failure-list .bar.menu.spec-list, .jasmine_html-reporter.failure-list .summary { display: none; }
39 | .jasmine_html-reporter .running-alert { background-color: #666666; }
40 | .jasmine_html-reporter .results { margin-top: 14px; }
41 | .jasmine_html-reporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; }
42 | .jasmine_html-reporter.showDetails .summaryMenuItem:hover { text-decoration: underline; }
43 | .jasmine_html-reporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; }
44 | .jasmine_html-reporter.showDetails .summary { display: none; }
45 | .jasmine_html-reporter.showDetails #details { display: block; }
46 | .jasmine_html-reporter .summaryMenuItem { font-weight: bold; text-decoration: underline; }
47 | .jasmine_html-reporter .summary { margin-top: 14px; }
48 | .jasmine_html-reporter .summary ul { list-style-type: none; margin-left: 14px; padding-top: 0; padding-left: 0; }
49 | .jasmine_html-reporter .summary ul.suite { margin-top: 7px; margin-bottom: 7px; }
50 | .jasmine_html-reporter .summary li.passed a { color: #007069; }
51 | .jasmine_html-reporter .summary li.failed a { color: #ca3a11; }
52 | .jasmine_html-reporter .summary li.empty a { color: #ba9d37; }
53 | .jasmine_html-reporter .summary li.pending a { color: #ba9d37; }
54 | .jasmine_html-reporter .description + .suite { margin-top: 0; }
55 | .jasmine_html-reporter .suite { margin-top: 14px; }
56 | .jasmine_html-reporter .suite a { color: #333333; }
57 | .jasmine_html-reporter .failures .spec-detail { margin-bottom: 28px; }
58 | .jasmine_html-reporter .failures .spec-detail .description { background-color: #ca3a11; }
59 | .jasmine_html-reporter .failures .spec-detail .description a { color: white; }
60 | .jasmine_html-reporter .result-message { padding-top: 14px; color: #333333; white-space: pre; }
61 | .jasmine_html-reporter .result-message span.result { display: block; }
62 | .jasmine_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; }
63 |
--------------------------------------------------------------------------------
/test/lib/jasmine-2.1.3/jasmine.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2008-2014 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 | getJasmineRequireObj = (function (jasmineGlobal) {
24 | var jasmineRequire;
25 |
26 | if (typeof module !== 'undefined' && module.exports) {
27 | jasmineGlobal = global;
28 | jasmineRequire = exports;
29 | } else {
30 | jasmineRequire = jasmineGlobal.jasmineRequire = jasmineGlobal.jasmineRequire || {};
31 | }
32 |
33 | function getJasmineRequire() {
34 | return jasmineRequire;
35 | }
36 |
37 | getJasmineRequire().core = function(jRequire) {
38 | var j$ = {};
39 |
40 | jRequire.base(j$, jasmineGlobal);
41 | j$.util = jRequire.util();
42 | j$.Any = jRequire.Any();
43 | j$.CallTracker = jRequire.CallTracker();
44 | j$.MockDate = jRequire.MockDate();
45 | j$.Clock = jRequire.Clock();
46 | j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler();
47 | j$.Env = jRequire.Env(j$);
48 | j$.ExceptionFormatter = jRequire.ExceptionFormatter();
49 | j$.Expectation = jRequire.Expectation();
50 | j$.buildExpectationResult = jRequire.buildExpectationResult();
51 | j$.JsApiReporter = jRequire.JsApiReporter();
52 | j$.matchersUtil = jRequire.matchersUtil(j$);
53 | j$.ObjectContaining = jRequire.ObjectContaining(j$);
54 | j$.pp = jRequire.pp(j$);
55 | j$.QueueRunner = jRequire.QueueRunner(j$);
56 | j$.ReportDispatcher = jRequire.ReportDispatcher();
57 | j$.Spec = jRequire.Spec(j$);
58 | j$.SpyRegistry = jRequire.SpyRegistry(j$);
59 | j$.SpyStrategy = jRequire.SpyStrategy();
60 | j$.Suite = jRequire.Suite();
61 | j$.Timer = jRequire.Timer();
62 | j$.version = jRequire.version();
63 |
64 | j$.matchers = jRequire.requireMatchers(jRequire, j$);
65 |
66 | return j$;
67 | };
68 |
69 | return getJasmineRequire;
70 | })(this);
71 |
72 | getJasmineRequireObj().requireMatchers = function(jRequire, j$) {
73 | var availableMatchers = [
74 | 'toBe',
75 | 'toBeCloseTo',
76 | 'toBeDefined',
77 | 'toBeFalsy',
78 | 'toBeGreaterThan',
79 | 'toBeLessThan',
80 | 'toBeNaN',
81 | 'toBeNull',
82 | 'toBeTruthy',
83 | 'toBeUndefined',
84 | 'toContain',
85 | 'toEqual',
86 | 'toHaveBeenCalled',
87 | 'toHaveBeenCalledWith',
88 | 'toMatch',
89 | 'toThrow',
90 | 'toThrowError'
91 | ],
92 | matchers = {};
93 |
94 | for (var i = 0; i < availableMatchers.length; i++) {
95 | var name = availableMatchers[i];
96 | matchers[name] = jRequire[name](j$);
97 | }
98 |
99 | return matchers;
100 | };
101 |
102 | getJasmineRequireObj().base = function(j$, jasmineGlobal) {
103 | j$.unimplementedMethod_ = function() {
104 | throw new Error('unimplemented method');
105 | };
106 |
107 | j$.MAX_PRETTY_PRINT_DEPTH = 40;
108 | j$.MAX_PRETTY_PRINT_ARRAY_LENGTH = 100;
109 | j$.DEFAULT_TIMEOUT_INTERVAL = 5000;
110 |
111 | j$.getGlobal = function() {
112 | return jasmineGlobal;
113 | };
114 |
115 | j$.getEnv = function(options) {
116 | var env = j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options);
117 | //jasmine. singletons in here (setTimeout blah blah).
118 | return env;
119 | };
120 |
121 | j$.isArray_ = function(value) {
122 | return j$.isA_('Array', value);
123 | };
124 |
125 | j$.isString_ = function(value) {
126 | return j$.isA_('String', value);
127 | };
128 |
129 | j$.isNumber_ = function(value) {
130 | return j$.isA_('Number', value);
131 | };
132 |
133 | j$.isA_ = function(typeName, value) {
134 | return Object.prototype.toString.apply(value) === '[object ' + typeName + ']';
135 | };
136 |
137 | j$.isDomNode = function(obj) {
138 | return obj.nodeType > 0;
139 | };
140 |
141 | j$.any = function(clazz) {
142 | return new j$.Any(clazz);
143 | };
144 |
145 | j$.objectContaining = function(sample) {
146 | return new j$.ObjectContaining(sample);
147 | };
148 |
149 | j$.createSpy = function(name, originalFn) {
150 |
151 | var spyStrategy = new j$.SpyStrategy({
152 | name: name,
153 | fn: originalFn,
154 | getSpy: function() { return spy; }
155 | }),
156 | callTracker = new j$.CallTracker(),
157 | spy = function() {
158 | var callData = {
159 | object: this,
160 | args: Array.prototype.slice.apply(arguments)
161 | };
162 |
163 | callTracker.track(callData);
164 | var returnValue = spyStrategy.exec.apply(this, arguments);
165 | callData.returnValue = returnValue;
166 |
167 | return returnValue;
168 | };
169 |
170 | for (var prop in originalFn) {
171 | if (prop === 'and' || prop === 'calls') {
172 | throw new Error('Jasmine spies would overwrite the \'and\' and \'calls\' properties on the object being spied upon');
173 | }
174 |
175 | spy[prop] = originalFn[prop];
176 | }
177 |
178 | spy.and = spyStrategy;
179 | spy.calls = callTracker;
180 |
181 | return spy;
182 | };
183 |
184 | j$.isSpy = function(putativeSpy) {
185 | if (!putativeSpy) {
186 | return false;
187 | }
188 | return putativeSpy.and instanceof j$.SpyStrategy &&
189 | putativeSpy.calls instanceof j$.CallTracker;
190 | };
191 |
192 | j$.createSpyObj = function(baseName, methodNames) {
193 | if (!j$.isArray_(methodNames) || methodNames.length === 0) {
194 | throw 'createSpyObj requires a non-empty array of method names to create spies for';
195 | }
196 | var obj = {};
197 | for (var i = 0; i < methodNames.length; i++) {
198 | obj[methodNames[i]] = j$.createSpy(baseName + '.' + methodNames[i]);
199 | }
200 | return obj;
201 | };
202 | };
203 |
204 | getJasmineRequireObj().util = function() {
205 |
206 | var util = {};
207 |
208 | util.inherit = function(childClass, parentClass) {
209 | var Subclass = function() {
210 | };
211 | Subclass.prototype = parentClass.prototype;
212 | childClass.prototype = new Subclass();
213 | };
214 |
215 | util.htmlEscape = function(str) {
216 | if (!str) {
217 | return str;
218 | }
219 | return str.replace(/&/g, '&')
220 | .replace(//g, '>');
222 | };
223 |
224 | util.argsToArray = function(args) {
225 | var arrayOfArgs = [];
226 | for (var i = 0; i < args.length; i++) {
227 | arrayOfArgs.push(args[i]);
228 | }
229 | return arrayOfArgs;
230 | };
231 |
232 | util.isUndefined = function(obj) {
233 | return obj === void 0;
234 | };
235 |
236 | util.arrayContains = function(array, search) {
237 | var i = array.length;
238 | while (i--) {
239 | if (array[i] === search) {
240 | return true;
241 | }
242 | }
243 | return false;
244 | };
245 |
246 | util.clone = function(obj) {
247 | if (Object.prototype.toString.apply(obj) === '[object Array]') {
248 | return obj.slice();
249 | }
250 |
251 | var cloned = {};
252 | for (var prop in obj) {
253 | if (obj.hasOwnProperty(prop)) {
254 | cloned[prop] = obj[prop];
255 | }
256 | }
257 |
258 | return cloned;
259 | };
260 |
261 | return util;
262 | };
263 |
264 | getJasmineRequireObj().Spec = function(j$) {
265 | function Spec(attrs) {
266 | this.expectationFactory = attrs.expectationFactory;
267 | this.resultCallback = attrs.resultCallback || function() {};
268 | this.id = attrs.id;
269 | this.description = attrs.description || '';
270 | this.queueableFn = attrs.queueableFn;
271 | this.beforeAndAfterFns = attrs.beforeAndAfterFns || function() { return {befores: [], afters: []}; };
272 | this.userContext = attrs.userContext || function() { return {}; };
273 | this.onStart = attrs.onStart || function() {};
274 | this.getSpecName = attrs.getSpecName || function() { return ''; };
275 | this.expectationResultFactory = attrs.expectationResultFactory || function() { };
276 | this.queueRunnerFactory = attrs.queueRunnerFactory || function() {};
277 | this.catchingExceptions = attrs.catchingExceptions || function() { return true; };
278 |
279 | if (!this.queueableFn.fn) {
280 | this.pend();
281 | }
282 |
283 | this.result = {
284 | id: this.id,
285 | description: this.description,
286 | fullName: this.getFullName(),
287 | failedExpectations: [],
288 | passedExpectations: []
289 | };
290 | }
291 |
292 | Spec.prototype.addExpectationResult = function(passed, data) {
293 | var expectationResult = this.expectationResultFactory(data);
294 | if (passed) {
295 | this.result.passedExpectations.push(expectationResult);
296 | } else {
297 | this.result.failedExpectations.push(expectationResult);
298 | }
299 | };
300 |
301 | Spec.prototype.expect = function(actual) {
302 | return this.expectationFactory(actual, this);
303 | };
304 |
305 | Spec.prototype.execute = function(onComplete) {
306 | var self = this;
307 |
308 | this.onStart(this);
309 |
310 | if (this.markedPending || this.disabled) {
311 | complete();
312 | return;
313 | }
314 |
315 | var fns = this.beforeAndAfterFns();
316 | var allFns = fns.befores.concat(this.queueableFn).concat(fns.afters);
317 |
318 | this.queueRunnerFactory({
319 | queueableFns: allFns,
320 | onException: function() { self.onException.apply(self, arguments); },
321 | onComplete: complete,
322 | userContext: this.userContext()
323 | });
324 |
325 | function complete() {
326 | self.result.status = self.status();
327 | self.resultCallback(self.result);
328 |
329 | if (onComplete) {
330 | onComplete();
331 | }
332 | }
333 | };
334 |
335 | Spec.prototype.onException = function onException(e) {
336 | if (Spec.isPendingSpecException(e)) {
337 | this.pend();
338 | return;
339 | }
340 |
341 | this.addExpectationResult(false, {
342 | matcherName: '',
343 | passed: false,
344 | expected: '',
345 | actual: '',
346 | error: e
347 | });
348 | };
349 |
350 | Spec.prototype.disable = function() {
351 | this.disabled = true;
352 | };
353 |
354 | Spec.prototype.pend = function() {
355 | this.markedPending = true;
356 | };
357 |
358 | Spec.prototype.status = function() {
359 | if (this.disabled) {
360 | return 'disabled';
361 | }
362 |
363 | if (this.markedPending) {
364 | return 'pending';
365 | }
366 |
367 | if (this.result.failedExpectations.length > 0) {
368 | return 'failed';
369 | } else {
370 | return 'passed';
371 | }
372 | };
373 |
374 | Spec.prototype.isExecutable = function() {
375 | return !this.disabled && !this.markedPending;
376 | };
377 |
378 | Spec.prototype.getFullName = function() {
379 | return this.getSpecName(this);
380 | };
381 |
382 | Spec.pendingSpecExceptionMessage = '=> marked Pending';
383 |
384 | Spec.isPendingSpecException = function(e) {
385 | return !!(e && e.toString && e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1);
386 | };
387 |
388 | return Spec;
389 | };
390 |
391 | if (typeof window == void 0 && typeof exports == 'object') {
392 | exports.Spec = jasmineRequire.Spec;
393 | }
394 |
395 | getJasmineRequireObj().Env = function(j$) {
396 | function Env(options) {
397 | options = options || {};
398 |
399 | var self = this;
400 | var global = options.global || j$.getGlobal();
401 |
402 | var totalSpecsDefined = 0;
403 |
404 | var catchExceptions = true;
405 |
406 | var realSetTimeout = j$.getGlobal().setTimeout;
407 | var realClearTimeout = j$.getGlobal().clearTimeout;
408 | this.clock = new j$.Clock(global, new j$.DelayedFunctionScheduler(), new j$.MockDate(global));
409 |
410 | var runnableLookupTable = {};
411 | var runnableResources = {};
412 |
413 | var currentSpec = null;
414 | var currentlyExecutingSuites = [];
415 | var currentDeclarationSuite = null;
416 |
417 | var currentSuite = function() {
418 | return currentlyExecutingSuites[currentlyExecutingSuites.length - 1];
419 | };
420 |
421 | var currentRunnable = function() {
422 | return currentSpec || currentSuite();
423 | };
424 |
425 | var reporter = new j$.ReportDispatcher([
426 | 'jasmineStarted',
427 | 'jasmineDone',
428 | 'suiteStarted',
429 | 'suiteDone',
430 | 'specStarted',
431 | 'specDone'
432 | ]);
433 |
434 | this.specFilter = function() {
435 | return true;
436 | };
437 |
438 | this.addCustomEqualityTester = function(tester) {
439 | if(!currentRunnable()) {
440 | throw new Error('Custom Equalities must be added in a before function or a spec');
441 | }
442 | runnableResources[currentRunnable().id].customEqualityTesters.push(tester);
443 | };
444 |
445 | this.addMatchers = function(matchersToAdd) {
446 | if(!currentRunnable()) {
447 | throw new Error('Matchers must be added in a before function or a spec');
448 | }
449 | var customMatchers = runnableResources[currentRunnable().id].customMatchers;
450 | for (var matcherName in matchersToAdd) {
451 | customMatchers[matcherName] = matchersToAdd[matcherName];
452 | }
453 | };
454 |
455 | j$.Expectation.addCoreMatchers(j$.matchers);
456 |
457 | var nextSpecId = 0;
458 | var getNextSpecId = function() {
459 | return 'spec' + nextSpecId++;
460 | };
461 |
462 | var nextSuiteId = 0;
463 | var getNextSuiteId = function() {
464 | return 'suite' + nextSuiteId++;
465 | };
466 |
467 | var expectationFactory = function(actual, spec) {
468 | return j$.Expectation.Factory({
469 | util: j$.matchersUtil,
470 | customEqualityTesters: runnableResources[spec.id].customEqualityTesters,
471 | customMatchers: runnableResources[spec.id].customMatchers,
472 | actual: actual,
473 | addExpectationResult: addExpectationResult
474 | });
475 |
476 | function addExpectationResult(passed, result) {
477 | return spec.addExpectationResult(passed, result);
478 | }
479 | };
480 |
481 | var defaultResourcesForRunnable = function(id, parentRunnableId) {
482 | var resources = {spies: [], customEqualityTesters: [], customMatchers: {}};
483 |
484 | if(runnableResources[parentRunnableId]){
485 | resources.customEqualityTesters = j$.util.clone(runnableResources[parentRunnableId].customEqualityTesters);
486 | resources.customMatchers = j$.util.clone(runnableResources[parentRunnableId].customMatchers);
487 | }
488 |
489 | runnableResources[id] = resources;
490 | };
491 |
492 | var clearResourcesForRunnable = function(id) {
493 | spyRegistry.clearSpies();
494 | delete runnableResources[id];
495 | };
496 |
497 | var beforeAndAfterFns = function(suite, runnablesExplictlySet) {
498 | return function() {
499 | var befores = [],
500 | afters = [],
501 | beforeAlls = [],
502 | afterAlls = [];
503 |
504 | while(suite) {
505 | befores = befores.concat(suite.beforeFns);
506 | afters = afters.concat(suite.afterFns);
507 |
508 | if (runnablesExplictlySet()) {
509 | beforeAlls = beforeAlls.concat(suite.beforeAllFns);
510 | afterAlls = afterAlls.concat(suite.afterAllFns);
511 | }
512 |
513 | suite = suite.parentSuite;
514 | }
515 | return {
516 | befores: beforeAlls.reverse().concat(befores.reverse()),
517 | afters: afters.concat(afterAlls)
518 | };
519 | };
520 | };
521 |
522 | var getSpecName = function(spec, suite) {
523 | return suite.getFullName() + ' ' + spec.description;
524 | };
525 |
526 | // TODO: we may just be able to pass in the fn instead of wrapping here
527 | var buildExpectationResult = j$.buildExpectationResult,
528 | exceptionFormatter = new j$.ExceptionFormatter(),
529 | expectationResultFactory = function(attrs) {
530 | attrs.messageFormatter = exceptionFormatter.message;
531 | attrs.stackFormatter = exceptionFormatter.stack;
532 |
533 | return buildExpectationResult(attrs);
534 | };
535 |
536 | // TODO: fix this naming, and here's where the value comes in
537 | this.catchExceptions = function(value) {
538 | catchExceptions = !!value;
539 | return catchExceptions;
540 | };
541 |
542 | this.catchingExceptions = function() {
543 | return catchExceptions;
544 | };
545 |
546 | var maximumSpecCallbackDepth = 20;
547 | var currentSpecCallbackDepth = 0;
548 |
549 | function clearStack(fn) {
550 | currentSpecCallbackDepth++;
551 | if (currentSpecCallbackDepth >= maximumSpecCallbackDepth) {
552 | currentSpecCallbackDepth = 0;
553 | realSetTimeout(fn, 0);
554 | } else {
555 | fn();
556 | }
557 | }
558 |
559 | var catchException = function(e) {
560 | return j$.Spec.isPendingSpecException(e) || catchExceptions;
561 | };
562 |
563 | var queueRunnerFactory = function(options) {
564 | options.catchException = catchException;
565 | options.clearStack = options.clearStack || clearStack;
566 | options.timer = {setTimeout: realSetTimeout, clearTimeout: realClearTimeout};
567 | options.fail = self.fail;
568 |
569 | new j$.QueueRunner(options).execute();
570 | };
571 |
572 | var topSuite = new j$.Suite({
573 | env: this,
574 | id: getNextSuiteId(),
575 | description: 'Jasmine__TopLevel__Suite',
576 | queueRunner: queueRunnerFactory
577 | });
578 | runnableLookupTable[topSuite.id] = topSuite;
579 | defaultResourcesForRunnable(topSuite.id);
580 | currentDeclarationSuite = topSuite;
581 |
582 | this.topSuite = function() {
583 | return topSuite;
584 | };
585 |
586 | this.execute = function(runnablesToRun) {
587 | if(runnablesToRun) {
588 | runnablesExplictlySet = true;
589 | } else if (focusedRunnables.length) {
590 | runnablesExplictlySet = true;
591 | runnablesToRun = focusedRunnables;
592 | } else {
593 | runnablesToRun = [topSuite.id];
594 | }
595 |
596 | var allFns = [];
597 | for(var i = 0; i < runnablesToRun.length; i++) {
598 | var runnable = runnableLookupTable[runnablesToRun[i]];
599 | allFns.push((function(runnable) { return { fn: function(done) { runnable.execute(done); } }; })(runnable));
600 | }
601 |
602 | reporter.jasmineStarted({
603 | totalSpecsDefined: totalSpecsDefined
604 | });
605 |
606 | queueRunnerFactory({queueableFns: allFns, onComplete: reporter.jasmineDone});
607 | };
608 |
609 | this.addReporter = function(reporterToAdd) {
610 | reporter.addReporter(reporterToAdd);
611 | };
612 |
613 | var spyRegistry = new j$.SpyRegistry({currentSpies: function() {
614 | if(!currentRunnable()) {
615 | throw new Error('Spies must be created in a before function or a spec');
616 | }
617 | return runnableResources[currentRunnable().id].spies;
618 | }});
619 |
620 | this.spyOn = function() {
621 | return spyRegistry.spyOn.apply(spyRegistry, arguments);
622 | };
623 |
624 | var suiteFactory = function(description) {
625 | var suite = new j$.Suite({
626 | env: self,
627 | id: getNextSuiteId(),
628 | description: description,
629 | parentSuite: currentDeclarationSuite,
630 | queueRunner: queueRunnerFactory,
631 | onStart: suiteStarted,
632 | expectationFactory: expectationFactory,
633 | expectationResultFactory: expectationResultFactory,
634 | resultCallback: function(attrs) {
635 | if (!suite.disabled) {
636 | clearResourcesForRunnable(suite.id);
637 | currentlyExecutingSuites.pop();
638 | }
639 | reporter.suiteDone(attrs);
640 | }
641 | });
642 |
643 | runnableLookupTable[suite.id] = suite;
644 | return suite;
645 |
646 | function suiteStarted(suite) {
647 | currentlyExecutingSuites.push(suite);
648 | defaultResourcesForRunnable(suite.id, suite.parentSuite.id);
649 | reporter.suiteStarted(suite.result);
650 | }
651 | };
652 |
653 | this.describe = function(description, specDefinitions) {
654 | var suite = suiteFactory(description);
655 | addSpecsToSuite(suite, specDefinitions);
656 | return suite;
657 | };
658 |
659 | this.xdescribe = function(description, specDefinitions) {
660 | var suite = this.describe(description, specDefinitions);
661 | suite.disable();
662 | return suite;
663 | };
664 |
665 | var focusedRunnables = [];
666 |
667 | this.fdescribe = function(description, specDefinitions) {
668 | var suite = suiteFactory(description);
669 | suite.isFocused = true;
670 |
671 | focusedRunnables.push(suite.id);
672 | unfocusAncestor();
673 | addSpecsToSuite(suite, specDefinitions);
674 |
675 | return suite;
676 | };
677 |
678 | function addSpecsToSuite(suite, specDefinitions) {
679 | var parentSuite = currentDeclarationSuite;
680 | parentSuite.addChild(suite);
681 | currentDeclarationSuite = suite;
682 |
683 | var declarationError = null;
684 | try {
685 | specDefinitions.call(suite);
686 | } catch (e) {
687 | declarationError = e;
688 | }
689 |
690 | if (declarationError) {
691 | self.it('encountered a declaration exception', function() {
692 | throw declarationError;
693 | });
694 | }
695 |
696 | currentDeclarationSuite = parentSuite;
697 | }
698 |
699 | function findFocusedAncestor(suite) {
700 | while (suite) {
701 | if (suite.isFocused) {
702 | return suite.id;
703 | }
704 | suite = suite.parentSuite;
705 | }
706 |
707 | return null;
708 | }
709 |
710 | function unfocusAncestor() {
711 | var focusedAncestor = findFocusedAncestor(currentDeclarationSuite);
712 | if (focusedAncestor) {
713 | for (var i = 0; i < focusedRunnables.length; i++) {
714 | if (focusedRunnables[i] === focusedAncestor) {
715 | focusedRunnables.splice(i, 1);
716 | break;
717 | }
718 | }
719 | }
720 | }
721 |
722 | var runnablesExplictlySet = false;
723 |
724 | var runnablesExplictlySetGetter = function(){
725 | return runnablesExplictlySet;
726 | };
727 |
728 | var specFactory = function(description, fn, suite, timeout) {
729 | totalSpecsDefined++;
730 | var spec = new j$.Spec({
731 | id: getNextSpecId(),
732 | beforeAndAfterFns: beforeAndAfterFns(suite, runnablesExplictlySetGetter),
733 | expectationFactory: expectationFactory,
734 | resultCallback: specResultCallback,
735 | getSpecName: function(spec) {
736 | return getSpecName(spec, suite);
737 | },
738 | onStart: specStarted,
739 | description: description,
740 | expectationResultFactory: expectationResultFactory,
741 | queueRunnerFactory: queueRunnerFactory,
742 | userContext: function() { return suite.clonedSharedUserContext(); },
743 | queueableFn: {
744 | fn: fn,
745 | timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; }
746 | }
747 | });
748 |
749 | runnableLookupTable[spec.id] = spec;
750 |
751 | if (!self.specFilter(spec)) {
752 | spec.disable();
753 | }
754 |
755 | return spec;
756 |
757 | function specResultCallback(result) {
758 | clearResourcesForRunnable(spec.id);
759 | currentSpec = null;
760 | reporter.specDone(result);
761 | }
762 |
763 | function specStarted(spec) {
764 | currentSpec = spec;
765 | defaultResourcesForRunnable(spec.id, suite.id);
766 | reporter.specStarted(spec.result);
767 | }
768 | };
769 |
770 | this.it = function(description, fn, timeout) {
771 | var spec = specFactory(description, fn, currentDeclarationSuite, timeout);
772 | currentDeclarationSuite.addChild(spec);
773 | return spec;
774 | };
775 |
776 | this.xit = function() {
777 | var spec = this.it.apply(this, arguments);
778 | spec.pend();
779 | return spec;
780 | };
781 |
782 | this.fit = function(){
783 | var spec = this.it.apply(this, arguments);
784 |
785 | focusedRunnables.push(spec.id);
786 | unfocusAncestor();
787 | return spec;
788 | };
789 |
790 | this.expect = function(actual) {
791 | if (!currentRunnable()) {
792 | throw new Error('\'expect\' was used when there was no current spec, this could be because an asynchronous test timed out');
793 | }
794 |
795 | return currentRunnable().expect(actual);
796 | };
797 |
798 | this.beforeEach = function(beforeEachFunction, timeout) {
799 | currentDeclarationSuite.beforeEach({
800 | fn: beforeEachFunction,
801 | timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; }
802 | });
803 | };
804 |
805 | this.beforeAll = function(beforeAllFunction, timeout) {
806 | currentDeclarationSuite.beforeAll({
807 | fn: beforeAllFunction,
808 | timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; }
809 | });
810 | };
811 |
812 | this.afterEach = function(afterEachFunction, timeout) {
813 | currentDeclarationSuite.afterEach({
814 | fn: afterEachFunction,
815 | timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; }
816 | });
817 | };
818 |
819 | this.afterAll = function(afterAllFunction, timeout) {
820 | currentDeclarationSuite.afterAll({
821 | fn: afterAllFunction,
822 | timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; }
823 | });
824 | };
825 |
826 | this.pending = function() {
827 | throw j$.Spec.pendingSpecExceptionMessage;
828 | };
829 |
830 | this.fail = function(error) {
831 | var message = 'Failed';
832 | if (error) {
833 | message += ': ';
834 | message += error.message || error;
835 | }
836 |
837 | currentRunnable().addExpectationResult(false, {
838 | matcherName: '',
839 | passed: false,
840 | expected: '',
841 | actual: '',
842 | message: message
843 | });
844 | };
845 | }
846 |
847 | return Env;
848 | };
849 |
850 | getJasmineRequireObj().JsApiReporter = function() {
851 |
852 | var noopTimer = {
853 | start: function(){},
854 | elapsed: function(){ return 0; }
855 | };
856 |
857 | function JsApiReporter(options) {
858 | var timer = options.timer || noopTimer,
859 | status = 'loaded';
860 |
861 | this.started = false;
862 | this.finished = false;
863 |
864 | this.jasmineStarted = function() {
865 | this.started = true;
866 | status = 'started';
867 | timer.start();
868 | };
869 |
870 | var executionTime;
871 |
872 | this.jasmineDone = function() {
873 | this.finished = true;
874 | executionTime = timer.elapsed();
875 | status = 'done';
876 | };
877 |
878 | this.status = function() {
879 | return status;
880 | };
881 |
882 | var suites = [],
883 | suites_hash = {};
884 |
885 | this.suiteStarted = function(result) {
886 | suites_hash[result.id] = result;
887 | };
888 |
889 | this.suiteDone = function(result) {
890 | storeSuite(result);
891 | };
892 |
893 | this.suiteResults = function(index, length) {
894 | return suites.slice(index, index + length);
895 | };
896 |
897 | function storeSuite(result) {
898 | suites.push(result);
899 | suites_hash[result.id] = result;
900 | }
901 |
902 | this.suites = function() {
903 | return suites_hash;
904 | };
905 |
906 | var specs = [];
907 |
908 | this.specDone = function(result) {
909 | specs.push(result);
910 | };
911 |
912 | this.specResults = function(index, length) {
913 | return specs.slice(index, index + length);
914 | };
915 |
916 | this.specs = function() {
917 | return specs;
918 | };
919 |
920 | this.executionTime = function() {
921 | return executionTime;
922 | };
923 |
924 | }
925 |
926 | return JsApiReporter;
927 | };
928 |
929 | getJasmineRequireObj().Any = function() {
930 |
931 | function Any(expectedObject) {
932 | this.expectedObject = expectedObject;
933 | }
934 |
935 | Any.prototype.jasmineMatches = function(other) {
936 | if (this.expectedObject == String) {
937 | return typeof other == 'string' || other instanceof String;
938 | }
939 |
940 | if (this.expectedObject == Number) {
941 | return typeof other == 'number' || other instanceof Number;
942 | }
943 |
944 | if (this.expectedObject == Function) {
945 | return typeof other == 'function' || other instanceof Function;
946 | }
947 |
948 | if (this.expectedObject == Object) {
949 | return typeof other == 'object';
950 | }
951 |
952 | if (this.expectedObject == Boolean) {
953 | return typeof other == 'boolean';
954 | }
955 |
956 | return other instanceof this.expectedObject;
957 | };
958 |
959 | Any.prototype.jasmineToString = function() {
960 | return '';
961 | };
962 |
963 | return Any;
964 | };
965 |
966 | getJasmineRequireObj().CallTracker = function() {
967 |
968 | function CallTracker() {
969 | var calls = [];
970 |
971 | this.track = function(context) {
972 | calls.push(context);
973 | };
974 |
975 | this.any = function() {
976 | return !!calls.length;
977 | };
978 |
979 | this.count = function() {
980 | return calls.length;
981 | };
982 |
983 | this.argsFor = function(index) {
984 | var call = calls[index];
985 | return call ? call.args : [];
986 | };
987 |
988 | this.all = function() {
989 | return calls;
990 | };
991 |
992 | this.allArgs = function() {
993 | var callArgs = [];
994 | for(var i = 0; i < calls.length; i++){
995 | callArgs.push(calls[i].args);
996 | }
997 |
998 | return callArgs;
999 | };
1000 |
1001 | this.first = function() {
1002 | return calls[0];
1003 | };
1004 |
1005 | this.mostRecent = function() {
1006 | return calls[calls.length - 1];
1007 | };
1008 |
1009 | this.reset = function() {
1010 | calls = [];
1011 | };
1012 | }
1013 |
1014 | return CallTracker;
1015 | };
1016 |
1017 | getJasmineRequireObj().Clock = function() {
1018 | function Clock(global, delayedFunctionScheduler, mockDate) {
1019 | var self = this,
1020 | realTimingFunctions = {
1021 | setTimeout: global.setTimeout,
1022 | clearTimeout: global.clearTimeout,
1023 | setInterval: global.setInterval,
1024 | clearInterval: global.clearInterval
1025 | },
1026 | fakeTimingFunctions = {
1027 | setTimeout: setTimeout,
1028 | clearTimeout: clearTimeout,
1029 | setInterval: setInterval,
1030 | clearInterval: clearInterval
1031 | },
1032 | installed = false,
1033 | timer;
1034 |
1035 |
1036 | self.install = function() {
1037 | replace(global, fakeTimingFunctions);
1038 | timer = fakeTimingFunctions;
1039 | installed = true;
1040 |
1041 | return self;
1042 | };
1043 |
1044 | self.uninstall = function() {
1045 | delayedFunctionScheduler.reset();
1046 | mockDate.uninstall();
1047 | replace(global, realTimingFunctions);
1048 |
1049 | timer = realTimingFunctions;
1050 | installed = false;
1051 | };
1052 |
1053 | self.mockDate = function(initialDate) {
1054 | mockDate.install(initialDate);
1055 | };
1056 |
1057 | self.setTimeout = function(fn, delay, params) {
1058 | if (legacyIE()) {
1059 | if (arguments.length > 2) {
1060 | throw new Error('IE < 9 cannot support extra params to setTimeout without a polyfill');
1061 | }
1062 | return timer.setTimeout(fn, delay);
1063 | }
1064 | return Function.prototype.apply.apply(timer.setTimeout, [global, arguments]);
1065 | };
1066 |
1067 | self.setInterval = function(fn, delay, params) {
1068 | if (legacyIE()) {
1069 | if (arguments.length > 2) {
1070 | throw new Error('IE < 9 cannot support extra params to setInterval without a polyfill');
1071 | }
1072 | return timer.setInterval(fn, delay);
1073 | }
1074 | return Function.prototype.apply.apply(timer.setInterval, [global, arguments]);
1075 | };
1076 |
1077 | self.clearTimeout = function(id) {
1078 | return Function.prototype.call.apply(timer.clearTimeout, [global, id]);
1079 | };
1080 |
1081 | self.clearInterval = function(id) {
1082 | return Function.prototype.call.apply(timer.clearInterval, [global, id]);
1083 | };
1084 |
1085 | self.tick = function(millis) {
1086 | if (installed) {
1087 | mockDate.tick(millis);
1088 | delayedFunctionScheduler.tick(millis);
1089 | } else {
1090 | throw new Error('Mock clock is not installed, use jasmine.clock().install()');
1091 | }
1092 | };
1093 |
1094 | return self;
1095 |
1096 | function legacyIE() {
1097 | //if these methods are polyfilled, apply will be present
1098 | return !(realTimingFunctions.setTimeout || realTimingFunctions.setInterval).apply;
1099 | }
1100 |
1101 | function replace(dest, source) {
1102 | for (var prop in source) {
1103 | dest[prop] = source[prop];
1104 | }
1105 | }
1106 |
1107 | function setTimeout(fn, delay) {
1108 | return delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2));
1109 | }
1110 |
1111 | function clearTimeout(id) {
1112 | return delayedFunctionScheduler.removeFunctionWithId(id);
1113 | }
1114 |
1115 | function setInterval(fn, interval) {
1116 | return delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true);
1117 | }
1118 |
1119 | function clearInterval(id) {
1120 | return delayedFunctionScheduler.removeFunctionWithId(id);
1121 | }
1122 |
1123 | function argSlice(argsObj, n) {
1124 | return Array.prototype.slice.call(argsObj, n);
1125 | }
1126 | }
1127 |
1128 | return Clock;
1129 | };
1130 |
1131 | getJasmineRequireObj().DelayedFunctionScheduler = function() {
1132 | function DelayedFunctionScheduler() {
1133 | var self = this;
1134 | var scheduledLookup = [];
1135 | var scheduledFunctions = {};
1136 | var currentTime = 0;
1137 | var delayedFnCount = 0;
1138 |
1139 | self.tick = function(millis) {
1140 | millis = millis || 0;
1141 | var endTime = currentTime + millis;
1142 |
1143 | runScheduledFunctions(endTime);
1144 | currentTime = endTime;
1145 | };
1146 |
1147 | self.scheduleFunction = function(funcToCall, millis, params, recurring, timeoutKey, runAtMillis) {
1148 | var f;
1149 | if (typeof(funcToCall) === 'string') {
1150 | /* jshint evil: true */
1151 | f = function() { return eval(funcToCall); };
1152 | /* jshint evil: false */
1153 | } else {
1154 | f = funcToCall;
1155 | }
1156 |
1157 | millis = millis || 0;
1158 | timeoutKey = timeoutKey || ++delayedFnCount;
1159 | runAtMillis = runAtMillis || (currentTime + millis);
1160 |
1161 | var funcToSchedule = {
1162 | runAtMillis: runAtMillis,
1163 | funcToCall: f,
1164 | recurring: recurring,
1165 | params: params,
1166 | timeoutKey: timeoutKey,
1167 | millis: millis
1168 | };
1169 |
1170 | if (runAtMillis in scheduledFunctions) {
1171 | scheduledFunctions[runAtMillis].push(funcToSchedule);
1172 | } else {
1173 | scheduledFunctions[runAtMillis] = [funcToSchedule];
1174 | scheduledLookup.push(runAtMillis);
1175 | scheduledLookup.sort(function (a, b) {
1176 | return a - b;
1177 | });
1178 | }
1179 |
1180 | return timeoutKey;
1181 | };
1182 |
1183 | self.removeFunctionWithId = function(timeoutKey) {
1184 | for (var runAtMillis in scheduledFunctions) {
1185 | var funcs = scheduledFunctions[runAtMillis];
1186 | var i = indexOfFirstToPass(funcs, function (func) {
1187 | return func.timeoutKey === timeoutKey;
1188 | });
1189 |
1190 | if (i > -1) {
1191 | if (funcs.length === 1) {
1192 | delete scheduledFunctions[runAtMillis];
1193 | deleteFromLookup(runAtMillis);
1194 | } else {
1195 | funcs.splice(i, 1);
1196 | }
1197 |
1198 | // intervals get rescheduled when executed, so there's never more
1199 | // than a single scheduled function with a given timeoutKey
1200 | break;
1201 | }
1202 | }
1203 | };
1204 |
1205 | self.reset = function() {
1206 | currentTime = 0;
1207 | scheduledLookup = [];
1208 | scheduledFunctions = {};
1209 | delayedFnCount = 0;
1210 | };
1211 |
1212 | return self;
1213 |
1214 | function indexOfFirstToPass(array, testFn) {
1215 | var index = -1;
1216 |
1217 | for (var i = 0; i < array.length; ++i) {
1218 | if (testFn(array[i])) {
1219 | index = i;
1220 | break;
1221 | }
1222 | }
1223 |
1224 | return index;
1225 | }
1226 |
1227 | function deleteFromLookup(key) {
1228 | var value = Number(key);
1229 | var i = indexOfFirstToPass(scheduledLookup, function (millis) {
1230 | return millis === value;
1231 | });
1232 |
1233 | if (i > -1) {
1234 | scheduledLookup.splice(i, 1);
1235 | }
1236 | }
1237 |
1238 | function reschedule(scheduledFn) {
1239 | self.scheduleFunction(scheduledFn.funcToCall,
1240 | scheduledFn.millis,
1241 | scheduledFn.params,
1242 | true,
1243 | scheduledFn.timeoutKey,
1244 | scheduledFn.runAtMillis + scheduledFn.millis);
1245 | }
1246 |
1247 | function runScheduledFunctions(endTime) {
1248 | if (scheduledLookup.length === 0 || scheduledLookup[0] > endTime) {
1249 | return;
1250 | }
1251 |
1252 | do {
1253 | currentTime = scheduledLookup.shift();
1254 |
1255 | var funcsToRun = scheduledFunctions[currentTime];
1256 | delete scheduledFunctions[currentTime];
1257 |
1258 | for (var i = 0; i < funcsToRun.length; ++i) {
1259 | var funcToRun = funcsToRun[i];
1260 |
1261 | if (funcToRun.recurring) {
1262 | reschedule(funcToRun);
1263 | }
1264 |
1265 | funcToRun.funcToCall.apply(null, funcToRun.params || []);
1266 | }
1267 | } while (scheduledLookup.length > 0 &&
1268 | // checking first if we're out of time prevents setTimeout(0)
1269 | // scheduled in a funcToRun from forcing an extra iteration
1270 | currentTime !== endTime &&
1271 | scheduledLookup[0] <= endTime);
1272 | }
1273 | }
1274 |
1275 | return DelayedFunctionScheduler;
1276 | };
1277 |
1278 | getJasmineRequireObj().ExceptionFormatter = function() {
1279 | function ExceptionFormatter() {
1280 | this.message = function(error) {
1281 | var message = '';
1282 |
1283 | if (error.name && error.message) {
1284 | message += error.name + ': ' + error.message;
1285 | } else {
1286 | message += error.toString() + ' thrown';
1287 | }
1288 |
1289 | if (error.fileName || error.sourceURL) {
1290 | message += ' in ' + (error.fileName || error.sourceURL);
1291 | }
1292 |
1293 | if (error.line || error.lineNumber) {
1294 | message += ' (line ' + (error.line || error.lineNumber) + ')';
1295 | }
1296 |
1297 | return message;
1298 | };
1299 |
1300 | this.stack = function(error) {
1301 | return error ? error.stack : null;
1302 | };
1303 | }
1304 |
1305 | return ExceptionFormatter;
1306 | };
1307 |
1308 | getJasmineRequireObj().Expectation = function() {
1309 |
1310 | function Expectation(options) {
1311 | this.util = options.util || { buildFailureMessage: function() {} };
1312 | this.customEqualityTesters = options.customEqualityTesters || [];
1313 | this.actual = options.actual;
1314 | this.addExpectationResult = options.addExpectationResult || function(){};
1315 | this.isNot = options.isNot;
1316 |
1317 | var customMatchers = options.customMatchers || {};
1318 | for (var matcherName in customMatchers) {
1319 | this[matcherName] = Expectation.prototype.wrapCompare(matcherName, customMatchers[matcherName]);
1320 | }
1321 | }
1322 |
1323 | Expectation.prototype.wrapCompare = function(name, matcherFactory) {
1324 | return function() {
1325 | var args = Array.prototype.slice.call(arguments, 0),
1326 | expected = args.slice(0),
1327 | message = '';
1328 |
1329 | args.unshift(this.actual);
1330 |
1331 | var matcher = matcherFactory(this.util, this.customEqualityTesters),
1332 | matcherCompare = matcher.compare;
1333 |
1334 | function defaultNegativeCompare() {
1335 | var result = matcher.compare.apply(null, args);
1336 | result.pass = !result.pass;
1337 | return result;
1338 | }
1339 |
1340 | if (this.isNot) {
1341 | matcherCompare = matcher.negativeCompare || defaultNegativeCompare;
1342 | }
1343 |
1344 | var result = matcherCompare.apply(null, args);
1345 |
1346 | if (!result.pass) {
1347 | if (!result.message) {
1348 | args.unshift(this.isNot);
1349 | args.unshift(name);
1350 | message = this.util.buildFailureMessage.apply(null, args);
1351 | } else {
1352 | if (Object.prototype.toString.apply(result.message) === '[object Function]') {
1353 | message = result.message();
1354 | } else {
1355 | message = result.message;
1356 | }
1357 | }
1358 | }
1359 |
1360 | if (expected.length == 1) {
1361 | expected = expected[0];
1362 | }
1363 |
1364 | // TODO: how many of these params are needed?
1365 | this.addExpectationResult(
1366 | result.pass,
1367 | {
1368 | matcherName: name,
1369 | passed: result.pass,
1370 | message: message,
1371 | actual: this.actual,
1372 | expected: expected // TODO: this may need to be arrayified/sliced
1373 | }
1374 | );
1375 | };
1376 | };
1377 |
1378 | Expectation.addCoreMatchers = function(matchers) {
1379 | var prototype = Expectation.prototype;
1380 | for (var matcherName in matchers) {
1381 | var matcher = matchers[matcherName];
1382 | prototype[matcherName] = prototype.wrapCompare(matcherName, matcher);
1383 | }
1384 | };
1385 |
1386 | Expectation.Factory = function(options) {
1387 | options = options || {};
1388 |
1389 | var expect = new Expectation(options);
1390 |
1391 | // TODO: this would be nice as its own Object - NegativeExpectation
1392 | // TODO: copy instead of mutate options
1393 | options.isNot = true;
1394 | expect.not = new Expectation(options);
1395 |
1396 | return expect;
1397 | };
1398 |
1399 | return Expectation;
1400 | };
1401 |
1402 | //TODO: expectation result may make more sense as a presentation of an expectation.
1403 | getJasmineRequireObj().buildExpectationResult = function() {
1404 | function buildExpectationResult(options) {
1405 | var messageFormatter = options.messageFormatter || function() {},
1406 | stackFormatter = options.stackFormatter || function() {};
1407 |
1408 | var result = {
1409 | matcherName: options.matcherName,
1410 | message: message(),
1411 | stack: stack(),
1412 | passed: options.passed
1413 | };
1414 |
1415 | if(!result.passed) {
1416 | result.expected = options.expected;
1417 | result.actual = options.actual;
1418 | }
1419 |
1420 | return result;
1421 |
1422 | function message() {
1423 | if (options.passed) {
1424 | return 'Passed.';
1425 | } else if (options.message) {
1426 | return options.message;
1427 | } else if (options.error) {
1428 | return messageFormatter(options.error);
1429 | }
1430 | return '';
1431 | }
1432 |
1433 | function stack() {
1434 | if (options.passed) {
1435 | return '';
1436 | }
1437 |
1438 | var error = options.error;
1439 | if (!error) {
1440 | try {
1441 | throw new Error(message());
1442 | } catch (e) {
1443 | error = e;
1444 | }
1445 | }
1446 | return stackFormatter(error);
1447 | }
1448 | }
1449 |
1450 | return buildExpectationResult;
1451 | };
1452 |
1453 | getJasmineRequireObj().MockDate = function() {
1454 | function MockDate(global) {
1455 | var self = this;
1456 | var currentTime = 0;
1457 |
1458 | if (!global || !global.Date) {
1459 | self.install = function() {};
1460 | self.tick = function() {};
1461 | self.uninstall = function() {};
1462 | return self;
1463 | }
1464 |
1465 | var GlobalDate = global.Date;
1466 |
1467 | self.install = function(mockDate) {
1468 | if (mockDate instanceof GlobalDate) {
1469 | currentTime = mockDate.getTime();
1470 | } else {
1471 | currentTime = new GlobalDate().getTime();
1472 | }
1473 |
1474 | global.Date = FakeDate;
1475 | };
1476 |
1477 | self.tick = function(millis) {
1478 | millis = millis || 0;
1479 | currentTime = currentTime + millis;
1480 | };
1481 |
1482 | self.uninstall = function() {
1483 | currentTime = 0;
1484 | global.Date = GlobalDate;
1485 | };
1486 |
1487 | createDateProperties();
1488 |
1489 | return self;
1490 |
1491 | function FakeDate() {
1492 | switch(arguments.length) {
1493 | case 0:
1494 | return new GlobalDate(currentTime);
1495 | case 1:
1496 | return new GlobalDate(arguments[0]);
1497 | case 2:
1498 | return new GlobalDate(arguments[0], arguments[1]);
1499 | case 3:
1500 | return new GlobalDate(arguments[0], arguments[1], arguments[2]);
1501 | case 4:
1502 | return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3]);
1503 | case 5:
1504 | return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3],
1505 | arguments[4]);
1506 | case 6:
1507 | return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3],
1508 | arguments[4], arguments[5]);
1509 | case 7:
1510 | return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3],
1511 | arguments[4], arguments[5], arguments[6]);
1512 | }
1513 | }
1514 |
1515 | function createDateProperties() {
1516 | FakeDate.prototype = GlobalDate.prototype;
1517 |
1518 | FakeDate.now = function() {
1519 | if (GlobalDate.now) {
1520 | return currentTime;
1521 | } else {
1522 | throw new Error('Browser does not support Date.now()');
1523 | }
1524 | };
1525 |
1526 | FakeDate.toSource = GlobalDate.toSource;
1527 | FakeDate.toString = GlobalDate.toString;
1528 | FakeDate.parse = GlobalDate.parse;
1529 | FakeDate.UTC = GlobalDate.UTC;
1530 | }
1531 | }
1532 |
1533 | return MockDate;
1534 | };
1535 |
1536 | getJasmineRequireObj().ObjectContaining = function(j$) {
1537 |
1538 | function ObjectContaining(sample) {
1539 | this.sample = sample;
1540 | }
1541 |
1542 | ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) {
1543 | if (typeof(this.sample) !== 'object') { throw new Error('You must provide an object to objectContaining, not \''+this.sample+'\'.'); }
1544 |
1545 | mismatchKeys = mismatchKeys || [];
1546 | mismatchValues = mismatchValues || [];
1547 |
1548 | var hasKey = function(obj, keyName) {
1549 | return obj !== null && !j$.util.isUndefined(obj[keyName]);
1550 | };
1551 |
1552 | for (var property in this.sample) {
1553 | if (!hasKey(other, property) && hasKey(this.sample, property)) {
1554 | mismatchKeys.push('expected has key \'' + property + '\', but missing from actual.');
1555 | }
1556 | else if (!j$.matchersUtil.equals(other[property], this.sample[property])) {
1557 | 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.');
1558 | }
1559 | }
1560 |
1561 | return (mismatchKeys.length === 0 && mismatchValues.length === 0);
1562 | };
1563 |
1564 | ObjectContaining.prototype.jasmineToString = function() {
1565 | return '';
1566 | };
1567 |
1568 | return ObjectContaining;
1569 | };
1570 |
1571 | getJasmineRequireObj().pp = function(j$) {
1572 |
1573 | function PrettyPrinter() {
1574 | this.ppNestLevel_ = 0;
1575 | this.seen = [];
1576 | }
1577 |
1578 | PrettyPrinter.prototype.format = function(value) {
1579 | this.ppNestLevel_++;
1580 | try {
1581 | if (j$.util.isUndefined(value)) {
1582 | this.emitScalar('undefined');
1583 | } else if (value === null) {
1584 | this.emitScalar('null');
1585 | } else if (value === 0 && 1/value === -Infinity) {
1586 | this.emitScalar('-0');
1587 | } else if (value === j$.getGlobal()) {
1588 | this.emitScalar('');
1589 | } else if (value.jasmineToString) {
1590 | this.emitScalar(value.jasmineToString());
1591 | } else if (typeof value === 'string') {
1592 | this.emitString(value);
1593 | } else if (j$.isSpy(value)) {
1594 | this.emitScalar('spy on ' + value.and.identity());
1595 | } else if (value instanceof RegExp) {
1596 | this.emitScalar(value.toString());
1597 | } else if (typeof value === 'function') {
1598 | this.emitScalar('Function');
1599 | } else if (typeof value.nodeType === 'number') {
1600 | this.emitScalar('HTMLNode');
1601 | } else if (value instanceof Date) {
1602 | this.emitScalar('Date(' + value + ')');
1603 | } else if (j$.util.arrayContains(this.seen, value)) {
1604 | this.emitScalar('');
1605 | } else if (j$.isArray_(value) || j$.isA_('Object', value)) {
1606 | this.seen.push(value);
1607 | if (j$.isArray_(value)) {
1608 | this.emitArray(value);
1609 | } else {
1610 | this.emitObject(value);
1611 | }
1612 | this.seen.pop();
1613 | } else {
1614 | this.emitScalar(value.toString());
1615 | }
1616 | } finally {
1617 | this.ppNestLevel_--;
1618 | }
1619 | };
1620 |
1621 | PrettyPrinter.prototype.iterateObject = function(obj, fn) {
1622 | for (var property in obj) {
1623 | if (!Object.prototype.hasOwnProperty.call(obj, property)) { continue; }
1624 | fn(property, obj.__lookupGetter__ ? (!j$.util.isUndefined(obj.__lookupGetter__(property)) &&
1625 | obj.__lookupGetter__(property) !== null) : false);
1626 | }
1627 | };
1628 |
1629 | PrettyPrinter.prototype.emitArray = j$.unimplementedMethod_;
1630 | PrettyPrinter.prototype.emitObject = j$.unimplementedMethod_;
1631 | PrettyPrinter.prototype.emitScalar = j$.unimplementedMethod_;
1632 | PrettyPrinter.prototype.emitString = j$.unimplementedMethod_;
1633 |
1634 | function StringPrettyPrinter() {
1635 | PrettyPrinter.call(this);
1636 |
1637 | this.string = '';
1638 | }
1639 |
1640 | j$.util.inherit(StringPrettyPrinter, PrettyPrinter);
1641 |
1642 | StringPrettyPrinter.prototype.emitScalar = function(value) {
1643 | this.append(value);
1644 | };
1645 |
1646 | StringPrettyPrinter.prototype.emitString = function(value) {
1647 | this.append('\'' + value + '\'');
1648 | };
1649 |
1650 | StringPrettyPrinter.prototype.emitArray = function(array) {
1651 | if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) {
1652 | this.append('Array');
1653 | return;
1654 | }
1655 | var length = Math.min(array.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH);
1656 | this.append('[ ');
1657 | for (var i = 0; i < length; i++) {
1658 | if (i > 0) {
1659 | this.append(', ');
1660 | }
1661 | this.format(array[i]);
1662 | }
1663 | if(array.length > length){
1664 | this.append(', ...');
1665 | }
1666 | this.append(' ]');
1667 | };
1668 |
1669 | StringPrettyPrinter.prototype.emitObject = function(obj) {
1670 | if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) {
1671 | this.append('Object');
1672 | return;
1673 | }
1674 |
1675 | var self = this;
1676 | this.append('{ ');
1677 | var first = true;
1678 |
1679 | this.iterateObject(obj, function(property, isGetter) {
1680 | if (first) {
1681 | first = false;
1682 | } else {
1683 | self.append(', ');
1684 | }
1685 |
1686 | self.append(property);
1687 | self.append(': ');
1688 | if (isGetter) {
1689 | self.append('');
1690 | } else {
1691 | self.format(obj[property]);
1692 | }
1693 | });
1694 |
1695 | this.append(' }');
1696 | };
1697 |
1698 | StringPrettyPrinter.prototype.append = function(value) {
1699 | this.string += value;
1700 | };
1701 |
1702 | return function(value) {
1703 | var stringPrettyPrinter = new StringPrettyPrinter();
1704 | stringPrettyPrinter.format(value);
1705 | return stringPrettyPrinter.string;
1706 | };
1707 | };
1708 |
1709 | getJasmineRequireObj().QueueRunner = function(j$) {
1710 |
1711 | function once(fn) {
1712 | var called = false;
1713 | return function() {
1714 | if (!called) {
1715 | called = true;
1716 | fn();
1717 | }
1718 | };
1719 | }
1720 |
1721 | function QueueRunner(attrs) {
1722 | this.queueableFns = attrs.queueableFns || [];
1723 | this.onComplete = attrs.onComplete || function() {};
1724 | this.clearStack = attrs.clearStack || function(fn) {fn();};
1725 | this.onException = attrs.onException || function() {};
1726 | this.catchException = attrs.catchException || function() { return true; };
1727 | this.userContext = attrs.userContext || {};
1728 | this.timer = attrs.timeout || {setTimeout: setTimeout, clearTimeout: clearTimeout};
1729 | this.fail = attrs.fail || function() {};
1730 | }
1731 |
1732 | QueueRunner.prototype.execute = function() {
1733 | this.run(this.queueableFns, 0);
1734 | };
1735 |
1736 | QueueRunner.prototype.run = function(queueableFns, recursiveIndex) {
1737 | var length = queueableFns.length,
1738 | self = this,
1739 | iterativeIndex;
1740 |
1741 |
1742 | for(iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex++) {
1743 | var queueableFn = queueableFns[iterativeIndex];
1744 | if (queueableFn.fn.length > 0) {
1745 | return attemptAsync(queueableFn);
1746 | } else {
1747 | attemptSync(queueableFn);
1748 | }
1749 | }
1750 |
1751 | var runnerDone = iterativeIndex >= length;
1752 |
1753 | if (runnerDone) {
1754 | this.clearStack(this.onComplete);
1755 | }
1756 |
1757 | function attemptSync(queueableFn) {
1758 | try {
1759 | queueableFn.fn.call(self.userContext);
1760 | } catch (e) {
1761 | handleException(e, queueableFn);
1762 | }
1763 | }
1764 |
1765 | function attemptAsync(queueableFn) {
1766 | var clearTimeout = function () {
1767 | Function.prototype.apply.apply(self.timer.clearTimeout, [j$.getGlobal(), [timeoutId]]);
1768 | },
1769 | next = once(function () {
1770 | clearTimeout(timeoutId);
1771 | self.run(queueableFns, iterativeIndex + 1);
1772 | }),
1773 | timeoutId;
1774 |
1775 | next.fail = function() {
1776 | self.fail.apply(null, arguments);
1777 | next();
1778 | };
1779 |
1780 | if (queueableFn.timeout) {
1781 | timeoutId = Function.prototype.apply.apply(self.timer.setTimeout, [j$.getGlobal(), [function() {
1782 | var error = new Error('Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.');
1783 | onException(error, queueableFn);
1784 | next();
1785 | }, queueableFn.timeout()]]);
1786 | }
1787 |
1788 | try {
1789 | queueableFn.fn.call(self.userContext, next);
1790 | } catch (e) {
1791 | handleException(e, queueableFn);
1792 | next();
1793 | }
1794 | }
1795 |
1796 | function onException(e, queueableFn) {
1797 | self.onException(e);
1798 | }
1799 |
1800 | function handleException(e, queueableFn) {
1801 | onException(e, queueableFn);
1802 | if (!self.catchException(e)) {
1803 | //TODO: set a var when we catch an exception and
1804 | //use a finally block to close the loop in a nice way..
1805 | throw e;
1806 | }
1807 | }
1808 | };
1809 |
1810 | return QueueRunner;
1811 | };
1812 |
1813 | getJasmineRequireObj().ReportDispatcher = function() {
1814 | function ReportDispatcher(methods) {
1815 |
1816 | var dispatchedMethods = methods || [];
1817 |
1818 | for (var i = 0; i < dispatchedMethods.length; i++) {
1819 | var method = dispatchedMethods[i];
1820 | this[method] = (function(m) {
1821 | return function() {
1822 | dispatch(m, arguments);
1823 | };
1824 | }(method));
1825 | }
1826 |
1827 | var reporters = [];
1828 |
1829 | this.addReporter = function(reporter) {
1830 | reporters.push(reporter);
1831 | };
1832 |
1833 | return this;
1834 |
1835 | function dispatch(method, args) {
1836 | for (var i = 0; i < reporters.length; i++) {
1837 | var reporter = reporters[i];
1838 | if (reporter[method]) {
1839 | reporter[method].apply(reporter, args);
1840 | }
1841 | }
1842 | }
1843 | }
1844 |
1845 | return ReportDispatcher;
1846 | };
1847 |
1848 |
1849 | getJasmineRequireObj().SpyRegistry = function(j$) {
1850 |
1851 | function SpyRegistry(options) {
1852 | options = options || {};
1853 | var currentSpies = options.currentSpies || function() { return []; };
1854 |
1855 | this.spyOn = function(obj, methodName) {
1856 | if (j$.util.isUndefined(obj)) {
1857 | throw new Error('spyOn could not find an object to spy upon for ' + methodName + '()');
1858 | }
1859 |
1860 | if (j$.util.isUndefined(obj[methodName])) {
1861 | throw new Error(methodName + '() method does not exist');
1862 | }
1863 |
1864 | if (obj[methodName] && j$.isSpy(obj[methodName])) {
1865 | //TODO?: should this return the current spy? Downside: may cause user confusion about spy state
1866 | throw new Error(methodName + ' has already been spied upon');
1867 | }
1868 |
1869 | var spy = j$.createSpy(methodName, obj[methodName]);
1870 |
1871 | currentSpies().push({
1872 | spy: spy,
1873 | baseObj: obj,
1874 | methodName: methodName,
1875 | originalValue: obj[methodName]
1876 | });
1877 |
1878 | obj[methodName] = spy;
1879 |
1880 | return spy;
1881 | };
1882 |
1883 | this.clearSpies = function() {
1884 | var spies = currentSpies();
1885 | for (var i = 0; i < spies.length; i++) {
1886 | var spyEntry = spies[i];
1887 | spyEntry.baseObj[spyEntry.methodName] = spyEntry.originalValue;
1888 | }
1889 | };
1890 | }
1891 |
1892 | return SpyRegistry;
1893 | };
1894 |
1895 | getJasmineRequireObj().SpyStrategy = function() {
1896 |
1897 | function SpyStrategy(options) {
1898 | options = options || {};
1899 |
1900 | var identity = options.name || 'unknown',
1901 | originalFn = options.fn || function() {},
1902 | getSpy = options.getSpy || function() {},
1903 | plan = function() {};
1904 |
1905 | this.identity = function() {
1906 | return identity;
1907 | };
1908 |
1909 | this.exec = function() {
1910 | return plan.apply(this, arguments);
1911 | };
1912 |
1913 | this.callThrough = function() {
1914 | plan = originalFn;
1915 | return getSpy();
1916 | };
1917 |
1918 | this.returnValue = function(value) {
1919 | plan = function() {
1920 | return value;
1921 | };
1922 | return getSpy();
1923 | };
1924 |
1925 | this.returnValues = function() {
1926 | var values = Array.prototype.slice.call(arguments);
1927 | plan = function () {
1928 | return values.shift();
1929 | };
1930 | return getSpy();
1931 | };
1932 |
1933 | this.throwError = function(something) {
1934 | var error = (something instanceof Error) ? something : new Error(something);
1935 | plan = function() {
1936 | throw error;
1937 | };
1938 | return getSpy();
1939 | };
1940 |
1941 | this.callFake = function(fn) {
1942 | plan = fn;
1943 | return getSpy();
1944 | };
1945 |
1946 | this.stub = function(fn) {
1947 | plan = function() {};
1948 | return getSpy();
1949 | };
1950 | }
1951 |
1952 | return SpyStrategy;
1953 | };
1954 |
1955 | getJasmineRequireObj().Suite = function() {
1956 | function Suite(attrs) {
1957 | this.env = attrs.env;
1958 | this.id = attrs.id;
1959 | this.parentSuite = attrs.parentSuite;
1960 | this.description = attrs.description;
1961 | this.onStart = attrs.onStart || function() {};
1962 | this.resultCallback = attrs.resultCallback || function() {};
1963 | this.clearStack = attrs.clearStack || function(fn) {fn();};
1964 | this.expectationFactory = attrs.expectationFactory;
1965 | this.expectationResultFactory = attrs.expectationResultFactory;
1966 |
1967 | this.beforeFns = [];
1968 | this.afterFns = [];
1969 | this.beforeAllFns = [];
1970 | this.afterAllFns = [];
1971 | this.queueRunner = attrs.queueRunner || function() {};
1972 | this.disabled = false;
1973 |
1974 | this.children = [];
1975 |
1976 | this.result = {
1977 | id: this.id,
1978 | description: this.description,
1979 | fullName: this.getFullName(),
1980 | failedExpectations: []
1981 | };
1982 | }
1983 |
1984 | Suite.prototype.expect = function(actual) {
1985 | return this.expectationFactory(actual, this);
1986 | };
1987 |
1988 | Suite.prototype.getFullName = function() {
1989 | var fullName = this.description;
1990 | for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) {
1991 | if (parentSuite.parentSuite) {
1992 | fullName = parentSuite.description + ' ' + fullName;
1993 | }
1994 | }
1995 | return fullName;
1996 | };
1997 |
1998 | Suite.prototype.disable = function() {
1999 | this.disabled = true;
2000 | };
2001 |
2002 | Suite.prototype.beforeEach = function(fn) {
2003 | this.beforeFns.unshift(fn);
2004 | };
2005 |
2006 | Suite.prototype.beforeAll = function(fn) {
2007 | this.beforeAllFns.push(fn);
2008 | };
2009 |
2010 | Suite.prototype.afterEach = function(fn) {
2011 | this.afterFns.unshift(fn);
2012 | };
2013 |
2014 | Suite.prototype.afterAll = function(fn) {
2015 | this.afterAllFns.push(fn);
2016 | };
2017 |
2018 | Suite.prototype.addChild = function(child) {
2019 | this.children.push(child);
2020 | };
2021 |
2022 | Suite.prototype.status = function() {
2023 | if (this.disabled) {
2024 | return 'disabled';
2025 | }
2026 |
2027 | if (this.result.failedExpectations.length > 0) {
2028 | return 'failed';
2029 | } else {
2030 | return 'finished';
2031 | }
2032 | };
2033 |
2034 | Suite.prototype.execute = function(onComplete) {
2035 | var self = this;
2036 |
2037 | this.onStart(this);
2038 |
2039 | if (this.disabled) {
2040 | complete();
2041 | return;
2042 | }
2043 |
2044 | var allFns = [];
2045 |
2046 | for (var i = 0; i < this.children.length; i++) {
2047 | allFns.push(wrapChildAsAsync(this.children[i]));
2048 | }
2049 |
2050 | if (this.isExecutable()) {
2051 | allFns = this.beforeAllFns.concat(allFns);
2052 | allFns = allFns.concat(this.afterAllFns);
2053 | }
2054 |
2055 | this.queueRunner({
2056 | queueableFns: allFns,
2057 | onComplete: complete,
2058 | userContext: this.sharedUserContext(),
2059 | onException: function() { self.onException.apply(self, arguments); }
2060 | });
2061 |
2062 | function complete() {
2063 | self.result.status = self.status();
2064 | self.resultCallback(self.result);
2065 |
2066 | if (onComplete) {
2067 | onComplete();
2068 | }
2069 | }
2070 |
2071 | function wrapChildAsAsync(child) {
2072 | return { fn: function(done) { child.execute(done); } };
2073 | }
2074 | };
2075 |
2076 | Suite.prototype.isExecutable = function() {
2077 | var foundActive = false;
2078 | for(var i = 0; i < this.children.length; i++) {
2079 | if(this.children[i].isExecutable()) {
2080 | foundActive = true;
2081 | break;
2082 | }
2083 | }
2084 | return foundActive;
2085 | };
2086 |
2087 | Suite.prototype.sharedUserContext = function() {
2088 | if (!this.sharedContext) {
2089 | this.sharedContext = this.parentSuite ? clone(this.parentSuite.sharedUserContext()) : {};
2090 | }
2091 |
2092 | return this.sharedContext;
2093 | };
2094 |
2095 | Suite.prototype.clonedSharedUserContext = function() {
2096 | return clone(this.sharedUserContext());
2097 | };
2098 |
2099 | Suite.prototype.onException = function() {
2100 | if(isAfterAll(this.children)) {
2101 | var data = {
2102 | matcherName: '',
2103 | passed: false,
2104 | expected: '',
2105 | actual: '',
2106 | error: arguments[0]
2107 | };
2108 | this.result.failedExpectations.push(this.expectationResultFactory(data));
2109 | } else {
2110 | for (var i = 0; i < this.children.length; i++) {
2111 | var child = this.children[i];
2112 | child.onException.apply(child, arguments);
2113 | }
2114 | }
2115 | };
2116 |
2117 | Suite.prototype.addExpectationResult = function () {
2118 | if(isAfterAll(this.children) && isFailure(arguments)){
2119 | var data = arguments[1];
2120 | this.result.failedExpectations.push(this.expectationResultFactory(data));
2121 | } else {
2122 | for (var i = 0; i < this.children.length; i++) {
2123 | var child = this.children[i];
2124 | child.addExpectationResult.apply(child, arguments);
2125 | }
2126 | }
2127 | };
2128 |
2129 | function isAfterAll(children) {
2130 | return children && children[0].result.status;
2131 | }
2132 |
2133 | function isFailure(args) {
2134 | return !args[0];
2135 | }
2136 |
2137 | function clone(obj) {
2138 | var clonedObj = {};
2139 | for (var prop in obj) {
2140 | if (obj.hasOwnProperty(prop)) {
2141 | clonedObj[prop] = obj[prop];
2142 | }
2143 | }
2144 |
2145 | return clonedObj;
2146 | }
2147 |
2148 | return Suite;
2149 | };
2150 |
2151 | if (typeof window == void 0 && typeof exports == 'object') {
2152 | exports.Suite = jasmineRequire.Suite;
2153 | }
2154 |
2155 | getJasmineRequireObj().Timer = function() {
2156 | var defaultNow = (function(Date) {
2157 | return function() { return new Date().getTime(); };
2158 | })(Date);
2159 |
2160 | function Timer(options) {
2161 | options = options || {};
2162 |
2163 | var now = options.now || defaultNow,
2164 | startTime;
2165 |
2166 | this.start = function() {
2167 | startTime = now();
2168 | };
2169 |
2170 | this.elapsed = function() {
2171 | return now() - startTime;
2172 | };
2173 | }
2174 |
2175 | return Timer;
2176 | };
2177 |
2178 | getJasmineRequireObj().matchersUtil = function(j$) {
2179 | // TODO: what to do about jasmine.pp not being inject? move to JSON.stringify? gut PrettyPrinter?
2180 |
2181 | return {
2182 | equals: function(a, b, customTesters) {
2183 | customTesters = customTesters || [];
2184 |
2185 | return eq(a, b, [], [], customTesters);
2186 | },
2187 |
2188 | contains: function(haystack, needle, customTesters) {
2189 | customTesters = customTesters || [];
2190 |
2191 | if ((Object.prototype.toString.apply(haystack) === '[object Array]') ||
2192 | (!!haystack && !haystack.indexOf))
2193 | {
2194 | for (var i = 0; i < haystack.length; i++) {
2195 | if (eq(haystack[i], needle, [], [], customTesters)) {
2196 | return true;
2197 | }
2198 | }
2199 | return false;
2200 | }
2201 |
2202 | return !!haystack && haystack.indexOf(needle) >= 0;
2203 | },
2204 |
2205 | buildFailureMessage: function() {
2206 | var args = Array.prototype.slice.call(arguments, 0),
2207 | matcherName = args[0],
2208 | isNot = args[1],
2209 | actual = args[2],
2210 | expected = args.slice(3),
2211 | englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); });
2212 |
2213 | var message = 'Expected ' +
2214 | j$.pp(actual) +
2215 | (isNot ? ' not ' : ' ') +
2216 | englishyPredicate;
2217 |
2218 | if (expected.length > 0) {
2219 | for (var i = 0; i < expected.length; i++) {
2220 | if (i > 0) {
2221 | message += ',';
2222 | }
2223 | message += ' ' + j$.pp(expected[i]);
2224 | }
2225 | }
2226 |
2227 | return message + '.';
2228 | }
2229 | };
2230 |
2231 | // Equality function lovingly adapted from isEqual in
2232 | // [Underscore](http://underscorejs.org)
2233 | function eq(a, b, aStack, bStack, customTesters) {
2234 | var result = true;
2235 |
2236 | for (var i = 0; i < customTesters.length; i++) {
2237 | var customTesterResult = customTesters[i](a, b);
2238 | if (!j$.util.isUndefined(customTesterResult)) {
2239 | return customTesterResult;
2240 | }
2241 | }
2242 |
2243 | if (a instanceof j$.Any) {
2244 | result = a.jasmineMatches(b);
2245 | if (result) {
2246 | return true;
2247 | }
2248 | }
2249 |
2250 | if (b instanceof j$.Any) {
2251 | result = b.jasmineMatches(a);
2252 | if (result) {
2253 | return true;
2254 | }
2255 | }
2256 |
2257 | if (b instanceof j$.ObjectContaining) {
2258 | result = b.jasmineMatches(a);
2259 | if (result) {
2260 | return true;
2261 | }
2262 | }
2263 |
2264 | if (a instanceof Error && b instanceof Error) {
2265 | return a.message == b.message;
2266 | }
2267 |
2268 | // Identical objects are equal. `0 === -0`, but they aren't identical.
2269 | // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
2270 | if (a === b) { return a !== 0 || 1 / a == 1 / b; }
2271 | // A strict comparison is necessary because `null == undefined`.
2272 | if (a === null || b === null) { return a === b; }
2273 | var className = Object.prototype.toString.call(a);
2274 | if (className != Object.prototype.toString.call(b)) { return false; }
2275 | switch (className) {
2276 | // Strings, numbers, dates, and booleans are compared by value.
2277 | case '[object String]':
2278 | // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
2279 | // equivalent to `new String("5")`.
2280 | return a == String(b);
2281 | case '[object Number]':
2282 | // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
2283 | // other numeric values.
2284 | return a != +a ? b != +b : (a === 0 ? 1 / a == 1 / b : a == +b);
2285 | case '[object Date]':
2286 | case '[object Boolean]':
2287 | // Coerce dates and booleans to numeric primitive values. Dates are compared by their
2288 | // millisecond representations. Note that invalid dates with millisecond representations
2289 | // of `NaN` are not equivalent.
2290 | return +a == +b;
2291 | // RegExps are compared by their source patterns and flags.
2292 | case '[object RegExp]':
2293 | return a.source == b.source &&
2294 | a.global == b.global &&
2295 | a.multiline == b.multiline &&
2296 | a.ignoreCase == b.ignoreCase;
2297 | }
2298 | if (typeof a != 'object' || typeof b != 'object') { return false; }
2299 | // Assume equality for cyclic structures. The algorithm for detecting cyclic
2300 | // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
2301 | var length = aStack.length;
2302 | while (length--) {
2303 | // Linear search. Performance is inversely proportional to the number of
2304 | // unique nested structures.
2305 | if (aStack[length] == a) { return bStack[length] == b; }
2306 | }
2307 | // Add the first object to the stack of traversed objects.
2308 | aStack.push(a);
2309 | bStack.push(b);
2310 | var size = 0;
2311 | // Recursively compare objects and arrays.
2312 | if (className == '[object Array]') {
2313 | // Compare array lengths to determine if a deep comparison is necessary.
2314 | size = a.length;
2315 | result = size == b.length;
2316 | if (result) {
2317 | // Deep compare the contents, ignoring non-numeric properties.
2318 | while (size--) {
2319 | if (!(result = eq(a[size], b[size], aStack, bStack, customTesters))) { break; }
2320 | }
2321 | }
2322 | } else {
2323 | // Objects with different constructors are not equivalent, but `Object`s
2324 | // from different frames are.
2325 | var aCtor = a.constructor, bCtor = b.constructor;
2326 | if (aCtor !== bCtor && !(isFunction(aCtor) && (aCtor instanceof aCtor) &&
2327 | isFunction(bCtor) && (bCtor instanceof bCtor))) {
2328 | return false;
2329 | }
2330 | // Deep compare objects.
2331 | for (var key in a) {
2332 | if (has(a, key)) {
2333 | // Count the expected number of properties.
2334 | size++;
2335 | // Deep compare each member.
2336 | if (!(result = has(b, key) && eq(a[key], b[key], aStack, bStack, customTesters))) { break; }
2337 | }
2338 | }
2339 | // Ensure that both objects contain the same number of properties.
2340 | if (result) {
2341 | for (key in b) {
2342 | if (has(b, key) && !(size--)) { break; }
2343 | }
2344 | result = !size;
2345 | }
2346 | }
2347 | // Remove the first object from the stack of traversed objects.
2348 | aStack.pop();
2349 | bStack.pop();
2350 |
2351 | return result;
2352 |
2353 | function has(obj, key) {
2354 | return obj.hasOwnProperty(key);
2355 | }
2356 |
2357 | function isFunction(obj) {
2358 | return typeof obj === 'function';
2359 | }
2360 | }
2361 | };
2362 |
2363 | getJasmineRequireObj().toBe = function() {
2364 | function toBe() {
2365 | return {
2366 | compare: function(actual, expected) {
2367 | return {
2368 | pass: actual === expected
2369 | };
2370 | }
2371 | };
2372 | }
2373 |
2374 | return toBe;
2375 | };
2376 |
2377 | getJasmineRequireObj().toBeCloseTo = function() {
2378 |
2379 | function toBeCloseTo() {
2380 | return {
2381 | compare: function(actual, expected, precision) {
2382 | if (precision !== 0) {
2383 | precision = precision || 2;
2384 | }
2385 |
2386 | return {
2387 | pass: Math.abs(expected - actual) < (Math.pow(10, -precision) / 2)
2388 | };
2389 | }
2390 | };
2391 | }
2392 |
2393 | return toBeCloseTo;
2394 | };
2395 |
2396 | getJasmineRequireObj().toBeDefined = function() {
2397 | function toBeDefined() {
2398 | return {
2399 | compare: function(actual) {
2400 | return {
2401 | pass: (void 0 !== actual)
2402 | };
2403 | }
2404 | };
2405 | }
2406 |
2407 | return toBeDefined;
2408 | };
2409 |
2410 | getJasmineRequireObj().toBeFalsy = function() {
2411 | function toBeFalsy() {
2412 | return {
2413 | compare: function(actual) {
2414 | return {
2415 | pass: !!!actual
2416 | };
2417 | }
2418 | };
2419 | }
2420 |
2421 | return toBeFalsy;
2422 | };
2423 |
2424 | getJasmineRequireObj().toBeGreaterThan = function() {
2425 |
2426 | function toBeGreaterThan() {
2427 | return {
2428 | compare: function(actual, expected) {
2429 | return {
2430 | pass: actual > expected
2431 | };
2432 | }
2433 | };
2434 | }
2435 |
2436 | return toBeGreaterThan;
2437 | };
2438 |
2439 |
2440 | getJasmineRequireObj().toBeLessThan = function() {
2441 | function toBeLessThan() {
2442 | return {
2443 |
2444 | compare: function(actual, expected) {
2445 | return {
2446 | pass: actual < expected
2447 | };
2448 | }
2449 | };
2450 | }
2451 |
2452 | return toBeLessThan;
2453 | };
2454 | getJasmineRequireObj().toBeNaN = function(j$) {
2455 |
2456 | function toBeNaN() {
2457 | return {
2458 | compare: function(actual) {
2459 | var result = {
2460 | pass: (actual !== actual)
2461 | };
2462 |
2463 | if (result.pass) {
2464 | result.message = 'Expected actual not to be NaN.';
2465 | } else {
2466 | result.message = function() { return 'Expected ' + j$.pp(actual) + ' to be NaN.'; };
2467 | }
2468 |
2469 | return result;
2470 | }
2471 | };
2472 | }
2473 |
2474 | return toBeNaN;
2475 | };
2476 |
2477 | getJasmineRequireObj().toBeNull = function() {
2478 |
2479 | function toBeNull() {
2480 | return {
2481 | compare: function(actual) {
2482 | return {
2483 | pass: actual === null
2484 | };
2485 | }
2486 | };
2487 | }
2488 |
2489 | return toBeNull;
2490 | };
2491 |
2492 | getJasmineRequireObj().toBeTruthy = function() {
2493 |
2494 | function toBeTruthy() {
2495 | return {
2496 | compare: function(actual) {
2497 | return {
2498 | pass: !!actual
2499 | };
2500 | }
2501 | };
2502 | }
2503 |
2504 | return toBeTruthy;
2505 | };
2506 |
2507 | getJasmineRequireObj().toBeUndefined = function() {
2508 |
2509 | function toBeUndefined() {
2510 | return {
2511 | compare: function(actual) {
2512 | return {
2513 | pass: void 0 === actual
2514 | };
2515 | }
2516 | };
2517 | }
2518 |
2519 | return toBeUndefined;
2520 | };
2521 |
2522 | getJasmineRequireObj().toContain = function() {
2523 | function toContain(util, customEqualityTesters) {
2524 | customEqualityTesters = customEqualityTesters || [];
2525 |
2526 | return {
2527 | compare: function(actual, expected) {
2528 |
2529 | return {
2530 | pass: util.contains(actual, expected, customEqualityTesters)
2531 | };
2532 | }
2533 | };
2534 | }
2535 |
2536 | return toContain;
2537 | };
2538 |
2539 | getJasmineRequireObj().toEqual = function() {
2540 |
2541 | function toEqual(util, customEqualityTesters) {
2542 | customEqualityTesters = customEqualityTesters || [];
2543 |
2544 | return {
2545 | compare: function(actual, expected) {
2546 | var result = {
2547 | pass: false
2548 | };
2549 |
2550 | result.pass = util.equals(actual, expected, customEqualityTesters);
2551 |
2552 | return result;
2553 | }
2554 | };
2555 | }
2556 |
2557 | return toEqual;
2558 | };
2559 |
2560 | getJasmineRequireObj().toHaveBeenCalled = function(j$) {
2561 |
2562 | function toHaveBeenCalled() {
2563 | return {
2564 | compare: function(actual) {
2565 | var result = {};
2566 |
2567 | if (!j$.isSpy(actual)) {
2568 | throw new Error('Expected a spy, but got ' + j$.pp(actual) + '.');
2569 | }
2570 |
2571 | if (arguments.length > 1) {
2572 | throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith');
2573 | }
2574 |
2575 | result.pass = actual.calls.any();
2576 |
2577 | result.message = result.pass ?
2578 | 'Expected spy ' + actual.and.identity() + ' not to have been called.' :
2579 | 'Expected spy ' + actual.and.identity() + ' to have been called.';
2580 |
2581 | return result;
2582 | }
2583 | };
2584 | }
2585 |
2586 | return toHaveBeenCalled;
2587 | };
2588 |
2589 | getJasmineRequireObj().toHaveBeenCalledWith = function(j$) {
2590 |
2591 | function toHaveBeenCalledWith(util, customEqualityTesters) {
2592 | return {
2593 | compare: function() {
2594 | var args = Array.prototype.slice.call(arguments, 0),
2595 | actual = args[0],
2596 | expectedArgs = args.slice(1),
2597 | result = { pass: false };
2598 |
2599 | if (!j$.isSpy(actual)) {
2600 | throw new Error('Expected a spy, but got ' + j$.pp(actual) + '.');
2601 | }
2602 |
2603 | if (!actual.calls.any()) {
2604 | result.message = function() { return 'Expected spy ' + actual.and.identity() + ' to have been called with ' + j$.pp(expectedArgs) + ' but it was never called.'; };
2605 | return result;
2606 | }
2607 |
2608 | if (util.contains(actual.calls.allArgs(), expectedArgs, customEqualityTesters)) {
2609 | result.pass = true;
2610 | result.message = function() { return 'Expected spy ' + actual.and.identity() + ' not to have been called with ' + j$.pp(expectedArgs) + ' but it was.'; };
2611 | } else {
2612 | result.message = function() { return 'Expected spy ' + actual.and.identity() + ' to have been called with ' + j$.pp(expectedArgs) + ' but actual calls were ' + j$.pp(actual.calls.allArgs()).replace(/^\[ | \]$/g, '') + '.'; };
2613 | }
2614 |
2615 | return result;
2616 | }
2617 | };
2618 | }
2619 |
2620 | return toHaveBeenCalledWith;
2621 | };
2622 |
2623 | getJasmineRequireObj().toMatch = function() {
2624 |
2625 | function toMatch() {
2626 | return {
2627 | compare: function(actual, expected) {
2628 | var regexp = new RegExp(expected);
2629 |
2630 | return {
2631 | pass: regexp.test(actual)
2632 | };
2633 | }
2634 | };
2635 | }
2636 |
2637 | return toMatch;
2638 | };
2639 |
2640 | getJasmineRequireObj().toThrow = function(j$) {
2641 |
2642 | function toThrow(util) {
2643 | return {
2644 | compare: function(actual, expected) {
2645 | var result = { pass: false },
2646 | threw = false,
2647 | thrown;
2648 |
2649 | if (typeof actual != 'function') {
2650 | throw new Error('Actual is not a Function');
2651 | }
2652 |
2653 | try {
2654 | actual();
2655 | } catch (e) {
2656 | threw = true;
2657 | thrown = e;
2658 | }
2659 |
2660 | if (!threw) {
2661 | result.message = 'Expected function to throw an exception.';
2662 | return result;
2663 | }
2664 |
2665 | if (arguments.length == 1) {
2666 | result.pass = true;
2667 | result.message = function() { return 'Expected function not to throw, but it threw ' + j$.pp(thrown) + '.'; };
2668 |
2669 | return result;
2670 | }
2671 |
2672 | if (util.equals(thrown, expected)) {
2673 | result.pass = true;
2674 | result.message = function() { return 'Expected function not to throw ' + j$.pp(expected) + '.'; };
2675 | } else {
2676 | result.message = function() { return 'Expected function to throw ' + j$.pp(expected) + ', but it threw ' + j$.pp(thrown) + '.'; };
2677 | }
2678 |
2679 | return result;
2680 | }
2681 | };
2682 | }
2683 |
2684 | return toThrow;
2685 | };
2686 |
2687 | getJasmineRequireObj().toThrowError = function(j$) {
2688 | function toThrowError (util) {
2689 | return {
2690 | compare: function(actual) {
2691 | var threw = false,
2692 | pass = {pass: true},
2693 | fail = {pass: false},
2694 | thrown;
2695 |
2696 | if (typeof actual != 'function') {
2697 | throw new Error('Actual is not a Function');
2698 | }
2699 |
2700 | var errorMatcher = getMatcher.apply(null, arguments);
2701 |
2702 | try {
2703 | actual();
2704 | } catch (e) {
2705 | threw = true;
2706 | thrown = e;
2707 | }
2708 |
2709 | if (!threw) {
2710 | fail.message = 'Expected function to throw an Error.';
2711 | return fail;
2712 | }
2713 |
2714 | if (!(thrown instanceof Error)) {
2715 | fail.message = function() { return 'Expected function to throw an Error, but it threw ' + j$.pp(thrown) + '.'; };
2716 | return fail;
2717 | }
2718 |
2719 | if (errorMatcher.hasNoSpecifics()) {
2720 | pass.message = 'Expected function not to throw an Error, but it threw ' + fnNameFor(thrown) + '.';
2721 | return pass;
2722 | }
2723 |
2724 | if (errorMatcher.matches(thrown)) {
2725 | pass.message = function() {
2726 | return 'Expected function not to throw ' + errorMatcher.errorTypeDescription + errorMatcher.messageDescription() + '.';
2727 | };
2728 | return pass;
2729 | } else {
2730 | fail.message = function() {
2731 | return 'Expected function to throw ' + errorMatcher.errorTypeDescription + errorMatcher.messageDescription() +
2732 | ', but it threw ' + errorMatcher.thrownDescription(thrown) + '.';
2733 | };
2734 | return fail;
2735 | }
2736 | }
2737 | };
2738 |
2739 | function getMatcher() {
2740 | var expected = null,
2741 | errorType = null;
2742 |
2743 | if (arguments.length == 2) {
2744 | expected = arguments[1];
2745 | if (isAnErrorType(expected)) {
2746 | errorType = expected;
2747 | expected = null;
2748 | }
2749 | } else if (arguments.length > 2) {
2750 | errorType = arguments[1];
2751 | expected = arguments[2];
2752 | if (!isAnErrorType(errorType)) {
2753 | throw new Error('Expected error type is not an Error.');
2754 | }
2755 | }
2756 |
2757 | if (expected && !isStringOrRegExp(expected)) {
2758 | if (errorType) {
2759 | throw new Error('Expected error message is not a string or RegExp.');
2760 | } else {
2761 | throw new Error('Expected is not an Error, string, or RegExp.');
2762 | }
2763 | }
2764 |
2765 | function messageMatch(message) {
2766 | if (typeof expected == 'string') {
2767 | return expected == message;
2768 | } else {
2769 | return expected.test(message);
2770 | }
2771 | }
2772 |
2773 | return {
2774 | errorTypeDescription: errorType ? fnNameFor(errorType) : 'an exception',
2775 | thrownDescription: function(thrown) {
2776 | var thrownName = errorType ? fnNameFor(thrown.constructor) : 'an exception',
2777 | thrownMessage = '';
2778 |
2779 | if (expected) {
2780 | thrownMessage = ' with message ' + j$.pp(thrown.message);
2781 | }
2782 |
2783 | return thrownName + thrownMessage;
2784 | },
2785 | messageDescription: function() {
2786 | if (expected === null) {
2787 | return '';
2788 | } else if (expected instanceof RegExp) {
2789 | return ' with a message matching ' + j$.pp(expected);
2790 | } else {
2791 | return ' with message ' + j$.pp(expected);
2792 | }
2793 | },
2794 | hasNoSpecifics: function() {
2795 | return expected === null && errorType === null;
2796 | },
2797 | matches: function(error) {
2798 | return (errorType === null || error.constructor === errorType) &&
2799 | (expected === null || messageMatch(error.message));
2800 | }
2801 | };
2802 | }
2803 |
2804 | function fnNameFor(func) {
2805 | return func.name || func.toString().match(/^\s*function\s*(\w*)\s*\(/)[1];
2806 | }
2807 |
2808 | function isStringOrRegExp(potential) {
2809 | return potential instanceof RegExp || (typeof potential == 'string');
2810 | }
2811 |
2812 | function isAnErrorType(type) {
2813 | if (typeof type !== 'function') {
2814 | return false;
2815 | }
2816 |
2817 | var Surrogate = function() {};
2818 | Surrogate.prototype = type.prototype;
2819 | return (new Surrogate()) instanceof Error;
2820 | }
2821 | }
2822 |
2823 | return toThrowError;
2824 | };
2825 |
2826 | getJasmineRequireObj().interface = function(jasmine, env) {
2827 | var jasmineInterface = {
2828 | describe: function(description, specDefinitions) {
2829 | return env.describe(description, specDefinitions);
2830 | },
2831 |
2832 | xdescribe: function(description, specDefinitions) {
2833 | return env.xdescribe(description, specDefinitions);
2834 | },
2835 |
2836 | fdescribe: function(description, specDefinitions) {
2837 | return env.fdescribe(description, specDefinitions);
2838 | },
2839 |
2840 | it: function(desc, func) {
2841 | return env.it(desc, func);
2842 | },
2843 |
2844 | xit: function(desc, func) {
2845 | return env.xit(desc, func);
2846 | },
2847 |
2848 | fit: function(desc, func) {
2849 | return env.fit(desc, func);
2850 | },
2851 |
2852 | beforeEach: function(beforeEachFunction) {
2853 | return env.beforeEach(beforeEachFunction);
2854 | },
2855 |
2856 | afterEach: function(afterEachFunction) {
2857 | return env.afterEach(afterEachFunction);
2858 | },
2859 |
2860 | beforeAll: function(beforeAllFunction) {
2861 | return env.beforeAll(beforeAllFunction);
2862 | },
2863 |
2864 | afterAll: function(afterAllFunction) {
2865 | return env.afterAll(afterAllFunction);
2866 | },
2867 |
2868 | expect: function(actual) {
2869 | return env.expect(actual);
2870 | },
2871 |
2872 | pending: function() {
2873 | return env.pending();
2874 | },
2875 |
2876 | fail: function() {
2877 | return env.fail.apply(env, arguments);
2878 | },
2879 |
2880 | spyOn: function(obj, methodName) {
2881 | return env.spyOn(obj, methodName);
2882 | },
2883 |
2884 | jsApiReporter: new jasmine.JsApiReporter({
2885 | timer: new jasmine.Timer()
2886 | }),
2887 |
2888 | jasmine: jasmine
2889 | };
2890 |
2891 | jasmine.addCustomEqualityTester = function(tester) {
2892 | env.addCustomEqualityTester(tester);
2893 | };
2894 |
2895 | jasmine.addMatchers = function(matchers) {
2896 | return env.addMatchers(matchers);
2897 | };
2898 |
2899 | jasmine.clock = function() {
2900 | return env.clock;
2901 | };
2902 |
2903 | return jasmineInterface;
2904 | };
2905 |
2906 | getJasmineRequireObj().version = function() {
2907 | return '2.1.3';
2908 | };
2909 |
--------------------------------------------------------------------------------
/test/lib/jasmine-2.1.3/jasmine_favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rafaeleyng/weborm/44191d4f77fe630fee1aa65cd69ee3d853df0b45/test/lib/jasmine-2.1.3/jasmine_favicon.png
--------------------------------------------------------------------------------
/test/spec/LocalStorageHelpersSpec.js:
--------------------------------------------------------------------------------
1 | describe('LocalStorage Helpers', function() {
2 |
3 |
4 | var weborm;
5 | var storage;
6 | var schema = {
7 | _Base: {
8 | attrs: ['id'],
9 | },
10 | Country: {
11 | attrs: ['name', 'abbr'],
12 | }
13 | };
14 | var config = {
15 | pluralization: {
16 | Country: 'Countries'
17 | }
18 | };
19 |
20 | beforeEach(function() {
21 | weborm = new WebORM(schema, config);
22 | storage = weborm.storage;
23 | storage.clean();
24 | });
25 |
26 | afterAll(function() {
27 | storage.clean();
28 | });
29 |
30 | it('should be able to clean localStorage', function() {
31 | localStorage.setItem('someKey', 'someValue');
32 | expect(localStorage.length).toEqual(1);
33 | storage.clean();
34 | expect(localStorage.length).toEqual(0);
35 | });
36 |
37 | it('should generate an unique key for each record based on entity name + id', function() {
38 | expect(storage._helpers.genKey('Country', 1)).toEqual('Country_1');
39 | });
40 |
41 | });
42 |
--------------------------------------------------------------------------------
/test/spec/LocalStorageSpec.js:
--------------------------------------------------------------------------------
1 | describe('LocalStorage', function() {
2 |
3 | var ENTITY = 'Country';
4 | var ID = 1;
5 |
6 | var weborm;
7 | var storage;
8 | var schema = {
9 | _Base: {
10 | attrs: ['id'],
11 | },
12 | Country: {
13 | attrs: ['name', 'abbr'],
14 | }
15 | };
16 | var config = {
17 | pluralization: {
18 | Country: 'Countries'
19 | }
20 | };
21 |
22 | beforeEach(function() {
23 | weborm = new WebORM(schema, config);
24 | storage = weborm.storage;
25 | storage.clean();
26 | });
27 |
28 | afterAll(function() {
29 | storage.clean();
30 | });
31 |
32 | it('should be defined', function() {
33 | expect(storage).toBeDefined();
34 | });
35 |
36 | it('should save object to local storage and create index for the entity', function() {
37 | expect(localStorage.length).toEqual(0);
38 | storage.save(ENTITY, {id: ID});
39 | expect(localStorage.length).toEqual(3);
40 | expect(localStorage[storage._helpers.genKey(ENTITY, ID)]).toBeDefined();
41 | var entityIndex = localStorage[ENTITY];
42 | expect(entityIndex).toBeDefined();
43 | expect(entityIndex.split('_').length).toEqual(1);
44 | });
45 |
46 | it('should override objects of same entity with same id when saving', function() {
47 | expect(localStorage.length).toEqual(0);
48 | var moreThanOnce = 2;
49 | for (var i = 0; i < moreThanOnce; i++) {
50 | storage.save(ENTITY, {id: ID});
51 | }
52 | expect(localStorage.length).toEqual(3);
53 | expect(localStorage[ENTITY].split('_').length).toEqual(1);
54 | });
55 |
56 | it('shouldn\'t find objects not previously saved', function() {
57 | expect(storage.find(ENTITY, ID)).toBeUndefined();
58 | });
59 |
60 | it('should find objects previously saved', function() {
61 | storage.save(ENTITY, {id: ID});
62 | expect(storage.find(ENTITY, ID)).toBeDefined();
63 | });
64 |
65 | it('should find the first object of a given entity', function() {
66 | storage.save(ENTITY, {id: ID});
67 | storage.save(ENTITY, {id: ID+1});
68 | storage.save(ENTITY, {id: ID+2});
69 | expect(storage.first(ENTITY).id).toEqual(ID);
70 | });
71 |
72 | it('should find the first object of a given entity', function() {
73 | storage.save(ENTITY, {id: ID});
74 | storage.save(ENTITY, {id: ID+1});
75 | storage.save(ENTITY, {id: ID+2});
76 | expect(storage.last(ENTITY).id).toEqual(ID+2);
77 | });
78 |
79 | it('should count records of a given entity', function() {
80 | var aNumberOfRecords = 6;
81 | for (var i = 0; i < aNumberOfRecords; i++) {
82 | storage.save(ENTITY, {id: i+1});
83 | }
84 | expect(storage.count(ENTITY)).toEqual(aNumberOfRecords);
85 | expect(storage.count(ENTITY)).toEqual(storage.all(ENTITY).length);
86 | });
87 |
88 | it('should retrieve all records of a given entity', function() {
89 | var aNumberOfRecords = 10;
90 | for (var i = 0; i < aNumberOfRecords; i++) {
91 | storage.save(ENTITY, {id: i+1});
92 | }
93 | expect(storage.all(ENTITY).length).toEqual(aNumberOfRecords);
94 | });
95 |
96 | it('should retrieve any page of the records of a given entity', function() {
97 | var pageSize = 5;
98 | var numberOfPages = 3;
99 | var someNumberSmallerThanPageSize = pageSize - 1
100 | var aNumberOfRecords = (pageSize * numberOfPages) - someNumberSmallerThanPageSize;
101 |
102 | for (var i = 0; i < aNumberOfRecords; i++) {
103 | storage.save(ENTITY, {id: i+1});
104 | }
105 |
106 | for (var pageNumber = 0; pageNumber < numberOfPages; pageNumber++) {
107 | if (pageNumber === numberOfPages - 1) {
108 | expect(storage.page(ENTITY, pageNumber, pageSize).length).toEqual(pageSize - someNumberSmallerThanPageSize);
109 | } else {
110 | expect(storage.page(ENTITY, pageNumber, pageSize).length).toEqual(pageSize);
111 | }
112 | }
113 | });
114 |
115 | it('should filter the records of a given entity by any property', function() {
116 | storage.save(ENTITY, {id: 1, name: 'Brazil', abbr: 'BR'});
117 | storage.save(ENTITY, {id: 2, name: 'Brazil', abbr: 'BRA'});
118 | storage.save(ENTITY, {id: 3, name: 'Peru', abbr: 'PE'});
119 | expect(storage.count(ENTITY)).toEqual(3);
120 | expect(storage.filter(ENTITY, function(data) { return data.name === 'Brazil'}).length).toEqual(2);
121 | expect(storage.filter(ENTITY, function(data) { return data.name === 'Brazil' && data.abbr === 'BR'}).length).toEqual(1);
122 | expect(storage.filter(ENTITY, function(data) { return data.name === 'Peru'}).length).toEqual(1);
123 | });
124 |
125 | it('should be able to delete a record', function() {
126 | storage.save(ENTITY, {id: ID});
127 | expect(storage.count(ENTITY)).toEqual(1);
128 | storage.save(ENTITY, {id: ID+1});
129 | expect(storage.count(ENTITY)).toEqual(2);
130 | storage.delete(ENTITY, ID);
131 | expect(storage.count(ENTITY)).toEqual(1);
132 | storage.delete(ENTITY, ID+1);
133 | expect(storage.count(ENTITY)).toEqual(0);
134 | });
135 |
136 | });
137 |
--------------------------------------------------------------------------------
/test/spec/WebORMHelpersSpec.js:
--------------------------------------------------------------------------------
1 | describe('WebORM Helpers', function() {
2 |
3 | var weborm;
4 | var schema = {
5 | _Base: {
6 | attrs: ['id'],
7 | },
8 | Country: {
9 | attrs: ['name', 'abbr'],
10 | },
11 | State: {
12 | attrs: ['name', 'abbr'],
13 | relsToOne: ['Country'],
14 | }
15 | };
16 | var config = {
17 | pluralization: {
18 | Country: 'Countries'
19 | }
20 | };
21 |
22 | beforeAll(function() {
23 | weborm = new WebORM(schema, config);
24 | });
25 |
26 | it('should handle pluralization', function() {
27 | expect(weborm._pluralize('State')).toEqual('States');
28 | expect(weborm._pluralize('Country')).toEqual('Countries');
29 | });
30 |
31 | it('should identify the type of an object', function() {
32 | expect(weborm._typeOf(0)).toEqual('Number');
33 | expect(weborm._typeOf(NaN)).toEqual('Number');
34 | expect(weborm._typeOf('')).toEqual('String');
35 | expect(weborm._typeOf(undefined)).toEqual('Undefined');
36 | expect(weborm._typeOf(null)).toEqual('Null');
37 | expect(weborm._typeOf(function(){})).toEqual('Function');
38 | expect(weborm._typeOf([])).toEqual('Array');
39 | expect(weborm._typeOf({})).toEqual('Object');
40 | });
41 |
42 | it('should idenfity collections', function() {
43 | expect(weborm._isCollection([])).toBeTruthy();
44 | expect(weborm._isCollection([1,2,3])).toBeTruthy();
45 | expect(weborm._isCollection(new Array())).toBeTruthy();
46 |
47 | expect(weborm._isCollection({})).toBeFalsy();
48 | expect(weborm._isCollection(1)).toBeFalsy();
49 | expect(weborm._isCollection('a')).toBeFalsy();
50 | expect(weborm._isCollection(null)).toBeFalsy();
51 | expect(weborm._isCollection(undefined)).toBeFalsy();
52 | });
53 |
54 | it('should be able to make collections out of both objects and collections', function() {
55 | expect(weborm._makeCollection(1).length).toEqual(1);
56 | expect(weborm._makeCollection('a').length).toEqual(1);
57 | expect(weborm._makeCollection({}).length).toEqual(1);
58 |
59 | expect(weborm._makeCollection([]).length).toEqual(0);
60 | expect(weborm._makeCollection([1]).length).toEqual(1);
61 | expect(weborm._makeCollection([1,2,3]).length).toEqual(3);
62 | });
63 |
64 | it('should lowercase the first letter of a string', function() {
65 | expect(weborm._lcFirst('ANything')).toEqual('aNything');
66 | expect(weborm._lcFirst('anything')).toEqual('anything');
67 | });
68 |
69 | it('should uppercase the first letter of a string', function() {
70 | expect(weborm._ucFirst('ANything')).toEqual('ANything');
71 | expect(weborm._ucFirst('anything')).toEqual('Anything');
72 | });
73 |
74 | it('should generate an unique key for each record based on entity name + id', function() {
75 | expect(weborm._genKey('Country', 1)).toEqual('Country_1');
76 | });
77 |
78 | it('should filter data for an object based on its entity schema', function() {
79 | var dirtyData = {name: 'Brazil', someProperty: 'some value'};
80 | var filteredData = weborm._filterData('Country', dirtyData);
81 | expect(filteredData.name).toBeDefined();
82 | expect(filteredData.someProperty).toBeUndefined();
83 | });
84 |
85 | });
86 |
--------------------------------------------------------------------------------
/test/spec/WebORMRelationshipSpec.js:
--------------------------------------------------------------------------------
1 | describe('WebORM relationships', function() {
2 |
3 | var weborm;
4 | var storage;
5 | var schema = {
6 | _Base: {
7 | attrs: ['name']
8 | },
9 | Country: {
10 | attrs: ['abbr']
11 | },
12 | State: {
13 | attrs: ['abbr'],
14 | relsToOne: ['Country']
15 | },
16 | City: {
17 | relsToOne: ['State'],
18 | relsToMany: ['Service']
19 | },
20 | Service: {}
21 | };
22 |
23 | var config = {
24 | pluralization: {
25 | Country: 'Countries',
26 | City: 'Cities'
27 | }
28 | };
29 |
30 | var ENTITY = 'Country';
31 | var ID = 1;
32 |
33 | beforeEach(function() {
34 | weborm = new WebORM(schema, config);
35 | weborm.storage.clean();
36 | });
37 |
38 | afterAll(function() {
39 | weborm.storage.clean();
40 | });
41 |
42 | it('should persist a relationship', function() {
43 | var brazil = weborm.save('Country', {name:'Brazil'});
44 | var rs = weborm.save('State', {name:'Rio Grande do Sul', _countryId: brazil.id});
45 |
46 | expect(rs.Country).toBeDefined();
47 | expect(rs.countryId).toBeDefined();
48 | });
49 |
50 | it('should relate two objects when creating a new object passing the relationship id', function() {
51 | var brazil = weborm.save('Country', {name:'Brazil'});
52 | var rs = weborm.save('State', {name:'Rio Grande do Sul', _countryId: brazil.id});
53 |
54 | expect(rs.Country).toEqual(brazil);
55 | });
56 |
57 | it('should relate two objects by setting the relationship id', function() {
58 | var brazil = weborm.save('Country', {name:'Brazil'});
59 | var rs = weborm.save('State', {name:'Rio Grande do Sul'});
60 |
61 | rs.countryId = brazil.id;
62 | expect(rs.Country).toEqual(brazil);
63 | });
64 |
65 | it('should relate two objects by setting the relationship object', function() {
66 | var brazil = weborm.save('Country', {name:'Brazil'});
67 | var rs = weborm.save('State', {name:'Rio Grande do Sul'});
68 |
69 | rs.Country = brazil;
70 | expect(rs.countryId).toEqual(brazil.id);
71 | });
72 |
73 | it('should hold a single object instantiated for a record, even when used in a relationship', function() {
74 | var brazil = weborm.save('Country', {name:'Brazil'});
75 | var rs = weborm.save('State', {name:'Rio Grande do Sul', _countryId: brazil.id});
76 | var sc = weborm.save('State', {name:'Santa Catarina', _countryId: brazil.id});
77 |
78 | expect(rs.Country).toEqual(sc.Country);
79 | });
80 |
81 | it('should maintain a relationship deeper than 1 level', function() {
82 | var brazil = weborm.save('Country', {name:'Brazil'});
83 | var rs = weborm.save('State', {name:'Rio Grande do Sul', _countryId: brazil.id});
84 | var feliz = weborm.save('City', {name:'Feliz', _stateId: rs.id});
85 |
86 | expect(feliz.State.Country).toEqual(brazil);
87 | });
88 |
89 | it('should hold a single object instantiated for a record, even when used in a deeper relationship', function() {
90 | var brazil = weborm.save('Country', {name:'Brazil'});
91 | var rs = weborm.save('State', {name:'Rio Grande do Sul', _countryId: brazil.id});
92 | var feliz = weborm.save('City', {name:'Feliz', _stateId: rs.id});
93 | var sc = weborm.save('State', {name:'Santa Catarina', _countryId: brazil.id});
94 | var florianopolis = weborm.save('City', {name:'Florianópolis', _stateId: sc.id});
95 |
96 | expect(rs.Country).toEqual(sc.Country);
97 | expect(rs.Country).toEqual(feliz.State.Country);
98 | expect(feliz.State.Country).toEqual(florianopolis.State.Country);
99 |
100 | var newCountryName = 'Brasil';
101 | feliz.State.Country.name = newCountryName;
102 | expect(florianopolis.State.Country.name).toEqual(newCountryName);
103 | });
104 |
105 | it('should keep the inverse relationships', function() {
106 | var brazil = weborm.save('Country', {name:'Brazil'});
107 |
108 | var rs = weborm.save('State', {name:'Rio Grande do Sul', _countryId: brazil.id});
109 | var sc = weborm.save('State', {name:'Santa Catarina', _countryId: brazil.id});
110 | expect(brazil.States.length).toEqual(2);
111 |
112 | var feliz = weborm.save('City', {name:'Feliz', _stateId: rs.id});
113 | var saoLeopoldo = weborm.save('City', {name:'São Leopoldo', _stateId: rs.id});
114 | var portoAlegre = weborm.save('City', {name:'Porto Alegre', _stateId: rs.id});
115 | expect(rs.Cities.length).toEqual(3);
116 |
117 | var florianopolis = weborm.save('City', {name:'Florianópolis', _stateId: sc.id});
118 | var garopaba = weborm.save('City', {name:'Garopaba', _stateId: sc.id});
119 | expect(sc.Cities.length).toEqual(2);
120 | });
121 |
122 | it('should handle `1 to many` relationships', function() {
123 | var restaurant = weborm.save('Service', {name:'Restaurant'});
124 | var shoppingCenter = weborm.save('Service', {name:'Shopping Center'});
125 | var skatepark = weborm.save('Service', {name:'Skatepark'});
126 |
127 | var feliz = weborm.save('City', {name:'Feliz', _servicesId:[restaurant.id]});
128 | expect(feliz.Services.length).toEqual(1);
129 |
130 | var saoLeopoldoServicesIds = [restaurant.id, shoppingCenter.id];
131 | var saoLeopoldo = weborm.save('City', {name:'São Leopoldo', _servicesId:saoLeopoldoServicesIds});
132 | expect(saoLeopoldo.Services.length).toEqual(saoLeopoldoServicesIds.length);
133 |
134 | var portoAlegreServicesIds = [restaurant.id, shoppingCenter.id, skatepark.id];
135 | var portoAlegre = weborm.save('City', {name:'Porto Alegre', _servicesId:portoAlegreServicesIds});
136 | expect(portoAlegre.Services.length).toEqual(portoAlegreServicesIds.length);
137 | });
138 |
139 | it('should make `1 to many` relationships by setting the relation id', function() {
140 | var restaurant = weborm.save('Service', {name:'Restaurant'});
141 | var feliz = weborm.save('City', {name:'Feliz', _servicesId:[restaurant.id]});
142 |
143 | expect(feliz.Services[0]).toEqual(restaurant);
144 | });
145 |
146 | it('should add and remove `1 to many` relationships', function() {
147 | var restaurant = weborm.save('Service', {name:'Restaurant'});
148 | var feliz = weborm.save('City', {name:'Feliz'});
149 |
150 | expect(feliz.Services.length).toEqual(0);
151 | weborm.addTo(restaurant, feliz);
152 | expect(feliz.Services.length).toEqual(1);
153 | expect(feliz.Services[0]).toEqual(restaurant);
154 |
155 | weborm.removeFrom(restaurant, feliz);
156 | expect(feliz.Services.length).toEqual(0);
157 | expect(feliz.Services[0]).toBeUndefined();
158 | });
159 |
160 | });
161 |
--------------------------------------------------------------------------------
/test/spec/WebORMSelfRelationshipSpec.js:
--------------------------------------------------------------------------------
1 | describe('WebORM self relationships', function() {
2 |
3 | var weborm;
4 | var storage;
5 | var schema = {
6 | Node: {
7 | attrs: ['content'],
8 | relsToOne: ['Node']
9 | },
10 | };
11 |
12 | beforeEach(function() {
13 | weborm = new WebORM(schema);
14 | weborm.storage.clean();
15 | });
16 |
17 | afterAll(function() {
18 | weborm.storage.clean();
19 | });
20 |
21 | it('should handle self relationships `to one`', function() {
22 | var root = weborm.save('Node', {content:'A'});
23 | var child = weborm.save('Node', {content:'B', _nodeId: root.id});
24 |
25 | expect(child.Node).toEqual(root);
26 | expect(child.nodeId).toEqual(root.id);
27 | });
28 |
29 | it('should handle the inverse of self relationships `to one`', function() {
30 | var root = weborm.save('Node', {content:'A'});
31 |
32 | var numberOfRootChilds = 10;
33 | for (var i = 0; i < 10; i++) {
34 | weborm.save('Node', {content:'B' + i, _nodeId: root.id});
35 | }
36 |
37 | expect(root.Nodes.length).toEqual(numberOfRootChilds);
38 |
39 | weborm.save('Node', {content:'C', _nodeId: root.Nodes[0].id});
40 | expect(root.Nodes[0].Nodes.length).toEqual(1);
41 | expect(root.Nodes.length).toEqual(numberOfRootChilds);
42 | });
43 |
44 | });
45 |
--------------------------------------------------------------------------------
/test/spec/WebORMSpec.js:
--------------------------------------------------------------------------------
1 | describe('WebORM', function() {
2 |
3 | var weborm;
4 | var storage;
5 | var schema = {
6 | _Base: new WebORM.SchemaEntity(['name']),
7 | Country: new WebORM.SchemaEntity(['abbr']),
8 | State: new WebORM.SchemaEntity(['abbr'], ['Country']),
9 | City: new WebORM.SchemaEntity([], ['State'])
10 | };
11 |
12 | var config = {
13 | pluralization: {
14 | Country: 'Countries',
15 | City: 'Cities'
16 | }
17 | };
18 |
19 | var ENTITY = 'Country';
20 | var ID = 1;
21 |
22 | beforeEach(function() {
23 | weborm = new WebORM(schema, config);
24 | weborm.storage.clean();
25 | });
26 |
27 | afterAll(function() {
28 | weborm.storage.clean();
29 | });
30 |
31 | it('should be defined', function() {
32 | expect(weborm).toBeDefined();
33 | });
34 |
35 | it('should create new object', function() {
36 | var country = weborm.save('Country', {name: 'country'});
37 | expect(country).toBeDefined();
38 | });
39 |
40 | it('should generate an id to a new object', function() {
41 | var country = weborm.save('Country', {name: 'country'});
42 | expect(country.id).toBeDefined();
43 | });
44 |
45 | it('should save to/read from client storage', function() {
46 | var savedObject = weborm.save('Country', { name: 'country'});
47 | expect(weborm.find('Country', savedObject.id)).toBeDefined();
48 | });
49 |
50 | it('should not find object with invalid id', function() {
51 | var invalidId = -1;
52 | expect(weborm.find('Country', invalidId)).toBeUndefined();
53 | });
54 |
55 | it('shouldn\'t allow to change the id', function() {
56 | var country = weborm.save('Country', {name: 'country'});
57 | var id = country.id;
58 | expect(id).toBeDefined();
59 | country.id = -1;
60 | expect(country.id).toEqual(id);
61 | });
62 |
63 | it('should filter properties not in the schema', function() {
64 | var country = weborm.save('Country', {name: 'country', propNotInSchema: 'any value'});
65 | expect(country.propNotInSchema).toBeUndefined();
66 | });
67 |
68 | it('entities should inherit properties from the base entity', function() {
69 | var name = 'country';
70 | var country = weborm.save('Country', {name: name, propNotInSchema: 'any value'});
71 | expect(country.name).toBeDefined();
72 | expect(country.propNotInSchema).toBeUndefined();
73 | });
74 |
75 | it('should tell whether two WebORM objects reffer to the same record', function() {
76 | var country1 = weborm.save('Country', {name: 'Brazil'});
77 | var country1Found = weborm.find('Country', country1.id);
78 | var country2 = weborm.save('Country', {name: 'Peru'});
79 | var country2Found = weborm.find('Country', country2.id);
80 | var state1 = weborm.save('State', {name: 'Rio Grande do Sul'});
81 |
82 | expect(weborm.same(country1, country1Found)).toBeTruthy();
83 | expect(weborm.same(country2, country2Found)).toBeTruthy();
84 |
85 | expect(weborm.same(country1, country2)).toBeFalsy();
86 | expect(weborm.same(country1, state1)).toBeFalsy();
87 | });
88 |
89 | it('should keep objects in context and return always the same instance for a record', function() {
90 | var country1 = weborm.save('Country', {name: 'Brazil'});
91 | var country1Found = weborm.find('Country', country1.id);
92 | expect(country1).toEqual(country1Found);
93 |
94 | var state1 = weborm.save('State', {name: 'Rio Grande do Sul'});
95 | state1.Country = country1;
96 | state1.save();
97 | var state1Found = weborm.find('State', state1.id);
98 | expect(country1).toEqual(state1Found.Country);
99 | });
100 |
101 | it('should tell whether two WebORM objects are equal', function() {
102 | var brazil = weborm.save('Country', {name: 'Brazil', abbr: 'BR'});
103 | var brazil2 = weborm.save('Country', {name: 'Brazil', abbr: 'BRA'});
104 | var brasil = weborm.save('Country', {name: 'Brasil', abbr: 'BR'});
105 | var sc = weborm.save('State', {name: 'Santa Catarina'});
106 |
107 | expect(weborm.equals(brazil, brazil)).toBeTruthy();
108 | expect(weborm.equals(brazil, brasil)).toBeFalsy();
109 | expect(weborm.equals(brazil, brazil2)).toBeFalsy();
110 | expect(weborm.equals(brazil, sc)).toBeFalsy();
111 | // TODO test relationships?
112 | // TODO does this 'equals' method really have a point for existing?
113 | });
114 |
115 | it('should find objects previously saved', function() {
116 | weborm.save(ENTITY, {id: ID});
117 | expect(weborm.find(ENTITY, ID)).toBeDefined();
118 | });
119 |
120 | it('should find the first object of a given entity', function() {
121 | weborm.save(ENTITY, {id: ID});
122 | weborm.save(ENTITY, {id: ID+1});
123 | weborm.save(ENTITY, {id: ID+2});
124 | expect(weborm.first(ENTITY).id).toEqual(ID);
125 | });
126 |
127 | it('should find the last object of a given entity', function() {
128 | weborm.save(ENTITY, {id: ID});
129 | weborm.save(ENTITY, {id: ID+1});
130 | weborm.save(ENTITY, {id: ID+2});
131 | expect(weborm.last(ENTITY).id).toEqual(ID+2);
132 | });
133 |
134 | it('should count records of a given entity', function() {
135 | var aNumberOfRecords = 6;
136 | for (var i = 0; i < aNumberOfRecords; i++) {
137 | weborm.save(ENTITY, {id: i+1});
138 | }
139 | expect(weborm.count(ENTITY)).toEqual(aNumberOfRecords);
140 | expect(weborm.count(ENTITY)).toEqual(weborm.all(ENTITY).length);
141 | });
142 |
143 | it('should retrieve all records of a given entity', function() {
144 | var aNumberOfRecords = 10;
145 | for (var i = 0; i < aNumberOfRecords; i++) {
146 | weborm.save(ENTITY, {id: i+1});
147 | }
148 | expect(weborm.all(ENTITY).length).toEqual(aNumberOfRecords);
149 | });
150 |
151 | it('should retrieve any page of the records of a given entity', function() {
152 | var pageSize = 5;
153 | var numberOfPages = 3;
154 | var someNumberSmallerThanPageSize = pageSize - 1
155 | var aNumberOfRecords = (pageSize * numberOfPages) - someNumberSmallerThanPageSize;
156 |
157 | for (var i = 0; i < aNumberOfRecords; i++) {
158 | weborm.save(ENTITY, {id: i+1});
159 | }
160 |
161 | for (var pageNumber = 0; pageNumber < numberOfPages; pageNumber++) {
162 | if (pageNumber === numberOfPages - 1) {
163 | expect(weborm.page(ENTITY, pageNumber, pageSize).length).toEqual(pageSize - someNumberSmallerThanPageSize);
164 | } else {
165 | expect(weborm.page(ENTITY, pageNumber, pageSize).length).toEqual(pageSize);
166 | }
167 | }
168 | });
169 |
170 | it('should filter the records of a given entity by any property', function() {
171 | weborm.save(ENTITY, {name: 'Brazil', abbr: 'BR'});
172 | weborm.save(ENTITY, {name: 'Brazil', abbr: 'BRA'});
173 | weborm.save(ENTITY, {name: 'Peru', abbr: 'PE'});
174 | expect(weborm.count(ENTITY)).toEqual(3);
175 | expect(weborm.filter(ENTITY, function(data) { return data.name === 'Brazil'}).length).toEqual(2);
176 | expect(weborm.filter(ENTITY, function(data) { return data.name === 'Brazil' && data.abbr === 'BR'}).length).toEqual(1);
177 | expect(weborm.filter(ENTITY, function(data) { return data.name === 'Peru'}).length).toEqual(1);
178 | });
179 |
180 | it('should be able to delete records', function() {
181 | weborm.save(ENTITY);
182 | expect(weborm.count(ENTITY)).toEqual(1);
183 | weborm.save(ENTITY);
184 | expect(weborm.count(ENTITY)).toEqual(2);
185 |
186 | weborm.delete(ENTITY, ID);
187 | expect(weborm.count(ENTITY)).toEqual(1);
188 | weborm.delete(ENTITY, ID+1);
189 | expect(weborm.count(ENTITY)).toEqual(0);
190 | });
191 |
192 | it('should save a bunch of objects', function() {
193 | var data = [
194 | {name: 'Brazil'},
195 | {name: 'Uruguay'},
196 | {name: 'Argentina'},
197 | {name: 'Chile'}
198 | ];
199 | var dataLength = data.length;
200 | var countries = weborm.save('Country', data);
201 |
202 | expect(countries.length).toEqual(dataLength);
203 | expect(weborm.count('Country')).toEqual(dataLength);
204 | expect(weborm.all('Country').length).toEqual(dataLength);
205 | });
206 |
207 | it('should delete object when delete function is called on the object itself', function() {
208 | var obj = weborm.save(ENTITY, {name: 'Brazil'});
209 | expect(weborm.count(ENTITY)).toEqual(1);
210 | obj.delete();
211 | expect(weborm.count(ENTITY)).toEqual(0);
212 | });
213 |
214 | it('should maintain a sequential id for each entity', function() {
215 | var aNumberOfRecords = 5;
216 | for (var i = 0; i < aNumberOfRecords; i++) {
217 | weborm.save(ENTITY, {name: 'country'});
218 | }
219 |
220 | var count = weborm.count(ENTITY);
221 | expect(count).toEqual(aNumberOfRecords);
222 |
223 | var all = weborm.all(ENTITY);
224 | var lastId = all[count - 1].id;
225 |
226 | for (var i in all) {
227 | all[i].delete();
228 | }
229 | expect(weborm.count(ENTITY)).toEqual(0);
230 |
231 | var lastSaved = weborm.save(ENTITY, {name: 'country'});
232 | expect(lastSaved.id).toEqual(lastId + 1);
233 | });
234 |
235 | it('should tell wheter a record exists', function(){
236 | var br = weborm.save('Country', {name: 'Brazil'});
237 | var es = weborm.save('State', {name: 'Espírito Santo'});
238 |
239 | expect(weborm.exists('Country', br.id)).toBeTruthy();
240 | expect(weborm.exists('State', es.id)).toBeTruthy();
241 |
242 | expect(weborm.exists('Country', 2)).toBeFalsy();
243 | expect(weborm.exists('State', 3)).toBeFalsy();
244 | });
245 |
246 | it('shouldn\'t allow to set the id when creating a record', function() {
247 | weborm.save('City', {name:'Paris', id: 2});
248 | weborm.save('City', {name:'Nice', id: 4});
249 |
250 | var cities = weborm.all('City');
251 | expect(cities[0].id).toEqual(1);
252 | expect(cities[1].id).toEqual(2);
253 | });
254 |
255 | it('should allow to set the id when updating a record', function() {
256 | var santiago = weborm.save('City', {name:'Santiago', id: 2});
257 | var vina = weborm.save('City', {name:'Viña', id: 4});
258 |
259 | expect(weborm.count('City')).toEqual(2);
260 | expect(vina.id).toEqual(2);
261 |
262 | var newName = 'Viña del Mar';
263 | weborm.save('City', {name: newName, id: vina.id});
264 | expect(weborm.count('City')).toEqual(2);
265 | expect(weborm.find('City', 2).name).toEqual(newName);
266 | });
267 |
268 | it('should retain all attributes after setting an relationship', function() {
269 | var country1 = weborm.save('Country', {name:'Brazil'});
270 | var state1 = weborm.save('State', {name:'Rio Grande do Sul', abbr:'RS'});
271 |
272 | state1.Country = country1;
273 | state1.save();
274 |
275 | var state1Found = weborm.find('State', state1.id);
276 | expect(state1).toEqual(state1Found);
277 | expect(state1.name).toEqual(state1Found.name);
278 | expect(state1.abbr).toEqual(state1Found.abbr);
279 | });
280 |
281 | it('should keep objects in context consistent after modifying their attributes and relationships', function() {
282 | var br = weborm.save('Country', {name:'Brasil'});
283 | var para = weborm.save('State', {name:'Para'});
284 | para.Country = br;
285 | para.save();
286 | var paraFound = weborm.find('State', para.id);
287 |
288 | var newStateName = 'Pará';
289 | paraFound.name = newStateName;
290 |
291 | expect(para).toEqual(paraFound);
292 | expect(para.name).toEqual(paraFound.name);
293 | expect(para.abbr).toEqual(paraFound.abbr);
294 | expect(para.name).toEqual(newStateName);
295 | });
296 |
297 | });
298 |
--------------------------------------------------------------------------------
/weborm.js:
--------------------------------------------------------------------------------
1 | /* WebORM v0.1.0 https://github.com/rafaeleyng/weborm */
2 | var WebORM = function(schema, config) {
3 |
4 | var self = this;
5 | var ID = 'id';
6 |
7 | /*
8 | LocalStorage
9 | */
10 | var LocalStorage = function LocalStorage() {
11 | this.clean = function() {
12 | for (var key in localStorage) {
13 | localStorage.removeItem(key);
14 | }
15 | };
16 | // CRUD
17 | // read
18 | this.count = function(entity) {
19 | return this._getIndex(entity).length;
20 | };
21 | this.find = function(entity, id) {
22 | var key = this._helpers.genKey(entity, id);
23 | var stringData = localStorage.getItem(key);
24 | if (!stringData) {
25 | return undefined;
26 | }
27 | return JSON.parse(stringData);
28 | };
29 | this.first = function(entity) {
30 | if (this.count(entity) === 0) {
31 | return undefined;
32 | }
33 | var index = this._getIndex(entity);
34 | var firstId = index[0];
35 | return this.find(entity, firstId);
36 | };
37 | this.last = function(entity) {
38 | var count = this.count(entity);
39 | if (count === 0) {
40 | return undefined;
41 | }
42 | var index = this._getIndex(entity);
43 | var lastId = index[count - 1];
44 | return this.find(entity, lastId);
45 | };
46 | this.all = function(entity) {
47 | var index = this._getIndex(entity);
48 | var objects = [];
49 | for (var i in index) {
50 | var id = index[i];
51 | objects.push(this.find(entity, id));
52 | }
53 | return objects;
54 | };
55 | this.page = function(entity, pageNumber, pageSize) {
56 | var offset = pageSize * pageNumber;
57 | if (offset >= this.count(entity)) {
58 | return [];
59 | }
60 | var index = this._getIndex(entity);
61 | var pageIds = index.slice(offset, offset+pageSize);
62 |
63 | var objects = [];
64 | for (var i in pageIds) {
65 | var id = pageIds[i];
66 | objects.push(this.find(entity, id));
67 | }
68 | return objects;
69 | };
70 | this.filter = function(entity, filters) {
71 | return this.all(entity).filter(filters);
72 | };
73 | // create / update
74 | this.save = function(entity, object) {
75 | var objectId = object.id;
76 | var key = this._helpers.genKey(entity, objectId);
77 | var isAdding = localStorage.getItem(key) === null;
78 |
79 | // add the id to entity index, if is a new record
80 | if (isAdding) {
81 | var index = this._getIndex(entity);
82 | var location = this._helpers.locationOf(objectId, index);
83 | if (!location.found) {
84 | index.splice(location.location, 0, objectId);
85 | this._saveIndex(entity, index);
86 | }
87 | localStorage.setItem(this._idKey(entity), objectId);
88 | }
89 |
90 | // add or replace the individual record
91 | localStorage.setItem(key, JSON.stringify(object));
92 | return isAdding;
93 | };
94 |
95 | // delete
96 | this.delete = function(entity, id) {
97 | var key = this._helpers.genKey(entity, id);
98 |
99 | var index = this._getIndex(entity);
100 | var location = this._helpers.locationOf(id, index);
101 | if (!location.found) {
102 | return false;
103 | }
104 | // remove id from index
105 | index.splice(location.location, 1);
106 | this._saveIndex(entity, index);
107 |
108 | // remove the individual record
109 | localStorage.removeItem(key);
110 | return true;
111 | };
112 |
113 | // Index - index is an ordered array of all ids of an entity
114 | this._getIndex = function(entity) {
115 | var indexString = localStorage.getItem(entity);
116 | if (indexString) {
117 | return JSON.parse(indexString);
118 | } else {
119 | return [];
120 | }
121 | };
122 | this._saveIndex = function(entity, index) {
123 | localStorage.setItem(entity, JSON.stringify(index));
124 | };
125 | this._idKey = function(entity) {
126 | return entity + self._ucFirst(ID);
127 | };
128 | this.genId = function(entity) {
129 | var lastId = localStorage.getItem(this._idKey(entity));
130 | if (!lastId) {
131 | return 1;
132 | }
133 | return parseInt(lastId) + 1;
134 | };
135 |
136 | // HELPERS
137 | this._helpers = {};
138 | this._helpers.genKey = function(entity, id) {
139 | return entity + '_' + id;
140 | };
141 | // binary search - return the index where to insert (when adding) or the index to delete (when deleting)
142 | this._helpers.locationOf = function(elt, array) {
143 | var low = 0;
144 | var high = array.length-1;
145 | var mid = 0;
146 | var midElt = elt;
147 | var iterations = 0;
148 | while (low <= high) {
149 | iterations++;
150 | mid = (low + high) / 2 | 0;
151 | midElt = array[mid];
152 | if (elt == midElt) {
153 | return {found: true, location: mid};
154 | }
155 | if (elt > midElt) {
156 | low = mid + 1;
157 | }
158 | else {
159 | high = mid - 1;
160 | }
161 | }
162 |
163 | if (elt > midElt) {
164 | mid++;
165 | }
166 | return {found: false, location: mid};
167 | };
168 | };
169 |
170 | /*
171 | WebORM
172 | */
173 |
174 | // CONFIG
175 | var defaults = {
176 | pluralization: {}
177 | };
178 | this.config = defaults;
179 | // using user-defined configs
180 | for (var param in config) {
181 | if (this.config[param] !== undefined) {
182 | this.config[param] = config[param];
183 | }
184 | }
185 | // non-configurable defaults
186 | this.config.base = '_Base';
187 | this.config.defaultBase = '_DefaultBase';
188 | schema[this.config.defaultBase] = new WebORM.SchemaEntity([ID]);
189 |
190 | this.storage = new LocalStorage();
191 |
192 | // CONSTRUCTORS
193 | // base constructor
194 | this.schema = schema;
195 | this.Entity = {}; // holds a constructor for each entity in the schema
196 | this.Entity[this.config.defaultBase] = function(data, entity) {
197 | for (var key in data) {
198 | if (key === ID) {
199 | Object.defineProperty(this, ID, {value: data[key], writable: false, enumerable: true});
200 | } else {
201 | this[key] = data[key];
202 | }
203 | }
204 | if (entity) {
205 | this.class = entity;
206 | }
207 | }
208 |
209 | // create a constructor for each entity
210 | for (var entity in this.schema) {
211 | if (entity === this.config.defaultBase) {
212 | continue; // won't allow to override the defaultBase entity, which provides the id for each record
213 | }
214 | if (!this.schema[entity].attrs) {
215 | this.schema[entity].attrs = [];
216 | }
217 | (function(ent) {
218 | self.Entity[ent] = function(data) {
219 | self.Entity[self.config.defaultBase].call(this, data, ent)
220 | };
221 | })(entity);
222 | }
223 | this._attrsForEntity = function(entity) {
224 | var defaultBaseAttrs = this.schema[this.config.defaultBase].attrs;
225 | var customBaseAttrs = this.schema[this.config.base] ? this.schema[this.config.base].attrs : [];
226 | var entityAttrs = this.schema[entity].attrs;
227 | return defaultBaseAttrs.concat(customBaseAttrs).concat(entityAttrs);
228 | };
229 |
230 | // CONTEXT
231 | // holds WebORMEntity objects (not plain JS objects)
232 | this.context = {};
233 |
234 | this._getFromContext = function(entity, data) {
235 | return this.context[this._genKey(entity, data.id)];
236 | };
237 | this._putInContext = function(entity, object) {
238 | var contextKey = this._genKey(entity, object.id);
239 | if (this._contextContains(entity, object)) {
240 | var attrsForEntity = this._attrsForEntity(entity);
241 | for (var i in attrsForEntity) {
242 | var attr = attrsForEntity[i];
243 | if (attr === ID) {
244 | continue;
245 | }
246 | this.context[contextKey][attr] = object[attr];
247 | }
248 | } else {
249 | this.context[contextKey] = object;
250 | }
251 | return object;
252 | };
253 | this._contextContains = function(entity, data) {
254 | return this.context[entity + '_' + data.id] !== undefined;
255 | };
256 | // returns one or an array of WebORMEntity objects with the correct entity type
257 | this._create = function(entity, data) {
258 | data = data || {};
259 | if (this._isCollection(data)) {
260 | var objects = [];
261 | for (var i in data) {
262 | objects.push(this._createOrGetFromContex(entity, data[i]));
263 | }
264 | return objects;
265 | } else {
266 | return this._createOrGetFromContex(entity, data);
267 | }
268 | };
269 |
270 | this._createOrGetFromContex = function(entity, data) {
271 | if (this._contextContains(entity, data)) {
272 | return this._getFromContext(entity, data);
273 | }
274 | var Constructor = this.Entity[entity];
275 | return this._putInContext(entity, new Constructor(data));
276 | };
277 |
278 | // CRUD
279 | // read
280 | this.count = function(entity) {
281 | return this.storage.count(entity);
282 | };
283 | this.find = function(entity, id) {
284 | var data = this.storage.find(entity, id);
285 | if (!data) {
286 | return undefined;
287 | }
288 | return this._create(entity, data);
289 | };
290 | this.first = function(entity) {
291 | return this._create(entity, this.storage.first(entity));
292 | };
293 | this.last = function(entity) {
294 | return this._create(entity, this.storage.last(entity));
295 | };
296 | this.all = function(entity) {
297 | return this._create(entity, this.storage.all(entity));
298 | };
299 | this.page = function(entity, pageNumber, pageSize) {
300 | return this._create(entity, this.storage.page(entity, pageNumber, pageSize));
301 | };
302 | this.filter = function(entity, filterFunction) {
303 | if (!filterFunction) {
304 | return this.all(entity);
305 | };
306 | return this._create(entity, this.storage.filter(entity, filterFunction));
307 | };
308 |
309 | this.exists = function(entity, id) {
310 | return this.find(entity, id) !== undefined;
311 | };
312 |
313 | // insert / update
314 | this.save = function(entity, data) {
315 | // skip if entity is not in schema
316 | if (this.schema[entity] === undefined) {
317 | return;
318 | }
319 |
320 | var filteredData = this._filterData(entity, data);
321 | if (this._isCollection(filteredData)) {
322 | var savedObjects = [];
323 | for (var i in filteredData) {
324 | if (!filteredData[i].id) {
325 | filteredData[i].id = this._genId(entity);
326 | } else {
327 | if (!this.exists(entity, filteredData[i].id)) {
328 | filteredData[i].id = this._genId(entity);
329 | }
330 | }
331 | savedObjects.push(this._save(entity, filteredData[i]));
332 | }
333 | return savedObjects;
334 | } else {
335 | if (!filteredData.id) {
336 | filteredData.id = this._genId(entity);
337 | } else {
338 | if (!this.exists(entity, filteredData.id)) {
339 | filteredData.id = this._genId(entity);
340 | }
341 | }
342 | return this._save(entity, filteredData);
343 | }
344 | };
345 |
346 | this._save = function(entity, filteredData) {
347 | var isAdding = this.storage.save(entity, filteredData);
348 | var Constructor = this.Entity[entity];
349 | var record = new Constructor(filteredData);
350 | this._putInContext(entity, record);
351 |
352 | // insert the new object in the inverse relationship arrays
353 | if (isAdding) {
354 | var inverseRelName = this._pluralize(entity);
355 | for (var i in this.context) {
356 | var ctxObj = this.context[i];
357 | var inverseRelObjs = ctxObj[inverseRelName];
358 | if (inverseRelObjs) {
359 | if (ctxObj.id === record[this._lcFirst(ctxObj.class) + self._ucFirst(ID)]) {
360 | var alreadyInTheInverse = false;
361 | for (var j in inverseRelObjs) {
362 | if (inverseRelObjs[j].id === record.id) {
363 | alreadyInTheInverse = true;
364 | break;
365 | }
366 | }
367 | if (!alreadyInTheInverse) {
368 | inverseRelObjs.push(record);
369 | }
370 | }
371 | }
372 | }
373 | }
374 |
375 | return record;
376 | };
377 |
378 | // delete
379 | this.delete = function(entity, id) {
380 | delete this.context[this._genKey(entity, id)];
381 | // delete the deleted object in the inverse relationship arrays
382 | var inverseRelName = this._pluralize(entity);
383 | for (var i in this.context) {
384 | var ctxObj = this.context[i];
385 | var inverseRelObjs = ctxObj[inverseRelName];
386 | if (inverseRelObjs) {
387 | for (var j in inverseRelObjs) {
388 | var inverseRelObj = inverseRelObjs[j];
389 | if (inverseRelObj.id === id) {
390 | var index = parseInt(j);
391 | inverseRelObjs.splice(index,1);
392 | break;
393 | }
394 | }
395 | }
396 | }
397 | this.storage.delete(entity, id);
398 | };
399 |
400 | // TO MANY
401 | this.addTo = function(addThis, toObj) {
402 | var property = this._pluralize(addThis.class);
403 | var newRelationObjs = this._makeCollection(addThis);
404 | var oldRelationIds = toObj[this._lcFirst(property) + self._ucFirst(ID)];
405 | var filteredObjs = [];
406 | // won't allow duplicates
407 | for (var i in newRelationObjs) {
408 | var newRelationObj = newRelationObjs[i];
409 | if (oldRelationIds.indexOf(newRelationObj.id) === -1) {
410 | filteredObjs.push(newRelationObj);
411 | }
412 | }
413 | // this also updates the relationship ids
414 | toObj[property] = toObj[property].concat(filteredObjs);
415 | };
416 |
417 | this.removeFrom = function(removeThis, fromObj) {
418 | var property = this._pluralize(removeThis.class);
419 | var oldRelationObjs = fromObj[property];
420 | for (var i in oldRelationObjs) {
421 | var oldRelationObj = oldRelationObjs[i];
422 | if (this.same(removeThis, oldRelationObj)) {
423 | oldRelationObjs.splice(i,1);
424 | break;
425 | }
426 | }
427 | // this also updates the relationship ids
428 | fromObj[property] = oldRelationObjs;
429 | }
430 |
431 | this.relatedTo = function(related, toObj) {
432 | var property = this._pluralize(related.class);
433 | var relationObjs = toObj[property];
434 | for (var i in relationObjs) {
435 | var relationObj = relationObjs[i];
436 | if (this.same(related, relationObj)) {
437 | return true;
438 | }
439 | }
440 | return false;
441 | };
442 |
443 |
444 | // OTHERS
445 | this.same = function(obj1, obj2) {
446 | return obj1.class === obj2.class && obj1.id === obj2.id;
447 | };
448 | // whether two objects have the same values for properties, not considering the id
449 | this.equals = function(obj1, obj2) {
450 | if (!obj1.class || obj1.class !== obj2.class) {
451 | return false;
452 | }
453 | var entity = obj1.class
454 | var attrs = this._attrsForEntity(entity);
455 | for (var i in attrs) {
456 | var attr = attrs[i];
457 | if (attr === ID) {
458 | continue;
459 | }
460 | if (obj1[attr] !== obj2[attr]) {
461 | return false;
462 | }
463 | }
464 | return true;
465 | };
466 |
467 |
468 | // HELPERS
469 | this._pluralize = function(entity) {
470 | return this.config.pluralization[entity] || entity + 's';
471 | };
472 | this._typeOf = function(value) {
473 | return Object.prototype.toString.call(value).slice(8,-1);
474 | };
475 | this._isCollection = function(value) {
476 | return this._typeOf(value) === 'Array';
477 | };
478 | this._makeCollection = function(value) {
479 | if (this._isCollection(value)) {
480 | return value;
481 | }
482 | return [value];
483 | };
484 | this._lcFirst = function(str) {
485 | return str.substr(0,1).toLowerCase() + str.substr(1, str.length);
486 | };
487 | this._ucFirst = function(str) {
488 | return str.substr(0,1).toUpperCase() + str.substr(1, str.length);
489 | };
490 | this._genKey = function(entity, id) {
491 | return entity + '_' + id;
492 | };
493 | this._genId = function(entity) {
494 | return this.storage.genId(entity);
495 | };
496 | this._filterData = function(entity, dirtyData) {
497 | var entitySchema = this._attrsForEntity(entity);
498 |
499 | if (this._isCollection(dirtyData)) {
500 | var filteredObjects = [];
501 | for (var i in dirtyData) {
502 | var dirtyObject = dirtyData[i];
503 | var filteredObject = {};
504 | for (var prop in dirtyObject) {
505 | if (entitySchema.indexOf(prop) > -1) {
506 | filteredObject[prop] = dirtyObject[prop];
507 | }
508 | }
509 | filteredObjects.push(filteredObject);
510 | }
511 | return filteredObjects;
512 | } else {
513 | var filteredObject = {};
514 | for (var prop in dirtyData) {
515 | if (entitySchema.indexOf(prop) !== -1) {
516 | filteredObject[prop] = dirtyData[prop];
517 | }
518 | }
519 | return filteredObject;
520 | }
521 | }
522 |
523 | // the prototype for each entity constructor and for each entity object
524 | var basePrototype = {
525 | // parameters are capitalized to better represent the capitalization of the strings they represent
526 | directRelToOne: function(Property) {
527 | // Property: e.g. Country - the relationship object accessor
528 | var _Property = '_' + Property; // e.g. _Country - the variable that holds the relationship object
529 | var property = self._lcFirst(Property); // e.g. country
530 | var propertyId = property + self._ucFirst(ID); // e.g. countryId - the relationship id accessor
531 | var _propertyId = '_' + propertyId; // e.g. _countryId - the variable that holds the relationship id
532 |
533 | // accessors for relationship object
534 | Object.defineProperty(this, Property, {
535 | get: function() {
536 | if (!this[_Property]) {
537 | this[_Property] = self.find(Property, this[_propertyId]);
538 | }
539 | return this[_Property];
540 | },
541 | set: function(newObj) {
542 | this[_propertyId] = newObj.id;
543 | this[_Property] = newObj;
544 | },
545 | });
546 |
547 | // accessors for relationship id
548 | Object.defineProperty(this, propertyId, {
549 | get: function() {
550 | return this[_propertyId];
551 | },
552 | set: function(newId) {
553 | this[_propertyId] = newId;
554 | this[_Property] = undefined; // let it be lazy-loaded when accessed again
555 | }
556 | });
557 | },
558 |
559 | // parameters are capitalized to better represent the capitalization of the strings they represent
560 | directRelToMany: function(Entity, Pluralized) {
561 | // pluralized: e.g. Services - the relationship object accessor
562 | var _Pluralized = '_' + Pluralized; // _Services - the variable that holds the relationship objects
563 | var pluralized = self._lcFirst(Pluralized); // services
564 | var pluralizedId = pluralized + self._ucFirst(ID); // servicesId - the relationships id accessor
565 | var _pluralizedId = '_' + pluralizedId; // _servicesId - the variable that holds the relationships id
566 |
567 | // accessors for relationship objects
568 | Object.defineProperty(this, Pluralized, {
569 | get: function() {
570 | if (!this[_Pluralized]) {
571 | var _this = this;
572 | this[_Pluralized] = self.filter(Entity,
573 | function(obj) {
574 | if (_this[_pluralizedId] === undefined) {
575 | return false;
576 | }
577 | return _this[_pluralizedId].indexOf(obj.id) > -1 });
578 | this[_Pluralized] = this[_Pluralized] || [];
579 | }
580 | return this[_Pluralized] || [];
581 | },
582 | set: function(newObjs) {
583 | this[_pluralizedId] = self._makeCollection(newObjs).map(function(obj) { return obj.id; });
584 | this[_Pluralized] = self._makeCollection(newObjs);
585 | },
586 | });
587 |
588 | // accessors for relationship ids
589 | Object.defineProperty(this, pluralizedId, {
590 | get: function() {
591 | return this[_pluralizedId] || [];
592 | },
593 | set: function(newIds) {
594 | this[_pluralizedId] = newIds;
595 | this[_Pluralized] = undefined; // let it be lazy-loaded when accessed again
596 | }
597 | });
598 | },
599 |
600 | inverseRel: function(entity, inverse, inverseName) {
601 | // entity: e.g. State
602 | // inverse: e.g City
603 | // inverseName: e.g Cities
604 | var _inverseName = '_' + inverseName; // _Cities
605 | var entityId = '_' + self._lcFirst(entity) + self._ucFirst(ID); // _stateId
606 |
607 | // accessors for inverse relationship objects (an array)
608 | Object.defineProperty(this, inverseName, {
609 | get: function() {
610 | if (!this[_inverseName]) {
611 | var thisId = this.id;
612 | this[_inverseName] = self.filter(inverse,
613 | function(obj) { return obj[entityId] === thisId; }); }
614 | return this[_inverseName];
615 | },
616 | });
617 | },
618 |
619 | // convenience methods
620 | save: function() {
621 | self.save(this.class, this);
622 | },
623 | delete: function() {
624 | self.delete(this.class, this.id);
625 | },
626 |
627 | };
628 |
629 | // RELATIONSHIPS
630 | for (var entity in this.Entity) {
631 | var entityPrototype = Object.create(basePrototype);
632 |
633 | // create the direct relationships 'to one' (e.g. state.Country)
634 | var relsToOne = this.schema[entity].relsToOne;
635 | for (var i in relsToOne) {
636 | var relationship = relsToOne[i];
637 | // augment the schema by adding the fields that will hold the relationship ids (_countryId)
638 | this.schema[entity].attrs.push('_' + this._lcFirst(relationship) + self._ucFirst(ID));
639 | entityPrototype.directRelToOne(relationship);
640 | }
641 |
642 | // create the direct relationships 'to many' (e.g. city.Services)
643 | var relsToMany = this.schema[entity].relsToMany;
644 | for (var i in relsToMany) {
645 | var relationship = relsToMany[i];
646 | // augment the schema by adding the fields that will hold the relationship ids (_servicesId)
647 | var pluralized = this._pluralize(relationship);
648 | this.schema[entity].attrs.push('_' + this._lcFirst(pluralized) + self._ucFirst(ID));
649 | entityPrototype.directRelToMany(relationship, pluralized);
650 | }
651 |
652 | // create the inverse relationships
653 | for (var entity2 in this.Entity) {
654 | var relationships2 = this.schema[entity2].relsToOne;
655 | // if 'entity2' has 'entity' as a relationship, create the 'entity2' in 'entity'
656 | if (relationships2 && relationships2.indexOf(entity) > -1) {
657 | var inverse = this._pluralize(entity2);
658 | entityPrototype.inverseRel(entity, entity2, inverse);
659 | };
660 | }
661 |
662 | // each entity has his own prototype (entityPrototype), whose prototype is basePrototype
663 | var Constructor = this.Entity[entity];
664 | Constructor.prototype = entityPrototype;
665 | }
666 | };
667 |
668 | WebORM.SchemaEntity = function(attrs, relsToOne, relsToMany) {
669 | this.attrs = attrs || [];
670 | this.relsToOne = relsToOne || [];
671 | this.relsToMany = relsToMany || [];
672 | };
673 |
--------------------------------------------------------------------------------