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 |
|---|---|---|---|---|---|
Text | Text | remove view system docs. they are mis-information | 982346b1427db257d2565541187386e26c3af0a0 | <ide><path>docs/advanced/view-system.md
<del>## Atom's View System
<del>
<del>### SpacePen Basics
<del>
<del>Atom's view system is built around the [SpacePen] view framework. SpacePen
<del>view objects inherit from the jQuery prototype, and wrap DOM nodes
<del>
<del>View objects are actually jQuery wrappers around DOM fragments, supporting all
<del>the typical jQuery traversal and manipulation methods. In addition, view objects
<del>have methods that are view-specific. For example, you could call both general
<del>and view-specific on the global `atom.workspaceView` instance:
<del>
<del>```coffeescript
<del>atom.workspaceView.find('atom-text-editor.active') # standard jQuery method
<del>atom.workspaceView.getActiveEditor() # view-specific method
<del>```
<del>
<del>If you retrieve a jQuery wrapper for an element associated with a view, use the
<del>`.view()` method to retrieve the element's view object:
<del>
<del>```coffeescript
<del># this is a plain jQuery object; you can't call view-specific methods
<del>editorElement = atom.workspaceView.find('atom-text-editor.active')
<del>
<del># get the view object by calling `.view()` to call view-specific methods
<del>editorView = editorElement.view()
<del>editorView.setCursorBufferPosition([1, 2])
<del>```
<del>
<del>Refer to the [SpacePen] documentation for more details.
<del>
<del>### WorkspaceView
<del>
<del>The root of Atom's view hierarchy is a global called `atom.workspaceView`, which is a
<del>singleton instance of the `WorkspaceView` view class. The root view fills the entire
<del>window, and contains every other view. If you open Atom's inspector with
<del>`alt-cmd-i`, you can see the internal structure of `WorkspaceView`:
<del>
<del>![WorkspaceView in the inspector][workspaceview-inspector]
<del>
<del>#### Panes
<del>
<del>The `WorkspaceView` contains `prependToBottom/Top/Left/Right` and
<del>`appendToBottom/Top/Left/Right` methods, which are used to add Tool Panels. Tool
<del>panels are elements that take up screen real estate not devoted to text editing.
<del>In the example above, the `TreeView` is appended to the left, and the
<del>`CommandPanel` is appended to the top.
<del>
<del>```coffeescript
<del># place a view to the left of the panes
<del>atom.workspaceView.appendToLeft(new MyView)
<del>
<del># place a view below the panes
<del>atom.workspaceView.appendToBottom(new MyOtherView)
<del>```
<del>
<del>[spacepen]: http://github.com/nathansobo/space-pen
<del>[workspaceView-inspector]: https://f.cloud.github.com/assets/1424/1091631/1932c2d6-166b-11e3-8adf-9690fe82d3b8.png
<ide><path>docs/index.md
<ide> * [Developing Node Modules](advanced/node-modules.md)
<ide> * [Keymaps](advanced/keymaps.md)
<ide> * [Serialization](advanced/serialization.md)
<del>* [View System](advanced/view-system.md)
<ide> * [Scopes and Scope Descriptors](advanced/scopes-and-scope-descriptors.md)
<ide>
<ide> ### Upgrading to 1.0 APIs | 2 |
Python | Python | add regression test for #768 | 0967eb07bea28d84bac696de2c5ea6630424d92a | <ide><path>spacy/tests/regression/test_issue768.py
<add># coding: utf-8
<add>from __future__ import unicode_literals
<add>
<add>from ...language import Language
<add>from ...attrs import LANG
<add>from ...fr.language_data import TOKENIZER_EXCEPTIONS, STOP_WORDS
<add>from ...language_data.punctuation import TOKENIZER_INFIXES, ALPHA
<add>
<add>import pytest
<add>
<add>
<add>@pytest.fixture
<add>def fr_tokenizer_w_infix():
<add> SPLIT_INFIX = r'(?<=[{a}]\')(?=[{a}])'.format(a=ALPHA)
<add>
<add> # create new Language subclass to add to default infixes
<add> class French(Language):
<add> lang = 'fr'
<add>
<add> class Defaults(Language.Defaults):
<add> lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
<add> lex_attr_getters[LANG] = lambda text: 'fr'
<add> tokenizer_exceptions = TOKENIZER_EXCEPTIONS
<add> stop_words = STOP_WORDS
<add> infixes = TOKENIZER_INFIXES + [SPLIT_INFIX]
<add>
<add> return French.Defaults.create_tokenizer()
<add>
<add>
<add>@pytest.mark.parametrize('text,expected_tokens', [("l'avion", ["l'", "avion"]),
<add> ("j'ai", ["j'", "ai"])])
<add>def test_issue768(fr_tokenizer_w_infix, text, expected_tokens):
<add> """Allow zero-width 'infix' token during the tokenization process."""
<add> tokens = fr_tokenizer_w_infix(text)
<add> assert len(tokens) == 2
<add> assert [t.text for t in tokens] == expected_tokens | 1 |
Python | Python | add tests for divmod | 18aeffd93797df872539a9bd16efa4f67887f568 | <ide><path>numpy/core/tests/test_multiarray.py
<ide> def test_int_subclassing(self):
<ide> numpy_int = np.int_(0)
<ide>
<ide> if sys.version_info[0] >= 3:
<del> # On Py3k int_ should not inherit from int, because it's not fixed-width anymore
<add> # On Py3k int_ should not inherit from int, because it's not
<add> # fixed-width anymore
<ide> assert_equal(isinstance(numpy_int, int), False)
<ide> else:
<ide> # Otherwise, it should inherit from int...
<ide> def test_set_stridesattr(self):
<ide>
<ide> def make_array(size, offset, strides):
<ide> try:
<del> r = np.ndarray([size], dtype=int, buffer=x, offset=offset*x.itemsize)
<add> r = np.ndarray([size], dtype=int, buffer=x,
<add> offset=offset*x.itemsize)
<ide> except:
<ide> raise RuntimeError(getexception())
<ide> r.strides = strides = strides*x.itemsize
<ide> def test_conjugate(self):
<ide> assert_raises(AttributeError, lambda: a.conj())
<ide> assert_raises(AttributeError, lambda: a.conjugate())
<ide>
<add> def test_divmod_basic(self):
<add> dt = np.typecodes['AllInteger'] + np.typecodes['Float']
<add> for dt1, dt2 in itertools.product(dt, dt):
<add> for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
<add> if sg1 == -1 and dt1 in np.typecodes['UnsignedInteger']:
<add> continue
<add> if sg2 == -1 and dt2 in np.typecodes['UnsignedInteger']:
<add> continue
<add> fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s'
<add> msg = fmt % (dt1, dt2, sg1, sg2)
<add> a = np.array(sg1*71, dtype=dt1)
<add> b = np.array(sg2*19, dtype=dt2)
<add> div, rem = divmod(a, b)
<add> assert_allclose(div*b + rem, a, err_msg=msg)
<add> if sg2 == -1:
<add> assert_(b < rem <= 0, msg)
<add> else:
<add> assert_(b > rem >= 0, msg)
<add>
<add> def test_divmod_roundoff(self):
<add> # gh-6127
<add> dt = 'fdg'
<add> for dt1, dt2 in itertools.product(dt, dt):
<add> for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
<add> fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s'
<add> msg = fmt % (dt1, dt2, sg1, sg2)
<add> a = np.array(sg1*78*6e-8, dtype=dt1)
<add> b = np.array(sg2*6e-8, dtype=dt2)
<add> div, rem = divmod(a, b)
<add> assert_allclose(div*b + rem, a, err_msg=msg)
<add> if sg2 == -1:
<add> assert_(b < rem <= 0, msg)
<add> else:
<add> assert_(b > rem >= 0, msg)
<add>
<ide>
<ide> class TestBinop(object):
<ide> def test_inplace(self):
<ide><path>numpy/core/tests/test_scalarmath.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> import sys
<add>import itertools
<ide>
<ide> import numpy as np
<ide> from numpy.testing.utils import _gen_alignment_data
<ide> from numpy.testing import (
<ide> TestCase, run_module_suite, assert_, assert_equal, assert_raises,
<del> assert_almost_equal
<add> assert_almost_equal, assert_allclose
<ide> )
<ide>
<ide> types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc,
<ide> def test_mixed_types(self):
<ide> else:
<ide> assert_almost_equal(result, 9, err_msg=msg)
<ide>
<add>
<add>class TestDivmod(TestCase):
<add> def test_divmod_basic(self):
<add> dt = np.typecodes['AllInteger'] + np.typecodes['Float']
<add> for dt1, dt2 in itertools.product(dt, dt):
<add> for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
<add> if sg1 == -1 and dt1 in np.typecodes['UnsignedInteger']:
<add> continue
<add> if sg2 == -1 and dt2 in np.typecodes['UnsignedInteger']:
<add> continue
<add> fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s'
<add> msg = fmt % (dt1, dt2, sg1, sg2)
<add> a = np.array(sg1*71, dtype=dt1)[()]
<add> b = np.array(sg2*19, dtype=dt2)[()]
<add> div, rem = divmod(a, b)
<add> assert_allclose(div*b + rem, a, err_msg=msg)
<add> if sg2 == -1:
<add> assert_(b < rem <= 0, msg)
<add> else:
<add> assert_(b > rem >= 0, msg)
<add>
<add> def test_divmod_roundoff(self):
<add> # gh-6127
<add> dt = 'fdg'
<add> for dt1, dt2 in itertools.product(dt, dt):
<add> for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
<add> fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s'
<add> msg = fmt % (dt1, dt2, sg1, sg2)
<add> a = np.array(sg1*78*6e-8, dtype=dt1)[()]
<add> b = np.array(sg2*6e-8, dtype=dt2)[()]
<add> div, rem = divmod(a, b)
<add> assert_allclose(div*b + rem, a, err_msg=msg)
<add> if sg2 == -1:
<add> assert_(b < rem <= 0, msg)
<add> else:
<add> assert_(b > rem >= 0, msg)
<add>
<add>
<ide> class TestComplexDivision(TestCase):
<ide> def test_zero_division(self):
<ide> with np.errstate(all="ignore"): | 2 |
Javascript | Javascript | update basic tests | 1122abef59a1f957ab5f838029b5731a869b5a99 | <ide><path>packages/ember-application/tests/system/logging_test.js
<ide> module("Ember.Application – logging of generated classes", {
<ide> function visit(path) {
<ide> stop();
<ide>
<del> var promise = new Ember.RSVP.Promise(function(resolve, reject){
<del> var router = App.__container__.lookup('router:main');
<del>
<del> Ember.run(App, 'handleURL', path);
<del> Ember.run(router, router.location.setURL, path);
<del>
<del> Ember.run(resolve);
<del> start();
<add> var promise = Ember.run(function(){
<add> return new Ember.RSVP.Promise(function(resolve, reject){
<add> var router = App.__container__.lookup('router:main');
<add>
<add> resolve(router.handleURL(path).then(function(value){
<add> start();
<add> ok(true, 'visited: `' + path + '`');
<add> return value;
<add> }, function(reason) {
<add> start();
<add> ok(false, 'failed to visit:`' + path + '` reason: `' + QUnit.jsDump.parse(reason));
<add> throw reason;
<add> }));
<add> });
<ide> });
<ide>
<ide> return {
<ide><path>packages/ember/tests/routing/basic_test.js
<ide> function compile(string) {
<ide> return Ember.Handlebars.compile(string);
<ide> }
<ide>
<add>function handleURL(path) {
<add> return Ember.run(function() {
<add> return router.handleURL(path).then(function(value) {
<add> ok(true, 'url: `' + path + '` was handled');
<add> return value;
<add> }, function(reason) {
<add> ok(false, 'failed to visit:`' + path + '` reason: `' + QUnit.jsDump.parse(reason));
<add> throw reason;
<add> });
<add> });
<add>}
<add>
<add>function handleURLAborts(path) {
<add> Ember.run(function() {
<add> router.handleURL(path).then(function(value) {
<add> ok(false, 'url: `' + path + '` was NOT to be handled');
<add> }, function(reason) {
<add> ok(reason && reason.message === "TransitionAborted", 'url: `' + path + '` was to be aborted');
<add> });
<add> });
<add>}
<add>
<add>
<add>
<add>function handleURLRejectsWith(path, expectedReason) {
<add> Ember.run(function() {
<add> router.handleURL(path).then(function(value) {
<add> ok(false, 'expected handleURLing: `' + path + '` to fail');
<add> }, function(reason) {
<add> equal(expectedReason, reason);
<add> });
<add> });
<add>}
<add>
<ide> module("Basic Routing", {
<ide> setup: function() {
<ide> Ember.run(function() {
<ide> test("The Homepage", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(currentPath, 'home');
<ide> equal(Ember.$('h3:contains(Hours)', '#qunit-fixture').length, 1, "The home template was rendered");
<ide> test("The Home page and the Camelot page with multiple Router.map calls", functi
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/camelot");
<del> });
<add> handleURL("/camelot");
<ide>
<ide> equal(currentPath, 'camelot');
<ide> equal(Ember.$('h3:contains(silly)', '#qunit-fixture').length, 1, "The camelot template was rendered");
<ide>
<del>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL("/");
<ide>
<ide> equal(currentPath, 'home');
<ide> equal(Ember.$('h3:contains(Hours)', '#qunit-fixture').length, 1, "The home template was rendered");
<ide> test("The Homepage register as activeView", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> ok(router._lookupActiveView('home'), '`home` active view is connected');
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/homepage");
<del> });
<add> handleURL('/homepage');
<ide>
<ide> ok(router._lookupActiveView('homepage'), '`homepage` active view is connected');
<ide> equal(router._lookupActiveView('home'), undefined, '`home` active view is disconnected');
<ide> test("The Homepage with explicit template name in renderTemplate", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(Ember.$('h3:contains(Megatroll)', '#qunit-fixture').length, 1, "The homepage template was rendered");
<ide> });
<ide> test("An alternate template will pull in an alternate controller", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(Ember.$('h3:contains(Megatroll) + p:contains(Comes from homepage)', '#qunit-fixture').length, 1, "The homepage template was rendered");
<ide> });
<ide> test("The template will pull in an alternate controller via key/value", function
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(Ember.$('h3:contains(Megatroll) + p:contains(Comes from home.)', '#qunit-fixture').length, 1, "The homepage template was rendered from data from the HomeController");
<ide> });
<ide> test("The Homepage with explicit template name in renderTemplate and controller"
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(Ember.$('h3:contains(Megatroll) + p:contains(YES I AM HOME)', '#qunit-fixture').length, 1, "The homepage template was rendered");
<ide> });
<ide> test("Renders correct view with slash notation", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(Ember.$('p:contains(Home/Page)', '#qunit-fixture').length, 1, "The homepage template was rendered");
<ide> });
<ide> test('render does not replace templateName if user provided', function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(Ember.$('p', '#qunit-fixture').text(), "THIS IS THE REAL HOME", "The homepage template was rendered");
<ide> });
<ide> test("The Homepage with a `setupController` hook", function() {
<ide>
<ide> container.register('controller:home', Ember.Controller.extend());
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(Ember.$('ul li', '#qunit-fixture').eq(2).text(), "Sunday: Noon to 6pm", "The template was rendered with the hours context");
<ide> });
<ide> test("The Homepage with a `setupController` hook modifying other controllers", f
<ide>
<ide> container.register('controller:home', Ember.Controller.extend());
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(Ember.$('ul li', '#qunit-fixture').eq(2).text(), "Sunday: Noon to 6pm", "The template was rendered with the hours context");
<ide> });
<ide> test("The Homepage with a computed context that does not get overridden", functi
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(Ember.$('ul li', '#qunit-fixture').eq(2).text(), "Sunday: Noon to 6pm", "The template was rendered with the context intact");
<ide> });
<ide> test("The Homepage getting its controller context via model", function() {
<ide>
<ide> container.register('controller:home', Ember.Controller.extend());
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(Ember.$('ul li', '#qunit-fixture').eq(2).text(), "Sunday: Noon to 6pm", "The template was rendered with the hours context");
<ide> });
<ide> test("The Specials Page getting its controller context by deserializing the para
<ide>
<ide> container.register('controller:special', Ember.Controller.extend());
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/specials/1");
<del> });
<add> handleURL("/specials/1");
<ide>
<ide> equal(Ember.$('p', '#qunit-fixture').text(), "1", "The model was used to render the template");
<ide> });
<ide> test("The Specials Page defaults to looking models up via `find`", function() {
<ide> });
<ide>
<ide> App.MenuItem = Ember.Object.extend();
<del> App.MenuItem.find = function(id) {
<del> return Ember.Object.create({
<del> id: id
<del> });
<del> };
<add> App.MenuItem.reopenClass({
<add> find: function(id) {
<add> return App.MenuItem.create({
<add> id: id
<add> });
<add> }
<add> });
<ide>
<ide> App.SpecialRoute = Ember.Route.extend({
<ide> setupController: function(controller, model) {
<ide> test("The Specials Page defaults to looking models up via `find`", function() {
<ide>
<ide> container.register('controller:special', Ember.Controller.extend());
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/specials/1");
<del> });
<add> handleURL("/specials/1");
<ide>
<ide> equal(Ember.$('p', '#qunit-fixture').text(), "1", "The model was used to render the template");
<ide> });
<ide> test("The Special Page returning a promise puts the app into a loading state unt
<ide> var menuItem;
<ide>
<ide> App.MenuItem = Ember.Object.extend(Ember.DeferredMixin);
<del> App.MenuItem.find = function(id) {
<del> menuItem = App.MenuItem.create({ id: id });
<del> return menuItem;
<del> };
<add> App.MenuItem.reopenClass({
<add> find: function(id) {
<add> menuItem = App.MenuItem.create({
<add> id: id
<add> });
<add>
<add> return menuItem;
<add> }
<add> });
<ide>
<ide> App.LoadingRoute = Ember.Route.extend({
<ide>
<ide> test("The Special Page returning a promise puts the app into a loading state unt
<ide>
<ide> container.register('controller:special', Ember.Controller.extend());
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/specials/1");
<del> });
<add> handleURL("/specials/1");
<ide>
<ide> equal(Ember.$('p', '#qunit-fixture').text(), "LOADING!", "The app is in the loading state");
<ide>
<ide> test("The loading state doesn't get entered for promises that resolve on the sam
<ide> this.resource("special", { path: "/specials/:menu_item_id" });
<ide> });
<ide>
<del> var menuItem;
<del>
<del> App.MenuItem = Ember.Object.extend(Ember.DeferredMixin);
<del> App.MenuItem.find = function(id) {
<del> menuItem = { id: 1 };
<del> return menuItem;
<del> };
<add> App.MenuItem = Ember.Object.extend();
<add> App.MenuItem.reopenClass({
<add> find: function(id) {
<add> return { id: id };
<add> }
<add> });
<ide>
<ide> App.LoadingRoute = Ember.Route.extend({
<ide> enter: function() {
<ide> test("The loading state doesn't get entered for promises that resolve on the sam
<ide>
<ide> container.register('controller:special', Ember.Controller.extend());
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/specials/1");
<del> });
<add> handleURL("/specials/1");
<ide>
<ide> equal(Ember.$('p', '#qunit-fixture').text(), "1", "The app is now in the specials state");
<ide> });
<ide> asyncTest("The Special page returning an error fires the error hook on SpecialRo
<ide> var menuItem;
<ide>
<ide> App.MenuItem = Ember.Object.extend(Ember.DeferredMixin);
<del> App.MenuItem.find = function(id) {
<del> menuItem = App.MenuItem.create({ id: id });
<del>
<del> Ember.run.later(function() { menuItem.resolve(menuItem); }, 1);
<del>
<del> return menuItem;
<del> };
<add> App.MenuItem.reopenClass({
<add> find: function(id) {
<add> menuItem = App.MenuItem.create({ id: id });
<add> Ember.run.later(function() { menuItem.resolve(menuItem); }, 1);
<add> return menuItem;
<add> }
<add> });
<ide>
<ide> App.SpecialRoute = Ember.Route.extend({
<ide> setup: function() {
<ide> asyncTest("The Special page returning an error fires the error hook on SpecialRo
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/specials/1");
<del> });
<del>
<add> handleURLRejectsWith('/specials/1', 'Setup error');
<ide> });
<ide>
<ide> asyncTest("The Special page returning an error invokes SpecialRoute's error handler", function() {
<ide> asyncTest("The Special page returning an error invokes SpecialRoute's error hand
<ide> var menuItem;
<ide>
<ide> App.MenuItem = Ember.Object.extend(Ember.DeferredMixin);
<del> App.MenuItem.find = function(id) {
<del> menuItem = App.MenuItem.create({ id: id });
<del> Ember.run.later(function() {
<del> menuItem.resolve(menuItem);
<del> }, 1);
<del> return menuItem;
<del> };
<add> App.MenuItem.reopenClass({
<add> find: function(id) {
<add> menuItem = App.MenuItem.create({ id: id });
<add> Ember.run.later(function() {
<add> menuItem.resolve(menuItem);
<add> }, 1);
<add> return menuItem;
<add> }
<add> });
<ide>
<ide> App.SpecialRoute = Ember.Route.extend({
<ide> setup: function() {
<ide> asyncTest("The Special page returning an error invokes SpecialRoute's error hand
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/specials/1");
<del> });
<add> handleURLRejectsWith('/specials/1', 'Setup error');
<ide> });
<ide>
<ide> asyncTest("ApplicationRoute's default error handler can be overridden", function() {
<ide> asyncTest("ApplicationRoute's default error handler can be overridden", function
<ide> var menuItem;
<ide>
<ide> App.MenuItem = Ember.Object.extend(Ember.DeferredMixin);
<del> App.MenuItem.find = function(id) {
<del> menuItem = App.MenuItem.create({ id: id });
<del> Ember.run.later(function() {
<del> menuItem.resolve(menuItem);
<del> }, 1);
<del> return menuItem;
<del> };
<add> App.MenuItem.reopenClass({
<add> find: function(id) {
<add> menuItem = App.MenuItem.create({ id: id });
<add> Ember.run.later(function() {
<add> menuItem.resolve(menuItem);
<add> }, 1);
<add> return menuItem;
<add> }
<add> });
<ide>
<ide> App.ApplicationRoute = Ember.Route.extend({
<ide> events: {
<ide> asyncTest("ApplicationRoute's default error handler can be overridden", function
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/specials/1");
<del> });
<add> handleURLRejectsWith("/specials/1", "Setup error");
<ide> });
<ide>
<ide> asyncTest("Moving from one page to another triggers the correct callbacks", function() {
<del>
<del> expect(2);
<add> expect(3);
<ide>
<ide> Router.map(function() {
<ide> this.route("home", { path: "/" });
<ide> asyncTest("Moving from one page to another triggers the correct callbacks", func
<ide>
<ide> container.register('controller:special', Ember.Controller.extend());
<ide>
<add> var transition = handleURL('/');
<add>
<ide> Ember.run(function() {
<del> router.handleURL("/").then(function() {
<add> transition.then(function() {
<ide> equal(Ember.$('h3', '#qunit-fixture').text(), "Home", "The app is now in the initial state");
<ide>
<ide> var promiseContext = App.MenuItem.create({ id: 1 });
<ide> asyncTest("Nested callbacks are not exited when moving to siblings", function()
<ide> var menuItem;
<ide>
<ide> App.MenuItem = Ember.Object.extend(Ember.DeferredMixin);
<del> App.MenuItem.find = function(id) {
<del> menuItem = App.MenuItem.create({ id: id });
<del> return menuItem;
<del> };
<add> App.MenuItem.reopenClass({
<add> find: function(id) {
<add> menuItem = App.MenuItem.create({ id: id });
<add> return menuItem;
<add> }
<add> });
<ide>
<ide> App.LoadingRoute = Ember.Route.extend({
<ide>
<ide> asyncTest("Nested callbacks are not exited when moving to siblings", function()
<ide>
<ide> var rootSetup = 0, rootRender = 0, rootModel = 0, rootSerialize = 0;
<ide>
<del> Ember.run(function() {
<del> bootApplication();
<del> });
<add> bootApplication();
<ide>
<ide> container.register('controller:special', Ember.Controller.extend());
<ide>
<ide> asyncTest("Nested callbacks are not exited when moving to siblings", function()
<ide> router = container.lookup('router:main');
<ide>
<ide> Ember.run(function() {
<del>
<ide> var menuItem = App.MenuItem.create({ id: 1 });
<ide> Ember.run.later(function() { menuItem.resolve(menuItem); }, 1);
<ide>
<ide> asyncTest("Nested callbacks are not exited when moving to siblings", function()
<ide>
<ide> deepEqual(router.location.path, '/specials/1');
<ide> equal(currentPath, 'root.special');
<del>
<add>
<ide> start();
<ide> });
<ide> });
<ide> asyncTest("Events are triggered on the controller if a matching action name is i
<ide>
<ide> bootApplication();
<ide>
<del>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> var actionId = Ember.$("#qunit-fixture a").data("ember-action");
<ide> var action = Ember.Handlebars.ActionHelper.registeredActions[actionId];
<ide> asyncTest("Events are triggered on the current state", function() {
<ide> //var controller = router._container.controller.home = Ember.Controller.create();
<ide> //controller.target = router;
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> var actionId = Ember.$("#qunit-fixture a").data("ember-action");
<ide> var action = Ember.Handlebars.ActionHelper.registeredActions[actionId];
<ide> test("transitioning multiple times in a single run loop only sets the URL once",
<ide> set(this, 'path', path);
<ide> };
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(urlSetCount, 0);
<ide>
<ide> test('navigating away triggers a url property change', function() {
<ide>
<ide> equal(urlPropertyChangeCount, 0);
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/").then(function() {
<add> var transition = handleURL("/");
<add>
<add> Ember.run(function(){
<add> transition.then(function() {
<ide> equal(urlPropertyChangeCount, 2);
<ide>
<ide> // Trigger the callback that would otherwise be triggered
<ide> test("using replaceWith calls location.replaceURL if available", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(setCount, 0);
<ide> equal(replaceCount, 0);
<ide> test("using replaceWith calls setURL if location.replaceURL is not defined", fun
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL('/');
<ide>
<ide> equal(setCount, 0);
<ide>
<ide> test("using replaceWith calls setURL if location.replaceURL is not defined", fun
<ide> });
<ide>
<ide> test("It is possible to get the model from a parent route", function() {
<del> expect(6);
<add> expect(9);
<ide>
<ide> Router.map(function() {
<ide> this.resource("the_post", { path: "/posts/:post_id" }, function() {
<ide> test("It is possible to get the model from a parent route", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> currentPost = post1;
<del> router.handleURL("/posts/1/comments");
<del> });
<add> currentPost = post1;
<add> handleURL("/posts/1/comments");
<ide>
<del> Ember.run(function() {
<del> currentPost = post2;
<del> router.handleURL("/posts/2/comments");
<del> });
<add> currentPost = post2;
<add> handleURL("/posts/2/comments");
<ide>
<del> Ember.run(function() {
<del> currentPost = post3;
<del> router.handleURL("/posts/3/comments");
<del> });
<add> currentPost = post3;
<add> handleURL("/posts/3/comments");
<ide> });
<ide>
<ide> test("A redirection hook is provided", function() {
<ide> test("A redirection hook is provided", function() {
<ide> });
<ide>
<ide> test("Redirecting from the middle of a route aborts the remainder of the routes", function() {
<del> expect(2);
<add> expect(3);
<ide>
<ide> Router.map(function() {
<ide> this.route("home");
<ide> test("Redirecting from the middle of a route aborts the remainder of the routes"
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/foo/bar/baz");
<del> });
<add> handleURLAborts("/foo/bar/baz");
<ide>
<ide> equal(router.container.lookup('controller:application').get('currentPath'), 'home');
<ide> equal(router.get('location').getURL(), "/home");
<ide> });
<ide>
<ide> test("Redirecting to the current target in the middle of a route does not abort initial routing", function() {
<del> expect(4);
<add> expect(5);
<ide>
<ide> Router.map(function() {
<ide> this.route("home");
<ide> test("Redirecting to the current target in the middle of a route does not abort
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/foo/bar/baz");
<del> });
<add> handleURL("/foo/bar/baz");
<ide>
<ide> equal(router.container.lookup('controller:application').get('currentPath'), 'foo.bar.baz');
<ide> equal(successCount, 1, 'transitionTo success handler was called once');
<ide>
<ide> });
<ide>
<ide> test("Redirecting to the current target with a different context aborts the remainder of the routes", function() {
<del> expect(3);
<add> expect(4);
<ide>
<ide> Router.map(function() {
<ide> this.route("home");
<ide> test("Redirecting to the current target with a different context aborts the rema
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/foo/bar/1/baz");
<del> });
<add> handleURLAborts("/foo/bar/1/baz");
<ide>
<ide> equal(router.container.lookup('controller:application').get('currentPath'), 'foo.bar.baz');
<ide> equal(router.get('location').getURL(), "/foo/bar/2/baz");
<ide> test("Transitioning from a parent event does not prevent currentPath from being
<ide>
<ide> var applicationController = router.container.lookup('controller:application');
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/foo/bar/baz");
<del> });
<add> handleURL("/foo/bar/baz");
<ide>
<ide> equal(applicationController.get('currentPath'), 'foo.bar.baz');
<ide>
<ide> test("Transitioning from a parent event does not prevent currentPath from being
<ide> });
<ide>
<ide> test("Generated names can be customized when providing routes with dot notation", function() {
<del> expect(3);
<add> expect(4);
<ide>
<ide> Ember.TEMPLATES.index = compile("<div>Index</div>");
<ide> Ember.TEMPLATES.application = compile("<h1>Home</h1><div class='main'>{{outlet}}</div>");
<ide> test("Generated names can be customized when providing routes with dot notation"
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/top/middle/bottom");
<del> });
<add> handleURL("/top/middle/bottom");
<ide>
<ide> equal(Ember.$('.main .middle .bottom p', '#qunit-fixture').text(), "BarBazBottom!", "The templates were rendered into their appropriate parents");
<ide> });
<ide> test("Child routes render into their parent route's template by default", functi
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/top/middle/bottom");
<del> });
<add> handleURL("/top/middle/bottom");
<ide>
<ide> equal(Ember.$('.main .middle .bottom p', '#qunit-fixture').text(), "Bottom!", "The templates were rendered into their appropriate parents");
<ide> });
<ide> test("Child routes render into specified template", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/top/middle/bottom");
<del> });
<add> handleURL("/top/middle/bottom");
<ide>
<ide> equal(Ember.$('.main .middle .bottom p', '#qunit-fixture').length, 0, "should not render into the middle template");
<ide> equal(Ember.$('.main .middle > p', '#qunit-fixture').text(), "Bottom!", "The template was rendered into the top template");
<ide> test("Rendering into specified template with slash notation", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL("/");
<ide>
<ide> equal(Ember.$('#qunit-fixture:contains(profile details!)').length, 1, "The templates were rendered");
<ide> });
<ide> test("Parent route context change", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/posts/1");
<del> });
<add> handleURL("/posts/1");
<ide>
<ide> Ember.run(function() {
<ide> router.send('editPost');
<ide> test("Only use route rendered into main outlet for default into property on chil
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/posts");
<del> });
<add> handleURL("/posts");
<ide>
<ide> equal(Ember.$('div.posts-menu:contains(postsMenu)', '#qunit-fixture').length, 1, "The posts/menu template was rendered");
<ide> equal(Ember.$('p.posts-index:contains(postsIndex)', '#qunit-fixture').length, 1, "The posts/index template was rendered");
<ide> test("Generating a URL should not affect currentModel", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/posts/1");
<del> });
<add> handleURL("/posts/1");
<ide>
<ide> var route = container.lookup('route:post');
<ide> equal(route.modelFor('post'), posts[1]);
<ide> test("Generated route should be an instance of App.Route if provided", function(
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/posts");
<del> });
<add> handleURL("/posts");
<ide>
<ide> generatedRoute = container.lookup('route:posts');
<ide>
<ide> test("Application template does not duplicate when re-rendered", function() {
<ide> bootApplication();
<ide>
<ide> // should cause application template to re-render
<del> Ember.run(function() {
<del> router.handleURL('/posts');
<del> });
<add> handleURL('/posts');
<ide>
<ide> equal(Ember.$('h3:contains(I Render Once)').size(), 1);
<ide> });
<ide> test("The template is not re-rendered when the route's context changes", functio
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/page/first");
<del> });
<add> handleURL("/page/first");
<ide>
<ide> equal(Ember.$('p', '#qunit-fixture').text(), "first");
<ide> equal(insertionCount, 1);
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/page/second");
<del> });
<add> handleURL("/page/second");
<ide>
<ide> equal(Ember.$('p', '#qunit-fixture').text(), "second");
<ide> equal(insertionCount, 1, "view should have inserted only once");
<ide> test("The template is not re-rendered when two routes present the exact same tem
<ide> App.SecondRoute = App.SharedRoute.extend();
<ide> App.ThirdRoute = App.SharedRoute.extend();
<ide> App.FourthRoute = App.SharedRoute.extend();
<del>
<add>
<ide> App.SharedController = Ember.Controller.extend();
<ide>
<ide> var insertionCount = 0;
<ide> test("The template is not re-rendered when two routes present the exact same tem
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/first");
<del> });
<add> handleURL("/first");
<ide>
<ide> equal(Ember.$('p', '#qunit-fixture').text(), "This is the first message");
<ide> equal(insertionCount, 1);
<ide>
<ide> // Transition by URL
<del> Ember.run(function() {
<del> router.handleURL("/second");
<del> });
<add> handleURL("/second");
<ide>
<ide> equal(Ember.$('p', '#qunit-fixture').text(), "This is the second message");
<ide> equal(insertionCount, 1, "view should have inserted only once");
<ide> test("The template is not re-rendered when two routes present the exact same tem
<ide>
<ide> equal(Ember.$('p', '#qunit-fixture').text(), "This is the third message");
<ide> equal(insertionCount, 1, "view should still have inserted only once");
<del>
<add>
<ide> // Lastly transition to a different view, with the same controller and template
<del> Ember.run(function() {
<del> router.handleURL("/fourth");
<del> });
<add> handleURL("/fourth");
<ide>
<ide> equal(Ember.$('p', '#qunit-fixture').text(), "This is the fourth message");
<ide> equal(insertionCount, 2, "view should have inserted a second time");
<del>
<add>
<ide> });
<ide>
<ide> test("ApplicationRoute with model does not proxy the currentPath", function() {
<ide> test("ApplicationRoute with model does not proxy the currentPath", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/");
<del> });
<add> handleURL("/");
<ide>
<ide> equal(currentPath, 'index', 'currentPath is index');
<ide> equal('currentPath' in model, false, 'should have defined currentPath on controller');
<ide> test("Route should tear down multiple outlets", function() {
<ide> tagName: 'p',
<ide> classNames: ['posts-index']
<ide> });
<del>
<add>
<ide> App.PostsFooterView = Ember.View.extend({
<ide> tagName: 'div',
<ide> templateName: 'posts/footer',
<ide> test("Route should tear down multiple outlets", function() {
<ide> into: 'application',
<ide> outlet: 'menu'
<ide> });
<del>
<add>
<ide> this.render();
<del>
<add>
<ide> this.render('postsFooter', {
<ide> into: 'application',
<ide> outlet: 'footer'
<ide> test("Route should tear down multiple outlets", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/posts");
<del> });
<add> handleURL('/posts');
<ide>
<ide> equal(Ember.$('div.posts-menu:contains(postsMenu)', '#qunit-fixture').length, 1, "The posts/menu template was rendered");
<ide> equal(Ember.$('p.posts-index:contains(postsIndex)', '#qunit-fixture').length, 1, "The posts/index template was rendered");
<ide> equal(Ember.$('div.posts-footer:contains(postsFooter)', '#qunit-fixture').length, 1, "The posts/footer template was rendered");
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/users");
<del> });
<del>
<add> handleURL('/users');
<add>
<ide> equal(Ember.$('div.posts-menu:contains(postsMenu)', '#qunit-fixture').length, 0, "The posts/menu template was removed");
<del> equal(Ember.$('p.posts-index:contains(postsIndex)', '#qunit-fixture').length, 0, "The posts/index template was removed");
<add> equal(Ember.$('p.posts-index:contains(postsIndex)', '#qunit-fixture').length, 0, "The posts/index template was removed");
<ide> equal(Ember.$('div.posts-footer:contains(postsFooter)', '#qunit-fixture').length, 0, "The posts/footer template was removed");
<del>
<add>
<ide> });
<ide>
<ide>
<ide> test("Route supports clearing outlet explicitly", function() {
<ide>
<ide> bootApplication();
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/posts");
<del> });
<add> handleURL('/posts');
<add>
<ide> equal(Ember.$('div.posts-index:contains(postsIndex)', '#qunit-fixture').length, 1, "The posts/index template was rendered");
<ide> Ember.run(function() {
<ide> router.send('showModal');
<ide> test("Route supports clearing outlet explicitly", function() {
<ide> });
<ide> equal(Ember.$('div.posts-extra:contains(postsExtra)', '#qunit-fixture').length, 0, "The posts/extra template was removed");
<ide>
<del> Ember.run(function() {
<del> router.handleURL("/users");
<del> });
<add> handleURL('/users');
<ide>
<ide> equal(Ember.$('div.posts-index:contains(postsIndex)', '#qunit-fixture').length, 0, "The posts/index template was removed");
<ide> equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 0, "The posts/modal template was removed");
<ide> equal(Ember.$('div.posts-extra:contains(postsExtra)', '#qunit-fixture').length, 0, "The posts/extra template was removed");
<ide> });
<ide>
<del> | 2 |
Ruby | Ruby | avoid extra scoping when using `relation#update` | c83e30da27eafde79164ecb376e8a28ccc8d841f | <ide><path>activerecord/lib/active_record/persistence.rb
<ide> def instantiate_instance_of(klass, attributes, column_types = {}, &block)
<ide> # When running callbacks is not needed for each record update,
<ide> # it is preferred to use {update_all}[rdoc-ref:Relation#update_all]
<ide> # for updating all records in a single query.
<del> def update(id = :all, attributes)
<add> def update(id, attributes)
<ide> if id.is_a?(Array)
<ide> id.map { |one_id| find(one_id) }.each_with_index { |object, idx|
<ide> object.update(attributes[idx])
<ide> }
<del> elsif id == :all
<del> all.each { |record| record.update(attributes) }
<ide> else
<ide> if ActiveRecord::Base === id
<ide> raise ArgumentError,
<ide><path>activerecord/lib/active_record/relation.rb
<ide> def update_all(updates)
<ide> @klass.connection.update stmt, "#{@klass} Update All"
<ide> end
<ide>
<add> def update(attributes) # :nodoc:
<add> each { |record| record.update(attributes) }
<add> end
<add>
<ide> def update_counters(counters) # :nodoc:
<ide> touch = counters.delete(:touch)
<ide>
<ide><path>activerecord/test/cases/relations_test.rb
<ide> class RelationTest < ActiveRecord::TestCase
<ide>
<ide> class TopicWithCallbacks < ActiveRecord::Base
<ide> self.table_name = :topics
<add> cattr_accessor :topic_count
<ide> before_update { |topic| topic.author_name = "David" if topic.author_name.blank? }
<add> after_update { |topic| topic.class.topic_count = topic.class.count }
<ide> end
<ide>
<ide> def test_do_not_double_quote_string_id
<ide> def test_update_on_relation
<ide> topics = TopicWithCallbacks.where(id: [topic1.id, topic2.id])
<ide> topics.update(title: "adequaterecord")
<ide>
<add> assert_equal TopicWithCallbacks.count, TopicWithCallbacks.topic_count
<add>
<ide> assert_equal "adequaterecord", topic1.reload.title
<ide> assert_equal "adequaterecord", topic2.reload.title
<ide> # Testing that the before_update callbacks have run | 3 |
Go | Go | sync minor changes between config and secret tests | 348f412d850eea85541e57f5545ae3719931da5a | <ide><path>integration/config/config_test.go
<ide> func TestConfigList(t *testing.T) {
<ide> defer d.Stop(t)
<ide> c := d.NewClientT(t)
<ide> defer c.Close()
<del>
<ide> ctx := context.Background()
<ide>
<ide> // This test case is ported from the original TestConfigsEmptyList
<ide> func TestConfigsCreateAndDelete(t *testing.T) {
<ide> defer d.Stop(t)
<ide> c := d.NewClientT(t)
<ide> defer c.Close()
<del>
<ide> ctx := context.Background()
<ide>
<ide> testName := "test_config-" + t.Name()
<ide> func TestConfigsUpdate(t *testing.T) {
<ide> defer d.Stop(t)
<ide> c := d.NewClientT(t)
<ide> defer c.Close()
<del>
<ide> ctx := context.Background()
<ide>
<ide> testName := "test_config-" + t.Name()
<del>
<del> // This test case is ported from the original TestConfigsCreate
<ide> configID := createConfig(ctx, t, c, testName, []byte("TESTINGDATA"), nil)
<ide>
<ide> insp, _, err := c.ConfigInspectWithRaw(ctx, configID)
<ide> func TestTemplatedConfig(t *testing.T) {
<ide> templatedConfig, err := c.ConfigCreate(ctx, configSpec)
<ide> assert.Check(t, err)
<ide>
<add> serviceName := "svc_" + t.Name()
<ide> serviceID := swarm.CreateService(t, d,
<ide> swarm.ServiceWithConfig(
<ide> &swarmtypes.ConfigReference{
<ide> File: &swarmtypes.ConfigReferenceFileTarget{
<del> Name: "/" + templatedConfigName,
<add> Name: "templated_config",
<ide> UID: "0",
<ide> GID: "0",
<ide> Mode: 0600,
<ide> func TestTemplatedConfig(t *testing.T) {
<ide> SecretName: referencedSecretName,
<ide> },
<ide> ),
<del> swarm.ServiceWithName("svc"),
<add> swarm.ServiceWithName(serviceName),
<ide> )
<ide>
<ide> poll.WaitOn(t, swarm.RunningTasksCount(c, serviceID, 1), swarm.ServicePoll, poll.WithTimeout(1*time.Minute))
<ide> func TestTemplatedConfig(t *testing.T) {
<ide> assert.Assert(t, len(tasks) > 0, "no running tasks found for service %s", serviceID)
<ide>
<ide> attach := swarm.ExecTask(t, d, tasks[0], types.ExecConfig{
<del> Cmd: []string{"/bin/cat", "/" + templatedConfigName},
<add> Cmd: []string{"/bin/cat", "/templated_config"},
<ide> AttachStdout: true,
<ide> AttachStderr: true,
<ide> })
<ide>
<del> expect := "SERVICE_NAME=svc\n" +
<add> expect := "SERVICE_NAME=" + serviceName + "\n" +
<ide> "this is a secret\n" +
<ide> "this is a config\n"
<ide> assertAttachedStream(t, attach, expect)
<ide> func TestTemplatedConfig(t *testing.T) {
<ide> AttachStdout: true,
<ide> AttachStderr: true,
<ide> })
<del> assertAttachedStream(t, attach, "tmpfs on /"+templatedConfigName+" type tmpfs")
<del>}
<del>
<del>func assertAttachedStream(t *testing.T, attach types.HijackedResponse, expect string) {
<del> buf := bytes.NewBuffer(nil)
<del> _, err := stdcopy.StdCopy(buf, buf, attach.Reader)
<del> assert.NilError(t, err)
<del> assert.Check(t, is.Contains(buf.String(), expect))
<add> assertAttachedStream(t, attach, "tmpfs on /templated_config type tmpfs")
<ide> }
<ide>
<ide> func TestConfigCreateWithLabels(t *testing.T) {
<ide> func TestConfigCreateResolve(t *testing.T) {
<ide> ctx := context.Background()
<ide>
<ide> configName := "test_config_" + t.Name()
<del>
<ide> configID := createConfig(ctx, t, c, configName, []byte("foo"), nil)
<add>
<ide> fakeName := configID
<ide> fakeID := createConfig(ctx, t, c, fakeName, []byte("fake foo"), nil)
<ide>
<ide> func TestConfigDaemonLibtrustID(t *testing.T) {
<ide> assert.Equal(t, info.ID, "WTJ3:YSIP:CE2E:G6KJ:PSBD:YX2Y:WEYD:M64G:NU2V:XPZV:H2CR:VLUB")
<ide> }
<ide>
<add>func assertAttachedStream(t *testing.T, attach types.HijackedResponse, expect string) {
<add> buf := bytes.NewBuffer(nil)
<add> _, err := stdcopy.StdCopy(buf, buf, attach.Reader)
<add> assert.NilError(t, err)
<add> assert.Check(t, is.Contains(buf.String(), expect))
<add>}
<add>
<ide> func configNamesFromList(entries []swarmtypes.Config) []string {
<ide> var values []string
<ide> for _, entry := range entries {
<ide><path>integration/secret/secret_test.go
<ide> func TestSecretsCreateAndDelete(t *testing.T) {
<ide> })
<ide> assert.Check(t, is.ErrorContains(err, "already exists"))
<ide>
<del> // Ported from original TestSecretsDelete
<ide> err = c.SecretRemove(ctx, secretID)
<ide> assert.NilError(t, err)
<ide>
<ide> func TestSecretsCreateAndDelete(t *testing.T) {
<ide> err = c.SecretRemove(ctx, "non-existin")
<ide> assert.Check(t, is.ErrorContains(err, "No such secret: non-existin"))
<ide>
<del> // Ported from original TestSecretsCreteaWithLabels
<ide> testName = "test_secret_with_labels_" + t.Name()
<ide> secretID = createSecret(ctx, t, c, testName, []byte("TESTINGDATA"), map[string]string{
<ide> "key1": "value1", | 2 |
Ruby | Ruby | move repeated pathname into setup | 083448d55d90400c10fa352bf676f5cfe1c2c16d | <ide><path>Library/Homebrew/test/test_keg.rb
<ide> def setup
<ide> end
<ide>
<ide> @keg = Keg.new(keg)
<add> @dst = HOMEBREW_PREFIX.join("bin", "helloworld")
<ide>
<ide> @mode = OpenStruct.new
<ide>
<ide> def test_linking_fails_when_already_linked
<ide> end
<ide>
<ide> def test_linking_fails_when_files_exist
<del> touch HOMEBREW_PREFIX/"bin/helloworld"
<add> touch @dst
<ide> assert_raises(Keg::ConflictError) { @keg.link }
<ide> end
<ide>
<ide> def test_link_ignores_broken_symlinks_at_target
<del> dst = HOMEBREW_PREFIX/"bin/helloworld"
<del> src = @keg/"bin/helloworld"
<del> ln_s "/some/nonexistent/path", dst
<add> src = @keg.join("bin", "helloworld")
<add> ln_s "/some/nonexistent/path", @dst
<ide> @keg.link
<del> assert_equal src.relative_path_from(dst.dirname), dst.readlink
<add> assert_equal src.relative_path_from(@dst.dirname), @dst.readlink
<ide> end
<ide>
<ide> def test_link_overwrite
<del> touch HOMEBREW_PREFIX/"bin/helloworld"
<add> touch @dst
<ide> @mode.overwrite = true
<ide> assert_equal 3, @keg.link(@mode)
<ide> assert_predicate @keg, :linked?
<ide> def test_link_overwrite_broken_symlinks
<ide> end
<ide>
<ide> def test_link_overwrite_dryrun
<del> touch HOMEBREW_PREFIX/"bin/helloworld"
<add> touch @dst
<ide> @mode.overwrite = true
<ide> @mode.dry_run = true
<ide>
<ide> assert_equal 0, @keg.link(@mode)
<ide> refute_predicate @keg, :linked?
<ide>
<del> assert_equal "#{HOMEBREW_PREFIX}/bin/helloworld\n", $stdout.string
<add> assert_equal "#{@dst}\n", $stdout.string
<ide> end
<ide>
<ide> def test_unlink_prunes_empty_toplevel_directories | 1 |
Go | Go | implement container.exportrw() on device-mapper | b0626f403b168b9020a802ec3bc4ad8c9bbc2486 | <ide><path>container.go
<ide> func (container *Container) Resize(h, w int) error {
<ide> }
<ide>
<ide> func (container *Container) ExportRw() (Archive, error) {
<del> return Tar(container.rwPath(), Uncompressed)
<add> if err := container.EnsureMounted(); err != nil {
<add> return nil, err
<add> }
<add>
<add> image, err := container.GetImage()
<add> if err != nil {
<add> return nil, err
<add> }
<add> return image.ExportChanges(container.runtime, container.RootfsPath(), container.rwPath(), container.ID)
<ide> }
<ide>
<ide> func (container *Container) RwChecksum() (string, error) {
<ide><path>image.go
<ide> func (image *Image) Changes(runtime *Runtime, root, rw, id string) ([]Change, er
<ide> return nil, fmt.Errorf("No supported Changes implementation")
<ide> }
<ide>
<add>func (image *Image) ExportChanges(runtime *Runtime, root, rw, id string) (Archive, error) {
<add> switch runtime.GetMountMethod() {
<add> case MountMethodAUFS:
<add> return Tar(rw, Uncompressed)
<add>
<add> case MountMethodDeviceMapper:
<add> changes, err := image.Changes(runtime, root, rw, id)
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> files := make([]string, 0)
<add> deletions := make([]string, 0)
<add> for _, change := range changes {
<add> if change.Kind == ChangeModify || change.Kind == ChangeAdd {
<add> files = append(files, change.Path)
<add> }
<add> if change.Kind == ChangeDelete {
<add> base := filepath.Base(change.Path)
<add> dir := filepath.Dir(change.Path)
<add> deletions = append(deletions, filepath.Join(dir, ".wh."+base))
<add> }
<add> }
<add>
<add> return TarFilter(root, Uncompressed, files, false, deletions)
<add> }
<add>
<add> return nil, fmt.Errorf("No supported Changes implementation")
<add>}
<add>
<add>
<ide> func (image *Image) ShortID() string {
<ide> return utils.TruncateID(image.ID)
<ide> } | 2 |
Javascript | Javascript | stop non-negative prop undershoot on animation | 56426261f0ee97d6d2f903d08b137a6f5f2c0916 | <ide><path>src/effects.js
<ide> jQuery.extend( jQuery.fx, {
<ide> }
<ide> });
<ide>
<del>// Adds width/height step functions
<del>// Do not set anything below 0
<del>jQuery.each([ "width", "height" ], function( i, prop ) {
<add>// Ensure props that can't be negative don't go there on undershoot easing
<add>jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) {
<ide> jQuery.fx.step[ prop ] = function( fx ) {
<ide> jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
<ide> };
<ide><path>test/unit/effects.js
<ide> test("animate negative height", function() {
<ide> });
<ide> });
<ide>
<add>test("animate negative padding", function() {
<add> expect(1);
<add> stop();
<add> jQuery("#foo").animate({ paddingBottom: -100 }, 100, function() {
<add> equal( jQuery(this).css("paddingBottom"), "0px", "Verify paddingBottom." );
<add> start();
<add> });
<add>});
<add>
<ide> test("animate block as inline width/height", function() {
<ide> expect(3);
<ide> | 2 |
Javascript | Javascript | fix example controller and style | 2fe5a2def026ac1aa63a98be7135b93784677129 | <ide><path>src/ng/anchorScroll.js
<ide> * @example
<ide> <example>
<ide> <file name="index.html">
<del> <div ng-controller="MainCtrl">
<add> <div id="scrollArea" ng-controller="ScrollCtrl">
<ide> <a ng-click="gotoBottom()">Go to bottom</a>
<ide> <a id="bottom"></a> You're at the bottom!
<ide> </div>
<ide> }
<ide> </file>
<ide> <file name="style.css">
<add> #scrollArea {
<add> height: 350px;
<add> overflow: auto;
<add> }
<add>
<ide> #bottom {
<ide> display: block;
<ide> margin-top: 2000px; | 1 |
Javascript | Javascript | add preprocess for buck worker | bfc0e8c26f9e66c525401e92e801410a3ea8be39 | <ide><path>local-cli/util/Config.js
<ide> const RN_CLI_CONFIG = 'rn-cli.config.js';
<ide> import type {GetTransformOptions, PostMinifyProcess, PostProcessModules} from '../../packager/src/Bundler';
<ide> import type {HasteImpl} from '../../packager/src/node-haste/Module';
<ide> import type {TransformVariants} from '../../packager/src/ModuleGraph/types.flow';
<add>import type {PostProcessModules as PostProcessModulesForBuck} from '../../packager/src/ModuleGraph/types.flow.js';
<ide>
<ide> /**
<ide> * Configuration file of the CLI.
<ide> export type ConfigT = {
<ide> */
<ide> postProcessModules: PostProcessModules,
<ide>
<add> /**
<add> * Same as `postProcessModules` but for the Buck worker. Eventually we do want
<add> * to unify both variants.
<add> */
<add> postProcessModulesForBuck: PostProcessModulesForBuck,
<add>
<ide> /**
<ide> * A module that exports:
<ide> * - a `getHasteName(filePath)` method that returns `hasteName` for module at
<ide> const defaultConfig: ConfigT = {
<ide> getTransformOptions: async () => ({}),
<ide> postMinifyProcess: x => x,
<ide> postProcessModules: modules => modules,
<add> postProcessModulesForBuck: modules => modules,
<ide> transformVariants: () => ({default: {}}),
<ide> };
<ide>
<ide><path>packager/src/ModuleGraph/ModuleGraph.js
<ide> import type {
<ide> GraphFn,
<ide> GraphResult,
<ide> Module,
<add> PostProcessModules,
<ide> } from './types.flow';
<ide>
<ide> type BuildFn = (
<ide> type BuildOptions = {|
<ide>
<ide> exports.createBuildSetup = (
<ide> graph: GraphFn,
<add> postProcessModules: PostProcessModules,
<ide> translateDefaultsPath: string => string = x => x,
<ide> ): BuildFn =>
<ide> (entryPoints, options, callback) => {
<ide> exports.createBuildSetup = (
<ide> const graphOnlyModules = seq(graphWithOptions, getModules);
<ide>
<ide> parallel({
<del> graph: cb => graphWithOptions(
<del> entryPoints,
<del> cb,
<del> ),
<add> graph: cb => graphWithOptions(entryPoints, (error, result) => {
<add> if (error) {
<add> cb(error);
<add> return;
<add> }
<add> /* $FlowFixMe: not undefined if there is no error */
<add> const {modules, entryModules} = result;
<add> const prModules = postProcessModules(modules, [...entryPoints]);
<add> cb(null, {modules: prModules, entryModules});
<add> }),
<ide> moduleSystem: cb => graphOnlyModules(
<ide> [translateDefaultsPath(defaults.moduleSystem)],
<ide> cb,
<ide><path>packager/src/ModuleGraph/__tests__/ModuleGraph-test.js
<ide> const defaults = require('../../../defaults');
<ide> const FILE_TYPE = 'module';
<ide>
<ide> describe('build setup', () => {
<del> const buildSetup = ModuleGraph.createBuildSetup(graph);
<add> const buildSetup = ModuleGraph.createBuildSetup(graph, mds => {
<add> return [...mds].sort((l, r) => l.file.path > r.file.path);
<add> });
<ide> const noOptions = {};
<ide> const noEntryPoints = [];
<ide>
<ide> describe('build setup', () => {
<ide> });
<ide> });
<ide>
<del> it('places all entry points at the end', done => {
<del> const entryPoints = ['a', 'b', 'c'];
<add> it('places all entry points and dependencies at the end, post-processed', done => {
<add> const entryPoints = ['b', 'c', 'd'];
<ide> buildSetup(entryPoints, noOptions, (error, result) => {
<del> expect(Array.from(result.modules).slice(-3))
<del> .toEqual(entryPoints.map(moduleFromPath));
<add> expect(Array.from(result.modules).slice(-4))
<add> .toEqual(['a', 'b', 'c', 'd'].map(moduleFromPath));
<ide> done();
<ide> });
<ide> });
<ide> });
<ide>
<ide> function moduleFromPath(path) {
<ide> return {
<del> dependencies: [],
<add> dependencies: path === 'b' ? ['a'] : [],
<ide> file: {
<ide> code: '',
<ide> path,
<ide> function moduleFromPath(path) {
<ide>
<ide> function graph(entryPoints, platform, options, callback) {
<ide> const modules = Array.from(entryPoints, moduleFromPath);
<add> const depModules = Array.prototype.concat.apply(
<add> [],
<add> modules.map(x => x.dependencies.map(moduleFromPath)),
<add> );
<ide> callback(null, {
<ide> entryModules: modules,
<del> modules,
<add> modules: modules.concat(depModules),
<ide> });
<ide> }
<ide><path>packager/src/ModuleGraph/types.flow.js
<ide> export type Module = {|
<ide> file: File,
<ide> |};
<ide>
<add>export type PostProcessModules = (
<add> modules: Iterable<Module>,
<add> entryPoints: Array<string>,
<add>) => Iterable<Module>;
<add>
<ide> export type OutputFn = ({|
<ide> filename: string,
<ide> idForPath: IdForPathFn, | 4 |
Go | Go | replace use of deprecated functions | bf28003c99ef6900d0b006450cd9b6bdf3a23f72 | <ide><path>libnetwork/drivers/windows/overlay/ov_endpoint_windows.go
<ide> import (
<ide> "sync"
<ide>
<ide> "github.com/Microsoft/hcsshim"
<del> "github.com/docker/docker/pkg/system"
<add> "github.com/Microsoft/hcsshim/osversion"
<ide> "github.com/docker/libnetwork/driverapi"
<ide> "github.com/docker/libnetwork/drivers/windows"
<ide> "github.com/docker/libnetwork/netlabel"
<ide> var (
<ide> //Server 2016 (RS1) does not support concurrent add/delete of endpoints. Therefore, we need
<ide> //to use this mutex and serialize the add/delete of endpoints on RS1.
<ide> endpointMu sync.Mutex
<del> windowsBuild = system.GetOSVersion().Build
<add> windowsBuild = osversion.Build()
<ide> )
<ide>
<ide> func validateID(nid, eid string) error {
<ide> func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo,
<ide>
<ide> hnsEndpoint.Policies = append(hnsEndpoint.Policies, paPolicy)
<ide>
<del> if system.GetOSVersion().Build > 16236 {
<add> if osversion.Build() > 16236 {
<ide> natPolicy, err := json.Marshal(hcsshim.PaPolicy{
<ide> Type: "OutBoundNAT",
<ide> })
<ide><path>libnetwork/drivers/windows/windows.go
<ide> import (
<ide> "sync"
<ide>
<ide> "github.com/Microsoft/hcsshim"
<del> "github.com/docker/docker/pkg/system"
<add> "github.com/Microsoft/hcsshim/osversion"
<ide> "github.com/docker/libnetwork/datastore"
<ide> "github.com/docker/libnetwork/discoverapi"
<ide> "github.com/docker/libnetwork/driverapi"
<ide> func (d *driver) parseNetworkOptions(id string, genericOptions map[string]string
<ide> }
<ide> config.VSID = uint(vsid)
<ide> case EnableOutboundNat:
<del> if system.GetOSVersion().Build <= 16236 {
<add> if osversion.Build() <= 16236 {
<ide> return nil, fmt.Errorf("Invalid network option. OutboundNat is not supported on this OS version")
<ide> }
<ide> b, err := strconv.ParseBool(value)
<ide><path>libnetwork/firewall_test.go
<ide> package libnetwork
<ide>
<ide> import (
<ide> "fmt"
<del> "gotest.tools/assert"
<ide> "strings"
<ide> "testing"
<ide>
<ide> "github.com/docker/libnetwork/iptables"
<ide> "github.com/docker/libnetwork/netlabel"
<ide> "github.com/docker/libnetwork/options"
<add> "gotest.tools/assert"
<ide> )
<ide>
<ide> const (
<ide><path>libnetwork/service_windows.go
<ide> import (
<ide> "net"
<ide>
<ide> "github.com/Microsoft/hcsshim"
<del> "github.com/docker/docker/pkg/system"
<add> "github.com/Microsoft/hcsshim/osversion"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<ide> func (n *network) addLBBackend(ip net.IP, lb *loadBalancer) {
<ide> vip := lb.vip
<ide> ingressPorts := lb.service.ingressPorts
<ide>
<del> if system.GetOSVersion().Build > 16236 {
<add> if osversion.Build() > 16236 {
<ide> lb.Lock()
<ide> defer lb.Unlock()
<ide> //find the load balancer IP for the network.
<ide> func (n *network) rmLBBackend(ip net.IP, lb *loadBalancer, rmService bool, fullR
<ide> return
<ide> }
<ide>
<del> if system.GetOSVersion().Build > 16236 {
<add> if osversion.Build() > 16236 {
<ide> if numEnabledBackends(lb) > 0 {
<ide> //Reprogram HNS (actually VFP) with the existing backends.
<ide> n.addLBBackend(ip, lb) | 4 |
Text | Text | add an item to changelog | 190a1141ccccde0d04b53347f2c60eafb244bb02 | <ide><path>CHANGELOG.md
<ide> * Fix a crash rendering into shadow root. ([@gaearon](https://github.com/gaearon) in [#11037](https://github.com/facebook/react/pull/11037))
<ide> * Suppress the new unknown tag warning for `<dialog>` element. ([@gaearon](http://github.com/gaearon) in [#11035](https://github.com/facebook/react/pull/11035))
<ide> * Warn about function child no more than once. ([@andreysaleba](https://github.com/andreysaleba) in [#11120](https://github.com/facebook/react/pull/11120))
<add>* Warn about nested updates no more than once. ([@anushreesubramani](https://github.com/anushreesubramani) in [#11113](https://github.com/facebook/react/pull/11113))
<ide> * Minor bundle size improvements. ([@gaearon](https://github.com/gaearon) in [#10802](https://github.com/facebook/react/pull/10802), [#10803](https://github.com/facebook/react/pull/10803))
<ide>
<ide> ### React DOM Server | 1 |
PHP | PHP | update docblock and include strings | b960fd0d3d9e498219e21a88edc0fe18537c28ab | <ide><path>src/Illuminate/Console/Scheduling/ManagesFrequencies.php
<ide> public function yearly()
<ide> * Schedule the event to run yearly on a given month, day, and time.
<ide> *
<ide> * @param int $month
<del> * @param int $dayOfMonth
<add> * @param int|string $dayOfMonth
<ide> * @param string $time
<ide> * @return $this
<ide> */
<ide><path>tests/Console/Scheduling/FrequencyTest.php
<ide> public function testYearlyOn()
<ide> $this->assertSame('8 15 5 4 *', $this->event->yearlyOn(4, 5, '15:08')->getExpression());
<ide> }
<ide>
<del> public function testYearlyOnTuesdays()
<add> public function testYearlyOnMondaysOnly()
<add> {
<add> $this->assertSame('1 9 * 7 1', $this->event->mondays()->yearlyOn(7, '*', '09:01')->getExpression());
<add> }
<add>
<add> public function testYearlyOnTuesdaysAndDayOfMonth20()
<ide> {
<ide> $this->assertSame('1 9 20 7 2', $this->event->tuesdays()->yearlyOn(7, 20, '09:01')->getExpression());
<ide> } | 2 |
Ruby | Ruby | fix documentation for string#mb_chars | 27b79f4c911fdfce186086cfaa6646f1c2083aa0 | <ide><path>activesupport/lib/active_support/core_ext/string/multibyte.rb
<ide> class String
<ide> #
<ide> # +mb_chars+ is a multibyte safe proxy for string methods.
<ide> #
<del> # In Ruby 1.8 and older it creates and returns an instance of the ActiveSupport::Multibyte::Chars class which
<add> # It creates and returns an instance of the ActiveSupport::Multibyte::Chars class which
<ide> # encapsulates the original string. A Unicode safe version of all the String methods are defined on this proxy
<ide> # class. If the proxy class doesn't respond to a certain method, it's forwarded to the encapsulated string.
<ide> #
<ide> class String
<ide> # name.mb_chars.reverse.to_s # => "rellüM sualC"
<ide> # name.mb_chars.length # => 12
<ide> #
<del> # In Ruby 1.9 and newer +mb_chars+ returns +self+ because String is (mostly) encoding aware. This means that
<del> # it becomes easy to run one version of your code on multiple Ruby versions.
<del> #
<ide> # == Method chaining
<ide> #
<ide> # All the methods on the Chars proxy which normally return a string will return a Chars object. This allows | 1 |
Ruby | Ruby | fix incorrect unsubscription | d9396a07ebe69b211365f14b8e2c7c10e75fb61c | <ide><path>railties/test/rack_logger_test.rb
<ide> def finish(name, id, payload)
<ide> def setup
<ide> @subscriber = Subscriber.new
<ide> @notifier = ActiveSupport::Notifications.notifier
<del> notifier.subscribe 'request.action_dispatch', subscriber
<add> @subscription = notifier.subscribe 'request.action_dispatch', subscriber
<ide> end
<ide>
<ide> def teardown
<del> notifier.unsubscribe subscriber
<add> notifier.unsubscribe @subscription
<ide> end
<ide>
<ide> def test_notification | 1 |
Go | Go | enable some cp integration tests | 088c3eeea8ae6e46bf698d0c99c98b92bc894063 | <ide><path>integration-cli/docker_cli_cp_from_container_test.go
<ide> import (
<ide>
<ide> // Test for error when SRC does not exist.
<ide> func (s *DockerSuite) TestCpFromErrSrcNotExists(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> containerID := makeTestContainer(c, testContainerOptions{})
<ide>
<ide> tmpDir := getTestDir(c, "test-cp-from-err-src-not-exists")
<ide><path>integration-cli/docker_cli_cp_test.go
<ide> func (s *DockerSuite) TestCpLocalOnly(c *check.C) {
<ide> // Test for #5656
<ide> // Check that garbage paths don't escape the container's rootfs
<ide> func (s *DockerSuite) TestCpGarbagePath(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath)
<ide>
<ide> containerID := strings.TrimSpace(out)
<ide> func (s *DockerSuite) TestCpGarbagePath(c *check.C) {
<ide>
<ide> // Check that relative paths are relative to the container's rootfs
<ide> func (s *DockerSuite) TestCpRelativePath(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath)
<ide>
<ide> containerID := strings.TrimSpace(out)
<ide> func (s *DockerSuite) TestCpRelativePath(c *check.C) {
<ide>
<ide> // Check that absolute paths are relative to the container's rootfs
<ide> func (s *DockerSuite) TestCpAbsolutePath(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath)
<ide>
<ide> containerID := strings.TrimSpace(out)
<ide> func (s *DockerSuite) TestCpVolumePath(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestCpToDot(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /test")
<ide>
<ide> containerID := strings.TrimSpace(out)
<ide> func (s *DockerSuite) TestCpToDot(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestCpToStdout(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /test")
<ide>
<ide> containerID := strings.TrimSpace(out)
<ide><path>integration-cli/docker_cli_cp_to_container_test.go
<ide> import (
<ide>
<ide> // Test for error when SRC does not exist.
<ide> func (s *DockerSuite) TestCpToErrSrcNotExists(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> containerID := makeTestContainer(c, testContainerOptions{})
<ide>
<ide> tmpDir := getTestDir(c, "test-cp-to-err-src-not-exists")
<ide> func (s *DockerSuite) TestCpToErrSrcNotExists(c *check.C) {
<ide> // Test for error when SRC ends in a trailing
<ide> // path separator but it exists as a file.
<ide> func (s *DockerSuite) TestCpToErrSrcNotDir(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> containerID := makeTestContainer(c, testContainerOptions{})
<ide>
<ide> tmpDir := getTestDir(c, "test-cp-to-err-src-not-dir")
<ide> func (s *DockerSuite) TestCpToSymlinkDestination(c *check.C) {
<ide> // exist. This should create a file with the name DST and copy the
<ide> // contents of the source file into it.
<ide> func (s *DockerSuite) TestCpToCaseA(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> containerID := makeTestContainer(c, testContainerOptions{
<ide> workDir: "/root", command: makeCatFileCommand("itWorks.txt"),
<ide> })
<ide> func (s *DockerSuite) TestCpToCaseA(c *check.C) {
<ide> // exist. This should cause an error because the copy operation cannot
<ide> // create a directory when copying a single file.
<ide> func (s *DockerSuite) TestCpToCaseB(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> containerID := makeTestContainer(c, testContainerOptions{
<ide> command: makeCatFileCommand("testDir/file1"),
<ide> })
<ide> func (s *DockerSuite) TestCpToCaseD(c *check.C) {
<ide> // directory. Ensure this works whether DST has a trailing path separator or
<ide> // not.
<ide> func (s *DockerSuite) TestCpToCaseE(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> containerID := makeTestContainer(c, testContainerOptions{
<ide> command: makeCatFileCommand("/testDir/file1-1"),
<ide> })
<ide> func (s *DockerSuite) TestCpToCaseG(c *check.C) {
<ide> // directory (but not the directory itself) into the DST directory. Ensure
<ide> // this works whether DST has a trailing path separator or not.
<ide> func (s *DockerSuite) TestCpToCaseH(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> containerID := makeTestContainer(c, testContainerOptions{
<ide> command: makeCatFileCommand("/testDir/file1-1"),
<ide> }) | 3 |
PHP | PHP | remove useless $app arguments in bindshared | ffc947ae339ce7e66eecdfb2f2d1bc197ba6b356 | <ide><path>src/Illuminate/Auth/Reminders/ReminderServiceProvider.php
<ide> protected function registerCommands()
<ide> return new RemindersTableCommand($app['files']);
<ide> });
<ide>
<del> $this->app->bindShared('command.auth.reminders.clear', function($app)
<add> $this->app->bindShared('command.auth.reminders.clear', function()
<ide> {
<ide> return new ClearRemindersCommand;
<ide> });
<ide><path>src/Illuminate/Database/MigrationServiceProvider.php
<ide> protected function registerResetCommand()
<ide> */
<ide> protected function registerRefreshCommand()
<ide> {
<del> $this->app->bindShared('command.migrate.refresh', function($app)
<add> $this->app->bindShared('command.migrate.refresh', function()
<ide> {
<ide> return new RefreshCommand;
<ide> });
<ide><path>src/Illuminate/Database/SeedServiceProvider.php
<ide> public function register()
<ide> {
<ide> $this->registerSeedCommand();
<ide>
<del> $this->app->bindShared('seeder', function($app)
<add> $this->app->bindShared('seeder', function()
<ide> {
<ide> return new Seeder;
<ide> });
<ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
<ide> public function register()
<ide> return new Artisan($app);
<ide> });
<ide>
<del> $this->app->bindShared('command.tail', function($app)
<add> $this->app->bindShared('command.tail', function()
<ide> {
<ide> return new TailCommand;
<ide> });
<ide>
<del> $this->app->bindShared('command.changes', function($app)
<add> $this->app->bindShared('command.changes', function()
<ide> {
<ide> return new ChangesCommand;
<ide> });
<ide>
<del> $this->app->bindShared('command.environment', function($app)
<add> $this->app->bindShared('command.environment', function()
<ide> {
<ide> return new EnvironmentCommand;
<ide> });
<ide><path>src/Illuminate/Foundation/Providers/MaintenanceServiceProvider.php
<ide> class MaintenanceServiceProvider extends ServiceProvider {
<ide> */
<ide> public function register()
<ide> {
<del> $this->app->bindShared('command.up', function($app)
<add> $this->app->bindShared('command.up', function()
<ide> {
<ide> return new UpCommand;
<ide> });
<ide>
<del> $this->app->bindShared('command.down', function($app)
<add> $this->app->bindShared('command.down', function()
<ide> {
<ide> return new DownCommand;
<ide> });
<ide><path>src/Illuminate/Foundation/Providers/PublisherServiceProvider.php
<ide> protected function registerMigrationPublisher()
<ide> */
<ide> protected function registerMigratePublishCommand()
<ide> {
<del> $this->app->bindShared('command.migrate.publish', function($app)
<add> $this->app->bindShared('command.migrate.publish', function()
<ide> {
<ide> return new MigratePublishCommand;
<ide> });
<ide><path>src/Illuminate/Queue/FailConsoleServiceProvider.php
<ide> class FailConsoleServiceProvider extends ServiceProvider {
<ide> */
<ide> public function register()
<ide> {
<del> $this->app->bindShared('command.queue.failed', function($app)
<add> $this->app->bindShared('command.queue.failed', function()
<ide> {
<ide> return new ListFailedCommand;
<ide> });
<ide>
<del> $this->app->bindShared('command.queue.retry', function($app)
<add> $this->app->bindShared('command.queue.retry', function()
<ide> {
<ide> return new RetryCommand;
<ide> });
<ide>
<del> $this->app->bindShared('command.queue.forget', function($app)
<add> $this->app->bindShared('command.queue.forget', function()
<ide> {
<ide> return new ForgetFailedCommand;
<ide> });
<ide>
<del> $this->app->bindShared('command.queue.flush', function($app)
<add> $this->app->bindShared('command.queue.flush', function()
<ide> {
<ide> return new FlushFailedCommand;
<ide> });
<ide><path>src/Illuminate/Queue/QueueServiceProvider.php
<ide> protected function registerListenCommand()
<ide> */
<ide> public function registerRestartCommand()
<ide> {
<del> $this->app->bindShared('command.queue.restart', function($app)
<add> $this->app->bindShared('command.queue.restart', function()
<ide> {
<ide> return new RestartCommand;
<ide> });
<ide> public function registerRestartCommand()
<ide> */
<ide> protected function registerSubscriber()
<ide> {
<del> $this->app->bindShared('command.queue.subscribe', function($app)
<add> $this->app->bindShared('command.queue.subscribe', function()
<ide> {
<ide> return new SubscribeCommand;
<ide> });
<ide><path>src/Illuminate/View/ViewServiceProvider.php
<ide> public function register()
<ide> */
<ide> public function registerEngineResolver()
<ide> {
<del> $this->app->bindShared('view.engine.resolver', function($app)
<add> $this->app->bindShared('view.engine.resolver', function()
<ide> {
<ide> $resolver = new EngineResolver;
<ide> | 9 |
Ruby | Ruby | fix punctuation in `has_secure_password` docs | 12f3da0ac327c2c6256252dc24c5551c83c48dc4 | <ide><path>activemodel/lib/active_model/secure_password.rb
<ide> class << self
<ide>
<ide> module ClassMethods
<ide> # Adds methods to set and authenticate against a BCrypt password.
<del> # This mechanism requires you to have a +XXX_digest+ attribute.
<del> # Where +XXX+ is the attribute name of your desired password.
<add> # This mechanism requires you to have a +XXX_digest+ attribute,
<add> # where +XXX+ is the attribute name of your desired password.
<ide> #
<ide> # The following validations are added automatically:
<ide> # * Password must be present on creation | 1 |
Text | Text | fix sentence which ended abruptly | 8d341c9705aa05bc3301f17bd5ef7a876c850ded | <ide><path>guide/portuguese/accessibility/accessibility-basics/index.md
<ide> title: Accessibility Basics
<ide> localeTitle: Noções básicas de acessibilidade
<ide> ---
<add>
<ide> > "As Artes das Trevas são muitas, variadas, estão em constante mudança, e são eternas. Combatê-las é como combater um monstro de muitas cabeças, no qual, cada vez que cortamos uma cabeça, surge outra ainda mais feroz e inteligente do que a anterior. Você está lutando contra algo que não é fixo, mutável e indestrutível.".
<del>>
<ide> > \- Professor Severo Snape, Série Harry Potter
<ide>
<ide> O papel da acessibilidade no desenvolvimento é essencialmente entender a perspectiva e as necessidades do usuário e saber que a Web e os aplicativos são uma solução para pessoas com deficiências.
<ide>
<del>Hoje em dia, mais e mais novas tecnologias são inventadas para tornar a vida dos desenvolvedores, assim como dos usuários, mais fácil. Até que ponto isso é uma coisa boa é um debate para outro momento, por enquanto é o suficiente para dizer que a caixa de ferramentas de um desenvolvedor, especialmente um desenvolvedor web, está tão em constante mudança quanto as chamadas "artes das trevas" estão de acordo com nosso amigo. Snape
<add>Hoje em dia, mais e mais novas tecnologias são inventadas para tornar a vida dos desenvolvedores, assim como dos usuários, mais fácil. Até que ponto isso é uma coisa boa é um debate para outro momento, por enquanto é o suficiente para dizer que a caixa de ferramentas de um desenvolvedor, especialmente um desenvolvedor web, está tão em constante mudança quanto as chamadas "artes das trevas" estão de acordo com nosso amigo Snape.
<ide>
<ide> Uma ferramenta nessa caixa de ferramentas deve ser acessibilidade. É uma ferramenta que deve idealmente ser usada em um dos primeiros passos de escrever qualquer forma de conteúdo da web. No entanto, esta ferramenta muitas vezes não é tão bem apresentada na caixa de ferramentas da maioria dos desenvolvedores. Isso pode ser devido a um simples caso de não saber que existe até casos extremos, como não se importar com isso.
<ide>
<ide> Na minha vida como usuário e, mais tarde, como desenvolvedor, que se beneficia da acessibilidade em qualquer forma de conteúdo, eu vi os dois lados desse espectro. Se você estiver lendo este artigo, acredito que esteja em uma das seguintes categorias:
<ide>
<del>* Você é um desenvolvedor web iniciante e gostaria de saber mais sobre acessibilidade
<del>* Você é um desenvolvedor web experiente e perdeu o seu caminho (mais sobre isso mais tarde)
<add>* Você é um desenvolvedor web iniciante e gostaria de saber mais sobre acessibilidade.
<add>* Você é um desenvolvedor web experiente e perdeu o seu caminho (mais sobre isso mais tarde).
<ide> * Você sente que existe uma obrigação legal do trabalho e precisa aprender mais sobre isso.
<ide>
<ide> Se você ficar fora dessas categorias bastante amplas, por favor me avise. Eu sempre gosto de ouvir as pessoas que lêem o que eu escrevo. A implementação da acessibilidade afeta toda a equipe, desde as cores escolhidas pelo designer, a cópia escrita pelo redator e até você, o desenvolvedor. | 1 |
Javascript | Javascript | relax the comparison for undefined properties | 3c2e1c5e4d12529b1d69a6173c38097527dccc4f | <ide><path>src/Angular.js
<ide> function equals(o1, o2) {
<ide> } else {
<ide> if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false;
<ide> keySet = {};
<del> length = 0;
<ide> for(key in o1) {
<del> if (key.charAt(0) === '$') continue;
<del>
<del> if (!isFunction(o1[key]) && !equals(o1[key], o2[key])) return false;
<del>
<del> length++;
<add> if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
<add> if (!equals(o1[key], o2[key])) return false;
<ide> keySet[key] = true;
<ide> }
<ide> for(key in o2) {
<del> if (key.charAt(0) === '$') {
<del> continue;
<del> }
<del> if (!keySet[key] && !isFunction(o2[key])) return false;
<del> length--;
<add> if (!keySet[key] &&
<add> key.charAt(0) !== '$' &&
<add> o2[key] !== undefined &&
<add> !isFunction(o2[key])) return false;
<ide> }
<del> return length === 0;
<add> return true;
<ide> }
<ide> }
<ide> }
<ide><path>test/AngularSpec.js
<ide> describe('angular', function() {
<ide> expect(equals(['misko'], ['misko', 'adam'])).toEqual(false);
<ide> });
<ide>
<del> it('should ignore undefined member variables', function() {
<add> it('should ignore undefined member variables during comparison', function() {
<ide> var obj1 = {name: 'misko'},
<ide> obj2 = {name: 'misko', undefinedvar: undefined};
<ide>
<del> expect(equals(obj1, obj2)).toBe(false);
<del> expect(equals(obj2, obj1)).toBe(false);
<add> expect(equals(obj1, obj2)).toBe(true);
<add> expect(equals(obj2, obj1)).toBe(true);
<ide> });
<ide>
<ide> it('should ignore $ member variables', function() { | 2 |
Go | Go | improve consistency in log messages | d86a331fa498e184992205387f3270a59a5ce48b | <ide><path>libnetwork/resolver.go
<ide> func (r *resolver) Start() error {
<ide> r.server = s
<ide> go func() {
<ide> if err := s.ActivateAndServe(); err != nil {
<del> logrus.WithError(err).Error("error starting packetconn dns server")
<add> logrus.WithError(err).Error("[resolver] failed to start PacketConn DNS server")
<ide> }
<ide> }()
<ide>
<ide> tcpServer := &dns.Server{Handler: r, Listener: r.tcpListen}
<ide> r.tcpServer = tcpServer
<ide> go func() {
<ide> if err := tcpServer.ActivateAndServe(); err != nil {
<del> logrus.WithError(err).Error("error starting tcp dns server")
<add> logrus.WithError(err).Error("[resolver] failed to start TCP DNS server")
<ide> }
<ide> }()
<ide> return nil
<ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
<ide> }
<ide>
<ide> if err != nil {
<del> logrus.Error(err)
<add> logrus.WithError(err).Errorf("[resolver] failed to handle query: %s (%s) from %s", name, dns.TypeToString[query.Question[0].Qtype], extConn.LocalAddr().String())
<ide> return
<ide> }
<ide>
<ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
<ide> resp = new(dns.Msg)
<ide> resp.SetRcode(query, dns.RcodeServerFailure)
<ide> if err := w.WriteMsg(resp); err != nil {
<del> logrus.WithError(err).Error("Error writing dns response")
<add> logrus.WithError(err).Error("[resolver] error writing dns response")
<ide> }
<ide> return
<ide> }
<ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
<ide>
<ide> // Timeout has to be set for every IO operation.
<ide> if err := extConn.SetDeadline(time.Now().Add(extIOTimeout)); err != nil {
<del> logrus.WithError(err).Error("Error setting conn deadline")
<add> logrus.WithError(err).Error("[resolver] error setting conn deadline")
<ide> }
<ide> co := &dns.Conn{
<ide> Conn: extConn,
<ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
<ide> // client can retry over TCP
<ide> if err != nil && (resp == nil || !resp.Truncated) {
<ide> r.forwardQueryEnd()
<del> logrus.Debugf("[resolver] read from DNS server failed, %s", err)
<add> logrus.WithError(err).Debugf("[resolver] failed to read from DNS server")
<ide> continue
<ide> }
<ide> r.forwardQueryEnd()
<ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
<ide> }
<ide>
<ide> if err = w.WriteMsg(resp); err != nil {
<del> logrus.Errorf("[resolver] error writing resolver resp, %s", err)
<add> logrus.WithError(err).Errorf("[resolver] failed to write resolver response")
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | deprecate additional arch functions | b670ab1c7b1bf3a2edecbbe0e12f8ab5b86732af | <ide><path>Library/Homebrew/hardware.rb
<ide> def arch
<ide> end
<ide>
<ide> def universal_archs
<add> odeprecated "Hardware::CPU.universal_archs"
<add>
<ide> [arch].extend ArchitectureListExtension
<ide> end
<ide>
<ide><path>Library/Homebrew/os/mac/architecture_list.rb
<ide> # typed: false
<ide> # frozen_string_literal: true
<ide>
<add># TODO: (3.2) remove this module when the linked deprecated functions are removed.
<add>
<ide> require "hardware"
<ide>
<ide> module ArchitectureListExtension
<ide><path>Library/Homebrew/os/mac/mach.rb
<ide> def dynamically_linked_libraries(except: :none)
<ide> end
<ide>
<ide> def archs
<add> # TODO: (3.2) remove ArchitectureListExtension
<ide> mach_data.map { |m| m.fetch :arch }.extend(ArchitectureListExtension)
<ide> end
<ide>
<ide><path>Library/Homebrew/utils.rb
<ide> def gzip(*paths)
<ide>
<ide> # Returns array of architectures that the given command or library is built for.
<ide> def archs_for_command(cmd)
<add> odeprecated "archs_for_command"
<add>
<ide> cmd = which(cmd) unless Pathname.new(cmd).absolute?
<ide> Pathname.new(cmd).archs
<ide> end | 4 |
PHP | PHP | convert language php 5.4 arrays | 5f5cc828d3ab3e0b6c955eb944914eecec8ce1ad | <ide><path>resources/lang/en/reminders.php
<ide> <?php
<ide>
<del>return array(
<add>return [
<ide>
<ide> /*
<ide> |--------------------------------------------------------------------------
<ide>
<ide> "reset" => "Password has been reset!",
<ide>
<del>);
<add>]; | 1 |
PHP | PHP | add contract for bc | 38420603d81b6f5cd763f602eb35d7a30f24726c | <ide><path>src/Illuminate/Contracts/Bus/SelfHandling.php
<add><?php
<add>
<add>namespace Illuminate\Contracts\Bus;
<add>
<add>/**
<add> * @deprecated since version 5.2. Remove from jobs since self-handling is default.
<add> */
<add>interface SelfHandling
<add>{
<add> //
<add>} | 1 |
Text | Text | add description of jagged arrays | c7499729e2029ef63308995800642c8a027a6a68 | <ide><path>guide/english/csharp/array/index.md
<ide> or simply:
<ide>
<ide> `var nameOfArray = new dataType {value1, value2, value3, value4};`
<ide>
<add>## Jagged Arrays
<add>
<add>Jagged arrays contain elements that are arrays itself. Example of declaration and initialization of jagged array:
<add>
<add>```csharp
<add>int[][] array = new int[2][];
<add>```
<add>
<add>Each element of jagged array can contains array of different length, ex:
<add>
<add>```csharp
<add>array[0] = new int[2];
<add>array[1] = new int[4];
<add>
<add>array[0][0] = 1;
<add>array[0][1] = 2;
<add>
<add>array[1][0] = 1;
<add>array[1][1] = 2;
<add>array[1][2] = 3;
<add>array[1][3] = 4;
<add>```
<add>As you see the array contains 2 other arrays which respectively contain 2 and 4 elements. Above code can be written shorter by using different format:
<add>
<add>```csharp
<add>int[][] array =
<add>{
<add> new int[] {1,2},
<add> new int[] {1,2,3,4}
<add>};
<add>```
<add>
<add>It's important to remember that types of subarrays must be the same as type of main array. To access specific element of jagged array you should use `array[x][y]` syntax where x is an index of main array which indicates subarray and y is index of subarray which indicates element within that subarray.
<add>
<add>```csharp
<add>Console.Write(array[0][0]); // Displays 1 (first element of first subarray)
<add>Console.Write(array[1][2]); // Displays 3 (third element of second subarray)
<add>Console.Write(array[1][0]); // Displays 1 (first element of second subarray)
<add>```
<add>
<ide> ## Advantages
<ide>
<ide> * Can be easily accessed in a random manner | 1 |
Ruby | Ruby | remove another lolinject | 6e1df2ca4631b8da6dae348af9d791f6e9aee1c5 | <ide><path>activesupport/lib/active_support/cache/mem_cache_store.rb
<ide> def initialize(*addresses)
<ide> def read_multi(*names)
<ide> options = names.extract_options!
<ide> options = merged_options(options)
<del> keys_to_names = names.inject({}){|map, name| map[escape_key(namespaced_key(name, options))] = name; map}
<add> keys_to_names = Hash[names.map{|name| [escape_key(namespaced_key(name, options)), name]}]
<ide> raw_values = @data.get_multi(keys_to_names.keys, :raw => true)
<ide> values = {}
<ide> raw_values.each do |key, value| | 1 |
Ruby | Ruby | fix missing methods in cask dsl | 77d25da5e5420d2e17c721f010cc06704d1d20d5 | <ide><path>Library/Homebrew/cask/dsl.rb
<ide> def auto_updates(auto_updates = nil)
<ide> end
<ide> end
<ide>
<add> def respond_to_missing?(*)
<add> super
<add> end
<add>
<ide> def method_missing(method, *)
<ide> if method
<ide> Utils.method_missing_message(method, token)
<ide> def method_missing(method, *)
<ide> end
<ide> end
<ide>
<del> def respond_to_missing?(*)
<del> super || true
<del> end
<del>
<ide> def appdir
<ide> cask.config.appdir
<ide> end
<ide><path>Library/Homebrew/cask/dsl/base.rb
<ide> def system_command(executable, **options)
<ide> @command.run!(executable, **options)
<ide> end
<ide>
<add> def respond_to_missing?(*)
<add> super
<add> end
<add>
<ide> def method_missing(method, *)
<ide> if method
<ide> underscored_class = self.class.name.gsub(/([[:lower:]])([[:upper:]][[:lower:]])/, '\1_\2').downcase
<ide> def method_missing(method, *)
<ide> super
<ide> end
<ide> end
<del>
<del> def respond_to_missing?(*)
<del> super || true
<del> end
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cask/utils.rb
<ide> def self.error_message_with_suggestions
<ide> end
<ide>
<ide> def self.method_missing_message(method, token, section = nil)
<del> poo = []
<del> poo << "Unexpected method '#{method}' called"
<del> poo << "during #{section}" if section
<del> poo << "on Cask #{token}."
<add> message = +"Unexpected method '#{method}' called "
<add> message << "during #{section} " if section
<add> message << "on Cask #{token}."
<ide>
<del> opoo("#{poo.join(" ")}\n#{error_message_with_suggestions}")
<add> opoo "#{message}\n#{error_message_with_suggestions}"
<ide> end
<ide> end
<ide> end | 3 |
Javascript | Javascript | test it too | 39c370a19b266fd2286b25c32a602d54365bc734 | <ide><path>test/TestCases.test.js
<ide> describe("TestCases", function() {
<ide> { name: "hot", plugins: [
<ide> new webpack.HotModuleReplacementPlugin()
<ide> ]},
<add> { name: "hot-multi-step", plugins: [
<add> new webpack.HotModuleReplacementPlugin({
<add> multiStep: true
<add> })
<add> ]},
<ide> { name: "devtool-eval", devtool: "eval" },
<ide> { name: "devtool-eval-source-map", devtool: "#eval-source-map" },
<ide> { name: "devtool-source-map", devtool: "#@source-map" },
<ide> describe("TestCases", function() {
<ide> });
<ide> });
<ide> });
<del>});
<ide>\ No newline at end of file
<add>}); | 1 |
Python | Python | destroy selenium before live server threads | 2c6079775e12366279dc0bb094ba860e4473be3c | <ide><path>django/contrib/admin/tests.py
<ide> def setUpClass(cls):
<ide>
<ide> @classmethod
<ide> def _tearDownClassInternal(cls):
<del> super(AdminSeleniumWebDriverTestCase, cls)._tearDownClassInternal()
<ide> if hasattr(cls, 'selenium'):
<ide> cls.selenium.quit()
<add> super(AdminSeleniumWebDriverTestCase, cls)._tearDownClassInternal()
<ide>
<ide> def wait_until(self, callback, timeout=10):
<ide> """ | 1 |
Javascript | Javascript | remove object3d child from scene too | 914e1c4e959696545f44c3257e42576feff80d20 | <ide><path>src/core/Object3D.js
<ide> THREE.Object3D.prototype = {
<ide> },
<ide>
<ide> remove: function ( object ) {
<add> var scene = this;
<ide>
<del> var childIndex = this.children.indexOf( object );
<add> var childIndex = this.children.indexOf( child );
<ide>
<ide> if ( childIndex !== - 1 ) {
<ide>
<del> object.parent = undefined;
<add> child.parent = undefined;
<ide> this.children.splice( childIndex, 1 );
<ide>
<add> // remove from scene
<add>
<add> while ( scene.parent !== undefined ) {
<add>
<add> scene = scene.parent;
<add>
<add> }
<add>
<add> if ( scene !== undefined && scene instanceof THREE.Scene ) {
<add>
<add> scene.removeChildRecurse( child );
<add>
<add> }
<add>
<ide> }
<ide>
<ide> }, | 1 |
Go | Go | fix golint errors for casing in api/client package | a465e26bb05083c247ba74e1092338c43c76be47 | <ide><path>api/client/build.go
<ide> func (cli *DockerCli) CmdBuild(args ...string) error {
<ide> dockerfileName := cmd.String([]string{"f", "-file"}, "", "Name of the Dockerfile (Default is 'PATH/Dockerfile')")
<ide> flMemoryString := cmd.String([]string{"m", "-memory"}, "", "Memory limit")
<ide> flMemorySwap := cmd.String([]string{"-memory-swap"}, "", "Total memory (memory + swap), '-1' to disable swap")
<del> flCpuShares := cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
<del> flCpuSetCpus := cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)")
<add> flCPUShares := cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
<add> flCPUSetCpus := cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)")
<ide>
<ide> cmd.Require(flag.Exact, 1)
<ide>
<ide> func (cli *DockerCli) CmdBuild(args ...string) error {
<ide> v.Set("pull", "1")
<ide> }
<ide>
<del> v.Set("cpusetcpus", *flCpuSetCpus)
<del> v.Set("cpushares", strconv.FormatInt(*flCpuShares, 10))
<add> v.Set("cpusetcpus", *flCPUSetCpus)
<add> v.Set("cpushares", strconv.FormatInt(*flCPUShares, 10))
<ide> v.Set("memory", strconv.FormatInt(memory, 10))
<ide> v.Set("memswap", strconv.FormatInt(memorySwap, 10))
<ide>
<ide><path>api/client/events.go
<ide> func (cli *DockerCli) CmdEvents(args ...string) error {
<ide> setTime("until", *until)
<ide> }
<ide> if len(eventFilterArgs) > 0 {
<del> filterJson, err := filters.ToParam(eventFilterArgs)
<add> filterJSON, err := filters.ToParam(eventFilterArgs)
<ide> if err != nil {
<ide> return err
<ide> }
<del> v.Set("filters", filterJson)
<add> v.Set("filters", filterJSON)
<ide> }
<ide> if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
<ide> return err
<ide><path>api/client/images.go
<ide> func (cli *DockerCli) CmdImages(args ...string) error {
<ide> "all": []string{"1"},
<ide> }
<ide> if len(imageFilterArgs) > 0 {
<del> filterJson, err := filters.ToParam(imageFilterArgs)
<add> filterJSON, err := filters.ToParam(imageFilterArgs)
<ide> if err != nil {
<ide> return err
<ide> }
<del> v.Set("filters", filterJson)
<add> v.Set("filters", filterJSON)
<ide> }
<ide>
<ide> body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false))
<ide> func (cli *DockerCli) CmdImages(args ...string) error {
<ide> } else {
<ide> v := url.Values{}
<ide> if len(imageFilterArgs) > 0 {
<del> filterJson, err := filters.ToParam(imageFilterArgs)
<add> filterJSON, err := filters.ToParam(imageFilterArgs)
<ide> if err != nil {
<ide> return err
<ide> }
<del> v.Set("filters", filterJson)
<add> v.Set("filters", filterJSON)
<ide> }
<ide>
<ide> if cmd.NArg() == 1 {
<ide><path>api/client/ps.go
<ide> func (cli *DockerCli) CmdPs(args ...string) error {
<ide> }
<ide>
<ide> if len(psFilterArgs) > 0 {
<del> filterJson, err := filters.ToParam(psFilterArgs)
<add> filterJSON, err := filters.ToParam(psFilterArgs)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> v.Set("filters", filterJson)
<add> v.Set("filters", filterJSON)
<ide> }
<ide>
<ide> body, _, err := readBody(cli.call("GET", "/containers/json?"+v.Encode(), nil, false))
<ide><path>api/client/rename.go
<ide> func (cli *DockerCli) CmdRename(args ...string) error {
<ide> cmd.Usage()
<ide> return nil
<ide> }
<del> old_name := cmd.Arg(0)
<del> new_name := cmd.Arg(1)
<add> oldName := cmd.Arg(0)
<add> newName := cmd.Arg(1)
<ide>
<del> if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/rename?name=%s", old_name, new_name), nil, false)); err != nil {
<add> if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/rename?name=%s", oldName, newName), nil, false)); err != nil {
<ide> fmt.Fprintf(cli.err, "%s\n", err)
<del> return fmt.Errorf("Error: failed to rename container named %s", old_name)
<add> return fmt.Errorf("Error: failed to rename container named %s", oldName)
<ide> }
<ide> return nil
<ide> }
<ide><path>api/client/run.go
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> defer signal.StopCatch(sigc)
<ide> }
<ide> var (
<del> waitDisplayId chan struct{}
<add> waitDisplayID chan struct{}
<ide> errCh chan error
<ide> )
<ide> if !config.AttachStdout && !config.AttachStderr {
<ide> // Make this asynchronous to allow the client to write to stdin before having to read the ID
<del> waitDisplayId = make(chan struct{})
<add> waitDisplayID = make(chan struct{})
<ide> go func() {
<del> defer close(waitDisplayId)
<add> defer close(waitDisplayID)
<ide> fmt.Fprintf(cli.out, "%s\n", createResponse.ID)
<ide> }()
<ide> }
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> // Detached mode: wait for the id to be displayed and return.
<ide> if !config.AttachStdout && !config.AttachStderr {
<ide> // Detached mode
<del> <-waitDisplayId
<add> <-waitDisplayID
<ide> return nil
<ide> }
<ide>
<ide><path>api/client/stats.go
<ide> import (
<ide>
<ide> type containerStats struct {
<ide> Name string
<del> CpuPercentage float64
<add> CPUPercentage float64
<ide> Memory float64
<ide> MemoryLimit float64
<ide> MemoryPercentage float64
<ide> func (s *containerStats) Collect(cli *DockerCli) {
<ide> }
<ide> defer stream.Close()
<ide> var (
<del> previousCpu uint64
<add> previousCPU uint64
<ide> previousSystem uint64
<ide> start = true
<ide> dec = json.NewDecoder(stream)
<ide> func (s *containerStats) Collect(cli *DockerCli) {
<ide> cpuPercent = 0.0
<ide> )
<ide> if !start {
<del> cpuPercent = calculateCpuPercent(previousCpu, previousSystem, v)
<add> cpuPercent = calculateCPUPercent(previousCPU, previousSystem, v)
<ide> }
<ide> start = false
<ide> s.mu.Lock()
<del> s.CpuPercentage = cpuPercent
<add> s.CPUPercentage = cpuPercent
<ide> s.Memory = float64(v.MemoryStats.Usage)
<ide> s.MemoryLimit = float64(v.MemoryStats.Limit)
<ide> s.MemoryPercentage = memPercent
<ide> s.NetworkRx = float64(v.Network.RxBytes)
<ide> s.NetworkTx = float64(v.Network.TxBytes)
<ide> s.mu.Unlock()
<del> previousCpu = v.CpuStats.CpuUsage.TotalUsage
<add> previousCPU = v.CpuStats.CpuUsage.TotalUsage
<ide> previousSystem = v.CpuStats.SystemUsage
<ide> u <- nil
<ide> }
<ide> func (s *containerStats) Collect(cli *DockerCli) {
<ide> // zero out the values if we have not received an update within
<ide> // the specified duration.
<ide> s.mu.Lock()
<del> s.CpuPercentage = 0
<add> s.CPUPercentage = 0
<ide> s.Memory = 0
<ide> s.MemoryPercentage = 0
<ide> s.mu.Unlock()
<ide> func (s *containerStats) Display(w io.Writer) error {
<ide> }
<ide> fmt.Fprintf(w, "%s\t%.2f%%\t%s/%s\t%.2f%%\t%s/%s\n",
<ide> s.Name,
<del> s.CpuPercentage,
<add> s.CPUPercentage,
<ide> units.BytesSize(s.Memory), units.BytesSize(s.MemoryLimit),
<ide> s.MemoryPercentage,
<ide> units.BytesSize(s.NetworkRx), units.BytesSize(s.NetworkTx))
<ide> func (cli *DockerCli) CmdStats(args ...string) error {
<ide> return nil
<ide> }
<ide>
<del>func calculateCpuPercent(previousCpu, previousSystem uint64, v *types.Stats) float64 {
<add>func calculateCPUPercent(previousCPU, previousSystem uint64, v *types.Stats) float64 {
<ide> var (
<ide> cpuPercent = 0.0
<ide> // calculate the change for the cpu usage of the container in between readings
<del> cpuDelta = float64(v.CpuStats.CpuUsage.TotalUsage - previousCpu)
<add> cpuDelta = float64(v.CpuStats.CpuUsage.TotalUsage - previousCPU)
<ide> // calculate the change for the entire system between readings
<ide> systemDelta = float64(v.CpuStats.SystemUsage - previousSystem)
<ide> )
<ide><path>api/client/utils.go
<ide> func (cli *DockerCli) resizeTty(id string, isExec bool) {
<ide> }
<ide> }
<ide>
<del>func waitForExit(cli *DockerCli, containerId string) (int, error) {
<del> stream, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil, false)
<add>func waitForExit(cli *DockerCli, containerID string) (int, error) {
<add> stream, _, err := cli.call("POST", "/containers/"+containerID+"/wait", nil, false)
<ide> if err != nil {
<ide> return -1, err
<ide> }
<ide> func waitForExit(cli *DockerCli, containerId string) (int, error) {
<ide>
<ide> // getExitCode perform an inspect on the container. It returns
<ide> // the running state and the exit code.
<del>func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
<del> stream, _, err := cli.call("GET", "/containers/"+containerId+"/json", nil, false)
<add>func getExitCode(cli *DockerCli, containerID string) (bool, int, error) {
<add> stream, _, err := cli.call("GET", "/containers/"+containerID+"/json", nil, false)
<ide> if err != nil {
<ide> // If we can't connect, then the daemon probably died.
<ide> if err != ErrConnectionRefused {
<ide> func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
<ide>
<ide> // getExecExitCode perform an inspect on the exec command. It returns
<ide> // the running state and the exit code.
<del>func getExecExitCode(cli *DockerCli, execId string) (bool, int, error) {
<del> stream, _, err := cli.call("GET", "/exec/"+execId+"/json", nil, false)
<add>func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) {
<add> stream, _, err := cli.call("GET", "/exec/"+execID+"/json", nil, false)
<ide> if err != nil {
<ide> // If we can't connect, then the daemon probably died.
<ide> if err != ErrConnectionRefused { | 8 |
Java | Java | add attributedoesnotexist modelresultmatcher | 909577082d7e4a74780bf32bf0c54a1370c76b1f | <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/ModelResultMatchers.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void match(MvcResult result) throws Exception {
<ide> };
<ide> }
<ide>
<add> /**
<add> * Assert the given model attributes do not exist
<add> */
<add> public ResultMatcher attributeDoesNotExist(final String... names) {
<add> return new ResultMatcher() {
<add> @Override
<add> public void match(MvcResult result) throws Exception {
<add> ModelAndView mav = getModelAndView(result);
<add> for (String name : names) {
<add> assertTrue("Model attribute '" + name + "' exists", mav.getModel().get(name) == null);
<add> }
<add> }
<add> };
<add> }
<add>
<ide> /**
<ide> * Assert the given model attribute(s) have errors.
<ide> */
<ide><path>spring-test-mvc/src/test/java/org/springframework/test/web/servlet/result/ModelResultMatchersTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void attributeExists_doesNotExist() throws Exception {
<ide> this.matchers.attributeExists("bad").match(this.mvcResult);
<ide> }
<ide>
<del> @Test
<add> @Test
<add> public void attributeDoesNotExist() throws Exception {
<add> this.matchers.attributeDoesNotExist("bad").match(this.mvcResult);
<add> }
<add>
<add> @Test(expected=AssertionError.class)
<add> public void attributeDoesNotExist_doesExist() throws Exception {
<add> this.matchers.attributeDoesNotExist("good").match(this.mvcResultWithError);
<add> }
<add>
<add> @Test
<ide> public void attribute_equal() throws Exception {
<ide> this.matchers.attribute("good", is("good")).match(this.mvcResult);
<ide> } | 2 |
Python | Python | pin dill to fix examples | 3fd7de49f4d53832621ef67cfd1825b000323250 | <ide><path>setup.py
<ide> "dataclasses",
<ide> "datasets",
<ide> "deepspeed>=0.6.4",
<add> "dill<0.3.5",
<ide> "fairscale>0.3",
<ide> "faiss-cpu",
<ide> "fastapi",
<ide> def run(self):
<ide> "parameterized",
<ide> "psutil",
<ide> "datasets",
<add> "dill",
<ide> "pytest-timeout",
<ide> "black",
<ide> "sacrebleu",
<ide><path>src/transformers/dependency_versions_table.py
<ide> "dataclasses": "dataclasses",
<ide> "datasets": "datasets",
<ide> "deepspeed": "deepspeed>=0.6.4",
<add> "dill": "dill<0.3.5",
<ide> "fairscale": "fairscale>0.3",
<ide> "faiss-cpu": "faiss-cpu",
<ide> "fastapi": "fastapi", | 2 |
Ruby | Ruby | fix indentation [ci skip] | 672c6cad78b102f5736f7a76ebe616e1e47ef557 | <ide><path>activerecord/test/cases/scoping/default_scoping_test.rb
<ide> def test_joins_not_affected_by_scope_other_than_default_or_unscoped
<ide> end
<ide>
<ide> def test_unscoped_with_joins_should_not_have_default_scope
<del> assert_equal Comment.joins(:post).sort_by(&:id),
<del> SpecialPostWithDefaultScope.unscoped { Comment.joins(:special_post_with_default_scope).sort_by(&:id) }
<add> assert_equal Comment.joins(:post).sort_by(&:id),
<add> SpecialPostWithDefaultScope.unscoped { Comment.joins(:special_post_with_default_scope).sort_by(&:id) }
<ide> end
<ide>
<ide> def test_sti_association_with_unscoped_not_affected_by_default_scope | 1 |
Javascript | Javascript | fix a crash with buildmeta of null | 4d77f847db9bb8e9cae78c57682e416b22ffbe80 | <ide><path>lib/RuntimeTemplate.js
<ide> module.exports = class RuntimeTemplate {
<ide>
<ide> exportFromImport({
<ide> module,
<add> request,
<ide> exportName,
<ide> originModule,
<ide> asiSafe,
<ide> isCall,
<ide> callContext,
<ide> importVar
<ide> }) {
<add> if(!module) return this.missingModule({
<add> request
<add> });
<ide> const exportsType = module.buildMeta && module.buildMeta.exportsType;
<ide>
<ide> if(!exportsType) {
<ide><path>lib/dependencies/HarmonyImportSpecifierDependency.js
<ide> HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependen
<ide> getContent(dep, runtime) {
<ide> const exportExpr = runtime.exportFromImport({
<ide> module: dep.module,
<add> request: dep.request,
<ide> exportName: dep.id,
<ide> originModule: dep.originModule,
<ide> asiSafe: dep.shorthand,
<ide><path>test/cases/errors/crash-missing-import/a.js
<add>import { x } from "./missing";
<add>
<add>x();
<ide><path>test/cases/errors/crash-missing-import/errors.js
<add>module.exports = [
<add> [/Module not found/],
<add>];
<ide><path>test/cases/errors/crash-missing-import/index.js
<add>it("should not crash when imported module is missing", function() {
<add>});
<add>
<add>require.include("./a"); | 5 |
Python | Python | fix backend regex | 254fef67cf1f54f692871147e6b4fca1ff90347e | <ide><path>utils/check_inits.py
<ide>
<ide>
<ide> # Matches is_xxx_available()
<del>_re_backend = re.compile(r"is\_([a-z]*)_available()")
<add>_re_backend = re.compile(r"is\_([a-z_]*)_available()")
<ide> # Catches a line with a key-values pattern: "bla": ["foo", "bar"]
<ide> _re_import_struct_key_value = re.compile(r'\s+"\S*":\s+\[([^\]]*)\]')
<ide> # Catches a line if is_foo_available
<del>_re_test_backend = re.compile(r"^\s*if\s+is\_[a-z]*\_available\(\)")
<add>_re_test_backend = re.compile(r"^\s*if\s+is\_[a-z_]*\_available\(\)")
<ide> # Catches a line _import_struct["bla"].append("foo")
<ide> _re_import_struct_add_one = re.compile(r'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)')
<ide> # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] | 1 |
Javascript | Javascript | add test for ascii data-uri | b9a818386aff5c745cd7ce3526fd1ee40896e42d | <ide><path>test/cases/resolving/data-uri/index.js
<del>it("should require module from data-uri", function() {
<add>it("should require js module from base64 data-uri", function() {
<ide> const mod = require("data:text/javascript;charset=utf-8;base64,bW9kdWxlLmV4cG9ydHMgPSB7CiAgbnVtYmVyOiA0MiwKICBmbjogKCkgPT4gIkhlbGxvIHdvcmxkIgp9Ow==");
<ide> expect(mod.number).toBe(42);
<ide> expect(mod.fn()).toBe("Hello world");
<ide> });
<ide>
<del>it("should import module from data-uri", function() {
<add>it("should require js module from ascii data-uri", function() {
<add> const mod = require("data:text/javascript;charset=utf-8;ascii,module.exports={number:42,fn:()=>\"Hello world\"}");
<add> expect(mod.number).toBe(42);
<add> expect(mod.fn()).toBe("Hello world");
<add>});
<add>
<add>it("should import js module from base64 data-uri", function() {
<ide> const mod = require('./module-with-imports');
<ide> expect(mod.number).toBe(42);
<ide> expect(mod.fn()).toBe("Hello world"); | 1 |
Python | Python | remove extraneous imports | a6b3c88c57bd5686dc35b2cf4cceb029b590886d | <ide><path>celery/task.py
<ide> from celery.log import setup_logger
<ide> from celery.registry import tasks
<ide> from celery.messaging import TaskPublisher, TaskConsumer
<del>from celery.models import TaskMeta
<del>from django.core.cache import cache
<ide> from datetime import timedelta
<ide> from celery.backends import default_backend
<ide> from celery.datastructures import PositionQueue | 1 |
PHP | PHP | remove unused variables and code | bc40ac7d3f5c3f5448225bff3f368db7902e9107 | <ide><path>lib/Cake/Controller/Component/Acl/PhpAcl.php
<ide> public function resolve($aco) {
<ide> * @return void
<ide> */
<ide> public function build(array $allow, array $deny = array()) {
<del> $stack = array();
<ide> $this->_tree = array();
<ide> $tree = array();
<del> $root = &$tree;
<ide>
<ide> foreach ($allow as $dotPath => $aros) {
<ide> if (is_string($aros)) {
<ide><path>lib/Cake/Controller/Controller.php
<ide> protected function _mergeControllerVars() {
<ide>
<ide> if ($mergeParent || !empty($pluginController)) {
<ide> $appVars = get_class_vars($this->_mergeParent);
<del> $uses = $appVars['uses'];
<ide> $merge = array('components', 'helpers');
<ide> $this->_mergeVars($merge, $this->_mergeParent, true);
<ide> }
<ide><path>lib/Cake/Core/Configure.php
<ide> public static function read($var = null) {
<ide> */
<ide> public static function delete($var = null) {
<ide> $keys = explode('.', $var);
<del> $last = array_pop($keys);
<ide> self::$_values = Hash::remove(self::$_values, $var);
<ide> }
<ide>
<ide><path>lib/Cake/Model/Behavior/TranslateBehavior.php
<ide> public function unbindTranslation(Model $Model, $fields = null) {
<ide> if (is_string($fields)) {
<ide> $fields = array($fields);
<ide> }
<del> $RuntimeModel = $this->translateModel($Model);
<ide> $associations = array();
<ide>
<ide> foreach ($fields as $key => $value) {
<ide><path>lib/Cake/Model/CakeSchema.php
<ide> public function read($options = array()) {
<ide> unset($currentTables[$key]);
<ide> }
<ide> if (!empty($Object->hasAndBelongsToMany)) {
<del> foreach ($Object->hasAndBelongsToMany as $Assoc => $assocData) {
<add> foreach ($Object->hasAndBelongsToMany as $assocData) {
<ide> if (isset($assocData['with'])) {
<ide> $class = $assocData['with'];
<ide> }
<ide> protected function _columns(&$Obj) {
<ide> $db = $Obj->getDataSource();
<ide> $fields = $Obj->schema(true);
<ide>
<del> $columns = $props = array();
<add> $columns = array();
<ide> foreach ($fields as $name => $value) {
<ide> if ($Obj->primaryKey == $name) {
<ide> $value['key'] = 'primary';
<ide><path>lib/Cake/Model/Datasource/CakeSession.php
<ide> public static function clear() {
<ide> */
<ide> protected static function _configureSession() {
<ide> $sessionConfig = Configure::read('Session');
<del> $iniSet = function_exists('ini_set');
<ide>
<ide> if (isset($sessionConfig['defaults'])) {
<ide> $defaults = self::_defaultConfig($sessionConfig['defaults']);
<ide><path>lib/Cake/Model/Datasource/Database/Postgres.php
<ide> public function index($model) {
<ide> )
<ide> AND c.oid = i.indrelid AND i.indexrelid = c2.oid
<ide> ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname", false);
<del> foreach ($indexes as $i => $info) {
<add> foreach ($indexes as $info) {
<ide> $key = array_pop($info);
<ide> if ($key['indisprimary']) {
<ide> $key['relname'] = 'PRIMARY';
<ide><path>lib/Cake/Model/Datasource/Database/Sqlite.php
<ide> public function index($model) {
<ide> if (is_bool($indexes)) {
<ide> return array();
<ide> }
<del> foreach ($indexes as $i => $info) {
<add> foreach ($indexes as $info) {
<ide> $key = array_pop($info);
<ide> $keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
<ide> foreach ($keyInfo as $keyCol) {
<ide><path>lib/Cake/Model/Datasource/DboSource.php
<ide> public function queryAssociation(Model $model, &$linkModel, $type, $association,
<ide> }
<ide> }
<ide> if ($type === 'hasAndBelongsToMany') {
<del> $uniqueIds = $merge = array();
<add> $merge = array();
<ide>
<del> foreach ($fetch as $j => $data) {
<add> foreach ($fetch as $data) {
<ide> if (isset($data[$with]) && $data[$with][$foreignKey] === $row[$modelAlias][$modelPK]) {
<ide> if ($habtmFieldsCount <= 2) {
<ide> unset($data[$with]);
<ide> protected function _mergeAssociation(&$data, &$merge, $association, $type, $self
<ide> $data[$association] = array();
<ide> }
<ide> } else {
<del> foreach ($merge as $i => $row) {
<add> foreach ($merge as $row) {
<ide> $insert = array();
<ide> if (count($row) === 1) {
<ide> $insert = $row[$association];
<ide> public function conditions($conditions, $quoteValues = true, $where = true, $mod
<ide> }
<ide> $clauses = '/^WHERE\\x20|^GROUP\\x20BY\\x20|^HAVING\\x20|^ORDER\\x20BY\\x20/i';
<ide>
<del> if (preg_match($clauses, $conditions, $match)) {
<add> if (preg_match($clauses, $conditions)) {
<ide> $clause = '';
<ide> }
<ide> $conditions = $this->_quoteFields($conditions);
<ide> public function insertMulti($table, $fields, $values) {
<ide> $columnMap[$key] = $pdoMap[$type];
<ide> }
<ide>
<del> foreach ($values as $row => $value) {
<add> foreach ($values as $value) {
<ide> $i = 1;
<ide> foreach ($value as $col => $val) {
<ide> $statement->bindValue($i, $val, $columnMap[$col]);
<ide> public function introspectType($value) {
<ide>
<ide> $isAllFloat = $isAllInt = true;
<ide> $containsFloat = $containsInt = $containsString = false;
<del> foreach ($value as $key => $valElement) {
<add> foreach ($value as $valElement) {
<ide> $valElement = trim($valElement);
<ide> if (!is_float($valElement) && !preg_match('/^[\d]+\.[\d]+$/', $valElement)) {
<ide> $isAllFloat = false;
<ide><path>lib/Cake/Model/Model.php
<ide> public function delete($id = null, $cascade = true) {
<ide>
<ide> $updateCounterCache = false;
<ide> if (!empty($this->belongsTo)) {
<del> foreach ($this->belongsTo as $parent => $assoc) {
<add> foreach ($this->belongsTo as $assoc) {
<ide> if (!empty($assoc['counterCache'])) {
<ide> $updateCounterCache = true;
<ide> break;
<ide> protected function _deleteDependent($id, $cascade) {
<ide> * @return void
<ide> */
<ide> protected function _deleteLinks($id) {
<del> foreach ($this->hasAndBelongsToMany as $assoc => $data) {
<add> foreach ($this->hasAndBelongsToMany as $data) {
<ide> list($plugin, $joinModel) = pluginSplit($data['with']);
<ide> $records = $this->{$joinModel}->find('all', array(
<ide> 'conditions' => array($this->{$joinModel}->escapeField($data['foreignKey']) => $id),
<ide> public function invalidate($field, $value = true) {
<ide> public function isForeignKey($field) {
<ide> $foreignKeys = array();
<ide> if (!empty($this->belongsTo)) {
<del> foreach ($this->belongsTo as $assoc => $data) {
<add> foreach ($this->belongsTo as $data) {
<ide> $foreignKeys[] = $data['foreignKey'];
<ide> }
<ide> }
<ide><path>lib/Cake/Network/CakeRequest.php
<ide> public function subdomains($tldLength = 1) {
<ide> public function accepts($type = null) {
<ide> $raw = $this->parseAccept();
<ide> $accept = array();
<del> foreach ($raw as $value => $types) {
<add> foreach ($raw as $types) {
<ide> $accept = array_merge($accept, $types);
<ide> }
<ide> if ($type === null) {
<ide><path>lib/Cake/Utility/ClassRegistry.php
<ide> public static function init($class, $strict = false) {
<ide> }
<ide>
<ide> if (!isset($instance)) {
<del> trigger_error(__d('cake_dev', '(ClassRegistry::init() could not create instance of %1$s class %2$s ', $class, $type), E_USER_WARNING);
<add> trigger_error(__d('cake_dev', '(ClassRegistry::init() could not create instance of %s', $class), E_USER_WARNING);
<ide> return $false;
<ide> }
<ide> }
<ide><path>lib/Cake/Utility/Debugger.php
<ide> public static function showError($code, $description, $file = null, $line = null
<ide> if (empty($line)) {
<ide> $line = '??';
<ide> }
<del> $path = self::trimPath($file);
<ide>
<ide> $info = compact('code', 'description', 'file', 'line');
<ide> if (!in_array($info, $self->errors)) {
<ide><path>lib/Cake/Utility/Folder.php
<ide> public function chmod($path, $mode = false, $recursive = true, $exceptions = arr
<ide> $paths = $this->tree($path);
<ide>
<ide> foreach ($paths as $type) {
<del> foreach ($type as $key => $fullpath) {
<add> foreach ($type as $fullpath) {
<ide> $check = explode(DS, $fullpath);
<ide> $count = count($check);
<ide>
<ide><path>lib/Cake/Utility/Hash.php
<ide> public static function contains(array $data, array $needle) {
<ide> }
<ide> $stack = array();
<ide>
<del> $i = 1;
<ide> while (!empty($needle)) {
<ide> $key = key($needle);
<ide> $val = $needle[$key];
<ide><path>lib/Cake/View/Helper/FormHelper.php
<ide> protected function _introspectModel($model, $key, $field = null) {
<ide>
<ide> if ($key === 'fields') {
<ide> if (!isset($this->fieldset[$model]['fields'])) {
<del> $fields = $this->fieldset[$model]['fields'] = $object->schema();
<add> $this->fieldset[$model]['fields'] = $object->schema();
<ide> foreach ($object->hasAndBelongsToMany as $alias => $assocData) {
<ide> $this->fieldset[$object->alias]['fields'][$alias] = array('type' => 'multiple');
<ide> }
<ide> public function create($model = null, $options = array()) {
<ide>
<ide> $key = null;
<ide> if ($model !== false) {
<del> $object = $this->_getModel($model);
<ide> $key = $this->_introspectModel($model, 'key');
<ide> $this->setEntity($model, true);
<ide> }
<ide><path>lib/Cake/View/Helper/MootoolsEngineHelper.php
<ide> public function request($url, $options = array()) {
<ide> $options['url'] = $url;
<ide> $options = $this->_prepareCallbacks('request', $options);
<ide> if (!empty($options['dataExpression'])) {
<del> $callbacks[] = 'data';
<ide> unset($options['dataExpression']);
<ide> } elseif (!empty($data)) {
<ide> $data = $this->object($data);
<ide><path>lib/Cake/View/Helper/PrototypeEngineHelper.php
<ide> public function request($url, $options = array()) {
<ide> $url = '"' . $this->url($url) . '"';
<ide> $options = $this->_mapOptions('request', $options);
<ide> $type = '.Request';
<del> $data = null;
<ide> if (isset($options['type']) && strtolower($options['type']) == 'json') {
<ide> unset($options['type']);
<ide> }
<ide><path>lib/Cake/View/Helper/RssHelper.php
<ide> public function elem($name, $attrib = array(), $content = null, $endTag = true)
<ide> $nodes->item(0)->setAttribute($key, $value);
<ide> }
<ide> }
<del> foreach ($children as $k => $child) {
<add> foreach ($children as $child) {
<ide> $child = $elem->createElement($name, $child);
<ide> $nodes->item(0)->appendChild($child);
<ide> }
<ide><path>lib/Cake/View/Helper/TimeHelper.php
<ide> public function toRSS($dateString, $timezone = null) {
<ide> */
<ide> public function timeAgoInWords($dateTime, $options = array()) {
<ide> $element = null;
<del> $stringDate = '';
<ide>
<ide> if (is_array($options) && !empty($options['element'])) {
<ide> $element = array(
<ide><path>lib/Cake/View/MediaView.php
<ide> public function render($view = null, $layout = null) {
<ide>
<ide> if ($this->_isActive()) {
<ide> $extension = strtolower($extension);
<del> $chunkSize = 8192;
<del> $buffer = '';
<ide> $fileSize = @filesize($path);
<ide> $handle = fopen($path, 'rb');
<ide>
<ide><path>lib/Cake/View/View.php
<ide> class View extends Object {
<ide> */
<ide> protected $_eventManager = null;
<ide>
<del>/**
<del> * The view file to be rendered, only used inside _execute()
<del> */
<del> private $__viewFileName = null;
<del>
<ide> /**
<ide> * Whether the event manager was already configured for this object
<ide> *
<ide> public function __isset($name) {
<ide> */
<ide> public function loadHelpers() {
<ide> $helpers = HelperCollection::normalizeObjectArray($this->helpers);
<del> foreach ($helpers as $name => $properties) {
<add> foreach ($helpers as $properties) {
<ide> list($plugin, $class) = pluginSplit($properties['class']);
<ide> $this->{$class} = $this->Helpers->load($properties['class'], $properties['settings']);
<ide> } | 22 |
Text | Text | replace anonymous function with arrow function | 9fe02af79425ae455e888ce2b99f86448d0053e6 | <ide><path>doc/guides/writing-and-running-benchmarks.md
<ide> function main(conf) {
<ide> const http = require('http');
<ide> const len = conf.kb * 1024;
<ide> const chunk = Buffer.alloc(len, 'x');
<del> const server = http.createServer(function(req, res) {
<add> const server = http.createServer((req, res) => {
<ide> res.end(chunk);
<ide> });
<ide>
<del> server.listen(common.PORT, function() {
<add> server.listen(common.PORT, () => {
<ide> bench.http({
<ide> connections: conf.connections,
<del> }, function() {
<add> }, () => {
<ide> server.close();
<ide> });
<ide> }); | 1 |
PHP | PHP | create factory modifiers | 1a4c410edfe723ab7d873392eab165e37fd65e33 | <ide><path>src/Illuminate/Database/Eloquent/Factory.php
<ide> public function __construct(Faker $faker)
<ide> */
<ide> protected $definitions = [];
<ide>
<add> /**
<add> * The model modifiers in the container.
<add> *
<add> * @var array
<add> */
<add> protected $modifiers = [];
<add>
<ide> /**
<ide> * Create a new factory container.
<ide> *
<ide> public function define($class, callable $attributes, $name = 'default')
<ide> $this->definitions[$class][$name] = $attributes;
<ide> }
<ide>
<add> /**
<add> * Define a modifier with a given set of attributes.
<add> *
<add> * @param string $class
<add> * @param string $name
<add> * @param callable $attributes
<add> * @return void
<add> */
<add> public function defineModifier($class, $name, callable $attributes)
<add> {
<add> $this->modifiers[$class][$name] = $attributes;
<add> }
<add>
<ide> /**
<ide> * Create an instance of the given model and persist it to the database.
<ide> *
<ide> public function raw($class, array $attributes = [], $name = 'default')
<ide> */
<ide> public function of($class, $name = 'default')
<ide> {
<del> return new FactoryBuilder($class, $name, $this->definitions, $this->faker);
<add> return new FactoryBuilder($class, $name, $this->definitions, $this->faker, $this->modifiers);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Eloquent/FactoryBuilder.php
<ide> class FactoryBuilder
<ide> */
<ide> protected $definitions;
<ide>
<add> /**
<add> * The model modifiers in the container.
<add> *
<add> * @var array
<add> */
<add> protected $modifiers;
<add>
<ide> /**
<ide> * The model being built.
<ide> *
<ide> class FactoryBuilder
<ide> */
<ide> protected $amount = 1;
<ide>
<add> /**
<add> * The modifiers to apply.
<add> *
<add> * @var array
<add> */
<add> protected $activeModifiers = [];
<add>
<ide> /**
<ide> * The Faker instance for the builder.
<ide> *
<ide> class FactoryBuilder
<ide> * @param string $name
<ide> * @param array $definitions
<ide> * @param \Faker\Generator $faker
<add> * @param array $modifiers
<ide> * @return void
<ide> */
<del> public function __construct($class, $name, array $definitions, Faker $faker)
<add> public function __construct($class, $name, array $definitions, Faker $faker, array $modifiers)
<ide> {
<ide> $this->name = $name;
<ide> $this->class = $class;
<ide> $this->faker = $faker;
<ide> $this->definitions = $definitions;
<add> $this->modifiers = $modifiers;
<ide> }
<ide>
<ide> /**
<ide> public function times($amount)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Set the active modifiers.
<add> *
<add> * @param array|string $modifiers
<add> * @return $this
<add> */
<add> public function modifiers($modifiers)
<add> {
<add> if(is_string($modifiers)){
<add> $modifiers = [$modifiers];
<add> }
<add>
<add> $this->activeModifiers = $modifiers;
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Create a collection of models and persist them to the database.
<ide> *
<ide> protected function makeInstance(array $attributes = [])
<ide> $this->faker, $attributes
<ide> );
<ide>
<add> foreach($this->activeModifiers as $activeModifier){
<add> if( ! isset($this->modifiers[$this->class][$activeModifier])) {
<add> throw new InvalidArgumentException("Unable to locate factory modifier with name [{$activeModifier}] [{$this->class}].");
<add> }
<add>
<add> $modifier = call_user_func(
<add> $this->modifiers[$this->class][$activeModifier],
<add> $this->faker, $attributes
<add> );
<add>
<add> $definition = array_merge($definition, $modifier);
<add> }
<add>
<ide> $evaluated = $this->callClosureAttributes(
<ide> array_merge($definition, $attributes)
<ide> ); | 2 |
PHP | PHP | remove files resurrected in merge | 211e4a577bbae594ea49044a8494fcbc122a5a8c | <ide><path>lib/Cake/Test/Case/Core/ObjectTest.php
<del><?php
<del>/**
<del> * ObjectTest file
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.Core
<del> * @since CakePHP(tm) v 1.2.0.5432
<del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<del> */
<del>
<del>App::uses('Object', 'Core');
<del>App::uses('Router', 'Routing');
<del>App::uses('Controller', 'Controller');
<del>App::uses('Model', 'Model');
<del>
<del>/**
<del> * RequestActionPost class
<del> *
<del> * @package Cake.Test.Case.Core
<del> */
<del>class RequestActionPost extends CakeTestModel {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ControllerPost'
<del> */
<del> public $name = 'RequestActionPost';
<del>
<del>/**
<del> * useTable property
<del> *
<del> * @var string 'posts'
<del> */
<del> public $useTable = 'posts';
<del>}
<del>
<del>/**
<del> * RequestActionController class
<del> *
<del> * @package Cake.Test.Case.Core
<del> */
<del>class RequestActionController extends Controller {
<del>
<del>/**
<del> * uses property
<del> *
<del> * @var array
<del> * @access public
<del> */
<del> public $uses = array('RequestActionPost');
<del>
<del>/**
<del> * test_request_action method
<del> *
<del> * @access public
<del> * @return void
<del> */
<del> public function test_request_action() {
<del> return 'This is a test';
<del> }
<del>
<del>/**
<del> * another_ra_test method
<del> *
<del> * @param mixed $id
<del> * @param mixed $other
<del> * @access public
<del> * @return void
<del> */
<del> public function another_ra_test($id, $other) {
<del> return $id + $other;
<del> }
<del>
<del>/**
<del> * normal_request_action method
<del> *
<del> * @return void
<del> */
<del> public function normal_request_action() {
<del> return 'Hello World';
<del> }
<del>
<del>/**
<del> * returns $this->here
<del> *
<del> * @return void
<del> */
<del> public function return_here() {
<del> return $this->here;
<del> }
<del>
<del>/**
<del> * paginate_request_action method
<del> *
<del> * @return void
<del> */
<del> public function paginate_request_action() {
<del> $this->paginate();
<del> return true;
<del> }
<del>
<del>/**
<del> * post pass, testing post passing
<del> *
<del> * @return array
<del> */
<del> public function post_pass() {
<del> return $this->request->data;
<del> }
<del>
<del>/**
<del> * test param passing and parsing.
<del> *
<del> * @return array
<del> */
<del> public function params_pass() {
<del> return $this->request;
<del> }
<del>
<del> public function param_check() {
<del> $this->autoRender = false;
<del> $content = '';
<del> if (isset($this->request->params[0])) {
<del> $content = 'return found';
<del> }
<del> $this->response->body($content);
<del> }
<del>
<del>}
<del>
<del>/**
<del> * TestObject class
<del> *
<del> * @package Cake.Test.Case.Core
<del> */
<del>class TestObject extends Object {
<del>
<del>/**
<del> * firstName property
<del> *
<del> * @var string 'Joel'
<del> */
<del> public $firstName = 'Joel';
<del>
<del>/**
<del> * lastName property
<del> *
<del> * @var string 'Moss'
<del> */
<del> public $lastName = 'Moss';
<del>
<del>/**
<del> * methodCalls property
<del> *
<del> * @var array
<del> */
<del> public $methodCalls = array();
<del>
<del>/**
<del> * emptyMethod method
<del> *
<del> * @return void
<del> */
<del> public function emptyMethod() {
<del> $this->methodCalls[] = 'emptyMethod';
<del> }
<del>
<del>/**
<del> * oneParamMethod method
<del> *
<del> * @param mixed $param
<del> * @return void
<del> */
<del> public function oneParamMethod($param) {
<del> $this->methodCalls[] = array('oneParamMethod' => array($param));
<del> }
<del>
<del>/**
<del> * twoParamMethod method
<del> *
<del> * @param mixed $param
<del> * @param mixed $paramTwo
<del> * @return void
<del> */
<del> public function twoParamMethod($param, $paramTwo) {
<del> $this->methodCalls[] = array('twoParamMethod' => array($param, $paramTwo));
<del> }
<del>
<del>/**
<del> * threeParamMethod method
<del> *
<del> * @param mixed $param
<del> * @param mixed $paramTwo
<del> * @param mixed $paramThree
<del> * @return void
<del> */
<del> public function threeParamMethod($param, $paramTwo, $paramThree) {
<del> $this->methodCalls[] = array('threeParamMethod' => array($param, $paramTwo, $paramThree));
<del> }
<del>
<del>/**
<del> * fourParamMethod method
<del> *
<del> * @param mixed $param
<del> * @param mixed $paramTwo
<del> * @param mixed $paramThree
<del> * @param mixed $paramFour
<del> * @return void
<del> */
<del> public function fourParamMethod($param, $paramTwo, $paramThree, $paramFour) {
<del> $this->methodCalls[] = array('fourParamMethod' => array($param, $paramTwo, $paramThree, $paramFour));
<del> }
<del>
<del>/**
<del> * fiveParamMethod method
<del> *
<del> * @param mixed $param
<del> * @param mixed $paramTwo
<del> * @param mixed $paramThree
<del> * @param mixed $paramFour
<del> * @param mixed $paramFive
<del> * @return void
<del> */
<del> public function fiveParamMethod($param, $paramTwo, $paramThree, $paramFour, $paramFive) {
<del> $this->methodCalls[] = array('fiveParamMethod' => array($param, $paramTwo, $paramThree, $paramFour, $paramFive));
<del> }
<del>
<del>/**
<del> * crazyMethod method
<del> *
<del> * @param mixed $param
<del> * @param mixed $paramTwo
<del> * @param mixed $paramThree
<del> * @param mixed $paramFour
<del> * @param mixed $paramFive
<del> * @param mixed $paramSix
<del> * @param mixed $paramSeven
<del> * @return void
<del> */
<del> public function crazyMethod($param, $paramTwo, $paramThree, $paramFour, $paramFive, $paramSix, $paramSeven = null) {
<del> $this->methodCalls[] = array('crazyMethod' => array($param, $paramTwo, $paramThree, $paramFour, $paramFive, $paramSix, $paramSeven));
<del> }
<del>
<del>/**
<del> * methodWithOptionalParam method
<del> *
<del> * @param mixed $param
<del> * @return void
<del> */
<del> public function methodWithOptionalParam($param = null) {
<del> $this->methodCalls[] = array('methodWithOptionalParam' => array($param));
<del> }
<del>
<del>/**
<del> * undocumented function
<del> *
<del> * @return void
<del> */
<del> public function set($properties = array()) {
<del> return parent::_set($properties);
<del> }
<del>
<del>}
<del>
<del>/**
<del> * ObjectTestModel class
<del> *
<del> * @package Cake.Test.Case.Core
<del> */
<del>class ObjectTestModel extends CakeTestModel {
<del>
<del> public $useTable = false;
<del>
<del> public $name = 'ObjectTestModel';
<del>
<del>}
<del>
<del>/**
<del> * Object Test class
<del> *
<del> * @package Cake.Test.Case.Core
<del> */
<del>class ObjectTest extends CakeTestCase {
<del>
<del>/**
<del> * fixtures
<del> *
<del> * @var string
<del> */
<del> public $fixtures = array('core.post', 'core.test_plugin_comment', 'core.comment');
<del>
<del>/**
<del> * setUp method
<del> *
<del> * @return void
<del> */
<del> public function setUp() {
<del> parent::setUp();
<del> $this->object = new TestObject();
<del> }
<del>
<del>/**
<del> * tearDown method
<del> *
<del> * @return void
<del> */
<del> public function tearDown() {
<del> parent::tearDown();
<del> CakePlugin::unload();
<del> unset($this->object);
<del> }
<del>
<del>/**
<del> * testLog method
<del> *
<del> * @return void
<del> */
<del> public function testLog() {
<del> if (file_exists(LOGS . 'error.log')) {
<del> unlink(LOGS . 'error.log');
<del> }
<del> $this->assertTrue($this->object->log('Test warning 1'));
<del> $this->assertTrue($this->object->log(array('Test' => 'warning 2')));
<del> $result = file(LOGS . 'error.log');
<del> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Error: Test warning 1$/', $result[0]);
<del> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Error: Array$/', $result[1]);
<del> $this->assertRegExp('/^\($/', $result[2]);
<del> $this->assertRegExp('/\[Test\] => warning 2$/', $result[3]);
<del> $this->assertRegExp('/^\)$/', $result[4]);
<del> unlink(LOGS . 'error.log');
<del>
<del> $this->assertTrue($this->object->log('Test warning 1', LOG_WARNING));
<del> $this->assertTrue($this->object->log(array('Test' => 'warning 2'), LOG_WARNING));
<del> $result = file(LOGS . 'error.log');
<del> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 1$/', $result[0]);
<del> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Array$/', $result[1]);
<del> $this->assertRegExp('/^\($/', $result[2]);
<del> $this->assertRegExp('/\[Test\] => warning 2$/', $result[3]);
<del> $this->assertRegExp('/^\)$/', $result[4]);
<del> unlink(LOGS . 'error.log');
<del> }
<del>
<del>/**
<del> * testSet method
<del> *
<del> * @return void
<del> */
<del> public function testSet() {
<del> $this->object->set('a string');
<del> $this->assertEquals('Joel', $this->object->firstName);
<del>
<del> $this->object->set(array('firstName'));
<del> $this->assertEquals('Joel', $this->object->firstName);
<del>
<del> $this->object->set(array('firstName' => 'Ashley'));
<del> $this->assertEquals('Ashley', $this->object->firstName);
<del>
<del> $this->object->set(array('firstName' => 'Joel', 'lastName' => 'Moose'));
<del> $this->assertEquals('Joel', $this->object->firstName);
<del> $this->assertEquals('Moose', $this->object->lastName);
<del> }
<del>
<del>/**
<del> * testToString method
<del> *
<del> * @return void
<del> */
<del> public function testToString() {
<del> $result = strtolower($this->object->toString());
<del> $this->assertEquals('testobject', $result);
<del> }
<del>
<del>/**
<del> * testMethodDispatching method
<del> *
<del> * @return void
<del> */
<del> public function testMethodDispatching() {
<del> $this->object->emptyMethod();
<del> $expected = array('emptyMethod');
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object->oneParamMethod('Hello');
<del> $expected[] = array('oneParamMethod' => array('Hello'));
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object->twoParamMethod(true, false);
<del> $expected[] = array('twoParamMethod' => array(true, false));
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object->threeParamMethod(true, false, null);
<del> $expected[] = array('threeParamMethod' => array(true, false, null));
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object->crazyMethod(1, 2, 3, 4, 5, 6, 7);
<del> $expected[] = array('crazyMethod' => array(1, 2, 3, 4, 5, 6, 7));
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object = new TestObject();
<del> $this->assertSame($this->object->methodCalls, array());
<del>
<del> $this->object->dispatchMethod('emptyMethod');
<del> $expected = array('emptyMethod');
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object->dispatchMethod('oneParamMethod', array('Hello'));
<del> $expected[] = array('oneParamMethod' => array('Hello'));
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object->dispatchMethod('twoParamMethod', array(true, false));
<del> $expected[] = array('twoParamMethod' => array(true, false));
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object->dispatchMethod('threeParamMethod', array(true, false, null));
<del> $expected[] = array('threeParamMethod' => array(true, false, null));
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object->dispatchMethod('fourParamMethod', array(1, 2, 3, 4));
<del> $expected[] = array('fourParamMethod' => array(1, 2, 3, 4));
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object->dispatchMethod('fiveParamMethod', array(1, 2, 3, 4, 5));
<del> $expected[] = array('fiveParamMethod' => array(1, 2, 3, 4, 5));
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object->dispatchMethod('crazyMethod', array(1, 2, 3, 4, 5, 6, 7));
<del> $expected[] = array('crazyMethod' => array(1, 2, 3, 4, 5, 6, 7));
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object->dispatchMethod('methodWithOptionalParam', array('Hello'));
<del> $expected[] = array('methodWithOptionalParam' => array("Hello"));
<del> $this->assertSame($this->object->methodCalls, $expected);
<del>
<del> $this->object->dispatchMethod('methodWithOptionalParam');
<del> $expected[] = array('methodWithOptionalParam' => array(null));
<del> $this->assertSame($this->object->methodCalls, $expected);
<del> }
<del>
<del>/**
<del> * testRequestAction method
<del> *
<del> * @return void
<del> */
<del> public function testRequestAction() {
<del> App::build(array(
<del> 'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS),
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS),
<del> 'Controller' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Controller' . DS)
<del> ), App::RESET);
<del> $this->assertNull(Router::getRequest(), 'request stack should be empty.');
<del>
<del> $result = $this->object->requestAction('');
<del> $this->assertFalse($result);
<del>
<del> $result = $this->object->requestAction('/request_action/test_request_action');
<del> $expected = 'This is a test';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction(FULL_BASE_URL . '/request_action/test_request_action');
<del> $expected = 'This is a test';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction('/request_action/another_ra_test/2/5');
<del> $expected = 7;
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction('/tests_apps/index', array('return'));
<del> $expected = 'This is the TestsAppsController index view ';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction('/tests_apps/some_method');
<del> $expected = 5;
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction('/request_action/paginate_request_action');
<del> $this->assertTrue($result);
<del>
<del> $result = $this->object->requestAction('/request_action/normal_request_action');
<del> $expected = 'Hello World';
<del> $this->assertEquals($expected, $result);
<del>
<del> $this->assertNull(Router::getRequest(), 'requests were not popped off the stack, this will break url generation');
<del> }
<del>
<del>/**
<del> * test requestAction() and plugins.
<del> *
<del> * @return void
<del> */
<del> public function testRequestActionPlugins() {
<del> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
<del> ), App::RESET);
<del> CakePlugin::load('TestPlugin');
<del> Router::reload();
<del>
<del> $result = $this->object->requestAction('/test_plugin/tests/index', array('return'));
<del> $expected = 'test plugin index';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction('/test_plugin/tests/index/some_param', array('return'));
<del> $expected = 'test plugin index';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction(
<del> array('controller' => 'tests', 'action' => 'index', 'plugin' => 'test_plugin'), array('return')
<del> );
<del> $expected = 'test plugin index';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction('/test_plugin/tests/some_method');
<del> $expected = 25;
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction(
<del> array('controller' => 'tests', 'action' => 'some_method', 'plugin' => 'test_plugin')
<del> );
<del> $expected = 25;
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<del>/**
<del> * test requestAction() with arrays.
<del> *
<del> * @return void
<del> */
<del> public function testRequestActionArray() {
<del> App::build(array(
<del> 'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS),
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS),
<del> 'Controller' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Controller' . DS),
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<del> ), App::RESET);
<del> CakePlugin::load(array('TestPlugin'));
<del>
<del> $result = $this->object->requestAction(
<del> array('controller' => 'request_action', 'action' => 'test_request_action')
<del> );
<del> $expected = 'This is a test';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction(
<del> array('controller' => 'request_action', 'action' => 'another_ra_test'),
<del> array('pass' => array('5', '7'))
<del> );
<del> $expected = 12;
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction(
<del> array('controller' => 'tests_apps', 'action' => 'index'), array('return')
<del> );
<del> $expected = 'This is the TestsAppsController index view ';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction(array('controller' => 'tests_apps', 'action' => 'some_method'));
<del> $expected = 5;
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction(
<del> array('controller' => 'request_action', 'action' => 'normal_request_action')
<del> );
<del> $expected = 'Hello World';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction(
<del> array('controller' => 'request_action', 'action' => 'paginate_request_action')
<del> );
<del> $this->assertTrue($result);
<del>
<del> $result = $this->object->requestAction(
<del> array('controller' => 'request_action', 'action' => 'paginate_request_action'),
<del> array('pass' => array(5), 'named' => array('param' => 'value'))
<del> );
<del> $this->assertTrue($result);
<del> }
<del>
<del>/**
<del> * Test that requestAction() does not forward the 0 => return value.
<del> *
<del> * @return void
<del> */
<del> public function testRequestActionRemoveReturnParam() {
<del> $result = $this->object->requestAction(
<del> '/request_action/param_check', array('return')
<del> );
<del> $this->assertEquals('', $result, 'Return key was found');
<del> }
<del>
<del>/**
<del> * Test that requestAction() is populating $this->params properly
<del> *
<del> * @return void
<del> */
<del> public function testRequestActionParamParseAndPass() {
<del> $result = $this->object->requestAction('/request_action/params_pass');
<del> $this->assertEquals('request_action/params_pass', $result->url);
<del> $this->assertEquals('request_action', $result['controller']);
<del> $this->assertEquals('params_pass', $result['action']);
<del> $this->assertEquals(null, $result['plugin']);
<del>
<del> $result = $this->object->requestAction('/request_action/params_pass/sort:desc/limit:5');
<del> $expected = array('sort' => 'desc', 'limit' => 5,);
<del> $this->assertEquals($expected, $result['named']);
<del>
<del> $result = $this->object->requestAction(
<del> array('controller' => 'request_action', 'action' => 'params_pass'),
<del> array('named' => array('sort' => 'desc', 'limit' => 5))
<del> );
<del> $this->assertEquals($expected, $result['named']);
<del> }
<del>
<del>/**
<del> * Test that requestAction handles get parameters correctly.
<del> *
<del> * @return void
<del> */
<del> public function testRequestActionGetParameters() {
<del> $result = $this->object->requestAction(
<del> '/request_action/params_pass?get=value&limit=5'
<del> );
<del> $this->assertEquals('value', $result->query['get']);
<del>
<del> $result = $this->object->requestAction(
<del> array('controller' => 'request_action', 'action' => 'params_pass'),
<del> array('url' => array('get' => 'value', 'limit' => 5))
<del> );
<del> $this->assertEquals('value', $result->query['get']);
<del> }
<del>
<del>/**
<del> * test that requestAction does not fish data out of the POST
<del> * superglobal.
<del> *
<del> * @return void
<del> */
<del> public function testRequestActionNoPostPassing() {
<del> $_tmp = $_POST;
<del>
<del> $_POST = array('data' => array(
<del> 'item' => 'value'
<del> ));
<del> $result = $this->object->requestAction(array('controller' => 'request_action', 'action' => 'post_pass'));
<del> $this->assertEmpty($result);
<del>
<del> $result = $this->object->requestAction(
<del> array('controller' => 'request_action', 'action' => 'post_pass'),
<del> array('data' => $_POST['data'])
<del> );
<del> $expected = $_POST['data'];
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->object->requestAction('/request_action/post_pass');
<del> $expected = $_POST['data'];
<del> $this->assertEquals($expected, $result);
<del>
<del> $_POST = $_tmp;
<del> }
<del>
<del>/**
<del> * Test requestAction with post data.
<del> *
<del> * @return void
<del> */
<del> public function testRequestActionPostWithData() {
<del> $data = array(
<del> 'Post' => array('id' => 2)
<del> );
<del> $result = $this->object->requestAction(
<del> array('controller' => 'request_action', 'action' => 'post_pass'),
<del> array('data' => $data)
<del> );
<del> $this->assertEquals($data, $result);
<del>
<del> $result = $this->object->requestAction(
<del> '/request_action/post_pass',
<del> array('data' => $data)
<del> );
<del> $this->assertEquals($data, $result);
<del> }
<del>}
<ide><path>lib/Cake/Test/Case/Log/CakeLogTest.php
<del><?php
<del>/**
<del> * CakeLogTest file
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.Log
<del> * @since CakePHP(tm) v 1.2.0.5432
<del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<del> */
<del>
<del>App::uses('CakeLog', 'Log');
<del>App::uses('FileLog', 'Log/Engine');
<del>
<del>/**
<del> * CakeLogTest class
<del> *
<del> * @package Cake.Test.Case.Log
<del> */
<del>class CakeLogTest extends CakeTestCase {
<del>
<del>/**
<del> * Start test callback, clears all streams enabled.
<del> *
<del> * @return void
<del> */
<del> public function setUp() {
<del> parent::setUp();
<del> $streams = CakeLog::configured();
<del> foreach ($streams as $stream) {
<del> CakeLog::drop($stream);
<del> }
<del> }
<del>
<del>/**
<del> * test importing loggers from app/libs and plugins.
<del> *
<del> * @return void
<del> */
<del> public function testImportingLoggers() {
<del> App::build(array(
<del> 'Lib' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Lib' . DS),
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<del> ), App::RESET);
<del> CakePlugin::load('TestPlugin');
<del>
<del> $result = CakeLog::config('libtest', array(
<del> 'engine' => 'TestAppLog'
<del> ));
<del> $this->assertTrue($result);
<del> $this->assertEquals(CakeLog::configured(), array('libtest'));
<del>
<del> $result = CakeLog::config('plugintest', array(
<del> 'engine' => 'TestPlugin.TestPluginLog'
<del> ));
<del> $this->assertTrue($result);
<del> $this->assertEquals(CakeLog::configured(), array('libtest', 'plugintest'));
<del>
<del> CakeLog::write(LOG_INFO, 'TestPluginLog is not a BaseLog descendant');
<del>
<del> App::build();
<del> CakePlugin::unload();
<del> }
<del>
<del>/**
<del> * test all the errors from failed logger imports
<del> *
<del> * @expectedException CakeLogException
<del> * @return void
<del> */
<del> public function testImportingLoggerFailure() {
<del> CakeLog::config('fail', array());
<del> }
<del>
<del>/**
<del> * test config() with valid key name
<del> *
<del> * @return void
<del> */
<del> public function testValidKeyName() {
<del> CakeLog::config('valid', array('engine' => 'FileLog'));
<del> $stream = CakeLog::stream('valid');
<del> $this->assertInstanceOf('FileLog', $stream);
<del> CakeLog::drop('valid');
<del> }
<del>
<del>/**
<del> * test config() with invalid key name
<del> *
<del> * @expectedException CakeLogException
<del> * @return void
<del> */
<del> public function testInvalidKeyName() {
<del> CakeLog::config('1nv', array('engine' => 'FileLog'));
<del> }
<del>
<del>/**
<del> * test that loggers have to implement the correct interface.
<del> *
<del> * @expectedException CakeLogException
<del> * @return void
<del> */
<del> public function testNotImplementingInterface() {
<del> CakeLog::config('fail', array('engine' => 'stdClass'));
<del> }
<del>
<del>/**
<del> * Test that CakeLog autoconfigures itself to use a FileLogger with the LOGS dir.
<del> * When no streams are there.
<del> *
<del> * @return void
<del> */
<del> public function testAutoConfig() {
<del> if (file_exists(LOGS . 'error.log')) {
<del> unlink(LOGS . 'error.log');
<del> }
<del> CakeLog::write(LOG_WARNING, 'Test warning');
<del> $this->assertTrue(file_exists(LOGS . 'error.log'));
<del>
<del> $result = CakeLog::configured();
<del> $this->assertEquals(array('default'), $result);
<del>
<del> $testMessage = 'custom message';
<del> CakeLog::write('custom', $testMessage);
<del> $content = file_get_contents(LOGS . 'custom.log');
<del> $this->assertContains($testMessage, $content);
<del> unlink(LOGS . 'error.log');
<del> unlink(LOGS . 'custom.log');
<del> }
<del>
<del>/**
<del> * test configuring log streams
<del> *
<del> * @return void
<del> */
<del> public function testConfig() {
<del> CakeLog::config('file', array(
<del> 'engine' => 'FileLog',
<del> 'path' => LOGS
<del> ));
<del> $result = CakeLog::configured();
<del> $this->assertEquals(array('file'), $result);
<del>
<del> if (file_exists(LOGS . 'error.log')) {
<del> unlink(LOGS . 'error.log');
<del> }
<del> CakeLog::write(LOG_WARNING, 'Test warning');
<del> $this->assertTrue(file_exists(LOGS . 'error.log'));
<del>
<del> $result = file_get_contents(LOGS . 'error.log');
<del> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning/', $result);
<del> unlink(LOGS . 'error.log');
<del> }
<del>
<del>/**
<del> * explicit tests for drop()
<del> *
<del> * @return void
<del> */
<del> public function testDrop() {
<del> CakeLog::config('file', array(
<del> 'engine' => 'FileLog',
<del> 'path' => LOGS
<del> ));
<del> $result = CakeLog::configured();
<del> $this->assertEquals(array('file'), $result);
<del>
<del> CakeLog::drop('file');
<del> $result = CakeLog::configured();
<del> $this->assertSame(array(), $result);
<del> }
<del>
<del>/**
<del> * testLogFileWriting method
<del> *
<del> * @return void
<del> */
<del> public function testLogFileWriting() {
<del> if (file_exists(LOGS . 'error.log')) {
<del> unlink(LOGS . 'error.log');
<del> }
<del> $result = CakeLog::write(LOG_WARNING, 'Test warning');
<del> $this->assertTrue($result);
<del> $this->assertTrue(file_exists(LOGS . 'error.log'));
<del> unlink(LOGS . 'error.log');
<del>
<del> CakeLog::write(LOG_WARNING, 'Test warning 1');
<del> CakeLog::write(LOG_WARNING, 'Test warning 2');
<del> $result = file_get_contents(LOGS . 'error.log');
<del> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 1/', $result);
<del> $this->assertRegExp('/2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 2$/', $result);
<del> unlink(LOGS . 'error.log');
<del> }
<del>
<del>/**
<del> * test selective logging by level/type
<del> *
<del> * @return void
<del> */
<del> public function testSelectiveLoggingByLevel() {
<del> if (file_exists(LOGS . 'spam.log')) {
<del> unlink(LOGS . 'spam.log');
<del> }
<del> if (file_exists(LOGS . 'eggs.log')) {
<del> unlink(LOGS . 'eggs.log');
<del> }
<del> CakeLog::config('spam', array(
<del> 'engine' => 'FileLog',
<del> 'types' => 'debug',
<del> 'file' => 'spam',
<del> ));
<del> CakeLog::config('eggs', array(
<del> 'engine' => 'FileLog',
<del> 'types' => array('eggs', 'debug', 'error', 'warning'),
<del> 'file' => 'eggs',
<del> ));
<del>
<del> $testMessage = 'selective logging';
<del> CakeLog::write(LOG_WARNING, $testMessage);
<del>
<del> $this->assertTrue(file_exists(LOGS . 'eggs.log'));
<del> $this->assertFalse(file_exists(LOGS . 'spam.log'));
<del>
<del> CakeLog::write(LOG_DEBUG, $testMessage);
<del> $this->assertTrue(file_exists(LOGS . 'spam.log'));
<del>
<del> $contents = file_get_contents(LOGS . 'spam.log');
<del> $this->assertContains('Debug: ' . $testMessage, $contents);
<del> $contents = file_get_contents(LOGS . 'eggs.log');
<del> $this->assertContains('Debug: ' . $testMessage, $contents);
<del>
<del> if (file_exists(LOGS . 'spam.log')) {
<del> unlink(LOGS . 'spam.log');
<del> }
<del> if (file_exists(LOGS . 'eggs.log')) {
<del> unlink(LOGS . 'eggs.log');
<del> }
<del> }
<del>
<del>/**
<del> * test enable
<del> *
<del> * @expectedException CakeLogException
<del> */
<del> public function testStreamEnable() {
<del> CakeLog::config('spam', array(
<del> 'engine' => 'FileLog',
<del> 'file' => 'spam',
<del> ));
<del> $this->assertTrue(CakeLog::enabled('spam'));
<del> CakeLog::drop('spam');
<del> CakeLog::enable('bogus_stream');
<del> }
<del>
<del>/**
<del> * test disable
<del> *
<del> * @expectedException CakeLogException
<del> */
<del> public function testStreamDisable() {
<del> CakeLog::config('spam', array(
<del> 'engine' => 'FileLog',
<del> 'file' => 'spam',
<del> ));
<del> $this->assertTrue(CakeLog::enabled('spam'));
<del> CakeLog::disable('spam');
<del> $this->assertFalse(CakeLog::enabled('spam'));
<del> CakeLog::drop('spam');
<del> CakeLog::enable('bogus_stream');
<del> }
<del>
<del>/**
<del> * test enabled() invalid stream
<del> *
<del> * @expectedException CakeLogException
<del> */
<del> public function testStreamEnabledInvalid() {
<del> CakeLog::enabled('bogus_stream');
<del> }
<del>
<del>/**
<del> * test disable invalid stream
<del> *
<del> * @expectedException CakeLogException
<del> */
<del> public function testStreamDisableInvalid() {
<del> CakeLog::disable('bogus_stream');
<del> }
<del>
<del> protected function _resetLogConfig() {
<del> CakeLog::config('debug', array(
<del> 'engine' => 'FileLog',
<del> 'types' => array('notice', 'info', 'debug'),
<del> 'file' => 'debug',
<del> ));
<del> CakeLog::config('error', array(
<del> 'engine' => 'FileLog',
<del> 'types' => array('warning', 'error', 'critical', 'alert', 'emergency'),
<del> 'file' => 'error',
<del> ));
<del> }
<del>
<del> protected function _deleteLogs() {
<del> if (file_exists(LOGS . 'shops.log')) {
<del> unlink(LOGS . 'shops.log');
<del> }
<del> if (file_exists(LOGS . 'error.log')) {
<del> unlink(LOGS . 'error.log');
<del> }
<del> if (file_exists(LOGS . 'debug.log')) {
<del> unlink(LOGS . 'debug.log');
<del> }
<del> if (file_exists(LOGS . 'bogus.log')) {
<del> unlink(LOGS . 'bogus.log');
<del> }
<del> if (file_exists(LOGS . 'spam.log')) {
<del> unlink(LOGS . 'spam.log');
<del> }
<del> if (file_exists(LOGS . 'eggs.log')) {
<del> unlink(LOGS . 'eggs.log');
<del> }
<del> }
<del>
<del>/**
<del> * test backward compatible scoped logging
<del> *
<del> * @return void
<del> */
<del> public function testScopedLoggingBC() {
<del> $this->_resetLogConfig();
<del>
<del> CakeLog::config('shops', array(
<del> 'engine' => 'FileLog',
<del> 'types' => array('info', 'notice', 'warning'),
<del> 'scopes' => array('transactions', 'orders'),
<del> 'file' => 'shops',
<del> ));
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('info', 'info message');
<del> $this->assertFalse(file_exists(LOGS . 'error.log'));
<del> $this->assertTrue(file_exists(LOGS . 'debug.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('transactions', 'transaction message');
<del> $this->assertTrue(file_exists(LOGS . 'shops.log'));
<del> $this->assertFalse(file_exists(LOGS . 'transactions.log'));
<del> $this->assertFalse(file_exists(LOGS . 'error.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('error', 'error message');
<del> $this->assertTrue(file_exists(LOGS . 'error.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->assertFalse(file_exists(LOGS . 'shops.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('orders', 'order message');
<del> $this->assertFalse(file_exists(LOGS . 'error.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->assertFalse(file_exists(LOGS . 'orders.log'));
<del> $this->assertTrue(file_exists(LOGS . 'shops.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('warning', 'warning message');
<del> $this->assertTrue(file_exists(LOGS . 'error.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::drop('shops');
<del> }
<del>
<del>/**
<del> * Test that scopes are exclusive and don't bleed.
<del> *
<del> * @return void
<del> */
<del> public function testScopedLoggingExclusive() {
<del> $this->_deleteLogs();
<del>
<del> CakeLog::config('shops', array(
<del> 'engine' => 'FileLog',
<del> 'types' => array('info', 'notice', 'warning'),
<del> 'scopes' => array('transactions', 'orders'),
<del> 'file' => 'shops.log',
<del> ));
<del> CakeLog::config('eggs', array(
<del> 'engine' => 'FileLog',
<del> 'types' => array('info', 'notice', 'warning'),
<del> 'scopes' => array('eggs'),
<del> 'file' => 'eggs.log',
<del> ));
<del>
<del> CakeLog::write('info', 'transactions message', 'transactions');
<del> $this->assertFalse(file_exists(LOGS . 'eggs.log'));
<del> $this->assertTrue(file_exists(LOGS . 'shops.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('info', 'eggs message', 'eggs');
<del> $this->assertTrue(file_exists(LOGS . 'eggs.log'));
<del> $this->assertFalse(file_exists(LOGS . 'shops.log'));
<del> }
<del>
<del>/**
<del> * test scoped logging
<del> *
<del> * @return void
<del> */
<del> public function testScopedLogging() {
<del> $this->_resetLogConfig();
<del> $this->_deleteLogs();
<del>
<del> CakeLog::config('string-scope', array(
<del> 'engine' => 'FileLog',
<del> 'types' => array('info', 'notice', 'warning'),
<del> 'scopes' => 'string-scope',
<del> 'file' => 'string-scope.log'
<del> ));
<del> CakeLog::write('info', 'info message', 'string-scope');
<del> $this->assertTrue(file_exists(LOGS . 'string-scope.log'));
<del>
<del> CakeLog::drop('string-scope');
<del>
<del> CakeLog::config('shops', array(
<del> 'engine' => 'FileLog',
<del> 'types' => array('info', 'notice', 'warning'),
<del> 'scopes' => array('transactions', 'orders'),
<del> 'file' => 'shops.log',
<del> ));
<del>
<del> CakeLog::write('info', 'info message', 'transactions');
<del> $this->assertFalse(file_exists(LOGS . 'error.log'));
<del> $this->assertTrue(file_exists(LOGS . 'shops.log'));
<del> $this->assertTrue(file_exists(LOGS . 'debug.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('transactions', 'transaction message', 'orders');
<del> $this->assertTrue(file_exists(LOGS . 'shops.log'));
<del> $this->assertFalse(file_exists(LOGS . 'transactions.log'));
<del> $this->assertFalse(file_exists(LOGS . 'error.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('error', 'error message', 'orders');
<del> $this->assertTrue(file_exists(LOGS . 'error.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->assertFalse(file_exists(LOGS . 'shops.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('orders', 'order message', 'transactions');
<del> $this->assertFalse(file_exists(LOGS . 'error.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->assertFalse(file_exists(LOGS . 'orders.log'));
<del> $this->assertTrue(file_exists(LOGS . 'shops.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('warning', 'warning message', 'orders');
<del> $this->assertTrue(file_exists(LOGS . 'error.log'));
<del> $this->assertTrue(file_exists(LOGS . 'shops.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::drop('shops');
<del> }
<del>
<del>/**
<del> * test bogus type and scope
<del> *
<del> */
<del> public function testBogusTypeAndScope() {
<del> $this->_resetLogConfig();
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('bogus', 'bogus message');
<del> $this->assertTrue(file_exists(LOGS . 'bogus.log'));
<del> $this->assertFalse(file_exists(LOGS . 'error.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('bogus', 'bogus message', 'bogus');
<del> $this->assertTrue(file_exists(LOGS . 'bogus.log'));
<del> $this->assertFalse(file_exists(LOGS . 'error.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->_deleteLogs();
<del>
<del> CakeLog::write('error', 'bogus message', 'bogus');
<del> $this->assertFalse(file_exists(LOGS . 'bogus.log'));
<del> $this->assertTrue(file_exists(LOGS . 'error.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->_deleteLogs();
<del> }
<del>
<del>/**
<del> * test scoped logging with convenience methods
<del> */
<del> public function testConvenienceScopedLogging() {
<del> if (file_exists(LOGS . 'shops.log')) {
<del> unlink(LOGS . 'shops.log');
<del> }
<del> if (file_exists(LOGS . 'error.log')) {
<del> unlink(LOGS . 'error.log');
<del> }
<del> if (file_exists(LOGS . 'debug.log')) {
<del> unlink(LOGS . 'debug.log');
<del> }
<del>
<del> $this->_resetLogConfig();
<del> CakeLog::config('shops', array(
<del> 'engine' => 'FileLog',
<del> 'types' => array('info', 'debug', 'notice', 'warning'),
<del> 'scopes' => array('transactions', 'orders'),
<del> 'file' => 'shops',
<del> ));
<del>
<del> CakeLog::info('info message', 'transactions');
<del> $this->assertFalse(file_exists(LOGS . 'error.log'));
<del> $this->assertTrue(file_exists(LOGS . 'shops.log'));
<del> $this->assertTrue(file_exists(LOGS . 'debug.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::error('error message', 'orders');
<del> $this->assertTrue(file_exists(LOGS . 'error.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->assertFalse(file_exists(LOGS . 'shops.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::warning('warning message', 'orders');
<del> $this->assertTrue(file_exists(LOGS . 'error.log'));
<del> $this->assertTrue(file_exists(LOGS . 'shops.log'));
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del>
<del> $this->_deleteLogs();
<del>
<del> CakeLog::drop('shops');
<del> }
<del>
<del>/**
<del> * test convenience methods
<del> */
<del> public function testConvenienceMethods() {
<del> $this->_deleteLogs();
<del>
<del> CakeLog::config('debug', array(
<del> 'engine' => 'FileLog',
<del> 'types' => array('notice', 'info', 'debug'),
<del> 'file' => 'debug',
<del> ));
<del> CakeLog::config('error', array(
<del> 'engine' => 'FileLog',
<del> 'types' => array('emergency', 'alert', 'critical', 'error', 'warning'),
<del> 'file' => 'error',
<del> ));
<del>
<del> $testMessage = 'emergency message';
<del> CakeLog::emergency($testMessage);
<del> $contents = file_get_contents(LOGS . 'error.log');
<del> $this->assertRegExp('/(Emergency|Critical): ' . $testMessage . '/', $contents);
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->_deleteLogs();
<del>
<del> $testMessage = 'alert message';
<del> CakeLog::alert($testMessage);
<del> $contents = file_get_contents(LOGS . 'error.log');
<del> $this->assertRegExp('/(Alert|Critical): ' . $testMessage . '/', $contents);
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->_deleteLogs();
<del>
<del> $testMessage = 'critical message';
<del> CakeLog::critical($testMessage);
<del> $contents = file_get_contents(LOGS . 'error.log');
<del> $this->assertContains('Critical: ' . $testMessage, $contents);
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->_deleteLogs();
<del>
<del> $testMessage = 'error message';
<del> CakeLog::error($testMessage);
<del> $contents = file_get_contents(LOGS . 'error.log');
<del> $this->assertContains('Error: ' . $testMessage, $contents);
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->_deleteLogs();
<del>
<del> $testMessage = 'warning message';
<del> CakeLog::warning($testMessage);
<del> $contents = file_get_contents(LOGS . 'error.log');
<del> $this->assertContains('Warning: ' . $testMessage, $contents);
<del> $this->assertFalse(file_exists(LOGS . 'debug.log'));
<del> $this->_deleteLogs();
<del>
<del> $testMessage = 'notice message';
<del> CakeLog::notice($testMessage);
<del> $contents = file_get_contents(LOGS . 'debug.log');
<del> $this->assertRegExp('/(Notice|Debug): ' . $testMessage . '/', $contents);
<del> $this->assertFalse(file_exists(LOGS . 'error.log'));
<del> $this->_deleteLogs();
<del>
<del> $testMessage = 'info message';
<del> CakeLog::info($testMessage);
<del> $contents = file_get_contents(LOGS . 'debug.log');
<del> $this->assertRegExp('/(Info|Debug): ' . $testMessage . '/', $contents);
<del> $this->assertFalse(file_exists(LOGS . 'error.log'));
<del> $this->_deleteLogs();
<del>
<del> $testMessage = 'debug message';
<del> CakeLog::debug($testMessage);
<del> $contents = file_get_contents(LOGS . 'debug.log');
<del> $this->assertContains('Debug: ' . $testMessage, $contents);
<del> $this->assertFalse(file_exists(LOGS . 'error.log'));
<del> $this->_deleteLogs();
<del> }
<del>
<del>/**
<del> * test levels customization
<del> */
<del> public function testLevelCustomization() {
<del> $this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Log level tests not supported on Windows.');
<del>
<del> $levels = CakeLog::defaultLevels();
<del> $this->assertNotEmpty($levels);
<del> $result = array_keys($levels);
<del> $this->assertEquals(array(0, 1, 2, 3, 4, 5, 6, 7), $result);
<del>
<del> $levels = CakeLog::levels(array('foo', 'bar'));
<del> CakeLog::defaultLevels();
<del> $this->assertEquals('foo', $levels[8]);
<del> $this->assertEquals('bar', $levels[9]);
<del>
<del> $levels = CakeLog::levels(array(11 => 'spam', 'bar' => 'eggs'));
<del> CakeLog::defaultLevels();
<del> $this->assertEquals('spam', $levels[8]);
<del> $this->assertEquals('eggs', $levels[9]);
<del>
<del> $levels = CakeLog::levels(array(11 => 'spam', 'bar' => 'eggs'), false);
<del> CakeLog::defaultLevels();
<del> $this->assertEquals(array('spam', 'eggs'), $levels);
<del>
<del> $levels = CakeLog::levels(array('ham', 9 => 'spam', '12' => 'fam'), false);
<del> CakeLog::defaultLevels();
<del> $this->assertEquals(array('ham', 'spam', 'fam'), $levels);
<del> }
<del>
<del>/**
<del> * Test writing log files with custom levels
<del> */
<del> public function testCustomLevelWrites() {
<del> $this->_deleteLogs();
<del> $this->_resetLogConfig();
<del>
<del> CakeLog::levels(array('spam', 'eggs'));
<del>
<del> $testMessage = 'error message';
<del> CakeLog::write('error', $testMessage);
<del> CakeLog::defaultLevels();
<del> $this->assertTrue(file_exists(LOGS . 'error.log'));
<del> $contents = file_get_contents(LOGS . 'error.log');
<del> $this->assertContains('Error: ' . $testMessage, $contents);
<del>
<del> CakeLog::config('spam', array(
<del> 'engine' => 'FileLog',
<del> 'file' => 'spam.log',
<del> 'types' => 'spam',
<del> ));
<del> CakeLog::config('eggs', array(
<del> 'engine' => 'FileLog',
<del> 'file' => 'eggs.log',
<del> 'types' => array('spam', 'eggs'),
<del> ));
<del>
<del> $testMessage = 'spam message';
<del> CakeLog::write('spam', $testMessage);
<del> CakeLog::defaultLevels();
<del> $this->assertTrue(file_exists(LOGS . 'spam.log'));
<del> $this->assertTrue(file_exists(LOGS . 'eggs.log'));
<del> $contents = file_get_contents(LOGS . 'spam.log');
<del> $this->assertContains('Spam: ' . $testMessage, $contents);
<del>
<del> $testMessage = 'egg message';
<del> CakeLog::write('eggs', $testMessage);
<del> CakeLog::defaultLevels();
<del> $contents = file_get_contents(LOGS . 'spam.log');
<del> $this->assertNotContains('Eggs: ' . $testMessage, $contents);
<del> $contents = file_get_contents(LOGS . 'eggs.log');
<del> $this->assertContains('Eggs: ' . $testMessage, $contents);
<del>
<del> CakeLog::drop('spam');
<del> CakeLog::drop('eggs');
<del>
<del> $this->_deleteLogs();
<del> }
<del>
<del>}
<ide><path>lib/Cake/Test/Case/Network/Http/HttpResponseTest.php
<del><?php
<del>/**
<del> * HttpResponseTest file
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.Network.Http
<del> * @since CakePHP(tm) v 1.2.0.4206
<del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<del> */
<del>
<del>App::uses('HttpResponse', 'Network/Http');
<del>
<del>/**
<del> * TestHttpResponse class
<del> *
<del> * @package Cake.Test.Case.Network.Http
<del> */
<del>class TestHttpResponse extends HttpResponse {
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param array $header Header as an indexed array (field => value)
<del> * @return array Parsed header
<del> */
<del> public function parseHeader($header) {
<del> return parent::_parseHeader($header);
<del> }
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param string $body A string containing the body to decode
<del> * @param boolean|string $encoding Can be false in case no encoding is being used, or a string representing the encoding
<del> * @return mixed Array or false
<del> */
<del> public function decodeBody($body, $encoding = 'chunked') {
<del> return parent::_decodeBody($body, $encoding);
<del> }
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param string $body A string containing the chunked body to decode
<del> * @return mixed Array or false
<del> */
<del> public function decodeChunkedBody($body) {
<del> return parent::_decodeChunkedBody($body);
<del> }
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param string $token Token to unescape
<del> * @return string Unescaped token
<del> */
<del> public function unescapeToken($token, $chars = null) {
<del> return parent::_unescapeToken($token, $chars);
<del> }
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param boolean $hex true to get them as HEX values, false otherwise
<del> * @return array Escape chars
<del> */
<del> public function tokenEscapeChars($hex = true, $chars = null) {
<del> return parent::_tokenEscapeChars($hex, $chars);
<del> }
<del>
<del>}
<del>
<del>/**
<del> * HttpResponseTest class
<del> *
<del> * @package Cake.Test.Case.Network.Http
<del> */
<del>class HttpResponseTest extends CakeTestCase {
<del>
<del>/**
<del> * This function sets up a HttpResponse
<del> *
<del> * @return void
<del> */
<del> public function setUp() {
<del> $this->HttpResponse = new TestHttpResponse();
<del> }
<del>
<del>/**
<del> * testBody
<del> *
<del> * @return void
<del> */
<del> public function testBody() {
<del> $this->HttpResponse->body = 'testing';
<del> $this->assertEquals('testing', $this->HttpResponse->body());
<del>
<del> $this->HttpResponse->body = null;
<del> $this->assertSame($this->HttpResponse->body(), '');
<del> }
<del>
<del>/**
<del> * testToString
<del> *
<del> * @return void
<del> */
<del> public function testToString() {
<del> $this->HttpResponse->body = 'other test';
<del> $this->assertEquals('other test', $this->HttpResponse->body());
<del> $this->assertEquals('other test', (string)$this->HttpResponse);
<del> $this->assertTrue(strpos($this->HttpResponse, 'test') > 0);
<del>
<del> $this->HttpResponse->body = null;
<del> $this->assertEquals('', (string)$this->HttpResponse);
<del> }
<del>
<del>/**
<del> * testGetHeader
<del> *
<del> * @return void
<del> */
<del> public function testGetHeader() {
<del> $this->HttpResponse->headers = array(
<del> 'foo' => 'Bar',
<del> 'Some' => 'ok',
<del> 'HeAdEr' => 'value',
<del> 'content-Type' => 'text/plain'
<del> );
<del>
<del> $this->assertEquals('Bar', $this->HttpResponse->getHeader('foo'));
<del> $this->assertEquals('Bar', $this->HttpResponse->getHeader('Foo'));
<del> $this->assertEquals('Bar', $this->HttpResponse->getHeader('FOO'));
<del> $this->assertEquals('value', $this->HttpResponse->getHeader('header'));
<del> $this->assertEquals('text/plain', $this->HttpResponse->getHeader('Content-Type'));
<del> $this->assertSame($this->HttpResponse->getHeader(0), null);
<del>
<del> $this->assertEquals('Bar', $this->HttpResponse->getHeader('foo', false));
<del> $this->assertEquals('not from class', $this->HttpResponse->getHeader('foo', array('foo' => 'not from class')));
<del> }
<del>
<del>/**
<del> * testIsOk
<del> *
<del> * @return void
<del> */
<del> public function testIsOk() {
<del> $this->HttpResponse->code = 0;
<del> $this->assertFalse($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = -1;
<del> $this->assertFalse($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 'what?';
<del> $this->assertFalse($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 200;
<del> $this->assertTrue($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 201;
<del> $this->assertTrue($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 202;
<del> $this->assertTrue($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 203;
<del> $this->assertTrue($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 204;
<del> $this->assertTrue($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 205;
<del> $this->assertTrue($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 206;
<del> $this->assertTrue($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 207;
<del> $this->assertFalse($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 208;
<del> $this->assertFalse($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 209;
<del> $this->assertFalse($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 210;
<del> $this->assertFalse($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 226;
<del> $this->assertFalse($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 288;
<del> $this->assertFalse($this->HttpResponse->isOk());
<del> $this->HttpResponse->code = 301;
<del> $this->assertFalse($this->HttpResponse->isOk());
<del> }
<del>
<del>/**
<del> * testIsRedirect
<del> *
<del> * @return void
<del> */
<del> public function testIsRedirect() {
<del> $this->HttpResponse->code = 0;
<del> $this->assertFalse($this->HttpResponse->isRedirect());
<del> $this->HttpResponse->code = -1;
<del> $this->assertFalse($this->HttpResponse->isRedirect());
<del> $this->HttpResponse->code = 201;
<del> $this->assertFalse($this->HttpResponse->isRedirect());
<del> $this->HttpResponse->code = 'what?';
<del> $this->assertFalse($this->HttpResponse->isRedirect());
<del> $this->HttpResponse->code = 301;
<del> $this->assertFalse($this->HttpResponse->isRedirect());
<del> $this->HttpResponse->code = 302;
<del> $this->assertFalse($this->HttpResponse->isRedirect());
<del> $this->HttpResponse->code = 303;
<del> $this->assertFalse($this->HttpResponse->isRedirect());
<del> $this->HttpResponse->code = 307;
<del> $this->assertFalse($this->HttpResponse->isRedirect());
<del> $this->HttpResponse->code = 301;
<del> $this->HttpResponse->headers['Location'] = 'http://somewhere/';
<del> $this->assertTrue($this->HttpResponse->isRedirect());
<del> $this->HttpResponse->code = 302;
<del> $this->HttpResponse->headers['Location'] = 'http://somewhere/';
<del> $this->assertTrue($this->HttpResponse->isRedirect());
<del> $this->HttpResponse->code = 303;
<del> $this->HttpResponse->headers['Location'] = 'http://somewhere/';
<del> $this->assertTrue($this->HttpResponse->isRedirect());
<del> $this->HttpResponse->code = 307;
<del> $this->HttpResponse->headers['Location'] = 'http://somewhere/';
<del> $this->assertTrue($this->HttpResponse->isRedirect());
<del> }
<del>
<del>/**
<del> * Test that HttpSocket::parseHeader can take apart a given (and valid) $header string and turn it into an array.
<del> *
<del> * @return void
<del> */
<del> public function testParseHeader() {
<del> $r = $this->HttpResponse->parseHeader(array('foo' => 'Bar', 'fOO-bAr' => 'quux'));
<del> $this->assertEquals(array('foo' => 'Bar', 'fOO-bAr' => 'quux'), $r);
<del>
<del> $r = $this->HttpResponse->parseHeader(true);
<del> $this->assertEquals(false, $r);
<del>
<del> $header = "Host: cakephp.org\t\r\n";
<del> $r = $this->HttpResponse->parseHeader($header);
<del> $expected = array(
<del> 'Host' => 'cakephp.org'
<del> );
<del> $this->assertEquals($expected, $r);
<del>
<del> $header = "Date:Sat, 07 Apr 2007 10:10:25 GMT\r\nX-Powered-By: PHP/5.1.2\r\n";
<del> $r = $this->HttpResponse->parseHeader($header);
<del> $expected = array(
<del> 'Date' => 'Sat, 07 Apr 2007 10:10:25 GMT',
<del> 'X-Powered-By' => 'PHP/5.1.2'
<del> );
<del> $this->assertEquals($expected, $r);
<del>
<del> $header = "people: Jim,John\r\nfoo-LAND: Bar\r\ncAKe-PHP: rocks\r\n";
<del> $r = $this->HttpResponse->parseHeader($header);
<del> $expected = array(
<del> 'people' => 'Jim,John',
<del> 'foo-LAND' => 'Bar',
<del> 'cAKe-PHP' => 'rocks'
<del> );
<del> $this->assertEquals($expected, $r);
<del>
<del> $header = "People: Jim,John,Tim\r\nPeople: Lisa,Tina,Chelsea\r\n";
<del> $r = $this->HttpResponse->parseHeader($header);
<del> $expected = array(
<del> 'People' => array('Jim,John,Tim', 'Lisa,Tina,Chelsea')
<del> );
<del> $this->assertEquals($expected, $r);
<del>
<del> $header = "Multi-Line: I am a \r\nmulti line\t\r\nfield value.\r\nSingle-Line: I am not\r\n";
<del> $r = $this->HttpResponse->parseHeader($header);
<del> $expected = array(
<del> 'Multi-Line' => "I am a\r\nmulti line\r\nfield value.",
<del> 'Single-Line' => 'I am not'
<del> );
<del> $this->assertEquals($expected, $r);
<del>
<del> $header = "Esc\"@\"ped: value\r\n";
<del> $r = $this->HttpResponse->parseHeader($header);
<del> $expected = array(
<del> 'Esc@ped' => 'value'
<del> );
<del> $this->assertEquals($expected, $r);
<del> }
<del>
<del>/**
<del> * testParseResponse method
<del> *
<del> * @return void
<del> */
<del> public function testParseResponse() {
<del> $tests = array(
<del> 'simple-request' => array(
<del> 'response' => array(
<del> 'status-line' => "HTTP/1.x 200 OK\r\n",
<del> 'header' => "Date: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\n",
<del> 'body' => "<h1>Hello World</h1>\r\n<p>It's good to be html</p>"
<del> ),
<del> 'expectations' => array(
<del> 'httpVersion' => 'HTTP/1.x',
<del> 'code' => 200,
<del> 'reasonPhrase' => 'OK',
<del> 'headers' => array('Date' => 'Mon, 16 Apr 2007 04:14:16 GMT', 'Server' => 'CakeHttp Server'),
<del> 'body' => "<h1>Hello World</h1>\r\n<p>It's good to be html</p>"
<del> )
<del> ),
<del> 'no-header' => array(
<del> 'response' => array(
<del> 'status-line' => "HTTP/1.x 404 OK\r\n",
<del> 'header' => null
<del> ),
<del> 'expectations' => array(
<del> 'code' => 404,
<del> 'headers' => array()
<del> )
<del> )
<del> );
<del>
<del> $testResponse = array();
<del> $expectations = array();
<del>
<del> foreach ($tests as $name => $test) {
<del> $testResponse = array_merge($testResponse, $test['response']);
<del> $testResponse['response'] = $testResponse['status-line'] . $testResponse['header'] . "\r\n" . $testResponse['body'];
<del> $this->HttpResponse->parseResponse($testResponse['response']);
<del> $expectations = array_merge($expectations, $test['expectations']);
<del>
<del> foreach ($expectations as $property => $expectedVal) {
<del> $this->assertEquals($expectedVal, $this->HttpResponse->{$property}, 'Test "' . $name . '": response.' . $property . ' - %s');
<del> }
<del>
<del> foreach (array('status-line', 'header', 'body', 'response') as $field) {
<del> $this->assertEquals($this->HttpResponse['raw'][$field], $testResponse[$field], 'Test response.raw.' . $field . ': %s');
<del> }
<del> }
<del> }
<del>
<del>/**
<del> * data provider function for testInvalidParseResponseData
<del> *
<del> * @return array
<del> */
<del> public static function invalidParseResponseDataProvider() {
<del> return array(
<del> array(array('foo' => 'bar')),
<del> array(true),
<del> array("HTTP Foo\r\nBar: La"),
<del> array('HTTP/1.1 TEST ERROR')
<del> );
<del> }
<del>
<del>/**
<del> * testInvalidParseResponseData
<del> *
<del> * @dataProvider invalidParseResponseDataProvider
<del> * @expectedException SocketException
<del> * return void
<del> */
<del> public function testInvalidParseResponseData($value) {
<del> $this->HttpResponse->parseResponse($value);
<del> }
<del>
<del>/**
<del> * testDecodeBody method
<del> *
<del> * @return void
<del> */
<del> public function testDecodeBody() {
<del> $r = $this->HttpResponse->decodeBody(true);
<del> $this->assertEquals(false, $r);
<del>
<del> $r = $this->HttpResponse->decodeBody('Foobar', false);
<del> $this->assertEquals(array('body' => 'Foobar', 'header' => false), $r);
<del>
<del> $encoding = 'chunked';
<del> $sample = array(
<del> 'encoded' => "19\r\nThis is a chunked message\r\n0\r\n",
<del> 'decoded' => array('body' => "This is a chunked message", 'header' => false)
<del> );
<del>
<del> $r = $this->HttpResponse->decodeBody($sample['encoded'], $encoding);
<del> $this->assertEquals($r, $sample['decoded']);
<del>
<del> $encoding = 'chunked';
<del> $sample = array(
<del> 'encoded' => "19\nThis is a chunked message\r\n0\n",
<del> 'decoded' => array('body' => "This is a chunked message", 'header' => false)
<del> );
<del>
<del> $r = $this->HttpResponse->decodeBody($sample['encoded'], $encoding);
<del> $this->assertEquals($r, $sample['decoded'], 'Inconsistent line terminators should be tolerated.');
<del> }
<del>
<del>/**
<del> * testDecodeFooCoded
<del> *
<del> * @return void
<del> */
<del> public function testDecodeFooCoded() {
<del> $r = $this->HttpResponse->decodeBody(true);
<del> $this->assertEquals(false, $r);
<del>
<del> $r = $this->HttpResponse->decodeBody('Foobar', false);
<del> $this->assertEquals(array('body' => 'Foobar', 'header' => false), $r);
<del>
<del> $encoding = 'foo-bar';
<del> $sample = array(
<del> 'encoded' => '!Foobar!',
<del> 'decoded' => array('body' => '!Foobar!', 'header' => false),
<del> );
<del>
<del> $r = $this->HttpResponse->decodeBody($sample['encoded'], $encoding);
<del> $this->assertEquals($r, $sample['decoded']);
<del> }
<del>
<del>/**
<del> * testDecodeChunkedBody method
<del> *
<del> * @return void
<del> */
<del> public function testDecodeChunkedBody() {
<del> $r = $this->HttpResponse->decodeChunkedBody(true);
<del> $this->assertEquals(false, $r);
<del>
<del> $encoded = "19\r\nThis is a chunked message\r\n0\r\n";
<del> $decoded = "This is a chunked message";
<del> $r = $this->HttpResponse->decodeChunkedBody($encoded);
<del> $this->assertEquals($r['body'], $decoded);
<del> $this->assertEquals(false, $r['header']);
<del>
<del> $encoded = "19 \r\nThis is a chunked message\r\n0\r\n";
<del> $r = $this->HttpResponse->decodeChunkedBody($encoded);
<del> $this->assertEquals($r['body'], $decoded);
<del>
<del> $encoded = "19\r\nThis is a chunked message\r\nE\r\n\nThat is cool\n\r\n0\r\n";
<del> $decoded = "This is a chunked message\nThat is cool\n";
<del> $r = $this->HttpResponse->decodeChunkedBody($encoded);
<del> $this->assertEquals($r['body'], $decoded);
<del> $this->assertEquals(false, $r['header']);
<del>
<del> $encoded = "19\r\nThis is a chunked message\r\nE;foo-chunk=5\r\n\nThat is cool\n\r\n0\r\n";
<del> $r = $this->HttpResponse->decodeChunkedBody($encoded);
<del> $this->assertEquals($r['body'], $decoded);
<del> $this->assertEquals(false, $r['header']);
<del>
<del> $encoded = "19\r\nThis is a chunked message\r\nE\r\n\nThat is cool\n\r\n0\r\nfoo-header: bar\r\ncake: PHP\r\n\r\n";
<del> $r = $this->HttpResponse->decodeChunkedBody($encoded);
<del> $this->assertEquals($r['body'], $decoded);
<del> $this->assertEquals(array('foo-header' => 'bar', 'cake' => 'PHP'), $r['header']);
<del> }
<del>
<del>/**
<del> * testDecodeChunkedBodyError method
<del> *
<del> * @expectedException SocketException
<del> * @return void
<del> */
<del> public function testDecodeChunkedBodyError() {
<del> $encoded = "19\r\nThis is a chunked message\r\nE\r\n\nThat is cool\n\r\n";
<del> $this->HttpResponse->decodeChunkedBody($encoded);
<del> }
<del>
<del>/**
<del> * testParseCookies method
<del> *
<del> * @return void
<del> */
<del> public function testParseCookies() {
<del> $header = array(
<del> 'Set-Cookie' => array(
<del> 'foo=bar',
<del> 'people=jim,jack,johnny";";Path=/accounts',
<del> 'google=not=nice'
<del> ),
<del> 'Transfer-Encoding' => 'chunked',
<del> 'Date' => 'Sun, 18 Nov 2007 18:57:42 GMT',
<del> );
<del> $cookies = $this->HttpResponse->parseCookies($header);
<del> $expected = array(
<del> 'foo' => array(
<del> 'value' => 'bar'
<del> ),
<del> 'people' => array(
<del> 'value' => 'jim,jack,johnny";"',
<del> 'path' => '/accounts',
<del> ),
<del> 'google' => array(
<del> 'value' => 'not=nice',
<del> )
<del> );
<del> $this->assertEquals($expected, $cookies);
<del>
<del> $header['Set-Cookie'][] = 'cakephp=great; Secure';
<del> $expected['cakephp'] = array('value' => 'great', 'secure' => true);
<del> $cookies = $this->HttpResponse->parseCookies($header);
<del> $this->assertEquals($expected, $cookies);
<del>
<del> $header['Set-Cookie'] = 'foo=bar';
<del> unset($expected['people'], $expected['cakephp'], $expected['google']);
<del> $cookies = $this->HttpResponse->parseCookies($header);
<del> $this->assertEquals($expected, $cookies);
<del> }
<del>
<del>/**
<del> * Test that escaped token strings are properly unescaped by HttpSocket::unescapeToken
<del> *
<del> * @return void
<del> */
<del> public function testUnescapeToken() {
<del> $this->assertEquals('Foo', $this->HttpResponse->unescapeToken('Foo'));
<del>
<del> $escape = $this->HttpResponse->tokenEscapeChars(false);
<del> foreach ($escape as $char) {
<del> $token = 'My-special-"' . $char . '"-Token';
<del> $unescapedToken = $this->HttpResponse->unescapeToken($token);
<del> $expectedToken = 'My-special-' . $char . '-Token';
<del>
<del> $this->assertEquals($expectedToken, $unescapedToken, 'Test token unescaping for ASCII ' . ord($char));
<del> }
<del>
<del> $token = 'Extreme-":"Token-" "-""""@"-test';
<del> $escapedToken = $this->HttpResponse->unescapeToken($token);
<del> $expectedToken = 'Extreme-:Token- -"@-test';
<del> $this->assertEquals($expectedToken, $escapedToken);
<del> }
<del>
<del>/**
<del> * testArrayAccess
<del> *
<del> * @return void
<del> */
<del> public function testArrayAccess() {
<del> $this->HttpResponse->httpVersion = 'HTTP/1.1';
<del> $this->HttpResponse->code = 200;
<del> $this->HttpResponse->reasonPhrase = 'OK';
<del> $this->HttpResponse->headers = array(
<del> 'Server' => 'CakePHP',
<del> 'ContEnt-Type' => 'text/plain'
<del> );
<del> $this->HttpResponse->cookies = array(
<del> 'foo' => array('value' => 'bar'),
<del> 'bar' => array('value' => 'foo')
<del> );
<del> $this->HttpResponse->body = 'This is a test!';
<del> $this->HttpResponse->raw = "HTTP/1.1 200 OK\r\nServer: CakePHP\r\nContEnt-Type: text/plain\r\n\r\nThis is a test!";
<del> $expectedOne = "HTTP/1.1 200 OK\r\n";
<del> $this->assertEquals($expectedOne, $this->HttpResponse['raw']['status-line']);
<del> $expectedTwo = "Server: CakePHP\r\nContEnt-Type: text/plain\r\n";
<del> $this->assertEquals($expectedTwo, $this->HttpResponse['raw']['header']);
<del> $expectedThree = 'This is a test!';
<del> $this->assertEquals($expectedThree, $this->HttpResponse['raw']['body']);
<del> $expected = $expectedOne . $expectedTwo . "\r\n" . $expectedThree;
<del> $this->assertEquals($expected, $this->HttpResponse['raw']['response']);
<del>
<del> $expected = 'HTTP/1.1';
<del> $this->assertEquals($expected, $this->HttpResponse['status']['http-version']);
<del> $expected = 200;
<del> $this->assertEquals($expected, $this->HttpResponse['status']['code']);
<del> $expected = 'OK';
<del> $this->assertEquals($expected, $this->HttpResponse['status']['reason-phrase']);
<del>
<del> $expected = array(
<del> 'Server' => 'CakePHP',
<del> 'ContEnt-Type' => 'text/plain'
<del> );
<del> $this->assertEquals($expected, $this->HttpResponse['header']);
<del>
<del> $expected = 'This is a test!';
<del> $this->assertEquals($expected, $this->HttpResponse['body']);
<del>
<del> $expected = array(
<del> 'foo' => array('value' => 'bar'),
<del> 'bar' => array('value' => 'foo')
<del> );
<del> $this->assertEquals($expected, $this->HttpResponse['cookies']);
<del>
<del> $this->HttpResponse->raw = "HTTP/1.1 200 OK\r\n\r\nThis is a test!";
<del> $this->assertSame($this->HttpResponse['raw']['header'], null);
<del> }
<del>
<del>}
<ide><path>lib/Cake/Test/Case/Network/Http/HttpSocketTest.php
<del><?php
<del>/**
<del> * HttpSocketTest file
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.Network.Http
<del> * @since CakePHP(tm) v 1.2.0.4206
<del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<del> */
<del>
<del>App::uses('HttpSocket', 'Network/Http');
<del>App::uses('HttpResponse', 'Network/Http');
<del>
<del>/**
<del> * TestAuthentication class
<del> *
<del> * @package Cake.Test.Case.Network.Http
<del> * @package Cake.Test.Case.Network.Http
<del> */
<del>class TestAuthentication {
<del>
<del>/**
<del> * authentication method
<del> *
<del> * @param HttpSocket $http
<del> * @param array $authInfo
<del> * @return void
<del> */
<del> public static function authentication(HttpSocket $http, &$authInfo) {
<del> $http->request['header']['Authorization'] = 'Test ' . $authInfo['user'] . '.' . $authInfo['pass'];
<del> }
<del>
<del>/**
<del> * proxyAuthentication method
<del> *
<del> * @param HttpSocket $http
<del> * @param array $proxyInfo
<del> * @return void
<del> */
<del> public static function proxyAuthentication(HttpSocket $http, &$proxyInfo) {
<del> $http->request['header']['Proxy-Authorization'] = 'Test ' . $proxyInfo['user'] . '.' . $proxyInfo['pass'];
<del> }
<del>
<del>}
<del>
<del>/**
<del> * CustomResponse
<del> *
<del> */
<del>class CustomResponse {
<del>
<del>/**
<del> * First 10 chars
<del> *
<del> * @var string
<del> */
<del> public $first10;
<del>
<del>/**
<del> * Constructor
<del> *
<del> */
<del> public function __construct($message) {
<del> $this->first10 = substr($message, 0, 10);
<del> }
<del>
<del>}
<del>
<del>/**
<del> * TestHttpSocket
<del> *
<del> */
<del>class TestHttpSocket extends HttpSocket {
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param string|array $uri URI (see {@link _parseUri()})
<del> * @return array Current configuration settings
<del> */
<del> public function configUri($uri = null) {
<del> return parent::_configUri($uri);
<del> }
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param string|array $uri URI to parse
<del> * @param boolean|array $base If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc.
<del> * @return array Parsed URI
<del> */
<del> public function parseUri($uri = null, $base = array()) {
<del> return parent::_parseUri($uri, $base);
<del> }
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param array $uri A $uri array, or uses $this->config if left empty
<del> * @param string $uriTemplate The Uri template/format to use
<del> * @return string A fully qualified URL formatted according to $uriTemplate
<del> */
<del> public function buildUri($uri = array(), $uriTemplate = '%scheme://%user:%pass@%host:%port/%path?%query#%fragment') {
<del> return parent::_buildUri($uri, $uriTemplate);
<del> }
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param array $header Header to build
<del> * @return string Header built from array
<del> */
<del> public function buildHeader($header, $mode = 'standard') {
<del> return parent::_buildHeader($header, $mode);
<del> }
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param string|array $query A query string to parse into an array or an array to return directly "as is"
<del> * @return array The $query parsed into a possibly multi-level array. If an empty $query is given, an empty array is returned.
<del> */
<del> public function parseQuery($query) {
<del> return parent::_parseQuery($query);
<del> }
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param array $request Needs to contain a 'uri' key. Should also contain a 'method' key, otherwise defaults to GET.
<del> * @param string $versionToken The version token to use, defaults to HTTP/1.1
<del> * @return string Request line
<del> */
<del> public function buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') {
<del> return parent::_buildRequestLine($request, $versionToken);
<del> }
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param boolean $hex true to get them as HEX values, false otherwise
<del> * @return array Escape chars
<del> */
<del> public function tokenEscapeChars($hex = true, $chars = null) {
<del> return parent::_tokenEscapeChars($hex, $chars);
<del> }
<del>
<del>/**
<del> * Convenience method for testing protected method
<del> *
<del> * @param string $token Token to escape
<del> * @return string Escaped token
<del> */
<del> public function escapeToken($token, $chars = null) {
<del> return parent::_escapeToken($token, $chars);
<del> }
<del>
<del>}
<del>
<del>/**
<del> * HttpSocketTest class
<del> *
<del> * @package Cake.Test.Case.Network.Http
<del> */
<del>class HttpSocketTest extends CakeTestCase {
<del>
<del>/**
<del> * Socket property
<del> *
<del> * @var mixed null
<del> */
<del> public $Socket = null;
<del>
<del>/**
<del> * RequestSocket property
<del> *
<del> * @var mixed null
<del> */
<del> public $RequestSocket = null;
<del>
<del>/**
<del> * This function sets up a TestHttpSocket instance we are going to use for testing
<del> *
<del> * @return void
<del> */
<del> public function setUp() {
<del> if (!class_exists('MockHttpSocket')) {
<del> $this->getMock('TestHttpSocket', array('read', 'write', 'connect'), array(), 'MockHttpSocket');
<del> $this->getMock('TestHttpSocket', array('read', 'write', 'connect', 'request'), array(), 'MockHttpSocketRequests');
<del> }
<del>
<del> $this->Socket = new MockHttpSocket();
<del> $this->RequestSocket = new MockHttpSocketRequests();
<del> }
<del>
<del>/**
<del> * We use this function to clean up after the test case was executed
<del> *
<del> * @return void
<del> */
<del> public function tearDown() {
<del> unset($this->Socket, $this->RequestSocket);
<del> }
<del>
<del>/**
<del> * Test that HttpSocket::__construct does what one would expect it to do
<del> *
<del> * @return void
<del> */
<del> public function testConstruct() {
<del> $this->Socket->reset();
<del> $baseConfig = $this->Socket->config;
<del> $this->Socket->expects($this->never())->method('connect');
<del> $this->Socket->__construct(array('host' => 'foo-bar'));
<del> $baseConfig['host'] = 'foo-bar';
<del> $baseConfig['protocol'] = getprotobyname($baseConfig['protocol']);
<del> $this->assertEquals($this->Socket->config, $baseConfig);
<del>
<del> $this->Socket->reset();
<del> $baseConfig = $this->Socket->config;
<del> $this->Socket->__construct('http://www.cakephp.org:23/');
<del> $baseConfig['host'] = $baseConfig['request']['uri']['host'] = 'www.cakephp.org';
<del> $baseConfig['port'] = $baseConfig['request']['uri']['port'] = 23;
<del> $baseConfig['request']['uri']['scheme'] = 'http';
<del> $baseConfig['protocol'] = getprotobyname($baseConfig['protocol']);
<del> $this->assertEquals($this->Socket->config, $baseConfig);
<del>
<del> $this->Socket->reset();
<del> $this->Socket->__construct(array('request' => array('uri' => 'http://www.cakephp.org:23/')));
<del> $this->assertEquals($this->Socket->config, $baseConfig);
<del> }
<del>
<del>/**
<del> * Test that HttpSocket::configUri works properly with different types of arguments
<del> *
<del> * @return void
<del> */
<del> public function testConfigUri() {
<del> $this->Socket->reset();
<del> $r = $this->Socket->configUri('https://bob:secret@www.cakephp.org:23/?query=foo');
<del> $expected = array(
<del> 'persistent' => false,
<del> 'host' => 'www.cakephp.org',
<del> 'protocol' => 'tcp',
<del> 'port' => 23,
<del> 'timeout' => 30,
<del> 'ssl_verify_peer' => true,
<del> 'ssl_verify_depth' => 5,
<del> 'ssl_verify_host' => true,
<del> 'request' => array(
<del> 'uri' => array(
<del> 'scheme' => 'https',
<del> 'host' => 'www.cakephp.org',
<del> 'port' => 23
<del> ),
<del> 'redirect' => false,
<del> 'cookies' => array(),
<del> )
<del> );
<del> $this->assertEquals($expected, $this->Socket->config);
<del> $this->assertTrue($r);
<del> $r = $this->Socket->configUri(array('host' => 'www.foo-bar.org'));
<del> $expected['host'] = 'www.foo-bar.org';
<del> $expected['request']['uri']['host'] = 'www.foo-bar.org';
<del> $this->assertEquals($expected, $this->Socket->config);
<del> $this->assertTrue($r);
<del>
<del> $r = $this->Socket->configUri('http://www.foo.com');
<del> $expected = array(
<del> 'persistent' => false,
<del> 'host' => 'www.foo.com',
<del> 'protocol' => 'tcp',
<del> 'port' => 80,
<del> 'timeout' => 30,
<del> 'ssl_verify_peer' => true,
<del> 'ssl_verify_depth' => 5,
<del> 'ssl_verify_host' => true,
<del> 'request' => array(
<del> 'uri' => array(
<del> 'scheme' => 'http',
<del> 'host' => 'www.foo.com',
<del> 'port' => 80
<del> ),
<del> 'redirect' => false,
<del> 'cookies' => array(),
<del> )
<del> );
<del> $this->assertEquals($expected, $this->Socket->config);
<del> $this->assertTrue($r);
<del>
<del> $r = $this->Socket->configUri('/this-is-broken');
<del> $this->assertEquals($expected, $this->Socket->config);
<del> $this->assertFalse($r);
<del>
<del> $r = $this->Socket->configUri(false);
<del> $this->assertEquals($expected, $this->Socket->config);
<del> $this->assertFalse($r);
<del> }
<del>
<del>/**
<del> * Tests that HttpSocket::request (the heart of the HttpSocket) is working properly.
<del> *
<del> * @return void
<del> */
<del> public function testRequest() {
<del> $this->Socket->reset();
<del>
<del> $response = $this->Socket->request(true);
<del> $this->assertFalse($response);
<del>
<del> $context = array(
<del> 'ssl' => array(
<del> 'verify_peer' => true,
<del> 'verify_depth' => 5,
<del> 'CN_match' => 'www.cakephp.org',
<del> 'cafile' => CAKE . 'Config' . DS . 'cacert.pem'
<del> )
<del> );
<del>
<del> $tests = array(
<del> array(
<del> 'request' => 'http://www.cakephp.org/?foo=bar',
<del> 'expectation' => array(
<del> 'config' => array(
<del> 'persistent' => false,
<del> 'host' => 'www.cakephp.org',
<del> 'protocol' => 'tcp',
<del> 'port' => 80,
<del> 'timeout' => 30,
<del> 'context' => $context,
<del> 'request' => array(
<del> 'uri' => array(
<del> 'scheme' => 'http',
<del> 'host' => 'www.cakephp.org',
<del> 'port' => 80
<del> ),
<del> 'redirect' => false,
<del> 'cookies' => array()
<del> )
<del> ),
<del> 'request' => array(
<del> 'method' => 'GET',
<del> 'uri' => array(
<del> 'scheme' => 'http',
<del> 'host' => 'www.cakephp.org',
<del> 'port' => 80,
<del> 'user' => null,
<del> 'pass' => null,
<del> 'path' => '/',
<del> 'query' => array('foo' => 'bar'),
<del> 'fragment' => null
<del> ),
<del> 'version' => '1.1',
<del> 'body' => '',
<del> 'line' => "GET /?foo=bar HTTP/1.1\r\n",
<del> 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n",
<del> 'raw' => "",
<del> 'redirect' => false,
<del> 'cookies' => array(),
<del> 'proxy' => array(),
<del> 'auth' => array()
<del> )
<del> )
<del> ),
<del> array(
<del> 'request' => array(
<del> 'uri' => array(
<del> 'host' => 'www.cakephp.org',
<del> 'query' => '?foo=bar'
<del> )
<del> )
<del> ),
<del> array(
<del> 'request' => 'www.cakephp.org/?foo=bar'
<del> ),
<del> array(
<del> 'request' => array(
<del> 'host' => '192.168.0.1',
<del> 'uri' => 'http://www.cakephp.org/?foo=bar'
<del> ),
<del> 'expectation' => array(
<del> 'request' => array(
<del> 'uri' => array('host' => 'www.cakephp.org')
<del> ),
<del> 'config' => array(
<del> 'request' => array(
<del> 'uri' => array('host' => 'www.cakephp.org')
<del> ),
<del> 'host' => '192.168.0.1'
<del> )
<del> )
<del> ),
<del> 'reset4' => array(
<del> 'request.uri.query' => array()
<del> ),
<del> array(
<del> 'request' => array(
<del> 'header' => array('Foo@woo' => 'bar-value')
<del> ),
<del> 'expectation' => array(
<del> 'request' => array(
<del> 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nFoo\"@\"woo: bar-value\r\n",
<del> 'line' => "GET / HTTP/1.1\r\n"
<del> )
<del> )
<del> ),
<del> array(
<del> 'request' => array('header' => array('Foo@woo' => 'bar-value', 'host' => 'foo.com'), 'uri' => 'http://www.cakephp.org/'),
<del> 'expectation' => array(
<del> 'request' => array(
<del> 'header' => "Host: foo.com\r\nConnection: close\r\nUser-Agent: CakePHP\r\nFoo\"@\"woo: bar-value\r\n"
<del> ),
<del> 'config' => array(
<del> 'host' => 'www.cakephp.org'
<del> )
<del> )
<del> ),
<del> array(
<del> 'request' => array('header' => "Foo: bar\r\n"),
<del> 'expectation' => array(
<del> 'request' => array(
<del> 'header' => "Foo: bar\r\n"
<del> )
<del> )
<del> ),
<del> array(
<del> 'request' => array('header' => "Foo: bar\r\n", 'uri' => 'http://www.cakephp.org/search?q=http_socket#ignore-me'),
<del> 'expectation' => array(
<del> 'request' => array(
<del> 'uri' => array(
<del> 'path' => '/search',
<del> 'query' => array('q' => 'http_socket'),
<del> 'fragment' => 'ignore-me'
<del> ),
<del> 'line' => "GET /search?q=http_socket HTTP/1.1\r\n"
<del> )
<del> )
<del> ),
<del> 'reset8' => array(
<del> 'request.uri.query' => array()
<del> ),
<del> array(
<del> 'request' => array(
<del> 'method' => 'POST',
<del> 'uri' => 'http://www.cakephp.org/posts/add',
<del> 'body' => array(
<del> 'name' => 'HttpSocket-is-released',
<del> 'date' => 'today'
<del> )
<del> ),
<del> 'expectation' => array(
<del> 'request' => array(
<del> 'method' => 'POST',
<del> 'uri' => array(
<del> 'path' => '/posts/add',
<del> 'fragment' => null
<del> ),
<del> 'body' => "name=HttpSocket-is-released&date=today",
<del> 'line' => "POST /posts/add HTTP/1.1\r\n",
<del> 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\n",
<del> 'raw' => "name=HttpSocket-is-released&date=today"
<del> )
<del> )
<del> ),
<del> array(
<del> 'request' => array(
<del> 'method' => 'POST',
<del> 'uri' => 'http://www.cakephp.org:8080/posts/add',
<del> 'body' => array(
<del> 'name' => 'HttpSocket-is-released',
<del> 'date' => 'today'
<del> )
<del> ),
<del> 'expectation' => array(
<del> 'config' => array(
<del> 'port' => 8080,
<del> 'request' => array(
<del> 'uri' => array(
<del> 'port' => 8080
<del> )
<del> )
<del> ),
<del> 'request' => array(
<del> 'uri' => array(
<del> 'port' => 8080
<del> ),
<del> 'header' => "Host: www.cakephp.org:8080\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\n"
<del> )
<del> )
<del> ),
<del> array(
<del> 'request' => array(
<del> 'method' => 'POST',
<del> 'uri' => 'https://www.cakephp.org/posts/add',
<del> 'body' => array(
<del> 'name' => 'HttpSocket-is-released',
<del> 'date' => 'today'
<del> )
<del> ),
<del> 'expectation' => array(
<del> 'config' => array(
<del> 'port' => 443,
<del> 'request' => array(
<del> 'uri' => array(
<del> 'scheme' => 'https',
<del> 'port' => 443
<del> )
<del> )
<del> ),
<del> 'request' => array(
<del> 'uri' => array(
<del> 'scheme' => 'https',
<del> 'port' => 443
<del> ),
<del> 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\n"
<del> )
<del> )
<del> ),
<del> array(
<del> 'request' => array(
<del> 'method' => 'POST',
<del> 'uri' => 'https://www.cakephp.org/posts/add',
<del> 'body' => array('name' => 'HttpSocket-is-released', 'date' => 'today'),
<del> 'cookies' => array('foo' => array('value' => 'bar'))
<del> ),
<del> 'expectation' => array(
<del> 'request' => array(
<del> 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\nCookie: foo=bar\r\n",
<del> 'cookies' => array(
<del> 'foo' => array('value' => 'bar'),
<del> )
<del> )
<del> )
<del> )
<del> );
<del>
<del> $expectation = array();
<del> foreach ($tests as $i => $test) {
<del> if (strpos($i, 'reset') === 0) {
<del> foreach ($test as $path => $val) {
<del> $expectation = Hash::insert($expectation, $path, $val);
<del> }
<del> continue;
<del> }
<del>
<del> if (isset($test['expectation'])) {
<del> $expectation = Hash::merge($expectation, $test['expectation']);
<del> }
<del> $this->Socket->request($test['request']);
<del>
<del> $raw = $expectation['request']['raw'];
<del> $expectation['request']['raw'] = $expectation['request']['line'] . $expectation['request']['header'] . "\r\n" . $raw;
<del>
<del> $r = array('config' => $this->Socket->config, 'request' => $this->Socket->request);
<del> $this->assertEquals($r, $expectation, 'Failed test #' . $i . ' ');
<del> $expectation['request']['raw'] = $raw;
<del> }
<del>
<del> $this->Socket->reset();
<del> $request = array('method' => 'POST', 'uri' => 'http://www.cakephp.org/posts/add', 'body' => array('name' => 'HttpSocket-is-released', 'date' => 'today'));
<del> $response = $this->Socket->request($request);
<del> $this->assertEquals("name=HttpSocket-is-released&date=today", $this->Socket->request['body']);
<del> }
<del>
<del>/**
<del> * Test the scheme + port keys
<del> *
<del> * @return void
<del> */
<del> public function testGetWithSchemeAndPort() {
<del> $this->Socket->reset();
<del> $request = array(
<del> 'uri' => array(
<del> 'scheme' => 'http',
<del> 'host' => 'cakephp.org',
<del> 'port' => 8080,
<del> 'path' => '/',
<del> ),
<del> 'method' => 'GET'
<del> );
<del> $this->Socket->request($request);
<del> $this->assertContains('Host: cakephp.org:8080', $this->Socket->request['header']);
<del> }
<del>
<del>/**
<del> * Test urls like http://cakephp.org/index.php?somestring without key/value pair for query
<del> *
<del> * @return void
<del> */
<del> public function testRequestWithStringQuery() {
<del> $this->Socket->reset();
<del> $request = array(
<del> 'uri' => array(
<del> 'scheme' => 'http',
<del> 'host' => 'cakephp.org',
<del> 'path' => 'index.php',
<del> 'query' => 'somestring'
<del> ),
<del> 'method' => 'GET'
<del> );
<del> $this->Socket->request($request);
<del> $this->assertContains("GET /index.php?somestring HTTP/1.1", $this->Socket->request['line']);
<del> }
<del>
<del>/**
<del> * The "*" asterisk character is only allowed for the following methods: OPTIONS.
<del> *
<del> * @expectedException SocketException
<del> * @return void
<del> */
<del> public function testRequestNotAllowedUri() {
<del> $this->Socket->reset();
<del> $request = array('uri' => '*', 'method' => 'GET');
<del> $this->Socket->request($request);
<del> }
<del>
<del>/**
<del> * testRequest2 method
<del> *
<del> * @return void
<del> */
<del> public function testRequest2() {
<del> $this->Socket->reset();
<del> $request = array('uri' => 'htpp://www.cakephp.org/');
<del> $number = mt_rand(0, 9999999);
<del> $this->Socket->expects($this->once())->method('connect')->will($this->returnValue(true));
<del> $serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>Hello, your lucky number is " . $number . "</h1>";
<del> $this->Socket->expects($this->at(0))->method('read')->will($this->returnValue(false));
<del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse));
<del> $this->Socket->expects($this->once())->method('write')
<del> ->with("GET / HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n\r\n");
<del> $response = (string)$this->Socket->request($request);
<del> $this->assertEquals($response, "<h1>Hello, your lucky number is " . $number . "</h1>");
<del> }
<del>
<del>/**
<del> * testRequest3 method
<del> *
<del> * @return void
<del> */
<del> public function testRequest3() {
<del> $request = array('uri' => 'htpp://www.cakephp.org/');
<del> $serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: foo=bar\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a cookie test!</h1>";
<del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse));
<del> $this->Socket->connected = true;
<del> $this->Socket->request($request);
<del> $result = $this->Socket->response['cookies'];
<del> $expect = array(
<del> 'foo' => array(
<del> 'value' => 'bar'
<del> )
<del> );
<del> $this->assertEquals($expect, $result);
<del> $this->assertEquals($this->Socket->config['request']['cookies']['www.cakephp.org'], $expect);
<del> $this->assertFalse($this->Socket->connected);
<del> }
<del>
<del>/**
<del> * testRequestWithConstructor method
<del> *
<del> * @return void
<del> */
<del> public function testRequestWithConstructor() {
<del> $request = array(
<del> 'request' => array(
<del> 'uri' => array(
<del> 'scheme' => 'http',
<del> 'host' => 'localhost',
<del> 'port' => '5984',
<del> 'user' => null,
<del> 'pass' => null
<del> )
<del> )
<del> );
<del> $http = new MockHttpSocketRequests($request);
<del>
<del> $expected = array('method' => 'GET', 'uri' => '/_test');
<del> $http->expects($this->at(0))->method('request')->with($expected);
<del> $http->get('/_test');
<del>
<del> $expected = array('method' => 'GET', 'uri' => 'http://localhost:5984/_test?count=4');
<del> $http->expects($this->at(0))->method('request')->with($expected);
<del> $http->get('/_test', array('count' => 4));
<del> }
<del>
<del>/**
<del> * testRequestWithResource
<del> *
<del> * @return void
<del> */
<del> public function testRequestWithResource() {
<del> $serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a test!</h1>";
<del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse));
<del> $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false));
<del> $this->Socket->expects($this->at(4))->method('read')->will($this->returnValue($serverResponse));
<del> $this->Socket->connected = true;
<del>
<del> $f = fopen(TMP . 'download.txt', 'w');
<del> if (!$f) {
<del> $this->markTestSkipped('Can not write in TMP directory.');
<del> }
<del>
<del> $this->Socket->setContentResource($f);
<del> $result = (string)$this->Socket->request('http://www.cakephp.org/');
<del> $this->assertEquals('', $result);
<del> $this->assertEquals('CakeHttp Server', $this->Socket->response['header']['Server']);
<del> fclose($f);
<del> $this->assertEquals(file_get_contents(TMP . 'download.txt'), '<h1>This is a test!</h1>');
<del> unlink(TMP . 'download.txt');
<del>
<del> $this->Socket->setContentResource(false);
<del> $result = (string)$this->Socket->request('http://www.cakephp.org/');
<del> $this->assertEquals('<h1>This is a test!</h1>', $result);
<del> }
<del>
<del>/**
<del> * testRequestWithCrossCookie
<del> *
<del> * @return void
<del> */
<del> public function testRequestWithCrossCookie() {
<del> $this->Socket->connected = true;
<del> $this->Socket->config['request']['cookies'] = array();
<del>
<del> $serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: foo=bar\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a test!</h1>";
<del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse));
<del> $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false));
<del> $expected = array('www.cakephp.org' => array('foo' => array('value' => 'bar')));
<del> $this->Socket->request('http://www.cakephp.org/');
<del> $this->assertEquals($expected, $this->Socket->config['request']['cookies']);
<del>
<del> $serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: bar=foo\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a test!</h1>";
<del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse));
<del> $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false));
<del> $this->Socket->request('http://www.cakephp.org/other');
<del> $this->assertEquals(array('foo' => array('value' => 'bar')), $this->Socket->request['cookies']);
<del> $expected['www.cakephp.org'] += array('bar' => array('value' => 'foo'));
<del> $this->assertEquals($expected, $this->Socket->config['request']['cookies']);
<del>
<del> $serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a test!</h1>";
<del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse));
<del> $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false));
<del> $this->Socket->request('/other2');
<del> $this->assertEquals($expected, $this->Socket->config['request']['cookies']);
<del>
<del> $serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: foobar=ok\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a test!</h1>";
<del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse));
<del> $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false));
<del> $this->Socket->request('http://www.cake.com');
<del> $this->assertTrue(empty($this->Socket->request['cookies']));
<del> $expected['www.cake.com'] = array('foobar' => array('value' => 'ok'));
<del> $this->assertEquals($expected, $this->Socket->config['request']['cookies']);
<del> }
<del>
<del>/**
<del> * testRequestCustomResponse
<del> *
<del> * @return void
<del> */
<del> public function testRequestCustomResponse() {
<del> $this->Socket->connected = true;
<del> $serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a test!</h1>";
<del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse));
<del> $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false));
<del>
<del> $this->Socket->responseClass = 'CustomResponse';
<del> $response = $this->Socket->request('http://www.cakephp.org/');
<del> $this->assertInstanceOf('CustomResponse', $response);
<del> $this->assertEquals('HTTP/1.x 2', $response->first10);
<del> }
<del>
<del>/**
<del> * Test that redirect urls are urldecoded
<del> *
<del> * @return void
<del> */
<del> public function testRequestWithRedirectUrlEncoded() {
<del> $request = array(
<del> 'uri' => 'http://localhost/oneuri',
<del> 'redirect' => 1
<del> );
<del> $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://i.cmpnet.com%2Ftechonline%2Fpdf%2Fa.pdf=\r\n\r\n";
<del> $serverResponse2 = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>You have been redirected</h1>";
<del>
<del> $this->Socket->expects($this->at(1))
<del> ->method('read')
<del> ->will($this->returnValue($serverResponse1));
<del>
<del> $this->Socket->expects($this->at(3))
<del> ->method('write')
<del> ->with($this->logicalAnd(
<del> $this->stringContains('Host: i.cmpnet.com'),
<del> $this->stringContains('GET /techonline/pdf/a.pdf')
<del> ));
<del>
<del> $this->Socket->expects($this->at(4))
<del> ->method('read')
<del> ->will($this->returnValue($serverResponse2));
<del>
<del> $response = $this->Socket->request($request);
<del> $this->assertEquals('<h1>You have been redirected</h1>', $response->body());
<del> }
<del>
<del>/**
<del> * testRequestWithRedirect method
<del> *
<del> * @return void
<del> */
<del> public function testRequestWithRedirectAsTrue() {
<del> $request = array(
<del> 'uri' => 'http://localhost/oneuri',
<del> 'redirect' => true
<del> );
<del> $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://localhost/anotheruri\r\n\r\n";
<del> $serverResponse2 = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>You have been redirected</h1>";
<del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse1));
<del> $this->Socket->expects($this->at(4))->method('read')->will($this->returnValue($serverResponse2));
<del>
<del> $response = $this->Socket->request($request);
<del> $this->assertEquals('<h1>You have been redirected</h1>', $response->body());
<del> }
<del>
<del>/**
<del> * Test that redirects with a count limit are decremented.
<del> *
<del> * @return void
<del> */
<del> public function testRequestWithRedirectAsInt() {
<del> $request = array(
<del> 'uri' => 'http://localhost/oneuri',
<del> 'redirect' => 2
<del> );
<del> $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://localhost/anotheruri\r\n\r\n";
<del> $serverResponse2 = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>You have been redirected</h1>";
<del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse1));
<del> $this->Socket->expects($this->at(4))->method('read')->will($this->returnValue($serverResponse2));
<del>
<del> $this->Socket->request($request);
<del> $this->assertEquals(1, $this->Socket->request['redirect']);
<del> }
<del>
<del>/**
<del> * Test that redirects after the redirect count reaches 9 are not followed.
<del> *
<del> * @return void
<del> */
<del> public function testRequestWithRedirectAsIntReachingZero() {
<del> $request = array(
<del> 'uri' => 'http://localhost/oneuri',
<del> 'redirect' => 1
<del> );
<del> $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://localhost/oneruri\r\n\r\n";
<del> $serverResponse2 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://localhost/anotheruri\r\n\r\n";
<del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse1));
<del> $this->Socket->expects($this->at(4))->method('read')->will($this->returnValue($serverResponse2));
<del>
<del> $response = $this->Socket->request($request);
<del> $this->assertEquals(0, $this->Socket->request['redirect']);
<del> $this->assertEquals(302, $response->code);
<del> $this->assertEquals('http://localhost/anotheruri', $response->getHeader('Location'));
<del> }
<del>
<del>/**
<del> * testProxy method
<del> *
<del> * @return void
<del> */
<del> public function testProxy() {
<del> $this->Socket->reset();
<del> $this->Socket->expects($this->any())->method('connect')->will($this->returnValue(true));
<del> $this->Socket->expects($this->any())->method('read')->will($this->returnValue(false));
<del>
<del> $this->Socket->configProxy('proxy.server', 123);
<del> $expected = "GET http://www.cakephp.org/ HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n\r\n";
<del> $this->Socket->request('http://www.cakephp.org/');
<del> $this->assertEquals($expected, $this->Socket->request['raw']);
<del> $this->assertEquals('proxy.server', $this->Socket->config['host']);
<del> $this->assertEquals(123, $this->Socket->config['port']);
<del> $expected = array(
<del> 'host' => 'proxy.server',
<del> 'port' => 123,
<del> 'method' => null,
<del> 'user' => null,
<del> 'pass' => null
<del> );
<del> $this->assertEquals($expected, $this->Socket->request['proxy']);
<del>
<del> $expected = "GET http://www.cakephp.org/bakery HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n\r\n";
<del> $this->Socket->request('/bakery');
<del> $this->assertEquals($expected, $this->Socket->request['raw']);
<del> $this->assertEquals('proxy.server', $this->Socket->config['host']);
<del> $this->assertEquals(123, $this->Socket->config['port']);
<del> $expected = array(
<del> 'host' => 'proxy.server',
<del> 'port' => 123,
<del> 'method' => null,
<del> 'user' => null,
<del> 'pass' => null
<del> );
<del> $this->assertEquals($expected, $this->Socket->request['proxy']);
<del>
<del> $expected = "GET http://www.cakephp.org/ HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nProxy-Authorization: Test mark.secret\r\n\r\n";
<del> $this->Socket->configProxy('proxy.server', 123, 'Test', 'mark', 'secret');
<del> $this->Socket->request('http://www.cakephp.org/');
<del> $this->assertEquals($expected, $this->Socket->request['raw']);
<del> $this->assertEquals('proxy.server', $this->Socket->config['host']);
<del> $this->assertEquals(123, $this->Socket->config['port']);
<del> $expected = array(
<del> 'host' => 'proxy.server',
<del> 'port' => 123,
<del> 'method' => 'Test',
<del> 'user' => 'mark',
<del> 'pass' => 'secret'
<del> );
<del> $this->assertEquals($expected, $this->Socket->request['proxy']);
<del>
<del> $this->Socket->configAuth('Test', 'login', 'passwd');
<del> $expected = "GET http://www.cakephp.org/ HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nProxy-Authorization: Test mark.secret\r\nAuthorization: Test login.passwd\r\n\r\n";
<del> $this->Socket->request('http://www.cakephp.org/');
<del> $this->assertEquals($expected, $this->Socket->request['raw']);
<del> $expected = array(
<del> 'host' => 'proxy.server',
<del> 'port' => 123,
<del> 'method' => 'Test',
<del> 'user' => 'mark',
<del> 'pass' => 'secret'
<del> );
<del> $this->assertEquals($expected, $this->Socket->request['proxy']);
<del> $expected = array(
<del> 'Test' => array(
<del> 'user' => 'login',
<del> 'pass' => 'passwd'
<del> )
<del> );
<del> $this->assertEquals($expected, $this->Socket->request['auth']);
<del> }
<del>
<del>/**
<del> * testUrl method
<del> *
<del> * @return void
<del> */
<del> public function testUrl() {
<del> $this->Socket->reset(true);
<del>
<del> $this->assertEquals(false, $this->Socket->url(true));
<del>
<del> $url = $this->Socket->url('www.cakephp.org');
<del> $this->assertEquals('http://www.cakephp.org/', $url);
<del>
<del> $url = $this->Socket->url('https://www.cakephp.org/posts/add');
<del> $this->assertEquals('https://www.cakephp.org/posts/add', $url);
<del> $url = $this->Socket->url('http://www.cakephp/search?q=socket', '/%path?%query');
<del> $this->assertEquals('/search?q=socket', $url);
<del>
<del> $this->Socket->config['request']['uri']['host'] = 'bakery.cakephp.org';
<del> $url = $this->Socket->url();
<del> $this->assertEquals('http://bakery.cakephp.org/', $url);
<del>
<del> $this->Socket->configUri('http://www.cakephp.org');
<del> $url = $this->Socket->url('/search?q=bar');
<del> $this->assertEquals('http://www.cakephp.org/search?q=bar', $url);
<del>
<del> $url = $this->Socket->url(array('host' => 'www.foobar.org', 'query' => array('q' => 'bar')));
<del> $this->assertEquals('http://www.foobar.org/?q=bar', $url);
<del>
<del> $url = $this->Socket->url(array('path' => '/supersearch', 'query' => array('q' => 'bar')));
<del> $this->assertEquals('http://www.cakephp.org/supersearch?q=bar', $url);
<del>
<del> $this->Socket->configUri('http://www.google.com');
<del> $url = $this->Socket->url('/search?q=socket');
<del> $this->assertEquals('http://www.google.com/search?q=socket', $url);
<del>
<del> $url = $this->Socket->url();
<del> $this->assertEquals('http://www.google.com/', $url);
<del>
<del> $this->Socket->configUri('https://www.google.com');
<del> $url = $this->Socket->url('/search?q=socket');
<del> $this->assertEquals('https://www.google.com/search?q=socket', $url);
<del>
<del> $this->Socket->reset();
<del> $this->Socket->configUri('www.google.com:443');
<del> $url = $this->Socket->url('/search?q=socket');
<del> $this->assertEquals('https://www.google.com/search?q=socket', $url);
<del>
<del> $this->Socket->reset();
<del> $this->Socket->configUri('www.google.com:8080');
<del> $url = $this->Socket->url('/search?q=socket');
<del> $this->assertEquals('http://www.google.com:8080/search?q=socket', $url);
<del> }
<del>
<del>/**
<del> * testGet method
<del> *
<del> * @return void
<del> */
<del> public function testGet() {
<del> $this->RequestSocket->reset();
<del>
<del> $this->RequestSocket->expects($this->at(0))
<del> ->method('request')
<del> ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/'));
<del>
<del> $this->RequestSocket->expects($this->at(1))
<del> ->method('request')
<del> ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/?foo=bar'));
<del>
<del> $this->RequestSocket->expects($this->at(2))
<del> ->method('request')
<del> ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/?foo=bar'));
<del>
<del> $this->RequestSocket->expects($this->at(3))
<del> ->method('request')
<del> ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/?foo=23&foobar=42'));
<del>
<del> $this->RequestSocket->expects($this->at(4))
<del> ->method('request')
<del> ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/', 'version' => '1.0'));
<del>
<del> $this->RequestSocket->expects($this->at(5))
<del> ->method('request')
<del> ->with(array('method' => 'GET', 'uri' => 'https://secure.example.com/test.php?one=two'));
<del>
<del> $this->RequestSocket->expects($this->at(6))
<del> ->method('request')
<del> ->with(array('method' => 'GET', 'uri' => 'https://example.com/oauth/access?clientid=123&redirect_uri=http%3A%2F%2Fexample.com&code=456'));
<del>
<del> $this->RequestSocket->get('http://www.google.com/');
<del> $this->RequestSocket->get('http://www.google.com/', array('foo' => 'bar'));
<del> $this->RequestSocket->get('http://www.google.com/', 'foo=bar');
<del> $this->RequestSocket->get('http://www.google.com/?foo=bar', array('foobar' => '42', 'foo' => '23'));
<del> $this->RequestSocket->get('http://www.google.com/', null, array('version' => '1.0'));
<del> $this->RequestSocket->get('https://secure.example.com/test.php', array('one' => 'two'));
<del> $this->RequestSocket->get('https://example.com/oauth/access', array(
<del> 'clientid' => '123',
<del> 'redirect_uri' => 'http://example.com',
<del> 'code' => 456
<del> ));
<del> }
<del>
<del>/**
<del> * Test authentication
<del> *
<del> * @return void
<del> */
<del> public function testAuth() {
<del> $socket = new MockHttpSocket();
<del> $socket->get('http://mark:secret@example.com/test');
<del> $this->assertTrue(strpos($socket->request['header'], 'Authorization: Basic bWFyazpzZWNyZXQ=') !== false);
<del>
<del> $socket->configAuth(false);
<del> $socket->get('http://example.com/test');
<del> $this->assertFalse(strpos($socket->request['header'], 'Authorization:'));
<del>
<del> $socket->configAuth('Test', 'mark', 'passwd');
<del> $socket->get('http://example.com/test');
<del> $this->assertTrue(strpos($socket->request['header'], 'Authorization: Test mark.passwd') !== false);
<del> }
<del>
<del>/**
<del> * test that two consecutive get() calls reset the authentication credentials.
<del> *
<del> * @return void
<del> */
<del> public function testConsecutiveGetResetsAuthCredentials() {
<del> $socket = new MockHttpSocket();
<del> $socket->get('http://mark:secret@example.com/test');
<del> $this->assertEquals('mark', $socket->request['uri']['user']);
<del> $this->assertEquals('secret', $socket->request['uri']['pass']);
<del> $this->assertTrue(strpos($socket->request['header'], 'Authorization: Basic bWFyazpzZWNyZXQ=') !== false);
<del>
<del> $socket->get('/test2');
<del> $this->assertTrue(strpos($socket->request['header'], 'Authorization: Basic bWFyazpzZWNyZXQ=') !== false);
<del>
<del> $socket->get('/test3');
<del> $this->assertTrue(strpos($socket->request['header'], 'Authorization: Basic bWFyazpzZWNyZXQ=') !== false);
<del> }
<del>
<del>/**
<del> * testPostPutDelete method
<del> *
<del> * @return void
<del> */
<del> public function testPost() {
<del> $this->RequestSocket->reset();
<del> $this->RequestSocket->expects($this->at(0))
<del> ->method('request')
<del> ->with(array('method' => 'POST', 'uri' => 'http://www.google.com/', 'body' => array()));
<del>
<del> $this->RequestSocket->expects($this->at(1))
<del> ->method('request')
<del> ->with(array('method' => 'POST', 'uri' => 'http://www.google.com/', 'body' => array('Foo' => 'bar')));
<del>
<del> $this->RequestSocket->expects($this->at(2))
<del> ->method('request')
<del> ->with(array('method' => 'POST', 'uri' => 'http://www.google.com/', 'body' => null, 'line' => 'Hey Server'));
<del>
<del> $this->RequestSocket->post('http://www.google.com/');
<del> $this->RequestSocket->post('http://www.google.com/', array('Foo' => 'bar'));
<del> $this->RequestSocket->post('http://www.google.com/', null, array('line' => 'Hey Server'));
<del> }
<del>
<del>/**
<del> * testPut
<del> *
<del> * @return void
<del> */
<del> public function testPut() {
<del> $this->RequestSocket->reset();
<del> $this->RequestSocket->expects($this->at(0))
<del> ->method('request')
<del> ->with(array('method' => 'PUT', 'uri' => 'http://www.google.com/', 'body' => array()));
<del>
<del> $this->RequestSocket->expects($this->at(1))
<del> ->method('request')
<del> ->with(array('method' => 'PUT', 'uri' => 'http://www.google.com/', 'body' => array('Foo' => 'bar')));
<del>
<del> $this->RequestSocket->expects($this->at(2))
<del> ->method('request')
<del> ->with(array('method' => 'PUT', 'uri' => 'http://www.google.com/', 'body' => null, 'line' => 'Hey Server'));
<del>
<del> $this->RequestSocket->put('http://www.google.com/');
<del> $this->RequestSocket->put('http://www.google.com/', array('Foo' => 'bar'));
<del> $this->RequestSocket->put('http://www.google.com/', null, array('line' => 'Hey Server'));
<del> }
<del>
<del>/**
<del> * testDelete
<del> *
<del> * @return void
<del> */
<del> public function testDelete() {
<del> $this->RequestSocket->reset();
<del> $this->RequestSocket->expects($this->at(0))
<del> ->method('request')
<del> ->with(array('method' => 'DELETE', 'uri' => 'http://www.google.com/', 'body' => array()));
<del>
<del> $this->RequestSocket->expects($this->at(1))
<del> ->method('request')
<del> ->with(array('method' => 'DELETE', 'uri' => 'http://www.google.com/', 'body' => array('Foo' => 'bar')));
<del>
<del> $this->RequestSocket->expects($this->at(2))
<del> ->method('request')
<del> ->with(array('method' => 'DELETE', 'uri' => 'http://www.google.com/', 'body' => null, 'line' => 'Hey Server'));
<del>
<del> $this->RequestSocket->delete('http://www.google.com/');
<del> $this->RequestSocket->delete('http://www.google.com/', array('Foo' => 'bar'));
<del> $this->RequestSocket->delete('http://www.google.com/', null, array('line' => 'Hey Server'));
<del> }
<del>
<del>/**
<del> * testBuildRequestLine method
<del> *
<del> * @return void
<del> */
<del> public function testBuildRequestLine() {
<del> $this->Socket->reset();
<del>
<del> $this->Socket->quirksMode = true;
<del> $r = $this->Socket->buildRequestLine('Foo');
<del> $this->assertEquals('Foo', $r);
<del> $this->Socket->quirksMode = false;
<del>
<del> $r = $this->Socket->buildRequestLine(true);
<del> $this->assertEquals(false, $r);
<del>
<del> $r = $this->Socket->buildRequestLine(array('foo' => 'bar', 'method' => 'foo'));
<del> $this->assertEquals(false, $r);
<del>
<del> $r = $this->Socket->buildRequestLine(array('method' => 'GET', 'uri' => 'http://www.cakephp.org/search?q=socket'));
<del> $this->assertEquals("GET /search?q=socket HTTP/1.1\r\n", $r);
<del>
<del> $request = array(
<del> 'method' => 'GET',
<del> 'uri' => array(
<del> 'path' => '/search',
<del> 'query' => array('q' => 'socket')
<del> )
<del> );
<del> $r = $this->Socket->buildRequestLine($request);
<del> $this->assertEquals("GET /search?q=socket HTTP/1.1\r\n", $r);
<del>
<del> unset($request['method']);
<del> $r = $this->Socket->buildRequestLine($request);
<del> $this->assertEquals("GET /search?q=socket HTTP/1.1\r\n", $r);
<del>
<del> $r = $this->Socket->buildRequestLine($request, 'CAKE-HTTP/0.1');
<del> $this->assertEquals("GET /search?q=socket CAKE-HTTP/0.1\r\n", $r);
<del>
<del> $request = array('method' => 'OPTIONS', 'uri' => '*');
<del> $r = $this->Socket->buildRequestLine($request);
<del> $this->assertEquals("OPTIONS * HTTP/1.1\r\n", $r);
<del>
<del> $request['method'] = 'GET';
<del> $this->Socket->quirksMode = true;
<del> $r = $this->Socket->buildRequestLine($request);
<del> $this->assertEquals("GET * HTTP/1.1\r\n", $r);
<del>
<del> $r = $this->Socket->buildRequestLine("GET * HTTP/1.1\r\n");
<del> $this->assertEquals("GET * HTTP/1.1\r\n", $r);
<del> }
<del>
<del>/**
<del> * testBadBuildRequestLine method
<del> *
<del> * @expectedException SocketException
<del> * @return void
<del> */
<del> public function testBadBuildRequestLine() {
<del> $this->Socket->buildRequestLine('Foo');
<del> }
<del>
<del>/**
<del> * testBadBuildRequestLine2 method
<del> *
<del> * @expectedException SocketException
<del> * @return void
<del> */
<del> public function testBadBuildRequestLine2() {
<del> $this->Socket->buildRequestLine("GET * HTTP/1.1\r\n");
<del> }
<del>
<del>/**
<del> * Asserts that HttpSocket::parseUri is working properly
<del> *
<del> * @return void
<del> */
<del> public function testParseUri() {
<del> $this->Socket->reset();
<del>
<del> $uri = $this->Socket->parseUri(array('invalid' => 'uri-string'));
<del> $this->assertEquals(false, $uri);
<del>
<del> $uri = $this->Socket->parseUri(array('invalid' => 'uri-string'), array('host' => 'somehost'));
<del> $this->assertEquals(array('host' => 'somehost', 'invalid' => 'uri-string'), $uri);
<del>
<del> $uri = $this->Socket->parseUri(false);
<del> $this->assertEquals(false, $uri);
<del>
<del> $uri = $this->Socket->parseUri('/my-cool-path');
<del> $this->assertEquals(array('path' => '/my-cool-path'), $uri);
<del>
<del> $uri = $this->Socket->parseUri('http://bob:foo123@www.cakephp.org:40/search?q=dessert#results');
<del> $this->assertEquals($uri, array(
<del> 'scheme' => 'http',
<del> 'host' => 'www.cakephp.org',
<del> 'port' => 40,
<del> 'user' => 'bob',
<del> 'pass' => 'foo123',
<del> 'path' => '/search',
<del> 'query' => array('q' => 'dessert'),
<del> 'fragment' => 'results'
<del> ));
<del>
<del> $uri = $this->Socket->parseUri('http://www.cakephp.org/');
<del> $this->assertEquals($uri, array(
<del> 'scheme' => 'http',
<del> 'host' => 'www.cakephp.org',
<del> 'path' => '/'
<del> ));
<del>
<del> $uri = $this->Socket->parseUri('http://www.cakephp.org', true);
<del> $this->assertEquals($uri, array(
<del> 'scheme' => 'http',
<del> 'host' => 'www.cakephp.org',
<del> 'port' => 80,
<del> 'user' => null,
<del> 'pass' => null,
<del> 'path' => '/',
<del> 'query' => array(),
<del> 'fragment' => null
<del> ));
<del>
<del> $uri = $this->Socket->parseUri('https://www.cakephp.org', true);
<del> $this->assertEquals($uri, array(
<del> 'scheme' => 'https',
<del> 'host' => 'www.cakephp.org',
<del> 'port' => 443,
<del> 'user' => null,
<del> 'pass' => null,
<del> 'path' => '/',
<del> 'query' => array(),
<del> 'fragment' => null
<del> ));
<del>
<del> $uri = $this->Socket->parseUri('www.cakephp.org:443/query?foo', true);
<del> $this->assertEquals($uri, array(
<del> 'scheme' => 'https',
<del> 'host' => 'www.cakephp.org',
<del> 'port' => 443,
<del> 'user' => null,
<del> 'pass' => null,
<del> 'path' => '/query',
<del> 'query' => array('foo' => ""),
<del> 'fragment' => null
<del> ));
<del>
<del> $uri = $this->Socket->parseUri('http://www.cakephp.org', array('host' => 'piephp.org', 'user' => 'bob', 'fragment' => 'results'));
<del> $this->assertEquals($uri, array(
<del> 'host' => 'www.cakephp.org',
<del> 'user' => 'bob',
<del> 'fragment' => 'results',
<del> 'scheme' => 'http'
<del> ));
<del>
<del> $uri = $this->Socket->parseUri('https://www.cakephp.org', array('scheme' => 'http', 'port' => 23));
<del> $this->assertEquals($uri, array(
<del> 'scheme' => 'https',
<del> 'port' => 23,
<del> 'host' => 'www.cakephp.org'
<del> ));
<del>
<del> $uri = $this->Socket->parseUri('www.cakephp.org:59', array('scheme' => array('http', 'https'), 'port' => 80));
<del> $this->assertEquals($uri, array(
<del> 'scheme' => 'http',
<del> 'port' => 59,
<del> 'host' => 'www.cakephp.org'
<del> ));
<del>
<del> $uri = $this->Socket->parseUri(array('scheme' => 'http', 'host' => 'www.google.com', 'port' => 8080), array('scheme' => array('http', 'https'), 'host' => 'www.google.com', 'port' => array(80, 443)));
<del> $this->assertEquals($uri, array(
<del> 'scheme' => 'http',
<del> 'host' => 'www.google.com',
<del> 'port' => 8080
<del> ));
<del>
<del> $uri = $this->Socket->parseUri('http://www.cakephp.org/?param1=value1¶m2=value2%3Dvalue3');
<del> $this->assertEquals($uri, array(
<del> 'scheme' => 'http',
<del> 'host' => 'www.cakephp.org',
<del> 'path' => '/',
<del> 'query' => array(
<del> 'param1' => 'value1',
<del> 'param2' => 'value2=value3'
<del> )
<del> ));
<del>
<del> $uri = $this->Socket->parseUri('http://www.cakephp.org/?param1=value1¶m2=value2=value3');
<del> $this->assertEquals($uri, array(
<del> 'scheme' => 'http',
<del> 'host' => 'www.cakephp.org',
<del> 'path' => '/',
<del> 'query' => array(
<del> 'param1' => 'value1',
<del> 'param2' => 'value2=value3'
<del> )
<del> ));
<del> }
<del>
<del>/**
<del> * Tests that HttpSocket::buildUri can turn all kinds of uri arrays (and strings) into fully or partially qualified URI's
<del> *
<del> * @return void
<del> */
<del> public function testBuildUri() {
<del> $this->Socket->reset();
<del>
<del> $r = $this->Socket->buildUri(true);
<del> $this->assertEquals(false, $r);
<del>
<del> $r = $this->Socket->buildUri('foo.com');
<del> $this->assertEquals('http://foo.com/', $r);
<del>
<del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org'));
<del> $this->assertEquals('http://www.cakephp.org/', $r);
<del>
<del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'scheme' => 'https'));
<del> $this->assertEquals('https://www.cakephp.org/', $r);
<del>
<del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'port' => 23));
<del> $this->assertEquals('http://www.cakephp.org:23/', $r);
<del>
<del> $r = $this->Socket->buildUri(array('path' => 'www.google.com/search', 'query' => 'q=cakephp'));
<del> $this->assertEquals('http://www.google.com/search?q=cakephp', $r);
<del>
<del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'scheme' => 'https', 'port' => 79));
<del> $this->assertEquals('https://www.cakephp.org:79/', $r);
<del>
<del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'path' => 'foo'));
<del> $this->assertEquals('http://www.cakephp.org/foo', $r);
<del>
<del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'path' => '/foo'));
<del> $this->assertEquals('http://www.cakephp.org/foo', $r);
<del>
<del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'path' => '/search', 'query' => array('q' => 'HttpSocket')));
<del> $this->assertEquals('http://www.cakephp.org/search?q=HttpSocket', $r);
<del>
<del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'fragment' => 'bar'));
<del> $this->assertEquals('http://www.cakephp.org/#bar', $r);
<del>
<del> $r = $this->Socket->buildUri(array(
<del> 'scheme' => 'https',
<del> 'host' => 'www.cakephp.org',
<del> 'port' => 25,
<del> 'user' => 'bob',
<del> 'pass' => 'secret',
<del> 'path' => '/cool',
<del> 'query' => array('foo' => 'bar'),
<del> 'fragment' => 'comment'
<del> ));
<del> $this->assertEquals('https://bob:secret@www.cakephp.org:25/cool?foo=bar#comment', $r);
<del>
<del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'fragment' => 'bar'), '%fragment?%host');
<del> $this->assertEquals('bar?www.cakephp.org', $r);
<del>
<del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org'), '%fragment???%host');
<del> $this->assertEquals('???www.cakephp.org', $r);
<del>
<del> $r = $this->Socket->buildUri(array('path' => '*'), '/%path?%query');
<del> $this->assertEquals('*', $r);
<del>
<del> $r = $this->Socket->buildUri(array('scheme' => 'foo', 'host' => 'www.cakephp.org'));
<del> $this->assertEquals('foo://www.cakephp.org:80/', $r);
<del> }
<del>
<del>/**
<del> * Asserts that HttpSocket::parseQuery is working properly
<del> *
<del> * @return void
<del> */
<del> public function testParseQuery() {
<del> $this->Socket->reset();
<del>
<del> $query = $this->Socket->parseQuery(array('framework' => 'cakephp'));
<del> $this->assertEquals(array('framework' => 'cakephp'), $query);
<del>
<del> $query = $this->Socket->parseQuery('');
<del> $this->assertEquals(array(), $query);
<del>
<del> $query = $this->Socket->parseQuery('framework=cakephp');
<del> $this->assertEquals(array('framework' => 'cakephp'), $query);
<del>
<del> $query = $this->Socket->parseQuery('?framework=cakephp');
<del> $this->assertEquals(array('framework' => 'cakephp'), $query);
<del>
<del> $query = $this->Socket->parseQuery('a&b&c');
<del> $this->assertEquals(array('a' => '', 'b' => '', 'c' => ''), $query);
<del>
<del> $query = $this->Socket->parseQuery('value=12345');
<del> $this->assertEquals(array('value' => '12345'), $query);
<del>
<del> $query = $this->Socket->parseQuery('a[0]=foo&a[1]=bar&a[2]=cake');
<del> $this->assertEquals(array('a' => array(0 => 'foo', 1 => 'bar', 2 => 'cake')), $query);
<del>
<del> $query = $this->Socket->parseQuery('a[]=foo&a[]=bar&a[]=cake');
<del> $this->assertEquals(array('a' => array(0 => 'foo', 1 => 'bar', 2 => 'cake')), $query);
<del>
<del> $query = $this->Socket->parseQuery('a[][]=foo&a[][]=bar&a[][]=cake');
<del> $expectedQuery = array(
<del> 'a' => array(
<del> 0 => array(
<del> 0 => 'foo'
<del> ),
<del> 1 => array(
<del> 0 => 'bar'
<del> ),
<del> array(
<del> 0 => 'cake'
<del> )
<del> )
<del> );
<del> $this->assertEquals($expectedQuery, $query);
<del>
<del> $query = $this->Socket->parseQuery('a[][]=foo&a[bar]=php&a[][]=bar&a[][]=cake');
<del> $expectedQuery = array(
<del> 'a' => array(
<del> array('foo'),
<del> 'bar' => 'php',
<del> array('bar'),
<del> array('cake')
<del> )
<del> );
<del> $this->assertEquals($expectedQuery, $query);
<del>
<del> $query = $this->Socket->parseQuery('user[]=jim&user[3]=tom&user[]=bob');
<del> $expectedQuery = array(
<del> 'user' => array(
<del> 0 => 'jim',
<del> 3 => 'tom',
<del> 4 => 'bob'
<del> )
<del> );
<del> $this->assertEquals($expectedQuery, $query);
<del>
<del> $queryStr = 'user[0]=foo&user[0][items][]=foo&user[0][items][]=bar&user[][name]=jim&user[1][items][personal][]=book&user[1][items][personal][]=pen&user[1][items][]=ball&user[count]=2&empty';
<del> $query = $this->Socket->parseQuery($queryStr);
<del> $expectedQuery = array(
<del> 'user' => array(
<del> 0 => array(
<del> 'items' => array(
<del> 'foo',
<del> 'bar'
<del> )
<del> ),
<del> 1 => array(
<del> 'name' => 'jim',
<del> 'items' => array(
<del> 'personal' => array(
<del> 'book'
<del> , 'pen'
<del> ),
<del> 'ball'
<del> )
<del> ),
<del> 'count' => '2'
<del> ),
<del> 'empty' => ''
<del> );
<del> $this->assertEquals($expectedQuery, $query);
<del>
<del> $query = 'openid.ns=example.com&foo=bar&foo=baz';
<del> $result = $this->Socket->parseQuery($query);
<del> $expected = array(
<del> 'openid.ns' => 'example.com',
<del> 'foo' => array('bar', 'baz')
<del> );
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<del>/**
<del> * Tests that HttpSocket::buildHeader can turn a given $header array into a proper header string according to
<del> * HTTP 1.1 specs.
<del> *
<del> * @return void
<del> */
<del> public function testBuildHeader() {
<del> $this->Socket->reset();
<del>
<del> $r = $this->Socket->buildHeader(true);
<del> $this->assertEquals(false, $r);
<del>
<del> $r = $this->Socket->buildHeader('My raw header');
<del> $this->assertEquals('My raw header', $r);
<del>
<del> $r = $this->Socket->buildHeader(array('Host' => 'www.cakephp.org'));
<del> $this->assertEquals("Host: www.cakephp.org\r\n", $r);
<del>
<del> $r = $this->Socket->buildHeader(array('Host' => 'www.cakephp.org', 'Connection' => 'Close'));
<del> $this->assertEquals("Host: www.cakephp.org\r\nConnection: Close\r\n", $r);
<del>
<del> $r = $this->Socket->buildHeader(array('People' => array('Bob', 'Jim', 'John')));
<del> $this->assertEquals("People: Bob,Jim,John\r\n", $r);
<del>
<del> $r = $this->Socket->buildHeader(array('Multi-Line-Field' => "This is my\r\nMulti Line field"));
<del> $this->assertEquals("Multi-Line-Field: This is my\r\n Multi Line field\r\n", $r);
<del>
<del> $r = $this->Socket->buildHeader(array('Multi-Line-Field' => "This is my\r\n Multi Line field"));
<del> $this->assertEquals("Multi-Line-Field: This is my\r\n Multi Line field\r\n", $r);
<del>
<del> $r = $this->Socket->buildHeader(array('Multi-Line-Field' => "This is my\r\n\tMulti Line field"));
<del> $this->assertEquals("Multi-Line-Field: This is my\r\n\tMulti Line field\r\n", $r);
<del>
<del> $r = $this->Socket->buildHeader(array('Test@Field' => "My value"));
<del> $this->assertEquals("Test\"@\"Field: My value\r\n", $r);
<del> }
<del>
<del>/**
<del> * testBuildCookies method
<del> *
<del> * @return void
<del> */
<del> public function testBuildCookies() {
<del> $cookies = array(
<del> 'foo' => array(
<del> 'value' => 'bar'
<del> ),
<del> 'people' => array(
<del> 'value' => 'jim,jack,johnny;',
<del> 'path' => '/accounts'
<del> )
<del> );
<del> $expect = "Cookie: foo=bar; people=jim,jack,johnny\";\"\r\n";
<del> $result = $this->Socket->buildCookies($cookies);
<del> $this->assertEquals($expect, $result);
<del> }
<del>
<del>/**
<del> * Tests that HttpSocket::_tokenEscapeChars() returns the right characters.
<del> *
<del> * @return void
<del> */
<del> public function testTokenEscapeChars() {
<del> $this->Socket->reset();
<del>
<del> $expected = array(
<del> '\x22','\x28','\x29','\x3c','\x3e','\x40','\x2c','\x3b','\x3a','\x5c','\x2f','\x5b','\x5d','\x3f','\x3d','\x7b',
<del> '\x7d','\x20','\x00','\x01','\x02','\x03','\x04','\x05','\x06','\x07','\x08','\x09','\x0a','\x0b','\x0c','\x0d',
<del> '\x0e','\x0f','\x10','\x11','\x12','\x13','\x14','\x15','\x16','\x17','\x18','\x19','\x1a','\x1b','\x1c','\x1d',
<del> '\x1e','\x1f','\x7f'
<del> );
<del> $r = $this->Socket->tokenEscapeChars();
<del> $this->assertEquals($expected, $r);
<del>
<del> foreach ($expected as $key => $char) {
<del> $expected[$key] = chr(hexdec(substr($char, 2)));
<del> }
<del>
<del> $r = $this->Socket->tokenEscapeChars(false);
<del> $this->assertEquals($expected, $r);
<del> }
<del>
<del>/**
<del> * Test that HttpSocket::escapeToken is escaping all characters as described in RFC 2616 (HTTP 1.1 specs)
<del> *
<del> * @return void
<del> */
<del> public function testEscapeToken() {
<del> $this->Socket->reset();
<del>
<del> $this->assertEquals('Foo', $this->Socket->escapeToken('Foo'));
<del>
<del> $escape = $this->Socket->tokenEscapeChars(false);
<del> foreach ($escape as $char) {
<del> $token = 'My-special-' . $char . '-Token';
<del> $escapedToken = $this->Socket->escapeToken($token);
<del> $expectedToken = 'My-special-"' . $char . '"-Token';
<del>
<del> $this->assertEquals($expectedToken, $escapedToken, 'Test token escaping for ASCII ' . ord($char));
<del> }
<del>
<del> $token = 'Extreme-:Token- -"@-test';
<del> $escapedToken = $this->Socket->escapeToken($token);
<del> $expectedToken = 'Extreme-":"Token-" "-""""@"-test';
<del> $this->assertEquals($expectedToken, $escapedToken);
<del> }
<del>
<del>/**
<del> * This tests asserts HttpSocket::reset() resets a HttpSocket instance to it's initial state (before Object::__construct
<del> * got executed)
<del> *
<del> * @return void
<del> */
<del> public function testReset() {
<del> $this->Socket->reset();
<del>
<del> $initialState = get_class_vars('HttpSocket');
<del> foreach ($initialState as $property => $value) {
<del> $this->Socket->{$property} = 'Overwritten';
<del> }
<del>
<del> $return = $this->Socket->reset();
<del>
<del> foreach ($initialState as $property => $value) {
<del> $this->assertEquals($this->Socket->{$property}, $value);
<del> }
<del>
<del> $this->assertEquals(true, $return);
<del> }
<del>
<del>/**
<del> * This tests asserts HttpSocket::reset(false) resets certain HttpSocket properties to their initial state (before
<del> * Object::__construct got executed).
<del> *
<del> * @return void
<del> */
<del> public function testPartialReset() {
<del> $this->Socket->reset();
<del>
<del> $partialResetProperties = array('request', 'response');
<del> $initialState = get_class_vars('HttpSocket');
<del>
<del> foreach ($initialState as $property => $value) {
<del> $this->Socket->{$property} = 'Overwritten';
<del> }
<del>
<del> $return = $this->Socket->reset(false);
<del>
<del> foreach ($initialState as $property => $originalValue) {
<del> if (in_array($property, $partialResetProperties)) {
<del> $this->assertEquals($this->Socket->{$property}, $originalValue);
<del> } else {
<del> $this->assertEquals('Overwritten', $this->Socket->{$property});
<del> }
<del> }
<del> $this->assertEquals(true, $return);
<del> }
<del>
<del>/**
<del> * test configuring the context from the flat keys.
<del> *
<del> * @return void
<del> */
<del> public function testConfigContext() {
<del> $this->Socket->reset();
<del> $this->Socket->request('http://example.com');
<del> $this->assertTrue($this->Socket->config['context']['ssl']['verify_peer']);
<del> $this->assertEquals(5, $this->Socket->config['context']['ssl']['verify_depth']);
<del> $this->assertEquals('example.com', $this->Socket->config['context']['ssl']['CN_match']);
<del> $this->assertArrayNotHasKey('ssl_verify_peer', $this->Socket->config);
<del> $this->assertArrayNotHasKey('ssl_verify_host', $this->Socket->config);
<del> $this->assertArrayNotHasKey('ssl_verify_depth', $this->Socket->config);
<del> }
<del>
<del>/**
<del> * Test that requests fail when peer verification fails.
<del> *
<del> * @return void
<del> */
<del> public function testVerifyPeer() {
<del> $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
<del> $socket = new HttpSocket();
<del> try {
<del> $socket->get('https://typography.com');
<del> $this->markTestSkipped('Found valid certificate, was expecting invalid certificate.');
<del> } catch (SocketException $e) {
<del> $message = $e->getMessage();
<del> $this->skipIf(strpos($message, 'Invalid HTTP') !== false, 'Invalid HTTP Response received, skipping.');
<del> $this->assertContains('Peer certificate CN', $message);
<del> $this->assertContains('Failed to enable crypto', $message);
<del> }
<del> }
<del>}
<ide><path>lib/Cake/Test/Case/Routing/DispatcherTest.php
<del><?php
<del>/**
<del> * DispatcherTest file
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.Routing
<del> * @since CakePHP(tm) v 1.2.0.4206
<del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<del> */
<del>App::uses('Dispatcher', 'Routing');
<del>
<del>if (!class_exists('AppController', false)) {
<del> require_once CAKE . 'Test' . DS . 'test_app' . DS . 'Controller' . DS . 'AppController.php';
<del>} elseif (!defined('APP_CONTROLLER_EXISTS')) {
<del> define('APP_CONTROLLER_EXISTS', true);
<del>}
<del>
<del>/**
<del> * A testing stub that doesn't send headers.
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class DispatcherMockCakeResponse extends CakeResponse {
<del>
<del> protected function _sendHeader($name, $value = null) {
<del> return $name . ' ' . $value;
<del> }
<del>
<del>}
<del>
<del>/**
<del> * TestDispatcher class
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class TestDispatcher extends Dispatcher {
<del>
<del>/**
<del> * Controller instance, made publicly available for testing
<del> *
<del> * @var Controller
<del> */
<del> public $controller;
<del>
<del>/**
<del> * invoke method
<del> *
<del> * @param Controller $controller
<del> * @param CakeRequest $request
<del> * @param CakeResponse $response
<del> * @return void
<del> */
<del> protected function _invoke(Controller $controller, CakeRequest $request, CakeResponse $response) {
<del> $this->controller = $controller;
<del> return parent::_invoke($controller, $request, $response);
<del> }
<del>
<del>/**
<del> * Helper function to test single method attaching for dispatcher filters
<del> *
<del> * @param CakeEvent $event
<del> * @return void
<del> */
<del> public function filterTest($event) {
<del> $event->data['request']->params['eventName'] = $event->name();
<del> }
<del>
<del>/**
<del> * Helper function to test single method attaching for dispatcher filters
<del> *
<del> * @param CakeEvent
<del> * @return void
<del> */
<del> public function filterTest2($event) {
<del> $event->stopPropagation();
<del> return $event->data['response'];
<del> }
<del>
<del>}
<del>
<del>/**
<del> * MyPluginAppController class
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class MyPluginAppController extends AppController {
<del>}
<del>
<del>abstract class DispatcherTestAbstractController extends Controller {
<del>
<del> abstract public function index();
<del>
<del>}
<del>
<del>interface DispatcherTestInterfaceController {
<del>
<del> public function index();
<del>
<del>}
<del>
<del>/**
<del> * MyPluginController class
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class MyPluginController extends MyPluginAppController {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'MyPlugin'
<del> */
<del> public $name = 'MyPlugin';
<del>
<del>/**
<del> * uses property
<del> *
<del> * @var array
<del> */
<del> public $uses = array();
<del>
<del>/**
<del> * index method
<del> *
<del> * @return void
<del> */
<del> public function index() {
<del> return true;
<del> }
<del>
<del>/**
<del> * add method
<del> *
<del> * @return void
<del> */
<del> public function add() {
<del> return true;
<del> }
<del>
<del>/**
<del> * admin_add method
<del> *
<del> * @param mixed $id
<del> * @return void
<del> */
<del> public function admin_add($id = null) {
<del> return $id;
<del> }
<del>
<del>}
<del>
<del>/**
<del> * SomePagesController class
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class SomePagesController extends AppController {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'SomePages'
<del> */
<del> public $name = 'SomePages';
<del>
<del>/**
<del> * uses property
<del> *
<del> * @var array
<del> */
<del> public $uses = array();
<del>
<del>/**
<del> * display method
<del> *
<del> * @param string $page
<del> * @return void
<del> */
<del> public function display($page = null) {
<del> return $page;
<del> }
<del>
<del>/**
<del> * index method
<del> *
<del> * @return void
<del> */
<del> public function index() {
<del> return true;
<del> }
<del>
<del>/**
<del> * Test method for returning responses.
<del> *
<del> * @return CakeResponse
<del> */
<del> public function responseGenerator() {
<del> return new CakeResponse(array('body' => 'new response'));
<del> }
<del>
<del>/**
<del> * Test file sending
<del> *
<del> * @return CakeResponse
<del> */
<del> public function sendfile() {
<del> $this->response->file(CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS . 'css' . DS . 'test_asset.css');
<del> return $this->response;
<del> }
<del>
<del>}
<del>
<del>/**
<del> * OtherPagesController class
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class OtherPagesController extends MyPluginAppController {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'OtherPages'
<del> */
<del> public $name = 'OtherPages';
<del>
<del>/**
<del> * uses property
<del> *
<del> * @var array
<del> */
<del> public $uses = array();
<del>
<del>/**
<del> * display method
<del> *
<del> * @param string $page
<del> * @return void
<del> */
<del> public function display($page = null) {
<del> return $page;
<del> }
<del>
<del>/**
<del> * index method
<del> *
<del> * @return void
<del> */
<del> public function index() {
<del> return true;
<del> }
<del>
<del>}
<del>
<del>/**
<del> * TestDispatchPagesController class
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class TestDispatchPagesController extends AppController {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'TestDispatchPages'
<del> */
<del> public $name = 'TestDispatchPages';
<del>
<del>/**
<del> * uses property
<del> *
<del> * @var array
<del> */
<del> public $uses = array();
<del>
<del>/**
<del> * admin_index method
<del> *
<del> * @return void
<del> */
<del> public function admin_index() {
<del> return true;
<del> }
<del>
<del>/**
<del> * camelCased method
<del> *
<del> * @return void
<del> */
<del> public function camelCased() {
<del> return true;
<del> }
<del>
<del>}
<del>
<del>/**
<del> * ArticlesTestAppController class
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class ArticlesTestAppController extends AppController {
<del>}
<del>
<del>/**
<del> * ArticlesTestController class
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class ArticlesTestController extends ArticlesTestAppController {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ArticlesTest'
<del> */
<del> public $name = 'ArticlesTest';
<del>
<del>/**
<del> * uses property
<del> *
<del> * @var array
<del> */
<del> public $uses = array();
<del>
<del>/**
<del> * admin_index method
<del> *
<del> * @return void
<del> */
<del> public function admin_index() {
<del> return true;
<del> }
<del>
<del>/**
<del> * fake index method.
<del> *
<del> * @return void
<del> */
<del> public function index() {
<del> return true;
<del> }
<del>
<del>}
<del>
<del>/**
<del> * SomePostsController class
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class SomePostsController extends AppController {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'SomePosts'
<del> */
<del> public $name = 'SomePosts';
<del>
<del>/**
<del> * uses property
<del> *
<del> * @var array
<del> */
<del> public $uses = array();
<del>
<del>/**
<del> * autoRender property
<del> *
<del> * @var bool false
<del> */
<del> public $autoRender = false;
<del>
<del>/**
<del> * beforeFilter method
<del> *
<del> * @return void
<del> */
<del> public function beforeFilter() {
<del> if ($this->params['action'] === 'index') {
<del> $this->params['action'] = 'view';
<del> } else {
<del> $this->params['action'] = 'change';
<del> }
<del> $this->params['pass'] = array('changed');
<del> }
<del>
<del>/**
<del> * index method
<del> *
<del> * @return void
<del> */
<del> public function index() {
<del> return true;
<del> }
<del>
<del>/**
<del> * change method
<del> *
<del> * @return void
<del> */
<del> public function change() {
<del> return true;
<del> }
<del>
<del>}
<del>
<del>/**
<del> * TestCachedPagesController class
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class TestCachedPagesController extends Controller {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'TestCachedPages'
<del> */
<del> public $name = 'TestCachedPages';
<del>
<del>/**
<del> * uses property
<del> *
<del> * @var array
<del> */
<del> public $uses = array();
<del>
<del>/**
<del> * helpers property
<del> *
<del> * @var array
<del> */
<del> public $helpers = array('Cache', 'Html');
<del>
<del>/**
<del> * cacheAction property
<del> *
<del> * @var array
<del> */
<del> public $cacheAction = array(
<del> 'index' => '+2 sec',
<del> 'test_nocache_tags' => '+2 sec',
<del> 'view' => '+2 sec'
<del> );
<del>
<del>/**
<del> * Mock out the response object so it doesn't send headers.
<del> *
<del> * @var string
<del> */
<del> protected $_responseClass = 'DispatcherMockCakeResponse';
<del>
<del>/**
<del> * viewPath property
<del> *
<del> * @var string 'posts'
<del> */
<del> public $viewPath = 'Posts';
<del>
<del>/**
<del> * index method
<del> *
<del> * @return void
<del> */
<del> public function index() {
<del> $this->render();
<del> }
<del>
<del>/**
<del> * test_nocache_tags method
<del> *
<del> * @return void
<del> */
<del> public function test_nocache_tags() {
<del> $this->render();
<del> }
<del>
<del>/**
<del> * view method
<del> *
<del> * @return void
<del> */
<del> public function view($id = null) {
<del> $this->render('index');
<del> }
<del>
<del>/**
<del> * test cached forms / tests view object being registered
<del> *
<del> * @return void
<del> */
<del> public function cache_form() {
<del> $this->cacheAction = 10;
<del> $this->helpers[] = 'Form';
<del> }
<del>
<del>/**
<del> * Test cached views with themes.
<del> */
<del> public function themed() {
<del> $this->cacheAction = 10;
<del> $this->viewClass = 'Theme';
<del> $this->theme = 'TestTheme';
<del> }
<del>
<del>}
<del>
<del>/**
<del> * TimesheetsController class
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class TimesheetsController extends Controller {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Timesheets'
<del> */
<del> public $name = 'Timesheets';
<del>
<del>/**
<del> * uses property
<del> *
<del> * @var array
<del> */
<del> public $uses = array();
<del>
<del>/**
<del> * index method
<del> *
<del> * @return void
<del> */
<del> public function index() {
<del> return true;
<del> }
<del>
<del>}
<del>
<del>/**
<del> * DispatcherTest class
<del> *
<del> * @package Cake.Test.Case.Routing
<del> */
<del>class DispatcherTest extends CakeTestCase {
<del>
<del>/**
<del> * setUp method
<del> *
<del> * @return void
<del> */
<del> public function setUp() {
<del> $this->_get = $_GET;
<del> $_GET = array();
<del> $this->_post = $_POST;
<del> $this->_files = $_FILES;
<del> $this->_server = $_SERVER;
<del>
<del> $this->_app = Configure::read('App');
<del> Configure::write('App.base', false);
<del> Configure::write('App.baseUrl', false);
<del> Configure::write('App.dir', 'app');
<del> Configure::write('App.webroot', 'webroot');
<del>
<del> $this->_cache = Configure::read('Cache');
<del> Configure::write('Cache.disable', true);
<del>
<del> $this->_debug = Configure::read('debug');
<del>
<del> App::build();
<del> App::objects('plugin', null, false);
<del> }
<del>
<del>/**
<del> * tearDown method
<del> *
<del> * @return void
<del> */
<del> public function tearDown() {
<del> $_GET = $this->_get;
<del> $_POST = $this->_post;
<del> $_FILES = $this->_files;
<del> $_SERVER = $this->_server;
<del> App::build();
<del> CakePlugin::unload();
<del> Configure::write('App', $this->_app);
<del> Configure::write('Cache', $this->_cache);
<del> Configure::write('debug', $this->_debug);
<del> Configure::write('Dispatcher.filters', array());
<del> }
<del>
<del>/**
<del> * testParseParamsWithoutZerosAndEmptyPost method
<del> *
<del> * @return void
<del> */
<del> public function testParseParamsWithoutZerosAndEmptyPost() {
<del> $Dispatcher = new Dispatcher();
<del> $request = new CakeRequest("/testcontroller/testaction/params1/params2/params3");
<del> $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $request));
<del> $Dispatcher->parseParams($event);
<del> $this->assertSame($request['controller'], 'testcontroller');
<del> $this->assertSame($request['action'], 'testaction');
<del> $this->assertSame($request['pass'][0], 'params1');
<del> $this->assertSame($request['pass'][1], 'params2');
<del> $this->assertSame($request['pass'][2], 'params3');
<del> $this->assertFalse(!empty($request['form']));
<del> }
<del>
<del>/**
<del> * testParseParamsReturnsPostedData method
<del> *
<del> * @return void
<del> */
<del> public function testParseParamsReturnsPostedData() {
<del> $_POST['testdata'] = "My Posted Content";
<del> $Dispatcher = new Dispatcher();
<del> $request = new CakeRequest("/");
<del> $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $request));
<del> $Dispatcher->parseParams($event);
<del> $Dispatcher->parseParams($event);
<del> $this->assertEquals("My Posted Content", $request['data']['testdata']);
<del> }
<del>
<del>/**
<del> * testParseParamsWithSingleZero method
<del> *
<del> * @return void
<del> */
<del> public function testParseParamsWithSingleZero() {
<del> $Dispatcher = new Dispatcher();
<del> $test = new CakeRequest("/testcontroller/testaction/1/0/23");
<del> $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $test));
<del> $Dispatcher->parseParams($event);
<del>
<del> $this->assertSame($test['controller'], 'testcontroller');
<del> $this->assertSame($test['action'], 'testaction');
<del> $this->assertSame($test['pass'][0], '1');
<del> $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][1]);
<del> $this->assertSame($test['pass'][2], '23');
<del> }
<del>
<del>/**
<del> * testParseParamsWithManySingleZeros method
<del> *
<del> * @return void
<del> */
<del> public function testParseParamsWithManySingleZeros() {
<del> $Dispatcher = new Dispatcher();
<del> $test = new CakeRequest("/testcontroller/testaction/0/0/0/0/0/0");
<del> $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $test));
<del> $Dispatcher->parseParams($event);
<del>
<del> $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][0]);
<del> $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][1]);
<del> $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][2]);
<del> $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][3]);
<del> $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][4]);
<del> $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][5]);
<del> }
<del>
<del>/**
<del> * testParseParamsWithManyZerosInEachSectionOfUrl method
<del> *
<del> * @return void
<del> */
<del> public function testParseParamsWithManyZerosInEachSectionOfUrl() {
<del> $Dispatcher = new Dispatcher();
<del> $test = new CakeRequest("/testcontroller/testaction/000/0000/00000/000000/000000/0000000");
<del> $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $test));
<del> $Dispatcher->parseParams($event);
<del>
<del> $this->assertRegExp('/\\A(?:000)\\z/', $test['pass'][0]);
<del> $this->assertRegExp('/\\A(?:0000)\\z/', $test['pass'][1]);
<del> $this->assertRegExp('/\\A(?:00000)\\z/', $test['pass'][2]);
<del> $this->assertRegExp('/\\A(?:000000)\\z/', $test['pass'][3]);
<del> $this->assertRegExp('/\\A(?:000000)\\z/', $test['pass'][4]);
<del> $this->assertRegExp('/\\A(?:0000000)\\z/', $test['pass'][5]);
<del> }
<del>
<del>/**
<del> * testParseParamsWithMixedOneToManyZerosInEachSectionOfUrl method
<del> *
<del> * @return void
<del> */
<del> public function testParseParamsWithMixedOneToManyZerosInEachSectionOfUrl() {
<del> $Dispatcher = new Dispatcher();
<del> $test = new CakeRequest("/testcontroller/testaction/01/0403/04010/000002/000030/0000400");
<del> $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $test));
<del> $Dispatcher->parseParams($event);
<del>
<del> $this->assertRegExp('/\\A(?:01)\\z/', $test['pass'][0]);
<del> $this->assertRegExp('/\\A(?:0403)\\z/', $test['pass'][1]);
<del> $this->assertRegExp('/\\A(?:04010)\\z/', $test['pass'][2]);
<del> $this->assertRegExp('/\\A(?:000002)\\z/', $test['pass'][3]);
<del> $this->assertRegExp('/\\A(?:000030)\\z/', $test['pass'][4]);
<del> $this->assertRegExp('/\\A(?:0000400)\\z/', $test['pass'][5]);
<del> }
<del>
<del>/**
<del> * testQueryStringOnRoot method
<del> *
<del> * @return void
<del> */
<del> public function testQueryStringOnRoot() {
<del> Router::reload();
<del> Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
<del> Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
<del> Router::connect('/:controller/:action/*');
<del>
<del> $_GET = array('coffee' => 'life', 'sleep' => 'sissies');
<del> $Dispatcher = new Dispatcher();
<del> $request = new CakeRequest('posts/home/?coffee=life&sleep=sissies');
<del> $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $request));
<del> $Dispatcher->parseParams($event);
<del>
<del> $this->assertRegExp('/posts/', $request['controller']);
<del> $this->assertRegExp('/home/', $request['action']);
<del> $this->assertTrue(isset($request['url']['sleep']));
<del> $this->assertTrue(isset($request['url']['coffee']));
<del>
<del> $Dispatcher = new Dispatcher();
<del> $request = new CakeRequest('/?coffee=life&sleep=sissy');
<del>
<del> $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $request));
<del> $Dispatcher->parseParams($event);
<del> $this->assertRegExp('/pages/', $request['controller']);
<del> $this->assertRegExp('/display/', $request['action']);
<del> $this->assertTrue(isset($request['url']['sleep']));
<del> $this->assertTrue(isset($request['url']['coffee']));
<del> $this->assertEquals('life', $request['url']['coffee']);
<del> }
<del>
<del>/**
<del> * testMissingController method
<del> *
<del> * @expectedException MissingControllerException
<del> * @expectedExceptionMessage Controller class SomeControllerController could not be found.
<del> * @return void
<del> */
<del> public function testMissingController() {
<del> Router::connect('/:controller/:action/*');
<del>
<del> $Dispatcher = new TestDispatcher();
<del> Configure::write('App.baseUrl', '/index.php');
<del> $url = new CakeRequest('some_controller/home/param:value/param2:value2');
<del> $response = $this->getMock('CakeResponse');
<del>
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> }
<del>
<del>/**
<del> * testMissingControllerInterface method
<del> *
<del> * @expectedException MissingControllerException
<del> * @expectedExceptionMessage Controller class DispatcherTestInterfaceController could not be found.
<del> * @return void
<del> */
<del> public function testMissingControllerInterface() {
<del> Router::connect('/:controller/:action/*');
<del>
<del> $Dispatcher = new TestDispatcher();
<del> Configure::write('App.baseUrl', '/index.php');
<del> $url = new CakeRequest('dispatcher_test_interface/index');
<del> $response = $this->getMock('CakeResponse');
<del>
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> }
<del>
<del>/**
<del> * testMissingControllerInterface method
<del> *
<del> * @expectedException MissingControllerException
<del> * @expectedExceptionMessage Controller class DispatcherTestAbstractController could not be found.
<del> * @return void
<del> */
<del> public function testMissingControllerAbstract() {
<del> Router::connect('/:controller/:action/*');
<del>
<del> $Dispatcher = new TestDispatcher();
<del> Configure::write('App.baseUrl', '/index.php');
<del> $url = new CakeRequest('dispatcher_test_abstract/index');
<del> $response = $this->getMock('CakeResponse');
<del>
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> }
<del>
<del>/**
<del> * testDispatch method
<del> *
<del> * @return void
<del> */
<del> public function testDispatchBasic() {
<del> App::build(array(
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<del> ));
<del> $Dispatcher = new TestDispatcher();
<del> Configure::write('App.baseUrl', '/index.php');
<del> $url = new CakeRequest('pages/home/param:value/param2:value2');
<del> $response = $this->getMock('CakeResponse');
<del>
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> $expected = 'Pages';
<del> $this->assertEquals($expected, $Dispatcher->controller->name);
<del>
<del> $expected = array('0' => 'home', 'param' => 'value', 'param2' => 'value2');
<del> $this->assertSame($expected, $Dispatcher->controller->passedArgs);
<del>
<del> Configure::write('App.baseUrl', '/pages/index.php');
<del>
<del> $url = new CakeRequest('pages/home');
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del>
<del> $expected = 'Pages';
<del> $this->assertEquals($expected, $Dispatcher->controller->name);
<del>
<del> $url = new CakeRequest('pages/home/');
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> $this->assertNull($Dispatcher->controller->plugin);
<del>
<del> $expected = 'Pages';
<del> $this->assertEquals($expected, $Dispatcher->controller->name);
<del>
<del> unset($Dispatcher);
<del>
<del> require CAKE . 'Config' . DS . 'routes.php';
<del> $Dispatcher = new TestDispatcher();
<del> Configure::write('App.baseUrl', '/timesheets/index.php');
<del>
<del> $url = new CakeRequest('timesheets');
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del>
<del> $expected = 'Timesheets';
<del> $this->assertEquals($expected, $Dispatcher->controller->name);
<del>
<del> $url = new CakeRequest('timesheets/');
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del>
<del> $this->assertEquals('Timesheets', $Dispatcher->controller->name);
<del> $this->assertEquals('/timesheets/index.php', $url->base);
<del>
<del> $url = new CakeRequest('test_dispatch_pages/camelCased');
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> $this->assertEquals('TestDispatchPages', $Dispatcher->controller->name);
<del>
<del> $url = new CakeRequest('test_dispatch_pages/camelCased/something. .');
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> $this->assertEquals('something. .', $Dispatcher->controller->params['pass'][0], 'Period was chopped off. %s');
<del> }
<del>
<del>/**
<del> * Test that Dispatcher handles actions that return response objects.
<del> *
<del> * @return void
<del> */
<del> public function testDispatchActionReturnsResponse() {
<del> Router::connect('/:controller/:action');
<del> $Dispatcher = new Dispatcher();
<del> $request = new CakeRequest('some_pages/responseGenerator');
<del> $response = $this->getMock('CakeResponse', array('_sendHeader'));
<del>
<del> ob_start();
<del> $Dispatcher->dispatch($request, $response);
<del> $result = ob_get_clean();
<del>
<del> $this->assertEquals('new response', $result);
<del> }
<del>
<del>/**
<del> * testDispatchActionSendsFile
<del> *
<del> * @return void
<del> */
<del> public function testDispatchActionSendsFile() {
<del> Router::connect('/:controller/:action');
<del> $Dispatcher = new Dispatcher();
<del> $request = new CakeRequest('some_pages/sendfile');
<del> $response = $this->getMock('CakeResponse', array(
<del> 'header',
<del> 'type',
<del> 'download',
<del> '_sendHeader',
<del> '_setContentType',
<del> '_isActive',
<del> '_clearBuffer',
<del> '_flushBuffer'
<del> ));
<del>
<del> $response->expects($this->never())
<del> ->method('body');
<del>
<del> $response->expects($this->exactly(1))
<del> ->method('_isActive')
<del> ->will($this->returnValue(true));
<del>
<del> ob_start();
<del> $Dispatcher->dispatch($request, $response);
<del> $result = ob_get_clean();
<del>
<del> $this->assertEquals("/* this is the test asset css file */\n", $result);
<del> }
<del>
<del>/**
<del> * testAdminDispatch method
<del> *
<del> * @return void
<del> */
<del> public function testAdminDispatch() {
<del> $_POST = array();
<del> $Dispatcher = new TestDispatcher();
<del> Configure::write('Routing.prefixes', array('admin'));
<del> Configure::write('App.baseUrl','/cake/repo/branches/1.2.x.x/index.php');
<del> $url = new CakeRequest('admin/test_dispatch_pages/index/param:value/param2:value2');
<del> $response = $this->getMock('CakeResponse');
<del>
<del> Router::reload();
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del>
<del> $this->assertEquals('TestDispatchPages', $Dispatcher->controller->name);
<del>
<del> $this->assertSame($Dispatcher->controller->passedArgs, array('param' => 'value', 'param2' => 'value2'));
<del> $this->assertTrue($Dispatcher->controller->params['admin']);
<del>
<del> $expected = '/cake/repo/branches/1.2.x.x/index.php/admin/test_dispatch_pages/index/param:value/param2:value2';
<del> $this->assertSame($expected, $Dispatcher->controller->here);
<del>
<del> $expected = '/cake/repo/branches/1.2.x.x/index.php';
<del> $this->assertSame($expected, $Dispatcher->controller->base);
<del> }
<del>
<del>/**
<del> * testPluginDispatch method
<del> *
<del> * @return void
<del> */
<del> public function testPluginDispatch() {
<del> $_POST = array();
<del>
<del> Router::reload();
<del> $Dispatcher = new TestDispatcher();
<del> Router::connect(
<del> '/my_plugin/:controller/*',
<del> array('plugin' => 'my_plugin', 'controller' => 'pages', 'action' => 'display')
<del> );
<del>
<del> $url = new CakeRequest('my_plugin/some_pages/home/param:value/param2:value2');
<del> $response = $this->getMock('CakeResponse');
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del>
<del> $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $url));
<del> $Dispatcher->parseParams($event);
<del> $expected = array(
<del> 'pass' => array('home'),
<del> 'named' => array('param' => 'value', 'param2' => 'value2'), 'plugin' => 'my_plugin',
<del> 'controller' => 'some_pages', 'action' => 'display'
<del> );
<del> foreach ($expected as $key => $value) {
<del> $this->assertEquals($value, $url[$key], 'Value mismatch ' . $key . ' %');
<del> }
<del>
<del> $this->assertSame($Dispatcher->controller->plugin, 'MyPlugin');
<del> $this->assertSame($Dispatcher->controller->name, 'SomePages');
<del> $this->assertSame($Dispatcher->controller->params['controller'], 'some_pages');
<del> $this->assertSame($Dispatcher->controller->passedArgs, array('0' => 'home', 'param' => 'value', 'param2' => 'value2'));
<del> }
<del>
<del>/**
<del> * testAutomaticPluginDispatch method
<del> *
<del> * @return void
<del> */
<del> public function testAutomaticPluginDispatch() {
<del> $_POST = array();
<del> $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php';
<del>
<del> Router::reload();
<del> $Dispatcher = new TestDispatcher();
<del> Router::connect(
<del> '/my_plugin/:controller/:action/*',
<del> array('plugin' => 'my_plugin', 'controller' => 'pages', 'action' => 'display')
<del> );
<del>
<del> $Dispatcher->base = false;
<del>
<del> $url = new CakeRequest('my_plugin/other_pages/index/param:value/param2:value2');
<del> $response = $this->getMock('CakeResponse');
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del>
<del> $this->assertSame($Dispatcher->controller->plugin, 'MyPlugin');
<del> $this->assertSame($Dispatcher->controller->name, 'OtherPages');
<del> $this->assertSame($Dispatcher->controller->action, 'index');
<del> $this->assertSame($Dispatcher->controller->passedArgs, array('param' => 'value', 'param2' => 'value2'));
<del>
<del> $expected = '/cake/repo/branches/1.2.x.x/my_plugin/other_pages/index/param:value/param2:value2';
<del> $this->assertSame($expected, $url->here);
<del>
<del> $expected = '/cake/repo/branches/1.2.x.x';
<del> $this->assertSame($expected, $url->base);
<del> }
<del>
<del>/**
<del> * testAutomaticPluginControllerDispatch method
<del> *
<del> * @return void
<del> */
<del> public function testAutomaticPluginControllerDispatch() {
<del> $plugins = App::objects('plugin');
<del> $plugins[] = 'MyPlugin';
<del> $plugins[] = 'ArticlesTest';
<del>
<del> CakePlugin::load('MyPlugin', array('path' => '/fake/path'));
<del>
<del> Router::reload();
<del> $Dispatcher = new TestDispatcher();
<del> $Dispatcher->base = false;
<del>
<del> $url = new CakeRequest('my_plugin/my_plugin/add/param:value/param2:value2');
<del> $response = $this->getMock('CakeResponse');
<del>
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del>
<del> $this->assertSame($Dispatcher->controller->plugin, 'MyPlugin');
<del> $this->assertSame($Dispatcher->controller->name, 'MyPlugin');
<del> $this->assertSame($Dispatcher->controller->action, 'add');
<del> $this->assertEquals(array('param' => 'value', 'param2' => 'value2'), $Dispatcher->controller->params['named']);
<del>
<del> Router::reload();
<del> require CAKE . 'Config' . DS . 'routes.php';
<del> $Dispatcher = new TestDispatcher();
<del> $Dispatcher->base = false;
<del>
<del> // Simulates the Route for a real plugin, installed in APP/plugins
<del> Router::connect('/my_plugin/:controller/:action/*', array('plugin' => 'my_plugin'));
<del>
<del> $plugin = 'MyPlugin';
<del> $pluginUrl = Inflector::underscore($plugin);
<del>
<del> $url = new CakeRequest($pluginUrl);
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> $this->assertSame($Dispatcher->controller->plugin, 'MyPlugin');
<del> $this->assertSame($Dispatcher->controller->name, 'MyPlugin');
<del> $this->assertSame($Dispatcher->controller->action, 'index');
<del>
<del> $expected = $pluginUrl;
<del> $this->assertEquals($expected, $Dispatcher->controller->params['controller']);
<del>
<del> Configure::write('Routing.prefixes', array('admin'));
<del>
<del> Router::reload();
<del> require CAKE . 'Config' . DS . 'routes.php';
<del> $Dispatcher = new TestDispatcher();
<del>
<del> $url = new CakeRequest('admin/my_plugin/my_plugin/add/5/param:value/param2:value2');
<del> $response = $this->getMock('CakeResponse');
<del>
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del>
<del> $this->assertEquals('my_plugin', $Dispatcher->controller->params['plugin']);
<del> $this->assertEquals('my_plugin', $Dispatcher->controller->params['controller']);
<del> $this->assertEquals('admin_add', $Dispatcher->controller->params['action']);
<del> $this->assertEquals(array(5), $Dispatcher->controller->params['pass']);
<del> $this->assertEquals(array('param' => 'value', 'param2' => 'value2'), $Dispatcher->controller->params['named']);
<del> $this->assertSame($Dispatcher->controller->plugin, 'MyPlugin');
<del> $this->assertSame($Dispatcher->controller->name, 'MyPlugin');
<del> $this->assertSame($Dispatcher->controller->action, 'admin_add');
<del>
<del> $expected = array(0 => 5, 'param' => 'value', 'param2' => 'value2');
<del> $this->assertEquals($expected, $Dispatcher->controller->passedArgs);
<del>
<del> Configure::write('Routing.prefixes', array('admin'));
<del> CakePlugin::load('ArticlesTest', array('path' => '/fake/path'));
<del> Router::reload();
<del> require CAKE . 'Config' . DS . 'routes.php';
<del>
<del> $Dispatcher = new TestDispatcher();
<del>
<del> $Dispatcher->dispatch(new CakeRequest('admin/articles_test'), $response, array('return' => 1));
<del> $this->assertSame($Dispatcher->controller->plugin, 'ArticlesTest');
<del> $this->assertSame($Dispatcher->controller->name, 'ArticlesTest');
<del> $this->assertSame($Dispatcher->controller->action, 'admin_index');
<del>
<del> $expected = array(
<del> 'pass' => array(),
<del> 'named' => array(),
<del> 'controller' => 'articles_test',
<del> 'plugin' => 'articles_test',
<del> 'action' => 'admin_index',
<del> 'prefix' => 'admin',
<del> 'admin' => true,
<del> 'return' => 1
<del> );
<del> foreach ($expected as $key => $value) {
<del> $this->assertEquals($expected[$key], $Dispatcher->controller->request[$key], 'Value mismatch ' . $key);
<del> }
<del> }
<del>
<del>/**
<del> * test Plugin dispatching without controller name and using
<del> * plugin short form instead.
<del> *
<del> * @return void
<del> */
<del> public function testAutomaticPluginDispatchWithShortAccess() {
<del> CakePlugin::load('MyPlugin', array('path' => '/fake/path'));
<del> Router::reload();
<del>
<del> $Dispatcher = new TestDispatcher();
<del> $Dispatcher->base = false;
<del>
<del> $url = new CakeRequest('my_plugin/');
<del> $response = $this->getMock('CakeResponse');
<del>
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> $this->assertEquals('my_plugin', $Dispatcher->controller->params['controller']);
<del> $this->assertEquals('my_plugin', $Dispatcher->controller->params['plugin']);
<del> $this->assertEquals('index', $Dispatcher->controller->params['action']);
<del> $this->assertFalse(isset($Dispatcher->controller->params['pass'][0]));
<del> }
<del>
<del>/**
<del> * test plugin shortcut urls with controllers that need to be loaded,
<del> * the above test uses a controller that has already been included.
<del> *
<del> * @return void
<del> */
<del> public function testPluginShortCutUrlsWithControllerThatNeedsToBeLoaded() {
<del> $loaded = class_exists('TestPluginController', false);
<del> $this->skipIf($loaded, 'TestPluginController already loaded.');
<del>
<del> Router::reload();
<del> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<del> ), App::RESET);
<del> CakePlugin::load(array('TestPlugin', 'TestPluginTwo'));
<del>
<del> $Dispatcher = new TestDispatcher();
<del> $Dispatcher->base = false;
<del>
<del> $url = new CakeRequest('test_plugin/');
<del> $response = $this->getMock('CakeResponse');
<del>
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> $this->assertEquals('test_plugin', $Dispatcher->controller->params['controller']);
<del> $this->assertEquals('test_plugin', $Dispatcher->controller->params['plugin']);
<del> $this->assertEquals('index', $Dispatcher->controller->params['action']);
<del> $this->assertFalse(isset($Dispatcher->controller->params['pass'][0]));
<del>
<del> $url = new CakeRequest('/test_plugin/tests/index');
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> $this->assertEquals('tests', $Dispatcher->controller->params['controller']);
<del> $this->assertEquals('test_plugin', $Dispatcher->controller->params['plugin']);
<del> $this->assertEquals('index', $Dispatcher->controller->params['action']);
<del> $this->assertFalse(isset($Dispatcher->controller->params['pass'][0]));
<del>
<del> $url = new CakeRequest('/test_plugin/tests/index/some_param');
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> $this->assertEquals('tests', $Dispatcher->controller->params['controller']);
<del> $this->assertEquals('test_plugin', $Dispatcher->controller->params['plugin']);
<del> $this->assertEquals('index', $Dispatcher->controller->params['action']);
<del> $this->assertEquals('some_param', $Dispatcher->controller->params['pass'][0]);
<del>
<del> App::build();
<del> }
<del>
<del>/**
<del> * testAutomaticPluginControllerMissingActionDispatch method
<del> *
<del> * @expectedException MissingActionException
<del> * @expectedExceptionMessage Action MyPluginController::not_here() could not be found.
<del> * @return void
<del> */
<del> public function testAutomaticPluginControllerMissingActionDispatch() {
<del> Router::reload();
<del> $Dispatcher = new TestDispatcher();
<del>
<del> $url = new CakeRequest('my_plugin/not_here/param:value/param2:value2');
<del> $response = $this->getMock('CakeResponse');
<del>
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> }
<del>
<del>/**
<del> * testAutomaticPluginControllerMissingActionDispatch method
<del> *
<del> * @expectedException MissingActionException
<del> * @expectedExceptionMessage Action MyPluginController::param:value() could not be found.
<del> * @return void
<del> */
<del>
<del> public function testAutomaticPluginControllerIndexMissingAction() {
<del> Router::reload();
<del> $Dispatcher = new TestDispatcher();
<del>
<del> $url = new CakeRequest('my_plugin/param:value/param2:value2');
<del> $response = $this->getMock('CakeResponse');
<del>
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> }
<del>
<del>/**
<del> * Test dispatching into the TestPlugin in the test_app
<del> *
<del> * @return void
<del> */
<del> public function testTestPluginDispatch() {
<del> $Dispatcher = new TestDispatcher();
<del> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<del> ), App::RESET);
<del> CakePlugin::load(array('TestPlugin', 'TestPluginTwo'));
<del> Router::reload();
<del> Router::parse('/');
<del>
<del> $url = new CakeRequest('/test_plugin/tests/index');
<del> $response = $this->getMock('CakeResponse');
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> $this->assertTrue(class_exists('TestsController'));
<del> $this->assertTrue(class_exists('TestPluginAppController'));
<del> $this->assertTrue(class_exists('PluginsComponent'));
<del>
<del> $this->assertEquals('tests', $Dispatcher->controller->params['controller']);
<del> $this->assertEquals('test_plugin', $Dispatcher->controller->params['plugin']);
<del> $this->assertEquals('index', $Dispatcher->controller->params['action']);
<del>
<del> App::build();
<del> }
<del>
<del>/**
<del> * Tests that it is possible to attach filter classes to the dispatch cycle
<del> *
<del> * @return void
<del> */
<del> public function testDispatcherFilterSubscriber() {
<del> App::build(array(
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS),
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<del> ), App::RESET);
<del>
<del> CakePlugin::load('TestPlugin');
<del> Configure::write('Dispatcher.filters', array(
<del> array('callable' => 'TestPlugin.TestDispatcherFilter')
<del> ));
<del> $dispatcher = new TestDispatcher();
<del> $request = new CakeRequest('/');
<del> $request->params['altered'] = false;
<del> $response = $this->getMock('CakeResponse', array('send'));
<del>
<del> $dispatcher->dispatch($request, $response);
<del> $this->assertTrue($request->params['altered']);
<del> $this->assertEquals(304, $response->statusCode());
<del>
<del> Configure::write('Dispatcher.filters', array(
<del> 'TestPlugin.Test2DispatcherFilter',
<del> 'TestPlugin.TestDispatcherFilter'
<del> ));
<del> $dispatcher = new TestDispatcher();
<del> $request = new CakeRequest('/');
<del> $request->params['altered'] = false;
<del> $response = $this->getMock('CakeResponse', array('send'));
<del>
<del> $dispatcher->dispatch($request, $response);
<del> $this->assertFalse($request->params['altered']);
<del> $this->assertEquals(500, $response->statusCode());
<del> $this->assertNull($dispatcher->controller);
<del> }
<del>
<del>/**
<del> * Tests that attaching an inexistent class as filter will throw an exception
<del> *
<del> * @expectedException MissingDispatcherFilterException
<del> * @return void
<del> */
<del> public function testDispatcherFilterSuscriberMissing() {
<del> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<del> ), App::RESET);
<del>
<del> CakePlugin::load('TestPlugin');
<del> Configure::write('Dispatcher.filters', array(
<del> array('callable' => 'TestPlugin.NotAFilter')
<del> ));
<del> $dispatcher = new TestDispatcher();
<del> $request = new CakeRequest('/');
<del> $response = $this->getMock('CakeResponse', array('send'));
<del> $dispatcher->dispatch($request, $response);
<del> }
<del>
<del>/**
<del> * Tests it is possible to attach single callables as filters
<del> *
<del> * @return void
<del> */
<del> public function testDispatcherFilterCallable() {
<del> App::build(array(
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<del> ), App::RESET);
<del>
<del> $dispatcher = new TestDispatcher();
<del> Configure::write('Dispatcher.filters', array(
<del> array('callable' => array($dispatcher, 'filterTest'), 'on' => 'before')
<del> ));
<del>
<del> $request = new CakeRequest('/');
<del> $response = $this->getMock('CakeResponse', array('send'));
<del> $dispatcher->dispatch($request, $response);
<del> $this->assertEquals('Dispatcher.beforeDispatch', $request->params['eventName']);
<del>
<del> $dispatcher = new TestDispatcher();
<del> Configure::write('Dispatcher.filters', array(
<del> array('callable' => array($dispatcher, 'filterTest'), 'on' => 'after')
<del> ));
<del>
<del> $request = new CakeRequest('/');
<del> $response = $this->getMock('CakeResponse', array('send'));
<del> $dispatcher->dispatch($request, $response);
<del> $this->assertEquals('Dispatcher.afterDispatch', $request->params['eventName']);
<del>
<del> // Test that it is possible to skip the route connection process
<del> $dispatcher = new TestDispatcher();
<del> Configure::write('Dispatcher.filters', array(
<del> array('callable' => array($dispatcher, 'filterTest2'), 'on' => 'before', 'priority' => 1)
<del> ));
<del>
<del> $request = new CakeRequest('/');
<del> $response = $this->getMock('CakeResponse', array('send'));
<del> $dispatcher->dispatch($request, $response);
<del> $this->assertEmpty($dispatcher->controller);
<del> $expected = array('controller' => null, 'action' => null, 'plugin' => null, 'named' => array(), 'pass' => array());
<del> $this->assertEquals($expected, $request->params);
<del>
<del> $dispatcher = new TestDispatcher();
<del> Configure::write('Dispatcher.filters', array(
<del> array('callable' => array($dispatcher, 'filterTest2'), 'on' => 'before', 'priority' => 1)
<del> ));
<del>
<del> $request = new CakeRequest('/');
<del> $request->params['return'] = true;
<del> $response = $this->getMock('CakeResponse', array('send'));
<del> $response->body('this is a body');
<del> $result = $dispatcher->dispatch($request, $response);
<del> $this->assertEquals('this is a body', $result);
<del>
<del> $request = new CakeRequest('/');
<del> $response = $this->getMock('CakeResponse', array('send'));
<del> $response->expects($this->once())->method('send');
<del> $response->body('this is a body');
<del> $result = $dispatcher->dispatch($request, $response);
<del> $this->assertNull($result);
<del> }
<del>
<del>/**
<del> * testChangingParamsFromBeforeFilter method
<del> *
<del> * @return void
<del> */
<del> public function testChangingParamsFromBeforeFilter() {
<del> $Dispatcher = new TestDispatcher();
<del> $response = $this->getMock('CakeResponse');
<del> $url = new CakeRequest('some_posts/index/param:value/param2:value2');
<del>
<del> try {
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del> $this->fail('No exception.');
<del> } catch (MissingActionException $e) {
<del> $this->assertEquals('Action SomePostsController::view() could not be found.', $e->getMessage());
<del> }
<del>
<del> $url = new CakeRequest('some_posts/something_else/param:value/param2:value2');
<del> $Dispatcher->dispatch($url, $response, array('return' => 1));
<del>
<del> $expected = 'SomePosts';
<del> $this->assertEquals($expected, $Dispatcher->controller->name);
<del>
<del> $expected = 'change';
<del> $this->assertEquals($expected, $Dispatcher->controller->action);
<del>
<del> $expected = array('changed');
<del> $this->assertSame($expected, $Dispatcher->controller->params['pass']);
<del> }
<del>
<del>/**
<del> * testStaticAssets method
<del> *
<del> * @return void
<del> */
<del> public function testAssets() {
<del> Router::reload();
<del>
<del> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
<del> 'Vendor' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS),
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<del> ));
<del> CakePlugin::load(array('TestPlugin', 'TestPluginTwo'));
<del> Configure::write('Dispatcher.filters', array('AssetDispatcher'));
<del>
<del> $Dispatcher = new TestDispatcher();
<del> $response = $this->getMock('CakeResponse', array('_sendHeader'));
<del>
<del> try {
<del> $Dispatcher->dispatch(new CakeRequest('theme/test_theme/../webroot/css/test_asset.css'), $response);
<del> $this->fail('No exception');
<del> } catch (MissingControllerException $e) {
<del> $this->assertEquals('Controller class ThemeController could not be found.', $e->getMessage());
<del> }
<del>
<del> try {
<del> $Dispatcher->dispatch(new CakeRequest('theme/test_theme/pdfs'), $response);
<del> $this->fail('No exception');
<del> } catch (MissingControllerException $e) {
<del> $this->assertEquals('Controller class ThemeController could not be found.', $e->getMessage());
<del> }
<del> }
<del>
<del>/**
<del> * Data provider for asset filter
<del> *
<del> * - theme assets.
<del> * - plugin assets.
<del> * - plugin assets in sub directories.
<del> * - unknown plugin assets.
<del> *
<del> * @return array
<del> */
<del> public static function assetProvider() {
<del> return array(
<del> array(
<del> 'theme/test_theme/flash/theme_test.swf',
<del> 'View/Themed/TestTheme/webroot/flash/theme_test.swf'
<del> ),
<del> array(
<del> 'theme/test_theme/pdfs/theme_test.pdf',
<del> 'View/Themed/TestTheme/webroot/pdfs/theme_test.pdf'
<del> ),
<del> array(
<del> 'theme/test_theme/img/test.jpg',
<del> 'View/Themed/TestTheme/webroot/img/test.jpg'
<del> ),
<del> array(
<del> 'theme/test_theme/css/test_asset.css',
<del> 'View/Themed/TestTheme/webroot/css/test_asset.css'
<del> ),
<del> array(
<del> 'theme/test_theme/js/theme.js',
<del> 'View/Themed/TestTheme/webroot/js/theme.js'
<del> ),
<del> array(
<del> 'theme/test_theme/js/one/theme_one.js',
<del> 'View/Themed/TestTheme/webroot/js/one/theme_one.js'
<del> ),
<del> array(
<del> 'theme/test_theme/space%20image.text',
<del> 'View/Themed/TestTheme/webroot/space image.text'
<del> ),
<del> array(
<del> 'test_plugin/root.js',
<del> 'Plugin/TestPlugin/webroot/root.js'
<del> ),
<del> array(
<del> 'test_plugin/flash/plugin_test.swf',
<del> 'Plugin/TestPlugin/webroot/flash/plugin_test.swf'
<del> ),
<del> array(
<del> 'test_plugin/pdfs/plugin_test.pdf',
<del> 'Plugin/TestPlugin/webroot/pdfs/plugin_test.pdf'
<del> ),
<del> array(
<del> 'test_plugin/js/test_plugin/test.js',
<del> 'Plugin/TestPlugin/webroot/js/test_plugin/test.js'
<del> ),
<del> array(
<del> 'test_plugin/css/test_plugin_asset.css',
<del> 'Plugin/TestPlugin/webroot/css/test_plugin_asset.css'
<del> ),
<del> array(
<del> 'test_plugin/img/cake.icon.gif',
<del> 'Plugin/TestPlugin/webroot/img/cake.icon.gif'
<del> ),
<del> array(
<del> 'plugin_js/js/plugin_js.js',
<del> 'Plugin/PluginJs/webroot/js/plugin_js.js'
<del> ),
<del> array(
<del> 'plugin_js/js/one/plugin_one.js',
<del> 'Plugin/PluginJs/webroot/js/one/plugin_one.js'
<del> ),
<del> array(
<del> 'test_plugin/css/unknown.extension',
<del> 'Plugin/TestPlugin/webroot/css/unknown.extension'
<del> ),
<del> array(
<del> 'test_plugin/css/theme_one.htc',
<del> 'Plugin/TestPlugin/webroot/css/theme_one.htc'
<del> ),
<del> );
<del> }
<del>
<del>/**
<del> * Test assets
<del> *
<del> * @dataProvider assetProvider
<del> * @outputBuffering enabled
<del> * @return void
<del> */
<del> public function testAsset($url, $file) {
<del> Router::reload();
<del>
<del> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
<del> 'Vendor' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS),
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
<del> ));
<del> CakePlugin::load(array('TestPlugin', 'PluginJs'));
<del> Configure::write('Dispatcher.filters', array('AssetDispatcher'));
<del>
<del> $Dispatcher = new TestDispatcher();
<del> $response = $this->getMock('CakeResponse', array('_sendHeader'));
<del>
<del> $Dispatcher->dispatch(new CakeRequest($url), $response);
<del> $result = ob_get_clean();
<del>
<del> $path = CAKE . 'Test' . DS . 'test_app' . DS . str_replace('/', DS, $file);
<del> $file = file_get_contents($path);
<del> $this->assertEquals($file, $result);
<del>
<del> $expected = filesize($path);
<del> $headers = $response->header();
<del> $this->assertEquals($expected, $headers['Content-Length']);
<del> }
<del>
<del>/**
<del> * test that missing asset processors trigger a 404 with no response body.
<del> *
<del> * @return void
<del> */
<del> public function testMissingAssetProcessor404() {
<del> $response = $this->getMock('CakeResponse', array('send'));
<del> $Dispatcher = new TestDispatcher();
<del> Configure::write('Asset.filter', array(
<del> 'js' => '',
<del> 'css' => null
<del> ));
<del> Configure::write('Dispatcher.filters', array('AssetDispatcher'));
<del>
<del> $request = new CakeRequest('ccss/cake.generic.css');
<del> $Dispatcher->dispatch($request, $response);
<del> $this->assertEquals('404', $response->statusCode());
<del> }
<del>
<del>/**
<del> * Data provider for cached actions.
<del> *
<del> * - Test simple views
<del> * - Test views with nocache tags
<del> * - Test requests with named + passed params.
<del> * - Test requests with query string params
<del> * - Test themed views.
<del> *
<del> * @return array
<del> */
<del> public static function cacheActionProvider() {
<del> return array(
<del> array('/'),
<del> array('test_cached_pages/index'),
<del> array('TestCachedPages/index'),
<del> array('test_cached_pages/test_nocache_tags'),
<del> array('TestCachedPages/test_nocache_tags'),
<del> array('test_cached_pages/view/param/param'),
<del> array('test_cached_pages/view/foo:bar/value:goo'),
<del> array('test_cached_pages/view?q=cakephp'),
<del> array('test_cached_pages/themed'),
<del> );
<del> }
<del>
<del>/**
<del> * testFullPageCachingDispatch method
<del> *
<del> * @dataProvider cacheActionProvider
<del> * @return void
<del> */
<del> public function testFullPageCachingDispatch($url) {
<del> Configure::write('Cache.disable', false);
<del> Configure::write('Cache.check', true);
<del> Configure::write('debug', 2);
<del>
<del> Router::reload();
<del> Router::connect('/', array('controller' => 'test_cached_pages', 'action' => 'index'));
<del> Router::connect('/:controller/:action/*');
<del>
<del> App::build(array(
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS),
<del> ), App::RESET);
<del>
<del> $dispatcher = new TestDispatcher();
<del> $request = new CakeRequest($url);
<del> $response = $this->getMock('CakeResponse', array('send'));
<del>
<del> $dispatcher->dispatch($request, $response);
<del> $out = $response->body();
<del>
<del> Configure::write('Dispatcher.filters', array('CacheDispatcher'));
<del> $request = new CakeRequest($url);
<del> $response = $this->getMock('CakeResponse', array('send'));
<del> $dispatcher = new TestDispatcher();
<del> $dispatcher->dispatch($request, $response);
<del> $cached = $response->body();
<del>
<del> $cached = preg_replace('/<!--+[^<>]+-->/', '', $cached);
<del>
<del> $this->assertTextEquals($out, $cached);
<del>
<del> $filename = $this->_cachePath($request->here());
<del> unlink($filename);
<del> }
<del>
<del>/**
<del> * testHttpMethodOverrides method
<del> *
<del> * @return void
<del> */
<del> public function testHttpMethodOverrides() {
<del> Router::reload();
<del> Router::mapResources('Posts');
<del>
<del> $_SERVER['REQUEST_METHOD'] = 'POST';
<del> $dispatcher = new Dispatcher();
<del>
<del> $request = new CakeRequest('/posts');
<del> $event = new CakeEvent('DispatcherTest', $dispatcher, array('request' => $request));
<del> $dispatcher->parseParams($event);
<del> $expected = array('pass' => array(), 'named' => array(), 'plugin' => null, 'controller' => 'posts', 'action' => 'add', '[method]' => 'POST');
<del> foreach ($expected as $key => $value) {
<del> $this->assertEquals($value, $request[$key], 'Value mismatch for ' . $key . ' %s');
<del> }
<del>
<del> $_SERVER['REQUEST_METHOD'] = 'GET';
<del> $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT';
<del>
<del> $request = new CakeRequest('/posts/5');
<del> $event = new CakeEvent('DispatcherTest', $dispatcher, array('request' => $request));
<del> $dispatcher->parseParams($event);
<del> $expected = array(
<del> 'pass' => array('5'),
<del> 'named' => array(),
<del> 'id' => '5',
<del> 'plugin' => null,
<del> 'controller' => 'posts',
<del> 'action' => 'edit',
<del> '[method]' => 'PUT'
<del> );
<del> foreach ($expected as $key => $value) {
<del> $this->assertEquals($value, $request[$key], 'Value mismatch for ' . $key . ' %s');
<del> }
<del>
<del> unset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
<del> $_SERVER['REQUEST_METHOD'] = 'GET';
<del>
<del> $request = new CakeRequest('/posts/5');
<del> $event = new CakeEvent('DispatcherTest', $dispatcher, array('request' => $request));
<del> $dispatcher->parseParams($event);
<del> $expected = array('pass' => array('5'), 'named' => array(), 'id' => '5', 'plugin' => null, 'controller' => 'posts', 'action' => 'view', '[method]' => 'GET');
<del> foreach ($expected as $key => $value) {
<del> $this->assertEquals($value, $request[$key], 'Value mismatch for ' . $key . ' %s');
<del> }
<del>
<del> $_POST['_method'] = 'PUT';
<del>
<del> $request = new CakeRequest('/posts/5');
<del> $event = new CakeEvent('DispatcherTest', $dispatcher, array('request' => $request));
<del> $dispatcher->parseParams($event);
<del> $expected = array('pass' => array('5'), 'named' => array(), 'id' => '5', 'plugin' => null, 'controller' => 'posts', 'action' => 'edit', '[method]' => 'PUT');
<del> foreach ($expected as $key => $value) {
<del> $this->assertEquals($value, $request[$key], 'Value mismatch for ' . $key . ' %s');
<del> }
<del>
<del> $_POST['_method'] = 'POST';
<del> $_POST['data'] = array('Post' => array('title' => 'New Post'));
<del> $_POST['extra'] = 'data';
<del> $_SERVER = array();
<del>
<del> $request = new CakeRequest('/posts');
<del> $event = new CakeEvent('DispatcherTest', $dispatcher, array('request' => $request));
<del> $dispatcher->parseParams($event);
<del> $expected = array(
<del> 'pass' => array(), 'named' => array(), 'plugin' => null, 'controller' => 'posts', 'action' => 'add',
<del> '[method]' => 'POST', 'data' => array('extra' => 'data', 'Post' => array('title' => 'New Post')),
<del> );
<del> foreach ($expected as $key => $value) {
<del> $this->assertEquals($value, $request[$key], 'Value mismatch for ' . $key . ' %s');
<del> }
<del>
<del> unset($_POST['_method']);
<del> }
<del>
<del>/**
<del> * cachePath method
<del> *
<del> * @param string $here
<del> * @return string
<del> */
<del> protected function _cachePath($here) {
<del> $path = $here;
<del> if ($here === '/') {
<del> $path = 'home';
<del> }
<del> $path = strtolower(Inflector::slug($path));
<del>
<del> $filename = CACHE . 'views' . DS . $path . '.php';
<del>
<del> if (!file_exists($filename)) {
<del> $filename = CACHE . 'views' . DS . $path . '_index.php';
<del> }
<del> return $filename;
<del> }
<del>}
<ide><path>lib/Cake/Test/Case/View/ScaffoldViewTest.php
<del><?php
<del>/**
<del> * ScaffoldViewTest file
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.Controller
<del> * @since CakePHP(tm) v 2.0
<del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<del> */
<del>App::uses('Controller', 'Controller');
<del>App::uses('Scaffold', 'Controller');
<del>App::uses('ScaffoldView', 'View');
<del>App::uses('AppModel', 'Model');
<del>
<del>require_once dirname(dirname(__FILE__)) . DS . 'Model' . DS . 'models.php';
<del>
<del>/**
<del> * TestScaffoldView class
<del> *
<del> * @package Cake.Test.Case.Controller
<del> */
<del>class TestScaffoldView extends ScaffoldView {
<del>
<del>/**
<del> * testGetFilename method
<del> *
<del> * @param string $action
<del> * @return void
<del> */
<del> public function testGetFilename($action) {
<del> return $this->_getViewFileName($action);
<del> }
<del>
<del>}
<del>
<del>/**
<del> * ScaffoldViewMockController class
<del> *
<del> * @package Cake.Test.Case.Controller
<del> */
<del>class ScaffoldViewMockController extends Controller {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ScaffoldMock'
<del> */
<del> public $name = 'ScaffoldMock';
<del>
<del>/**
<del> * scaffold property
<del> *
<del> * @var mixed
<del> */
<del> public $scaffold;
<del>}
<del>
<del>/**
<del> * ScaffoldViewTest class
<del> *
<del> * @package Cake.Test.Case.Controller
<del> */
<del>class ScaffoldViewTest extends CakeTestCase {
<del>
<del>/**
<del> * fixtures property
<del> *
<del> * @var array
<del> */
<del> public $fixtures = array('core.article', 'core.user', 'core.comment', 'core.join_thing', 'core.tag');
<del>
<del>/**
<del> * setUp method
<del> *
<del> * @return void
<del> */
<del> public function setUp() {
<del> parent::setUp();
<del> $this->request = new CakeRequest(null, false);
<del> $this->Controller = new ScaffoldViewMockController($this->request);
<del> $this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader'));
<del>
<del> App::build(array(
<del> 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS),
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<del> ));
<del> CakePlugin::load('TestPlugin');
<del> }
<del>
<del>/**
<del> * tearDown method
<del> *
<del> * @return void
<del> */
<del> public function tearDown() {
<del> unset($this->Controller, $this->request);
<del> parent::tearDown();
<del> }
<del>
<del>/**
<del> * testGetViewFilename method
<del> *
<del> * @return void
<del> */
<del> public function testGetViewFilename() {
<del> $_admin = Configure::read('Routing.prefixes');
<del> Configure::write('Routing.prefixes', array('admin'));
<del>
<del> $this->Controller->request->params['action'] = 'index';
<del> $ScaffoldView = new TestScaffoldView($this->Controller);
<del> $result = $ScaffoldView->testGetFilename('index');
<del> $expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'index.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $ScaffoldView->testGetFilename('edit');
<del> $expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'form.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $ScaffoldView->testGetFilename('add');
<del> $expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'form.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $ScaffoldView->testGetFilename('view');
<del> $expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'view.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $ScaffoldView->testGetFilename('admin_index');
<del> $expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'index.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $ScaffoldView->testGetFilename('admin_view');
<del> $expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'view.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $ScaffoldView->testGetFilename('admin_edit');
<del> $expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'form.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $ScaffoldView->testGetFilename('admin_add');
<del> $expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'form.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $ScaffoldView->testGetFilename('error');
<del> $expected = CAKE . 'View' . DS . 'Errors' . DS . 'scaffold_error.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> $Controller = new ScaffoldViewMockController($this->request);
<del> $Controller->scaffold = 'admin';
<del> $Controller->viewPath = 'Posts';
<del> $Controller->request['action'] = 'admin_edit';
<del>
<del> $ScaffoldView = new TestScaffoldView($Controller);
<del> $result = $ScaffoldView->testGetFilename('admin_edit');
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Posts' . DS . 'scaffold.form.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $ScaffoldView->testGetFilename('edit');
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Posts' . DS . 'scaffold.form.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> $Controller = new ScaffoldViewMockController($this->request);
<del> $Controller->scaffold = 'admin';
<del> $Controller->viewPath = 'Tests';
<del> $Controller->request->addParams(array(
<del> 'plugin' => 'test_plugin',
<del> 'action' => 'admin_add',
<del> 'admin' => true
<del> ));
<del> $Controller->plugin = 'TestPlugin';
<del>
<del> $ScaffoldView = new TestScaffoldView($Controller);
<del> $result = $ScaffoldView->testGetFilename('admin_add');
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' .
<del> DS . 'TestPlugin' . DS . 'View' . DS . 'Tests' . DS . 'scaffold.form.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $ScaffoldView->testGetFilename('add');
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' .
<del> DS . 'TestPlugin' . DS . 'View' . DS . 'Tests' . DS . 'scaffold.form.ctp';
<del> $this->assertEquals($expected, $result);
<del>
<del> Configure::write('Routing.prefixes', $_admin);
<del> }
<del>
<del>/**
<del> * test getting the view file name for themed scaffolds.
<del> *
<del> * @return void
<del> */
<del> public function testGetViewFileNameWithTheme() {
<del> $this->Controller->request['action'] = 'index';
<del> $this->Controller->viewPath = 'Posts';
<del> $this->Controller->theme = 'TestTheme';
<del> $ScaffoldView = new TestScaffoldView($this->Controller);
<del>
<del> $result = $ScaffoldView->testGetFilename('index');
<del> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS .
<del> 'Themed' . DS . 'TestTheme' . DS . 'Posts' . DS . 'scaffold.index.ctp';
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<del>/**
<del> * test default index scaffold generation
<del> *
<del> * @return void
<del> */
<del> public function testIndexScaffold() {
<del> $params = array(
<del> 'plugin' => null,
<del> 'pass' => array(),
<del> 'form' => array(),
<del> 'named' => array(),
<del> 'url' => array('url' => 'scaffold_mock'),
<del> 'controller' => 'scaffold_mock',
<del> 'action' => 'index',
<del> );
<del> $this->Controller->request->addParams($params);
<del> $this->Controller->request->webroot = '/';
<del> $this->Controller->request->base = '';
<del> $this->Controller->request->here = '/scaffold_mock/index';
<del>
<del> //set router.
<del> Router::reload();
<del> Router::setRequestInfo($this->Controller->request);
<del>
<del> $this->Controller->constructClasses();
<del> ob_start();
<del> new Scaffold($this->Controller, $this->Controller->request);
<del> $this->Controller->response->send();
<del> $result = ob_get_clean();
<del>
<del> $this->assertRegExp('#<h2>Scaffold Mock</h2>#', $result);
<del> $this->assertRegExp('#<table cellpadding="0" cellspacing="0">#', $result);
<del>
<del> $this->assertRegExp('#<a href="/scaffold_users/view/1">1</a>#', $result); //belongsTo links
<del> $this->assertRegExp('#<li><a href="/scaffold_mock/add">New Scaffold Mock</a></li>#', $result);
<del> $this->assertRegExp('#<li><a href="/scaffold_users">List Scaffold Users</a></li>#', $result);
<del> $this->assertRegExp('#<li><a href="/scaffold_comments/add">New Comment</a></li>#', $result);
<del> }
<del>
<del>/**
<del> * test default view scaffold generation
<del> *
<del> * @return void
<del> */
<del> public function testViewScaffold() {
<del> $this->Controller->request->base = '';
<del> $this->Controller->request->here = '/scaffold_mock';
<del> $this->Controller->request->webroot = '/';
<del> $params = array(
<del> 'plugin' => null,
<del> 'pass' => array(1),
<del> 'form' => array(),
<del> 'named' => array(),
<del> 'url' => array('url' => 'scaffold_mock/view/1'),
<del> 'controller' => 'scaffold_mock',
<del> 'action' => 'view',
<del> );
<del> $this->Controller->request->addParams($params);
<del>
<del> //set router.
<del> Router::reload();
<del> Router::setRequestInfo($this->Controller->request);
<del> $this->Controller->constructClasses();
<del>
<del> ob_start();
<del> new Scaffold($this->Controller, $this->Controller->request);
<del> $this->Controller->response->send();
<del> $result = ob_get_clean();
<del>
<del> $this->assertRegExp('/<h2>View Scaffold Mock<\/h2>/', $result);
<del> $this->assertRegExp('/<dl>/', $result);
<del>
<del> $this->assertRegExp('/<a href="\/scaffold_users\/view\/1">1<\/a>/', $result); //belongsTo links
<del> $this->assertRegExp('/<li><a href="\/scaffold_mock\/edit\/1">Edit Scaffold Mock<\/a>\s<\/li>/', $result);
<del> $this->assertRegExp('/<a href="\#" onclick="if[^>]*>Delete Scaffold Mock<\/a>\s<\/li>/', $result);
<del> //check related table
<del> $this->assertRegExp('/<div class="related">\s*<h3>Related Scaffold Comments<\/h3>\s*<table cellpadding="0" cellspacing="0">/', $result);
<del> $this->assertRegExp('/<li><a href="\/scaffold_comments\/add">New Comment<\/a><\/li>/', $result);
<del> $this->assertNotRegExp('/<th>JoinThing<\/th>/', $result);
<del> }
<del>
<del>/**
<del> * test default view scaffold generation
<del> *
<del> * @return void
<del> */
<del> public function testEditScaffold() {
<del> $this->Controller->request->base = '';
<del> $this->Controller->request->webroot = '/';
<del> $this->Controller->request->here = '/scaffold_mock/edit/1';
<del>
<del> $params = array(
<del> 'plugin' => null,
<del> 'pass' => array(1),
<del> 'form' => array(),
<del> 'named' => array(),
<del> 'url' => array('url' => 'scaffold_mock'),
<del> 'controller' => 'scaffold_mock',
<del> 'action' => 'edit',
<del> );
<del> $this->Controller->request->addParams($params);
<del>
<del> //set router.
<del> Router::reload();
<del> Router::setRequestInfo($this->Controller->request);
<del> $this->Controller->constructClasses();
<del>
<del> ob_start();
<del> new Scaffold($this->Controller, $this->Controller->request);
<del> $this->Controller->response->send();
<del> $result = ob_get_clean();
<del>
<del> $this->assertContains('<form action="/scaffold_mock/edit/1" id="ScaffoldMockEditForm" method="post"', $result);
<del> $this->assertContains('<legend>Edit Scaffold Mock</legend>', $result);
<del>
<del> $this->assertContains('input type="hidden" name="data[ScaffoldMock][id]" value="1" id="ScaffoldMockId"', $result);
<del> $this->assertContains('select name="data[ScaffoldMock][user_id]" id="ScaffoldMockUserId"', $result);
<del> $this->assertContains('input name="data[ScaffoldMock][title]" maxlength="255" type="text" value="First Article" id="ScaffoldMockTitle"', $result);
<del> $this->assertContains('input name="data[ScaffoldMock][published]" maxlength="1" type="text" value="Y" id="ScaffoldMockPublished"', $result);
<del> $this->assertContains('textarea name="data[ScaffoldMock][body]" cols="30" rows="6" id="ScaffoldMockBody"', $result);
<del> $this->assertRegExp('/<a href="\#" onclick="if[^>]*>Delete<\/a><\/li>/', $result);
<del> }
<del>
<del>/**
<del> * Test Admin Index Scaffolding.
<del> *
<del> * @return void
<del> */
<del> public function testAdminIndexScaffold() {
<del> $_backAdmin = Configure::read('Routing.prefixes');
<del>
<del> Configure::write('Routing.prefixes', array('admin'));
<del> $params = array(
<del> 'plugin' => null,
<del> 'pass' => array(),
<del> 'form' => array(),
<del> 'named' => array(),
<del> 'prefix' => 'admin',
<del> 'url' => array('url' => 'admin/scaffold_mock'),
<del> 'controller' => 'scaffold_mock',
<del> 'action' => 'admin_index',
<del> 'admin' => 1,
<del> );
<del> $this->Controller->request->base = '';
<del> $this->Controller->request->webroot = '/';
<del> $this->Controller->request->here = '/admin/scaffold_mock';
<del> $this->Controller->request->addParams($params);
<del>
<del> //reset, and set router.
<del> Router::reload();
<del> Router::setRequestInfo($this->Controller->request);
<del>
<del> $this->Controller->scaffold = 'admin';
<del> $this->Controller->constructClasses();
<del>
<del> ob_start();
<del> new Scaffold($this->Controller, $this->Controller->request);
<del> $this->Controller->response->send();
<del> $result = ob_get_clean();
<del>
<del> $this->assertRegExp('/<h2>Scaffold Mock<\/h2>/', $result);
<del> $this->assertRegExp('/<table cellpadding="0" cellspacing="0">/', $result);
<del>
<del> $this->assertRegExp('/<li><a href="\/admin\/scaffold_mock\/add">New Scaffold Mock<\/a><\/li>/', $result);
<del>
<del> Configure::write('Routing.prefixes', $_backAdmin);
<del> }
<del>
<del>/**
<del> * Test Admin Index Scaffolding.
<del> *
<del> * @return void
<del> */
<del> public function testAdminEditScaffold() {
<del> Configure::write('Routing.prefixes', array('admin'));
<del> $params = array(
<del> 'plugin' => null,
<del> 'pass' => array(1),
<del> 'form' => array(),
<del> 'named' => array(),
<del> 'prefix' => 'admin',
<del> 'url' => array('url' => 'admin/scaffold_mock/edit/1'),
<del> 'controller' => 'scaffold_mock',
<del> 'action' => 'admin_edit',
<del> 'admin' => 1,
<del> );
<del> $this->Controller->request->base = '';
<del> $this->Controller->request->webroot = '/';
<del> $this->Controller->request->here = '/admin/scaffold_mock/edit/1';
<del> $this->Controller->request->addParams($params);
<del>
<del> //reset, and set router.
<del> Router::reload();
<del> Router::setRequestInfo($this->Controller->request);
<del>
<del> $this->Controller->scaffold = 'admin';
<del> $this->Controller->constructClasses();
<del>
<del> ob_start();
<del> new Scaffold($this->Controller, $this->Controller->request);
<del> $this->Controller->response->send();
<del> $result = ob_get_clean();
<del>
<del> $this->assertRegExp('#admin/scaffold_mock/edit/1#', $result);
<del> $this->assertRegExp('#Scaffold Mock#', $result);
<del> }
<del>
<del>/**
<del> * Test Admin Index Scaffolding.
<del> *
<del> * @return void
<del> */
<del> public function testMultiplePrefixScaffold() {
<del> $_backAdmin = Configure::read('Routing.prefixes');
<del>
<del> Configure::write('Routing.prefixes', array('admin', 'member'));
<del> $params = array(
<del> 'plugin' => null,
<del> 'pass' => array(),
<del> 'form' => array(),
<del> 'named' => array(),
<del> 'prefix' => 'member',
<del> 'url' => array('url' => 'member/scaffold_mock'),
<del> 'controller' => 'scaffold_mock',
<del> 'action' => 'member_index',
<del> 'member' => 1,
<del> );
<del> $this->Controller->request->base = '';
<del> $this->Controller->request->webroot = '/';
<del> $this->Controller->request->here = '/member/scaffold_mock';
<del> $this->Controller->request->addParams($params);
<del>
<del> //reset, and set router.
<del> Router::reload();
<del> Router::setRequestInfo($this->Controller->request);
<del>
<del> $this->Controller->scaffold = 'member';
<del> $this->Controller->constructClasses();
<del>
<del> ob_start();
<del> new Scaffold($this->Controller, $this->Controller->request);
<del> $this->Controller->response->send();
<del> $result = ob_get_clean();
<del>
<del> $this->assertRegExp('/<h2>Scaffold Mock<\/h2>/', $result);
<del> $this->assertRegExp('/<table cellpadding="0" cellspacing="0">/', $result);
<del>
<del> $this->assertRegExp('/<li><a href="\/member\/scaffold_mock\/add">New Scaffold Mock<\/a><\/li>/', $result);
<del>
<del> Configure::write('Routing.prefixes', $_backAdmin);
<del> }
<del>
<del>} | 6 |
Javascript | Javascript | add a button to show/hide the grid | 4c9a7f6fd114ad0095cdafe0305c3f3dff8bb972 | <ide><path>editor/js/Editor.js
<ide> var Editor = function () {
<ide> fogTypeChanged: new SIGNALS.Signal(),
<ide> fogColorChanged: new SIGNALS.Signal(),
<ide> fogParametersChanged: new SIGNALS.Signal(),
<del> windowResize: new SIGNALS.Signal()
<add> windowResize: new SIGNALS.Signal(),
<add>
<add> showGridChanged: new SIGNALS.Signal()
<ide>
<ide> };
<ide>
<ide><path>editor/js/Toolbar.js
<ide> var Toolbar = function ( editor ) {
<ide> buttons.add( local );
<ide> buttons.add( new UI.Text( 'local' ) );
<ide>
<add> var showGrid = new UI.Checkbox().onChange( update ).setValue( true );
<add> buttons.add( showGrid );
<add> buttons.add( new UI.Text( 'show' ) );
<add>
<ide> function update() {
<ide>
<ide> signals.snapChanged.dispatch( snap.getValue() === true ? grid.getValue() : null );
<ide> signals.spaceChanged.dispatch( local.getValue() === true ? "local" : "world" );
<add> signals.showGridChanged.dispatch( showGrid.getValue() );
<ide>
<ide> }
<ide>
<ide><path>editor/js/Viewport.js
<ide> var Viewport = function ( editor ) {
<ide>
<ide> } );
<ide>
<add> signals.showGridChanged.add( function ( showGrid ) {
<add>
<add> grid.visible = showGrid;
<add> render();
<add>
<add> } );
<add>
<ide> var animations = [];
<ide>
<ide> signals.playAnimation.add( function ( animation ) { | 3 |
Text | Text | add model_cards for dynabert | 0a3b9733cb5b57a8550bd48e278d67f47a9afcf8 | <ide><path>model_cards/huawei-noah/DynaBERT_MNLI/README.md
<add>## DynaBERT: Dynamic BERT with Adaptive Width and Depth
<add>
<add>* DynaBERT can flexibly adjust the size and latency by selecting adaptive width and depth, and
<add>the subnetworks of it have competitive performances as other similar-sized compressed models.
<add>The training process of DynaBERT includes first training a width-adaptive BERT and then
<add>allowing both adaptive width and depth using knowledge distillation.
<add>
<add>* This code is modified based on the repository developed by Hugging Face: [Transformers v2.1.1](https://github.com/huggingface/transformers/tree/v2.1.1), and is released in [GitHub](https://github.com/huawei-noah/Pretrained-Language-Model/tree/master/DynaBERT).
<add>
<add>### Reference
<add>Lu Hou, Zhiqi Huang, Lifeng Shang, Xin Jiang, Qun Liu.
<add>[DynaBERT: Dynamic BERT with Adaptive Width and Depth](https://arxiv.org/abs/2004.04037).
<add>```
<add>@inproceedings{hou2020dynabert,
<add> title = {DynaBERT: Dynamic BERT with Adaptive Width and Depth},
<add> author = {Lu Hou, Zhiqi Huang, Lifeng Shang, Xin Jiang, Qun Liu},
<add> booktitle = {NeurIPS},
<add> year = {2020}
<add>}
<add>```
<ide><path>model_cards/huawei-noah/DynaBERT_SST-2/README.md
<del># DynaBERT: Dynamic BERT with Adaptive Width and Depth
<add>## DynaBERT: Dynamic BERT with Adaptive Width and Depth
<ide>
<ide> * DynaBERT can flexibly adjust the size and latency by selecting adaptive width and depth, and
<ide> the subnetworks of it have competitive performances as other similar-sized compressed models.
<ide> The training process of DynaBERT includes first training a width-adaptive BERT and then
<ide> allowing both adaptive width and depth using knowledge distillation.
<ide>
<del>* This code is modified based on the repository developed by Hugging Face: [Transformers v2.1.1](https://github.com/huggingface/transformers/tree/v2.1.1)
<del>* The results in the paper are produced by using single V100 GPU.
<add>* This code is modified based on the repository developed by Hugging Face: [Transformers v2.1.1](https://github.com/huggingface/transformers/tree/v2.1.1), and is released in [GitHub](https://github.com/huawei-noah/Pretrained-Language-Model/tree/master/DynaBERT).
<add>
<add>### Reference
<add>Lu Hou, Zhiqi Huang, Lifeng Shang, Xin Jiang, Qun Liu.
<add>[DynaBERT: Dynamic BERT with Adaptive Width and Depth](https://arxiv.org/abs/2004.04037).
<add>```
<add>@inproceedings{hou2020dynabert,
<add> title = {DynaBERT: Dynamic BERT with Adaptive Width and Depth},
<add> author = {Lu Hou, Zhiqi Huang, Lifeng Shang, Xin Jiang, Qun Liu},
<add> booktitle = {NeurIPS},
<add> year = {2020}
<add>}
<add>``` | 2 |
Javascript | Javascript | remove extra space in wedge.js | cfafeb68580d7a230550a6758aa834f6bb3bd28a | <ide><path>packages/react-art/npm/Wedge.js
<ide> var Shape = ReactART.Shape;
<ide> var Path = ReactART.Path;
<ide>
<ide> /**
<del> * Wedge is a React component for drawing circles, wedges and arcs. Like other
<add> * Wedge is a React component for drawing circles, wedges and arcs. Like other
<ide> * ReactART components, it must be used in a <Surface>.
<ide> */
<ide> var Wedge = createReactClass({ | 1 |
Javascript | Javascript | extract code to own method for faster jpx decoding | f6841d1720d9dbc52bd353ca63c3fba2cb141db9 | <ide><path>src/core/jpx.js
<ide> var JpxImage = (function JpxImageClosure() {
<ide> }
<ide> return ll;
<ide> };
<add> Transform.prototype.expand = function expand(buffer, bufferPadding, step) {
<add> // Section F.3.7 extending... using max extension of 4
<add> var i1 = bufferPadding - 1, j1 = bufferPadding + 1;
<add> var i2 = bufferPadding + step - 2, j2 = bufferPadding + step;
<add> buffer[i1--] = buffer[j1++];
<add> buffer[j2++] = buffer[i2--];
<add> buffer[i1--] = buffer[j1++];
<add> buffer[j2++] = buffer[i2--];
<add> buffer[i1--] = buffer[j1++];
<add> buffer[j2++] = buffer[i2--];
<add> buffer[i1--] = buffer[j1++];
<add> buffer[j2++] = buffer[i2--];
<add> };
<ide> Transform.prototype.iterate = function Transform_iterate(ll, hl, lh, hh,
<ide> u0, v0) {
<ide> var llWidth = ll.width, llHeight = ll.height, llItems = ll.items;
<ide> var JpxImage = (function JpxImageClosure() {
<ide> for (var u = 0; u < width; u++, k++, l++)
<ide> buffer[l] = items[k];
<ide>
<del> // Section F.3.7 extending... using max extension of 4
<del> var i1 = bufferPadding - 1, j1 = bufferPadding + 1;
<del> var i2 = bufferPadding + width - 2, j2 = bufferPadding + width;
<del> buffer[i1--] = buffer[j1++];
<del> buffer[j2++] = buffer[i2--];
<del> buffer[i1--] = buffer[j1++];
<del> buffer[j2++] = buffer[i2--];
<del> buffer[i1--] = buffer[j1++];
<del> buffer[j2++] = buffer[i2--];
<del> buffer[i1--] = buffer[j1++];
<del> buffer[j2++] = buffer[i2--];
<del>
<add> this.expand(buffer, bufferPadding, width);
<ide> this.filter(buffer, bufferPadding, width, u0, bufferOut);
<ide>
<ide> k = v * width;
<ide> var JpxImage = (function JpxImageClosure() {
<ide> for (var v = 0; v < height; v++, k += width, l++)
<ide> buffer[l] = items[k];
<ide>
<del> // Section F.3.7 extending... using max extension of 4
<del> var i1 = bufferPadding - 1, j1 = bufferPadding + 1;
<del> var i2 = bufferPadding + height - 2, j2 = bufferPadding + height;
<del> buffer[i1--] = buffer[j1++];
<del> buffer[j2++] = buffer[i2--];
<del> buffer[i1--] = buffer[j1++];
<del> buffer[j2++] = buffer[i2--];
<del> buffer[i1--] = buffer[j1++];
<del> buffer[j2++] = buffer[i2--];
<del> buffer[i1--] = buffer[j1++];
<del> buffer[j2++] = buffer[i2--];
<del>
<add> this.expand(buffer, bufferPadding, height);
<ide> this.filter(buffer, bufferPadding, height, v0, bufferOut);
<ide>
<ide> k = u; | 1 |
Javascript | Javascript | make util.debuglog() consistent with doc | 3b0e800f18133674ae30b4c6cd5729c12fa054ff | <ide><path>lib/util.js
<ide> exports.deprecate = internalUtil.deprecate;
<ide> var debugs = {};
<ide> var debugEnviron;
<ide> exports.debuglog = function(set) {
<del> if (debugEnviron === undefined)
<del> debugEnviron = process.env.NODE_DEBUG || '';
<add> if (debugEnviron === undefined) {
<add> debugEnviron = new Set(
<add> (process.env.NODE_DEBUG || '').split(',').map((s) => s.toUpperCase()));
<add> }
<ide> set = set.toUpperCase();
<ide> if (!debugs[set]) {
<del> if (new RegExp(`\\b${set}\\b`, 'i').test(debugEnviron)) {
<add> if (debugEnviron.has(set)) {
<ide> var pid = process.pid;
<ide> debugs[set] = function() {
<ide> var msg = exports.format.apply(exports, arguments);
<ide><path>test/sequential/test-util-debug.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide>
<del>if (process.argv[2] === 'child')
<del> child();
<add>const [, , modeArgv, sectionArgv] = process.argv;
<add>
<add>if (modeArgv === 'child')
<add> child(sectionArgv);
<ide> else
<ide> parent();
<ide>
<ide> function parent() {
<del> test('foo,tud,bar', true);
<del> test('foo,tud', true);
<del> test('tud,bar', true);
<del> test('tud', true);
<del> test('foo,bar', false);
<del> test('', false);
<add> test('foo,tud,bar', true, 'tud');
<add> test('foo,tud', true, 'tud');
<add> test('tud,bar', true, 'tud');
<add> test('tud', true, 'tud');
<add> test('foo,bar', false, 'tud');
<add> test('', false, 'tud');
<add>
<add> test('###', true, '###');
<add> test('hi:)', true, 'hi:)');
<add> test('f$oo', true, 'f$oo');
<add> test('f$oo', false, 'f.oo');
<add> test('no-bar-at-all', false, 'bar');
<ide> }
<ide>
<del>function test(environ, shouldWrite) {
<add>function test(environ, shouldWrite, section) {
<ide> let expectErr = '';
<del> if (shouldWrite) {
<del> expectErr = 'TUD %PID%: this { is: \'a\' } /debugging/\n' +
<del> 'TUD %PID%: number=1234 string=asdf obj={"foo":"bar"}\n';
<del> }
<ide> const expectOut = 'ok\n';
<ide>
<ide> const spawn = require('child_process').spawn;
<del> const child = spawn(process.execPath, [__filename, 'child'], {
<add> const child = spawn(process.execPath, [__filename, 'child', section], {
<ide> env: Object.assign(process.env, { NODE_DEBUG: environ })
<ide> });
<ide>
<del> expectErr = expectErr.split('%PID%').join(child.pid);
<add> if (shouldWrite) {
<add> expectErr =
<add> `${section.toUpperCase()} ${child.pid}: this { is: 'a' } /debugging/\n${
<add> section.toUpperCase()} ${child.pid}: num=1 str=a obj={"foo":"bar"}\n`;
<add> }
<ide>
<ide> let err = '';
<ide> child.stderr.setEncoding('utf8');
<ide> function test(environ, shouldWrite) {
<ide> }
<ide>
<ide>
<del>function child() {
<add>function child(section) {
<ide> const util = require('util');
<del> const debug = util.debuglog('tud');
<add> const debug = util.debuglog(section);
<ide> debug('this', { is: 'a' }, /debugging/);
<del> debug('number=%d string=%s obj=%j', 1234, 'asdf', { foo: 'bar' });
<add> debug('num=%d str=%s obj=%j', 1, 'a', { foo: 'bar' });
<ide> console.log('ok');
<ide> } | 2 |
Mixed | Javascript | change the way the extra info appears | daeac82fdaebc6e2b7b447d09bfa03c01b20e425 | <ide><path>utils/build/build.js
<ide> function main() {
<ide>
<ide> var buffer = [];
<ide> var sources = [];
<add>
<add> buffer.push('// You shouldn\'t edit this build file. \n');
<add> buffer.push('// The following source code is build from the src folder. \n');
<ide>
<ide> if ( args.amd ){
<ide> buffer.push('function ( root, factory ) {\n\n\tif ( typeof define === \'function\' && define.amd ) {\n\n\t\tdefine( [ \'exports\' ], factory );\n\n\t} else if ( typeof exports === \'object\' ) {\n\n\t\tfactory( exports );\n\n\t} else {\n\n\t\tfactory( root );\n\n\t}\n\n}( this, function ( exports ) {\n\n');
<ide> function main() {
<ide> var file = '../../' + files[ j ];
<ide>
<ide> sources.push( file );
<del> buffer.push('// You shouldn\'t edit this build file. \n');
<del> buffer.push('// The following source code should be edited in \n');
<del> buffer.push('// ' + files[ j ]);
<add> buffer.push('// File:' + files[ j ]);
<ide> buffer.push('\n\n');
<ide> buffer.push( fs.readFileSync( file, 'utf8' ) );
<ide> buffer.push('\n');
<ide><path>utils/build/build.py
<ide> if sys.version_info < (2, 7):
<ide> print("This script requires at least Python 2.7.")
<ide> print("Please, update to a newer version: http://www.python.org/download/releases/")
<del> exit()
<add># exit()
<ide>
<ide> import argparse
<ide> import json
<ide> def main(argv=None):
<ide> fd, path = tempfile.mkstemp()
<ide> tmp = open(path, 'w')
<ide> sources = []
<del>
<add>
<add> tmp.write('// You shouldn\'t edit this build file. \n')
<add> tmp.write('// The following source code is build from the src folder. \n')
<add>
<ide> if args.amd:
<ide> tmp.write('( function ( root, factory ) {\n\n\tif ( typeof define === \'function\' && define.amd ) {\n\n\t\tdefine( [ \'exports\' ], factory );\n\n\t} else if ( typeof exports === \'object\' ) {\n\n\t\tfactory( exports );\n\n\t} else {\n\n\t\tfactory( root );\n\n\t}\n\n}( this, function ( exports ) {\n\n')
<ide>
<ide> for include in args.include:
<ide> with open('includes/' + include + '.json','r') as f:
<ide> files = json.load(f)
<ide> for filename in files:
<del> tmp.write('// You shouldn\'t edit this build file. \n')
<del> tmp.write('// The following source code should be edited in \n')
<del> tmp.write('// ' + filename)
<add> tmp.write('// File:' + filename)
<ide> tmp.write('\n\n')
<ide> filename = '../../' + filename;
<ide> sources.append(filename) | 2 |
Python | Python | fix typo in documentation of loadtxt (closes ) | 7d25864a56bb8fb53face5cf1ad0721795e03a02 | <ide><path>numpy/lib/npyio.py
<ide> def loadtxt(fname, dtype=float, comments='#', delimiter=None,
<ide>
<ide> Also when a single column has to be read it is possible to use
<ide> an integer instead of a tuple. E.g ``usecols = 3`` reads the
<del> third column the same way as `usecols = (3,)`` would.
<add> fourth column the same way as `usecols = (3,)`` would.
<ide>
<ide> unpack : bool, optional
<ide> If True, the returned array is transposed, so that arguments may be | 1 |
Text | Text | update portuguese translation | f2ac393c47d39042816b4918a777f6ff61d0c9c4 | <ide><path>guide/portuguese/javascript/await-promises/index.md
<ide> ---
<ide> title: Await Promises
<del>localeTitle: Aguardar Promessas
<add>localeTitle: Await Promises
<ide> ---
<del>## Aguardar Promessas
<add>## Await Promises
<ide>
<del>Os [operadores](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) `async` / `await` facilitam a implementação de muitas promessas assíncronas. Eles também permitem que os engenheiros escrevam códigos mais claros, mais sucintos e testáveis.
<add>Os [operadores](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) `async` / `await` facilitam a implementação de muitas `Promises` assíncronas. Eles também permitem que os engenheiros escrevam códigos mais claros, mais sucintos e testáveis.
<ide>
<del>Para entender esse assunto, você deve ter uma compreensão sólida de como as [Promessas](https://guide.freecodecamp.org/javascript/promises) funcionam.
<add>Para entender esse assunto, você deve ter uma compreensão sólida de como as [Promises](https://guide.freecodecamp.org/javascript/promises) funcionam.
<ide>
<ide> * * *
<ide>
<ide> ## Sintaxe Básica
<ide>
<del>```javascript
<del>function slowlyResolvedPromiseFunc (string) {
<del> return new Promise (resolve => {
<del> setTimeout (() => { resolver (string); }, 5000);
<del> });
<add>``` javascript
<add>function slowlyResolvedPromiseFunc(string) {
<add> return new Promise(resolve => {
<add> setTimeout(() => {
<add> resolve(string);
<add> }, 5000);
<add> });
<ide> }
<ide>
<del>função assíncrona doIt () {
<del> const myPromise = aguardar lentamenteResolvedPromiseFunc ("foo");
<del> console.log (myPromise); // "foo"
<add>async function doIt() {
<add> const myPromise = await slowlyResolvedPromiseFunc("foo");
<add> console.log(myPromise); // "foo"
<ide> }
<ide>
<del>faça();
<add>doIt();
<ide> ```
<ide>
<ide> Há outras coisas para se prestar atenção:
<ide>
<ide> * A função que contém alguma declaração de `await` precisa incluir o operador `async` em sua declaração. Isso irá dizer ao interpretador JS para que ele espere até que a `Promise` seja resolvida ou rejeitada.
<del> * O operador `await` precisa ser declarado inline.
<del> * `const something = await thisReturnsAPromise()`
<add> * O operador `await` precisa ser declarado inline, durante a declaração da `const`.
<ide> * Isso funciona tanto para a rejeição ou a resolução de uma `Promise`.
<ide>
<ide> ---
<ide>
<ide> ## Promises aninhadas vs. `Async` / `Await`
<ide>
<del> Implementar uma unica promise é muito facil. Por outro lado promises aninhadas ou a criação de uma "dependency pattern" pode produzir um código spagetti.
<add> Implementar uma unica Promise é muito fácil. Por outro lado Promises aninhadas ou a criação de uma "dependency pattern" pode produzir um "código spagetti".
<ide>
<ide> Os exemplos a seguir assumem que <a href='https://github.com/request/request-promise' target='_blank' rel='nofollow'>`request-promise`</a> está disponível como `rp`.
<ide>
<ide> ### Promises encadeadas/aninhadas
<del>```js
<del>
<del>// Primeira Promisse
<del>const fooPromise = rp("http://domain.com/foo");
<del>
<del>fooPromise.then(resultFoo => {
<del>// deve esperar por "foo" para resolver
<del> console.log (resultFoo);
<del>})
<del>```
<del>```js
<del>const barPromise = rp("http://domain.com/bar");
<del>const bazPromise = rp("http://domain.com/baz");
<ide>
<del>Promise.all([barPromise, bazPromise])
<del>.then(resultArr => {
<del> // Lidar com as resoluções "bar" e "baz" aqui
<del> console.log(resultArr [0]);
<del> console.log(resultArr [1]);
<del>});
<del>```
<del>### `async` and `await` Promises
<add>
<add>``` javascript
<add>// Primeira Promise
<add>const fooPromise = rp("http://domain.com/foo");
<ide>
<del>```js
<add>fooPromise.then(resultFoo => {
<add> // Deve aguardar por "foo" para resolver
<add> console.log(resultFoo);
<ide>
<del>// Enrole tudo em uma função assíncrona função assíncrona
<del>async doItAll () {
<del> // Pega dados do ponto de extremidade "foo", mas aguarde a resolução
<del> console.log (await rp("http://domain.com/foo"));
<add> const barPromise = rp("http://domain.com/bar");
<add> const bazPromise = rp("http://domain.com/baz");
<ide>
<del> // Concorrência aconteceConcurrently kick off the next two async calls,
<del> // não espere por "bar" para disparar "baz"
<del> const barPromise = rp("http://domain.com/bar");
<del> const bazPromise = rp("http://domain.com/baz");
<del>
<del> // Depois que as duas foram disparadas, espere pelas duas
<del> const barResponse = await barPromise;
<del> const bazResponse = await bazPromise;
<add> return Promise.all([barPromise, bazPromise]);
<add>}).then(resultArr => {
<add> // Lidar com as resoluções "bar" e "baz" aqui
<add> console.log(resultArr[0]);
<add> console.log(resultArr[1]);
<add>});
<add>```
<ide>
<del> console.log(barResponse);
<del> console.log(bazResponse);
<add>### `async` e `await` Promises
<add>
<add>``` javascript
<add>// Envolva tudo em uma função assíncrona (async)
<add>async function doItAll() {
<add> // Pega os dados do ponto final "foo", mas aguarda a resolução
<add> console.log(await rp("http://domain.com/foo"));
<add>
<add> // Ao mesmo tempo, inicie as próximas duas chamadas assíncronas,
<add> // Não espera por "bar" para disparar "baz"
<add> const barPromise = rp("http://domain.com/bar");
<add> const bazPromise = rp("http://domain.com/baz");
<add>
<add> // Depois que as duas foram disparadas, espere pelas duas
<add> const barResponse = await barPromise;
<add> const bazResponse = await bazPromise;
<add>
<add> console.log(barResponse);
<add> console.log(bazResponse);
<ide> }
<del>```
<ide>
<del>```js
<del>// Finalmente, invoque a função assíncrona
<del>doItAll().then(() => console.log ('Feito!'));
<add>// Finalmente, chame a função assíncrona
<add>doItAll().then(() => console.log('Done!'));
<ide> ```
<ide>
<del>As vantagens de usar `async` e `await` deve estar claro. O codigo é mais modular, testavel e legível.
<add>As vantagens de usar `async` e `await` devem estar bem claras. O código é mais modular, testavel e legível.
<ide>
<del>Entretanto há um senso de concorrencia, os processos computacionais que ocorrem são os mesmos do exemplo anterior.
<add>É justo notar que, embora exista uma sensação adicional de simultaneidade, os processos computacionais que ocorrem são os mesmos do exemplo anterior.
<ide>
<ide> ---
<ide>
<ide> ## Lidando com Errors / Rejection
<ide>
<ide> Um bloco `try-catch` consegue lidar com rejeição de promises.
<ide>
<del>```js
<del>async errorExample () {
<del> try {
<del> const rejectedPromise = await Promise.reject ("Oh-oh!");
<del> } catch (erro) {
<del> console.log (erro);
<add>``` javascript
<add>async function errorExample() {
<add> try {
<add> const rejectedPromise = await Promise.reject("Oh-oh!");
<add> } catch (error) {
<add> console.log(error); // "Uh-oh!"
<ide> }
<add>}
<ide>
<del>errorExample ();
<add>errorExample();
<ide> ```
<ide>
<del>* * *
<add>---
<ide>
<del>#### Mais Informações:
<add>### Mais informação:
<ide>
<del>* `await` Operador [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)
<del>* [Documentos do MDN do](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function) operador de funções `async`
<add>* Operador `await` <a href='https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/await' target='_blank' rel='nofollow'>MDN Docs</a>
<add>* Função `async` <a href='https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/async_function' target='_blank' rel=''nofollow'>MDN Docs</a> | 1 |
PHP | PHP | revert "no truncate when drop table." | 1686edf01624313962aa167a7001245dd4d044ae | <ide><path>lib/Cake/TestSuite/Fixture/CakeFixtureManager.php
<ide> public function load(CakeTestCase $test) {
<ide> $db = ConnectionManager::getDataSource($fixture->useDbConfig);
<ide> $db->begin();
<ide> $this->_setupTable($fixture, $db, $test->dropTables);
<del> if (!$test->dropTables) {
<del> $fixture->truncate($db);
<del> }
<add> $fixture->truncate($db);
<ide> $fixture->insert($db);
<ide> $db->commit();
<ide> }
<ide> public function loadSingle($name, $db = null, $dropTables = true) {
<ide> $db = ConnectionManager::getDataSource($fixture->useDbConfig);
<ide> }
<ide> $this->_setupTable($fixture, $db, $dropTables);
<del> if (!$dropTables) {
<del> $fixture->truncate($db);
<del> }
<add> $fixture->truncate($db);
<ide> $fixture->insert($db);
<ide> } else {
<ide> throw new UnexpectedValueException(__d('cake_dev', 'Referenced fixture class %s not found', $name)); | 1 |
Javascript | Javascript | replace google servers with localhost | 6d937c01b00652b1a97136d96d8d9fd3925af420 | <ide><path>test/parallel/test-dns-setserver-when-querying.js
<ide> const common = require('../common');
<ide>
<ide> const dns = require('dns');
<ide>
<del>const goog = [
<del> '8.8.8.8',
<del> '8.8.4.4',
<del>];
<add>const localhost = [ '127.0.0.1' ];
<ide>
<ide> {
<ide> // Fix https://github.com/nodejs/node/issues/14734
<ide> const goog = [
<ide> const resolver = new dns.Resolver();
<ide> resolver.resolve('localhost', common.mustCall());
<ide>
<del> common.expectsError(resolver.setServers.bind(resolver, goog), {
<add> common.expectsError(resolver.setServers.bind(resolver, localhost), {
<ide> code: 'ERR_DNS_SET_SERVERS_FAILED',
<ide> message: /^c-ares failed to set servers: "There are pending queries\." \[.+\]$/g
<ide> });
<ide> const goog = [
<ide> dns.resolve('localhost', common.mustCall());
<ide>
<ide> // should not throw
<del> dns.setServers(goog);
<add> dns.setServers(localhost);
<ide> }
<ide> } | 1 |
Javascript | Javascript | condense uvgen as suggested by @anthornet in | d9379fc8a5034efd664c8dfd7e9ce39a98dd85ef | <ide><path>src/extras/geometries/ExtrudeGeometry.js
<ide> THREE.ExtrudeGeometry.prototype.addShape = function( shape, options ) {
<ide>
<ide> var material = options.material;
<ide> var extrudeMaterial = options.extrudeMaterial;
<del> var uvGenerator = options.uvGenerator || null;
<add>
<add> // Use default WorldUVGenerator if no UV generators are specified.
<add> var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
<ide>
<ide> var shapebb = this.shapebb;
<ide> //shapebb = shape.getBoundingBox();
<ide> THREE.ExtrudeGeometry.prototype.addShape = function( shape, options ) {
<ide>
<ide> }
<ide>
<del> // choose UV generator
<del> var uvgen = uvGenerator /* specified */ ||
<del> THREE.ExtrudeGeometry.WorldUVGenerator; /* default */
<add>
<ide>
<ide> ////
<ide> /// Handle Faces | 1 |
PHP | PHP | remove warning for orwhere() | 075d8c1fe9bd193e294316e0cb3f4af07c5cf728 | <ide><path>src/Database/Query.php
<ide> public function andWhere($conditions, $types = [])
<ide> */
<ide> public function orWhere($conditions, $types = [])
<ide> {
<del> deprecationWarning('Query::orWhere() is deprecated. Use Query::where() instead.');
<ide> $this->_conjugate('where', $conditions, 'OR', $types);
<ide>
<ide> return $this; | 1 |
Javascript | Javascript | improve short months | 3683efa8942cd68b03fd699b1dceb9c3af628dac | <ide><path>src/locale/vi.js
<ide> export default moment.defineLocale('vi', {
<ide> months: 'tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12'.split(
<ide> '_'
<ide> ),
<del> monthsShort: 'Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12'.split(
<add> monthsShort: 'Thg 01_Thg 02_Thg 03_Thg 04_Thg 05_Thg 06_Thg 07_Thg 08_Thg 09_Thg 10_Thg 11_Thg 12'.split(
<ide> '_'
<ide> ),
<ide> monthsParseExact: true,
<ide><path>src/test/locale/vi.js
<ide> localeModule('vi');
<ide>
<ide> test('parse', function (assert) {
<ide> var i,
<del> tests = 'tháng 1,Th01_tháng 2,Th02_tháng 3,Th03_tháng 4,Th04_tháng 5,Th05_tháng 6,Th06_tháng 7,Th07_tháng 8,Th08_tháng 9,Th09_tháng 10,Th10_tháng 11,Th11_tháng 12,Th12'.split(
<add> tests = 'tháng 1,Thg 01_tháng 2,Thg 02_tháng 3,Thg 03_tháng 4,Thg 04_tháng 5,Thg 05_tháng 6,Thg 06_tháng 7,Thg 07_tháng 8,Thg 08_tháng 9,Thg 09_tháng 10,Thg 10_tháng 11,Thg 11_tháng 12,Thg 12'.split(
<ide> '_'
<ide> );
<ide>
<ide> test('format', function (assert) {
<ide> 'chủ nhật, tháng 2 14 2010, 3:25:50 ch',
<ide> ],
<ide> ['ddd, hA', 'CN, 3CH'],
<del> ['M Mo MM MMMM MMM', '2 2 02 tháng 2 Th02'],
<add> ['M Mo MM MMMM MMM', '2 2 02 tháng 2 Thg 02'],
<ide> ['YYYY YY', '2010 10'],
<ide> ['D Do DD', '14 14 14'],
<ide> ['d do dddd ddd dd', '0 0 chủ nhật CN CN'],
<ide> test('format', function (assert) {
<ide> ['LLL', '14 tháng 2 năm 2010 15:25'],
<ide> ['LLLL', 'chủ nhật, 14 tháng 2 năm 2010 15:25'],
<ide> ['l', '14/2/2010'],
<del> ['ll', '14 Th02 2010'],
<del> ['lll', '14 Th02 2010 15:25'],
<del> ['llll', 'CN, 14 Th02 2010 15:25'],
<add> ['ll', '14 Thg 02 2010'],
<add> ['lll', '14 Thg 02 2010 15:25'],
<add> ['llll', 'CN, 14 Thg 02 2010 15:25'],
<ide> ],
<ide> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
<ide> i;
<ide> test('format ordinal', function (assert) {
<ide>
<ide> test('format month', function (assert) {
<ide> var i,
<del> expected = 'tháng 1,Th01_tháng 2,Th02_tháng 3,Th03_tháng 4,Th04_tháng 5,Th05_tháng 6,Th06_tháng 7,Th07_tháng 8,Th08_tháng 9,Th09_tháng 10,Th10_tháng 11,Th11_tháng 12,Th12'.split(
<add> expected = 'tháng 1,Thg 01_tháng 2,Thg 02_tháng 3,Thg 03_tháng 4,Thg 04_tháng 5,Thg 05_tháng 6,Thg 06_tháng 7,Thg 07_tháng 8,Thg 08_tháng 9,Thg 09_tháng 10,Thg 10_tháng 11,Thg 11_tháng 12,Thg 12'.split(
<ide> '_'
<ide> );
<ide> | 2 |
Ruby | Ruby | fix microsecond precision of time#at_with_coercion | 484253515c0e05760541dc48946361185c9e6904 | <ide><path>activesupport/lib/active_support/core_ext/time/calculations.rb
<ide> def current
<ide> # instances can be used when called with a single argument
<ide> def at_with_coercion(*args)
<ide> if args.size == 1 && args.first.acts_like?(:time)
<del> at_without_coercion(args.first.to_i)
<add> at_without_coercion(args.first.to_f)
<ide> else
<ide> at_without_coercion(*args)
<ide> end
<ide><path>activesupport/test/core_ext/time_ext_test.rb
<ide> def test_at_with_time_with_zone
<ide> end
<ide> end
<ide>
<add> def test_at_with_time_microsecond_precision
<add> assert_equal Time.at(Time.utc(2000, 1, 1, 0, 0, 0, 111)).to_f, Time.utc(2000, 1, 1, 0, 0, 0, 111).to_f
<add> end
<add>
<ide> def test_eql?
<ide> assert_equal true, Time.utc(2000).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']) )
<ide> assert_equal true, Time.utc(2000).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) ) | 2 |
Ruby | Ruby | add help message for cargo | 3dc0df5a774272766e2187b46df97742b3aec28a | <ide><path>Library/Homebrew/missing_formula.rb
<ide> def blacklisted_reason(name)
<ide> EOS
<ide> when "tex", "tex-live", "texlive", "latex" then <<~EOS
<ide> Installing TeX from source is weird and gross, requires a lot of patches,
<del> and only builds 32-bit (and thus can't use Homebrew dependencies)
<add> and only builds 32-bit (and thus can’t use Homebrew dependencies)
<ide>
<ide> We recommend using a MacTeX distribution: https://www.tug.org/mactex/
<ide>
<ide> def blacklisted_reason(name)
<ide> You can read more about it at:
<ide> #{Formatter.url("https://github.com/MacRuby/MacRuby")}
<ide> EOS
<del> when /(lib)?lzma/
<del> "lzma is now part of the xz formula."
<add> when /(lib)?lzma/ then <<~EOS
<add> lzma is now part of the xz formula, and can be installed with:
<add> brew install xz.
<add> EOS
<ide> when "gtest", "googletest", "google-test" then <<~EOS
<ide> Installing gtest system-wide is not recommended; it should be vendored
<ide> in your projects that use it.
<ide> def blacklisted_reason(name)
<ide> Install gsutil with `pip2 install gsutil`
<ide> EOS
<ide> when "gfortran" then <<~EOS
<del> GNU Fortran is now provided as part of GCC, and can be installed with:
<add> GNU Fortran is now part of the GCC formula, and can be installed with:
<ide> brew install gcc
<ide> EOS
<ide> when "play" then <<~EOS
<ide> def blacklisted_reason(name)
<ide> If you wish to use the 2.x release you can install with Homebrew Cask:
<ide> brew cask install ngrok
<ide> EOS
<add> when "cargo" then <<~EOS
<add> Homebrew provides cargo via: `brew install rust`.
<add> EOS
<ide> end
<ide> end
<ide> alias generic_blacklisted_reason blacklisted_reason | 1 |
Ruby | Ruby | fix typo in example formula | ee1d8512bf4cd6deadfa8c7a55f189cac61c221a | <ide><path>Library/Contributions/example-formula.rb
<ide> def install
<ide> args << "--i-want-spam" if build.include? "enable-spam"
<ide> args << "--qt-gui" if build.with? "qt" # "--with-qt" ==> build.with? "qt"
<ide> args << "--some-new-stuff" if build.head? # if head is used instead of url.
<del> args << "--universal-binray" if build.universal?
<add> args << "--universal-binary" if build.universal?
<ide>
<ide> # The `build.with?` and `build.without?` are smart enough to do the
<ide> # right thing™ with respect to defaults defined via `:optional` and | 1 |
Text | Text | add keyboard-layout to build-status.md | e90d538b017b4589a43c7a694cdd1f8c11ccac8e | <ide><path>docs/build-instructions/build-status.md
<ide> | [Fs Plus](https://github.com/atom/fs-plus) | [](https://travis-ci.org/atom/fs-plus) | [](https://ci.appveyor.com/project/Atom/fs-plus/branch/master) | [](https://david-dm.org/atom/fs-plus) |
<ide> | [Grim](https://github.com/atom/grim) | [](https://travis-ci.org/atom/grim) | [](https://ci.appveyor.com/project/Atom/grim/branch/master) | [](https://david-dm.org/atom/grim) |
<ide> | [Jasmine Focused](https://github.com/atom/jasmine-focused) | [](https://travis-ci.org/atom/grim) | [](https://ci.appveyor.com/project/Atom/jasmine-focused/branch/master) | [](https://david-dm.org/atom/jasmine-focused) |
<add>| [Keyboard-Layout](https://github.com/atom/keyboard-layout) | [](https://travis-ci.org/atom/keyboard-layout) [] (https://ci.appveyor.com/project/Atom/keyboard-layout) [](https://david-dm.org/atom/keyboard-layout) |
<ide> | [Oniguruma](https://github.com/atom/node-oniguruma) | [](https://travis-ci.org/atom/node-oniguruma) | [](https://ci.appveyor.com/project/Atom/node-oniguruma/branch/master) | [](https://david-dm.org/atom/node-oniguruma) |
<ide> | [Property Accessors](https://github.com/atom/property-accessors) | [](https://travis-ci.org/atom/property-accessors) | [](https://ci.appveyor.com/project/Atom/property-accessors/branch/master) | [](https://david-dm.org/atom/property-accessors) |
<ide> | [TextBuffer](https://github.com/atom/text-buffer) | [](https://travis-ci.org/atom/text-buffer) | [](https://ci.appveyor.com/project/Atom/text-buffer/branch/master) | [](https://david-dm.org/atom/text-buffer) | | 1 |
PHP | PHP | fix spelling error | 991a7630ad3a577d8380c92e6bf18141a95e8c9a | <ide><path>lib/Cake/Test/TestCase/Utility/MergeVariablesTraitTest.php
<ide> public function testMergeVarsMixedModes() {
<ide> }
<ide>
<ide> /**
<del> * Test that merging variables with booleans in the class heirarchy
<add> * Test that merging variables with booleans in the class hierarchy
<ide> * doesn't cause issues.
<ide> *
<ide> * @return void | 1 |
Python | Python | fix a race condition in gce’s list_nodes() | b1d0731959637ab9df8876a3f3b9ad9fb2f38efd | <ide><path>libcloud/compute/drivers/gce.py
<ide> def list_nodes(self, ex_zone=None):
<ide> # The aggregated response returns a dict for each zone
<ide> if zone is None:
<ide> for v in response['items'].values():
<del> zone_nodes = [self._to_node(i) for i in
<del> v.get('instances', [])]
<del> list_nodes.extend(zone_nodes)
<add> for i in v.get('instances', []):
<add> try:
<add> list_nodes.append(self._to_node(i))
<add> # If a GCE node has been deleted between
<add> # - is was listed by `request('.../instances', 'GET')
<add> # - it is converted by `self._to_node(i)`
<add> # `_to_node()` will raise a ResourceNotFoundError.
<add> #
<add> # Just ignore that node and return the list of the
<add> # other nodes.
<add> except ResourceNotFoundError:
<add> pass
<ide> else:
<del> list_nodes = [self._to_node(i) for i in response['items']]
<add> for i in response['items']:
<add> try:
<add> list_nodes.append(self._to_node(i))
<add> # If a GCE node has been deleted between
<add> # - is was listed by `request('.../instances', 'GET')
<add> # - it is converted by `self._to_node(i)`
<add> # `_to_node()` will raise a ResourceNotFoundError.
<add> #
<add> # Just ignore that node and return the list of the
<add> # other nodes.
<add> except ResourceNotFoundError:
<add> pass
<ide> return list_nodes
<ide>
<ide> def ex_list_regions(self): | 1 |
Go | Go | make use of os.pathseparator | 8ba64b383dee8827c70f9c0a0d71aa61d0f0c595 | <ide><path>pkg/archive/archive_windows.go
<ide> package archive
<ide>
<ide> import (
<ide> "fmt"
<add> "os"
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide> func CanonicalTarNameForPath(p string) (string, error) {
<ide> if strings.Contains(p, "/") {
<ide> return "", fmt.Errorf("windows path contains forward slash: %s", p)
<ide> }
<del> return strings.Replace(p, "\\", "/", -1), nil
<add> return strings.Replace(p, string(os.PathSeparator), "/", -1), nil
<add>
<ide> }
<ide>
<ide> func setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (nlink uint32, inode uint64, err error) { | 1 |
Text | Text | remove obsolete external link | c6f959a9d09f6d15e334d66d331994b01f9753c0 | <ide><path>doc/api/addons.md
<ide> console.log(addon.hello());
<ide> // Prints: 'world'
<ide> ```
<ide>
<del>Please see the examples below for further information or
<del><https://github.com/arturadib/node-qt> for an example in production.
<del>
<ide> Because the exact path to the compiled Addon binary can vary depending on how
<ide> it is compiled (i.e. sometimes it may be in `./build/Debug/`), Addons can use
<ide> the [bindings][] package to load the compiled module. | 1 |
Python | Python | fix copyright holder | 91e4f7effb6c0911d2db68c9f17b40f484838538 | <ide><path>django/utils/baseconv.py
<del># Copyright (c) 2010 Taurinus Collective. All rights reserved.
<add># Copyright (c) 2010 Guilherme Gondim. All rights reserved.
<ide> # Copyright (c) 2009 Simon Willison. All rights reserved.
<ide> # Copyright (c) 2002 Drew Perttula. All rights reserved.
<ide> # | 1 |
PHP | PHP | add withdisabledcache() header macro | 5326287d60500757e99d474a8d4928186dc235fd | <ide><path>src/Network/Response.php
<ide> public function charset($charset = null)
<ide> * Sets the correct headers to instruct the client to not cache the response
<ide> *
<ide> * @return void
<add> * @deprected 3.4.0 Use withDisabledCache() instead.
<ide> */
<ide> public function disableCache()
<ide> {
<ide> public function disableCache()
<ide> $this->_setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
<ide> }
<ide>
<add> /**
<add> * Create a new instance with headers to instruct the client to not cache the response
<add> *
<add> * @return static
<add> */
<add> public function withDisabledCache()
<add> {
<add> return $this->withHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT')
<add> ->withHeader('Last-Modified', gmdate("D, d M Y H:i:s") . " GMT")
<add> ->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
<add> }
<add>
<ide> /**
<ide> * Sets the correct headers to instruct the client to cache the response.
<ide> *
<ide><path>tests/TestCase/Network/ResponseTest.php
<ide> public function testDisableCache()
<ide> $this->assertEquals($expected, $response->header());
<ide> }
<ide>
<add> /**
<add> * Tests the withDisabledCache method
<add> *
<add> * @return void
<add> */
<add> public function testWithDisabledCache()
<add> {
<add> $response = new Response();
<add> $expected = [
<add> 'Expires' => ['Mon, 26 Jul 1997 05:00:00 GMT'],
<add> 'Last-Modified' => [gmdate("D, d M Y H:i:s") . " GMT"],
<add> 'Cache-Control' => ['no-store, no-cache, must-revalidate, post-check=0, pre-check=0'],
<add> 'Content-Type' => ['text/html; charset=UTF-8'],
<add> ];
<add> $new = $response->withDisabledCache();
<add> $this->assertFalse($response->hasHeader('Expires'), 'Old instance not mutated.');
<add>
<add> $this->assertEquals($expected, $new->getHeaders());
<add> }
<add>
<ide> /**
<ide> * Tests the cache method
<ide> * | 2 |
Mixed | Python | improve control of training progress and logging | db419f6b2f31f603484d8cce2587f5fc2ad31825 | <ide><path>spacy/cli/train.py
<ide> from wasabi import msg
<ide> import typer
<ide> import logging
<add>import sys
<ide>
<ide> from ._util import app, Arg, Opt, parse_config_overrides, show_validation_error
<ide> from ._util import import_code, setup_gpu
<ide> def train_cli(
<ide> DOCS: https://nightly.spacy.io/api/cli#train
<ide> """
<ide> util.logger.setLevel(logging.DEBUG if verbose else logging.INFO)
<del> verify_cli_args(config_path, output_path)
<add> # Make sure all files and paths exists if they are needed
<add> if not config_path or not config_path.exists():
<add> msg.fail("Config file not found", config_path, exits=1)
<add> if output_path is not None and not output_path.exists():
<add> output_path.mkdir()
<add> msg.good(f"Created output directory: {output_path}")
<ide> overrides = parse_config_overrides(ctx.args)
<ide> import_code(code_path)
<ide> setup_gpu(use_gpu)
<ide> def train_cli(
<ide> nlp = init_nlp(config, use_gpu=use_gpu)
<ide> msg.good("Initialized pipeline")
<ide> msg.divider("Training pipeline")
<del> train(nlp, output_path, use_gpu=use_gpu, silent=False)
<del>
<del>
<del>def verify_cli_args(config_path: Path, output_path: Optional[Path] = None) -> None:
<del> # Make sure all files and paths exists if they are needed
<del> if not config_path or not config_path.exists():
<del> msg.fail("Config file not found", config_path, exits=1)
<del> if output_path is not None:
<del> if not output_path.exists():
<del> output_path.mkdir()
<del> msg.good(f"Created output directory: {output_path}")
<add> train(nlp, output_path, use_gpu=use_gpu, stdout=sys.stdout, stderr=sys.stderr)
<ide><path>spacy/training/initialize.py
<ide> def load_vectors_into_model(
<ide> "with the packaged vectors. Make sure that the vectors package you're "
<ide> "loading is compatible with the current version of spaCy."
<ide> )
<del> err = ConfigValidationError.from_error(config=None, title=title, desc=desc)
<add> err = ConfigValidationError.from_error(e, config=None, title=title, desc=desc)
<ide> raise err from None
<ide> nlp.vocab.vectors = vectors_nlp.vocab.vectors
<ide> if add_strings:
<ide><path>spacy/training/loggers.py
<del>from typing import Dict, Any, Tuple, Callable, List
<add>from typing import TYPE_CHECKING, Dict, Any, Tuple, Callable, List, Optional, IO
<add>import wasabi
<add>import tqdm
<add>import sys
<ide>
<ide> from ..util import registry
<ide> from .. import util
<ide> from ..errors import Errors
<del>from wasabi import msg
<ide>
<ide>
<ide> @registry.loggers("spacy.ConsoleLogger.v1")
<del>def console_logger():
<add>def console_logger(progress_bar: bool=False):
<ide> def setup_printer(
<ide> nlp: "Language",
<del> ) -> Tuple[Callable[[Dict[str, Any]], None], Callable]:
<add> stdout: IO=sys.stdout,
<add> stderr: IO=sys.stderr
<add> ) -> Tuple[Callable[[Optional[Dict[str, Any]]], None], Callable]:
<add> msg = wasabi.Printer(no_print=True)
<ide> # we assume here that only components are enabled that should be trained & logged
<ide> logged_pipes = nlp.pipe_names
<add> eval_frequency = nlp.config["training"]["eval_frequency"]
<ide> score_weights = nlp.config["training"]["score_weights"]
<ide> score_cols = [col for col, value in score_weights.items() if value is not None]
<ide> score_widths = [max(len(col), 6) for col in score_cols]
<ide> def setup_printer(
<ide> table_header = [col.upper() for col in table_header]
<ide> table_widths = [3, 6] + loss_widths + score_widths + [6]
<ide> table_aligns = ["r" for _ in table_widths]
<del> msg.row(table_header, widths=table_widths)
<del> msg.row(["-" * width for width in table_widths])
<add> stdout.write(msg.row(table_header, widths=table_widths))
<add> stdout.write(msg.row(["-" * width for width in table_widths]))
<add> progress = None
<add>
<add> def log_step(info: Optional[Dict[str, Any]]):
<add> nonlocal progress
<ide>
<del> def log_step(info: Dict[str, Any]):
<add> if info is None:
<add> # If we don't have a new checkpoint, just return.
<add> if progress is not None:
<add> progress.update(1)
<add> return
<ide> try:
<ide> losses = [
<ide> "{0:.2f}".format(float(info["losses"][pipe_name]))
<ide> def log_step(info: Dict[str, Any]):
<ide> keys=list(info["losses"].keys()),
<ide> )
<ide> ) from None
<add>
<ide> scores = []
<ide> for col in score_cols:
<ide> score = info["other_scores"].get(col, 0.0)
<ide> try:
<ide> score = float(score)
<del> if col != "speed":
<del> score *= 100
<del> scores.append("{0:.2f}".format(score))
<ide> except TypeError:
<ide> err = Errors.E916.format(name=col, score_type=type(score))
<ide> raise ValueError(err) from None
<add> if col != "speed":
<add> score *= 100
<add> scores.append("{0:.2f}".format(score))
<add>
<ide> data = (
<ide> [info["epoch"], info["step"]]
<ide> + losses
<ide> + scores
<ide> + ["{0:.2f}".format(float(info["score"]))]
<ide> )
<del> msg.row(data, widths=table_widths, aligns=table_aligns)
<add> if progress is not None:
<add> progress.close()
<add> stdout.write(msg.row(data, widths=table_widths, aligns=table_aligns))
<add> if progress_bar:
<add> # Set disable=None, so that it disables on non-TTY
<add> progress = tqdm.tqdm(
<add> total=eval_frequency,
<add> disable=None,
<add> leave=False,
<add> file=stderr
<add> )
<add> progress.set_description(f"Epoch {info['epoch']+1}")
<ide>
<ide> def finalize():
<ide> pass
<ide> def finalize():
<ide> def wandb_logger(project_name: str, remove_config_values: List[str] = []):
<ide> import wandb
<ide>
<del> console = console_logger()
<add> console = console_logger(progress_bar=False)
<ide>
<ide> def setup_logger(
<ide> nlp: "Language",
<add> stdout: IO=sys.stdout,
<add> stderr: IO=sys.stderr
<ide> ) -> Tuple[Callable[[Dict[str, Any]], None], Callable]:
<ide> config = nlp.config.interpolate()
<ide> config_dot = util.dict_to_dot(config)
<ide> for field in remove_config_values:
<ide> del config_dot[field]
<ide> config = util.dot_to_dict(config_dot)
<ide> wandb.init(project=project_name, config=config, reinit=True)
<del> console_log_step, console_finalize = console(nlp)
<add> console_log_step, console_finalize = console(nlp, stdout, stderr)
<ide>
<del> def log_step(info: Dict[str, Any]):
<add> def log_step(info: Optional[Dict[str, Any]]):
<ide> console_log_step(info)
<del> score = info["score"]
<del> other_scores = info["other_scores"]
<del> losses = info["losses"]
<del> wandb.log({"score": score})
<del> if losses:
<del> wandb.log({f"loss_{k}": v for k, v in losses.items()})
<del> if isinstance(other_scores, dict):
<del> wandb.log(other_scores)
<add> if info is not None:
<add> score = info["score"]
<add> other_scores = info["other_scores"]
<add> losses = info["losses"]
<add> wandb.log({"score": score})
<add> if losses:
<add> wandb.log({f"loss_{k}": v for k, v in losses.items()})
<add> if isinstance(other_scores, dict):
<add> wandb.log(other_scores)
<ide>
<ide> def finalize():
<ide> console_finalize()
<ide><path>spacy/training/loop.py
<del>from typing import List, Callable, Tuple, Dict, Iterable, Iterator, Union, Any
<add>from typing import List, Callable, Tuple, Dict, Iterable, Iterator, Union, Any, IO
<ide> from typing import Optional, TYPE_CHECKING
<ide> from pathlib import Path
<ide> from timeit import default_timer as timer
<ide> from thinc.api import Optimizer, Config, constant, fix_random_seed, set_gpu_allocator
<ide> import random
<del>import tqdm
<del>from wasabi import Printer
<add>import wasabi
<add>import sys
<ide>
<ide> from .example import Example
<ide> from ..schemas import ConfigSchemaTraining
<ide> def train(
<ide> output_path: Optional[Path] = None,
<ide> *,
<ide> use_gpu: int = -1,
<del> silent: bool = False,
<add> stdout: IO=sys.stdout,
<add> stderr: IO=sys.stderr
<ide> ) -> None:
<ide> """Train a pipeline.
<ide>
<ide> nlp (Language): The initialized nlp object with the full config.
<ide> output_path (Path): Optional output path to save trained model to.
<ide> use_gpu (int): Whether to train on GPU. Make sure to call require_gpu
<ide> before calling this function.
<del> silent (bool): Whether to pretty-print outputs.
<add> stdout (file): A file-like object to write output messages. To disable
<add> printing, set to io.StringIO.
<add> stderr (file): A second file-like object to write output messages. To disable
<add> printing, set to io.StringIO.
<add>
<ide> RETURNS (Path / None): The path to the final exported model.
<ide> """
<del> msg = Printer(no_print=silent)
<add> # We use no_print here so we can respect the stdout/stderr options.
<add> msg = wasabi.Printer(no_print=True)
<ide> # Create iterator, which yields out info after each optimization step.
<ide> config = nlp.config.interpolate()
<ide> if config["training"]["seed"] is not None:
<ide> def train(
<ide> eval_frequency=T["eval_frequency"],
<ide> exclude=frozen_components,
<ide> )
<del> msg.info(f"Pipeline: {nlp.pipe_names}")
<add> stdout.write(msg.info(f"Pipeline: {nlp.pipe_names}"))
<ide> if frozen_components:
<del> msg.info(f"Frozen components: {frozen_components}")
<del> msg.info(f"Initial learn rate: {optimizer.learn_rate}")
<add> stdout.write(msg.info(f"Frozen components: {frozen_components}"))
<add> stdout.write(msg.info(f"Initial learn rate: {optimizer.learn_rate}"))
<ide> with nlp.select_pipes(disable=frozen_components):
<del> print_row, finalize_logger = train_logger(nlp)
<add> log_step, finalize_logger = train_logger(nlp, stdout, stderr)
<ide> try:
<del> progress = tqdm.tqdm(total=T["eval_frequency"], leave=False)
<del> progress.set_description(f"Epoch 1")
<ide> for batch, info, is_best_checkpoint in training_step_iterator:
<del> progress.update(1)
<del> if is_best_checkpoint is not None:
<del> progress.close()
<del> print_row(info)
<del> if is_best_checkpoint and output_path is not None:
<del> with nlp.select_pipes(disable=frozen_components):
<del> update_meta(T, nlp, info)
<del> with nlp.use_params(optimizer.averages):
<del> nlp = before_to_disk(nlp)
<del> nlp.to_disk(output_path / "model-best")
<del> progress = tqdm.tqdm(total=T["eval_frequency"], leave=False)
<del> progress.set_description(f"Epoch {info['epoch']}")
<add> log_step(info if is_best_checkpoint else None)
<add> if is_best_checkpoint is not None and output_path is not None:
<add> with nlp.select_pipes(disable=frozen_components):
<add> update_meta(T, nlp, info)
<add> with nlp.use_params(optimizer.averages):
<add> nlp = before_to_disk(nlp)
<add> nlp.to_disk(output_path / "model-best")
<ide> except Exception as e:
<del> finalize_logger()
<ide> if output_path is not None:
<ide> # We don't want to swallow the traceback if we don't have a
<del> # specific error.
<del> msg.warn(
<del> f"Aborting and saving the final best model. "
<del> f"Encountered exception: {str(e)}"
<add> # specific error, but we do want to warn that we're trying
<add> # to do something here.
<add> stdout.write(
<add> msg.warn(
<add> f"Aborting and saving the final best model. "
<add> f"Encountered exception: {str(e)}"
<add> )
<ide> )
<del> nlp = before_to_disk(nlp)
<del> nlp.to_disk(output_path / "model-final")
<ide> raise e
<ide> finally:
<ide> finalize_logger()
<ide> if output_path is not None:
<del> final_model_path = output_path / "model-final"
<add> final_model_path = output_path / "model-last"
<ide> if optimizer.averages:
<ide> with nlp.use_params(optimizer.averages):
<ide> nlp.to_disk(final_model_path)
<ide> else:
<ide> nlp.to_disk(final_model_path)
<del> msg.good(f"Saved pipeline to output directory", final_model_path)
<add> # This will only run if we don't hit an error
<add> stdout.write(msg.good("Saved pipeline to output directory", final_model_path))
<ide>
<ide>
<ide> def train_while_improving(
<ide><path>website/docs/usage/training.md
<ide> During training, the results of each step are passed to a logger function. By
<ide> default, these results are written to the console with the
<ide> [`ConsoleLogger`](/api/top-level#ConsoleLogger). There is also built-in support
<ide> for writing the log files to [Weights & Biases](https://www.wandb.com/) with the
<del>[`WandbLogger`](/api/top-level#WandbLogger). The logger function receives a
<del>**dictionary** with the following keys:
<add>[`WandbLogger`](/api/top-level#WandbLogger). On each step, the logger function
<add>receives a **dictionary** with the following keys:
<ide>
<ide> | Key | Value |
<ide> | -------------- | ---------------------------------------------------------------------------------------------- |
<ide> tabular results to a file:
<ide>
<ide> ```python
<ide> ### functions.py
<del>from typing import Tuple, Callable, Dict, Any
<add>import sys
<add>from typing import IO, Tuple, Callable, Dict, Any
<ide> import spacy
<add>from spacy import Language
<ide> from pathlib import Path
<ide>
<ide> @spacy.registry.loggers("my_custom_logger.v1")
<ide> def custom_logger(log_path):
<del> def setup_logger(nlp: "Language") -> Tuple[Callable, Callable]:
<del> with Path(log_path).open("w", encoding="utf8") as file_:
<del> file_.write("step\\t")
<del> file_.write("score\\t")
<del> for pipe in nlp.pipe_names:
<del> file_.write(f"loss_{pipe}\\t")
<del> file_.write("\\n")
<del>
<del> def log_step(info: Dict[str, Any]):
<del> with Path(log_path).open("a") as file_:
<del> file_.write(f"{info['step']}\\t")
<del> file_.write(f"{info['score']}\\t")
<add> def setup_logger(
<add> nlp: Language,
<add> stdout: IO=sys.stdout,
<add> stderr: IO=sys.stderr
<add> ) -> Tuple[Callable, Callable]:
<add> stdout.write(f"Logging to {log_path}\n")
<add> log_file = Path(log_path).open("w", encoding="utf8")
<add> log_file.write("step\\t")
<add> log_file.write("score\\t")
<add> for pipe in nlp.pipe_names:
<add> log_file.write(f"loss_{pipe}\\t")
<add> log_file.write("\\n")
<add>
<add> def log_step(info: Optional[Dict[str, Any]]):
<add> if info:
<add> log_file.write(f"{info['step']}\\t")
<add> log_file.write(f"{info['score']}\\t")
<ide> for pipe in nlp.pipe_names:
<del> file_.write(f"{info['losses'][pipe]}\\t")
<del> file_.write("\\n")
<add> log_file.write(f"{info['losses'][pipe]}\\t")
<add> log_file.write("\\n")
<ide>
<ide> def finalize():
<del> pass
<add> log_file.close()
<ide>
<ide> return log_step, finalize
<ide> | 5 |
Javascript | Javascript | remove redundant texture binds | 77c7364298361a55deae254e185f1a083e7826be | <ide><path>src/renderers/WebGLRenderer.js
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> }
<ide>
<del> _gl.activeTexture( _gl.TEXTURE0 + slot );
<del> _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
<add> state.activeTexture( _gl.TEXTURE0 + slot );
<add> state.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
<ide>
<ide> _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
<ide> _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> }
<ide>
<del> _gl.activeTexture( _gl.TEXTURE0 + slot );
<del> _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
<add> state.activeTexture( _gl.TEXTURE0 + slot );
<add> state.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
<ide>
<ide> };
<ide>
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> }
<ide>
<del> _gl.activeTexture( _gl.TEXTURE0 + slot );
<del> _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
<add> state.activeTexture( _gl.TEXTURE0 + slot );
<add> state.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
<ide>
<ide> _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
<ide>
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> } else {
<ide>
<del> _gl.activeTexture( _gl.TEXTURE0 + slot );
<del> _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
<add> state.activeTexture( _gl.TEXTURE0 + slot );
<add> state.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
<ide>
<ide> }
<ide>
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> function setCubeTextureDynamic ( texture, slot ) {
<ide>
<del> _gl.activeTexture( _gl.TEXTURE0 + slot );
<del> _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
<add> state.activeTexture( _gl.TEXTURE0 + slot );
<add> state.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
<ide>
<ide> }
<ide>
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide> renderTarget.__webglFramebuffer = [];
<ide> renderTarget.__webglRenderbuffer = [];
<ide>
<del> _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
<add> state.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
<add>
<ide> setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
<ide>
<ide> for ( var i = 0; i < 6; i ++ ) {
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> }
<ide>
<del> _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
<add> state.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
<ide> setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
<ide>
<ide> _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> if ( isCube ) {
<ide>
<del> _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
<add> state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
<ide>
<ide> } else {
<ide>
<del> _gl.bindTexture( _gl.TEXTURE_2D, null );
<add> state.bindTexture( _gl.TEXTURE_2D, null );
<ide>
<ide> }
<ide>
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
<ide>
<del> _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
<add> state.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
<ide> _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
<del> _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
<add> state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
<ide>
<ide> } else {
<ide>
<del> _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
<add> state.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
<ide> _gl.generateMipmap( _gl.TEXTURE_2D );
<del> _gl.bindTexture( _gl.TEXTURE_2D, null );
<add> state.bindTexture( _gl.TEXTURE_2D, null );
<ide>
<ide> }
<ide>
<ide><path>src/renderers/webgl/WebGLState.js
<ide>
<ide> THREE.WebGLState = function ( gl, paramThreeToGL ) {
<ide>
<add> var _this = this;
<add>
<ide> var newAttributes = new Uint8Array( 16 );
<ide> var enabledAttributes = new Uint8Array( 16 );
<ide>
<ide> THREE.WebGLState = function ( gl, paramThreeToGL ) {
<ide> var currentPolygonOffsetFactor = null;
<ide> var currentPolygonOffsetUnits = null;
<ide>
<add> var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
<add>
<add> var currentTextureSlot = undefined;
<add> var currentBoundTextures = {};
<add>
<ide> this.initAttributes = function () {
<ide>
<ide> for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
<ide> THREE.WebGLState = function ( gl, paramThreeToGL ) {
<ide>
<ide> };
<ide>
<add> this.activeTexture = function ( webglSlot ) {
<add>
<add> if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
<add>
<add> if ( currentTextureSlot !== webglSlot ) {
<add>
<add> gl.activeTexture( webglSlot );
<add> currentTextureSlot = webglSlot;
<add>
<add> }
<add>
<add> }
<add>
<add> this.bindTexture = function ( webglType, webglTexture ) {
<add>
<add> if ( currentTextureSlot === undefined ) {
<add>
<add> _this.activeTexture();
<add>
<add> }
<add>
<add> var boundTexture = currentBoundTextures[currentTextureSlot];
<add>
<add> if ( boundTexture === undefined ) {
<add>
<add> boundTexture = { type: undefined, texture: undefined };
<add> currentBoundTextures[currentTextureSlot] = boundTexture;
<add>
<add> }
<add>
<add> if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
<add>
<add> gl.bindTexture( webglType, webglTexture );
<add>
<add> boundTexture.type = webglType;
<add> boundTexture.texture = webglTexture;
<add>
<add> }
<add>
<add> }
<add>
<ide> this.reset = function () {
<ide>
<ide> for ( var i = 0; i < enabledAttributes.length; i ++ ) {
<ide><path>src/renderers/webgl/plugins/LensFlarePlugin.js
<ide> THREE.LensFlarePlugin = function ( renderer, flares ) {
<ide> tempTexture = gl.createTexture();
<ide> occlusionTexture = gl.createTexture();
<ide>
<del> gl.bindTexture( gl.TEXTURE_2D, tempTexture );
<add> renderer.state.bindTexture( gl.TEXTURE_2D, tempTexture );
<ide> gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
<ide> gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
<ide> gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
<ide> gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
<ide> gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
<ide>
<del> gl.bindTexture( gl.TEXTURE_2D, occlusionTexture );
<add> renderer.state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
<ide> gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
<ide> gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
<ide> gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
<ide> THREE.LensFlarePlugin = function ( renderer, flares ) {
<ide>
<ide> // save current RGB to temp texture
<ide>
<del> gl.activeTexture( gl.TEXTURE1 );
<del> gl.bindTexture( gl.TEXTURE_2D, tempTexture );
<add> renderer.state.activeTexture( gl.TEXTURE1 );
<add> renderer.state.bindTexture( gl.TEXTURE_2D, tempTexture );
<ide> gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
<ide>
<ide>
<ide> THREE.LensFlarePlugin = function ( renderer, flares ) {
<ide>
<ide> // copy result to occlusionMap
<ide>
<del> gl.activeTexture( gl.TEXTURE0 );
<del> gl.bindTexture( gl.TEXTURE_2D, occlusionTexture );
<add> renderer.state.activeTexture( gl.TEXTURE0 );
<add> renderer.state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
<ide> gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
<ide>
<ide>
<ide> THREE.LensFlarePlugin = function ( renderer, flares ) {
<ide> gl.uniform1i( uniforms.renderType, 1 );
<ide> gl.disable( gl.DEPTH_TEST );
<ide>
<del> gl.activeTexture( gl.TEXTURE1 );
<del> gl.bindTexture( gl.TEXTURE_2D, tempTexture );
<add> renderer.state.activeTexture( gl.TEXTURE1 );
<add> renderer.state.bindTexture( gl.TEXTURE_2D, tempTexture );
<ide> gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
<ide>
<ide>
<ide><path>src/renderers/webgl/plugins/SpritePlugin.js
<ide> THREE.SpritePlugin = function ( renderer, sprites ) {
<ide>
<ide> gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
<ide>
<del> gl.activeTexture( gl.TEXTURE0 );
<add> renderer.state.activeTexture( gl.TEXTURE0 );
<ide> gl.uniform1i( uniforms.map, 0 );
<ide>
<ide> var oldFogType = 0; | 4 |
PHP | PHP | fix two typos | 881c6582c58a3bcea69bf4f16e6f1c1539d94661 | <ide><path>src/Illuminate/Database/Capsule/Manager.php
<ide> public function __construct(Container $container = null)
<ide>
<ide> // Once we have the container setup, we will setup the default configuration
<ide> // options in the container "config" binding. This will make the database
<del> // manager behave correctly since all the correct binding are in place.
<add> // manager behave correctly since all the correct bindings are in place.
<ide> $this->setupDefaultConfiguration();
<ide>
<ide> $this->setupManager();
<ide> public function bootEloquent()
<ide>
<ide> // If we have an event dispatcher instance, we will go ahead and register it
<ide> // with the Eloquent ORM, allowing for model callbacks while creating and
<del> // updating "model" instances; however, if it not necessary to operate.
<add> // updating "model" instances; however, it is not necessary to operate.
<ide> if ($dispatcher = $this->getEventDispatcher()) {
<ide> Eloquent::setEventDispatcher($dispatcher);
<ide> } | 1 |
Ruby | Ruby | ignore empty `patch` blocks | 94138c0848d586fbe9c76327a45069036642b0fb | <ide><path>Library/Homebrew/software_spec.rb
<ide> def recursive_requirements
<ide>
<ide> def patch(strip = :p1, src = nil, &block)
<ide> p = Patch.create(strip, src, &block)
<add> return if p.is_a?(ExternalPatch) && p.url.blank?
<add>
<ide> dependency_collector.add(p.resource) if p.is_a? ExternalPatch
<ide> patches << p
<ide> end
<ide><path>Library/Homebrew/test/software_spec_spec.rb
<ide> expect(spec.patches.count).to eq(1)
<ide> expect(spec.patches.first.strip).to eq(:p1)
<ide> end
<add>
<add> it "doesn't add a patch with no url" do
<add> spec.patch do
<add> sha256 "7852a7a365f518b12a1afd763a6a80ece88ac7aeea3c9023aa6c1fe46ac5a1ae"
<add> end
<add> expect(spec.patches.empty?).to be true
<add> end
<ide> end
<ide> end | 2 |
Go | Go | simplify code by using sendwpipe utility | 29ddf2be1e9b9349865e3d0f34b1d4fc0b960ee3 | <ide><path>pkg/beam/examples/beamsh/beamsh.go
<ide> func GetHandler(name string) Handler {
<ide> if attachment == nil {
<ide> continue
<ide> }
<del> r, w, err := os.Pipe()
<add> w, err := sendWPipe(out, payload)
<ide> if err != nil {
<del> attachment.Close()
<del> return
<del> }
<del> if err := beam.Send(out, payload, r); err != nil {
<del> attachment.Close()
<del> r.Close()
<del> w.Close()
<ide> fmt.Fprintf(stderr, "%v\n", err)
<add> attachment.Close()
<ide> return
<ide> }
<ide> tasks.Add(1)
<ide> func GetHandler(name string) Handler {
<ide> } else if name == "exec" {
<ide> return func(args []string, in *net.UnixConn, out *net.UnixConn) {
<ide> cmd := exec.Command(args[1], args[2:]...)
<del> outR, outW, err := os.Pipe()
<add> stdout, err := sendWPipe(out, data.Empty().Set("cmd", "log", "stdout").Set("fromcmd", args...).Bytes())
<ide> if err != nil {
<ide> return
<ide> }
<del> cmd.Stdout = outW
<del> errR, errW, err := os.Pipe()
<add> defer stdout.Close()
<add> cmd.Stdout = stdout
<add> stderr, err := sendWPipe(out, data.Empty().Set("cmd", "log", "stderr").Set("fromcmd", args...).Bytes())
<ide> if err != nil {
<ide> return
<ide> }
<del> cmd.Stderr = errW
<add> defer stderr.Close()
<add> cmd.Stderr = stderr
<ide> cmd.Stdin = os.Stdin
<del> beam.Send(out, data.Empty().Set("cmd", "log", "stdout").Set("fromcmd", args...).Bytes(), outR)
<del> beam.Send(out, data.Empty().Set("cmd", "log", "stderr").Set("fromcmd", args...).Bytes(), errR)
<ide> execErr := cmd.Run()
<ide> var status string
<ide> if execErr != nil {
<ide> func GetHandler(name string) Handler {
<ide> status = "ok"
<ide> }
<ide> beam.Send(out, data.Empty().Set("status", status).Set("cmd", args...).Bytes(), nil)
<del> outW.Close()
<del> errW.Close()
<ide> }
<ide> } else if name == "trace" {
<ide> return func(args []string, in *net.UnixConn, out *net.UnixConn) { | 1 |
Mixed | Javascript | remove html legend that is mostly unsupported. | e96ad6f2491db9e7a94f734ca09330b296d47f52 | <ide><path>docs/configuration/legend.md
<ide> var chart = new Chart(ctx, {
<ide> ```
<ide>
<ide> Now when you click the legend in this chart, the visibility of the first two datasets will be linked together.
<del>
<del>## HTML Legends
<del>
<del>Sometimes you need a very complex legend. In these cases, it makes sense to generate an HTML legend. Charts provide a `generateLegend()` method on their prototype that returns an HTML string for the legend.
<del>
<del>To configure how this legend is generated, you can change the `legendCallback` config property.
<del>
<del>```javascript
<del>var chart = new Chart(ctx, {
<del> type: 'line',
<del> data: data,
<del> options: {
<del> legendCallback: function(chart) {
<del> // Return the HTML string here.
<del> }
<del> }
<del>});
<del>```
<del>
<del>Note that legendCallback is not called automatically and you must call `generateLegend()` yourself in code when creating a legend using this method.
<ide><path>docs/developers/api.md
<ide> myLineChart.toBase64Image();
<ide> // => returns png data url of the image on the canvas
<ide> ```
<ide>
<del>## .generateLegend()
<del>
<del>Returns an HTML string of a legend for that chart. The legend is generated from the `legendCallback` in the options.
<del>
<del>```javascript
<del>myLineChart.generateLegend();
<del>// => returns HTML string of a legend for this chart
<del>```
<del>
<ide> ## .getElementAtEvent(e)
<ide>
<ide> Calling `getElementAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the single element at the event position. If there are multiple items within range, only the first is returned. The value returned from this method is an array with a single parameter. An array is used to keep a consistent API between the `get*AtEvent` methods.
<ide><path>docs/getting-started/v3-migration.md
<ide> Animation system was completely rewritten in Chart.js v3. Each property can now
<ide>
<ide> * `Chart.chart.chart`
<ide> * `Chart.Controller`
<add>* `Chart.prototype.generateLegend`
<ide> * `Chart.types`
<ide> * `DatasetController.addElementAndReset`
<ide> * `DatasetController.createMetaData`
<ide><path>src/controllers/controller.doughnut.js
<ide> defaults._set('doughnut', {
<ide> // Boolean - Whether we animate scaling the Doughnut from the centre
<ide> animateScale: false
<ide> },
<del> legendCallback: function(chart) {
<del> var list = document.createElement('ul');
<del> var data = chart.data;
<del> var datasets = data.datasets;
<del> var labels = data.labels;
<del> var i, ilen, listItem, listItemSpan;
<del>
<del> list.setAttribute('class', chart.id + '-legend');
<del> if (datasets.length) {
<del> for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
<del> listItem = list.appendChild(document.createElement('li'));
<del> listItemSpan = listItem.appendChild(document.createElement('span'));
<del> listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
<del> if (labels[i]) {
<del> listItem.appendChild(document.createTextNode(labels[i]));
<del> }
<del> }
<del> }
<del>
<del> return list.outerHTML;
<del> },
<ide> legend: {
<ide> labels: {
<ide> generateLabels: function(chart) {
<ide><path>src/controllers/controller.polarArea.js
<ide> defaults._set('polarArea', {
<ide> },
<ide>
<ide> startAngle: -0.5 * Math.PI,
<del> legendCallback: function(chart) {
<del> var list = document.createElement('ul');
<del> var data = chart.data;
<del> var datasets = data.datasets;
<del> var labels = data.labels;
<del> var i, ilen, listItem, listItemSpan;
<del>
<del> list.setAttribute('class', chart.id + '-legend');
<del> if (datasets.length) {
<del> for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
<del> listItem = list.appendChild(document.createElement('li'));
<del> listItemSpan = listItem.appendChild(document.createElement('span'));
<del> listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
<del> if (labels[i]) {
<del> listItem.appendChild(document.createTextNode(labels[i]));
<del> }
<del> }
<del> }
<del>
<del> return list.outerHTML;
<del> },
<ide> legend: {
<ide> labels: {
<ide> generateLabels: function(chart) {
<ide><path>src/core/core.controller.js
<ide> class Chart {
<ide> return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
<ide> }
<ide>
<del> generateLegend() {
<del> return this.options.legendCallback(this);
<del> }
<del>
<ide> /**
<ide> * @private
<ide> */
<ide><path>src/plugins/plugin.legend.js
<ide> defaults._set('global', {
<ide> }, this);
<ide> }
<ide> }
<del> },
<del>
<del> legendCallback: function(chart) {
<del> var list = document.createElement('ul');
<del> var datasets = chart.data.datasets;
<del> var i, ilen, listItem, listItemSpan;
<del>
<del> list.setAttribute('class', chart.id + '-legend');
<del>
<del> for (i = 0, ilen = datasets.length; i < ilen; i++) {
<del> listItem = list.appendChild(document.createElement('li'));
<del> listItemSpan = listItem.appendChild(document.createElement('span'));
<del> listItemSpan.style.backgroundColor = datasets[i].backgroundColor;
<del> if (datasets[i].label) {
<del> listItem.appendChild(document.createTextNode(datasets[i].label));
<del> }
<del> }
<del>
<del> return list.outerHTML;
<ide> }
<ide> });
<ide>
<ide><path>test/specs/global.defaults.tests.js
<ide> describe('Default Configs', function() {
<ide> }]);
<ide> });
<ide>
<del> it('should return the correct html legend', function() {
<del> var config = Chart.defaults.doughnut;
<del> var chart = window.acquireChart({
<del> type: 'doughnut',
<del> data: {
<del> labels: ['label1', 'label2'],
<del> datasets: [{
<del> data: [10, 20],
<del> backgroundColor: ['red', 'green']
<del> }]
<del> },
<del> options: config
<del> });
<del>
<del> var expectedLegend = '<ul class="' + chart.id + '-legend"><li><span style="background-color: red;"></span>label1</li><li><span style="background-color: green;"></span>label2</li></ul>';
<del> expect(chart.generateLegend()).toBe(expectedLegend);
<del> });
<del>
<ide> it('should return correct legend label objects', function() {
<ide> var config = Chart.defaults.doughnut;
<ide> var chart = window.acquireChart({
<ide> describe('Default Configs', function() {
<ide> }]);
<ide> });
<ide>
<del> it('should return the correct html legend', function() {
<del> var config = Chart.defaults.polarArea;
<del> var chart = window.acquireChart({
<del> type: 'polarArea',
<del> data: {
<del> labels: ['label1', 'label2'],
<del> datasets: [{
<del> data: [10, 20],
<del> backgroundColor: ['red', 'green']
<del> }]
<del> },
<del> options: config
<del> });
<del>
<del> var expectedLegend = '<ul class="' + chart.id + '-legend"><li><span style="background-color: red;"></span>label1</li><li><span style="background-color: green;"></span>label2</li></ul>';
<del> expect(chart.generateLegend()).toBe(expectedLegend);
<del> });
<del>
<ide> it('should return correct legend label objects', function() {
<ide> var config = Chart.defaults.polarArea;
<ide> var chart = window.acquireChart({ | 8 |
Python | Python | address feedback from previous commit | 0a00ad98e6216d2845a5dfb9e144e903b2f4f245 | <ide><path>celery/beat.py
<ide> def tick(self, event_t=event_t, min=min, heappop=heapq.heappop,
<ide> return min(adjust(next_time_to_run) or max_interval, max_interval)
<ide>
<ide> def schedules_equal(self, a, b):
<del> if a.keys() != b.keys():
<add> if set(a.keys()) != set(b.keys()):
<ide> return False
<ide> for name, model in a.items():
<ide> b_model = b.get(name)
<ide> if not b_model:
<ide> return False
<del> if (hasattr(model.schedule, '__repr__') and
<del> model.schedule.__repr__() != b_model.schedule.__repr__()):
<add> if model.schedule != b_model.schedule:
<ide> return False
<ide> return True
<ide> | 1 |
Text | Text | show images in next_frame_prediction/readme.md | 3d5ab03cab36814d8b1af81b3fcf98e32c3bf0df | <ide><path>next_frame_prediction/README.md
<ide> Authors: Xin Pan (Github: panyx0718), Anelia Angelova
<ide>
<ide> <b>Results:</b>
<ide>
<del><left>
<ide> 
<del></left>
<del><left>
<ide> 
<del></left>
<del>
<del><left>
<ide> 
<del></left>
<ide>
<ide>
<ide> <b>Prerequisite:</b> | 1 |
Javascript | Javascript | update the `repl` for the new `readline` behavior | 327286dbcdd91b9a6c983cdf307e36ac36acf05d | <ide><path>lib/repl.js
<ide> function REPLServer(prompt, stream, eval, useGlobal, ignoreUndefined) {
<ide>
<ide> rli.setPrompt(self.prompt);
<ide>
<del> rli.on('end', function() {
<add> rli.on('close', function() {
<ide> self.emit('exit');
<ide> });
<ide>
<ide> function REPLServer(prompt, stream, eval, useGlobal, ignoreUndefined) {
<ide>
<ide> if (!(self.bufferedCommand && self.bufferedCommand.length > 0) && empty) {
<ide> if (sawSIGINT) {
<del> rli.pause();
<del> self.emit('exit');
<add> rli.close();
<ide> sawSIGINT = false;
<ide> return;
<ide> }
<ide> function defineDefaultCommands(repl) {
<ide> repl.defineCommand('exit', {
<ide> help: 'Exit the repl',
<ide> action: function() {
<del> this.rli.pause();
<del> this.emit('exit');
<add> this.rli.close();
<ide> }
<ide> });
<ide> | 1 |
PHP | PHP | fix routing pipeline | 7573abf0202cac49aa626d2186091f45097fff17 | <ide><path>src/Illuminate/Pipeline/Pipeline.php
<ide> public function via($method)
<ide> */
<ide> public function then(Closure $destination)
<ide> {
<del> $destination = function ($passable) use ($destination) {
<del> return $destination($passable);
<del> };
<del>
<ide> $pipeline = array_reduce(
<del> array_reverse($this->pipes), $this->carry(), $destination
<add> array_reverse($this->pipes), $this->carry(), $this->prepareDestination($destination)
<ide> );
<ide>
<ide> return $pipeline($this->passable);
<ide> }
<ide>
<add> /**
<add> * Get the final piece of the Closure onion.
<add> *
<add> * @param \Closure $destination
<add> * @return \Closure
<add> */
<add> protected function prepareDestination(Closure $destination)
<add> {
<add> return function ($passable) use ($destination) {
<add> return $destination($passable);
<add> };
<add> }
<add>
<ide> /**
<ide> * Get a Closure that represents a slice of the application onion.
<ide> *
<ide><path>src/Illuminate/Routing/Pipeline.php
<ide> */
<ide> class Pipeline extends BasePipeline
<ide> {
<add> /**
<add> * Get the final piece of the Closure onion.
<add> *
<add> * @param \Closure $destination
<add> * @return \Closure
<add> */
<add> protected function prepareDestination(Closure $destination)
<add> {
<add> return function ($passable) use ($destination) {
<add> try {
<add> return $destination($passable);
<add> } catch (Exception $e) {
<add> return $this->handleException($passable, $e);
<add> } catch (Throwable $e) {
<add> return $this->handleException($passable, new FatalThrowableError($e));
<add> }
<add> };
<add> }
<add>
<ide> /**
<ide> * Get a Closure that represents a slice of the application onion.
<ide> *
<ide> * @return \Closure
<ide> */
<del> protected function getSlice()
<add> protected function carry()
<ide> {
<ide> return function ($stack, $pipe) {
<ide> return function ($passable) use ($stack, $pipe) {
<ide> try {
<del> $slice = parent::getSlice();
<add> $slice = parent::carry();
<add>
<ide> $callable = $slice($stack, $pipe);
<ide>
<ide> return $callable($passable);
<ide> protected function getSlice()
<ide> };
<ide> }
<ide>
<del> /**
<del> * Get the initial slice to begin the stack call.
<del> *
<del> * @param \Closure $destination
<del> * @return \Closure
<del> */
<del> protected function getInitialSlice(Closure $destination)
<del> {
<del> return function ($passable) use ($destination) {
<del> try {
<del> return $destination($passable);
<del> } catch (Exception $e) {
<del> return $this->handleException($passable, $e);
<del> } catch (Throwable $e) {
<del> return $this->handleException($passable, new FatalThrowableError($e));
<del> }
<del> };
<del> }
<del>
<ide> /**
<ide> * Handle the given exception.
<ide> * | 2 |
Java | Java | add all non-file parts as request parameters | 584dabbb3980dbed5272f79a61aa996d390e528c | <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilder.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.test.web.servlet.request;
<ide>
<ide> import java.io.IOException;
<add>import java.io.InputStream;
<ide> import java.io.InputStreamReader;
<ide> import java.net.URI;
<ide> import java.nio.charset.Charset;
<ide> import org.springframework.util.FileCopyUtils;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<del>import org.springframework.web.multipart.MultipartFile;
<ide>
<ide> /**
<ide> * Default builder for {@link MockMultipartHttpServletRequest}.
<ide> public Object merge(@Nullable Object parent) {
<ide> @Override
<ide> protected final MockHttpServletRequest createServletRequest(ServletContext servletContext) {
<ide> MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(servletContext);
<add> Charset defaultCharset = (request.getCharacterEncoding() != null ?
<add> Charset.forName(request.getCharacterEncoding()) : StandardCharsets.UTF_8);
<add>
<ide> this.files.forEach(request::addFile);
<ide> this.parts.values().stream().flatMap(Collection::stream).forEach(part -> {
<ide> request.addPart(part);
<ide> try {
<del> MultipartFile file = asMultipartFile(part);
<del> if (file != null) {
<del> request.addFile(file);
<del> return;
<add> String name = part.getName();
<add> String filename = part.getSubmittedFileName();
<add> InputStream is = part.getInputStream();
<add> if (filename != null) {
<add> request.addFile(new MockMultipartFile(name, filename, part.getContentType(), is));
<ide> }
<del> String value = toParameterValue(part);
<del> if (value != null) {
<del> request.addParameter(part.getName(), toParameterValue(part));
<add> else {
<add> InputStreamReader reader = new InputStreamReader(is, getCharsetOrDefault(part, defaultCharset));
<add> String value = FileCopyUtils.copyToString(reader);
<add> request.addParameter(part.getName(), value);
<ide> }
<ide> }
<ide> catch (IOException ex) {
<ide> throw new IllegalStateException("Failed to read content for part " + part.getName(), ex);
<ide> }
<ide> });
<del> return request;
<del> }
<ide>
<del> @Nullable
<del> private MultipartFile asMultipartFile(Part part) throws IOException {
<del> String name = part.getName();
<del> String filename = part.getSubmittedFileName();
<del> if (filename != null) {
<del> return new MockMultipartFile(name, filename, part.getContentType(), part.getInputStream());
<del> }
<del> return null;
<add> return request;
<ide> }
<ide>
<del> @Nullable
<del> private String toParameterValue(Part part) throws IOException {
<del> String rawType = part.getContentType();
<del> MediaType mediaType = (rawType != null ? MediaType.parseMediaType(rawType) : MediaType.TEXT_PLAIN);
<del> if (!mediaType.isCompatibleWith(MediaType.TEXT_PLAIN)) {
<del> return null;
<add> private Charset getCharsetOrDefault(Part part, Charset defaultCharset) {
<add> if (part.getContentType() != null) {
<add> MediaType mediaType = MediaType.parseMediaType(part.getContentType());
<add> if (mediaType.getCharset() != null) {
<add> return mediaType.getCharset();
<add> }
<ide> }
<del> Charset charset = (mediaType.getCharset() != null ? mediaType.getCharset() : StandardCharsets.UTF_8);
<del> InputStreamReader reader = new InputStreamReader(part.getInputStream(), charset);
<del> return FileCopyUtils.copyToString(reader);
<add> return defaultCharset;
<ide> }
<del>
<ide> }
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilderTests.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> void addFileAndParts() throws Exception {
<ide> assertThat(mockRequest.getParts()).extracting(Part::getName).containsExactly("name");
<ide> }
<ide>
<del> @Test // gh-26261
<add> @Test // gh-26261, gh-26400
<ide> void addFileWithoutFilename() throws Exception {
<ide> MockPart jsonPart = new MockPart("data", "{\"node\":\"node\"}".getBytes(UTF_8));
<ide> jsonPart.getHeaders().setContentType(MediaType.APPLICATION_JSON);
<ide> void addFileWithoutFilename() throws Exception {
<ide> .buildRequest(new MockServletContext());
<ide>
<ide> assertThat(mockRequest.getFileMap()).containsOnlyKeys("file");
<del> assertThat(mockRequest.getParameterMap()).isEmpty();
<add> assertThat(mockRequest.getParameterMap()).hasSize(1);
<add> assertThat(mockRequest.getParameter("data")).isEqualTo("{\"node\":\"node\"}");
<ide> assertThat(mockRequest.getParts()).extracting(Part::getName).containsExactly("data");
<ide> }
<ide> | 2 |
Python | Python | fix issues with undetected fortran compilers | 47478cba842b48c43846d7f343261154b7f16b66 | <ide><path>numpy/distutils/ccompiler.py
<ide> def CCompiler_get_version(self, force=0, ok_status=[0]):
<ide> version_cmd = self.version_cmd
<ide> except AttributeError:
<ide> return None
<del> if not version_cmd or not version_cmd[0]:
<add> if not version_cmd or not version_cmd[0] or None in version_cmd:
<ide> return None
<ide> cmd = ' '.join(version_cmd)
<ide> try:
<ide><path>numpy/distutils/command/build_ext.py
<ide> def run(self):
<ide>
<ide> # Initialize Fortran 77 compiler:
<ide> if need_f77_compiler:
<add> ctype = self.fcompiler
<ide> self._f77_compiler = new_fcompiler(compiler=self.fcompiler,
<ide> verbose=self.verbose,
<ide> dry_run=self.dry_run,
<ide> force=self.force,
<ide> requiref90=False)
<ide> fcompiler = self._f77_compiler
<add> if fcompiler:
<add> ctype = fcompiler.compiler_type
<ide> if fcompiler and fcompiler.get_version():
<ide> fcompiler.customize(self.distribution)
<ide> fcompiler.customize_cmd(self)
<ide> fcompiler.show_customization()
<ide> else:
<ide> self.warn('f77_compiler=%s is not available.' %
<del> (fcompiler.compiler_type))
<add> (ctype))
<ide> self._f77_compiler = None
<ide> else:
<ide> self._f77_compiler = None
<ide>
<ide> # Initialize Fortran 90 compiler:
<ide> if need_f90_compiler:
<add> ctype = self.fcompiler
<ide> self._f90_compiler = new_fcompiler(compiler=self.fcompiler,
<ide> verbose=self.verbose,
<ide> dry_run=self.dry_run,
<ide> force=self.force,
<ide> requiref90=True)
<ide> fcompiler = self._f90_compiler
<add> if fcompiler:
<add> ctype = fcompiler.compiler_type
<ide> if fcompiler and fcompiler.get_version():
<ide> fcompiler.customize(self.distribution)
<ide> fcompiler.customize_cmd(self)
<ide> fcompiler.show_customization()
<ide> else:
<ide> self.warn('f90_compiler=%s is not available.' %
<del> (fcompiler.compiler_type))
<add> (ctype))
<ide> self._f90_compiler = None
<ide> else:
<ide> self._f90_compiler = None
<ide><path>numpy/distutils/command/config.py
<ide> def _check_compiler (self):
<ide> if not isinstance(self.fcompiler, FCompiler):
<ide> self.fcompiler = new_fcompiler(compiler=self.fcompiler,
<ide> dry_run=self.dry_run, force=1)
<del> if self.fcompiler is not None:
<add> if self.fcompiler is not None and self.fcompiler.get_version():
<ide> self.fcompiler.customize(self.distribution)
<ide> self.fcompiler.customize_cmd(self)
<ide> self.fcompiler.show_customization() | 3 |
Ruby | Ruby | remove empty lines | 324201d7b9f1cd8a79baea64cdbf0df2be60decd | <ide><path>railties/test/application/rake/notes_test.rb
<ide> def teardown
<ide> assert_equal ' ', line[1]
<ide> end
<ide> end
<del>
<ide> end
<ide>
<ide> test 'notes finds notes in default directories' do
<ide> def teardown
<ide> assert_equal 4, line_number.size
<ide> end
<ide> end
<del>
<ide> end
<ide>
<ide> test 'notes finds notes in custom directories' do
<del>
<ide> app_file "app/controllers/some_controller.rb", "# TODO: note in app directory"
<ide> app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory"
<ide> app_file "lib/some_file.rb", "# TODO: note in lib directory"
<ide> def teardown
<ide> assert_equal 4, line_number.size
<ide> end
<ide> end
<del>
<ide> end
<ide>
<ide> private | 1 |
Ruby | Ruby | use accessors instead of manipulating the hash | b42c58636571ccbf4bfc23f89039f43e63c98211 | <ide><path>actionpack/lib/action_controller/metal/live.rb
<ide> def initialize(response)
<ide>
<ide> def write(string)
<ide> unless @response.committed?
<del> @response.headers["Cache-Control"] = "no-cache"
<del> @response.headers.delete "Content-Length"
<add> @response.set_header "Cache-Control", "no-cache"
<add> @response.delete_header "Content-Length"
<ide> end
<ide>
<ide> super | 1 |
PHP | PHP | update the tests for the exception of `insertat()` | 96145faba813b189e0d81d74b67602db6a9d583c | <ide><path>src/View/Helper/BreadcrumbsHelper.php
<ide> public function insertAfter($matchingTitle, $title, $url = null, array $options
<ide> throw new LogicException(sprintf("No crumb matching '%s' could be found.", $matchingTitle));
<ide> }
<ide>
<del> return $this->insertAt($key, $title, $url, $options);
<add> return $this->insertAt($key + 1, $title, $url, $options);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/Helper/BreadcrumbsHelperTest.php
<ide> public function setUp()
<ide>
<ide> /**
<ide> * Test adding crumbs to the trail using add()
<add> *
<ide> * @return void
<ide> */
<ide> public function testAdd()
<ide> public function testAdd()
<ide>
<ide> /**
<ide> * Test adding multiple crumbs at once to the trail using add()
<add> *
<ide> * @return void
<ide> */
<ide> public function testAddMultiple()
<ide> public function testAddMultiple()
<ide>
<ide> /**
<ide> * Test adding crumbs to the trail using prepend()
<add> *
<ide> * @return void
<ide> */
<ide> public function testPrepend()
<ide> public function testPrepend()
<ide>
<ide> /**
<ide> * Test adding crumbs to a specific index
<add> *
<ide> * @return void
<ide> */
<ide> public function testInsertAt()
<ide> public function testInsertAt()
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add> /**
<add> * Test adding crumbs to a specific index
<add> *
<add> * @expectedException \LogicException
<add> */
<add> public function testInsertAtIndexOutOfBounds()
<add> {
<add> $this->breadcrumbs
<add> ->add('Home', '/', ['class' => 'first'])
<add> ->insertAt(2, 'Insert At Again', ['controller' => 'Insert', 'action' => 'at_again']);
<add> }
<add>
<ide> /**
<ide> * Test adding crumbs before a specific one
<add> *
<ide> * @return void
<ide> */
<ide> public function testInsertBefore()
<ide> public function testInsertBefore()
<ide>
<ide> /**
<ide> * Test adding crumbs after a specific one
<add> *
<ide> * @return void
<ide> */
<ide> public function testInsertAfter()
<ide> public function testInsertAfter()
<ide>
<ide> /**
<ide> * Tests the render method
<add> *
<ide> * @return void
<ide> */
<ide> public function testRender()
<ide> public function testRender()
<ide>
<ide> /**
<ide> * Tests the render method with custom templates
<add> *
<ide> * @return void
<ide> */
<ide> public function testRenderCustomTemplate()
<ide> public function testRenderCustomTemplate()
<ide>
<ide> /**
<ide> * Tests the render method with template vars
<add> *
<ide> * @return void
<ide> */
<ide> public function testRenderCustomTemplateTemplateVars() | 2 |
PHP | PHP | fix expression doc blocks | f10d092d968df1007be35d573f98c2d61702b599 | <ide><path>src/Database/Expression/BetweenExpression.php
<ide> class BetweenExpression implements ExpressionInterface, FieldInterface
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param mixed $field The field name to compare for values in between the range.
<add> * @param string|\Cake\Database\ExpressionInterface $field The field name to compare for values in between the range.
<ide> * @param mixed $from The initial value of the range.
<ide> * @param mixed $to The ending value in the comparison range.
<ide> * @param string|null $type The data type name to bind the values with.
<ide><path>src/Database/Expression/Comparison.php
<ide> class Comparison implements ExpressionInterface, FieldInterface
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param string $field the field name to compare to a value
<add> * @param string|\Cake\Database\ExpressionInterface $field the field name to compare to a value
<ide> * @param mixed $value The value to be used in comparison
<ide> * @param string $type the type name used to cast the value
<ide> * @param string $operator the operator used for comparing field and value
<ide><path>src/Database/Expression/FieldInterface.php
<ide> interface FieldInterface
<ide> /**
<ide> * Sets the field name
<ide> *
<del> * @param string $field The field to compare with.
<add> * @param string|\Cake\Database\ExpressionInterface $field The field to compare with.
<ide> * @return void
<ide> */
<ide> public function setField($field);
<ide><path>src/Database/Expression/FieldTrait.php
<ide> trait FieldTrait
<ide> /**
<ide> * The field name or expression to be used in the left hand side of the operator
<ide> *
<del> * @var string
<add> * @var string|\Cake\Database\ExpressionInterface
<ide> */
<ide> protected $_field;
<ide>
<ide> /**
<ide> * Sets the field name
<ide> *
<del> * @param string $field The field to compare with.
<add> * @param string|\Cake\Database\ExpressionInterface $field The field to compare with.
<ide> * @return void
<ide> */
<ide> public function setField($field)
<ide><path>src/Database/Expression/OrderByExpression.php
<ide> class OrderByExpression extends QueryExpression
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param array $conditions The sort columns
<del> * @param array $types The types for each column.
<add> * @param string|array|\Cake\Database\ExpressionInterface $conditions The sort columns
<add> * @param array|\Cake\Database\TypeMap $types The types for each column.
<ide> * @param string $conjunction The glue used to join conditions together.
<ide> */
<ide> public function __construct($conditions = [], $types = [], $conjunction = '')
<ide><path>src/Database/Expression/QueryExpression.php
<ide> class QueryExpression implements ExpressionInterface, Countable
<ide> * expression objects. Optionally, you can set the conjunction keyword to be used
<ide> * for joining each part of this level of the expression tree.
<ide> *
<del> * @param string|array|\Cake\Database\Expression\QueryExpression $conditions tree-like array structure containing all the conditions
<add> * @param string|array|\Cake\Database\ExpressionInterface $conditions tree-like array structure containing all the conditions
<ide> * to be added or nested inside this expression object.
<ide> * @param array|\Cake\Database\TypeMap $types associative array of types to be associated with the values
<ide> * passed in $conditions.
<ide> public function add($conditions, $types = [])
<ide> /**
<ide> * Adds a new condition to the expression object in the form "field = value".
<ide> *
<del> * @param string $field Database field to be compared against value
<add> * @param string|\Cake\Database\ExpressionInterface $field Database field to be compared against value
<ide> * @param mixed $value The value to be bound to $field for comparison
<ide> * @param string|null $type the type name for $value as configured using the Type map.
<ide> * If it is suffixed with "[]" and the value is an array then multiple placeholders
<ide> public function eq($field, $value, $type = null)
<ide> /**
<ide> * Adds a new condition to the expression object in the form "field != value".
<ide> *
<del> * @param string $field Database field to be compared against value
<add> * @param string|\Cake\Database\ExpressionInterface $field Database field to be compared against value
<ide> * @param mixed $value The value to be bound to $field for comparison
<ide> * @param string|null $type the type name for $value as configured using the Type map.
<ide> * If it is suffixed with "[]" and the value is an array then multiple placeholders
<ide> public function notEq($field, $value, $type = null)
<ide> /**
<ide> * Adds a new condition to the expression object in the form "field > value".
<ide> *
<del> * @param string $field Database field to be compared against value
<add> * @param string|\Cake\Database\ExpressionInterface $field Database field to be compared against value
<ide> * @param mixed $value The value to be bound to $field for comparison
<ide> * @param string|null $type the type name for $value as configured using the Type map.
<ide> * @return $this
<ide> public function gt($field, $value, $type = null)
<ide> /**
<ide> * Adds a new condition to the expression object in the form "field < value".
<ide> *
<del> * @param string $field Database field to be compared against value
<add> * @param string|\Cake\Database\ExpressionInterface $field Database field to be compared against value
<ide> * @param mixed $value The value to be bound to $field for comparison
<ide> * @param string|null $type the type name for $value as configured using the Type map.
<ide> * @return $this
<ide> public function lt($field, $value, $type = null)
<ide> /**
<ide> * Adds a new condition to the expression object in the form "field >= value".
<ide> *
<del> * @param string $field Database field to be compared against value
<add> * @param string|\Cake\Database\ExpressionInterface $field Database field to be compared against value
<ide> * @param mixed $value The value to be bound to $field for comparison
<ide> * @param string|null $type the type name for $value as configured using the Type map.
<ide> * @return $this
<ide> public function gte($field, $value, $type = null)
<ide> /**
<ide> * Adds a new condition to the expression object in the form "field <= value".
<ide> *
<del> * @param string $field Database field to be compared against value
<add> * @param string|\Cake\Database\ExpressionInterface $field Database field to be compared against value
<ide> * @param mixed $value The value to be bound to $field for comparison
<ide> * @param string|null $type the type name for $value as configured using the Type map.
<ide> * @return $this
<ide> public function isNotNull($field)
<ide> /**
<ide> * Adds a new condition to the expression object in the form "field LIKE value".
<ide> *
<del> * @param string $field Database field to be compared against value
<add> * @param string|\Cake\Database\ExpressionInterface $field Database field to be compared against value
<ide> * @param mixed $value The value to be bound to $field for comparison
<ide> * @param string|null $type the type name for $value as configured using the Type map.
<ide> * @return $this
<ide> public function like($field, $value, $type = null)
<ide> /**
<ide> * Adds a new condition to the expression object in the form "field NOT LIKE value".
<ide> *
<del> * @param string $field Database field to be compared against value
<add> * @param string|\Cake\Database\ExpressionInterface $field Database field to be compared against value
<ide> * @param mixed $value The value to be bound to $field for comparison
<ide> * @param string|null $type the type name for $value as configured using the Type map.
<ide> * @return $this
<ide> public function notLike($field, $value, $type = null)
<ide> * Adds a new condition to the expression object in the form
<ide> * "field IN (value1, value2)".
<ide> *
<del> * @param string $field Database field to be compared against value
<add> * @param string|\Cake\Database\ExpressionInterface $field Database field to be compared against value
<ide> * @param string|array $values the value to be bound to $field for comparison
<ide> * @param string|null $type the type name for $value as configured using the Type map.
<ide> * @return $this
<ide> public function addCase($conditions, $values = [], $types = [])
<ide> * Adds a new condition to the expression object in the form
<ide> * "field NOT IN (value1, value2)".
<ide> *
<del> * @param string $field Database field to be compared against value
<add> * @param string|\Cake\Database\ExpressionInterface $field Database field to be compared against value
<ide> * @param array $values the value to be bound to $field for comparison
<ide> * @param string|null $type the type name for $value as configured using the Type map.
<ide> * @return $this
<ide> public function notExists(ExpressionInterface $query)
<ide> * Adds a new condition to the expression object in the form
<ide> * "field BETWEEN from AND to".
<ide> *
<del> * @param mixed $field The field name to compare for values in between the range.
<add> * @param string|\Cake\Database\ExpressionInterface $field The field name to compare for values in between the range.
<ide> * @param mixed $from The initial value of the range.
<ide> * @param mixed $to The ending value in the comparison range.
<ide> * @param string|null $type the type name for $value as configured using the Type map.
<ide> public function between($field, $from, $to, $type = null)
<ide> * Returns a new QueryExpression object containing all the conditions passed
<ide> * and set up the conjunction to be "AND"
<ide> *
<del> * @param string|array|QueryExpression $conditions to be joined with AND
<add> * @param string|array|\Cake\Database\ExpressionInterface $conditions to be joined with AND
<ide> * @param array $types associative array of fields pointing to the type of the
<ide> * values that are being passed. Used for correctly binding values to statements.
<ide> * @return \Cake\Database\Expression\QueryExpression
<ide> public function and_($conditions, $types = [])
<ide> * Returns a new QueryExpression object containing all the conditions passed
<ide> * and set up the conjunction to be "OR"
<ide> *
<del> * @param string|array|QueryExpression $conditions to be joined with OR
<add> * @param string|array|\Cake\Database\ExpressionInterface $conditions to be joined with OR
<ide> * @param array $types associative array of fields pointing to the type of the
<ide> * values that are being passed. Used for correctly binding values to statements.
<ide> * @return \Cake\Database\Expression\QueryExpression
<ide> public function or_($conditions, $types = [])
<ide> * "NOT ( (condition1) AND (conditions2) )" conjunction depends on the one
<ide> * currently configured for this object.
<ide> *
<del> * @param string|array|\Cake\Database\Expression\QueryExpression $conditions to be added and negated
<add> * @param string|array|\Cake\Database\ExpressionInterface $conditions to be added and negated
<ide> * @param array $types associative array of fields pointing to the type of the
<ide> * values that are being passed. Used for correctly binding values to statements.
<ide> * @return $this
<ide> protected function _parseCondition($field, $value)
<ide> /**
<ide> * Returns the type name for the passed field if it was stored in the typeMap
<ide> *
<del> * @param string|\Cake\Database\Expression\QueryExpression $field The field name to get a type for.
<add> * @param string|\Cake\Database\Expression\IdentifierExpression $field The field name to get a type for.
<ide> * @return string|null The computed type or null, if the type is unknown.
<ide> */
<ide> protected function _calculateType($field)
<ide><path>src/Database/Expression/TupleComparison.php
<ide> class TupleComparison extends Comparison
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param string|array $fields the fields to use to form a tuple
<add> * @param string|array|\Cake\Database\ExpressionInterface $fields the fields to use to form a tuple
<ide> * @param array|\Cake\Database\ExpressionInterface $values the values to use to form a tuple
<ide> * @param array $types the types names to use for casting each of the values, only
<ide> * one type per position in the value array in needed | 7 |
Ruby | Ruby | add version number to cask json option | 7e5addfb22661814a10253648719be9f4f8041dd | <ide><path>Library/Homebrew/cask/lib/hbc/cli/info.rb
<ide> module Hbc
<ide> class CLI
<ide> class Info < AbstractCommand
<del> option "--json-v1", :json, false
<add> option "--json=VERSION", :json
<ide>
<ide> def initialize(*)
<ide> super
<ide> raise CaskUnspecifiedError if args.empty?
<ide> end
<ide>
<ide> def run
<del> if json?
<del> json = casks.map(&:to_hash)
<del> puts JSON.generate(json)
<add> if json == "v1"
<add> puts JSON.generate(casks.map(&:to_hash))
<ide> else
<ide> casks.each do |cask|
<ide> odebug "Getting info for Cask #{cask}" | 1 |
Java | Java | fix resolvabletype isassignablefrom for <?> | 5358cc0f5f412b541bdb7e8b89374d924eb12fa4 | <ide><path>spring-core/src/main/java/org/springframework/core/ResolvableType.java
<ide> private boolean isAssignableFrom(ResolvableType type, boolean checkingGeneric) {
<ide> Assert.notNull(type, "Type must not be null");
<ide>
<ide> // If we cannot resolve types, we are not assignable
<del> if (resolve() == null || type.resolve() == null) {
<add> if (this == NONE || type == NONE) {
<ide> return false;
<ide> }
<ide>
<ide> private boolean isAssignableFrom(ResolvableType type, boolean checkingGeneric) {
<ide> }
<ide>
<ide> // Main assignability check
<del> boolean rtn = resolve().isAssignableFrom(type.resolve());
<add> boolean rtn = resolve(Object.class).isAssignableFrom(type.resolve(Object.class));
<ide>
<ide> // We need an exact type match for generics
<ide> // List<CharSequence> is not assignable from List<String>
<del> rtn &= (!checkingGeneric || resolve().equals(type.resolve()));
<add> rtn &= (!checkingGeneric || resolve(Object.class).equals(type.resolve(Object.class)));
<ide>
<ide> // Recursively check each generic
<ide> for (int i = 0; i < getGenerics().length; i++) {
<del> rtn &= getGeneric(i).isAssignableFrom(type.as(resolve()).getGeneric(i), true);
<add> rtn &= getGeneric(i).isAssignableFrom(
<add> type.as(resolve(Object.class)).getGeneric(i), true);
<ide> }
<ide>
<ide> return rtn;
<ide><path>spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java
<ide> import static org.mockito.Matchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<del>// FIXME nested
<del>
<ide> /**
<ide> * Tests for {@link ResolvableType}.
<ide> *
<ide> public void isAssignableFromCannotBeResolved() throws Exception {
<ide> ResolvableType objectType = ResolvableType.forClass(Object.class);
<ide> ResolvableType unresolvableVariable = ResolvableType.forField(AssignmentBase.class.getField("o"));
<ide> assertThat(unresolvableVariable.resolve(), nullValue());
<del> assertAssignable(objectType, unresolvableVariable).equalTo(false);
<del> assertAssignable(unresolvableVariable, objectType).equalTo(false);
<add> assertAssignable(objectType, unresolvableVariable).equalTo(true);
<add> assertAssignable(unresolvableVariable, objectType).equalTo(true);
<ide> }
<ide>
<ide> @Test
<ide> public void isAssignableFromForWildcards() throws Exception {
<ide> ResolvableType object = ResolvableType.forClass(Object.class);
<ide> ResolvableType charSequence = ResolvableType.forClass(CharSequence.class);
<ide> ResolvableType string = ResolvableType.forClass(String.class);
<add> ResolvableType extendsAnon = ResolvableType.forField(AssignmentBase.class.getField("listAnon"), Assignment.class).getGeneric();
<ide> ResolvableType extendsObject = ResolvableType.forField(AssignmentBase.class.getField("listxo"), Assignment.class).getGeneric();
<ide> ResolvableType extendsCharSequence = ResolvableType.forField(AssignmentBase.class.getField("listxc"), Assignment.class).getGeneric();
<ide> ResolvableType extendsString = ResolvableType.forField(AssignmentBase.class.getField("listxs"), Assignment.class).getGeneric();
<ide> public void isAssignableFromForWildcards() throws Exception {
<ide> equalTo(false, true, true);
<ide> assertAssignable(charSequence, extendsObject, extendsCharSequence, extendsString).
<ide> equalTo(false, false, false);
<add> assertAssignable(extendsAnon, object, charSequence, string).
<add> equalTo(true, true, true);
<ide>
<ide> // T <= ? super T
<ide> assertAssignable(superCharSequence, object, charSequence, string).
<ide> static class TypedFields extends Fields<String> {
<ide>
<ide> public List<S> lists;
<ide>
<add> public List<?> listAnon;
<add>
<ide> public List<? extends O> listxo;
<ide>
<ide> public List<? extends C> listxc; | 2 |
Javascript | Javascript | fix stale scene cleanup | b4d15d3c5ac4542931e0f3d1b93b42109e523550 | <ide><path>Libraries/NavigationExperimental/NavigationTransitioner.js
<ide> class NavigationTransitioner extends React.Component<any, Props, State> {
<ide> const prevTransitionProps = this._prevTransitionProps;
<ide> this._prevTransitionProps = null;
<ide>
<del> const scenes = this.state.scenes.filter(isSceneNotStale);
<del> this.setState({ scenes });
<add> const nextState = {
<add> ...this.state,
<add> scenes: this.state.scenes.filter(isSceneNotStale),
<add> };
<add>
<add> this._transitionProps = buildTransitionProps(this.props, nextState);
<add>
<add> this.setState(nextState);
<ide>
<ide> this.props.onTransitionEnd && this.props.onTransitionEnd(
<ide> this._transitionProps, | 1 |
Text | Text | add updated scrimba link to word blank challenge | 28575e987771914169c6e2e473a10bfc7c52c353 | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/word-blanks.english.md
<ide> id: 56533eb9ac21ba0edf2244bb
<ide> title: Word Blanks
<ide> challengeType: 1
<del>videoUrl: 'https://scrimba.com/c/cP3vVsm'
<add>videoUrl: 'https://scrimba.com/c/caqn8zuP'
<ide> forumTopicId: 18377
<ide> ---
<ide> | 1 |
Javascript | Javascript | add compiler v2.0 - not connected | 8af4fde18246ac1587b471a549e70d5d858bf0ee | <ide><path>src/Angular.js
<ide> function copy(source, destination){
<ide> return destination;
<ide> }
<ide>
<add>/**
<add> * Create a shallow copy of an object
<add> * @param src
<add> */
<add>function shallowCopy(src) {
<add> var dst = {},
<add> key;
<add> for(key in src) {
<add> if (src.hasOwnProperty(key)) {
<add> dst[key] = src[key];
<add> }
<add> }
<add> return dst;
<add>}
<add>
<add>
<ide> /**
<ide> * @ngdoc function
<ide> * @name angular.equals
<ide> function toBoolean(value) {
<ide> return value;
<ide> }
<ide>
<add>/**
<add> * @returns {string} Returns the string representation of the element.
<add> */
<add>function startingTag(element) {
<add> element = jqLite(element).clone();
<add> try {
<add> // turns out IE does not let you set .html() on elements which
<add> // are not allowed to have children. So we just ignore it.
<add> element.html('');
<add> } catch(e) {};
<add> return jqLite('<div>').append(element).html().replace(/\<\/[\w\:\-]+\>$/, '');
<add>}
<add>
<ide>
<ide> /////////////////////////////////////////////////
<ide>
<ide> function bootstrap(element, modules) {
<ide> return injector;
<ide> }
<ide>
<add>var SNAKE_CASE_REGEXP = /[A-Z]/g;
<add>function snake_case(name, separator){
<add> separator = separator || '_';
<add> return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
<add> return (pos ? separator : '') + letter.toLowerCase();
<add> });
<add>}
<add>
<ide> function bindJQuery() {
<ide> // bind to jQuery if present;
<ide> jQuery = window.jQuery;
<ide> function assertArg(arg, name, reason) {
<ide> }
<ide>
<ide> function assertArgFn(arg, name) {
<add> assertArg(arg, name);
<ide> assertArg(isFunction(arg), name, 'not a function, got ' +
<ide> (typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
<ide> return arg;
<ide><path>src/angular-mocks.js
<ide> angular.mock.dump = function(object) {
<ide> *
<ide> * <pre>
<ide> // controller
<del> function MyController($http) {
<del> var scope = this;
<del>
<add> function MyController($scope, $http) {
<ide> $http.get('/auth.py').success(function(data) {
<del> scope.user = data;
<add> $scope.user = data;
<ide> });
<ide>
<ide> this.saveMessage = function(message) {
<del> scope.status = 'Saving...';
<add> $scope.status = 'Saving...';
<ide> $http.post('/add-msg.py', message).success(function(response) {
<del> scope.status = '';
<add> $scope.status = '';
<ide> }).error(function() {
<del> scope.status = 'ERROR!';
<add> $scope.status = 'ERROR!';
<ide> });
<ide> };
<ide> }
<ide><path>src/jqLite.js
<ide> function getStyle(element) {
<ide> }
<ide>
<ide>
<add>var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
<add>var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
<add>var MOZ_HACK_REGEXP = /^moz([A-Z])/;
<ide> /**
<del> * Converts dash-separated names to camelCase. Useful for dealing with css properties.
<add> * Converts all accepted directives format into proper directive name.
<add> * All of these will become 'myDirective':
<add> * my:DiRective
<add> * my-directive
<add> * x-my-directive
<add> * data-my:directive
<add> *
<add> * Also there is special case for Moz prefix starting with upper case letter.
<add> * @param name Name to normalize
<ide> */
<ide> function camelCase(name) {
<del> return name.replace(/\-(\w)/g, function(all, letter, offset){
<del> return (offset == 0 && letter == 'w') ? 'w' : letter.toUpperCase();
<del> });
<add> return name.
<add> replace(PREFIX_REGEXP, '').
<add> replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
<add> return offset ? letter.toUpperCase() : letter;
<add> }).
<add> replace(MOZ_HACK_REGEXP, 'Moz$1');
<ide> }
<ide>
<ide> /////////////////////////////////////////////
<ide><path>src/service/compiler.js
<ide> 'use strict';
<ide>
<add>/**
<add> * @ngdoc function
<add> * @name angular.module.ng.$compile
<add> * @function
<add> *
<add> * @description
<add> * Compiles a piece of HTML string or DOM into a template and produces a template function, which
<add> * can then be used to link {@link angular.module.ng.$rootScope.Scope scope} and the template together.
<add> *
<add> * The compilation is a process of walking the DOM tree and trying to match DOM elements to
<add> * {@link angular.module.ng.$compileProvider.directive directives}. For each match it
<add> * executes corresponding template function and collects the
<add> * instance functions into a single template function which is then returned.
<add> *
<add> * The template function can then be used once to produce the view or as it is the case with
<add> * {@link angular.module.ng.$compileProvider.directive.ng:repeat repeater} many-times, in which
<add> * case each call results in a view that is a DOM clone of the original template.
<add> *
<add> <doc:example module="compile">
<add> <doc:source>
<add> <script>
<add> // declare a new module, and inject the $compileProvider
<add> angular.module('compile', [], function($compileProvider) {
<add> // configure new 'compile' directive by passing a directive
<add> // factory function. The factory function injects the '$compile'
<add> $compileProvider.directive('compile', function($compile) {
<add> // directive factory creates a link function
<add> return function(scope, element, attrs) {
<add> scope.$watch(
<add> function(scope) {
<add> // watch the 'compile' expression for changes
<add> return scope.$eval(attrs.compile);
<add> },
<add> function(scope, value) {
<add> // when the 'compile' expression changes
<add> // assign it into the current DOM
<add> element.html(value);
<ide>
<del>function $CompileProvider(){
<del> this.$get = ['$injector', '$exceptionHandler', '$textMarkup', '$attrMarkup', '$directive', '$widget',
<del> function( $injector, $exceptionHandler, $textMarkup, $attrMarkup, $directive, $widget){
<del> /**
<del> * Template provides directions an how to bind to a given element.
<del> * It contains a list of init functions which need to be called to
<del> * bind to a new instance of elements. It also provides a list
<del> * of child paths which contain child templates
<del> */
<del> function Template() {
<del> this.paths = [];
<del> this.children = [];
<del> this.linkFns = [];
<del> this.newScope = false;
<add> // compile the new DOM and link it to the current
<add> // scope.
<add> // NOTE: we only compile .childNodes so that
<add> // we don't get into infinite loop compiling ourselves
<add> $compile(element.contents())(scope);
<add> }
<add> );
<add> };
<add> })
<add> });
<add>
<add> function Ctrl() {
<add> this.name = 'Angular';
<add> this.html = 'Hello {{name}}';
<ide> }
<add> </script>
<add> <div ng-controller="Ctrl">
<add> <input ng:model="name"> <br>
<add> <textarea ng:model="html"></textarea> <br>
<add> <div compile="html"></div>
<add> </div>
<add> </doc:source>
<add> <doc:scenario>
<add> it('should auto compile', function() {
<add> expect(element('div[compile]').text()).toBe('Hello Angular');
<add> input('html').enter('{{name}}!');
<add> expect(element('div[compile]').text()).toBe('Angular!');
<add> });
<add> </doc:scenario>
<add> </doc:example>
<ide>
<del> Template.prototype = {
<del> link: function(element, scope) {
<del> var childScope = scope,
<del> locals = {$element: element};
<del> if (this.newScope) {
<del> childScope = scope.$new();
<del> element.data($$scope, childScope);
<del> }
<del> forEach(this.linkFns, function(fn) {
<del> try {
<del> if (isArray(fn) || fn.$inject) {
<del> $injector.invoke(fn, childScope, locals);
<del> } else {
<del> fn.call(childScope, element);
<add> *
<add> *
<add> * @param {string|DOMElement} element Element or HTML string to compile into a template function.
<add> * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
<add> * (a DOM element/tree) to a scope. Where:
<add> *
<add> * * `scope` - A {@link angular.module.ng.$rootScope.Scope Scope} to bind to.
<add> * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
<add> * `template` and call the `cloneAttachFn` function allowing the caller to attach the
<add> * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
<add> * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
<add> *
<add> * * `clonedElement` - is a clone of the original `element` passed into the compiler.
<add> * * `scope` - is the current scope with which the linking function is working with.
<add> *
<add> * Calling the linking 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.
<add> *
<add> * After linking the view is not updateh until after a call to $digest which typically is done by
<add> * Angular automatically.
<add> *
<add> * If you need access to the bound view, there are two ways to do it:
<add> *
<add> * - If you are not asking the linking function to clone the template, create the DOM element(s)
<add> * before you send them to the compiler and keep this reference around.
<add> * <pre>
<add> * var element = $compile('<p>{{total}}</p>')(scope);
<add> * </pre>
<add> *
<add> * - if on the other hand, you need the element to be cloned, the view reference from the original
<add> * example would not point to the clone, but rather to the original template that was cloned. In
<add> * this case, you can access the clone via the cloneAttachFn:
<add> * <pre>
<add> * var templateHTML = angular.element('<p>{{total}}</p>'),
<add> * scope = ....;
<add> *
<add> * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
<add> * //attach the clone to DOM document at the right place
<add> * });
<add> *
<add> * //now we have reference to the cloned DOM via `clone`
<add> * </pre>
<add> *
<add> *
<add> * Compiler Methods For Widgets and Directives:
<add> *
<add> * The following methods are available for use when you write your own widgets, directives,
<add> * and markup.
<add> *
<add> *
<add> * For information on how the compiler works, see the
<add> * {@link guide/dev_guide.compiler Angular HTML Compiler} section of the Developer Guide.
<add> */
<add>
<add>
<add>$CompileProvider.$inject = ['$provide'];
<add>function $CompileProvider($provide) {
<add> var hasDirectives = {},
<add> Suffix = 'Directive',
<add> COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
<add> CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
<add> CONTENT_REGEXP = /\<\<content\>\>/i,
<add> HAS_ROOT_ELEMENT = /^\<[\s\S]*\>$/,
<add> SIDE_EFFECT_ATTRS = {};
<add>
<add> forEach('src,href,multiple,selected,checked,disabled,readonly,required'.split(','), function(name) {
<add> SIDE_EFFECT_ATTRS[name] = name;
<add> SIDE_EFFECT_ATTRS[directiveNormalize('ng_' + name)] = name;
<add> });
<add>
<add>
<add> this.directive = function registerDirective(name, directiveFactory) {
<add> if (isString(name)) {
<add> assertArg(directiveFactory, 'directive');
<add> if (!hasDirectives.hasOwnProperty(name)) {
<add> hasDirectives[name] = [];
<add> $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
<add> function($injector, $exceptionHandler) {
<add> var directives = [];
<add> forEach(hasDirectives[name], function(directiveFactory) {
<add> try {
<add> var directive = $injector.invoke(directiveFactory);
<add> if (isFunction(directive)) {
<add> directive = { compile: valueFn(directive) };
<add> } else if (!directive.compile && directive.link) {
<add> directive.compile = valueFn(directive.link);
<add> }
<add> directive.priority = directive.priority || 0;
<add> directive.name = name;
<add> directive.restrict = directive.restrict || 'EACM';
<add> directives.push(directive);
<add> } catch (e) {
<add> $exceptionHandler(e);
<ide> }
<del> } catch (e) {
<del> $exceptionHandler(e);
<add> });
<add> return directives;
<add> }]);
<add> }
<add> hasDirectives[name].push(directiveFactory);
<add> } else {
<add> forEach(name, reverseParams(registerDirective));
<add> }
<add> return this;
<add> };
<add>
<add>
<add> this.$get = ['$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache',
<add> function($injector, $interpolate, $exceptionHandler, $http, $templateCache) {
<add>
<add> return function(templateElement) {
<add> templateElement = jqLite(templateElement);
<add> var linkingFn = compileNodes(templateElement, templateElement);
<add> return function(scope, cloneConnectFn){
<add> assertArg(scope, 'scope');
<add> // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
<add> // and sometimes changes the structure of the DOM.
<add> var element = cloneConnectFn
<add> ? JQLitePrototype.clone.call(templateElement) // IMPORTANT!!!
<add> : templateElement;
<add> element.data('$scope', scope);
<add> if (cloneConnectFn) cloneConnectFn(element, scope);
<add> if (linkingFn) linkingFn(scope, element, element);
<add> return element;
<add> };
<add> };
<add>
<add> //================================
<add>
<add> /**
<add> * Compile function matches each node in nodeList against the directives. Once all directives
<add> * for a particular node are collected their compile functions are executed. The compile
<add> * functions return values - the linking functions - are combined into a composite linking
<add> * function, which is the a linking function for the node.
<add> *
<add> * @param {NodeList} nodeList an array of nodes to compile
<add> * @param {DOMElement=} rootElement If the nodeList is the root of the compilation tree then the
<add> * rootElement must be set the jqLite collection of the compile root. This is
<add> * needed so that the jqLite collection items can be replaced with widgets.
<add> * @returns {?function} A composite linking function of all of the matched directives or null.
<add> */
<add> function compileNodes(nodeList, rootElement) {
<add> var linkingFns = [],
<add> directiveLinkingFn, childLinkingFn, directives, attrs, linkingFnFound;
<add>
<add> for(var i = 0, ii = nodeList.length; i < ii; i++) {
<add> attrs = {
<add> $attr: {},
<add> $normalize: directiveNormalize,
<add> $set: attrSetter
<add> };
<add> // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
<add> directives = collectDirectives(nodeList[i], [], attrs);
<add>
<add> directiveLinkingFn = (directives.length)
<add> ? applyDirectivesToNode(directives, nodeList[i], attrs, rootElement)
<add> : null;
<add>
<add> childLinkingFn = (directiveLinkingFn && directiveLinkingFn.terminal)
<add> ? null
<add> : compileNodes(nodeList[i].childNodes);
<add>
<add> linkingFns.push(directiveLinkingFn);
<add> linkingFns.push(childLinkingFn);
<add> linkingFnFound = (linkingFnFound || directiveLinkingFn || childLinkingFn);
<add> }
<add>
<add> // return a linking function if we have found anything, null otherwise
<add> return linkingFnFound ? linkingFn : null;
<add>
<add> function linkingFn(scope, nodeList, rootElement) {
<add> if (linkingFns.length != nodeList.length * 2) {
<add> throw Error('Template changed structure!');
<add> }
<add>
<add> var childLinkingFn, directiveLinkingFn, node, childScope;
<add>
<add> for(var i=0, n=0, ii=linkingFns.length; i<ii; n++) {
<add> node = nodeList[n];
<add> directiveLinkingFn = linkingFns[i++];
<add> childLinkingFn = linkingFns[i++];
<add>
<add> if (directiveLinkingFn) {
<add> if (directiveLinkingFn.scope && !rootElement) {
<add> childScope = scope.$new();
<add> jqLite(node).data('$scope', childScope);
<add> } else {
<add> childScope = scope;
<add> }
<add> directiveLinkingFn(childLinkingFn, childScope, node, rootElement);
<add> } else if (childLinkingFn) {
<add> childLinkingFn(scope, node.childNodes);
<add> }
<add> }
<add> }
<add> }
<add>
<add>
<add> /**
<add> * Looks for directives on the given node ands them to the directive collection which is sorted.
<add> *
<add> * @param node node to search
<add> * @param directives an array to which the directives are added to. This array is sorted before
<add> * the function returns.
<add> * @param attrs the shared attrs object which is used to populate the normalized attributes.
<add> */
<add> function collectDirectives(node, directives, attrs) {
<add> var nodeType = node.nodeType,
<add> attrsMap = attrs.$attr,
<add> match,
<add> className;
<add>
<add> switch(nodeType) {
<add> case 1: /* Element */
<add> // use the node name: <directive>
<add> addDirective(directives, directiveNormalize(nodeName_(node).toLowerCase()), 'E');
<add>
<add> // iterate over the attributes
<add> for (var attr, name, nName, value, nAttrs = node.attributes,
<add> j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
<add> attr = nAttrs[j];
<add> name = attr.name;
<add> nName = directiveNormalize(name.toLowerCase());
<add> attrsMap[nName] = name;
<add> attrs[nName] = value = trim((msie && name == 'href')
<add> ? decodeURIComponent(node.getAttribute(name, 2))
<add> : attr.value);
<add> if (BOOLEAN_ATTR[nName]) {
<add> attrs[nName] = true; // presence means true
<ide> }
<del> });
<del> var i,
<del> childNodes = element[0].childNodes,
<del> children = this.children,
<del> paths = this.paths,
<del> length = paths.length;
<del> for (i = 0; i < length; i++) {
<del> // sometimes `element` can be modified by one of the linker functions in `this.linkFns`
<del> // and childNodes may be added or removed
<del> // TODO: element structure needs to be re-evaluated if new children added
<del> // if the childNode still exists
<del> if (childNodes[paths[i]])
<del> children[i].link(jqLite(childNodes[paths[i]]), childScope);
<del> else
<del> delete paths[i]; // if child no longer available, delete path
<add> addAttrInterpolateDirective(directives, value, nName);
<add> addDirective(directives, nName, 'A');
<ide> }
<del> },
<ide>
<del>
<del> addLinkFn:function(linkingFn) {
<del> if (linkingFn) {
<del> this.linkFns.push(linkingFn);
<add> // use class as directive
<add> className = node.className;
<add> while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
<add> nName = directiveNormalize(match[2]);
<add> if (addDirective(directives, nName, 'C')) {
<add> attrs[nName] = trim(match[3]);
<add> }
<add> className = className.substr(match.index + match[0].length);
<ide> }
<del> },
<add> break;
<add> case 3: /* Text Node */
<add> addTextInterpolateDirective(directives, node.nodeValue);
<add> break;
<add> case 8: /* Comment */
<add> match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
<add> if (match) {
<add> nName = directiveNormalize(match[1]);
<add> if (addDirective(directives, nName, 'M')) {
<add> attrs[nName] = trim(match[2]);
<add> }
<add> }
<add> break;
<add> }
<add>
<add> directives.sort(byPriority);
<add> return directives;
<add> }
<ide>
<ide>
<del> addChild: function(index, template) {
<del> if (template) {
<del> this.paths.push(index);
<del> this.children.push(template);
<add> /**
<add> * Once the directives have been collected their compile functions is executed. This method
<add> * is responsible for inlining widget templates as well as terminating the application
<add> * of the directives if the terminal directive has been reached..
<add> *
<add> * @param {Array} directives Array of collected directives to execute their compile function.
<add> * this needs to be pre-sorted by priority order.
<add> * @param {Node} templateNode The raw DOM node to apply the compile functions to
<add> * @param {Object} templateAttrs The shared attribute function
<add> * @param {DOMElement} rootElement If we are working on the root of the compile tree then this
<add> * argument has the root jqLite array so that we can replace widgets on it.
<add> * @returns linkingFn
<add> */
<add> function applyDirectivesToNode(directives, templateNode, templateAttrs, rootElement) {
<add> var terminalPriority = -Number.MAX_VALUE,
<add> preLinkingFns = [],
<add> postLinkingFns = [],
<add> newScopeDirective = null,
<add> templateDirective = null,
<add> delayedLinkingFn = null,
<add> element = templateAttrs.$element = jqLite(templateNode),
<add> directive, linkingFn;
<add>
<add> // executes all directives on the current element
<add> for(var i = 0, ii = directives.length; i < ii; i++) {
<add> directive = directives[i];
<add>
<add> if (terminalPriority > directive.priority) {
<add> break; // prevent further processing of directives
<add> }
<add>
<add> if (directive.scope) {
<add> assertNoDuplicate('new scope', newScopeDirective, directive, element);
<add> newScopeDirective = directive;
<add> }
<add>
<add> if (directive.template) {
<add> assertNoDuplicate('template', templateDirective, directive, element);
<add> templateDirective = directive;
<add>
<add> // include the contents of the original element into the template and replace the element
<add> var content = directive.template.replace(CONTENT_REGEXP, element.html());
<add> templateNode = jqLite(content)[0];
<add> if (directive.replace) {
<add> replaceWith(rootElement, element, templateNode);
<add>
<add> var newTemplateAttrs = {$attr: {}};
<add>
<add> // combine directives from the original node and from the template:
<add> // - take the array of directives for this element
<add> // - split it into two parts, those that were already applied and those that weren't
<add> // - collect directives from the template, add them to the second group and sort them
<add> // - append the second group with new directives to the first group
<add> directives = directives.concat(
<add> collectDirectives(
<add> templateNode,
<add> directives.splice(i + 1, directives.length - (i + 1)),
<add> newTemplateAttrs
<add> )
<add> );
<add> mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
<add>
<add> ii = directives.length;
<add> } else {
<add> element.html(content);
<add> }
<add> }
<add>
<add> if (directive.templateUrl) {
<add> assertNoDuplicate('template', templateDirective, directive, element);
<add> templateDirective = directive;
<add> delayedLinkingFn = compileTemplateUrl(directives.splice(i, directives.length - i),
<add> compositeLinkFn, element, templateAttrs, rootElement, directive.replace);
<add> ii = directives.length;
<add> } else if (directive.compile) {
<add> try {
<add> linkingFn = directive.compile(element, templateAttrs);
<add> if (isFunction(linkingFn)) {
<add> postLinkingFns.push(linkingFn);
<add> } else if (linkingFn) {
<add> if (linkingFn.pre) preLinkingFns.push(linkingFn.pre);
<add> if (linkingFn.post) postLinkingFns.push(linkingFn.post);
<add> }
<add> } catch (e) {
<add> $exceptionHandler(e, startingTag(element));
<ide> }
<del> },
<add> }
<ide>
<del> empty: function() {
<del> return this.linkFns.length === 0 && this.paths.length === 0;
<add> if (directive.terminal) {
<add> compositeLinkFn.terminal = true;
<add> terminalPriority = Math.max(terminalPriority, directive.priority);
<ide> }
<del> };
<ide>
<del> ///////////////////////////////////
<del> //Compiler
<del> //////////////////////////////////
<del>
<del> /**
<del> * @ngdoc function
<del> * @name angular.module.ng.$compile
<del> * @function
<del> *
<del> * @description
<del> * Compiles a piece of HTML string or DOM into a template and produces a template function, which
<del> * can then be used to link {@link angular.module.ng.$rootScope.Scope scope} and the template together.
<del> *
<del> * The compilation is a process of walking the DOM tree and trying to match DOM elements to
<del> * {@link angular.markup markup}, {@link angular.attrMarkup attrMarkup},
<del> * {@link angular.widget widgets}, and {@link angular.directive directives}. For each match it
<del> * executes corresponding markup, attrMarkup, widget or directive template function and collects the
<del> * instance functions into a single template function which is then returned.
<del> *
<del> * The template function can then be used once to produce the view or as it is the case with
<del> * {@link angular.widget.@ng:repeat repeater} many-times, in which case each call results in a view
<del> * that is a DOM clone of the original template.
<del> *
<del> <pre>
<del> angular.injector(['ng']).invoke(function($rootScope, $compile) {
<del> // Chose one:
<del>
<del> // A: compile the entire window.document.
<del> var element = $compile(window.document)($rootScope);
<del>
<del> // B: compile a piece of html
<del> var element = $compile('<div ng:click="clicked = true">click me</div>')($rootScope);
<del>
<del> // C: compile a piece of html and retain reference to both the dom and scope
<del> var element = $compile('<div ng:click="clicked = true">click me</div>')(scope);
<del> // at this point template was transformed into a view
<del> });
<del> </pre>
<del> *
<del> *
<del> * @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
<del> * (a DOM element/tree) to a scope. Where:
<del> *
<del> * * `scope` - A {@link angular.module.ng.$rootScope.Scope Scope} to bind to.
<del> * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
<del> * `template` and call the `cloneAttachFn` function allowing the caller to attach the
<del> * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
<del> * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
<del> *
<del> * * `clonedElement` - is a clone of the original `element` passed into the compiler.
<del> * * `scope` - is the current scope with which the linking function is working with.
<del> *
<del> * Calling the template function returns the element of the template. It is either the original element
<del> * passed in, or the clone of the element if the `cloneAttachFn` is provided.
<del> *
<del> * It is important to understand that the returned scope is "linked" to the view DOM, but no linking
<del> * (instance) functions registered by {@link angular.directive directives} or
<del> * {@link angular.widget widgets} found in the template have been executed yet. This means that the
<del> * view is likely empty and doesn't contain any values that result from evaluation on the scope. To
<del> * bring the view to life, the scope needs to run through a $digest phase which typically is done by
<del> * Angular automatically, except for the case when an application is being
<del> * {@link guide/dev_guide.bootstrap.manual_bootstrap} manually bootstrapped, in which case the
<del> * $digest phase must be invoked by calling {@link angular.module.ng.$rootScope.Scope#$apply}.
<del> *
<del> * If you need access to the bound view, there are two ways to do it:
<del> *
<del> * - If you are not asking the linking function to clone the template, create the DOM element(s)
<del> * before you send them to the compiler and keep this reference around.
<del> * <pre>
<del> * var $injector = angular.injector(['ng']);
<del> * var scope = $injector.invoke(function($rootScope, $compile){
<del> * var element = $compile('<p>{{total}}</p>')($rootScope);
<del> * });
<del> * </pre>
<del> *
<del> * - if on the other hand, you need the element to be cloned, the view reference from the original
<del> * example would not point to the clone, but rather to the original template that was cloned. In
<del> * this case, you can access the clone via the cloneAttachFn:
<del> * <pre>
<del> * var original = angular.element('<p>{{total}}</p>'),
<del> * scope = someParentScope.$new(),
<del> * clone;
<del> *
<del> * $compile(original)(scope, function(clonedElement, scope) {
<del> * clone = clonedElement;
<del> * //attach the clone to DOM document at the right place
<del> * });
<del> *
<del> * //now we have reference to the cloned DOM via `clone`
<del> * </pre>
<del> *
<del> *
<del> * Compiler Methods For Widgets and Directives:
<del> *
<del> * The following methods are available for use when you write your own widgets, directives,
<del> * and markup. (Recall that the compile function's this is a reference to the compiler.)
<del> *
<del> * `compile(element)` - returns linker -
<del> * Invoke a new instance of the compiler to compile a DOM element and return a linker function.
<del> * You can apply the linker function to the original element or a clone of the original element.
<del> * The linker function returns a scope.
<del> *
<del> * * `comment(commentText)` - returns element - Create a comment element.
<del> *
<del> * * `element(elementName)` - returns element - Create an element by name.
<del> *
<del> * * `text(text)` - returns element - Create a text element.
<del> *
<del> * * `descend([set])` - returns descend state (true or false). Get or set the current descend
<del> * state. If true the compiler will descend to children elements.
<del> *
<del> * * `directives([set])` - returns directive state (true or false). Get or set the current
<del> * directives processing state. The compiler will process directives only when directives set to
<del> * true.
<del> *
<del> * For information on how the compiler works, see the
<del> * {@link guide/dev_guide.compiler Angular HTML Compiler} section of the Developer Guide.
<del> */
<del> function Compiler(markup, attrMarkup, directives, widgets){
<del> this.markup = markup;
<del> this.attrMarkup = attrMarkup;
<del> this.directives = directives;
<del> this.widgets = widgets;
<ide> }
<add> compositeLinkFn.scope = !!newScopeDirective;
<add>
<add> // if we have templateUrl, then we have to delay linking
<add> return delayedLinkingFn || compositeLinkFn;
<ide>
<del> Compiler.prototype = {
<del> compile: function(templateElement) {
<del> templateElement = jqLite(templateElement);
<del> var index = 0,
<del> template,
<del> parent = templateElement.parent();
<del> if (templateElement.length > 1) {
<del> // https://github.com/angular/angular.js/issues/338
<del> throw Error("Cannot compile multiple element roots: " +
<del> jqLite('<div>').append(templateElement.clone()).html());
<add> ////////////////////
<add>
<add>
<add> function compositeLinkFn(childLinkingFn, scope, linkNode) {
<add> var attrs, element, i, ii;
<add>
<add> if (templateNode === linkNode) {
<add> attrs = templateAttrs;
<add> } else {
<add> attrs = shallowCopy(templateAttrs);
<add> attrs.$element = jqLite(linkNode);
<add> }
<add> element = attrs.$element;
<add>
<add> // PRELINKING
<add> for(i = 0, ii = preLinkingFns.length; i < ii; i++) {
<add> try {
<add> preLinkingFns[i](scope, element, attrs);
<add> } catch (e) {
<add> $exceptionHandler(e, startingTag(element));
<ide> }
<del> if (parent && parent[0]) {
<del> parent = parent[0];
<del> for(var i = 0; i < parent.childNodes.length; i++) {
<del> if (parent.childNodes[i] == templateElement[0]) {
<del> index = i;
<del> }
<del> }
<add> }
<add>
<add> // RECURSION
<add> childLinkingFn && childLinkingFn(scope, linkNode.childNodes);
<add>
<add> // POSTLINKING
<add> for(i = 0, ii = postLinkingFns.length; i < ii; i++) {
<add> try {
<add> postLinkingFns[i](scope, element, attrs);
<add> } catch (e) {
<add> $exceptionHandler(e, startingTag(element));
<ide> }
<del> template = this.templatize(templateElement, index) || new Template();
<del> return function(scope, cloneConnectFn){
<del> assertArg(scope, 'scope');
<del> // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
<del> // and sometimes changes the structure of the DOM.
<del> var element = cloneConnectFn
<del> ? JQLitePrototype.clone.call(templateElement) // IMPORTANT!!!
<del> : templateElement;
<del> element.data($$scope, scope);
<del> scope.$element = element;
<del> (cloneConnectFn||noop)(element, scope);
<del> template.link(element, scope);
<del> return element;
<del> };
<del> },
<del>
<del> templatize: function(element, elementIndex){
<del> var self = this,
<del> widget,
<del> fn,
<del> directiveFns = self.directives,
<del> descend = true,
<del> directives = true,
<del> elementName = nodeName_(element),
<del> elementNamespace = elementName.indexOf(':') > 0 ? lowercase(elementName).replace(':', '-') : '',
<del> template,
<del> locals = {$element: element},
<del> selfApi = {
<del> compile: bind(self, self.compile),
<del> descend: function(value){ if(isDefined(value)) descend = value; return descend;},
<del> directives: function(value){ if(isDefined(value)) directives = value; return directives;},
<del> scope: function(value){ if(isDefined(value)) template.newScope = template.newScope || value; return template.newScope;}
<del> };
<del> element.addClass(elementNamespace);
<del> template = new Template();
<del> eachAttribute(element, function(value, name){
<del> if (!widget) {
<del> if ((widget = self.widgets('@' + name))) {
<del> element.addClass('ng-attr-widget');
<del> if (isFunction(widget) && !widget.$inject) {
<del> widget.$inject = ['$value', '$element'];
<del> }
<del> locals.$value = value;
<del> }
<del> }
<del> });
<del> if (!widget) {
<del> if ((widget = self.widgets(elementName))) {
<del> if (elementNamespace)
<del> element.addClass('ng-widget');
<del> if (isFunction(widget) && !widget.$inject) {
<del> widget.$inject = ['$element'];
<del> }
<add> }
<add> }
<add> }
<add>
<add>
<add> /**
<add> * looks up the directive and decorates it with exception handling and proper parameters. We
<add> * call this the boundDirective.
<add> *
<add> * @param {string} name name of the directive to look up.
<add> * @param {string} location The directive must be found in specific format.
<add> * String containing any of theses characters:
<add> *
<add> * * `E`: element name
<add> * * `A': attribute
<add> * * `C`: class
<add> * * `M`: comment
<add> * @returns true if directive was added.
<add> */
<add> function addDirective(tDirectives, name, location) {
<add> var match = false;
<add> if (hasDirectives.hasOwnProperty(name)) {
<add> for(var directive, directives = $injector.get(name + Suffix),
<add> i=0, ii = directives.length; i<ii; i++) {
<add> try {
<add> directive = directives[i];
<add> if (directive.restrict.indexOf(location) != -1) {
<add> tDirectives.push(directive);
<add> match = true;
<ide> }
<add> } catch(e) { $exceptionHandler(e); }
<add> }
<add> }
<add> return match;
<add> }
<add>
<add>
<add> /**
<add> * When the element is replaced with HTML template then the new attributes
<add> * on the template need to be merged with the existing attributes in the DOM.
<add> * The desired effect is to have both of the attributes present.
<add> *
<add> * @param {object} dst destination attributes (original DOM)
<add> * @param {object} src source attributes (from the directive template)
<add> */
<add> function mergeTemplateAttributes(dst, src) {
<add> var srcAttr = src.$attr,
<add> dstAttr = dst.$attr,
<add> element = dst.$element;
<add> // reapply the old attributes to the new element
<add> forEach(dst, function(value, key) {
<add> if (key.charAt(0) != '$') {
<add> dst.$set(key, value, srcAttr[key]);
<add> }
<add> });
<add> // copy the new attributes on the old attrs object
<add> forEach(src, function(value, key) {
<add> if (key == 'class') {
<add> element.addClass(value);
<add> } else if (key == 'style') {
<add> element.attr('style', element.attr('style') + ';' + value);
<add> } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
<add> dst[key] = value;
<add> dstAttr[key] = srcAttr[key];
<add> }
<add> });
<add> }
<add>
<add>
<add> function compileTemplateUrl(directives, beforeWidgetLinkFn, tElement, tAttrs, rootElement,
<add> replace) {
<add> var linkQueue = [],
<add> afterWidgetLinkFn,
<add> afterWidgetChildrenLinkFn,
<add> originalWidgetNode = tElement[0],
<add> asyncWidgetDirective = directives.shift(),
<add> // The fact that we have to copy and patch the directive seems wrong!
<add> syncWidgetDirective = extend({}, asyncWidgetDirective, {templateUrl:null}),
<add> html = tElement.html();
<add>
<add> tElement.html('');
<add>
<add> $http.get(asyncWidgetDirective.templateUrl, {cache: $templateCache}).
<add> success(function(content) {
<add> content = trim(content).replace(CONTENT_REGEXP, html);
<add> if (replace && !content.match(HAS_ROOT_ELEMENT)) {
<add> throw Error('Template must have exactly one root element: ' + content);
<ide> }
<del> if (widget) {
<del> descend = false;
<del> directives = false;
<del> var parent = element.parent();
<del> template.addLinkFn($injector.invoke(widget, selfApi, locals));
<del> if (parent && parent[0]) {
<del> element = jqLite(parent[0].childNodes[elementIndex]);
<del> }
<add>
<add> var templateNode, tempTemplateAttrs;
<add>
<add> if (replace) {
<add> tempTemplateAttrs = {$attr: {}};
<add> templateNode = jqLite(content)[0];
<add> replaceWith(rootElement, tElement, templateNode);
<add> collectDirectives(tElement[0], directives, tempTemplateAttrs);
<add> mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
<add> } else {
<add> templateNode = tElement[0];
<add> tElement.html(content);
<ide> }
<del> if (descend){
<del> // process markup for text nodes only
<del> for(var i=0, child=element[0].childNodes;
<del> i<child.length; i++) {
<del> if (isTextNode(child[i])) {
<del> forEach(self.markup, function(markup){
<del> if (i<child.length) {
<del> var textNode = jqLite(child[i]);
<del> markup.call(selfApi, textNode.text(), textNode, element);
<del> }
<del> });
<del> }
<add>
<add> directives.unshift(syncWidgetDirective);
<add> afterWidgetLinkFn = applyDirectivesToNode(directives, tElement, tAttrs);
<add> afterWidgetChildrenLinkFn = compileNodes(tElement.contents());
<add>
<add>
<add> while(linkQueue.length) {
<add> var linkRootElement = linkQueue.pop(),
<add> cLinkNode = linkQueue.pop(),
<add> scope = linkQueue.pop(),
<add> node = templateNode;
<add>
<add> if (cLinkNode !== originalWidgetNode) {
<add> // it was cloned therefore we have to clone as well.
<add> node = JQLiteClone(templateNode);
<add> replaceWith(linkRootElement, jqLite(cLinkNode), node);
<ide> }
<add> afterWidgetLinkFn(function() {
<add> beforeWidgetLinkFn(afterWidgetChildrenLinkFn, scope, node);
<add> }, scope, node);
<ide> }
<add> linkQueue = null;
<add> }).
<add> error(function(response, code, headers, config) {
<add> throw Error('Failed to load template: ' + config.url);
<add> });
<ide>
<del> if (directives) {
<del> // Process attributes/directives
<del> eachAttribute(element, function(value, name){
<del> forEach(self.attrMarkup, function(markup){
<del> markup.call(selfApi, value, name, element);
<del> });
<del> });
<del> eachAttribute(element, function(value, name){
<del> name = lowercase(name);
<del> fn = directiveFns[name];
<del> if (fn) {
<del> element.addClass('ng-directive');
<del> template.addLinkFn((isArray(fn) || fn.$inject)
<del> ? $injector.invoke(fn, selfApi, {$value:value, $element: element})
<del> : fn.call(selfApi, value, element));
<del> }
<add> return function(ignoreChildLinkingFn, scope, node, rootElement) {
<add> if (linkQueue) {
<add> linkQueue.push(scope);
<add> linkQueue.push(node);
<add> linkQueue.push(rootElement);
<add> } else {
<add> afterWidgetLinkFn(function() {
<add> beforeWidgetLinkFn(afterWidgetChildrenLinkFn, scope, node);
<add> }, scope, node);
<add> }
<add> };
<add> }
<add>
<add>
<add> /**
<add> * Sorting function for bound directives.
<add> */
<add> function byPriority(a, b) {
<add> return b.priority - a.priority;
<add> }
<add>
<add>
<add> function assertNoDuplicate(what, previousDirective, directive, element) {
<add> if (previousDirective) {
<add> throw Error('Multiple directives [' + previousDirective.name + ', ' +
<add> directive.name + '] asking for ' + what + ' on: ' + startingTag(element));
<add> }
<add> }
<add>
<add>
<add> function addTextInterpolateDirective(directives, text) {
<add> var interpolateFn = $interpolate(text, true);
<add> if (interpolateFn) {
<add> directives.push({
<add> priority: 0,
<add> compile: valueFn(function(scope, node) {
<add> var parent = node.parent(),
<add> bindings = parent.data('$binding') || [];
<add> bindings.push(interpolateFn);
<add> parent.data('$binding', bindings).addClass('ng-binding');
<add> scope.$watch(interpolateFn, function(scope, value) {
<add> node[0].nodeValue = value;
<ide> });
<add> })
<add> });
<add> }
<add> }
<add>
<add>
<add> function addAttrInterpolateDirective(directives, value, name) {
<add> var interpolateFn = $interpolate(value, true);
<add> if (SIDE_EFFECT_ATTRS[name]) {
<add> name = SIDE_EFFECT_ATTRS[name];
<add> if (BOOLEAN_ATTR[name]) {
<add> value = true;
<add> }
<add> } else if (!interpolateFn) {
<add> // we are not a side-effect attr, and we have no side-effects -> ignore
<add> return;
<add> }
<add> directives.push({
<add> priority: 100,
<add> compile: function(element, attr) {
<add> if (interpolateFn) {
<add> return function(scope, element, attr) {
<add> scope.$watch(interpolateFn, function(scope, value){
<add> attr.$set(name, value);
<add> });
<add> };
<add> } else {
<add> attr.$set(name, value);
<ide> }
<del> // Process non text child nodes
<del> if (descend) {
<del> eachNode(element, function(child, i){
<del> template.addChild(i, self.templatize(child, i));
<del> });
<add> }
<add> });
<add> }
<add>
<add>
<add> /**
<add> * This is a special jqLite.replaceWith, which can replace items which
<add> * have no parents, provided that the containing jqLite collection is provided.
<add> *
<add> * @param {JqLite=} rootElement The root of the compile tree. Used so that we can replace nodes
<add> * in the root of the tree.
<add> * @param {JqLite} element The jqLite element which we are going to replace. We keep the shell,
<add> * but replace its DOM node reference.
<add> * @param {Node} newNode The new DOM node.
<add> */
<add> function replaceWith(rootElement, element, newNode) {
<add> var oldNode = element[0],
<add> parent = oldNode.parentNode,
<add> i, ii;
<add>
<add> if (rootElement) {
<add> for(i = 0, ii = rootElement.length; i<ii; i++) {
<add> if (rootElement[i] == oldNode) {
<add> rootElement[i] = newNode;
<ide> }
<del> return template.empty() ? null : template;
<ide> }
<del> };
<add> }
<add> if (parent) {
<add> parent.replaceChild(newNode, oldNode);
<add> }
<add> element[0] = newNode;
<add> }
<add> }];
<ide>
<del> /////////////////////////////////////////////////////////////////////
<del> var compiler = new Compiler($textMarkup, $attrMarkup, $directive, $widget);
<del> return bind(compiler, compiler.compile);
<del> }];
<del>};
<ide>
<add> /**
<add> * Set a normalized attribute on the element in a way such that all directives
<add> * can share the attribute. This function properly handles boolean attributes.
<add> * @param {string} key Normalized key. (ie ngAttribute)
<add> * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
<add> * @param {string=} attrName Optional none normalized name. Defaults to key.
<add> */
<add> function attrSetter(key, value, attrName) {
<add> var booleanKey = BOOLEAN_ATTR[key.toLowerCase()];
<ide>
<del>function eachNode(element, fn){
<del> var i, chldNodes = element[0].childNodes || [], chld;
<del> for (i = 0; i < chldNodes.length; i++) {
<del> if(!isTextNode(chld = chldNodes[i])) {
<del> fn(jqLite(chld), i);
<add> if (booleanKey) {
<add> value = toBoolean(value);
<add> this.$element.prop(key, value);
<add> this[key] = value;
<add> attrName = key = booleanKey;
<add> value = value ? booleanKey : undefined;
<add> } else {
<add> this[key] = value;
<add> }
<add>
<add> // translate normalized key to actual key
<add> if (attrName) {
<add> this.$attr[key] = attrName;
<add> } else {
<add> attrName = this.$attr[key];
<add> if (!attrName) {
<add> this.$attr[key] = attrName = snake_case(key, '-');
<add> }
<ide> }
<del> }
<del>}
<ide>
<del>function eachAttribute(element, fn){
<del> var i, attrs = element[0].attributes || [], chld, attr, name, value, attrValue = {};
<del> for (i = 0; i < attrs.length; i++) {
<del> attr = attrs[i];
<del> name = attr.name;
<del> value = attr.value;
<del> if (msie && name == 'href') {
<del> value = decodeURIComponent(element[0].getAttribute(name, 2));
<add> if (value === null || value === undefined) {
<add> this.$element.removeAttr(attrName);
<add> } else {
<add> this.$element.attr(attrName, value);
<ide> }
<del> attrValue[name] = value;
<ide> }
<del> forEachSorted(attrValue, fn);
<add>}
<add>
<add>var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
<add>/**
<add> * Converts all accepted directives format into proper directive name.
<add> * All of these will become 'myDirective':
<add> * my:DiRective
<add> * my-directive
<add> * x-my-directive
<add> * data-my:directive
<add> *
<add> * Also there is special case for Moz prefix starting with upper case letter.
<add> * @param name Name to normalize
<add> */
<add>function directiveNormalize(name) {
<add> return camelCase(name.replace(PREFIX_REGEXP, ''));
<ide> }
<ide><path>src/service/formFactory.js
<ide> });
<ide> }
<ide>
<del> angular.directive('ng:contenteditable', function() {
<del> return ['$formFactory', '$element', function ($formFactory, element) {
<del> var exp = element.attr('ng:contenteditable'),
<del> form = $formFactory.forElement(element),
<del> widget;
<del> element.attr('contentEditable', true);
<del> widget = form.$createWidget({
<del> scope: this,
<del> model: exp,
<del> controller: HTMLEditorWidget,
<del> controllerArgs: {$element: element}});
<del> // if the element is destroyed, then we need to notify the form.
<del> element.bind('$destroy', function() {
<del> widget.$destroy();
<del> });
<del> }];
<del> });
<del> </script>
<del> <form name='editorForm' ng:controller="EditorCntl">
<del> <div ng:contenteditable="html"></div>
<del> <hr/>
<del> HTML: <br/>
<del> <textarea ng:model="html" cols=80></textarea>
<del> <hr/>
<del> <pre>editorForm = {{editorForm}}</pre>
<del> </form>
<del> </doc:source>
<del> <doc:scenario>
<del> it('should enter invalid HTML', function() {
<del> expect(element('form[name=editorForm]').prop('className')).toMatch(/ng-valid/);
<del> input('html').enter('<');
<del> expect(element('form[name=editorForm]').prop('className')).toMatch(/ng-invalid/);
<del> });
<del> </doc:scenario>
<del> </doc:example>
<add> angular.module('formModule', [], function($compileProvider){
<add> $compileProvider.directive('ngHtmlEditorModel', function ($formFactory) {
<add> return function(scope, element, attr) {
<add> var form = $formFactory.forElement(element),
<add> widget;
<add> element.attr('contentEditable', true);
<add> widget = form.$createWidget({
<add> scope: scope,
<add> model: attr.ngHtmlEditorModel,
<add> controller: HTMLEditorWidget,
<add> controllerArgs: {$element: element}});
<add> // if the element is destroyed, then we need to
<add> // notify the form.
<add> element.bind('$destroy', function() {
<add> widget.$destroy();
<add> });
<add> };
<add> });
<add> });
<add> </script>
<add> <form name='editorForm' ng:controller="EditorCntl">
<add> <div ng:html-editor-model="htmlContent"></div>
<add> <hr/>
<add> HTML: <br/>
<add> <textarea ng:model="htmlContent" cols="80"></textarea>
<add> <hr/>
<add> <pre>editorForm = {{editorForm|json}}</pre>
<add> </form>
<add> </doc:source>
<add> <doc:scenario>
<add> it('should enter invalid HTML', function() {
<add> expect(element('form[name=editorForm]').prop('className')).toMatch(/ng-valid/);
<add> input('htmlContent').enter('<');
<add> expect(element('form[name=editorForm]').prop('className')).toMatch(/ng-invalid/);
<add> });
<add> </doc:scenario>
<add> </doc:example>
<ide> */
<ide>
<ide> /**
<ide><path>test/AngularSpec.js
<ide> describe('angular', function() {
<ide> });
<ide> });
<ide>
<add> describe('shallow copy', function() {
<add> it('should make a copy', function() {
<add> var original = {key:{}};
<add> var copy = shallowCopy(original);
<add> expect(copy).toEqual(original);
<add> expect(copy.key).toBe(original.key);
<add> });
<add> });
<add>
<add> describe('elementHTML', function() {
<add> it('should dump element', function() {
<add> expect(lowercase(startingTag('<div attr="123">something<span></span></div>'))).
<add> toEqual('<div attr="123">');
<add> });
<add> });
<add>
<ide> describe('equals', function() {
<ide> it('should return true if same object', function() {
<ide> var o = {};
<ide> describe('angular', function() {
<ide> dealoc(element);
<ide> });
<ide> });
<add>
<add>
<add> describe('startingElementHtml', function(){
<add> it('should show starting element tag only', function(){
<add> expect(startingTag('<ng:abc x="2"><div>text</div></ng:abc>')).toEqual('<ng:abc x="2">');
<add> });
<add> });
<ide> });
<ide><path>test/directivesSpec.js
<ide>
<ide> describe("directive", function() {
<ide>
<del> var $filterProvider;
<add> var $filterProvider, element;
<ide>
<ide> beforeEach(module(['$filterProvider', function(provider){
<ide> $filterProvider = provider;
<ide> }]));
<ide>
<add> afterEach(function() {
<add> dealoc(element);
<add> });
<add>
<ide> it("should ng:init", inject(function($rootScope, $compile) {
<del> var element = $compile('<div ng:init="a=123"></div>')($rootScope);
<add> element = $compile('<div ng:init="a=123"></div>')($rootScope);
<ide> expect($rootScope.a).toEqual(123);
<ide> }));
<ide>
<ide><path>test/jqLiteSpec.js
<del>'use strict';
<ide>
<ide> describe('jqLite', function() {
<ide> var scope, a, b, c;
<ide> describe('jqLite', function() {
<ide> it('should covert dash-separated strings to camelCase', function() {
<ide> expect(camelCase('foo-bar')).toBe('fooBar');
<ide> expect(camelCase('foo-bar-baz')).toBe('fooBarBaz');
<add> expect(camelCase('foo:bar_baz')).toBe('fooBarBaz');
<ide> });
<ide>
<ide>
<ide><path>test/service/compilerSpec.js
<ide> 'use strict';
<ide>
<del>describe('compiler', function() {
<del> var textMarkup, attrMarkup, directives, widgets, compile, log;
<del>
<del> beforeEach(module(function($provide){
<del> textMarkup = [];
<del> attrMarkup = [];
<del> widgets = extensionMap({}, 'widget');
<del> directives = {
<del> hello: function(expression, element){
<del> log += "hello ";
<del> return function() {
<del> log += expression;
<del> };
<del> },
<del>
<del> observe: function(expression, element){
<del> return function() {
<del> this.$watch(expression, function(val) {
<del> if (val)
<del> log += ":" + val;
<del> });
<del> };
<del> }
<del>
<del> };
<del> log = "";
<del> $provide.value('$textMarkup', textMarkup);
<del> $provide.value('$attrMarkup', attrMarkup);
<del> $provide.value('$directive', directives);
<del> $provide.value('$widget', widgets);
<del> }));
<add>describe('$compile', function() {
<add> var element;
<ide>
<add> beforeEach(module(provideLog, function($provide, $compileProvider){
<add> element = null;
<ide>
<del> it('should not allow compilation of multiple roots', inject(function($rootScope, $compile) {
<del> expect(function() {
<del> $compile('<div>A</div><span></span>');
<del> }).toThrow("Cannot compile multiple element roots: " + ie("<div>A</div><span></span>"));
<del> function ie(text) {
<del> return msie < 9 ? uppercase(text) : text;
<del> }
<del> }));
<add> $compileProvider.directive('log', function(log) {
<add> return {
<add> priority:0,
<add> compile: valueFn(function(scope, element, attrs) {
<add> log(attrs.log || 'LOG');
<add> })
<add> };
<add> });
<add>
<add> $compileProvider.directive('highLog', function(log) {
<add> return { priority:3, compile: valueFn(function(scope, element, attrs) {
<add> log(attrs.highLog || 'HIGH');
<add> })};
<add> });
<add>
<add> $compileProvider.directive('mediumLog', function(log) {
<add> return { priority:2, compile: valueFn(function(scope, element, attrs) {
<add> log(attrs.mediumLog || 'MEDIUM');
<add> })};
<add> });
<ide>
<add> $compileProvider.directive('greet', function() {
<add> return { priority:10, compile: valueFn(function(scope, element, attrs) {
<add> element.text("Hello " + attrs.greet);
<add> })};
<add> });
<ide>
<del> it('should recognize a directive', inject(function($rootScope, $compile) {
<del> var e = jqLite('<div directive="expr" ignore="me"></div>');
<del> directives.directive = function(expression, element){
<del> log += "found";
<del> expect(expression).toEqual("expr");
<del> expect(element).toEqual(e);
<del> return function initFn() {
<del> log += ":init";
<add> $compileProvider.directive('set', function() {
<add> return function(scope, element, attrs) {
<add> element.text(attrs.set);
<ide> };
<del> };
<del> var linkFn = $compile(e);
<del> expect(log).toEqual("found");
<del> linkFn($rootScope);
<del> expect(e.hasClass('ng-directive')).toEqual(true);
<del> expect(log).toEqual("found:init");
<del> }));
<add> });
<ide>
<add> $compileProvider.directive('mediumStop', valueFn({
<add> priority: 2,
<add> terminal: true
<add> }));
<ide>
<del> it('should recurse to children', inject(function($rootScope, $compile) {
<del> $compile('<div><span hello="misko"/></div>')($rootScope);
<del> expect(log).toEqual("hello misko");
<add> $compileProvider.directive('stop', valueFn({
<add> terminal: true
<add> }));
<add>
<add> $compileProvider.directive('negativeStop', valueFn({
<add> priority: -100, // even with negative priority we still should be able to stop descend
<add> terminal: true
<add> }));
<ide> }));
<ide>
<ide>
<del> it('should observe scope', inject(function($rootScope, $compile) {
<del> $compile('<span observe="name"></span>')($rootScope);
<del> expect(log).toEqual("");
<del> $rootScope.$digest();
<del> $rootScope.name = 'misko';
<del> $rootScope.$digest();
<del> $rootScope.$digest();
<del> $rootScope.name = 'adam';
<del> $rootScope.$digest();
<del> $rootScope.$digest();
<del> expect(log).toEqual(":misko:adam");
<del> }));
<add> afterEach(function(){
<add> dealoc(element);
<add> });
<ide>
<ide>
<del> it('should prevent descend', inject(function($rootScope, $compile) {
<del> directives.stop = function() { this.descend(false); };
<del> $compile('<span hello="misko" stop="true"><span hello="adam"/></span>')($rootScope);
<del> expect(log).toEqual("hello misko");
<del> }));
<add> describe('configuration', function() {
<add> it('should register a directive', function() {
<add> module(function($compileProvider) {
<add> $compileProvider.directive('div', function(log) {
<add> return function(scope, element) {
<add> log('OK');
<add> element.text('SUCCESS');
<add> };
<add> })
<add> });
<add> inject(function($compile, $rootScope, log) {
<add> element = $compile('<div></div>')($rootScope);
<add> expect(element.text()).toEqual('SUCCESS');
<add> expect(log).toEqual('OK');
<add> })
<add> });
<ide>
<add> it('should allow registration of multiple directives with same name', function() {
<add> module(function($compileProvider) {
<add> $compileProvider.directive('div', function(log) {
<add> return log.fn('1');
<add> });
<add> $compileProvider.directive('div', function(log) {
<add> return log.fn('2');
<add> });
<add> });
<add> inject(function($compile, $rootScope, log) {
<add> element = $compile('<div></div>')($rootScope);
<add> expect(log).toEqual('1; 2');
<add> });
<add> });
<add> });
<add>
<add>
<add> describe('compile phase', function() {
<add>
<add> describe('multiple directives per element', function() {
<add> it('should allow multiple directives per element', inject(function($compile, $rootScope, log){
<add> element = $compile(
<add> '<span greet="angular" log="L" x-high-log="H" data-medium-log="M"></span>')
<add> ($rootScope);
<add> expect(element.text()).toEqual('Hello angular');
<add> expect(log).toEqual('H; M; L');
<add> }));
<add>
<add>
<add> it('should recurse to children', inject(function($compile, $rootScope){
<add> element = $compile('<div>0<a set="hello">1</a>2<b set="angular">3</b>4</div>')($rootScope);
<add> expect(element.text()).toEqual('0hello2angular4');
<add> }));
<ide>
<del> it('should allow creation of templates', inject(function($rootScope, $compile) {
<del> directives.duplicate = function(expr, element){
<del> element.replaceWith(document.createComment("marker"));
<del> element.removeAttr("duplicate");
<del> var linker = this.compile(element);
<del> return function(marker) {
<del> this.$watch('value', function() {
<del> var scope = $rootScope.$new;
<del> linker(scope, noop);
<del> marker.after(scope.$element);
<add>
<add> it('should allow directives in classes', inject(function($compile, $rootScope, log) {
<add> element = $compile('<div class="greet: angular; log:123;"></div>')($rootScope);
<add> expect(element.html()).toEqual('Hello angular');
<add> expect(log).toEqual('123');
<add> }));
<add>
<add>
<add> it('should allow directives in comments', inject(
<add> function($compile, $rootScope, log) {
<add> element = $compile('<div>0<!-- directive: log angular -->1</div>')($rootScope);
<add> expect(log).toEqual('angular');
<add> }
<add> ));
<add>
<add>
<add> it('should receive scope, element, and attributes', function() {
<add> var injector;
<add> module(function($compileProvider) {
<add> $compileProvider.directive('log', function($injector, $rootScope) {
<add> injector = $injector;
<add> return {
<add> compile: function(element, templateAttr) {
<add> expect(typeof templateAttr.$normalize).toBe('function');
<add> expect(typeof templateAttr.$set).toBe('function');
<add> expect(isElement(templateAttr.$element)).toBeTruthy();
<add> expect(element.text()).toEqual('unlinked');
<add> expect(templateAttr.exp).toEqual('abc');
<add> expect(templateAttr.aa).toEqual('A');
<add> expect(templateAttr.bb).toEqual('B');
<add> expect(templateAttr.cc).toEqual('C');
<add> return function(scope, element, attr) {
<add> expect(element.text()).toEqual('unlinked');
<add> expect(attr).toBe(templateAttr);
<add> expect(scope).toEqual($rootScope);
<add> element.text('worked');
<add> }
<add> }
<add> };
<add> });
<ide> });
<del> };
<del> };
<del> $compile('<div>before<span duplicate="expr">x</span>after</div>')($rootScope);
<del> expect(sortedHtml($rootScope.$element)).
<del> toEqual('<div>' +
<del> 'before<#comment></#comment>' +
<del> 'after' +
<add> inject(function($rootScope, $compile, $injector) {
<add> element = $compile(
<add> '<div class="log" exp="abc" aa="A" x-Bb="B" daTa-cC="C">unlinked</div>')($rootScope);
<add> expect(element.text()).toEqual('worked');
<add> expect(injector).toBe($injector); // verify that directive is injectable
<add> });
<add> });
<add> });
<add>
<add> describe('error handling', function() {
<add>
<add> it('should handle exceptions', function() {
<add> module(function($compileProvider, $exceptionHandlerProvider) {
<add> $exceptionHandlerProvider.mode('log');
<add> $compileProvider.directive('factoryError', function() { throw 'FactoryError'; });
<add> $compileProvider.directive('templateError',
<add> valueFn({ compile: function() { throw 'TemplateError'; } }));
<add> $compileProvider.directive('linkingError',
<add> valueFn(function() { throw 'LinkingError'; }));
<add> });
<add> inject(function($rootScope, $compile, $exceptionHandler) {
<add> element = $compile('<div factory-error template-error linking-error></div>')($rootScope);
<add> expect($exceptionHandler.errors[0]).toEqual('FactoryError');
<add> expect($exceptionHandler.errors[1][0]).toEqual('TemplateError');
<add> expect(ie($exceptionHandler.errors[1][1])).
<add> toEqual('<div factory-error linking-error template-error>');
<add> expect($exceptionHandler.errors[2][0]).toEqual('LinkingError');
<add> expect(ie($exceptionHandler.errors[2][1])).
<add> toEqual('<div factory-error linking-error template-error>');
<add>
<add>
<add> // crazy stuff to make IE happy
<add> function ie(text) {
<add> var list = [],
<add> parts;
<add>
<add> parts = lowercase(text).
<add> replace('<', '').
<add> replace('>', '').
<add> split(' ');
<add> parts.sort();
<add> forEach(parts, function(value, key){
<add> if (value.substring(0,3) == 'ng-') {
<add> } else {
<add> list.push(value.replace('=""', ''));
<add> }
<add> });
<add> return '<' + list.join(' ') + '>';
<add> }
<add> });
<add> });
<add>
<add>
<add> it('should prevent changing of structure', inject(
<add> function($compile, $rootScope){
<add> element = jqLite("<div><div log></div></div>");
<add> var linkFn = $compile(element);
<add> element.append("<div></div>");
<add> expect(function() {
<add> linkFn($rootScope);
<add> }).toThrow('Template changed structure!');
<add> }
<add> ));
<add> });
<add>
<add> describe('compiler control', function() {
<add> describe('priority', function() {
<add> it('should honor priority', inject(function($compile, $rootScope, log){
<add> element = $compile(
<add> '<span log="L" x-high-log="H" data-medium-log="M"></span>')
<add> ($rootScope);
<add> expect(log).toEqual('H; M; L');
<add> }));
<add> });
<add>
<add>
<add> describe('terminal', function() {
<add>
<add> it('should prevent further directives from running', inject(function($rootScope, $compile) {
<add> element = $compile('<div negative-stop><a set="FAIL">OK</a></div>')($rootScope);
<add> expect(element.text()).toEqual('OK');
<add> }
<add> ));
<add>
<add>
<add> it('should prevent further directives from running, but finish current priority level',
<add> inject(function($rootScope, $compile, log) {
<add> // class is processed after attrs, so putting log in class will put it after
<add> // the stop in the current level. This proves that the log runs after stop
<add> element = $compile(
<add> '<div high-log medium-stop log class="medium-log"><a set="FAIL">OK</a></div>')($rootScope);
<add> expect(element.text()).toEqual('OK');
<add> expect(log.toArray().sort()).toEqual(['HIGH', 'MEDIUM']);
<add> })
<add> );
<add> });
<add>
<add>
<add> describe('restrict', function() {
<add>
<add> it('should allow restriction of attributes', function() {
<add> module(function($compileProvider, $provide) {
<add> forEach({div:'E', attr:'A', clazz:'C', all:'EAC'}, function(restrict, name) {
<add> $compileProvider.directive(name, function(log) {
<add> return {
<add> restrict: restrict,
<add> compile: valueFn(function(scope, element, attr) {
<add> log(name);
<add> })
<add> };
<add> });
<add> });
<add> });
<add> inject(function($rootScope, $compile, log) {
<add> dealoc($compile('<span div class="div"></span>')($rootScope));
<add> expect(log).toEqual('');
<add> log.reset();
<add>
<add> dealoc($compile('<div></div>')($rootScope));
<add> expect(log).toEqual('div');
<add> log.reset();
<add>
<add> dealoc($compile('<attr class=""attr"></attr>')($rootScope));
<add> expect(log).toEqual('');
<add> log.reset();
<add>
<add> dealoc($compile('<span attr></span>')($rootScope));
<add> expect(log).toEqual('attr');
<add> log.reset();
<add>
<add> dealoc($compile('<clazz clazz></clazz>')($rootScope));
<add> expect(log).toEqual('');
<add> log.reset();
<add>
<add> dealoc($compile('<span class="clazz"></span>')($rootScope));
<add> expect(log).toEqual('clazz');
<add> log.reset();
<add>
<add> dealoc($compile('<all class="all" all></all>')($rootScope));
<add> expect(log).toEqual('all; all; all');
<add> });
<add> });
<add> });
<add>
<add>
<add> describe('template', function() {
<add>
<add>
<add> beforeEach(module(function($compileProvider) {
<add> $compileProvider.directive('replace', valueFn({
<add> replace: true,
<add> template: '<div class="log" style="width: 10px" high-log>Hello: <<CONTENT>></div>',
<add> compile: function(element, attr) {
<add> attr.$set('compiled', 'COMPILED');
<add> expect(element).toBe(attr.$element);
<add> }
<add> }));
<add> $compileProvider.directive('append', valueFn({
<add> template: '<div class="log" style="width: 10px" high-log>Hello: <<CONTENT>></div>',
<add> compile: function(element, attr) {
<add> attr.$set('compiled', 'COMPILED');
<add> expect(element).toBe(attr.$element);
<add> }
<add> }));
<add> }));
<add>
<add>
<add> it('should replace element with template', inject(function($compile, $rootScope) {
<add> element = $compile('<div><div replace>content</div><div>')($rootScope);
<add> expect(element.text()).toEqual('Hello: content');
<add> expect(element.find('div').attr('compiled')).toEqual('COMPILED');
<add> }));
<add>
<add>
<add> it('should append element with template', inject(function($compile, $rootScope) {
<add> element = $compile('<div><div append>content</div><div>')($rootScope);
<add> expect(element.text()).toEqual('Hello: content');
<add> expect(element.find('div').attr('compiled')).toEqual('COMPILED');
<add> }));
<add>
<add>
<add> it('should compile replace template', inject(function($compile, $rootScope, log) {
<add> element = $compile('<div><div replace medium-log>{{ "angular" }}</div><div>')
<add> ($rootScope);
<add> $rootScope.$digest();
<add> expect(element.text()).toEqual('Hello: angular');
<add> // HIGH goes after MEDIUM since it executes as part of replaced template
<add> expect(log).toEqual('MEDIUM; HIGH; LOG');
<add> }));
<add>
<add>
<add> it('should compile append template', inject(function($compile, $rootScope, log) {
<add> element = $compile('<div><div append medium-log>{{ "angular" }}</div><div>')
<add> ($rootScope);
<add> $rootScope.$digest();
<add> expect(element.text()).toEqual('Hello: angular');
<add> expect(log).toEqual('HIGH; LOG; MEDIUM');
<add> }));
<add>
<add>
<add> it('should merge attributes', inject(function($compile, $rootScope) {
<add> element = $compile(
<add> '<div><div replace class="medium-log" style="height: 20px" ></div><div>')
<add> ($rootScope);
<add> var div = element.find('div');
<add> expect(div.hasClass('medium-log')).toBe(true);
<add> expect(div.hasClass('log')).toBe(true);
<add> expect(div.css('width')).toBe('10px');
<add> expect(div.css('height')).toBe('20px');
<add> expect(div.attr('replace')).toEqual('');
<add> expect(div.attr('high-log')).toEqual('');
<add> }));
<add>
<add> it('should prevent multiple templates per element', inject(function($compile) {
<add> try {
<add> $compile('<div><span replace class="replace"></span></div>')
<add> fail();
<add> } catch(e) {
<add> expect(e.message).toMatch(/Multiple directives .* asking for template/);
<add> }
<add> }));
<add>
<add> it('should play nice with repeater when inline', inject(function($compile, $rootScope) {
<add> element = $compile(
<add> '<div>' +
<add> '<div ng-repeat="i in [1,2]" replace>{{i}}; </div>' +
<add> '</div>')($rootScope);
<add> $rootScope.$digest();
<add> expect(element.text()).toEqual('Hello: 1; Hello: 2; ');
<add> }));
<add>
<add>
<add> it('should play nice with repeater when append', inject(function($compile, $rootScope) {
<add> element = $compile(
<add> '<div>' +
<add> '<div ng-repeat="i in [1,2]" append>{{i}}; </div>' +
<add> '</div>')($rootScope);
<add> $rootScope.$digest();
<add> expect(element.text()).toEqual('Hello: 1; Hello: 2; ');
<add> }));
<add> });
<add>
<add>
<add> describe('async templates', function() {
<add>
<add> beforeEach(module(
<add> function($compileProvider) {
<add> $compileProvider.directive('hello', valueFn({ templateUrl: 'hello.html' }));
<add> $compileProvider.directive('cau', valueFn({ templateUrl:'cau.html' }));
<add>
<add> $compileProvider.directive('cError', valueFn({
<add> templateUrl:'error.html',
<add> compile: function() {
<add> throw Error('cError');
<add> }
<add> }));
<add> $compileProvider.directive('lError', valueFn({
<add> templateUrl: 'error.html',
<add> compile: function() {
<add> throw Error('lError');
<add> }
<add> }));
<add>
<add>
<add> $compileProvider.directive('iHello', valueFn({
<add> replace: true,
<add> templateUrl: 'hello.html'
<add> }));
<add> $compileProvider.directive('iCau', valueFn({
<add> replace: true,
<add> templateUrl:'cau.html'
<add> }));
<add>
<add> $compileProvider.directive('iCError', valueFn({
<add> replace: true,
<add> templateUrl:'error.html',
<add> compile: function() {
<add> throw Error('cError');
<add> }
<add> }));
<add> $compileProvider.directive('iLError', valueFn({
<add> replace: true,
<add> templateUrl: 'error.html',
<add> compile: function() {
<add> throw Error('lError');
<add> }
<add> }));
<add>
<add> }
<add> ));
<add>
<add>
<add> it('should append template via $http and cache it in $templateCache', inject(
<add> function($compile, $httpBackend, $templateCache, $rootScope, $browser) {
<add> $httpBackend.expect('GET', 'hello.html').respond('<span>Hello!</span> World!');
<add> $templateCache.put('cau.html', '<span>Cau!</span>');
<add> element = $compile('<div><b class="hello">ignore</b><b class="cau">ignore</b></div>')($rootScope);
<add> expect(sortedHtml(element)).
<add> toEqual('<div><b class="hello"></b><b class="cau"></b></div>');
<add>
<add> $rootScope.$digest();
<add>
<add>
<add> expect(sortedHtml(element)).
<add> toEqual('<div><b class="hello"></b><b class="cau"><span>Cau!</span></b></div>');
<add>
<add> $httpBackend.flush();
<add> expect(sortedHtml(element)).toEqual(
<add> '<div>' +
<add> '<b class="hello"><span>Hello!</span> World!</b>' +
<add> '<b class="cau"><span>Cau!</span></b>' +
<add> '</div>');
<add> }
<add> ));
<add>
<add>
<add> it('should inline template via $http and cache it in $templateCache', inject(
<add> function($compile, $httpBackend, $templateCache, $rootScope) {
<add> $httpBackend.expect('GET', 'hello.html').respond('<span>Hello!</span>');
<add> $templateCache.put('cau.html', '<span>Cau!</span>');
<add> element = $compile('<div><b class=i-hello>ignore</b><b class=i-cau>ignore</b></div>')($rootScope);
<add> expect(sortedHtml(element)).
<add> toEqual('<div><b class="i-hello"></b><b class="i-cau"></b></div>');
<add>
<add> $rootScope.$digest();
<add>
<add>
<add> expect(sortedHtml(element)).
<add> toEqual('<div><b class="i-hello"></b><span class="i-cau">Cau!</span></div>');
<add>
<add> $httpBackend.flush();
<add> expect(sortedHtml(element)).
<add> toEqual('<div><span class="i-hello">Hello!</span><span class="i-cau">Cau!</span></div>');
<add> }
<add> ));
<add>
<add>
<add> it('should compile, link and flush the template append', inject(
<add> function($compile, $templateCache, $rootScope, $browser) {
<add> $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
<add> $rootScope.name = 'Elvis';
<add> element = $compile('<div><b class="hello"></b></div>')($rootScope);
<add>
<add> $rootScope.$digest();
<add>
<add> expect(sortedHtml(element)).
<add> toEqual('<div><b class="hello"><span>Hello, Elvis!</span></b></div>');
<add> }
<add> ));
<add>
<add>
<add> it('should compile, link and flush the template inline', inject(
<add> function($compile, $templateCache, $rootScope) {
<add> $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
<add> $rootScope.name = 'Elvis';
<add> element = $compile('<div><b class=i-hello></b></div>')($rootScope);
<add>
<add> $rootScope.$digest();
<add>
<add> expect(sortedHtml(element)).
<add> toEqual('<div><span class="i-hello">Hello, Elvis!</span></div>');
<add> }
<add> ));
<add>
<add>
<add> it('should compile, flush and link the template append', inject(
<add> function($compile, $templateCache, $rootScope) {
<add> $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
<add> $rootScope.name = 'Elvis';
<add> var template = $compile('<div><b class="hello"></b></div>');
<add>
<add> element = template($rootScope);
<add> $rootScope.$digest();
<add>
<add> expect(sortedHtml(element)).
<add> toEqual('<div><b class="hello"><span>Hello, Elvis!</span></b></div>');
<add> }
<add> ));
<add>
<add>
<add> it('should compile, flush and link the template inline', inject(
<add> function($compile, $templateCache, $rootScope) {
<add> $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
<add> $rootScope.name = 'Elvis';
<add> var template = $compile('<div><b class=i-hello></b></div>');
<add>
<add> element = template($rootScope);
<add> $rootScope.$digest();
<add>
<add> expect(sortedHtml(element)).
<add> toEqual('<div><span class="i-hello">Hello, Elvis!</span></div>');
<add> }
<add> ));
<add>
<add>
<add> it('should resolve widgets after cloning in append mode', function() {
<add> module(function($exceptionHandlerProvider) {
<add> $exceptionHandlerProvider.mode('log');
<add> });
<add> inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
<add> $exceptionHandler) {
<add> $httpBackend.expect('GET', 'hello.html').respond('<span>{{greeting}} </span>');
<add> $httpBackend.expect('GET', 'error.html').respond('<div></div>');
<add> $templateCache.put('cau.html', '<span>{{name}}</span>');
<add> $rootScope.greeting = 'Hello';
<add> $rootScope.name = 'Elvis';
<add> var template = $compile(
<add> '<div>' +
<add> '<b class="hello"></b>' +
<add> '<b class="cau"></b>' +
<add> '<b class=c-error></b>' +
<add> '<b class=l-error></b>' +
<ide> '</div>');
<del> $rootScope.value = 1;
<del> $rootScope.$digest();
<del> expect(sortedHtml($rootScope.$element)).
<del> toEqual('<div>' +
<del> 'before<#comment></#comment>' +
<del> '<span>x</span>' +
<del> 'after' +
<del> '</div>');
<del> $rootScope.value = 2;
<del> $rootScope.$digest();
<del> expect(sortedHtml($rootScope.$element)).
<del> toEqual('<div>' +
<del> 'before<#comment></#comment>' +
<del> '<span>x</span>' +
<del> '<span>x</span>' +
<del> 'after' +
<del> '</div>');
<del> $rootScope.value = 3;
<del> $rootScope.$digest();
<del> expect(sortedHtml($rootScope.$element)).
<del> toEqual('<div>' +
<del> 'before<#comment></#comment>' +
<del> '<span>x</span>' +
<del> '<span>x</span>' +
<del> '<span>x</span>' +
<del> 'after' +
<del> '</div>');
<del> }));
<add> var e1;
<add> var e2;
<add>
<add> e1 = template($rootScope.$new(), noop); // clone
<add> expect(e1.text()).toEqual('');
<add>
<add> $httpBackend.flush();
<add>
<add> e2 = template($rootScope.$new(), noop); // clone
<add> $rootScope.$digest();
<add> expect(e1.text()).toEqual('Hello Elvis');
<add> expect(e2.text()).toEqual('Hello Elvis');
<add>
<add> expect($exceptionHandler.errors.length).toEqual(2);
<add> expect($exceptionHandler.errors[0][0].message).toEqual('cError');
<add> expect($exceptionHandler.errors[1][0].message).toEqual('lError');
<add>
<add> dealoc(e1);
<add> dealoc(e2);
<add> });
<add> });
<add>
<add>
<add> it('should resolve widgets after cloning in inline mode', function() {
<add> module(function($exceptionHandlerProvider) {
<add> $exceptionHandlerProvider.mode('log');
<add> });
<add> inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
<add> $exceptionHandler) {
<add> $httpBackend.expect('GET', 'hello.html').respond('<span>{{greeting}} </span>');
<add> $httpBackend.expect('GET', 'error.html').respond('<div></div>');
<add> $templateCache.put('cau.html', '<span>{{name}}</span>');
<add> $rootScope.greeting = 'Hello';
<add> $rootScope.name = 'Elvis';
<add> var template = $compile(
<add> '<div>' +
<add> '<b class=i-hello></b>' +
<add> '<b class=i-cau></b>' +
<add> '<b class=i-c-error></b>' +
<add> '<b class=i-l-error></b>' +
<add> '</div>');
<add> var e1;
<add> var e2;
<add>
<add> e1 = template($rootScope.$new(), noop); // clone
<add> expect(e1.text()).toEqual('');
<add>
<add> $httpBackend.flush();
<add>
<add> e2 = template($rootScope.$new(), noop); // clone
<add> $rootScope.$digest();
<add> expect(e1.text()).toEqual('Hello Elvis');
<add> expect(e2.text()).toEqual('Hello Elvis');
<add>
<add> expect($exceptionHandler.errors.length).toEqual(2);
<add> expect($exceptionHandler.errors[0][0].message).toEqual('cError');
<add> expect($exceptionHandler.errors[1][0].message).toEqual('lError');
<add>
<add> dealoc(e1);
<add> dealoc(e2);
<add> });
<add> });
<add>
<add>
<add> it('should be implicitly terminal and not compile placeholder content in append', inject(
<add> function($compile, $templateCache, $rootScope, log) {
<add> // we can't compile the contents because that would result in a memory leak
<add>
<add> $templateCache.put('hello.html', 'Hello!');
<add> element = $compile('<div><b class="hello"><div log></div></b></div>')($rootScope);
<add>
<add> expect(log).toEqual('');
<add> }
<add> ));
<add>
<add>
<add> it('should be implicitly terminal and not compile placeholder content in inline', inject(
<add> function($compile, $templateCache, $rootScope, log) {
<add> // we can't compile the contents because that would result in a memory leak
<add>
<add> $templateCache.put('hello.html', 'Hello!');
<add> element = $compile('<div><b class=i-hello><div log></div></b></div>')($rootScope);
<add>
<add> expect(log).toEqual('');
<add> }
<add> ));
<add>
<add>
<add> it('should throw an error and clear element content if the template fails to load', inject(
<add> function($compile, $httpBackend, $rootScope) {
<add> $httpBackend.expect('GET', 'hello.html').respond(404, 'Not Found!');
<add> element = $compile('<div><b class="hello">content</b></div>')($rootScope);
<add>
<add> expect(function() {
<add> $httpBackend.flush();
<add> }).toThrow('Failed to load template: hello.html');
<add> expect(sortedHtml(element)).toBe('<div><b class="hello"></b></div>');
<add> }
<add> ));
<add>
<add>
<add> it('should prevent multiple templates per element', function() {
<add> module(function($compileProvider) {
<add> $compileProvider.directive('sync', valueFn({
<add> template: '<span></span>'
<add> }));
<add> $compileProvider.directive('async', valueFn({
<add> templateUrl: 'template.html'
<add> }));
<add> });
<add> inject(function($compile){
<add> expect(function() {
<add> $compile('<div><div class="sync async"></div></div>');
<add> }).toThrow('Multiple directives [sync, async] asking for template on: <'+
<add> (msie <= 8 ? 'DIV' : 'div') + ' class="sync async">');
<add> });
<add> });
<add>
<add>
<add> describe('delay compile / linking functions until after template is resolved', function(){
<add> var template;
<add> beforeEach(module(function($compileProvider) {
<add> function directive (name, priority, options) {
<add> $compileProvider.directive(name, function(log) {
<add> return (extend({
<add> priority: priority,
<add> compile: function() {
<add> log(name + '-C');
<add> return function() { log(name + '-L'); }
<add> }
<add> }, options || {}));
<add> });
<add> }
<add>
<add> directive('first', 10);
<add> directive('second', 5, { templateUrl: 'second.html' });
<add> directive('third', 3);
<add> directive('last', 0);
<add>
<add> directive('iFirst', 10, {replace: true});
<add> directive('iSecond', 5, {replace: true, templateUrl: 'second.html' });
<add> directive('iThird', 3, {replace: true});
<add> directive('iLast', 0, {replace: true});
<add> }));
<add>
<add> it('should flush after link append', inject(
<add> function($compile, $rootScope, $httpBackend, log) {
<add> $httpBackend.expect('GET', 'second.html').respond('<div third>{{1+2}}</div>');
<add> template = $compile('<div><span first second last></span></div>');
<add> element = template($rootScope);
<add> expect(log).toEqual('first-C');
<add>
<add> log('FLUSH');
<add> $httpBackend.flush();
<add> $rootScope.$digest();
<add> expect(log).toEqual(
<add> 'first-C; FLUSH; second-C; last-C; third-C; ' +
<add> 'third-L; first-L; second-L; last-L');
<add>
<add> var span = element.find('span');
<add> expect(span.attr('first')).toEqual('');
<add> expect(span.attr('second')).toEqual('');
<add> expect(span.find('div').attr('third')).toEqual('');
<add> expect(span.attr('last')).toEqual('');
<add>
<add> expect(span.text()).toEqual('3');
<add> }));
<add>
<add>
<add> it('should flush after link inline', inject(
<add> function($compile, $rootScope, $httpBackend, log) {
<add> $httpBackend.expect('GET', 'second.html').respond('<div i-third>{{1+2}}</div>');
<add> template = $compile('<div><span i-first i-second i-last></span></div>');
<add> element = template($rootScope);
<add> expect(log).toEqual('iFirst-C');
<add>
<add> log('FLUSH');
<add> $httpBackend.flush();
<add> $rootScope.$digest();
<add> expect(log).toEqual(
<add> 'iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C; ' +
<add> 'iFirst-L; iSecond-L; iThird-L; iLast-L');
<add>
<add> var div = element.find('div');
<add> expect(div.attr('i-first')).toEqual('');
<add> expect(div.attr('i-second')).toEqual('');
<add> expect(div.attr('i-third')).toEqual('');
<add> expect(div.attr('i-last')).toEqual('');
<add>
<add> expect(div.text()).toEqual('3');
<add> }));
<add>
<add>
<add> it('should flush before link append', inject(
<add> function($compile, $rootScope, $httpBackend, log) {
<add> $httpBackend.expect('GET', 'second.html').respond('<div third>{{1+2}}</div>');
<add> template = $compile('<div><span first second last></span></div>');
<add> expect(log).toEqual('first-C');
<add> log('FLUSH');
<add> $httpBackend.flush();
<add> expect(log).toEqual('first-C; FLUSH; second-C; last-C; third-C');
<add>
<add> element = template($rootScope);
<add> $rootScope.$digest();
<add> expect(log).toEqual(
<add> 'first-C; FLUSH; second-C; last-C; third-C; ' +
<add> 'third-L; first-L; second-L; last-L');
<add>
<add> var span = element.find('span');
<add> expect(span.attr('first')).toEqual('');
<add> expect(span.attr('second')).toEqual('');
<add> expect(span.find('div').attr('third')).toEqual('');
<add> expect(span.attr('last')).toEqual('');
<add>
<add> expect(span.text()).toEqual('3');
<add> }));
<add>
<add>
<add> it('should flush before link inline', inject(
<add> function($compile, $rootScope, $httpBackend, log) {
<add> $httpBackend.expect('GET', 'second.html').respond('<div i-third>{{1+2}}</div>');
<add> template = $compile('<div><span i-first i-second i-last></span></div>');
<add> expect(log).toEqual('iFirst-C');
<add> log('FLUSH');
<add> $httpBackend.flush();
<add> expect(log).toEqual('iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C');
<add>
<add> element = template($rootScope);
<add> $rootScope.$digest();
<add> expect(log).toEqual(
<add> 'iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C; ' +
<add> 'iFirst-L; iSecond-L; iThird-L; iLast-L');
<add>
<add> var div = element.find('div');
<add> expect(div.attr('i-first')).toEqual('');
<add> expect(div.attr('i-second')).toEqual('');
<add> expect(div.attr('i-third')).toEqual('');
<add> expect(div.attr('i-last')).toEqual('');
<add>
<add> expect(div.text()).toEqual('3');
<add> }));
<add> });
<add>
<add>
<add> it('should check that template has root element', inject(function($compile, $httpBackend) {
<add> $httpBackend.expect('GET', 'hello.html').respond('before <b>mid</b> after');
<add> $compile('<div i-hello></div>');
<add> expect(function(){
<add> $httpBackend.flush();
<add> }).toThrow('Template must have exactly one root element: before <b>mid</b> after');
<add> }));
<add>
<add>
<add> it('should allow multiple elements in template', inject(function($compile, $httpBackend) {
<add> $httpBackend.expect('GET', 'hello.html').respond('before <b>mid</b> after');
<add> element = jqLite('<div hello></div>');
<add> $compile(element);
<add> $httpBackend.flush();
<add> expect(element.text()).toEqual('before mid after');
<add> }));
<add>
<add>
<add> it('should work when widget is in root element', inject(
<add> function($compile, $httpBackend, $rootScope) {
<add> $httpBackend.expect('GET', 'hello.html').respond('<span>3==<<content>></span>');
<add> element = jqLite('<b class="hello">{{1+2}}</b>');
<add> $compile(element)($rootScope);
<add>
<add> $httpBackend.flush();
<add> expect(element.text()).toEqual('3==3');
<add> }
<add> ));
<add>
<add>
<add> it('should work when widget is a repeater', inject(
<add> function($compile, $httpBackend, $rootScope) {
<add> $httpBackend.expect('GET', 'hello.html').respond('<span>i=<<content>>;</span>');
<add> element = jqLite('<div><b class=hello ng-repeat="i in [1,2]">{{i}}</b></div>');
<add> $compile(element)($rootScope);
<add>
<add> $httpBackend.flush();
<add> expect(element.text()).toEqual('i=1;i=2;');
<add> }
<add> ));
<add> });
<add>
<add>
<add> describe('scope', function() {
<add>
<add> beforeEach(module(function($compileProvider) {
<add> forEach(['', 'a', 'b'], function(name) {
<add> $compileProvider.directive('scope' + uppercase(name), function(log) {
<add> return {
<add> scope: true,
<add> compile: function() {
<add> return function (scope, element) {
<add> log(scope.$id);
<add> expect(element.data('$scope')).toBe(scope);
<add> };
<add> }
<add> };
<add> });
<add> });
<add> $compileProvider.directive('log', function(log) {
<add> return function(scope) {
<add> log('log-' + scope.$id + '-' + scope.$parent.$id);
<add> };
<add> });
<add> }));
<add>
<add>
<add> it('should allow creation of new scopes', inject(function($rootScope, $compile, log) {
<add> element = $compile('<div><span scope><a log></a></span></div>')($rootScope);
<add> expect(log).toEqual('LOG; log-002-001; 002');
<add> }));
<add>
<ide>
<add> it('should correctly create the scope hierachy properly', inject(
<add> function($rootScope, $compile, log) {
<add> element = $compile(
<add> '<div>' + //1
<add> '<b class=scope>' + //2
<add> '<b class=scope><b class=log></b></b>' + //3
<add> '<b class=log></b>' +
<add> '</b>' +
<add> '<b class=scope>' + //4
<add> '<b class=log></b>' +
<add> '</b>' +
<add> '</div>'
<add> )($rootScope);
<add> expect(log).toEqual('LOG; log-003-002; 003; LOG; log-002-001; 002; LOG; log-004-001; 004');
<add> }));
<ide>
<del> it('should process markup before directives', inject(function($rootScope, $compile) {
<del> textMarkup.push(function(text, textNode, parentNode) {
<del> if (text == 'middle') {
<del> expect(textNode.text()).toEqual(text);
<del> parentNode.attr('hello', text);
<del> textNode[0].nodeValue = 'replaced';
<del> }
<add>
<add> it('should not allow more then one scope creation per element', inject(
<add> function($rootScope, $compile) {
<add> expect(function(){
<add> $compile('<div class="scope-a; scope-b"></div>');
<add> }).toThrow('Multiple directives [scopeA, scopeB] asking for new scope on: ' +
<add> '<' + (msie < 9 ? 'DIV' : 'div') + ' class="scope-a; scope-b">');
<add> }));
<add>
<add>
<add> it('should treat new scope on new template as noop', inject(
<add> function($rootScope, $compile, log) {
<add> element = $compile('<div scope-a></div>')($rootScope);
<add> expect(log).toEqual('001');
<add> }));
<add> });
<ide> });
<del> $compile('<div>before<span>middle</span>after</div>')($rootScope);
<del> expect(sortedHtml($rootScope.$element[0], true)).
<del> toEqual('<div>before<span class="ng-directive" hello="middle">replaced</span>after</div>');
<del> expect(log).toEqual("hello middle");
<del> }));
<add> });
<ide>
<ide>
<del> it('should replace widgets', inject(function($rootScope, $compile) {
<del> widgets['NG:BUTTON'] = function(element) {
<del> expect(element.hasClass('ng-widget')).toEqual(true);
<del> element.replaceWith('<div>button</div>');
<del> return function(element) {
<del> log += 'init';
<del> };
<del> };
<del> $compile('<div><ng:button>push me</ng:button></div>')($rootScope);
<del> expect(lowercase($rootScope.$element[0].innerHTML)).toEqual('<div>button</div>');
<del> expect(log).toEqual('init');
<del> }));
<add> describe('interpolation', function() {
<ide>
<add> it('should compile and link both attribute and text bindings', inject(
<add> function($rootScope, $compile) {
<add> $rootScope.name = 'angular';
<add> element = $compile('<div name="attr: {{name}}">text: {{name}}</div>')($rootScope);
<add> $rootScope.$digest();
<add> expect(element.text()).toEqual('text: angular');
<add> expect(element.attr('name')).toEqual('attr: angular');
<add> }));
<ide>
<del> it('should use the replaced element after calling widget', inject(function($rootScope, $compile) {
<del> widgets['H1'] = function(element) {
<del> // HTML elements which are augmented by acting as widgets, should not be marked as so
<del> expect(element.hasClass('ng-widget')).toEqual(false);
<del> var span = angular.element('<span>{{1+2}}</span>');
<del> element.replaceWith(span);
<del> this.descend(true);
<del> this.directives(true);
<del> return noop;
<del> };
<del> textMarkup.push(function(text, textNode, parent){
<del> if (text == '{{1+2}}')
<del> parent.text('3');
<del> });
<del> $compile('<div><h1>ignore me</h1></div>')($rootScope);
<del> expect($rootScope.$element.text()).toEqual('3');
<del> }));
<ide>
<add> it('should decorate the binding with ng-binding and interpolation function', inject(
<add> function($compile, $rootScope) {
<add> element = $compile('<div>{{1+2}}</div>')($rootScope);
<add> expect(element.hasClass('ng-binding')).toBe(true);
<add> expect(element.data('$binding')[0].exp).toEqual('{{1+2}}');
<add> }));
<add> });
<ide>
<del> it('should allow multiple markups per text element', inject(function($rootScope, $compile) {
<del> textMarkup.push(function(text, textNode, parent){
<del> var index = text.indexOf('---');
<del> if (index > -1) {
<del> textNode.after(text.substring(index + 3));
<del> textNode.after("<hr/>");
<del> textNode.after(text.substring(0, index));
<del> textNode.remove();
<del> }
<del> });
<del> textMarkup.push(function(text, textNode, parent){
<del> var index = text.indexOf('===');
<del> if (index > -1) {
<del> textNode.after(text.substring(index + 3));
<del> textNode.after("<p>");
<del> textNode.after(text.substring(0, index));
<del> textNode.remove();
<del> }
<del> });
<del> $compile('<div>A---B---C===D</div>')($rootScope);
<del> expect(sortedHtml($rootScope.$element)).toEqual('<div>A<hr></hr>B<hr></hr>C<p></p>D</div>');
<del> }));
<ide>
<add> describe('link phase', function() {
<ide>
<del> it('should add class for namespace elements', inject(function($rootScope, $compile) {
<del> var element = $compile('<ng:space>abc</ng:space>')($rootScope);
<del> expect(element.hasClass('ng-space')).toEqual(true);
<del> }));
<add> beforeEach(module(function($compileProvider) {
<add>
<add> forEach(['a', 'b', 'c'], function(name) {
<add> $compileProvider.directive(name, function(log) {
<add> return {
<add> compile: function() {
<add> log('t' + uppercase(name))
<add> return {
<add> pre: function() {
<add> log('pre' + uppercase(name));
<add> },
<add> post: function linkFn() {
<add> log('post' + uppercase(name));
<add> }
<add> };
<add> }
<add> };
<add> });
<add> });
<add> }));
<add>
<add>
<add> it('should not store linkingFns for noop branches', inject(function ($rootScope, $compile) {
<add> element = jqLite('<div name="{{a}}"><span>ignore</span></div>');
<add> var linkingFn = $compile(element);
<add> // Now prune the branches with no directives
<add> element.find('span').remove();
<add> expect(element.find('span').length).toBe(0);
<add> // and we should still be able to compile without errors
<add> linkingFn($rootScope);
<add> }));
<add>
<add>
<add> it('should compile from top to bottom but link from bottom up', inject(
<add> function($compile, $rootScope, log) {
<add> element = $compile('<a b><c></c></a>')($rootScope);
<add> expect(log).toEqual('tA; tB; tC; preA; preB; preC; postC; postA; postB');
<add> }
<add> ));
<add>
<add>
<add> it('should support link function on directive object', function() {
<add> module(function($compileProvider) {
<add> $compileProvider.directive('abc', valueFn({
<add> link: function(scope, element, attrs) {
<add> element.text(attrs.abc);
<add> }
<add> }));
<add> });
<add> inject(function($compile, $rootScope) {
<add> element = $compile('<div abc="WORKS">FAIL</div>')($rootScope);
<add> expect(element.text()).toEqual('WORKS');
<add> });
<add> });
<add> });
<add>
<add>
<add> describe('attrs', function() {
<add>
<add> it('should allow setting of attributes', function() {
<add> module(function($compileProvider) {
<add> $compileProvider.directive({
<add> setter: valueFn(function(scope, element, attr) {
<add> attr.$set('name', 'abc');
<add> attr.$set('disabled', true);
<add> expect(attr.name).toBe('abc');
<add> expect(attr.disabled).toBe(true);
<add> })
<add> });
<add> });
<add> inject(function($rootScope, $compile) {
<add> element = $compile('<div setter></div>')($rootScope);
<add> expect(element.attr('name')).toEqual('abc');
<add> expect(element.attr('disabled')).toEqual('disabled');
<add> });
<add> });
<add>
<add>
<add> it('should read boolean attributes as boolean', function() {
<add> module(function($compileProvider) {
<add> $compileProvider.directive({
<add> div: valueFn(function(scope, element, attr) {
<add> element.text(attr.required);
<add> })
<add> });
<add> });
<add> inject(function($rootScope, $compile) {
<add> element = $compile('<div required></div>')($rootScope);
<add> expect(element.text()).toEqual('true');
<add> });
<add> });
<add>
<add> it('should allow setting of attributes', function() {
<add> module(function($compileProvider) {
<add> $compileProvider.directive({
<add> setter: valueFn(function(scope, element, attr) {
<add> attr.$set('name', 'abc');
<add> attr.$set('disabled', true);
<add> expect(attr.name).toBe('abc');
<add> expect(attr.disabled).toBe(true);
<add> })
<add> });
<add> });
<add> inject(function($rootScope, $compile) {
<add> element = $compile('<div setter></div>')($rootScope);
<add> expect(element.attr('name')).toEqual('abc');
<add> expect(element.attr('disabled')).toEqual('disabled');
<add> });
<add> });
<add>
<add>
<add> it('should read boolean attributes as boolean', function() {
<add> module(function($compileProvider) {
<add> $compileProvider.directive({
<add> div: valueFn(function(scope, element, attr) {
<add> element.text(attr.required);
<add> })
<add> });
<add> });
<add> inject(function($rootScope, $compile) {
<add> element = $compile('<div required></div>')($rootScope);
<add> expect(element.text()).toEqual('true');
<add> });
<add> });
<add>
<add>
<add> it('should create new instance of attr for each template stamping', function() {
<add> module(function($compileProvider, $provide) {
<add> var state = { first: [], second: [] };
<add> $provide.value('state', state);
<add> $compileProvider.directive({
<add> first: valueFn({
<add> priority: 1,
<add> compile: function(templateElement, templateAttr) {
<add> return function(scope, element, attr) {
<add> state.first.push({
<add> template: {element: templateElement, attr:templateAttr},
<add> link: {element: element, attr: attr}
<add> });
<add> }
<add> }
<add> }),
<add> second: valueFn({
<add> priority: 2,
<add> compile: function(templateElement, templateAttr) {
<add> return function(scope, element, attr) {
<add> state.second.push({
<add> template: {element: templateElement, attr:templateAttr},
<add> link: {element: element, attr: attr}
<add> });
<add> }
<add> }
<add> })
<add> });
<add> });
<add> inject(function($rootScope, $compile, state) {
<add> var template = $compile('<div first second>');
<add> dealoc(template($rootScope.$new(), noop));
<add> dealoc(template($rootScope.$new(), noop));
<add>
<add> // instance between directives should be shared
<add> expect(state.first[0].template.element).toBe(state.second[0].template.element);
<add> expect(state.first[0].template.attr).toBe(state.second[0].template.attr);
<add>
<add> // the template and the link can not be the same instance
<add> expect(state.first[0].template.element).not.toBe(state.first[0].link.element);
<add> expect(state.first[0].template.attr).not.toBe(state.first[0].link.attr);
<add>
<add> // each new template needs to be new instance
<add> expect(state.first[0].link.element).not.toBe(state.first[1].link.element);
<add> expect(state.first[0].link.attr).not.toBe(state.first[1].link.attr);
<add> expect(state.second[0].link.element).not.toBe(state.second[1].link.element);
<add> expect(state.second[0].link.attr).not.toBe(state.second[1].link.attr);
<add> });
<add> });
<add>
<add>
<add> describe('$set', function() {
<add> var attr;
<add> beforeEach(function(){
<add> module(function($compileProvider) {
<add> $compileProvider.directive('div', valueFn(function(scope, element, attr){
<add> scope.attr = attr;
<add> }));
<add> });
<add> inject(function($compile, $rootScope) {
<add> element = $compile('<div></div>')($rootScope);
<add> attr = $rootScope.attr;
<add> expect(attr).toBeDefined();
<add> });
<add> });
<add>
<add>
<add> it('should set attributes', function() {
<add> attr.$set('ngMyAttr', 'value');
<add> expect(element.attr('ng-my-attr')).toEqual('value');
<add> expect(attr.ngMyAttr).toEqual('value');
<add> });
<add>
<add>
<add> it('should allow overriding of attribute name and remember the name', function() {
<add> attr.$set('ngOther', '123', 'other');
<add> expect(element.attr('other')).toEqual('123');
<add> expect(attr.ngOther).toEqual('123');
<add>
<add> attr.$set('ngOther', '246');
<add> expect(element.attr('other')).toEqual('246');
<add> expect(attr.ngOther).toEqual('246');
<add> });
<add>
<add>
<add> it('should set boolean attributes', function() {
<add> attr.$set('disabled', 'true');
<add> attr.$set('readOnly', 'true');
<add> expect(element.attr('disabled')).toEqual('disabled');
<add> expect(element.attr('readonly')).toEqual('readonly');
<add>
<add> attr.$set('disabled', 'false');
<add> expect(element.attr('disabled')).toEqual(undefined);
<add>
<add> attr.$set('disabled', false);
<add> attr.$set('readOnly', false);
<add> expect(element.attr('disabled')).toEqual(undefined);
<add> expect(element.attr('readonly')).toEqual(undefined);
<add> });
<add>
<add>
<add> it('should remove attribute', function() {
<add> attr.$set('ngMyAttr', 'value');
<add> expect(element.attr('ng-my-attr')).toEqual('value');
<add>
<add> attr.$set('ngMyAttr', undefined);
<add> expect(element.attr('ng-my-attr')).toBe(undefined);
<add>
<add> attr.$set('ngMyAttr', 'value');
<add> attr.$set('ngMyAttr', null);
<add> expect(element.attr('ng-my-attr')).toBe(undefined);
<add> })
<add> });
<add> });
<ide> });
<ide><path>test/testabilityPatch.js
<ide> function dealoc(obj) {
<ide> }
<ide> }
<ide>
<del>
<add>/**
<add> * @param {DOMElement} element
<add> * @param {boolean=} showNgClass
<add> */
<ide> function sortedHtml(element, showNgClass) {
<ide> var html = "";
<ide> forEach(jqLite(element), function toString(node) { | 10 |
Text | Text | add section about error handling | 9359b1aa3664ca568b80a3bb067b929f26c12262 | <ide><path>guide/english/swift/error-handling/index.md
<add>---
<add>title: Error Handling
<add>---
<add>
<add># Error Handling
<add>
<add>You represent errors using any type that adopts the `Error` protocol.
<add>
<add>```Swift
<add>enum PrinterError: Error {
<add> case outOfPaper
<add> case noToner
<add> case onFire
<add>}
<add>```
<add>Use `throw` to throw an error and `throws` to mark a function that can throw an error. If you throw an error in a function, the function returns immediately and the code that called the function handles the error.
<add>
<add>```swift
<add>func send(job: Int, toPrinter printerName: String) throws -> String {
<add> if printerName == "Never Has Toner" {
<add> throw PrinterError.noToner
<add> }
<add> return "Job sent"
<add>}
<add>```
<add>
<add>There are several ways to handle errors. One way is to use `do`-`catch`. Inside the `do`block, you mark code that can throw an error by writing `try` in front of it. Inside the `catch` block, the error is automatically given the name `error` unless you give it a different name.
<add>
<add>```swift
<add>do {
<add> let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng")
<add> print(printerResponse)
<add>} catch {
<add> print(error)
<add>}
<add>// Prints "Job sent"
<add>``` | 1 |
Text | Text | fix a typo | b0f727880a7a3e907470937b74a7e573615b57e5 | <ide><path>activerecord/CHANGELOG.md
<ide>
<ide> *Justin George*
<ide>
<del>* The database adpters now converts the options passed thought `DATABASE_URL`
<add>* The database adapters now converts the options passed thought `DATABASE_URL`
<ide> environment variable to the proper Ruby types before using. For example, SQLite requires
<ide> that the timeout value is an integer, and PostgreSQL requires that the
<ide> prepared_statements option is a boolean. These now work as expected: | 1 |
PHP | PHP | add some docs | 8a41259903f66e718d7abdd160a7fa0fc097e0d8 | <ide><path>lib/Cake/Routing/RouteCollection.php
<ide> protected function _getNames($url) {
<ide> $fallbacks = array(
<ide> '%2$s:%3$s',
<ide> '%2$s:_action',
<del> '_controller::_action'
<add> '_controller:_action'
<ide> );
<ide> if ($plugin) {
<ide> $fallbacks = array(
<ide><path>lib/Cake/Routing/Router.php
<ide> public static function promote($which = null) {
<ide> * - `_base` - Set to false to remove the base path from the generated url. If your application
<ide> * is not in the root directory, this can be used to generate urls that are 'cake relative'.
<ide> * cake relative urls are required when using requestAction.
<add> * - `_scheme` - Set to create links on different schemes like `webcal` or `ftp`. Defaults
<add> * to the current scheme.
<add> * - `_host` - Set the host to use for the link. Defaults to the current host.
<add> * - `_port` - Set the port if you need to create links on non-standard ports.
<ide> * - `_full` - If true the `FULL_BASE_URL` constant will be prepended to generated urls.
<ide> * - `#` - Allows you to set url hash fragments.
<ide> * - `ssl` - Set to true to convert the generated url to https, or false to force http. | 2 |
Java | Java | provide a flag to disable spel support | 1c75f95be092cf0b65e19ab71173f9473c1edc82 | <ide><path>spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> private static int resolveOrder(Method method) {
<ide> /**
<ide> * Initialize this instance.
<ide> */
<del> void init(ApplicationContext applicationContext, EventExpressionEvaluator evaluator) {
<add> void init(ApplicationContext applicationContext, @Nullable EventExpressionEvaluator evaluator) {
<ide> this.applicationContext = applicationContext;
<ide> this.evaluator = evaluator;
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/context/event/EventListenerMethodProcessor.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.context.ApplicationListener;
<ide> import org.springframework.context.ConfigurableApplicationContext;
<ide> import org.springframework.core.MethodIntrospector;
<add>import org.springframework.core.SpringProperties;
<ide> import org.springframework.core.annotation.AnnotatedElementUtils;
<ide> import org.springframework.core.annotation.AnnotationAwareOrderComparator;
<ide> import org.springframework.core.annotation.AnnotationUtils;
<ide> *
<ide> * @author Stephane Nicoll
<ide> * @author Juergen Hoeller
<add> * @author Sebastien Deleuze
<ide> * @since 4.2
<ide> * @see EventListenerFactory
<ide> * @see DefaultEventListenerFactory
<ide> */
<ide> public class EventListenerMethodProcessor
<ide> implements SmartInitializingSingleton, ApplicationContextAware, BeanFactoryPostProcessor {
<ide>
<add> /**
<add> * Boolean flag controlled by a {@code spring.spel.ignore} system property that instructs Spring to
<add> * ignore SpEL, i.e. to not initialize the SpEL infrastructure.
<add> * <p>The default is "false".
<add> */
<add> private static final boolean shouldIgnoreSpel = SpringProperties.getFlag("spring.spel.ignore");
<add>
<add>
<ide> protected final Log logger = LogFactory.getLog(getClass());
<ide>
<ide> @Nullable
<ide> @Nullable
<ide> private List<EventListenerFactory> eventListenerFactories;
<ide>
<del> private final EventExpressionEvaluator evaluator = new EventExpressionEvaluator();
<add> @Nullable
<add> private final EventExpressionEvaluator evaluator;
<ide>
<ide> private final Set<Class<?>> nonAnnotatedClasses = Collections.newSetFromMap(new ConcurrentHashMap<>(64));
<ide>
<ide>
<add> public EventListenerMethodProcessor() {
<add> if (shouldIgnoreSpel) {
<add> this.evaluator = null;
<add> }
<add> else {
<add> this.evaluator = new EventExpressionEvaluator();
<add> }
<add> }
<add>
<ide> @Override
<ide> public void setApplicationContext(ApplicationContext applicationContext) {
<ide> Assert.isTrue(applicationContext instanceof ConfigurableApplicationContext,
<ide><path>spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java
<ide> import org.springframework.context.weaving.LoadTimeWeaverAware;
<ide> import org.springframework.context.weaving.LoadTimeWeaverAwareProcessor;
<ide> import org.springframework.core.ResolvableType;
<add>import org.springframework.core.SpringProperties;
<ide> import org.springframework.core.annotation.AnnotationUtils;
<ide> import org.springframework.core.convert.ConversionService;
<ide> import org.springframework.core.env.ConfigurableEnvironment;
<ide> * @author Mark Fisher
<ide> * @author Stephane Nicoll
<ide> * @author Sam Brannen
<add> * @author Sebastien Deleuze
<ide> * @since January 21, 2001
<ide> * @see #refreshBeanFactory
<ide> * @see #getBeanFactory
<ide> public abstract class AbstractApplicationContext extends DefaultResourceLoader
<ide> */
<ide> public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
<ide>
<add> /**
<add> * Boolean flag controlled by a {@code spring.spel.ignore} system property that instructs Spring to
<add> * ignore SpEL, i.e. to not initialize the SpEL infrastructure.
<add> * <p>The default is "false".
<add> */
<add> private static final boolean shouldIgnoreSpel = SpringProperties.getFlag("spring.spel.ignore");
<add>
<ide>
<ide> static {
<ide> // Eagerly load the ContextClosedEvent class to avoid weird classloader issues
<ide> protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
<ide> protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
<ide> // Tell the internal bean factory to use the context's class loader etc.
<ide> beanFactory.setBeanClassLoader(getClassLoader());
<del> beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
<add> if (!shouldIgnoreSpel) {
<add> beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
<add> }
<ide> beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
<ide>
<ide> // Configure the bean factory with context callbacks. | 3 |
PHP | PHP | list command | 5fad1041f790ed4c1c565c1bc85a9ac2072d7a8e | <ide><path>src/Illuminate/Foundation/Console/RouteListCommand.php
<ide> protected function getColumns()
<ide> }
<ide>
<ide> if ($columns = $this->option('columns')) {
<del> return array_intersect($availableColumns, $columns);
<add> return array_intersect($availableColumns, $this->parseColumns($columns));
<ide> }
<ide>
<ide> return $availableColumns;
<ide> }
<ide>
<add> /**
<add> * Parse the exact listing of columns.
<add> *
<add> * @param array $columns
<add> * @return array
<add> */
<add> protected function parseColumns(array $columns)
<add> {
<add> $results = [];
<add>
<add> foreach ($columns as $i => $column) {
<add> if (Str::contains($column, ',')) {
<add> $results = array_merge($results, explode(',', $column));
<add> } else {
<add> $results[] = $column;
<add> }
<add> }
<add>
<add> return $results;
<add> }
<ide> /**
<ide> * Get the console command options.
<ide> * | 1 |
Text | Text | add missing entry for to 15.4.2 changelog | 6b1c86020da4e5f15686134b712fe7c3efa86022 | <ide><path>CHANGELOG.md
<ide>
<ide> ### React DOM
<ide>
<add>* Fixed a decimal point issue on uncontrolled number inputs. ([@nhunzaker](https://github.com/nhunzaker) in [#7750](https://github.com/facebook/react/pull/7750))
<ide> * Fixed rendering of textarea placeholder in IE11. ([@aweary](https://github.com/aweary) in [#8020](https://github.com/facebook/react/pull/8020))
<ide> * Worked around a script engine bug in IE9. ([@eoin](https://github.com/eoin) in [#8018](https://github.com/facebook/react/pull/8018))
<ide> | 1 |
Java | Java | fix replaysubject termination race | 42fa5aab312a4bf38558d6ec07b0f4a7596e13f3 | <ide><path>rxjava-core/src/main/java/rx/subjects/ReplaySubject.java
<ide> import rx.Observer;
<ide> import rx.functions.Action0;
<ide> import rx.functions.Action1;
<add>import rx.operators.NotificationLite;
<ide> import rx.subjects.SubjectSubscriptionManager.SubjectObserver;
<ide>
<ide> /**
<ide> public void onCompleted() {
<ide>
<ide> @Override
<ide> public void call() {
<del> state.history.complete(Notification.<T> createOnCompleted());
<add> state.history.complete();
<ide> }
<ide> });
<ide> if (observers != null) {
<ide> public void onError(final Throwable e) {
<ide>
<ide> @Override
<ide> public void call() {
<del> state.history.complete(Notification.<T> createOnError(e));
<add> state.history.complete(e);
<ide> }
<ide> });
<ide> if (observers != null) {
<ide> public void call() {
<ide>
<ide> @Override
<ide> public void onNext(T v) {
<del> if (state.history.terminalValue.get() != null) {
<add> if (state.history.terminated) {
<ide> return;
<ide> }
<ide> state.history.next(v);
<ide> private void replayObserver(SubjectObserver<? super T> observer) {
<ide>
<ide> private static <T> int replayObserverFromIndex(History<T> history, Integer l, SubjectObserver<? super T> observer) {
<ide> while (l < history.index.get()) {
<del> observer.onNext(history.list.get(l));
<add> history.accept(observer, l);
<ide> l++;
<ide> }
<del> if (history.terminalValue.get() != null) {
<del> history.terminalValue.get().accept(observer);
<del> }
<ide>
<ide> return l;
<ide> }
<ide> private static <T> int replayObserverFromIndex(History<T> history, Integer l, Su
<ide> * @param <T>
<ide> */
<ide> private static class History<T> {
<add> private final NotificationLite<T> nl = NotificationLite.instance();
<ide> private final AtomicInteger index;
<del> private final ArrayList<T> list;
<del> private final AtomicReference<Notification<T>> terminalValue;
<add> private final ArrayList<Object> list;
<add> private boolean terminated;
<ide>
<ide> public History(int initialCapacity) {
<ide> index = new AtomicInteger(0);
<del> list = new ArrayList<T>(initialCapacity);
<del> terminalValue = new AtomicReference<Notification<T>>();
<add> list = new ArrayList<Object>(initialCapacity);
<ide> }
<ide>
<ide> public boolean next(T n) {
<del> if (terminalValue.get() == null) {
<del> list.add(n);
<add> if (!terminated) {
<add> list.add(nl.next(n));
<ide> index.getAndIncrement();
<ide> return true;
<ide> } else {
<ide> return false;
<ide> }
<ide> }
<ide>
<del> public void complete(Notification<T> n) {
<del> terminalValue.set(n);
<add> public void accept(Observer<? super T> o, int idx) {
<add> nl.accept(o, list.get(idx));
<add> }
<add>
<add> public void complete() {
<add> if (!terminated) {
<add> terminated = true;
<add> list.add(nl.completed());
<add> index.getAndIncrement();
<add> }
<add> }
<add> public void complete(Throwable e) {
<add> if (!terminated) {
<add> terminated = true;
<add> list.add(nl.error(e));
<add> index.getAndIncrement();
<add> }
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | remove options from keg#dylib_id_for | 4d772042f7e16933ec851edd649e613a3fbbfbbe | <ide><path>Library/Homebrew/cmd/bottle.rb
<ide> def bottle_formula(f)
<ide> keg.lock do
<ide> begin
<ide> keg.relocate_install_names prefix, Keg::PREFIX_PLACEHOLDER,
<del> cellar, Keg::CELLAR_PLACEHOLDER, :keg_only => f.keg_only?
<add> cellar, Keg::CELLAR_PLACEHOLDER
<ide> keg.relocate_text_files prefix, Keg::PREFIX_PLACEHOLDER,
<ide> cellar, Keg::CELLAR_PLACEHOLDER
<ide>
<ide> def bottle_formula(f)
<ide> ensure
<ide> ignore_interrupts do
<ide> keg.relocate_install_names Keg::PREFIX_PLACEHOLDER, prefix,
<del> Keg::CELLAR_PLACEHOLDER, cellar, :keg_only => f.keg_only?
<add> Keg::CELLAR_PLACEHOLDER, cellar
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def install_plist
<ide> end
<ide>
<ide> def fix_install_names(keg)
<del> keg.fix_install_names(:keg_only => formula.keg_only?)
<add> keg.fix_install_names
<ide> rescue Exception => e
<ide> onoe "Failed to fix install names"
<ide> puts "The formula built, but you may encounter issues using it or linking other"
<ide> def pour
<ide> keg = Keg.new(formula.prefix)
<ide> unless formula.bottle_specification.skip_relocation?
<ide> keg.relocate_install_names Keg::PREFIX_PLACEHOLDER, HOMEBREW_PREFIX.to_s,
<del> Keg::CELLAR_PLACEHOLDER, HOMEBREW_CELLAR.to_s, :keg_only => formula.keg_only?
<add> Keg::CELLAR_PLACEHOLDER, HOMEBREW_CELLAR.to_s
<ide> end
<ide> keg.relocate_text_files Keg::PREFIX_PLACEHOLDER, HOMEBREW_PREFIX.to_s,
<ide> Keg::CELLAR_PLACEHOLDER, HOMEBREW_CELLAR.to_s
<ide><path>Library/Homebrew/keg_relocate.rb
<ide> class Keg
<ide> PREFIX_PLACEHOLDER = "".freeze
<ide> CELLAR_PLACEHOLDER = "".freeze
<ide>
<del> def fix_install_names(options = {})
<add> def fix_install_names
<ide> mach_o_files.each do |file|
<ide> file.ensure_writable do
<del> change_dylib_id(dylib_id_for(file, options), file) if file.dylib?
<add> change_dylib_id(dylib_id_for(file), file) if file.dylib?
<ide>
<ide> each_install_name_for(file) do |bad_name|
<ide> # Don't fix absolute paths unless they are rooted in the build directory
<ide> def fix_install_names(options = {})
<ide> end
<ide> end
<ide>
<del> def relocate_install_names(old_prefix, new_prefix, old_cellar, new_cellar, options = {})
<add> def relocate_install_names(old_prefix, new_prefix, old_cellar, new_cellar)
<ide> mach_o_files.each do |file|
<ide> file.ensure_writable do
<ide> if file.dylib?
<del> id = dylib_id_for(file, options).sub(old_prefix, new_prefix)
<add> id = dylib_id_for(file).sub(old_prefix, new_prefix)
<ide> change_dylib_id(id, file)
<ide> end
<ide>
<ide> def each_install_name_for(file, &block)
<ide> dylibs.each(&block)
<ide> end
<ide>
<del> def dylib_id_for(file, options)
<add> def dylib_id_for(file)
<ide> # The new dylib ID should have the same basename as the old dylib ID, not
<ide> # the basename of the file itself.
<ide> basename = File.basename(file.dylib_id) | 3 |
PHP | PHP | add missing docblock | 752c177386ae1c4b9002e58508386d1dad2f13fe | <ide><path>src/Routing/Exception/MissingDispatcherFilterException.php
<ide> class MissingDispatcherFilterException extends Exception
<ide> {
<ide>
<add> /**
<add> * {@inheritDoc}
<add> */
<ide> protected $_messageTemplate = 'Dispatcher filter %s could not be found.';
<ide> } | 1 |
Javascript | Javascript | remove functions from closures in color | e1bfbac95bcba147debae2c51d921d7ea0e24833 | <ide><path>src/math/Color.js
<ide> function Color( r, g, b ) {
<ide>
<ide> }
<ide>
<add>function hue2rgb( p, q, t ) {
<add>
<add> if ( t < 0 ) t += 1;
<add> if ( t > 1 ) t -= 1;
<add> if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
<add> if ( t < 1 / 2 ) return q;
<add> if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
<add> return p;
<add>
<add>}
<add>
<add>function SRGBToLinear( c ) {
<add>
<add> return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
<add>
<add>}
<add>
<add>function LinearToSRGB( c ) {
<add>
<add> return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
<add>
<add>}
<add>
<ide> Object.assign( Color.prototype, {
<ide>
<ide> isColor: true,
<ide> Object.assign( Color.prototype, {
<ide>
<ide> },
<ide>
<del> setHSL: function () {
<del>
<del> function hue2rgb( p, q, t ) {
<add> setHSL: function ( h, s, l ) {
<ide>
<del> if ( t < 0 ) t += 1;
<del> if ( t > 1 ) t -= 1;
<del> if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
<del> if ( t < 1 / 2 ) return q;
<del> if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
<del> return p;
<del>
<del> }
<del>
<del> return function setHSL( h, s, l ) {
<del>
<del> // h,s,l ranges are in 0.0 - 1.0
<del> h = _Math.euclideanModulo( h, 1 );
<del> s = _Math.clamp( s, 0, 1 );
<del> l = _Math.clamp( l, 0, 1 );
<del>
<del> if ( s === 0 ) {
<add> // h,s,l ranges are in 0.0 - 1.0
<add> h = _Math.euclideanModulo( h, 1 );
<add> s = _Math.clamp( s, 0, 1 );
<add> l = _Math.clamp( l, 0, 1 );
<ide>
<del> this.r = this.g = this.b = l;
<add> if ( s === 0 ) {
<ide>
<del> } else {
<add> this.r = this.g = this.b = l;
<ide>
<del> var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
<del> var q = ( 2 * l ) - p;
<add> } else {
<ide>
<del> this.r = hue2rgb( q, p, h + 1 / 3 );
<del> this.g = hue2rgb( q, p, h );
<del> this.b = hue2rgb( q, p, h - 1 / 3 );
<add> var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
<add> var q = ( 2 * l ) - p;
<ide>
<del> }
<add> this.r = hue2rgb( q, p, h + 1 / 3 );
<add> this.g = hue2rgb( q, p, h );
<add> this.b = hue2rgb( q, p, h - 1 / 3 );
<ide>
<del> return this;
<add> }
<ide>
<del> };
<add> return this;
<ide>
<del> }(),
<add> },
<ide>
<ide> setStyle: function ( style ) {
<ide>
<ide> Object.assign( Color.prototype, {
<ide>
<ide> },
<ide>
<del> copySRGBToLinear: function () {
<del>
<del> function SRGBToLinear( c ) {
<del>
<del> return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
<del>
<del> }
<add> copySRGBToLinear: function ( color ) {
<ide>
<del> return function copySRGBToLinear( color ) {
<add> this.r = SRGBToLinear( color.r );
<add> this.g = SRGBToLinear( color.g );
<add> this.b = SRGBToLinear( color.b );
<ide>
<del> this.r = SRGBToLinear( color.r );
<del> this.g = SRGBToLinear( color.g );
<del> this.b = SRGBToLinear( color.b );
<del>
<del> return this;
<del>
<del> };
<del>
<del> }(),
<del>
<del> copyLinearToSRGB: function () {
<del>
<del> function LinearToSRGB( c ) {
<del>
<del> return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
<del>
<del> }
<add> return this;
<ide>
<del> return function copyLinearToSRGB( color ) {
<add> },
<ide>
<del> this.r = LinearToSRGB( color.r );
<del> this.g = LinearToSRGB( color.g );
<del> this.b = LinearToSRGB( color.b );
<add> copyLinearToSRGB: function ( color ) {
<ide>
<del> return this;
<add> this.r = LinearToSRGB( color.r );
<add> this.g = LinearToSRGB( color.g );
<add> this.b = LinearToSRGB( color.b );
<ide>
<del> };
<add> return this;
<ide>
<del> }(),
<add> },
<ide>
<ide> convertSRGBToLinear: function () {
<ide>
<ide> Object.assign( Color.prototype, {
<ide> if ( offset === undefined ) offset = 0;
<ide>
<ide> this.r = array[ offset ];
<del> this.g = array[ offset + 1 ];
<add> this.g = array[ offset + 1 ];
<ide> this.b = array[ offset + 2 ];
<ide>
<ide> return this; | 1 |
Ruby | Ruby | write sql queries to terminal | e267c0ee5e59812359b33676454178e788f798ec | <ide><path>guides/bug_report_templates/active_record_gem.rb
<ide> # Activate the gem you are reporting the issue against.
<ide> gem 'activerecord', '3.2.11'
<ide> require 'active_record'
<del>require "minitest/autorun"
<add>require 'minitest/autorun'
<add>require 'logger'
<ide>
<ide> # This connection will do for database-independent bug reports.
<ide> ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
<add>ActiveRecord::Base.logger = Logger.new(STDOUT)
<ide>
<ide> ActiveRecord::Schema.define do
<ide> create_table :posts do |t|
<ide><path>guides/bug_report_templates/active_record_master.rb
<ide> Bundler.setup(:default)
<ide>
<ide> require 'active_record'
<del>require "minitest/autorun"
<add>require 'minitest/autorun'
<add>require 'logger'
<ide>
<ide> # This connection will do for database-independent bug reports.
<ide> ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
<add>ActiveRecord::Base.logger = Logger.new(STDOUT)
<ide>
<ide> ActiveRecord::Schema.define do
<ide> create_table :posts do |t| | 2 |
Ruby | Ruby | use instance_eval for schema block | 2e9c7759984573944592fb1bda5aeb7c58edba55 | <ide><path>activeresource/lib/active_resource/base.rb
<ide> class << self
<ide> #
<ide> # example:
<ide> # class Person < ActiveResource::Base
<del> # schema do |s|
<add> # schema do
<ide> # # define each attribute separately
<del> # s.attribute 'name', :string
<add> # attribute 'name', :string
<ide> #
<ide> # # or use the convenience methods and pass >=1 attribute names
<del> # s.string 'eye_colour', 'hair_colour'
<del> # s.integer 'age'
<del> # s.float 'height', 'weight'
<add> # string 'eye_colour', 'hair_colour'
<add> # integer 'age'
<add> # float 'height', 'weight'
<ide> #
<ide> # # unsupported types should be left as strings
<ide> # # overload the accessor methods if you need to convert them
<del> # s.attribute 'created_at', 'string'
<add> # attribute 'created_at', 'string'
<ide> # end
<ide> # end
<ide> #
<ide> class << self
<ide> def schema(&block)
<ide> if block_given?
<ide> schema_definition = Schema.new
<del> yield schema_definition
<add> schema_definition.instance_eval(&block)
<ide>
<ide> # skip out if we didn't define anything
<ide> return unless schema_definition.attrs.present?
<ide> def schema=(the_schema)
<ide>
<ide> raise ArgumentError, "Expected a hash" unless the_schema.kind_of? Hash
<ide>
<del> schema do |s|
<del> the_schema.each {|k,v| s.attribute(k,v) }
<add> schema do
<add> the_schema.each {|k,v| attribute(k,v) }
<ide> end
<ide> end
<ide>
<ide><path>activeresource/lib/active_resource/schema.rb
<ide>
<ide> module ActiveResource # :nodoc:
<ide> class Schema # :nodoc:
<del>
<ide> # attributes can be known to be one of these types. They are easy to
<ide> # cast to/from.
<ide> KNOWN_ATTRIBUTE_TYPES = %w( string integer float )
<ide> class Schema # :nodoc:
<ide> # unlike an Active Record TableDefinition (on which it is based).
<ide> # It provides a set of convenience methods for people to define their
<ide> # schema using the syntax:
<del> # schema do |s|
<del> # s.string :foo
<del> # s.integer :bar
<add> # schema do
<add> # string :foo
<add> # integer :bar
<ide> # end
<ide> #
<ide> # The schema stores the name and type of each attribute. That is then
<ide> def attribute(name, type, options = {})
<ide> # %w( string text integer float decimal datetime timestamp time date binary boolean ).each do |attr_type|
<ide> KNOWN_ATTRIBUTE_TYPES.each do |attr_type|
<ide> class_eval <<-EOV
<del> def #{attr_type.to_s}(*args) # def string(*args)
<add> def #{attr_type.to_s}(*args) # def string(*args)
<ide> options = args.extract_options! # options = args.extract_options!
<ide> attr_names = args # attr_names = args
<ide> #
<ide> attr_names.each { |name| attribute(name, '#{attr_type}', options) } # attr_names.each { |name| attribute(name, 'string', options) }
<ide> end # end
<ide> EOV
<del>
<ide> end
<del>
<ide> end
<ide> end
<ide><path>activeresource/test/cases/base/schema_test.rb
<ide> def teardown
<ide> assert Person.respond_to?(:schema), "should at least respond to the schema method"
<ide>
<ide> assert_nothing_raised("Should allow the schema to take a block") do
<del> Person.schema do |s|
<del> assert s.kind_of?(ActiveResource::Schema), "the 's' should be a schema definition or we're way off track..."
<del> end
<add> Person.schema { }
<ide> end
<ide> end
<ide>
<ide> test "schema definition should store and return attribute set" do
<ide> assert_nothing_raised do
<del> Person.schema do |s|
<del> assert s.respond_to?(:attrs), "should return attributes in theory"
<del> s.attribute :foo, :string
<del> assert_equal({'foo' => 'string' }, s.attrs, "should return attributes in practice")
<add> s = nil
<add> Person.schema do
<add> s = self
<add> attribute :foo, :string
<ide> end
<add> assert s.respond_to?(:attrs), "should return attributes in theory"
<add> assert_equal({'foo' => 'string' }, s.attrs, "should return attributes in practice")
<ide> end
<ide> end
<ide>
<ide> test "should be able to add attributes through schema" do
<ide> assert_nothing_raised do
<del> Person.schema do |s|
<del> assert s.attribute('foo', 'string'), "should take a simple attribute"
<del> assert s.attrs.has_key?('foo'), "should have saved the attribute name"
<del> assert_equal 'string', s.attrs['foo'], "should have saved the attribute type"
<add> s = nil
<add> Person.schema do
<add> s = self
<add> attribute('foo', 'string')
<ide> end
<add> assert s.attrs.has_key?('foo'), "should have saved the attribute name"
<add> assert_equal 'string', s.attrs['foo'], "should have saved the attribute type"
<ide> end
<ide> end
<ide>
<ide> test "should convert symbol attributes to strings" do
<ide> assert_nothing_raised do
<del> Person.schema do |s|
<del> assert s.attribute(:foo, :integer), "should take a simple attribute as symbols"
<del> assert s.attrs.has_key?('foo'), "should have saved the attribute name as a string"
<del> assert_equal 'integer', s.attrs['foo'], "should have saved the attribute type as a string"
<add> s = nil
<add> Person.schema do
<add> attribute(:foo, :integer)
<add> s = self
<ide> end
<add>
<add> assert s.attrs.has_key?('foo'), "should have saved the attribute name as a string"
<add> assert_equal 'integer', s.attrs['foo'], "should have saved the attribute type as a string"
<ide> end
<ide> end
<ide>
<ide> test "should be able to add all known attribute types" do
<del> Person.schema do |s|
<add> assert_nothing_raised do
<ide> ActiveResource::Schema::KNOWN_ATTRIBUTE_TYPES.each do |the_type|
<del> assert_nothing_raised do
<del> assert s.attribute('foo', the_type), "should take a simple attribute of type: #{the_type}"
<del> assert s.attrs.has_key?('foo'), "should have saved the attribute name"
<del> assert_equal the_type.to_s, s.attrs['foo'], "should have saved the attribute type of: #{the_type}"
<add> s = nil
<add> Person.schema do
<add> s = self
<add> attribute('foo', the_type)
<ide> end
<add> assert s.attrs.has_key?('foo'), "should have saved the attribute name"
<add> assert_equal the_type.to_s, s.attrs['foo'], "should have saved the attribute type of: #{the_type}"
<ide> end
<ide> end
<ide> end
<ide>
<ide> test "attributes should not accept unknown values" do
<ide> bad_values = [ :oogle, :blob, 'thing']
<ide>
<del> Person.schema do |s|
<del> bad_values.each do |bad_value|
<del> assert_raises(ArgumentError,"should only accept a known attribute type, but accepted: #{bad_value.inspect}") do
<del> s.attribute 'key', bad_value
<add> bad_values.each do |bad_value|
<add> s = nil
<add> assert_raises(ArgumentError,"should only accept a known attribute type, but accepted: #{bad_value.inspect}") do
<add> Person.schema do
<add> s = self
<add> attribute 'key', bad_value
<ide> end
<del> assert !s.respond_to?(bad_value), "should only respond to a known attribute type, but accepted: #{bad_value.inspect}"
<del> assert_raises(NoMethodError,"should only have methods for known attribute types, but accepted: #{bad_value.inspect}") do
<del> s.send bad_value, 'key'
<add> end
<add> assert !self.respond_to?(bad_value), "should only respond to a known attribute type, but accepted: #{bad_value.inspect}"
<add> assert_raises(NoMethodError,"should only have methods for known attribute types, but accepted: #{bad_value.inspect}") do
<add> Person.schema do
<add> send bad_value, 'key'
<ide> end
<ide> end
<ide> end
<ide> end
<ide>
<ide>
<ide> test "should accept attribute types as the type's name as the method" do
<del> Person.schema do |s|
<del> ActiveResource::Schema::KNOWN_ATTRIBUTE_TYPES.each do |the_type|
<del> assert s.respond_to?(the_type), "should recognise the attribute-type: #{the_type} as a method"
<del> assert_nothing_raised("should take the method #{the_type} with the attribute name") do
<del> s.send(the_type,'foo') # eg s.string :foo
<del> end
<del> assert s.attrs.has_key?('foo'), "should now have saved the attribute name"
<del> assert_equal the_type.to_s, s.attrs['foo'], "should have saved the attribute type of: #{the_type}"
<add> ActiveResource::Schema::KNOWN_ATTRIBUTE_TYPES.each do |the_type|
<add> s = nil
<add> Person.schema do
<add> s = self
<add> send(the_type,'foo')
<ide> end
<add> assert s.attrs.has_key?('foo'), "should now have saved the attribute name"
<add> assert_equal the_type.to_s, s.attrs['foo'], "should have saved the attribute type of: #{the_type}"
<ide> end
<ide> end
<ide>
<ide> test "should accept multiple attribute names for an attribute method" do
<ide> names = ['foo','bar','baz']
<del> Person.schema do |s|
<del> assert_nothing_raised("should take strings with multiple attribute names as params") do
<del> s.string( *names)
<del> end
<del> names.each do |the_name|
<del> assert s.attrs.has_key?(the_name), "should now have saved the attribute name: #{the_name}"
<del> assert_equal 'string', s.attrs[the_name], "should have saved the attribute as a string"
<del> end
<add> s = nil
<add> Person.schema do
<add> s = self
<add> string(*names)
<add> end
<add> names.each do |the_name|
<add> assert s.attrs.has_key?(the_name), "should now have saved the attribute name: #{the_name}"
<add> assert_equal 'string', s.attrs[the_name], "should have saved the attribute as a string"
<ide> end
<ide> end
<ide>
<ide> def teardown
<ide>
<ide> assert_nothing_raised do
<ide> Person.schema = {new_attr_name.to_s => 'string'}
<del> Person.schema {|s| s.string new_attr_name_two }
<add> Person.schema { string new_attr_name_two }
<ide> end
<ide>
<ide> assert Person.new.respond_to?(new_attr_name), "should respond to the attribute in a passed-in schema, but failed on: #{new_attr_name}"
<ide> def teardown
<ide> assert !Person.new.respond_do?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet"
<ide>
<ide> assert_nothing_raised do
<del> Person.schema {|s| s.string new_attr_name_two }
<add> Person.schema { string new_attr_name_two }
<ide> Person.schema = {new_attr_name.to_s => 'string'}
<ide> end
<ide>
<ide> def teardown
<ide> end
<ide>
<ide> Person.schema = {new_attr_name.to_s => :float}
<del> Person.schema {|s| s.string new_attr_name_two }
<add> Person.schema { string new_attr_name_two }
<ide>
<ide> assert_nothing_raised do
<ide> Person.new.send(new_attr_name) | 3 |
Go | Go | use gotestyourself env patching | 2b445a53c17ae6526c11a729cb6d1d1dc57490ff | <ide><path>client/client_test.go
<ide> import (
<ide> "net/url"
<ide> "os"
<ide> "runtime"
<del> "strings"
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/internal/testutil"
<add> "github.com/gotestyourself/gotestyourself/env"
<ide> "github.com/gotestyourself/gotestyourself/skip"
<ide> "github.com/stretchr/testify/assert"
<add> "github.com/stretchr/testify/require"
<ide> )
<ide>
<ide> func TestNewEnvClient(t *testing.T) {
<del> skip.IfCondition(t, runtime.GOOS == "windows")
<add> skip.If(t, runtime.GOOS == "windows")
<ide>
<ide> testcases := []struct {
<ide> doc string
<ide> func TestNewEnvClient(t *testing.T) {
<ide> },
<ide> }
<ide>
<del> env := envToMap()
<del> defer mapToEnv(env)
<add> defer env.PatchAll(t, nil)()
<ide> for _, c := range testcases {
<del> mapToEnv(c.envs)
<add> env.PatchAll(t, c.envs)
<ide> apiclient, err := NewEnvClient()
<ide> if c.expectedError != "" {
<ide> assert.Error(t, err, c.doc)
<ide> func TestParseHostURL(t *testing.T) {
<ide> }
<ide>
<ide> func TestNewEnvClientSetsDefaultVersion(t *testing.T) {
<del> env := envToMap()
<del> defer mapToEnv(env)
<del>
<del> envMap := map[string]string{
<add> defer env.PatchAll(t, map[string]string{
<ide> "DOCKER_HOST": "",
<ide> "DOCKER_API_VERSION": "",
<ide> "DOCKER_TLS_VERIFY": "",
<ide> "DOCKER_CERT_PATH": "",
<del> }
<del> mapToEnv(envMap)
<add> })()
<ide>
<ide> client, err := NewEnvClient()
<ide> if err != nil {
<ide> func TestNewEnvClientSetsDefaultVersion(t *testing.T) {
<ide> // TestNegotiateAPIVersionEmpty asserts that client.Client can
<ide> // negotiate a compatible APIVersion when omitted
<ide> func TestNegotiateAPIVersionEmpty(t *testing.T) {
<del> env := envToMap()
<del> defer mapToEnv(env)
<del>
<del> envMap := map[string]string{
<del> "DOCKER_API_VERSION": "",
<del> }
<del> mapToEnv(envMap)
<add> defer env.PatchAll(t, map[string]string{"DOCKER_API_VERSION": ""})
<ide>
<ide> client, err := NewEnvClient()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> require.NoError(t, err)
<ide>
<ide> ping := types.Ping{
<ide> APIVersion: "",
<ide> func TestNegotiateAPIVersionEmpty(t *testing.T) {
<ide> // negotiate a compatible APIVersion with the server
<ide> func TestNegotiateAPIVersion(t *testing.T) {
<ide> client, err := NewEnvClient()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> require.NoError(t, err)
<ide>
<ide> expected := "1.21"
<del>
<ide> ping := types.Ping{
<ide> APIVersion: expected,
<ide> OSType: "linux",
<ide> func TestNegotiateAPIVersion(t *testing.T) {
<ide> // TestNegotiateAPIVersionOverride asserts that we honor
<ide> // the environment variable DOCKER_API_VERSION when negotianing versions
<ide> func TestNegotiateAPVersionOverride(t *testing.T) {
<del> env := envToMap()
<del> defer mapToEnv(env)
<del>
<del> envMap := map[string]string{
<del> "DOCKER_API_VERSION": "9.99",
<del> }
<del> mapToEnv(envMap)
<add> expected := "9.99"
<add> defer env.PatchAll(t, map[string]string{"DOCKER_API_VERSION": expected})()
<ide>
<ide> client, err := NewEnvClient()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> require.NoError(t, err)
<ide>
<ide> ping := types.Ping{
<ide> APIVersion: "1.24",
<ide> OSType: "linux",
<ide> Experimental: false,
<ide> }
<ide>
<del> expected := envMap["DOCKER_API_VERSION"]
<del>
<ide> // test that we honored the env var
<ide> client.NegotiateAPIVersionPing(ping)
<ide> assert.Equal(t, expected, client.version)
<ide> }
<ide>
<del>// mapToEnv takes a map of environment variables and sets them
<del>func mapToEnv(env map[string]string) {
<del> for k, v := range env {
<del> os.Setenv(k, v)
<del> }
<del>}
<del>
<del>// envToMap returns a map of environment variables
<del>func envToMap() map[string]string {
<del> env := make(map[string]string)
<del> for _, e := range os.Environ() {
<del> kv := strings.SplitAfterN(e, "=", 2)
<del> env[kv[0]] = kv[1]
<del> }
<del>
<del> return env
<del>}
<del>
<ide> type roundTripFunc func(*http.Request) (*http.Response, error)
<ide>
<ide> func (rtf roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.