content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Javascript | Javascript | use commas in non-csv rate output | 17eb8fce0548290ae7cc1befa69c845552603565 | <ide><path>benchmark/common.js
<ide> function formatResult(data) {
<ide> conf += ' ' + key + '=' + JSON.stringify(data.conf[key]);
<ide> }
<ide>
<del> return `${data.name}${conf}: ${data.rate}`;
<add> const rate = Math.floor(data.rate)
<add> .toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
<add> return `${data.name}${conf}: ${rate}`;
<ide> }
<ide>
<ide> function sendResult(data) {
<ide><path>benchmark/run.js
<ide> if (format === 'csv') {
<ide> conf = conf.replace(/"/g, '""');
<ide> console.log(`"${data.name}", "${conf}", ${data.rate}, ${data.time}`);
<ide> } else {
<del> console.log(`${data.name} ${conf}: ${data.rate}`);
<add> const rate = Math.floor(data.rate)
<add> .toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
<add> console.log(`${data.name} ${conf}: ${rate}`);
<ide> }
<ide> });
<ide> | 2 |
PHP | PHP | fix incorrect documentation | dffcf048d9e05d0ee465e8d4909357ea444272d4 | <ide><path>lib/Cake/Console/Command/AclShell.php
<ide> public function getOptionParser() {
<ide> 'help' => __d('cake_console', 'Check the permissions between an ACO and ARO.'),
<ide> 'parser' => array(
<ide> 'description' => array(
<del> __d('cake_console', 'Use this command to grant ACL permissions. Once executed, the ARO specified (and its children, if any) will have ALLOW access to the specified ACO action (and the ACO\'s children, if any).')
<add> __d('cake_console', 'Use this command to check ACL permissions.')
<ide> ),
<ide> 'arguments' => array(
<ide> 'aro' => array('help' => __d('cake_console', 'ARO to check.'), 'required' => true), | 1 |
Javascript | Javascript | turn scope into a service | 48697a2b86dbb12ea8de64cc5fece7caf68b321e | <ide><path>example/personalLog/test/personalLogSpec.js
<ide> describe('example.personalLog.LogCtrl', function() {
<ide> var logCtrl;
<ide>
<ide> function createNotesCtrl() {
<del> var scope = angular.scope();
<del> scope.$cookies = scope.$service('$cookies');
<add> var injector = angular.injector();
<add> var scope = injector('$rootScope');
<add> scope.$cookies = injector('$cookies');
<ide> return scope.$new(example.personalLog.LogCtrl);
<ide> }
<ide>
<ide><path>src/Angular.js
<ide> function angularInit(config, document){
<ide> var autobind = config.autobind;
<ide>
<ide> if (autobind) {
<del> var element = isString(autobind) ? document.getElementById(autobind) : document;
<del> compile(element)().$apply();
<add> var element = isString(autobind) ? document.getElementById(autobind) : document,
<add> injector = createInjector(),
<add> scope = injector('$rootScope');
<add>
<add> compile(element)(scope);
<add> scope.$apply();
<ide> }
<ide> }
<ide>
<ide><path>src/AngularPublic.js
<ide> extend(angular, {
<ide> // disabled for now until we agree on public name
<ide> //'annotate': annotate,
<ide> 'compile': compile,
<del> 'scope': createScope,
<ide> 'copy': copy,
<ide> 'extend': extend,
<ide> 'equals': equals,
<ide><path>src/Compiler.js
<ide> Template.prototype = {
<ide> *
<ide> *
<ide> * @param {string|DOMElement} element Element or HTML to compile into a template function.
<del> * @returns {function([scope][, cloneAttachFn])} a template function which is used to bind template
<add> * @returns {function(scope[, cloneAttachFn])} a template function which is used to bind template
<ide> * (a DOM element/tree) to a scope. Where:
<ide> *
<del> * * `scope` - A {@link angular.scope Scope} to bind to. If none specified, then a new
<del> * root scope is created.
<add> * * `scope` - A {@link angular.scope Scope} to bind to.
<ide> * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
<ide> * `template` and call the `cloneAttachFn` function allowing the caller to attach the
<ide> * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
<ide> Template.prototype = {
<ide> * * `clonedElement` - is a clone of the original `element` passed into the compiler.
<ide> * * `scope` - is the current scope with which the linking function is working with.
<ide> *
<del> * Calling the template function returns the scope to which the element is bound to. It is either
<del> * the same scope as the one passed into the template function, or if none were provided it's the
<del> * newly create scope.
<add> * Calling the template function returns the element of the template. It is either the original element
<add> * passed in, or the clone of the element if the `cloneAttachFn` is provided.
<ide> *
<ide> * It is important to understand that the returned scope is "linked" to the view DOM, but no linking
<ide> * (instance) functions registered by {@link angular.directive directives} or
<ide> Template.prototype = {
<ide> * - If you are not asking the linking function to clone the template, create the DOM element(s)
<ide> * before you send them to the compiler and keep this reference around.
<ide> * <pre>
<del> * var view = angular.element('<p>{{total}}</p>'),
<del> * scope = angular.compile(view)();
<add> * var scope = angular.injector()('$rootScope');
<add> * var element = angular.compile('<p>{{total}}</p>')(scope);
<ide> * </pre>
<ide> *
<ide> * - if on the other hand, you need the element to be cloned, the view reference from the original
<ide> Compiler.prototype = {
<ide> }
<ide> template = this.templatize(templateElement, index) || new Template();
<ide> return function(scope, cloneConnectFn){
<add> assertArg(scope, 'scope');
<ide> // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
<ide> // and sometimes changes the structure of the DOM.
<ide> var element = cloneConnectFn
<ide> ? JQLitePrototype.clone.call(templateElement) // IMPORTANT!!!
<ide> : templateElement;
<del> scope = scope || createScope();
<ide> element.data($$scope, scope);
<ide> scope.$element = element;
<ide> (cloneConnectFn||noop)(element, scope);
<ide> template.link(element, scope);
<del> return scope;
<add> return element;
<ide> };
<ide> },
<ide>
<ide><path>src/Injector.js
<ide> * Creates an injector function that can be used for retrieving services as well as for
<ide> * dependency injection (see {@link guide/dev_guide.di dependency injection}).
<ide> *
<del> * Angular creates an injector automatically for the root scope and it is available as the
<del> * {@link angular.scope.$service $service} property. Creating an injector doesn't automatically
<del> * create all of the `$eager` {@link angular.service services}. You have to call `injector.eager()`
<del> * to initialize them.
<add> * Creating an injector doesn't automatically create all of the `$eager`
<add> * {@link angular.service services}. You have to call `injector.eager()` to initialize them.
<ide> *
<del> * @param {Object=} [factoryScope={}] The `this` for the service factory function.
<ide> * @param {Object.<string, function()>=} [factories=angular.service] Map of the service factory
<ide> * functions.
<del> * @param {Object.<string, function()>=} [instanceCache={}] Place where instances of services are
<del> * saved for reuse. Can also be used to override services specified by `serviceFactory`
<del> * (useful in tests).
<ide> * @returns {function()} Injector function:
<ide> *
<ide> * * `injector(serviceName)`:
<ide> * * An `eager` property which is used to initialize the eager services.
<ide> * `injector.eager()`
<ide> */
<del>function createInjector(factoryScope, factories, instanceCache) {
<add>function createInjector(factories) {
<add> var instanceCache = {$injector: injector};
<ide> factories = factories || angularService;
<del> instanceCache = instanceCache || {};
<del> factoryScope = factoryScope || {};
<del> injector.invoke = invoke;
<ide>
<del> injector.eager = function() {
<del> forEach(factories, function(factory, name){
<del> if (factory.$eager)
<del> injector(name);
<add> injector.invoke = invoke;
<ide>
<del> if (factory.$creation)
<del> throw new Error("Failed to register service '" + name +
<del> "': $creation property is unsupported. Use $eager:true or see release notes.");
<del> });
<del> };
<add> forEach(factories, function(factory, name){
<add> if (factory.$eager)
<add> injector(name);
<add> });
<ide> return injector;
<ide>
<ide> function injector(value){
<ide> if (!(value in instanceCache)) {
<ide> var factory = factories[value];
<del> if (!factory) throw Error("Unknown provider for '"+value+"'.");
<add> if (!factory) throw Error("Unknown provider for '" + value + "'.");
<ide> inferInjectionArgs(factory);
<del> instanceCache[value] = invoke(factoryScope, factory);
<add> instanceCache[value] = invoke(null, factory);
<ide> }
<ide> return instanceCache[value];
<ide> }
<ide><path>src/scenario/Runner.js
<ide> angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) {
<ide> */
<ide> angular.scenario.Runner.prototype.run = function(application) {
<ide> var self = this;
<del> var $root = angular.scope();
<add> var $root = angular.injector()('$rootScope');
<ide> angular.extend($root, this);
<ide> angular.forEach(angular.scenario.Runner.prototype, function(fn, name) {
<ide> $root[name] = angular.bind(self, fn);
<ide><path>src/scenario/dsl.js
<ide> angular.scenario.dsl('browser', function() {
<ide>
<ide> api.url = function() {
<ide> return this.addFutureAction('$location.url()', function($window, $document, done) {
<del> done(null, $window.angular.scope().$service('$location').url());
<add> done(null, $window.angular.injector()('$location').url());
<ide> });
<ide> };
<ide>
<ide> api.path = function() {
<ide> return this.addFutureAction('$location.path()', function($window, $document, done) {
<del> done(null, $window.angular.scope().$service('$location').path());
<add> done(null, $window.angular.injector()('$location').path());
<ide> });
<ide> };
<ide>
<ide> api.search = function() {
<ide> return this.addFutureAction('$location.search()', function($window, $document, done) {
<del> done(null, $window.angular.scope().$service('$location').search());
<add> done(null, $window.angular.injector()('$location').search());
<ide> });
<ide> };
<ide>
<ide> api.hash = function() {
<ide> return this.addFutureAction('$location.hash()', function($window, $document, done) {
<del> done(null, $window.angular.scope().$service('$location').hash());
<add> done(null, $window.angular.injector()('$location').hash());
<ide> });
<ide> };
<ide>
<ide><path>src/service/cookies.js
<ide> *
<ide> * @example
<ide> */
<del>angularServiceInject('$cookies', function($browser) {
<del> var rootScope = this,
<del> cookies = {},
<add>angularServiceInject('$cookies', function($rootScope, $browser) {
<add> var cookies = {},
<ide> lastCookies = {},
<ide> lastBrowserCookies,
<ide> runEval = false;
<ide> angularServiceInject('$cookies', function($browser) {
<ide> lastBrowserCookies = currentCookies;
<ide> copy(currentCookies, lastCookies);
<ide> copy(currentCookies, cookies);
<del> if (runEval) rootScope.$apply();
<add> if (runEval) $rootScope.$apply();
<ide> }
<ide> })();
<ide>
<ide> angularServiceInject('$cookies', function($browser) {
<ide> //at the end of each eval, push cookies
<ide> //TODO: this should happen before the "delayed" watches fire, because if some cookies are not
<ide> // strings or browser refuses to store some cookies, we update the model in the push fn.
<del> this.$watch(push);
<add> $rootScope.$watch(push);
<ide>
<ide> return cookies;
<ide>
<ide> angularServiceInject('$cookies', function($browser) {
<ide> }
<ide> }
<ide> }
<del>}, ['$browser']);
<add>}, ['$rootScope', '$browser']);
<ide><path>src/service/defer.js
<ide> * @param {*} deferId Token returned by the `$defer` function.
<ide> * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled.
<ide> */
<del>angularServiceInject('$defer', function($browser) {
<del> var scope = this;
<del>
<add>angularServiceInject('$defer', function($rootScope, $browser) {
<ide> function defer(fn, delay) {
<ide> return $browser.defer(function() {
<del> scope.$apply(fn);
<add> $rootScope.$apply(fn);
<ide> }, delay);
<ide> }
<ide>
<ide> angularServiceInject('$defer', function($browser) {
<ide> };
<ide>
<ide> return defer;
<del>}, ['$browser']);
<add>}, ['$rootScope', '$browser']);
<ide><path>src/service/formFactory.js
<ide> </doc:scenario>
<ide> </doc:example>
<ide> */
<del>angularServiceInject('$formFactory', function() {
<add>angularServiceInject('$formFactory', function($rootScope) {
<ide>
<ide>
<ide> /**
<ide> angularServiceInject('$formFactory', function() {
<ide> * Each application ({@link guide/dev_guide.scopes.internals root scope}) gets a root form which
<ide> * is the top-level parent of all forms.
<ide> */
<del> formFactory.rootForm = formFactory(this);
<add> formFactory.rootForm = formFactory($rootScope);
<ide>
<ide>
<ide> /**
<ide> angularServiceInject('$formFactory', function() {
<ide> return (parent || formFactory.rootForm).$new(FormController);
<ide> }
<ide>
<del>});
<add>}, ['$rootScope']);
<ide>
<ide> function propertiesUpdate(widget) {
<ide> widget.$valid = !(widget.$invalid =
<ide><path>src/service/location.js
<ide> function locationGetterSetter(property, preprocess) {
<ide> *
<ide> * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular Services: Using $location}
<ide> */
<del>angularServiceInject('$location', function($browser, $sniffer, $locationConfig, $document) {
<del> var scope = this, currentUrl,
<add>angularServiceInject('$location', function($rootScope, $browser, $sniffer, $locationConfig, $document) {
<add> var currentUrl,
<ide> basePath = $browser.baseHref() || '/',
<ide> pathPrefix = pathPrefixFromBase(basePath),
<ide> hashPrefix = $locationConfig.hashPrefix || '',
<ide> angularServiceInject('$location', function($browser, $sniffer, $locationConfig,
<ide> href = href.indexOf(pathPrefix) === 0 ? href.substr(pathPrefix.length) : href;
<ide>
<ide> currentUrl.url(href);
<del> scope.$apply();
<add> $rootScope.$apply();
<ide> event.preventDefault();
<ide> // hack to work around FF6 bug 684208 when scenario runner clicks on links
<ide> window.angular['ff-684208-preventDefault'] = true;
<ide> angularServiceInject('$location', function($browser, $sniffer, $locationConfig,
<ide> $browser.onUrlChange(function(newUrl) {
<ide> if (currentUrl.absUrl() != newUrl) {
<ide> currentUrl.$$parse(newUrl);
<del> scope.$apply();
<add> $rootScope.$apply();
<ide> }
<ide> });
<ide>
<ide> // update browser
<ide> var changeCounter = 0;
<del> scope.$watch(function() {
<add> $rootScope.$watch(function() {
<ide> if ($browser.url() != currentUrl.absUrl()) {
<ide> changeCounter++;
<del> scope.$evalAsync(function() {
<add> $rootScope.$evalAsync(function() {
<ide> $browser.url(currentUrl.absUrl(), currentUrl.$$replace);
<ide> currentUrl.$$replace = false;
<ide> });
<ide> angularServiceInject('$location', function($browser, $sniffer, $locationConfig,
<ide> });
<ide>
<ide> return currentUrl;
<del>}, ['$browser', '$sniffer', '$locationConfig', '$document']);
<add>}, ['$rootScope', '$browser', '$sniffer', '$locationConfig', '$document']);
<ide>
<ide>
<ide> angular.service('$locationConfig', function() {
<ide><path>src/service/route.js
<ide> </doc:scenario>
<ide> </doc:example>
<ide> */
<del>angularServiceInject('$route', function($location, $routeParams) {
<add>angularServiceInject('$route', function($rootScope, $location, $routeParams) {
<ide> /**
<ide> * @ngdoc event
<ide> * @name angular.service.$route#$beforeRouteChange
<ide> angularServiceInject('$route', function($location, $routeParams) {
<ide>
<ide> var routes = {},
<ide> matcher = switchRouteMatcher,
<del> parentScope = this,
<del> rootScope = this,
<add> parentScope = $rootScope,
<ide> dirty = 0,
<ide> forceReload = false,
<ide> $route = {
<ide> angularServiceInject('$route', function($location, $routeParams) {
<ide> }
<ide> };
<ide>
<del> this.$watch(function() { return dirty + $location.url(); }, updateRoute);
<add> $rootScope.$watch(function() { return dirty + $location.url(); }, updateRoute);
<ide>
<ide> return $route;
<ide>
<ide> angularServiceInject('$route', function($location, $routeParams) {
<ide> last.scope && last.scope.$emit('$routeUpdate');
<ide> } else {
<ide> forceReload = false;
<del> rootScope.$broadcast('$beforeRouteChange', next, last);
<add> $rootScope.$broadcast('$beforeRouteChange', next, last);
<ide> last && last.scope && last.scope.$destroy();
<ide> $route.current = next;
<ide> if (next) {
<ide> angularServiceInject('$route', function($location, $routeParams) {
<ide> next.scope = parentScope.$new(Controller);
<ide> }
<ide> }
<del> rootScope.$broadcast('$afterRouteChange', next, last);
<add> $rootScope.$broadcast('$afterRouteChange', next, last);
<ide> }
<ide> }
<ide>
<ide> angularServiceInject('$route', function($location, $routeParams) {
<ide> }
<ide>
<ide>
<del>}, ['$location', '$routeParams']);
<add>}, ['$rootScope', '$location', '$routeParams']);
<ide><path>src/service/scope.js
<ide> * are expensive to construct.
<ide> */
<ide>
<del>
<del>function createScope(providers, instanceCache) {
<del> var scope = new Scope();
<del> (scope.$service = createInjector(scope, providers, instanceCache)).eager();
<del> return scope;
<del>}
<del>
<del>
<del>/**
<del> * @ngdoc function
<del> * @name angular.scope
<del> *
<del> * @description
<del> * A root scope can be created by calling {@link angular.scope angular.scope()}. Child scopes
<del> * are created using the {@link angular.scope.$new $new()} method.
<del> * (Most scopes are created automatically when compiled HTML template is executed.)
<del> *
<del> * Here is a simple scope snippet to show how you can interact with the scope.
<del> * <pre>
<del> var scope = angular.scope();
<del> scope.salutation = 'Hello';
<del> scope.name = 'World';
<del>
<del> expect(scope.greeting).toEqual(undefined);
<del>
<del> scope.$watch('name', function() {
<del> this.greeting = this.salutation + ' ' + this.name + '!';
<del> }); // initialize the watch
<del>
<del> expect(scope.greeting).toEqual(undefined);
<del> scope.name = 'Misko';
<del> // still old value, since watches have not been called yet
<del> expect(scope.greeting).toEqual(undefined);
<del>
<del> scope.$digest(); // fire all the watches
<del> expect(scope.greeting).toEqual('Hello Misko!');
<del> * </pre>
<del> *
<del> * # Inheritance
<del> * A scope can inherit from a parent scope, as in this example:
<del> * <pre>
<del> var parent = angular.scope();
<del> var child = parent.$new();
<del>
<del> parent.salutation = "Hello";
<del> child.name = "World";
<del> expect(child.salutation).toEqual('Hello');
<del>
<del> child.salutation = "Welcome";
<del> expect(child.salutation).toEqual('Welcome');
<del> expect(parent.salutation).toEqual('Hello');
<del> * </pre>
<del> *
<del> * # Dependency Injection
<del> * See {@link guide/dev_guide.di dependency injection}.
<del> *
<del> *
<del> * @param {Object.<string, function()>=} providers Map of service factory which need to be provided
<del> * for the current scope. Defaults to {@link angular.service}.
<del> * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
<del> * append/override services provided by `providers`. This is handy when unit-testing and having
<del> * the need to override a default service.
<del> * @returns {Object} Newly created scope.
<del> *
<del> */
<del>function Scope() {
<del> this.$id = nextUid();
<del> this.$$phase = this.$parent = this.$$watchers =
<del> this.$$nextSibling = this.$$prevSibling =
<del> this.$$childHead = this.$$childTail = null;
<del> this.$destructor = noop;
<del> this['this'] = this.$root = this;
<del> this.$$asyncQueue = [];
<del> this.$$listeners = {};
<del>}
<del>
<del>/**
<del> * @ngdoc property
<del> * @name angular.scope.$id
<del> * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
<del> * debugging.
<del> */
<del>
<del>/**
<del> * @ngdoc property
<del> * @name angular.scope.$service
<del> * @function
<del> *
<del> * @description
<del> * Provides reference to an instance of {@link angular.injector injector} which can be used to
<del> * retrieve {@link angular.service services}. In general the use of this api is discouraged,
<del> * in favor of proper {@link guide/dev_guide.di dependency injection}.
<del> *
<del> * @returns {function} {@link angular.injector injector}
<del> */
<del>
<del>/**
<del> * @ngdoc property
<del> * @name angular.scope.$root
<del> * @returns {Scope} The root scope of the current scope hierarchy.
<del> */
<del>
<del>/**
<del> * @ngdoc property
<del> * @name angular.scope.$parent
<del> * @returns {Scope} The parent scope of the current scope.
<del> */
<del>
<del>
<del>Scope.prototype = {
<add>angularServiceInject('$rootScope', function($injector, $exceptionHandler){
<ide> /**
<ide> * @ngdoc function
<del> * @name angular.scope.$new
<del> * @function
<add> * @name angular.scope
<ide> *
<ide> * @description
<del> * Creates a new child {@link angular.scope scope}. The new scope can optionally behave as a
<del> * controller. The parent scope will propagate the {@link angular.scope.$digest $digest()} and
<del> * {@link angular.scope.$digest $digest()} events. The scope can be removed from the scope
<del> * hierarchy using {@link angular.scope.$destroy $destroy()}.
<del> *
<del> * {@link angular.scope.$destroy $destroy()} must be called on a scope when it is desired for
<del> * the scope and its child scopes to be permanently detached from the parent and thus stop
<del> * participating in model change detection and listener notification by invoking.
<del> *
<del> * @param {function()=} Class Constructor function which the scope should be applied to the scope.
<del> * @param {...*} curryArguments Any additional arguments which are curried into the constructor.
<del> * See {@link guide/dev_guide.di dependency injection}.
<del> * @returns {Object} The newly created child scope.
<add> * A root scope can be created by calling {@link angular.scope angular.scope()}. Child scopes
<add> * are created using the {@link angular.scope.$new $new()} method.
<add> * (Most scopes are created automatically when compiled HTML template is executed.)
<ide> *
<del> */
<del> $new: function(Class, curryArguments) {
<del> var Child = function() {}; // should be anonymous; This is so that when the minifier munges
<del> // the name it does not become random set of chars. These will then show up as class
<del> // name in the debugger.
<del> var child;
<del> Child.prototype = this;
<del> child = new Child();
<del> child['this'] = child;
<del> child.$$listeners = {};
<del> child.$parent = this;
<del> child.$id = nextUid();
<del> child.$$asyncQueue = [];
<del> child.$$phase = child.$$watchers =
<del> child.$$nextSibling = child.$$childHead = child.$$childTail = null;
<del> child.$$prevSibling = this.$$childTail;
<del> if (this.$$childHead) {
<del> this.$$childTail.$$nextSibling = child;
<del> this.$$childTail = child;
<del> } else {
<del> this.$$childHead = this.$$childTail = child;
<del> }
<del> // short circuit if we have no class
<del> if (Class) {
<del> // can't use forEach, we need speed!
<del> var ClassPrototype = Class.prototype;
<del> for(var key in ClassPrototype) {
<del> child[key] = bind(child, ClassPrototype[key]);
<del> }
<del> this.$service.invoke(child, Class, curryArguments);
<del> }
<del> return child;
<del> },
<add> * Here is a simple scope snippet to show how you can interact with the scope.
<add> * <pre>
<add> var scope = angular.scope();
<add> scope.salutation = 'Hello';
<add> scope.name = 'World';
<ide>
<del> /**
<del> * @ngdoc function
<del> * @name angular.scope.$watch
<del> * @function
<del> *
<del> * @description
<del> * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
<del> *
<del> * - The `watchExpression` is called on every call to {@link angular.scope.$digest $digest()} and
<del> * should return the value which will be watched. (Since {@link angular.scope.$digest $digest()}
<del> * reruns when it detects changes the `watchExpression` can execute multiple times per
<del> * {@link angular.scope.$digest $digest()} and should be idempotent.)
<del> * - The `listener` is called only when the value from the current `watchExpression` and the
<del> * previous call to `watchExpression' are not equal. The inequality is determined according to
<del> * {@link angular.equals} function. To save the value of the object for later comparison
<del> * {@link angular.copy} function is used. It also means that watching complex options will
<del> * have adverse memory and performance implications.
<del> * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
<del> * is achieved by rerunning the watchers until no changes are detected. The rerun iteration
<del> * limit is 100 to prevent infinity loop deadlock.
<del> *
<del> *
<del> * If you want to be notified whenever {@link angular.scope.$digest $digest} is called,
<del> * you can register an `watchExpression` function with no `listener`. (Since `watchExpression`,
<del> * can execute multiple times per {@link angular.scope.$digest $digest} cycle when a change is
<del> * detected, be prepared for multiple calls to your listener.)
<del> *
<del> *
<del> * # Example
<del> <pre>
<del> var scope = angular.scope();
<del> scope.name = 'misko';
<del> scope.counter = 0;
<del>
<del> expect(scope.counter).toEqual(0);
<del> scope.$watch('name', function(scope, newValue, oldValue) { counter = counter + 1; });
<del> expect(scope.counter).toEqual(0);
<del>
<del> scope.$digest();
<del> // no variable change
<del> expect(scope.counter).toEqual(0);
<del>
<del> scope.name = 'adam';
<del> scope.$digest();
<del> expect(scope.counter).toEqual(1);
<del> </pre>
<add> expect(scope.greeting).toEqual(undefined);
<add>
<add> scope.$watch('name', function() {
<add> this.greeting = this.salutation + ' ' + this.name + '!';
<add> }); // initialize the watch
<add>
<add> expect(scope.greeting).toEqual(undefined);
<add> scope.name = 'Misko';
<add> // still old value, since watches have not been called yet
<add> expect(scope.greeting).toEqual(undefined);
<add>
<add> scope.$digest(); // fire all the watches
<add> expect(scope.greeting).toEqual('Hello Misko!');
<add> * </pre>
<ide> *
<add> * # Inheritance
<add> * A scope can inherit from a parent scope, as in this example:
<add> * <pre>
<add> var parent = angular.scope();
<add> var child = parent.$new();
<add>
<add> parent.salutation = "Hello";
<add> child.name = "World";
<add> expect(child.salutation).toEqual('Hello');
<add>
<add> child.salutation = "Welcome";
<add> expect(child.salutation).toEqual('Welcome');
<add> expect(parent.salutation).toEqual('Hello');
<add> * </pre>
<ide> *
<add> * # Dependency Injection
<add> * See {@link guide/dev_guide.di dependency injection}.
<ide> *
<del> * @param {(function()|string)} watchExpression Expression that is evaluated on each
<del> * {@link angular.scope.$digest $digest} cycle. A change in the return value triggers a
<del> * call to the `listener`.
<ide> *
<del> * - `string`: Evaluated as {@link guide/dev_guide.expressions expression}
<del> * - `function(scope)`: called with current `scope` as a parameter.
<del> * @param {(function()|string)=} listener Callback called whenever the return value of
<del> * the `watchExpression` changes.
<add> * @param {Object.<string, function()>=} providers Map of service factory which need to be provided
<add> * for the current scope. Defaults to {@link angular.service}.
<add> * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
<add> * append/override services provided by `providers`. This is handy when unit-testing and having
<add> * the need to override a default service.
<add> * @returns {Object} Newly created scope.
<ide> *
<del> * - `string`: Evaluated as {@link guide/dev_guide.expressions expression}
<del> * - `function(scope, newValue, oldValue)`: called with current `scope` an previous and
<del> * current values as parameters.
<del> * @returns {function()} Returns a deregistration function for this listener.
<ide> */
<del> $watch: function(watchExp, listener) {
<del> var scope = this,
<del> get = compileToFn(watchExp, 'watch'),
<del> listenFn = compileToFn(listener || noop, 'listener'),
<del> array = scope.$$watchers,
<del> watcher = {
<del> fn: listenFn,
<del> last: Number.NaN, // NaN !== NaN. We used this to force $watch to fire on first run.
<del> get: get,
<del> exp: watchExp
<del> };
<del>
<del> if (!array) {
<del> array = scope.$$watchers = [];
<del> }
<del> // we use unshift since we use a while loop in $digest for speed.
<del> // the while loop reads in reverse order.
<del> array.unshift(watcher);
<del>
<del> return function() {
<del> angularArray.remove(array, watcher);
<del> };
<del> },
<add> function Scope() {
<add> this.$id = nextUid();
<add> this.$$phase = this.$parent = this.$$watchers =
<add> this.$$nextSibling = this.$$prevSibling =
<add> this.$$childHead = this.$$childTail = null;
<add> this.$destructor = noop;
<add> this['this'] = this.$root = this;
<add> this.$$asyncQueue = [];
<add> this.$$listeners = {};
<add> }
<ide>
<ide> /**
<del> * @ngdoc function
<del> * @name angular.scope.$digest
<del> * @function
<del> *
<del> * @description
<del> * Process all of the {@link angular.scope.$watch watchers} of the current scope and its children.
<del> * Because a {@link angular.scope.$watch watcher}'s listener can change the model, the
<del> * `$digest()` keeps calling the {@link angular.scope.$watch watchers} until no more listeners are
<del> * firing. This means that it is possible to get into an infinite loop. This function will throw
<del> * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 100.
<del> *
<del> * Usually you don't call `$digest()` directly in
<del> * {@link angular.directive.ng:controller controllers} or in {@link angular.directive directives}.
<del> * Instead a call to {@link angular.scope.$apply $apply()} (typically from within a
<del> * {@link angular.directive directive}) will force a `$digest()`.
<del> *
<del> * If you want to be notified whenever `$digest()` is called,
<del> * you can register a `watchExpression` function with {@link angular.scope.$watch $watch()}
<del> * with no `listener`.
<del> *
<del> * You may have a need to call `$digest()` from within unit-tests, to simulate the scope
<del> * life-cycle.
<del> *
<del> * # Example
<del> <pre>
<del> var scope = angular.scope();
<del> scope.name = 'misko';
<del> scope.counter = 0;
<del>
<del> expect(scope.counter).toEqual(0);
<del> scope.$digest('name', function(scope, newValue, oldValue) { counter = counter + 1; });
<del> expect(scope.counter).toEqual(0);
<del>
<del> scope.$digest();
<del> // no variable change
<del> expect(scope.counter).toEqual(0);
<del>
<del> scope.name = 'adam';
<del> scope.$digest();
<del> expect(scope.counter).toEqual(1);
<del> </pre>
<del> *
<add> * @ngdoc property
<add> * @name angular.scope.$id
<add> * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
<add> * debugging.
<ide> */
<del> $digest: function() {
<del> var watch, value, last,
<del> watchers,
<del> asyncQueue,
<del> length,
<del> dirty, ttl = 100,
<del> next, current, target = this,
<del> watchLog = [];
<del>
<del> if (target.$$phase) {
<del> throw Error(target.$$phase + ' already in progress');
<del> }
<del> do {
<ide>
<del> dirty = false;
<del> current = target;
<del> do {
<del> current.$$phase = '$digest';
<del> asyncQueue = current.$$asyncQueue;
<del> while(asyncQueue.length) {
<del> try {
<del> current.$eval(asyncQueue.shift());
<del> } catch (e) {
<del> current.$service('$exceptionHandler')(e);
<del> }
<add>
<add> Scope.prototype = {
<add> /**
<add> * @ngdoc function
<add> * @name angular.scope.$new
<add> * @function
<add> *
<add> * @description
<add> * Creates a new child {@link angular.scope scope}. The new scope can optionally behave as a
<add> * controller. The parent scope will propagate the {@link angular.scope.$digest $digest()} and
<add> * {@link angular.scope.$digest $digest()} events. The scope can be removed from the scope
<add> * hierarchy using {@link angular.scope.$destroy $destroy()}.
<add> *
<add> * {@link angular.scope.$destroy $destroy()} must be called on a scope when it is desired for
<add> * the scope and its child scopes to be permanently detached from the parent and thus stop
<add> * participating in model change detection and listener notification by invoking.
<add> *
<add> * @param {function()=} Class Constructor function which the scope should be applied to the scope.
<add> * @param {...*} curryArguments Any additional arguments which are curried into the constructor.
<add> * See {@link guide/dev_guide.di dependency injection}.
<add> * @returns {Object} The newly created child scope.
<add> *
<add> */
<add> $new: function(Class, curryArguments) {
<add> var Child = function() {}; // should be anonymous; This is so that when the minifier munges
<add> // the name it does not become random set of chars. These will then show up as class
<add> // name in the debugger.
<add> var child;
<add> Child.prototype = this;
<add> child = new Child();
<add> child['this'] = child;
<add> child.$$listeners = {};
<add> child.$parent = this;
<add> child.$id = nextUid();
<add> child.$$asyncQueue = [];
<add> child.$$phase = child.$$watchers =
<add> child.$$nextSibling = child.$$childHead = child.$$childTail = null;
<add> child.$$prevSibling = this.$$childTail;
<add> if (this.$$childHead) {
<add> this.$$childTail.$$nextSibling = child;
<add> this.$$childTail = child;
<add> } else {
<add> this.$$childHead = this.$$childTail = child;
<add> }
<add> // short circuit if we have no class
<add> if (Class) {
<add> // can't use forEach, we need speed!
<add> var ClassPrototype = Class.prototype;
<add> for(var key in ClassPrototype) {
<add> child[key] = bind(child, ClassPrototype[key]);
<ide> }
<del> if ((watchers = current.$$watchers)) {
<del> // process our watches
<del> length = watchers.length;
<del> while (length--) {
<add> $injector.invoke(child, Class, curryArguments);
<add> }
<add> return child;
<add> },
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.scope.$watch
<add> * @function
<add> *
<add> * @description
<add> * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
<add> *
<add> * - The `watchExpression` is called on every call to {@link angular.scope.$digest $digest()} and
<add> * should return the value which will be watched. (Since {@link angular.scope.$digest $digest()}
<add> * reruns when it detects changes the `watchExpression` can execute multiple times per
<add> * {@link angular.scope.$digest $digest()} and should be idempotent.)
<add> * - The `listener` is called only when the value from the current `watchExpression` and the
<add> * previous call to `watchExpression' are not equal. The inequality is determined according to
<add> * {@link angular.equals} function. To save the value of the object for later comparison
<add> * {@link angular.copy} function is used. It also means that watching complex options will
<add> * have adverse memory and performance implications.
<add> * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
<add> * is achieved by rerunning the watchers until no changes are detected. The rerun iteration
<add> * limit is 100 to prevent infinity loop deadlock.
<add> *
<add> *
<add> * If you want to be notified whenever {@link angular.scope.$digest $digest} is called,
<add> * you can register an `watchExpression` function with no `listener`. (Since `watchExpression`,
<add> * can execute multiple times per {@link angular.scope.$digest $digest} cycle when a change is
<add> * detected, be prepared for multiple calls to your listener.)
<add> *
<add> *
<add> * # Example
<add> <pre>
<add> var scope = angular.scope();
<add> scope.name = 'misko';
<add> scope.counter = 0;
<add>
<add> expect(scope.counter).toEqual(0);
<add> scope.$watch('name', function(scope, newValue, oldValue) { counter = counter + 1; });
<add> expect(scope.counter).toEqual(0);
<add>
<add> scope.$digest();
<add> // no variable change
<add> expect(scope.counter).toEqual(0);
<add>
<add> scope.name = 'adam';
<add> scope.$digest();
<add> expect(scope.counter).toEqual(1);
<add> </pre>
<add> *
<add> *
<add> *
<add> * @param {(function()|string)} watchExpression Expression that is evaluated on each
<add> * {@link angular.scope.$digest $digest} cycle. A change in the return value triggers a
<add> * call to the `listener`.
<add> *
<add> * - `string`: Evaluated as {@link guide/dev_guide.expressions expression}
<add> * - `function(scope)`: called with current `scope` as a parameter.
<add> * @param {(function()|string)=} listener Callback called whenever the return value of
<add> * the `watchExpression` changes.
<add> *
<add> * - `string`: Evaluated as {@link guide/dev_guide.expressions expression}
<add> * - `function(scope, newValue, oldValue)`: called with current `scope` an previous and
<add> * current values as parameters.
<add> * @returns {function()} Returns a deregistration function for this listener.
<add> */
<add> $watch: function(watchExp, listener) {
<add> var scope = this,
<add> get = compileToFn(watchExp, 'watch'),
<add> listenFn = compileToFn(listener || noop, 'listener'),
<add> array = scope.$$watchers,
<add> watcher = {
<add> fn: listenFn,
<add> last: Number.NaN, // NaN !== NaN. We used this to force $watch to fire on first run.
<add> get: get,
<add> exp: watchExp
<add> };
<add>
<add> if (!array) {
<add> array = scope.$$watchers = [];
<add> }
<add> // we use unshift since we use a while loop in $digest for speed.
<add> // the while loop reads in reverse order.
<add> array.unshift(watcher);
<add>
<add> return function() {
<add> angularArray.remove(array, watcher);
<add> };
<add> },
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.scope.$digest
<add> * @function
<add> *
<add> * @description
<add> * Process all of the {@link angular.scope.$watch watchers} of the current scope and its children.
<add> * Because a {@link angular.scope.$watch watcher}'s listener can change the model, the
<add> * `$digest()` keeps calling the {@link angular.scope.$watch watchers} until no more listeners are
<add> * firing. This means that it is possible to get into an infinite loop. This function will throw
<add> * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 100.
<add> *
<add> * Usually you don't call `$digest()` directly in
<add> * {@link angular.directive.ng:controller controllers} or in {@link angular.directive directives}.
<add> * Instead a call to {@link angular.scope.$apply $apply()} (typically from within a
<add> * {@link angular.directive directive}) will force a `$digest()`.
<add> *
<add> * If you want to be notified whenever `$digest()` is called,
<add> * you can register a `watchExpression` function with {@link angular.scope.$watch $watch()}
<add> * with no `listener`.
<add> *
<add> * You may have a need to call `$digest()` from within unit-tests, to simulate the scope
<add> * life-cycle.
<add> *
<add> * # Example
<add> <pre>
<add> var scope = angular.scope();
<add> scope.name = 'misko';
<add> scope.counter = 0;
<add>
<add> expect(scope.counter).toEqual(0);
<add> scope.$digest('name', function(scope, newValue, oldValue) { counter = counter + 1; });
<add> expect(scope.counter).toEqual(0);
<add>
<add> scope.$digest();
<add> // no variable change
<add> expect(scope.counter).toEqual(0);
<add>
<add> scope.name = 'adam';
<add> scope.$digest();
<add> expect(scope.counter).toEqual(1);
<add> </pre>
<add> *
<add> */
<add> $digest: function() {
<add> var watch, value, last,
<add> watchers,
<add> asyncQueue,
<add> length,
<add> dirty, ttl = 100,
<add> next, current, target = this,
<add> watchLog = [];
<add>
<add> if (target.$$phase) {
<add> throw Error(target.$$phase + ' already in progress');
<add> }
<add> do {
<add>
<add> dirty = false;
<add> current = target;
<add> do {
<add> current.$$phase = '$digest';
<add> asyncQueue = current.$$asyncQueue;
<add> while(asyncQueue.length) {
<ide> try {
<del> watch = watchers[length];
<del> // Most common watches are on primitives, in which case we can short
<del> // circuit it with === operator, only when === fails do we use .equals
<del> if ((value = watch.get(current)) !== (last = watch.last) && !equals(value, last)) {
<del> dirty = true;
<del> watch.last = copy(value);
<del> watch.fn(current, value, last);
<del> if (ttl < 5) {
<del> if (!watchLog[4-ttl]) watchLog[4-ttl] = [];
<del> if (isFunction(watch.exp)) {
<del> watchLog[4-ttl].push('fn: ' + (watch.exp.name || watch.exp.toString()));
<del> } else {
<del> watchLog[4-ttl].push(watch.exp);
<add> current.$eval(asyncQueue.shift());
<add> } catch (e) {
<add> current.$service('$exceptionHandler')(e);
<add> }
<add> }
<add> if ((watchers = current.$$watchers)) {
<add> // process our watches
<add> length = watchers.length;
<add> while (length--) {
<add> try {
<add> watch = watchers[length];
<add> // Most common watches are on primitives, in which case we can short
<add> // circuit it with === operator, only when === fails do we use .equals
<add> if ((value = watch.get(current)) !== (last = watch.last) && !equals(value, last)) {
<add> dirty = true;
<add> watch.last = copy(value);
<add> watch.fn(current, value, last);
<add> if (ttl < 5) {
<add> if (!watchLog[4-ttl]) watchLog[4-ttl] = [];
<add> if (isFunction(watch.exp)) {
<add> watchLog[4-ttl].push('fn: ' + (watch.exp.name || watch.exp.toString()));
<add> } else {
<add> watchLog[4-ttl].push(watch.exp);
<add> }
<ide> }
<ide> }
<add> } catch (e) {
<add> $exceptionHandler(e);
<ide> }
<del> } catch (e) {
<del> current.$service('$exceptionHandler')(e);
<ide> }
<ide> }
<add>
<add> current.$$phase = null;
<add>
<add> // Insanity Warning: scope depth-first traversal
<add> // yes, this code is a bit crazy, but it works and we have tests to prove it!
<add> // this piece should be kept in sync with the traversal in $broadcast
<add> if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
<add> while(current !== target && !(next = current.$$nextSibling)) {
<add> current = current.$parent;
<add> }
<add> }
<add> } while ((current = next));
<add>
<add> if(!(ttl--)) {
<add> throw Error('100 $digest() iterations reached. Aborting!\n' +
<add> 'Watchers fired in the last 5 iterations: ' + toJson(watchLog));
<ide> }
<add> } while (dirty);
<add> },
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.scope.$destroy
<add> * @function
<add> *
<add> * @description
<add> * Remove the current scope (and all of its children) from the parent scope. Removal implies
<add> * that calls to {@link angular.scope.$digest $digest()} will no longer propagate to the current
<add> * scope and its children. Removal also implies that the current scope is eligible for garbage
<add> * collection.
<add> *
<add> * The destructing scope emits an `$destroy` {@link angular.scope.$emit event}.
<add> *
<add> * The `$destroy()` is usually used by directives such as
<add> * {@link angular.widget.@ng:repeat ng:repeat} for managing the unrolling of the loop.
<add> *
<add> */
<add> $destroy: function() {
<add> if (this.$root == this) return; // we can't remove the root node;
<add> this.$emit('$destroy');
<add> var parent = this.$parent;
<add>
<add> if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
<add> if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
<add> if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
<add> if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
<add> },
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.scope.$eval
<add> * @function
<add> *
<add> * @description
<add> * Executes the `expression` on the current scope returning the result. Any exceptions in the
<add> * expression are propagated (uncaught). This is useful when evaluating engular expressions.
<add> *
<add> * # Example
<add> <pre>
<add> var scope = angular.scope();
<add> scope.a = 1;
<add> scope.b = 2;
<add>
<add> expect(scope.$eval('a+b')).toEqual(3);
<add> expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
<add> </pre>
<add> *
<add> * @param {(string|function())=} expression An angular expression to be executed.
<add> *
<add> * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}.
<add> * - `function(scope)`: execute the function with the current `scope` parameter.
<add> *
<add> * @returns {*} The result of evaluating the expression.
<add> */
<add> $eval: function(expr) {
<add> var fn = isString(expr)
<add> ? expressionCompile(expr)
<add> : expr || noop;
<add> return fn(this);
<add> },
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.scope.$evalAsync
<add> * @function
<add> *
<add> * @description
<add> * Executes the expression on the current scope at a later point in time.
<add> *
<add> * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
<add> *
<add> * - it will execute in the current script execution context (before any DOM rendering).
<add> * - at least one {@link angular.scope.$digest $digest cycle} will be performed after
<add> * `expression` execution.
<add> *
<add> * Any exceptions from the execution of the expression are forwarded to the
<add> * {@link angular.service.$exceptionHandler $exceptionHandler} service.
<add> *
<add> * @param {(string|function())=} expression An angular expression to be executed.
<add> *
<add> * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}.
<add> * - `function(scope)`: execute the function with the current `scope` parameter.
<add> *
<add> */
<add> $evalAsync: function(expr) {
<add> this.$$asyncQueue.push(expr);
<add> },
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.scope.$apply
<add> * @function
<add> *
<add> * @description
<add> * `$apply()` is used to execute an expression in angular from outside of the angular framework.
<add> * (For example from browser DOM events, setTimeout, XHR or third party libraries).
<add> * Because we are calling into the angular framework we need to perform proper scope life-cycle
<add> * of {@link angular.service.$exceptionHandler exception handling},
<add> * {@link angular.scope.$digest executing watches}.
<add> *
<add> * ## Life cycle
<add> *
<add> * # Pseudo-Code of `$apply()`
<add> function $apply(expr) {
<add> try {
<add> return $eval(expr);
<add> } catch (e) {
<add> $exceptionHandler(e);
<add> } finally {
<add> $root.$digest();
<add> }
<add> }
<add> *
<add> *
<add> * Scope's `$apply()` method transitions through the following stages:
<add> *
<add> * 1. The {@link guide/dev_guide.expressions expression} is executed using the
<add> * {@link angular.scope.$eval $eval()} method.
<add> * 2. Any exceptions from the execution of the expression are forwarded to the
<add> * {@link angular.service.$exceptionHandler $exceptionHandler} service.
<add> * 3. The {@link angular.scope.$watch watch} listeners are fired immediately after the expression
<add> * was executed using the {@link angular.scope.$digest $digest()} method.
<add> *
<add> *
<add> * @param {(string|function())=} exp An angular expression to be executed.
<add> *
<add> * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}.
<add> * - `function(scope)`: execute the function with current `scope` parameter.
<add> *
<add> * @returns {*} The result of evaluating the expression.
<add> */
<add> $apply: function(expr) {
<add> try {
<add> return this.$eval(expr);
<add> } catch (e) {
<add> $exceptionHandler(e);
<add> } finally {
<add> this.$root.$digest();
<add> }
<add> },
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.scope.$on
<add> * @function
<add> *
<add> * @description
<add> * Listen on events of a given type. See {@link angular.scope.$emit $emit} for discussion of
<add> * event life cycle.
<add> *
<add> * @param {string} name Event name to listen on.
<add> * @param {function(event)} listener Function to call when the event is emitted.
<add> * @returns {function()} Returns a deregistration function for this listener.
<add> *
<add> * The event listener function format is: `function(event)`. The `event` object passed into the
<add> * listener has the following attributes
<add> * - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed.
<add> * - `currentScope` - {Scope}: the current scope which is handling the event.
<add> * - `name` - {string}: Name of the event.
<add> * - `cancel` - {function=}: calling `cancel` function will cancel further event propagation
<add> * (available only for events that were `$emit`-ed).
<add> */
<add> $on: function(name, listener) {
<add> var namedListeners = this.$$listeners[name];
<add> if (!namedListeners) {
<add> this.$$listeners[name] = namedListeners = [];
<add> }
<add> namedListeners.push(listener);
<add>
<add> return function() {
<add> angularArray.remove(namedListeners, listener);
<add> };
<add> },
<add>
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.scope.$emit
<add> * @function
<add> *
<add> * @description
<add> * Dispatches an event `name` upwards through the scope hierarchy notifying the
<add> * registered {@link angular.scope.$on} listeners.
<add> *
<add> * The event life cycle starts at the scope on which `$emit` was called. All
<add> * {@link angular.scope.$on listeners} listening for `name` event on this scope get notified.
<add> * Afterwards, the event traverses upwards toward the root scope and calls all registered
<add> * listeners along the way. The event will stop propagating if one of the listeners cancels it.
<add> *
<add> * Any exception emmited from the {@link angular.scope.$on listeners} will be passed
<add> * onto the {@link angular.service.$exceptionHandler $exceptionHandler} service.
<add> *
<add> * @param {string} name Event name to emit.
<add> * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
<add> */
<add> $emit: function(name, args) {
<add> var empty = [],
<add> namedListeners,
<add> canceled = false,
<add> scope = this,
<add> event = {
<add> name: name,
<add> targetScope: scope,
<add> cancel: function() {canceled = true;}
<add> },
<add> listenerArgs = concat([event], arguments, 1),
<add> i, length;
<ide>
<del> current.$$phase = null;
<add> do {
<add> namedListeners = scope.$$listeners[name] || empty;
<add> event.currentScope = scope;
<add> for (i=0, length=namedListeners.length; i<length; i++) {
<add> try {
<add> namedListeners[i].apply(null, listenerArgs);
<add> if (canceled) return;
<add> } catch (e) {
<add> $exceptionHandler(e);
<add> }
<add> }
<add> //traverse upwards
<add> scope = scope.$parent;
<add> } while (scope);
<add> },
<add>
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.scope.$broadcast
<add> * @function
<add> *
<add> * @description
<add> * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
<add> * registered {@link angular.scope.$on} listeners.
<add> *
<add> * The event life cycle starts at the scope on which `$broadcast` was called. All
<add> * {@link angular.scope.$on listeners} listening for `name` event on this scope get notified.
<add> * Afterwards, the event propagates to all direct and indirect scopes of the current scope and
<add> * calls all registered listeners along the way. The event cannot be canceled.
<add> *
<add> * Any exception emmited from the {@link angular.scope.$on listeners} will be passed
<add> * onto the {@link angular.service.$exceptionHandler $exceptionHandler} service.
<add> *
<add> * @param {string} name Event name to emit.
<add> * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
<add> */
<add> $broadcast: function(name, args) {
<add> var target = this,
<add> current = target,
<add> next = target,
<add> event = { name: name,
<add> targetScope: target },
<add> listenerArgs = concat([event], arguments, 1);
<add>
<add> //down while you can, then up and next sibling or up and next sibling until back at root
<add> do {
<add> current = next;
<add> event.currentScope = current;
<add> forEach(current.$$listeners[name], function(listener) {
<add> try {
<add> listener.apply(null, listenerArgs);
<add> } catch(e) {
<add> $exceptionHandler(e);
<add> }
<add> });
<ide>
<ide> // Insanity Warning: scope depth-first traversal
<ide> // yes, this code is a bit crazy, but it works and we have tests to prove it!
<del> // this piece should be kept in sync with the traversal in $broadcast
<add> // this piece should be kept in sync with the traversal in $digest
<ide> if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
<ide> while(current !== target && !(next = current.$$nextSibling)) {
<ide> current = current.$parent;
<ide> }
<ide> }
<ide> } while ((current = next));
<del>
<del> if(!(ttl--)) {
<del> throw Error('100 $digest() iterations reached. Aborting!\n' +
<del> 'Watchers fired in the last 5 iterations: ' + toJson(watchLog));
<del> }
<del> } while (dirty);
<del> },
<del>
<del> /**
<del> * @ngdoc function
<del> * @name angular.scope.$destroy
<del> * @function
<del> *
<del> * @description
<del> * Remove the current scope (and all of its children) from the parent scope. Removal implies
<del> * that calls to {@link angular.scope.$digest $digest()} will no longer propagate to the current
<del> * scope and its children. Removal also implies that the current scope is eligible for garbage
<del> * collection.
<del> *
<del> * The destructing scope emits an `$destroy` {@link angular.scope.$emit event}.
<del> *
<del> * The `$destroy()` is usually used by directives such as
<del> * {@link angular.widget.@ng:repeat ng:repeat} for managing the unrolling of the loop.
<del> *
<del> */
<del> $destroy: function() {
<del> if (this.$root == this) return; // we can't remove the root node;
<del> this.$emit('$destroy');
<del> var parent = this.$parent;
<del>
<del> if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
<del> if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
<del> if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
<del> if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
<del> },
<del>
<del> /**
<del> * @ngdoc function
<del> * @name angular.scope.$eval
<del> * @function
<del> *
<del> * @description
<del> * Executes the `expression` on the current scope returning the result. Any exceptions in the
<del> * expression are propagated (uncaught). This is useful when evaluating engular expressions.
<del> *
<del> * # Example
<del> <pre>
<del> var scope = angular.scope();
<del> scope.a = 1;
<del> scope.b = 2;
<del>
<del> expect(scope.$eval('a+b')).toEqual(3);
<del> expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
<del> </pre>
<del> *
<del> * @param {(string|function())=} expression An angular expression to be executed.
<del> *
<del> * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}.
<del> * - `function(scope)`: execute the function with the current `scope` parameter.
<del> *
<del> * @returns {*} The result of evaluating the expression.
<del> */
<del> $eval: function(expr) {
<del> var fn = isString(expr)
<del> ? expressionCompile(expr)
<del> : expr || noop;
<del> return fn(this);
<del> },
<del>
<del> /**
<del> * @ngdoc function
<del> * @name angular.scope.$evalAsync
<del> * @function
<del> *
<del> * @description
<del> * Executes the expression on the current scope at a later point in time.
<del> *
<del> * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
<del> *
<del> * - it will execute in the current script execution context (before any DOM rendering).
<del> * - at least one {@link angular.scope.$digest $digest cycle} will be performed after
<del> * `expression` execution.
<del> *
<del> * Any exceptions from the execution of the expression are forwarded to the
<del> * {@link angular.service.$exceptionHandler $exceptionHandler} service.
<del> *
<del> * @param {(string|function())=} expression An angular expression to be executed.
<del> *
<del> * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}.
<del> * - `function(scope)`: execute the function with the current `scope` parameter.
<del> *
<del> */
<del> $evalAsync: function(expr) {
<del> this.$$asyncQueue.push(expr);
<del> },
<del>
<del> /**
<del> * @ngdoc function
<del> * @name angular.scope.$apply
<del> * @function
<del> *
<del> * @description
<del> * `$apply()` is used to execute an expression in angular from outside of the angular framework.
<del> * (For example from browser DOM events, setTimeout, XHR or third party libraries).
<del> * Because we are calling into the angular framework we need to perform proper scope life-cycle
<del> * of {@link angular.service.$exceptionHandler exception handling},
<del> * {@link angular.scope.$digest executing watches}.
<del> *
<del> * ## Life cycle
<del> *
<del> * # Pseudo-Code of `$apply()`
<del> function $apply(expr) {
<del> try {
<del> return $eval(expr);
<del> } catch (e) {
<del> $exceptionHandler(e);
<del> } finally {
<del> $root.$digest();
<del> }
<del> }
<del> *
<del> *
<del> * Scope's `$apply()` method transitions through the following stages:
<del> *
<del> * 1. The {@link guide/dev_guide.expressions expression} is executed using the
<del> * {@link angular.scope.$eval $eval()} method.
<del> * 2. Any exceptions from the execution of the expression are forwarded to the
<del> * {@link angular.service.$exceptionHandler $exceptionHandler} service.
<del> * 3. The {@link angular.scope.$watch watch} listeners are fired immediately after the expression
<del> * was executed using the {@link angular.scope.$digest $digest()} method.
<del> *
<del> *
<del> * @param {(string|function())=} exp An angular expression to be executed.
<del> *
<del> * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}.
<del> * - `function(scope)`: execute the function with current `scope` parameter.
<del> *
<del> * @returns {*} The result of evaluating the expression.
<del> */
<del> $apply: function(expr) {
<del> try {
<del> return this.$eval(expr);
<del> } catch (e) {
<del> this.$service('$exceptionHandler')(e);
<del> } finally {
<del> this.$root.$digest();
<ide> }
<del> },
<del>
<del> /**
<del> * @ngdoc function
<del> * @name angular.scope.$on
<del> * @function
<del> *
<del> * @description
<del> * Listen on events of a given type. See {@link angular.scope.$emit $emit} for discussion of
<del> * event life cycle.
<del> *
<del> * @param {string} name Event name to listen on.
<del> * @param {function(event)} listener Function to call when the event is emitted.
<del> * @returns {function()} Returns a deregistration function for this listener.
<del> *
<del> * The event listener function format is: `function(event)`. The `event` object passed into the
<del> * listener has the following attributes
<del> * - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed.
<del> * - `currentScope` - {Scope}: the current scope which is handling the event.
<del> * - `name` - {string}: Name of the event.
<del> * - `cancel` - {function=}: calling `cancel` function will cancel further event propagation
<del> * (available only for events that were `$emit`-ed).
<del> */
<del> $on: function(name, listener) {
<del> var namedListeners = this.$$listeners[name];
<del> if (!namedListeners) {
<del> this.$$listeners[name] = namedListeners = [];
<del> }
<del> namedListeners.push(listener);
<del>
<del> return function() {
<del> angularArray.remove(namedListeners, listener);
<del> };
<del> },
<del>
<del>
<del> /**
<del> * @ngdoc function
<del> * @name angular.scope.$emit
<del> * @function
<del> *
<del> * @description
<del> * Dispatches an event `name` upwards through the scope hierarchy notifying the
<del> * registered {@link angular.scope.$on} listeners.
<del> *
<del> * The event life cycle starts at the scope on which `$emit` was called. All
<del> * {@link angular.scope.$on listeners} listening for `name` event on this scope get notified.
<del> * Afterwards, the event traverses upwards toward the root scope and calls all registered
<del> * listeners along the way. The event will stop propagating if one of the listeners cancels it.
<del> *
<del> * Any exception emmited from the {@link angular.scope.$on listeners} will be passed
<del> * onto the {@link angular.service.$exceptionHandler $exceptionHandler} service.
<del> *
<del> * @param {string} name Event name to emit.
<del> * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
<del> */
<del> $emit: function(name, args) {
<del> var empty = [],
<del> namedListeners,
<del> canceled = false,
<del> scope = this,
<del> event = {
<del> name: name,
<del> targetScope: scope,
<del> cancel: function() {canceled = true;}
<del> },
<del> listenerArgs = concat([event], arguments, 1),
<del> i, length;
<del>
<del> do {
<del> namedListeners = scope.$$listeners[name] || empty;
<del> event.currentScope = scope;
<del> for (i=0, length=namedListeners.length; i<length; i++) {
<del> try {
<del> namedListeners[i].apply(null, listenerArgs);
<del> if (canceled) return;
<del> } catch (e) {
<del> scope.$service('$exceptionHandler')(e);
<del> }
<del> }
<del> //traverse upwards
<del> scope = scope.$parent;
<del> } while (scope);
<del> },
<add> };
<ide>
<add> // TODO(misko): remove this;
<add> var scope = new Scope();
<add> scope.$service = $injector;
<add> return scope;
<ide>
<del> /**
<del> * @ngdoc function
<del> * @name angular.scope.$broadcast
<del> * @function
<del> *
<del> * @description
<del> * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
<del> * registered {@link angular.scope.$on} listeners.
<del> *
<del> * The event life cycle starts at the scope on which `$broadcast` was called. All
<del> * {@link angular.scope.$on listeners} listening for `name` event on this scope get notified.
<del> * Afterwards, the event propagates to all direct and indirect scopes of the current scope and
<del> * calls all registered listeners along the way. The event cannot be canceled.
<del> *
<del> * Any exception emmited from the {@link angular.scope.$on listeners} will be passed
<del> * onto the {@link angular.service.$exceptionHandler $exceptionHandler} service.
<del> *
<del> * @param {string} name Event name to emit.
<del> * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
<del> */
<del> $broadcast: function(name, args) {
<del> var target = this,
<del> current = target,
<del> next = target,
<del> event = { name: name,
<del> targetScope: target },
<del> listenerArgs = concat([event], arguments, 1);
<del>
<del> //down while you can, then up and next sibling or up and next sibling until back at root
<del> do {
<del> current = next;
<del> event.currentScope = current;
<del> forEach(current.$$listeners[name], function(listener) {
<del> try {
<del> listener.apply(null, listenerArgs);
<del> } catch(e) {
<del> current.$service('$exceptionHandler')(e);
<del> }
<del> });
<del>
<del> // Insanity Warning: scope depth-first traversal
<del> // yes, this code is a bit crazy, but it works and we have tests to prove it!
<del> // this piece should be kept in sync with the traversal in $digest
<del> if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
<del> while(current !== target && !(next = current.$$nextSibling)) {
<del> current = current.$parent;
<del> }
<del> }
<del> } while ((current = next));
<add> function compileToFn(exp, name) {
<add> var fn = isString(exp)
<add> ? expressionCompile(exp)
<add> : exp;
<add> assertArgFn(fn, name);
<add> return fn;
<ide> }
<del>};
<ide>
<ide>
<del>function compileToFn(exp, name) {
<del> var fn = isString(exp)
<del> ? expressionCompile(exp)
<del> : exp;
<del> assertArgFn(fn, name);
<del> return fn;
<del>}
<add>}, ['$injector', '$exceptionHandler']);
<ide><path>src/service/xhr.bulk.js
<ide> *
<ide> * @example
<ide> */
<del>angularServiceInject('$xhr.bulk', function($xhr, $error, $log){
<del> var requests = [],
<del> scope = this;
<add>angularServiceInject('$xhr.bulk', function($rootScope, $xhr, $error, $log){
<add> var requests = [];
<ide> function bulkXHR(method, url, post, success, error) {
<ide> if (isFunction(post)) {
<ide> error = success;
<ide> angularServiceInject('$xhr.bulk', function($xhr, $error, $log){
<ide> }
<ide> });
<ide> };
<del> this.$watch(function() { bulkXHR.flush(); });
<add> $rootScope.$watch(function() { bulkXHR.flush(); });
<ide> return bulkXHR;
<del>}, ['$xhr', '$xhr.error', '$log']);
<add>}, ['$rootScope', '$xhr', '$xhr.error', '$log']);
<ide><path>src/service/xhr.cache.js
<ide> * @param {boolean=} [sync=false] in case of cache hit execute `success` synchronously.
<ide> */
<ide> angularServiceInject('$xhr.cache', function($xhr, $defer, $error, $log) {
<del> var inflight = {}, self = this;
<add> var inflight = {};
<ide> function cache(method, url, post, success, error, verifyCache, sync) {
<ide> if (isFunction(post)) {
<ide> if (!isFunction(success)) {
<ide><path>src/service/xhr.js
<ide> </doc:scenario>
<ide> </doc:example>
<ide> */
<del>angularServiceInject('$xhr', function($browser, $error, $log){
<del> var rootScope = this;
<add>angularServiceInject('$xhr', function($rootScope, $browser, $error, $log){
<ide> var xhrHeaderDefaults = {
<ide> common: {
<ide> "Accept": "application/json, text/plain, */*",
<ide> angularServiceInject('$xhr', function($browser, $error, $log){
<ide> response = fromJson(response, true);
<ide> }
<ide> }
<del> rootScope.$apply(function() {
<add> $rootScope.$apply(function() {
<ide> if (200 <= code && code < 300) {
<ide> success(code, response);
<ide> } else if (isFunction(error)) {
<ide> angularServiceInject('$xhr', function($browser, $error, $log){
<ide> xhr.defaults = {headers: xhrHeaderDefaults};
<ide>
<ide> return xhr;
<del>}, ['$browser', '$xhr.error', '$log']);
<add>}, ['$rootScope', '$browser', '$xhr.error', '$log']);
<ide><path>test/AngularSpec.js
<ide> describe('angular', function() {
<ide> '</div>' +
<ide> '</div>');
<ide> });
<del>
<del>
<del> xit('should add custom css when specified via css', function() {
<del> //TODO
<del> });
<ide> });
<ide>
<ide>
<ide> describe('angular service', function() {
<del> it('should override services', function() {
<del> var scope = createScope();
<del> angular.service('fake', function() { return 'old'; });
<del> angular.service('fake', function() { return 'new'; });
<del>
<del> expect(scope.$service('fake')).toEqual('new');
<del> });
<add> it('should override services', inject(function(service){
<add> service('fake', function() { return 'old'; });
<add> service('fake', function() { return 'new'; });
<add> }, function(fake) {
<add> expect(fake).toEqual('new');
<add> }));
<ide>
<ide> it('should not preserve properties on override', function() {
<ide> angular.service('fake', {$one: true}, {$two: true}, {three: true});
<ide> describe('angular', function() {
<ide> it('should inject dependencies specified by $inject', function() {
<ide> angular.service('svc1', function() { return 'svc1'; });
<ide> angular.service('svc2', function(svc1) { return 'svc2-' + svc1; }, {$inject: ['svc1']});
<del> expect(angular.scope().$service('svc2')).toEqual('svc2-svc1');
<add> expect(createInjector()('svc2')).toEqual('svc2-svc1');
<ide> });
<ide>
<ide> it('should inject dependencies specified by $inject and ignore function argument name', function() {
<ide> angular.service('svc1', function() { return 'svc1'; });
<ide> angular.service('svc2', function(foo) { return 'svc2-' + foo; }, {$inject: ['svc1']});
<del> expect(angular.scope().$service('svc2')).toEqual('svc2-svc1');
<add> expect(createInjector()('svc2')).toEqual('svc2-svc1');
<ide> });
<ide>
<ide> it('should eagerly instantiate a service if $eager is true', function() {
<ide> var log = [];
<ide> angular.service('svc1', function() { log.push('svc1'); }, {$eager: true});
<del> angular.scope();
<add> createInjector();
<ide> expect(log).toEqual(['svc1']);
<ide> });
<ide> });
<ide> describe('angular', function() {
<ide> });
<ide>
<ide> describe('compile', function() {
<del> var scope, template;
<del>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<del>
<del> it('should link to existing node and create scope', function() {
<del> template = angular.element('<div>{{greeting = "hello world"}}</div>');
<del> scope = angular.compile(template)();
<del> scope.$digest();
<add> it('should link to existing node and create scope', inject(function($rootScope) {
<add> var template = angular.element('<div>{{greeting = "hello world"}}</div>');
<add> angular.compile(template)($rootScope);
<add> $rootScope.$digest();
<ide> expect(template.text()).toEqual('hello world');
<del> expect(scope.greeting).toEqual('hello world');
<del> });
<add> expect($rootScope.greeting).toEqual('hello world');
<add> }));
<ide>
<del> it('should link to existing node and given scope', function() {
<del> scope = angular.scope();
<del> template = angular.element('<div>{{greeting = "hello world"}}</div>');
<del> angular.compile(template)(scope);
<del> scope.$digest();
<add> it('should link to existing node and given scope', inject(function($rootScope) {
<add> var template = angular.element('<div>{{greeting = "hello world"}}</div>');
<add> angular.compile(template)($rootScope);
<add> $rootScope.$digest();
<ide> expect(template.text()).toEqual('hello world');
<del> expect(scope).toEqual(scope);
<del> });
<add> }));
<ide>
<del> it('should link to new node and given scope', function() {
<del> scope = angular.scope();
<del> template = jqLite('<div>{{greeting = "hello world"}}</div>');
<add> it('should link to new node and given scope', inject(function($rootScope) {
<add> var template = jqLite('<div>{{greeting = "hello world"}}</div>');
<ide>
<ide> var templateFn = angular.compile(template);
<ide> var templateClone = template.clone();
<ide>
<del> templateFn(scope, function(clone){
<add> var element = templateFn($rootScope, function(clone){
<ide> templateClone = clone;
<ide> });
<del> scope.$digest();
<add> $rootScope.$digest();
<ide>
<ide> expect(template.text()).toEqual('');
<del> expect(scope.$element.text()).toEqual('hello world');
<del> expect(scope.$element).toEqual(templateClone);
<del> expect(scope.greeting).toEqual('hello world');
<del> });
<del>
<del> it('should link to cloned node and create scope', function() {
<del> scope = angular.scope();
<del> template = jqLite('<div>{{greeting = "hello world"}}</div>');
<del> angular.compile(template)(scope, noop).$digest();
<add> expect(element.text()).toEqual('hello world');
<add> expect(element).toEqual(templateClone);
<add> expect($rootScope.greeting).toEqual('hello world');
<add> }));
<add>
<add> it('should link to cloned node and create scope', inject(function($rootScope) {
<add> var template = jqLite('<div>{{greeting = "hello world"}}</div>');
<add> var element = angular.compile(template)($rootScope, noop);
<add> $rootScope.$digest();
<ide> expect(template.text()).toEqual('');
<del> expect(scope.$element.text()).toEqual('hello world');
<del> expect(scope.greeting).toEqual('hello world');
<del> });
<add> expect(element.text()).toEqual('hello world');
<add> expect($rootScope.greeting).toEqual('hello world');
<add> }));
<ide> });
<ide>
<ide>
<ide><path>test/BinderSpec.js
<ide>
<ide> describe('Binder', function() {
<ide> beforeEach(function() {
<del> var self = this;
<del>
<del> this.compile = function(html, parent, logErrors) {
<del> if (self.element) dealoc(self.element);
<del> var element;
<del> if (parent) {
<del> parent.html(html);
<del> element = parent.children();
<del> } else {
<del> element = jqLite(html);
<del> }
<del> self.element = element;
<del> return angular.compile(element)(angular.scope(null,
<del> logErrors ? {'$exceptionHandler': $exceptionHandlerMockFactory()} : null));
<del> };
<ide> this.compileToHtml = function (content) {
<del> return sortedHtml(this.compile(content).$element);
<add> var html;
<add> inject(function($rootScope){
<add> content = jqLite(content);
<add> angular.compile(content)($rootScope);
<add> html = sortedHtml(content);
<add> }).call(this);
<add> return html;
<ide> };
<ide> });
<ide>
<ide> describe('Binder', function() {
<ide> }
<ide> });
<ide>
<del> it('BindUpdate', function() {
<del> var scope = this.compile('<div ng:init="a=123"/>');
<del> scope.$digest();
<del> assertEquals(123, scope.a);
<del> });
<add> it('BindUpdate', inject(function($rootScope) {
<add> angular.compile('<div ng:init="a=123"/>')($rootScope);
<add> $rootScope.$digest();
<add> assertEquals(123, $rootScope.a);
<add> }));
<ide>
<del> it('ExecuteInitialization', function() {
<del> var scope = this.compile('<div ng:init="a=123">');
<del> assertEquals(scope.a, 123);
<del> });
<add> it('ExecuteInitialization', inject(function($rootScope) {
<add> angular.compile('<div ng:init="a=123">')($rootScope);
<add> assertEquals($rootScope.a, 123);
<add> }));
<ide>
<del> it('ExecuteInitializationStatements', function() {
<del> var scope = this.compile('<div ng:init="a=123;b=345">');
<del> assertEquals(scope.a, 123);
<del> assertEquals(scope.b, 345);
<del> });
<add> it('ExecuteInitializationStatements', inject(function($rootScope) {
<add> angular.compile('<div ng:init="a=123;b=345">')($rootScope);
<add> assertEquals($rootScope.a, 123);
<add> assertEquals($rootScope.b, 345);
<add> }));
<ide>
<del> it('ApplyTextBindings', function() {
<del> var scope = this.compile('<div ng:bind="model.a">x</div>');
<del> scope.model = {a:123};
<del> scope.$apply();
<del> assertEquals('123', scope.$element.text());
<add> it('ApplyTextBindings', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:bind="model.a">x</div>')($rootScope);
<add> $rootScope.model = {a:123};
<add> $rootScope.$apply();
<add> assertEquals('123', element.text());
<add> }));
<add>
<add> it('ReplaceBindingInTextWithSpan preserve surounding text', function() {
<add> assertEquals(this.compileToHtml("<b>a{{b}}c</b>"), '<b>a<span ng:bind="b"></span>c</b>');
<ide> });
<ide>
<ide> it('ReplaceBindingInTextWithSpan', function() {
<del> assertEquals(this.compileToHtml("<b>a{{b}}c</b>"), '<b>a<span ng:bind="b"></span>c</b>');
<ide> assertEquals(this.compileToHtml("<b>{{b}}</b>"), '<b><span ng:bind="b"></span></b>');
<ide> });
<ide>
<del> it('BindingSpaceConfusesIE', function() {
<add> it('BindingSpaceConfusesIE', inject(function($rootScope) {
<ide> if (!msie) return;
<ide> var span = document.createElement("span");
<ide> span.innerHTML = ' ';
<ide> var nbsp = span.firstChild.nodeValue;
<ide> assertEquals(
<ide> '<b><span ng:bind="a"></span><span>'+nbsp+'</span><span ng:bind="b"></span></b>',
<ide> this.compileToHtml("<b>{{a}} {{b}}</b>"));
<add> dealoc(($rootScope));
<ide> assertEquals(
<ide> '<b><span ng:bind="A"></span><span>'+nbsp+'x </span><span ng:bind="B"></span><span>'+nbsp+'(</span><span ng:bind="C"></span>)</b>',
<ide> this.compileToHtml("<b>{{A}} x {{B}} ({{C}})</b>"));
<del> });
<add> }));
<ide>
<del> it('BindingOfAttributes', function() {
<del> var scope = this.compile("<a href='http://s/a{{b}}c' foo='x'></a>");
<del> var attrbinding = scope.$element.attr("ng:bind-attr");
<add> it('BindingOfAttributes', inject(function($rootScope) {
<add> var element = angular.compile("<a href='http://s/a{{b}}c' foo='x'></a>")($rootScope);
<add> var attrbinding = element.attr("ng:bind-attr");
<ide> var bindings = fromJson(attrbinding);
<ide> assertEquals("http://s/a{{b}}c", decodeURI(bindings.href));
<ide> assertTrue(!bindings.foo);
<del> });
<add> }));
<ide>
<del> it('MarkMultipleAttributes', function() {
<del> var scope = this.compile('<a href="http://s/a{{b}}c" foo="{{d}}"></a>');
<del> var attrbinding = scope.$element.attr("ng:bind-attr");
<add> it('MarkMultipleAttributes', inject(function($rootScope) {
<add> var element = angular.compile('<a href="http://s/a{{b}}c" foo="{{d}}"></a>')($rootScope);
<add> var attrbinding = element.attr("ng:bind-attr");
<ide> var bindings = fromJson(attrbinding);
<ide> assertEquals(bindings.foo, "{{d}}");
<ide> assertEquals(decodeURI(bindings.href), "http://s/a{{b}}c");
<del> });
<add> }));
<ide>
<del> it('AttributesNoneBound', function() {
<del> var scope = this.compile("<a href='abc' foo='def'></a>");
<del> var a = scope.$element;
<add> it('AttributesNoneBound', inject(function($rootScope) {
<add> var a = angular.compile("<a href='abc' foo='def'></a>")($rootScope);
<ide> assertEquals(a[0].nodeName, "A");
<ide> assertTrue(!a.attr("ng:bind-attr"));
<del> });
<add> }));
<ide>
<del> it('ExistingAttrbindingIsAppended', function() {
<del> var scope = this.compile("<a href='http://s/{{abc}}' ng:bind-attr='{\"b\":\"{{def}}\"}'></a>");
<del> var a = scope.$element;
<add> it('ExistingAttrbindingIsAppended', inject(function($rootScope) {
<add> var a = angular.compile("<a href='http://s/{{abc}}' ng:bind-attr='{\"b\":\"{{def}}\"}'></a>")($rootScope);
<ide> assertEquals('{"b":"{{def}}","href":"http://s/{{abc}}"}', a.attr('ng:bind-attr'));
<del> });
<add> }));
<ide>
<del> it('AttributesAreEvaluated', function() {
<del> var scope = this.compile('<a ng:bind-attr=\'{"a":"a", "b":"a+b={{a+b}}"}\'></a>');
<del> scope.$eval('a=1;b=2');
<del> scope.$apply();
<del> var a = scope.$element;
<add> it('AttributesAreEvaluated', inject(function($rootScope) {
<add> var a = angular.compile('<a ng:bind-attr=\'{"a":"a", "b":"a+b={{a+b}}"}\'></a>')($rootScope);
<add> $rootScope.$eval('a=1;b=2');
<add> $rootScope.$apply();
<ide> assertEquals(a.attr('a'), 'a');
<ide> assertEquals(a.attr('b'), 'a+b=3');
<del> });
<add> }));
<ide>
<del> it('InputTypeButtonActionExecutesInScope', function() {
<add> it('InputTypeButtonActionExecutesInScope', inject(function($rootScope) {
<ide> var savedCalled = false;
<del> var scope = this.compile('<input type="button" ng:click="person.save()" value="Apply">');
<del> scope.person = {};
<del> scope.person.save = function() {
<add> var element = angular.compile(
<add> '<input type="button" ng:click="person.save()" value="Apply">')($rootScope);
<add> $rootScope.person = {};
<add> $rootScope.person.save = function() {
<ide> savedCalled = true;
<ide> };
<del> browserTrigger(scope.$element, 'click');
<add> browserTrigger(element, 'click');
<ide> assertTrue(savedCalled);
<del> });
<add> }));
<ide>
<del> it('InputTypeButtonActionExecutesInScope2', function() {
<add> it('InputTypeButtonActionExecutesInScope2', inject(function($rootScope) {
<ide> var log = "";
<del> var scope = this.compile('<input type="image" ng:click="action()">');
<del> scope.action = function() {
<add> var element = angular.compile('<input type="image" ng:click="action()">')($rootScope);
<add> $rootScope.action = function() {
<ide> log += 'click;';
<ide> };
<ide> expect(log).toEqual('');
<del> browserTrigger(scope.$element, 'click');
<add> browserTrigger(element, 'click');
<ide> expect(log).toEqual('click;');
<del> });
<add> }));
<ide>
<del> it('ButtonElementActionExecutesInScope', function() {
<add> it('ButtonElementActionExecutesInScope', inject(function($rootScope) {
<ide> var savedCalled = false;
<del> var scope = this.compile('<button ng:click="person.save()">Apply</button>');
<del> scope.person = {};
<del> scope.person.save = function() {
<add> var element = angular.compile('<button ng:click="person.save()">Apply</button>')($rootScope);
<add> $rootScope.person = {};
<add> $rootScope.person.save = function() {
<ide> savedCalled = true;
<ide> };
<del> browserTrigger(scope.$element, 'click');
<add> browserTrigger(element, 'click');
<ide> assertTrue(savedCalled);
<del> });
<add> }));
<ide>
<del> it('RepeaterUpdateBindings', function() {
<del> var scope = this.compile('<ul><LI ng:repeat="item in model.items" ng:bind="item.a"/></ul>');
<del> var form = scope.$element;
<add> it('RepeaterUpdateBindings', inject(function($rootScope) {
<add> var form = angular.compile(
<add> '<ul>' +
<add> '<LI ng:repeat="item in model.items" ng:bind="item.a"></LI>' +
<add> '</ul>')($rootScope);
<ide> var items = [{a:"A"}, {a:"B"}];
<del> scope.model = {items:items};
<add> $rootScope.model = {items:items};
<ide>
<del> scope.$apply();
<add> $rootScope.$apply();
<ide> assertEquals('<ul>' +
<ide> '<#comment></#comment>' +
<ide> '<li ng:bind="item.a">A</li>' +
<ide> '<li ng:bind="item.a">B</li>' +
<ide> '</ul>', sortedHtml(form));
<ide>
<ide> items.unshift({a:'C'});
<del> scope.$apply();
<add> $rootScope.$apply();
<ide> assertEquals('<ul>' +
<ide> '<#comment></#comment>' +
<ide> '<li ng:bind="item.a">C</li>' +
<ide> describe('Binder', function() {
<ide> '</ul>', sortedHtml(form));
<ide>
<ide> items.shift();
<del> scope.$apply();
<add> $rootScope.$apply();
<ide> assertEquals('<ul>' +
<ide> '<#comment></#comment>' +
<ide> '<li ng:bind="item.a">A</li>' +
<ide> describe('Binder', function() {
<ide>
<ide> items.shift();
<ide> items.shift();
<del> scope.$apply();
<del> });
<del>
<del> it('RepeaterContentDoesNotBind', function() {
<del> var scope = this.compile('<ul><LI ng:repeat="item in model.items"><span ng:bind="item.a"></span></li></ul>');
<del> scope.model = {items:[{a:"A"}]};
<del> scope.$apply();
<add> $rootScope.$apply();
<add> }));
<add>
<add> it('RepeaterContentDoesNotBind', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<ul>' +
<add> '<LI ng:repeat="item in model.items"><span ng:bind="item.a"></span></li>' +
<add> '</ul>')($rootScope);
<add> $rootScope.model = {items:[{a:"A"}]};
<add> $rootScope.$apply();
<ide> assertEquals('<ul>' +
<ide> '<#comment></#comment>' +
<ide> '<li><span ng:bind="item.a">A</span></li>' +
<del> '</ul>', sortedHtml(scope.$element));
<del> });
<add> '</ul>', sortedHtml(element));
<add> }));
<ide>
<ide> it('DoNotOverwriteCustomAction', function() {
<ide> var html = this.compileToHtml('<input type="submit" value="Save" action="foo();">');
<ide> assertTrue(html.indexOf('action="foo();"') > 0 );
<ide> });
<ide>
<del> it('RepeaterAdd', function() {
<del> var scope = this.compile('<div><input type="text" ng:model="item.x" ng:repeat="item in items"></div>');
<del> scope.items = [{x:'a'}, {x:'b'}];
<del> scope.$apply();
<del> var first = childNode(scope.$element, 1);
<del> var second = childNode(scope.$element, 2);
<add> it('RepeaterAdd', inject(function($rootScope) {
<add> var element = angular.compile('<div><input type="text" ng:model="item.x" ng:repeat="item in items"></div>')($rootScope);
<add> $rootScope.items = [{x:'a'}, {x:'b'}];
<add> $rootScope.$apply();
<add> var first = childNode(element, 1);
<add> var second = childNode(element, 2);
<ide> expect(first.val()).toEqual('a');
<ide> expect(second.val()).toEqual('b');
<ide>
<ide> first.val('ABC');
<ide> browserTrigger(first, 'keydown');
<del> scope.$service('$browser').defer.flush();
<del> expect(scope.items[0].x).toEqual('ABC');
<del> });
<add> $rootScope.$service('$browser').defer.flush();
<add> expect($rootScope.items[0].x).toEqual('ABC');
<add> }));
<ide>
<del> it('ItShouldRemoveExtraChildrenWhenIteratingOverHash', function() {
<del> var scope = this.compile('<div><div ng:repeat="i in items">{{i}}</div></div>');
<add> it('ItShouldRemoveExtraChildrenWhenIteratingOverHash', inject(function($rootScope) {
<add> var element = angular.compile('<div><div ng:repeat="i in items">{{i}}</div></div>')($rootScope);
<ide> var items = {};
<del> scope.items = items;
<add> $rootScope.items = items;
<ide>
<del> scope.$apply();
<del> expect(scope.$element[0].childNodes.length - 1).toEqual(0);
<add> $rootScope.$apply();
<add> expect(element[0].childNodes.length - 1).toEqual(0);
<ide>
<ide> items.name = "misko";
<del> scope.$apply();
<del> expect(scope.$element[0].childNodes.length - 1).toEqual(1);
<add> $rootScope.$apply();
<add> expect(element[0].childNodes.length - 1).toEqual(1);
<ide>
<ide> delete items.name;
<del> scope.$apply();
<del> expect(scope.$element[0].childNodes.length - 1).toEqual(0);
<del> });
<del>
<del> it('IfTextBindingThrowsErrorDecorateTheSpan', function() {
<del> var scope = this.compile('<div>{{error.throw()}}</div>', null, true);
<del> var errorLogs = scope.$service('$exceptionHandler').errors;
<del>
<del> scope.error = {
<del> 'throw': function() {throw "ErrorMsg1";}
<del> };
<del> scope.$apply();
<del>
<del> scope.error['throw'] = function() {throw "MyError";};
<del> errorLogs.length = 0;
<del> scope.$apply();
<del> assertEquals(['MyError'], errorLogs.shift());
<del>
<del> scope.error['throw'] = function() {return "ok";};
<del> scope.$apply();
<del> assertEquals(0, errorLogs.length);
<del> });
<del>
<del> it('IfAttrBindingThrowsErrorDecorateTheAttribute', function() {
<del> var scope = this.compile('<div attr="before {{error.throw()}} after"></div>', null, true);
<del> var errorLogs = scope.$service('$exceptionHandler').errors;
<add> $rootScope.$apply();
<add> expect(element[0].childNodes.length - 1).toEqual(0);
<add> }));
<add>
<add> it('IfTextBindingThrowsErrorDecorateTheSpan', inject(
<add> function(service){
<add> service('$exceptionHandler', $exceptionHandlerMockFactory);
<add> },
<add> function($rootScope, $exceptionHandler) {
<add> angular.compile('<div>{{error.throw()}}</div>', null, true)($rootScope);
<add> var errorLogs = $exceptionHandler.errors;
<add>
<add> $rootScope.error = {
<add> 'throw': function() {throw "ErrorMsg1";}
<add> };
<add> $rootScope.$apply();
<add>
<add> $rootScope.error['throw'] = function() {throw "MyError";};
<add> errorLogs.length = 0;
<add> $rootScope.$apply();
<add> assertEquals(['MyError'], errorLogs.shift());
<add>
<add> $rootScope.error['throw'] = function() {return "ok";};
<add> $rootScope.$apply();
<add> assertEquals(0, errorLogs.length);
<add> })
<add> );
<add>
<add> it('IfAttrBindingThrowsErrorDecorateTheAttribute', inject(function(service){
<add> service('$exceptionHandler', $exceptionHandlerMockFactory);
<add> }, function($rootScope, $exceptionHandler) {
<add> angular.compile('<div attr="before {{error.throw()}} after"></div>', null, true)($rootScope);
<add> var errorLogs = $exceptionHandler.errors;
<ide> var count = 0;
<ide>
<del> scope.error = {
<add> $rootScope.error = {
<ide> 'throw': function() {throw new Error("ErrorMsg" + (++count));}
<ide> };
<del> scope.$apply();
<add> $rootScope.$apply();
<ide> expect(errorLogs.length).not.toEqual(0);
<ide> expect(errorLogs.shift()).toMatch(/ErrorMsg1/);
<ide> errorLogs.length = 0;
<ide>
<del> scope.error['throw'] = function() { return 'X';};
<del> scope.$apply();
<add> $rootScope.error['throw'] = function() { return 'X';};
<add> $rootScope.$apply();
<ide> expect(errorLogs.length).toMatch(0);
<del> });
<add> }));
<ide>
<del> it('NestedRepeater', function() {
<del> var scope = this.compile('<div><div ng:repeat="m in model" name="{{m.name}}">' +
<del> '<ul name="{{i}}" ng:repeat="i in m.item"></ul>' +
<del> '</div></div>');
<add> it('NestedRepeater', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<div>' +
<add> '<div ng:repeat="m in model" name="{{m.name}}">' +
<add> '<ul name="{{i}}" ng:repeat="i in m.item"></ul>' +
<add> '</div>' +
<add> '</div>')($rootScope);
<ide>
<del> scope.model = [{name:'a', item:['a1', 'a2']}, {name:'b', item:['b1', 'b2']}];
<del> scope.$apply();
<add> $rootScope.model = [{name:'a', item:['a1', 'a2']}, {name:'b', item:['b1', 'b2']}];
<add> $rootScope.$apply();
<ide>
<ide> assertEquals('<div>'+
<ide> '<#comment></#comment>'+
<ide> describe('Binder', function() {
<ide> '<#comment></#comment>'+
<ide> '<ul name="b1" ng:bind-attr="{"name":"{{i}}"}"></ul>'+
<ide> '<ul name="b2" ng:bind-attr="{"name":"{{i}}"}"></ul>'+
<del> '</div></div>', sortedHtml(scope.$element));
<del> });
<add> '</div></div>', sortedHtml(element));
<add> }));
<ide>
<del> it('HideBindingExpression', function() {
<del> var scope = this.compile('<div ng:hide="hidden == 3"/>');
<add> it('HideBindingExpression', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:hide="hidden == 3"/>')($rootScope);
<ide>
<del> scope.hidden = 3;
<del> scope.$apply();
<add> $rootScope.hidden = 3;
<add> $rootScope.$apply();
<ide>
<del> assertHidden(scope.$element);
<add> assertHidden(element);
<ide>
<del> scope.hidden = 2;
<del> scope.$apply();
<add> $rootScope.hidden = 2;
<add> $rootScope.$apply();
<ide>
<del> assertVisible(scope.$element);
<del> });
<add> assertVisible(element);
<add> }));
<ide>
<del> it('HideBinding', function() {
<del> var scope = this.compile('<div ng:hide="hidden"/>');
<add> it('HideBinding', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:hide="hidden"/>')($rootScope);
<ide>
<del> scope.hidden = 'true';
<del> scope.$apply();
<add> $rootScope.hidden = 'true';
<add> $rootScope.$apply();
<ide>
<del> assertHidden(scope.$element);
<add> assertHidden(element);
<ide>
<del> scope.hidden = 'false';
<del> scope.$apply();
<add> $rootScope.hidden = 'false';
<add> $rootScope.$apply();
<ide>
<del> assertVisible(scope.$element);
<add> assertVisible(element);
<ide>
<del> scope.hidden = '';
<del> scope.$apply();
<add> $rootScope.hidden = '';
<add> $rootScope.$apply();
<ide>
<del> assertVisible(scope.$element);
<del> });
<add> assertVisible(element);
<add> }));
<ide>
<del> it('ShowBinding', function() {
<del> var scope = this.compile('<div ng:show="show"/>');
<add> it('ShowBinding', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:show="show"/>')($rootScope);
<ide>
<del> scope.show = 'true';
<del> scope.$apply();
<add> $rootScope.show = 'true';
<add> $rootScope.$apply();
<ide>
<del> assertVisible(scope.$element);
<add> assertVisible(element);
<ide>
<del> scope.show = 'false';
<del> scope.$apply();
<add> $rootScope.show = 'false';
<add> $rootScope.$apply();
<ide>
<del> assertHidden(scope.$element);
<add> assertHidden(element);
<ide>
<del> scope.show = '';
<del> scope.$apply();
<add> $rootScope.show = '';
<add> $rootScope.$apply();
<ide>
<del> assertHidden(scope.$element);
<del> });
<add> assertHidden(element);
<add> }));
<ide>
<ide>
<del> it('BindClass', function() {
<del> var scope = this.compile('<div ng:class="clazz"/>');
<add> it('BindClass', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:class="clazz"/>')($rootScope);
<ide>
<del> scope.clazz = 'testClass';
<del> scope.$apply();
<add> $rootScope.clazz = 'testClass';
<add> $rootScope.$apply();
<ide>
<del> assertEquals('<div class="testClass" ng:class="clazz"></div>', sortedHtml(scope.$element));
<add> assertEquals('<div class="testClass" ng:class="clazz"></div>', sortedHtml(element));
<ide>
<del> scope.clazz = ['a', 'b'];
<del> scope.$apply();
<add> $rootScope.clazz = ['a', 'b'];
<add> $rootScope.$apply();
<ide>
<del> assertEquals('<div class="a b" ng:class="clazz"></div>', sortedHtml(scope.$element));
<del> });
<add> assertEquals('<div class="a b" ng:class="clazz"></div>', sortedHtml(element));
<add> }));
<ide>
<del> it('BindClassEvenOdd', function() {
<del> var scope = this.compile('<div><div ng:repeat="i in [0,1]" ng:class-even="\'e\'" ng:class-odd="\'o\'"></div></div>');
<del> scope.$apply();
<del> var d1 = jqLite(scope.$element[0].childNodes[1]);
<del> var d2 = jqLite(scope.$element[0].childNodes[2]);
<add> it('BindClassEvenOdd', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<div>' +
<add> '<div ng:repeat="i in [0,1]" ng:class-even="\'e\'" ng:class-odd="\'o\'"></div>' +
<add> '</div>')($rootScope);
<add> $rootScope.$apply();
<add> var d1 = jqLite(element[0].childNodes[1]);
<add> var d2 = jqLite(element[0].childNodes[2]);
<ide> expect(d1.hasClass('o')).toBeTruthy();
<ide> expect(d2.hasClass('e')).toBeTruthy();
<ide> assertEquals(
<ide> '<div><#comment></#comment>' +
<ide> '<div class="o" ng:class-even="\'e\'" ng:class-odd="\'o\'"></div>' +
<ide> '<div class="e" ng:class-even="\'e\'" ng:class-odd="\'o\'"></div></div>',
<del> sortedHtml(scope.$element));
<del> });
<del>
<del> it('BindStyle', function() {
<del> var scope = this.compile('<div ng:style="style"/>');
<del>
<del> scope.$eval('style={height: "10px"}');
<del> scope.$apply();
<del>
<del> assertEquals("10px", scope.$element.css('height'));
<del>
<del> scope.$eval('style={}');
<del> scope.$apply();
<del> });
<del>
<del> it('ActionOnAHrefThrowsError', function() {
<del> var scope = this.compile('<a ng:click="action()">Add Phone</a>', null, true);
<del> scope.action = function() {
<del> throw new Error('MyError');
<del> };
<del> var input = scope.$element;
<del> browserTrigger(input, 'click');
<del> expect(scope.$service('$exceptionHandler').errors[0]).toMatch(/MyError/);
<del> });
<del>
<del> it('ShoulIgnoreVbNonBindable', function() {
<del> var scope = this.compile("<div>{{a}}" +
<add> sortedHtml(element));
<add> }));
<add>
<add> it('BindStyle', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:style="style"/>')($rootScope);
<add>
<add> $rootScope.$eval('style={height: "10px"}');
<add> $rootScope.$apply();
<add>
<add> assertEquals("10px", element.css('height'));
<add>
<add> $rootScope.$eval('style={}');
<add> $rootScope.$apply();
<add> }));
<add>
<add> it('ActionOnAHrefThrowsError', inject(
<add> function(service){
<add> service('$exceptionHandler', $exceptionHandlerMockFactory);
<add> },
<add> function($rootScope, $exceptionHandler) {
<add> var input = angular.compile('<a ng:click="action()">Add Phone</a>')($rootScope);
<add> $rootScope.action = function() {
<add> throw new Error('MyError');
<add> };
<add> browserTrigger(input, 'click');
<add> expect($exceptionHandler.errors[0]).toMatch(/MyError/);
<add> })
<add> );
<add>
<add> it('ShoulIgnoreVbNonBindable', inject(function($rootScope) {
<add> var element = angular.compile(
<add> "<div>{{a}}" +
<ide> "<div ng:non-bindable>{{a}}</div>" +
<ide> "<div ng:non-bindable=''>{{b}}</div>" +
<del> "<div ng:non-bindable='true'>{{c}}</div></div>");
<del> scope.a = 123;
<del> scope.$apply();
<del> assertEquals('123{{a}}{{b}}{{c}}', scope.$element.text());
<del> });
<add> "<div ng:non-bindable='true'>{{c}}</div>" +
<add> "</div>")($rootScope);
<add> $rootScope.a = 123;
<add> $rootScope.$apply();
<add> assertEquals('123{{a}}{{b}}{{c}}', element.text());
<add> }));
<add>
<add> it('ShouldTemplateBindPreElements', inject(function ($rootScope) {
<add> var element = angular.compile('<pre>Hello {{name}}!</pre>')($rootScope);
<add> $rootScope.name = "World";
<add> $rootScope.$apply();
<ide>
<del> it('ShouldTemplateBindPreElements', function () {
<del> var scope = this.compile('<pre>Hello {{name}}!</pre>');
<del> scope.name = "World";
<del> scope.$apply();
<del>
<del> assertEquals('<pre ng:bind-template="Hello {{name}}!">Hello World!</pre>', sortedHtml(scope.$element));
<del> });
<add> assertEquals(
<add> '<pre ng:bind-template="Hello {{name}}!">Hello World!</pre>',
<add> sortedHtml(element));
<add> }));
<ide>
<del> it('FillInOptionValueWhenMissing', function() {
<del> var scope = this.compile(
<add> it('FillInOptionValueWhenMissing', inject(function($rootScope) {
<add> var element = angular.compile(
<ide> '<select ng:model="foo">' +
<ide> '<option selected="true">{{a}}</option>' +
<ide> '<option value="">{{b}}</option>' +
<ide> '<option>C</option>' +
<del> '</select>');
<del> scope.a = 'A';
<del> scope.b = 'B';
<del> scope.$apply();
<del> var optionA = childNode(scope.$element, 0);
<del> var optionB = childNode(scope.$element, 1);
<del> var optionC = childNode(scope.$element, 2);
<add> '</select>')($rootScope);
<add> $rootScope.a = 'A';
<add> $rootScope.b = 'B';
<add> $rootScope.$apply();
<add> var optionA = childNode(element, 0);
<add> var optionB = childNode(element, 1);
<add> var optionC = childNode(element, 2);
<ide>
<ide> expect(optionA.attr('value')).toEqual('A');
<ide> expect(optionA.text()).toEqual('A');
<ide> describe('Binder', function() {
<ide>
<ide> expect(optionC.attr('value')).toEqual('C');
<ide> expect(optionC.text()).toEqual('C');
<del> });
<add> }));
<ide>
<del> it('DeleteAttributeIfEvaluatesFalse', function() {
<del> var scope = this.compile('<div>' +
<add> it('DeleteAttributeIfEvaluatesFalse', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<div>' +
<ide> '<input ng:model="a0" ng:bind-attr="{disabled:\'{{true}}\'}">' +
<ide> '<input ng:model="a1" ng:bind-attr="{disabled:\'{{false}}\'}">' +
<ide> '<input ng:model="b0" ng:bind-attr="{disabled:\'{{1}}\'}">' +
<ide> '<input ng:model="b1" ng:bind-attr="{disabled:\'{{0}}\'}">' +
<ide> '<input ng:model="c0" ng:bind-attr="{disabled:\'{{[0]}}\'}">' +
<del> '<input ng:model="c1" ng:bind-attr="{disabled:\'{{[]}}\'}"></div>');
<del> scope.$apply();
<add> '<input ng:model="c1" ng:bind-attr="{disabled:\'{{[]}}\'}">' +
<add> '</div>')($rootScope);
<add> $rootScope.$apply();
<ide> function assertChild(index, disabled) {
<del> var child = childNode(scope.$element, index);
<add> var child = childNode(element, index);
<ide> assertEquals(sortedHtml(child), disabled, !!child.attr('disabled'));
<ide> }
<ide>
<ide> describe('Binder', function() {
<ide> assertChild(3, false);
<ide> assertChild(4, true);
<ide> assertChild(5, false);
<del> });
<del>
<del> it('ItShouldDisplayErrorWhenActionIsSyntacticlyIncorrect', function() {
<del> var scope = this.compile('<div>' +
<del> '<input type="button" ng:click="greeting=\'ABC\'"/>' +
<del> '<input type="button" ng:click=":garbage:"/></div>', null, true);
<del> var first = jqLite(scope.$element[0].childNodes[0]);
<del> var second = jqLite(scope.$element[0].childNodes[1]);
<del> var errorLogs = scope.$service('$log').error.logs;
<del>
<del> browserTrigger(first, 'click');
<del> assertEquals("ABC", scope.greeting);
<del> expect(errorLogs).toEqual([]);
<del>
<del> browserTrigger(second, 'click');
<del> expect(scope.$service('$exceptionHandler').errors[0]).
<del> toMatchError(/Syntax Error: Token ':' not a primary expression/);
<del> });
<del>
<del> it('ItShouldSelectTheCorrectRadioBox', function() {
<del> var scope = this.compile('<div>' +
<add> }));
<add>
<add> it('ItShouldDisplayErrorWhenActionIsSyntacticlyIncorrect', inject(
<add> function(service){
<add> service('$exceptionHandler', $exceptionHandlerMockFactory);
<add> },
<add> function($rootScope, $exceptionHandler, $log) {
<add> var element = angular.compile(
<add> '<div>' +
<add> '<input type="button" ng:click="greeting=\'ABC\'"/>' +
<add> '<input type="button" ng:click=":garbage:"/>' +
<add> '</div>')($rootScope);
<add> var first = jqLite(element.find('input')[0]);
<add> var second = jqLite(element.find('input')[1]);
<add> var errorLogs = $log.error.logs;
<add>
<add> browserTrigger(first, 'click');
<add> assertEquals("ABC", $rootScope.greeting);
<add> expect(errorLogs).toEqual([]);
<add>
<add> browserTrigger(second, 'click');
<add> expect($exceptionHandler.errors[0]).
<add> toMatchError(/Syntax Error: Token ':' not a primary expression/);
<add> })
<add> );
<add>
<add> it('ItShouldSelectTheCorrectRadioBox', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<div>' +
<ide> '<input type="radio" ng:model="sex" value="female">' +
<del> '<input type="radio" ng:model="sex" value="male"></div>');
<del> var female = jqLite(scope.$element[0].childNodes[0]);
<del> var male = jqLite(scope.$element[0].childNodes[1]);
<add> '<input type="radio" ng:model="sex" value="male">' +
<add> '</div>')($rootScope);
<add> var female = jqLite(element[0].childNodes[0]);
<add> var male = jqLite(element[0].childNodes[1]);
<ide>
<ide> browserTrigger(female);
<del> assertEquals("female", scope.sex);
<add> assertEquals("female", $rootScope.sex);
<ide> assertEquals(true, female[0].checked);
<ide> assertEquals(false, male[0].checked);
<ide> assertEquals("female", female.val());
<ide>
<ide> browserTrigger(male);
<del> assertEquals("male", scope.sex);
<add> assertEquals("male", $rootScope.sex);
<ide> assertEquals(false, female[0].checked);
<ide> assertEquals(true, male[0].checked);
<ide> assertEquals("male", male.val());
<del> });
<del>
<del> it('ItShouldRepeatOnHashes', function() {
<del> var scope = this.compile('<ul><li ng:repeat="(k,v) in {a:0,b:1}" ng:bind=\"k + v\"></li></ul>');
<del> scope.$apply();
<add> }));
<add>
<add> it('ItShouldRepeatOnHashes', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<ul>' +
<add> '<li ng:repeat="(k,v) in {a:0,b:1}" ng:bind=\"k + v\"></li>' +
<add> '</ul>')($rootScope);
<add> $rootScope.$apply();
<ide> assertEquals('<ul>' +
<ide> '<#comment></#comment>' +
<ide> '<li ng:bind=\"k + v\">a0</li>' +
<ide> '<li ng:bind=\"k + v\">b1</li>' +
<ide> '</ul>',
<del> sortedHtml(scope.$element));
<del> });
<del>
<del> it('ItShouldFireChangeListenersBeforeUpdate', function() {
<del> var scope = this.compile('<div ng:bind="name"></div>');
<del> scope.name = "";
<del> scope.$watch("watched", "name=123");
<del> scope.watched = "change";
<del> scope.$apply();
<del> assertEquals(123, scope.name);
<add> sortedHtml(element));
<add> }));
<add>
<add> it('ItShouldFireChangeListenersBeforeUpdate', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:bind="name"></div>')($rootScope);
<add> $rootScope.name = "";
<add> $rootScope.$watch("watched", "name=123");
<add> $rootScope.watched = "change";
<add> $rootScope.$apply();
<add> assertEquals(123, $rootScope.name);
<ide> assertEquals(
<ide> '<div ng:bind="name">123</div>',
<del> sortedHtml(scope.$element));
<del> });
<del>
<del> it('ItShouldHandleMultilineBindings', function() {
<del> var scope = this.compile('<div>{{\n 1 \n + \n 2 \n}}</div>');
<del> scope.$apply();
<del> assertEquals("3", scope.$element.text());
<del> });
<add> sortedHtml(element));
<add> }));
<add>
<add> it('ItShouldHandleMultilineBindings', inject(function($rootScope) {
<add> var element = angular.compile('<div>{{\n 1 \n + \n 2 \n}}</div>')($rootScope);
<add> $rootScope.$apply();
<add> assertEquals("3", element.text());
<add> }));
<ide>
<ide> });
<ide><path>test/CompilerSpec.js
<ide> describe('compiler', function() {
<ide> var compiler, markup, attrMarkup, directives, widgets, compile, log, scope;
<ide>
<del> beforeEach(function() {
<add> beforeEach(inject(function($rootScope) {
<ide> log = "";
<ide> directives = {
<ide> hello: function(expression, element){
<ide> describe('compiler', function() {
<ide> compiler = new Compiler(markup, attrMarkup, directives, widgets);
<ide> compile = function(html){
<ide> var e = jqLite("<div>" + html + "</div>");
<del> return scope = compiler.compile(e)();
<add> compiler.compile(e)($rootScope);
<add> return scope = $rootScope;
<ide> };
<del> });
<del>
<del>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<add> }));
<ide>
<ide>
<ide> it('should not allow compilation of multiple roots', function() {
<ide> describe('compiler', function() {
<ide> });
<ide>
<ide>
<del> it('should recognize a directive', function() {
<add> it('should recognize a directive', inject(function($rootScope) {
<ide> var e = jqLite('<div directive="expr" ignore="me"></div>');
<ide> directives.directive = function(expression, element){
<ide> log += "found";
<ide> describe('compiler', function() {
<ide> };
<ide> var template = compiler.compile(e);
<ide> expect(log).toEqual("found");
<del> scope = template(angular.scope());
<add> scope = template($rootScope);
<ide> expect(e.hasClass('ng-directive')).toEqual(true);
<ide> expect(log).toEqual("found:init");
<del> });
<add> }));
<ide>
<ide>
<ide> it('should recurse to children', function() {
<ide> describe('compiler', function() {
<ide> });
<ide>
<ide>
<del> it('should allow creation of templates', function() {
<add> it('should allow creation of templates', inject(function($rootScope) {
<ide> directives.duplicate = function(expr, element){
<ide> element.replaceWith(document.createComment("marker"));
<ide> element.removeAttr("duplicate");
<ide> var linker = this.compile(element);
<ide> return function(marker) {
<ide> this.$watch('value', function() {
<del> var scope = linker(angular.scope(), noop);
<add> var scope = $rootScope.$new;
<add> linker(scope, noop);
<ide> marker.after(scope.$element);
<ide> });
<ide> };
<ide> describe('compiler', function() {
<ide> '<span>x</span>' +
<ide> 'after' +
<ide> '</div>');
<del> });
<add> }));
<ide>
<ide>
<ide> it('should process markup before directives', function() {
<ide><path>test/FiltersSpec.js
<ide> describe('filter', function() {
<ide>
<ide> var filter = angular.filter;
<ide>
<del> it('should called the filter when evaluating expression', function() {
<del> var scope = createScope();
<add> it('should called the filter when evaluating expression', inject(function($rootScope) {
<ide> filter.fakeFilter = function() {};
<ide> spyOn(filter, 'fakeFilter');
<ide>
<del> scope.$eval('10|fakeFilter');
<add> $rootScope.$eval('10|fakeFilter');
<ide> expect(filter.fakeFilter).toHaveBeenCalledWith(10);
<ide> delete filter['fakeFilter'];
<del> });
<add> }));
<ide>
<del> it('should call filter on scope context', function() {
<del> var scope = createScope();
<del> scope.name = 'misko';
<add> it('should call filter on scope context', inject(function($rootScope) {
<add> $rootScope.name = 'misko';
<ide> filter.fakeFilter = function() {
<ide> expect(this.name).toEqual('misko');
<ide> };
<ide> spyOn(filter, 'fakeFilter').andCallThrough();
<ide>
<del> scope.$eval('10|fakeFilter');
<add> $rootScope.$eval('10|fakeFilter');
<ide> expect(filter.fakeFilter).toHaveBeenCalled();
<ide> delete filter['fakeFilter'];
<del> });
<add> }));
<ide>
<ide> describe('formatNumber', function() {
<ide> var pattern;
<ide> describe('filter', function() {
<ide> describe('currency', function() {
<ide> var currency, html, context;
<ide>
<del> beforeEach(function() {
<add> beforeEach(inject(function($rootScope) {
<ide> html = jqLite('<span></span>');
<del> context = createScope();
<add> context = $rootScope;
<ide> context.$element = html;
<ide> currency = bind(context, filter.currency);
<del> });
<del>
<del> afterEach(function() {
<del> dealoc(context);
<del> });
<del>
<add> }));
<ide>
<ide> it('should do basic currency filtering', function() {
<ide> expect(currency(0)).toEqual('$0.00');
<ide> describe('filter', function() {
<ide> describe('number', function() {
<ide> var context, number;
<ide>
<del> beforeEach(function() {
<del> context = createScope();
<add> beforeEach(inject(function($rootScope) {
<add> context = $rootScope;
<ide> number = bind(context, filter.number);
<del> });
<add> }));
<ide>
<ide>
<ide> it('should do basic filter', function() {
<ide> describe('filter', function() {
<ide>
<ide> var context, date;
<ide>
<del> beforeEach(function() {
<del> context = createScope();
<add> beforeEach(inject(function($rootScope) {
<add> context = $rootScope;
<ide> date = bind(context, filter.date);
<del> });
<add> }));
<ide>
<ide> it('should ignore falsy inputs', function() {
<ide> expect(date(null)).toBeNull();
<ide><path>test/InjectorSpec.js
<ide>
<ide> describe('injector', function() {
<ide> var providers;
<del> var cache;
<ide> var injector;
<del> var scope;
<ide>
<ide> beforeEach(function() {
<ide> providers = extensionMap({}, 'providers');
<del> cache = {};
<del> scope = {};
<del> injector = createInjector(scope, providers, cache);
<add> injector = createInjector(providers);
<ide> });
<ide>
<ide> it("should return same instance from calling provider", function() {
<del> providers('text', function() { return scope.name; });
<del> scope.name = 'abc';
<del> expect(injector('text')).toEqual('abc');
<del> expect(cache.text).toEqual('abc');
<del> scope.name = 'deleted';
<del> expect(injector('text')).toEqual('abc');
<add> var instance = {},
<add> original = instance;
<add> providers('instance', function() { return instance; });
<add> expect(injector('instance')).toEqual(instance);
<add> instance = 'deleted';
<add> expect(injector('instance')).toEqual(original);
<ide> });
<ide>
<ide> it("should call function", function() {
<ide> describe('injector', function() {
<ide> });
<ide>
<ide> it('should inject providers', function() {
<del> providers('a', function() {return this.mi = 'Mi';});
<del> providers('b', function(mi){return this.name = mi+'sko';}, {$inject:['a']});
<add> providers('a', function() {return 'Mi';});
<add> providers('b', function(mi){return mi+'sko';}, {$inject:['a']});
<ide> expect(injector('b')).toEqual('Misko');
<del> expect(scope).toEqual({mi:'Mi', name:'Misko'});
<ide> });
<ide>
<ide>
<ide> describe('injector', function() {
<ide> it('should autostart eager services', function() {
<ide> var log = '';
<ide> providers('eager', function() {log += 'eager;'; return 'foo';}, {$eager: true});
<del> injector.eager();
<add> injector = createInjector(providers);
<ide> expect(log).toEqual('eager;');
<ide> expect(injector('eager')).toBe('foo');
<ide> });
<ide> describe('injector', function() {
<ide> });
<ide>
<ide> it('should infer injection on services', function() {
<del> var scope = angular.scope({
<add> var $injector = createInjector({
<ide> a: function() { return 'a';},
<ide> b: function(a){ return a + 'b';}
<ide> });
<del> expect(scope.$service('b')).toEqual('ab');
<add> expect($injector('b')).toEqual('ab');
<ide> });
<ide> });
<ide>
<ide><path>test/ParserSpec.js
<ide> describe('parser', function() {
<ide> expect(tokens[0].text).toEqual(0.5);
<ide> });
<ide>
<del> it('should tokenize negative number', function() {
<del> var value = createScope().$eval("-0.5");
<add> it('should tokenize negative number', inject(function($rootScope) {
<add> var value = $rootScope.$eval("-0.5");
<ide> expect(value).toEqual(-0.5);
<ide>
<del> value = createScope().$eval("{a:-0.5}");
<add> value = $rootScope.$eval("{a:-0.5}");
<ide> expect(value).toEqual({a:-0.5});
<del> });
<add> }));
<ide>
<del> it('should tokenize number with exponent', function() {
<add> it('should tokenize number with exponent', inject(function($rootScope) {
<ide> var tokens = lex("0.5E-10");
<ide> expect(tokens[0].text).toEqual(0.5E-10);
<del> expect(createScope().$eval("0.5E-10")).toEqual(0.5E-10);
<add> expect($rootScope.$eval("0.5E-10")).toEqual(0.5E-10);
<ide>
<ide> tokens = lex("0.5E+10");
<ide> expect(tokens[0].text).toEqual(0.5E+10);
<del> });
<add> }));
<ide>
<ide> it('should throws exception for invalid exponent', function() {
<ide> expect(function() {
<ide> describe('parser', function() {
<ide> });
<ide>
<ide> var scope;
<del> beforeEach(function () {
<del> scope = createScope();
<del> });
<add> beforeEach(inject(function ($rootScope) {
<add> scope = $rootScope;
<add> }));
<ide>
<ide> it('should parse expressions', function() {
<ide> expect(scope.$eval("-1")).toEqual(-1);
<ide> describe('parser', function() {
<ide> expect(scope.$eval("a=12")).toEqual(12);
<ide> expect(scope.a).toEqual(12);
<ide>
<del> scope = createScope();
<ide> expect(scope.$eval("x.y.z=123;")).toEqual(123);
<ide> expect(scope.x.y.z).toEqual(123);
<ide>
<ide> describe('parser', function() {
<ide> });
<ide>
<ide> it('should allow assignment after array dereference', function() {
<del> scope = angular.scope();
<ide> scope.obj = [{}];
<ide> scope.$eval('obj[0].name=1');
<ide> expect(scope.obj.name).toBeUndefined();
<ide> expect(scope.obj[0].name).toEqual(1);
<ide> });
<ide>
<ide> it('should short-circuit AND operator', function() {
<del> var scope = angular.scope();
<ide> scope.run = function() {
<ide> throw "IT SHOULD NOT HAVE RUN";
<ide> };
<ide> expect(scope.$eval('false && run()')).toBe(false);
<ide> });
<ide>
<ide> it('should short-circuit OR operator', function() {
<del> var scope = angular.scope();
<ide> scope.run = function() {
<ide> throw "IT SHOULD NOT HAVE RUN";
<ide> };
<ide><path>test/ResourceSpec.js
<ide> 'use strict';
<ide>
<ide> describe("resource", function() {
<del> var xhr, resource, CreditCard, callback, $xhrErr;
<del>
<del> beforeEach(function() {
<del> var scope = angular.scope(angularService, {'$xhr.error': $xhrErr = jasmine.createSpy('xhr.error')});
<del> xhr = scope.$service('$browser').xhr;
<del> resource = new ResourceFactory(scope.$service('$xhr'));
<del> CreditCard = resource.route('/CreditCard/:id:verb', {id:'@id.key'}, {
<del> charge:{
<del> method:'POST',
<del> params:{verb:'!charge'}
<del> }
<del> });
<del> callback = jasmine.createSpy();
<del> });
<add> var resource, CreditCard, callback;
<add>
<add> beforeEach(inject(
<add> function(service) {
<add> service('$xhr.error', function(){return jasmine.createSpy('xhr.error')});
<add> service.alias('$xhr.error', '$xhrError');
<add> },
<add> function($xhr) {
<add> resource = new ResourceFactory($xhr);
<add> CreditCard = resource.route('/CreditCard/:id:verb', {id:'@id.key'}, {
<add> charge:{
<add> method:'POST',
<add> params:{verb:'!charge'}
<add> }
<add> });
<add> callback = jasmine.createSpy();
<add> })
<add> );
<ide>
<ide> it("should build resource", function() {
<ide> expect(typeof CreditCard).toBe('function');
<ide> describe("resource", function() {
<ide> expect(typeof CreditCard.query).toBe('function');
<ide> });
<ide>
<del> it('should default to empty parameters', function() {
<del> xhr.expectGET('URL').respond({});
<add> it('should default to empty parameters', inject(function($browser) {
<add> $browser.xhr.expectGET('URL').respond({});
<ide> resource.route('URL').query();
<del> });
<add> }));
<ide>
<del> it('should ignore slashes of undefinend parameters', function() {
<add> it('should ignore slashes of undefinend parameters', inject(function($browser) {
<ide> var R = resource.route('/Path/:a/:b/:c');
<del> xhr.expectGET('/Path').respond({});
<del> xhr.expectGET('/Path/1').respond({});
<del> xhr.expectGET('/Path/2/3').respond({});
<del> xhr.expectGET('/Path/4/5/6').respond({});
<add> $browser.xhr.expectGET('/Path').respond({});
<add> $browser.xhr.expectGET('/Path/1').respond({});
<add> $browser.xhr.expectGET('/Path/2/3').respond({});
<add> $browser.xhr.expectGET('/Path/4/5/6').respond({});
<ide> R.get({});
<ide> R.get({a:1});
<ide> R.get({a:2, b:3});
<ide> R.get({a:4, b:5, c:6});
<del> });
<add> }));
<ide>
<del> it('should correctly encode url params', function() {
<add> it('should correctly encode url params', inject(function($browser) {
<ide> var R = resource.route('/Path/:a');
<del> xhr.expectGET('/Path/foo%231').respond({});
<del> xhr.expectGET('/Path/doh!@foo?bar=baz%231').respond({});
<add> $browser.xhr.expectGET('/Path/foo%231').respond({});
<add> $browser.xhr.expectGET('/Path/doh!@foo?bar=baz%231').respond({});
<ide> R.get({a: 'foo#1'});
<ide> R.get({a: 'doh!@foo', bar: 'baz#1'});
<del> });
<add> }));
<ide>
<del> it('should not encode @ in url params', function() {
<add> it('should not encode @ in url params', inject(function($browser) {
<ide> //encodeURIComponent is too agressive and doesn't follow http://www.ietf.org/rfc/rfc3986.txt
<ide> //with regards to the character set (pchar) allowed in path segments
<ide> //so we need this test to make sure that we don't over-encode the params and break stuff like
<ide> //buzz api which uses @self
<ide>
<ide> var R = resource.route('/Path/:a');
<del> xhr.expectGET('/Path/doh@fo%20o?!do%26h=g%3Da+h&:bar=$baz@1').respond({});
<add> $browser.xhr.expectGET('/Path/doh@fo%20o?!do%26h=g%3Da+h&:bar=$baz@1').respond({});
<ide> R.get({a: 'doh@fo o', ':bar': '$baz@1', '!do&h': 'g=a h'});
<del> });
<add> }));
<ide>
<del> it('should encode & in url params', function() {
<add> it('should encode & in url params', inject(function($browser) {
<ide> var R = resource.route('/Path/:a');
<del> xhr.expectGET('/Path/doh&foo?bar=baz%261').respond({});
<add> $browser.xhr.expectGET('/Path/doh&foo?bar=baz%261').respond({});
<ide> R.get({a: 'doh&foo', bar: 'baz&1'});
<del> });
<add> }));
<ide>
<del> it("should build resource with default param", function() {
<del> xhr.expectGET('/Order/123/Line/456.visa?minimum=0.05').respond({id:'abc'});
<add> it("should build resource with default param", inject(function($browser) {
<add> $browser.xhr.expectGET('/Order/123/Line/456.visa?minimum=0.05').respond({id:'abc'});
<ide> var LineItem = resource.route('/Order/:orderId/Line/:id:verb', {orderId: '123', id: '@id.key', verb:'.visa', minimum:0.05});
<ide> var item = LineItem.get({id:456});
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> nakedExpect(item).toEqual({id:'abc'});
<del> });
<add> }));
<ide>
<del> it("should build resource with action default param overriding default param", function() {
<del> xhr.expectGET('/Customer/123').respond({id:'abc'});
<add> it("should build resource with action default param overriding default param", inject(function($browser) {
<add> $browser.xhr.expectGET('/Customer/123').respond({id:'abc'});
<ide> var TypeItem = resource.route('/:type/:typeId', {type: 'Order'},
<ide> {get: {method: 'GET', params: {type: 'Customer'}}});
<ide> var item = TypeItem.get({typeId:123});
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> nakedExpect(item).toEqual({id:'abc'});
<del> });
<add> }));
<ide>
<del> it("should create resource", function() {
<del> xhr.expectPOST('/CreditCard', {name:'misko'}).respond({id:123, name:'misko'});
<add> it("should create resource", inject(function($browser) {
<add> $browser.xhr.expectPOST('/CreditCard', {name:'misko'}).respond({id:123, name:'misko'});
<ide>
<ide> var cc = CreditCard.save({name:'misko'}, callback);
<ide> nakedExpect(cc).toEqual({name:'misko'});
<ide> expect(callback).not.toHaveBeenCalled();
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> nakedExpect(cc).toEqual({id:123, name:'misko'});
<ide> expect(callback).toHaveBeenCalledWith(cc);
<del> });
<add> }));
<ide>
<del> it("should read resource", function() {
<del> xhr.expectGET("/CreditCard/123").respond({id:123, number:'9876'});
<add> it("should read resource", inject(function($browser) {
<add> $browser.xhr.expectGET("/CreditCard/123").respond({id:123, number:'9876'});
<ide> var cc = CreditCard.get({id:123}, callback);
<ide> expect(cc instanceof CreditCard).toBeTruthy();
<ide> nakedExpect(cc).toEqual({});
<ide> expect(callback).not.toHaveBeenCalled();
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> nakedExpect(cc).toEqual({id:123, number:'9876'});
<ide> expect(callback).toHaveBeenCalledWith(cc);
<del> });
<add> }));
<ide>
<del> it("should read partial resource", function() {
<del> xhr.expectGET("/CreditCard").respond([{id:{key:123}}]);
<del> xhr.expectGET("/CreditCard/123").respond({id:{key:123}, number:'9876'});
<add> it("should read partial resource", inject(function($browser) {
<add> $browser.xhr.expectGET("/CreditCard").respond([{id:{key:123}}]);
<add> $browser.xhr.expectGET("/CreditCard/123").respond({id:{key:123}, number:'9876'});
<ide> var ccs = CreditCard.query();
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> expect(ccs.length).toEqual(1);
<ide> var cc = ccs[0];
<ide> expect(cc instanceof CreditCard).toBeTruthy();
<ide> expect(cc.number).not.toBeDefined();
<ide> cc.$get(callback);
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> expect(callback).toHaveBeenCalledWith(cc);
<ide> expect(cc.number).toEqual('9876');
<del> });
<add> }));
<ide>
<del> it("should update resource", function() {
<del> xhr.expectPOST('/CreditCard/123', {id:{key:123}, name:'misko'}).respond({id:{key:123}, name:'rama'});
<add> it("should update resource", inject(function($browser) {
<add> $browser.xhr.expectPOST('/CreditCard/123', {id:{key:123}, name:'misko'}).respond({id:{key:123}, name:'rama'});
<ide>
<ide> var cc = CreditCard.save({id:{key:123}, name:'misko'}, callback);
<ide> nakedExpect(cc).toEqual({id:{key:123}, name:'misko'});
<ide> expect(callback).not.toHaveBeenCalled();
<del> xhr.flush();
<del> });
<add> $browser.xhr.flush();
<add> }));
<ide>
<del> it("should query resource", function() {
<del> xhr.expectGET("/CreditCard?key=value").respond([{id:1}, {id:2}]);
<add> it("should query resource", inject(function($browser) {
<add> $browser.xhr.expectGET("/CreditCard?key=value").respond([{id:1}, {id:2}]);
<ide>
<ide> var ccs = CreditCard.query({key:'value'}, callback);
<ide> expect(ccs).toEqual([]);
<ide> expect(callback).not.toHaveBeenCalled();
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> nakedExpect(ccs).toEqual([{id:1}, {id:2}]);
<ide> expect(callback).toHaveBeenCalledWith(ccs);
<del> });
<add> }));
<ide>
<del> it("should have all arguments optional", function() {
<del> xhr.expectGET('/CreditCard').respond([{id:1}]);
<add> it("should have all arguments optional", inject(function($browser) {
<add> $browser.xhr.expectGET('/CreditCard').respond([{id:1}]);
<ide> var log = '';
<ide> var ccs = CreditCard.query(function() { log += 'cb;'; });
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> nakedExpect(ccs).toEqual([{id:1}]);
<ide> expect(log).toEqual('cb;');
<del> });
<add> }));
<ide>
<del> it('should delete resource and call callback', function() {
<del> xhr.expectDELETE("/CreditCard/123").respond(200, {});
<add> it('should delete resource and call callback', inject(function($browser) {
<add> $browser.xhr.expectDELETE("/CreditCard/123").respond(200, {});
<ide>
<ide> CreditCard.remove({id:123}, callback);
<ide> expect(callback).not.toHaveBeenCalled();
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> nakedExpect(callback.mostRecentCall.args).toEqual([{}]);
<ide>
<ide> callback.reset();
<del> xhr.expectDELETE("/CreditCard/333").respond(204, null);
<add> $browser.xhr.expectDELETE("/CreditCard/333").respond(204, null);
<ide> CreditCard.remove({id:333}, callback);
<ide> expect(callback).not.toHaveBeenCalled();
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> nakedExpect(callback.mostRecentCall.args).toEqual([{}]);
<del> });
<add> }));
<ide>
<del> it('should post charge verb', function() {
<del> xhr.expectPOST('/CreditCard/123!charge?amount=10', {auth:'abc'}).respond({success:'ok'});
<add> it('should post charge verb', inject(function($browser) {
<add> $browser.xhr.expectPOST('/CreditCard/123!charge?amount=10', {auth:'abc'}).respond({success:'ok'});
<ide>
<ide> CreditCard.charge({id:123, amount:10},{auth:'abc'}, callback);
<del> });
<add> }));
<ide>
<del> it('should post charge verb on instance', function() {
<del> xhr.expectPOST('/CreditCard/123!charge?amount=10', {id:{key:123}, name:'misko'}).respond({success:'ok'});
<add> it('should post charge verb on instance', inject(function($browser) {
<add> $browser.xhr.expectPOST('/CreditCard/123!charge?amount=10', {id:{key:123}, name:'misko'}).respond({success:'ok'});
<ide>
<ide> var card = new CreditCard({id:{key:123}, name:'misko'});
<ide> card.$charge({amount:10}, callback);
<del> });
<add> }));
<ide>
<del> it('should create on save', function() {
<del> xhr.expectPOST('/CreditCard', {name:'misko'}).respond({id:123});
<add> it('should create on save', inject(function($browser) {
<add> $browser.xhr.expectPOST('/CreditCard', {name:'misko'}).respond({id:123});
<ide> var cc = new CreditCard();
<ide> expect(cc.$get).toBeDefined();
<ide> expect(cc.$query).toBeDefined();
<ide> describe("resource", function() {
<ide> cc.name = 'misko';
<ide> cc.$save(callback);
<ide> nakedExpect(cc).toEqual({name:'misko'});
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> nakedExpect(cc).toEqual({id:123});
<ide> expect(callback).toHaveBeenCalledWith(cc);
<del> });
<add> }));
<ide>
<del> it('should not mutate the resource object if response contains no body', function() {
<add> it('should not mutate the resource object if response contains no body', inject(function($browser) {
<ide> var data = {id:{key:123}, number:'9876'};
<del> xhr.expectGET("/CreditCard/123").respond(data);
<add> $browser.xhr.expectGET("/CreditCard/123").respond(data);
<ide> var cc = CreditCard.get({id:123});
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> expect(cc instanceof CreditCard).toBeTruthy();
<ide> var idBefore = cc.id;
<ide>
<del> xhr.expectPOST("/CreditCard/123", data).respond('');
<add> $browser.xhr.expectPOST("/CreditCard/123", data).respond('');
<ide> cc.$save();
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> expect(idBefore).toEqual(cc.id);
<del> });
<add> }));
<ide>
<del> it('should bind default parameters', function() {
<del> xhr.expectGET('/CreditCard/123.visa?minimum=0.05').respond({id:123});
<add> it('should bind default parameters', inject(function($browser) {
<add> $browser.xhr.expectGET('/CreditCard/123.visa?minimum=0.05').respond({id:123});
<ide> var Visa = CreditCard.bind({verb:'.visa', minimum:0.05});
<ide> var visa = Visa.get({id:123});
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> nakedExpect(visa).toEqual({id:123});
<del> });
<add> }));
<ide>
<del> it('should excersize full stack', function() {
<del> var scope = angular.compile('<div></div>')();
<del> var $browser = scope.$service('$browser');
<del> var $resource = scope.$service('$resource');
<add> it('should excersize full stack', inject(function($rootScope, $browser, $resource) {
<add> angular.compile('<div></div>')($rootScope);
<ide> var Person = $resource('/Person/:id');
<ide> $browser.xhr.expectGET('/Person/123').respond('\n{\n"name":\n"misko"\n}\n');
<ide> var person = Person.get({id:123});
<ide> $browser.xhr.flush();
<ide> expect(person.name).toEqual('misko');
<del> dealoc(scope);
<del> });
<add> }));
<ide>
<del> it('should return the same object when verifying the cache', function() {
<del> var scope = angular.compile('<div></div>')();
<del> var $browser = scope.$service('$browser');
<del> var $resource = scope.$service('$resource');
<add> it('should return the same object when verifying the cache', inject(function($rootScope) {
<add> angular.compile('<div></div>')($rootScope);
<add> var $browser = $rootScope.$service('$browser');
<add> var $resource = $rootScope.$service('$resource');
<ide> var Person = $resource('/Person/:id', null, {query: {method:'GET', isArray: true, verifyCache: true}});
<ide> $browser.xhr.expectGET('/Person/123').respond('[\n{\n"name":\n"misko"\n}\n]');
<ide> var person = Person.query({id:123});
<ide> describe("resource", function() {
<ide> $browser.xhr.flush();
<ide> expect(person2Cache).toEqual(person2);
<ide> expect(person2[0].name).toEqual('rob');
<del> dealoc(scope);
<del> });
<add> }));
<ide>
<ide> describe('failure mode', function() {
<ide> var ERROR_CODE = 500,
<ide> describe("resource", function() {
<ide> errorCB = jasmine.createSpy();
<ide> });
<ide>
<del> it('should report error when non 2xx if error callback is not provided', function() {
<del> xhr.expectGET('/CreditCard/123').respond(ERROR_CODE, ERROR_RESPONSE);
<add> it('should report error when non 2xx if error callback is not provided',
<add> inject(function($browser, $xhrError) {
<add> $browser.xhr.expectGET('/CreditCard/123').respond(ERROR_CODE, ERROR_RESPONSE);
<ide> CreditCard.get({id:123});
<del> xhr.flush();
<del> expect($xhrErr).toHaveBeenCalled();
<del> });
<add> $browser.xhr.flush();
<add> expect($xhrError).toHaveBeenCalled();
<add> }));
<ide>
<del> it('should call the error callback if provided on non 2xx response', function() {
<del> xhr.expectGET('/CreditCard/123').respond(ERROR_CODE, ERROR_RESPONSE);
<add> it('should call the error callback if provided on non 2xx response',
<add> inject(function($browser, $xhrError) {
<add> $browser.xhr.expectGET('/CreditCard/123').respond(ERROR_CODE, ERROR_RESPONSE);
<ide> CreditCard.get({id:123}, callback, errorCB);
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> expect(errorCB).toHaveBeenCalledWith(500, ERROR_RESPONSE);
<ide> expect(callback).not.toHaveBeenCalled();
<del> expect($xhrErr).not.toHaveBeenCalled();
<del> });
<add> expect($xhrError).not.toHaveBeenCalled();
<add> }));
<ide>
<del> it('should call the error callback if provided on non 2xx response', function() {
<del> xhr.expectGET('/CreditCard').respond(ERROR_CODE, ERROR_RESPONSE);
<add> it('should call the error callback if provided on non 2xx response',
<add> inject(function($browser, $xhrError) {
<add> $browser.xhr.expectGET('/CreditCard').respond(ERROR_CODE, ERROR_RESPONSE);
<ide> CreditCard.get(callback, errorCB);
<del> xhr.flush();
<add> $browser.xhr.flush();
<ide> expect(errorCB).toHaveBeenCalledWith(500, ERROR_RESPONSE);
<ide> expect(callback).not.toHaveBeenCalled();
<del> expect($xhrErr).not.toHaveBeenCalled();
<del> });
<add> expect($xhrError).not.toHaveBeenCalled();
<add> }));
<ide> });
<ide> });
<ide><path>test/ScenarioSpec.js
<ide> 'use strict';
<ide>
<ide> describe("ScenarioSpec: Compilation", function() {
<del> var scope;
<del>
<del> beforeEach(function() {
<del> scope = null;
<del> });
<del>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<del>
<ide> describe('compilation', function() {
<del> it("should compile dom node and return scope", function() {
<add> it("should compile dom node and return scope", inject(function($rootScope) {
<ide> var node = jqLite('<div ng:init="a=1">{{b=a+1}}</div>')[0];
<del> scope = angular.compile(node)();
<del> scope.$digest();
<del> expect(scope.a).toEqual(1);
<del> expect(scope.b).toEqual(2);
<del> });
<add> angular.compile(node)($rootScope);
<add> $rootScope.$digest();
<add> expect($rootScope.a).toEqual(1);
<add> expect($rootScope.b).toEqual(2);
<add> }));
<ide>
<del> it("should compile jQuery node and return scope", function() {
<del> scope = compile(jqLite('<div>{{a=123}}</div>'))();
<del> scope.$digest();
<del> expect(jqLite(scope.$element).text()).toEqual('123');
<del> });
<add> it("should compile jQuery node and return scope", inject(function($rootScope) {
<add> var element = compile(jqLite('<div>{{a=123}}</div>'))($rootScope);
<add> $rootScope.$digest();
<add> expect(jqLite(element).text()).toEqual('123');
<add> }));
<ide>
<del> it("should compile text node and return scope", function() {
<del> scope = angular.compile('<div>{{a=123}}</div>')();
<del> scope.$digest();
<del> expect(jqLite(scope.$element).text()).toEqual('123');
<del> });
<add> it("should compile text node and return scope", inject(function($rootScope) {
<add> var element = angular.compile('<div>{{a=123}}</div>')($rootScope);
<add> $rootScope.$digest();
<add> expect(jqLite(element).text()).toEqual('123');
<add> }));
<ide> });
<ide> });
<ide><path>test/angular-mocksSpec.js
<ide> describe('mocks', function() {
<ide>
<ide>
<ide> describe('$exceptionHandler', function() {
<del> it('should rethrow exceptions', function() {
<del> var rootScope = angular.scope(),
<del> exHandler = rootScope.$service('$exceptionHandler');
<del>
<del> expect(function() { exHandler('myException'); }).toThrow('myException');
<del> });
<add> it('should rethrow exceptions', inject(function($exceptionHandler) {
<add> expect(function() { $exceptionHandler('myException'); }).toThrow('myException');
<add> }));
<ide> });
<ide> });
<ide><path>test/directivesSpec.js
<ide>
<ide> describe("directive", function() {
<ide>
<del> var compile, model, element;
<del>
<del> beforeEach(function() {
<del> compile = function(html) {
<del> element = jqLite(html);
<del> return model = angular.compile(element)();
<del> };
<del> });
<del>
<del> afterEach(function() {
<del> dealoc(model);
<del> });
<del>
<del> it("should ng:init", function() {
<del> var scope = compile('<div ng:init="a=123"></div>');
<del> expect(scope.a).toEqual(123);
<del> });
<add> it("should ng:init", inject(function($rootScope) {
<add> var element = angular.compile('<div ng:init="a=123"></div>')($rootScope);
<add> expect($rootScope.a).toEqual(123);
<add> }));
<ide>
<ide> describe('ng:bind', function() {
<del> it('should set text', function() {
<del> var scope = compile('<div ng:bind="a"></div>');
<add> it('should set text', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:bind="a"></div>')($rootScope);
<ide> expect(element.text()).toEqual('');
<del> scope.a = 'misko';
<del> scope.$digest();
<add> $rootScope.a = 'misko';
<add> $rootScope.$digest();
<ide> expect(element.hasClass('ng-binding')).toEqual(true);
<ide> expect(element.text()).toEqual('misko');
<del> });
<add> }));
<ide>
<del> it('should set text to blank if undefined', function() {
<del> var scope = compile('<div ng:bind="a"></div>');
<del> scope.a = 'misko';
<del> scope.$digest();
<add> it('should set text to blank if undefined', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:bind="a"></div>')($rootScope);
<add> $rootScope.a = 'misko';
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('misko');
<del> scope.a = undefined;
<del> scope.$digest();
<add> $rootScope.a = undefined;
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('');
<del> });
<add> }));
<ide>
<del> it('should set html', function() {
<del> var scope = compile('<div ng:bind="html|html"></div>');
<del> scope.html = '<div unknown>hello</div>';
<del> scope.$digest();
<add> it('should set html', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:bind="html|html"></div>')($rootScope);
<add> $rootScope.html = '<div unknown>hello</div>';
<add> $rootScope.$digest();
<ide> expect(lowercase(element.html())).toEqual('<div>hello</div>');
<del> });
<add> }));
<ide>
<del> it('should set unsafe html', function() {
<del> var scope = compile('<div ng:bind="html|html:\'unsafe\'"></div>');
<del> scope.html = '<div onclick="">hello</div>';
<del> scope.$digest();
<add> it('should set unsafe html', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:bind="html|html:\'unsafe\'"></div>')($rootScope);
<add> $rootScope.html = '<div onclick="">hello</div>';
<add> $rootScope.$digest();
<ide> expect(lowercase(element.html())).toEqual('<div onclick="">hello</div>');
<del> });
<add> }));
<ide>
<del> it('should set element element', function() {
<add> it('should set element element', inject(function($rootScope) {
<ide> angularFilter.myElement = function() {
<ide> return jqLite('<a>hello</a>');
<ide> };
<del> var scope = compile('<div ng:bind="0|myElement"></div>');
<del> scope.$digest();
<add> var element = angular.compile('<div ng:bind="0|myElement"></div>')($rootScope);
<add> $rootScope.$digest();
<ide> expect(lowercase(element.html())).toEqual('<a>hello</a>');
<del> });
<add> }));
<ide>
<del> it('should have $element set to current bind element', function() {
<add> it('should have $element set to current bind element', inject(function($rootScope) {
<ide> angularFilter.myFilter = function() {
<ide> this.$element.addClass("filter");
<ide> return 'HELLO';
<ide> };
<del> var scope = compile('<div>before<div ng:bind="0|myFilter"></div>after</div>');
<del> scope.$digest();
<del> expect(sortedHtml(scope.$element)).toEqual('<div>before<div class="filter" ng:bind="0|myFilter">HELLO</div>after</div>');
<del> });
<del>
<del>
<del> it('should suppress rendering of falsy values', function() {
<del> var scope = compile('<div>{{ null }}{{ undefined }}{{ "" }}-{{ 0 }}{{ false }}</div>');
<del> scope.$digest();
<del> expect(scope.$element.text()).toEqual('-0false');
<del> });
<del>
<del> it('should render object as JSON ignore $$', function() {
<del> var scope = compile('<div>{{ {key:"value", $$key:"hide"} }}</div>');
<del> scope.$digest();
<del> expect(fromJson(scope.$element.text())).toEqual({key:'value'});
<del> });
<add> var element = angular.compile('<div>before<div ng:bind="0|myFilter"></div>after</div>')($rootScope);
<add> $rootScope.$digest();
<add> expect(sortedHtml(element)).toEqual('<div>before<div class="filter" ng:bind="0|myFilter">HELLO</div>after</div>');
<add> }));
<add>
<add>
<add> it('should suppress rendering of falsy values', inject(function($rootScope) {
<add> var element = angular.compile('<div>{{ null }}{{ undefined }}{{ "" }}-{{ 0 }}{{ false }}</div>')($rootScope);
<add> $rootScope.$digest();
<add> expect(element.text()).toEqual('-0false');
<add> }));
<add>
<add> it('should render object as JSON ignore $$', inject(function($rootScope) {
<add> var element = angular.compile('<div>{{ {key:"value", $$key:"hide"} }}</div>')($rootScope);
<add> $rootScope.$digest();
<add> expect(fromJson(element.text())).toEqual({key:'value'});
<add> }));
<ide> });
<ide>
<ide> describe('ng:bind-template', function() {
<del> it('should ng:bind-template', function() {
<del> var scope = compile('<div ng:bind-template="Hello {{name}}!"></div>');
<del> scope.name = 'Misko';
<del> scope.$digest();
<add> it('should ng:bind-template', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:bind-template="Hello {{name}}!"></div>')($rootScope);
<add> $rootScope.name = 'Misko';
<add> $rootScope.$digest();
<ide> expect(element.hasClass('ng-binding')).toEqual(true);
<ide> expect(element.text()).toEqual('Hello Misko!');
<del> });
<add> }));
<ide>
<del> it('should have $element set to current bind element', function() {
<add> it('should have $element set to current bind element', inject(function($rootScope) {
<ide> var innerText;
<ide> angularFilter.myFilter = function(text) {
<ide> innerText = innerText || this.$element.text();
<ide> return text;
<ide> };
<del> var scope = compile('<div>before<span ng:bind-template="{{\'HELLO\'|myFilter}}">INNER</span>after</div>');
<del> scope.$digest();
<del> expect(scope.$element.text()).toEqual("beforeHELLOafter");
<add> var element = angular.compile('<div>before<span ng:bind-template="{{\'HELLO\'|myFilter}}">INNER</span>after</div>')($rootScope);
<add> $rootScope.$digest();
<add> expect(element.text()).toEqual("beforeHELLOafter");
<ide> expect(innerText).toEqual('INNER');
<del> });
<add> }));
<ide>
<del> it('should render object as JSON ignore $$', function() {
<del> var scope = compile('<pre>{{ {key:"value", $$key:"hide"} }}</pre>');
<del> scope.$digest();
<del> expect(fromJson(scope.$element.text())).toEqual({key:'value'});
<del> });
<add> it('should render object as JSON ignore $$', inject(function($rootScope) {
<add> var element = angular.compile('<pre>{{ {key:"value", $$key:"hide"} }}</pre>')($rootScope);
<add> $rootScope.$digest();
<add> expect(fromJson(element.text())).toEqual({key:'value'});
<add> }));
<ide>
<ide> });
<ide>
<ide> describe('ng:bind-attr', function() {
<del> it('should bind attributes', function() {
<del> var scope = compile('<div ng:bind-attr="{src:\'http://localhost/mysrc\', alt:\'myalt\'}"/>');
<del> scope.$digest();
<add> it('should bind attributes', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:bind-attr="{src:\'http://localhost/mysrc\', alt:\'myalt\'}"/>')($rootScope);
<add> $rootScope.$digest();
<ide> expect(element.attr('src')).toEqual('http://localhost/mysrc');
<ide> expect(element.attr('alt')).toEqual('myalt');
<del> });
<add> }));
<ide>
<del> it('should not pretty print JSON in attributes', function() {
<del> var scope = compile('<img alt="{{ {a:1} }}"/>');
<del> scope.$digest();
<add> it('should not pretty print JSON in attributes', inject(function($rootScope) {
<add> var element = angular.compile('<img alt="{{ {a:1} }}"/>')($rootScope);
<add> $rootScope.$digest();
<ide> expect(element.attr('alt')).toEqual('{"a":1}');
<del> });
<add> }));
<ide> });
<ide>
<del> it('should remove special attributes on false', function() {
<del> var scope = compile('<input ng:bind-attr="{disabled:\'{{disabled}}\', readonly:\'{{readonly}}\', checked:\'{{checked}}\'}"/>');
<del> var input = scope.$element[0];
<add> it('should remove special attributes on false', inject(function($rootScope) {
<add> var element = angular.compile('<input ng:bind-attr="{disabled:\'{{disabled}}\', readonly:\'{{readonly}}\', checked:\'{{checked}}\'}"/>')($rootScope);
<add> var input = element[0];
<ide> expect(input.disabled).toEqual(false);
<ide> expect(input.readOnly).toEqual(false);
<ide> expect(input.checked).toEqual(false);
<ide>
<del> scope.disabled = true;
<del> scope.readonly = true;
<del> scope.checked = true;
<del> scope.$digest();
<add> $rootScope.disabled = true;
<add> $rootScope.readonly = true;
<add> $rootScope.checked = true;
<add> $rootScope.$digest();
<ide>
<ide> expect(input.disabled).toEqual(true);
<ide> expect(input.readOnly).toEqual(true);
<ide> expect(input.checked).toEqual(true);
<del> });
<add> }));
<ide>
<ide> describe('ng:click', function() {
<del> it('should get called on a click', function() {
<del> var scope = compile('<div ng:click="clicked = true"></div>');
<del> scope.$digest();
<del> expect(scope.clicked).toBeFalsy();
<add> it('should get called on a click', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:click="clicked = true"></div>')($rootScope);
<add> $rootScope.$digest();
<add> expect($rootScope.clicked).toBeFalsy();
<ide>
<ide> browserTrigger(element, 'click');
<del> expect(scope.clicked).toEqual(true);
<del> });
<add> expect($rootScope.clicked).toEqual(true);
<add> }));
<ide>
<del> it('should stop event propagation', function() {
<del> var scope = compile('<div ng:click="outer = true"><div ng:click="inner = true"></div></div>');
<del> scope.$digest();
<del> expect(scope.outer).not.toBeDefined();
<del> expect(scope.inner).not.toBeDefined();
<add> it('should stop event propagation', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:click="outer = true"><div ng:click="inner = true"></div></div>')($rootScope);
<add> $rootScope.$digest();
<add> expect($rootScope.outer).not.toBeDefined();
<add> expect($rootScope.inner).not.toBeDefined();
<ide>
<ide> var innerDiv = element.children()[0];
<ide>
<ide> browserTrigger(innerDiv, 'click');
<del> expect(scope.outer).not.toBeDefined();
<del> expect(scope.inner).toEqual(true);
<del> });
<add> expect($rootScope.outer).not.toBeDefined();
<add> expect($rootScope.inner).toEqual(true);
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('ng:submit', function() {
<del> it('should get called on form submit', function() {
<del> var scope = compile('<form action="" ng:submit="submitted = true">' +
<del> '<input type="submit"/>' +
<del> '</form>');
<del> scope.$digest();
<del> expect(scope.submitted).not.toBeDefined();
<add> it('should get called on form submit', inject(function($rootScope) {
<add> var element = angular.compile('<form action="" ng:submit="submitted = true">' +
<add> '<input type="submit"/>' +
<add> '</form>')($rootScope);
<add> $rootScope.$digest();
<add> expect($rootScope.submitted).not.toBeDefined();
<ide>
<ide> browserTrigger(element.children()[0]);
<del> expect(scope.submitted).toEqual(true);
<del> });
<add> expect($rootScope.submitted).toEqual(true);
<add> }));
<ide> });
<ide>
<ide> describe('ng:class', function() {
<del> it('should add new and remove old classes dynamically', function() {
<del> var scope = compile('<div class="existing" ng:class="dynClass"></div>');
<del> scope.dynClass = 'A';
<del> scope.$digest();
<add> it('should add new and remove old classes dynamically', inject(function($rootScope) {
<add> var element = angular.compile('<div class="existing" ng:class="dynClass"></div>')($rootScope);
<add> $rootScope.dynClass = 'A';
<add> $rootScope.$digest();
<ide> expect(element.hasClass('existing')).toBe(true);
<ide> expect(element.hasClass('A')).toBe(true);
<ide>
<del> scope.dynClass = 'B';
<del> scope.$digest();
<add> $rootScope.dynClass = 'B';
<add> $rootScope.$digest();
<ide> expect(element.hasClass('existing')).toBe(true);
<ide> expect(element.hasClass('A')).toBe(false);
<ide> expect(element.hasClass('B')).toBe(true);
<ide>
<del> delete scope.dynClass;
<del> scope.$digest();
<add> delete $rootScope.dynClass;
<add> $rootScope.$digest();
<ide> expect(element.hasClass('existing')).toBe(true);
<ide> expect(element.hasClass('A')).toBe(false);
<ide> expect(element.hasClass('B')).toBe(false);
<del> });
<add> }));
<ide>
<ide>
<del> it('should support adding multiple classes via an array', function() {
<del> var scope = compile('<div class="existing" ng:class="[\'A\', \'B\']"></div>');
<del> scope.$digest();
<add> it('should support adding multiple classes via an array', inject(function($rootScope) {
<add> var element = angular.compile('<div class="existing" ng:class="[\'A\', \'B\']"></div>')($rootScope);
<add> $rootScope.$digest();
<ide> expect(element.hasClass('existing')).toBeTruthy();
<ide> expect(element.hasClass('A')).toBeTruthy();
<ide> expect(element.hasClass('B')).toBeTruthy();
<del> });
<add> }));
<ide>
<ide>
<del> it('should support adding multiple classes via a space delimited string', function() {
<del> var scope = compile('<div class="existing" ng:class="\'A B\'"></div>');
<del> scope.$digest();
<add> it('should support adding multiple classes via a space delimited string', inject(function($rootScope) {
<add> var element = angular.compile('<div class="existing" ng:class="\'A B\'"></div>')($rootScope);
<add> $rootScope.$digest();
<ide> expect(element.hasClass('existing')).toBeTruthy();
<ide> expect(element.hasClass('A')).toBeTruthy();
<ide> expect(element.hasClass('B')).toBeTruthy();
<del> });
<add> }));
<ide>
<ide>
<del> it('should preserve class added post compilation with pre-existing classes', function() {
<del> var scope = compile('<div class="existing" ng:class="dynClass"></div>');
<del> scope.dynClass = 'A';
<del> scope.$digest();
<add> it('should preserve class added post compilation with pre-existing classes', inject(function($rootScope) {
<add> var element = angular.compile('<div class="existing" ng:class="dynClass"></div>')($rootScope);
<add> $rootScope.dynClass = 'A';
<add> $rootScope.$digest();
<ide> expect(element.hasClass('existing')).toBe(true);
<ide>
<ide> // add extra class, change model and eval
<ide> element.addClass('newClass');
<del> scope.dynClass = 'B';
<del> scope.$digest();
<add> $rootScope.dynClass = 'B';
<add> $rootScope.$digest();
<ide>
<ide> expect(element.hasClass('existing')).toBe(true);
<ide> expect(element.hasClass('B')).toBe(true);
<ide> expect(element.hasClass('newClass')).toBe(true);
<del> });
<add> }));
<ide>
<ide>
<del> it('should preserve class added post compilation without pre-existing classes"', function() {
<del> var scope = compile('<div ng:class="dynClass"></div>');
<del> scope.dynClass = 'A';
<del> scope.$digest();
<add> it('should preserve class added post compilation without pre-existing classes"', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:class="dynClass"></div>')($rootScope);
<add> $rootScope.dynClass = 'A';
<add> $rootScope.$digest();
<ide> expect(element.hasClass('A')).toBe(true);
<ide>
<ide> // add extra class, change model and eval
<ide> element.addClass('newClass');
<del> scope.dynClass = 'B';
<del> scope.$digest();
<add> $rootScope.dynClass = 'B';
<add> $rootScope.$digest();
<ide>
<ide> expect(element.hasClass('B')).toBe(true);
<ide> expect(element.hasClass('newClass')).toBe(true);
<del> });
<add> }));
<ide>
<ide>
<del> it('should preserve other classes with similar name"', function() {
<del> var scope = compile('<div class="ui-panel ui-selected" ng:class="dynCls"></div>');
<del> scope.dynCls = 'panel';
<del> scope.$digest();
<del> scope.dynCls = 'foo';
<del> scope.$digest();
<add> it('should preserve other classes with similar name"', inject(function($rootScope) {
<add> var element = angular.compile('<div class="ui-panel ui-selected" ng:class="dynCls"></div>')($rootScope);
<add> $rootScope.dynCls = 'panel';
<add> $rootScope.$digest();
<add> $rootScope.dynCls = 'foo';
<add> $rootScope.$digest();
<ide> expect(element[0].className).toBe('ui-panel ui-selected ng-directive foo');
<del> });
<add> }));
<ide>
<ide>
<del> it('should not add duplicate classes', function() {
<del> var scope = compile('<div class="panel bar" ng:class="dynCls"></div>');
<del> scope.dynCls = 'panel';
<del> scope.$digest();
<add> it('should not add duplicate classes', inject(function($rootScope) {
<add> var element = angular.compile('<div class="panel bar" ng:class="dynCls"></div>')($rootScope);
<add> $rootScope.dynCls = 'panel';
<add> $rootScope.$digest();
<ide> expect(element[0].className).toBe('panel bar ng-directive');
<del> });
<add> }));
<ide>
<ide>
<del> it('should remove classes even if it was specified via class attribute', function() {
<del> var scope = compile('<div class="panel bar" ng:class="dynCls"></div>');
<del> scope.dynCls = 'panel';
<del> scope.$digest();
<del> scope.dynCls = 'window';
<del> scope.$digest();
<add> it('should remove classes even if it was specified via class attribute', inject(function($rootScope) {
<add> var element = angular.compile('<div class="panel bar" ng:class="dynCls"></div>')($rootScope);
<add> $rootScope.dynCls = 'panel';
<add> $rootScope.$digest();
<add> $rootScope.dynCls = 'window';
<add> $rootScope.$digest();
<ide> expect(element[0].className).toBe('bar ng-directive window');
<del> });
<add> }));
<ide>
<ide>
<del> it('should remove classes even if they were added by another code', function() {
<del> var scope = compile('<div ng:class="dynCls"></div>');
<del> scope.dynCls = 'foo';
<del> scope.$digest();
<add> it('should remove classes even if they were added by another code', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:class="dynCls"></div>')($rootScope);
<add> $rootScope.dynCls = 'foo';
<add> $rootScope.$digest();
<ide> element.addClass('foo');
<del> scope.dynCls = '';
<del> scope.$digest();
<add> $rootScope.dynCls = '';
<add> $rootScope.$digest();
<ide> expect(element[0].className).toBe('ng-directive');
<del> });
<add> }));
<ide>
<ide>
<del> it('should convert undefined and null values to an empty string', function() {
<del> var scope = compile('<div ng:class="dynCls"></div>');
<del> scope.dynCls = [undefined, null];
<del> scope.$digest();
<add> it('should convert undefined and null values to an empty string', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:class="dynCls"></div>')($rootScope);
<add> $rootScope.dynCls = [undefined, null];
<add> $rootScope.$digest();
<ide> expect(element[0].className).toBe('ng-directive');
<del> });
<add> }));
<ide> });
<ide>
<ide>
<del> it('should ng:class odd/even', function() {
<del> var scope = compile('<ul><li ng:repeat="i in [0,1]" class="existing" ng:class-odd="\'odd\'" ng:class-even="\'even\'"></li><ul>');
<del> scope.$digest();
<add> it('should ng:class odd/even', inject(function($rootScope) {
<add> var element = angular.compile('<ul><li ng:repeat="i in [0,1]" class="existing" ng:class-odd="\'odd\'" ng:class-even="\'even\'"></li><ul>')($rootScope);
<add> $rootScope.$digest();
<ide> var e1 = jqLite(element[0].childNodes[1]);
<ide> var e2 = jqLite(element[0].childNodes[2]);
<ide> expect(e1.hasClass('existing')).toBeTruthy();
<ide> expect(e1.hasClass('odd')).toBeTruthy();
<ide> expect(e2.hasClass('existing')).toBeTruthy();
<ide> expect(e2.hasClass('even')).toBeTruthy();
<del> });
<add> }));
<ide>
<ide>
<del> it('should allow both ng:class and ng:class-odd/even on the same element', function() {
<del> var scope = compile('<ul>' +
<del> '<li ng:repeat="i in [0,1]" ng:class="\'plainClass\'" ' +
<del> 'ng:class-odd="\'odd\'" ng:class-even="\'even\'"></li>' +
<del> '<ul>');
<del> scope.$apply();
<add> it('should allow both ng:class and ng:class-odd/even on the same element', inject(function($rootScope) {
<add> var element = angular.compile('<ul>' +
<add> '<li ng:repeat="i in [0,1]" ng:class="\'plainClass\'" ' +
<add> 'ng:class-odd="\'odd\'" ng:class-even="\'even\'"></li>' +
<add> '<ul>')($rootScope);
<add> $rootScope.$apply();
<ide> var e1 = jqLite(element[0].childNodes[1]);
<ide> var e2 = jqLite(element[0].childNodes[2]);
<ide>
<ide> describe("directive", function() {
<ide> expect(e2.hasClass('plainClass')).toBeTruthy();
<ide> expect(e2.hasClass('even')).toBeTruthy();
<ide> expect(e2.hasClass('odd')).toBeFalsy();
<del> });
<add> }));
<ide>
<ide>
<del> it('should allow both ng:class and ng:class-odd/even with multiple classes', function() {
<del> var scope = compile('<ul>' +
<del> '<li ng:repeat="i in [0,1]" ng:class="[\'A\', \'B\']" ' +
<del> 'ng:class-odd="[\'C\', \'D\']" ng:class-even="[\'E\', \'F\']"></li>' +
<del> '<ul>');
<del> scope.$apply();
<add> it('should allow both ng:class and ng:class-odd/even with multiple classes', inject(function($rootScope) {
<add> var element = angular.compile('<ul>' +
<add> '<li ng:repeat="i in [0,1]" ng:class="[\'A\', \'B\']" ' +
<add> 'ng:class-odd="[\'C\', \'D\']" ng:class-even="[\'E\', \'F\']"></li>' +
<add> '<ul>')($rootScope);
<add> $rootScope.$apply();
<ide> var e1 = jqLite(element[0].childNodes[1]);
<ide> var e2 = jqLite(element[0].childNodes[2]);
<ide>
<ide> describe("directive", function() {
<ide> expect(e2.hasClass('F')).toBeTruthy();
<ide> expect(e2.hasClass('C')).toBeFalsy();
<ide> expect(e2.hasClass('D')).toBeFalsy();
<del> });
<add> }));
<ide>
<ide>
<ide> describe('ng:style', function() {
<ide>
<del> it('should set', function() {
<del> var scope = compile('<div ng:style="{height: \'40px\'}"></div>');
<del> scope.$digest();
<add> it('should set', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:style="{height: \'40px\'}"></div>')($rootScope);
<add> $rootScope.$digest();
<ide> expect(element.css('height')).toEqual('40px');
<del> });
<add> }));
<ide>
<ide>
<del> it('should silently ignore undefined style', function() {
<del> var scope = compile('<div ng:style="myStyle"></div>');
<del> scope.$digest();
<add> it('should silently ignore undefined style', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:style="myStyle"></div>')($rootScope);
<add> $rootScope.$digest();
<ide> expect(element.hasClass('ng-exception')).toBeFalsy();
<del> });
<add> }));
<ide>
<ide>
<ide> describe('preserving styles set before and after compilation', function() {
<del> var scope, preCompStyle, preCompVal, postCompStyle, postCompVal;
<add> var scope, preCompStyle, preCompVal, postCompStyle, postCompVal, element;
<ide>
<del> beforeEach(function() {
<add> beforeEach(inject(function($rootScope) {
<ide> preCompStyle = 'width';
<ide> preCompVal = '300px';
<ide> postCompStyle = 'height';
<ide> postCompVal = '100px';
<ide> element = jqLite('<div ng:style="styleObj"></div>');
<ide> element.css(preCompStyle, preCompVal);
<ide> jqLite(document.body).append(element);
<del> scope = compile(element);
<add> angular.compile(element)($rootScope);
<add> scope = $rootScope;
<ide> scope.styleObj = {'margin-top': '44px'};
<ide> scope.$apply();
<ide> element.css(postCompStyle, postCompVal);
<del> });
<add> }));
<ide>
<ide> afterEach(function() {
<ide> element.remove();
<ide> describe("directive", function() {
<ide>
<ide>
<ide> describe('ng:show', function() {
<del> it('should show and hide an element', function() {
<del> var element = jqLite('<div ng:show="exp"></div>'),
<del> scope = compile(element);
<del>
<del> scope.$digest();
<add> it('should show and hide an element', inject(function($rootScope) {
<add> var element = jqLite('<div ng:show="exp"></div>');
<add> var element = angular.compile(element)($rootScope);
<add> $rootScope.$digest();
<ide> expect(isCssVisible(element)).toEqual(false);
<del> scope.exp = true;
<del> scope.$digest();
<add> $rootScope.exp = true;
<add> $rootScope.$digest();
<ide> expect(isCssVisible(element)).toEqual(true);
<del> });
<del>
<add> }));
<ide>
<del> it('should make hidden element visible', function() {
<del> var element = jqLite('<div style="display: none" ng:show="exp"></div>'),
<del> scope = compile(element);
<ide>
<add> it('should make hidden element visible', inject(function($rootScope) {
<add> var element = jqLite('<div style="display: none" ng:show="exp"></div>');
<add> var element = angular.compile(element)($rootScope);
<ide> expect(isCssVisible(element)).toBe(false);
<del> scope.exp = true;
<del> scope.$digest();
<add> $rootScope.exp = true;
<add> $rootScope.$digest();
<ide> expect(isCssVisible(element)).toBe(true);
<del> });
<add> }));
<ide> });
<ide>
<ide> describe('ng:hide', function() {
<del> it('should hide an element', function() {
<del> var element = jqLite('<div ng:hide="exp"></div>'),
<del> scope = compile(element);
<del>
<add> it('should hide an element', inject(function($rootScope) {
<add> var element = jqLite('<div ng:hide="exp"></div>');
<add> var element = angular.compile(element)($rootScope);
<ide> expect(isCssVisible(element)).toBe(true);
<del> scope.exp = true;
<del> scope.$digest();
<add> $rootScope.exp = true;
<add> $rootScope.$digest();
<ide> expect(isCssVisible(element)).toBe(false);
<del> });
<add> }));
<ide> });
<ide>
<ide> describe('ng:controller', function() {
<ide> describe("directive", function() {
<ide> window.temp = undefined;
<ide> });
<ide>
<del> it('should bind', function() {
<del> var scope = compile('<div ng:controller="temp.Greeter"></div>');
<del> expect(scope.greeter.greeting).toEqual('hello');
<del> expect(scope.greeter.greet('misko')).toEqual('hello misko!');
<del> });
<add> it('should bind', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:controller="temp.Greeter"></div>')($rootScope);
<add> expect($rootScope.greeter.greeting).toEqual('hello');
<add> expect($rootScope.greeter.greet('misko')).toEqual('hello misko!');
<add> }));
<ide>
<del> it('should support nested controllers', function() {
<add> it('should support nested controllers', inject(function($rootScope) {
<ide> temp.ChildGreeter = function() {
<ide> this.greeting = 'hey';
<ide> this.$root.childGreeter = this;
<ide> describe("directive", function() {
<ide> return this.greeting + ' dude' + this.suffix;
<ide> }
<ide> };
<del> var scope = compile('<div ng:controller="temp.Greeter"><div ng:controller="temp.ChildGreeter">{{greet("misko")}}</div></div>');
<del> expect(scope.greeting).not.toBeDefined();
<del> expect(scope.greeter.greeting).toEqual('hello');
<del> expect(scope.greeter.greet('misko')).toEqual('hello misko!');
<del> expect(scope.greeter.greeting).toEqual('hello');
<del> expect(scope.childGreeter.greeting).toEqual('hey');
<del> expect(scope.childGreeter.$parent.greeting).toEqual('hello');
<del> scope.$digest();
<del> expect(scope.$element.text()).toEqual('hey dude!');
<del> });
<del>
<del> it('should infer injection arguments', function() {
<add> var element = angular.compile('<div ng:controller="temp.Greeter"><div ng:controller="temp.ChildGreeter">{{greet("misko")}}</div></div>')($rootScope);
<add> expect($rootScope.greeting).not.toBeDefined();
<add> expect($rootScope.greeter.greeting).toEqual('hello');
<add> expect($rootScope.greeter.greet('misko')).toEqual('hello misko!');
<add> expect($rootScope.greeter.greeting).toEqual('hello');
<add> expect($rootScope.childGreeter.greeting).toEqual('hey');
<add> expect($rootScope.childGreeter.$parent.greeting).toEqual('hello');
<add> $rootScope.$digest();
<add> expect(element.text()).toEqual('hey dude!');
<add> }));
<add>
<add> it('should infer injection arguments', inject(function($rootScope) {
<ide> temp.MyController = function($xhr){
<ide> this.$root.someService = $xhr;
<ide> };
<del> var scope = compile('<div ng:controller="temp.MyController"></div>');
<del> expect(scope.someService).toBe(scope.$service('$xhr'));
<del> });
<add> var element = angular.compile('<div ng:controller="temp.MyController"></div>')($rootScope);
<add> expect($rootScope.someService).toBe($rootScope.$service('$xhr'));
<add> }));
<ide> });
<ide>
<ide> describe('ng:cloak', function() {
<ide>
<del> it('should get removed when an element is compiled', function() {
<add> it('should get removed when an element is compiled', inject(function($rootScope) {
<ide> var element = jqLite('<div ng:cloak></div>');
<ide> expect(element.attr('ng:cloak')).toBe('');
<ide> angular.compile(element);
<ide> expect(element.attr('ng:cloak')).toBeUndefined();
<del> });
<add> }));
<ide>
<ide>
<del> it('should remove ng-cloak class from a compiled element', function() {
<add> it('should remove ng-cloak class from a compiled element', inject(function($rootScope) {
<ide> var element = jqLite('<div ng:cloak class="foo ng-cloak bar"></div>');
<ide>
<ide> expect(element.hasClass('foo')).toBe(true);
<ide> describe("directive", function() {
<ide> expect(element.hasClass('foo')).toBe(true);
<ide> expect(element.hasClass('ng-cloak')).toBe(false);
<ide> expect(element.hasClass('bar')).toBe(true);
<del> });
<add> }));
<ide> });
<ide> });
<ide><path>test/jqLiteSpec.js
<ide> describe('jqLite', function() {
<ide> });
<ide>
<ide>
<del> beforeEach(function() {
<del> scope = angular.scope();
<add> beforeEach(inject(function($rootScope) {
<add> scope = $rootScope;
<ide> this.addMatchers({
<ide> toJqEqual: function(expected) {
<ide> var msg = "Unequal length";
<ide> describe('jqLite', function() {
<ide> return value;
<ide> }
<ide> });
<del> });
<add> }));
<ide>
<ide>
<ide> afterEach(function() {
<ide><path>test/markupSpec.js
<ide>
<ide> describe("markups", function() {
<ide>
<del> var compile, element, scope;
<del>
<del> beforeEach(function() {
<del> scope = null;
<del> element = null;
<del> compile = function(html) {
<del> element = jqLite(html);
<del> scope = angular.compile(element)();
<del> };
<del> });
<del>
<del> afterEach(function() {
<del> dealoc(element);
<del> });
<del>
<del> it('should translate {{}} in text', function() {
<del> compile('<div>hello {{name}}!</div>');
<add> it('should translate {{}} in text', inject(function($rootScope) {
<add> var element = angular.compile('<div>hello {{name}}!</div>')($rootScope)
<ide> expect(sortedHtml(element)).toEqual('<div>hello <span ng:bind="name"></span>!</div>');
<del> scope.name = 'Misko';
<del> scope.$digest();
<add> $rootScope.name = 'Misko';
<add> $rootScope.$digest();
<ide> expect(sortedHtml(element)).toEqual('<div>hello <span ng:bind="name">Misko</span>!</div>');
<del> });
<add> }));
<ide>
<del> it('should translate {{}} in terminal nodes', function() {
<del> compile('<select ng:model="x"><option value="">Greet {{name}}!</option></select>');
<del> scope.$digest();
<add> it('should translate {{}} in terminal nodes', inject(function($rootScope) {
<add> var element = angular.compile('<select ng:model="x"><option value="">Greet {{name}}!</option></select>')($rootScope)
<add> $rootScope.$digest();
<ide> expect(sortedHtml(element).replace(' selected="true"', '')).
<ide> toEqual('<select ng:model="x">' +
<ide> '<option ng:bind-template="Greet {{name}}!">Greet !</option>' +
<ide> '</select>');
<del> scope.name = 'Misko';
<del> scope.$digest();
<add> $rootScope.name = 'Misko';
<add> $rootScope.$digest();
<ide> expect(sortedHtml(element).replace(' selected="true"', '')).
<ide> toEqual('<select ng:model="x">' +
<ide> '<option ng:bind-template="Greet {{name}}!">Greet Misko!</option>' +
<ide> '</select>');
<del> });
<add> }));
<ide>
<del> it('should translate {{}} in attributes', function() {
<del> compile('<div src="http://server/{{path}}.png"/>');
<add> it('should translate {{}} in attributes', inject(function($rootScope) {
<add> var element = angular.compile('<div src="http://server/{{path}}.png"/>')($rootScope)
<ide> expect(element.attr('ng:bind-attr')).toEqual('{"src":"http://server/{{path}}.png"}');
<del> scope.path = 'a/b';
<del> scope.$digest();
<add> $rootScope.path = 'a/b';
<add> $rootScope.$digest();
<ide> expect(element.attr('src')).toEqual("http://server/a/b.png");
<del> });
<add> }));
<ide>
<ide> describe('OPTION value', function() {
<ide> beforeEach(function() {
<ide> describe("markups", function() {
<ide> });
<ide> });
<ide>
<del> afterEach(function() {
<del> if (element) element.remove();
<del> });
<del>
<ide>
<del> it('should populate value attribute on OPTION', function() {
<del> compile('<select ng:model="x"><option>abc</option></select>');
<add> it('should populate value attribute on OPTION', inject(function($rootScope) {
<add> var element = angular.compile('<select ng:model="x"><option>abc</option></select>')($rootScope)
<ide> expect(element).toHaveValue('abc');
<del> });
<add> }));
<ide>
<del> it('should ignore value if already exists', function() {
<del> compile('<select ng:model="x"><option value="abc">xyz</option></select>');
<add> it('should ignore value if already exists', inject(function($rootScope) {
<add> var element = angular.compile('<select ng:model="x"><option value="abc">xyz</option></select>')($rootScope)
<ide> expect(element).toHaveValue('abc');
<del> });
<add> }));
<ide>
<del> it('should set value even if newlines present', function() {
<del> compile('<select ng:model="x"><option attr="\ntext\n" \n>\nabc\n</option></select>');
<add> it('should set value even if newlines present', inject(function($rootScope) {
<add> var element = angular.compile('<select ng:model="x"><option attr="\ntext\n" \n>\nabc\n</option></select>')($rootScope)
<ide> expect(element).toHaveValue('\nabc\n');
<del> });
<add> }));
<ide>
<del> it('should set value even if self closing HTML', function() {
<add> it('should set value even if self closing HTML', inject(function($rootScope) {
<ide> // IE removes the \n from option, which makes this test pointless
<ide> if (msie) return;
<del> compile('<select ng:model="x"><option>\n</option></select>');
<add> var element = angular.compile('<select ng:model="x"><option>\n</option></select>')($rootScope)
<ide> expect(element).toHaveValue('\n');
<del> });
<add> }));
<ide>
<ide> });
<ide>
<del> it('should bind href', function() {
<del> compile('<a ng:href="{{url}}"></a>');
<add> it('should bind href', inject(function($rootScope) {
<add> var element = angular.compile('<a ng:href="{{url}}"></a>')($rootScope)
<ide> expect(sortedHtml(element)).toEqual('<a ng:bind-attr="{"href":"{{url}}"}"></a>');
<del> });
<add> }));
<ide>
<del> it('should bind disabled', function() {
<del> compile('<button ng:disabled="{{isDisabled}}">Button</button>');
<del> scope.isDisabled = false;
<del> scope.$digest();
<add> it('should bind disabled', inject(function($rootScope) {
<add> var element = angular.compile('<button ng:disabled="{{isDisabled}}">Button</button>')($rootScope)
<add> $rootScope.isDisabled = false;
<add> $rootScope.$digest();
<ide> expect(element.attr('disabled')).toBeFalsy();
<del> scope.isDisabled = true;
<del> scope.$digest();
<add> $rootScope.isDisabled = true;
<add> $rootScope.$digest();
<ide> expect(element.attr('disabled')).toBeTruthy();
<del> });
<add> }));
<ide>
<del> it('should bind checked', function() {
<del> compile('<input type="checkbox" ng:checked="{{isChecked}}" />');
<del> scope.isChecked = false;
<del> scope.$digest();
<add> it('should bind checked', inject(function($rootScope) {
<add> var element = angular.compile('<input type="checkbox" ng:checked="{{isChecked}}" />')($rootScope)
<add> $rootScope.isChecked = false;
<add> $rootScope.$digest();
<ide> expect(element.attr('checked')).toBeFalsy();
<del> scope.isChecked=true;
<del> scope.$digest();
<add> $rootScope.isChecked=true;
<add> $rootScope.$digest();
<ide> expect(element.attr('checked')).toBeTruthy();
<del> });
<add> }));
<ide>
<del> it('should bind selected', function() {
<del> compile('<select><option value=""></option><option ng:selected="{{isSelected}}">Greetings!</option></select>');
<add> it('should bind selected', inject(function($rootScope) {
<add> var element = angular.compile('<select><option value=""></option><option ng:selected="{{isSelected}}">Greetings!</option></select>')($rootScope)
<ide> jqLite(document.body).append(element)
<del> scope.isSelected=false;
<del> scope.$digest();
<add> $rootScope.isSelected=false;
<add> $rootScope.$digest();
<ide> expect(element.children()[1].selected).toBeFalsy();
<del> scope.isSelected=true;
<del> scope.$digest();
<add> $rootScope.isSelected=true;
<add> $rootScope.$digest();
<ide> expect(element.children()[1].selected).toBeTruthy();
<del> });
<add> }));
<ide>
<del> it('should bind readonly', function() {
<del> compile('<input type="text" ng:readonly="{{isReadonly}}" />');
<del> scope.isReadonly=false;
<del> scope.$digest();
<add> it('should bind readonly', inject(function($rootScope) {
<add> var element = angular.compile('<input type="text" ng:readonly="{{isReadonly}}" />')($rootScope)
<add> $rootScope.isReadonly=false;
<add> $rootScope.$digest();
<ide> expect(element.attr('readOnly')).toBeFalsy();
<del> scope.isReadonly=true;
<del> scope.$digest();
<add> $rootScope.isReadonly=true;
<add> $rootScope.$digest();
<ide> expect(element.attr('readOnly')).toBeTruthy();
<del> });
<add> }));
<ide>
<del> it('should bind multiple', function() {
<del> compile('<select ng:multiple="{{isMultiple}}"></select>');
<del> scope.isMultiple=false;
<del> scope.$digest();
<add> it('should bind multiple', inject(function($rootScope) {
<add> var element = angular.compile('<select ng:multiple="{{isMultiple}}"></select>')($rootScope)
<add> $rootScope.isMultiple=false;
<add> $rootScope.$digest();
<ide> expect(element.attr('multiple')).toBeFalsy();
<del> scope.isMultiple='multiple';
<del> scope.$digest();
<add> $rootScope.isMultiple='multiple';
<add> $rootScope.$digest();
<ide> expect(element.attr('multiple')).toBeTruthy();
<del> });
<add> }));
<ide>
<del> it('should bind src', function() {
<del> compile('<div ng:src="{{url}}" />');
<del> scope.url = 'http://localhost/';
<del> scope.$digest();
<add> it('should bind src', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:src="{{url}}" />')($rootScope)
<add> $rootScope.url = 'http://localhost/';
<add> $rootScope.$digest();
<ide> expect(element.attr('src')).toEqual('http://localhost/');
<del> });
<add> }));
<ide>
<del> it('should bind href and merge with other attrs', function() {
<del> compile('<a ng:href="{{url}}" rel="{{rel}}"></a>');
<add> it('should bind href and merge with other attrs', inject(function($rootScope) {
<add> var element = angular.compile('<a ng:href="{{url}}" rel="{{rel}}"></a>')($rootScope)
<ide> expect(sortedHtml(element)).toEqual('<a ng:bind-attr="{"href":"{{url}}","rel":"{{rel}}"}"></a>');
<del> });
<del>
<del> it('should bind Text with no Bindings', function() {
<del> forEach(['checked', 'disabled', 'multiple', 'readonly', 'selected', 'src', 'href'],
<del> function(name) {
<del> compile('<div ng:' + name +'="some"></div>');
<del> expect(sortedHtml(element)).toEqual('<div ng:bind-attr="{"' + name +'":"some"}"></div>');
<add> }));
<add>
<add> it('should bind Text with no Bindings', inject(function() {
<add> var $rootScope;
<add> function newScope (){
<add> return $rootScope = angular.injector()('$rootScope');
<add> }
<add> forEach(['checked', 'disabled', 'multiple', 'readonly', 'selected'], function(name) {
<add> var element = angular.compile('<div ng:' + name + '="some"></div>')(newScope())
<add> expect(element.attr('ng:bind-attr')).toBe('{"' + name +'":"some"}');
<add> $rootScope.$digest();
<add> expect(element.attr(name)).toBe(name);
<ide> dealoc(element);
<ide> });
<del> });
<ide>
<del> it('should Parse Text With No Bindings', function() {
<add> var element = angular.compile('<div ng:src="some"></div>')(newScope())
<add> $rootScope.$digest();
<add> expect(sortedHtml(element)).toEqual('<div ng:bind-attr="{"src":"some"}" src="some"></div>');
<add> dealoc(element);
<add>
<add> var element = angular.compile('<div ng:href="some"></div>')(newScope())
<add> $rootScope.$digest();
<add> expect(sortedHtml(element)).toEqual('<div href="some" ng:bind-attr="{"href":"some"}"></div>');
<add> dealoc(element);
<add> }));
<add>
<add> it('should Parse Text With No Bindings', inject(function($rootScope) {
<ide> var parts = parseBindings("a");
<ide> assertEquals(parts.length, 1);
<ide> assertEquals(parts[0], "a");
<ide> assertTrue(!binding(parts[0]));
<del> });
<add> }));
<ide>
<del> it('should Parse Empty Text', function() {
<add> it('should Parse Empty Text', inject(function($rootScope) {
<ide> var parts = parseBindings("");
<ide> assertEquals(parts.length, 1);
<ide> assertEquals(parts[0], "");
<ide> assertTrue(!binding(parts[0]));
<del> });
<add> }));
<ide>
<del> it('should Parse Inner Binding', function() {
<add> it('should Parse Inner Binding', inject(function($rootScope) {
<ide> var parts = parseBindings("a{{b}}C");
<ide> assertEquals(parts.length, 3);
<ide> assertEquals(parts[0], "a");
<ide> describe("markups", function() {
<ide> assertEquals(binding(parts[1]), "b");
<ide> assertEquals(parts[2], "C");
<ide> assertTrue(!binding(parts[2]));
<del> });
<add> }));
<ide>
<del> it('should Parse Ending Binding', function() {
<add> it('should Parse Ending Binding', inject(function($rootScope) {
<ide> var parts = parseBindings("a{{b}}");
<ide> assertEquals(parts.length, 2);
<ide> assertEquals(parts[0], "a");
<ide> assertTrue(!binding(parts[0]));
<ide> assertEquals(parts[1], "{{b}}");
<ide> assertEquals(binding(parts[1]), "b");
<del> });
<add> }));
<ide>
<del> it('should Parse Begging Binding', function() {
<add> it('should Parse Begging Binding', inject(function($rootScope) {
<ide> var parts = parseBindings("{{b}}c");
<ide> assertEquals(parts.length, 2);
<ide> assertEquals(parts[0], "{{b}}");
<ide> assertEquals(binding(parts[0]), "b");
<ide> assertEquals(parts[1], "c");
<ide> assertTrue(!binding(parts[1]));
<del> });
<add> }));
<ide>
<del> it('should Parse Loan Binding', function() {
<add> it('should Parse Loan Binding', inject(function($rootScope) {
<ide> var parts = parseBindings("{{b}}");
<ide> assertEquals(parts.length, 1);
<ide> assertEquals(parts[0], "{{b}}");
<ide> assertEquals(binding(parts[0]), "b");
<del> });
<add> }));
<ide>
<del> it('should Parse Two Bindings', function() {
<add> it('should Parse Two Bindings', inject(function($rootScope) {
<ide> var parts = parseBindings("{{b}}{{c}}");
<ide> assertEquals(parts.length, 2);
<ide> assertEquals(parts[0], "{{b}}");
<ide> assertEquals(binding(parts[0]), "b");
<ide> assertEquals(parts[1], "{{c}}");
<ide> assertEquals(binding(parts[1]), "c");
<del> });
<add> }));
<ide>
<del> it('should Parse Two Bindings With Text In Middle', function() {
<add> it('should Parse Two Bindings With Text In Middle', inject(function($rootScope) {
<ide> var parts = parseBindings("{{b}}x{{c}}");
<ide> assertEquals(parts.length, 3);
<ide> assertEquals(parts[0], "{{b}}");
<ide> describe("markups", function() {
<ide> assertTrue(!binding(parts[1]));
<ide> assertEquals(parts[2], "{{c}}");
<ide> assertEquals(binding(parts[2]), "c");
<del> });
<add> }));
<ide>
<del> it('should Parse Multiline', function() {
<add> it('should Parse Multiline', inject(function($rootScope) {
<ide> var parts = parseBindings('"X\nY{{A\nB}}C\nD"');
<ide> assertTrue(!!binding('{{A\nB}}'));
<ide> assertEquals(parts.length, 3);
<ide> assertEquals(parts[0], '"X\nY');
<ide> assertEquals(parts[1], '{{A\nB}}');
<ide> assertEquals(parts[2], 'C\nD"');
<del> });
<add> }));
<ide>
<del> it('should Has Binding', function() {
<add> it('should Has Binding', inject(function($rootScope) {
<ide> assertTrue(hasBindings(parseBindings("{{a}}")));
<ide> assertTrue(!hasBindings(parseBindings("a")));
<ide> assertTrue(hasBindings(parseBindings("{{b}}x{{c}}")));
<del> });
<add> }));
<ide>
<ide> });
<ide>
<ide><path>test/scenario/SpecRunnerSpec.js
<ide> describe('angular.scenario.SpecRunner', function() {
<ide> };
<ide> }
<ide>
<del> beforeEach(function() {
<add> beforeEach(inject(function($rootScope) {
<ide> log = [];
<ide> $window = {};
<ide> $window.setTimeout = function(fn, timeout) {
<ide> fn();
<ide> };
<del> $root = angular.scope();
<add> $root = $rootScope;
<ide> $root.emit = function(eventName) {
<ide> log.push(eventName);
<ide> };
<ide> describe('angular.scenario.SpecRunner', function() {
<ide> $root.application = new ApplicationMock($window);
<ide> $root.$window = $window;
<ide> runner = $root.$new(angular.scenario.SpecRunner);
<del> });
<add> }));
<ide>
<ide> it('should bind futures to the spec', function() {
<ide> runner.addFuture('test future', function(done) {
<ide><path>test/scenario/dslSpec.js
<ide> describe("angular.scenario.dsl", function() {
<ide> document: _jQuery("<div></div>"),
<ide> angular: new angular.scenario.testing.MockAngular()
<ide> };
<del> $root = angular.scope();
<add> $root = angular.injector()('$rootScope');
<ide> $root.emit = function(eventName) {
<ide> eventLog.push(eventName);
<ide> };
<ide> describe("angular.scenario.dsl", function() {
<ide>
<ide> describe('location', function() {
<ide> beforeEach(function() {
<del> $window.angular.scope = function() {
<del> return {
<del> $service: function(serviceId) {
<del> if (serviceId == '$location') {
<del> return {
<del> url: function() {return '/path?search=a#hhh';},
<del> path: function() {return '/path';},
<del> search: function() {return {search: 'a'};},
<del> hash: function() {return 'hhh';}
<del> };
<del> }
<del> throw new Error('unknown service id ' + serviceId);
<add> $window.angular.injector = function() {
<add> return function(serviceId) {
<add> if (serviceId == '$location') {
<add> return {
<add> url: function() {return '/path?search=a#hhh';},
<add> path: function() {return '/path';},
<add> search: function() {return {search: 'a'};},
<add> hash: function() {return 'hhh';}
<add> };
<ide> }
<add> throw new Error('unknown service id ' + serviceId);
<ide> };
<ide> };
<ide> });
<ide><path>test/service/cookieStoreSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$cookieStore', function() {
<del> var scope, $browser, $cookieStore;
<ide>
<del> beforeEach(function() {
<del> scope = angular.scope();
<del> $cookieStore = scope.$service('$cookieStore');
<del> $browser = scope.$service('$browser');
<del> });
<ide>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<del>
<del>
<del> it('should serialize objects to json', function() {
<add> it('should serialize objects to json', inject(function($cookieStore, $browser, $rootScope) {
<ide> $cookieStore.put('objectCookie', {id: 123, name: 'blah'});
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($browser.cookies()).toEqual({'objectCookie': '{"id":123,"name":"blah"}'});
<del> });
<add> }));
<ide>
<ide>
<del> it('should deserialize json to object', function() {
<add> it('should deserialize json to object', inject(function($cookieStore, $browser) {
<ide> $browser.cookies('objectCookie', '{"id":123,"name":"blah"}');
<ide> $browser.poll();
<ide> expect($cookieStore.get('objectCookie')).toEqual({id: 123, name: 'blah'});
<del> });
<add> }));
<ide>
<ide>
<del> it('should delete objects from the store when remove is called', function() {
<add> it('should delete objects from the store when remove is called', inject(function($cookieStore, $browser, $rootScope) {
<ide> $cookieStore.put('gonner', { "I'll":"Be Back"});
<del> scope.$digest(); //force eval in test
<add> $rootScope.$digest(); //force eval in test
<ide> $browser.poll();
<ide> expect($browser.cookies()).toEqual({'gonner': '{"I\'ll":"Be Back"}'});
<ide>
<ide> $cookieStore.remove('gonner');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($browser.cookies()).toEqual({});
<del> });
<add> }));
<ide> });
<ide><path>test/service/cookiesSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$cookies', function() {
<del> var scope, $browser;
<del>
<del> beforeEach(function() {
<del> $browser = new MockBrowser();
<del> $browser.cookieHash['preexisting'] = 'oldCookie';
<del> scope = angular.scope(angular.service, {$browser: $browser});
<del> scope.$cookies = scope.$service('$cookies');
<del> });
<del>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<del>
<add> beforeEach(inject(function(service) {
<add> service('$browser', function(){
<add> return angular.extend(new MockBrowser(), {cookieHash: {preexisting:'oldCookie'}});
<add> });
<add> }));
<ide>
<add>
<ide> it('should provide access to existing cookies via object properties and keep them in sync',
<del> function() {
<del> expect(scope.$cookies).toEqual({'preexisting': 'oldCookie'});
<add> inject(function($cookies, $browser, $rootScope) {
<add> expect($cookies).toEqual({'preexisting': 'oldCookie'});
<ide>
<ide> // access internal cookie storage of the browser mock directly to simulate behavior of
<ide> // document.cookie
<ide> $browser.cookieHash['brandNew'] = 'cookie';
<ide> $browser.poll();
<ide>
<del> expect(scope.$cookies).toEqual({'preexisting': 'oldCookie', 'brandNew':'cookie'});
<add> expect($cookies).toEqual({'preexisting': 'oldCookie', 'brandNew':'cookie'});
<ide>
<ide> $browser.cookieHash['brandNew'] = 'cookie2';
<ide> $browser.poll();
<del> expect(scope.$cookies).toEqual({'preexisting': 'oldCookie', 'brandNew':'cookie2'});
<add> expect($cookies).toEqual({'preexisting': 'oldCookie', 'brandNew':'cookie2'});
<ide>
<ide> delete $browser.cookieHash['brandNew'];
<ide> $browser.poll();
<del> expect(scope.$cookies).toEqual({'preexisting': 'oldCookie'});
<del> });
<add> expect($cookies).toEqual({'preexisting': 'oldCookie'});
<add> }));
<ide>
<ide>
<del> it('should create or update a cookie when a value is assigned to a property', function() {
<del> scope.$cookies.oatmealCookie = 'nom nom';
<del> scope.$digest();
<add> it('should create or update a cookie when a value is assigned to a property',
<add> inject(function($cookies, $browser, $rootScope) {
<add> $cookies.oatmealCookie = 'nom nom';
<add> $rootScope.$digest();
<ide>
<ide> expect($browser.cookies()).
<ide> toEqual({'preexisting': 'oldCookie', 'oatmealCookie':'nom nom'});
<ide>
<del> scope.$cookies.oatmealCookie = 'gone';
<del> scope.$digest();
<add> $cookies.oatmealCookie = 'gone';
<add> $rootScope.$digest();
<ide>
<ide> expect($browser.cookies()).
<ide> toEqual({'preexisting': 'oldCookie', 'oatmealCookie': 'gone'});
<del> });
<add> }));
<ide>
<ide>
<del> it('should drop or reset any cookie that was set to a non-string value', function() {
<del> scope.$cookies.nonString = [1, 2, 3];
<del> scope.$cookies.nullVal = null;
<del> scope.$cookies.undefVal = undefined;
<del> scope.$cookies.preexisting = function() {};
<del> scope.$digest();
<add> it('should drop or reset any cookie that was set to a non-string value',
<add> inject(function($cookies, $browser, $rootScope) {
<add> $cookies.nonString = [1, 2, 3];
<add> $cookies.nullVal = null;
<add> $cookies.undefVal = undefined;
<add> $cookies.preexisting = function() {};
<add> $rootScope.$digest();
<ide> expect($browser.cookies()).toEqual({'preexisting': 'oldCookie'});
<del> expect(scope.$cookies).toEqual({'preexisting': 'oldCookie'});
<del> });
<add> expect($cookies).toEqual({'preexisting': 'oldCookie'});
<add> }));
<ide>
<ide>
<del> it('should remove a cookie when a $cookies property is deleted', function() {
<del> scope.$cookies.oatmealCookie = 'nom nom';
<del> scope.$digest();
<add> it('should remove a cookie when a $cookies property is deleted',
<add> inject(function($cookies, $browser, $rootScope) {
<add> $cookies.oatmealCookie = 'nom nom';
<add> $rootScope.$digest();
<ide> $browser.poll();
<ide> expect($browser.cookies()).
<ide> toEqual({'preexisting': 'oldCookie', 'oatmealCookie':'nom nom'});
<ide>
<del> delete scope.$cookies.oatmealCookie;
<del> scope.$digest();
<add> delete $cookies.oatmealCookie;
<add> $rootScope.$digest();
<ide>
<ide> expect($browser.cookies()).toEqual({'preexisting': 'oldCookie'});
<del> });
<add> }));
<ide>
<ide>
<del> it('should drop or reset cookies that browser refused to store', function() {
<add> it('should drop or reset cookies that browser refused to store',
<add> inject(function($cookies, $browser, $rootScope) {
<ide> var i, longVal;
<ide>
<ide> for (i=0; i<5000; i++) {
<ide> longVal += '*';
<ide> }
<ide>
<ide> //drop if no previous value
<del> scope.$cookies.longCookie = longVal;
<del> scope.$digest();
<del> expect(scope.$cookies).toEqual({'preexisting': 'oldCookie'});
<add> $cookies.longCookie = longVal;
<add> $rootScope.$digest();
<add> expect($cookies).toEqual({'preexisting': 'oldCookie'});
<ide>
<ide>
<ide> //reset if previous value existed
<del> scope.$cookies.longCookie = 'shortVal';
<del> scope.$digest();
<del> expect(scope.$cookies).toEqual({'preexisting': 'oldCookie', 'longCookie': 'shortVal'});
<del> scope.$cookies.longCookie = longVal;
<del> scope.$digest();
<del> expect(scope.$cookies).toEqual({'preexisting': 'oldCookie', 'longCookie': 'shortVal'});
<del> });
<add> $cookies.longCookie = 'shortVal';
<add> $rootScope.$digest();
<add> expect($cookies).toEqual({'preexisting': 'oldCookie', 'longCookie': 'shortVal'});
<add> $cookies.longCookie = longVal;
<add> $rootScope.$digest();
<add> expect($cookies).toEqual({'preexisting': 'oldCookie', 'longCookie': 'shortVal'});
<add> }));
<ide> });
<ide><path>test/service/deferSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$defer', function() {
<del> var scope, $browser, $defer, $exceptionHandler;
<del>
<del> beforeEach(function() {
<del> scope = angular.scope(angular.service,
<del> {'$exceptionHandler': jasmine.createSpy('$exceptionHandler')});
<del> $browser = scope.$service('$browser');
<del> $defer = scope.$service('$defer');
<del> $exceptionHandler = scope.$service('$exceptionHandler');
<del> });
<del>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<add> beforeEach(inject(function(service) {
<add> service('$exceptionHandler', function(){
<add> return jasmine.createSpy('$exceptionHandler');
<add> });
<add> }));
<ide>
<ide>
<del> it('should delegate functions to $browser.defer', function() {
<add> it('should delegate functions to $browser.defer', inject(function($defer, $browser, $exceptionHandler) {
<ide> var counter = 0;
<ide> $defer(function() { counter++; });
<ide>
<ide> describe('$defer', function() {
<ide> expect(counter).toBe(1);
<ide>
<ide> expect($exceptionHandler).not.toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<del> it('should delegate exception to the $exceptionHandler service', function() {
<add> it('should delegate exception to the $exceptionHandler service', inject(function($defer, $browser, $exceptionHandler) {
<ide> $defer(function() {throw "Test Error";});
<ide> expect($exceptionHandler).not.toHaveBeenCalled();
<ide>
<ide> $browser.defer.flush();
<ide> expect($exceptionHandler).toHaveBeenCalledWith("Test Error");
<del> });
<add> }));
<ide>
<ide>
<del> it('should call $apply after each callback is executed', function() {
<del> var applySpy = this.spyOn(scope, '$apply').andCallThrough();
<add> it('should call $apply after each callback is executed', inject(function($defer, $browser, $rootScope) {
<add> var applySpy = this.spyOn($rootScope, '$apply').andCallThrough();
<ide>
<ide> $defer(function() {});
<ide> expect(applySpy).not.toHaveBeenCalled();
<ide> describe('$defer', function() {
<ide> $defer(function() {});
<ide> $browser.defer.flush();
<ide> expect(applySpy.callCount).toBe(2);
<del> });
<add> }));
<ide>
<ide>
<del> it('should call $apply even if an exception is thrown in callback', function() {
<del> var applySpy = this.spyOn(scope, '$apply').andCallThrough();
<add> it('should call $apply even if an exception is thrown in callback', inject(function($defer, $browser, $rootScope) {
<add> var applySpy = this.spyOn($rootScope, '$apply').andCallThrough();
<ide>
<ide> $defer(function() {throw "Test Error";});
<ide> expect(applySpy).not.toHaveBeenCalled();
<ide>
<ide> $browser.defer.flush();
<ide> expect(applySpy).toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<del> it('should allow you to specify the delay time', function() {
<add> it('should allow you to specify the delay time', inject(function($defer, $browser) {
<ide> var defer = this.spyOn($browser, 'defer');
<ide> $defer(noop, 123);
<ide> expect(defer.callCount).toEqual(1);
<ide> expect(defer.mostRecentCall.args[1]).toEqual(123);
<del> });
<add> }));
<ide>
<ide>
<del> it('should return a cancelation token', function() {
<add> it('should return a cancelation token', inject(function($defer, $browser) {
<ide> var defer = this.spyOn($browser, 'defer').andReturn('xxx');
<ide> expect($defer(noop)).toEqual('xxx');
<del> });
<add> }));
<ide>
<ide>
<ide> describe('cancel', function() {
<del> it('should cancel tasks', function() {
<add> it('should cancel tasks', inject(function($defer, $browser) {
<ide> var task1 = jasmine.createSpy('task1'),
<ide> task2 = jasmine.createSpy('task2'),
<ide> task3 = jasmine.createSpy('task3'),
<ide> describe('$defer', function() {
<ide> expect(task1).not.toHaveBeenCalled();
<ide> expect(task2).toHaveBeenCalledOnce();
<ide> expect(task3).not.toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<del> it('should return true if a task was succesffuly canceled', function() {
<add> it('should return true if a task was succesffuly canceled', inject(function($defer, $browser) {
<ide> var task1 = jasmine.createSpy('task1'),
<ide> task2 = jasmine.createSpy('task2'),
<ide> token1, token2;
<ide> describe('$defer', function() {
<ide>
<ide> expect($defer.cancel(token1)).toBe(false);
<ide> expect($defer.cancel(token2)).toBe(true);
<del> });
<add> }));
<ide> });
<ide> });
<ide><path>test/service/documentSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$document', function() {
<del> var scope;
<ide>
<del> beforeEach(function() {
<del> scope = angular.scope();
<del> });
<ide>
<del>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<del>
<del>
<del> it("should inject $document", function() {
<del> expect(scope.$service('$document')).toEqual(jqLite(document));
<del> });
<add> it("should inject $document", inject(function($document) {
<add> expect($document).toEqual(jqLite(document));
<add> }));
<ide> });
<ide><path>test/service/exceptionHandlerSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$exceptionHandler', function() {
<del> var scope;
<ide>
<del> beforeEach(function() {
<del> scope = angular.scope();
<del> });
<ide>
<del>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<del>
<del>
<del> it('should log errors', function() {
<del> var scope = createScope({$exceptionHandler: $exceptionHandlerFactory},
<del> {$log: $logMock}),
<del> $log = scope.$service('$log'),
<del> $exceptionHandler = scope.$service('$exceptionHandler');
<del>
<del> $log.error.rethrow = false;
<del> $exceptionHandler('myError');
<del> expect($log.error.logs.shift()).toEqual(['myError']);
<del> });
<add> it('should log errors', inject(
<add> function(service){
<add> service('$exceptionHandler', $exceptionHandlerFactory);
<add> service('$log', valueFn($logMock));
<add> },
<add> function($log, $exceptionHandler) {
<add> $log.error.rethrow = false;
<add> $exceptionHandler('myError');
<add> expect($log.error.logs.shift()).toEqual(['myError']);
<add> }
<add> ));
<ide> });
<ide><path>test/service/formFactorySpec.js
<ide>
<ide> describe('$formFactory', function() {
<ide>
<del> var rootScope;
<del> var formFactory;
<del>
<del> beforeEach(function() {
<del> rootScope = angular.scope();
<del> formFactory = rootScope.$service('$formFactory');
<del> });
<del>
<del>
<del> it('should have global form', function() {
<del> expect(formFactory.rootForm).toBeTruthy();
<del> expect(formFactory.rootForm.$createWidget).toBeTruthy();
<del> });
<add> it('should have global form', inject(function($rootScope, $formFactory) {
<add> expect($formFactory.rootForm).toBeTruthy();
<add> expect($formFactory.rootForm.$createWidget).toBeTruthy();
<add> }));
<ide>
<ide>
<ide> describe('new form', function() {
<ide> describe('$formFactory', function() {
<ide> }
<ide> };
<ide>
<del> beforeEach(function() {
<add> beforeEach(inject(function($rootScope, $formFactory) {
<ide> log = '';
<del> scope = rootScope.$new();
<del> form = formFactory(scope);
<del> });
<add> scope = $rootScope.$new();
<add> form = $formFactory(scope);
<add> }));
<ide>
<ide> describe('$createWidget', function() {
<ide> var widget;
<ide> describe('$formFactory', function() {
<ide>
<ide>
<ide> describe('data flow', function() {
<del> it('should have status properties', function() {
<add> it('should have status properties', inject(function($rootScope, $formFactory) {
<ide> expect(widget.$error).toEqual({});
<ide> expect(widget.$valid).toBe(true);
<ide> expect(widget.$invalid).toBe(false);
<del> });
<add> }));
<ide>
<ide>
<del> it('should update view when model changes', function() {
<add> it('should update view when model changes', inject(function($rootScope, $formFactory) {
<ide> scope.text = 'abc';
<ide> scope.$digest();
<ide> expect(log).toEqual('<init>$validate();$render();');
<ide> describe('$formFactory', function() {
<ide> scope.$digest();
<ide> expect(widget.$modelValue).toEqual('xyz');
<ide>
<del> });
<add> }));
<ide>
<ide>
<del> it('should have controller prototype methods', function() {
<del> expect(widget.getFormFactory()).toEqual(formFactory);
<del> });
<add> it('should have controller prototype methods', inject(function($rootScope, $formFactory) {
<add> expect(widget.getFormFactory()).toEqual($formFactory);
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('validation', function() {
<del> it('should update state on error', function() {
<add> it('should update state on error', inject(function($rootScope, $formFactory) {
<ide> widget.$emit('$invalid', 'E');
<ide> expect(widget.$valid).toEqual(false);
<ide> expect(widget.$invalid).toEqual(true);
<ide>
<ide> widget.$emit('$valid', 'E');
<ide> expect(widget.$valid).toEqual(true);
<ide> expect(widget.$invalid).toEqual(false);
<del> });
<add> }));
<ide>
<ide>
<del> it('should have called the model setter before the validation', function() {
<add> it('should have called the model setter before the validation', inject(function($rootScope, $formFactory) {
<ide> var modelValue;
<ide> widget.$on('$validate', function() {
<ide> modelValue = scope.text;
<ide> });
<ide> widget.$emit('$viewChange', 'abc');
<ide> expect(modelValue).toEqual('abc');
<del> });
<add> }));
<ide>
<ide>
<ide> describe('form', function() {
<del> it('should invalidate form when widget is invalid', function() {
<add> it('should invalidate form when widget is invalid', inject(function($rootScope, $formFactory) {
<ide> expect(form.$error).toEqual({});
<ide> expect(form.$valid).toEqual(true);
<ide> expect(form.$invalid).toEqual(false);
<ide> describe('$formFactory', function() {
<ide> expect(form.$error).toEqual({});
<ide> expect(form.$valid).toEqual(true);
<ide> expect(form.$invalid).toEqual(false);
<del> });
<add> }));
<ide> });
<ide>
<ide> });
<ide>
<ide> describe('id assignment', function() {
<del> it('should default to name expression', function() {
<add> it('should default to name expression', inject(function($rootScope, $formFactory) {
<ide> expect(form.text).toEqual(widget);
<del> });
<add> }));
<ide>
<ide>
<del> it('should use ng:id', function() {
<add> it('should use ng:id', inject(function($rootScope, $formFactory) {
<ide> widget = form.$createWidget({
<ide> scope:scope,
<ide> model:'text',
<ide> alias:'my.id',
<ide> controller:WidgetCtrl
<ide> });
<ide> expect(form['my.id']).toEqual(widget);
<del> });
<add> }));
<ide>
<ide>
<del> it('should not override existing names', function() {
<add> it('should not override existing names', inject(function($rootScope, $formFactory) {
<ide> var widget2 = form.$createWidget({
<ide> scope:scope,
<ide> model:'text',
<ide> describe('$formFactory', function() {
<ide> });
<ide> expect(form.text).toEqual(widget);
<ide> expect(widget2).not.toEqual(widget);
<del> });
<add> }));
<ide> });
<ide>
<ide> describe('dealocation', function() {
<del> it('should dealocate', function() {
<add> it('should dealocate', inject(function($rootScope, $formFactory) {
<ide> var widget2 = form.$createWidget({
<ide> scope:scope,
<ide> model:'text',
<ide> describe('$formFactory', function() {
<ide>
<ide> widget2.$destroy();
<ide> expect(form.myId).toBeUndefined();
<del> });
<add> }));
<ide>
<ide>
<del> it('should remove invalid fields from errors, when child widget removed', function() {
<add> it('should remove invalid fields from errors, when child widget removed', inject(function($rootScope, $formFactory) {
<ide> widget.$emit('$invalid', 'MyError');
<ide>
<ide> expect(form.$error.MyError).toEqual([widget]);
<ide> describe('$formFactory', function() {
<ide>
<ide> expect(form.$error.MyError).toBeUndefined();
<ide> expect(form.$invalid).toEqual(false);
<del> });
<add> }));
<ide> });
<ide> });
<ide> });
<ide><path>test/service/locationSpec.js
<ide> describe('$location', function() {
<ide> });
<ide>
<ide>
<del> var $browser, $location, scope;
<del>
<del> function init(url, html5Mode, basePath, hashPrefix, supportHistory) {
<del> scope = angular.scope(null, {
<del> $locationConfig: {html5Mode: html5Mode, hashPrefix: hashPrefix},
<del> $sniffer: {history: supportHistory}});
<del>
<del> $browser = scope.$service('$browser');
<del> $browser.url(url);
<del> $browser.$$baseHref = basePath;
<del> $location = scope.$service('$location');
<add> function initService(html5Mode, hashPrefix, supportHistory) {
<add> return function(service){
<add> service('$locationConfig', function(){
<add> return {html5Mode: html5Mode, hashPrefix: hashPrefix};
<add> });
<add> service('$sniffer', function(){
<add> return {history: supportHistory};
<add> });
<add> };
<ide> }
<del>
<del> function dealocRootElement() {
<del> dealoc(scope.$service('$document'));
<add> function initBrowser(url, basePath) {
<add> return function($browser){
<add> $browser.url(url);
<add> $browser.$$baseHref = basePath;
<add> };
<ide> }
<ide>
<del>
<ide> describe('wiring', function() {
<ide>
<del> beforeEach(function() {
<del> init('http://new.com/a/b#!', false, '/a/b', '!', true);
<del> });
<add> beforeEach(inject(initService(false, '!', true), initBrowser('http://new.com/a/b#!', '/a/b')));
<ide>
<ide>
<del> it('should update $location when browser url changes', function() {
<add> it('should update $location when browser url changes', inject(function($browser, $location) {
<ide> spyOn($location, '$$parse').andCallThrough();
<ide> $browser.url('http://new.com/a/b#!/aaa');
<ide> $browser.poll();
<ide> expect($location.absUrl()).toBe('http://new.com/a/b#!/aaa');
<ide> expect($location.path()).toBe('/aaa');
<ide> expect($location.$$parse).toHaveBeenCalledOnce();
<del> });
<add> }));
<ide>
<ide>
<del> it('should update browser when $location changes', function() {
<add> it('should update browser when $location changes', inject(function($rootScope, $browser, $location) {
<ide> var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').andCallThrough();
<ide> $location.path('/new/path');
<ide> expect($browserUrl).not.toHaveBeenCalled();
<del> scope.$apply();
<add> $rootScope.$apply();
<ide>
<ide> expect($browserUrl).toHaveBeenCalledOnce();
<ide> expect($browser.url()).toBe('http://new.com/a/b#!/new/path');
<del> });
<add> }));
<ide>
<ide>
<del> it('should update browser only once per $apply cycle', function() {
<add> it('should update browser only once per $apply cycle', inject(function($rootScope, $browser, $location) {
<ide> var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').andCallThrough();
<ide> $location.path('/new/path');
<ide>
<del> scope.$watch(function() {
<add> $rootScope.$watch(function() {
<ide> $location.search('a=b');
<ide> });
<ide>
<del> scope.$apply();
<add> $rootScope.$apply();
<ide> expect($browserUrl).toHaveBeenCalledOnce();
<ide> expect($browser.url()).toBe('http://new.com/a/b#!/new/path?a=b');
<del> });
<add> }));
<ide>
<ide>
<del> it('should replace browser url when url was replaced at least once', function() {
<add> it('should replace browser url when url was replaced at least once',
<add> inject(function($rootScope, $location, $browser) {
<ide> var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').andCallThrough();
<ide> $location.path('/n/url').replace();
<del> scope.$apply();
<add> $rootScope.$apply();
<ide>
<ide> expect($browserUrl).toHaveBeenCalledOnce();
<ide> expect($browserUrl.mostRecentCall.args).toEqual(['http://new.com/a/b#!/n/url', true]);
<del> });
<add> }));
<ide>
<ide>
<del> it('should update the browser if changed from within a watcher', function() {
<del> scope.$watch(function() { return true; }, function() {
<add> it('should update the browser if changed from within a watcher', inject(function($rootScope, $location, $browser) {
<add> $rootScope.$watch(function() { return true; }, function() {
<ide> $location.path('/changed');
<ide> });
<ide>
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($browser.url()).toBe('http://new.com/a/b#!/changed');
<del> });
<add> }));
<ide> });
<ide>
<ide>
<ide> // html5 history is disabled
<ide> describe('disabled history', function() {
<ide>
<del> it('should use hashbang url with hash prefix', function() {
<del> init('http://domain.com/base/index.html#!/a/b', false, '/base/index.html', '!');
<del> expect($browser.url()).toBe('http://domain.com/base/index.html#!/a/b');
<del> $location.path('/new');
<del> $location.search({a: true});
<del> scope.$apply();
<del> expect($browser.url()).toBe('http://domain.com/base/index.html#!/new?a');
<del> });
<del>
<del>
<del> it('should use hashbang url without hash prefix', function() {
<del> init('http://domain.com/base/index.html#/a/b', false, '/base/index.html', '');
<del> expect($browser.url()).toBe('http://domain.com/base/index.html#/a/b');
<del> $location.path('/new');
<del> $location.search({a: true});
<del> scope.$apply();
<del> expect($browser.url()).toBe('http://domain.com/base/index.html#/new?a');
<del> });
<add> it('should use hashbang url with hash prefix', inject(
<add> initService(false, '!'),
<add> initBrowser('http://domain.com/base/index.html#!/a/b', '/base/index.html'),
<add> function($rootScope, $location, $browser) {
<add> expect($browser.url()).toBe('http://domain.com/base/index.html#!/a/b');
<add> $location.path('/new');
<add> $location.search({a: true});
<add> $rootScope.$apply();
<add> expect($browser.url()).toBe('http://domain.com/base/index.html#!/new?a');
<add> })
<add> );
<add>
<add>
<add> it('should use hashbang url without hash prefix', inject(
<add> initService(false, ''),
<add> initBrowser('http://domain.com/base/index.html#/a/b', '/base/index.html'),
<add> function($rootScope, $location, $browser) {
<add> expect($browser.url()).toBe('http://domain.com/base/index.html#/a/b');
<add> $location.path('/new');
<add> $location.search({a: true});
<add> $rootScope.$apply();
<add> expect($browser.url()).toBe('http://domain.com/base/index.html#/new?a');
<add> })
<add> );
<ide> });
<ide>
<ide>
<ide> // html5 history enabled, but not supported by browser
<ide> describe('history on old browser', function() {
<ide>
<del> afterEach(dealocRootElement);
<del>
<del> it('should use hashbang url with hash prefix', function() {
<del> init('http://domain.com/base/index.html#!!/a/b', true, '/base/index.html', '!!', false);
<del> expect($browser.url()).toBe('http://domain.com/base/index.html#!!/a/b');
<del> $location.path('/new');
<del> $location.search({a: true});
<del> scope.$apply();
<del> expect($browser.url()).toBe('http://domain.com/base/index.html#!!/new?a');
<del> });
<del>
<del>
<del> it('should redirect to hashbang url when new url given', function() {
<del> init('http://domain.com/base/new-path/index.html', true, '/base/index.html', '!');
<del> expect($browser.url()).toBe('http://domain.com/base/index.html#!/new-path/index.html');
<del> });
<add> afterEach(inject(function($document){
<add> dealoc($document);
<add> }));
<add>
<add> it('should use hashbang url with hash prefix', inject(
<add> initService(true, '!!', false),
<add> initBrowser('http://domain.com/base/index.html#!!/a/b', '/base/index.html'),
<add> function($rootScope, $location, $browser) {
<add> expect($browser.url()).toBe('http://domain.com/base/index.html#!!/a/b');
<add> $location.path('/new');
<add> $location.search({a: true});
<add> $rootScope.$apply();
<add> expect($browser.url()).toBe('http://domain.com/base/index.html#!!/new?a');
<add> })
<add> );
<add>
<add>
<add> it('should redirect to hashbang url when new url given', inject(
<add> initService(true, '!'),
<add> initBrowser('http://domain.com/base/new-path/index.html', '/base/index.html'),
<add> function($browser, $location) {
<add> expect($browser.url()).toBe('http://domain.com/base/index.html#!/new-path/index.html');
<add> })
<add> );
<ide> });
<ide>
<ide>
<ide> // html5 history enabled and supported by browser
<ide> describe('history on new browser', function() {
<ide>
<del> afterEach(dealocRootElement);
<del>
<del> it('should use new url', function() {
<del> init('http://domain.com/base/old/index.html#a', true, '/base/index.html', '', true);
<del> expect($browser.url()).toBe('http://domain.com/base/old/index.html#a');
<del> $location.path('/new');
<del> $location.search({a: true});
<del> scope.$apply();
<del> expect($browser.url()).toBe('http://domain.com/base/new?a#a');
<del> });
<del>
<del>
<del> it('should rewrite when hashbang url given', function() {
<del> init('http://domain.com/base/index.html#!/a/b', true, '/base/index.html', '!', true);
<del> expect($browser.url()).toBe('http://domain.com/base/a/b');
<del> $location.path('/new');
<del> $location.hash('abc');
<del> scope.$apply();
<del> expect($browser.url()).toBe('http://domain.com/base/new#abc');
<del> expect($location.path()).toBe('/new');
<del> });
<del>
<del>
<del> it('should rewrite when hashbang url given (without hash prefix)', function() {
<del> init('http://domain.com/base/index.html#/a/b', true, '/base/index.html', '', true);
<del> expect($browser.url()).toBe('http://domain.com/base/a/b');
<del> expect($location.path()).toBe('/a/b');
<del> });
<add> afterEach(inject(function($document){
<add> dealoc($document);
<add> }));
<add>
<add> it('should use new url', inject(
<add> initService(true, '', true),
<add> initBrowser('http://domain.com/base/old/index.html#a', '/base/index.html'),
<add> function($rootScope, $location, $browser) {
<add> expect($browser.url()).toBe('http://domain.com/base/old/index.html#a');
<add> $location.path('/new');
<add> $location.search({a: true});
<add> $rootScope.$apply();
<add> expect($browser.url()).toBe('http://domain.com/base/new?a#a');
<add> })
<add> );
<add>
<add>
<add> it('should rewrite when hashbang url given', inject(
<add> initService(true, '!', true),
<add> initBrowser('http://domain.com/base/index.html#!/a/b', '/base/index.html'),
<add> function($rootScope, $location, $browser) {
<add> expect($browser.url()).toBe('http://domain.com/base/a/b');
<add> $location.path('/new');
<add> $location.hash('abc');
<add> $rootScope.$apply();
<add> expect($browser.url()).toBe('http://domain.com/base/new#abc');
<add> expect($location.path()).toBe('/new');
<add> })
<add> );
<add>
<add>
<add> it('should rewrite when hashbang url given (without hash prefix)', inject(
<add> initService(true, '', true),
<add> initBrowser('http://domain.com/base/index.html#/a/b', '/base/index.html'),
<add> function($rootScope, $location, $browser) {
<add> expect($browser.url()).toBe('http://domain.com/base/a/b');
<add> expect($location.path()).toBe('/a/b');
<add> })
<add> );
<ide> });
<ide>
<ide>
<ide> describe('$location', function() {
<ide>
<ide> describe('link rewriting', function() {
<ide>
<del> var root, link, extLink, $browser, originalBrowser, lastEventPreventDefault;
<add> var root, link, originalBrowser, lastEventPreventDefault;
<ide>
<del> function init(linkHref, html5Mode, supportHist, attrs, content) {
<del> var jqRoot = jqLite('<div></div>');
<del> attrs = attrs ? ' ' + attrs + ' ' : '';
<del> content = content || 'link';
<del> link = jqLite('<a href="' + linkHref + '"' + attrs + '>' + content + '</a>')[0];
<del> root = jqRoot.append(link)[0];
<add> function configureService(linkHref, html5Mode, supportHist, attrs, content) {
<add> return function(service){
<add> var jqRoot = jqLite('<div></div>');
<add> attrs = attrs ? ' ' + attrs + ' ' : '';
<add> link = jqLite('<a href="' + linkHref + '"' + attrs + '>' + content + '</a>')[0];
<add> root = jqRoot.append(link)[0];
<ide>
<del> jqLite(document.body).append(jqRoot);
<add> jqLite(document.body).append(jqRoot);
<ide>
<del> var scope = angular.scope(null, {
<del> $document: jqRoot,
<del> $sniffer: {history: supportHist},
<del> $locationConfig: {html5Mode: html5Mode, hashPrefix: '!'}
<del> });
<add> service('$document', function(){ return jqRoot; });
<add> service('$sniffer', function(){ return {history: supportHist}; });
<add> service('$locationConfig', function(){ return {html5Mode: html5Mode, hashPrefix: '!'}; });
<add> };
<add> }
<ide>
<del> $browser = scope.$service('$browser');
<del> $browser.url('http://host.com/base');
<del> $browser.$$baseHref = '/base/index.html';
<del> var $location = scope.$service('$location');
<del> originalBrowser = $browser.url();
<del>
<del> // we have to prevent the default operation, as we need to test absolute links (http://...)
<del> // and navigating to these links would kill jstd
<del> jqRoot.bind('click', function(e) {
<del> lastEventPreventDefault = e.isDefaultPrevented();
<del> e.preventDefault();
<del> });
<add> function initBrowser() {
<add> return function($browser){
<add> $browser.url('http://host.com/base');
<add> $browser.$$baseHref = '/base/index.html';
<add> };
<add> }
<add>
<add> function initLocation() {
<add> return function($browser, $location, $document) {
<add> originalBrowser = $browser.url();
<add> // we have to prevent the default operation, as we need to test absolute links (http://...)
<add> // and navigating to these links would kill jstd
<add> $document.bind('click', function(e) {
<add> lastEventPreventDefault = e.isDefaultPrevented();
<add> e.preventDefault();
<add> });
<add> };
<ide> }
<ide>
<del> function expectRewriteTo(url) {
<add> function expectRewriteTo($browser, url) {
<ide> expect(lastEventPreventDefault).toBe(true);
<ide> expect($browser.url()).toBe(url);
<ide> }
<ide>
<del> function expectNoRewrite() {
<add> function expectNoRewrite($browser) {
<ide> expect(lastEventPreventDefault).toBe(false);
<ide> expect($browser.url()).toBe(originalBrowser);
<ide> }
<ide> describe('$location', function() {
<ide> });
<ide>
<ide>
<del> it('should rewrite rel link to new url when history enabled on new browser', function() {
<del> init('link?a#b', true, true);
<del> browserTrigger(link, 'click');
<del> expectRewriteTo('http://host.com/base/link?a#b');
<del> });
<del>
<del>
<del> it('should rewrite abs link to new url when history enabled on new browser', function() {
<del> init('/base/link?a#b', true, true);
<del> browserTrigger(link, 'click');
<del> expectRewriteTo('http://host.com/base/link?a#b');
<del> });
<del>
<del>
<del> it('should rewrite rel link to hashbang url when history enabled on old browser', function() {
<del> init('link?a#b', true, false);
<del> browserTrigger(link, 'click');
<del> expectRewriteTo('http://host.com/base/index.html#!/link?a#b');
<del> });
<del>
<del>
<del> it('should rewrite abs link to hashbang url when history enabled on old browser', function() {
<del> init('/base/link?a#b', true, false);
<del> browserTrigger(link, 'click');
<del> expectRewriteTo('http://host.com/base/index.html#!/link?a#b');
<del> });
<del>
<del>
<del> it('should not rewrite when history disabled', function() {
<del> init('#new', false);
<del> browserTrigger(link, 'click');
<del> expectNoRewrite();
<del> });
<del>
<del>
<del> it('should not rewrite ng:ext-link', function() {
<del> init('#new', true, true, 'ng:ext-link');
<del> browserTrigger(link, 'click');
<del> expectNoRewrite();
<del> });
<del>
<del>
<del> it('should not rewrite full url links do different domain', function() {
<del> init('http://www.dot.abc/a?b=c', true);
<del> browserTrigger(link, 'click');
<del> expectNoRewrite();
<del> });
<del>
<del>
<del> it('should not rewrite links with target="_blank"', function() {
<del> init('/a?b=c', true, true, 'target="_blank"');
<del> browserTrigger(link, 'click');
<del> expectNoRewrite();
<del> });
<del>
<del>
<del> it('should not rewrite links with target specified', function() {
<del> init('/a?b=c', true, true, 'target="some-frame"');
<del> browserTrigger(link, 'click');
<del> expectNoRewrite();
<del> });
<del>
<del>
<del> it('should rewrite full url links to same domain and base path', function() {
<del> init('http://host.com/base/new', true);
<del> browserTrigger(link, 'click');
<del> expectRewriteTo('http://host.com/base/index.html#!/new');
<del> });
<del>
<del>
<del> it('should rewrite when clicked span inside link', function() {
<del> init('some/link', true, true, '', '<span>link</span>');
<del> var span = jqLite(link).find('span');
<del>
<del> browserTrigger(span, 'click');
<del> expectRewriteTo('http://host.com/base/some/link');
<del> });
<add> it('should rewrite rel link to new url when history enabled on new browser', inject(
<add> configureService('link?a#b', true, true),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click');
<add> expectRewriteTo($browser, 'http://host.com/base/link?a#b');
<add> })
<add> );
<add>
<add>
<add> it('should rewrite abs link to new url when history enabled on new browser', inject(
<add> configureService('/base/link?a#b', true, true),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click');
<add> expectRewriteTo($browser, 'http://host.com/base/link?a#b');
<add> })
<add> );
<add>
<add>
<add> it('should rewrite rel link to hashbang url when history enabled on old browser', inject(
<add> configureService('link?a#b', true, false),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click');
<add> expectRewriteTo($browser, 'http://host.com/base/index.html#!/link?a#b');
<add> })
<add> );
<add>
<add>
<add> it('should rewrite abs link to hashbang url when history enabled on old browser', inject(
<add> configureService('/base/link?a#b', true, false),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click');
<add> expectRewriteTo($browser, 'http://host.com/base/index.html#!/link?a#b');
<add> })
<add> );
<add>
<add>
<add> it('should not rewrite when history disabled', inject(
<add> configureService('#new', false),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click');
<add> expectNoRewrite($browser);
<add> })
<add> );
<add>
<add>
<add> it('should not rewrite ng:ext-link', inject(
<add> configureService('#new', true, true, 'ng:ext-link'),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click');
<add> expectNoRewrite($browser);
<add> })
<add> );
<add>
<add>
<add> it('should not rewrite full url links do different domain', inject(
<add> configureService('http://www.dot.abc/a?b=c', true),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click');
<add> expectNoRewrite($browser);
<add> })
<add> );
<add>
<add>
<add> it('should not rewrite links with target="_blank"', inject(
<add> configureService('/a?b=c', true, true, 'target="_blank"'),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click');
<add> expectNoRewrite($browser);
<add> })
<add> );
<add>
<add>
<add> it('should not rewrite links with target specified', inject(
<add> configureService('/a?b=c', true, true, 'target="some-frame"'),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click');
<add> expectNoRewrite($browser);
<add> })
<add> );
<add>
<add>
<add> it('should rewrite full url links to same domain and base path', inject(
<add> configureService('http://host.com/base/new', true),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click');
<add> expectRewriteTo($browser, 'http://host.com/base/index.html#!/new');
<add> })
<add> );
<add>
<add>
<add> it('should rewrite when clicked span inside link', inject(
<add> configureService('some/link', true, true, '', '<span>link</span>'),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> var span = jqLite(link).find('span');
<add>
<add> browserTrigger(span, 'click');
<add> expectRewriteTo($browser, 'http://host.com/base/some/link');
<add> })
<add> );
<ide>
<ide>
<ide> // don't run next tests on IE<9, as browserTrigger does not simulate pressed keys
<ide> if (!(msie < 9)) {
<ide>
<del> it('should not rewrite when clicked with ctrl pressed', function() {
<del> init('/a?b=c', true, true);
<del> browserTrigger(link, 'click', ['ctrl']);
<del> expectNoRewrite();
<del> });
<del>
<del>
<del> it('should not rewrite when clicked with meta pressed', function() {
<del> init('/a?b=c', true, true);
<del> browserTrigger(link, 'click', ['meta']);
<del> expectNoRewrite();
<del> });
<add> it('should not rewrite when clicked with ctrl pressed', inject(
<add> configureService('/a?b=c', true, true),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click', ['ctrl']);
<add> expectNoRewrite($browser);
<add> })
<add> );
<add>
<add>
<add> it('should not rewrite when clicked with meta pressed', inject(
<add> configureService('/a?b=c', true, true),
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click', ['meta']);
<add> expectNoRewrite($browser);
<add> })
<add> );
<ide> }
<ide> });
<ide> });
<ide><path>test/service/logSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$log', function() {
<del> var scope;
<del>
<del> beforeEach(function() {
<del> scope = angular.scope();
<del> });
<del>
<del>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<del>
<del>
<del> it('should use console if present', function() {
<del> var logger = "";
<del> function log() { logger+= 'log;'; }
<del> function warn() { logger+= 'warn;'; }
<del> function info() { logger+= 'info;'; }
<del> function error() { logger+= 'error;'; }
<del> var scope = createScope({$log: $logFactory},
<del> {$exceptionHandler: rethrow,
<del> $window: {console: {log: log,
<del> warn: warn,
<del> info: info,
<del> error: error}}}),
<del> $log = scope.$service('$log');
<del>
<del> $log.log();
<del> $log.warn();
<del> $log.info();
<del> $log.error();
<del> expect(logger).toEqual('log;warn;info;error;');
<del> });
<del>
<del>
<del> it('should use console.log() if other not present', function() {
<del> var logger = "";
<del> function log() { logger+= 'log;'; }
<del> var scope = createScope({$log: $logFactory},
<del> {$window: {console:{log:log}},
<del> $exceptionHandler: rethrow});
<del> var $log = scope.$service('$log');
<del> $log.log();
<del> $log.warn();
<del> $log.info();
<del> $log.error();
<del> expect(logger).toEqual('log;log;log;log;');
<del> });
<del>
<del>
<del> it('should use noop if no console', function() {
<del> var scope = createScope({$log: $logFactory},
<del> {$window: {},
<del> $exceptionHandler: rethrow}),
<del> $log = scope.$service('$log');
<del> $log.log();
<del> $log.warn();
<del> $log.info();
<del> $log.error();
<del> });
<add> var $window;
<add> var logger;
<add>
<add> function log() { logger+= 'log;'; }
<add> function warn() { logger+= 'warn;'; }
<add> function info() { logger+= 'info;'; }
<add> function error() { logger+= 'error;'; }
<add>
<add> beforeEach(inject(function(service){
<add> $window = {};
<add> logger = '';
<add> service('$log', $logFactory);
<add> service('$exceptionHandler', valueFn(rethrow));
<add> service('$window', valueFn($window));
<add> }));
<add>
<add> it('should use console if present', inject(
<add> function(){
<add> $window.console = {log: log,
<add> warn: warn,
<add> info: info,
<add> error: error};
<add> },
<add> function($log) {
<add> $log.log();
<add> $log.warn();
<add> $log.info();
<add> $log.error();
<add> expect(logger).toEqual('log;warn;info;error;');
<add> }
<add> ));
<add>
<add>
<add> it('should use console.log() if other not present', inject(
<add> function(){
<add> $window.console = {log: log};
<add> },
<add> function($log) {
<add> $log.log();
<add> $log.warn();
<add> $log.info();
<add> $log.error();
<add> expect(logger).toEqual('log;log;log;log;');
<add> }
<add> ));
<add>
<add>
<add> it('should use noop if no console', inject(
<add> function($log) {
<add> $log.log();
<add> $log.warn();
<add> $log.info();
<add> $log.error();
<add> }
<add> ));
<ide>
<ide>
<ide> describe('$log.error', function() {
<ide><path>test/service/routeParamsSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$routeParams', function() {
<del> it('should publish the params into a service', function() {
<del> var scope = angular.scope(),
<del> $location = scope.$service('$location'),
<del> $route = scope.$service('$route'),
<del> $routeParams = scope.$service('$routeParams');
<del>
<add> it('should publish the params into a service', inject(function($rootScope, $route, $location, $routeParams) {
<ide> $route.when('/foo');
<ide> $route.when('/bar/:barId');
<ide>
<ide> $location.path('/foo').search('a=b');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($routeParams).toEqual({a:'b'});
<ide>
<ide> $location.path('/bar/123').search('x=abc');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($routeParams).toEqual({barId:'123', x:'abc'});
<del> });
<del>
<del>
<del> it('should preserve object identity during route reloads', function() {
<del> var scope = angular.scope(),
<del> $location = scope.$service('$location'),
<del> $route = scope.$service('$route'),
<del> $routeParams = scope.$service('$routeParams'),
<del> firstRouteParams = $routeParams;
<del>
<del> $route.when('/foo');
<del> $route.when('/bar/:barId');
<del>
<del> $location.path('/foo').search('a=b');
<del> scope.$digest();
<del> expect(scope.$service('$routeParams')).toBe(firstRouteParams);
<del>
<del> $location.path('/bar/123').search('x=abc');
<del> scope.$digest();
<del> expect(scope.$service('$routeParams')).toBe(firstRouteParams);
<del> });
<add> }));
<ide> });
<ide><path>test/service/routeSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$route', function() {
<del> var scope, $route, $location;
<del>
<del> beforeEach(function() {
<del> scope = angular.scope();
<del> $location = scope.$service('$location');
<del> $route = scope.$service('$route');
<del> });
<del>
<del>
<del> it('should route and fire change event', function() {
<add> it('should route and fire change event', inject(function($route, $location, $rootScope) {
<ide> var log = '',
<ide> lastRoute,
<ide> nextRoute;
<ide> describe('$route', function() {
<ide>
<ide> $route.when('/Book/:book/Chapter/:chapter', {controller: BookChapter, template: 'Chapter.html'});
<ide> $route.when('/Blank');
<del> scope.$on('$beforeRouteChange', function(event, next, current) {
<add> $rootScope.$on('$beforeRouteChange', function(event, next, current) {
<ide> log += 'before();';
<ide> expect(current).toBe($route.current);
<ide> lastRoute = current;
<ide> nextRoute = next;
<ide> });
<del> scope.$on('$afterRouteChange', function(event, current, last) {
<add> $rootScope.$on('$afterRouteChange', function(event, current, last) {
<ide> log += 'after();';
<ide> expect(current).toBe($route.current);
<ide> expect(lastRoute).toBe(last);
<ide> expect(nextRoute).toBe(current);
<ide> });
<ide>
<ide> $location.path('/Book/Moby/Chapter/Intro').search('p=123');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(log).toEqual('before();<init>;after();');
<ide> expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', p:'123'});
<ide> var lastId = $route.current.scope.$id;
<ide>
<ide> log = '';
<ide> $location.path('/Blank').search('ignore');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(log).toEqual('before();after();');
<ide> expect($route.current.params).toEqual({ignore:true});
<ide> expect($route.current.scope.$id).not.toEqual(lastId);
<ide>
<ide> log = '';
<ide> $location.path('/NONE');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(log).toEqual('before();after();');
<ide> expect($route.current).toEqual(null);
<ide>
<ide> $route.when('/NONE', {template:'instant update'});
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($route.current.template).toEqual('instant update');
<del> });
<add> }));
<ide>
<ide>
<del> it('should match a route that contains special chars in the path', function() {
<add> it('should match a route that contains special chars in the path', inject(function($route, $location, $rootScope) {
<ide> $route.when('/$test.23/foo(bar)/:baz', {template: 'test.html'});
<ide>
<ide> $location.path('/test');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($route.current).toBeUndefined();
<ide>
<ide> $location.path('/$testX23/foo(bar)/222');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($route.current).toBeUndefined();
<ide>
<ide> $location.path('/$test.23/foo(bar)/222');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($route.current).toBeDefined();
<ide>
<ide> $location.path('/$test.23/foo\\(bar)/222');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($route.current).toBeUndefined();
<del> });
<add> }));
<ide>
<ide>
<del> it('should change route even when only search param changes', function() {
<add> it('should change route even when only search param changes', inject(function($route, $location, $rootScope) {
<ide> var callback = jasmine.createSpy('onRouteChange');
<ide>
<ide> $route.when('/test', {template: 'test.html'});
<del> scope.$on('$beforeRouteChange', callback);
<add> $rootScope.$on('$beforeRouteChange', callback);
<ide> $location.path('/test');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> callback.reset();
<ide>
<ide> $location.search({any: true});
<del> scope.$digest();
<add> $rootScope.$digest();
<ide>
<ide> expect(callback).toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<del> it('should allow routes to be defined with just templates without controllers', function() {
<add> it('should allow routes to be defined with just templates without controllers',
<add> inject(function($route, $location, $rootScope) {
<ide> var onChangeSpy = jasmine.createSpy('onChange');
<ide>
<ide> $route.when('/foo', {template: 'foo.html'});
<del> scope.$on('$beforeRouteChange', onChangeSpy);
<add> $rootScope.$on('$beforeRouteChange', onChangeSpy);
<ide> expect($route.current).toBeUndefined();
<ide> expect(onChangeSpy).not.toHaveBeenCalled();
<ide>
<ide> $location.path('/foo');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide>
<ide> expect($route.current.template).toEqual('foo.html');
<ide> expect($route.current.controller).toBeUndefined();
<ide> expect(onChangeSpy).toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<del> it('should handle unknown routes with "otherwise" route definition', function() {
<add> it('should handle unknown routes with "otherwise" route definition', inject(function($route, $location, $rootScope) {
<ide> var onChangeSpy = jasmine.createSpy('onChange');
<ide>
<ide> function NotFoundCtrl() {this.notFoundProp = 'not found!';}
<ide>
<ide> $route.when('/foo', {template: 'foo.html'});
<ide> $route.otherwise({template: '404.html', controller: NotFoundCtrl});
<del> scope.$on('$beforeRouteChange', onChangeSpy);
<add> $rootScope.$on('$beforeRouteChange', onChangeSpy);
<ide> expect($route.current).toBeUndefined();
<ide> expect(onChangeSpy).not.toHaveBeenCalled();
<ide>
<ide> $location.path('/unknownRoute');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide>
<ide> expect($route.current.template).toBe('404.html');
<ide> expect($route.current.controller).toBe(NotFoundCtrl);
<ide> describe('$route', function() {
<ide>
<ide> onChangeSpy.reset();
<ide> $location.path('/foo');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide>
<ide> expect($route.current.template).toEqual('foo.html');
<ide> expect($route.current.controller).toBeUndefined();
<ide> expect($route.current.scope.notFoundProp).toBeUndefined();
<ide> expect(onChangeSpy).toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<del> it('should $destroy old routes', function() {
<add> it('should $destroy old routes', inject(function($route, $location, $rootScope) {
<ide> $route.when('/foo', {template: 'foo.html', controller: function() {this.name = 'FOO';}});
<ide> $route.when('/bar', {template: 'bar.html', controller: function() {this.name = 'BAR';}});
<ide> $route.when('/baz', {template: 'baz.html'});
<ide>
<del> expect(scope.$childHead).toEqual(null);
<add> expect($rootScope.$childHead).toEqual(null);
<ide>
<ide> $location.path('/foo');
<del> scope.$digest();
<del> expect(scope.$$childHead.$id).toBeTruthy();
<del> expect(scope.$$childHead.$id).toEqual(scope.$$childTail.$id);
<add> $rootScope.$digest();
<add> expect($rootScope.$$childHead.$id).toBeTruthy();
<add> expect($rootScope.$$childHead.$id).toEqual($rootScope.$$childTail.$id);
<ide>
<ide> $location.path('/bar');
<del> scope.$digest();
<del> expect(scope.$$childHead.$id).toBeTruthy();
<del> expect(scope.$$childHead.$id).toEqual(scope.$$childTail.$id);
<add> $rootScope.$digest();
<add> expect($rootScope.$$childHead.$id).toBeTruthy();
<add> expect($rootScope.$$childHead.$id).toEqual($rootScope.$$childTail.$id);
<ide>
<ide> $location.path('/baz');
<del> scope.$digest();
<del> expect(scope.$$childHead.$id).toBeTruthy();
<del> expect(scope.$$childHead.$id).toEqual(scope.$$childTail.$id);
<add> $rootScope.$digest();
<add> expect($rootScope.$$childHead.$id).toBeTruthy();
<add> expect($rootScope.$$childHead.$id).toEqual($rootScope.$$childTail.$id);
<ide>
<ide> $location.path('/');
<del> scope.$digest();
<del> expect(scope.$$childHead).toEqual(null);
<del> expect(scope.$$childTail).toEqual(null);
<del> });
<add> $rootScope.$digest();
<add> expect($rootScope.$$childHead).toEqual(null);
<add> expect($rootScope.$$childTail).toEqual(null);
<add> }));
<ide>
<ide>
<del> it('should infer arguments in injection', function() {
<add> it('should infer arguments in injection', inject(function($route, $location, $rootScope) {
<ide> $route.when('/test', {controller: function($route){ this.$route = $route; }});
<ide> $location.path('/test');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($route.current.scope.$route).toBe($route);
<del> });
<add> }));
<ide>
<ide>
<ide> describe('redirection', function() {
<del> it('should support redirection via redirectTo property by updating $location', function() {
<add> it('should support redirection via redirectTo property by updating $location',
<add> inject(function($route, $location, $rootScope) {
<ide> var onChangeSpy = jasmine.createSpy('onChange');
<ide>
<ide> $route.when('/', {redirectTo: '/foo'});
<ide> $route.when('/foo', {template: 'foo.html'});
<ide> $route.when('/bar', {template: 'bar.html'});
<ide> $route.when('/baz', {redirectTo: '/bar'});
<ide> $route.otherwise({template: '404.html'});
<del> scope.$on('$beforeRouteChange', onChangeSpy);
<add> $rootScope.$on('$beforeRouteChange', onChangeSpy);
<ide> expect($route.current).toBeUndefined();
<ide> expect(onChangeSpy).not.toHaveBeenCalled();
<ide>
<ide> $location.path('/');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($location.path()).toBe('/foo');
<ide> expect($route.current.template).toBe('foo.html');
<ide> expect(onChangeSpy.callCount).toBe(2);
<ide>
<ide> onChangeSpy.reset();
<ide> $location.path('/baz');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($location.path()).toBe('/bar');
<ide> expect($route.current.template).toBe('bar.html');
<ide> expect(onChangeSpy.callCount).toBe(2);
<del> });
<add> }));
<ide>
<ide>
<del> it('should interpolate route vars in the redirected path from original path', function() {
<add> it('should interpolate route vars in the redirected path from original path',
<add> inject(function($route, $location, $rootScope) {
<ide> $route.when('/foo/:id/foo/:subid/:extraId', {redirectTo: '/bar/:id/:subid/23'});
<ide> $route.when('/bar/:id/:subid/:subsubid', {template: 'bar.html'});
<ide>
<ide> $location.path('/foo/id1/foo/subid3/gah');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide>
<ide> expect($location.path()).toEqual('/bar/id1/subid3/23');
<ide> expect($location.search()).toEqual({extraId: 'gah'});
<ide> expect($route.current.template).toEqual('bar.html');
<del> });
<add> }));
<ide>
<ide>
<del> it('should interpolate route vars in the redirected path from original search', function() {
<add> it('should interpolate route vars in the redirected path from original search',
<add> inject(function($route, $location, $rootScope) {
<ide> $route.when('/bar/:id/:subid/:subsubid', {template: 'bar.html'});
<ide> $route.when('/foo/:id/:extra', {redirectTo: '/bar/:id/:subid/99'});
<ide>
<ide> $location.path('/foo/id3/eId').search('subid=sid1&appended=true');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide>
<ide> expect($location.path()).toEqual('/bar/id3/sid1/99');
<ide> expect($location.search()).toEqual({appended: 'true', extra: 'eId'});
<ide> expect($route.current.template).toEqual('bar.html');
<del> });
<add> }));
<ide>
<ide>
<del> it('should allow custom redirectTo function to be used', function() {
<add> it('should allow custom redirectTo function to be used', inject(function($route, $location, $rootScope) {
<ide> $route.when('/bar/:id/:subid/:subsubid', {template: 'bar.html'});
<ide> $route.when('/foo/:id', {redirectTo: customRedirectFn});
<ide>
<ide> $location.path('/foo/id3').search('subid=sid1&appended=true');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide>
<ide> expect($location.path()).toEqual('/custom');
<ide>
<ide> describe('$route', function() {
<ide> expect(search).toEqual($location.search());
<ide> return '/custom';
<ide> }
<del> });
<add> }));
<ide>
<ide>
<del> it('should replace the url when redirecting', function() {
<add> it('should replace the url when redirecting', inject(function($route, $location, $rootScope) {
<ide> $route.when('/bar/:id', {template: 'bar.html'});
<ide> $route.when('/foo/:id/:extra', {redirectTo: '/bar/:id'});
<ide>
<ide> var replace;
<del> scope.$watch(function() {
<add> $rootScope.$watch(function() {
<ide> if (isUndefined(replace)) replace = $location.$$replace;
<ide> });
<ide>
<ide> $location.path('/foo/id3/eId');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide>
<ide> expect($location.path()).toEqual('/bar/id3');
<ide> expect(replace).toBe(true);
<del> });
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('reloadOnSearch', function() {
<del> it('should reload a route when reloadOnSearch is enabled and .search() changes', function() {
<del> var $routeParams = scope.$service('$routeParams'),
<add> it('should reload a route when reloadOnSearch is enabled and .search() changes',
<add> inject(function($route, $location, $rootScope) {
<add> var $routeParams = $rootScope.$service('$routeParams'),
<ide> reloaded = jasmine.createSpy('route reload');
<ide>
<ide> $route.when('/foo', {controller: FooCtrl});
<del> scope.$on('$beforeRouteChange', reloaded);
<add> $rootScope.$on('$beforeRouteChange', reloaded);
<ide>
<ide> function FooCtrl() {
<ide> reloaded();
<ide> }
<ide>
<ide> $location.path('/foo');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(reloaded).toHaveBeenCalled();
<ide> expect($routeParams).toEqual({});
<ide> reloaded.reset();
<ide>
<ide> // trigger reload
<ide> $location.search({foo: 'bar'});
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(reloaded).toHaveBeenCalled();
<ide> expect($routeParams).toEqual({foo:'bar'});
<del> });
<add> }));
<ide>
<ide>
<ide> it('should not reload a route when reloadOnSearch is disabled and only .search() changes',
<del> function() {
<add> inject(function($route, $location, $rootScope) {
<ide> var reloaded = jasmine.createSpy('route reload'),
<ide> routeUpdateEvent = jasmine.createSpy('route reload');
<ide>
<ide> $route.when('/foo', {controller: FooCtrl, reloadOnSearch: false});
<del> scope.$on('$beforeRouteChange', reloaded);
<add> $rootScope.$on('$beforeRouteChange', reloaded);
<ide>
<ide> function FooCtrl() {
<ide> reloaded();
<ide> describe('$route', function() {
<ide> expect(reloaded).not.toHaveBeenCalled();
<ide>
<ide> $location.path('/foo');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(reloaded).toHaveBeenCalled();
<ide> expect(routeUpdateEvent).not.toHaveBeenCalled();
<ide> reloaded.reset();
<ide>
<ide> // don't trigger reload
<ide> $location.search({foo: 'bar'});
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(reloaded).not.toHaveBeenCalled();
<ide> expect(routeUpdateEvent).toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<del> it('should reload reloadOnSearch route when url differs only in route path param', function() {
<add> it('should reload reloadOnSearch route when url differs only in route path param',
<add> inject(function($route, $location, $rootScope) {
<ide> var reloaded = jasmine.createSpy('routeReload'),
<ide> onRouteChange = jasmine.createSpy('onRouteChange');
<ide>
<ide> $route.when('/foo/:fooId', {controller: FooCtrl, reloadOnSearch: false});
<del> scope.$on('$beforeRouteChange', onRouteChange);
<add> $rootScope.$on('$beforeRouteChange', onRouteChange);
<ide>
<ide> function FooCtrl() {
<ide> reloaded();
<ide> describe('$route', function() {
<ide> expect(onRouteChange).not.toHaveBeenCalled();
<ide>
<ide> $location.path('/foo/aaa');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(reloaded).toHaveBeenCalled();
<ide> expect(onRouteChange).toHaveBeenCalled();
<ide> reloaded.reset();
<ide> onRouteChange.reset();
<ide>
<ide> $location.path('/foo/bbb');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(reloaded).toHaveBeenCalled();
<ide> expect(onRouteChange).toHaveBeenCalled();
<ide> reloaded.reset();
<ide> onRouteChange.reset();
<ide>
<ide> $location.search({foo: 'bar'});
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(reloaded).not.toHaveBeenCalled();
<ide> expect(onRouteChange).not.toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<del> it('should update params when reloadOnSearch is disabled and .search() changes', function() {
<add> it('should update params when reloadOnSearch is disabled and .search() changes',
<add> inject(function($route, $location, $rootScope) {
<ide> var routeParams = jasmine.createSpy('routeParams');
<ide>
<ide> $route.when('/foo', {controller: FooCtrl});
<ide> describe('$route', function() {
<ide> expect(routeParams).not.toHaveBeenCalled();
<ide>
<ide> $location.path('/foo');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(routeParams).toHaveBeenCalledWith({});
<ide> routeParams.reset();
<ide>
<ide> // trigger reload
<ide> $location.search({foo: 'bar'});
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(routeParams).toHaveBeenCalledWith({foo: 'bar'});
<ide> routeParams.reset();
<ide>
<ide> $location.path('/bar/123').search({});
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(routeParams).toHaveBeenCalledWith({barId: '123'});
<ide> routeParams.reset();
<ide>
<ide> // don't trigger reload
<ide> $location.search({foo: 'bar'});
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect(routeParams).toHaveBeenCalledWith({barId: '123', foo: 'bar'});
<del> });
<add> }));
<ide>
<ide>
<ide> describe('reload', function() {
<ide>
<del> it('should reload even if reloadOnSearch is false', function() {
<del> var $routeParams = scope.$service('$routeParams'),
<add> it('should reload even if reloadOnSearch is false', inject(function($route, $location, $rootScope) {
<add> var $routeParams = $rootScope.$service('$routeParams'),
<ide> count = 0;
<ide>
<ide> $route.when('/bar/:barId', {controller: FooCtrl, reloadOnSearch: false});
<ide>
<ide> function FooCtrl() { count ++; }
<ide>
<ide> $location.path('/bar/123');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($routeParams).toEqual({barId:'123'});
<ide> expect(count).toEqual(1);
<ide>
<ide> $location.path('/bar/123').search('a=b');
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($routeParams).toEqual({barId:'123', a:'b'});
<ide> expect(count).toEqual(1);
<ide>
<ide> $route.reload();
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> expect($routeParams).toEqual({barId:'123', a:'b'});
<ide> expect(count).toEqual(2);
<del> });
<add> }));
<ide> });
<ide> });
<ide> });
<ide><path>test/service/scopeSpec.js
<ide> 'use strict';
<ide>
<ide> describe('Scope', function() {
<del> var root = null, mockHandler = null;
<ide>
<del> beforeEach(function() {
<del> root = createScope(angular.service, {
<del> '$exceptionHandler': $exceptionHandlerMockFactory()
<del> });
<del> mockHandler = root.$service('$exceptionHandler');
<del> });
<add> beforeEach(inject(function(service) {
<add> service('$exceptionHandler', $exceptionHandlerMockFactory);
<add> }));
<ide>
<ide>
<ide> describe('$root', function() {
<del> it('should point to itself', function() {
<del> expect(root.$root).toEqual(root);
<del> expect(root.hasOwnProperty('$root')).toBeTruthy();
<del> });
<add> it('should point to itself', inject(function($rootScope) {
<add> expect($rootScope.$root).toEqual($rootScope);
<add> expect($rootScope.hasOwnProperty('$root')).toBeTruthy();
<add> }));
<ide>
<ide>
<del> it('should not have $root on children, but should inherit', function() {
<del> var child = root.$new();
<del> expect(child.$root).toEqual(root);
<add> it('should not have $root on children, but should inherit', inject(function($rootScope) {
<add> var child = $rootScope.$new();
<add> expect(child.$root).toEqual($rootScope);
<ide> expect(child.hasOwnProperty('$root')).toBeFalsy();
<del> });
<add> }));
<ide>
<ide> });
<ide>
<ide>
<ide> describe('$parent', function() {
<del> it('should point to itself in root', function() {
<del> expect(root.$root).toEqual(root);
<del> });
<add> it('should point to itself in root', inject(function($rootScope) {
<add> expect($rootScope.$root).toEqual($rootScope);
<add> }));
<ide>
<ide>
<del> it('should point to parent', function() {
<del> var child = root.$new();
<del> expect(root.$parent).toEqual(null);
<del> expect(child.$parent).toEqual(root);
<add> it('should point to parent', inject(function($rootScope) {
<add> var child = $rootScope.$new();
<add> expect($rootScope.$parent).toEqual(null);
<add> expect(child.$parent).toEqual($rootScope);
<ide> expect(child.$new().$parent).toEqual(child);
<del> });
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('$id', function() {
<del> it('should have a unique id', function() {
<del> expect(root.$id < root.$new().$id).toBeTruthy();
<del> });
<add> it('should have a unique id', inject(function($rootScope) {
<add> expect($rootScope.$id < $rootScope.$new().$id).toBeTruthy();
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('this', function() {
<del> it('should have a \'this\'', function() {
<del> expect(root['this']).toEqual(root);
<del> });
<add> it('should have a \'this\'', inject(function($rootScope) {
<add> expect($rootScope['this']).toEqual($rootScope);
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('$new()', function() {
<del> it('should create a child scope', function() {
<del> var child = root.$new();
<del> root.a = 123;
<add> it('should create a child scope', inject(function($rootScope) {
<add> var child = $rootScope.$new();
<add> $rootScope.a = 123;
<ide> expect(child.a).toEqual(123);
<del> });
<add> }));
<ide>
<ide>
<del> it('should instantiate controller and bind functions', function() {
<add> it('should instantiate controller and bind functions', inject(function($rootScope) {
<ide> function Cntl($browser, name){
<ide> this.$browser = $browser;
<ide> this.callCount = 0;
<ide> describe('Scope', function() {
<ide> }
<ide> };
<ide>
<del> var cntl = root.$new(Cntl, ['misko']);
<add> var cntl = $rootScope.$new(Cntl, ['misko']);
<ide>
<del> expect(root.$browser).toBeUndefined();
<del> expect(root.myFn).toBeUndefined();
<add> expect($rootScope.$browser).toBeUndefined();
<add> expect($rootScope.myFn).toBeUndefined();
<ide>
<ide> expect(cntl.$browser).toBeDefined();
<ide> expect(cntl.name).toEqual('misko');
<ide>
<ide> cntl.myFn();
<ide> cntl.$new().myFn();
<ide> expect(cntl.callCount).toEqual(2);
<del> });
<del> });
<del>
<del>
<del> describe('$service', function() {
<del> it('should have it on root', function() {
<del> expect(root.hasOwnProperty('$service')).toBeTruthy();
<del> });
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('$watch/$digest', function() {
<del> it('should watch and fire on simple property change', function() {
<add> it('should watch and fire on simple property change', inject(function($rootScope) {
<ide> var spy = jasmine.createSpy();
<del> root.$watch('name', spy);
<del> root.$digest();
<add> $rootScope.$watch('name', spy);
<add> $rootScope.$digest();
<ide> spy.reset();
<ide>
<ide> expect(spy).not.wasCalled();
<del> root.$digest();
<add> $rootScope.$digest();
<ide> expect(spy).not.wasCalled();
<del> root.name = 'misko';
<del> root.$digest();
<del> expect(spy).wasCalledWith(root, 'misko', undefined);
<del> });
<add> $rootScope.name = 'misko';
<add> $rootScope.$digest();
<add> expect(spy).wasCalledWith($rootScope, 'misko', undefined);
<add> }));
<ide>
<ide>
<del> it('should watch and fire on expression change', function() {
<add> it('should watch and fire on expression change', inject(function($rootScope) {
<ide> var spy = jasmine.createSpy();
<del> root.$watch('name.first', spy);
<del> root.$digest();
<add> $rootScope.$watch('name.first', spy);
<add> $rootScope.$digest();
<ide> spy.reset();
<ide>
<del> root.name = {};
<add> $rootScope.name = {};
<ide> expect(spy).not.wasCalled();
<del> root.$digest();
<add> $rootScope.$digest();
<ide> expect(spy).not.wasCalled();
<del> root.name.first = 'misko';
<del> root.$digest();
<add> $rootScope.name.first = 'misko';
<add> $rootScope.$digest();
<ide> expect(spy).wasCalled();
<del> });
<add> }));
<ide>
<del> it('should delegate exceptions', function() {
<del> root.$watch('a', function() {throw new Error('abc');});
<del> root.a = 1;
<del> root.$digest();
<del> expect(mockHandler.errors[0].message).toEqual('abc');
<add> it('should delegate exceptions', inject(function($rootScope, $exceptionHandler) {
<add> $rootScope.$watch('a', function() {throw new Error('abc');});
<add> $rootScope.a = 1;
<add> $rootScope.$digest();
<add> expect($exceptionHandler.errors[0].message).toEqual('abc');
<ide> $logMock.error.logs.length = 0;
<del> });
<add> }));
<ide>
<ide>
<del> it('should fire watches in order of addition', function() {
<add> it('should fire watches in order of addition', inject(function($rootScope) {
<ide> // this is not an external guarantee, just our own sanity
<ide> var log = '';
<del> root.$watch('a', function() { log += 'a'; });
<del> root.$watch('b', function() { log += 'b'; });
<del> root.$watch('c', function() { log += 'c'; });
<del> root.a = root.b = root.c = 1;
<del> root.$digest();
<add> $rootScope.$watch('a', function() { log += 'a'; });
<add> $rootScope.$watch('b', function() { log += 'b'; });
<add> $rootScope.$watch('c', function() { log += 'c'; });
<add> $rootScope.a = $rootScope.b = $rootScope.c = 1;
<add> $rootScope.$digest();
<ide> expect(log).toEqual('abc');
<del> });
<add> }));
<ide>
<ide>
<del> it('should call child $watchers in addition order', function() {
<add> it('should call child $watchers in addition order', inject(function($rootScope) {
<ide> // this is not an external guarantee, just our own sanity
<ide> var log = '';
<del> var childA = root.$new();
<del> var childB = root.$new();
<del> var childC = root.$new();
<add> var childA = $rootScope.$new();
<add> var childB = $rootScope.$new();
<add> var childC = $rootScope.$new();
<ide> childA.$watch('a', function() { log += 'a'; });
<ide> childB.$watch('b', function() { log += 'b'; });
<ide> childC.$watch('c', function() { log += 'c'; });
<ide> childA.a = childB.b = childC.c = 1;
<del> root.$digest();
<add> $rootScope.$digest();
<ide> expect(log).toEqual('abc');
<del> });
<add> }));
<ide>
<ide>
<del> it('should allow $digest on a child scope with and without a right sibling', function() {
<add> it('should allow $digest on a child scope with and without a right sibling', inject(function($rootScope) {
<ide> // tests a traversal edge case which we originally missed
<ide> var log = '',
<del> childA = root.$new(),
<del> childB = root.$new();
<add> childA = $rootScope.$new(),
<add> childB = $rootScope.$new();
<ide>
<del> root.$watch(function() { log += 'r'; });
<add> $rootScope.$watch(function() { log += 'r'; });
<ide> childA.$watch(function() { log += 'a'; });
<ide> childB.$watch(function() { log += 'b'; });
<ide>
<ide> // init
<del> root.$digest();
<add> $rootScope.$digest();
<ide> expect(log).toBe('rabrab');
<ide>
<ide> log = '';
<ide> describe('Scope', function() {
<ide> log = '';
<ide> childB.$digest();
<ide> expect(log).toBe('b');
<del> });
<add> }));
<ide>
<ide>
<del> it('should repeat watch cycle while model changes are identified', function() {
<add> it('should repeat watch cycle while model changes are identified', inject(function($rootScope) {
<ide> var log = '';
<del> root.$watch('c', function(self, v){self.d = v; log+='c'; });
<del> root.$watch('b', function(self, v){self.c = v; log+='b'; });
<del> root.$watch('a', function(self, v){self.b = v; log+='a'; });
<del> root.$digest();
<add> $rootScope.$watch('c', function(self, v){self.d = v; log+='c'; });
<add> $rootScope.$watch('b', function(self, v){self.c = v; log+='b'; });
<add> $rootScope.$watch('a', function(self, v){self.b = v; log+='a'; });
<add> $rootScope.$digest();
<ide> log = '';
<del> root.a = 1;
<del> root.$digest();
<del> expect(root.b).toEqual(1);
<del> expect(root.c).toEqual(1);
<del> expect(root.d).toEqual(1);
<add> $rootScope.a = 1;
<add> $rootScope.$digest();
<add> expect($rootScope.b).toEqual(1);
<add> expect($rootScope.c).toEqual(1);
<add> expect($rootScope.d).toEqual(1);
<ide> expect(log).toEqual('abc');
<del> });
<add> }));
<ide>
<ide>
<del> it('should repeat watch cycle from the root elemnt', function() {
<add> it('should repeat watch cycle from the root elemnt', inject(function($rootScope) {
<ide> var log = '';
<del> var child = root.$new();
<del> root.$watch(function() { log += 'a'; });
<add> var child = $rootScope.$new();
<add> $rootScope.$watch(function() { log += 'a'; });
<ide> child.$watch(function() { log += 'b'; });
<del> root.$digest();
<add> $rootScope.$digest();
<ide> expect(log).toEqual('abab');
<del> });
<add> }));
<ide>
<ide>
<del> it('should prevent infinite recursion and print watcher expression', function() {
<del> root.$watch('a', function(self){self.b++;});
<del> root.$watch('b', function(self){self.a++;});
<del> root.a = root.b = 0;
<add> it('should prevent infinite recursion and print watcher expression',inject(function($rootScope) {
<add> $rootScope.$watch('a', function(self){self.b++;});
<add> $rootScope.$watch('b', function(self){self.a++;});
<add> $rootScope.a = $rootScope.b = 0;
<ide>
<ide> expect(function() {
<del> root.$digest();
<add> $rootScope.$digest();
<ide> }).toThrow('100 $digest() iterations reached. Aborting!\n'+
<ide> 'Watchers fired in the last 5 iterations: ' +
<ide> '[["a","b"],["a","b"],["a","b"],["a","b"],["a","b"]]');
<del> });
<add> }));
<ide>
<ide>
<ide> it('should prevent infinite recurcion and print print watcher function name or body',
<del> function() {
<del> root.$watch(function watcherA() {return root.a;}, function(self){self.b++;});
<del> root.$watch(function() {return root.b;}, function(self){self.a++;});
<del> root.a = root.b = 0;
<add> inject(function($rootScope) {
<add> $rootScope.$watch(function watcherA() {return $rootScope.a;}, function(self){self.b++;});
<add> $rootScope.$watch(function() {return $rootScope.b;}, function(self){self.a++;});
<add> $rootScope.a = $rootScope.b = 0;
<ide>
<ide> try {
<del> root.$digest();
<add> $rootScope.$digest();
<ide> throw Error('Should have thrown exception');
<ide> } catch(e) {
<ide> expect(e.message.match(/"fn: (watcherA|function)/g).length).toBe(10);
<ide> }
<del> });
<add> }));
<ide>
<ide>
<del> it('should not fire upon $watch registration on initial $digest', function() {
<add> it('should not fire upon $watch registration on initial $digest', inject(function($rootScope) {
<ide> var log = '';
<del> root.a = 1;
<del> root.$watch('a', function() { log += 'a'; });
<del> root.$watch('b', function() { log += 'b'; });
<del> root.$digest();
<add> $rootScope.a = 1;
<add> $rootScope.$watch('a', function() { log += 'a'; });
<add> $rootScope.$watch('b', function() { log += 'b'; });
<add> $rootScope.$digest();
<ide> log = '';
<del> root.$digest();
<add> $rootScope.$digest();
<ide> expect(log).toEqual('');
<del> });
<add> }));
<ide>
<ide>
<del> it('should watch objects', function() {
<add> it('should watch objects', inject(function($rootScope) {
<ide> var log = '';
<del> root.a = [];
<del> root.b = {};
<del> root.$watch('a', function(scope, value){
<add> $rootScope.a = [];
<add> $rootScope.b = {};
<add> $rootScope.$watch('a', function(scope, value){
<ide> log +='.';
<del> expect(value).toBe(root.a);
<add> expect(value).toBe($rootScope.a);
<ide> });
<del> root.$watch('b', function(scope, value){
<add> $rootScope.$watch('b', function(scope, value){
<ide> log +='!';
<del> expect(value).toBe(root.b);
<add> expect(value).toBe($rootScope.b);
<ide> });
<del> root.$digest();
<add> $rootScope.$digest();
<ide> log = '';
<ide>
<del> root.a.push({});
<del> root.b.name = '';
<add> $rootScope.a.push({});
<add> $rootScope.b.name = '';
<ide>
<del> root.$digest();
<add> $rootScope.$digest();
<ide> expect(log).toEqual('.!');
<del> });
<add> }));
<ide>
<ide>
<del> it('should prevent recursion', function() {
<add> it('should prevent recursion', inject(function($rootScope) {
<ide> var callCount = 0;
<del> root.$watch('name', function() {
<add> $rootScope.$watch('name', function() {
<ide> expect(function() {
<del> root.$digest();
<add> $rootScope.$digest();
<ide> }).toThrow('$digest already in progress');
<ide> callCount++;
<ide> });
<del> root.name = 'a';
<del> root.$digest();
<add> $rootScope.name = 'a';
<add> $rootScope.$digest();
<ide> expect(callCount).toEqual(1);
<del> });
<add> }));
<ide>
<ide>
<del> it('should return a function that allows listeners to be unregistered', function() {
<del> var root = angular.scope(),
<add> it('should return a function that allows listeners to be unregistered', inject(function($rootScope) {
<add> var root = angular.injector()('$rootScope'),
<ide> listener = jasmine.createSpy('watch listener'),
<ide> listenerRemove;
<ide>
<ide> describe('Scope', function() {
<ide> listenerRemove();
<ide> root.$digest(); //trigger
<ide> expect(listener).not.toHaveBeenCalled();
<del> });
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('$destroy', function() {
<ide> var first = null, middle = null, last = null, log = null;
<ide>
<del> beforeEach(function() {
<add> beforeEach(inject(function($rootScope) {
<ide> log = '';
<ide>
<del> first = root.$new();
<del> middle = root.$new();
<del> last = root.$new();
<add> first = $rootScope.$new();
<add> middle = $rootScope.$new();
<add> last = $rootScope.$new();
<ide>
<ide> first.$watch(function() { log += '1';});
<ide> middle.$watch(function() { log += '2';});
<ide> last.$watch(function() { log += '3';});
<ide>
<del> root.$digest();
<add> $rootScope.$digest();
<ide> log = '';
<del> });
<add> }));
<ide>
<ide>
<del> it('should ignore remove on root', function() {
<del> root.$destroy();
<del> root.$digest();
<add> it('should ignore remove on root', inject(function($rootScope) {
<add> $rootScope.$destroy();
<add> $rootScope.$digest();
<ide> expect(log).toEqual('123');
<del> });
<add> }));
<ide>
<ide>
<del> it('should remove first', function() {
<add> it('should remove first', inject(function($rootScope) {
<ide> first.$destroy();
<del> root.$digest();
<add> $rootScope.$digest();
<ide> expect(log).toEqual('23');
<del> });
<add> }));
<ide>
<ide>
<del> it('should remove middle', function() {
<add> it('should remove middle', inject(function($rootScope) {
<ide> middle.$destroy();
<del> root.$digest();
<add> $rootScope.$digest();
<ide> expect(log).toEqual('13');
<del> });
<add> }));
<ide>
<ide>
<del> it('should remove last', function() {
<add> it('should remove last', inject(function($rootScope) {
<ide> last.$destroy();
<del> root.$digest();
<add> $rootScope.$digest();
<ide> expect(log).toEqual('12');
<del> });
<add> }));
<ide>
<del> it('should fire a $destroy event', function() {
<add> it('should fire a $destroy event', inject(function($rootScope) {
<ide> var destructedScopes = [];
<ide> middle.$on('$destroy', function(event) {
<ide> destructedScopes.push(event.currentScope);
<ide> });
<ide> middle.$destroy();
<ide> expect(destructedScopes).toEqual([middle]);
<del> });
<add> }));
<ide>
<ide> });
<ide>
<ide>
<ide> describe('$eval', function() {
<del> it('should eval an expression', function() {
<del> expect(root.$eval('a=1')).toEqual(1);
<del> expect(root.a).toEqual(1);
<add> it('should eval an expression', inject(function($rootScope) {
<add> expect($rootScope.$eval('a=1')).toEqual(1);
<add> expect($rootScope.a).toEqual(1);
<ide>
<del> root.$eval(function(self){self.b=2;});
<del> expect(root.b).toEqual(2);
<del> });
<add> $rootScope.$eval(function(self){self.b=2;});
<add> expect($rootScope.b).toEqual(2);
<add> }));
<ide> });
<ide>
<ide> describe('$evalAsync', function() {
<ide>
<del> it('should run callback before $watch', function() {
<add> it('should run callback before $watch', inject(function($rootScope) {
<ide> var log = '';
<del> var child = root.$new();
<del> root.$evalAsync(function(scope){ log += 'parent.async;'; });
<del> root.$watch('value', function() { log += 'parent.$digest;'; });
<add> var child = $rootScope.$new();
<add> $rootScope.$evalAsync(function(scope){ log += 'parent.async;'; });
<add> $rootScope.$watch('value', function() { log += 'parent.$digest;'; });
<ide> child.$evalAsync(function(scope){ log += 'child.async;'; });
<ide> child.$watch('value', function() { log += 'child.$digest;'; });
<del> root.$digest();
<add> $rootScope.$digest();
<ide> expect(log).toEqual('parent.async;parent.$digest;child.async;child.$digest;');
<del> });
<del>
<del> it('should cause a $digest rerun', function() {
<del> root.log = '';
<del> root.value = 0;
<del> root.$watch('value', 'log = log + ".";');
<del> root.$watch('init', function() {
<del> root.$evalAsync('value = 123; log = log + "=" ');
<del> expect(root.value).toEqual(0);
<add> }));
<add>
<add> it('should cause a $digest rerun', inject(function($rootScope) {
<add> $rootScope.log = '';
<add> $rootScope.value = 0;
<add> $rootScope.$watch('value', 'log = log + ".";');
<add> $rootScope.$watch('init', function() {
<add> $rootScope.$evalAsync('value = 123; log = log + "=" ');
<add> expect($rootScope.value).toEqual(0);
<ide> });
<del> root.$digest();
<del> expect(root.log).toEqual('.=.');
<del> });
<del>
<del> it('should run async in the same order as added', function() {
<del> root.log = '';
<del> root.$evalAsync("log = log + 1");
<del> root.$evalAsync("log = log + 2");
<del> root.$digest();
<del> expect(root.log).toBe('12');
<del> });
<add> $rootScope.$digest();
<add> expect($rootScope.log).toEqual('.=.');
<add> }));
<add>
<add> it('should run async in the same order as added', inject(function($rootScope) {
<add> $rootScope.log = '';
<add> $rootScope.$evalAsync("log = log + 1");
<add> $rootScope.$evalAsync("log = log + 2");
<add> $rootScope.$digest();
<add> expect($rootScope.log).toBe('12');
<add> }));
<ide>
<ide> });
<ide>
<ide>
<ide> describe('$apply', function() {
<del> it('should apply expression with full lifecycle', function() {
<add> it('should apply expression with full lifecycle', inject(function($rootScope) {
<ide> var log = '';
<del> var child = root.$new();
<del> root.$watch('a', function(scope, a){ log += '1'; });
<add> var child = $rootScope.$new();
<add> $rootScope.$watch('a', function(scope, a){ log += '1'; });
<ide> child.$apply('$parent.a=0');
<ide> expect(log).toEqual('1');
<del> });
<add> }));
<ide>
<ide>
<del> it('should catch exceptions', function() {
<add> it('should catch exceptions', inject(function($rootScope, $exceptionHandler) {
<ide> var log = '';
<del> var child = root.$new();
<del> root.$watch('a', function(scope, a){ log += '1'; });
<del> root.a = 0;
<add> var child = $rootScope.$new();
<add> $rootScope.$watch('a', function(scope, a){ log += '1'; });
<add> $rootScope.a = 0;
<ide> child.$apply(function() { throw new Error('MyError'); });
<ide> expect(log).toEqual('1');
<del> expect(mockHandler.errors[0].message).toEqual('MyError');
<add> expect($exceptionHandler.errors[0].message).toEqual('MyError');
<ide> $logMock.error.logs.shift();
<del> });
<add> }));
<ide>
<ide>
<ide> describe('exceptions', function() {
<del> var $exceptionHandler, log;
<del> beforeEach(function() {
<add> var log;
<add> beforeEach(inject(function($rootScope) {
<ide> log = '';
<del> $exceptionHandler = jasmine.createSpy('$exceptionHandler');
<del> root.$service = function(name) {
<del> return {$exceptionHandler:$exceptionHandler}[name];
<del> };
<del> root.$watch(function() { log += '$digest;'; });
<del> root.$digest();
<add> $rootScope.$watch(function() { log += '$digest;'; });
<add> $rootScope.$digest();
<ide> log = '';
<del> });
<add> }));
<ide>
<ide>
<del> it('should execute and return value and update', function() {
<del> root.name = 'abc';
<del> expect(root.$apply(function(scope){
<add> it('should execute and return value and update', inject(function($rootScope, $exceptionHandler) {
<add> $rootScope.name = 'abc';
<add> expect($rootScope.$apply(function(scope){
<ide> return scope.name;
<ide> })).toEqual('abc');
<ide> expect(log).toEqual('$digest;');
<del> expect($exceptionHandler).not.wasCalled();
<del> });
<add> expect($exceptionHandler.errors).toEqual([]);
<add> }));
<ide>
<ide>
<del> it('should catch exception and update', function() {
<add> it('should catch exception and update', inject(function($rootScope, $exceptionHandler) {
<ide> var error = new Error('MyError');
<del> root.$apply(function() { throw error; });
<add> $rootScope.$apply(function() { throw error; });
<ide> expect(log).toEqual('$digest;');
<del> expect($exceptionHandler).wasCalledWith(error);
<del> });
<add> expect($exceptionHandler.errors).toEqual([error]);
<add> }));
<ide> });
<ide> });
<ide>
<ide> describe('Scope', function() {
<ide>
<ide> describe('$on', function() {
<ide>
<del> it('should add listener for both $emit and $broadcast events', function() {
<add> it('should add listener for both $emit and $broadcast events', inject(function($rootScope) {
<ide> var log = '',
<del> root = angular.scope(),
<add> root = angular.injector()('$rootScope'),
<ide> child = root.$new();
<ide>
<ide> function eventFn() {
<ide> describe('Scope', function() {
<ide>
<ide> child.$broadcast('abc');
<ide> expect(log).toEqual('XX');
<del> });
<add> }));
<ide>
<ide>
<del> it('should return a function that deregisters the listener', function() {
<add> it('should return a function that deregisters the listener', inject(function($rootScope) {
<ide> var log = '',
<del> root = angular.scope(),
<add> root = angular.injector()('$rootScope'),
<ide> child = root.$new(),
<ide> listenerRemove;
<ide>
<ide> describe('Scope', function() {
<ide> child.$emit('abc');
<ide> child.$broadcast('abc');
<ide> expect(log).toEqual('');
<del> });
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('Scope', function() {
<ide> log += event.currentScope.id + '>';
<ide> }
<ide>
<del> beforeEach(function() {
<add> beforeEach(inject(function($rootScope) {
<ide> log = '';
<del> child = root.$new();
<add> child = $rootScope.$new();
<ide> grandChild = child.$new();
<ide> greatGrandChild = grandChild.$new();
<ide>
<del> root.id = 0;
<add> $rootScope.id = 0;
<ide> child.id = 1;
<ide> grandChild.id = 2;
<ide> greatGrandChild.id = 3;
<ide>
<del> root.$on('myEvent', logger);
<add> $rootScope.$on('myEvent', logger);
<ide> child.$on('myEvent', logger);
<ide> grandChild.$on('myEvent', logger);
<ide> greatGrandChild.$on('myEvent', logger);
<del> });
<add> }));
<ide>
<del> it('should bubble event up to the root scope', function() {
<add> it('should bubble event up to the root scope', inject(function($rootScope) {
<ide> grandChild.$emit('myEvent');
<ide> expect(log).toEqual('2>1>0>');
<del> });
<add> }));
<ide>
<ide>
<del> it('should dispatch exceptions to the $exceptionHandler', function() {
<add> it('should dispatch exceptions to the $exceptionHandler',
<add> inject(function($rootScope, $exceptionHandler) {
<ide> child.$on('myEvent', function() { throw 'bubbleException'; });
<ide> grandChild.$emit('myEvent');
<ide> expect(log).toEqual('2>1>0>');
<del> expect(mockHandler.errors).toEqual(['bubbleException']);
<del> });
<add> expect($exceptionHandler.errors).toEqual(['bubbleException']);
<add> }));
<ide>
<ide>
<del> it('should allow cancelation of event propagation', function() {
<add> it('should allow cancelation of event propagation', inject(function($rootScope) {
<ide> child.$on('myEvent', function(event){ event.cancel(); });
<ide> grandChild.$emit('myEvent');
<ide> expect(log).toEqual('2>1>');
<del> });
<add> }));
<ide>
<ide>
<del> it('should forward method arguments', function() {
<add> it('should forward method arguments', inject(function($rootScope) {
<ide> child.$on('abc', function(event, arg1, arg2){
<ide> expect(event.name).toBe('abc');
<ide> expect(arg1).toBe('arg1');
<ide> expect(arg2).toBe('arg2');
<ide> });
<ide> child.$emit('abc', 'arg1', 'arg2');
<del> });
<add> }));
<ide>
<ide> describe('event object', function() {
<del> it('should have methods/properties', function() {
<add> it('should have methods/properties', inject(function($rootScope) {
<ide> var event;
<ide> child.$on('myEvent', function(e){
<ide> expect(e.targetScope).toBe(grandChild);
<ide> describe('Scope', function() {
<ide> });
<ide> grandChild.$emit('myEvent');
<ide> expect(event).toBeDefined();
<del> });
<add> }));
<ide> });
<ide> });
<ide>
<ide> describe('Scope', function() {
<ide> log += event.currentScope.id + '>';
<ide> }
<ide>
<del> beforeEach(function() {
<add> beforeEach(inject(function($rootScope) {
<ide> log = '';
<del> child1 = root.$new();
<del> child2 = root.$new();
<del> child3 = root.$new();
<add> child1 = $rootScope.$new();
<add> child2 = $rootScope.$new();
<add> child3 = $rootScope.$new();
<ide> grandChild11 = child1.$new();
<ide> grandChild21 = child2.$new();
<ide> grandChild22 = child2.$new();
<ide> grandChild23 = child2.$new();
<ide> greatGrandChild211 = grandChild21.$new();
<ide>
<del> root.id = 0;
<add> $rootScope.id = 0;
<ide> child1.id = 1;
<ide> child2.id = 2;
<ide> child3.id = 3;
<ide> describe('Scope', function() {
<ide> grandChild23.id = 23;
<ide> greatGrandChild211.id = 211;
<ide>
<del> root.$on('myEvent', logger);
<add> $rootScope.$on('myEvent', logger);
<ide> child1.$on('myEvent', logger);
<ide> child2.$on('myEvent', logger);
<ide> child3.$on('myEvent', logger);
<ide> describe('Scope', function() {
<ide> // 11 21 22 23
<ide> // |
<ide> // 211
<del> });
<add> }));
<ide>
<ide>
<del> it('should broadcast an event from the root scope', function() {
<del> root.$broadcast('myEvent');
<add> it('should broadcast an event from the root scope', inject(function($rootScope) {
<add> $rootScope.$broadcast('myEvent');
<ide> expect(log).toBe('0>1>11>2>21>211>22>23>3>');
<del> });
<add> }));
<ide>
<ide>
<del> it('should broadcast an event from a child scope', function() {
<add> it('should broadcast an event from a child scope', inject(function($rootScope) {
<ide> child2.$broadcast('myEvent');
<ide> expect(log).toBe('2>21>211>22>23>');
<del> });
<add> }));
<ide>
<ide>
<del> it('should broadcast an event from a leaf scope with a sibling', function() {
<add> it('should broadcast an event from a leaf scope with a sibling', inject(function($rootScope) {
<ide> grandChild22.$broadcast('myEvent');
<ide> expect(log).toBe('22>');
<del> });
<add> }));
<ide>
<ide>
<del> it('should broadcast an event from a leaf scope without a sibling', function() {
<add> it('should broadcast an event from a leaf scope without a sibling', inject(function($rootScope) {
<ide> grandChild23.$broadcast('myEvent');
<ide> expect(log).toBe('23>');
<del> });
<add> }));
<ide>
<ide>
<del> it('should not not fire any listeners for other events', function() {
<del> root.$broadcast('fooEvent');
<add> it('should not not fire any listeners for other events', inject(function($rootScope) {
<add> $rootScope.$broadcast('fooEvent');
<ide> expect(log).toBe('');
<del> });
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('listener', function() {
<del> it('should receive event object', function() {
<del> var scope = angular.scope(),
<add> it('should receive event object', inject(function($rootScope) {
<add> var scope = angular.injector()('$rootScope'),
<ide> child = scope.$new(),
<ide> event;
<ide>
<ide> describe('Scope', function() {
<ide> expect(event.name).toBe('fooEvent');
<ide> expect(event.targetScope).toBe(scope);
<ide> expect(event.currentScope).toBe(child);
<del> });
<add> }));
<ide>
<ide>
<del> it('should support passing messages as varargs', function() {
<del> var scope = angular.scope(),
<add> it('should support passing messages as varargs', inject(function($rootScope) {
<add> var scope = angular.injector()('$rootScope'),
<ide> child = scope.$new(),
<ide> args;
<ide>
<ide> describe('Scope', function() {
<ide>
<ide> expect(args.length).toBe(5);
<ide> expect(sliceArgs(args, 1)).toEqual(['do', 're', 'me', 'fa']);
<del> });
<add> }));
<ide> });
<ide> });
<ide> });
<ide><path>test/service/windowSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$window', function() {
<del> var scope;
<del>
<del> beforeEach(function() {
<del> scope = angular.scope();
<del> });
<del>
<del>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<del>
<del>
<del> it("should inject $window", function() {
<del> expect(scope.$service('$window')).toBe(window);
<del> });
<add> it("should inject $window", inject(function($window) {
<add> expect($window).toBe(window);
<add> }));
<ide> });
<ide><path>test/service/xhr.bulkSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$xhr.bulk', function() {
<del> var scope, $browser, $browserXhr, $log, $xhrBulk, $xhrError, log;
<add> var log;
<ide>
<del> beforeEach(function() {
<del> scope = angular.scope(angular.service, {
<del> '$xhr.error': $xhrError = jasmine.createSpy('$xhr.error'),
<del> '$log': $log = {}
<add> beforeEach(inject(function(service) {
<add> service('$xhr.error', function(){
<add> return jasmine.createSpy('$xhr.error');
<ide> });
<del> $browser = scope.$service('$browser');
<del> $browserXhr = $browser.xhr;
<del> $xhrBulk = scope.$service('$xhr.bulk');
<del> $log = scope.$service('$log');
<add> service.alias('$xhr.error', '$xhrError');
<add> service.alias('$xhr.bulk', '$xhrBulk');
<ide> log = '';
<del> });
<del>
<del>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<add> }));
<ide>
<ide>
<ide> function callback(code, response) {
<ide> describe('$xhr.bulk', function() {
<ide> }
<ide>
<ide>
<del> it('should collect requests', function() {
<add> it('should collect requests', inject(function($browser, $xhrBulk) {
<ide> $xhrBulk.urls["/"] = {match:/.*/};
<ide> $xhrBulk('GET', '/req1', null, callback);
<ide> $xhrBulk('POST', '/req2', {post:'data'}, callback);
<ide>
<del> $browserXhr.expectPOST('/', {
<add> $browser.xhr.expectPOST('/', {
<ide> requests:[{method:'GET', url:'/req1', data: null},
<ide> {method:'POST', url:'/req2', data:{post:'data'} }]
<ide> }).respond([
<ide> {status:200, response:'first'},
<ide> {status:200, response:'second'}
<ide> ]);
<ide> $xhrBulk.flush(function() { log += 'DONE';});
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(log).toEqual('"first";"second";DONE');
<del> });
<add> }));
<ide>
<ide>
<del> it('should handle non 200 status code by forwarding to error handler', function() {
<add> it('should handle non 200 status code by forwarding to error handler',
<add> inject(function($browser, $xhrBulk, $xhrError) {
<ide> $xhrBulk.urls['/'] = {match:/.*/};
<ide> $xhrBulk('GET', '/req1', null, callback);
<ide> $xhrBulk('POST', '/req2', {post:'data'}, callback);
<ide>
<del> $browserXhr.expectPOST('/', {
<add> $browser.xhr.expectPOST('/', {
<ide> requests:[{method:'GET', url:'/req1', data: null},
<ide> {method:'POST', url:'/req2', data:{post:'data'} }]
<ide> }).respond([
<ide> {status:404, response:'NotFound'},
<ide> {status:200, response:'second'}
<ide> ]);
<ide> $xhrBulk.flush(function() { log += 'DONE';});
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide>
<ide> expect($xhrError).toHaveBeenCalled();
<ide> var cb = $xhrError.mostRecentCall.args[0].success;
<ide> describe('$xhr.bulk', function() {
<ide> {status: 404, response: 'NotFound'});
<ide>
<ide> expect(log).toEqual('"second";DONE');
<del> });
<add> }));
<ide>
<del> it('should handle non 200 status code by calling error callback if provided', function() {
<add> it('should handle non 200 status code by calling error callback if provided',
<add> inject(function($browser, $xhrBulk, $xhrError) {
<ide> var callback = jasmine.createSpy('error');
<ide>
<ide> $xhrBulk.urls['/'] = {match: /.*/};
<ide> $xhrBulk('GET', '/req1', null, noop, callback);
<ide>
<del> $browserXhr.expectPOST('/', {
<add> $browser.xhr.expectPOST('/', {
<ide> requests:[{method: 'GET', url: '/req1', data: null}]
<ide> }).respond([{status: 404, response: 'NotFound'}]);
<ide>
<ide> $xhrBulk.flush();
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide>
<ide> expect($xhrError).not.toHaveBeenCalled();
<ide> expect(callback).toHaveBeenCalledWith(404, 'NotFound');
<del> });
<add> }));
<ide> });
<ide><path>test/service/xhr.cacheSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$xhr.cache', function() {
<del> var scope, $browser, $browserXhr, $xhrErr, cache, log;
<del>
<del> beforeEach(function() {
<del> scope = angular.scope(angularService, {'$xhr.error': $xhrErr = jasmine.createSpy('$xhr.error')});
<del> $browser = scope.$service('$browser');
<del> $browserXhr = $browser.xhr;
<del> cache = scope.$service('$xhr.cache');
<add> var log;
<add>
<add> beforeEach(inject(function(service) {
<add> service('$xhr.error', function(){
<add> return jasmine.createSpy('$xhr.error');
<add> });
<add> service.alias('$xhr.cache', '$xhrCache');
<add> service.alias('$xhr.bulk', '$xhrBulk');
<add> service.alias('$xhr.error', '$xhrError');
<ide> log = '';
<del> });
<del>
<del>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<add> }));
<ide>
<ide>
<ide> function callback(code, response) {
<ide> describe('$xhr.cache', function() {
<ide> }
<ide>
<ide>
<del> it('should cache requests', function() {
<del> $browserXhr.expectGET('/url').respond('first');
<del> cache('GET', '/url', null, callback);
<del> $browserXhr.flush();
<add> it('should cache requests', inject(function($browser, $xhrCache) {
<add> $browser.xhr.expectGET('/url').respond('first');
<add> $xhrCache('GET', '/url', null, callback);
<add> $browser.xhr.flush();
<ide>
<del> $browserXhr.expectGET('/url').respond('ERROR');
<del> cache('GET', '/url', null, callback);
<add> $browser.xhr.expectGET('/url').respond('ERROR');
<add> $xhrCache('GET', '/url', null, callback);
<ide> $browser.defer.flush();
<ide> expect(log).toEqual('"first";"first";');
<ide>
<del> cache('GET', '/url', null, callback, false);
<add> $xhrCache('GET', '/url', null, callback, false);
<ide> $browser.defer.flush();
<ide> expect(log).toEqual('"first";"first";"first";');
<del> });
<add> }));
<ide>
<ide>
<del> it('should first return cache request, then return server request', function() {
<del> $browserXhr.expectGET('/url').respond('first');
<del> cache('GET', '/url', null, callback, true);
<del> $browserXhr.flush();
<add> it('should first return cache request, then return server request', inject(function($browser, $xhrCache) {
<add> $browser.xhr.expectGET('/url').respond('first');
<add> $xhrCache('GET', '/url', null, callback, true);
<add> $browser.xhr.flush();
<ide>
<del> $browserXhr.expectGET('/url').respond('ERROR');
<del> cache('GET', '/url', null, callback, true);
<add> $browser.xhr.expectGET('/url').respond('ERROR');
<add> $xhrCache('GET', '/url', null, callback, true);
<ide> $browser.defer.flush();
<ide> expect(log).toEqual('"first";"first";');
<ide>
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(log).toEqual('"first";"first";"ERROR";');
<del> });
<add> }));
<ide>
<ide>
<del> it('should serve requests from cache', function() {
<del> cache.data.url = {value:'123'};
<del> cache('GET', 'url', null, callback);
<add> it('should serve requests from cache', inject(function($browser, $xhrCache) {
<add> $xhrCache.data.url = {value:'123'};
<add> $xhrCache('GET', 'url', null, callback);
<ide> $browser.defer.flush();
<ide> expect(log).toEqual('"123";');
<ide>
<del> cache('GET', 'url', null, callback, false);
<add> $xhrCache('GET', 'url', null, callback, false);
<ide> $browser.defer.flush();
<ide> expect(log).toEqual('"123";"123";');
<del> });
<add> }));
<ide>
<ide>
<del> it('should keep track of in flight requests and request only once', function() {
<del> scope.$service('$xhr.bulk').urls['/bulk'] = {
<add> it('should keep track of in flight requests and request only once', inject(function($browser, $xhrCache, $xhrBulk) {
<add> $xhrBulk.urls['/bulk'] = {
<ide> match:function(url){
<ide> return url == '/url';
<ide> }
<ide> };
<del> $browserXhr.expectPOST('/bulk', {
<add> $browser.xhr.expectPOST('/bulk', {
<ide> requests:[{method:'GET', url:'/url', data: null}]
<ide> }).respond([
<ide> {status:200, response:'123'}
<ide> ]);
<del> cache('GET', '/url', null, callback);
<del> cache('GET', '/url', null, callback);
<del> cache.delegate.flush();
<del> $browserXhr.flush();
<add> $xhrCache('GET', '/url', null, callback);
<add> $xhrCache('GET', '/url', null, callback);
<add> $xhrCache.delegate.flush();
<add> $browser.xhr.flush();
<ide> expect(log).toEqual('"123";"123";');
<del> });
<add> }));
<ide>
<ide>
<del> it('should clear cache on non GET', function() {
<del> $browserXhr.expectPOST('abc', {}).respond({});
<del> cache.data.url = {value:123};
<del> cache('POST', 'abc', {});
<del> expect(cache.data.url).toBeUndefined();
<del> });
<add> it('should clear cache on non GET', inject(function($browser, $xhrCache) {
<add> $browser.xhr.expectPOST('abc', {}).respond({});
<add> $xhrCache.data.url = {value:123};
<add> $xhrCache('POST', 'abc', {});
<add> expect($xhrCache.data.url).toBeUndefined();
<add> }));
<ide>
<ide>
<del> it('should call callback asynchronously for both cache hit and cache miss', function() {
<del> $browserXhr.expectGET('/url').respond('+');
<del> cache('GET', '/url', null, callback);
<add> it('should call callback asynchronously for both cache hit and cache miss', inject(function($browser, $xhrCache) {
<add> $browser.xhr.expectGET('/url').respond('+');
<add> $xhrCache('GET', '/url', null, callback);
<ide> expect(log).toEqual(''); //callback hasn't executed
<ide>
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(log).toEqual('"+";'); //callback has executed
<ide>
<del> cache('GET', '/url', null, callback);
<add> $xhrCache('GET', '/url', null, callback);
<ide> expect(log).toEqual('"+";'); //callback hasn't executed
<ide>
<ide> $browser.defer.flush();
<ide> expect(log).toEqual('"+";"+";'); //callback has executed
<del> });
<add> }));
<ide>
<ide>
<del> it('should call callback synchronously when sync flag is on', function() {
<del> $browserXhr.expectGET('/url').respond('+');
<del> cache('GET', '/url', null, callback, false, true);
<add> it('should call callback synchronously when sync flag is on', inject(function($browser, $xhrCache) {
<add> $browser.xhr.expectGET('/url').respond('+');
<add> $xhrCache('GET', '/url', null, callback, false, true);
<ide> expect(log).toEqual(''); //callback hasn't executed
<ide>
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(log).toEqual('"+";'); //callback has executed
<ide>
<del> cache('GET', '/url', null, callback, false, true);
<add> $xhrCache('GET', '/url', null, callback, false, true);
<ide> expect(log).toEqual('"+";"+";'); //callback has executed
<ide>
<ide> $browser.defer.flush();
<ide> expect(log).toEqual('"+";"+";'); //callback was not called again any more
<del> });
<add> }));
<ide>
<ide>
<del> it('should call eval after callbacks for both cache hit and cache miss execute', function() {
<del> var flushSpy = this.spyOn(scope, '$digest').andCallThrough();
<add> it('should call eval after callbacks for both cache hit and cache miss execute',
<add> inject(function($browser, $xhrCache, $rootScope) {
<add> var flushSpy = this.spyOn($rootScope, '$digest').andCallThrough();
<ide>
<del> $browserXhr.expectGET('/url').respond('+');
<del> cache('GET', '/url', null, callback);
<add> $browser.xhr.expectGET('/url').respond('+');
<add> $xhrCache('GET', '/url', null, callback);
<ide> expect(flushSpy).not.toHaveBeenCalled();
<ide>
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(flushSpy).toHaveBeenCalled();
<ide>
<ide> flushSpy.reset(); //reset the spy
<ide>
<del> cache('GET', '/url', null, callback);
<add> $xhrCache('GET', '/url', null, callback);
<ide> expect(flushSpy).not.toHaveBeenCalled();
<ide>
<ide> $browser.defer.flush();
<ide> expect(flushSpy).toHaveBeenCalled();
<del> });
<add> }));
<ide>
<del> it('should call the error callback on error if provided', function() {
<add> it('should call the error callback on error if provided', inject(function($browser, $xhrCache) {
<ide> var errorSpy = jasmine.createSpy('error'),
<ide> successSpy = jasmine.createSpy('success');
<ide>
<del> $browserXhr.expectGET('/url').respond(500, 'error');
<add> $browser.xhr.expectGET('/url').respond(500, 'error');
<ide>
<del> cache('GET', '/url', null, successSpy, errorSpy, false, true);
<del> $browserXhr.flush();
<add> $xhrCache('GET', '/url', null, successSpy, errorSpy, false, true);
<add> $browser.xhr.flush();
<ide> expect(errorSpy).toHaveBeenCalledWith(500, 'error');
<ide> expect(successSpy).not.toHaveBeenCalled();
<ide>
<ide> errorSpy.reset();
<del> cache('GET', '/url', successSpy, errorSpy, false, true);
<del> $browserXhr.flush();
<add> $xhrCache('GET', '/url', successSpy, errorSpy, false, true);
<add> $browser.xhr.flush();
<ide> expect(errorSpy).toHaveBeenCalledWith(500, 'error');
<ide> expect(successSpy).not.toHaveBeenCalled();
<del> });
<add> }));
<ide>
<del> it('should call the $xhr.error on error if error callback not provided', function() {
<add> it('should call the $xhr.error on error if error callback not provided',
<add> inject(function($browser, $xhrCache, $xhrError) {
<ide> var errorSpy = jasmine.createSpy('error'),
<ide> successSpy = jasmine.createSpy('success');
<ide>
<del> $browserXhr.expectGET('/url').respond(500, 'error');
<del> cache('GET', '/url', null, successSpy, false, true);
<del> $browserXhr.flush();
<add> $browser.xhr.expectGET('/url').respond(500, 'error');
<add> $xhrCache('GET', '/url', null, successSpy, false, true);
<add> $browser.xhr.flush();
<ide>
<ide> expect(successSpy).not.toHaveBeenCalled();
<del> expect($xhrErr).toHaveBeenCalledWith(
<add> expect($xhrError).toHaveBeenCalledWith(
<ide> {method: 'GET', url: '/url', data: null, success: successSpy},
<ide> {status: 500, body: 'error'});
<del> });
<add> }));
<ide> });
<ide><path>test/service/xhr.errorSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$xhr.error', function() {
<del> var scope, $browser, $browserXhr, $xhr, $xhrError, log;
<add> var log;
<ide>
<del> beforeEach(function() {
<del> scope = angular.scope(angular.service, {
<del> '$xhr.error': $xhrError = jasmine.createSpy('$xhr.error')
<add> beforeEach(inject(function(service) {
<add> service('$xhr.error', function(){
<add> return jasmine.createSpy('$xhr.error');
<ide> });
<del> $browser = scope.$service('$browser');
<del> $browserXhr = $browser.xhr;
<del> $xhr = scope.$service('$xhr');
<add> service.alias('$xhr.error', '$xhrError');
<ide> log = '';
<del> });
<del>
<del>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<add> }));
<ide>
<ide>
<ide> function callback(code, response) {
<ide> describe('$xhr.error', function() {
<ide> }
<ide>
<ide>
<del> it('should handle non 200 status codes by forwarding to error handler', function() {
<del> $browserXhr.expectPOST('/req', 'MyData').respond(500, 'MyError');
<add> it('should handle non 200 status codes by forwarding to error handler', inject(function($browser, $xhr, $xhrError) {
<add> $browser.xhr.expectPOST('/req', 'MyData').respond(500, 'MyError');
<ide> $xhr('POST', '/req', 'MyData', callback);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> var cb = $xhrError.mostRecentCall.args[0].success;
<ide> expect(typeof cb).toEqual('function');
<ide> expect($xhrError).toHaveBeenCalledWith(
<ide> {url: '/req', method: 'POST', data: 'MyData', success: cb},
<ide> {status: 500, body: 'MyError'});
<del> });
<add> }));
<ide> });
<ide><path>test/service/xhrSpec.js
<ide> 'use strict';
<ide>
<ide> describe('$xhr', function() {
<del> var scope, $browser, $browserXhr, $log, $xhr, $xhrErr, log;
<del>
<del> beforeEach(function() {
<del> var scope = angular.scope(angular.service, {
<del> '$xhr.error': $xhrErr = jasmine.createSpy('xhr.error')});
<del> $log = scope.$service('$log');
<del> $browser = scope.$service('$browser');
<del> $browserXhr = $browser.xhr;
<del> $xhr = scope.$service('$xhr');
<del> log = '';
<del> });
<ide>
<add> var log;
<ide>
<del> afterEach(function() {
<del> dealoc(scope);
<del> });
<add> beforeEach(inject(function(service) {
<add> log = '';
<add> service('$xhr.error', function(){
<add> return jasmine.createSpy('xhr.error');
<add> });
<add> service.alias('$xhr.error', '$xhrError');
<add> }));
<ide>
<ide>
<ide> function callback(code, response) {
<ide> log = log + '{code=' + code + '; response=' + toJson(response) + '}';
<ide> }
<ide>
<ide>
<del> it('should forward the request to $browser and decode JSON', function() {
<del> $browserXhr.expectGET('/reqGET').respond('first');
<del> $browserXhr.expectGET('/reqGETjson').respond('["second"]');
<del> $browserXhr.expectPOST('/reqPOST', {post:'data'}).respond('third');
<add> it('should forward the request to $browser and decode JSON', inject(function($browser, $xhr) {
<add> $browser.xhr.expectGET('/reqGET').respond('first');
<add> $browser.xhr.expectGET('/reqGETjson').respond('["second"]');
<add> $browser.xhr.expectPOST('/reqPOST', {post:'data'}).respond('third');
<ide>
<ide> $xhr('GET', '/reqGET', null, callback);
<ide> $xhr('GET', '/reqGETjson', null, callback);
<ide> $xhr('POST', '/reqPOST', {post:'data'}, callback);
<ide>
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide>
<ide> expect(log).toEqual(
<ide> '{code=200; response="third"}' +
<ide> '{code=200; response=["second"]}' +
<ide> '{code=200; response="first"}');
<del> });
<add> }));
<ide>
<del> it('should allow all 2xx requests', function() {
<del> $browserXhr.expectGET('/req1').respond(200, '1');
<add> it('should allow all 2xx requests', inject(function($browser, $xhr) {
<add> $browser.xhr.expectGET('/req1').respond(200, '1');
<ide> $xhr('GET', '/req1', null, callback);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide>
<del> $browserXhr.expectGET('/req2').respond(299, '2');
<add> $browser.xhr.expectGET('/req2').respond(299, '2');
<ide> $xhr('GET', '/req2', null, callback);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide>
<ide> expect(log).toEqual(
<ide> '{code=200; response="1"}' +
<ide> '{code=299; response="2"}');
<del> });
<add> }));
<ide>
<ide>
<del> it('should handle exceptions in callback', function() {
<del> $browserXhr.expectGET('/reqGET').respond('first');
<add> it('should handle exceptions in callback', inject(function($browser, $xhr, $log) {
<add> $browser.xhr.expectGET('/reqGET').respond('first');
<ide> $xhr('GET', '/reqGET', null, function() { throw "MyException"; });
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide>
<ide> expect($log.error.logs.shift()).toContain('MyException');
<del> });
<add> }));
<ide>
<ide>
<del> it('should automatically deserialize json objects', function() {
<add> it('should automatically deserialize json objects', inject(function($browser, $xhr) {
<ide> var response;
<ide>
<del> $browserXhr.expectGET('/foo').respond('{"foo":"bar","baz":23}');
<add> $browser.xhr.expectGET('/foo').respond('{"foo":"bar","baz":23}');
<ide> $xhr('GET', '/foo', function(code, resp) {
<ide> response = resp;
<ide> });
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide>
<ide> expect(response).toEqual({foo:'bar', baz:23});
<del> });
<add> }));
<ide>
<ide>
<del> it('should automatically deserialize json arrays', function() {
<add> it('should automatically deserialize json arrays', inject(function($browser, $xhr) {
<ide> var response;
<ide>
<del> $browserXhr.expectGET('/foo').respond('[1, "abc", {"foo":"bar"}]');
<add> $browser.xhr.expectGET('/foo').respond('[1, "abc", {"foo":"bar"}]');
<ide> $xhr('GET', '/foo', function(code, resp) {
<ide> response = resp;
<ide> });
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide>
<ide> expect(response).toEqual([1, 'abc', {foo:'bar'}]);
<del> });
<add> }));
<ide>
<ide>
<del> it('should automatically deserialize json with security prefix', function() {
<add> it('should automatically deserialize json with security prefix', inject(function($browser, $xhr) {
<ide> var response;
<ide>
<del> $browserXhr.expectGET('/foo').respond(')]}\',\n[1, "abc", {"foo":"bar"}]');
<add> $browser.xhr.expectGET('/foo').respond(')]}\',\n[1, "abc", {"foo":"bar"}]');
<ide> $xhr('GET', '/foo', function(code, resp) {
<ide> response = resp;
<ide> });
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide>
<ide> expect(response).toEqual([1, 'abc', {foo:'bar'}]);
<del> });
<add> }));
<ide>
<del> it('should call $xhr.error on error if no error callback provided', function() {
<add> it('should call $xhr.error on error if no error callback provided', inject(function($browser, $xhr, $xhrError) {
<ide> var successSpy = jasmine.createSpy('success');
<ide>
<del> $browserXhr.expectGET('/url').respond(500, 'error');
<add> $browser.xhr.expectGET('/url').respond(500, 'error');
<ide> $xhr('GET', '/url', null, successSpy);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide>
<ide> expect(successSpy).not.toHaveBeenCalled();
<del> expect($xhrErr).toHaveBeenCalledWith(
<add> expect($xhrError).toHaveBeenCalledWith(
<ide> {method: 'GET', url: '/url', data: null, success: successSpy},
<ide> {status: 500, body: 'error'}
<ide> );
<del> });
<add> }));
<ide>
<del> it('should call the error callback on error if provided', function() {
<add> it('should call the error callback on error if provided', inject(function($browser, $xhr) {
<ide> var errorSpy = jasmine.createSpy('error'),
<ide> successSpy = jasmine.createSpy('success');
<ide>
<del> $browserXhr.expectGET('/url').respond(500, 'error');
<add> $browser.xhr.expectGET('/url').respond(500, 'error');
<ide> $xhr('GET', '/url', null, successSpy, errorSpy);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide>
<ide> expect(errorSpy).toHaveBeenCalledWith(500, 'error');
<ide> expect(successSpy).not.toHaveBeenCalled();
<ide>
<ide> errorSpy.reset();
<ide> $xhr('GET', '/url', successSpy, errorSpy);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide>
<ide> expect(errorSpy).toHaveBeenCalledWith(500, 'error');
<ide> expect(successSpy).not.toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide> describe('http headers', function() {
<ide>
<ide> describe('default headers', function() {
<ide>
<del> it('should set default headers for GET request', function() {
<add> it('should set default headers for GET request', inject(function($browser, $xhr) {
<ide> var callback = jasmine.createSpy('callback');
<ide>
<del> $browserXhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*',
<add> $browser.xhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*',
<ide> 'X-Requested-With': 'XMLHttpRequest'}).
<ide> respond(234, 'OK');
<ide>
<ide> $xhr('GET', 'URL', callback);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(callback).toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<del> it('should set default headers for POST request', function() {
<add> it('should set default headers for POST request', inject(function($browser, $xhr) {
<ide> var callback = jasmine.createSpy('callback');
<ide>
<del> $browserXhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*',
<add> $browser.xhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*',
<ide> 'X-Requested-With': 'XMLHttpRequest',
<ide> 'Content-Type': 'application/x-www-form-urlencoded'}).
<ide> respond(200, 'OK');
<ide>
<ide> $xhr('POST', 'URL', 'xx', callback);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(callback).toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<del> it('should set default headers for custom HTTP method', function() {
<add> it('should set default headers for custom HTTP method', inject(function($browser, $xhr) {
<ide> var callback = jasmine.createSpy('callback');
<ide>
<del> $browserXhr.expect('FOO', 'URL', '', {'Accept': 'application/json, text/plain, */*',
<add> $browser.xhr.expect('FOO', 'URL', '', {'Accept': 'application/json, text/plain, */*',
<ide> 'X-Requested-With': 'XMLHttpRequest'}).
<ide> respond(200, 'OK');
<ide>
<ide> $xhr('FOO', 'URL', callback);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(callback).toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<ide> describe('custom headers', function() {
<ide>
<del> it('should allow appending a new header to the common defaults', function() {
<add> it('should allow appending a new header to the common defaults', inject(function($browser, $xhr) {
<ide> var callback = jasmine.createSpy('callback');
<ide>
<del> $browserXhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*',
<add> $browser.xhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*',
<ide> 'X-Requested-With': 'XMLHttpRequest',
<ide> 'Custom-Header': 'value'}).
<ide> respond(200, 'OK');
<ide>
<ide> $xhr.defaults.headers.common['Custom-Header'] = 'value';
<ide> $xhr('GET', 'URL', callback);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(callback).toHaveBeenCalled();
<ide> callback.reset();
<ide>
<del> $browserXhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*',
<add> $browser.xhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*',
<ide> 'X-Requested-With': 'XMLHttpRequest',
<ide> 'Content-Type': 'application/x-www-form-urlencoded',
<ide> 'Custom-Header': 'value'}).
<ide> respond(200, 'OK');
<ide>
<ide> $xhr('POST', 'URL', 'xx', callback);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(callback).toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<del> it('should allow appending a new header to a method specific defaults', function() {
<add> it('should allow appending a new header to a method specific defaults', inject(function($browser, $xhr) {
<ide> var callback = jasmine.createSpy('callback');
<ide>
<del> $browserXhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*',
<add> $browser.xhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*',
<ide> 'X-Requested-With': 'XMLHttpRequest',
<ide> 'Content-Type': 'application/json'}).
<ide> respond(200, 'OK');
<ide>
<ide> $xhr.defaults.headers.get['Content-Type'] = 'application/json';
<ide> $xhr('GET', 'URL', callback);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(callback).toHaveBeenCalled();
<ide> callback.reset();
<ide>
<del> $browserXhr.expectPOST('URL', 'x', {'Accept': 'application/json, text/plain, */*',
<add> $browser.xhr.expectPOST('URL', 'x', {'Accept': 'application/json, text/plain, */*',
<ide> 'X-Requested-With': 'XMLHttpRequest',
<ide> 'Content-Type': 'application/x-www-form-urlencoded'}).
<ide> respond(200, 'OK');
<ide>
<ide> $xhr('POST', 'URL', 'x', callback);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(callback).toHaveBeenCalled();
<del> });
<add> }));
<ide>
<ide>
<del> it('should support overwriting and deleting default headers', function() {
<add> it('should support overwriting and deleting default headers', inject(function($browser, $xhr) {
<ide> var callback = jasmine.createSpy('callback');
<ide>
<del> $browserXhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*'}).
<add> $browser.xhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*'}).
<ide> respond(200, 'OK');
<ide>
<ide> //delete a default header
<ide> delete $xhr.defaults.headers.common['X-Requested-With'];
<ide> $xhr('GET', 'URL', callback);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(callback).toHaveBeenCalled();
<ide> callback.reset();
<ide>
<del> $browserXhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*',
<add> $browser.xhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*',
<ide> 'Content-Type': 'application/json'}).
<ide> respond(200, 'OK');
<ide>
<ide> //overwrite a default header
<ide> $xhr.defaults.headers.post['Content-Type'] = 'application/json';
<ide> $xhr('POST', 'URL', 'xx', callback);
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(callback).toHaveBeenCalled();
<del> });
<add> }));
<ide> });
<ide> });
<ide> });
<ide>
<ide> describe('xsrf', function() {
<del> it('should copy the XSRF cookie into a XSRF Header', function() {
<add> it('should copy the XSRF cookie into a XSRF Header', inject(function($browser, $xhr) {
<ide> var code, response;
<del> $browserXhr
<add> $browser.xhr
<ide> .expectPOST('URL', 'DATA', {'X-XSRF-TOKEN': 'secret'})
<ide> .respond(234, 'OK');
<ide> $browser.cookies('XSRF-TOKEN', 'secret');
<ide> $xhr('POST', 'URL', 'DATA', function(c, r){
<ide> code = c;
<ide> response = r;
<ide> });
<del> $browserXhr.flush();
<add> $browser.xhr.flush();
<ide> expect(code).toEqual(234);
<ide> expect(response).toEqual('OK');
<del> });
<add> }));
<ide> });
<ide> });
<ide><path>test/testabilityPatch.js
<ide> if (window.jstestdriver) {
<ide> if (isElement(arg)) {
<ide> arg = sortedHtml(arg);
<ide> } else if (isObject(arg)) {
<del> if (arg.$eval == Scope.prototype.$eval) {
<add> if (isFunction(arg.$eval) && isFunction(arg.$apply)) {
<ide> arg = dumpScope(arg);
<ide> } else {
<ide> arg = toJson(arg, true);
<ide> beforeEach(function() {
<ide> $logMock.warn.logs = [];
<ide> $logMock.info.logs = [];
<ide> $logMock.error.logs = [];
<add>
<add> resetAngularPublic()
<ide> });
<ide>
<del>afterEach(function() {
<add>function inject(){
<add> var blockFns = sliceArgs(arguments);
<add> return function(){
<add> var spec = this;
<add> angular.forEach(blockFns, function(fn){
<add> fn.$inject = inferInjectionArgs(fn);
<add> if (equals(fn.$inject, [])) {
<add> fn.apply(spec);
<add> } else if (equals(fn.$inject, ['service'])) {
<add> if (spec.$injector) {
<add> throw Error('$injector already created for this test');
<add> }
<add> if (!spec.$service) {
<add> spec.$service = function(name, fn) {
<add> if (fn) { spec.$service[name] = fn; }
<add> return spec.$service[name];
<add> }
<add> spec.$service.alias = function (name, alias) {
<add> spec.$service(alias, extend(function(x){ return x; }, {$inject:[name]}));
<add> };
<add> forEach(angularService, function(value, key){
<add> spec.$service(key, value);
<add> });
<add> }
<add> fn.call(spec, spec.$service);
<add> } else {
<add> if (!spec.$injector) {
<add> spec.$injector = angular.injector(spec.$service);
<add> }
<add> spec.$injector.invoke(spec, fn);
<add> }
<add> });
<add> };
<add>}
<add>
<add>/**
<add> * This method republishes the public angular API. It should probably be cleaned up somehow.
<add> * //TODO: remove this method and merge it with the angularPublic.js class
<add> */
<add>function resetAngularPublic() {
<add> extend(angular, {
<add> 'element': jqLite,
<add> 'compile': compile,
<add> 'copy': copy,
<add> 'extend': extend,
<add> 'equals': equals,
<add> 'forEach': forEach,
<add> 'noop': noop,
<add> 'bind': bind,
<add> 'toJson': toJson,
<add> 'fromJson': fromJson,
<add> 'identity':identity,
<add> 'injector': createInjector,
<add> 'isUndefined': isUndefined,
<add> 'isDefined': isDefined,
<add> 'isString': isString,
<add> 'isFunction': isFunction,
<add> 'isObject': isObject,
<add> 'isNumber': isNumber,
<add> 'isArray': isArray
<add> });
<add>}
<add>
<add>resetAngularPublic();
<add>
<add>afterEach(inject(function($rootScope) {
<add> // release the injector
<add> dealoc($rootScope);
<add>
<ide> // check $log mock
<ide> forEach(['error', 'warn', 'info', 'log'], function(logLevel) {
<ide> if ($logMock[logLevel].logs.length) {
<ide> afterEach(function() {
<ide> });
<ide>
<ide> clearJqCache();
<del>});
<add>}));
<ide>
<ide> function clearJqCache() {
<ide> var count = 0;
<ide> function dealoc(obj) {
<ide> }
<ide> }
<ide>
<del>extend(angular, {
<del> 'element': jqLite,
<del> 'compile': compile,
<del> 'scope': createScope,
<del> 'copy': copy,
<del> 'extend': extend,
<del> 'equals': equals,
<del> 'forEach': forEach,
<del> 'noop':noop,
<del> 'bind':bind,
<del> 'toJson': toJson,
<del> 'fromJson': fromJson,
<del> 'identity':identity,
<del> 'injector': createInjector,
<del> 'isUndefined': isUndefined,
<del> 'isDefined': isDefined,
<del> 'isString': isString,
<del> 'isFunction': isFunction,
<del> 'isObject': isObject,
<del> 'isNumber': isNumber,
<del> 'isArray': isArray
<del>});
<del>
<ide>
<ide> function sortedHtml(element, showNgClass) {
<ide> var html = "";
<ide><path>test/widget/formSpec.js
<ide> describe('form', function() {
<ide> });
<ide>
<ide>
<del> it('should attach form to DOM', function() {
<add> it('should attach form to DOM', inject(function($rootScope) {
<ide> doc = angular.element('<form>');
<del> var scope = angular.compile(doc)();
<add> angular.compile(doc)($rootScope);
<ide> expect(doc.data('$form')).toBeTruthy();
<del> });
<add> }));
<ide>
<ide>
<del> it('should prevent form submission', function() {
<add> it('should prevent form submission', inject(function($rootScope) {
<ide> var startingUrl = '' + window.location;
<ide> doc = angular.element('<form name="myForm"><input type=submit val=submit>');
<del> var scope = angular.compile(doc)();
<add> angular.compile(doc)($rootScope);
<ide> browserTrigger(doc.find('input'));
<ide> waitsFor(
<ide> function() { return true; },
<ide> 'let browser breath, so that the form submision can manifest itself', 10);
<ide> runs(function() {
<ide> expect('' + window.location).toEqual(startingUrl);
<ide> });
<del> });
<add> }));
<ide>
<ide>
<del> it('should publish form to scope', function() {
<add> it('should publish form to scope', inject(function($rootScope) {
<ide> doc = angular.element('<form name="myForm"></form>');
<del> var scope = angular.compile(doc)();
<del> expect(scope.myForm).toBeTruthy();
<add> angular.compile(doc)($rootScope);
<add> expect($rootScope.myForm).toBeTruthy();
<ide> expect(doc.data('$form')).toBeTruthy();
<del> expect(doc.data('$form')).toEqual(scope.myForm);
<del> });
<add> expect(doc.data('$form')).toEqual($rootScope.myForm);
<add> }));
<ide>
<ide>
<del> it('should have ng-valide/ng-invalid style', function() {
<add> it('should have ng-valide/ng-invalid style', inject(function($rootScope) {
<ide> doc = angular.element('<form name="myForm"><input type=text ng:model=text required>');
<del> var scope = angular.compile(doc)();
<del> scope.text = 'misko';
<del> scope.$digest();
<add> angular.compile(doc)($rootScope);
<add> $rootScope.text = 'misko';
<add> $rootScope.$digest();
<ide>
<ide> expect(doc.hasClass('ng-valid')).toBe(true);
<ide> expect(doc.hasClass('ng-invalid')).toBe(false);
<ide>
<del> scope.text = '';
<del> scope.$digest();
<add> $rootScope.text = '';
<add> $rootScope.$digest();
<ide> expect(doc.hasClass('ng-valid')).toBe(false);
<ide> expect(doc.hasClass('ng-invalid')).toBe(true);
<del> });
<add> }));
<ide>
<ide>
<del> it('should chain nested forms', function() {
<add> it('should chain nested forms', inject(function($rootScope) {
<ide> doc = angular.element(
<ide> '<ng:form name=parent>' +
<ide> '<ng:form name=child>' +
<ide> '<input type=text ng:model=text name=text>' +
<ide> '</ng:form>' +
<ide> '</ng:form>');
<del> var scope = angular.compile(doc)();
<del> var parent = scope.parent;
<del> var child = scope.child;
<add> angular.compile(doc)($rootScope);
<add> var parent = $rootScope.parent;
<add> var child = $rootScope.child;
<ide> var input = child.text;
<ide>
<ide> input.$emit('$invalid', 'MyError');
<ide> describe('form', function() {
<ide> input.$emit('$valid', 'MyError');
<ide> expect(parent.$error.MyError).toBeUndefined();
<ide> expect(child.$error.MyError).toBeUndefined();
<del> });
<add> }));
<ide>
<ide>
<del> it('should chain nested forms in repeater', function() {
<add> it('should chain nested forms in repeater', inject(function($rootScope) {
<ide> doc = angular.element(
<ide> '<ng:form name=parent>' +
<ide> '<ng:form ng:repeat="f in forms" name=child>' +
<ide> '<input type=text ng:model=text name=text>' +
<ide> '</ng:form>' +
<ide> '</ng:form>');
<del> var scope = angular.compile(doc)();
<del> scope.forms = [1];
<del> scope.$digest();
<add> angular.compile(doc)($rootScope);
<add> $rootScope.forms = [1];
<add> $rootScope.$digest();
<ide>
<del> var parent = scope.parent;
<add> var parent = $rootScope.parent;
<ide> var child = doc.find('input').scope().child;
<ide> var input = child.text;
<ide> expect(parent).toBeDefined();
<ide> describe('form', function() {
<ide> input.$emit('$valid', 'myRule');
<ide> expect(parent.$error.myRule).toBeUndefined();
<ide> expect(child.$error.myRule).toBeUndefined();
<del> });
<add> }));
<ide> });
<ide><path>test/widget/inputSpec.js
<ide> describe('widget: input', function() {
<ide> var compile = null, element = null, scope = null, defer = null;
<ide> var doc = null;
<ide>
<del> beforeEach(function() {
<del> scope = null;
<add> beforeEach(inject(function($rootScope) {
<add> scope = $rootScope;
<ide> element = null;
<ide> compile = function(html, parent) {
<ide> if (parent) {
<ide> describe('widget: input', function() {
<ide> } else {
<ide> element = jqLite(html);
<ide> }
<del> scope = angular.compile(element)();
<add> angular.compile(element)(scope);
<ide> scope.$apply();
<ide> defer = scope.$service('$browser').defer;
<ide> return scope;
<ide> };
<del> });
<add> }));
<ide>
<ide> afterEach(function() {
<ide> dealoc(element);
<ide> describe('widget: input', function() {
<ide>
<ide>
<ide> describe('text', function() {
<del> var scope = null,
<del> form = null,
<add> var form = null,
<ide> formElement = null,
<ide> inputElement = null;
<ide>
<ide> describe('widget: input', function() {
<ide> formElement = doc = angular.element('<form name="form"><input ' + prefix +
<ide> 'type="text" ng:model="name" name="name" ng:change="change()"></form>');
<ide> inputElement = formElement.find('input');
<del> scope = angular.compile(doc)();
<add> angular.compile(doc)(scope);
<ide> form = formElement.inheritedData('$form');
<ide> };
<ide>
<ide> describe('widget: input', function() {
<ide> });
<ide>
<ide>
<del> it('should change non-html5 types to text', function() {
<add> it('should change non-html5 types to text', inject(function($rootScope) {
<ide> doc = angular.element('<form name="form"><input type="abc" ng:model="name"></form>');
<del> scope = angular.compile(doc)();
<add> angular.compile(doc)($rootScope);
<ide> expect(doc.find('input').attr('type')).toEqual('text');
<del> });
<add> }));
<ide>
<ide>
<del> it('should not change html5 types to text', function() {
<add> it('should not change html5 types to text', inject(function($rootScope) {
<ide> doc = angular.element('<form name="form"><input type="number" ng:model="name"></form>');
<del> scope = angular.compile(doc)();
<add> angular.compile(doc)($rootScope);
<ide> expect(doc.find('input')[0].getAttribute('type')).toEqual('number');
<del> });
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('widget: input', function() {
<ide>
<ide>
<ide> describe('scope declaration', function() {
<del> it('should read the declaration from scope', function() {
<add> it('should read the declaration from scope', inject(function($rootScope) {
<ide> var input, $formFactory;
<ide> element = angular.element('<input type="@MyType" ng:model="abc">');
<del> scope = angular.scope();
<del> scope.MyType = function($f, i) {
<add> $rootScope.MyType = function($f, i) {
<ide> input = i;
<ide> $formFactory = $f;
<ide> };
<del> scope.MyType.$inject = ['$formFactory'];
<add> $rootScope.MyType.$inject = ['$formFactory'];
<ide>
<del> angular.compile(element)(scope);
<add> angular.compile(element)($rootScope);
<ide>
<del> expect($formFactory).toBe(scope.$service('$formFactory'));
<add> expect($formFactory).toBe($rootScope.$service('$formFactory'));
<ide> expect(input[0]).toBe(element[0]);
<del> });
<add> }));
<ide>
<del> it('should throw an error of Cntoroller not declared in scope', function() {
<add> it('should throw an error of Controller not declared in scope', inject(function($rootScope) {
<ide> var input, $formFactory;
<ide> element = angular.element('<input type="@DontExist" ng:model="abc">');
<ide> var error;
<ide> try {
<del> scope = angular.scope();
<del> angular.compile(element)(scope);
<add> angular.compile(element)($rootScope);
<ide> error = 'no error thrown';
<ide> } catch (e) {
<ide> error = e;
<ide> }
<ide> expect(error.message).toEqual("Argument 'DontExist' is not a function, got undefined");
<del> });
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('widget: input', function() {
<ide> {'ng:maxlength': 3});
<ide>
<ide>
<del> it('should throw an error when scope pattern can\'t be found', function() {
<del> var el = jqLite('<input ng:model="foo" ng:pattern="fooRegexp">'),
<del> scope = angular.compile(el)();
<add> it('should throw an error when scope pattern can\'t be found', inject(function($rootScope) {
<add> var el = jqLite('<input ng:model="foo" ng:pattern="fooRegexp">');
<add> angular.compile(el)($rootScope);
<ide>
<ide> el.val('xx');
<ide> browserTrigger(el, 'keydown');
<del> expect(function() { scope.$service('$browser').defer.flush(); }).
<add> expect(function() { $rootScope.$service('$browser').defer.flush(); }).
<ide> toThrow('Expected fooRegexp to be a RegExp but was undefined');
<ide>
<ide> dealoc(el);
<del> });
<add> }));
<ide> });
<ide> });
<ide><path>test/widget/selectSpec.js
<ide> 'use strict';
<ide>
<ide> describe('select', function() {
<del> var compile = null, element = null, scope = null, $formFactory = null;
<add> var compile = null, element = null, scope = null;
<ide>
<del> beforeEach(function() {
<del> scope = null;
<add> beforeEach(inject(function($rootScope) {
<add> scope = $rootScope;
<ide> element = null;
<ide> compile = function(html, parent) {
<ide> if (parent) {
<ide> describe('select', function() {
<ide> } else {
<ide> element = jqLite(html);
<ide> }
<del> scope = angular.compile(element)();
<add> angular.compile(element)($rootScope);
<ide> scope.$apply();
<del> $formFactory = scope.$service('$formFactory');
<ide> return scope;
<ide> };
<del> });
<add> }));
<ide>
<ide> afterEach(function() {
<ide> dealoc(element);
<ide> describe('select', function() {
<ide> expect(scope.$element.text()).toBe('foobarC');
<ide> });
<ide>
<del> it('should require', function() {
<add> it('should require', inject(function($formFactory) {
<ide> compile('<select name="select" ng:model="selection" required ng:change="log=log+\'change;\'">' +
<ide> '<option value=""></option>' +
<ide> '<option value="c">C</option>' +
<ide> describe('select', function() {
<ide> expect(element).toBeValid();
<ide> expect(element).toBeDirty();
<ide> expect(scope.log).toEqual('change;');
<del> });
<add> }));
<ide>
<ide> it('should not be invalid if no require', function() {
<ide> compile('<select name="select" ng:model="selection">' +
<ide> describe('select', function() {
<ide> expect(element[0].childNodes[0].selected).toEqual(true);
<ide> });
<ide>
<del> it('should require', function() {
<add> it('should require', inject(function($formFactory) {
<ide> compile('<select name="select" ng:model="selection" multiple required>' +
<ide> '<option>A</option>' +
<ide> '<option>B</option>' +
<ide> describe('select', function() {
<ide> browserTrigger(element, 'change');
<ide> expect(element).toBeValid();
<ide> expect(element).toBeDirty();
<del> });
<add> }));
<ide>
<ide> });
<ide>
<ide> describe('select', function() {
<ide> dealoc(scope);
<ide> });
<ide>
<del> it('should throw when not formated "? for ? in ?"', function() {
<add> it('should throw when not formated "? for ? in ?"', inject(function($rootScope, $exceptionHandler) {
<ide> expect(function() {
<ide> compile('<select ng:model="selected" ng:options="i dont parse"></select>');
<ide> }).toThrow("Expected ng:options in form of '_select_ (as _label_)? for (_key_,)?_value_ in" +
<ide> " _collection_' but got 'i dont parse'.");
<del> });
<add> }));
<ide>
<ide> it('should render a list', function() {
<ide> createSingleSelect();
<ide><path>test/widgetsSpec.js
<ide> 'use strict';
<ide>
<ide> describe("widget", function() {
<del> var compile = null, element = null, scope = null;
<del>
<del> beforeEach(function() {
<del> scope = null;
<del> element = null;
<del> compile = function(html, parent) {
<del> if (parent) {
<del> parent.html(html);
<del> element = parent.children();
<del> } else {
<del> element = jqLite(html);
<del> }
<del> scope = angular.compile(element)();
<del> scope.$apply();
<del> return scope;
<del> };
<del> });
<del>
<del> afterEach(function() {
<del> dealoc(element);
<del> });
<del>
<del>
<del> describe('ng:switch', function() {
<del> it('should switch on value change', function() {
<del> compile('<ng:switch on="select">' +
<add> describe('ng:switch', inject(function($rootScope) {
<add> it('should switch on value change', inject(function($rootScope) {
<add> var element = angular.compile('<ng:switch on="select">' +
<ide> '<div ng:switch-when="1">first:{{name}}</div>' +
<ide> '<div ng:switch-when="2">second:{{name}}</div>' +
<ide> '<div ng:switch-when="true">true:{{name}}</div>' +
<del> '</ng:switch>');
<add> '</ng:switch>')($rootScope);
<ide> expect(element.html()).toEqual('');
<del> scope.select = 1;
<del> scope.$apply();
<add> $rootScope.select = 1;
<add> $rootScope.$apply();
<ide> expect(element.text()).toEqual('first:');
<del> scope.name="shyam";
<del> scope.$apply();
<add> $rootScope.name="shyam";
<add> $rootScope.$apply();
<ide> expect(element.text()).toEqual('first:shyam');
<del> scope.select = 2;
<del> scope.$apply();
<add> $rootScope.select = 2;
<add> $rootScope.$apply();
<ide> expect(element.text()).toEqual('second:shyam');
<del> scope.name = 'misko';
<del> scope.$apply();
<add> $rootScope.name = 'misko';
<add> $rootScope.$apply();
<ide> expect(element.text()).toEqual('second:misko');
<del> scope.select = true;
<del> scope.$apply();
<add> $rootScope.select = true;
<add> $rootScope.$apply();
<ide> expect(element.text()).toEqual('true:misko');
<del> });
<del>
<del> it('should switch on switch-when-default', function() {
<del> compile('<ng:switch on="select">' +
<del> '<div ng:switch-when="1">one</div>' +
<del> '<div ng:switch-default>other</div>' +
<del> '</ng:switch>');
<del> scope.$apply();
<add> }));
<add>
<add>
<add> it('should switch on switch-when-default', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<ng:switch on="select">' +
<add> '<div ng:switch-when="1">one</div>' +
<add> '<div ng:switch-default>other</div>' +
<add> '</ng:switch>')($rootScope);
<add> $rootScope.$apply();
<ide> expect(element.text()).toEqual('other');
<del> scope.select = 1;
<del> scope.$apply();
<add> $rootScope.select = 1;
<add> $rootScope.$apply();
<ide> expect(element.text()).toEqual('one');
<del> });
<del>
<del> it('should call change on switch', function() {
<del> var scope = angular.compile('<ng:switch on="url" change="name=\'works\'"><div ng:switch-when="a">{{name}}</div></ng:switch>')();
<del> scope.url = 'a';
<del> scope.$apply();
<del> expect(scope.name).toEqual(undefined);
<del> expect(scope.$element.text()).toEqual('works');
<del> dealoc(scope);
<del> });
<del>
<del> });
<del>
<del>
<del> describe('ng:include', function() {
<del> it('should include on external file', function() {
<add> }));
<add>
<add>
<add> it('should call change on switch', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<ng:switch on="url" change="name=\'works\'">' +
<add> '<div ng:switch-when="a">{{name}}</div>' +
<add> '</ng:switch>')($rootScope);
<add> $rootScope.url = 'a';
<add> $rootScope.$apply();
<add> expect($rootScope.name).toEqual(undefined);
<add> expect(element.text()).toEqual('works');
<add> }));
<add> }));
<add>
<add>
<add> describe('ng:include', inject(function($rootScope) {
<add> it('should include on external file', inject(function($rootScope) {
<ide> var element = jqLite('<ng:include src="url" scope="childScope"></ng:include>');
<del> var scope = angular.compile(element)();
<del> scope.childScope = scope.$new();
<del> scope.childScope.name = 'misko';
<del> scope.url = 'myUrl';
<del> scope.$service('$xhr.cache').data.myUrl = {value:'{{name}}'};
<del> scope.$digest();
<add> var element = angular.compile(element)($rootScope);
<add> $rootScope.childScope = $rootScope.$new();
<add> $rootScope.childScope.name = 'misko';
<add> $rootScope.url = 'myUrl';
<add> $rootScope.$service('$xhr.cache').data.myUrl = {value:'{{name}}'};
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('misko');
<del> dealoc(scope);
<del> });
<add> }));
<ide>
<del> it('should remove previously included text if a falsy value is bound to src', function() {
<add>
<add> it('should remove previously included text if a falsy value is bound to src', inject(function($rootScope) {
<ide> var element = jqLite('<ng:include src="url" scope="childScope"></ng:include>');
<del> var scope = angular.compile(element)();
<del> scope.childScope = scope.$new();
<del> scope.childScope.name = 'igor';
<del> scope.url = 'myUrl';
<del> scope.$service('$xhr.cache').data.myUrl = {value:'{{name}}'};
<del> scope.$digest();
<add> var element = angular.compile(element)($rootScope);
<add> $rootScope.childScope = $rootScope.$new();
<add> $rootScope.childScope.name = 'igor';
<add> $rootScope.url = 'myUrl';
<add> $rootScope.$service('$xhr.cache').data.myUrl = {value:'{{name}}'};
<add> $rootScope.$digest();
<ide>
<ide> expect(element.text()).toEqual('igor');
<ide>
<del> scope.url = undefined;
<del> scope.$digest();
<add> $rootScope.url = undefined;
<add> $rootScope.$digest();
<ide>
<ide> expect(element.text()).toEqual('');
<del> dealoc(scope);
<del> });
<add> }));
<ide>
<del> it('should allow this for scope', function() {
<add>
<add> it('should allow this for scope', inject(function($rootScope) {
<ide> var element = jqLite('<ng:include src="url" scope="this"></ng:include>');
<del> var scope = angular.compile(element)();
<del> scope.url = 'myUrl';
<del> scope.$service('$xhr.cache').data.myUrl = {value:'{{"abc"}}'};
<del> scope.$digest();
<add> var element = angular.compile(element)($rootScope);
<add> $rootScope.url = 'myUrl';
<add> $rootScope.$service('$xhr.cache').data.myUrl = {value:'{{"abc"}}'};
<add> $rootScope.$digest();
<ide> // TODO(misko): because we are using scope==this, the eval gets registered
<ide> // during the flush phase and hence does not get called.
<ide> // I don't think passing 'this' makes sense. Does having scope on ng:include makes sense?
<del> // should we make scope="this" ilegal?
<del> scope.$digest();
<add> // should we make scope="this" illegal?
<add> $rootScope.$digest();
<ide>
<ide> expect(element.text()).toEqual('abc');
<del> dealoc(element);
<del> });
<add> }));
<ide>
<del> it('should evaluate onload expression when a partial is loaded', function() {
<add>
<add> it('should evaluate onload expression when a partial is loaded', inject(function($rootScope) {
<ide> var element = jqLite('<ng:include src="url" onload="loaded = true"></ng:include>');
<del> var scope = angular.compile(element)();
<add> var element = angular.compile(element)($rootScope);
<ide>
<del> expect(scope.loaded).not.toBeDefined();
<add> expect($rootScope.loaded).not.toBeDefined();
<ide>
<del> scope.url = 'myUrl';
<del> scope.$service('$xhr.cache').data.myUrl = {value:'my partial'};
<del> scope.$digest();
<add> $rootScope.url = 'myUrl';
<add> $rootScope.$service('$xhr.cache').data.myUrl = {value:'my partial'};
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('my partial');
<del> expect(scope.loaded).toBe(true);
<del> dealoc(element);
<del> });
<add> expect($rootScope.loaded).toBe(true);
<add> }));
<ide>
<del> it('should destroy old scope', function() {
<add>
<add> it('should destroy old scope', inject(function($rootScope) {
<ide> var element = jqLite('<ng:include src="url"></ng:include>');
<del> var scope = angular.compile(element)();
<add> var element = angular.compile(element)($rootScope);
<ide>
<del> expect(scope.$$childHead).toBeFalsy();
<add> expect($rootScope.$$childHead).toBeFalsy();
<ide>
<del> scope.url = 'myUrl';
<del> scope.$service('$xhr.cache').data.myUrl = {value:'my partial'};
<del> scope.$digest();
<del> expect(scope.$$childHead).toBeTruthy();
<add> $rootScope.url = 'myUrl';
<add> $rootScope.$service('$xhr.cache').data.myUrl = {value:'my partial'};
<add> $rootScope.$digest();
<add> expect($rootScope.$$childHead).toBeTruthy();
<ide>
<del> scope.url = null;
<del> scope.$digest();
<del> expect(scope.$$childHead).toBeFalsy();
<del> dealoc(element);
<del> });
<del> });
<add> $rootScope.url = null;
<add> $rootScope.$digest();
<add> expect($rootScope.$$childHead).toBeFalsy();
<add> }));
<add> }));
<ide>
<ide>
<del> describe('a', function() {
<del> it('should prevent default action to be executed when href is empty', function() {
<add> describe('a', inject(function($rootScope) {
<add> it('should prevent default action to be executed when href is empty', inject(function($rootScope) {
<ide> var orgLocation = document.location.href,
<ide> preventDefaultCalled = false,
<ide> event;
<ide>
<del> compile('<a href="">empty link</a>');
<add> var element = angular.compile('<a href="">empty link</a>')($rootScope);
<ide>
<ide> if (msie < 9) {
<ide>
<ide> describe("widget", function() {
<ide> }
<ide>
<ide> expect(document.location.href).toEqual(orgLocation);
<del> });
<del> });
<add> }));
<add> }));
<ide>
<ide>
<del> describe('@ng:repeat', function() {
<del> it('should ng:repeat over array', function() {
<del> var scope = compile('<ul><li ng:repeat="item in items" ng:init="suffix = \';\'" ng:bind="item + suffix"></li></ul>');
<add> describe('@ng:repeat', inject(function($rootScope) {
<add> it('should ng:repeat over array', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<ul>' +
<add> '<li ng:repeat="item in items" ng:init="suffix = \';\'" ng:bind="item + suffix"></li>' +
<add> '</ul>')($rootScope);
<ide>
<ide> Array.prototype.extraProperty = "should be ignored";
<ide> // INIT
<del> scope.items = ['misko', 'shyam'];
<del> scope.$digest();
<add> $rootScope.items = ['misko', 'shyam'];
<add> $rootScope.$digest();
<ide> expect(element.find('li').length).toEqual(2);
<ide> expect(element.text()).toEqual('misko;shyam;');
<ide> delete Array.prototype.extraProperty;
<ide>
<ide> // GROW
<del> scope.items = ['adam', 'kai', 'brad'];
<del> scope.$digest();
<add> $rootScope.items = ['adam', 'kai', 'brad'];
<add> $rootScope.$digest();
<ide> expect(element.find('li').length).toEqual(3);
<ide> expect(element.text()).toEqual('adam;kai;brad;');
<ide>
<ide> // SHRINK
<del> scope.items = ['brad'];
<del> scope.$digest();
<add> $rootScope.items = ['brad'];
<add> $rootScope.$digest();
<ide> expect(element.find('li').length).toEqual(1);
<ide> expect(element.text()).toEqual('brad;');
<del> });
<add> }));
<ide>
<del> it('should ng:repeat over object', function() {
<del> var scope = compile('<ul><li ng:repeat="(key, value) in items" ng:bind="key + \':\' + value + \';\' "></li></ul>');
<del> scope.items = {misko:'swe', shyam:'set'};
<del> scope.$digest();
<add> it('should ng:repeat over object', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<ul>' +
<add> '<li ng:repeat="(key, value) in items" ng:bind="key + \':\' + value + \';\' "></li>' +
<add> '</ul>')($rootScope);
<add> $rootScope.items = {misko:'swe', shyam:'set'};
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('misko:swe;shyam:set;');
<del> });
<add> }));
<ide>
<del> it('should not ng:repeat over parent properties', function() {
<add> it('should not ng:repeat over parent properties', inject(function($rootScope) {
<ide> var Class = function() {};
<ide> Class.prototype.abc = function() {};
<ide> Class.prototype.value = 'abc';
<ide>
<del> var scope = compile('<ul><li ng:repeat="(key, value) in items" ng:bind="key + \':\' + value + \';\' "></li></ul>');
<del> scope.items = new Class();
<del> scope.items.name = 'value';
<del> scope.$digest();
<add> var element = angular.compile(
<add> '<ul>' +
<add> '<li ng:repeat="(key, value) in items" ng:bind="key + \':\' + value + \';\' "></li>' +
<add> '</ul>')($rootScope);
<add> $rootScope.items = new Class();
<add> $rootScope.items.name = 'value';
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('name:value;');
<del> });
<add> }));
<ide>
<del> it('should error on wrong parsing of ng:repeat', function() {
<add> it('should error on wrong parsing of ng:repeat', inject(function($rootScope) {
<ide> expect(function() {
<del> compile('<ul><li ng:repeat="i dont parse"></li></ul>');
<add> var element = angular.compile('<ul><li ng:repeat="i dont parse"></li></ul>')($rootScope);
<ide> }).toThrow("Expected ng:repeat in form of '_item_ in _collection_' but got 'i dont parse'.");
<ide>
<ide> $logMock.error.logs.shift();
<del> });
<add> }));
<ide>
<del> it('should expose iterator offset as $index when iterating over arrays', function() {
<del> var scope = compile('<ul><li ng:repeat="item in items" ' +
<del> 'ng:bind="item + $index + \'|\'"></li></ul>');
<del> scope.items = ['misko', 'shyam', 'frodo'];
<del> scope.$digest();
<add> it('should expose iterator offset as $index when iterating over arrays', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<ul>' +
<add> '<li ng:repeat="item in items" ng:bind="item + $index + \'|\'"></li>' +
<add> '</ul>')($rootScope);
<add> $rootScope.items = ['misko', 'shyam', 'frodo'];
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('misko0|shyam1|frodo2|');
<del> });
<add> }));
<ide>
<del> it('should expose iterator offset as $index when iterating over objects', function() {
<del> var scope = compile('<ul><li ng:repeat="(key, val) in items" ' +
<del> 'ng:bind="key + \':\' + val + $index + \'|\'"></li></ul>');
<del> scope.items = {'misko':'m', 'shyam':'s', 'frodo':'f'};
<del> scope.$digest();
<add> it('should expose iterator offset as $index when iterating over objects', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<ul>' +
<add> '<li ng:repeat="(key, val) in items" ng:bind="key + \':\' + val + $index + \'|\'"></li>' +
<add> '</ul>')($rootScope);
<add> $rootScope.items = {'misko':'m', 'shyam':'s', 'frodo':'f'};
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('frodo:f0|misko:m1|shyam:s2|');
<del> });
<add> }));
<ide>
<del> it('should expose iterator position as $position when iterating over arrays', function() {
<del> var scope = compile('<ul><li ng:repeat="item in items" ' +
<del> 'ng:bind="item + \':\' + $position + \'|\'"></li></ul>');
<del> scope.items = ['misko', 'shyam', 'doug'];
<del> scope.$digest();
<add> it('should expose iterator position as $position when iterating over arrays',
<add> inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<ul>' +
<add> '<li ng:repeat="item in items" ng:bind="item + \':\' + $position + \'|\'"></li>' +
<add> '</ul>')($rootScope);
<add> $rootScope.items = ['misko', 'shyam', 'doug'];
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('misko:first|shyam:middle|doug:last|');
<ide>
<del> scope.items.push('frodo');
<del> scope.$digest();
<add> $rootScope.items.push('frodo');
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('misko:first|shyam:middle|doug:middle|frodo:last|');
<ide>
<del> scope.items.pop();
<del> scope.items.pop();
<del> scope.$digest();
<add> $rootScope.items.pop();
<add> $rootScope.items.pop();
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('misko:first|shyam:last|');
<del> });
<add> }));
<ide>
<del> it('should expose iterator position as $position when iterating over objects', function() {
<del> var scope = compile(
<add> it('should expose iterator position as $position when iterating over objects', inject(function($rootScope) {
<add> var element = angular.compile(
<ide> '<ul>' +
<ide> '<li ng:repeat="(key, val) in items" ng:bind="key + \':\' + val + \':\' + $position + \'|\'">' +
<ide> '</li>' +
<del> '</ul>');
<del> scope.items = {'misko':'m', 'shyam':'s', 'doug':'d', 'frodo':'f'};
<del> scope.$digest();
<add> '</ul>')($rootScope);
<add> $rootScope.items = {'misko':'m', 'shyam':'s', 'doug':'d', 'frodo':'f'};
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('doug:d:first|frodo:f:middle|misko:m:middle|shyam:s:last|');
<ide>
<del> delete scope.items.doug;
<del> delete scope.items.frodo;
<del> scope.$digest();
<add> delete $rootScope.items.doug;
<add> delete $rootScope.items.frodo;
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('misko:m:first|shyam:s:last|');
<del> });
<add> }));
<ide>
<del> it('should ignore $ and $$ properties', function() {
<del> var scope = compile('<ul><li ng:repeat="i in items">{{i}}|</li></ul>');
<del> scope.items = ['a', 'b', 'c'];
<del> scope.items.$$hashkey = 'xxx';
<del> scope.items.$root = 'yyy';
<del> scope.$digest();
<add> it('should ignore $ and $$ properties', inject(function($rootScope) {
<add> var element = angular.compile('<ul><li ng:repeat="i in items">{{i}}|</li></ul>')($rootScope);
<add> $rootScope.items = ['a', 'b', 'c'];
<add> $rootScope.items.$$hashkey = 'xxx';
<add> $rootScope.items.$root = 'yyy';
<add> $rootScope.$digest();
<ide>
<ide> expect(element.text()).toEqual('a|b|c|');
<del> });
<add> }));
<ide>
<del> it('should repeat over nested arrays', function() {
<del> var scope = compile('<ul>' +
<del> '<li ng:repeat="subgroup in groups">' +
<del> '<div ng:repeat="group in subgroup">{{group}}|</div>X' +
<del> '</li>' +
<del> '</ul>');
<del> scope.groups = [['a', 'b'], ['c','d']];
<del> scope.$digest();
<add> it('should repeat over nested arrays', inject(function($rootScope) {
<add> var element = angular.compile(
<add> '<ul>' +
<add> '<li ng:repeat="subgroup in groups">' +
<add> '<div ng:repeat="group in subgroup">{{group}}|</div>X' +
<add> '</li>' +
<add> '</ul>')($rootScope);
<add> $rootScope.groups = [['a', 'b'], ['c','d']];
<add> $rootScope.$digest();
<ide>
<ide> expect(element.text()).toEqual('a|b|Xc|d|X');
<del> });
<add> }));
<ide>
<del> it('should ignore non-array element properties when iterating over an array', function() {
<del> var scope = compile('<ul><li ng:repeat="item in array">{{item}}|</li></ul>');
<del> scope.array = ['a', 'b', 'c'];
<del> scope.array.foo = '23';
<del> scope.array.bar = function() {};
<del> scope.$digest();
<add> it('should ignore non-array element properties when iterating over an array', inject(function($rootScope) {
<add> var element = angular.compile('<ul><li ng:repeat="item in array">{{item}}|</li></ul>')($rootScope);
<add> $rootScope.array = ['a', 'b', 'c'];
<add> $rootScope.array.foo = '23';
<add> $rootScope.array.bar = function() {};
<add> $rootScope.$digest();
<ide>
<ide> expect(element.text()).toBe('a|b|c|');
<del> });
<add> }));
<ide>
<del> it('should iterate over non-existent elements of a sparse array', function() {
<del> var scope = compile('<ul><li ng:repeat="item in array">{{item}}|</li></ul>');
<del> scope.array = ['a', 'b'];
<del> scope.array[4] = 'c';
<del> scope.array[6] = 'd';
<del> scope.$digest();
<add> it('should iterate over non-existent elements of a sparse array', inject(function($rootScope) {
<add> var element = angular.compile('<ul><li ng:repeat="item in array">{{item}}|</li></ul>')($rootScope);
<add> $rootScope.array = ['a', 'b'];
<add> $rootScope.array[4] = 'c';
<add> $rootScope.array[6] = 'd';
<add> $rootScope.$digest();
<ide>
<ide> expect(element.text()).toBe('a|b|||c||d|');
<del> });
<add> }));
<ide>
<ide>
<ide> describe('stability', function() {
<del> var a, b, c, d, scope, lis;
<add> var a, b, c, d, lis, element;
<ide>
<del> beforeEach(function() {
<del> scope = compile(
<add> beforeEach(inject(function($rootScope) {
<add> element = angular.compile(
<ide> '<ul>' +
<del> '<li ng:repeat="item in items" ng:bind="key + \':\' + val + \':\' + $position + \'|\'">' +
<del> '</li>' +
<del> '</ul>');
<add> '<li ng:repeat="item in items" ng:bind="key + \':\' + val + \':\' + $position + \'|\'"></li>' +
<add> '</ul>')($rootScope);
<ide> a = {};
<ide> b = {};
<ide> c = {};
<ide> d = {};
<ide>
<del> scope.items = [a, b, c];
<del> scope.$digest();
<add> $rootScope.items = [a, b, c];
<add> $rootScope.$digest();
<ide> lis = element.find('li');
<del> });
<add> }));
<ide>
<del> it('should preserve the order of elements', function() {
<del> scope.items = [a, c, d];
<del> scope.$digest();
<add> it('should preserve the order of elements', inject(function($rootScope) {
<add> $rootScope.items = [a, c, d];
<add> $rootScope.$digest();
<ide> var newElements = element.find('li');
<ide> expect(newElements[0]).toEqual(lis[0]);
<ide> expect(newElements[1]).toEqual(lis[2]);
<ide> expect(newElements[2]).not.toEqual(lis[1]);
<del> });
<add> }));
<ide>
<del> it('should support duplicates', function() {
<del> scope.items = [a, a, b, c];
<del> scope.$digest();
<add> it('should support duplicates', inject(function($rootScope) {
<add> $rootScope.items = [a, a, b, c];
<add> $rootScope.$digest();
<ide> var newElements = element.find('li');
<ide> expect(newElements[0]).toEqual(lis[0]);
<ide> expect(newElements[1]).not.toEqual(lis[0]);
<ide> expect(newElements[2]).toEqual(lis[1]);
<ide> expect(newElements[3]).toEqual(lis[2]);
<ide>
<ide> lis = newElements;
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> newElements = element.find('li');
<ide> expect(newElements[0]).toEqual(lis[0]);
<ide> expect(newElements[1]).toEqual(lis[1]);
<ide> expect(newElements[2]).toEqual(lis[2]);
<ide> expect(newElements[3]).toEqual(lis[3]);
<ide>
<del> scope.$digest();
<add> $rootScope.$digest();
<ide> newElements = element.find('li');
<ide> expect(newElements[0]).toEqual(lis[0]);
<ide> expect(newElements[1]).toEqual(lis[1]);
<ide> expect(newElements[2]).toEqual(lis[2]);
<ide> expect(newElements[3]).toEqual(lis[3]);
<del> });
<add> }));
<ide>
<del> it('should remove last item when one duplicate instance is removed', function() {
<del> scope.items = [a, a, a];
<del> scope.$digest();
<add> it('should remove last item when one duplicate instance is removed', inject(function($rootScope) {
<add> $rootScope.items = [a, a, a];
<add> $rootScope.$digest();
<ide> lis = element.find('li');
<ide>
<del> scope.items = [a, a];
<del> scope.$digest();
<add> $rootScope.items = [a, a];
<add> $rootScope.$digest();
<ide> var newElements = element.find('li');
<ide> expect(newElements.length).toEqual(2);
<ide> expect(newElements[0]).toEqual(lis[0]);
<ide> expect(newElements[1]).toEqual(lis[1]);
<del> });
<add> }));
<ide>
<del> it('should reverse items when the collection is reversed', function() {
<del> scope.items = [a, b, c];
<del> scope.$digest();
<add> it('should reverse items when the collection is reversed', inject(function($rootScope) {
<add> $rootScope.items = [a, b, c];
<add> $rootScope.$digest();
<ide> lis = element.find('li');
<ide>
<del> scope.items = [c, b, a];
<del> scope.$digest();
<add> $rootScope.items = [c, b, a];
<add> $rootScope.$digest();
<ide> var newElements = element.find('li');
<ide> expect(newElements.length).toEqual(3);
<ide> expect(newElements[0]).toEqual(lis[2]);
<ide> expect(newElements[1]).toEqual(lis[1]);
<ide> expect(newElements[2]).toEqual(lis[0]);
<del> });
<add> }));
<ide> });
<del> });
<add> }));
<ide>
<ide>
<ide> describe('@ng:non-bindable', function() {
<del> it('should prevent compilation of the owning element and its children', function() {
<del> var scope = compile('<div ng:non-bindable><span ng:bind="name"></span></div>');
<del> scope.name = 'misko';
<del> scope.$digest();
<add> it('should prevent compilation of the owning element and its children', inject(function($rootScope) {
<add> var element = angular.compile('<div ng:non-bindable><span ng:bind="name"></span></div>')($rootScope);
<add> $rootScope.name = 'misko';
<add> $rootScope.$digest();
<ide> expect(element.text()).toEqual('');
<del> });
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('ng:view', function() {
<del> var rootScope, $route, $location, $browser;
<del>
<del> beforeEach(function() {
<del> rootScope = angular.compile('<ng:view></ng:view>')();
<del> $route = rootScope.$service('$route');
<del> $location = rootScope.$service('$location');
<del> $browser = rootScope.$service('$browser');
<del> });
<del>
<del> afterEach(function() {
<del> dealoc(rootScope);
<del> });
<add> var element;
<add> beforeEach(inject(function($rootScope) {
<add> element = angular.compile('<ng:view></ng:view>')($rootScope);
<add> }));
<ide>
<ide>
<del> it('should do nothing when no routes are defined', function() {
<add> it('should do nothing when no routes are defined', inject(function($rootScope, $location) {
<ide> $location.path('/unknown');
<del> rootScope.$digest();
<del> expect(rootScope.$element.text()).toEqual('');
<del> });
<add> $rootScope.$digest();
<add> expect(element.text()).toEqual('');
<add> }));
<ide>
<ide>
<del> it('should load content via xhr when route changes', function() {
<add> it('should load content via xhr when route changes', inject(function($rootScope, $browser, $location, $route) {
<ide> $route.when('/foo', {template: 'myUrl1'});
<ide> $route.when('/bar', {template: 'myUrl2'});
<ide>
<del> expect(rootScope.$element.text()).toEqual('');
<add> expect(element.text()).toEqual('');
<ide>
<ide> $location.path('/foo');
<ide> $browser.xhr.expectGET('myUrl1').respond('<div>{{1+3}}</div>');
<del> rootScope.$digest();
<add> $rootScope.$digest();
<ide> $browser.xhr.flush();
<del> expect(rootScope.$element.text()).toEqual('4');
<add> expect(element.text()).toEqual('4');
<ide>
<ide> $location.path('/bar');
<ide> $browser.xhr.expectGET('myUrl2').respond('angular is da best');
<del> rootScope.$digest();
<add> $rootScope.$digest();
<ide> $browser.xhr.flush();
<del> expect(rootScope.$element.text()).toEqual('angular is da best');
<del> });
<add> expect(element.text()).toEqual('angular is da best');
<add> }));
<ide>
<del> it('should remove all content when location changes to an unknown route', function() {
<add> it('should remove all content when location changes to an unknown route',
<add> inject(function($rootScope, $location, $browser, $route) {
<ide> $route.when('/foo', {template: 'myUrl1'});
<ide>
<ide> $location.path('/foo');
<ide> $browser.xhr.expectGET('myUrl1').respond('<div>{{1+3}}</div>');
<del> rootScope.$digest();
<add> $rootScope.$digest();
<ide> $browser.xhr.flush();
<del> expect(rootScope.$element.text()).toEqual('4');
<add> expect(element.text()).toEqual('4');
<ide>
<ide> $location.path('/unknown');
<del> rootScope.$digest();
<del> expect(rootScope.$element.text()).toEqual('');
<del> });
<add> $rootScope.$digest();
<add> expect($rootScope.$element.text()).toEqual('');
<add> }));
<ide>
<del> it('should chain scopes and propagate evals to the child scope', function() {
<add> it('should chain scopes and propagate evals to the child scope',
<add> inject(function($rootScope, $location, $browser, $route) {
<ide> $route.when('/foo', {template: 'myUrl1'});
<del> rootScope.parentVar = 'parent';
<add> $rootScope.parentVar = 'parent';
<ide>
<ide> $location.path('/foo');
<ide> $browser.xhr.expectGET('myUrl1').respond('<div>{{parentVar}}</div>');
<del> rootScope.$digest();
<add> $rootScope.$digest();
<ide> $browser.xhr.flush();
<del> expect(rootScope.$element.text()).toEqual('parent');
<del>
<del> rootScope.parentVar = 'new parent';
<del> rootScope.$digest();
<del> expect(rootScope.$element.text()).toEqual('new parent');
<del> });
<add> expect(element.text()).toEqual('parent');
<ide>
<del> it('should be possible to nest ng:view in ng:include', function() {
<del> dealoc(rootScope); // we are about to override it.
<add> $rootScope.parentVar = 'new parent';
<add> $rootScope.$digest();
<add> expect($rootScope.$element.text()).toEqual('new parent');
<add> }));
<ide>
<del> var myApp = angular.scope();
<add> it('should be possible to nest ng:view in ng:include', inject(function() {
<add> var injector = createInjector();
<add> var myApp = injector('$rootScope');
<ide> var $browser = myApp.$service('$browser');
<ide> $browser.xhr.expectGET('includePartial.html').respond('view: <ng:view></ng:view>');
<del> myApp.$service('$location').path('/foo');
<add> injector('$location').path('/foo');
<ide>
<del> var $route = myApp.$service('$route');
<add> var $route = injector('$route');
<ide> $route.when('/foo', {controller: angular.noop, template: 'viewPartial.html'});
<ide>
<del> rootScope = angular.compile(
<add> var element = angular.compile(
<ide> '<div>' +
<del> 'include: <ng:include src="\'includePartial.html\'">' +
<del> '</ng:include></div>')(myApp);
<del> rootScope.$apply();
<add> 'include: <ng:include src="\'includePartial.html\'"> </ng:include>' +
<add> '</div>')(myApp);
<add> myApp.$apply();
<ide>
<ide> $browser.xhr.expectGET('viewPartial.html').respond('content');
<del> rootScope.$digest();
<add> myApp.$digest();
<ide> $browser.xhr.flush();
<ide>
<del> expect(rootScope.$element.text()).toEqual('include: view: content');
<add> expect(myApp.$element.text()).toEqual('include: view: content');
<ide> expect($route.current.template).toEqual('viewPartial.html');
<del> dealoc($route.current.scope);
<del> });
<add> dealoc(myApp);
<add> }));
<ide>
<ide> it('should initialize view template after the view controller was initialized even when ' +
<del> 'templates were cached', function() {
<add> 'templates were cached', inject(function($rootScope, $location, $browser, $route) {
<ide> // this is a test for a regression that was introduced by making the ng:view cache sync
<ide>
<ide> $route.when('/foo', {controller: ParentCtrl, template: 'viewPartial.html'});
<ide>
<del> rootScope.log = [];
<add> $rootScope.log = [];
<ide>
<ide> function ParentCtrl() {
<ide> this.log.push('parent');
<ide> }
<ide>
<del> rootScope.ChildCtrl = function() {
<add> $rootScope.ChildCtrl = function() {
<ide> this.log.push('child');
<ide> };
<ide>
<ide> describe("widget", function() {
<ide> respond('<div ng:init="log.push(\'init\')">' +
<ide> '<div ng:controller="ChildCtrl"></div>' +
<ide> '</div>');
<del> rootScope.$apply();
<add> $rootScope.$apply();
<ide> $browser.xhr.flush();
<ide>
<del> expect(rootScope.log).toEqual(['parent', 'init', 'child']);
<add> expect($rootScope.log).toEqual(['parent', 'init', 'child']);
<ide>
<ide> $location.path('/');
<del> rootScope.$apply();
<del> expect(rootScope.log).toEqual(['parent', 'init', 'child']);
<add> $rootScope.$apply();
<add> expect($rootScope.log).toEqual(['parent', 'init', 'child']);
<ide>
<del> rootScope.log = [];
<add> $rootScope.log = [];
<ide> $location.path('/foo');
<del> rootScope.$apply();
<add> $rootScope.$apply();
<ide> $browser.defer.flush();
<ide>
<del> expect(rootScope.log).toEqual(['parent', 'init', 'child']);
<del> });
<add> expect($rootScope.log).toEqual(['parent', 'init', 'child']);
<add> }));
<ide>
<ide> it('should discard pending xhr callbacks if a new route is requested before the current ' +
<del> 'finished loading', function() {
<add> 'finished loading', inject(function($route, $rootScope, $location, $browser) {
<ide> // this is a test for a bad race condition that affected feedback
<ide>
<ide> $route.when('/foo', {template: 'myUrl1'});
<ide> $route.when('/bar', {template: 'myUrl2'});
<ide>
<del> expect(rootScope.$element.text()).toEqual('');
<add> expect($rootScope.$element.text()).toEqual('');
<ide>
<ide> $location.path('/foo');
<ide> $browser.xhr.expectGET('myUrl1').respond('<div>{{1+3}}</div>');
<del> rootScope.$digest();
<add> $rootScope.$digest();
<ide> $location.path('/bar');
<ide> $browser.xhr.expectGET('myUrl2').respond('<div>{{1+1}}</div>');
<del> rootScope.$digest();
<add> $rootScope.$digest();
<ide> $browser.xhr.flush(); // now that we have to requests pending, flush!
<ide>
<del> expect(rootScope.$element.text()).toEqual('2');
<del> });
<add> expect($rootScope.$element.text()).toEqual('2');
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('ng:pluralize', function() {
<ide>
<ide>
<ide> describe('deal with pluralized strings without offset', function() {
<del> beforeEach(function() {
<del> compile('<ng:pluralize count="email"' +
<del> "when=\"{'0': 'You have no new email'," +
<del> "'one': 'You have one new email'," +
<del> "'other': 'You have {} new emails'}\">" +
<del> '</ng:pluralize>');
<del> });
<del>
<del> it('should show single/plural strings', function() {
<del> scope.email = 0;
<del> scope.$digest();
<add> var element;
<add> beforeEach(inject(function($rootScope) {
<add> element = angular.compile(
<add> '<ng:pluralize count="email"' +
<add> "when=\"{'0': 'You have no new email'," +
<add> "'one': 'You have one new email'," +
<add> "'other': 'You have {} new emails'}\">" +
<add> '</ng:pluralize>')($rootScope);
<add> }));
<add>
<add> it('should show single/plural strings', inject(function($rootScope) {
<add> $rootScope.email = 0;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have no new email');
<ide>
<del> scope.email = '0';
<del> scope.$digest();
<add> $rootScope.email = '0';
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have no new email');
<ide>
<del> scope.email = 1;
<del> scope.$digest();
<add> $rootScope.email = 1;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have one new email');
<ide>
<del> scope.email = 0.01;
<del> scope.$digest();
<add> $rootScope.email = 0.01;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have 0.01 new emails');
<ide>
<del> scope.email = '0.1';
<del> scope.$digest();
<add> $rootScope.email = '0.1';
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have 0.1 new emails');
<ide>
<del> scope.email = 2;
<del> scope.$digest();
<add> $rootScope.email = 2;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have 2 new emails');
<ide>
<del> scope.email = -0.1;
<del> scope.$digest();
<add> $rootScope.email = -0.1;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have -0.1 new emails');
<ide>
<del> scope.email = '-0.01';
<del> scope.$digest();
<add> $rootScope.email = '-0.01';
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have -0.01 new emails');
<ide>
<del> scope.email = -2;
<del> scope.$digest();
<add> $rootScope.email = -2;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have -2 new emails');
<del> });
<add> }));
<ide>
<ide>
<del> it('should show single/plural strings with mal-formed inputs', function() {
<del> scope.email = '';
<del> scope.$digest();
<add> it('should show single/plural strings with mal-formed inputs', inject(function($rootScope) {
<add> $rootScope.email = '';
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('');
<ide>
<del> scope.email = null;
<del> scope.$digest();
<add> $rootScope.email = null;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('');
<ide>
<del> scope.email = undefined;
<del> scope.$digest();
<add> $rootScope.email = undefined;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('');
<ide>
<del> scope.email = 'a3';
<del> scope.$digest();
<add> $rootScope.email = 'a3';
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('');
<ide>
<del> scope.email = '011';
<del> scope.$digest();
<add> $rootScope.email = '011';
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have 11 new emails');
<ide>
<del> scope.email = '-011';
<del> scope.$digest();
<add> $rootScope.email = '-011';
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have -11 new emails');
<ide>
<del> scope.email = '1fff';
<del> scope.$digest();
<add> $rootScope.email = '1fff';
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have one new email');
<ide>
<del> scope.email = '0aa22';
<del> scope.$digest();
<add> $rootScope.email = '0aa22';
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have no new email');
<ide>
<del> scope.email = '000001';
<del> scope.$digest();
<add> $rootScope.email = '000001';
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('You have one new email');
<del> });
<add> }));
<ide> });
<ide>
<ide>
<ide> describe('deal with pluralized strings with offset', function() {
<del> it('should show single/plural strings with offset', function() {
<del> compile("<ng:pluralize count=\"viewCount\" offset=2 " +
<del> "when=\"{'0': 'Nobody is viewing.'," +
<del> "'1': '{{p1}} is viewing.'," +
<del> "'2': '{{p1}} and {{p2}} are viewing.'," +
<del> "'one': '{{p1}}, {{p2}} and one other person are viewing.'," +
<del> "'other': '{{p1}}, {{p2}} and {} other people are viewing.'}\">" +
<del> "</ng:pluralize>");
<del> scope.p1 = 'Igor';
<del> scope.p2 = 'Misko';
<del>
<del> scope.viewCount = 0;
<del> scope.$digest();
<add> it('should show single/plural strings with offset', inject(function($rootScope) {
<add> var element = angular.compile(
<add> "<ng:pluralize count=\"viewCount\" offset=2 " +
<add> "when=\"{'0': 'Nobody is viewing.'," +
<add> "'1': '{{p1}} is viewing.'," +
<add> "'2': '{{p1}} and {{p2}} are viewing.'," +
<add> "'one': '{{p1}}, {{p2}} and one other person are viewing.'," +
<add> "'other': '{{p1}}, {{p2}} and {} other people are viewing.'}\">" +
<add> "</ng:pluralize>")($rootScope);
<add> $rootScope.p1 = 'Igor';
<add> $rootScope.p2 = 'Misko';
<add>
<add> $rootScope.viewCount = 0;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('Nobody is viewing.');
<ide>
<del> scope.viewCount = 1;
<del> scope.$digest();
<add> $rootScope.viewCount = 1;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('Igor is viewing.');
<ide>
<del> scope.viewCount = 2;
<del> scope.$digest();
<add> $rootScope.viewCount = 2;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('Igor and Misko are viewing.');
<ide>
<del> scope.viewCount = 3;
<del> scope.$digest();
<add> $rootScope.viewCount = 3;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('Igor, Misko and one other person are viewing.');
<ide>
<del> scope.viewCount = 4;
<del> scope.$digest();
<add> $rootScope.viewCount = 4;
<add> $rootScope.$digest();
<ide> expect(element.text()).toBe('Igor, Misko and 2 other people are viewing.');
<del> });
<add> }));
<ide> });
<ide> });
<ide> }); | 51 |
Javascript | Javascript | ignore spec window when saving application state | eb60e44ca73f00e6ccca7aceca70ae3d79594f4f | <ide><path>src/main-process/atom-application.js
<ide> module.exports = class AtomApplication extends EventEmitter {
<ide> async saveCurrentWindowOptions(allowEmpty = false) {
<ide> if (this.quitting) return;
<ide>
<add> const windows = this.getAllWindows();
<add> const hasASpecWindow = windows.some(window => window.isSpec);
<add>
<add> if (windows.length === 1 && hasASpecWindow) return;
<add>
<ide> const state = {
<ide> version: APPLICATION_STATE_VERSION,
<del> windows: this.getAllWindows()
<add> windows: windows
<ide> .filter(window => !window.isSpec)
<ide> .map(window => ({ projectRoots: window.projectRoots }))
<ide> }; | 1 |
Text | Text | improve pagination docs. refs [ci skip] | 19b415ec25089d16d7b78c99712522adf6a5ea02 | <ide><path>docs/api-guide/pagination.md
<ide> Pagination can be turned off by setting the pagination class to `None`.
<ide>
<ide> ## Setting the pagination style
<ide>
<del>The default pagination style may be set globally, using the `DEFAULT_PAGINATION_CLASS` settings key. For example, to use the built-in limit/offset pagination, you would do:
<add>The default pagination style may be set globally, using the `DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` setting keys. For example, to use the built-in limit/offset pagination, you would do something like this:
<ide>
<ide> REST_FRAMEWORK = {
<del> 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'
<add> 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
<add> 'PAGE_SIZE': 100
<ide> }
<ide>
<add>Note that you need to set both the pagination class, and the page size that should be used.
<add>
<ide> You can also set the pagination class on an individual view by using the `pagination_class` attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis.
<ide>
<ide> ## Modifying the pagination style
<ide> To set these attributes you should override the `PageNumberPagination` class, an
<ide>
<ide> ## LimitOffsetPagination
<ide>
<del>This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an
<add>This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an
<ide> "offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the `page_size` in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items.
<ide>
<ide> **Request**: | 1 |
Javascript | Javascript | make writeafterfin() return false | 714a32c41f7cedec76cd7a237ac12f4cee7fcf85 | <ide><path>lib/net.js
<ide> function writeAfterFIN(chunk, encoding, cb) {
<ide> if (typeof cb === 'function') {
<ide> defaultTriggerAsyncIdScope(this[async_id_symbol], process.nextTick, cb, er);
<ide> }
<add>
<add> return false;
<ide> }
<ide>
<ide> Socket.prototype.setTimeout = setStreamTimeout;
<ide><path>test/parallel/test-net-write-after-end-nt.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide>
<del>const { mustCall } = common;
<add>const { expectsError, mustCall } = common;
<ide>
<ide> // This test ensures those errors caused by calling `net.Socket.write()`
<ide> // after sockets ending will be emitted in the next tick.
<ide> const server = net.createServer(mustCall((socket) => {
<ide> server.close();
<ide> }));
<ide> client.on('end', mustCall(() => {
<del> client.write('hello', mustCall());
<add> const ret = client.write('hello', expectsError({
<add> code: 'EPIPE',
<add> message: 'This socket has been ended by the other party',
<add> type: Error
<add> }));
<add>
<add> assert.strictEqual(ret, false);
<ide> assert(!hasError, 'The error should be emitted in the next tick.');
<ide> }));
<ide> client.end(); | 2 |
Python | Python | fix layoutlmv3 documentation | 4c8ec66a7433589436d13d95d48601f274c92b44 | <ide><path>src/transformers/models/layoutlmv3/modeling_layoutlmv3.py
<ide> behavior.
<ide>
<ide> Parameters:
<del> config ([`LayoutLMv2Config`]): Model configuration class with all the parameters of the model.
<add> config ([`LayoutLMv3Config`]): Model configuration class with all the parameters of the model.
<ide> Initializing with a config file does not load the weights associated with the model, only the
<ide> configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
<ide> """
<ide>
<del>LAYOUTLMV3_INPUTS_DOCSTRING = r"""
<add>LAYOUTLMV3_MODEL_INPUTS_DOCSTRING = r"""
<ide> Args:
<del> input_ids (`torch.LongTensor` of shape `{0}`):
<add> input_ids (`torch.LongTensor` of shape `({0})`):
<ide> Indices of input sequence tokens in the vocabulary.
<ide>
<del> Indices can be obtained using [`LayoutLMv2Tokenizer`]. See [`PreTrainedTokenizer.encode`] and
<add> Note that `sequence_length = token_sequence_length + patch_sequence_length + 1` where `1` is for [CLS]
<add> token. See `pixel_values` for `patch_sequence_length`.
<add>
<add> Indices can be obtained using [`LayoutLMv3Tokenizer`]. See [`PreTrainedTokenizer.encode`] and
<add> [`PreTrainedTokenizer.__call__`] for details.
<add>
<add> [What are input IDs?](../glossary#input-ids)
<add>
<add> bbox (`torch.LongTensor` of shape `({0}, 4)`, *optional*):
<add> Bounding boxes of each input sequence tokens. Selected in the range `[0,
<add> config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
<add> format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
<add> y1) represents the position of the lower right corner.
<add>
<add> Note that `sequence_length = token_sequence_length + patch_sequence_length + 1` where `1` is for [CLS]
<add> token. See `pixel_values` for `patch_sequence_length`.
<add>
<add> pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
<add> Batch of document images. Each image is divided into patches of shape `(num_channels, config.patch_size,
<add> config.patch_size)` and the total number of patches (=`patch_sequence_length`) equals to `((height /
<add> config.patch_size) * (width / config.patch_size))`.
<add>
<add> attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
<add> Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
<add>
<add> - 1 for tokens that are **not masked**,
<add> - 0 for tokens that are **masked**.
<add>
<add> Note that `sequence_length = token_sequence_length + patch_sequence_length + 1` where `1` is for [CLS]
<add> token. See `pixel_values` for `patch_sequence_length`.
<add>
<add> [What are attention masks?](../glossary#attention-mask)
<add> token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
<add> Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
<add> 1]`:
<add>
<add> - 0 corresponds to a *sentence A* token,
<add> - 1 corresponds to a *sentence B* token.
<add>
<add> Note that `sequence_length = token_sequence_length + patch_sequence_length + 1` where `1` is for [CLS]
<add> token. See `pixel_values` for `patch_sequence_length`.
<add>
<add> [What are token type IDs?](../glossary#token-type-ids)
<add> position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
<add> Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
<add> config.max_position_embeddings - 1]`.
<add>
<add> Note that `sequence_length = token_sequence_length + patch_sequence_length + 1` where `1` is for [CLS]
<add> token. See `pixel_values` for `patch_sequence_length`.
<add>
<add> [What are position IDs?](../glossary#position-ids)
<add> head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
<add> Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
<add>
<add> - 1 indicates the head is **not masked**,
<add> - 0 indicates the head is **masked**.
<add>
<add> inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
<add> Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
<add> is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
<add> model's internal embedding lookup matrix.
<add> output_attentions (`bool`, *optional*):
<add> Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
<add> tensors for more detail.
<add> output_hidden_states (`bool`, *optional*):
<add> Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
<add> more detail.
<add> return_dict (`bool`, *optional*):
<add> Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
<add>"""
<add>
<add>LAYOUTLMV3_DOWNSTREAM_INPUTS_DOCSTRING = r"""
<add> Args:
<add> input_ids (`torch.LongTensor` of shape `({0})`):
<add> Indices of input sequence tokens in the vocabulary.
<add>
<add> Indices can be obtained using [`LayoutLMv3Tokenizer`]. See [`PreTrainedTokenizer.encode`] and
<ide> [`PreTrainedTokenizer.__call__`] for details.
<ide>
<ide> [What are input IDs?](../glossary#input-ids)
<ide> y1) represents the position of the lower right corner.
<ide>
<ide> pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
<del> Batch of document images.
<add> Batch of document images. Each image is divided into patches of shape `(num_channels, config.patch_size,
<add> config.patch_size)` and the total number of patches (=`patch_sequence_length`) equals to `((height /
<add> config.patch_size) * (width / config.patch_size))`.
<ide>
<del> attention_mask (`torch.FloatTensor` of shape `{0}`, *optional*):
<add> attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
<ide> Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
<ide>
<ide> - 1 for tokens that are **not masked**,
<ide> - 0 for tokens that are **masked**.
<ide>
<ide> [What are attention masks?](../glossary#attention-mask)
<del> token_type_ids (`torch.LongTensor` of shape `{0}`, *optional*):
<add> token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
<ide> Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
<ide> 1]`:
<ide>
<ide> - 0 corresponds to a *sentence A* token,
<ide> - 1 corresponds to a *sentence B* token.
<ide>
<ide> [What are token type IDs?](../glossary#token-type-ids)
<del> position_ids (`torch.LongTensor` of shape `{0}`, *optional*):
<add> position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
<ide> Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
<ide> config.max_position_embeddings - 1]`.
<ide>
<ide> - 1 indicates the head is **not masked**,
<ide> - 0 indicates the head is **masked**.
<ide>
<del> inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
<add> inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
<ide> Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
<ide> is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
<ide> model's internal embedding lookup matrix.
<ide> def forward_image(self, pixel_values):
<ide>
<ide> return embeddings
<ide>
<del> @add_start_docstrings_to_model_forward(LAYOUTLMV3_INPUTS_DOCSTRING.format("(batch_size, sequence_length)"))
<add> @add_start_docstrings_to_model_forward(
<add> LAYOUTLMV3_MODEL_INPUTS_DOCSTRING.format("batch_size, token_sequence_length")
<add> )
<ide> @replace_return_docstrings(output_type=BaseModelOutput, config_class=_CONFIG_FOR_DOC)
<ide> def forward(
<ide> self,
<ide> def __init__(self, config):
<ide>
<ide> self.init_weights()
<ide>
<del> @add_start_docstrings_to_model_forward(LAYOUTLMV3_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
<add> @add_start_docstrings_to_model_forward(
<add> LAYOUTLMV3_DOWNSTREAM_INPUTS_DOCSTRING.format("batch_size, sequence_length")
<add> )
<ide> @replace_return_docstrings(output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC)
<ide> def forward(
<ide> self,
<ide> def __init__(self, config):
<ide>
<ide> self.init_weights()
<ide>
<del> @add_start_docstrings_to_model_forward(LAYOUTLMV3_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
<add> @add_start_docstrings_to_model_forward(
<add> LAYOUTLMV3_DOWNSTREAM_INPUTS_DOCSTRING.format("batch_size, sequence_length")
<add> )
<ide> @replace_return_docstrings(output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC)
<ide> def forward(
<ide> self,
<ide> def __init__(self, config):
<ide>
<ide> self.init_weights()
<ide>
<del> @add_start_docstrings_to_model_forward(LAYOUTLMV3_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
<add> @add_start_docstrings_to_model_forward(
<add> LAYOUTLMV3_DOWNSTREAM_INPUTS_DOCSTRING.format("batch_size, sequence_length")
<add> )
<ide> @replace_return_docstrings(output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
<ide> def forward(
<ide> self, | 1 |
Python | Python | add regression test for gh-6922 | fe46c47a96e191b028823280fe3451a48d0fc18e | <ide><path>numpy/core/tests/test_regression.py
<ide> def test_empty_percentile(self):
<ide> # gh-6530 / gh-6553
<ide> assert_array_equal(np.percentile(np.arange(10), []), np.array([]))
<ide>
<add> def test_void_compare_segfault(self):
<add> # gh-6922. The following should not segfault
<add> a = np.ones(3, dtype=[('object', 'O'), ('int', '<i2')])
<add> a.sort()
<add>
<add>
<ide> if __name__ == "__main__":
<ide> run_module_suite() | 1 |
Text | Text | clarify environment_name for logs | 15a18c18e496c8fb46ee21d8a1af0c4012abc5f5 | <ide><path>guides/source/debugging_rails_applications.md
<ide> config.logger = Logger.new(STDOUT)
<ide> config.logger = Log4r::Logger.new("Application Log")
<ide> ```
<ide>
<del>TIP: By default, each log is created under `Rails.root/log/` and the log file name is `environment_name.log`.
<add>TIP: By default, each log is created under `Rails.root/log/` and the log file name is `environment_name.log`. example `production.log`, `development.log` etc.
<ide>
<ide> ### Log Levels
<ide> | 1 |
Go | Go | remove obsolete comment | 4cdb796b5453d4c2fe7dde85cadd2a56725e3452 | <ide><path>pkg/system/syscall_windows.go
<ide> func GetOSVersion() OSVersion {
<ide> }
<ide>
<ide> // IsWindowsClient returns true if the SKU is client
<del>// @engine maintainers - this function should not be removed or modified as it
<del>// is used to enforce licensing restrictions on Windows.
<ide> func IsWindowsClient() bool {
<ide> osviex := &osVersionInfoEx{OSVersionInfoSize: 284}
<ide> r1, _, err := procGetVersionExW.Call(uintptr(unsafe.Pointer(osviex))) | 1 |
Javascript | Javascript | remove un-helpful error in with-sentry example | 167a91b73e048211a855b38f50e7f551cdddd4cb | <ide><path>examples/with-sentry/pages/_error.js
<ide> const MyError = ({ statusCode, hasGetInitialPropsRun, err }) => {
<ide> return <NextErrorComponent statusCode={statusCode} />
<ide> }
<ide>
<del>MyError.getInitialProps = async ({ res, err, asPath }) => {
<add>MyError.getInitialProps = async ({ res, err }) => {
<ide> const errorInitialProps = await NextErrorComponent.getInitialProps({
<ide> res,
<ide> err,
<ide> MyError.getInitialProps = async ({ res, err, asPath }) => {
<ide> }
<ide>
<ide> // If this point is reached, getInitialProps was called without any
<del> // information about what the error might be. This is unexpected and may
<del> // indicate a bug introduced in Next.js, so record it in Sentry
<del> Sentry.captureException(
<del> new Error(`_error.js getInitialProps missing data at path: ${asPath}`)
<del> )
<del> await Sentry.flush(2000)
<del>
<add> // information about what the error might be. This can be caused by
<add> // a falsy value being thrown e.g. throw undefined
<ide> return errorInitialProps
<ide> }
<ide> | 1 |
PHP | PHP | fix failing testcase | 3a183849298e606475af8a606cb2c3a9c512ad8c | <ide><path>lib/Cake/Test/Case/Routing/Filter/AssetDispatcherTest.php
<ide> public function testNotModified() {
<ide> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<ide> ));
<ide> $time = filemtime(App::themePath('TestTheme') . 'webroot' . DS . 'img' . DS . 'cake.power.gif');
<del> $time = new DateTime(date('Y-m-d H:i:s', $time), new DateTimeZone('UTC'));
<add> $time = new DateTime('@' . $time);
<ide>
<ide> $response = $this->getMock('CakeResponse', array('send', 'checkNotModified'));
<ide> $request = new CakeRequest('theme/test_theme/img/cake.power.gif'); | 1 |
Javascript | Javascript | remove event simulation of onchange events | 32f6f258bad524ec3886901a5b132887f8dd7553 | <ide><path>packages/react-dom/src/__tests__/ReactDOMInput-test.js
<ide> describe('ReactDOMInput', () => {
<ide> let React;
<ide> let ReactDOM;
<ide> let ReactDOMServer;
<del> let ReactTestUtils;
<ide> let setUntrackedValue;
<add> let setUntrackedChecked;
<add> let container;
<ide>
<ide> function dispatchEventOnNode(node, type) {
<ide> node.dispatchEvent(new Event(type, {bubbles: true, cancelable: true}));
<ide> describe('ReactDOMInput', () => {
<ide> HTMLInputElement.prototype,
<ide> 'value',
<ide> ).set;
<add> setUntrackedChecked = Object.getOwnPropertyDescriptor(
<add> HTMLInputElement.prototype,
<add> 'checked',
<add> ).set;
<ide>
<ide> React = require('react');
<ide> ReactDOM = require('react-dom');
<ide> ReactDOMServer = require('react-dom/server');
<del> ReactTestUtils = require('react-dom/test-utils');
<add>
<add> container = document.createElement('div');
<add> document.body.appendChild(container);
<add> });
<add>
<add> afterEach(() => {
<add> document.body.removeChild(container);
<ide> });
<ide>
<ide> it('should properly control a value even if no event listener exists', () => {
<del> const container = document.createElement('div');
<ide> let node;
<ide>
<ide> expect(() => {
<ide> describe('ReactDOMInput', () => {
<ide> 'Failed prop type: You provided a `value` prop to a form field without an `onChange` handler.',
<ide> );
<ide>
<del> document.body.appendChild(container);
<del>
<del> try {
<del> setUntrackedValue.call(node, 'giraffe');
<add> setUntrackedValue.call(node, 'giraffe');
<ide>
<del> // This must use the native event dispatching. If we simulate, we will
<del> // bypass the lazy event attachment system so we won't actually test this.
<del> dispatchEventOnNode(node, 'change');
<add> // This must use the native event dispatching. If we simulate, we will
<add> // bypass the lazy event attachment system so we won't actually test this.
<add> dispatchEventOnNode(node, 'input');
<ide>
<del> expect(node.value).toBe('lion');
<del> } finally {
<del> document.body.removeChild(container);
<del> }
<add> expect(node.value).toBe('lion');
<ide> });
<ide>
<ide> it('should control a value in reentrant events', () => {
<ide> describe('ReactDOMInput', () => {
<ide> // Calling focus here will blur the text box which causes a native
<ide> // change event. Ideally we shouldn't have to fire this ourselves.
<ide> // Don't remove unless you've verified the fix in #8240 is still covered.
<del> dispatchEventOnNode(this.a, 'change');
<add> dispatchEventOnNode(this.a, 'input');
<ide> this.b.focus();
<ide> }
<ide> blur(currentValue) {
<ide> describe('ReactDOMInput', () => {
<ide> }
<ide> }
<ide>
<del> const container = document.createElement('div');
<ide> const instance = ReactDOM.render(<ControlledInputs />, container);
<ide>
<del> // We need it to be in the body to test native event dispatching.
<del> document.body.appendChild(container);
<del>
<ide> // Focus the field so we can later blur it.
<ide> // Don't remove unless you've verified the fix in #8240 is still covered.
<ide> instance.a.focus();
<ide> setUntrackedValue.call(instance.a, 'giraffe');
<ide> // This must use the native event dispatching. If we simulate, we will
<ide> // bypass the lazy event attachment system so we won't actually test this.
<del> dispatchEventOnNode(instance.a, 'change');
<add> dispatchEventOnNode(instance.a, 'input');
<ide> dispatchEventOnNode(instance.a, 'blur');
<ide>
<ide> expect(instance.a.value).toBe('giraffe');
<ide> expect(instance.switchedFocus).toBe(true);
<del>
<del> document.body.removeChild(container);
<ide> });
<ide>
<ide> it('should control values in reentrant events with different targets', () => {
<ide> describe('ReactDOMInput', () => {
<ide> }
<ide> }
<ide>
<del> const container = document.createElement('div');
<ide> const instance = ReactDOM.render(<ControlledInputs />, container);
<ide>
<del> // We need it to be in the body to test native event dispatching.
<del> document.body.appendChild(container);
<del>
<ide> setUntrackedValue.call(instance.a, 'giraffe');
<ide> // This must use the native event dispatching. If we simulate, we will
<ide> // bypass the lazy event attachment system so we won't actually test this.
<ide> dispatchEventOnNode(instance.a, 'input');
<ide>
<ide> expect(instance.a.value).toBe('lion');
<ide> expect(instance.b.checked).toBe(true);
<del>
<del> document.body.removeChild(container);
<ide> });
<ide>
<ide> describe('switching text inputs between numeric and string numbers', () => {
<ide> it('does change the number 2 to "2.0" with no change handler', () => {
<ide> const stub = <input type="text" value={2} onChange={jest.fn()} />;
<del> const node = ReactTestUtils.renderIntoDocument(stub);
<add> const node = ReactDOM.render(stub, container);
<ide>
<del> node.value = '2.0';
<add> setUntrackedValue.call(node, '2.0');
<ide>
<del> ReactTestUtils.Simulate.change(node);
<add> dispatchEventOnNode(node, 'input');
<ide>
<ide> expect(node.getAttribute('value')).toBe('2');
<ide> expect(node.value).toBe('2');
<ide> });
<ide>
<ide> it('does change the string "2" to "2.0" with no change handler', () => {
<ide> const stub = <input type="text" value={'2'} onChange={jest.fn()} />;
<del> const node = ReactTestUtils.renderIntoDocument(stub);
<add> const node = ReactDOM.render(stub, container);
<ide>
<del> node.value = '2.0';
<add> setUntrackedValue.call(node, '2.0');
<ide>
<del> ReactTestUtils.Simulate.change(node);
<add> dispatchEventOnNode(node, 'input');
<ide>
<ide> expect(node.getAttribute('value')).toBe('2');
<ide> expect(node.value).toBe('2');
<ide> describe('ReactDOMInput', () => {
<ide> }
<ide> }
<ide>
<del> const stub = ReactTestUtils.renderIntoDocument(<Stub />);
<add> const stub = ReactDOM.render(<Stub />, container);
<ide> const node = ReactDOM.findDOMNode(stub);
<ide>
<del> node.value = '2.0';
<add> setUntrackedValue.call(node, '2.0');
<ide>
<del> ReactTestUtils.Simulate.change(node);
<add> dispatchEventOnNode(node, 'input');
<ide>
<ide> expect(node.getAttribute('value')).toBe('2.0');
<ide> expect(node.value).toBe('2.0');
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> let stub;
<ide> expect(() => {
<del> stub = ReactTestUtils.renderIntoDocument(<Stub />);
<add> stub = ReactDOM.render(<Stub />, container);
<ide> }).toWarnDev(
<ide> 'You provided a `value` prop to a form field ' +
<ide> 'without an `onChange` handler.',
<ide> describe('ReactDOMInput', () => {
<ide> }
<ide> }
<ide>
<del> const stub = ReactTestUtils.renderIntoDocument(<Stub />);
<add> const stub = ReactDOM.render(<Stub />, container);
<ide> const node = ReactDOM.findDOMNode(stub);
<ide> stub.setState({value: 0});
<ide>
<ide> expect(node.value).toEqual('0');
<ide> });
<ide>
<ide> it('updates the value on radio buttons from "" to 0', function() {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(
<ide> <input type="radio" value="" onChange={function() {}} />,
<ide> container,
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('updates the value on checkboxes from "" to 0', function() {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(
<ide> <input type="checkbox" value="" onChange={function() {}} />,
<ide> container,
<ide> describe('ReactDOMInput', () => {
<ide> let stub;
<ide>
<ide> expect(() => {
<del> stub = ReactTestUtils.renderIntoDocument(<Stub />);
<add> stub = ReactDOM.render(<Stub />, container);
<ide> }).toWarnDev(
<ide> 'You provided a `value` prop to a form field ' +
<ide> 'without an `onChange` handler.',
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should display `defaultValue` of number 0', () => {
<ide> let stub = <input type="text" defaultValue={0} />;
<del> const node = ReactTestUtils.renderIntoDocument(stub);
<add> const node = ReactDOM.render(stub, container);
<ide>
<ide> expect(node.getAttribute('value')).toBe('0');
<ide> expect(node.value).toBe('0');
<ide> describe('ReactDOMInput', () => {
<ide> }
<ide> }
<ide>
<del> const component = ReactTestUtils.renderIntoDocument(<Test />);
<add> const component = ReactDOM.render(<Test />, container);
<ide> const node = ReactDOM.findDOMNode(component);
<ide>
<ide> Object.defineProperty(node, 'defaultValue', {
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should display "true" for `defaultValue` of `true`', () => {
<ide> let stub = <input type="text" defaultValue={true} />;
<del> const node = ReactTestUtils.renderIntoDocument(stub);
<add> const node = ReactDOM.render(stub, container);
<ide>
<ide> expect(node.value).toBe('true');
<ide> });
<ide>
<ide> it('should display "false" for `defaultValue` of `false`', () => {
<ide> let stub = <input type="text" defaultValue={false} />;
<del> const node = ReactTestUtils.renderIntoDocument(stub);
<add> const node = ReactDOM.render(stub, container);
<ide>
<ide> expect(node.value).toBe('false');
<ide> });
<ide>
<ide> it('should update `defaultValue` for uncontrolled input', () => {
<del> const container = document.createElement('div');
<del>
<ide> const node = ReactDOM.render(
<ide> <input type="text" defaultValue="0" />,
<ide> container,
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should update `defaultValue` for uncontrolled date/time input', () => {
<del> const container = document.createElement('div');
<del>
<ide> const node = ReactDOM.render(
<ide> <input type="date" defaultValue="1980-01-01" />,
<ide> container,
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should take `defaultValue` when changing to uncontrolled input', () => {
<del> const container = document.createElement('div');
<ide> const node = ReactDOM.render(
<ide> <input type="text" value="0" readOnly="true" />,
<ide> container,
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should render name attribute if it is supplied', () => {
<del> const container = document.createElement('div');
<ide> const node = ReactDOM.render(<input type="text" name="name" />, container);
<ide> expect(node.name).toBe('name');
<ide> expect(container.firstChild.getAttribute('name')).toBe('name');
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should not render name attribute if it is not supplied', () => {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input type="text" />, container);
<ide> expect(container.firstChild.getAttribute('name')).toBe(null);
<ide> });
<ide> describe('ReactDOMInput', () => {
<ide> };
<ide>
<ide> const stub = <input type="text" defaultValue={objToString} />;
<del> const node = ReactTestUtils.renderIntoDocument(stub);
<add> const node = ReactDOM.render(stub, container);
<ide>
<ide> expect(node.value).toBe('foobar');
<ide> });
<ide>
<ide> it('should display `value` of number 0', () => {
<ide> const stub = <input type="text" value={0} />;
<del> const node = ReactTestUtils.renderIntoDocument(stub);
<add> const node = ReactDOM.render(stub, container);
<ide>
<ide> expect(node.value).toBe('0');
<ide> });
<ide>
<ide> it('should allow setting `value` to `true`', () => {
<del> const container = document.createElement('div');
<ide> let stub = <input type="text" value="yolo" onChange={emptyFunction} />;
<ide> const node = ReactDOM.render(stub, container);
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should allow setting `value` to `false`', () => {
<del> const container = document.createElement('div');
<ide> let stub = <input type="text" value="yolo" onChange={emptyFunction} />;
<ide> const node = ReactDOM.render(stub, container);
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should allow setting `value` to `objToString`', () => {
<del> const container = document.createElement('div');
<ide> let stub = <input type="text" value="foo" onChange={emptyFunction} />;
<ide> const node = ReactDOM.render(stub, container);
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should not incur unnecessary DOM mutations', () => {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input value="a" onChange={() => {}} />, container);
<ide>
<ide> const node = container.firstChild;
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should not incur unnecessary DOM mutations for numeric type conversion', () => {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input value="0" onChange={() => {}} />, container);
<ide>
<ide> const node = container.firstChild;
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should not incur unnecessary DOM mutations for the boolean type conversion', () => {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input value="true" onChange={() => {}} />, container);
<ide>
<ide> const node = container.firstChild;
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should properly control a value of number `0`', () => {
<ide> const stub = <input type="text" value={0} onChange={emptyFunction} />;
<del> const node = ReactTestUtils.renderIntoDocument(stub);
<add> const node = ReactDOM.render(stub, container);
<ide>
<del> node.value = 'giraffe';
<del> ReactTestUtils.Simulate.change(node);
<add> setUntrackedValue.call(node, 'giraffe');
<add> dispatchEventOnNode(node, 'input');
<ide> expect(node.value).toBe('0');
<ide> });
<ide>
<ide> it('should properly control 0.0 for a text input', () => {
<ide> const stub = <input type="text" value={0} onChange={emptyFunction} />;
<del> const node = ReactTestUtils.renderIntoDocument(stub);
<add> const node = ReactDOM.render(stub, container);
<ide>
<del> node.value = '0.0';
<del> ReactTestUtils.Simulate.change(node, {target: {value: '0.0'}});
<add> setUntrackedValue.call(node, '0.0');
<add> dispatchEventOnNode(node, 'input');
<ide> expect(node.value).toBe('0');
<ide> });
<ide>
<ide> it('should properly control 0.0 for a number input', () => {
<ide> const stub = <input type="number" value={0} onChange={emptyFunction} />;
<del> const node = ReactTestUtils.renderIntoDocument(stub);
<add> const node = ReactDOM.render(stub, container);
<ide>
<del> node.value = '0.0';
<del> ReactTestUtils.Simulate.change(node, {target: {value: '0.0'}});
<add> setUntrackedValue.call(node, '0.0');
<add> dispatchEventOnNode(node, 'input');
<ide> expect(node.value).toBe('0.0');
<ide> });
<ide>
<ide> it('should properly transition from an empty value to 0', function() {
<del> const container = document.createElement('div');
<del>
<ide> ReactDOM.render(<input type="text" value="" />, container);
<ide> ReactDOM.render(<input type="text" value={0} />, container);
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should properly transition from 0 to an empty value', function() {
<del> const container = document.createElement('div');
<del>
<ide> ReactDOM.render(<input type="text" value={0} />, container);
<ide> ReactDOM.render(<input type="text" value="" />, container);
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should properly transition a text input from 0 to an empty 0.0', function() {
<del> const container = document.createElement('div');
<del>
<ide> ReactDOM.render(<input type="text" value={0} />, container);
<ide> ReactDOM.render(<input type="text" value="0.0" />, container);
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should properly transition a number input from "" to 0', function() {
<del> const container = document.createElement('div');
<del>
<ide> ReactDOM.render(<input type="number" value="" />, container);
<ide> ReactDOM.render(<input type="number" value={0} />, container);
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should properly transition a number input from "" to "0"', function() {
<del> const container = document.createElement('div');
<del>
<ide> ReactDOM.render(<input type="number" value="" />, container);
<ide> ReactDOM.render(<input type="number" value="0" />, container);
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> handled = true;
<ide> };
<ide> const stub = <input type="text" value={0} onChange={handler} />;
<del> const container = document.createElement('div');
<ide> const node = ReactDOM.render(stub, container);
<ide>
<ide> setUntrackedValue.call(node, 'giraffe');
<ide>
<del> ReactTestUtils.SimulateNative.input(node, {
<del> path: [node, container],
<del> });
<add> dispatchEventOnNode(node, 'input');
<ide>
<ide> expect(handled).toBe(true);
<ide> });
<ide>
<ide> it('should not set a value for submit buttons unnecessarily', () => {
<ide> const stub = <input type="submit" />;
<del> const node = ReactTestUtils.renderIntoDocument(stub);
<add> const node = ReactDOM.render(stub, container);
<ide>
<ide> // The value shouldn't be '', or else the button will have no text; it
<ide> // should have the default "Submit" or "Submit Query" label. Most browsers
<ide> describe('ReactDOMInput', () => {
<ide> }
<ide> }
<ide>
<del> const stub = ReactTestUtils.renderIntoDocument(<RadioGroup />);
<add> const stub = ReactDOM.render(<RadioGroup />, container);
<ide> const aNode = stub.refs.a;
<ide> const bNode = stub.refs.b;
<ide> const cNode = stub.refs.c;
<ide> describe('ReactDOMInput', () => {
<ide> expect(cNode.checked).toBe(true);
<ide> expect(cNode.hasAttribute('checked')).toBe(true);
<ide>
<del> bNode.checked = true;
<del> // This next line isn't necessary in a proper browser environment, but
<del> // jsdom doesn't uncheck the others in a group (which makes this whole test
<del> // a little less effective)
<del> aNode.checked = false;
<add> setUntrackedChecked.call(bNode, true);
<add> expect(aNode.checked).toBe(false);
<ide> expect(cNode.checked).toBe(true);
<ide>
<ide> // The original 'checked' attribute should be unchanged
<ide> describe('ReactDOMInput', () => {
<ide> expect(cNode.hasAttribute('checked')).toBe(true);
<ide>
<ide> // Now let's run the actual ReactDOMInput change event handler
<del> ReactTestUtils.Simulate.change(bNode);
<add> dispatchEventOnNode(bNode, 'click');
<ide>
<ide> // The original state should have been restored
<ide> expect(aNode.checked).toBe(true);
<ide> describe('ReactDOMInput', () => {
<ide> }
<ide> }
<ide>
<del> const stub = ReactTestUtils.renderIntoDocument(<App />);
<add> const stub = ReactDOM.render(<App />, container);
<ide> const buttonNode = ReactDOM.findDOMNode(stub).childNodes[0];
<ide> const firstRadioNode = ReactDOM.findDOMNode(stub).childNodes[1];
<ide> expect(firstRadioNode.checked).toBe(false);
<del> ReactTestUtils.Simulate.click(buttonNode);
<add> dispatchEventOnNode(buttonNode, 'click');
<ide> expect(firstRadioNode.checked).toBe(true);
<ide> });
<ide>
<ide> it('should control radio buttons if the tree updates during render', () => {
<del> const sharedParent = document.createElement('div');
<add> const sharedParent = container;
<ide> const container1 = document.createElement('div');
<ide> const container2 = document.createElement('div');
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> let aNode;
<ide> let bNode;
<ide> class ComponentA extends React.Component {
<add> state = {changed: false};
<add> handleChange = () => {
<add> this.setState({
<add> changed: true,
<add> });
<add> };
<add> componentDidUpdate() {
<add> sharedParent.appendChild(container2);
<add> }
<ide> componentDidMount() {
<ide> ReactDOM.render(<ComponentB />, container2);
<ide> }
<ide> describe('ReactDOMInput', () => {
<ide> ref={n => (aNode = n)}
<ide> type="radio"
<ide> name="fruit"
<del> checked={true}
<del> onChange={emptyFunction}
<add> checked={false}
<add> onChange={this.handleChange}
<ide> />
<ide> A
<ide> </div>
<ide> describe('ReactDOMInput', () => {
<ide> }
<ide>
<ide> class ComponentB extends React.Component {
<del> state = {changed: false};
<del> handleChange = () => {
<del> this.setState({
<del> changed: true,
<del> });
<del> };
<del> componentDidUpdate() {
<del> sharedParent.appendChild(container2);
<del> }
<ide> render() {
<ide> return (
<ide> <div>
<ide> <input
<ide> ref={n => (bNode = n)}
<ide> type="radio"
<ide> name="fruit"
<del> checked={false}
<del> onChange={this.handleChange}
<add> checked={true}
<add> onChange={emptyFunction}
<ide> />
<ide> B
<ide> </div>
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> ReactDOM.render(<ComponentA />, container1);
<ide>
<del> expect(aNode.checked).toBe(true);
<del> expect(bNode.checked).toBe(false);
<add> expect(aNode.checked).toBe(false);
<add> expect(bNode.checked).toBe(true);
<ide>
<del> bNode.checked = true;
<add> setUntrackedChecked.call(aNode, true);
<ide> // This next line isn't necessary in a proper browser environment, but
<del> // jsdom doesn't uncheck the others in a group (which makes this whole test
<del> // a little less effective)
<del> aNode.checked = false;
<add> // jsdom doesn't uncheck the others in a group (because they are not yet
<add> // sharing a parent), which makes this whole test a little less effective.
<add> setUntrackedChecked.call(bNode, false);
<ide>
<ide> // Now let's run the actual ReactDOMInput change event handler
<del> ReactTestUtils.Simulate.change(bNode);
<add> dispatchEventOnNode(aNode, 'click');
<ide>
<ide> // The original state should have been restored
<del> expect(aNode.checked).toBe(true);
<del> expect(bNode.checked).toBe(false);
<add> expect(aNode.checked).toBe(false);
<add> expect(bNode.checked).toBe(true);
<ide> });
<ide>
<ide> it('should warn with value and no onChange handler and readOnly specified', () => {
<del> ReactTestUtils.renderIntoDocument(
<add> ReactDOM.render(
<ide> <input type="text" value="zoink" readOnly={true} />,
<add> container,
<ide> );
<add> ReactDOM.unmountComponentAtNode(container);
<ide>
<ide> expect(() =>
<del> ReactTestUtils.renderIntoDocument(
<add> ReactDOM.render(
<ide> <input type="text" value="zoink" readOnly={false} />,
<add> container,
<ide> ),
<ide> ).toWarnDev(
<ide> 'Warning: Failed prop type: You provided a `value` prop to a form ' +
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should have a this value of undefined if bind is not used', () => {
<add> expect.assertions(1);
<ide> const unboundInputOnChange = function() {
<ide> expect(this).toBe(undefined);
<ide> };
<ide>
<del> let instance = <input type="text" onChange={unboundInputOnChange} />;
<del> instance = ReactTestUtils.renderIntoDocument(instance);
<add> const stub = <input type="text" onChange={unboundInputOnChange} />;
<add> const node = ReactDOM.render(stub, container);
<ide>
<del> ReactTestUtils.Simulate.change(instance);
<add> setUntrackedValue.call(node, 'giraffe');
<add> dispatchEventOnNode(node, 'input');
<ide> });
<ide>
<ide> it('should warn with checked and no onChange handler with readOnly specified', () => {
<del> ReactTestUtils.renderIntoDocument(
<add> ReactDOM.render(
<ide> <input type="checkbox" checked="false" readOnly={true} />,
<add> container,
<ide> );
<add> ReactDOM.unmountComponentAtNode(container);
<ide>
<ide> expect(() =>
<del> ReactTestUtils.renderIntoDocument(
<add> ReactDOM.render(
<ide> <input type="checkbox" checked="false" readOnly={false} />,
<add> container,
<ide> ),
<ide> ).toWarnDev(
<ide> 'Failed prop type: You provided a `checked` prop to a form field without an `onChange` handler. ' +
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should update defaultValue to empty string', () => {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input type="text" defaultValue={'foo'} />, container);
<ide> ReactDOM.render(<input type="text" defaultValue={''} />, container);
<ide> expect(container.firstChild.defaultValue).toBe('');
<ide> });
<ide>
<ide> it('should warn if value is null', () => {
<ide> expect(() =>
<del> ReactTestUtils.renderIntoDocument(<input type="text" value={null} />),
<add> ReactDOM.render(<input type="text" value={null} />, container),
<ide> ).toWarnDev(
<ide> '`value` prop on `input` should not be null. ' +
<ide> 'Consider using an empty string to clear the component or `undefined` ' +
<ide> 'for uncontrolled components.',
<ide> );
<add> ReactDOM.unmountComponentAtNode(container);
<ide>
<del> ReactTestUtils.renderIntoDocument(<input type="text" value={null} />);
<add> ReactDOM.render(<input type="text" value={null} />, container);
<ide> });
<ide>
<ide> it('should warn if checked and defaultChecked props are specified', () => {
<ide> expect(() =>
<del> ReactTestUtils.renderIntoDocument(
<add> ReactDOM.render(
<ide> <input
<ide> type="radio"
<ide> checked={true}
<ide> defaultChecked={true}
<ide> readOnly={true}
<ide> />,
<add> container,
<ide> ),
<ide> ).toWarnDev(
<ide> 'A component contains an input of type radio with both checked and defaultChecked props. ' +
<ide> describe('ReactDOMInput', () => {
<ide> 'element and remove one of these props. More info: ' +
<ide> 'https://fb.me/react-controlled-components',
<ide> );
<add> ReactDOM.unmountComponentAtNode(container);
<ide>
<del> ReactTestUtils.renderIntoDocument(
<add> ReactDOM.render(
<ide> <input
<ide> type="radio"
<ide> checked={true}
<ide> defaultChecked={true}
<ide> readOnly={true}
<ide> />,
<add> container,
<ide> );
<ide> });
<ide>
<ide> it('should warn if value and defaultValue props are specified', () => {
<ide> expect(() =>
<del> ReactTestUtils.renderIntoDocument(
<add> ReactDOM.render(
<ide> <input type="text" value="foo" defaultValue="bar" readOnly={true} />,
<add> container,
<ide> ),
<ide> ).toWarnDev(
<ide> 'A component contains an input of type text with both value and defaultValue props. ' +
<ide> describe('ReactDOMInput', () => {
<ide> 'element and remove one of these props. More info: ' +
<ide> 'https://fb.me/react-controlled-components',
<ide> );
<add> ReactDOM.unmountComponentAtNode(container);
<ide>
<del> ReactTestUtils.renderIntoDocument(
<add> ReactDOM.render(
<ide> <input type="text" value="foo" defaultValue="bar" readOnly={true} />,
<add> container,
<ide> );
<ide> });
<ide>
<ide> it('should warn if controlled input switches to uncontrolled (value is undefined)', () => {
<ide> const stub = (
<ide> <input type="text" value="controlled" onChange={emptyFunction} />
<ide> );
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() => ReactDOM.render(<input type="text" />, container)).toWarnDev(
<ide> 'Warning: A component is changing a controlled input of type text to be uncontrolled. ' +
<ide> describe('ReactDOMInput', () => {
<ide> const stub = (
<ide> <input type="text" value="controlled" onChange={emptyFunction} />
<ide> );
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() =>
<ide> ReactDOM.render(<input type="text" value={null} />, container),
<ide> describe('ReactDOMInput', () => {
<ide> const stub = (
<ide> <input type="text" value="controlled" onChange={emptyFunction} />
<ide> );
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() =>
<ide> ReactDOM.render(
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should warn if uncontrolled input (value is undefined) switches to controlled', () => {
<ide> const stub = <input type="text" />;
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() =>
<ide> ReactDOM.render(<input type="text" value="controlled" />, container),
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should warn if uncontrolled input (value is null) switches to controlled', () => {
<ide> const stub = <input type="text" value={null} />;
<del> const container = document.createElement('div');
<ide> expect(() => ReactDOM.render(stub, container)).toWarnDev(
<ide> '`value` prop on `input` should not be null. ' +
<ide> 'Consider using an empty string to clear the component or `undefined` for uncontrolled components.',
<ide> describe('ReactDOMInput', () => {
<ide> const stub = (
<ide> <input type="checkbox" checked={true} onChange={emptyFunction} />
<ide> );
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() =>
<ide> ReactDOM.render(<input type="checkbox" />, container),
<ide> describe('ReactDOMInput', () => {
<ide> const stub = (
<ide> <input type="checkbox" checked={true} onChange={emptyFunction} />
<ide> );
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() =>
<ide> ReactDOM.render(<input type="checkbox" checked={null} />, container),
<ide> describe('ReactDOMInput', () => {
<ide> const stub = (
<ide> <input type="checkbox" checked={true} onChange={emptyFunction} />
<ide> );
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() =>
<ide> ReactDOM.render(
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should warn if uncontrolled checkbox (checked is undefined) switches to controlled', () => {
<ide> const stub = <input type="checkbox" />;
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() =>
<ide> ReactDOM.render(<input type="checkbox" checked={true} />, container),
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should warn if uncontrolled checkbox (checked is null) switches to controlled', () => {
<ide> const stub = <input type="checkbox" checked={null} />;
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() =>
<ide> ReactDOM.render(<input type="checkbox" checked={true} />, container),
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should warn if controlled radio switches to uncontrolled (checked is undefined)', () => {
<ide> const stub = <input type="radio" checked={true} onChange={emptyFunction} />;
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() => ReactDOM.render(<input type="radio" />, container)).toWarnDev(
<ide> 'Warning: A component is changing a controlled input of type radio to be uncontrolled. ' +
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should warn if controlled radio switches to uncontrolled (checked is null)', () => {
<ide> const stub = <input type="radio" checked={true} onChange={emptyFunction} />;
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() =>
<ide> ReactDOM.render(<input type="radio" checked={null} />, container),
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should warn if controlled radio switches to uncontrolled with defaultChecked', () => {
<ide> const stub = <input type="radio" checked={true} onChange={emptyFunction} />;
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() =>
<ide> ReactDOM.render(<input type="radio" defaultChecked={true} />, container),
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should warn if uncontrolled radio (checked is undefined) switches to controlled', () => {
<ide> const stub = <input type="radio" />;
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() =>
<ide> ReactDOM.render(<input type="radio" checked={true} />, container),
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should warn if uncontrolled radio (checked is null) switches to controlled', () => {
<ide> const stub = <input type="radio" checked={null} />;
<del> const container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> expect(() =>
<ide> ReactDOM.render(<input type="radio" checked={true} />, container),
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should not warn if radio value changes but never becomes controlled', () => {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input type="radio" value="value" />, container);
<ide> ReactDOM.render(<input type="radio" />, container);
<ide> ReactDOM.render(
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should not warn if radio value changes but never becomes uncontrolled', () => {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(
<ide> <input type="radio" checked={false} onChange={() => null} />,
<ide> container,
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('should warn if radio checked false changes to become uncontrolled', () => {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(
<ide> <input
<ide> type="radio"
<ide> describe('ReactDOMInput', () => {
<ide> return el;
<ide> });
<ide>
<del> ReactTestUtils.renderIntoDocument(
<add> ReactDOM.render(
<ide> <input
<ide> value="0"
<ide> onChange={() => {}}
<ide> describe('ReactDOMInput', () => {
<ide> max="100"
<ide> step="1"
<ide> />,
<add> container,
<ide> );
<ide> expect(log).toEqual([
<ide> 'set attribute type',
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('sets value properly with type coming later in props', () => {
<del> const input = ReactTestUtils.renderIntoDocument(
<del> <input value="hi" type="radio" />,
<del> );
<add> const input = ReactDOM.render(<input value="hi" type="radio" />, container);
<ide> expect(input.value).toBe('hi');
<ide> });
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> }
<ide> }
<ide>
<del> const input = ReactTestUtils.renderIntoDocument(<Input />);
<add> const input = ReactDOM.render(<Input />, container);
<ide> const node = ReactDOM.findDOMNode(input);
<ide>
<ide> // If the value is set before the type, a validation warning will raise and
<ide> describe('ReactDOMInput', () => {
<ide> return el;
<ide> });
<ide>
<del> ReactTestUtils.renderIntoDocument(
<del> <input type="date" defaultValue="1980-01-01" />,
<del> );
<add> ReactDOM.render(<input type="date" defaultValue="1980-01-01" />, container);
<ide> expect(log).toEqual([
<ide> 'node.setAttribute("type", "date")',
<ide> 'node.value = "1980-01-01"',
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('always sets the attribute when values change on text inputs', function() {
<ide> const Input = getTestInput();
<del> const stub = ReactTestUtils.renderIntoDocument(<Input type="text" />);
<add> const stub = ReactDOM.render(<Input type="text" />, container);
<ide> const node = ReactDOM.findDOMNode(stub);
<ide>
<del> ReactTestUtils.Simulate.change(node, {target: {value: '2'}});
<add> setUntrackedValue.call(node, '2');
<add> dispatchEventOnNode(node, 'input');
<ide>
<ide> expect(node.getAttribute('value')).toBe('2');
<ide> });
<ide>
<ide> it('does not set the value attribute on number inputs if focused', () => {
<ide> const Input = getTestInput();
<del> const stub = ReactTestUtils.renderIntoDocument(
<add> const stub = ReactDOM.render(
<ide> <Input type="number" value="1" />,
<add> container,
<ide> );
<ide> const node = ReactDOM.findDOMNode(stub);
<ide>
<ide> node.focus();
<ide>
<del> ReactTestUtils.Simulate.change(node, {target: {value: '2'}});
<add> setUntrackedValue.call(node, '2');
<add> dispatchEventOnNode(node, 'input');
<ide>
<ide> expect(node.getAttribute('value')).toBe('1');
<ide> });
<ide>
<ide> it('sets the value attribute on number inputs on blur', () => {
<ide> const Input = getTestInput();
<del> const stub = ReactTestUtils.renderIntoDocument(
<add> const stub = ReactDOM.render(
<ide> <Input type="number" value="1" />,
<add> container,
<ide> );
<ide> const node = ReactDOM.findDOMNode(stub);
<ide>
<del> ReactTestUtils.Simulate.change(node, {target: {value: '2'}});
<del> ReactTestUtils.SimulateNative.blur(node);
<add> setUntrackedValue.call(node, '2');
<add> dispatchEventOnNode(node, 'input');
<add> dispatchEventOnNode(node, 'blur');
<ide>
<ide> expect(node.getAttribute('value')).toBe('2');
<ide> });
<ide>
<ide> it('an uncontrolled number input will not update the value attribute on blur', () => {
<del> const node = ReactTestUtils.renderIntoDocument(
<add> const node = ReactDOM.render(
<ide> <input type="number" defaultValue="1" />,
<add> container,
<ide> );
<ide>
<del> node.value = 4;
<add> setUntrackedValue.call(node, 4);
<ide>
<del> ReactTestUtils.SimulateNative.blur(node);
<add> dispatchEventOnNode(node, 'blur');
<ide>
<ide> expect(node.getAttribute('value')).toBe('1');
<ide> });
<ide>
<ide> it('an uncontrolled text input will not update the value attribute on blur', () => {
<del> const node = ReactTestUtils.renderIntoDocument(
<add> const node = ReactDOM.render(
<ide> <input type="text" defaultValue="1" />,
<add> container,
<ide> );
<ide>
<del> node.value = 4;
<add> setUntrackedValue.call(node, 4);
<ide>
<del> ReactTestUtils.SimulateNative.blur(node);
<add> dispatchEventOnNode(node, 'blur');
<ide>
<ide> expect(node.getAttribute('value')).toBe('1');
<ide> });
<ide> describe('ReactDOMInput', () => {
<ide> let input;
<ide>
<ide> function renderInputWithStringThenWithUndefined() {
<add> let setValueToUndefined;
<ide> class Input extends React.Component {
<add> constructor() {
<add> super();
<add> setValueToUndefined = () => this.setState({value: undefined});
<add> }
<ide> state = {value: 'first'};
<ide> render() {
<ide> return (
<ide> describe('ReactDOMInput', () => {
<ide> }
<ide> }
<ide>
<del> const stub = ReactTestUtils.renderIntoDocument(<Input />);
<add> const stub = ReactDOM.render(<Input />, container);
<ide> input = ReactDOM.findDOMNode(stub);
<del> ReactTestUtils.Simulate.change(input, {target: {value: 'latest'}});
<del> ReactTestUtils.Simulate.change(input, {target: {value: undefined}});
<add> setUntrackedValue.call(input, 'latest');
<add> dispatchEventOnNode(input, 'input');
<add> setValueToUndefined();
<ide> }
<ide>
<ide> it('reverts the value attribute to the initial value', () => {
<ide> describe('ReactDOMInput', () => {
<ide> let input;
<ide>
<ide> function renderInputWithStringThenWithNull() {
<add> let setValueToNull;
<ide> class Input extends React.Component {
<add> constructor() {
<add> super();
<add> setValueToNull = () => this.setState({value: null});
<add> }
<ide> state = {value: 'first'};
<ide> render() {
<ide> return (
<ide> describe('ReactDOMInput', () => {
<ide> }
<ide> }
<ide>
<del> const stub = ReactTestUtils.renderIntoDocument(<Input />);
<add> const stub = ReactDOM.render(<Input />, container);
<ide> input = ReactDOM.findDOMNode(stub);
<del> ReactTestUtils.Simulate.change(input, {target: {value: 'latest'}});
<del> ReactTestUtils.Simulate.change(input, {target: {value: null}});
<add> setUntrackedValue.call(input, 'latest');
<add> dispatchEventOnNode(input, 'input');
<add> setValueToNull();
<ide> }
<ide>
<ide> it('reverts the value attribute to the initial value', () => {
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> describe('When given a Symbol value', function() {
<ide> it('treats initial Symbol value as an empty string', function() {
<del> const container = document.createElement('div');
<ide> expect(() =>
<ide> ReactDOM.render(
<ide> <input value={Symbol('foobar')} onChange={() => {}} />,
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('treats updated Symbol value as an empty string', function() {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input value="foo" onChange={() => {}} />, container);
<ide> expect(() =>
<ide> ReactDOM.render(
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('treats initial Symbol defaultValue as an empty string', function() {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input defaultValue={Symbol('foobar')} />, container);
<ide> const node = container.firstChild;
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('treats updated Symbol defaultValue as an empty string', function() {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input defaultValue="foo" />, container);
<ide> ReactDOM.render(<input defaultValue={Symbol('foobar')} />, container);
<ide> const node = container.firstChild;
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> describe('When given a function value', function() {
<ide> it('treats initial function value as an empty string', function() {
<del> const container = document.createElement('div');
<ide> expect(() =>
<ide> ReactDOM.render(
<ide> <input value={() => {}} onChange={() => {}} />,
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('treats updated function value as an empty string', function() {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input value="foo" onChange={() => {}} />, container);
<ide> expect(() =>
<ide> ReactDOM.render(
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('treats initial function defaultValue as an empty string', function() {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input defaultValue={() => {}} />, container);
<ide> const node = container.firstChild;
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('treats updated function defaultValue as an empty string', function() {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input defaultValue="foo" />, container);
<ide> ReactDOM.render(<input defaultValue={() => {}} />, container);
<ide> const node = container.firstChild;
<ide> describe('ReactDOMInput', () => {
<ide> // value in order to "dettach" it from defaultValue. This had the unfortunate
<ide> // side-effect of assigning value="on" to radio and checkboxes
<ide> it('does not add "on" in absence of value on a checkbox', function() {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(
<ide> <input type="checkbox" defaultChecked={true} />,
<ide> container,
<ide> describe('ReactDOMInput', () => {
<ide> });
<ide>
<ide> it('does not add "on" in absence of value on a radio', function() {
<del> const container = document.createElement('div');
<ide> ReactDOM.render(<input type="radio" defaultChecked={true} />, container);
<ide> const node = container.firstChild;
<ide>
<ide><path>packages/react-dom/src/__tests__/ReactDOMSelect-test.js
<ide> describe('ReactDOMSelect', () => {
<ide> <option value="gorilla">A gorilla!</option>
<ide> </select>
<ide> );
<del> const node = ReactTestUtils.renderIntoDocument(stub);
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<ide>
<del> ReactTestUtils.Simulate.change(node);
<add> try {
<add> const node = ReactDOM.render(stub, container);
<ide>
<del> expect(node.value).toBe('giraffe');
<add> node.dispatchEvent(
<add> new Event('change', {bubbles: true, cancelable: false}),
<add> );
<add>
<add> expect(node.value).toBe('giraffe');
<add> } finally {
<add> document.body.removeChild(container);
<add> }
<ide> });
<ide>
<ide> it('should warn if value and defaultValue props are specified', () => {
<ide><path>packages/react-dom/src/__tests__/ReactDOMServerIntegrationForms-test.js
<ide> const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegratio
<ide> let React;
<ide> let ReactDOM;
<ide> let ReactDOMServer;
<del>let ReactTestUtils;
<ide>
<ide> function initModules() {
<ide> // Reset warning cache.
<ide> jest.resetModuleRegistry();
<ide> React = require('react');
<ide> ReactDOM = require('react-dom');
<del> ReactTestUtils = require('react-dom/test-utils');
<ide> ReactDOMServer = require('react-dom/server');
<ide>
<ide> // Make them available to the helpers.
<ide> describe('ReactDOMServerIntegration', () => {
<ide>
<ide> describe('user interaction with controlled inputs', function() {
<ide> itClientRenders('a controlled text input', async render => {
<add> const setUntrackedValue = Object.getOwnPropertyDescriptor(
<add> HTMLInputElement.prototype,
<add> 'value',
<add> ).set;
<add>
<ide> let changeCount = 0;
<ide> const e = await render(
<ide> <ControlledInput onChange={() => changeCount++} />,
<ide> );
<del> expect(changeCount).toBe(0);
<del> expect(e.value).toBe('Hello');
<add> const container = e.parentNode;
<add> document.body.appendChild(container);
<ide>
<del> // simulate a user typing.
<del> e.value = 'Goodbye';
<del> ReactTestUtils.Simulate.change(e);
<add> try {
<add> expect(changeCount).toBe(0);
<add> expect(e.value).toBe('Hello');
<ide>
<del> expect(changeCount).toBe(1);
<del> expect(e.value).toBe('Goodbye');
<add> // simulate a user typing.
<add> setUntrackedValue.call(e, 'Goodbye');
<add> e.dispatchEvent(
<add> new Event('input', {bubbles: true, cancelable: false}),
<add> );
<add>
<add> expect(changeCount).toBe(1);
<add> expect(e.value).toBe('Goodbye');
<add> } finally {
<add> document.body.removeChild(container);
<add> }
<ide> });
<ide>
<ide> itClientRenders('a controlled textarea', async render => {
<add> const setUntrackedValue = Object.getOwnPropertyDescriptor(
<add> HTMLTextAreaElement.prototype,
<add> 'value',
<add> ).set;
<add>
<ide> let changeCount = 0;
<ide> const e = await render(
<ide> <ControlledTextArea onChange={() => changeCount++} />,
<ide> );
<del> expect(changeCount).toBe(0);
<del> expect(e.value).toBe('Hello');
<add> const container = e.parentNode;
<add> document.body.appendChild(container);
<ide>
<del> // simulate a user typing.
<del> e.value = 'Goodbye';
<del> ReactTestUtils.Simulate.change(e);
<add> try {
<add> expect(changeCount).toBe(0);
<add> expect(e.value).toBe('Hello');
<ide>
<del> expect(changeCount).toBe(1);
<del> expect(e.value).toBe('Goodbye');
<add> // simulate a user typing.
<add> setUntrackedValue.call(e, 'Goodbye');
<add> e.dispatchEvent(
<add> new Event('input', {bubbles: true, cancelable: false}),
<add> );
<add>
<add> expect(changeCount).toBe(1);
<add> expect(e.value).toBe('Goodbye');
<add> } finally {
<add> document.body.removeChild(container);
<add> }
<ide> });
<ide>
<ide> itClientRenders('a controlled checkbox', async render => {
<ide> let changeCount = 0;
<ide> const e = await render(
<ide> <ControlledCheckbox onChange={() => changeCount++} />,
<ide> );
<del> expect(changeCount).toBe(0);
<del> expect(e.checked).toBe(true);
<add> const container = e.parentNode;
<add> document.body.appendChild(container);
<ide>
<del> // simulate a user typing.
<del> e.checked = false;
<del> ReactTestUtils.Simulate.change(e);
<add> try {
<add> expect(changeCount).toBe(0);
<add> expect(e.checked).toBe(true);
<ide>
<del> expect(changeCount).toBe(1);
<del> expect(e.checked).toBe(false);
<add> // simulate a user clicking.
<add> e.dispatchEvent(
<add> new Event('click', {bubbles: true, cancelable: true}),
<add> );
<add>
<add> expect(changeCount).toBe(1);
<add> expect(e.checked).toBe(false);
<add> } finally {
<add> document.body.removeChild(container);
<add> }
<ide> });
<ide>
<ide> itClientRenders('a controlled select', async render => {
<add> const setUntrackedValue = Object.getOwnPropertyDescriptor(
<add> HTMLSelectElement.prototype,
<add> 'value',
<add> ).set;
<add>
<ide> let changeCount = 0;
<ide> const e = await render(
<ide> <ControlledSelect onChange={() => changeCount++} />,
<ide> );
<del> expect(changeCount).toBe(0);
<del> expect(e.value).toBe('Hello');
<add> const container = e.parentNode;
<add> document.body.appendChild(container);
<ide>
<del> // simulate a user typing.
<del> e.value = 'Goodbye';
<del> ReactTestUtils.Simulate.change(e);
<add> try {
<add> expect(changeCount).toBe(0);
<add> expect(e.value).toBe('Hello');
<ide>
<del> expect(changeCount).toBe(1);
<del> expect(e.value).toBe('Goodbye');
<add> // simulate a user typing.
<add> setUntrackedValue.call(e, 'Goodbye');
<add> e.dispatchEvent(
<add> new Event('change', {bubbles: true, cancelable: false}),
<add> );
<add>
<add> expect(changeCount).toBe(1);
<add> expect(e.value).toBe('Goodbye');
<add> } finally {
<add> document.body.removeChild(container);
<add> }
<ide> });
<ide> });
<ide>
<ide><path>packages/react-dom/src/__tests__/ReactDOMTextarea-test.js
<ide> describe('ReactDOMTextarea', () => {
<ide>
<ide> it('should properly control a value of number `0`', () => {
<ide> const stub = <textarea value={0} onChange={emptyFunction} />;
<del> const node = renderTextarea(stub);
<add> const setUntrackedValue = Object.getOwnPropertyDescriptor(
<add> HTMLTextAreaElement.prototype,
<add> 'value',
<add> ).set;
<ide>
<del> node.value = 'giraffe';
<del> ReactTestUtils.Simulate.change(node);
<del> expect(node.value).toBe('0');
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add>
<add> try {
<add> const node = renderTextarea(stub, container);
<add>
<add> setUntrackedValue.call(node, 'giraffe');
<add> node.dispatchEvent(
<add> new Event('input', {bubbles: true, cancelable: false}),
<add> );
<add> expect(node.value).toBe('0');
<add> } finally {
<add> document.body.removeChild(container);
<add> }
<ide> });
<ide>
<ide> it('should treat children like `defaultValue`', () => { | 4 |
Python | Python | add tool to help speed up travis ci | 6185631ca9b6d426067eec6d8d22e60370281a0a | <ide><path>tools/travis-sorter.py
<add>#!/usr/bin/env python3
<add>"""
<add>Run with a repo/build number or list of Travis CI build times to show the optimal build
<add>order to run faster and make full use of all available parallel build jobs.
<add>
<add>Requires the Travis Client CLI
<add>
<add>https://github.com/travis-ci/travis.rb#installation
<add>
<add># Example
<add>
<add>$ # Check build 22 of hugovk/numpy, and skip the first job (it's a single stage)
<add>$ travis-sorter.py hugovk/numpy 22 --skip 1
<add>travis show -r hugovk/numpy 22
<add>[8, 7, 8, 10, 9, 18, 8, 11, 8, 10, 8, 8, 17, 8, 26]
<add>[7, 8, 10, 9, 18, 8, 11, 8, 10, 8, 8, 17, 8, 26]
<add>Before:
<add>
<add>ID Duration in mins
<add> 1 *******
<add> 2 ********
<add> 3 **********
<add> 4 *********
<add> 5 ******************
<add> 6 ********
<add> 7 ***********
<add> 8 ********
<add> 9 **********
<add>10 ********
<add>11 ********
<add>12 *****************
<add>13 ********
<add>14 **************************
<add>End: 46
<add> ----------------------------------------------
<add>
<add>After:
<add>
<add>ID Duration in mins
<add>14 **************************
<add> 5 ******************
<add>12 *****************
<add> 7 ***********
<add> 3 **********
<add> 9 **********
<add> 4 *********
<add> 2 ********
<add> 6 ********
<add> 8 ********
<add>10 ********
<add>11 ********
<add>13 ********
<add> 1 *******
<add>End: 34
<add> ----------------------------------
<add>
<add># Example
<add>
<add>$ python travis-sorter.py 4 4 4 4 4 12 19
<add>
<add>Before:
<add>
<add>****
<add>****
<add>****
<add>****
<add>****
<add> ************
<add> *******************
<add>12345678901234567890123 = 23 minutes
<add>
<add>After:
<add>
<add>*******************
<add>************
<add>****
<add>****
<add>****
<add> ****
<add> ****
<add>1234567890123456789 = 19 minutes
<add>"""
<add>import argparse
<add>import re
<add>import subprocess
<add>import sys
<add>
<add>count = 1
<add>
<add>
<add>def summarise(jobs):
<add> end = 0
<add> print("ID Duration in mins")
<add> for job in jobs:
<add> before = " " * job.started
<add> active = "*" * job.length
<add> print("{:2d} {}{}".format(job.id, before, active))
<add> if job.started + job.length > end:
<add> end = job.started + job.length
<add> # for job in jobs:
<add> # print(job)
<add> print("End:", end)
<add> print(" " + "-" * end)
<add>
<add>
<add>class Job(object):
<add> def __init__(self, length):
<add> global count
<add> self.id = count
<add> count += 1
<add> self.length = length
<add> self.started = -1
<add> self.status = "not started"
<add> self.ended = False
<add>
<add> def __str__(self):
<add> return "{}\tLength: {}\tStarted: {}\tEnded: {}".format(
<add> self.id, self.length, self.started, self.ended
<add> )
<add>
<add>
<add>def count_status(jobs, status):
<add> number = 0
<add> for job in jobs:
<add> if job.status == status:
<add> number += 1
<add> return number
<add>
<add>
<add>def simulate(jobs, limit):
<add>
<add> time = 0
<add>
<add> # summarise(jobs)
<add>
<add> while True:
<add> # Check if any have ended
<add> for job in jobs:
<add> if job.status == "active":
<add> if time >= job.started + job.length:
<add> # print("{}/{} Finished:".format(count_status(jobs, "active"), limit))
<add> job.ended = time
<add> job.status = "finished"
<add> # print(job)
<add>
<add> # Check if any can start
<add> for job in jobs:
<add> if job.status == "not started":
<add> if count_status(jobs, "active") < limit:
<add> # print("{}/{} Starting:".format(count_status(jobs, "active"), limit))
<add> job.started = time
<add> job.status = "active"
<add> # print(job)
<add>
<add> time += 1
<add>
<add> # Exit loop?
<add> if count_status(jobs, "finished") == len(jobs):
<add> break
<add>
<add> summarise(jobs)
<add>
<add>
<add>def do_thing(repo, number):
<add> cmd = f"travis show -r {repo} {number or ''}"
<add> # cmd = f"travis show --com -r {repo} {number or ''}"
<add> print(cmd)
<add>
<add> exitcode = 0
<add> # For offline testing
<add> output = """Build #4: Upgrade Python syntax with pyupgrade https://github.com/asottile/pyupgrade
<add>State: passed
<add>Type: push
<add>Branch: add-3.7
<add>Compare URL: https://github.com/hugovk/diff-cover/compare/4ae7cf97c6fa...7eeddb300175
<add>Duration: 16 min 7 sec
<add>Started: 2018-10-17 19:03:01
<add>Finished: 2018-10-17 19:09:53
<add>
<add>#4.1 passed: 1 min os: linux, env: TOXENV=py27, python: 2.7
<add>#4.2 passed: 1 min 43 sec os: linux, env: TOXENV=py34, python: 3.4
<add>#4.3 passed: 1 min 52 sec os: linux, env: TOXENV=py35, python: 3.5
<add>#4.4 passed: 1 min 38 sec os: linux, env: TOXENV=py36, python: 3.6
<add>#4.5 passed: 1 min 47 sec os: linux, env: TOXENV=py37, python: 3.7
<add>#4.6 passed: 4 min 35 sec os: linux, env: TOXENV=pypy, python: pypy
<add>#4.7 passed: 3 min 17 sec os: linux, env: TOXENV=pypy3, python: pypy3"""
<add>
<add> # For offline testing
<add> output = """Build #9: :arrows_clockwise: [EngCom] Public Pull Requests - 2.3-develop
<add>State: errored
<add>Type: push
<add>Branch: 2.3-develop
<add>Compare URL: https://github.com/hugovk/magento2/compare/80469a61e061...77af5d65ef4f
<add>Duration: 4 hrs 12 min 13 sec
<add>Started: 2018-10-27 17:50:51
<add>Finished: 2018-10-27 18:54:14
<add>
<add>#9.1 passed: 3 min 30 sec os: linux, env: TEST_SUITE=unit, php: 7.1
<add>#9.2 passed: 3 min 35 sec os: linux, env: TEST_SUITE=unit, php: 7.2
<add>#9.3 passed: 3 min 41 sec os: linux, env: TEST_SUITE=static, php: 7.2
<add>#9.4 passed: 8 min 48 sec os: linux, env: TEST_SUITE=js GRUNT_COMMAND=spec, php: 7.2
<add>#9.5 passed: 3 min 24 sec os: linux, env: TEST_SUITE=js GRUNT_COMMAND=static, php: 7.2
<add>#9.6 errored: 50 min os: linux, env: TEST_SUITE=integration INTEGRATION_INDEX=1, php: 7.1
<add>#9.7 passed: 49 min 25 sec os: linux, env: TEST_SUITE=integration INTEGRATION_INDEX=1, php: 7.2
<add>#9.8 passed: 31 min 54 sec os: linux, env: TEST_SUITE=integration INTEGRATION_INDEX=2, php: 7.1
<add>#9.9 passed: 31 min 24 sec os: linux, env: TEST_SUITE=integration INTEGRATION_INDEX=2, php: 7.2
<add>#9.10 passed: 27 min 23 sec os: linux, env: TEST_SUITE=integration INTEGRATION_INDEX=3, php: 7.1
<add>#9.11 passed: 26 min 9 sec os: linux, env: TEST_SUITE=integration INTEGRATION_INDEX=3, php: 7.2
<add>#9.12 passed: 13 min os: linux, env: TEST_SUITE=functional, php: 7.2"""
<add>
<add> # Real use
<add> exitcode, output = subprocess.getstatusoutput(cmd)
<add>
<add> # print(exitcode)
<add> # print(output)
<add> if exitcode != 0:
<add> print(output)
<add> sys.exit(exitcode)
<add>
<add> minutes = []
<add> matches = re.findall(r"(pass|fail|error)ed.* (\d+) min (\d+)? ", output)
<add> for match in matches:
<add> status, m, s = match
<add> s = 0 if s == "" else int(s)
<add> s += int(m) * 60
<add> minutes.append(round(s / 60))
<add>
<add> # print(minutes)
<add> return minutes
<add>
<add>
<add>if __name__ == "__main__":
<add> parser = argparse.ArgumentParser(
<add> description="Either give minutes for --jobs (3 5 3 2 5), "
<add> "or --repo slug (hugovk/test) and build --number (5)",
<add> formatter_class=argparse.ArgumentDefaultsHelpFormatter,
<add> )
<add> parser.add_argument(
<add> "input",
<add> nargs="+",
<add> help="Either: times for each build job (minutes), "
<add> "or an org/repo slug and optionally build number",
<add> )
<add> parser.add_argument(
<add> "-l", "--limit", type=int, default=5, help="Concurrent jobs limit"
<add> )
<add> parser.add_argument(
<add> "-s", "--skip", type=int, default=0, help="Skip X jobs at the start"
<add> )
<add> args = parser.parse_args()
<add>
<add> # If all ints
<add> try:
<add> for x in args.input:
<add> int(x)
<add> job_times = args.input
<add> except ValueError:
<add> try:
<add> number = args.input[1]
<add> except IndexError:
<add> number = None
<add> job_times = do_thing(args.input[0], number)
<add>
<add> job_times = job_times[args.skip :]
<add> # print(job_times)
<add>
<add> print("Before:")
<add> print()
<add>
<add> jobs = []
<add> for job_time in job_times:
<add> job = Job(job_time)
<add> jobs.append(job)
<add>
<add> simulate(jobs, args.limit)
<add>
<add> print()
<add> print("After:")
<add> print()
<add>
<add> # Sort with longest first
<add> jobs.sort(key=lambda job: job.length, reverse=True)
<add> # Reset status
<add> for job in jobs:
<add> job.status = "not started"
<add>
<add> simulate(jobs, args.limit) | 1 |
Javascript | Javascript | fix param type (not optional) | 2dc83b2f04848fc169b17a7aeac5395f03eb515b | <ide><path>src/ngMock/angular-mocks.js
<ide> angular.mock.$Browser.prototype = {
<ide> *
<ide> * <div class="alert alert-info">
<ide> * Periodic tasks scheduled via {@link $interval} use a different queue and are not flushed by
<del> * `$flushPendingTasks()`. Use {@link ngMock.$interval#flush $interval.flush([millis])} instead.
<add> * `$flushPendingTasks()`. Use {@link ngMock.$interval#flush $interval.flush(millis)} instead.
<ide> * </div>
<ide> *
<ide> * @param {number=} delay - The number of milliseconds to flush.
<ide> angular.mock.$IntervalProvider = function() {
<ide> *
<ide> * Runs interval tasks scheduled to be run in the next `millis` milliseconds.
<ide> *
<del> * @param {number=} millis maximum timeout amount to flush up until.
<add> * @param {number} millis maximum timeout amount to flush up until.
<ide> *
<ide> * @return {number} The amount of time moved forward.
<ide> */ | 1 |
PHP | PHP | add mix intergration tests | 87ef35362234c47e868fb19e4f7fad5371f0fe42 | <ide><path>tests/Integration/Foundation/FoundationHelpersTest.php
<ide>
<ide> use Exception;
<ide> use Orchestra\Testbench\TestCase;
<add>use Illuminate\Contracts\Debug\ExceptionHandler;
<ide>
<ide> /**
<ide> * @group integration
<ide> public function test(int $a)
<ide> $testClass->test([]);
<ide> }, 'rescued!'), 'rescued!');
<ide> }
<add>
<add> public function testMixReportsExceptionWhenAssetIsMissingFromManifest()
<add> {
<add> $handler = new FakeHandler;
<add> $this->app->instance(ExceptionHandler::class, $handler);
<add> $manifest = $this->makeManifest();
<add>
<add> mix('missing.js');
<add>
<add> $this->assertInstanceOf(Exception::class, $handler->reported);
<add> $this->assertSame('Unable to locate Mix file: /missing.js.', $handler->reported->getMessage());
<add>
<add> unlink($manifest);
<add> }
<add>
<add> public function testMixSilentlyFailsWhenAssetIsMissingFromManifestWhenNotInDebugMode()
<add> {
<add> $this->app['config']->set('app.debug', false);
<add> $manifest = $this->makeManifest();
<add>
<add> $path = mix('missing.js');
<add>
<add> $this->assertSame('/missing.js', $path);
<add>
<add> unlink($manifest);
<add> }
<add>
<add> /**
<add> * @expectedException \Exception
<add> * @expectedExceptionMessage Undefined index: /missing.js
<add> */
<add> public function testMixThrowsExceptionWhenAssetIsMissingFromManifestWhenInDebugMode()
<add> {
<add> $this->app['config']->set('app.debug', true);
<add> $manifest = $this->makeManifest();
<add>
<add> try {
<add> mix('missing.js');
<add> } catch (\Exception $e) {
<add> throw $e;
<add> } finally { // make sure we can cleanup the file
<add> unlink($manifest);
<add> }
<add> }
<add>
<add> protected function makeManifest($directory = '')
<add> {
<add> $this->app->singleton('path.public', function () {
<add> return __DIR__;
<add> });
<add>
<add> $path = public_path(str_finish($directory, '/').'mix-manifest.json');
<add>
<add> touch($path);
<add>
<add> // Laravel mix prints JSON pretty and with escaped
<add> // slashes, so we are doing that here for consistency.
<add> $content = json_encode(['/unversioned.css' => '/versioned.css'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
<add>
<add> file_put_contents($path, $content);
<add>
<add> return $path;
<add> }
<add>}
<add>
<add>class FakeHandler
<add>{
<add> public $reported;
<add>
<add> public function report($exception)
<add> {
<add> $this->reported = $exception;
<add> }
<ide> } | 1 |
Python | Python | add a test case for it | 1b2c399b06193145e0062667867e0b39ee754e9c | <ide><path>libcloud/test/compute/test_openstack.py
<ide> def test_attach_volume(self):
<ide> self.assertEqual(
<ide> self.driver.attach_volume(node, volume, '/dev/sdb'), True)
<ide>
<add> def test_attach_volume_device_auto(self):
<add> node = self.driver.list_nodes()[0]
<add> volume = self.driver.ex_get_volume(
<add> 'cd76a3a1-c4ce-40f6-9b9f-07a61508938d')
<add>
<add> OpenStack_1_1_MockHttp.type = 'DEVICE_AUTO'
<add> OpenStack_2_0_MockHttp.type = 'DEVICE_AUTO'
<add>
<add> self.assertEqual(
<add> self.driver.attach_volume(node, volume, 'auto'), True)
<add>
<ide> def test_detach_volume(self):
<ide> node = self.driver.list_nodes()[0]
<ide> volume = self.driver.ex_get_volume(
<ide> def _v2_1337_v2_0_ports_126da55e_cfcb_41c8_ae39_a26cb8a7e723(self, method, url,
<ide> else:
<ide> raise NotImplementedError()
<ide>
<add> def _v2_1337_servers_12065_os_volume_attachments_DEVICE_AUTO(self, method, url, body, headers):
<add> # test_attach_volume_device_auto
<add> if method == "POST":
<add> body = json.loads(body)
<add> self.assertEqual(body['volumeAttachment']['device'], None)
<add> return (httplib.NO_CONTENT, "", {}, httplib.responses[httplib.NO_CONTENT])
<add> else:
<add> raise NotImplementedError()
<add>
<ide> def _v2_1337_servers_1c01300f_ef97_4937_8f03_ac676d6234be_os_interface_126da55e_cfcb_41c8_ae39_a26cb8a7e723(self, method, url, body, headers):
<ide> if method == "DELETE":
<ide> return (httplib.NO_CONTENT, "", {}, httplib.responses[httplib.NO_CONTENT])
<ide> def _v1_1_slug_os_volumes_cd76a3a1_c4ce_40f6_9b9f_07a61508938d(self, method, url
<ide>
<ide> def _v1_1_slug_servers_12065_os_volume_attachments(self, method, url, body, headers):
<ide> if method == "POST":
<add> body = json.loads(body)
<add> self.assertEqual(body['volumeAttachment']['device'], '/dev/sdb')
<ide> body = self.fixtures.load(
<ide> '_servers_12065_os_volume_attachments.json')
<ide> else:
<ide> def _v2_1337_v2_0_floatingips(self, method, url, body, headers):
<ide> if method == 'GET':
<ide> body = self.fixtures.load('_v2_0__floatingips.json')
<ide> return (httplib.OK, body, self.json_content_headers, httplib.responses[httplib.OK])
<del>
<add>
<ide> def _v2_1337_v2_0_floatingips_foo_bar_id(self, method, url, body, headers):
<ide> if method == 'DELETE':
<ide> body = '' | 1 |
Java | Java | adjust layout animation with pending deletion set | c938c0afbfbd0e5ba8853feb212a976f605f51f0 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java
<ide> import com.facebook.systrace.Systrace;
<ide> import com.facebook.systrace.SystraceMessage;
<ide> import java.util.Arrays;
<add>import java.util.HashSet;
<add>import java.util.Set;
<ide> import javax.annotation.concurrent.NotThreadSafe;
<ide>
<ide> /**
<ide> public synchronized void manageChildren(
<ide> @Nullable int[] tagsToDelete) {
<ide> UiThreadUtil.assertOnUiThread();
<ide>
<add> final Set<Integer> pendingDeletionTags = new HashSet<>();
<ide> mLayoutAnimator.cancelAnimationsForViewTag(tag);
<ide>
<ide> final ViewGroup viewToManage = (ViewGroup) mTagsToViews.get(tag);
<ide> && arrayContains(tagsToDelete, viewToRemove.getId())) {
<ide> }
<ide>
<ide> if (mLayoutAnimationEnabled && mLayoutAnimator.shouldAnimateLayout(viewToDestroy)) {
<add> pendingDeletionTags.add(tagToDelete);
<ide> mLayoutAnimator.deleteView(
<ide> tag,
<ide> viewToDestroy,
<ide> public void onAnimationEnd() {
<ide>
<ide> viewManager.removeView(viewToManage, viewToDestroy);
<ide> dropView(viewToDestroy);
<add> pendingDeletionTags.remove(viewToDestroy.getId());
<ide> }
<ide> });
<ide> } else {
<ide> public void onAnimationEnd() {
<ide> + constructManageChildrenErrorMessage(
<ide> viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete));
<ide> }
<del> viewManager.addView(viewToManage, viewToAdd, viewAtIndex.mIndex);
<add>
<add> int normalizedIndex = viewAtIndex.mIndex;
<add> if (!pendingDeletionTags.isEmpty()) {
<add> normalizedIndex = 0;
<add> int counter = 0;
<add> while (normalizedIndex < viewToManage.getChildCount()) {
<add> if (counter == viewAtIndex.mIndex) {
<add> break;
<add> }
<add> View v = viewToManage.getChildAt(normalizedIndex);
<add> if (!pendingDeletionTags.contains(v.getId())) {
<add> counter++;
<add> }
<add> normalizedIndex++;
<add> }
<add> }
<add>
<add> viewManager.addView(viewToManage, viewToAdd, normalizedIndex);
<ide> }
<ide> }
<ide> } | 1 |
Go | Go | remove servicing mode | d4f37c08858b90e8603741ba92de8e0d39b88eb3 | <ide><path>daemon/monitor.go
<ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerd.EventType, ei libc
<ide> }
<ide>
<ide> daemon.setStateCounter(c)
<del> if err := c.CheckpointTo(daemon.containersReplica); err != nil {
<del> return err
<del> }
<del> return daemon.postRunProcessing(c, ei)
<add> return c.CheckpointTo(daemon.containersReplica)
<ide> }
<ide>
<ide> if execConfig := c.ExecCommands.Get(ei.ProcessID); execConfig != nil {
<ide><path>daemon/monitor_linux.go
<del>package daemon // import "github.com/docker/docker/daemon"
<del>
<del>import (
<del> "github.com/docker/docker/container"
<del> "github.com/docker/docker/libcontainerd"
<del>)
<del>
<del>// postRunProcessing perfoms any processing needed on the container after it has stopped.
<del>func (daemon *Daemon) postRunProcessing(_ *container.Container, _ libcontainerd.EventInfo) error {
<del> return nil
<del>}
<ide><path>daemon/monitor_windows.go
<del>package daemon // import "github.com/docker/docker/daemon"
<del>
<del>import (
<del> "context"
<del>
<del> "github.com/docker/docker/container"
<del> "github.com/docker/docker/libcontainerd"
<del> "github.com/pkg/errors"
<del> "github.com/sirupsen/logrus"
<del>)
<del>
<del>// postRunProcessing starts a servicing container if required
<del>func (daemon *Daemon) postRunProcessing(c *container.Container, ei libcontainerd.EventInfo) error {
<del> if ei.ExitCode == 0 && ei.UpdatePending {
<del> spec, err := daemon.createSpec(c)
<del> if err != nil {
<del> return err
<del> }
<del> // Turn on servicing
<del> spec.Windows.Servicing = true
<del>
<del> copts, err := daemon.getLibcontainerdCreateOptions(c)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> // Create a new servicing container, which will start, complete the
<del> // update, and merge back the results if it succeeded, all as part of
<del> // the below function call.
<del> ctx := context.Background()
<del> svcID := c.ID + "_servicing"
<del> logger := logrus.WithField("container", svcID)
<del> if err := daemon.containerd.Create(ctx, svcID, spec, copts); err != nil {
<del> c.SetExitCode(-1)
<del> return errors.Wrap(err, "post-run update servicing failed")
<del> }
<del> _, err = daemon.containerd.Start(ctx, svcID, "", false, nil)
<del> if err != nil {
<del> logger.WithError(err).Warn("failed to run servicing container")
<del> if err := daemon.containerd.Delete(ctx, svcID); err != nil {
<del> logger.WithError(err).Warn("failed to delete servicing container")
<del> }
<del> } else {
<del> if _, _, err := daemon.containerd.DeleteTask(ctx, svcID); err != nil {
<del> logger.WithError(err).Warn("failed to delete servicing container task")
<del> }
<del> if err := daemon.containerd.Delete(ctx, svcID); err != nil {
<del> logger.WithError(err).Warn("failed to delete servicing container")
<del> }
<del> }
<del> }
<del> return nil
<del>}
<ide><path>daemon/oci_windows.go
<ide> func (daemon *Daemon) createSpecWindowsFields(c *container.Container, s *specs.S
<ide> s.Windows.CredentialSpec = cs
<ide> }
<ide>
<del> // Assume we are not starting a container for a servicing operation
<del> s.Windows.Servicing = false
<del>
<ide> return nil
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunCredentialSpecWellFormed(c *check.C) {
<ide> dockerCmd(c, "run", `--security-opt=credentialspec=file://valid.json`, "busybox", "true")
<ide> }
<ide>
<del>// Windows specific test to ensure that a servicing app container is started
<del>// if necessary once a container exits. It does this by forcing a no-op
<del>// servicing event and verifying the event from Hyper-V-Compute
<del>func (s *DockerSuite) TestRunServicingContainer(c *check.C) {
<del> testRequires(c, DaemonIsWindows, SameHostDaemon)
<del>
<del> // This functionality does not exist in post-RS3 builds.
<del> // Note we get the version number from the full build string, as Windows
<del> // reports Windows 8 version 6.2 build 9200 from non-manifested binaries.
<del> // Ref: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx
<del> v, err := kernel.GetKernelVersion()
<del> c.Assert(err, checker.IsNil)
<del> build, _ := strconv.Atoi(strings.Split(strings.SplitN(v.String(), " ", 3)[2][1:], ".")[0])
<del> if build > 16299 {
<del> c.Skip("Disabled on post-RS3 builds")
<del> }
<del>
<del> out := cli.DockerCmd(c, "run", "-d", testEnv.PlatformDefaults.BaseImage, "cmd", "/c", "mkdir c:\\programdata\\Microsoft\\Windows\\ContainerUpdates\\000_000_d99f45d0-ffc8-4af7-bd9c-ea6a62e035c9_200 && sc control cexecsvc 255").Combined()
<del> containerID := strings.TrimSpace(out)
<del> cli.WaitExited(c, containerID, 60*time.Second)
<del>
<del> result := icmd.RunCommand("powershell", "echo", `(Get-WinEvent -ProviderName "Microsoft-Windows-Hyper-V-Compute" -FilterXPath 'Event[System[EventID=2010]]' -MaxEvents 1).Message`)
<del> result.Assert(c, icmd.Success)
<del> out2 := result.Combined()
<del> c.Assert(out2, checker.Contains, `"Servicing":true`, check.Commentf("Servicing container does not appear to have been started: %s", out2))
<del> c.Assert(out2, checker.Contains, `Windows Container (Servicing)`, check.Commentf("Didn't find 'Windows Container (Servicing): %s", out2))
<del> c.Assert(out2, checker.Contains, containerID+"_servicing", check.Commentf("Didn't find '%s_servicing': %s", containerID+"_servicing", out2))
<del>}
<del>
<ide> func (s *DockerSuite) TestRunDuplicateMount(c *check.C) {
<ide> testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
<ide>
<ide><path>libcontainerd/client_local_windows.go
<ide> func (c *client) Version(ctx context.Context) (containerd.Version, error) {
<ide> // | | Isolation=Process | Isolation=Hyper-V |
<ide> // +-----------------+--------------------------------------------+---------------------------------------------------+
<ide> // | VolumePath | \\?\\Volume{GUIDa} | |
<del>// | LayerFolderPath | %root%\windowsfilter\containerID | %root%\windowsfilter\containerID (servicing only) |
<add>// | LayerFolderPath | %root%\windowsfilter\containerID | |
<ide> // | Layers[] | ID=GUIDb;Path=%root%\windowsfilter\layerID | ID=GUIDb;Path=%root%\windowsfilter\layerID |
<ide> // | HvRuntime | | ImagePath=%root%\BaseLayerID\UtilityVM |
<ide> // +-----------------+--------------------------------------------+---------------------------------------------------+
<ide> func (c *client) Version(ctx context.Context) (containerd.Version, error) {
<ide> // "MappedDirectories": [],
<ide> // "HvPartition": false,
<ide> // "EndpointList": ["eef2649d-bb17-4d53-9937-295a8efe6f2c"],
<del>// "Servicing": false
<ide> //}
<ide> //
<ide> // Isolation=Hyper-V example:
<ide> func (c *client) Version(ctx context.Context) (containerd.Version, error) {
<ide> // "HvRuntime": {
<ide> // "ImagePath": "C:\\\\control\\\\windowsfilter\\\\65bf96e5760a09edf1790cb229e2dfb2dbd0fcdc0bf7451bae099106bfbfea0c\\\\UtilityVM"
<ide> // },
<del>// "Servicing": false
<ide> //}
<ide> func (c *client) Create(_ context.Context, id string, spec *specs.Spec, runtimeOptions interface{}) error {
<ide> if ctr := c.getContainer(id); ctr != nil {
<ide> func (c *client) createWindows(id string, spec *specs.Spec, runtimeOptions inter
<ide> IgnoreFlushesDuringBoot: spec.Windows.IgnoreFlushesDuringBoot,
<ide> HostName: spec.Hostname,
<ide> HvPartition: false,
<del> Servicing: spec.Windows.Servicing,
<ide> }
<ide>
<ide> if spec.Windows.Resources != nil {
<ide> func (c *client) createWindows(id string, spec *specs.Spec, runtimeOptions inter
<ide> waitCh: make(chan struct{}),
<ide> }
<ide>
<del> // Start the container. If this is a servicing container, this call
<del> // will block until the container is done with the servicing
<del> // execution.
<ide> logger.Debug("starting container")
<ide> if err = hcsContainer.Start(); err != nil {
<ide> c.logger.WithError(err).Error("failed to start container")
<ide> func (c *client) createLinux(id string, spec *specs.Spec, runtimeOptions interfa
<ide> waitCh: make(chan struct{}),
<ide> }
<ide>
<del> // Start the container. If this is a servicing container, this call
<del> // will block until the container is done with the servicing
<del> // execution.
<add> // Start the container.
<ide> logger.Debug("starting container")
<ide> if err = hcsContainer.Start(); err != nil {
<ide> c.logger.WithError(err).Error("failed to start container")
<ide> func (c *client) Start(_ context.Context, id, _ string, withStdin bool, attachSt
<ide> )
<ide> if ctr.ociSpec.Process != nil {
<ide> emulateConsole = ctr.ociSpec.Process.Terminal
<del> createStdErrPipe = !ctr.ociSpec.Process.Terminal && !ctr.ociSpec.Windows.Servicing
<add> createStdErrPipe = !ctr.ociSpec.Process.Terminal
<ide> }
<ide>
<ide> createProcessParms := &hcsshim.ProcessConfig{
<ide> EmulateConsole: emulateConsole,
<ide> WorkingDirectory: ctr.ociSpec.Process.Cwd,
<del> CreateStdInPipe: !ctr.ociSpec.Windows.Servicing,
<del> CreateStdOutPipe: !ctr.ociSpec.Windows.Servicing,
<add> CreateStdInPipe: true,
<add> CreateStdOutPipe: true,
<ide> CreateStdErrPipe: createStdErrPipe,
<ide> }
<ide>
<ide> func (c *client) Start(_ context.Context, id, _ string, withStdin bool, attachSt
<ide> }
<ide> logger.WithField("pid", p.pid).Debug("init process started")
<ide>
<del> // If this is a servicing container, wait on the process synchronously here and
<del> // if it succeeds, wait for it cleanly shutdown and merge into the parent container.
<del> if ctr.ociSpec.Windows.Servicing {
<del> // reapProcess takes the lock
<del> ctr.Unlock()
<del> defer ctr.Lock()
<del> exitCode := c.reapProcess(ctr, p)
<del>
<del> if exitCode != 0 {
<del> return -1, errors.Errorf("libcontainerd: servicing container %s returned non-zero exit code %d", ctr.id, exitCode)
<del> }
<del>
<del> return p.pid, nil
<del> }
<del>
<ide> dio, err := newIOFromProcess(newProcess, ctr.ociSpec.Process.Terminal)
<ide> if err != nil {
<ide> logger.WithError(err).Error("failed to get stdio pipes")
<ide> func (c *client) reapProcess(ctr *container, p *process) int {
<ide> eventErr = fmt.Errorf("hcsProcess.Close() failed %s", err)
<ide> }
<ide>
<del> var pendingUpdates bool
<ide> if p.id == InitProcessName {
<ide> // Update container status
<ide> ctr.Lock()
<ide> func (c *client) reapProcess(ctr *container, p *process) int {
<ide> close(ctr.waitCh)
<ide> ctr.Unlock()
<ide>
<del> // Handle any servicing
<del> if exitCode == 0 && ctr.isWindows && !ctr.ociSpec.Windows.Servicing {
<del> pendingUpdates, err = ctr.hcsContainer.HasPendingUpdates()
<del> logger.Infof("Pending updates: %v", pendingUpdates)
<del> if err != nil {
<del> logger.WithError(err).
<del> Warnf("failed to check for pending updates (container may have been killed)")
<del> }
<del> }
<del>
<ide> if err := c.shutdownContainer(ctr); err != nil {
<ide> exitCode = -1
<ide> logger.WithError(err).Warn("failed to shutdown container")
<ide> func (c *client) reapProcess(ctr *container, p *process) int {
<ide> }
<ide> }
<ide>
<del> if !(ctr.isWindows && ctr.ociSpec.Windows.Servicing) {
<del> c.eventQ.append(ctr.id, func() {
<del> ei := EventInfo{
<del> ContainerID: ctr.id,
<del> ProcessID: p.id,
<del> Pid: uint32(p.pid),
<del> ExitCode: uint32(exitCode),
<del> ExitedAt: exitedAt,
<del> UpdatePending: pendingUpdates,
<del> Error: eventErr,
<del> }
<del> c.logger.WithFields(logrus.Fields{
<add> c.eventQ.append(ctr.id, func() {
<add> ei := EventInfo{
<add> ContainerID: ctr.id,
<add> ProcessID: p.id,
<add> Pid: uint32(p.pid),
<add> ExitCode: uint32(exitCode),
<add> ExitedAt: exitedAt,
<add> Error: eventErr,
<add> }
<add> c.logger.WithFields(logrus.Fields{
<add> "container": ctr.id,
<add> "event": EventExit,
<add> "event-info": ei,
<add> }).Info("sending event")
<add> err := c.backend.ProcessEvent(ctr.id, EventExit, ei)
<add> if err != nil {
<add> c.logger.WithError(err).WithFields(logrus.Fields{
<ide> "container": ctr.id,
<ide> "event": EventExit,
<ide> "event-info": ei,
<del> }).Info("sending event")
<del> err := c.backend.ProcessEvent(ctr.id, EventExit, ei)
<del> if err != nil {
<del> c.logger.WithError(err).WithFields(logrus.Fields{
<del> "container": ctr.id,
<del> "event": EventExit,
<del> "event-info": ei,
<del> }).Error("failed to process event")
<del> }
<del> if p.id != InitProcessName {
<del> ctr.Lock()
<del> delete(ctr.execs, p.id)
<del> ctr.Unlock()
<del> }
<del> })
<del> }
<add> }).Error("failed to process event")
<add> }
<add> if p.id != InitProcessName {
<add> ctr.Lock()
<add> delete(ctr.execs, p.id)
<add> ctr.Unlock()
<add> }
<add> })
<ide>
<ide> return exitCode
<ide> }
<ide><path>libcontainerd/types.go
<ide> type EventInfo struct {
<ide> ExitCode uint32
<ide> ExitedAt time.Time
<ide> OOMKilled bool
<del> // Windows Only field
<del> UpdatePending bool
<del> Error error
<add> Error error
<ide> }
<ide>
<ide> // Backend defines callbacks that the client of the library needs to implement. | 7 |
Ruby | Ruby | add more tests for the dirty feature for enums | a0520fceff9148ebfbb2e09745ba1416bceef2bf | <ide><path>activerecord/lib/active_record/attribute_methods/dirty.rb
<ide> def write_attribute(attr, value)
<ide>
<ide> save_changed_attribute(attr, value)
<ide>
<del> # Carry on.
<ide> super(attr, value)
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/enum.rb
<ide> def enum(definitions)
<ide> def _enum_methods_module
<ide> @_enum_methods_module ||= begin
<ide> mod = Module.new do
<del> def save_changed_attribute(attr_name, value)
<del> if self.class.enum_attribute?(attr_name)
<del> old = clone_attribute_value(:read_attribute, attr_name)
<del> changed_attributes[attr_name] = self.class.public_send(attr_name.pluralize).key old
<del> else
<del> super
<add> private
<add> def save_changed_attribute(attr_name, value)
<add> if self.class.enum_attribute?(attr_name)
<add> if attribute_changed?(attr_name)
<add> old = changed_attributes[attr_name]
<add>
<add> if self.class.public_send(attr_name.pluralize)[old] == value
<add> changed_attributes.delete(attr_name)
<add> end
<add> else
<add> old = clone_attribute_value(:read_attribute, attr_name)
<add>
<add> if old != value
<add> changed_attributes[attr_name] = self.class.public_send(attr_name.pluralize).key old
<add> end
<add> end
<add> else
<add> super
<add> end
<ide> end
<del> end
<ide> end
<ide> include mod
<ide> mod
<ide><path>activerecord/test/cases/enum_test.rb
<ide> class EnumTest < ActiveRecord::TestCase
<ide> assert @book.attribute_changed?(:status, from: old_status, to: 'published')
<ide> end
<ide>
<add> test "enum didn't change" do
<add> old_status = @book.status
<add> @book.status = old_status
<add> assert_not @book.attribute_changed?(:status)
<add> end
<add>
<add> test "persist changes that are dirty" do
<add> old_status = @book.status
<add> @book.status = :published
<add> assert @book.attribute_changed?(:status)
<add> @book.status = :written
<add> assert @book.attribute_changed?(:status)
<add> end
<add>
<add> test "reverted changes that are not dirty" do
<add> old_status = @book.status
<add> @book.status = :published
<add> assert @book.attribute_changed?(:status)
<add> @book.status = old_status
<add> assert_not @book.attribute_changed?(:status)
<add> end
<add>
<add> test "reverted changes are not dirty going from nil to value and back" do
<add> book = Book.create!(nullable_status: nil)
<add>
<add> book.nullable_status = :married
<add> assert book.attribute_changed?(:nullable_status)
<add>
<add> book.nullable_status = nil
<add> assert_not book.attribute_changed?(:nullable_status)
<add> end
<add>
<ide> test "assign non existing value raises an error" do
<ide> e = assert_raises(ArgumentError) do
<ide> @book.status = :unknown
<ide><path>activerecord/test/models/book.rb
<ide> class Book < ActiveRecord::Base
<ide>
<ide> enum status: [:proposed, :written, :published]
<ide> enum read_status: {unread: 0, reading: 2, read: 3}
<add> enum nullable_status: [:single, :married]
<ide>
<ide> def published!
<ide> super
<ide><path>activerecord/test/schema/schema.rb
<ide> def create_table(*args, &block)
<ide> t.column :name, :string
<ide> t.column :status, :integer, default: 0
<ide> t.column :read_status, :integer, default: 0
<add> t.column :nullable_status, :integer
<ide> end
<ide>
<ide> create_table :booleans, force: true do |t| | 5 |
Text | Text | remove duplicate sections from 'react/state' | 7e866537a156ec3a978cf47d693936719619aabf | <ide><path>client/src/pages/guide/english/react/state/index.md
<ide> export default App;
<ide> ## Updating State
<ide> You can change the data stored in the state of your application using the `setState` method on your component.
<ide>
<del>```js
<del>this.setState({ value: 1 });
<del>```
<del>
<del>Keep in mind that `setState` is asynchronous so you should be careful when using the current state to set a new state. A good example of this would be if you want to increment a value in your state.
<del>
<del>#### The Wrong Way
<del>```js
<del>this.setState({ value: this.state.value + 1 });
<del>```
<del>
<del>This can lead to unexpected behavior in your app if the code above is called multiple times in the same update cycle. To avoid this you can pass an updater callback function to `setState` instead of an object.
<del>
<del>#### The Right Way
<del>```js
<del>this.setState(prevState => ({ value: prevState.value + 1 }));
<del>```
<del>
<del>## Updating State
<del>You can change the data stored in the state of your application using the `setState` method on your component.
<del>
<ide> ```js
<ide> this.setState({value: 1});
<ide> ```
<ide>
<ide> Keep in mind that `setState` may be asynchronous so you should be careful when using the current state to set a new state. A good example of this would be if you want to increment a value in your state.
<ide>
<del>##### The Wrong Way
<add>#### The Wrong Way
<ide> ```js
<ide> this.setState({value: this.state.value + 1});
<ide> ```
<ide>
<ide> This can lead to unexpected behavior in your app if the code above is called multiple times in the same update cycle. To avoid this you can pass an updater callback function to `setState` instead of an object.
<ide>
<del>##### The Right Way
<add>#### The Right Way
<ide> ```js
<ide> this.setState(prevState => ({value: prevState.value + 1}));
<ide> ```
<ide>
<del>##### The Cleaner Way
<add>#### The Cleaner Way
<ide> ```
<ide> this.setState(({ value }) => ({ value: value + 1 }));
<ide> ```
<ide>
<ide> When only a limited number of fields in the state object is required, object destructing can be used for cleaner code.
<ide>
<del>### More Information
<add>#### More Information
<ide>
<ide> - [React - State and Lifecycle](https://reactjs.org/docs/state-and-lifecycle.html)
<ide> - [React - Lifting State Up](https://reactjs.org/docs/lifting-state-up.html) | 1 |
Python | Python | fix spelling of von hann's surname | 7897da783e93c43711cf7d5b555674fefba4d16e | <ide><path>numpy/lib/function_base.py
<ide> def hanning(M):
<ide> .. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
<ide> \\qquad 0 \\leq n \\leq M-1
<ide>
<del> The Hanning was named for Julius van Hann, an Austrian meteorologist.
<add> The Hanning was named for Julius von Hann, an Austrian meteorologist.
<ide> It is also known as the Cosine Bell. Some authors prefer that it be
<ide> called a Hann window, to help avoid confusion with the very similar
<ide> Hamming window. | 1 |
Text | Text | propose a basic solution to adjacency list problem | 781c2170010a46a7b8545f9adf95ac1dade4c56a | <ide><path>guide/english/certifications/coding-interview-prep/data-structures/adjacency-list/index.md
<ide> title: Adjacency List
<ide> ---
<ide> ## Adjacency List
<add> Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program  and write your own code 
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/adjacency-list/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>###  Problem Explanation:
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>To solve this problem, you have to create a Javascript Object to emulate an undirected graph in the form of an adjacency list.
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>##  Hint: 1
<add>
<add>Create keys with the names James, Jill, Jenny and Jeff.
<add>
<add>> _try to solve the problem now_
<add>
<add>##  Hint: 2
<add>
<add>Read the presentation and try to understand what it means to be an undirected graph.
<add>
<add>> _try to solve the problem now_
<add>
<add>
<add>
<add>## Spoiler Alert!
<add>
<add>
<add>
<add>**Solution ahead!**
<add>
<add>##  Basic Code Solution:
<add>
<add> var undirectedAdjList = {
<add> James: ["Jeff"],
<add> Jill: ["Jenny"],
<add> Jenny: ["Jill", "Jeff"],
<add> Jeff: ["Jenny", "James"]
<add> };
<add>
<add>
<add>### Code Explanation:
<add>
<add>* The undirected graph is created using a Javascript Object. Each unique name is a key and the each person who has a relationship with the name is in the unique name's array value. e.g. if James and Jeff have a relationship, Jeff will be in James's array value and James will be in Jeff's array value.
<add>
<add>##  NOTES FOR CONTRIBUTIONS:
<add>
<add>*  **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
<add>* Add an explanation of your solution.
<add>* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**.  | 1 |
PHP | PHP | remove size argument from constructor | 860267cc6b9fa3e41de18ffd7e7326898007ac11 | <ide><path>src/Illuminate/Http/Testing/File.php
<ide> public function __construct($name, $tempFile)
<ide>
<ide> parent::__construct(
<ide> $this->tempFilePath(), $name, $this->getMimeType(),
<del> filesize($this->tempFilePath()), null, true
<add> null, true
<ide> );
<ide> }
<ide> | 1 |
Javascript | Javascript | update unsubscribe paths | cdc44e4b7e0b2d9cb3d7a1655d237279aa43a702 | <ide><path>server/boot/randomAPIs.js
<ide> module.exports = function(app) {
<ide> router.get('/pmi-acp-agile-project-managers-form', agileProjectManagersForm);
<ide> router.get('/nonprofits', nonprofits);
<ide> router.get('/nonprofits-form', nonprofitsForm);
<del> router.get('/unsubscribe/:email', unsubscribe);
<add> router.get('/unsubscribe/:email', unsubscribeMonthly);
<add> router.get('/unsubscribe-notifications/:email', unsubscribeNotifications);
<add> router.get('/unsubscribe-quincy/:email', unsubscribeQuincy);
<ide> router.get('/unsubscribed', unsubscribed);
<ide> router.get('/get-started', getStarted);
<ide> router.get('/submit-cat-photo', submitCatPhoto);
<ide> module.exports = function(app) {
<ide> res.redirect('https://twitch.tv/freecodecamp');
<ide> }
<ide>
<del> function unsubscribe(req, res, next) {
<add> function unsubscribeMonthly(req, res, next) {
<ide> User.findOne({ where: { email: req.params.email } }, function(err, user) {
<del> if (user) {
<add> user.updateAttribute('sendMonthlyEmail', false, function(err) {
<ide> if (err) { return next(err); }
<del> user.sendMonthlyEmail = false;
<del> return user.save(function() {
<del> if (err) { return next(err); }
<del> return res.redirect('/unsubscribed');
<del> });
<del> } else {
<del> return res.redirect('/unsubscribed');
<del> }
<add> req.flash('info', { msg: 'We\'ve successfully updated your Email preferences.' });
<add> res.redirect('/unsubscribed');
<add> });
<add> });
<add> }
<add>
<add> function unsubscribeNotifications(req, res, next) {
<add> User.findOne({ where: { email: req.params.email } }, function(err, user) {
<add> user.updateAttribute('sendNotificationEmail', false, function(err) {
<add> if (err) { return next(err); }
<add> req.flash('info', { msg: 'We\'ve successfully updated your Email preferences.' });
<add> res.redirect('/unsubscribed');
<add> });
<add> });
<add> }
<add>
<add> function unsubscribeQuincy(req, res, next) {
<add> User.findOne({ where: { email: req.params.email } }, function(err, user) {
<add> user.updateAttribute('sendQuincyEmail', false, function(err) {
<add> if (err) { return next(err); }
<add> req.flash('info', { msg: 'We\'ve successfully updated your Email preferences.' });
<add> res.redirect('/unsubscribed');
<add> });
<ide> });
<ide> }
<ide> | 1 |
Javascript | Javascript | add param info | de065f196129766f7e774ccf0a24916db2e0f06d | <ide><path>src/ngRoute/directive/ngView.js
<ide> ngRouteModule.directive('ngView', ngViewFillContentFactory);
<ide> *
<ide> * @scope
<ide> * @priority 400
<add> * @param {string=} onload Expression to evaluate whenever the view updates.
<add> *
<add> * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
<add> * $anchorScroll} to scroll the viewport after the view is updated.
<add> *
<add> * - If the attribute is not set, disable scrolling.
<add> * - If the attribute is set without value, enable scrolling.
<add> * - Otherwise enable scrolling only if the expression evaluates to truthy value.
<ide> * @example
<ide> <example module="ngViewExample" deps="angular-route.js" animations="true">
<ide> <file name="index.html"> | 1 |
Javascript | Javascript | remove duplicate util binding | 2bf4697ff4be6a510410be1f1e67549be347614b | <ide><path>lib/repl.js
<ide> const {
<ide> const internalUtil = require('internal/util');
<ide> const util = require('util');
<ide> const { internalBinding } = require('internal/bootstrap/loaders');
<del>const utilBinding = internalBinding('util');
<ide> const { inherits } = util;
<ide> const Stream = require('stream');
<ide> const vm = require('vm');
<ide> const {
<ide> propertyFilter: {
<ide> ALL_PROPERTIES,
<ide> SKIP_SYMBOLS
<del> }
<add> },
<add> startSigintWatchdog,
<add> stopSigintWatchdog
<ide> } = internalBinding('util');
<ide>
<ide> // Lazy-loaded.
<ide> function REPLServer(prompt,
<ide> if (self.breakEvalOnSigint) {
<ide> // Start the SIGINT watchdog before entering raw mode so that a very
<ide> // quick Ctrl+C doesn't lead to aborting the process completely.
<del> if (!utilBinding.startSigintWatchdog())
<add> if (!startSigintWatchdog())
<ide> throw new ERR_CANNOT_WATCH_SIGINT();
<ide> previouslyInRawMode = self._setRawMode(false);
<ide> }
<ide> function REPLServer(prompt,
<ide>
<ide> // Returns true if there were pending SIGINTs *after* the script
<ide> // has terminated without being interrupted itself.
<del> if (utilBinding.stopSigintWatchdog()) {
<add> if (stopSigintWatchdog()) {
<ide> self.emit('SIGINT');
<ide> }
<ide> } | 1 |
Javascript | Javascript | remove unnecessary check for `nativearray` | 69f6bea2c26d60c4c15ac96a674fa0865632d8fc | <ide><path>packages/ember-runtime/lib/system/native_array.js
<ide> forEach(NativeArray.keys(), function(methodName) {
<ide> }
<ide> });
<ide>
<del>if (ignore.length > 0) {
<del> NativeArray = NativeArray.without.apply(NativeArray, ignore);
<del>}
<add>NativeArray = NativeArray.without.apply(NativeArray, ignore);
<ide>
<ide> /**
<ide> Creates an `Ember.NativeArray` from an Array like object. | 1 |
Javascript | Javascript | fix transition bug | bcd6a56de6a5a2491d60b62badf3a672188a3a7d | <ide><path>common/app/routes/Hikes/flux/Actions.js
<ide> export default Actions({
<ide> userAnswer,
<ide> props: {
<ide> hike: { id, name, tests, challengeType },
<del> currentQuestion
<add> currentQuestion,
<add> username
<ide> }
<ide> }) {
<ide>
<ide> export default Actions({
<ide> }
<ide>
<ide> // challenge completed
<add> const optimisticSave = username ?
<add> this.post$('/completed-challenge', { id, name, challengeType }) :
<add> Observable.just(true);
<add>
<ide> const correctAnswer = {
<ide> transform(state) {
<ide> const hikesApp = {
<ide> export default Actions({
<ide> }
<ide> };
<ide>
<del> return this.post$('/completed-challenge', { id, name, challengeType })
<del> .map(() => {
<del> return {
<del> transform(state) {
<del> const { hikes, currentHike: { id } } = state.hikesApp;
<del> const currentHike = findNextHike(hikes, id);
<add> return Observable.just({
<add> transform(state) {
<add> const { hikes, currentHike: { id } } = state.hikesApp;
<add> const currentHike = findNextHike(hikes, id);
<ide>
<del> // go to next route
<del> state.route = currentHike && currentHike.dashedName ?
<del> `/hikes/${ currentHike.dashedName }` :
<del> '/hikes';
<add> // go to next route
<add> state.route = currentHike && currentHike.dashedName ?
<add> `/hikes/${ currentHike.dashedName }` :
<add> '/hikes';
<ide>
<del> const hikesApp = {
<del> ...state.hikesApp,
<del> currentHike,
<del> showQuestions: false
<del> };
<add> const hikesApp = {
<add> ...state.hikesApp,
<add> currentHike,
<add> showQuestions: false,
<add> currentQuestion: 1,
<add> mouse: [0, 0]
<add> };
<ide>
<del> return { ...state, hikesApp };
<del> }
<del> };
<add> return { ...state, hikesApp };
<add> },
<add> optimistic: optimisticSave
<ide> })
<add> .delay(500)
<ide> .startWith(correctAnswer)
<ide> .catch(err => {
<ide> console.error(err); | 1 |
Python | Python | use yaml.safe_load instead of load | 62ed1f82707916a23b4e97aae8e48f09ddaf1dea | <ide><path>tests/schemas/test_managementcommand.py
<ide> def test_renders_default_schema_with_custom_title_url_and_description(self):
<ide> '--description=Sample description',
<ide> stdout=self.out)
<ide> # Check valid YAML was output.
<del> schema = yaml.load(self.out.getvalue())
<add> schema = yaml.safe_load(self.out.getvalue())
<ide> assert schema['openapi'] == '3.0.2'
<ide>
<ide> def test_renders_openapi_json_schema(self): | 1 |
Javascript | Javascript | make .getrepo() submodule-aware | a79a528fd1de2ed1360ce3c2cc31a165b5183b3c | <ide><path>spec/git-repository-async-spec.js
<ide> function copyRepository (name = 'working-dir') {
<ide> return fs.realpathSync(workingDirPath)
<ide> }
<ide>
<add>function copySubmoduleRepository () {
<add> const workingDirectory = copyRepository('repo-with-submodules')
<add> const reGit = (name) => {
<add> fs.renameSync(path.join(workingDirectory, name, 'git.git'), path.join(workingDirectory, name, '.git'))
<add> }
<add> reGit('jstips')
<add> reGit('You-Dont-Need-jQuery')
<add>
<add> return workingDirectory
<add>}
<add>
<ide> describe('GitRepositoryAsync', () => {
<ide> let repo
<ide>
<ide> describe('GitRepositoryAsync', () => {
<ide> })
<ide> })
<ide>
<add> describe('.getRepo()', () => {
<add> beforeEach(() => {
<add> const workingDirectory = copySubmoduleRepository()
<add> repo = GitRepositoryAsync.open(workingDirectory)
<add> waitsForPromise(() => repo.refreshStatus())
<add> })
<add>
<add> it('returns the repository when not given a path', async () => {
<add> const nodeGitRepo1 = await repo.repoPromise
<add> const nodeGitRepo2 = await repo.getRepo()
<add> expect(nodeGitRepo1.workdir()).toBe(nodeGitRepo2.workdir())
<add> })
<add>
<add> it('returns the repository when given a non-submodule path', async () => {
<add> const nodeGitRepo1 = await repo.repoPromise
<add> const nodeGitRepo2 = await repo.getRepo('README')
<add> expect(nodeGitRepo1.workdir()).toBe(nodeGitRepo2.workdir())
<add> })
<add>
<add> it('returns the submodule repository when given a submodule path', async () => {
<add> const nodeGitRepo1 = await repo.repoPromise
<add> const nodeGitRepo2 = await repo.getRepo('jstips')
<add> expect(nodeGitRepo1.workdir()).not.toBe(nodeGitRepo2.workdir())
<add>
<add> const nodeGitRepo3 = await repo.getRepo('jstips/README.md')
<add> expect(nodeGitRepo1.workdir()).not.toBe(nodeGitRepo3.workdir())
<add> expect(nodeGitRepo2.workdir()).toBe(nodeGitRepo3.workdir())
<add> })
<add> })
<add>
<ide> describe('.openRepository()', () => {
<ide> it('returns a new repository instance', async () => {
<ide> repo = openFixture('master.git')
<ide> describe('GitRepositoryAsync', () => {
<ide>
<ide> describe('in a repository with submodules', () => {
<ide> beforeEach(() => {
<del> const workingDirectory = copyRepository('repo-with-submodules')
<add> const workingDirectory = copySubmoduleRepository()
<ide> repo = GitRepositoryAsync.open(workingDirectory)
<ide> modifiedPath = path.join(workingDirectory, 'jstips', 'README.md')
<ide> newPath = path.join(workingDirectory, 'You-Dont-Need-jQuery', 'untracked.txt')
<ide> cleanPath = path.join(workingDirectory, 'jstips', 'CONTRIBUTING.md')
<ide> fs.writeFileSync(newPath, '')
<ide> fs.writeFileSync(modifiedPath, 'making this path modified')
<ide> newPath = fs.absolute(newPath) // specs could be running under symbol path.
<del>
<del> const reGit = (name) => {
<del> fs.renameSync(path.join(workingDirectory, name, 'git.git'), path.join(workingDirectory, name, '.git'))
<del> }
<del> reGit('jstips')
<del> reGit('You-Dont-Need-jQuery')
<ide> })
<ide>
<ide> it('returns status information for all new and modified files', async () => {
<ide><path>src/git-repository-async.js
<ide> export default class GitRepositoryAsync {
<ide> })
<ide> }
<ide>
<add> // Get the submodule for the given path.
<add> //
<add> // Returns a {Promise} which resolves to the {GitRepositoryAsync} submodule or
<add> // null if it isn't a submodule path.
<ide> async _submoduleForPath (_path) {
<ide> let relativePath = await this.relativizeToWorkingDirectory(_path)
<del> for (const {submodulePath, submoduleRepo} in this.submodules) {
<add> for (const submodulePath in this.submodules) {
<add> const submoduleRepo = this.submodules[submodulePath]
<ide> if (relativePath === submodulePath) {
<ide> return submoduleRepo
<ide> } else if (relativePath.indexOf(`${submodulePath}/`) === 0) {
<ide> export default class GitRepositoryAsync {
<ide>
<ide> if (!_path) return this.repoPromise
<ide>
<del> return this.isSubmodule(_path)
<del> .then(isSubmodule => {
<del> if (isSubmodule) {
<del> return Git.Repository.open(_path)
<del> } else {
<del> return this.repoPromise
<del> }
<del> })
<add> return this._submoduleForPath(_path)
<add> .then(submodule => submodule ? submodule.getRepo() : this.repoPromise)
<ide> }
<ide>
<ide> // Open a new instance of the underlying {NodeGit.Repository}. | 2 |
Text | Text | update readme with the javadoc link | 2cdce62c3d9a1a5aec12676343e03e694a8a6e29 | <ide><path>spring-web-reactive/README.md
<ide> Spring Reactive JAR dependency is available from Spring snapshot repository:
<ide> - Version: `0.1.0.BUILD-SNAPSHOT`
<ide>
<ide> ## Documentation
<del>See the current [Javadoc][] and [reference docs][].
<add>See the current [Javadoc][].
<ide>
<ide> ## Sample application
<ide> [Spring Reactive Playground] is a sample application based on Spring Reactive and on MongoDB,
<ide> The Spring Reactive is released under version 2.0 of the [Apache License][].
<ide> [issue tracker]: https://github.com/spring-projects/spring-reactive/issues
<ide> [Pull requests]: http://help.github.com/send-pull-requests
<ide> [Apache License]: http://www.apache.org/licenses/LICENSE-2.0
<add>[Javadoc]: https://repo.spring.io/snapshot/org/springframework/reactive/spring-reactive/0.1.0.BUILD-SNAPSHOT/spring-reactive-0.1.0.BUILD-SNAPSHOT-javadoc.jar!/index.html | 1 |
PHP | PHP | update command.php | ac9f29da4785c8b942ced8c4ab308214d618a22b | <ide><path>src/Illuminate/Console/Command.php
<ide> public function run(InputInterface $input, OutputInterface $output)
<ide> */
<ide> protected function execute(InputInterface $input, OutputInterface $output)
<ide> {
<del> $method = method_exists($this, 'handle') ? 'handle' : 'fire';
<del>
<del> return $this->laravel->call([$this, $method]);
<add> return $this->laravel->call([$this, 'handle']);
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | make internal methods to private | e4108fc619e0f1c28cdec6049d31f2db01d56dfd | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
<ide> def lookup_cast_type_from_column(column) # :nodoc:
<ide> lookup_cast_type(column.sql_type)
<ide> end
<ide>
<del> def fetch_type_metadata(sql_type)
<del> cast_type = lookup_cast_type(sql_type)
<del> SqlTypeMetadata.new(
<del> sql_type: sql_type,
<del> type: cast_type.type,
<del> limit: cast_type.limit,
<del> precision: cast_type.precision,
<del> scale: cast_type.scale,
<del> )
<del> end
<del>
<ide> # Quotes a string, escaping any ' (single quote) and \ (backslash)
<ide> # characters.
<ide> def quote_string(s)
<ide> def type_casted_binds(binds) # :nodoc:
<ide> end
<ide>
<ide> private
<add> def lookup_cast_type(sql_type)
<add> type_map.lookup(sql_type)
<add> end
<add>
<ide> def id_value_for_database(value)
<ide> if primary_key = value.class.primary_key
<ide> value.instance_variable_get(:@attributes)[primary_key].value_for_database
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb
<ide> def action_sql(action, dependency)
<ide> end
<ide> end
<ide> end
<add> SchemaCreation = AbstractAdapter::SchemaCreation # :nodoc:
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def foreign_key_exists?(from_table, options_or_to_table = {})
<ide> foreign_key_for(from_table, options_or_to_table).present?
<ide> end
<ide>
<del> def foreign_key_for(from_table, options_or_to_table = {}) # :nodoc:
<del> return unless supports_foreign_keys?
<del> foreign_keys(from_table).detect { |fk| fk.defined_for? options_or_to_table }
<del> end
<del>
<del> def foreign_key_for!(from_table, options_or_to_table = {}) # :nodoc:
<del> foreign_key_for(from_table, options_or_to_table) || \
<del> raise(ArgumentError, "Table '#{from_table}' has no foreign key for #{options_or_to_table}")
<del> end
<del>
<ide> def foreign_key_column_for(table_name) # :nodoc:
<ide> prefix = Base.table_name_prefix
<ide> suffix = Base.table_name_suffix
<ide> def dump_schema_information #:nodoc:
<ide> insert_versions_sql(versions)
<ide> end
<ide>
<del> def insert_versions_sql(versions) # :nodoc:
<del> sm_table = quote_table_name(ActiveRecord::SchemaMigration.table_name)
<del>
<del> if versions.is_a?(Array)
<del> sql = "INSERT INTO #{sm_table} (version) VALUES\n"
<del> sql << versions.map { |v| "(#{quote(v)})" }.join(",\n")
<del> sql << ";\n\n"
<del> sql
<del> else
<del> "INSERT INTO #{sm_table} (version) VALUES (#{quote(versions)});"
<del> end
<del> end
<del>
<ide> def initialize_schema_migrations_table # :nodoc:
<ide> ActiveRecord::SchemaMigration.create_table
<ide> end
<ide> def rename_column_indexes(table_name, column_name, new_column_name)
<ide> end
<ide> end
<ide>
<add> def schema_creation
<add> SchemaCreation.new(self)
<add> end
<add>
<ide> def create_table_definition(*args)
<ide> TableDefinition.new(*args)
<ide> end
<ide> def create_alter_table(name)
<ide> AlterTable.new create_table_definition(name)
<ide> end
<ide>
<add> def fetch_type_metadata(sql_type)
<add> cast_type = lookup_cast_type(sql_type)
<add> SqlTypeMetadata.new(
<add> sql_type: sql_type,
<add> type: cast_type.type,
<add> limit: cast_type.limit,
<add> precision: cast_type.precision,
<add> scale: cast_type.scale,
<add> )
<add> end
<add>
<ide> def index_column_names(column_names)
<ide> if column_names.is_a?(String) && /\W/.match?(column_names)
<ide> column_names
<ide> def foreign_key_name(table_name, options)
<ide> end
<ide> end
<ide>
<add> def foreign_key_for(from_table, options_or_to_table = {})
<add> return unless supports_foreign_keys?
<add> foreign_keys(from_table).detect { |fk| fk.defined_for? options_or_to_table }
<add> end
<add>
<add> def foreign_key_for!(from_table, options_or_to_table = {})
<add> foreign_key_for(from_table, options_or_to_table) || \
<add> raise(ArgumentError, "Table '#{from_table}' has no foreign key for #{options_or_to_table}")
<add> end
<add>
<add> def extract_foreign_key_action(specifier)
<add> case specifier
<add> when "CASCADE"; :cascade
<add> when "SET NULL"; :nullify
<add> when "RESTRICT"; :restrict
<add> end
<add> end
<add>
<ide> def validate_index_length!(table_name, new_name, internal = false)
<ide> max_index_length = internal ? index_name_length : allowed_index_name_length
<ide>
<ide> def can_remove_index_by_name?(options)
<ide> options.is_a?(Hash) && options.key?(:name) && options.except(:name, :algorithm).empty?
<ide> end
<ide>
<add> def insert_versions_sql(versions)
<add> sm_table = quote_table_name(ActiveRecord::SchemaMigration.table_name)
<add>
<add> if versions.is_a?(Array)
<add> sql = "INSERT INTO #{sm_table} (version) VALUES\n"
<add> sql << versions.map { |v| "(#{quote(v)})" }.join(",\n")
<add> sql << ";\n\n"
<add> sql
<add> else
<add> "INSERT INTO #{sm_table} (version) VALUES (#{quote(versions)});"
<add> end
<add> end
<add>
<ide> def data_source_sql(name = nil, type: nil)
<ide> raise NotImplementedError
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> class AbstractAdapter
<ide> SIMPLE_INT = /\A\d+\z/
<ide>
<ide> attr_accessor :visitor, :pool
<del> attr_reader :schema_cache, :owner, :logger
<add> attr_reader :schema_cache, :owner, :logger, :prepared_statements
<ide> alias :in_use? :owner
<ide>
<ide> def self.type_cast_config_to_integer(config)
<ide> def self.type_cast_config_to_boolean(config)
<ide> end
<ide> end
<ide>
<del> attr_reader :prepared_statements
<del>
<ide> def initialize(connection, logger = nil, config = {}) # :nodoc:
<ide> super()
<ide>
<ide> def compile(bvs, conn)
<ide> end
<ide> end
<ide>
<del> def collector
<del> if prepared_statements
<del> SQLString.new
<del> else
<del> BindCollector.new
<del> end
<del> end
<del>
<del> def arel_visitor # :nodoc:
<del> Arel::Visitors::ToSql.new(self)
<del> end
<del>
<ide> def valid_type?(type) # :nodoc:
<ide> !native_database_types[type].nil?
<ide> end
<ide>
<del> def schema_creation
<del> SchemaCreation.new self
<del> end
<del>
<ide> # this method must only be called while holding connection pool's mutex
<ide> def lease
<ide> if in_use?
<ide> def type_map # :nodoc:
<ide> end
<ide> end
<ide>
<del> def new_column(name, default, sql_type_metadata, null, table_name, default_function = nil, collation = nil) # :nodoc:
<del> Column.new(name, default, sql_type_metadata, null, table_name, default_function, collation)
<del> end
<del>
<del> def lookup_cast_type(sql_type) # :nodoc:
<del> type_map.lookup(sql_type)
<del> end
<del>
<ide> def column_name_for_operation(operation, node) # :nodoc:
<ide> visitor.accept(node, collector).value
<ide> end
<ide> def column_for(table_name, column_name)
<ide> columns(table_name).detect { |c| c.name == column_name } ||
<ide> raise(ActiveRecordError, "No such column: #{table_name}.#{column_name}")
<ide> end
<add>
<add> def collector
<add> if prepared_statements
<add> SQLString.new
<add> else
<add> BindCollector.new
<add> end
<add> end
<add>
<add> def arel_visitor
<add> Arel::Visitors::ToSql.new(self)
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def update_table_definition(table_name, base) # :nodoc:
<ide> MySQL::Table.new(table_name, base)
<ide> end
<ide>
<del> def schema_creation # :nodoc:
<del> MySQL::SchemaCreation.new(self)
<del> end
<del>
<del> def arel_visitor # :nodoc:
<del> Arel::Visitors::MySQL.new(self)
<del> end
<del>
<ide> ##
<ide> # :singleton-method:
<ide> # By default, the Mysql2Adapter will consider all columns of type <tt>tinyint(1)</tt>
<ide> def each_hash(result) # :nodoc:
<ide> raise NotImplementedError
<ide> end
<ide>
<del> def new_column(*args) #:nodoc:
<del> MySQL::Column.new(*args)
<del> end
<del>
<ide> # Must return the MySQL error number from the exception, if the exception has an
<ide> # error number.
<ide> def error_number(exception) # :nodoc:
<ide> def indexes(table_name, name = nil) #:nodoc:
<ide> indexes
<ide> end
<ide>
<del> def new_column_from_field(table_name, field) # :nodoc:
<del> type_metadata = fetch_type_metadata(field[:Type], field[:Extra])
<del> if type_metadata.type == :datetime && field[:Default] == "CURRENT_TIMESTAMP"
<del> default, default_function = nil, field[:Default]
<del> else
<del> default, default_function = field[:Default], nil
<del> end
<del> new_column(field[:Field], default, type_metadata, field[:Null] == "YES", table_name, default_function, field[:Collation], comment: field[:Comment].presence)
<del> end
<del>
<ide> def table_comment(table_name) # :nodoc:
<ide> scope = quoted_scope(table_name)
<ide>
<ide> def extract_precision(sql_type)
<ide> end
<ide> end
<ide>
<del> def fetch_type_metadata(sql_type, extra = "")
<del> MySQL::TypeMetadata.new(super(sql_type), extra: extra)
<del> end
<del>
<ide> def add_index_length(quoted_columns, **options)
<ide> if length = options[:length]
<ide> case length
<ide> def column_definitions(table_name) # :nodoc:
<ide> end
<ide> end
<ide>
<del> def extract_foreign_key_action(specifier) # :nodoc:
<del> case specifier
<del> when "CASCADE"; :cascade
<del> when "SET NULL"; :nullify
<del> end
<del> end
<del>
<ide> def create_table_info(table_name) # :nodoc:
<ide> select_one("SHOW CREATE TABLE #{quote_table_name(table_name)}")["Create Table"]
<ide> end
<ide>
<del> def create_table_definition(*args) # :nodoc:
<del> MySQL::TableDefinition.new(*args)
<add> def arel_visitor
<add> Arel::Visitors::MySQL.new(self)
<ide> end
<ide>
<ide> def mismatched_foreign_key(message)
<ide><path>activerecord/lib/active_record/connection_adapters/mysql/schema_statements.rb
<ide> module ConnectionAdapters
<ide> module MySQL
<ide> module SchemaStatements # :nodoc:
<ide> private
<add> def schema_creation
<add> MySQL::SchemaCreation.new(self)
<add> end
<add>
<add> def create_table_definition(*args)
<add> MySQL::TableDefinition.new(*args)
<add> end
<add>
<add> def new_column_from_field(table_name, field)
<add> type_metadata = fetch_type_metadata(field[:Type], field[:Extra])
<add> if type_metadata.type == :datetime && field[:Default] == "CURRENT_TIMESTAMP"
<add> default, default_function = nil, field[:Default]
<add> else
<add> default, default_function = field[:Default], nil
<add> end
<add>
<add> MySQL::Column.new(
<add> field[:Field],
<add> default,
<add> type_metadata,
<add> field[:Null] == "YES",
<add> table_name,
<add> default_function,
<add> field[:Collation],
<add> comment: field[:Comment].presence
<add> )
<add> end
<add>
<add> def fetch_type_metadata(sql_type, extra = "")
<add> MySQL::TypeMetadata.new(super(sql_type), extra: extra)
<add> end
<add>
<add> def extract_foreign_key_action(specifier)
<add> super unless specifier == "RESTRICT"
<add> end
<add>
<ide> def data_source_sql(name = nil, type: nil)
<ide> scope = quoted_scope(name, type: type)
<ide>
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
<ide> def lookup_cast_type_from_column(column) # :nodoc:
<ide> end
<ide>
<ide> private
<add> def lookup_cast_type(sql_type)
<add> super(select_value("SELECT #{quote(sql_type)}::regtype::oid", "SCHEMA").to_i)
<add> end
<ide>
<ide> def _quote(value)
<ide> case value
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
<ide> def indexes(table_name, name = nil) # :nodoc:
<ide> end.compact
<ide> end
<ide>
<del> def new_column_from_field(table_name, field) # :nondoc:
<del> column_name, type, default, notnull, oid, fmod, collation, comment = field
<del> oid = oid.to_i
<del> fmod = fmod.to_i
<del> type_metadata = fetch_type_metadata(column_name, type, oid, fmod)
<del> default_value = extract_value_from_default(default)
<del> default_function = extract_default_function(default_value, default)
<del> PostgreSQLColumn.new(
<del> column_name,
<del> default_value,
<del> type_metadata,
<del> !notnull,
<del> table_name,
<del> default_function,
<del> collation,
<del> comment: comment.presence
<del> )
<del> end
<del>
<ide> def table_options(table_name) # :nodoc:
<ide> if comment = table_comment(table_name)
<ide> { comment: comment }
<ide> def foreign_keys(table_name)
<ide> end
<ide> end
<ide>
<del> def extract_foreign_key_action(specifier) # :nodoc:
<del> case specifier
<del> when "c"; :cascade
<del> when "n"; :nullify
<del> when "r"; :restrict
<del> end
<del> end
<del>
<ide> # Maps logical Rails types to PostgreSQL-specific data types.
<ide> def type_to_sql(type, limit: nil, precision: nil, scale: nil, array: nil, **) # :nodoc:
<ide> sql = \
<ide> def columns_for_distinct(columns, orders) #:nodoc:
<ide> [super, *order_columns].join(", ")
<ide> end
<ide>
<del> def fetch_type_metadata(column_name, sql_type, oid, fmod)
<del> cast_type = get_oid_type(oid, fmod, column_name, sql_type)
<del> simple_type = SqlTypeMetadata.new(
<del> sql_type: sql_type,
<del> type: cast_type.type,
<del> limit: cast_type.limit,
<del> precision: cast_type.precision,
<del> scale: cast_type.scale,
<del> )
<del> PostgreSQLTypeMetadata.new(simple_type, oid: oid, fmod: fmod)
<del> end
<del>
<ide> private
<add> def schema_creation
<add> PostgreSQL::SchemaCreation.new(self)
<add> end
<add>
<add> def create_table_definition(*args)
<add> PostgreSQL::TableDefinition.new(*args)
<add> end
<add>
<add> def new_column_from_field(table_name, field)
<add> column_name, type, default, notnull, oid, fmod, collation, comment = field
<add> type_metadata = fetch_type_metadata(column_name, type, oid.to_i, fmod.to_i)
<add> default_value = extract_value_from_default(default)
<add> default_function = extract_default_function(default_value, default)
<add>
<add> PostgreSQLColumn.new(
<add> column_name,
<add> default_value,
<add> type_metadata,
<add> !notnull,
<add> table_name,
<add> default_function,
<add> collation,
<add> comment: comment.presence
<add> )
<add> end
<add>
<add> def fetch_type_metadata(column_name, sql_type, oid, fmod)
<add> cast_type = get_oid_type(oid, fmod, column_name, sql_type)
<add> simple_type = SqlTypeMetadata.new(
<add> sql_type: sql_type,
<add> type: cast_type.type,
<add> limit: cast_type.limit,
<add> precision: cast_type.precision,
<add> scale: cast_type.scale,
<add> )
<add> PostgreSQLTypeMetadata.new(simple_type, oid: oid, fmod: fmod)
<add> end
<add>
<add> def extract_foreign_key_action(specifier)
<add> case specifier
<add> when "c"; :cascade
<add> when "n"; :nullify
<add> when "r"; :restrict
<add> end
<add> end
<add>
<ide> def data_source_sql(name = nil, type: nil)
<ide> scope = quoted_scope(name, type: type)
<ide> scope[:type] ||= "'r','v','m'" # (r)elation/table, (v)iew, (m)aterialized view
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> class PostgreSQLAdapter < AbstractAdapter
<ide> include PostgreSQL::DatabaseStatements
<ide> include PostgreSQL::ColumnDumper
<ide>
<del> def schema_creation # :nodoc:
<del> PostgreSQL::SchemaCreation.new self
<del> end
<del>
<del> def arel_visitor # :nodoc:
<del> Arel::Visitors::PostgreSQL.new(self)
<del> end
<del>
<ide> # Returns true, since this connection adapter supports prepared statement
<ide> # caching.
<ide> def supports_statement_cache?
<ide> def update_table_definition(table_name, base) #:nodoc:
<ide> PostgreSQL::Table.new(table_name, base)
<ide> end
<ide>
<del> def lookup_cast_type(sql_type) # :nodoc:
<del> oid = execute("SELECT #{quote(sql_type)}::regtype::oid", "SCHEMA").first["oid"].to_i
<del> super(oid)
<del> end
<del>
<ide> def column_name_for_operation(operation, node) # :nodoc:
<ide> OPERATION_ALIASES.fetch(operation) { operation.downcase }
<ide> end
<ide> def extract_table_ref_from_insert_sql(sql)
<ide> $1.strip if $1
<ide> end
<ide>
<del> def create_table_definition(*args)
<del> PostgreSQL::TableDefinition.new(*args)
<add> def arel_visitor
<add> Arel::Visitors::PostgreSQL.new(self)
<ide> end
<ide>
<ide> def can_perform_case_insensitive_comparison_for?(column)
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3/schema_statements.rb
<ide> module ConnectionAdapters
<ide> module SQLite3
<ide> module SchemaStatements # :nodoc:
<ide> private
<add> def schema_creation
<add> SQLite3::SchemaCreation.new(self)
<add> end
<add>
<add> def create_table_definition(*args)
<add> SQLite3::TableDefinition.new(*args)
<add> end
<add>
<add> def new_column_from_field(table_name, field)
<add> default = \
<add> case field["dflt_value"]
<add> when /^null$/i
<add> nil
<add> when /^'(.*)'$/m
<add> $1.gsub("''", "'")
<add> when /^"(.*)"$/m
<add> $1.gsub('""', '"')
<add> else
<add> field["dflt_value"]
<add> end
<add>
<add> type_metadata = fetch_type_metadata(field["type"])
<add> Column.new(field["name"], default, type_metadata, field["notnull"].to_i == 0, table_name, nil, field["collation"])
<add> end
<add>
<ide> def data_source_sql(name = nil, type: nil)
<ide> scope = quoted_scope(name, type: type)
<ide> scope[:type] ||= "'table','view'"
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
<ide> def update_table_definition(table_name, base) # :nodoc:
<ide> SQLite3::Table.new(table_name, base)
<ide> end
<ide>
<del> def schema_creation # :nodoc:
<del> SQLite3::SchemaCreation.new self
<del> end
<del>
<del> def arel_visitor # :nodoc:
<del> Arel::Visitors::SQLite.new(self)
<del> end
<del>
<ide> def initialize(connection, logger, connection_options, config)
<ide> super(connection, logger, config)
<ide>
<ide> def exec_rollback_db_transaction #:nodoc:
<ide>
<ide> # SCHEMA STATEMENTS ========================================
<ide>
<del> def new_column_from_field(table_name, field) # :nondoc:
<del> case field["dflt_value"]
<del> when /^null$/i
<del> field["dflt_value"] = nil
<del> when /^'(.*)'$/m
<del> field["dflt_value"] = $1.gsub("''", "'")
<del> when /^"(.*)"$/m
<del> field["dflt_value"] = $1.gsub('""', '"')
<del> end
<del>
<del> collation = field["collation"]
<del> sql_type = field["type"]
<del> type_metadata = fetch_type_metadata(sql_type)
<del> new_column(field["name"], field["dflt_value"], type_metadata, field["notnull"].to_i == 0, table_name, nil, collation)
<del> end
<del>
<ide> # Returns an array of indexes for the given table.
<ide> def indexes(table_name, name = nil) #:nodoc:
<ide> if name
<ide> def table_structure_with_collation(table_name, basic_structure)
<ide> end
<ide> end
<ide>
<del> def create_table_definition(*args)
<del> SQLite3::TableDefinition.new(*args)
<del> end
<del>
<del> def extract_foreign_key_action(specifier)
<del> case specifier
<del> when "CASCADE"; :cascade
<del> when "SET NULL"; :nullify
<del> when "RESTRICT"; :restrict
<del> end
<add> def arel_visitor
<add> Arel::Visitors::SQLite.new(self)
<ide> end
<ide>
<ide> def configure_connection
<ide><path>activerecord/test/cases/column_definition_test.rb
<ide> def setup
<ide> def @adapter.native_database_types
<ide> { string: "varchar" }
<ide> end
<del> @viz = @adapter.schema_creation
<add> @viz = @adapter.send(:schema_creation)
<ide> end
<ide>
<ide> # Avoid column definitions in create table statements like: | 12 |
Python | Python | add auth options in cassandra backend | afbd2330ed6f835d0c3774cff15c1c6312a1930d | <ide><path>celery/backends/cassandra.py
<ide> import sys
<ide> try: # pragma: no cover
<ide> import cassandra
<add> import cassandra.auth
<ide> import cassandra.cluster
<ide> except ImportError: # pragma: no cover
<ide> cassandra = None # noqa
<ide> def __init__(self, servers=None, keyspace=None, table=None, entry_ttl=None,
<ide> cassandra.ConsistencyLevel.LOCAL_QUORUM,
<ide> )
<ide>
<add> self.auth_provider = None
<add> auth_provider = conf.get('cassandra_auth_provider', None)
<add> auth_kwargs = conf.get('cassandra_auth_kwargs', None)
<add> if auth_provider and auth_kwargs:
<add> auth_provider_class = getattr(cassandra.auth, auth_provider)
<add> self.auth_provider = auth_provider_class(**auth_kwargs)
<add>
<ide> self._connection = None
<ide> self._session = None
<ide> self._write_stmt = None
<ide> def _get_connection(self, write=False):
<ide> """
<ide> if self._connection is None:
<ide> try:
<del> self._connection = cassandra.cluster.Cluster(self.servers,
<del> port=self.port)
<add> self._connection = cassandra.cluster.Cluster(
<add> self.servers, port=self.port,
<add> auth_provider=self.auth_provider)
<ide> self._session = self._connection.connect(self.keyspace)
<ide>
<ide> # We are forced to do concatenation below, as formatting would
<ide><path>celery/tests/backends/test_cassandra.py
<ide> AppCase, Mock, mock_module, depends_on_current_app
<ide> )
<ide>
<del>CASSANDRA_MODULES = ['cassandra', 'cassandra.cluster']
<add>CASSANDRA_MODULES = ['cassandra', 'cassandra.auth', 'cassandra.cluster']
<ide>
<ide>
<ide> class Object(object): | 2 |
Python | Python | enable colors for `runtests.py --ipython` | ce77458baaa9f452f89a5e80809dc7cd4fdc0140 | <ide><path>runtests.py
<ide> def main(argv):
<ide> import warnings; warnings.filterwarnings("always")
<ide> import IPython
<ide> import numpy as np
<del> IPython.embed(user_ns={"np": np})
<add> IPython.embed(colors='neutral', user_ns={"np": np})
<ide> sys.exit(0)
<ide>
<ide> if args.shell: | 1 |
Mixed | Ruby | add configuration to set custom serializers | a5f7357a3dff2617ba13a274feb8d8ac2492f26a | <ide><path>activejob/lib/active_job/railtie.rb
<ide> module ActiveJob
<ide> # = Active Job Railtie
<ide> class Railtie < Rails::Railtie # :nodoc:
<ide> config.active_job = ActiveSupport::OrderedOptions.new
<add> config.active_job.custom_serializers = []
<ide>
<ide> initializer "active_job.logger" do
<ide> ActiveSupport.on_load(:active_job) { self.logger = ::Rails.logger }
<ide> end
<ide>
<add> initializer "active_job.custom_serializers" do |app|
<add> custom_serializers = app.config.active_job.delete(:custom_serializers)
<add> ActiveJob::Serializers.add_serializers custom_serializers
<add> end
<add>
<ide> initializer "active_job.set_configs" do |app|
<ide> options = app.config.active_job
<ide> options.queue_adapter ||= :async
<ide><path>guides/source/configuring.md
<ide> There are a few configuration options available in Active Support:
<ide>
<ide> * `config.active_job.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Active Job. You can retrieve this logger by calling `logger` on either an Active Job class or an Active Job instance. Set to `nil` to disable logging.
<ide>
<add>* `config.active_job.custom_serializers` allows to set custom argument serializers. Defaults to `[]`.
<add>
<ide> ### Configuring Action Cable
<ide>
<ide> * `config.action_cable.url` accepts a string for the URL for where | 2 |
Javascript | Javascript | convert dock to an etch component | 113453a219e692fe1e5f0eb3c1c09703daaa0a89 | <ide><path>spec/dock-spec.js
<ide> const Grim = require('grim')
<ide>
<ide> import {it, fit, ffit, fffit, beforeEach, afterEach} from './async-spec-helpers'
<add>import etch from 'etch'
<add>
<add>const getNextUpdatePromise = () => etch.getScheduler().nextUpdatePromise
<ide>
<ide> describe('Dock', () => {
<ide> describe('when a dock is activated', () => {
<ide> describe('Dock', () => {
<ide> const dockElement = dock.getElement()
<ide>
<ide> dock.setState({size: 300})
<add> await getNextUpdatePromise()
<ide> expect(dockElement.offsetWidth).toBe(300)
<ide> dockElement.querySelector('.atom-dock-resize-handle').dispatchEvent(new MouseEvent('mousedown', {detail: 2}))
<add> await getNextUpdatePromise()
<ide>
<ide> expect(dockElement.offsetWidth).toBe(item.getPreferredWidth())
<ide> })
<ide> describe('Dock', () => {
<ide> const dockElement = dock.getElement()
<ide>
<ide> dock.setState({size: 300})
<add> await getNextUpdatePromise()
<ide> expect(dockElement.offsetHeight).toBe(300)
<ide> dockElement.querySelector('.atom-dock-resize-handle').dispatchEvent(new MouseEvent('mousedown', {detail: 2}))
<add> await getNextUpdatePromise()
<ide>
<ide> expect(dockElement.offsetHeight).toBe(item.getPreferredHeight())
<ide> })
<ide> describe('Dock', () => {
<ide> })
<ide>
<ide> describe('drag handling', () => {
<del> it('expands docks to match the preferred size of the dragged item', () => {
<add> it('expands docks to match the preferred size of the dragged item', async () => {
<ide> jasmine.attachToDOM(atom.workspace.getElement())
<ide>
<ide> const element = document.createElement('div')
<ide> describe('Dock', () => {
<ide> Object.defineProperty(dragEvent, 'target', {value: element})
<ide>
<ide> atom.workspace.getElement().handleDragStart(dragEvent)
<del> expect(atom.workspace.getLeftDock().wrapperElement.offsetWidth).toBe(144)
<add> await getNextUpdatePromise()
<add> expect(atom.workspace.getLeftDock().refs.wrapperElement.offsetWidth).toBe(144)
<ide> })
<ide>
<ide> it('does nothing when text nodes are dragged', () => {
<ide><path>spec/workspace-element-spec.js
<ide> /** @babel */
<ide>
<ide> const {ipcRenderer} = require('electron')
<add>const etch = require('etch')
<ide> const path = require('path')
<ide> const temp = require('temp').track()
<ide> const {Disposable} = require('event-kit')
<ide> const {it, fit, ffit, fffit, beforeEach, afterEach} = require('./async-spec-helpers')
<ide>
<add>const getNextUpdatePromise = () => etch.getScheduler().nextUpdatePromise
<add>
<ide> describe('WorkspaceElement', () => {
<ide> afterEach(() => {
<ide> try {
<ide> describe('WorkspaceElement', () => {
<ide>
<ide> // Mouse over where the toggle button would be if the dock were hovered
<ide> moveMouse({clientX: 440, clientY: 150})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonHidden(leftDock)
<ide> expectToggleButtonHidden(rightDock)
<ide> expectToggleButtonHidden(bottomDock)
<ide>
<ide> // Mouse over the dock
<ide> moveMouse({clientX: 460, clientY: 150})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonHidden(leftDock)
<ide> expectToggleButtonVisible(rightDock, 'icon-chevron-right')
<ide> expectToggleButtonHidden(bottomDock)
<ide>
<ide> // Mouse over the toggle button
<ide> moveMouse({clientX: 440, clientY: 150})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonHidden(leftDock)
<ide> expectToggleButtonVisible(rightDock, 'icon-chevron-right')
<ide> expectToggleButtonHidden(bottomDock)
<ide>
<ide> // Click the toggle button
<del> rightDock.toggleButton.innerElement.click()
<add> rightDock.refs.toggleButton.refs.innerElement.click()
<add> await getNextUpdatePromise()
<ide> expect(rightDock.isVisible()).toBe(false)
<ide> expectToggleButtonHidden(rightDock)
<ide>
<ide> // Mouse to edge of the window
<ide> moveMouse({clientX: 575, clientY: 150})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonHidden(rightDock)
<ide> moveMouse({clientX: 598, clientY: 150})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonVisible(rightDock, 'icon-chevron-left')
<ide>
<ide> // Click the toggle button again
<del> rightDock.toggleButton.innerElement.click()
<add> rightDock.refs.toggleButton.refs.innerElement.click()
<add> await getNextUpdatePromise()
<ide> expect(rightDock.isVisible()).toBe(true)
<ide> expectToggleButtonVisible(rightDock, 'icon-chevron-right')
<ide>
<ide> // --- Left Dock ---
<ide>
<ide> // Mouse over where the toggle button would be if the dock were hovered
<ide> moveMouse({clientX: 160, clientY: 150})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonHidden(leftDock)
<ide> expectToggleButtonHidden(rightDock)
<ide> expectToggleButtonHidden(bottomDock)
<ide>
<ide> // Mouse over the dock
<ide> moveMouse({clientX: 140, clientY: 150})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonVisible(leftDock, 'icon-chevron-left')
<ide> expectToggleButtonHidden(rightDock)
<ide> expectToggleButtonHidden(bottomDock)
<ide>
<ide> // Mouse over the toggle button
<ide> moveMouse({clientX: 160, clientY: 150})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonVisible(leftDock, 'icon-chevron-left')
<ide> expectToggleButtonHidden(rightDock)
<ide> expectToggleButtonHidden(bottomDock)
<ide>
<ide> // Click the toggle button
<del> leftDock.toggleButton.innerElement.click()
<add> leftDock.refs.toggleButton.refs.innerElement.click()
<add> await getNextUpdatePromise()
<ide> expect(leftDock.isVisible()).toBe(false)
<ide> expectToggleButtonHidden(leftDock)
<ide>
<ide> // Mouse to edge of the window
<ide> moveMouse({clientX: 25, clientY: 150})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonHidden(leftDock)
<ide> moveMouse({clientX: 2, clientY: 150})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonVisible(leftDock, 'icon-chevron-right')
<ide>
<ide> // Click the toggle button again
<del> leftDock.toggleButton.innerElement.click()
<add> leftDock.refs.toggleButton.refs.innerElement.click()
<add> await getNextUpdatePromise()
<ide> expect(leftDock.isVisible()).toBe(true)
<ide> expectToggleButtonVisible(leftDock, 'icon-chevron-left')
<ide>
<ide> // --- Bottom Dock ---
<ide>
<ide> // Mouse over where the toggle button would be if the dock were hovered
<ide> moveMouse({clientX: 300, clientY: 190})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonHidden(leftDock)
<ide> expectToggleButtonHidden(rightDock)
<ide> expectToggleButtonHidden(bottomDock)
<ide>
<ide> // Mouse over the dock
<ide> moveMouse({clientX: 300, clientY: 210})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonHidden(leftDock)
<ide> expectToggleButtonHidden(rightDock)
<ide> expectToggleButtonVisible(bottomDock, 'icon-chevron-down')
<ide>
<ide> // Mouse over the toggle button
<ide> moveMouse({clientX: 300, clientY: 195})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonHidden(leftDock)
<ide> expectToggleButtonHidden(rightDock)
<ide> expectToggleButtonVisible(bottomDock, 'icon-chevron-down')
<ide>
<ide> // Click the toggle button
<del> bottomDock.toggleButton.innerElement.click()
<add> bottomDock.refs.toggleButton.refs.innerElement.click()
<add> await getNextUpdatePromise()
<ide> expect(bottomDock.isVisible()).toBe(false)
<ide> expectToggleButtonHidden(bottomDock)
<ide>
<ide> // Mouse to edge of the window
<ide> moveMouse({clientX: 300, clientY: 290})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonHidden(leftDock)
<ide> moveMouse({clientX: 300, clientY: 299})
<add> await getNextUpdatePromise()
<ide> expectToggleButtonVisible(bottomDock, 'icon-chevron-up')
<ide>
<ide> // Click the toggle button again
<del> bottomDock.toggleButton.innerElement.click()
<add> bottomDock.refs.toggleButton.refs.innerElement.click()
<add> await getNextUpdatePromise()
<ide> expect(bottomDock.isVisible()).toBe(true)
<ide> expectToggleButtonVisible(bottomDock, 'icon-chevron-down')
<ide> })
<ide>
<del> function moveMouse(coordinates) {
<add> function moveMouse (coordinates) {
<ide> window.dispatchEvent(new MouseEvent('mousemove', coordinates))
<ide> advanceClock(100)
<ide> }
<ide>
<ide> function expectToggleButtonHidden(dock) {
<del> expect(dock.toggleButton.element).not.toHaveClass('atom-dock-toggle-button-visible')
<add> expect(dock.refs.toggleButton.element).not.toHaveClass('atom-dock-toggle-button-visible')
<ide> }
<ide>
<ide> function expectToggleButtonVisible(dock, iconClass) {
<del> expect(dock.toggleButton.element).toHaveClass('atom-dock-toggle-button-visible')
<del> expect(dock.toggleButton.iconElement).toHaveClass(iconClass)
<add> expect(dock.refs.toggleButton.element).toHaveClass('atom-dock-toggle-button-visible')
<add> expect(dock.refs.toggleButton.refs.iconElement).toHaveClass(iconClass)
<ide> }
<ide> })
<ide>
<ide><path>src/dock.js
<del>'use strict'
<add>/** @babel */
<add>/** @jsx etch.dom */
<ide>
<add>const etch = require('etch')
<ide> const _ = require('underscore-plus')
<ide> const {CompositeDisposable, Emitter} = require('event-kit')
<ide> const PaneContainer = require('./pane-container')
<ide> module.exports = class Dock {
<ide> this.handleMouseUp = this.handleMouseUp.bind(this)
<ide> this.handleDrag = _.throttle(this.handleDrag.bind(this), 30)
<ide> this.handleDragEnd = this.handleDragEnd.bind(this)
<add> this.handleToggleButtonDragEnter = this.handleToggleButtonDragEnter.bind(this)
<add> this.toggle = this.toggle.bind(this)
<ide>
<ide> this.location = params.location
<ide> this.widthOrHeight = getWidthOrHeight(this.location)
<ide> module.exports = class Dock {
<ide> this.paneContainer.onDidChangeActivePaneItem((item) => params.didChangeActivePaneItem(this, item)),
<ide> this.paneContainer.onDidDestroyPaneItem((item) => params.didDestroyPaneItem(item))
<ide> )
<add>
<add> etch.initialize(this)
<ide> }
<ide>
<ide> // This method is called explicitly by the object which adds the Dock to the document.
<ide> elementAttached () {
<ide> // Re-render when the dock is attached to make sure we remeasure sizes defined in CSS.
<del> this.render(this.state)
<add> etch.update(this)
<ide> }
<ide>
<ide> getElement () {
<del> if (!this.element) this.render(this.state)
<ide> return this.element
<ide> }
<ide>
<ide> module.exports = class Dock {
<ide> }
<ide>
<ide> this.state = nextState
<del> this.render(this.state)
<ide>
<ide> const {hovered, visible} = this.state
<add>
<add> // Render immediately if the dock becomes visible or the size changes in case people are
<add> // measuring after opening, for example.
<add> if ((visible && !prevState.visible) || (this.state.size !== prevState.size)) etch.updateSync(this)
<add> else etch.update(this)
<add>
<ide> if (hovered !== prevState.hovered) {
<ide> this.emitter.emit('did-change-hovered', hovered)
<ide> }
<ide> module.exports = class Dock {
<ide> }
<ide> }
<ide>
<del> render (state) {
<del> if (this.element == null) {
<del> this.element = document.createElement('atom-dock')
<del> this.element.classList.add(this.location)
<del> this.innerElement = document.createElement('div')
<del> this.innerElement.classList.add('atom-dock-inner', this.location)
<del> this.maskElement = document.createElement('div')
<del> this.maskElement.classList.add('atom-dock-mask')
<del> this.wrapperElement = document.createElement('div')
<del> this.wrapperElement.classList.add('atom-dock-content-wrapper', this.location)
<del> this.resizeHandle = new DockResizeHandle({
<del> location: this.location,
<del> onResizeStart: this.handleResizeHandleDragStart,
<del> onResizeToFit: this.handleResizeToFit
<del> })
<del> this.toggleButton = new DockToggleButton({
<del> onDragEnter: this.handleToggleButtonDragEnter.bind(this),
<del> location: this.location,
<del> toggle: this.toggle.bind(this)
<del> })
<del> this.cursorOverlayElement = document.createElement('div')
<del> this.cursorOverlayElement.classList.add('atom-dock-cursor-overlay', this.location)
<del>
<del> // Add the children to the DOM tree
<del> this.element.appendChild(this.innerElement)
<del> this.innerElement.appendChild(this.maskElement)
<del> this.maskElement.appendChild(this.wrapperElement)
<del> this.wrapperElement.appendChild(this.resizeHandle.getElement())
<del> this.wrapperElement.appendChild(this.paneContainer.getElement())
<del> this.wrapperElement.appendChild(this.cursorOverlayElement)
<del> // The toggle button must be rendered outside the mask because (1) it shouldn't be masked and
<del> // (2) if we made the mask larger to avoid masking it, the mask would block mouse events.
<del> this.innerElement.appendChild(this.toggleButton.getElement())
<del> }
<del>
<del> if (state.visible) {
<del> this.innerElement.classList.add(VISIBLE_CLASS)
<del> } else {
<del> this.innerElement.classList.remove(VISIBLE_CLASS)
<del> }
<add> render () {
<add> const innerElementClassList = ['atom-dock-inner', this.location]
<add> if (this.state.visible) innerElementClassList.push(VISIBLE_CLASS)
<ide>
<del> if (state.shouldAnimate) {
<del> this.maskElement.classList.add(SHOULD_ANIMATE_CLASS)
<del> } else {
<del> this.maskElement.classList.remove(SHOULD_ANIMATE_CLASS)
<del> }
<add> const maskElementClassList = ['atom-dock-mask']
<add> if (this.state.shouldAnimate) maskElementClassList.push(SHOULD_ANIMATE_CLASS)
<ide>
<del> if (state.resizing) {
<del> this.cursorOverlayElement.classList.add(CURSOR_OVERLAY_VISIBLE_CLASS)
<del> } else {
<del> this.cursorOverlayElement.classList.remove(CURSOR_OVERLAY_VISIBLE_CLASS)
<del> }
<add> const cursorOverlayElementClassList = ['atom-dock-cursor-overlay', this.location]
<add> if (this.state.resizing) cursorOverlayElementClassList.push(CURSOR_OVERLAY_VISIBLE_CLASS)
<ide>
<del> const shouldBeVisible = state.visible || state.showDropTarget
<add> const shouldBeVisible = this.state.visible || this.state.showDropTarget
<ide> const size = Math.max(MINIMUM_SIZE,
<del> state.size ||
<del> (state.draggingItem && getPreferredSize(state.draggingItem, this.location)) ||
<add> this.state.size ||
<add> (this.state.draggingItem && getPreferredSize(this.state.draggingItem, this.location)) ||
<ide> DEFAULT_INITIAL_SIZE
<ide> )
<ide>
<ide> // We need to change the size of the mask...
<del> this.maskElement.style[this.widthOrHeight] = `${shouldBeVisible ? size : 0}px`
<add> const maskStyle = {[this.widthOrHeight]: `${shouldBeVisible ? size : 0}px`}
<ide> // ...but the content needs to maintain a constant size.
<del> this.wrapperElement.style[this.widthOrHeight] = `${size}px`
<del>
<del> this.resizeHandle.update({dockIsVisible: this.state.visible})
<del> this.toggleButton.update({
<del> dockIsVisible: shouldBeVisible,
<del> visible:
<del> // Don't show the toggle button if the dock is closed and empty...
<del> (state.hovered && (this.state.visible || this.getPaneItems().length > 0)) ||
<del> // ...or if the item can't be dropped in that dock.
<del> (!shouldBeVisible && state.draggingItem && isItemAllowed(state.draggingItem, this.location))
<del> })
<add> const wrapperStyle = {[this.widthOrHeight]: `${size}px`}
<add>
<add> return (
<add> <atom-dock className={this.location}>
<add> <div ref='innerElement' className={innerElementClassList.join(' ')}>
<add> <div
<add> className={maskElementClassList.join(' ')}
<add> style={maskStyle}>
<add> <div
<add> ref='wrapperElement'
<add> className={`atom-dock-content-wrapper ${this.location}`}
<add> style={wrapperStyle}>
<add> <DockResizeHandle
<add> location={this.location}
<add> onResizeStart={this.handleResizeHandleDragStart}
<add> onResizeToFit={this.handleResizeToFit}
<add> dockIsVisible={this.state.visible}
<add> />
<add> <ElementComponent element={this.paneContainer.getElement()} />
<add> <div className={cursorOverlayElementClassList.join(' ')} />
<add> </div>
<add> </div>
<add> {/*
<add> The toggle button must be rendered outside the mask because (1) it shouldn't be masked
<add> and (2) if we made the mask larger to avoid masking it, the mask would block mouse
<add> events.
<add> */}
<add> <DockToggleButton
<add> ref='toggleButton'
<add> onDragEnter={this.handleToggleButtonDragEnter}
<add> location={this.location}
<add> toggle={this.toggle}
<add> dockIsVisible={shouldBeVisible}
<add> visible={
<add> // Don't show the toggle button if the dock is closed and empty...
<add> (this.state.hovered && (this.state.visible || this.getPaneItems().length > 0)) ||
<add> // ...or if the item can't be dropped in that dock.
<add> (!shouldBeVisible && this.state.draggingItem && isItemAllowed(this.state.draggingItem, this.location))
<add> }
<add> />
<add> </div>
<add> </atom-dock>
<add> )
<add> }
<add>
<add> update (props) {
<add> // Since we're interopping with non-etch stuff, this method's actually never called.
<add> return etch.update(this)
<ide> }
<ide>
<ide> handleDidAddPaneItem () {
<ide> module.exports = class Dock {
<ide> // area considered when detecting exit MUST fully encompass the area considered when detecting
<ide> // entry.
<ide> pointWithinHoverArea (point, detectingExit) {
<del> const dockBounds = this.innerElement.getBoundingClientRect()
<add> const dockBounds = this.refs.innerElement.getBoundingClientRect()
<ide>
<ide> // Copy the bounds object since we can't mutate it.
<ide> const bounds = {
<ide> module.exports = class Dock {
<ide> // remove it as an argument and determine whether we're inside the toggle button using
<ide> // mouseenter/leave events on it. This class would still need to keep track of the mouse
<ide> // position (via a mousemove listener) for the other measurements, though.
<del> const toggleButtonBounds = this.toggleButton.getBounds()
<add> const toggleButtonBounds = this.refs.toggleButton.getBounds()
<ide> if (rectContainsPoint(toggleButtonBounds, point)) return true
<ide>
<ide> // The area used when detecting exit is actually larger than when detecting entrances. Expand
<ide> module.exports = class Dock {
<ide>
<ide> class DockResizeHandle {
<ide> constructor (props) {
<del> this.handleMouseDown = this.handleMouseDown.bind(this)
<del>
<del> this.element = document.createElement('div')
<del> this.element.classList.add('atom-dock-resize-handle', props.location)
<del> this.element.addEventListener('mousedown', this.handleMouseDown)
<ide> this.props = props
<del> this.update(props)
<add> etch.initialize(this)
<add> }
<add>
<add> render () {
<add> const classList = ['atom-dock-resize-handle', this.props.location]
<add> if (this.props.dockIsVisible) classList.push(RESIZE_HANDLE_RESIZABLE_CLASS)
<add>
<add> return (
<add> <div
<add> className={classList.join(' ')}
<add> on={{mousedown: this.handleMouseDown}}
<add> />
<add> )
<ide> }
<ide>
<ide> getElement () {
<ide> class DockResizeHandle {
<ide>
<ide> update (newProps) {
<ide> this.props = Object.assign({}, this.props, newProps)
<del>
<del> if (this.props.dockIsVisible) {
<del> this.element.classList.add(RESIZE_HANDLE_RESIZABLE_CLASS)
<del> } else {
<del> this.element.classList.remove(RESIZE_HANDLE_RESIZABLE_CLASS)
<del> }
<add> return etch.update(this)
<ide> }
<ide>
<ide> handleMouseDown (event) {
<ide> class DockResizeHandle {
<ide>
<ide> class DockToggleButton {
<ide> constructor (props) {
<del> this.handleClick = this.handleClick.bind(this)
<del> this.handleDragEnter = this.handleDragEnter.bind(this)
<del>
<del> this.element = document.createElement('div')
<del> this.element.classList.add('atom-dock-toggle-button', props.location)
<del> this.element.classList.add(props.location)
<del> this.innerElement = document.createElement('div')
<del> this.innerElement.classList.add('atom-dock-toggle-button-inner', props.location)
<del> this.innerElement.addEventListener('click', this.handleClick)
<del> this.innerElement.addEventListener('dragenter', this.handleDragEnter)
<del> this.iconElement = document.createElement('span')
<del> this.innerElement.appendChild(this.iconElement)
<del> this.element.appendChild(this.innerElement)
<del>
<ide> this.props = props
<del> this.update(props)
<add> etch.initialize(this)
<add> }
<add>
<add> render () {
<add> const classList = ['atom-dock-toggle-button', this.props.location]
<add> if (this.props.visible) classList.push(TOGGLE_BUTTON_VISIBLE_CLASS)
<add>
<add> return (
<add> <div className={classList.join(' ')}>
<add> <div
<add> ref='innerElement'
<add> className={`atom-dock-toggle-button-inner ${this.props.location}`}
<add> on={{click: this.handleClick, dragenter: this.handleDragEnter}}>
<add> <span
<add> ref='iconElement'
<add> className={`icon ${getIconName(this.props.location, this.props.dockIsVisible)}`} />
<add> </div>
<add> </div>
<add> )
<ide> }
<ide>
<ide> getElement () {
<ide> return this.element
<ide> }
<ide>
<ide> getBounds () {
<del> return this.innerElement.getBoundingClientRect()
<add> return this.refs.innerElement.getBoundingClientRect()
<ide> }
<ide>
<ide> update (newProps) {
<ide> this.props = Object.assign({}, this.props, newProps)
<del>
<del> if (this.props.visible) {
<del> this.element.classList.add(TOGGLE_BUTTON_VISIBLE_CLASS)
<del> } else {
<del> this.element.classList.remove(TOGGLE_BUTTON_VISIBLE_CLASS)
<del> }
<del>
<del> this.iconElement.className = 'icon ' + getIconName(this.props.location, this.props.dockIsVisible)
<add> return etch.update(this)
<ide> }
<ide>
<ide> handleClick () {
<ide> class DockToggleButton {
<ide> }
<ide> }
<ide>
<add>// An etch component that doesn't use etch, this component provides a gateway from JSX back into
<add>// the mutable DOM world.
<add>class ElementComponent {
<add> constructor (props) {
<add> this.element = props.element
<add> }
<add>
<add> update (props) {
<add> this.element = props.element
<add> }
<add>}
<add>
<ide> function getWidthOrHeight (location) {
<ide> return location === 'left' || location === 'right' ? 'width' : 'height'
<ide> } | 3 |
Text | Text | use segment instead of fragment | c786f4f27ccd7158df97379af900eba23caf1052 | <ide><path>guides/source/routing.md
<ide> TIP: By default, dynamic segments don't accept dots - this is because the dot is
<ide>
<ide> ### Static Segments
<ide>
<del>You can specify static segments when creating a route by not prepending a colon to a fragment:
<add>You can specify static segments when creating a route by not prepending a colon to a segment:
<ide>
<ide> ```ruby
<ide> get 'photos/:id/with_user/:user_id', to: 'photos#show'
<ide> Route globbing is a way to specify that a particular parameter should be matched
<ide> get 'photos/*other', to: 'photos#unknown'
<ide> ```
<ide>
<del>This route would match `photos/12` or `/photos/long/path/to/12`, setting `params[:other]` to `"12"` or `"long/path/to/12"`. The fragments prefixed with a star are called "wildcard segments".
<add>This route would match `photos/12` or `/photos/long/path/to/12`, setting `params[:other]` to `"12"` or `"long/path/to/12"`. The segments prefixed with a star are called "wildcard segments".
<ide>
<ide> Wildcard segments can occur anywhere in a route. For example:
<ide> | 1 |
Ruby | Ruby | add missing newline to brew bottle | 8199f1d617b9992cb0e9f87b23ac4bcd5a0774c5 | <ide><path>Library/Contributions/examples/brew-bottle.rb
<ide> safe_system 'tar', 'czf', "#{destination}/#{filename}", "#{formula}/#{version}"
<ide> end
<ide> ohai "Bottled #{filename}"
<del>end
<ide>\ No newline at end of file
<add>end | 1 |
Go | Go | move userland proxies out of daemon's process | b4e2f5ed962f8ef81dbc2cbb1ff2a06bb64f8211 | <ide><path>daemon/networkdriver/bridge/driver_test.go
<ide> package bridge
<ide>
<ide> import (
<del> "fmt"
<ide> "net"
<ide> "strconv"
<ide> "testing"
<ide>
<add> "github.com/docker/docker/daemon/networkdriver/portmapper"
<ide> "github.com/docker/docker/engine"
<ide> )
<ide>
<add>func init() {
<add> // reset the new proxy command for mocking out the userland proxy in tests
<add> portmapper.NewProxy = portmapper.NewMockProxyCommand
<add>}
<add>
<ide> func findFreePort(t *testing.T) int {
<ide> l, err := net.Listen("tcp", ":0")
<ide> if err != nil {
<ide> func TestAllocatePortDetection(t *testing.T) {
<ide> t.Fatal("Duplicate port allocation granted by AllocatePort")
<ide> }
<ide> }
<del>
<del>func TestAllocatePortReclaim(t *testing.T) {
<del> eng := engine.New()
<del> eng.Logging = false
<del>
<del> freePort := findFreePort(t)
<del>
<del> // Init driver
<del> job := eng.Job("initdriver")
<del> if res := InitDriver(job); res != engine.StatusOK {
<del> t.Fatal("Failed to initialize network driver")
<del> }
<del>
<del> // Allocate interface
<del> job = eng.Job("allocate_interface", "container_id")
<del> if res := Allocate(job); res != engine.StatusOK {
<del> t.Fatal("Failed to allocate network interface")
<del> }
<del>
<del> // Occupy port
<del> listenAddr := fmt.Sprintf(":%d", freePort)
<del> tcpListenAddr, err := net.ResolveTCPAddr("tcp", listenAddr)
<del> if err != nil {
<del> t.Fatalf("Failed to resolve TCP address '%s'", listenAddr)
<del> }
<del>
<del> l, err := net.ListenTCP("tcp", tcpListenAddr)
<del> if err != nil {
<del> t.Fatalf("Fail to listen on port %d", freePort)
<del> }
<del>
<del> // Allocate port, expect failure
<del> job = newPortAllocationJob(eng, freePort)
<del> if res := AllocatePort(job); res == engine.StatusOK {
<del> t.Fatal("Successfully allocated currently used port")
<del> }
<del>
<del> // Reclaim port, retry allocation
<del> l.Close()
<del> if res := AllocatePort(job); res != engine.StatusOK {
<del> t.Fatal("Failed to allocate previously reclaimed port")
<del> }
<del>}
<ide><path>daemon/networkdriver/portmapper/mapper.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/daemon/networkdriver/portallocator"
<ide> "github.com/docker/docker/pkg/iptables"
<del> "github.com/docker/docker/pkg/proxy"
<ide> )
<ide>
<ide> type mapping struct {
<ide> proto string
<del> userlandProxy proxy.Proxy
<add> userlandProxy UserlandProxy
<ide> host net.Addr
<ide> container net.Addr
<ide> }
<ide> var (
<ide>
<ide> // udp:ip:port
<ide> currentMappings = make(map[string]*mapping)
<del> newProxy = proxy.NewProxy
<add>
<add> NewProxy = NewProxyCommand
<ide> )
<ide>
<ide> var (
<ide> func Map(container net.Addr, hostIP net.IP, hostPort int) (host net.Addr, err er
<ide> m *mapping
<ide> proto string
<ide> allocatedHostPort int
<add> proxy UserlandProxy
<ide> )
<ide>
<ide> switch container.(type) {
<ide> func Map(container net.Addr, hostIP net.IP, hostPort int) (host net.Addr, err er
<ide> if allocatedHostPort, err = portallocator.RequestPort(hostIP, proto, hostPort); err != nil {
<ide> return nil, err
<ide> }
<add>
<ide> m = &mapping{
<ide> proto: proto,
<ide> host: &net.TCPAddr{IP: hostIP, Port: allocatedHostPort},
<ide> container: container,
<ide> }
<add>
<add> proxy = NewProxy(proto, hostIP, allocatedHostPort, container.(*net.TCPAddr).IP, container.(*net.TCPAddr).Port)
<ide> case *net.UDPAddr:
<ide> proto = "udp"
<ide> if allocatedHostPort, err = portallocator.RequestPort(hostIP, proto, hostPort); err != nil {
<ide> return nil, err
<ide> }
<add>
<ide> m = &mapping{
<ide> proto: proto,
<ide> host: &net.UDPAddr{IP: hostIP, Port: allocatedHostPort},
<ide> container: container,
<ide> }
<add>
<add> proxy = NewProxy(proto, hostIP, allocatedHostPort, container.(*net.UDPAddr).IP, container.(*net.UDPAddr).Port)
<ide> default:
<ide> return nil, ErrUnknownBackendAddressType
<ide> }
<ide> func Map(container net.Addr, hostIP net.IP, hostPort int) (host net.Addr, err er
<ide> return nil, err
<ide> }
<ide>
<del> p, err := newProxy(m.host, m.container)
<del> if err != nil {
<add> m.userlandProxy = proxy
<add> currentMappings[key] = m
<add>
<add> if err := proxy.Start(); err != nil {
<ide> // need to undo the iptables rules before we return
<ide> forward(iptables.Delete, m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort)
<add>
<ide> return nil, err
<ide> }
<ide>
<del> m.userlandProxy = p
<del> currentMappings[key] = m
<del>
<del> go p.Run()
<del>
<ide> return m.host, nil
<ide> }
<ide>
<ide> func Unmap(host net.Addr) error {
<ide> return ErrPortNotMapped
<ide> }
<ide>
<del> data.userlandProxy.Close()
<add> data.userlandProxy.Stop()
<add>
<ide> delete(currentMappings, key)
<ide>
<ide> containerIP, containerPort := getIPAndPort(data.container)
<ide><path>daemon/networkdriver/portmapper/mapper_test.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/daemon/networkdriver/portallocator"
<ide> "github.com/docker/docker/pkg/iptables"
<del> "github.com/docker/docker/pkg/proxy"
<ide> )
<ide>
<ide> func init() {
<ide> // override this func to mock out the proxy server
<del> newProxy = proxy.NewStubProxy
<add> NewProxy = NewMockProxyCommand
<ide> }
<ide>
<ide> func reset() {
<ide><path>daemon/networkdriver/portmapper/mock_proxy.go
<add>package portmapper
<add>
<add>import "net"
<add>
<add>func NewMockProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.IP, containerPort int) UserlandProxy {
<add> return &mockProxyCommand{}
<add>}
<add>
<add>type mockProxyCommand struct {
<add>}
<add>
<add>func (p *mockProxyCommand) Start() error {
<add> return nil
<add>}
<add>
<add>func (p *mockProxyCommand) Stop() error {
<add> return nil
<add>}
<ide><path>daemon/networkdriver/portmapper/proxy.go
<add>package portmapper
<add>
<add>import (
<add> "flag"
<add> "log"
<add> "net"
<add> "os"
<add> "os/exec"
<add> "os/signal"
<add> "strconv"
<add> "syscall"
<add>
<add> "github.com/docker/docker/pkg/proxy"
<add> "github.com/docker/docker/reexec"
<add>)
<add>
<add>const userlandProxyCommandName = "docker-proxy"
<add>
<add>func init() {
<add> reexec.Register(userlandProxyCommandName, execProxy)
<add>}
<add>
<add>type UserlandProxy interface {
<add> Start() error
<add> Stop() error
<add>}
<add>
<add>// proxyCommand wraps an exec.Cmd to run the userland TCP and UDP
<add>// proxies as separate processes.
<add>type proxyCommand struct {
<add> cmd *exec.Cmd
<add>}
<add>
<add>// execProxy is the reexec function that is registered to start the userland proxies
<add>func execProxy() {
<add> host, container := parseHostContainerAddrs()
<add>
<add> p, err := proxy.NewProxy(host, container)
<add> if err != nil {
<add> log.Fatal(err)
<add> }
<add>
<add> go handleStopSignals(p)
<add>
<add> // Run will block until the proxy stops
<add> p.Run()
<add>}
<add>
<add>// parseHostContainerAddrs parses the flags passed on reexec to create the TCP or UDP
<add>// net.Addrs to map the host and container ports
<add>func parseHostContainerAddrs() (host net.Addr, container net.Addr) {
<add> var (
<add> proto = flag.String("proto", "tcp", "proxy protocol")
<add> hostIP = flag.String("host-ip", "", "host ip")
<add> hostPort = flag.Int("host-port", -1, "host port")
<add> containerIP = flag.String("container-ip", "", "container ip")
<add> containerPort = flag.Int("container-port", -1, "container port")
<add> )
<add>
<add> flag.Parse()
<add>
<add> switch *proto {
<add> case "tcp":
<add> host = &net.TCPAddr{IP: net.ParseIP(*hostIP), Port: *hostPort}
<add> container = &net.TCPAddr{IP: net.ParseIP(*containerIP), Port: *containerPort}
<add> case "udp":
<add> host = &net.UDPAddr{IP: net.ParseIP(*hostIP), Port: *hostPort}
<add> container = &net.UDPAddr{IP: net.ParseIP(*containerIP), Port: *containerPort}
<add> default:
<add> log.Fatalf("unsupported protocol %s", *proto)
<add> }
<add>
<add> return host, container
<add>}
<add>
<add>func handleStopSignals(p proxy.Proxy) {
<add> s := make(chan os.Signal, 10)
<add> signal.Notify(s, os.Interrupt, syscall.SIGTERM, syscall.SIGSTOP)
<add>
<add> for _ = range s {
<add> p.Close()
<add>
<add> os.Exit(0)
<add> }
<add>}
<add>
<add>func NewProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.IP, containerPort int) UserlandProxy {
<add> args := []string{
<add> userlandProxyCommandName,
<add> "-proto", proto,
<add> "-host-ip", hostIP.String(),
<add> "-host-port", strconv.Itoa(hostPort),
<add> "-container-ip", containerIP.String(),
<add> "-container-port", strconv.Itoa(containerPort),
<add> }
<add>
<add> return &proxyCommand{
<add> cmd: &exec.Cmd{
<add> Path: reexec.Self(),
<add> Args: args,
<add> Stdout: os.Stdout,
<add> Stderr: os.Stderr,
<add> SysProcAttr: &syscall.SysProcAttr{
<add> Pdeathsig: syscall.SIGTERM, // send a sigterm to the proxy if the daemon process dies
<add> },
<add> },
<add> }
<add>}
<add>
<add>func (p *proxyCommand) Start() error {
<add> return p.cmd.Start()
<add>}
<add>
<add>func (p *proxyCommand) Stop() error {
<add> err := p.cmd.Process.Signal(os.Interrupt)
<add> p.cmd.Wait()
<add>
<add> return err
<add>} | 5 |
Javascript | Javascript | fix memory leak in example embed code | 6c663154943e4c0c33c19026a7b500302bda29d4 | <ide><path>docs/components/angular-bootstrap/bootstrap-prettify.js
<ide> directive.ngEmbedApp = ['$templateCache', '$browser', '$rootScope', '$location',
<ide> return {
<ide> terminal: true,
<ide> link: function(scope, element, attrs) {
<del> var modules = [];
<add> var modules = [],
<add> embedRootScope,
<add> deregisterEmbedRootScope;
<ide>
<ide> modules.push(['$provide', function($provide) {
<ide> $provide.value('$templateCache', $templateCache);
<ide> directive.ngEmbedApp = ['$templateCache', '$browser', '$rootScope', '$location',
<ide> }
<ide> }, $delegate);
<ide> }]);
<del> $provide.decorator('$rootScope', ['$delegate', function(embedRootScope) {
<del> docsRootScope.$watch(function embedRootScopeDigestWatch() {
<add> $provide.decorator('$rootScope', ['$delegate', function($delegate) {
<add> embedRootScope = $delegate;
<add> deregisterEmbedRootScope = docsRootScope.$watch(function embedRootScopeDigestWatch() {
<ide> embedRootScope.$digest();
<ide> });
<add>
<ide> return embedRootScope;
<ide> }]);
<ide> }]);
<ide> directive.ngEmbedApp = ['$templateCache', '$browser', '$rootScope', '$location',
<ide> }
<ide> });
<ide>
<add> element.bind('$destroy', function() {
<add> deregisterEmbedRootScope();
<add> embedRootScope.$destroy();
<add> });
<add>
<ide> angular.bootstrap(element, modules);
<ide> }
<ide> }; | 1 |
Java | Java | behaviorsubject subscription timegap fix 2 | 265090cf3b1433a0ccaa19f5348189ceafa6a66c | <ide><path>rxjava-core/src/main/java/rx/subjects/BehaviorSubject.java
<ide> */
<ide> package rx.subjects;
<ide>
<add>
<ide> import java.util.ArrayList;
<del>import java.util.Collection;
<ide> import java.util.List;
<ide> import java.util.concurrent.atomic.AtomicReference;
<del>
<ide> import rx.Notification;
<ide> import rx.Observer;
<ide> import rx.Subscriber;
<ide> import rx.functions.Action0;
<del>import rx.functions.Action1;
<del>import rx.subjects.SubjectSubscriptionManager.SubjectObserver;
<add>import rx.subscriptions.Subscriptions;
<ide>
<ide> /**
<ide> * Subject that publishes the most recent and all subsequent events to each subscribed {@link Observer}.
<ide> *
<ide> * @param <T>
<ide> */
<add>@SuppressWarnings({ "unchecked", "rawtypes" })
<ide> public final class BehaviorSubject<T> extends Subject<T, T> {
<ide> /**
<ide> * Create a {@link BehaviorSubject} without a default value.
<ide> public static <T> BehaviorSubject<T> create(T defaultValue) {
<ide> return create(defaultValue, true);
<ide> }
<ide> private static <T> BehaviorSubject<T> create(T defaultValue, boolean hasDefault) {
<del> final SubjectSubscriptionManager<T> subscriptionManager = new SubjectSubscriptionManager<T>();
<del> // set a default value so subscriptions will immediately receive this until a new notification is received
<del> final State<T> state = new State<T>();
<add> State<T> state = new State<T>();
<ide> if (hasDefault) {
<del> state.lastNotification.set(Notification.createOnNext(defaultValue));
<add> state.set(Notification.createOnNext(defaultValue));
<ide> }
<del>
<del> final OnSubscribe<T> onSubscribeBase = subscriptionManager.getOnSubscribeFunc(
<del> /**
<del> * This function executes at beginning of subscription.
<del> *
<del> * This will always run, even if Subject is in terminal state.
<del> */
<del> new Action1<SubjectObserver<? super T>>() {
<del> @Override
<del> public void call(SubjectObserver<? super T> o) {
<del> /*
<del> * When we subscribe we always emit the latest value to the observer.
<del> *
<del> * Here we only emit if it's an onNext as terminal states are handled in the next function.
<del> */
<del> state.addPending(o);
<del> }
<del> },
<del> /**
<del> * This function executes if the Subject is terminated before subscription occurs.
<del> */
<del> new Action1<SubjectObserver<? super T>>() {
<del> @Override
<del> public void call(SubjectObserver<? super T> o) {
<del> /*
<del> * If we are already terminated, or termination happens while trying to subscribe
<del> * this will be invoked and we emit whatever the last terminal value was.
<del> */
<del> state.removePending(o);
<del> }
<del> }, new Action1<SubjectObserver<? super T>>() {
<del> @Override
<del> public void call(SubjectObserver<? super T> o) {
<del> state.removePending(o);
<del> }
<del>
<del> });
<del> OnSubscribe<T> onSubscribe = new OnSubscribe<T>() {
<del>
<del> @Override
<del> public void call(Subscriber<? super T> t1) {
<del> onSubscribeBase.call(t1);
<del> state.removePendingSubscriber(t1);
<del> }
<del> };
<del> return new BehaviorSubject<T>(onSubscribe, subscriptionManager, state);
<add> return new BehaviorSubject<T>(new BehaviorOnSubscribe<T>(state), state);
<ide> }
<ide>
<ide> static final class State<T> {
<del> final AtomicReference<Notification<T>> lastNotification;
<del> /** Guarded by this. */
<del> List<Object> pendingSubscriptions;
<del> public State() {
<del> this.lastNotification = new AtomicReference<Notification<T>>();
<add> final AtomicReference<Notification<T>> latest = new AtomicReference<Notification<T>>();
<add> final AtomicReference<BehaviorState> observers = new AtomicReference<BehaviorState>(BehaviorState.EMPTY);
<add> void set(Notification<T> value) {
<add> this.latest.set(value);
<ide> }
<del> public void addPending(SubjectObserver<? super T> subscriber) {
<del> synchronized (this) {
<del> if (pendingSubscriptions == null) {
<del> pendingSubscriptions = new ArrayList<Object>(4);
<del> }
<del> pendingSubscriptions.add(subscriber);
<del> List<Notification<T>> list = new ArrayList<Notification<T>>(4);
<del> list.add(lastNotification.get());
<del> pendingSubscriptions.add(list);
<del> }
<add> Notification<T> get() {
<add> return latest.get();
<ide> }
<del> public void bufferValue(Notification<T> value) {
<del> synchronized (this) {
<del> if (pendingSubscriptions == null) {
<del> return;
<add> BehaviorObserver<T>[] observers() {
<add> return observers.get().observers;
<add> }
<add> boolean add(BehaviorObserver<T> o) {
<add> do {
<add> BehaviorState oldState = observers.get();
<add> if (oldState.terminated) {
<add> o.emitFirst(get());
<add> return false;
<ide> }
<del> for (int i = 1; i < pendingSubscriptions.size(); i += 2) {
<del> @SuppressWarnings("unchecked")
<del> List<Notification<T>> list = (List<Notification<T>>)pendingSubscriptions.get(i);
<del> list.add(value);
<add> BehaviorState newState = oldState.add(o);
<add> if (observers.compareAndSet(oldState, newState)) {
<add> o.emitFirst(get());
<add> return true;
<ide> }
<del> }
<add> } while (true);
<ide> }
<del> public void removePending(SubjectObserver<? super T> subscriber) {
<del> List<Notification<T>> toCatchUp = null;
<del> synchronized (this) {
<del> if (pendingSubscriptions == null) {
<add> void remove(BehaviorObserver<T> o) {
<add> do {
<add> BehaviorState oldState = observers.get();
<add> if (oldState.terminated) {
<ide> return;
<ide> }
<del> int idx = pendingSubscriptions.indexOf(subscriber);
<del> if (idx >= 0) {
<del> pendingSubscriptions.remove(idx);
<del> @SuppressWarnings("unchecked")
<del> List<Notification<T>> list = (List<Notification<T>>)pendingSubscriptions.remove(idx);
<del> toCatchUp = list;
<del> subscriber.caughtUp = true;
<del> if (pendingSubscriptions.isEmpty()) {
<del> pendingSubscriptions = null;
<del> }
<del> }
<del> }
<del> if (toCatchUp != null) {
<del> for (Notification<T> n : toCatchUp) {
<del> if (n != null) {
<del> n.accept(subscriber);
<del> }
<add> BehaviorState newState = oldState.remove(o);
<add> if (newState == oldState || observers.compareAndSet(oldState, newState)) {
<add> return;
<ide> }
<del> }
<add> } while (true);
<ide> }
<del> public void removePendingSubscriber(Subscriber<? super T> subscriber) {
<del> List<Notification<T>> toCatchUp = null;
<del> synchronized (this) {
<del> if (pendingSubscriptions == null) {
<del> return;
<add> BehaviorObserver<T>[] next(Notification<T> n) {
<add> set(n);
<add> return observers.get().observers;
<add> }
<add> BehaviorObserver<T>[] terminate(Notification<T> n) {
<add> set(n);
<add> do {
<add> BehaviorState oldState = observers.get();
<add> if (oldState.terminated) {
<add> return BehaviorState.NO_OBSERVERS;
<ide> }
<del> for (int i = 0; i < pendingSubscriptions.size(); i += 2) {
<del> @SuppressWarnings("unchecked")
<del> SubjectObserver<? super T> so = (SubjectObserver<? super T>)pendingSubscriptions.get(i);
<del> if (so.getActual() == subscriber && !so.caughtUp) {
<del> @SuppressWarnings("unchecked")
<del> List<Notification<T>> list = (List<Notification<T>>)pendingSubscriptions.get(i + 1);
<del> toCatchUp = list;
<del> so.caughtUp = true;
<del> pendingSubscriptions.remove(i);
<del> pendingSubscriptions.remove(i);
<del> if (pendingSubscriptions.isEmpty()) {
<del> pendingSubscriptions = null;
<del> }
<del> break;
<del> }
<add> if (observers.compareAndSet(oldState, BehaviorState.TERMINATED)) {
<add> return oldState.observers;
<ide> }
<add> } while (true);
<add> }
<add> }
<add> static final class BehaviorState {
<add> final boolean terminated;
<add> final BehaviorObserver[] observers;
<add> static final BehaviorObserver[] NO_OBSERVERS = new BehaviorObserver[0];
<add> static final BehaviorState TERMINATED = new BehaviorState(true, NO_OBSERVERS);
<add> static final BehaviorState EMPTY = new BehaviorState(false, NO_OBSERVERS);
<add>
<add> public BehaviorState(boolean terminated, BehaviorObserver[] observers) {
<add> this.terminated = terminated;
<add> this.observers = observers;
<add> }
<add> public BehaviorState add(BehaviorObserver o) {
<add> int n = observers.length;
<add> BehaviorObserver[] a = new BehaviorObserver[n + 1];
<add> System.arraycopy(observers, 0, a, 0, n);
<add> a[n] = o;
<add> return new BehaviorState(terminated, a);
<add> }
<add> public BehaviorState remove(BehaviorObserver o) {
<add> BehaviorObserver[] a = observers;
<add> int n = a.length;
<add> if (n == 1 && a[0] == o) {
<add> return EMPTY;
<add> } else
<add> if (n == 0) {
<add> return this;
<ide> }
<del> if (toCatchUp != null) {
<del> for (Notification<T> n : toCatchUp) {
<del> if (n != null) {
<del> n.accept(subscriber);
<add> BehaviorObserver[] b = new BehaviorObserver[n - 1];
<add> int j = 0;
<add> for (int i = 0; i < n; i++) {
<add> BehaviorObserver ai = a[i];
<add> if (ai != o) {
<add> if (j == n - 1) {
<add> return this;
<ide> }
<add> b[j++] = ai;
<ide> }
<ide> }
<add> if (j == 0) {
<add> return EMPTY;
<add> }
<add> if (j < n - 1) {
<add> BehaviorObserver[] c = new BehaviorObserver[j];
<add> System.arraycopy(b, 0, c, 0, j);
<add> b = c;
<add> }
<add> return new BehaviorState(terminated, b);
<ide> }
<del> public void replayAllPending() {
<del> List<Object> localPending;
<del> synchronized (this) {
<del> localPending = pendingSubscriptions;
<del> pendingSubscriptions = null;
<add> }
<add>
<add> static final class BehaviorOnSubscribe<T> implements OnSubscribe<T> {
<add> private final State<T> state;
<add>
<add> public BehaviorOnSubscribe(State<T> state) {
<add> this.state = state;
<add> }
<add>
<add> @Override
<add> public void call(final Subscriber<? super T> child) {
<add> BehaviorObserver<T> bo = new BehaviorObserver<T>(child);
<add> addUnsubscriber(child, bo);
<add> if (state.add(bo) && child.isUnsubscribed()) {
<add> state.remove(bo);
<ide> }
<del> if (localPending != null) {
<del> for (int i = 0; i < localPending.size(); i += 2) {
<del> @SuppressWarnings("unchecked")
<del> SubjectObserver<? super T> so = (SubjectObserver<? super T>)localPending.get(i);
<del> if (!so.caughtUp) {
<del> @SuppressWarnings("unchecked")
<del> List<Notification<T>> list = (List<Notification<T>>)localPending.get(i + 1);
<del> for (Notification<T> v : list) {
<del> if (v != null) {
<del> v.accept(so);
<del> }
<del> }
<del> so.caughtUp = true;
<del> }
<add> }
<add>
<add> void addUnsubscriber(Subscriber<? super T> child, final BehaviorObserver<T> bo) {
<add> child.add(Subscriptions.create(new Action0() {
<add> @Override
<add> public void call() {
<add> state.remove(bo);
<ide> }
<del> }
<add> }));
<ide> }
<ide> }
<ide>
<add>
<ide> private final State<T> state;
<del> private final SubjectSubscriptionManager<T> subscriptionManager;
<ide>
<del> protected BehaviorSubject(OnSubscribe<T> onSubscribe, SubjectSubscriptionManager<T> subscriptionManager,
<del> State<T> state) {
<add> protected BehaviorSubject(OnSubscribe<T> onSubscribe, State<T> state) {
<ide> super(onSubscribe);
<del> this.subscriptionManager = subscriptionManager;
<ide> this.state = state;
<ide> }
<ide>
<ide> @Override
<ide> public void onCompleted() {
<del> Collection<SubjectObserver<? super T>> observers = subscriptionManager.terminate(new Action0() {
<del>
<del> @Override
<del> public void call() {
<del> final Notification<T> ne = Notification.<T>createOnCompleted();
<del> state.bufferValue(ne);
<del> state.lastNotification.set(ne);
<del> }
<del> });
<del> if (observers != null) {
<del> state.replayAllPending();
<del> for (Observer<? super T> o : observers) {
<del> o.onCompleted();
<add> Notification<T> last = state.get();
<add> if (last == null || last.isOnNext()) {
<add> Notification<T> n = Notification.<T>createOnCompleted();
<add> for (BehaviorObserver<T> bo : state.terminate(n)) {
<add> bo.emitNext(n);
<ide> }
<ide> }
<ide> }
<ide>
<ide> @Override
<del> public void onError(final Throwable e) {
<del> Collection<SubjectObserver<? super T>> observers = subscriptionManager.terminate(new Action0() {
<del>
<del> @Override
<del> public void call() {
<del> final Notification<T> ne = Notification.<T>createOnError(e);
<del> state.bufferValue(ne);
<del> state.lastNotification.set(ne);
<del> }
<del> });
<del> if (observers != null) {
<del> state.replayAllPending();
<del> for (Observer<? super T> o : observers) {
<del> o.onError(e);
<add> public void onError(Throwable e) {
<add> Notification<T> last = state.get();
<add> if (last == null || last.isOnNext()) {
<add> Notification<T> n = Notification.<T>createOnError(e);
<add> for (BehaviorObserver<T> bo : state.terminate(n)) {
<add> bo.emitNext(n);
<ide> }
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void onNext(T v) {
<del> // do not overwrite a terminal notification
<del> // so new subscribers can get them
<del> Notification<T> last = state.lastNotification.get();
<add> Notification<T> last = state.get();
<ide> if (last == null || last.isOnNext()) {
<ide> Notification<T> n = Notification.createOnNext(v);
<del> state.bufferValue(n);
<del> state.lastNotification.set(n);
<del>
<del> for (SubjectObserver<? super T> o : subscriptionManager.rawSnapshot()) {
<del> if (o.caughtUp) {
<del> o.onNext(v);
<del> } else {
<del> state.removePending(o);
<add> for (BehaviorObserver<T> bo : state.next(n)) {
<add> bo.emitNext(n);
<add> }
<add> }
<add> }
<add>
<add> /* test support */ int subscriberCount() {
<add> return state.observers.get().observers.length;
<add> }
<add>
<add> private static final class BehaviorObserver<T> {
<add> final Observer<? super T> actual;
<add> /** Guarded by this. */
<add> boolean first = true;
<add> /** Guarded by this. */
<add> boolean emitting;
<add> /** Guarded by this. */
<add> List<Notification<T>> queue;
<add> /** Accessed only from serialized state. */
<add> boolean done;
<add> volatile boolean fastPath;
<add> public BehaviorObserver(Observer<? super T> actual) {
<add> this.actual = actual;
<add> }
<add> void emitNext(Notification<T> n) {
<add> if (fastPath) {
<add> accept(n);
<add> return;
<add> }
<add> List<Notification<T>> localQueue;
<add> synchronized (this) {
<add> first = false;
<add> if (emitting) {
<add> if (queue == null) {
<add> queue = new ArrayList<Notification<T>>();
<add> }
<add> queue.add(n);
<add> return;
<add> }
<add> emitting = true;
<add> localQueue = queue;
<add> queue = null;
<add> }
<add> fastPath = true;
<add> emitLoop(localQueue, n);
<add> }
<add> void emitFirst(Notification<T> n) {
<add> List<Notification<T>> localQueue;
<add> synchronized (this) {
<add> if (!first || emitting) {
<add> return;
<add> }
<add> first = false;
<add> emitting = true;
<add> localQueue = queue;
<add> queue = null;
<add> }
<add> emitLoop(localQueue, n);
<add> }
<add> void emitLoop(List<Notification<T>> localQueue, Notification<T> current) {
<add> boolean once = true;
<add> boolean skipFinal = false;
<add> try {
<add> do {
<add> if (localQueue != null) {
<add> for (Notification<T> n : localQueue) {
<add> accept(n);
<add> }
<add> }
<add> if (once) {
<add> once = false;
<add> accept(current);
<add> }
<add> synchronized (this) {
<add> localQueue = queue;
<add> queue = null;
<add> if (localQueue == null) {
<add> emitting = false;
<add> skipFinal = true;
<add> break;
<add> }
<add> }
<add> } while (true);
<add> } finally {
<add> if (!skipFinal) {
<add> synchronized (this) {
<add> emitting = false;
<add> }
<add> }
<add> }
<add> }
<add> void accept(Notification<T> n) {
<add> if (n != null && !done) {
<add> if (!n.isOnNext()) {
<add> done = true;
<ide> }
<add> n.accept(actual);
<ide> }
<ide> }
<ide> }
<ide><path>rxjava-core/src/test/java/rx/subjects/BehaviorSubjectTest.java
<ide> */
<ide> package rx.subjects;
<ide>
<add>import static org.junit.Assert.assertEquals;
<ide> import static org.mockito.Matchers.any;
<ide> import static org.mockito.Mockito.inOrder;
<ide> import static org.mockito.Mockito.mock;
<ide> public void testStartEmptyCompleteWithOne() {
<ide> verify(o, never()).onError(any(Throwable.class));
<ide> verify(o, never()).onNext(any());
<ide> }
<add>
<add> @Test
<add> public void testTakeOneSubscriber() {
<add> BehaviorSubject<Integer> source = BehaviorSubject.create(1);
<add> @SuppressWarnings("unchecked")
<add> final Observer<Object> o = mock(Observer.class);
<add>
<add> source.take(1).subscribe(o);
<add>
<add> verify(o).onNext(1);
<add> verify(o).onCompleted();
<add> verify(o, never()).onError(any(Throwable.class));
<add>
<add> assertEquals(0, source.subscriberCount());
<add> }
<ide> } | 2 |
Javascript | Javascript | restore original click prop hook | 51fd4593fc43f4c935d3226485f6864b05366621 | <ide><path>test/unit/event.js
<ide> test("propHooks extensions", function() {
<ide>
<ide> delete jQuery.event.propHooks.click;
<ide> $fixture.unbind( "click" ).remove();
<add> jQuery.event.propHooks.click = saved;
<ide> });
<ide>
<ide> (function(){ | 1 |
Python | Python | use drain_events with amqplib/pika | e7a17c61d0e38cf3b70d4c818557df8d345658bb | <ide><path>celery/tests/test_worker.py
<ide> def test_connection(self):
<ide> send_events=False)
<ide>
<ide> l.reset_connection()
<del> self.assertTrue(isinstance(l.amqp_connection, BrokerConnection))
<add> self.assertTrue(isinstance(l.connection, BrokerConnection))
<ide>
<ide> l.close_connection()
<del> self.assertTrue(l.amqp_connection is None)
<add> self.assertTrue(l.connection is None)
<ide> self.assertTrue(l.task_consumer is None)
<ide>
<ide> l.reset_connection()
<del> self.assertTrue(isinstance(l.amqp_connection, BrokerConnection))
<add> self.assertTrue(isinstance(l.connection, BrokerConnection))
<ide>
<ide> l.stop()
<del> self.assertTrue(l.amqp_connection is None)
<add> self.assertTrue(l.connection is None)
<ide> self.assertTrue(l.task_consumer is None)
<ide>
<ide> def test_receieve_message(self):
<ide><path>celery/worker/listener.py
<ide> class CarrotListener(object):
<ide>
<ide> def __init__(self, ready_queue, eta_schedule, logger,
<ide> send_events=False, initial_prefetch_count=2):
<del> self.amqp_connection = None
<add> self.connection = None
<ide> self.task_consumer = None
<ide> self.ready_queue = ready_queue
<ide> self.eta_schedule = eta_schedule
<ide> def close_connection(self):
<ide> self.event_dispatcher.close()
<ide> self.logger.debug(
<ide> "CarrotListener: Closing connection to broker...")
<del> self.amqp_connection = self.amqp_connection and \
<del> self.amqp_connection.close()
<add> self.connection = self.connection and self.connection.close()
<ide>
<ide> def reset_connection(self):
<ide> self.logger.debug(
<ide> "CarrotListener: Re-establishing connection to the broker...")
<ide> self.close_connection()
<del> self.amqp_connection = self._open_connection()
<add> self.connection = self._open_connection()
<ide> self.logger.debug("CarrotListener: Connection Established.")
<del> self.task_consumer = get_consumer_set(connection=self.amqp_connection)
<del> self.broadcast_consumer = BroadcastConsumer(self.amqp_connection)
<add> self.task_consumer = get_consumer_set(connection=self.connection)
<add> self.broadcast_consumer = BroadcastConsumer(self.connection)
<ide> self.task_consumer.register_callback(self.receive_message)
<del> self.event_dispatcher = EventDispatcher(self.amqp_connection,
<add> self.event_dispatcher = EventDispatcher(self.connection,
<ide> enabled=self.send_events)
<ide> self.heart = Heart(self.event_dispatcher)
<ide> self.heart.start()
<ide>
<ide> self._state = RUN
<ide>
<del> def _amqplib_iterconsume(self, **kwargs):
<add> def _mainloop(self, **kwargs):
<ide> while 1:
<del> yield self.amqp_connection.connection.wait_any()
<add> yield self.connection.connection.drain_events()
<ide>
<ide> def _detect_wait_method(self):
<del> if hasattr(self.amqp_connection.connection, "wait_any"):
<add> if hasattr(self.connection.connection, "drain_events"):
<ide> self.broadcast_consumer.register_callback(self.receive_message)
<ide> self.task_consumer.iterconsume()
<ide> self.broadcast_consumer.iterconsume()
<del> return self._amqplib_iterconsume
<add> return self._mainloop
<ide> else:
<ide> self.task_consumer.add_consumer(self.broadcast_consumer)
<ide> return self.task_consumer.iterconsume | 2 |
Go | Go | add testcase isvalidstatestring | 675ac37482432e13d1312647762d9db8b9bb175e | <ide><path>container/state_test.go
<ide> func TestStateTimeoutWait(t *testing.T) {
<ide> }
<ide> }
<ide> }
<add>
<add>func TestIsValidStateString(t *testing.T) {
<add> states := []struct {
<add> state string
<add> expected bool
<add> }{
<add> {"paused", true},
<add> {"restarting", true},
<add> {"running", true},
<add> {"dead", true},
<add> {"start", false},
<add> {"created", true},
<add> {"exited", true},
<add> {"removing", true},
<add> {"stop", false},
<add> }
<add>
<add> for _, s := range states {
<add> v := IsValidStateString(s.state)
<add> if v != s.expected {
<add> t.Fatalf("Expected %t, but got %t", s.expected, v)
<add> }
<add> }
<add>} | 1 |
PHP | PHP | call fewer functions when generating routes | aeb609b4385350e2d62d8ea5b0f987ba1cf3cae9 | <ide><path>src/Routing/Route/Route.php
<ide> protected function _writeUrl($params, $pass = [], $query = []) {
<ide> $pass = implode('/', array_map('rawurlencode', $pass));
<ide> $out = $this->template;
<ide>
<del> if (!empty($this->keys)) {
<del> $search = $replace = [];
<del>
<del> foreach ($this->keys as $key) {
<del> $string = null;
<del> if (isset($params[$key])) {
<del> $string = $params[$key];
<del> } elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
<del> $key .= '/';
<del> }
<del> $search[] = ':' . $key;
<del> $replace[] = $string;
<add> $search = $replace = [];
<add> foreach ($this->keys as $key) {
<add> $string = null;
<add> if (isset($params[$key])) {
<add> $string = $params[$key];
<add> } elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
<add> $key .= '/';
<ide> }
<del> $out = str_replace($search, $replace, $out);
<add> $search[] = ':' . $key;
<add> $replace[] = $string;
<ide> }
<ide>
<ide> if (strpos($this->template, '**') !== false) {
<del> $out = str_replace('**', $pass, $out);
<del> $out = str_replace('%2F', '/', $out);
<add> array_push($search, '**', '%2F');
<add> array_push($replace, $pass, '/');
<ide> } elseif (strpos($this->template, '*') !== false) {
<del> $out = str_replace('*', $pass, $out);
<add> $search[] = '*';
<add> $replace[] = $pass;
<ide> }
<add> $out = str_replace($search, $replace, $out);
<ide>
<ide> // add base url if applicable.
<ide> if (isset($params['_base'])) {
<ide> protected function _writeUrl($params, $pass = [], $query = []) {
<ide> }
<ide>
<ide> $out = str_replace('//', '/', $out);
<del>
<ide> if (
<ide> isset($params['_scheme']) ||
<ide> isset($params['_host']) ||
<ide> protected function _writeUrl($params, $pass = [], $query = []) {
<ide> if (isset($params['_port'])) {
<ide> $host .= ':' . $params['_port'];
<ide> }
<del> $out = sprintf(
<del> '%s://%s%s',
<del> $params['_scheme'],
<del> $host,
<del> $out
<del> );
<add> $out = "{$params['_scheme']}://{$host}{$out}";
<ide> }
<ide> if (!empty($params['_ext']) || !empty($query)) {
<ide> $out = rtrim($out, '/'); | 1 |
Python | Python | add auth param to request client calls | b86765d9c02388f6bb82dbb5824a005e8fe73dec | <ide><path>rest_framework/tests/test_authentication.py
<ide> def test_post_form_with_request_token_failing_oauth(self):
<ide> def test_post_form_with_urlencoded_parameters(self):
<ide> """Ensure POSTing with x-www-form-urlencoded auth parameters passes"""
<ide> params = self._create_authorization_url_parameters()
<del> response = self.csrf_client.post('/oauth/', params)
<add> auth = self._create_authorization_header()
<add> response = self.csrf_client.post('/oauth/', params, HTTP_AUTHORIZATION=auth)
<ide> self.assertEqual(response.status_code, 200)
<ide>
<ide> @unittest.skipUnless(oauth_provider, 'django-oauth-plus not installed')
<ide> def test_post_form_with_write_resource_passing_auth(self):
<ide> read_write_access_token.resource.is_readonly = False
<ide> read_write_access_token.resource.save()
<ide> params = self._create_authorization_url_parameters()
<del> response = self.csrf_client.post('/oauth-with-scope/', params)
<add> auth = self._create_authorization_header()
<add> response = self.csrf_client.post('/oauth-with-scope/', params, HTTP_AUTHORIZATION=auth)
<ide> self.assertEqual(response.status_code, 200)
<ide>
<ide> @unittest.skipUnless(oauth_provider, 'django-oauth-plus not installed') | 1 |
Python | Python | fix usage of ``range(len())`` to ``enumerate`` | 29af57b6d8827949f553b997bbb860cd560fa0b2 | <ide><path>airflow/models/baseoperator.py
<ide> def resolve_template_files(self) -> None:
<ide> self.log.exception(e)
<ide> elif isinstance(content, list):
<ide> env = self.dag.get_template_env()
<del> for i in range(len(content)):
<del> if isinstance(content[i], str) and any(
<del> content[i].endswith(ext) for ext in self.template_ext
<del> ):
<add> for i, item in enumerate(content):
<add> if isinstance(item, str) and any(item.endswith(ext) for ext in self.template_ext):
<ide> try:
<del> content[i] = env.loader.get_source(env, content[i])[0]
<add> content[i] = env.loader.get_source(env, item)[0]
<ide> except Exception as e:
<ide> self.log.exception(e)
<ide> self.prepare_template()
<ide><path>airflow/providers/papermill/operators/papermill.py
<ide> def execute(self, context):
<ide> if not self.inlets or not self.outlets:
<ide> raise ValueError("Input notebook or output notebook is not specified")
<ide>
<del> for i in range(len(self.inlets)):
<add> for i, item in enumerate(self.inlets):
<ide> pm.execute_notebook(
<del> self.inlets[i].url,
<add> item.url,
<ide> self.outlets[i].url,
<del> parameters=self.inlets[i].parameters,
<add> parameters=item.parameters,
<ide> progress_bar=False,
<ide> report_mode=True,
<ide> )
<ide><path>tests/providers/apache/drill/hooks/test_drill.py
<ide> def test_get_pandas_df(self):
<ide> df = self.db_hook().get_pandas_df(statement)
<ide>
<ide> assert column == df.columns[0]
<del> for i in range(len(result_sets)): # pylint: disable=consider-using-enumerate
<del> assert result_sets[i][0] == df.values.tolist()[i][0]
<add> for i, item in enumerate(result_sets):
<add> assert item[0] == df.values.tolist()[i][0]
<ide> assert self.conn.close.call_count == 1
<ide> assert self.cur.close.call_count == 1
<ide> self.cur.execute.assert_called_once_with(statement)
<ide><path>tests/providers/apache/druid/hooks/test_druid.py
<ide> def test_get_pandas_df(self):
<ide> df = self.db_hook().get_pandas_df(statement)
<ide>
<ide> assert column == df.columns[0]
<del> for i in range(len(result_sets)):
<del> assert result_sets[i][0] == df.values.tolist()[i][0]
<add> for i, item in enumerate(result_sets):
<add> assert item[0] == df.values.tolist()[i][0]
<ide> assert self.conn.close.call_count == 1
<ide> assert self.cur.close.call_count == 1
<ide> self.cur.execute.assert_called_once_with(statement)
<ide><path>tests/providers/apache/pinot/hooks/test_pinot.py
<ide> def test_get_pandas_df(self):
<ide> self.cur.fetchall.return_value = result_sets
<ide> df = self.db_hook().get_pandas_df(statement)
<ide> assert column == df.columns[0]
<del> for i in range(len(result_sets)):
<del> assert result_sets[i][0] == df.values.tolist()[i][0]
<add> for i, item in enumerate(result_sets):
<add> assert item[0] == df.values.tolist()[i][0]
<ide>
<ide>
<ide> class TestPinotDbApiHookIntegration(unittest.TestCase):
<ide><path>tests/providers/exasol/hooks/test_exasol.py
<ide> def test_run_multi_queries(self):
<ide> sql = ['SQL1', 'SQL2']
<ide> self.db_hook.run(sql, autocommit=True)
<ide> self.conn.set_autocommit.assert_called_once_with(True)
<del> for i in range(len(self.conn.execute.call_args_list)):
<del> args, kwargs = self.conn.execute.call_args_list[i]
<add> for i, item in enumerate(self.conn.execute.call_args_list):
<add> args, kwargs = item
<ide> assert len(args) == 2
<ide> assert args[0] == sql[i]
<ide> assert kwargs == {}
<ide><path>tests/providers/mysql/hooks/test_mysql.py
<ide> def test_run_multi_queries(self):
<ide> sql = ['SQL1', 'SQL2']
<ide> self.db_hook.run(sql, autocommit=True)
<ide> self.conn.autocommit.assert_called_once_with(True)
<del> for i in range(len(self.cur.execute.call_args_list)):
<del> args, kwargs = self.cur.execute.call_args_list[i]
<add> for i, item in enumerate(self.cur.execute.call_args_list):
<add> args, kwargs = item
<ide> assert len(args) == 1
<ide> assert args[0] == sql[i]
<ide> assert kwargs == {} | 7 |
PHP | PHP | throw exception if cspbuilder is not available | 28cb132908c9c7c1ebf63e47705846bb6e27baac | <ide><path>src/Http/Middleware/CspMiddleware.php
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide> use Psr\Http\Server\MiddlewareInterface;
<ide> use Psr\Http\Server\RequestHandlerInterface;
<add>use RuntimeException;
<ide>
<ide> /**
<ide> * Content Security Policy Middleware
<ide> class CspMiddleware implements MiddlewareInterface
<ide> */
<ide> public function __construct($csp)
<ide> {
<add> if (!class_exists(CSPBuilder::class)) {
<add> throw new RuntimeException('You must install paragonie/csp-builder to use CspMiddleware');
<add> }
<add>
<ide> if (!$csp instanceof CSPBuilder) {
<ide> $csp = new CSPBuilder($csp);
<ide> } | 1 |
Mixed | Go | add format to docker stack ls | 205ec49de9c4f4abb8023d1ad36fdbc92e7ec294 | <ide><path>cli/command/formatter/stack.go
<add>package formatter
<add>
<add>import (
<add> "strconv"
<add>)
<add>
<add>const (
<add> defaultStackTableFormat = "table {{.Name}}\t{{.Services}}"
<add>
<add> stackServicesHeader = "SERVICES"
<add>)
<add>
<add>// Stack contains deployed stack information.
<add>type Stack struct {
<add> // Name is the name of the stack
<add> Name string
<add> // Services is the number of the services
<add> Services int
<add>}
<add>
<add>// NewStackFormat returns a format for use with a stack Context
<add>func NewStackFormat(source string) Format {
<add> switch source {
<add> case TableFormatKey:
<add> return defaultStackTableFormat
<add> }
<add> return Format(source)
<add>}
<add>
<add>// StackWrite writes formatted stacks using the Context
<add>func StackWrite(ctx Context, stacks []*Stack) error {
<add> render := func(format func(subContext subContext) error) error {
<add> for _, stack := range stacks {
<add> if err := format(&stackContext{s: stack}); err != nil {
<add> return err
<add> }
<add> }
<add> return nil
<add> }
<add> return ctx.Write(newStackContext(), render)
<add>}
<add>
<add>type stackContext struct {
<add> HeaderContext
<add> s *Stack
<add>}
<add>
<add>func newStackContext() *stackContext {
<add> stackCtx := stackContext{}
<add> stackCtx.header = map[string]string{
<add> "Name": nameHeader,
<add> "Services": stackServicesHeader,
<add> }
<add> return &stackCtx
<add>}
<add>
<add>func (s *stackContext) MarshalJSON() ([]byte, error) {
<add> return marshalJSON(s)
<add>}
<add>
<add>func (s *stackContext) Name() string {
<add> return s.s.Name
<add>}
<add>
<add>func (s *stackContext) Services() string {
<add> return strconv.Itoa(s.s.Services)
<add>}
<ide><path>cli/command/formatter/stack_test.go
<add>package formatter
<add>
<add>import (
<add> "bytes"
<add> "testing"
<add>
<add> "github.com/stretchr/testify/assert"
<add>)
<add>
<add>func TestStackContextWrite(t *testing.T) {
<add> cases := []struct {
<add> context Context
<add> expected string
<add> }{
<add> // Errors
<add> {
<add> Context{Format: "{{InvalidFunction}}"},
<add> `Template parsing error: template: :1: function "InvalidFunction" not defined
<add>`,
<add> },
<add> {
<add> Context{Format: "{{nil}}"},
<add> `Template parsing error: template: :1:2: executing "" at <nil>: nil is not a command
<add>`,
<add> },
<add> // Table format
<add> {
<add> Context{Format: NewStackFormat("table")},
<add> `NAME SERVICES
<add>baz 2
<add>bar 1
<add>`,
<add> },
<add> {
<add> Context{Format: NewStackFormat("table {{.Name}}")},
<add> `NAME
<add>baz
<add>bar
<add>`,
<add> },
<add> // Custom Format
<add> {
<add> Context{Format: NewStackFormat("{{.Name}}")},
<add> `baz
<add>bar
<add>`,
<add> },
<add> }
<add>
<add> stacks := []*Stack{
<add> {Name: "baz", Services: 2},
<add> {Name: "bar", Services: 1},
<add> }
<add> for _, testcase := range cases {
<add> out := bytes.NewBufferString("")
<add> testcase.context.Output = out
<add> err := StackWrite(testcase.context, stacks)
<add> if err != nil {
<add> assert.Error(t, err, testcase.expected)
<add> } else {
<add> assert.Equal(t, out.String(), testcase.expected)
<add> }
<add> }
<add>}
<ide><path>cli/command/stack/list.go
<ide> package stack
<ide>
<ide> import (
<del> "fmt"
<del> "io"
<ide> "sort"
<del> "strconv"
<del> "text/tabwriter"
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/cli/command"
<add> "github.com/docker/docker/cli/command/formatter"
<ide> "github.com/docker/docker/cli/compose/convert"
<ide> "github.com/docker/docker/client"
<ide> "github.com/pkg/errors"
<ide> "github.com/spf13/cobra"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<del>const (
<del> listItemFmt = "%s\t%s\n"
<del>)
<del>
<ide> type listOptions struct {
<add> format string
<ide> }
<ide>
<ide> func newListCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> func newListCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> },
<ide> }
<ide>
<add> flags := cmd.Flags()
<add> flags.StringVar(&opts.format, "format", "", "Pretty-print stacks using a Go template")
<ide> return cmd
<ide> }
<ide>
<ide> func runList(dockerCli *command.DockerCli, opts listOptions) error {
<ide> if err != nil {
<ide> return err
<ide> }
<del>
<del> out := dockerCli.Out()
<del> printTable(out, stacks)
<del> return nil
<add> format := opts.format
<add> if len(format) == 0 {
<add> format = formatter.TableFormatKey
<add> }
<add> stackCtx := formatter.Context{
<add> Output: dockerCli.Out(),
<add> Format: formatter.NewStackFormat(format),
<add> }
<add> sort.Sort(byName(stacks))
<add> return formatter.StackWrite(stackCtx, stacks)
<ide> }
<ide>
<del>type byName []*stack
<add>type byName []*formatter.Stack
<ide>
<ide> func (n byName) Len() int { return len(n) }
<ide> func (n byName) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
<ide> func (n byName) Less(i, j int) bool { return n[i].Name < n[j].Name }
<ide>
<del>func printTable(out io.Writer, stacks []*stack) {
<del> writer := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0)
<del>
<del> // Ignore flushing errors
<del> defer writer.Flush()
<del>
<del> sort.Sort(byName(stacks))
<del>
<del> fmt.Fprintf(writer, listItemFmt, "NAME", "SERVICES")
<del> for _, stack := range stacks {
<del> fmt.Fprintf(
<del> writer,
<del> listItemFmt,
<del> stack.Name,
<del> strconv.Itoa(stack.Services),
<del> )
<del> }
<del>}
<del>
<del>type stack struct {
<del> // Name is the name of the stack
<del> Name string
<del> // Services is the number of the services
<del> Services int
<del>}
<del>
<del>func getStacks(
<del> ctx context.Context,
<del> apiclient client.APIClient,
<del>) ([]*stack, error) {
<add>func getStacks(ctx context.Context, apiclient client.APIClient) ([]*formatter.Stack, error) {
<ide> services, err := apiclient.ServiceList(
<ide> ctx,
<ide> types.ServiceListOptions{Filters: getAllStacksFilter()})
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> m := make(map[string]*stack, 0)
<add> m := make(map[string]*formatter.Stack, 0)
<ide> for _, service := range services {
<ide> labels := service.Spec.Labels
<ide> name, ok := labels[convert.LabelNamespace]
<ide> func getStacks(
<ide> }
<ide> ztack, ok := m[name]
<ide> if !ok {
<del> m[name] = &stack{
<add> m[name] = &formatter.Stack{
<ide> Name: name,
<ide> Services: 1,
<ide> }
<ide> } else {
<ide> ztack.Services++
<ide> }
<ide> }
<del> var stacks []*stack
<add> var stacks []*formatter.Stack
<ide> for _, stack := range m {
<ide> stacks = append(stacks, stack)
<ide> }
<ide><path>docs/reference/commandline/stack_ls.md
<ide> Aliases:
<ide> ls, list
<ide>
<ide> Options:
<del> --help Print usage
<add> --help Print usage
<add> --format string Pretty-print stacks using a Go template
<ide> ```
<ide>
<ide> ## Description
<ide> vossibility-stack 6
<ide> myapp 2
<ide> ```
<ide>
<add>### Formatting
<add>
<add>The formatting option (`--format`) pretty-prints stacks using a Go template.
<add>
<add>Valid placeholders for the Go template are listed below:
<add>
<add>| Placeholder | Description |
<add>| ----------- | ------------------ |
<add>| `.Name` | Stack name |
<add>| `.Services` | Number of services |
<add>
<add>When using the `--format` option, the `stack ls` command either outputs
<add>the data exactly as the template declares or, when using the
<add>`table` directive, includes column headers as well.
<add>
<add>The following example uses a template without headers and outputs the
<add>`Name` and `Services` entries separated by a colon for all stacks:
<add>
<add>```bash
<add>$ docker stack ls --format "{{.Name}}: {{.Services}}"
<add>web-server: 1
<add>web-cache: 4
<add>```
<add>
<ide> ## Related commands
<ide>
<ide> * [stack deploy](stack_deploy.md)
<ide><path>integration-cli/docker_cli_stack_test.go
<ide> import (
<ide> "github.com/go-check/check"
<ide> )
<ide>
<add>var cleanSpaces = func(s string) string {
<add> lines := strings.Split(s, "\n")
<add> for i, line := range lines {
<add> spaceIx := strings.Index(line, " ")
<add> if spaceIx > 0 {
<add> lines[i] = line[:spaceIx+1] + strings.TrimLeft(line[spaceIx:], " ")
<add> }
<add> }
<add> return strings.Join(lines, "\n")
<add>}
<add>
<ide> func (s *DockerSwarmSuite) TestStackRemoveUnknown(c *check.C) {
<ide> d := s.AddDaemon(c, true, true)
<ide>
<ide> func (s *DockerSwarmSuite) TestStackDeployComposeFile(c *check.C) {
<ide>
<ide> out, err = d.Cmd("stack", "ls")
<ide> c.Assert(err, checker.IsNil)
<del> c.Assert(out, check.Equals, "NAME SERVICES\n"+"testdeploy 2\n")
<add> c.Assert(cleanSpaces(out), check.Equals, "NAME SERVICES\n"+"testdeploy 2\n")
<ide>
<ide> out, err = d.Cmd("stack", "rm", testStackName)
<ide> c.Assert(err, checker.IsNil)
<ide> out, err = d.Cmd("stack", "ls")
<ide> c.Assert(err, checker.IsNil)
<del> c.Assert(out, check.Equals, "NAME SERVICES\n")
<add> c.Assert(cleanSpaces(out), check.Equals, "NAME SERVICES\n")
<ide> }
<ide>
<ide> func (s *DockerSwarmSuite) TestStackDeployWithSecretsTwice(c *check.C) {
<ide> func (s *DockerSwarmSuite) TestStackDeployWithDAB(c *check.C) {
<ide> stackArgs = []string{"stack", "ls"}
<ide> out, err = d.Cmd(stackArgs...)
<ide> c.Assert(err, checker.IsNil)
<del> c.Assert(out, check.Equals, "NAME SERVICES\n"+"test 2\n")
<add> c.Assert(cleanSpaces(out), check.Equals, "NAME SERVICES\n"+"test 2\n")
<ide> // rm
<ide> stackArgs = []string{"stack", "rm", testStackName}
<ide> out, err = d.Cmd(stackArgs...)
<ide> func (s *DockerSwarmSuite) TestStackDeployWithDAB(c *check.C) {
<ide> stackArgs = []string{"stack", "ls"}
<ide> out, err = d.Cmd(stackArgs...)
<ide> c.Assert(err, checker.IsNil)
<del> c.Assert(out, check.Equals, "NAME SERVICES\n")
<add> c.Assert(cleanSpaces(out), check.Equals, "NAME SERVICES\n")
<ide> } | 5 |
Ruby | Ruby | reorder unpack strategies again | 278eace2faae151c753bf1fdfabe3175a23e7c35 | <ide><path>Library/Homebrew/unpack_strategy.rb
<ide> module UnpackStrategy
<ide>
<ide> def self.strategies
<ide> @strategies ||= [
<del> Pkg,
<del> Ttf,
<del> Otf,
<del> Air,
<del> Executable,
<del> Diff,
<add> Air, # needs to be before Zip
<ide> Jar, # needs to be before Zip
<ide> LuaRock, # needs to be before Zip
<ide> MicrosoftOfficeXml, # needs to be before Zip
<del> Zip,
<del> Xar,
<del> Compress,
<add> Zip, # needs to be before Tar
<add> Pkg, # needs to be before Xar
<add> Xar, # needs to be before Tar
<ide> Tar, # needs to be before Bzip2/Gzip/Xz/Lzma
<ide> Gzip,
<ide> Lzma,
<ide> Xz,
<ide> Lzip,
<add> Executable,
<add> Diff,
<ide> Git,
<ide> Mercurial,
<ide> Subversion,
<ide> Cvs,
<add> Ttf,
<add> Otf,
<ide> Dmg, # needs to be before Bzip2
<ide> Bzip2,
<ide> Fossil,
<ide> Bazaar,
<ide> SelfExtractingExecutable, # needs to be before Cab
<ide> Cab,
<add> Compress,
<ide> P7Zip,
<ide> Sit,
<ide> Rar, | 1 |
PHP | PHP | add test for cookie stuff | df041d2f92c3cc324617ee6707c8846e4e634872 | <ide><path>tests/Integration/Cookie/CookieTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Integration\Cookie;
<add>
<add>use Mockery;
<add>use Illuminate\Support\Str;
<add>use Illuminate\Http\Response;
<add>use Illuminate\Support\Carbon;
<add>use Orchestra\Testbench\TestCase;
<add>use Illuminate\Support\Facades\Route;
<add>use Illuminate\Support\Facades\Session;
<add>use Illuminate\Session\NullSessionHandler;
<add>use Illuminate\Contracts\Debug\ExceptionHandler;
<add>
<add>/**
<add> * @group integration
<add> */
<add>class CookieTest extends TestCase
<add>{
<add> public function test_cookie_is_sent_back_with_proper_expire_time_when_should_expire_on_close()
<add> {
<add> $this->app['config']->set('session.expire_on_close', true);
<add>
<add> Route::get('/', function () {
<add> return 'hello world';
<add> })->middleware('web');
<add>
<add> $response = $this->get('/');
<add> $this->assertCount(2, $response->headers->getCookies());
<add> $this->assertEquals(0, ($response->headers->getCookies()[1])->getExpiresTime());
<add> }
<add>
<add> public function test_cookie_is_sent_back_with_proper_expire_time_with_respect_to_lifetime()
<add> {
<add> $this->app['config']->set('session.expire_on_close', false);
<add> $this->app['config']->set('session.lifetime', 1);
<add>
<add> Route::get('/', function () {
<add> return 'hello world';
<add> })->middleware('web');
<add>
<add> Carbon::setTestNow(Carbon::now());
<add> $response = $this->get('/');
<add> $this->assertCount(2, $response->headers->getCookies());
<add> $this->assertEquals(Carbon::now()->getTimestamp() + 60, ($response->headers->getCookies()[1])->getExpiresTime());
<add> }
<add>
<add> protected function getEnvironmentSetUp($app)
<add> {
<add> $app->instance(
<add> ExceptionHandler::class,
<add> $handler = Mockery::mock(ExceptionHandler::class)->shouldIgnoreMissing()
<add> );
<add>
<add> $handler->shouldReceive('render')->andReturn(new Response);
<add>
<add> $app['config']->set('app.key', Str::random(32));
<add> $app['config']->set('session.driver', 'fake-null');
<add>
<add> Session::extend('fake-null', function () {
<add> return new NullSessionHandler;
<add> });
<add> }
<add>} | 1 |
Python | Python | fix typo in airflow/utils/dag_processing.py | a155db1d8836d78992280422e6b74b7e6f0426a6 | <ide><path>airflow/utils/dag_processing.py
<ide> def result(self) -> Optional[Tuple[int, int]]:
<ide> """
<ide> A list of simple dags found, and the number of import errors
<ide>
<del> :return: result of running SchedulerJob.process_file() if availlablle. Otherwise, none
<add> :return: result of running SchedulerJob.process_file() if available. Otherwise, none
<ide> :rtype: Optional[Tuple[int, int]]
<ide> """
<ide> raise NotImplementedError() | 1 |
Text | Text | unify dirname and filename description | 134481dbe96b7558c7a314c6bfe70aad4fe76ce3 | <ide><path>doc/api/globals.md
<ide> added: v0.1.27
<ide>
<ide> * {String}
<ide>
<del>The name of the directory that the currently executing script resides in.
<add>The directory name of the current module. This the same as the
<add>[`path.dirname()`][] of the [`__filename`][].
<add>
<add>`__dirname` isn't actually a global but rather local to each module.
<ide>
<ide> Example: running `node example.js` from `/Users/mjr`
<ide>
<ide> ```js
<ide> console.log(__dirname);
<ide> // Prints: /Users/mjr
<add>console.log(path.dirname(__filename));
<add>// Prints: /Users/mjr
<ide> ```
<ide>
<del>`__dirname` isn't actually a global but rather local to each module.
<del>
<del>For instance, given two modules: `a` and `b`, where `b` is a dependency of
<del>`a` and there is a directory structure of:
<del>
<del>* `/Users/mjr/app/a.js`
<del>* `/Users/mjr/app/node_modules/b/b.js`
<del>
<del>References to `__dirname` within `b.js` will return
<del>`/Users/mjr/app/node_modules/b` while references to `__dirname` within `a.js`
<del>will return `/Users/mjr/app`.
<del>
<ide> ## \_\_filename
<ide> <!-- YAML
<ide> added: v0.0.1
<ide> added: v0.0.1
<ide>
<ide> * {String}
<ide>
<del>The filename of the code being executed. This is the resolved absolute path
<del>of this code file. For a main program this is not necessarily the same
<del>filename used in the command line. The value inside a module is the path
<del>to that module file.
<add>The file name of the current module. This is the resolved absolute path of the
<add>current module file.
<ide>
<del>Example: running `node example.js` from `/Users/mjr`
<add>For a main program this is not necessarily the same as the file name used in the
<add>command line.
<add>
<add>See [`__dirname`][] for the directory name of the current module.
<add>
<add>`__filename` isn't actually a global but rather local to each module.
<add>
<add>Examples:
<add>
<add>Running `node example.js` from `/Users/mjr`
<ide>
<ide> ```js
<ide> console.log(__filename);
<ide> // Prints: /Users/mjr/example.js
<add>console.log(__dirname);
<add>// Prints: /Users/mjr
<ide> ```
<ide>
<del>`__filename` isn't actually a global but rather local to each module.
<add>Given two modules: `a` and `b`, where `b` is a dependency of
<add>`a` and there is a directory structure of:
<add>
<add>* `/Users/mjr/app/a.js`
<add>* `/Users/mjr/app/node_modules/b/b.js`
<add>
<add>References to `__filename` within `b.js` will return
<add>`/Users/mjr/app/node_modules/b/b.js` while references to `__filename` within
<add>`a.js` will return `/Users/mjr/app/a.js`.
<ide>
<ide> ## clearImmediate(immediateObject)
<ide> <!-- YAML
<ide> added: v0.0.1
<ide>
<ide> [`setTimeout`] is described in the [timers][] section.
<ide>
<add>[`__dirname`]: #globals_dirname
<add>[`__filename`]: #globals_filename
<ide> [`console`]: console.html
<add>[`path.dirname()`]: path.html#path_path_dirname_path
<ide> [`process` object]: process.html#process_process
<ide> [buffer section]: buffer.html
<ide> [module system documentation]: modules.html | 1 |
Ruby | Ruby | fix segmentation fault in actionpack tests | 22e0a22d5f98e162290d9820891d8191e720ad3b | <ide><path>actionpack/test/dispatch/response_test.rb
<ide> def test_response_body_encoding
<ide> original = ActionDispatch::Response.default_charset
<ide> begin
<ide> ActionDispatch::Response.default_charset = 'utf-16'
<del> resp = ActionDispatch::Response.new(200, { "Content-Type" => "text/xml" })
<add> resp = ActionDispatch::Response.new(200, { "Content-Type" => "text/xml" }, default_headers: nil)
<ide> assert_equal('utf-16', resp.charset)
<ide> ensure
<ide> ActionDispatch::Response.default_charset = original | 1 |
Python | Python | relax optimizer tests | 4b5984b8ce8799601ddf8f3fae0344b626c4ba48 | <ide><path>tests/keras/optimizers_test.py
<ide> def _test_optimizer(optimizer, target=0.75):
<ide> model.compile(loss='categorical_crossentropy',
<ide> optimizer=optimizer,
<ide> metrics=['accuracy'])
<del> history = model.fit(x_train, y_train, epochs=1, batch_size=16, verbose=0)
<add> history = model.fit(x_train, y_train, epochs=2, batch_size=16, verbose=0)
<ide> assert history.history['acc'][-1] >= target
<ide> config = optimizers.serialize(optimizer)
<ide> optim = optimizers.deserialize(config)
<ide> def test_adagrad():
<ide>
<ide>
<ide> def test_adadelta():
<del> _test_optimizer(optimizers.Adadelta())
<del> _test_optimizer(optimizers.Adadelta(decay=1e-3))
<add> _test_optimizer(optimizers.Adadelta(), target=0.6)
<add> _test_optimizer(optimizers.Adadelta(decay=1e-3), target=0.6)
<ide>
<ide>
<ide> def test_adam(): | 1 |
Javascript | Javascript | write more unit tests for the find controller | b1cef896f46319a9670fd0c528c8233e91dd97d8 | <ide><path>test/unit/pdf_find_controller_spec.js
<ide> describe('pdf_find_controller', function() {
<ide> pdfFindController = null;
<ide> });
<ide>
<del> it('performs a basic search', function(done) {
<del> pdfFindController.executeCommand('find', { query: 'Dynamic', });
<add> function testSearch({ parameters, matchesPerPage, selectedMatch, }) {
<add> return new Promise(function(resolve) {
<add> pdfFindController.executeCommand('find', parameters);
<add>
<add> // The `updatefindmatchescount` event is only emitted if the page contains
<add> // at least one match for the query, so the last non-zero item in the
<add> // matches per page array corresponds to the page for which the final
<add> // `updatefindmatchescount` event is emitted. If this happens, we know
<add> // that any subsequent pages won't trigger the event anymore and we
<add> // can start comparing the matches per page. This logic is necessary
<add> // because we call the `pdfFindController.pageMatches` getter directly
<add> // after receiving the event and the underlying `_pageMatches` array
<add> // is only extended when a page is processed, so it will only contain
<add> // entries for the pages processed until the time when the final event
<add> // was emitted.
<add> let totalPages = matchesPerPage.length;
<add> for (let i = totalPages - 1; i >= 0; i--) {
<add> if (matchesPerPage[i] > 0) {
<add> totalPages = i + 1;
<add> break;
<add> }
<add> }
<add>
<add> const totalMatches = matchesPerPage.reduce((a, b) => {
<add> return a + b;
<add> });
<ide>
<del> const matchesPerPage = [11, 5, 0, 3, 0, 0, 0, 1, 1, 1, 0, 3, 4, 4];
<del> const totalPages = matchesPerPage.length;
<del> const totalMatches = matchesPerPage.reduce((a, b) => {
<del> return a + b;
<add> eventBus.on('updatefindmatchescount',
<add> function onUpdateFindMatchesCount(evt) {
<add> if (pdfFindController.pageMatches.length !== totalPages) {
<add> return;
<add> }
<add> eventBus.off('updatefindmatchescount', onUpdateFindMatchesCount);
<add> console.log(pdfFindController.pageMatches);
<add>
<add> expect(evt.matchesCount.total).toBe(totalMatches);
<add> for (let i = 0; i < totalPages; i++) {
<add> expect(pdfFindController.pageMatches[i].length)
<add> .toEqual(matchesPerPage[i]);
<add> }
<add> expect(pdfFindController.selected.pageIdx)
<add> .toEqual(selectedMatch.pageIndex);
<add> expect(pdfFindController.selected.matchIdx)
<add> .toEqual(selectedMatch.matchIndex);
<add>
<add> resolve();
<add> });
<ide> });
<add> }
<ide>
<del> eventBus.on('updatefindmatchescount',
<del> function onUpdateFindMatchesCount(evt) {
<del> if (pdfFindController.pageMatches.length !== totalPages) {
<del> return;
<del> }
<del> eventBus.off('updatefindmatchescount', onUpdateFindMatchesCount);
<add> it('performs a normal search', function(done) {
<add> testSearch({
<add> parameters: {
<add> query: 'Dynamic',
<add> caseSensitive: false,
<add> entireWord: false,
<add> phraseSearch: true,
<add> findPrevious: false,
<add> },
<add> matchesPerPage: [11, 5, 0, 3, 0, 0, 0, 1, 1, 1, 0, 3, 4, 4],
<add> selectedMatch: {
<add> pageIndex: 0,
<add> matchIndex: 0,
<add> },
<add> }).then(done);
<add> });
<ide>
<del> expect(evt.matchesCount.total).toBe(totalMatches);
<del> for (let i = 0; i < totalPages; i++) {
<del> expect(pdfFindController.pageMatches[i].length)
<del> .toEqual(matchesPerPage[i]);
<del> }
<del> done();
<del> });
<add> it('performs a normal search and finds the previous result', function(done) {
<add> // Page 14 (with page index 13) contains five results. By default, the
<add> // first result (match index 0) is selected, so the previous result
<add> // should be the fifth result (match index 4).
<add> testSearch({
<add> parameters: {
<add> query: 'conference',
<add> caseSensitive: false,
<add> entireWord: false,
<add> phraseSearch: true,
<add> findPrevious: true,
<add> },
<add> matchesPerPage: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5],
<add> selectedMatch: {
<add> pageIndex: 13,
<add> matchIndex: 4,
<add> },
<add> }).then(done);
<add> });
<add>
<add> it('performs a case sensitive search', function(done) {
<add> testSearch({
<add> parameters: {
<add> query: 'Dynamic',
<add> caseSensitive: true,
<add> entireWord: false,
<add> phraseSearch: true,
<add> findPrevious: false,
<add> },
<add> matchesPerPage: [3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3],
<add> selectedMatch: {
<add> pageIndex: 0,
<add> matchIndex: 0,
<add> },
<add> }).then(done);
<add> });
<add>
<add> it('performs an entire word search', function(done) {
<add> // Page 13 contains both 'Government' and 'Governmental', so the latter
<add> // should not be found with entire word search.
<add> testSearch({
<add> parameters: {
<add> query: 'Government',
<add> caseSensitive: false,
<add> entireWord: true,
<add> phraseSearch: true,
<add> findPrevious: false,
<add> },
<add> matchesPerPage: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
<add> selectedMatch: {
<add> pageIndex: 12,
<add> matchIndex: 0,
<add> },
<add> }).then(done);
<add> });
<add>
<add> it('performs a multiple term (no phrase) search', function(done) {
<add> // Page 9 contains 'alternate' and pages 6 and 9 contain 'solution'.
<add> // Both should be found for multiple term (no phrase) search.
<add> testSearch({
<add> parameters: {
<add> query: 'alternate solution',
<add> caseSensitive: false,
<add> entireWord: false,
<add> phraseSearch: false,
<add> findPrevious: false,
<add> },
<add> matchesPerPage: [0, 0, 0, 0, 0, 1, 0, 0, 4, 0, 0, 0, 0, 0],
<add> selectedMatch: {
<add> pageIndex: 5,
<add> matchIndex: 0,
<add> },
<add> }).then(done);
<ide> });
<ide> }); | 1 |
Javascript | Javascript | update benchmark script to new api | 7c1c89fc29ccb1a27fb132e9299b5bb240b51df5 | <ide><path>benchmark/http_simple.js
<ide> http.createServer(function (req, res) {
<ide> }
<ide> );
<ide> res.write(body);
<del>
<del> res.finish();
<add> res.close();
<ide> }).listen(8000);
<ide><path>benchmark/static_http_server.js
<ide> var server = http.createServer(function (req, res) {
<ide> "Content-Length": body.length
<ide> });
<ide> res.write(body);
<del> res.finish();
<add> res.close();
<ide> })
<ide> server.listen(port);
<ide>
<ide> function responseListener (res) {
<ide> res.addListener("end", function () {
<ide> if (requests < n) {
<del> res.client.request("/").finish(responseListener);
<add> var req = res.client.request("/");
<add> req.addListener('response', responseListener);
<add> req.close();
<ide> requests++;
<ide> }
<ide>
<ide> function responseListener (res) {
<ide> for (var i = 0; i < concurrency; i++) {
<ide> var client = http.createClient(port);
<ide> client.id = i;
<del> client.request("/").finish(responseListener);
<add> var req = client.request("/");
<add> req.addListener('response', responseListener);
<add> req.close();
<ide> requests++;
<ide> } | 2 |
Text | Text | improve contributing.md about pull request | f5b1f157add9974b96def078592505b8b735950b | <ide><path>CONTRIBUTING.md
<ide> The core team will be monitoring for pull requests. When we get one, we'll run s
<ide> 2. **Describe your test plan in your commit.** If you've added code that should be tested, add tests!
<ide> 3. If you've changed APIs, update the documentation.
<ide> 4. If you've updated the docs, verify the website locally and submit screenshots if applicable
<del>```
<del>$ cd website
<del>$ npm install && npm start
<del>go to: http://localhost:8079/react-native/index.html
<del>```
<add>
<add> ```
<add> $ cd website
<add> $ npm install && npm start
<add> go to: http://localhost:8079/react-native/index.html
<add> ```
<add>
<ide> 5. Add the copyright notice to the top of any new files you've added.
<ide> 6. Ensure tests pass on Travis and Circle CI.
<ide> 7. Make sure your code lints (`node linter.js <files touched>`).
<del>8. Squash your commits (`git rebase -i`).
<del>9. If you haven't already, sign the [CLA](https://code.facebook.com/cla).
<add>8. If you haven't already, sign the [CLA](https://code.facebook.com/cla).
<add>9. Squash your commits (`git rebase -i`).
<add> one intent alongs with one commit makes it clearer for people to review and easier to understand your intention
<add>
<add>Note: It is not necessary to keep clicking `Merge master to your branch` on PR page. You would want to merge master if there are conflicts or tests are failing. The facebook-bot ultimately squashes all commits to a single one before merging your PR.
<ide>
<ide> #### Copyright Notice for files
<ide> | 1 |
Javascript | Javascript | add mustcall() to child-process test | f308b4d9ed234291890adec44750cb2f53b23e0e | <ide><path>test/parallel/test-child-process-stdio-big-write-end.js
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<ide> 'use strict';
<del>require('../common');
<add>const common = require('../common');
<ide> const assert = require('assert');
<ide> let bufsize = 0;
<ide>
<ide> function parent() {
<ide> child.stdout.on('data', function(c) {
<ide> n += c;
<ide> });
<del> child.stdout.on('end', function() {
<add> child.stdout.on('end', common.mustCall(function() {
<ide> assert.strictEqual(+n, sent);
<ide> console.log('ok');
<del> });
<add> }));
<ide>
<ide> // Write until the buffer fills up.
<ide> let buf; | 1 |
Ruby | Ruby | add message to `set_ownership` | 7f7eb7e6cdac080e85450def86db420480bdc695 | <ide><path>Library/Homebrew/cask/lib/hbc/staged.rb
<ide> def set_permissions(paths, permissions_str)
<ide> def set_ownership(paths, user: current_user, group: "staff")
<ide> full_paths = remove_nonexistent(paths)
<ide> return if full_paths.empty?
<add> ohai "Changing ownership of paths required by #{@cask}; your password may be necessary"
<ide> @command.run!("/usr/sbin/chown", args: ["-R", "--", "#{user}:#{group}"] + full_paths,
<ide> sudo: true)
<ide> end | 1 |
Java | Java | add params(multivaluemap) to mockmvc | c8aa48faa9a4a3aae642d02850ee0bf6b5d4071c | <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java
<ide> public MockHttpServletRequestBuilder param(String name, String... values) {
<ide> return this;
<ide> }
<ide>
<add> /**
<add> * Add request parameters to the {@link MockHttpServletRequest} for example
<add> * such as when testing a form submission. If called more than once, the new
<add> * values are added.
<add> * @param params the parameters to add
<add> */
<add> public MockHttpServletRequestBuilder params(MultiValueMap<String, String> params) {
<add> for (String name : params.keySet()) {
<add> for (String value : params.get(name)) {
<add> this.parameters.add(name, value);
<add> }
<add> }
<add> return this;
<add> }
<add>
<ide> /**
<ide> * Add a header to the request. Values are always added.
<ide> * @param name the header name
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java
<ide> import org.springframework.mock.web.MockHttpSession;
<ide> import org.springframework.mock.web.MockServletContext;
<ide> import org.springframework.util.FileCopyUtils;
<add>import org.springframework.util.LinkedMultiValueMap;
<add>import org.springframework.util.MultiValueMap;
<ide> import org.springframework.web.servlet.FlashMap;
<ide> import org.springframework.web.servlet.support.SessionFlashMapManager;
<ide>
<ide> public void requestParameterFromQueryNull() {
<ide> assertEquals("foo", request.getQueryString());
<ide> }
<ide>
<add> // SPR-13801
<add>
<add> @Test
<add> public void requestParameterFromMultiValueMap() throws Exception {
<add> MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
<add> params.add("foo", "bar");
<add> params.add("foo", "baz");
<add> this.builder = new MockHttpServletRequestBuilder(HttpMethod.POST, "/foo");
<add> this.builder.params(params);
<add>
<add> MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
<add>
<add> assertArrayEquals(new String[] {"bar", "baz"}, request.getParameterMap().get("foo"));
<add> }
<add>
<ide> @Test
<ide> public void acceptHeader() {
<ide> this.builder.accept(MediaType.TEXT_HTML, MediaType.APPLICATION_XML); | 2 |
Javascript | Javascript | remove unused variable | 34d8830064d1ffc731eeb80fdabd25b82b69500e | <ide><path>packages/ember-runtime/lib/controllers/array_controller.js
<ide> Ember.ArrayController = Ember.ArrayProxy.extend(Ember.ControllerMixin,
<ide> var container = get(this, 'container'),
<ide> subControllers = get(this, '_subControllers'),
<ide> subController = subControllers[idx],
<del> factory, fullName;
<add> fullName;
<ide>
<ide> if (subController) { return subController; }
<ide> | 1 |
Ruby | Ruby | detect versions with final/full suffix | 8b55f8f9a44a6f7acc0bfda6ee1708566b1f461e | <ide><path>Library/Homebrew/test/version_spec.rb
<ide> .to be_detected_from("https://ftpmirror.gnu.org/libidn/libidn-1.29-win64.zip")
<ide> end
<ide>
<add> specify "breseq version style" do
<add> expect(described_class.create("0.35.1"))
<add> .to be_detected_from(
<add> "https://github.com/barricklab/breseq" \
<add> "/releases/download/v0.35.1/breseq-0.35.1.Source.tar.gz",
<add> )
<add> end
<add>
<add> specify "wildfly version style" do
<add> expect(described_class.create("20.0.1"))
<add> .to be_detected_from("https://download.jboss.org/wildfly/20.0.1.Final/wildfly-20.0.1.Final.tar.gz")
<add> end
<add>
<add> specify "trinity version style" do
<add> expect(described_class.create("2.10.0"))
<add> .to be_detected_from(
<add> "https://github.com/trinityrnaseq/trinityrnaseq" \
<add> "/releases/download/v2.10.0/trinityrnaseq-v2.10.0.FULL.tar.gz",
<add> )
<add> end
<add>
<ide> specify "with arch" do
<ide> expect(described_class.create("4.0.18-1"))
<ide> .to be_detected_from("https://ftpmirror.gnu.org/mtools/mtools-4.0.18-1.i686.rpm")
<ide><path>Library/Homebrew/version.rb
<ide> def self._parse(spec)
<ide> # e.g. foobar-4.5.1-1
<ide> # e.g. unrtf_0.20.4-1
<ide> # e.g. ruby-1.9.1-p243
<del> m = /[-_]((?:\d+\.)*\d+\.\d+-(?:p|rc|RC)?\d+)(?:[-._](?:bin|dist|stable|src|sources))?$/.match(stem)
<add> m = /[-_]((?:\d+\.)*\d+\.\d+-(?:p|rc|RC)?\d+)(?:[-._](?i:bin|dist|stable|src|sources?|final|full))?$/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<ide> # URL with no extension
<ide> def self._parse(spec)
<ide> return m.captures.first unless m.nil?
<ide>
<ide> # e.g. foobar-4.5.0-bin
<del> m = /-((?:\d+\.)+\d+[abc]?)[-._](?:bin|dist|stable|src|sources?)$/.match(stem)
<add> m = /[-vV]((?:\d+\.)+\d+[abc]?)[-._](?i:bin|dist|stable|src|sources?|final|full)$/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<ide> # dash version style | 2 |
Text | Text | add v3.28.6 to changelog.md | 96143deb03ba5dd0c7a1b893f2128889beed6b0c | <ide><path>CHANGELOG.md
<ide> - [#19695](https://github.com/emberjs/ember.js/pull/19695) [CLEANUP] Remove {{partial}}
<ide> - [#19691](https://github.com/emberjs/ember.js/pull/19691) Add build assertion against `{{outlet named}}`
<ide>
<add>## v3.28.6 (November 4, 2021)
<add>
<add>- [#19683](https://github.com/emberjs/ember.js/pull/19683) Ensure super.willDestroy is called correctly in Router's willDestroy
<add>
<ide> ## v3.28.5 (November 3, 2021)
<ide>
<ide> - [#19820](https://github.com/emberjs/ember.js/pull/19820) Fix memory leak when looking up non-instantiable objects from the owner
<ide>
<add>## v3.28.4 (October 22, 2021)
<add>
<add>- [#19798](https://github.com/emberjs/ember.js/pull/19798) More fixes for errors while precompiling inline templates (introduced in 3.28.2)
<add>- [glimmerjs/glimmer-vm@0.80.3](https://github.com/glimmerjs/glimmer-vm/releases/tag/v0.80.3) Improve template compilation speed regression
<add>
<ide> ## v3.28.3 (October 22, 2021)
<ide>
<ide> - [#19799](https://github.com/emberjs/ember.js/pull/19799) / [glimmerjs/glimmer-vm#1354](https://github.com/glimmerjs/glimmer-vm/pull/1354) Fixes for errors while precompiling inline templates (introduced in 3.28.2) | 1 |
PHP | PHP | fix issues with sqlite multi inserts | c3f7ebd892f1dc4d53da69736701927f1862e465 | <ide><path>lib/Cake/Database/Dialect/SqliteDialectTrait.php
<ide> protected function _insertQueryTranslator($query) {
<ide> if ($fillLength > 0) {
<ide> $val = array_merge($val, array_fill(0, $fillLength, null));
<ide> }
<del> // TODO this doesn't work all columns are inserted as null.
<ide> $val = array_map(function($val) {
<ide> return $val instanceof ExpressionInterface ? $val : '?';
<ide> }, $val);
<ide> protected function _insertQueryTranslator($query) {
<ide> $newQuery->union($q->select($select), true);
<ide> }
<ide>
<del> $v->values([$newQuery]);
<del> $query->values($v);
<add> $v->values($values);
<ide> return $query;
<ide> }
<ide> | 1 |
Text | Text | update crypto.createsecretkey accepted types | fb88257b72bb6aba8f7c30cf78917299647697fe | <ide><path>doc/api/crypto.md
<ide> and it will be impossible to extract the private key from the returned object.
<ide> added: v11.6.0
<ide> -->
<ide>
<del>* `key` {Buffer}
<add>* `key` {Buffer | TypedArray | DataView}
<ide> * Returns: {KeyObject}
<ide>
<ide> Creates and returns a new key object containing a secret key for symmetric | 1 |
Javascript | Javascript | change colour => color | d2d34183249121d64c00a4bd2a646576789e37bf | <ide><path>editor/js/libs/tern-threejs/threejs.js
<ide> },
<ide> "material": {
<ide> "!type": "+THREE.Material",
<del> "!doc": "An instance of [page:Material], defining the object's appearance. Default is a [page:MeshBasicMaterial] with wireframe mode enabled and randomised colour."
<add> "!doc": "An instance of [page:Material], defining the object's appearance. Default is a [page:MeshBasicMaterial] with wireframe mode enabled and randomised color."
<ide> },
<ide> "getMorphTargetIndexByName": {
<ide> "!type": "fn(name: string) -> number",
<ide> },
<ide> "material": {
<ide> "!type": "+THREE.Material",
<del> "!doc": "An instance of [page:Material], defining the object's appearance. Default is a [page:PointCloudMaterial] with randomised colour."
<add> "!doc": "An instance of [page:Material], defining the object's appearance. Default is a [page:PointCloudMaterial] with randomised color."
<ide> },
<ide> "clone": {
<ide> "!type": "fn() -> +THREE.PointCloud", | 1 |
PHP | PHP | catch typeerror along with exception | 571401aee9b5d6b9dc3329d44dd0571d9ebbff1e | <ide><path>src/View/SerializedView.php
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\View\Exception\SerializationFailureException;
<ide> use Exception;
<add>use TypeError;
<ide>
<ide> /**
<ide> * Parent class for view classes generating serialized outputs like JsonView and XmlView.
<ide> function ($v) {
<ide> if ($serialize !== false) {
<ide> try {
<ide> return $this->_serialize($serialize);
<del> } catch (Exception $e) {
<add> } catch (Exception | TypeError $e) {
<ide> throw new SerializationFailureException(
<ide> 'Serialization of View data failed.',
<ide> null, | 1 |
Python | Python | add warning message for redundant outputs | bfa38fb747904d20e4fb73aa233c88bff2151916 | <ide><path>keras/engine/topology.py
<ide> def __init__(self, inputs, outputs, name=None):
<ide> self.outputs = [outputs]
<ide>
<ide> # Check for redundancy in inputs.
<del> inputs_set = set(self.inputs)
<del> if len(inputs_set) != len(self.inputs):
<add> if len(set(self.inputs)) != len(self.inputs):
<ide> raise ValueError('The list of inputs passed to the model '
<ide> 'is redundant. '
<ide> 'All inputs should only appear once.'
<ide> ' Found: ' + str(self.inputs))
<ide>
<add> # Check for redundancy in outputs.
<add> if len(set(self.outputs)) != len(self.outputs):
<add> warnings.warn('The list of outputs passed to the model '
<add> 'is redundant. '
<add> 'All outputs should only appear once.'
<add> ' Found: ' + str(self.outputs))
<add>
<ide> # List of initial layers (1 to 1 mapping with self.inputs,
<ide> # hence the same layer might appear twice)
<ide> self.input_layers = []
<ide><path>tests/keras/engine/test_topology.py
<ide> def test_recursion():
<ide> with pytest.raises(Exception) as e:
<ide> Model([j], [m, n])
<ide>
<del> # redudant outputs
<add> # redundant outputs
<ide> j = Input(shape=(32,), name='input_j')
<ide> k = Input(shape=(32,), name='input_k')
<ide> m, n = model([j, k])
<del> # this should work lol
<del> # TODO: raise a warning
<add> # this should work with a warning
<ide> Model([j, k], [m, n, n])
<ide>
<ide> # redundant inputs | 2 |
Text | Text | add figma, sketch and xd to the list of tools | 374df386fa1bde1046b02d58f7bb8befadce6fe7 | <ide><path>guide/english/visual-design/wireframing/index.md
<ide> title: Wireframing
<ide> <li>
<ide> <a href="http://pencil.evolus.vn/Default.html/" target="blank">Pencil</a>
<ide> </li>
<add> <li>
<add> <a href="https://www.figma.com/features/" target="blank">Figma</a>
<add> </li>
<add> <li>
<add> <a href="https://www.sketchapp.com/" target="blank">Sketch</a>
<add> </li>
<add> <li>
<add> <a href="https://www.adobe.com/ca/products/xd.html" target="blank">Adobe XD</a>
<add> </li>
<ide> </ul> | 1 |
PHP | PHP | replace more static return types | 45dc7bd26cf388e203b88d07f15093289b6188e1 | <ide><path>src/Illuminate/Database/Eloquent/Collection.php
<ide> public function contains($key)
<ide> * Fetch a nested element of the collection.
<ide> *
<ide> * @param string $key
<del> * @return \Illuminate\Database\Eloquent\Collection
<add> * @return static
<ide> */
<ide> public function fetch($key)
<ide> {
<ide> public function modelKeys()
<ide> * Merge the collection with the given items.
<ide> *
<ide> * @param \ArrayAccess|array $items
<del> * @return \Illuminate\Database\Eloquent\Collection
<add> * @return static
<ide> */
<ide> public function merge($items)
<ide> {
<ide> public function merge($items)
<ide> * Diff the collection with the given items.
<ide> *
<ide> * @param \ArrayAccess|array $items
<del> * @return \Illuminate\Database\Eloquent\Collection
<add> * @return static
<ide> */
<ide> public function diff($items)
<ide> {
<ide> public function diff($items)
<ide> * Intersect the collection with the given items.
<ide> *
<ide> * @param \ArrayAccess|array $items
<del> * @return \Illuminate\Database\Eloquent\Collection
<add> * @return static
<ide> */
<ide> public function intersect($items)
<ide> {
<ide> public function intersect($items)
<ide> /**
<ide> * Return only unique items from the collection.
<ide> *
<del> * @return \Illuminate\Database\Eloquent\Collection
<add> * @return static
<ide> */
<ide> public function unique()
<ide> {
<ide> public function unique()
<ide> * Returns only the models from the collection with the specified keys.
<ide> *
<ide> * @param mixed $keys
<del> * @return \Illuminate\Database\Eloquent\Collection
<add> * @return static
<ide> */
<ide> public function only($keys)
<ide> {
<ide> public function only($keys)
<ide> * Returns all models in the collection except the models with specified keys.
<ide> *
<ide> * @param mixed $keys
<del> * @return \Illuminate\Database\Eloquent\Collection
<add> * @return static
<ide> */
<ide> public function except($keys)
<ide> {
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> protected function fillableFromArray(array $attributes)
<ide> *
<ide> * @param array $attributes
<ide> * @param bool $exists
<del> * @return \Illuminate\Database\Eloquent\Model|static
<add> * @return static
<ide> */
<ide> public function newInstance($attributes = array(), $exists = false)
<ide> {
<ide> public function newInstance($attributes = array(), $exists = false)
<ide> * Create a new model instance that is existing.
<ide> *
<ide> * @param array $attributes
<del> * @return \Illuminate\Database\Eloquent\Model|static
<add> * @return static
<ide> */
<ide> public function newFromBuilder($attributes = array())
<ide> {
<ide> public static function hydrateRaw($query, $bindings = array(), $connection = nul
<ide> * Save a new model and return the instance.
<ide> *
<ide> * @param array $attributes
<del> * @return \Illuminate\Database\Eloquent\Model|static
<add> * @return static
<ide> */
<ide> public static function create(array $attributes)
<ide> {
<ide> public static function create(array $attributes)
<ide> * Get the first record matching the attributes or create it.
<ide> *
<ide> * @param array $attributes
<del> * @return \Illuminate\Database\Eloquent\Model
<add> * @return static
<ide> */
<ide> public static function firstOrCreate(array $attributes)
<ide> {
<ide> public static function firstOrCreate(array $attributes)
<ide> * Get the first record matching the attributes or instantiate it.
<ide> *
<ide> * @param array $attributes
<del> * @return \Illuminate\Database\Eloquent\Model
<add> * @return static
<ide> */
<ide> public static function firstOrNew(array $attributes)
<ide> {
<ide> public static function firstOrNew(array $attributes)
<ide> *
<ide> * @param array $attributes
<ide> * @param array $values
<del> * @return \Illuminate\Database\Eloquent\Model
<add> * @return static
<ide> */
<ide> public static function updateOrCreate(array $attributes, array $values = array())
<ide> {
<ide> public static function updateOrCreate(array $attributes, array $values = array()
<ide> * Get the first model for the given attributes.
<ide> *
<ide> * @param array $attributes
<del> * @return \Illuminate\Database\Eloquent\Model|null
<add> * @return static|null
<ide> */
<ide> protected static function firstByAttributes($attributes)
<ide> {
<ide> public static function all($columns = array('*'))
<ide> *
<ide> * @param mixed $id
<ide> * @param array $columns
<del> * @return \Illuminate\Database\Eloquent\Model|Collection|static
<add> * @return \Illuminate\Support\Collection|static
<ide> */
<ide> public static function find($id, $columns = array('*'))
<ide> {
<ide> public static function find($id, $columns = array('*'))
<ide> *
<ide> * @param mixed $id
<ide> * @param array $columns
<del> * @return \Illuminate\Database\Eloquent\Model|Collection|static
<add> * @return \Illuminate\Support\Collection|static
<ide> */
<ide> public static function findOrNew($id, $columns = array('*'))
<ide> {
<ide> public static function findOrNew($id, $columns = array('*'))
<ide> *
<ide> * @param mixed $id
<ide> * @param array $columns
<del> * @return \Illuminate\Database\Eloquent\Model|Collection|static
<add> * @return \Illuminate\Support\Collection|static
<ide> *
<ide> * @throws ModelNotFoundException
<ide> */
<ide><path>src/Illuminate/Support/Collection.php
<ide> public function __construct(array $items = array())
<ide> * Create a new collection instance if the value isn't one already.
<ide> *
<ide> * @param mixed $items
<del> * @return \Illuminate\Support\Collection
<add> * @return static
<ide> */
<ide> public static function make($items)
<ide> {
<ide> public function all()
<ide> /**
<ide> * Collapse the collection items into a single array.
<ide> *
<del> * @return \Illuminate\Support\Collection
<add> * @return static
<ide> */
<ide> public function collapse()
<ide> {
<ide> public function contains($value)
<ide> * Diff the collection with the given items.
<ide> *
<ide> * @param \Illuminate\Support\Collection|\Illuminate\Support\Contracts\ArrayableInterface|array $items
<del> * @return \Illuminate\Support\Collection
<add> * @return static
<ide> */
<ide> public function diff($items)
<ide> {
<ide> public function reduce(callable $callback, $initial = null)
<ide> * Create a colleciton of all elements that do not pass a given truth test.
<ide> *
<ide> * @param \Closure|mixed $callback
<del> * @return \Illuminate\Support\Collection
<add> * @return static
<ide> */
<ide> public function reject($callback)
<ide> { | 3 |
Ruby | Ruby | fix bug with typemap default values | d30c85cebd702aca01f52b60f56613c4e1434244 | <ide><path>activerecord/lib/active_record/type/type_map.rb
<ide> def alias_type(key, target_key)
<ide> end
<ide>
<ide> protected
<del> def perform_fetch(lookup_key)
<add> def perform_fetch(lookup_key, &block)
<ide> matching_pair = @mapping.reverse_each.detect do |key, _|
<ide> key === lookup_key
<ide> end
<ide>
<ide> if matching_pair
<ide> matching_pair.last.call(lookup_key)
<ide> elsif @parent
<del> @parent.perform_fetch(lookup_key)
<add> @parent.perform_fetch(lookup_key, &block)
<ide> else
<ide> yield lookup_key
<ide> end
<ide><path>activerecord/test/cases/type/type_map_test.rb
<ide> def test_parent_fallback
<ide> assert_equal boolean, mapping.lookup("boolean")
<ide> end
<ide>
<add> def test_parent_fallback_for_default_type
<add> parent = klass.new
<add> mapping = klass.new(parent)
<add>
<add> assert_kind_of Value, mapping.lookup(:undefined)
<add> end
<add>
<ide> private
<ide> def klass
<ide> TypeMap | 2 |
Mixed | Go | add support for metrics plugins | 0e8e8f0f318656be80e34db9b5e390ffeef3fd0d | <ide><path>daemon/daemon.go
<ide> type Daemon struct {
<ide> defaultIsolation containertypes.Isolation // Default isolation mode on Windows
<ide> clusterProvider cluster.Provider
<ide> cluster Cluster
<add> metricsPluginListener net.Listener
<ide>
<ide> machineMemory uint64
<ide>
<ide> func NewDaemon(config *config.Config, registryService registry.Service, containe
<ide> d.PluginStore = pluginStore
<ide> logger.RegisterPluginGetter(d.PluginStore)
<ide>
<add> metricsSockPath, err := d.listenMetricsSock()
<add> if err != nil {
<add> return nil, err
<add> }
<add> registerMetricsPluginCallback(d.PluginStore, metricsSockPath)
<add>
<ide> // Plugin system initialization should happen before restore. Do not change order.
<ide> d.pluginManager, err = plugin.NewManager(plugin.ManagerConfig{
<ide> Root: filepath.Join(config.Root, "plugins"),
<ide> func (daemon *Daemon) Shutdown() error {
<ide> if daemon.configStore.LiveRestoreEnabled && daemon.containers != nil {
<ide> // check if there are any running containers, if none we should do some cleanup
<ide> if ls, err := daemon.Containers(&types.ContainerListOptions{}); len(ls) != 0 || err != nil {
<add> // metrics plugins still need some cleanup
<add> daemon.cleanupMetricsPlugins()
<ide> return nil
<ide> }
<ide> }
<ide> func (daemon *Daemon) Shutdown() error {
<ide> daemon.DaemonLeavesCluster()
<ide> }
<ide>
<add> daemon.cleanupMetricsPlugins()
<add>
<ide> // Shutdown plugins after containers and layerstore. Don't change the order.
<ide> daemon.pluginShutdown()
<ide>
<ide><path>daemon/metrics.go
<ide> package daemon
<ide>
<ide> import (
<add> "path/filepath"
<ide> "sync"
<ide>
<add> "github.com/Sirupsen/logrus"
<add> "github.com/docker/docker/pkg/mount"
<add> "github.com/docker/docker/pkg/plugingetter"
<ide> "github.com/docker/go-metrics"
<add> "github.com/pkg/errors"
<ide> "github.com/prometheus/client_golang/prometheus"
<ide> )
<ide>
<add>const metricsPluginType = "MetricsCollector"
<add>
<ide> var (
<ide> containerActions metrics.LabeledTimer
<ide> containerStates metrics.LabeledGauge
<ide> func (ctr *stateCounter) Collect(ch chan<- prometheus.Metric) {
<ide> ch <- prometheus.MustNewConstMetric(ctr.desc, prometheus.GaugeValue, float64(paused), "paused")
<ide> ch <- prometheus.MustNewConstMetric(ctr.desc, prometheus.GaugeValue, float64(stopped), "stopped")
<ide> }
<add>
<add>func (d *Daemon) cleanupMetricsPlugins() {
<add> ls := d.PluginStore.GetAllManagedPluginsByCap(metricsPluginType)
<add> var wg sync.WaitGroup
<add> wg.Add(len(ls))
<add>
<add> for _, p := range ls {
<add> go func() {
<add> defer wg.Done()
<add> pluginStopMetricsCollection(p)
<add> }()
<add> }
<add> wg.Wait()
<add>
<add> if d.metricsPluginListener != nil {
<add> d.metricsPluginListener.Close()
<add> }
<add>}
<add>
<add>type metricsPlugin struct {
<add> plugingetter.CompatPlugin
<add>}
<add>
<add>func (p metricsPlugin) sock() string {
<add> return "metrics.sock"
<add>}
<add>
<add>func (p metricsPlugin) sockBase() string {
<add> return filepath.Join(p.BasePath(), "run", "docker")
<add>}
<add>
<add>func pluginStartMetricsCollection(p plugingetter.CompatPlugin) error {
<add> type metricsPluginResponse struct {
<add> Err string
<add> }
<add> var res metricsPluginResponse
<add> if err := p.Client().Call(metricsPluginType+".StartMetrics", nil, &res); err != nil {
<add> return errors.Wrap(err, "could not start metrics plugin")
<add> }
<add> if res.Err != "" {
<add> return errors.New(res.Err)
<add> }
<add> return nil
<add>}
<add>
<add>func pluginStopMetricsCollection(p plugingetter.CompatPlugin) {
<add> if err := p.Client().Call(metricsPluginType+".StopMetrics", nil, nil); err != nil {
<add> logrus.WithError(err).WithField("name", p.Name()).Error("error stopping metrics collector")
<add> }
<add>
<add> mp := metricsPlugin{p}
<add> sockPath := filepath.Join(mp.sockBase(), mp.sock())
<add> if err := mount.Unmount(sockPath); err != nil {
<add> if mounted, _ := mount.Mounted(sockPath); mounted {
<add> logrus.WithError(err).WithField("name", p.Name()).WithField("socket", sockPath).Error("error unmounting metrics socket for plugin")
<add> }
<add> }
<add> return
<add>}
<ide><path>daemon/metrics_unix.go
<add>// +build !windows
<add>
<add>package daemon
<add>
<add>import (
<add> "net"
<add> "net/http"
<add> "os"
<add> "path/filepath"
<add> "syscall"
<add>
<add> "github.com/Sirupsen/logrus"
<add> "github.com/docker/docker/pkg/mount"
<add> "github.com/docker/docker/pkg/plugingetter"
<add> "github.com/docker/docker/pkg/plugins"
<add> metrics "github.com/docker/go-metrics"
<add> "github.com/pkg/errors"
<add>)
<add>
<add>func (daemon *Daemon) listenMetricsSock() (string, error) {
<add> path := filepath.Join(daemon.configStore.ExecRoot, "metrics.sock")
<add> syscall.Unlink(path)
<add> l, err := net.Listen("unix", path)
<add> if err != nil {
<add> return "", errors.Wrap(err, "error setting up metrics plugin listener")
<add> }
<add>
<add> mux := http.NewServeMux()
<add> mux.Handle("/metrics", metrics.Handler())
<add> go func() {
<add> http.Serve(l, mux)
<add> }()
<add> daemon.metricsPluginListener = l
<add> return path, nil
<add>}
<add>
<add>func registerMetricsPluginCallback(getter plugingetter.PluginGetter, sockPath string) {
<add> getter.Handle(metricsPluginType, func(name string, client *plugins.Client) {
<add> // Use lookup since nothing in the system can really reference it, no need
<add> // to protect against removal
<add> p, err := getter.Get(name, metricsPluginType, plugingetter.Lookup)
<add> if err != nil {
<add> return
<add> }
<add>
<add> mp := metricsPlugin{p}
<add> sockBase := mp.sockBase()
<add> if err := os.MkdirAll(sockBase, 0755); err != nil {
<add> logrus.WithError(err).WithField("name", name).WithField("path", sockBase).Error("error creating metrics plugin base path")
<add> return
<add> }
<add>
<add> defer func() {
<add> if err != nil {
<add> os.RemoveAll(sockBase)
<add> }
<add> }()
<add>
<add> pluginSockPath := filepath.Join(sockBase, mp.sock())
<add> _, err = os.Stat(pluginSockPath)
<add> if err == nil {
<add> mount.Unmount(pluginSockPath)
<add> } else {
<add> logrus.WithField("path", pluginSockPath).Debugf("creating plugin socket")
<add> f, err := os.OpenFile(pluginSockPath, os.O_CREATE, 0600)
<add> if err != nil {
<add> return
<add> }
<add> f.Close()
<add> }
<add>
<add> if err := mount.Mount(sockPath, pluginSockPath, "none", "bind,ro"); err != nil {
<add> logrus.WithError(err).WithField("name", name).Error("could not mount metrics socket to plugin")
<add> return
<add> }
<add>
<add> if err := pluginStartMetricsCollection(p); err != nil {
<add> if err := mount.Unmount(pluginSockPath); err != nil {
<add> if mounted, _ := mount.Mounted(pluginSockPath); mounted {
<add> logrus.WithError(err).WithField("sock_path", pluginSockPath).Error("error unmounting metrics socket from plugin during cleanup")
<add> }
<add> }
<add> logrus.WithError(err).WithField("name", name).Error("error while initializing metrics plugin")
<add> }
<add> })
<add>}
<ide><path>daemon/metrics_unsupported.go
<add>// +build windows
<add>
<add>package daemon
<add>
<add>import "github.com/docker/docker/pkg/plugingetter"
<add>
<add>func registerMetricsPluginCallback(getter plugingetter.PluginGetter, sockPath string) {
<add>}
<add>
<add>func (daemon *Daemon) listenMetricsSock() (string, error) {
<add> return "", nil
<add>}
<ide><path>docs/extend/config.md
<ide> Config provides the base accessible fields for working with V0 plugin format
<ide>
<ide> - **docker.logdriver/1.0**
<ide>
<add> - **docker.metricscollector/1.0**
<add>
<ide> - **`socket`** *string*
<ide>
<ide> socket is the name of the socket the engine should use to communicate with the plugins.
<ide><path>docs/extend/plugins_metrics.md
<add>---
<add>title: "Docker metrics collector plugins"
<add>description: "Metrics plugins."
<add>keywords: "Examples, Usage, plugins, docker, documentation, user guide, metrics"
<add>---
<add>
<add><!-- This file is maintained within the docker/docker Github
<add> repository at https://github.com/docker/docker/. Make all
<add> pull requests against that repo. If you see this file in
<add> another repository, consider it read-only there, as it will
<add> periodically be overwritten by the definitive file. Pull
<add> requests which include edits to this file in other repositories
<add> will be rejected.
<add>-->
<add>
<add># Metrics Collector Plugins
<add>
<add>Docker exposes internal metrics based on the prometheus format. Metrics plugins
<add>enable accessing these metrics in a consistent way by providing a Unix
<add>socket at a predefined path where the plugin can scrape the metrics.
<add>
<add>> **Note**: that while the plugin interface for metrics is non-experimental, the naming
<add>of the metrics and metric labels is still considered experimental and may change
<add>in a future version.
<add>
<add>## Creating a metrics plugin
<add>
<add>You must currently set `PropagatedMount` in the plugin `config.json` to
<add>`/run/docker`. This allows the plugin to receive updated mounts
<add>(the bind-mounted socket) from Docker after the plugin is already configured.
<add>
<add>## MetricsCollector protocol
<add>
<add>Metrics plugins must register as implementing the`MetricsCollector` interface
<add>in `config.json`.
<add>
<add>On Unix platforms, the socket is located at `/run/docker/metrics.sock` in the
<add>plugin's rootfs.
<add>
<add>`MetricsCollector` must implement two endpoints:
<add>
<add>### `MetricsCollector.StartMetrics`
<add>
<add>Signals to the plugin that the metrics socket is now available for scraping
<add>
<add>**Request**
<add>```json
<add>{}
<add>```
<add>
<add>The request has no playload.
<add>
<add>**Response**
<add>```json
<add>{
<add> "Err": ""
<add>}
<add>```
<add>
<add>If an error occurred during this request, add an error message to the `Err` field
<add>in the response. If no error then you can either send an empty response (`{}`)
<add>or an empty value for the `Err` field. Errors will only be logged.
<add>
<add>### `MetricsCollector.StopMetrics`
<add>
<add>Signals to the plugin that the metrics socket is no longer available.
<add>This may happen when the daemon is shutting down.
<add>
<add>**Request**
<add>```json
<add>{}
<add>```
<add>
<add>The request has no playload.
<add>
<add>**Response**
<add>```json
<add>{
<add> "Err": ""
<add>}
<add>```
<add>
<add>If an error occurred during this request, add an error message to the `Err` field
<add>in the response. If no error then you can either send an empty response (`{}`)
<add>or an empty value for the `Err` field. Errors will only be logged.
<ide><path>docs/reference/commandline/plugin_ls.md
<ide> than one filter, then pass multiple flags (e.g., `--filter "foo=bar" --filter "b
<ide> The currently supported filters are:
<ide>
<ide> * enabled (boolean - true or false, 0 or 1)
<del>* capability (string - currently `volumedriver`, `networkdriver`, `ipamdriver`, or `authz`)
<add>* capability (string - currently `volumedriver`, `networkdriver`, `ipamdriver`, `logdriver`, `metricscollector`, or `authz`)
<ide>
<ide> #### enabled
<ide>
<ide> The `enabled` filter matches on plugins enabled or disabled.
<ide>
<ide> The `capability` filter matches on plugin capabilities. One plugin
<ide> might have multiple capabilities. Currently `volumedriver`, `networkdriver`,
<del>`ipamdriver`, and `authz` are supported capabilities.
<add>`ipamdriver`, `logdriver`, `metricscollector`, and `authz` are supported capabilities.
<ide>
<ide> ```bash
<ide> $ docker plugin install --disable tiborvass/no-remove
<ide><path>integration-cli/docker_cli_plugins_test.go
<ide> package main
<ide> import (
<ide> "fmt"
<ide> "io/ioutil"
<add> "net/http"
<ide> "os"
<ide> "path/filepath"
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<ide> "github.com/docker/docker/integration-cli/cli"
<add> "github.com/docker/docker/integration-cli/daemon"
<ide> icmd "github.com/docker/docker/pkg/testutil/cmd"
<ide> "github.com/go-check/check"
<ide> )
<ide> func (s *DockerSuite) TestPluginUpgrade(c *check.C) {
<ide> dockerCmd(c, "volume", "inspect", "bananas")
<ide> dockerCmd(c, "run", "--rm", "-v", "bananas:/apple", "busybox", "sh", "-c", "ls -lh /apple/core")
<ide> }
<add>
<add>func (s *DockerSuite) TestPluginMetricsCollector(c *check.C) {
<add> testRequires(c, DaemonIsLinux, Network, SameHostDaemon, IsAmd64)
<add> d := daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{})
<add> d.Start(c)
<add> defer d.Stop(c)
<add>
<add> name := "cpuguy83/docker-metrics-plugin-test:latest"
<add> r := cli.Docker(cli.Args("plugin", "install", "--grant-all-permissions", name), cli.Daemon(d))
<add> c.Assert(r.Error, checker.IsNil, check.Commentf(r.Combined()))
<add>
<add> // plugin lisens on localhost:19393 and proxies the metrics
<add> resp, err := http.Get("http://localhost:19393/metrics")
<add> c.Assert(err, checker.IsNil)
<add> defer resp.Body.Close()
<add>
<add> b, err := ioutil.ReadAll(resp.Body)
<add> c.Assert(err, checker.IsNil)
<add> // check that a known metric is there... don't epect this metric to change over time.. probably safe
<add> c.Assert(string(b), checker.Contains, "container_actions")
<add>} | 8 |
Javascript | Javascript | update landing [ci skip] | 38037d68169e07ffd0510818320da4cefb8dd3cc | <ide><path>website/src/widgets/landing.js
<ide> const Landing = ({ data }) => {
<ide> </LandingGrid>
<ide>
<ide> <LandingBannerGrid>
<add> <LandingBanner
<add> title="Prodigy: Radically efficient machine teaching"
<add> label="From the makers of spaCy"
<add> to="https://prodi.gy"
<add> button="Try it out"
<add> background="#eee"
<add> color="#252a33"
<add> small
<add> >
<add> Prodigy is an <strong>annotation tool</strong> so efficient that data scientists
<add> can do the annotation themselves, enabling a new level of rapid iteration.
<add> Whether you're working on entity recognition, intent detection or image
<add> classification, Prodigy can help you <strong>train and evaluate</strong> your
<add> models faster. Stream in your own examples or real-world data from live APIs,
<add> update your model in real-time and chain models together to build more complex
<add> systems.
<add> </LandingBanner>
<add>
<ide> <LandingBanner
<ide> title="spaCy IRL 2019: Two days of NLP"
<ide> label="Watch the videos"
<ide> const Landing = ({ data }) => {
<ide> research, development and applications, with keynotes by Sebastian Ruder
<ide> (DeepMind) and Yoav Goldberg (Allen AI).
<ide> </LandingBanner>
<del>
<del> <LandingBanner
<del> title="Prodigy: Radically efficient machine teaching"
<del> label="From the makers of spaCy"
<del> to="https://prodi.gy"
<del> button="Try it out"
<del> background="#eee"
<del> color="#252a33"
<del> small
<del> >
<del> Prodigy is an <strong>annotation tool</strong> so efficient that data scientists
<del> can do the annotation themselves, enabling a new level of rapid iteration.
<del> Whether you're working on entity recognition, intent detection or image
<del> classification, Prodigy can help you <strong>train and evaluate</strong> your
<del> models faster. Stream in your own examples or real-world data from live APIs,
<del> update your model in real-time and chain models together to build more complex
<del> systems.
<del> </LandingBanner>
<ide> </LandingBannerGrid>
<ide>
<ide> <LandingLogos title="spaCy is trusted by" logos={data.logosUsers}> | 1 |
Text | Text | update russian localization | c61c8c047455c5fe8aadf0d0e5ccf4a9c47420e3 | <ide><path>curriculum/challenges/russian/03-front-end-libraries/bootstrap/add-font-awesome-icons-to-all-of-our-buttons.russian.md
<ide> Font Awesome - это удобная библиотека иконок. Эти
<ide>
<ide> ## Instructions
<ide> <section id='instructions'>
<del>Use Font Awesome to add an <code>info-circle</code> icon to your info button and a <code>trash</code> icon to your delete button.
<add>Используйте Font Awesome чтобы добавить иконку <code>info-circle</code> к вашей info кнопке и иконку <code>trash</code> чтобы удалить вашу кнопку.
<ide>
<del><strong>Note:</strong> The <code>span</code> element is an acceptable alternative to the <code>i</code> element for the directions below.
<add><strong>Примечание:</strong> Элемент <code>span</code> является приемлемой альтернативой элементу <code>i</code> для приведенных ниже направлений.
<ide> </section>
<ide>
<ide> ## Tests | 1 |
Javascript | Javascript | remove unnecessary bind | d00d81edd7164e54bd0fd0d28bbaba2a19443150 | <ide><path>lib/internal/fs/promises.js
<ide> class FileHandle {
<ide> return writeFile(this, data, options);
<ide> }
<ide>
<del> close() {
<add> close = () => {
<ide> return this[kHandle].close();
<ide> }
<ide> }
<ide> async function lchmod(path, mode) {
<ide> throw new ERR_METHOD_NOT_IMPLEMENTED('lchmod()');
<ide>
<ide> const fd = await open(path, O_WRONLY | O_SYMLINK);
<del> return fchmod(fd, mode).finally(fd.close.bind(fd));
<add> return fchmod(fd, mode).finally(fd.close);
<ide> }
<ide>
<ide> async function lchown(path, uid, gid) {
<ide> async function writeFile(path, data, options) {
<ide> return writeFileHandle(path, data, options);
<ide>
<ide> const fd = await open(path, flag, options.mode);
<del> return writeFileHandle(fd, data, options).finally(fd.close.bind(fd));
<add> return writeFileHandle(fd, data, options).finally(fd.close);
<ide> }
<ide>
<ide> async function appendFile(path, data, options) {
<ide> async function readFile(path, options) {
<ide> return readFileHandle(path, options);
<ide>
<ide> const fd = await open(path, flag, 0o666);
<del> return readFileHandle(fd, options).finally(fd.close.bind(fd));
<add> return readFileHandle(fd, options).finally(fd.close);
<ide> }
<ide>
<ide> module.exports = {
<ide><path>lib/internal/fs/streams.js
<ide> WriteStream.prototype.close = function(cb) {
<ide> // If we are not autoClosing, we should call
<ide> // destroy on 'finish'.
<ide> if (!this.autoClose) {
<del> this.on('finish', this.destroy.bind(this));
<add> this.on('finish', this.destroy);
<ide> }
<ide>
<ide> // We use end() instead of destroy() because of | 2 |
Python | Python | remove duplicated tests | fb6d3928c847058301ff2365fae90916e8850640 | <ide><path>numpy/core/tests/test_numeric.py
<ide> def test_promote_types_strings(self, swap, string_dtype):
<ide> # Promote with object:
<ide> assert_equal(promote_types('O', S+'30'), np.dtype('O'))
<ide>
<del> @pytest.mark.parametrize(["dtype1", "dtype2"],
<del> [[np.dtype("V6"), np.dtype("V10")],
<del> [np.dtype([("name1", "i8")]), np.dtype([("name2", "i8")])],
<del> [np.dtype("i8,i8"), np.dtype("i4,i4")],
<del> ])
<del> def test_invalid_void_promotion(self, dtype1, dtype2):
<del> # Mainly test structured void promotion, which currently allows
<del> # byte-swapping, but nothing else:
<del> with pytest.raises(TypeError):
<del> np.promote_types(dtype1, dtype2)
<del>
<del> @pytest.mark.parametrize(["dtype1", "dtype2"],
<del> [[np.dtype("V10"), np.dtype("V10")],
<del> [np.dtype([("name1", "<i8")]), np.dtype([("name1", ">i8")])],
<del> [np.dtype("i8,i8"), np.dtype("i8,>i8")],
<del> ])
<del> def test_valid_void_promotion(self, dtype1, dtype2):
<del> assert np.promote_types(dtype1, dtype2) is dtype1
<del>
<ide> @pytest.mark.parametrize("dtype",
<ide> list(np.typecodes["All"]) +
<ide> ["i,i", "S3", "S100", "U3", "U100", rational]) | 1 |
Mixed | Ruby | drop mavericks support | b58fa4ebb1e6b918d8556cba629cb55b79d423f5 | <ide><path>Library/Homebrew/exceptions.rb
<ide> def initialize(inner)
<ide> set_backtrace inner["b"]
<ide> end
<ide> end
<add>
<add>class MacOSVersionError < RuntimeError
<add> attr_reader :version
<add>
<add> def initialize(version)
<add> @version = version
<add> super "unknown or unsupported macOS version: #{version.inspect}"
<add> end
<add>end
<ide><path>Library/Homebrew/extend/os/mac/formula_cellar_checks.rb
<ide> def check_shadowed_headers
<ide> end
<ide>
<ide> return if formula.name&.match?(Version.formula_optionally_versioned_regex(:php))
<del>
<del> return if MacOS.version < :mavericks && formula.name.start_with?("postgresql")
<del> return if MacOS.version < :yosemite && formula.name.start_with?("memcached")
<del>
<ide> return if formula.keg_only? || !formula.include.directory?
<ide>
<ide> files = relative_glob(formula.include, "**/*.h")
<ide><path>Library/Homebrew/extend/os/mac/utils/bottles.rb
<ide> def find_matching_tag(tag)
<ide> def find_older_compatible_tag(tag)
<ide> tag_version = begin
<ide> MacOS::Version.from_symbol(tag)
<del> rescue ArgumentError
<add> rescue MacOSVersionError
<ide> return
<ide> end
<ide>
<ide> keys.find do |key|
<ide> MacOS::Version.from_symbol(key) <= tag_version
<del> rescue ArgumentError
<add> rescue MacOSVersionError
<ide> false
<ide> end
<ide> end
<ide><path>Library/Homebrew/formula.rb
<ide> def mirror(val)
<ide> # prefix "/opt/homebrew" # Optional HOMEBREW_PREFIX in which the bottles were built.
<ide> # cellar "/opt/homebrew/Cellar" # Optional HOMEBREW_CELLAR in which the bottles were built.
<ide> # rebuild 1 # Making the old bottle outdated without bumping the version/revision of the formula.
<del> # sha256 "4355a46b19d348dc2f57c046f8ef63d4538ebb936000f3c9ee954a27460dd865" => :el_capitan
<del> # sha256 "53c234e5e8472b6ac51c1ae1cab3fe06fad053beb8ebfd8977b010655bfdd3c3" => :yosemite
<del> # sha256 "1121cfccd5913f0a63fec40a6ffd44ea64f9dc135c66634ba001d10bcf4302a2" => :mavericks
<add> # sha256 "ef65c759c5097a36323fa9c77756468649e8d1980a3a4e05695c05e39568967c" => :catalina
<add> # sha256 "28f4090610946a4eb207df102d841de23ced0d06ba31cb79e040d883906dcd4f" => :mojave
<add> # sha256 "91dd0caca9bd3f38c439d5a7b6f68440c4274945615fae035ff0a369264b8a2f" => :high_sierra
<ide> # end</pre>
<ide> #
<ide> # Only formulae where the upstream URL breaks or moves frequently, require compiling
<ide> def go_resource(name, &block)
<ide> # <pre># Optional and enforce that boost is built with `--with-c++11`.
<ide> # depends_on "boost" => [:optional, "with-c++11"]</pre>
<ide> # <pre># If a dependency is only needed in certain cases:
<del> # depends_on "sqlite" if MacOS.version == :mavericks
<add> # depends_on "sqlite" if MacOS.version == :catalina
<ide> # depends_on :xcode # If the formula really needs full Xcode.
<ide> # depends_on :macos => :mojave # Needs at least macOS Mojave (10.14).
<ide> # depends_on :x11 => :optional # X11/XQuartz components.
<ide><path>Library/Homebrew/os/mac/version.rb
<ide> class Version < ::Version
<ide> sierra: "10.12",
<ide> el_capitan: "10.11",
<ide> yosemite: "10.10",
<del> mavericks: "10.9",
<ide> }.freeze
<ide>
<ide> def self.from_symbol(sym)
<del> str = SYMBOLS.fetch(sym) do
<del> raise ArgumentError, "unknown version #{sym.inspect}"
<del> end
<add> str = SYMBOLS.fetch(sym) { raise MacOSVersionError, sym }
<ide> new(str)
<ide> end
<ide>
<ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def outdated?
<ide> end
<ide>
<ide> def detect_clang_version
<del> path = if MacOS.version >= :mavericks
<del> "#{PKG_PATH}/usr/bin/clang"
<del> else
<del> "/usr/bin/clang"
<del> end
<del>
<del> version_output = Utils.popen_read("#{path} --version")
<add> version_output = Utils.popen_read("#{PKG_PATH}/usr/bin/clang --version")
<ide> version_output[/clang-(\d+\.\d+\.\d+(\.\d+)?)/, 1]
<ide> end
<ide>
<ide><path>Library/Homebrew/requirements/macos_requirement.rb
<ide> class MacOSRequirement < Requirement
<ide> attr_reader :comparator, :version
<ide>
<ide> def initialize(tags = [], comparator: ">=")
<del> if comparator == "==" && tags.first.respond_to?(:map)
<del> @version = tags.shift.map { |s| MacOS::Version.from_symbol(s) }
<del> else
<del> @version = MacOS::Version.from_symbol(tags.shift) unless tags.empty?
<add> begin
<add> @version = if comparator == "==" && tags.first.respond_to?(:map)
<add> tags.shift.map { |s| MacOS::Version.from_symbol(s) }
<add> else
<add> MacOS::Version.from_symbol(tags.shift) unless tags.empty?
<add> end
<add> rescue MacOSVersionError => e
<add> raise if e.version != :mavericks
<add>
<add> odeprecated "depends_on :macos => :mavericks"
<ide> end
<ide>
<ide> @comparator = comparator
<ide><path>Library/Homebrew/software_spec.rb
<ide> def checksums
<ide> # Sort non-MacOS tags below MacOS tags.
<ide>
<ide> OS::Mac::Version.from_symbol tag
<del> rescue ArgumentError
<add> rescue MacOSVersionError
<ide> "0.#{tag}"
<ide> end
<ide> checksums = {}
<ide><path>Library/Homebrew/test/os/mac/software_spec_spec.rb
<ide> it "raises an error if passing invalid OS versions" do
<ide> expect {
<ide> spec.uses_from_macos("foo", since: :bar)
<del> }.to raise_error(ArgumentError, "unknown version :bar")
<add> }.to raise_error(MacOSVersionError, "unknown or unsupported macOS version: :bar")
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/os/mac/version_spec.rb
<ide> require "os/mac/version"
<ide>
<ide> describe OS::Mac::Version do
<del> subject { described_class.new("10.10") }
<add> subject { described_class.new("10.14") }
<ide>
<ide> specify "comparison with Symbol" do
<del> expect(subject).to be > :mavericks
<del> expect(subject).to be == :yosemite
<del> expect(subject).to be === :yosemite # rubocop:disable Style/CaseEquality
<del> expect(subject).to be < :el_capitan
<add> expect(subject).to be > :high_sierra
<add> expect(subject).to be == :mojave
<add> expect(subject).to be === :mojave # rubocop:disable Style/CaseEquality
<add> expect(subject).to be < :catalina
<ide> end
<ide>
<ide> specify "comparison with Fixnum" do
<ide> end
<ide>
<ide> specify "comparison with Float" do
<del> expect(subject).to be > 10.9
<del> expect(subject).to be < 10.11
<add> expect(subject).to be > 10.13
<add> expect(subject).to be < 10.15
<ide> end
<ide>
<ide> specify "comparison with String" do
<del> expect(subject).to be > "10.9"
<del> expect(subject).to be == "10.10"
<del> expect(subject).to be === "10.10" # rubocop:disable Style/CaseEquality
<del> expect(subject).to be < "10.11"
<add> expect(subject).to be > "10.3"
<add> expect(subject).to be == "10.14"
<add> expect(subject).to be === "10.14" # rubocop:disable Style/CaseEquality
<add> expect(subject).to be < "10.15"
<ide> end
<ide>
<ide> specify "comparison with Version" do
<del> expect(subject).to be > Version.create("10.9")
<del> expect(subject).to be == Version.create("10.10")
<del> expect(subject).to be === Version.create("10.10") # rubocop:disable Style/CaseEquality
<del> expect(subject).to be < Version.create("10.11")
<add> expect(subject).to be > Version.create("10.3")
<add> expect(subject).to be == Version.create("10.14")
<add> expect(subject).to be === Version.create("10.14") # rubocop:disable Style/CaseEquality
<add> expect(subject).to be < Version.create("10.15")
<ide> end
<ide>
<ide> specify "#from_symbol" do
<del> expect(described_class.from_symbol(:yosemite)).to eq(subject)
<add> expect(described_class.from_symbol(:mojave)).to eq(subject)
<ide> expect { described_class.from_symbol(:foo) }
<del> .to raise_error(ArgumentError)
<add> .to raise_error(MacOSVersionError, "unknown or unsupported macOS version: :foo")
<ide> end
<ide>
<ide> specify "#pretty_name" do
<ide><path>Library/Homebrew/test/requirements/macos_requirement_spec.rb
<ide> end
<ide>
<ide> it "supports maximum versions", :needs_macos do
<del> requirement = described_class.new([:mavericks], comparator: "<=")
<del> expect(requirement.satisfied?).to eq MacOS.version <= :mavericks
<add> requirement = described_class.new([:catalina], comparator: "<=")
<add> expect(requirement.satisfied?).to eq MacOS.version <= :catalina
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/invalid/invalid-depends-on-macos-conflicting-forms.rb
<del>cask 'invalid-depends-on-macos-conflicting-forms' do
<del> version '1.2.3'
<del> sha256 '67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94'
<add># frozen_string_literal: true
<add>
<add>cask "invalid-depends-on-macos-conflicting-forms" do
<add> version "1.2.3"
<add> sha256 "67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94"
<ide>
<ide> url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
<del> homepage 'https://brew.sh/invalid-depends-on-macos-conflicting-forms'
<add> homepage "https://brew.sh/invalid-depends-on-macos-conflicting-forms"
<ide>
<del> depends_on macos: :yosemite
<del> depends_on macos: '>= :mavericks'
<add> depends_on macos: :catalina
<add> depends_on macos: ">= :mojave"
<ide>
<del> app 'Caffeine.app'
<add> app "Caffeine.app"
<ide> end
<ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-depends-on-macos-array.rb
<del>cask 'with-depends-on-macos-array' do
<del> version '1.2.3'
<del> sha256 '67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94'
<add># frozen_string_literal: true
<add>
<add>cask "with-depends-on-macos-array" do
<add> version "1.2.3"
<add> sha256 "67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94"
<ide>
<ide> url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
<del> homepage 'https://brew.sh/with-depends-on-macos-array'
<add> homepage "https://brew.sh/with-depends-on-macos-array"
<ide>
<ide> # since all OS releases are included, this should always pass
<del> depends_on macos: [:mavericks, :sierra, MacOS.version.to_sym]
<add> depends_on macos: [:catalina, MacOS.version.to_sym]
<ide>
<del> app 'Caffeine.app'
<add> app "Caffeine.app"
<ide> end
<ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-depends-on-macos-comparison.rb
<del>cask 'with-depends-on-macos-comparison' do
<del> version '1.2.3'
<del> sha256 '67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94'
<add># frozen_string_literal: true
<add>
<add>cask "with-depends-on-macos-comparison" do
<add> version "1.2.3"
<add> sha256 "67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94"
<ide>
<ide> url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
<del> homepage 'https://brew.sh/with-depends-on-macos-comparison'
<add> homepage "https://brew.sh/with-depends-on-macos-comparison"
<ide>
<del> depends_on macos: '>= :mavericks'
<add> depends_on macos: ">= :catalina"
<ide>
<del> app 'Caffeine.app'
<add> app "Caffeine.app"
<ide> end
<ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-depends-on-macos-failure.rb
<ide> homepage 'https://brew.sh/with-depends-on-macos-failure'
<ide>
<ide> # guarantee a mismatched release
<del> depends_on macos: MacOS.version == :mavericks ? :sierra : :mavericks
<add> depends_on macos: MacOS.version == :catalina ? :mojave : :catalina
<ide>
<ide> app 'Caffeine.app'
<ide> end
<ide><path>Library/Homebrew/test/utils/bottles/bottles_spec.rb
<ide>
<ide> describe Utils::Bottles do
<ide> describe "#tag", :needs_macos do
<del> it "returns :mavericks on Mavericks" do
<del> allow(MacOS).to receive(:version).and_return(MacOS::Version.new("10.9"))
<del> expect(described_class.tag).to eq(:mavericks)
<add> it "returns :catalina on Catalina" do
<add> allow(MacOS).to receive(:version).and_return(MacOS::Version.new("10.15"))
<add> expect(described_class.tag).to eq(:catalina)
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/utils/bottles/collector_spec.rb
<ide> describe Utils::Bottles::Collector do
<ide> describe "#fetch_checksum_for" do
<ide> it "returns passed tags" do
<del> subject[:yosemite] = "foo"
<del> subject[:el_captain] = "bar"
<del> expect(subject.fetch_checksum_for(:el_captain)).to eq(["bar", :el_captain])
<add> subject[:mojave] = "foo"
<add> subject[:catalina] = "bar"
<add> expect(subject.fetch_checksum_for(:catalina)).to eq(["bar", :catalina])
<ide> end
<ide>
<ide> it "returns nil if empty" do
<ide> expect(subject.fetch_checksum_for(:foo)).to be nil
<ide> end
<ide>
<ide> it "returns nil when there is no match" do
<del> subject[:yosemite] = "foo"
<add> subject[:catalina] = "foo"
<ide> expect(subject.fetch_checksum_for(:foo)).to be nil
<ide> end
<ide>
<ide> it "uses older tags when needed", :needs_macos do
<del> subject[:mavericks] = "foo"
<del> expect(subject.send(:find_matching_tag, :mavericks)).to eq(:mavericks)
<del> expect(subject.send(:find_matching_tag, :yosemite)).to eq(:mavericks)
<add> subject[:mojave] = "foo"
<add> expect(subject.send(:find_matching_tag, :mojave)).to eq(:mojave)
<add> expect(subject.send(:find_matching_tag, :catalina)).to eq(:mojave)
<ide> end
<ide>
<ide> it "does not use older tags when requested not to", :needs_macos do
<ide> allow(Homebrew::EnvConfig).to receive(:developer?).and_return(true)
<ide> allow(Homebrew::EnvConfig).to receive(:skip_or_later_bottles?).and_return(true)
<ide> allow(OS::Mac).to receive(:prerelease?).and_return(true)
<del> subject[:mavericks] = "foo"
<del> expect(subject.send(:find_matching_tag, :mavericks)).to eq(:mavericks)
<del> expect(subject.send(:find_matching_tag, :yosemite)).to be_nil
<add> subject[:mojave] = "foo"
<add> expect(subject.send(:find_matching_tag, :mojave)).to eq(:mojave)
<add> expect(subject.send(:find_matching_tag, :catalina)).to be_nil
<ide> end
<ide>
<ide> it "ignores HOMEBREW_SKIP_OR_LATER_BOTTLES on release versions", :needs_macos do
<ide> allow(Homebrew::EnvConfig).to receive(:skip_or_later_bottles?).and_return(true)
<ide> allow(OS::Mac).to receive(:prerelease?).and_return(false)
<del> subject[:mavericks] = "foo"
<del> expect(subject.send(:find_matching_tag, :mavericks)).to eq(:mavericks)
<del> expect(subject.send(:find_matching_tag, :yosemite)).to eq(:mavericks)
<add> subject[:mojave] = "foo"
<add> expect(subject.send(:find_matching_tag, :mojave)).to eq(:mojave)
<add> expect(subject.send(:find_matching_tag, :catalina)).to eq(:mojave)
<ide> end
<ide> end
<ide> end
<ide><path>docs/Formula-Cookbook.md
<ide> A *formula* is a package definition written in Ruby. It can be created with `bre
<ide> | **opt prefix** | A symlink to the active version of a **Keg** | `/usr/local/opt/foo ` |
<ide> | **Cellar** | All **Kegs** are installed here | `/usr/local/Cellar` |
<ide> | **Tap** | A Git repository of **Formulae** and/or commands | `/usr/local/Homebrew/Library/Taps/homebrew/homebrew-core` |
<del>| **Bottle** | Pre-built **Keg** used instead of building from source | `qt-4.8.4.mavericks.bottle.tar.gz` |
<add>| **Bottle** | Pre-built **Keg** used instead of building from source | `qt-4.8.4.catalina.bottle.tar.gz` |
<ide> | **Cask** | An [extension of Homebrew](https://github.com/Homebrew/homebrew-cask) to install macOS native apps | `/Applications/MacDown.app/Contents/SharedSupport/bin/macdown` |
<ide> | **Brew Bundle**| An [extension of Homebrew](https://github.com/Homebrew/homebrew-bundle) to describe dependencies | `brew 'myservice', restart_service: true` |
<ide> | 18 |
Javascript | Javascript | make value of queueconnect a set<chunkgroupinfo> | bfe55b71a2ca32aba475264e072f082a46c3fa49 | <ide><path>lib/buildChunkGraph.js
<ide> const { connectChunkGroupParentAndChild } = require("./GraphHelpers");
<ide> * @property {Set<Module>[]} availableModulesToBeMerged enqueued updates to the minimal set of available modules
<ide> * @property {QueueItem[]} skippedItems queue items that were skipped because module is already available in parent chunks (need to reconsider when minAvailableModules is shrinking)
<ide> * @property {Set<Module>} resultingAvailableModules set of modules available including modules from this chunk group
<del> * @property {Set<ChunkGroup>} children set of children chunk groups, that will be revisited when availableModules shrink
<add> * @property {Set<ChunkGroupInfo>} children set of children chunk groups, that will be revisited when availableModules shrink
<ide> * @property {number} preOrderIndex next pre order index
<ide> * @property {number} postOrderIndex next post order index
<ide> */
<ide> const visitModules = (
<ide> // correct order
<ide> queue.reverse();
<ide>
<del> /** @type {Map<ChunkGroupInfo, Set<ChunkGroup>>} */
<add> /** @type {Map<ChunkGroupInfo, Set<ChunkGroupInfo>>} */
<ide> const queueConnect = new Map();
<ide> /** @type {Set<ChunkGroupInfo>} */
<ide> const outdatedChunkGroupInfo = new Set();
<ide> const visitModules = (
<ide> connectList = new Set();
<ide> queueConnect.set(chunkGroupInfo, connectList);
<ide> }
<del> connectList.add(c);
<add> connectList.add(cgi);
<ide>
<ide> // 4. We enqueue the DependenciesBlock for traversal
<ide> queueDelayed.push({
<ide> const visitModules = (
<ide>
<ide> // 2. Update chunk group info
<ide> for (const target of targets) {
<del> const chunkGroupInfo = chunkGroupInfoMap.get(target);
<del> chunkGroupInfo.availableModulesToBeMerged.push(
<del> resultingAvailableModules
<del> );
<del> outdatedChunkGroupInfo.add(chunkGroupInfo);
<add> target.availableModulesToBeMerged.push(resultingAvailableModules);
<add> outdatedChunkGroupInfo.add(target);
<ide> }
<ide> }
<ide> queueConnect.clear();
<ide> const visitModules = (
<ide>
<ide> // 3. Reconsider children chunk groups
<ide> if (info.children !== undefined) {
<del> for (const c of info.children) {
<add> for (const cgi of info.children) {
<ide> let connectList = queueConnect.get(info);
<ide> if (connectList === undefined) {
<ide> connectList = new Set();
<ide> queueConnect.set(info, connectList);
<ide> }
<del> connectList.add(c);
<add> connectList.add(cgi);
<ide> }
<ide> }
<ide> } | 1 |
PHP | PHP | replace last_page method with property | de48e194c7b02407ace412f87e36540e1bd8d3ab | <ide><path>system/paginator.php
<ide> public function __construct($results, $total, $per_page)
<ide> $this->per_page = $per_page;
<ide> $this->results = $results;
<ide> $this->total = $total;
<add>
<add> $this->last_page = ceil($total / $per_page);
<ide> }
<ide>
<ide> /**
<ide> public static function page($total, $per_page)
<ide> */
<ide> public function links($adjacent = 3)
<ide> {
<del> return ($this->last_page() > 1) ? '<div class="pagination">'.$this->previous().$this->numbers($adjacent).$this->next() : '';
<add> return ($this->last_page > 1) ? '<div class="pagination">'.$this->previous().$this->numbers($adjacent).$this->next() : '';
<ide> }
<ide>
<ide> /**
<ide> public function links($adjacent = 3)
<ide> */
<ide> private function numbers($adjacent = 3)
<ide> {
<del> return ($this->last_page() < 7 + ($adjacent * 2)) ? $this->range(1, $this->last_page()) : $this->slider($adjacent);
<add> return ($this->last_page < 7 + ($adjacent * 2)) ? $this->range(1, $this->last_page) : $this->slider($adjacent);
<ide> }
<ide>
<ide> /**
<ide> private function slider($adjacent)
<ide> {
<ide> return $this->range(1, 4 + ($adjacent * 2)).$this->ending();
<ide> }
<del> elseif ($this->page >= $this->last_page() - ($adjacent * 2))
<add> elseif ($this->page >= $this->last_page - ($adjacent * 2))
<ide> {
<del> return $this->beginning().$this->range($this->last_page() - 2 - ($adjacent * 2), $this->last_page());
<add> return $this->beginning().$this->range($this->last_page - 2 - ($adjacent * 2), $this->last_page);
<ide> }
<ide> else
<ide> {
<ide> public function next()
<ide> {
<ide> $text = Lang::line('pagination.next')->get($this->language);
<ide>
<del> if ($this->page < $this->last_page())
<add> if ($this->page < $this->last_page)
<ide> {
<ide> return HTML::link(Request::uri().'?page='.($this->page + 1), $text, array('class' => 'next_page'));
<ide> }
<ide> private function beginning()
<ide> */
<ide> private function ending()
<ide> {
<del> return '<span class="dots">...</span>'.$this->range($this->last_page() - 1, $this->last_page());
<del> }
<del>
<del> /**
<del> * Calculate the last page based on the last page and the items per page.
<del> *
<del> * @return int
<del> */
<del> private function last_page()
<del> {
<del> return ceil($this->total / $this->per_page);
<add> return '<span class="dots">...</span>'.$this->range($this->last_page - 1, $this->last_page);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | fix typo in lib/internal/bootstrap/loaders.js | 4b5db00ea1ed824bc405a227fea5ae66cc429f87 | <ide><path>lib/internal/bootstrap/loaders.js
<ide> // lib/internal/modules/esm/* (ES Modules).
<ide> //
<ide> // This file is compiled and run by node.cc before bootstrap/node.js
<del>// was called, therefore the loaders are bootstraped before we start to
<add>// was called, therefore the loaders are bootstrapped before we start to
<ide> // actually bootstrap Node.js. It creates the following objects:
<ide> //
<ide> // C++ binding loaders: | 1 |
PHP | PHP | reject file paths containing `..` | 6f68049bf507783c5f278eccbd0c807a0ecc45c3 | <ide><path>lib/Cake/Network/CakeResponse.php
<ide> public function file($path, $options = array()) {
<ide> 'download' => null
<ide> );
<ide>
<add> if (strpos($path, '..') !== false) {
<add> throw new NotFoundException(__d(
<add> 'cake_dev',
<add> 'The requested file contains `..` and will not be read.'
<add> ));
<add> }
<add>
<ide> if (!is_file($path)) {
<ide> $path = APP . $path;
<ide> }
<ide><path>lib/Cake/Test/Case/Network/CakeResponseTest.php
<ide> public function testFileNotFound() {
<ide> $response->file('/some/missing/folder/file.jpg');
<ide> }
<ide>
<add>/**
<add> * test file with ..
<add> *
<add> * @expectedException NotFoundException
<add> * @return void
<add> */
<add> public function testFileWithPathTraversal() {
<add> $response = new CakeResponse();
<add> $response->file('my/../cat.gif');
<add> }
<add>
<ide> /**
<ide> * testFile method
<ide> * | 2 |
Ruby | Ruby | add methods for building test file paths | 6e634890e8ffd8336e0826508ec0d67d1e426162 | <ide><path>Library/Homebrew/test/test_mach.rb
<ide> def setup
<ide> @archs = [:i386, :x86_64, :ppc7400, :ppc64].extend(ArchitectureListExtension)
<ide> end
<ide>
<add> def dylib_path(name)
<add> Pathname.new("#{TEST_FOLDER}/mach/#{name}.dylib")
<add> end
<add>
<add> def bundle_path(name)
<add> Pathname.new("#{TEST_FOLDER}/mach/#{name}.bundle")
<add> end
<add>
<ide> def test_fat_dylib
<del> pn = Pathname.new("#{TEST_FOLDER}/mach/fat.dylib")
<add> pn = dylib_path("fat")
<ide> assert pn.universal?
<ide> assert !pn.i386?
<ide> assert !pn.x86_64?
<ide> def test_fat_dylib
<ide> end
<ide>
<ide> def test_i386_dylib
<del> pn = Pathname.new("#{TEST_FOLDER}/mach/i386.dylib")
<add> pn = dylib_path("i386")
<ide> assert !pn.universal?
<ide> assert pn.i386?
<ide> assert !pn.x86_64?
<ide> def test_i386_dylib
<ide> end
<ide>
<ide> def test_x86_64_dylib
<del> pn = Pathname.new("#{TEST_FOLDER}/mach/x86_64.dylib")
<add> pn = dylib_path("x86_64")
<ide> assert !pn.universal?
<ide> assert !pn.i386?
<ide> assert pn.x86_64?
<ide> def test_mach_o_executable
<ide> end
<ide>
<ide> def test_fat_bundle
<del> pn = Pathname.new("#{TEST_FOLDER}/mach/fat.bundle")
<add> pn = bundle_path("fat")
<ide> assert pn.universal?
<ide> assert !pn.i386?
<ide> assert !pn.x86_64?
<ide> def test_fat_bundle
<ide> end
<ide>
<ide> def test_i386_bundle
<del> pn = Pathname.new("#{TEST_FOLDER}/mach/i386.bundle")
<add> pn = bundle_path("i386")
<ide> assert !pn.universal?
<ide> assert pn.i386?
<ide> assert !pn.x86_64?
<ide> def test_i386_bundle
<ide> end
<ide>
<ide> def test_x86_64_bundle
<del> pn = Pathname.new("#{TEST_FOLDER}/mach/x86_64.bundle")
<add> pn = bundle_path("x86_64")
<ide> assert !pn.universal?
<ide> assert !pn.i386?
<ide> assert pn.x86_64?
<ide> def test_architecture_list_extension_massaging_flags
<ide> end
<ide>
<ide> def test_architecture_list_arch_flags_methods
<del> pn = Pathname.new("#{TEST_FOLDER}/mach/fat.dylib")
<add> pn = dylib_path("fat")
<ide> assert pn.archs.intel_universal?
<ide> assert_equal "-arch x86_64 -arch i386", pn.archs.as_arch_flags
<ide> assert_equal "x86_64;i386", pn.archs.as_cmake_arch_flags | 1 |
Python | Python | fix multi query scenario in bigquery example dag | da1e6578e0207b7f2acab794ed3c5bf730719bf8 | <ide><path>airflow/providers/google/cloud/example_dags/example_bigquery_queries.py
<ide> task_id="execute_multi_query",
<ide> configuration={
<ide> "query": {
<del> "query": [
<del> f"SELECT * FROM {DATASET}.{TABLE_2}",
<del> f"SELECT COUNT(*) FROM {DATASET}.{TABLE_2}",
<del> ],
<add> "query": f"SELECT * FROM {DATASET}.{TABLE_2};SELECT COUNT(*) FROM {DATASET}.{TABLE_2}",
<ide> "useLegacySql": False,
<ide> }
<ide> }, | 1 |
Javascript | Javascript | handle index changes when an item is unshifted | 5fbd618c2ff0dbaa4e19d0fd0e55921ce7d89478 | <ide><path>src/ng/directive/ngClass.js
<ide> function classDirective(name, selector) {
<ide> scope.$watch('$index', function($index, old$index) {
<ide> // jshint bitwise: false
<ide> var mod = $index & 1;
<del> if (mod !== old$index & 1) {
<add> if (mod !== (old$index & 1)) {
<ide> var classes = arrayClasses(scope.$eval(attr[name]));
<ide> mod === selector ?
<ide> addClasses(classes) :
<ide><path>test/ng/directive/ngClassSpec.js
<ide> describe('ngClass', function() {
<ide> }));
<ide>
<ide>
<add> it('should update ngClassOdd/Even when an item is added to the model', inject(function($rootScope, $compile) {
<add> element = $compile('<ul>' +
<add> '<li ng-repeat="i in items" ' +
<add> 'ng-class-odd="\'odd\'" ng-class-even="\'even\'">i</li>' +
<add> '<ul>')($rootScope);
<add> $rootScope.items = ['b','c','d'];
<add> $rootScope.$digest();
<add>
<add> $rootScope.items.unshift('a');
<add> $rootScope.$digest();
<add>
<add> var e1 = jqLite(element[0].childNodes[1]);
<add> var e4 = jqLite(element[0].childNodes[7]);
<add>
<add> expect(e1.hasClass('odd')).toBeTruthy();
<add> expect(e1.hasClass('even')).toBeFalsy();
<add>
<add> expect(e4.hasClass('even')).toBeTruthy();
<add> expect(e4.hasClass('odd')).toBeFalsy();
<add> }));
<add>
<add>
<ide> it('should update ngClassOdd/Even when model is changed by filtering', inject(function($rootScope, $compile) {
<ide> element = $compile('<ul>' +
<ide> '<li ng-repeat="i in items track by $index" ' + | 2 |
Text | Text | fix doc for napi_get_typedarray_info | 35cf00842f65077bce64cc25d39b72477afa161e | <ide><path>doc/api/n-api.md
<ide> napi_status napi_get_typedarray_info(napi_env env,
<ide> properties to query.
<ide> - `[out] type`: Scalar datatype of the elements within the `TypedArray`.
<ide> - `[out] length`: The number of elements in the `TypedArray`.
<del>- `[out] data`: The data buffer underlying the `TypedArray`.
<add>- `[out] data`: The data buffer underlying the `TypedArray` adjusted by
<add>the `byte_offset` value so that it points to the first element in the
<add>`TypedArray`.
<ide> - `[out] arraybuffer`: The `ArrayBuffer` underlying the `TypedArray`.
<del>- `[out] byte_offset`: The byte offset within the data buffer from which
<del>to start projecting the `TypedArray`.
<add>- `[out] byte_offset`: The byte offset within the underlying native array
<add>at which the first element of the arrays is located. The value for the data
<add>parameter has already been adjusted so that data points to the first element
<add>in the array. Therefore, the first byte of the native array would be at
<add>data - `byte_offset`.
<ide>
<ide> Returns `napi_ok` if the API succeeded.
<ide> | 1 |
Ruby | Ruby | combine loops in relocate_install_names | 3662a2765de7ca27cd6c98ce50c98435a3e25f77 | <ide><path>Library/Homebrew/keg_fix_install_names.rb
<ide> def relocate_install_names old_prefix, new_prefix, old_cellar, new_cellar, optio
<ide> change_dylib_id(id, file)
<ide> end
<ide>
<del> each_install_name_for(file) do |old_cellar_name|
<del> next unless old_cellar_name.start_with? old_cellar
<del> new_cellar_name = old_cellar_name.sub(old_cellar, new_cellar)
<del> change_install_name(old_cellar_name, new_cellar_name, file)
<del> end
<del>
<del> each_install_name_for(file) do |old_prefix_name|
<del> next unless old_prefix_name.start_with? old_prefix
<del> new_prefix_name = old_prefix_name.sub(old_prefix, new_prefix)
<del> change_install_name(old_prefix_name, new_prefix_name, file)
<add> each_install_name_for(file) do |old_name|
<add> if old_name.start_with? old_cellar
<add> new_name = old_name.sub(old_cellar, new_cellar)
<add> elsif old_name.start_with? old_prefix
<add> new_name = old_name.sub(old_prefix, new_prefix)
<add> end
<add>
<add> change_install_name(old_name, new_name, file) if new_name
<ide> end
<ide> end
<ide> end | 1 |
Go | Go | remove producergone from logwatcher | 906b979b888cf9111a4a2583640e509d28395670 | <ide><path>daemon/logger/adapter_test.go
<ide> func TestAdapterReadLogs(t *testing.T) {
<ide> t.Fatal("timeout waiting for message channel to close")
<ide>
<ide> }
<del> lw.ProducerGone()
<add> lw.ConsumerGone()
<ide>
<ide> lw = lr.ReadLogs(ReadConfig{Follow: true})
<ide> for _, x := range testMsg {
<ide><path>daemon/logger/journald/journald.go
<ide> package journald // import "github.com/docker/docker/daemon/logger/journald"
<ide> import (
<ide> "fmt"
<ide> "strconv"
<del> "sync"
<ide> "unicode"
<ide>
<ide> "github.com/coreos/go-systemd/v22/journal"
<ide> import (
<ide> const name = "journald"
<ide>
<ide> type journald struct {
<del> mu sync.Mutex //nolint:structcheck,unused
<del> vars map[string]string // additional variables and values to send to the journal along with the log message
<del> readers map[*logger.LogWatcher]struct{}
<add> vars map[string]string // additional variables and values to send to the journal along with the log message
<add>
<add> closed chan struct{}
<ide> }
<ide>
<ide> func init() {
<ide> func New(info logger.Info) (logger.Logger, error) {
<ide> for k, v := range extraAttrs {
<ide> vars[k] = v
<ide> }
<del> return &journald{vars: vars, readers: make(map[*logger.LogWatcher]struct{})}, nil
<add> return &journald{vars: vars, closed: make(chan struct{})}, nil
<ide> }
<ide>
<ide> // We don't actually accept any options, but we have to supply a callback for
<ide> func (s *journald) Log(msg *logger.Message) error {
<ide> func (s *journald) Name() string {
<ide> return name
<ide> }
<add>
<add>func (s *journald) Close() error {
<add> close(s.closed)
<add> return nil
<add>}
<ide><path>daemon/logger/journald/read.go
<ide> import (
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<del>func (s *journald) Close() error {
<del> s.mu.Lock()
<del> for r := range s.readers {
<del> r.ProducerGone()
<del> delete(s.readers, r)
<del> }
<del> s.mu.Unlock()
<del> return nil
<del>}
<del>
<ide> // CErr converts error code returned from a sd_journal_* function
<ide> // (which returns -errno) to a string
<ide> func CErr(ret C.int) string {
<ide> drain:
<ide> }
<ide>
<ide> func (s *journald) followJournal(logWatcher *logger.LogWatcher, j *C.sd_journal, cursor *C.char, untilUnixMicro uint64) *C.char {
<del> s.mu.Lock()
<del> s.readers[logWatcher] = struct{}{}
<del> s.mu.Unlock()
<add> defer close(logWatcher.Msg)
<ide>
<ide> waitTimeout := C.uint64_t(250000) // 0.25s
<ide>
<ide> for {
<ide> status := C.sd_journal_wait(j, waitTimeout)
<ide> if status < 0 {
<ide> logWatcher.Err <- errors.New("error waiting for journal: " + CErr(status))
<del> goto cleanup
<add> break
<ide> }
<ide> select {
<ide> case <-logWatcher.WatchConsumerGone():
<del> goto cleanup // won't be able to write anything anymore
<del> case <-logWatcher.WatchProducerGone():
<add> break // won't be able to write anything anymore
<add> case <-s.closed:
<ide> // container is gone, drain journal
<ide> default:
<ide> // container is still alive
<ide> func (s *journald) followJournal(logWatcher *logger.LogWatcher, j *C.sd_journal,
<ide> }
<ide> }
<ide>
<del>cleanup:
<del> s.mu.Lock()
<del> delete(s.readers, logWatcher)
<del> s.mu.Unlock()
<del> close(logWatcher.Msg)
<ide> return cursor
<ide> }
<ide>
<ide><path>daemon/logger/journald/read_unsupported.go
<del>//go:build !linux || !cgo || static_build || !journald
<del>// +build !linux !cgo static_build !journald
<del>
<del>package journald // import "github.com/docker/docker/daemon/logger/journald"
<del>
<del>func (s *journald) Close() error {
<del> return nil
<del>}
<ide><path>daemon/logger/jsonfilelog/read_test.go
<ide> func BenchmarkJSONFileLoggerReadLogs(b *testing.B) {
<ide> lw := jsonlogger.(*JSONFileLogger).ReadLogs(logger.ReadConfig{Follow: true})
<ide> for {
<ide> select {
<del> case <-lw.Msg:
<del> case <-lw.WatchProducerGone():
<del> return
<add> case _, ok := <-lw.Msg:
<add> if !ok {
<add> return
<add> }
<ide> case err := <-chError:
<ide> b.Fatal(err)
<ide> }
<ide><path>daemon/logger/logger.go
<ide> type LogWatcher struct {
<ide> Msg chan *Message
<ide> // For sending error messages that occur while reading logs.
<ide> Err chan error
<del> producerOnce sync.Once
<del> producerGone chan struct{}
<ide> consumerOnce sync.Once
<ide> consumerGone chan struct{}
<ide> }
<ide> func NewLogWatcher() *LogWatcher {
<ide> return &LogWatcher{
<ide> Msg: make(chan *Message, logWatcherBufferSize),
<ide> Err: make(chan error, 1),
<del> producerGone: make(chan struct{}),
<ide> consumerGone: make(chan struct{}),
<ide> }
<ide> }
<ide>
<del>// ProducerGone notifies the underlying log reader that
<del>// the logs producer (a container) is gone.
<del>func (w *LogWatcher) ProducerGone() {
<del> // only close if not already closed
<del> w.producerOnce.Do(func() {
<del> close(w.producerGone)
<del> })
<del>}
<del>
<del>// WatchProducerGone returns a channel receiver that receives notification
<del>// once the logs producer (a container) is gone.
<del>func (w *LogWatcher) WatchProducerGone() <-chan struct{} {
<del> return w.producerGone
<del>}
<del>
<ide> // ConsumerGone notifies that the logs consumer is gone.
<ide> func (w *LogWatcher) ConsumerGone() {
<ide> // only close if not already closed
<ide><path>daemon/logger/loggerutils/follow.go
<ide> type follow struct {
<ide> dec Decoder
<ide> fileWatcher filenotify.FileWatcher
<ide> logWatcher *logger.LogWatcher
<add> producerGone <-chan struct{}
<ide> notifyRotate, notifyEvict chan interface{}
<ide> oldSize int64
<ide> retries int
<ide> func (fl *follow) waitRead() error {
<ide> case fsnotify.Rename, fsnotify.Remove:
<ide> select {
<ide> case <-fl.notifyRotate:
<del> case <-fl.logWatcher.WatchProducerGone():
<add> case <-fl.producerGone:
<ide> return errDone
<ide> case <-fl.logWatcher.WatchConsumerGone():
<ide> return errDone
<ide> func (fl *follow) waitRead() error {
<ide> return errRetry
<ide> }
<ide> return err
<del> case <-fl.logWatcher.WatchProducerGone():
<add> case <-fl.producerGone:
<ide> return errDone
<ide> case <-fl.logWatcher.WatchConsumerGone():
<ide> return errDone
<ide> func (fl *follow) mainLoop(since, until time.Time) {
<ide> }
<ide> }
<ide>
<del>func followLogs(f *os.File, logWatcher *logger.LogWatcher, notifyRotate, notifyEvict chan interface{}, dec Decoder, since, until time.Time) {
<add>func followLogs(f *os.File, logWatcher *logger.LogWatcher, producerGone <-chan struct{}, notifyRotate, notifyEvict chan interface{}, dec Decoder, since, until time.Time) {
<ide> dec.Reset(f)
<ide>
<ide> name := f.Name()
<ide> func followLogs(f *os.File, logWatcher *logger.LogWatcher, notifyRotate, notifyE
<ide> oldSize: -1,
<ide> logWatcher: logWatcher,
<ide> fileWatcher: fileWatcher,
<add> producerGone: producerGone,
<ide> notifyRotate: notifyRotate,
<ide> notifyEvict: notifyEvict,
<ide> dec: dec,
<ide><path>daemon/logger/loggerutils/logfile.go
<ide> type LogFile struct {
<ide> mu sync.RWMutex // protects the logfile access
<ide> f *os.File // store for closing
<ide> closed bool
<add> closedCh chan struct{}
<ide> rotateMu sync.Mutex // blocks the next rotation until the current rotation is completed
<ide> capacity int64 // maximum size of each file
<ide> currentSize int64 // current size of the latest file
<ide> type LogFile struct {
<ide> lastTimestamp time.Time // timestamp of the last log
<ide> filesRefCounter refCounter // keep reference-counted of decompressed files
<ide> notifyReaders *pubsub.Publisher
<del> readers map[*logger.LogWatcher]struct{} // stores the active log followers
<ide> marshal logger.MarshalFunc
<ide> createDecoder MakeDecoderFn
<ide> getTailReader GetTailReaderFunc
<ide> func NewLogFile(logPath string, capacity int64, maxFiles int, compress bool, mar
<ide>
<ide> return &LogFile{
<ide> f: log,
<add> closedCh: make(chan struct{}),
<ide> capacity: capacity,
<ide> currentSize: size,
<ide> maxFiles: maxFiles,
<ide> compress: compress,
<ide> filesRefCounter: refCounter{counter: make(map[string]int)},
<ide> notifyReaders: pubsub.NewPublisher(0, 1),
<del> readers: make(map[*logger.LogWatcher]struct{}),
<ide> marshal: marshaller,
<ide> createDecoder: decodeFunc,
<ide> perms: perms,
<ide> func (w *LogFile) Close() error {
<ide> if w.closed {
<ide> return nil
<ide> }
<del> for r := range w.readers {
<del> r.ProducerGone()
<del> delete(w.readers, r)
<del> }
<ide> if err := w.f.Close(); err != nil && !errors.Is(err, os.ErrClosed) {
<ide> return err
<ide> }
<ide> w.closed = true
<add> close(w.closedCh)
<ide> return nil
<ide> }
<ide>
<ide> func (w *LogFile) Close() error {
<ide> // TODO: Consider a different implementation which can effectively follow logs under frequent rotations.
<ide> func (w *LogFile) ReadLogs(config logger.ReadConfig) *logger.LogWatcher {
<ide> watcher := logger.NewLogWatcher()
<del> w.mu.Lock()
<del> w.readers[watcher] = struct{}{}
<del> w.mu.Unlock()
<del>
<ide> // Lock before starting the reader goroutine to synchronize operations
<ide> // for race-free unit testing. The writer is locked out until the reader
<ide> // has opened the log file and set the read cursor to the current
<ide> func (w *LogFile) ReadLogs(config logger.ReadConfig) *logger.LogWatcher {
<ide> }
<ide>
<ide> func (w *LogFile) readLogsLocked(config logger.ReadConfig, watcher *logger.LogWatcher) {
<del> defer func() {
<del> close(watcher.Msg)
<del> w.mu.Lock()
<del> delete(w.readers, watcher)
<del> w.mu.Unlock()
<del> }()
<add> defer close(watcher.Msg)
<ide>
<ide> currentFile, err := open(w.f.Name())
<ide> if err != nil {
<ide> func (w *LogFile) readLogsLocked(config logger.ReadConfig, watcher *logger.LogWa
<ide> })
<ide> defer w.notifyReaders.Evict(notifyRotate)
<ide>
<del> followLogs(currentFile, watcher, notifyRotate, notifyEvict, dec, config.Since, config.Until)
<add> followLogs(currentFile, watcher, w.closedCh, notifyRotate, notifyEvict, dec, config.Since, config.Until)
<ide> }
<ide>
<ide> func (w *LogFile) openRotatedFiles(config logger.ReadConfig) (files []*os.File, err error) {
<ide><path>daemon/logger/loggerutils/logfile_test.go
<ide> func TestFollowLogsConsumerGone(t *testing.T) {
<ide> followLogsDone := make(chan struct{})
<ide> var since, until time.Time
<ide> go func() {
<del> followLogs(f, lw, make(chan interface{}), make(chan interface{}), dec, since, until)
<add> followLogs(f, lw, nil, make(chan interface{}), make(chan interface{}), dec, since, until)
<ide> close(followLogsDone)
<ide> }()
<ide>
<ide> func TestFollowLogsProducerGone(t *testing.T) {
<ide> var since, until time.Time
<ide>
<ide> followLogsDone := make(chan struct{})
<add> producerGone := make(chan struct{})
<ide> go func() {
<del> followLogs(f, lw, make(chan interface{}), make(chan interface{}), dec, since, until)
<add> followLogs(f, lw, producerGone, make(chan interface{}), make(chan interface{}), dec, since, until)
<ide> close(followLogsDone)
<ide> }()
<ide>
<ide> func TestFollowLogsProducerGone(t *testing.T) {
<ide>
<ide> // "stop" the "container"
<ide> atomic.StoreInt32(&closed, 1)
<del> lw.ProducerGone()
<add> close(producerGone)
<ide>
<ide> // should receive all the messages sent
<ide> readDone := make(chan struct{})
<ide> func waitForMsg(t *testing.T, lw *logger.LogWatcher, timeout time.Duration) {
<ide> defer timer.Stop()
<ide>
<ide> select {
<del> case <-lw.Msg:
<del> case <-lw.WatchProducerGone():
<del> t.Fatal("log producer gone before log message arrived")
<add> case _, ok := <-lw.Msg:
<add> assert.Assert(t, ok, "log producer gone before log message arrived")
<ide> case err := <-lw.Err:
<ide> assert.NilError(t, err)
<ide> case <-timer.C: | 9 |
Python | Python | correct an issue on amp module import error | eeb847fba6b9bac58aa0435a38cd850bf191efc8 | <ide><path>glances/amps_list.py
<ide> def load_amps(self):
<ide> item.endswith(".py") and
<ide> item != (header + "amp.py")):
<ide> # Import the amp
<del> amp = __import__(os.path.basename(item)[:-3])
<del> # Add the AMP to the dictionary
<del> # The key is the AMP name
<del> # for example, the file glances_xxx.py
<del> # generate self._amps_list["xxx"] = ...
<del> amp_name = os.path.basename(item)[len(header):-3].lower()
<del> self.__amps_dict[amp_name] = amp.Amp(self.args)
<add> try:
<add> amp = __import__(os.path.basename(item)[:-3])
<add> except ImportError as e:
<add> logger.warning("Can not load {0}, you need to install an external Python package ({1})".format(os.path.basename(item), e))
<add> except Exception as e:
<add> logger.warning("Can not load {0} ({1})".format(os.path.basename(item), e))
<add> else:
<add> # Add the AMP to the dictionary
<add> # The key is the AMP name
<add> # for example, the file glances_xxx.py
<add> # generate self._amps_list["xxx"] = ...
<add> amp_name = os.path.basename(item)[len(header):-3].lower()
<add> self.__amps_dict[amp_name] = amp.Amp(self.args)
<ide> # Log AMPs list
<ide> logger.debug("Available AMPs list: {0}".format(self.getList()))
<ide> | 1 |
PHP | PHP | fix style issue | c1820b2039f4bb44322c704f9c208fb10341cd38 | <ide><path>src/Illuminate/Auth/Events/Logout.php
<ide> class Logout
<ide> {
<ide> use SerializesModels;
<del>
<ide> /**
<ide> * The authenticated user.
<ide> * | 1 |
Python | Python | fix non-versioneer uses | 8faae9d5fad6a8342b21deed1dcbecaaa9a32711 | <ide><path>numpy/distutils/misc_util.py
<ide> def get_version(self, version_file=None, version_variable=None):
<ide> try:
<ide> version = version_module.get_versions()['version']
<ide> except AttributeError:
<del> version = None
<add> pass
<ide>
<ide> if version is not None:
<ide> break | 1 |
Text | Text | fix spelling and punctuation | eba06309d5a42cfb64297b228b03ae4fa32118e7 | <ide><path>guide/english/developer-ethics/dark-patterns/index.md
<ide> Examples include:
<ide>
<ide> * [**Bait and Switch**](https://darkpatterns.org/types-of-dark-pattern/bait-and-switch) – A user sets out to do one thing, but a different, undesirable thing happens instead.
<ide>
<del>* [**Disguised Ads**](https://darkpatterns.org/types-of-dark-pattern/disguised-ads) – Adverts disguised as other kinds of content or navigation, in order to get users to click on them.
<add>* [**Disguised Ads**](https://darkpatterns.org/types-of-dark-pattern/disguised-ads) – Advertisements disguised as other kinds of content or navigation, in order to get users to click on them.
<ide>
<ide> * [**Forced Continuity**](https://darkpatterns.org/types-of-dark-pattern/forced-continuity) – Silently charging a user's credit card without warning at the end of a free trial.
<ide>
<del>* [**Friend Spam**](https://darkpatterns.org/types-of-dark-pattern/friend-spam) – A website or app asks for a user's email or social media permissions under the pretence it will be used for a desirable outcome (e.g. finding friends), but then spams all the user's contacts in a message that claims to be from that user.
<add>* [**Friend Spam**](https://darkpatterns.org/types-of-dark-pattern/friend-spam) – A website or app asks for a user's email or social media permissions under the pretense it will be used for a desirable outcome (e.g. finding friends), but then spams all the user's contacts in a message that claims to be from that user.
<ide>
<del>* [**Hidden Costs**](https://darkpatterns.org/types-of-dark-pattern/hidden-costs) – At the last step of a checkout process, only to discover some unexpected charges appear, e.g. delivery charges, tax, etc. that were not disclosed prior to processing the user's payment.
<add>* [**Hidden Costs**](https://darkpatterns.org/types-of-dark-pattern/hidden-costs) – User arrives at the last step of a checkout process, only to discover some unexpected charges appear, e.g. delivery charges, tax, etc. that were not disclosed prior to processing the user's payment.
<ide>
<del>* [**Misdirection**](https://darkpatterns.org/types-of-dark-pattern/misdirection) – The design purposefully focuses a users' attention on one thing in order to distract their attention from another.
<add>* [**Misdirection**](https://darkpatterns.org/types-of-dark-pattern/misdirection) – The design purposefully focuses a user's attention on one thing in order to distract their attention from another.
<ide>
<del>* [**Price Comparison Prevention**](https://darkpatterns.org/types-of-dark-pattern/price-comparison-prevention) – An online retailer makes it hard for visitor's to compare the price of an item with another item, so they cannot make an informed decision.
<add>* [**Price Comparison Prevention**](https://darkpatterns.org/types-of-dark-pattern/price-comparison-prevention) – An online retailer makes it hard for visitors to compare the price of an item with another item, so they cannot make an informed decision.
<ide>
<ide> * [**Privacy Zuckering**](https://darkpatterns.org/types-of-dark-pattern/privacy-zuckering) – Users are tricked into publicly sharing more information about themselves than they really intended to. Named after Facebook CEO Mark Zuckerberg.
<ide> | 1 |
PHP | PHP | add stringable support for strip_tags() | 9b85771608d71988078fb9ce2b5c44c7e1fdfef6 | <ide><path>src/Illuminate/Support/Stringable.php
<ide> public function start($prefix)
<ide> return new static(Str::start($this->value, $prefix));
<ide> }
<ide>
<add> /**
<add> * Strip HTML and PHP tags from the given string.
<add> *
<add> * @param string $allowedTags
<add> * @return static
<add> */
<add> public function stripTags($allowedTags = null)
<add> {
<add> return new static(strip_tags($this->value, $allowedTags));
<add> }
<add>
<ide> /**
<ide> * Convert the given string to upper-case.
<ide> *
<ide><path>tests/Support/SupportStringableTest.php
<ide> public function testWordCount()
<ide> $this->assertEquals(2, $this->stringable('Hello, world!')->wordCount());
<ide> $this->assertEquals(10, $this->stringable('Hi, this is my first contribution to the Laravel framework.')->wordCount());
<ide> }
<add>
<add> public function testStripTags()
<add> {
<add> $this->assertSame('beforeafter', (string) $this->stringable('before<br>after')->stripTags());
<add> $this->assertSame('before<br>after', (string) $this->stringable('before<br>after')->stripTags('<br>'));
<add> $this->assertSame('before<br>after', (string) $this->stringable('<strong>before</strong><br>after')->stripTags('<br>'));
<add> $this->assertSame('<strong>before</strong><br>after', (string) $this->stringable('<strong>before</strong><br>after')->stripTags('<br><strong>'));
<add> }
<ide> } | 2 |
Python | Python | use an array type for list view response schemas | b45ff072947d01917132ef6993bf1b7f46d9f2c8 | <ide><path>rest_framework/schemas/openapi.py
<ide> def _get_request_body(self, path, method):
<ide> }
<ide>
<ide> def _get_responses(self, path, method):
<del> # TODO: Handle multiple codes.
<del> content = {}
<add> # TODO: Handle multiple codes and pagination classes.
<add> item_schema = {}
<ide> serializer = self._get_serializer(path, method)
<ide>
<ide> if isinstance(serializer, serializers.Serializer):
<del> content = self._map_serializer(serializer)
<add> item_schema = self._map_serializer(serializer)
<ide> # No write_only fields for response.
<del> for name, schema in content['properties'].copy().items():
<add> for name, schema in item_schema['properties'].copy().items():
<ide> if 'writeOnly' in schema:
<del> del content['properties'][name]
<del> content['required'] = [f for f in content['required'] if f != name]
<add> del item_schema['properties'][name]
<add> item_schema['required'] = [f for f in item_schema['required'] if f != name]
<add>
<add> if is_list_view(path, method, self.view):
<add> response_schema = {
<add> 'type': 'array',
<add> 'items': item_schema,
<add> }
<add> else:
<add> response_schema = item_schema
<ide>
<ide> return {
<ide> '200': {
<ide> 'content': {
<del> ct: {'schema': content}
<add> ct: {'schema': response_schema}
<ide> for ct in self.content_types
<ide> }
<ide> }
<ide><path>tests/schemas/test_openapi.py
<ide> def test_path_without_parameters(self):
<ide> assert operation == {
<ide> 'operationId': 'ListExamples',
<ide> 'parameters': [],
<del> 'responses': {'200': {'content': {'application/json': {'schema': {}}}}},
<add> 'responses': {
<add> '200': {
<add> 'content': {
<add> 'application/json': {
<add> 'schema': {
<add> 'type': 'array',
<add> 'items': {},
<add> },
<add> },
<add> },
<add> },
<add> },
<ide> }
<ide>
<ide> def test_path_with_id_parameter(self):
<ide> class View(generics.GenericAPIView):
<ide> assert list(schema['properties']['nested']['properties'].keys()) == ['number']
<ide> assert schema['properties']['nested']['required'] == ['number']
<ide>
<add> def test_list_response_body_generation(self):
<add> """Test that an array schema is returned for list views."""
<add> path = '/'
<add> method = 'GET'
<add>
<add> class ItemSerializer(serializers.Serializer):
<add> text = serializers.CharField()
<add>
<add> class View(generics.GenericAPIView):
<add> serializer_class = ItemSerializer
<add>
<add> view = create_view(
<add> View,
<add> method,
<add> create_request(path),
<add> )
<add> inspector = AutoSchema()
<add> inspector.view = view
<add>
<add> responses = inspector._get_responses(path, method)
<add> assert responses == {
<add> '200': {
<add> 'content': {
<add> 'application/json': {
<add> 'schema': {
<add> 'type': 'array',
<add> 'items': {
<add> 'properties': {
<add> 'text': {
<add> 'type': 'string',
<add> },
<add> },
<add> 'required': ['text'],
<add> },
<add> },
<add> },
<add> },
<add> },
<add> }
<add>
<add> def test_retrieve_response_body_generation(self):
<add> """Test that a list of properties is returned for retrieve item views."""
<add> path = '/{id}/'
<add> method = 'GET'
<add>
<add> class ItemSerializer(serializers.Serializer):
<add> text = serializers.CharField()
<add>
<add> class View(generics.GenericAPIView):
<add> serializer_class = ItemSerializer
<add>
<add> view = create_view(
<add> View,
<add> method,
<add> create_request(path),
<add> )
<add> inspector = AutoSchema()
<add> inspector.view = view
<add>
<add> responses = inspector._get_responses(path, method)
<add> assert responses == {
<add> '200': {
<add> 'content': {
<add> 'application/json': {
<add> 'schema': {
<add> 'properties': {
<add> 'text': {
<add> 'type': 'string',
<add> },
<add> },
<add> 'required': ['text'],
<add> },
<add> },
<add> },
<add> },
<add> }
<add>
<ide> def test_operation_id_generation(self):
<ide> path = '/'
<ide> method = 'GET'
<ide> def test_serializer_datefield(self):
<ide> inspector.view = view
<ide>
<ide> responses = inspector._get_responses(path, method)
<del> response_schema = responses['200']['content']['application/json']['schema']['properties']
<del> assert response_schema['date']['type'] == response_schema['datetime']['type'] == 'string'
<del> assert response_schema['date']['format'] == 'date'
<del> assert response_schema['datetime']['format'] == 'date-time'
<add> response_schema = responses['200']['content']['application/json']['schema']
<add> properties = response_schema['items']['properties']
<add> assert properties['date']['type'] == properties['datetime']['type'] == 'string'
<add> assert properties['date']['format'] == 'date'
<add> assert properties['datetime']['format'] == 'date-time'
<ide>
<ide> def test_serializer_validators(self):
<ide> path = '/'
<ide> def test_serializer_validators(self):
<ide> inspector.view = view
<ide>
<ide> responses = inspector._get_responses(path, method)
<del> response_schema = responses['200']['content']['application/json']['schema']['properties']
<add> response_schema = responses['200']['content']['application/json']['schema']
<add> properties = response_schema['items']['properties']
<ide>
<del> assert response_schema['integer']['type'] == 'integer'
<del> assert response_schema['integer']['maximum'] == 99
<del> assert response_schema['integer']['minimum'] == -11
<add> assert properties['integer']['type'] == 'integer'
<add> assert properties['integer']['maximum'] == 99
<add> assert properties['integer']['minimum'] == -11
<ide>
<del> assert response_schema['string']['minLength'] == 2
<del> assert response_schema['string']['maxLength'] == 10
<add> assert properties['string']['minLength'] == 2
<add> assert properties['string']['maxLength'] == 10
<ide>
<del> assert response_schema['regex']['pattern'] == r'[ABC]12{3}'
<del> assert response_schema['regex']['description'] == 'must have an A, B, or C followed by 1222'
<add> assert properties['regex']['pattern'] == r'[ABC]12{3}'
<add> assert properties['regex']['description'] == 'must have an A, B, or C followed by 1222'
<ide>
<del> assert response_schema['decimal1']['type'] == 'number'
<del> assert response_schema['decimal1']['multipleOf'] == .01
<del> assert response_schema['decimal1']['maximum'] == 10000
<del> assert response_schema['decimal1']['minimum'] == -10000
<add> assert properties['decimal1']['type'] == 'number'
<add> assert properties['decimal1']['multipleOf'] == .01
<add> assert properties['decimal1']['maximum'] == 10000
<add> assert properties['decimal1']['minimum'] == -10000
<ide>
<del> assert response_schema['decimal2']['type'] == 'number'
<del> assert response_schema['decimal2']['multipleOf'] == .0001
<add> assert properties['decimal2']['type'] == 'number'
<add> assert properties['decimal2']['multipleOf'] == .0001
<ide>
<del> assert response_schema['email']['type'] == 'string'
<del> assert response_schema['email']['format'] == 'email'
<del> assert response_schema['email']['default'] == 'foo@bar.com'
<add> assert properties['email']['type'] == 'string'
<add> assert properties['email']['format'] == 'email'
<add> assert properties['email']['default'] == 'foo@bar.com'
<ide>
<del> assert response_schema['url']['type'] == 'string'
<del> assert response_schema['url']['nullable'] is True
<del> assert response_schema['url']['default'] == 'http://www.example.com'
<add> assert properties['url']['type'] == 'string'
<add> assert properties['url']['nullable'] is True
<add> assert properties['url']['default'] == 'http://www.example.com'
<ide>
<del> assert response_schema['uuid']['type'] == 'string'
<del> assert response_schema['uuid']['format'] == 'uuid'
<add> assert properties['uuid']['type'] == 'string'
<add> assert properties['uuid']['format'] == 'uuid'
<ide>
<del> assert response_schema['ip4']['type'] == 'string'
<del> assert response_schema['ip4']['format'] == 'ipv4'
<add> assert properties['ip4']['type'] == 'string'
<add> assert properties['ip4']['format'] == 'ipv4'
<ide>
<del> assert response_schema['ip6']['type'] == 'string'
<del> assert response_schema['ip6']['format'] == 'ipv6'
<add> assert properties['ip6']['type'] == 'string'
<add> assert properties['ip6']['format'] == 'ipv6'
<ide>
<del> assert response_schema['ip']['type'] == 'string'
<del> assert 'format' not in response_schema['ip']
<add> assert properties['ip']['type'] == 'string'
<add> assert 'format' not in properties['ip']
<ide>
<ide>
<ide> @pytest.mark.skipif(uritemplate is None, reason='uritemplate not installed.') | 2 |
Python | Python | add a new test for the gogrid lb driver | b8d3d379bb636631c299967bd36a9f4799e58e2a | <ide><path>test/loadbalancer/test_gogrid.py
<ide> import unittest
<ide> from urlparse import urlparse, parse_qsl
<ide>
<add>from libcloud.common.types import LibcloudError
<ide> from libcloud.loadbalancer.base import LoadBalancer, Member, Algorithm
<ide> from libcloud.loadbalancer.drivers.gogrid import GoGridLBDriver
<ide>
<ide> def test_create_balancer(self):
<ide> self.assertEquals(balancer.name, 'test2')
<ide> self.assertEquals(balancer.id, '123')
<ide>
<add> def test_create_balancer_UNEXPECTED_ERROR(self):
<add> # Try to create new balancer and attach members with an IP address which
<add> # does not belong to this account
<add> GoGridLBMockHttp.type = 'UNEXPECTED_ERROR'
<add>
<add> try:
<add> self.driver.create_balancer(name='test2',
<add> port=80,
<add> protocol='http',
<add> algorithm=Algorithm.ROUND_ROBIN,
<add> members=(Member(None, '10.1.0.10', 80),
<add> Member(None, '10.1.0.11', 80))
<add> )
<add> except LibcloudError, e:
<add> self.assertTrue(str(e).find('tried to add a member with an IP address not assigned to your account') != -1)
<add> else:
<add> self.fail('Exception was not thrown')
<add>
<ide> def test_destroy_balancer(self):
<ide> balancer = self.driver.list_balancers()[0]
<ide>
<ide> def _api_grid_loadbalancer_add(self, method, url, body, headers):
<ide> body = self.fixtures.load('loadbalancer_add.json')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<add> def _api_grid_ip_list_UNEXPECTED_ERROR(self, method, url, body, headers):
<add> return self._api_grid_ip_list(method, url, body, headers)
<add>
<add> def _api_grid_loadbalancer_add_UNEXPECTED_ERROR(self, method, url, body, headers):
<add> body = self.fixtures.load('unexpected_error.json')
<add> return (httplib.INTERNAL_SERVER_ERROR, body, {}, httplib.responses[httplib.OK])
<add>
<ide> def _api_grid_loadbalancer_delete(self, method, url, body, headers):
<ide> body = self.fixtures.load('loadbalancer_add.json')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) | 1 |
Text | Text | fix intended parameter name | 1e8af643e3ebb63444e49a213f5480508bb8d8e0 | <ide><path>docs/advanced/AsyncActions.md
<ide> store.dispatch(selectReddit('reactjs'));
<ide>
<ide> store.dispatch(requestPosts('reactjs'));
<ide> fetch(`http://www.reddit.com/r/${reddit}.json`)
<del> .then(req => req.json())
<add> .then(response => response.json())
<ide> .then(json =>
<ide> store.dispatch(receivePosts(reddit, json))
<ide> )
<ide> export function fetchPosts(reddit) {
<ide> // Return a promise to wait for
<ide> // (this is not required by thunk middleware, but it is convenient for us)
<ide> return fetch(`http://www.reddit.com/r/${reddit}.json`)
<del> .then(req => req.json())
<add> .then(response => response.json())
<ide> .then(json =>
<ide> // We can dispatch many times!
<ide> dispatch(receivePosts(reddit, json))
<ide> function fetchPosts(reddit) {
<ide> return dispatch => {
<ide> dispatch(requestPosts(reddit));
<ide> return fetch(`http://www.reddit.com/r/${reddit}.json`)
<del> .then(req => req.json())
<add> .then(response => response.json())
<ide> .then(json => dispatch(receivePosts(reddit, json)));
<ide> };
<ide> } | 1 |
Javascript | Javascript | remove legacy www config from rollup build | 529e58ab0a62ed22be9b40bbe44a6ac1b2c89cfe | <ide><path>scripts/rollup/build.js
<ide> async function createBundle(bundle, bundleType) {
<ide> bundle.moduleType,
<ide> pureExternalModules
<ide> ),
<del> // We can't use getters in www.
<del> legacy:
<del> bundleType === FB_WWW_DEV ||
<del> bundleType === FB_WWW_PROD ||
<del> bundleType === FB_WWW_PROFILING,
<ide> };
<ide> const [mainOutputPath, ...otherOutputPaths] = Packaging.getBundleOutputPaths(
<ide> bundleType, | 1 |
Javascript | Javascript | use absolute path for auth0 callback | 0e0bebed4a9f61bc454b91fa6a4fc4d961630393 | <ide><path>api-server/server/passport-providers.js
<ide> import { auth0 } from '../../config/secrets';
<del>import { homeLocation } from '../../config/env';
<add>import { homeLocation, apiLocation } from '../../config/env';
<ide>
<ide> const { clientID, clientSecret, domain } = auth0;
<ide>
<ide> const successRedirect = `${homeLocation}/welcome`;
<del>const failureRedirect = '/signin';
<add>const failureRedirect = `${homeLocation}/signin`;
<ide>
<ide> export default {
<ide> devlogin: {
<ide> export default {
<ide> clientID,
<ide> clientSecret,
<ide> domain,
<del> cookieDomain: 'freeCodeCamp.org',
<del> callbackURL: '/auth/auth0/callback',
<add> cookieDomain: process.env.COOKIE_DOMAIN || 'localhost',
<add> callbackURL: `${apiLocation}/auth/auth0/callback`,
<ide> authPath: '/auth/auth0',
<ide> callbackPath: '/auth/auth0/callback',
<ide> useCustomCallback: true, | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.