angular.js/test/helpers/testabilityPatch.js

308 lines
8.6 KiB
JavaScript
Raw Permalink Normal View History

'use strict';
/**
* Here is the problem: http://bugs.jquery.com/ticket/7292
* basically jQuery treats change event on some browsers (IE) as a
* special event and changes it form 'change' to 'click/keydown' and
* few others. This horrible hack removes the special treatment
*/
if (window._jQuery) _jQuery.event.special.change = undefined;
if (window.bindJQuery) bindJQuery();
beforeEach(function() {
// all this stuff is not needed for module tests, where jqlite and publishExternalAPI and jqLite are not global vars
if (window.publishExternalAPI) {
publishExternalAPI(angular);
// workaround for IE bug https://plus.google.com/104744871076396904202/posts/Kqjuj6RSbbT
// IE overwrite window.jQuery with undefined because of empty jQuery var statement, so we have to
// correct this, but only if we are not running in jqLite mode
if (!_jqLiteMode && _jQuery !== jQuery) {
jQuery = _jQuery;
}
// This resets global id counter;
uid = ['0', '0', '0'];
// reset to jQuery or default to us.
bindJQuery();
}
angular.element(document.body).empty().removeData();
});
afterEach(function() {
if (this.$injector) {
var $rootScope = this.$injector.get('$rootScope');
var $rootElement = this.$injector.get('$rootElement');
var $log = this.$injector.get('$log');
// release the injector
dealoc($rootScope);
dealoc($rootElement);
// check $log mock
$log.assertEmpty && $log.assertEmpty();
}
// complain about uncleared jqCache references
var count = 0;
// This line should be enabled as soon as this bug is fixed: http://bugs.jquery.com/ticket/11775
//var cache = jqLite.cache;
var cache = angular.element.cache;
forEachSorted(cache, function(expando, key){
angular.forEach(expando.data, function(value, key){
count ++;
if (value && value.$element) {
dump('LEAK', key, value.$id, sortedHtml(value.$element));
} else {
dump('LEAK', key, angular.toJson(value));
}
});
});
if (count) {
throw new Error('Found jqCache references that were not deallocated! count: ' + count);
}
// copied from Angular.js
// we need these two methods here so that we can run module tests with wrapped angular.js
function sortedKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for ( var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
});
2010-01-06 00:36:58 +00:00
2010-03-30 21:55:04 +00:00
function dealoc(obj) {
var jqCache = angular.element.cache;
if (obj) {
if (angular.isElement(obj)) {
cleanup(angular.element(obj));
} else {
for(var key in jqCache) {
var value = jqCache[key];
if (value.data && value.data.$scope == obj) {
delete jqCache[key];
}
}
}
}
function cleanup(element) {
element.off().removeData();
feat($sce): new $sce service for Strict Contextual Escaping. $sce is a service that provides Strict Contextual Escaping services to AngularJS. Strict Contextual Escaping -------------------------- Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain contexts to result in a value that is marked as safe to use for that context One example of such a context is binding arbitrary html controlled by the user via ng-bind-html-unsafe. We refer to these contexts as privileged or SCE contexts. As of version 1.2, Angular ships with SCE enabled by default. Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows one to execute arbitrary javascript by the use of the expression() syntax. Refer http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx to learn more about them. You can ensure your document is in standards mode and not quirks mode by adding <!doctype html> to the top of your HTML document. SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier. Here's an example of a binding in a privileged context: <input ng-model="userHtml"> <div ng-bind-html-unsafe="{{userHtml}}"> Notice that ng-bind-html-unsafe is bound to {{userHtml}} controlled by the user. With SCE disabled, this application allows the user to render arbitrary HTML into the DIV. In a more realistic example, one may be rendering user comments, blog articles, etc. via bindings. (HTML is just one example of a context where rendering user controlled input creates security vulnerabilities.) For the case of HTML, you might use a library, either on the client side, or on the server side, to sanitize unsafe HTML before binding to the value and rendering it in the document. How would you ensure that every place that used these types of bindings was bound to a value that was sanitized by your library (or returned as safe for rendering by your server?) How can you ensure that you didn't accidentally delete the line that sanitized the value, or renamed some properties/fields and forgot to update the binding to the sanitized value? To be secure by default, you want to ensure that any such bindings are disallowed unless you can determine that something explicitly says it's safe to use a value for binding in that context. You can then audit your code (a simple grep would do) to ensure that this is only done for those values that you can easily tell are safe - because they were received from your server, sanitized by your library, etc. You can organize your codebase to help with this - perhaps allowing only the files in a specific directory to do this. Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. In the case of AngularJS' SCE service, one uses $sce.trustAs (and shorthand methods such as $sce.trustAsHtml, etc.) to obtain values that will be accepted by SCE / privileged contexts. In privileged contexts, directives and code will bind to the result of $sce.getTrusted(context, value) rather than to the value directly. Directives use $sce.parseAs rather than $parse to watch attribute bindings, which performs the $sce.getTrusted behind the scenes on non-constant literals. As an example, ngBindHtmlUnsafe uses $sce.parseAsHtml(binding expression). Here's the actual code (slightly simplified): var ngBindHtmlUnsafeDirective = ['$sce', function($sce) { return function(scope, element, attr) { scope.$watch($sce.parseAsHtml(attr.ngBindHtmlUnsafe), function(value) { element.html(value || ''); }); }; }]; Impact on loading templates --------------------------- This applies both to the ng-include directive as well as templateUrl's specified by directives. By default, Angular only loads templates from the same domain and protocol as the application document. This is done by calling $sce.getTrustedResourceUrl on the template URL. To load templates from other domains and/or protocols, you may either either whitelist them or wrap it into a trusted value. *Please note*: The browser's Same Origin Policy and Cross-Origin Resource Sharing (CORS) policy apply in addition to this and may further restrict whether the template is successfully loaded. This means that without the right CORS policy, loading templates from a different domain won't work on all browsers. Also, loading templates from file:// URL does not work on some browsers. This feels like too much overhead for the developer? ---------------------------------------------------- It's important to remember that SCE only applies to interpolation expressions. If your expressions are constant literals, they're automatically trusted and you don't need to call $sce.trustAs on them. e.g. <div ng-html-bind-unsafe="'<b>implicitly trusted</b>'"></div> just works. Additionally, a[href] and img[src] automatically sanitize their URLs and do not pass them through $sce.getTrusted. SCE doesn't play a role here. The included $sceDelegate comes with sane defaults to allow you to load templates in ng-include from your application's domain without having to even know about SCE. It blocks loading templates from other domains or loading templates over http from an https served document. You can change these by setting your own custom whitelists and blacklists for matching such URLs. This significantly reduces the overhead. It is far easier to pay the small overhead and have an application that's secure and can be audited to verify that with much more ease than bolting security onto an application later.
2013-05-14 21:51:39 +00:00
// Note: We aren't using element.contents() here. Under jQuery, element.contents() can fail
// for IFRAME elements. jQuery explicitly uses (element.contentDocument ||
// element.contentWindow.document) and both properties are null for IFRAMES that aren't attached
// to a document.
var children = element[0].childNodes || [];
for ( var i = 0; i < children.length; i++) {
cleanup(angular.element(children[i]));
}
}
}
/**
* @param {DOMElement} element
* @param {boolean=} showNgClass
*/
function sortedHtml(element, showNgClass) {
2010-01-06 00:36:58 +00:00
var html = "";
forEach(jqLite(element), function toString(node) {
2010-01-06 00:36:58 +00:00
if (node.nodeName == "#text") {
html += node.nodeValue.
replace(/&(\w+[&;\W])?/g, function(match, entity){return entity?match:'&amp;';}).
replace(/</g, '&lt;').
replace(/>/g, '&gt;');
} else if (node.nodeName == "#comment") {
html += '<!--' + node.nodeValue + '-->';
2010-01-06 00:36:58 +00:00
} else {
html += '<' + (node.nodeName || '?NOT_A_NODE?').toLowerCase();
2010-01-06 00:36:58 +00:00
var attributes = node.attributes || [];
var attrs = [];
var className = node.className || '';
if (!showNgClass) {
className = className.replace(/ng-[\w-]+\s*/g, '');
}
className = trim(className);
if (className) {
attrs.push(' class="' + className + '"');
}
2010-01-06 00:36:58 +00:00
for(var i=0; i<attributes.length; i++) {
if (i>0 && attributes[i] == attributes[i-1])
continue; //IE9 creates dupes. Ignore them!
2010-01-06 00:36:58 +00:00
var attr = attributes[i];
2012-03-09 08:00:05 +00:00
if(attr.name.match(/^ng[\:\-]/) ||
(attr.value || attr.value == '') &&
2010-01-06 00:36:58 +00:00
attr.value !='null' &&
attr.value !='auto' &&
attr.value !='false' &&
attr.value !='inherit' &&
2011-04-19 23:34:49 +00:00
(attr.value !='0' || attr.name =='value') &&
2010-01-06 00:36:58 +00:00
attr.name !='loop' &&
2010-04-21 19:50:05 +00:00
attr.name !='complete' &&
2010-01-06 00:36:58 +00:00
attr.name !='maxLength' &&
attr.name !='size' &&
2010-07-23 20:54:12 +00:00
attr.name !='class' &&
2010-01-06 00:36:58 +00:00
attr.name !='start' &&
attr.name !='tabIndex' &&
attr.name !='style' &&
2010-01-06 00:36:58 +00:00
attr.name.substr(0, 6) != 'jQuery') {
// in IE we need to check for all of these.
if (/ng-\d+/.exec(attr.name) ||
attr.name == 'getElementById' ||
// IE7 has `selected` in attributes
attr.name == 'selected' ||
// IE7 adds `value` attribute to all LI tags
(node.nodeName == 'LI' && attr.name == 'value') ||
// IE8 adds bogus rowspan=1 and colspan=1 to TD elements
(node.nodeName == 'TD' && attr.name == 'rowSpan' && attr.value == '1') ||
(node.nodeName == 'TD' && attr.name == 'colSpan' && attr.value == '1')) {
continue;
}
attrs.push(' ' + attr.name + '="' + attr.value + '"');
2010-01-06 00:36:58 +00:00
}
}
attrs.sort();
html += attrs.join('');
2010-04-15 21:17:33 +00:00
if (node.style) {
var style = [];
if (node.style.cssText) {
forEach(node.style.cssText.split(';'), function(value){
2010-04-15 21:17:33 +00:00
value = trim(value);
if (value) {
2010-04-21 19:50:05 +00:00
style.push(lowercase(value));
2010-04-15 21:17:33 +00:00
}
});
}
for(var css in node.style){
var value = node.style[css];
if (isString(value) && isString(css) && css != 'cssText' && value && (1*css != css)) {
2010-04-21 19:50:05 +00:00
var text = lowercase(css + ': ' + value);
2010-04-19 21:36:41 +00:00
if (value != 'false' && indexOf(style, text) == -1) {
2010-04-15 21:17:33 +00:00
style.push(text);
}
}
2010-04-19 21:41:36 +00:00
}
2010-04-13 02:16:30 +00:00
style.sort();
2010-04-22 22:50:20 +00:00
var tmp = style;
style = [];
forEach(tmp, function(value){
2010-04-22 22:50:20 +00:00
if (!value.match(/^max[^\-]/))
style.push(value);
});
2010-04-15 21:17:33 +00:00
if (style.length) {
html += ' style="' + style.join('; ') + ';"';
}
}
2010-01-06 00:36:58 +00:00
html += '>';
var children = node.childNodes;
for(var j=0; j<children.length; j++) {
toString(children[j]);
2010-01-06 00:36:58 +00:00
}
html += '</' + node.nodeName.toLowerCase() + '>';
}
});
2010-01-06 00:36:58 +00:00
return html;
2010-04-04 00:04:36 +00:00
}
2010-01-06 00:36:58 +00:00
function childrenTagsOf(element) {
var tags = [];
forEach(jqLite(element).children(), function(child) {
tags.push(child.nodeName.toLowerCase());
});
return tags;
}
// TODO(vojta): migrate these helpers into jasmine matchers
/**a
* This method is a cheap way of testing if css for a given node is not set to 'none'. It doesn't
* actually test if an element is displayed by the browser. Be aware!!!
*/
2010-04-08 20:43:40 +00:00
function isCssVisible(node) {
2010-03-31 20:57:25 +00:00
var display = node.css('display');
return !node.hasClass('ng-hide') && display != 'none';
}
2010-01-06 00:36:58 +00:00
function assertHidden(node) {
if (isCssVisible(node)) {
throw new Error('Node should be hidden but was visible: ' + angular.module.ngMock.dump(node));
}
2010-01-06 00:36:58 +00:00
}
function assertVisible(node) {
if (!isCssVisible(node)) {
throw new Error('Node should be visible but was hidden: ' + angular.module.ngMock.dump(node));
}
2010-01-06 00:36:58 +00:00
}
function provideLog($provide) {
$provide.factory('log', function() {
var messages = [];
function log(msg) {
messages.push(msg);
return msg;
}
log.toString = function() {
return messages.join('; ');
}
log.toArray = function() {
return messages;
}
log.reset = function() {
messages = [];
}
log.fn = function(msg) {
return function() {
log(msg);
}
}
log.$$log = true;
return log;
});
}
function pending() {
dump('PENDING');
};
function trace(name) {
dump(new Error(name).stack);
}
var karmaDump = dump;
window.dump = function () {
karmaDump.apply(undefined, map(arguments, function(arg) {
return angular.mock.dump(arg);
}));
};