<commit_before>/**
 * Utility for switching the current date range.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import { pageWait } from '../utils';

/**
 * Changes the currently selected date range.
 *
 * Currently only identifiable by the option values.
 *
 * @since 1.0.0
 *
 * @param {string} fromRange The currently selected date range.
 * @param {string} toRange   The new date range to select.
 */
export async function switchDateRange( fromRange, toRange ) {
	await pageWait();
	await Promise.all( [
		expect( page ).toClick( '.googlesitekit-date-range-selector .mdc-button__label', { text: new RegExp( fromRange, 'i' ) } ),
		page.waitForSelector( '.googlesitekit-date-range-selector .mdc-menu-surface--open .mdc-list-item' ),
	] );
	// Intentionally left off the '--open' suffix here as it proved problematic for stability.
	await expect( page ).toClick( '.mdc-menu-surface .mdc-list-item', { text: new RegExp( toRange, 'i' ) } );
}
<commit_msg>Update the e2e switch-date-range helper to use the .googlesitekit-date-range-selector class prefix.<commit_after>/**
 * Utility for switching the current date range.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import { pageWait } from '../utils';

/**
 * Changes the currently selected date range.
 *
 * Currently only identifiable by the option values.
 *
 * @since 1.0.0
 *
 * @param {string} fromRange The currently selected date range.
 * @param {string} toRange   The new date range to select.
 */
export async function switchDateRange( fromRange, toRange ) {
	await pageWait();
	await Promise.all( [
		expect( page ).toClick( '.googlesitekit-date-range-selector .mdc-button__label', { text: new RegExp( fromRange, 'i' ) } ),
		page.waitForSelector( '.googlesitekit-date-range-selector .mdc-menu-surface--open .mdc-list-item' ),
	] );
	// Intentionally left off the '--open' suffix here as it proved problematic for stability.
	await expect( page ).toClick( '.googlesitekit-date-range-selector .mdc-menu-surface .mdc-list-item', { text: new RegExp( toRange, 'i' ) } );
}
<|endoftext|>


<commit_before>// Use the external Chai As Promised to deal with resolving promises in
// expectations.
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

var expect = chai.expect;

// Chai expect().to.exist syntax makes default jshint unhappy.
// jshint expr:true

var MainPage = require('./main_page.js');

module.exports = function() {

    var page,
        startParamCount;

    this.Given(/^I go to the front page$/, function(next) {
        page = new MainPage();
        page.get().then(next);
    });

    this.Then(/^there should be (\d+) parameter sets?$/, function(expected_count, next) {
        var expected_count = Number(expected_count);
        page.paramCount().then(
            function(c) {
                expect(c).to.equal(expected_count);
                next();
            });
    });

    this.When(/^I add a parameter set$/, function (next) {
        page.addParameter().then(next);
    });

    this.When(/^I delete a parameter set$/, function (next) {
        page.deleteParameter(0).then(next);
    });

};
<commit_msg>ui tests returning promises rather than callbacking.<commit_after>// Use the external Chai As Promised to deal with resolving promises in
// expectations.
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

var expect = chai.expect;

// Chai expect().to.exist syntax makes default jshint unhappy.
// jshint expr:true

var MainPage = require('./main_page.js');

module.exports = function() {

    var page,
        startParamCount;

    this.Given(/^I go to the front page$/, function() {
        page = new MainPage();
        return page.get();
    });

    this.Then(/^there should be (\d+) parameter sets?$/, function(expected_count) {
        var expected_count = Number(expected_count);
        return page.paramCount().then(
            function(c) {
                expect(c).to.equal(expected_count);
            });
    });

    this.When(/^I add a parameter set$/, function () {
        return page.addParameter();
    });

    this.When(/^I delete a parameter set$/, function () {
        return page.deleteParameter(0);
    });

};
<|endoftext|>


<commit_before>import axios from 'axios'
import Auth from 'app/js/services/auth.js'
import Cookies from 'js-cookie'
import { Promise } from 'es6-promise'

const CP_API_URL = 'http://localhost:10000/api/v1/'

describe('Auth', () => {
  beforeEach(() => {
    jasmine.Ajax.install()
  })

  afterEach(() => {
    jasmine.Ajax.uninstall()
  })

  describe('init', () => {
    describe('basic ajax call setup', () => {
      it('add authorization cookie to request headers', (done) => {
        Cookies.set('accessToken', 'secretToken')
        jasmine.Ajax.stubRequest('/foo').andReturn({status: 200})

        Auth.init()

        axios('/foo').then(() => {
          let request = jasmine.Ajax.requests.mostRecent()
          expect(request.requestHeaders.Authorization).toEqual('secretToken')
          done()
        })
      })
    })

    describe('when accessToken is invalid', () => {
      beforeEach(() => {
        let routeUtils = { redirectTo: () => Promise.resolve() }

        let AuthRewireAPI = Auth.__RewireAPI__
        AuthRewireAPI.__Rewire__('routeUtils', routeUtils)

        Cookies.set('refreshToken', 'secretRefreshToken')

        jasmine.Ajax.stubRequest('/unauthorized').andReturn({status: 401})
        jasmine.Ajax.stubRequest(`${CP_API_URL}api_session/refresh`).andReturn({
          responseText: '{"access_token":"NewAccessToken"}',
        })

        Auth.init()
      })

      it('call refresh token API endpoint with refresh token from cookie', (done) => {
        axios.get('/unauthorized').then(() => {
          let request = jasmine.Ajax.requests.at(1)

          expect(request.url).toEqual(`${CP_API_URL}api_session/refresh`)
          expect(request.method).toEqual('POST')
          expect(request.data()).toEqual({ refresh_token: 'secretRefreshToken' })

          done()
        })
      })

      it('set new access token to cookie', (done) => {
        axios.get('/unauthorized').then(() => {
          expect(Cookies.get('accessToken')).toEqual('NewAccessToken')
          done()
        })
      })

      it('recall previous request', (done) => {
        axios.get('/unauthorized').then(() => {
          let request = jasmine.Ajax.requests.at(4)
          expect(request.url).toEqual('/unauthorized')
          done()
        })
      })

      it('restart request maximum 5 times', (done) => {
        spyOn(axios, 'request').and.callThrough()

        axios.get('/unauthorized').then(() => {
          expect(axios.request.calls.count()).toEqual(5)
          done()
        })
      })
    })

    describe('when refreshToken is invalid', () => {
      it('call routeUtils.redirectTo with login url', (done) => {
        let routeUtils = { redirectTo: jasmine.createSpy('redirectTo') }
        let AuthRewireAPI = Auth.__RewireAPI__
        AuthRewireAPI.__Rewire__('routeUtils', routeUtils)

        jasmine.Ajax.stubRequest('/unauthorized').andReturn({status: 401})
        jasmine.Ajax.stubRequest(`${CP_API_URL}api_session/refresh`).andReturn({
          status: 400,
        })

        Auth.init()
        axios.get('/unauthorized')

        setTimeout(() => {
          expect(routeUtils.redirectTo).toHaveBeenCalledWith(
            'http://test.com/admin/#/auth/sign_in?return_url=http://test.com/analytics/'
          )
          done()
        }, 1)
      })
    })
  })
})
<commit_msg>[+TC] Imported cp admin url from app constants in test<commit_after>import axios from 'axios'
import Auth from 'app/js/services/auth.js'
import Cookies from 'js-cookie'
import { Promise } from 'es6-promise'
import { CP_ADMIN_API } from 'app/js/constants/app_constants'

describe('Auth', () => {
  beforeEach(() => {
    jasmine.Ajax.install()
  })

  afterEach(() => {
    jasmine.Ajax.uninstall()
  })

  describe('init', () => {
    describe('basic ajax call setup', () => {
      it('add authorization cookie to request headers', (done) => {
        Cookies.set('accessToken', 'secretToken')
        jasmine.Ajax.stubRequest('/foo').andReturn({status: 200})

        Auth.init()

        axios('/foo').then(() => {
          let request = jasmine.Ajax.requests.mostRecent()
          expect(request.requestHeaders.Authorization).toEqual('secretToken')
          done()
        })
      })
    })

    describe('when accessToken is invalid', () => {
      beforeEach(() => {
        let routeUtils = { redirectTo: () => Promise.resolve() }

        let AuthRewireAPI = Auth.__RewireAPI__
        AuthRewireAPI.__Rewire__('routeUtils', routeUtils)

        Cookies.set('refreshToken', 'secretRefreshToken')

        jasmine.Ajax.stubRequest('/unauthorized').andReturn({status: 401})
        jasmine.Ajax.stubRequest(`${CP_ADMIN_API}api_session/refresh`).andReturn({
          responseText: '{"access_token":"NewAccessToken"}',
        })

        Auth.init()
      })

      it('call refresh token API endpoint with refresh token from cookie', (done) => {
        axios.get('/unauthorized').then(() => {
          let request = jasmine.Ajax.requests.at(1)

          expect(request.url).toEqual(`${CP_ADMIN_API}api_session/refresh`)
          expect(request.method).toEqual('POST')
          expect(request.data()).toEqual({ refresh_token: 'secretRefreshToken' })

          done()
        })
      })

      it('set new access token to cookie', (done) => {
        axios.get('/unauthorized').then(() => {
          expect(Cookies.get('accessToken')).toEqual('NewAccessToken')
          done()
        })
      })

      it('recall previous request', (done) => {
        axios.get('/unauthorized').then(() => {
          let request = jasmine.Ajax.requests.at(4)
          expect(request.url).toEqual('/unauthorized')
          done()
        })
      })

      it('restart request maximum 5 times', (done) => {
        spyOn(axios, 'request').and.callThrough()

        axios.get('/unauthorized').then(() => {
          expect(axios.request.calls.count()).toEqual(5)
          done()
        })
      })
    })

    describe('when refreshToken is invalid', () => {
      it('call routeUtils.redirectTo with login url', (done) => {
        let routeUtils = { redirectTo: jasmine.createSpy('redirectTo') }
        let AuthRewireAPI = Auth.__RewireAPI__
        AuthRewireAPI.__Rewire__('routeUtils', routeUtils)

        jasmine.Ajax.stubRequest('/unauthorized').andReturn({status: 401})
        jasmine.Ajax.stubRequest(`${CP_ADMIN_API}api_session/refresh`).andReturn({
          status: 400,
        })

        Auth.init()
        axios.get('/unauthorized')

        setTimeout(() => {
          expect(routeUtils.redirectTo).toHaveBeenCalledWith(
            'http://test.com/admin/#/auth/sign_in?return_url=http://test.com/analytics/'
          )
          done()
        }, 1)
      })
    })
  })
})
<|endoftext|>


<commit_before>/*
 * dialog_defaults.js
 */

var dialog_defaults = {
	autoOpen: true,
	buttons: {},
	closeOnEscape: true,
	closeText: 'close',
	disabled: false,
	dialogClass: '',
	draggable: true,
	height: 'auto',
	hide: null,
	maxHeight: false,
	maxWidth: false,
	minHeight: 150,
	minWidth: 150,
	modal: false,
	position: 'center',
	resizable: true,
	show: null,
	stack: true,
	title: '',
	width: 300,
	zIndex: 1000
};

commonWidgetTests('dialog', { defaults: dialog_defaults });
<commit_msg>Dialog: Updated test for default position option. QUnit still fails the test though.<commit_after>/*
 * dialog_defaults.js
 */

var dialog_defaults = {
	autoOpen: true,
	buttons: {},
	closeOnEscape: true,
	closeText: 'close',
	disabled: false,
	dialogClass: '',
	draggable: true,
	height: 'auto',
	hide: null,
	maxHeight: false,
	maxWidth: false,
	minHeight: 150,
	minWidth: 150,
	modal: false,
	position: {
		my: 'center',
		at: 'center',
		of: window,
		collision: 'fit',
		// ensure that the titlebar is never outside the document
		using: function(pos) {
			var topOffset = $(this).css(pos).offset().top;
			if (topOffset < 0) {
				$(this).css('top', pos.top - topOffset);
			}
		}
	},
	resizable: true,
	show: null,
	stack: true,
	title: '',
	width: 300,
	zIndex: 1000
};

commonWidgetTests('dialog', { defaults: dialog_defaults });
<|endoftext|>


<commit_before>import Ember from 'ember';
import ObservableMixin from 'ember-cli-rxjs/mixins/observable';
import { module, test } from 'qunit';

module('Unit | Mixin | observable');

test('this.observable.property', function(assert) {
  let done = assert.async();

  let ObserveActionObject = Ember.Object.extend(ObservableMixin);
  let subject = ObserveActionObject.create({ x: '1' });
  assert.ok(subject);

  let expected = ['1','4','3'];
  subject.observable.property('x').subscribe(x => {
    assert.equal(x, expected.shift());
    if (expected.length === 0) {
      done();
    }
  });

  subject.set('x', '4');
  subject.set('x', '3');
});

test('this.observable.properties', function(assert) {
  let done = assert.async();

  let ObserveActionObject = Ember.Object.extend(ObservableMixin);
  let subject = ObserveActionObject.create({ x: '1', y: 'a' });
  assert.ok(subject);

  let expected = [['1','a'],['1','b'],['2','b']];
  subject.observable.properties('x','y').subscribe(xs => {
    assert.deepEqual(xs, expected.shift());
    if (expected.length === 0) {
      done();
    }
  });

  subject.set('y', 'b');
  subject.set('x', '2');
});
<commit_msg>more tests<commit_after>import Ember from 'ember';
import ObservableMixin from 'ember-cli-rxjs/mixins/observable';
import { module, test } from 'qunit';

module('Unit | Mixin | observable');

test('this.observable.property', function(assert) {
  let done = assert.async();

  let ObserveActionObject = Ember.Object.extend(ObservableMixin);
  let subject = ObserveActionObject.create({ x: '1' });
  assert.ok(subject);

  let expected = ['1','4','3'];
  subject.observable.property('x').subscribe(x => {
    assert.equal(x, expected.shift());
    if (expected.length === 0) {
      done();
    }
  });

  subject.set('x', '4');
  subject.set('x', '3');
});

test('this.observable.properties', function(assert) {
  let done = assert.async();

  let ObserveActionObject = Ember.Object.extend(ObservableMixin);
  let subject = ObserveActionObject.create({ x: '1', y: 'a' });
  assert.ok(subject);

  let expected = [['1','a'],['1','b'],['2','b']];
  subject.observable.properties('x','y').subscribe(xs => {
    assert.deepEqual(xs, expected.shift());
    if (expected.length === 0) {
      done();
    }
  });

  subject.set('y', 'b');
  subject.set('x', '2');
});

test('this.observable.action', function(assert) {
  let done = assert.async();

  let ObserveActionRoute = Ember.Route.extend(ObservableMixin);
  let subject = ObserveActionRoute.create();
  assert.ok(subject);

  let expected = { x: 1 };
  subject.observable.action('test').subscribe(x => {
    assert.deepEqual(x, expected);
    done();
  });

  subject.send('test', { x: 1 });
});
<|endoftext|>


<commit_before>/**
 * @param {string} name
 * @param {Object=} lifecycle
 */
function module(name, lifecycle) {}

/**
 * @param {string} title
 * @param {Number|Function} expected
 * @param {Function=} test_func
 */
function test(title, expected, test_func){}

/**
 * @param {string} name
 * @param {Number|Function} expected
 * @param {Function=} test_func
 */
function asyncTest(name, expected, test_func){}

/**
 * @param {number} amount
 */
function expect(amount){}

/**
 * @param {*} state
 * @param {string=} message
 */
function ok(state, message){}

/**
 * @param {*} actual
 * @param {*} expected
 * @param {string=} message
 */
function equal(actual, expected, message){}

/**
 * @param {*} actual
 * @param {*} expected
 * @param {string=} message
 */
function notEqual(actual, expected, message){}

/**
 * @param {*} actual
 * @param {*} expected
 * @param {string=} message
 */
function deepEqual(actual, expected, message){}

/**
 * @param {*} actual
 * @param {*} expected
 * @param {string=} message
 */
function notDeepEqual(actual, expected, message){}

/**
 * @param {*} actual
 * @param {*} expected
 * @param {string=} message
 */
function strictEqual(actual, expected, message){}

/**
 * @param {*} actual
 * @param {*} expected
 * @param {string=} message
 */
function notStrictEqual(actual, expected, message){}

/**
 * @param {number=} increment
 */
function start(increment){}

/**
 * @param {number=} increment
 */
function stop(increment){}
<commit_msg>Bugfix to qunit externs: Number -> number<commit_after>/**
 * @param {string} name
 * @param {Object=} lifecycle
 */
function module(name, lifecycle) {}

/**
 * @param {string} title
 * @param {number|Function} expected
 * @param {Function=} test_func
 */
function test(title, expected, test_func){}

/**
 * @param {string} name
 * @param {number|Function} expected
 * @param {Function=} test_func
 */
function asyncTest(name, expected, test_func){}

/**
 * @param {number} amount
 */
function expect(amount){}

/**
 * @param {*} state
 * @param {string=} message
 */
function ok(state, message){}

/**
 * @param {*} actual
 * @param {*} expected
 * @param {string=} message
 */
function equal(actual, expected, message){}

/**
 * @param {*} actual
 * @param {*} expected
 * @param {string=} message
 */
function notEqual(actual, expected, message){}

/**
 * @param {*} actual
 * @param {*} expected
 * @param {string=} message
 */
function deepEqual(actual, expected, message){}

/**
 * @param {*} actual
 * @param {*} expected
 * @param {string=} message
 */
function notDeepEqual(actual, expected, message){}

/**
 * @param {*} actual
 * @param {*} expected
 * @param {string=} message
 */
function strictEqual(actual, expected, message){}

/**
 * @param {*} actual
 * @param {*} expected
 * @param {string=} message
 */
function notStrictEqual(actual, expected, message){}

/**
 * @param {number=} increment
 */
function start(increment){}

/**
 * @param {number=} increment
 */
function stop(increment){}
<|endoftext|>


<commit_before>// Copyright 2013 The Polymer Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

(function(scope) {
  'use strict';

  var HTMLCollection = scope.wrappers.HTMLCollection;
  var NodeList = scope.wrappers.NodeList;
  var getTreeScope = scope.getTreeScope;
  var wrap = scope.wrap;

  var originalDocumentQuerySelector = document.querySelector;
  var originalElementQuerySelector = document.documentElement.querySelector;

  var originalDocumentQuerySelectorAll = document.querySelectorAll;
  var originalElementQuerySelectorAll = document.documentElement.querySelectorAll;

  var originalDocumentGetElementsByTagName = document.getElementsByTagName;
  var originalElementGetElementsByTagName = document.documentElement.getElementsByTagName;

  var originalDocumentGetElementsByTagNameNS = document.getElementsByTagNameNS;
  var originalElementGetElementsByTagNameNS = document.documentElement.getElementsByTagNameNS;

  var OriginalElement = window.Element;
  var OriginalDocument = window.HTMLDocument;

  function filterNodeList(list, index, result) {
    var wrappedItem = null;
    var root = null;
    for (var i = 0, length = list.length; i < length; i++) {
      wrappedItem = wrap(list[i]);
      if (root = getTreeScope(wrappedItem).root) {
        if (root instanceof scope.wrappers.ShadowRoot) {
          continue;
        }
      }
      result[index++] = wrappedItem;
    }

    return index;
  }

  function findOne(node, selector) {
    var m, el = node.firstElementChild;
    while (el) {
      if (el.matches(selector))
        return el;
      m = findOne(el, selector);
      if (m)
        return m;
      el = el.nextElementSibling;
    }
    return null;
  }

  function matchesSelector(el, selector) {
    return el.matches(selector);
  }

  var XHTML_NS = 'http://www.w3.org/1999/xhtml';

  function matchesTagName(el, localName, localNameLowerCase) {
    var ln = el.localName;
    return ln === localName ||
        ln === localNameLowerCase && el.namespaceURI === XHTML_NS;
  }

  function matchesEveryThing() {
    return true;
  }

  function matchesLocalNameOnly(el, ns, localName) {
    return el.localName === localName;
  }

  function matchesNameSpace(el, ns) {
    return el.namespaceURI === ns;
  }

  function matchesLocalNameNS(el, ns, localName) {
    return el.namespaceURI === ns && el.localName === localName;
  }

  function findElements(node, index, result, p, arg0, arg1) {
    var el = node.firstElementChild;
    while (el) {
      if (p(el, arg0, arg1))
        result[index++] = el;
      index = findElements(el, index, result, p, arg0, arg1);
      el = el.nextElementSibling;
    }
    return index;
  }

  // find and findAll will only match Simple Selectors,
  // Structural Pseudo Classes are not guarenteed to be correct
  // http://www.w3.org/TR/css3-selectors/#simple-selectors

  function querySelectorAllFiltered (p, index, result, selector) {
    var target = this.impl;
    var list;
    var root = getTreeScope(this).root;
    if (root instanceof scope.wrappers.ShadowRoot) {
      // We are in the shadow tree and the logical tree is
      // going to be disconnected so we do a manual tree traversal
      return findElements(this, index, result, p, selector, null);
    } else if (target instanceof OriginalElement) {
      list = originalElementQuerySelectorAll.call(target, selector);
    } else if (target instanceof OriginalDocument) {
      list = originalDocumentQuerySelectorAll.call(target, selector);
    } else {
      // When we get a ShadowRoot the logical tree is going to be disconnected
      // so we do a manual tree traversal
      return findElements(this, index, result, p, selector, null);
    }

    return filterNodeList(list, index, result);
  }

  var SelectorsInterface = {
    querySelector: function(selector) {
      var target = this.impl;
      var wrappedItem;
      var root = getTreeScope(this).root;
      if (root instanceof scope.wrappers.ShadowRoot) {
        // We are in the shadow tree and the logical tree is
        // going to be disconnected so we do a manual tree traversal
        return findOne(this, selector);
      } else if (target instanceof OriginalElement) {
        wrappedItem = wrap(originalElementQuerySelector.call(target, selector));
      } else if (target instanceof OriginalDocument) {
        wrappedItem = wrap(originalDocumentQuerySelector.call(target, selector));
      } else {
        // When we get a ShadowRoot the logical tree is going to be disconnected
        // so we do a manual tree traversal
        return findOne(this, selector);
      }

      if (!wrappedItem) {
        // When the original query returns nothing
        // we return nothing (to be consistent with the other wrapped calls)
        return wrappedItem;
      } else if (root = getTreeScope(wrappedItem).root) {
        if (root instanceof scope.wrappers.ShadowRoot) {
          // When the original query returns an element in the ShadowDOM
          // we must do a manual tree traversal
          return findOne(this, selector);
        }
      }

      return wrappedItem;
    },
    querySelectorAll: function(selector) {
      var result = new NodeList();

      result.length = querySelectorAllFiltered.call(this,
          matchesSelector,
          0,
          result,
          selector);

      return result;
    }
  };

  function getElementsByTagNameFiltered (p, index, result, localName, lowercase) {
    var target = this.impl;
    var list;
    var root = getTreeScope(this).root;
    if (root instanceof scope.wrappers.ShadowRoot) {
      // We are in the shadow tree and the logical tree is
      // going to be disconnected so we do a manual tree traversal
      return findElements(this, index, result, p, localName, lowercase);
    } else if (target instanceof OriginalElement) {
      list = originalElementGetElementsByTagName.call(target, localName, lowercase);
    } else if (target instanceof OriginalDocument) {
      list = originalDocumentGetElementsByTagName.call(target, localName, lowercase);
    } else {
      // When we get a ShadowRoot the logical tree is going to be disconnected
      // so we do a manual tree traversal
      return findElements(this, index, result, p, localName, lowercase);
    }

    return filterNodeList(list, index, result);
  }

  function getElementsByTagNameNSFiltered (p, index, result, ns, localName) {
    var target = this.impl;
    var list;
    var root = getTreeScope(this).root;
    if (root instanceof scope.wrappers.ShadowRoot) {
      // We are in the shadow tree and the logical tree is
      // going to be disconnected so we do a manual tree traversal
      return findElements(this, index, result, p, ns, localName);
    } else if (target instanceof OriginalElement) {
      list = originalElementGetElementsByTagNameNS.call(target, ns, localName);
    } else if (target instanceof OriginalDocument) {
      list = originalDocumentGetElementsByTagNameNS.call(target, ns, localName);
    } else {
      // When we get a ShadowRoot the logical tree is going to be disconnected
      // so we do a manual tree traversal
      return findElements(this, index, result, p, ns, localName);
    }

    return filterNodeList(list, index, result);
  }

  var GetElementsByInterface = {
    getElementsByTagName: function(localName) {
      var result = new HTMLCollection();
      var match = localName === '*' ? matchesEveryThing : matchesTagName;

      result.length = getElementsByTagNameFiltered.call(this,
          match,
          0,
          result,
          localName,
          localName.toLowerCase());

      return result;
    },

    getElementsByClassName: function(className) {
      // TODO(arv): Check className?
      return this.querySelectorAll('.' + className);
    },

    getElementsByTagNameNS: function(ns, localName) {
      var result = new HTMLCollection();
      var match = null;

      if (ns === '*') {
        match = localName === '*' ? matchesEveryThing : matchesLocalNameOnly;
      } else {
        match = localName === '*' ? matchesNameSpace : matchesLocalNameNS;
      }

      result.length = getElementsByTagNameNSFiltered.call(this,
          match,
          0,
          result,
          ns || null,
          localName);

      return result;
    }
  };

  scope.GetElementsByInterface = GetElementsByInterface;
  scope.SelectorsInterface = SelectorsInterface;

})(window.ShadowDOMPolyfill);
<commit_msg>Restore IE10 functionality.<commit_after>// Copyright 2013 The Polymer Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

(function(scope) {
  'use strict';

  var HTMLCollection = scope.wrappers.HTMLCollection;
  var NodeList = scope.wrappers.NodeList;
  var getTreeScope = scope.getTreeScope;
  var wrap = scope.wrap;

  var originalDocumentQuerySelector = document.querySelector;
  var originalElementQuerySelector = document.documentElement.querySelector;

  var originalDocumentQuerySelectorAll = document.querySelectorAll;
  var originalElementQuerySelectorAll = document.documentElement.querySelectorAll;

  var originalDocumentGetElementsByTagName = document.getElementsByTagName;
  var originalElementGetElementsByTagName = document.documentElement.getElementsByTagName;

  var originalDocumentGetElementsByTagNameNS = document.getElementsByTagNameNS;
  var originalElementGetElementsByTagNameNS = document.documentElement.getElementsByTagNameNS;

  var OriginalElement = window.Element;
  var OriginalDocument = window.HTMLDocument || window.Document;

  function filterNodeList(list, index, result) {
    var wrappedItem = null;
    var root = null;
    for (var i = 0, length = list.length; i < length; i++) {
      wrappedItem = wrap(list[i]);
      if (root = getTreeScope(wrappedItem).root) {
        if (root instanceof scope.wrappers.ShadowRoot) {
          continue;
        }
      }
      result[index++] = wrappedItem;
    }

    return index;
  }

  function findOne(node, selector) {
    var m, el = node.firstElementChild;
    while (el) {
      if (el.matches(selector))
        return el;
      m = findOne(el, selector);
      if (m)
        return m;
      el = el.nextElementSibling;
    }
    return null;
  }

  function matchesSelector(el, selector) {
    return el.matches(selector);
  }

  var XHTML_NS = 'http://www.w3.org/1999/xhtml';

  function matchesTagName(el, localName, localNameLowerCase) {
    var ln = el.localName;
    return ln === localName ||
        ln === localNameLowerCase && el.namespaceURI === XHTML_NS;
  }

  function matchesEveryThing() {
    return true;
  }

  function matchesLocalNameOnly(el, ns, localName) {
    return el.localName === localName;
  }

  function matchesNameSpace(el, ns) {
    return el.namespaceURI === ns;
  }

  function matchesLocalNameNS(el, ns, localName) {
    return el.namespaceURI === ns && el.localName === localName;
  }

  function findElements(node, index, result, p, arg0, arg1) {
    var el = node.firstElementChild;
    while (el) {
      if (p(el, arg0, arg1))
        result[index++] = el;
      index = findElements(el, index, result, p, arg0, arg1);
      el = el.nextElementSibling;
    }
    return index;
  }

  // find and findAll will only match Simple Selectors,
  // Structural Pseudo Classes are not guarenteed to be correct
  // http://www.w3.org/TR/css3-selectors/#simple-selectors

  function querySelectorAllFiltered (p, index, result, selector) {
    var target = this.impl;
    var list;
    var root = getTreeScope(this).root;
    if (root instanceof scope.wrappers.ShadowRoot) {
      // We are in the shadow tree and the logical tree is
      // going to be disconnected so we do a manual tree traversal
      return findElements(this, index, result, p, selector, null);
    } else if (target instanceof OriginalElement) {
      list = originalElementQuerySelectorAll.call(target, selector);
    } else if (target instanceof OriginalDocument) {
      list = originalDocumentQuerySelectorAll.call(target, selector);
    } else {
      // When we get a ShadowRoot the logical tree is going to be disconnected
      // so we do a manual tree traversal
      return findElements(this, index, result, p, selector, null);
    }

    return filterNodeList(list, index, result);
  }

  var SelectorsInterface = {
    querySelector: function(selector) {
      var target = this.impl;
      var wrappedItem;
      var root = getTreeScope(this).root;
      if (root instanceof scope.wrappers.ShadowRoot) {
        // We are in the shadow tree and the logical tree is
        // going to be disconnected so we do a manual tree traversal
        return findOne(this, selector);
      } else if (target instanceof OriginalElement) {
        wrappedItem = wrap(originalElementQuerySelector.call(target, selector));
      } else if (target instanceof OriginalDocument) {
        wrappedItem = wrap(originalDocumentQuerySelector.call(target, selector));
      } else {
        // When we get a ShadowRoot the logical tree is going to be disconnected
        // so we do a manual tree traversal
        return findOne(this, selector);
      }

      if (!wrappedItem) {
        // When the original query returns nothing
        // we return nothing (to be consistent with the other wrapped calls)
        return wrappedItem;
      } else if (root = getTreeScope(wrappedItem).root) {
        if (root instanceof scope.wrappers.ShadowRoot) {
          // When the original query returns an element in the ShadowDOM
          // we must do a manual tree traversal
          return findOne(this, selector);
        }
      }

      return wrappedItem;
    },
    querySelectorAll: function(selector) {
      var result = new NodeList();

      result.length = querySelectorAllFiltered.call(this,
          matchesSelector,
          0,
          result,
          selector);

      return result;
    }
  };

  function getElementsByTagNameFiltered (p, index, result, localName, lowercase) {
    var target = this.impl;
    var list;
    var root = getTreeScope(this).root;
    if (root instanceof scope.wrappers.ShadowRoot) {
      // We are in the shadow tree and the logical tree is
      // going to be disconnected so we do a manual tree traversal
      return findElements(this, index, result, p, localName, lowercase);
    } else if (target instanceof OriginalElement) {
      list = originalElementGetElementsByTagName.call(target, localName, lowercase);
    } else if (target instanceof OriginalDocument) {
      list = originalDocumentGetElementsByTagName.call(target, localName, lowercase);
    } else {
      // When we get a ShadowRoot the logical tree is going to be disconnected
      // so we do a manual tree traversal
      return findElements(this, index, result, p, localName, lowercase);
    }

    return filterNodeList(list, index, result);
  }

  function getElementsByTagNameNSFiltered (p, index, result, ns, localName) {
    var target = this.impl;
    var list;
    var root = getTreeScope(this).root;
    if (root instanceof scope.wrappers.ShadowRoot) {
      // We are in the shadow tree and the logical tree is
      // going to be disconnected so we do a manual tree traversal
      return findElements(this, index, result, p, ns, localName);
    } else if (target instanceof OriginalElement) {
      list = originalElementGetElementsByTagNameNS.call(target, ns, localName);
    } else if (target instanceof OriginalDocument) {
      list = originalDocumentGetElementsByTagNameNS.call(target, ns, localName);
    } else {
      // When we get a ShadowRoot the logical tree is going to be disconnected
      // so we do a manual tree traversal
      return findElements(this, index, result, p, ns, localName);
    }

    return filterNodeList(list, index, result);
  }

  var GetElementsByInterface = {
    getElementsByTagName: function(localName) {
      var result = new HTMLCollection();
      var match = localName === '*' ? matchesEveryThing : matchesTagName;

      result.length = getElementsByTagNameFiltered.call(this,
          match,
          0,
          result,
          localName,
          localName.toLowerCase());

      return result;
    },

    getElementsByClassName: function(className) {
      // TODO(arv): Check className?
      return this.querySelectorAll('.' + className);
    },

    getElementsByTagNameNS: function(ns, localName) {
      var result = new HTMLCollection();
      var match = null;

      if (ns === '*') {
        match = localName === '*' ? matchesEveryThing : matchesLocalNameOnly;
      } else {
        match = localName === '*' ? matchesNameSpace : matchesLocalNameNS;
      }

      result.length = getElementsByTagNameNSFiltered.call(this,
          match,
          0,
          result,
          ns || null,
          localName);

      return result;
    }
  };

  scope.GetElementsByInterface = GetElementsByInterface;
  scope.SelectorsInterface = SelectorsInterface;

})(window.ShadowDOMPolyfill);
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express'),
    Buffer = require('buffer').Buffer;

module.exports = {
    'test #send()': function(assert){
        var app = express.createServer();

        app.get('/html', function(req, res){
            res.send('
test
', { 'Content-Language': 'en' });
        });

        app.get('/json', function(req, res){
            res.header('X-Foo', 'bar');
            res.send({ foo: 'bar' }, { 'X-Foo': 'baz' }, 201);
        });

        app.get('/text', function(req, res){
            res.header('X-Foo', 'bar');
            res.contentType('.txt');
            res.send('wahoo');
        });

        app.get('/status', function(req, res){
            res.send(404);
        });

        app.get('/error', function(req, res){
            res.send('Oh shit!', { 'Content-Type': 'text/plain' }, 500);
        });

        app.get('/buffer', function(req, res){
            res.send(new Buffer('wahoo!'));
        });

        app.get('/noargs', function(req, res, next){
            res.send();
        });

        assert.response(app,
            { url: '/html' },
            { body: '
test
', headers: { 'Content-Language': 'en', 'Content-Type': 'text/html; charset=utf-8' }});
        assert.response(app,
            { url: '/json' },
            { body: '{"foo":"bar"}', status: 201, headers: { 'Content-Type': 'application/json', 'X-Foo': 'baz' }});
        assert.response(app,
            { url: '/text' },
            { body: 'wahoo', headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Foo': 'bar' }});
        assert.response(app,
            { url: '/status' },
            { body: 'Not Found', status: 404, headers: { 'Content-Type': 'text/plain; charset=utf-8' }});
        assert.response(app,
            { url: '/error' },
            { body: 'Oh shit!', status: 500, headers: { 'Content-Type': 'text/plain' }});
        assert.response(app,
            { url: '/buffer' },
            { body: 'wahoo!', headers: { 'Content-Type': 'application/octet-stream' }});
        assert.response(app,
            { url: '/noargs' },
            { status: 204 }, function(res){
                assert.equal(undefined, res.headers['content-type']);
                assert.equal(undefined, res.headers['content-length']);
            });
    },

    'test #contentType()': function(assert){
        var app = express.createServer();

        app.get('/html', function(req, res){
            res.contentType('index.html');
            res.writeHead(200, res.headers);
            res.end('
yay
');
        });

        assert.response(app,
            { url: '/html' },
            { body: '
yay
', headers: { 'Content-Type': 'text/html; charset=utf-8' }});
    },

    'test #attachment()': function(assert){
        var app = express.createServer();

        app.get('/style.css', function(req, res){
            res.attachment();
            res.send('some stylezzz');
        });

        app.get('/*', function(req, res){
            res.attachment(req.params[0]);
            res.send('whatever');
        });

        assert.response(app,
            { url: '/javascripts/jquery.js' },
            { body: 'whatever', headers: { 'Content-Disposition': 'attachment; filename="jquery.js"' }});
        assert.response(app,
            { url: '/style.css' },
            { body: 'some stylezzz', headers: { 'Content-Disposition': 'attachment' }});
    },

    'test #redirect()': function(assert){
        var app = express.createServer(),
            app2 = express.createServer();

        app2.set('home', '/blog');

        app2.redirect('google', 'http://google.com');

        app2.redirect('blog', function(req, res){
            return req.params.id
                ? '/user/' + req.params.id + '/blog'
                : null;
        });

        app.get('/', function(req, res){
            res.redirect('http://google.com', 301);
        });

        app.get('/back', function(req, res){
            res.redirect('back');
        });

        app.get('/home', function(req, res){
            res.redirect('home');
        });

        app2.get('/', function(req, res){
            res.redirect('http://google.com', 301);
        });

        app2.get('/back', function(req, res){
            res.redirect('back');
        });

        app2.get('/home', function(req, res){
            res.redirect('home');
        });

        app2.get('/google', function(req, res){
            res.redirect('google');
        });

        app2.get('/user/:id', function(req, res){
            res.header('X-Foo', 'bar');
            res.redirect('blog');
        });

        assert.response(app,
            { url: '/' },
            { body: 'Redirecting to http://google.com', status: 301, headers: { Location: 'http://google.com' }});
        assert.response(app,
            { url: '/back' },
            { body: 'Redirecting to /', status: 302, headers: { Location: '/', 'Content-Type': 'text/plain' }});
        assert.response(app,
            { url: '/back', headers: { Referer: '/foo' }},
            { body: 'Redirecting to /foo', status: 302, headers: { Location: '/foo' }});
        assert.response(app,
            { url: '/back', headers: { Referrer: '/foo' }},
            { body: 'Redirecting to /foo', status: 302, headers: { Location: '/foo' }});
        assert.response(app,
            { url: '/home' },
            { body: 'Redirecting to /', status: 302, headers: { Location: '/' }});

        assert.response(app2,
            { url: '/' },
            { body: 'Redirecting to http://google.com', status: 301, headers: { Location: 'http://google.com' }});
        assert.response(app2,
            { url: '/back' },
            { body: 'Redirecting to /blog', status: 302, headers: { Location: '/blog' }});
        assert.response(app2,
            { url: '/home' },
            { body: 'Redirecting to /blog', status: 302, headers: { Location: '/blog' }});
        assert.response(app2,
            { url: '/google' },
            { body: 'Redirecting to http://google.com', headers: { Location: 'http://google.com' }});
        assert.response(app2,
            { url: '/user/12' },
            { body: 'Redirecting to /user/12/blog', headers: { Location: '/user/12/blog', 'X-Foo': 'bar' }});
    },

    'test #sendfile()': function(assert){
        var app = express.createServer();

        app.get('/*', function(req, res, next){
            var file = req.params[0],
                filePath = __dirname + '/fixtures/' + file;
            res.sendfile(filePath, function(err, path){
                assert.equal(path, filePath);
                if (err) next(err);
            });
        });

        app.use(express.errorHandler());

        assert.response(app,
            { url: '/user.json' },
            { body: '{"name":"tj"}', status: 200, headers: { 'Content-Type': 'application/json' }});
        assert.response(app,
            { url: '/hello.haml' },
            { body: '%p Hello World', status: 200, headers: { 'Content-Type': 'application/octet-stream' }});
        assert.response(app,
            { url: '/doesNotExist' },
            { body: 'Internal Server Error', status: 500 });
        assert.response(app,
            { url: '/partials' },
            { body: 'Internal Server Error', status: 500 });
    },

    'test #download()': function(assert){
        var app = express.createServer();

        app.get('/json', function(req, res, next){
            var filePath = __dirname + '/fixtures/user.json';
            res.download(filePath, 'account.json', function(err, path){
                assert.equal(filePath, path);
            });
        });

        app.get('/*', function(req, res, next){
            res.download(__dirname + '/fixtures/' + req.params[0]);
        });

        assert.response(app,
            { url: '/user.json' },
            { body: '{"name":"tj"}', status: 200, headers: {
                'Content-Type': 'application/json',
                'Content-Disposition': 'attachment; filename="user.json"'
            }});

        assert.response(app,
            { url: '/json' },
            { body: '{"name":"tj"}', status: 200, headers: {
                'Content-Type': 'application/json',
                'Content-Disposition': 'attachment; filename="account.json"'
            }});
    },

    'test #cookie()': function(assert){
        var app = express.createServer();

        app.get('/', function(req, res){
            res.cookie('rememberme', 'yes', { expires: new Date(1), httpOnly: true });
            res.redirect('/');
        });

        assert.response(app,
            { url: '/' },
            function(res){
                assert.length(res.headers['set-cookie'], 1);
                assert.length(
                    'rememberme=yes; expires=Thu, 01 Jan 1970 00:00:00 GMT; httpOnly',
                    res.headers['set-cookie'][0]);
            });
    }
};<commit_msg>Fixed res.cookie() test<commit_after>
/**
 * Module dependencies.
 */

var express = require('express'),
    Buffer = require('buffer').Buffer;

module.exports = {
    'test #send()': function(assert){
        var app = express.createServer();

        app.get('/html', function(req, res){
            res.send('
test
', { 'Content-Language': 'en' });
        });

        app.get('/json', function(req, res){
            res.header('X-Foo', 'bar');
            res.send({ foo: 'bar' }, { 'X-Foo': 'baz' }, 201);
        });

        app.get('/text', function(req, res){
            res.header('X-Foo', 'bar');
            res.contentType('.txt');
            res.send('wahoo');
        });

        app.get('/status', function(req, res){
            res.send(404);
        });

        app.get('/error', function(req, res){
            res.send('Oh shit!', { 'Content-Type': 'text/plain' }, 500);
        });

        app.get('/buffer', function(req, res){
            res.send(new Buffer('wahoo!'));
        });

        app.get('/noargs', function(req, res, next){
            res.send();
        });

        assert.response(app,
            { url: '/html' },
            { body: '
test
', headers: { 'Content-Language': 'en', 'Content-Type': 'text/html; charset=utf-8' }});
        assert.response(app,
            { url: '/json' },
            { body: '{"foo":"bar"}', status: 201, headers: { 'Content-Type': 'application/json', 'X-Foo': 'baz' }});
        assert.response(app,
            { url: '/text' },
            { body: 'wahoo', headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Foo': 'bar' }});
        assert.response(app,
            { url: '/status' },
            { body: 'Not Found', status: 404, headers: { 'Content-Type': 'text/plain; charset=utf-8' }});
        assert.response(app,
            { url: '/error' },
            { body: 'Oh shit!', status: 500, headers: { 'Content-Type': 'text/plain' }});
        assert.response(app,
            { url: '/buffer' },
            { body: 'wahoo!', headers: { 'Content-Type': 'application/octet-stream' }});
        assert.response(app,
            { url: '/noargs' },
            { status: 204 }, function(res){
                assert.equal(undefined, res.headers['content-type']);
                assert.equal(undefined, res.headers['content-length']);
            });
    },

    'test #contentType()': function(assert){
        var app = express.createServer();

        app.get('/html', function(req, res){
            res.contentType('index.html');
            res.writeHead(200, res.headers);
            res.end('
yay
');
        });

        assert.response(app,
            { url: '/html' },
            { body: '
yay
', headers: { 'Content-Type': 'text/html; charset=utf-8' }});
    },

    'test #attachment()': function(assert){
        var app = express.createServer();

        app.get('/style.css', function(req, res){
            res.attachment();
            res.send('some stylezzz');
        });

        app.get('/*', function(req, res){
            res.attachment(req.params[0]);
            res.send('whatever');
        });

        assert.response(app,
            { url: '/javascripts/jquery.js' },
            { body: 'whatever', headers: { 'Content-Disposition': 'attachment; filename="jquery.js"' }});
        assert.response(app,
            { url: '/style.css' },
            { body: 'some stylezzz', headers: { 'Content-Disposition': 'attachment' }});
    },

    'test #redirect()': function(assert){
        var app = express.createServer(),
            app2 = express.createServer();

        app2.set('home', '/blog');

        app2.redirect('google', 'http://google.com');

        app2.redirect('blog', function(req, res){
            return req.params.id
                ? '/user/' + req.params.id + '/blog'
                : null;
        });

        app.get('/', function(req, res){
            res.redirect('http://google.com', 301);
        });

        app.get('/back', function(req, res){
            res.redirect('back');
        });

        app.get('/home', function(req, res){
            res.redirect('home');
        });

        app2.get('/', function(req, res){
            res.redirect('http://google.com', 301);
        });

        app2.get('/back', function(req, res){
            res.redirect('back');
        });

        app2.get('/home', function(req, res){
            res.redirect('home');
        });

        app2.get('/google', function(req, res){
            res.redirect('google');
        });

        app2.get('/user/:id', function(req, res){
            res.header('X-Foo', 'bar');
            res.redirect('blog');
        });

        assert.response(app,
            { url: '/' },
            { body: 'Redirecting to http://google.com', status: 301, headers: { Location: 'http://google.com' }});
        assert.response(app,
            { url: '/back' },
            { body: 'Redirecting to /', status: 302, headers: { Location: '/', 'Content-Type': 'text/plain' }});
        assert.response(app,
            { url: '/back', headers: { Referer: '/foo' }},
            { body: 'Redirecting to /foo', status: 302, headers: { Location: '/foo' }});
        assert.response(app,
            { url: '/back', headers: { Referrer: '/foo' }},
            { body: 'Redirecting to /foo', status: 302, headers: { Location: '/foo' }});
        assert.response(app,
            { url: '/home' },
            { body: 'Redirecting to /', status: 302, headers: { Location: '/' }});

        assert.response(app2,
            { url: '/' },
            { body: 'Redirecting to http://google.com', status: 301, headers: { Location: 'http://google.com' }});
        assert.response(app2,
            { url: '/back' },
            { body: 'Redirecting to /blog', status: 302, headers: { Location: '/blog' }});
        assert.response(app2,
            { url: '/home' },
            { body: 'Redirecting to /blog', status: 302, headers: { Location: '/blog' }});
        assert.response(app2,
            { url: '/google' },
            { body: 'Redirecting to http://google.com', headers: { Location: 'http://google.com' }});
        assert.response(app2,
            { url: '/user/12' },
            { body: 'Redirecting to /user/12/blog', headers: { Location: '/user/12/blog', 'X-Foo': 'bar' }});
    },

    'test #sendfile()': function(assert){
        var app = express.createServer();

        app.get('/*', function(req, res, next){
            var file = req.params[0],
                filePath = __dirname + '/fixtures/' + file;
            res.sendfile(filePath, function(err, path){
                assert.equal(path, filePath);
                if (err) next(err);
            });
        });

        app.use(express.errorHandler());

        assert.response(app,
            { url: '/user.json' },
            { body: '{"name":"tj"}', status: 200, headers: { 'Content-Type': 'application/json' }});
        assert.response(app,
            { url: '/hello.haml' },
            { body: '%p Hello World', status: 200, headers: { 'Content-Type': 'application/octet-stream' }});
        assert.response(app,
            { url: '/doesNotExist' },
            { body: 'Internal Server Error', status: 500 });
        assert.response(app,
            { url: '/partials' },
            { body: 'Internal Server Error', status: 500 });
    },

    'test #download()': function(assert){
        var app = express.createServer();

        app.get('/json', function(req, res, next){
            var filePath = __dirname + '/fixtures/user.json';
            res.download(filePath, 'account.json', function(err, path){
                assert.equal(filePath, path);
            });
        });

        app.get('/*', function(req, res, next){
            res.download(__dirname + '/fixtures/' + req.params[0]);
        });

        assert.response(app,
            { url: '/user.json' },
            { body: '{"name":"tj"}', status: 200, headers: {
                'Content-Type': 'application/json',
                'Content-Disposition': 'attachment; filename="user.json"'
            }});

        assert.response(app,
            { url: '/json' },
            { body: '{"name":"tj"}', status: 200, headers: {
                'Content-Type': 'application/json',
                'Content-Disposition': 'attachment; filename="account.json"'
            }});
    },

    'test #cookie()': function(assert){
        var app = express.createServer();

        app.get('/', function(req, res){
            res.cookie('rememberme', 'yes', { expires: new Date(1), httpOnly: true });
            res.redirect('/');
        });

        assert.response(app,
            { url: '/' },
            function(res){
                //assert.length(res.headers['set-cookie'], 1);
                assert.equal(
                    'rememberme=yes; expires=Thu, 01 Jan 1970 00:00:00 GMT; httpOnly',
                    res.headers['set-cookie'][0]);
            });
    }
};<|endoftext|>


<commit_before>
require('./helpers').allDrivers("Rollback transaction", {autoEnd: false}, function (conn, t) {
	t.plan(2)

	conn.query("CREATE TABLE transaction_test (a int)", function (err) {
		if (err) {
			conn.end()
			throw err
		}

		t.on('end', function dropTable () {
			conn.query('DROP TABLE transaction_test', function (err) {
				conn.end()
				if (err) t.emit('error', err)
			})
		})

		var tx = conn.begin()
		tx.on('error', function (err) { t.emit(err) })
		tx.query('INSERT INTO transaction_test (a) VALUES (1)')
		tx.query('SELECT * FROM transaction_test', function (err, res) {
			if (err) throw err
			t.deepEqual(res.rows, [{a: 1}])
			tx.rollback(function (err) {
				if (err) throw err
				conn.query('SELECT * FROM transaction_test', function (err, res) {
					if (err) throw err
					t.deepEqual(res.rows, [])
				})
			})
		})
	})
})
<commit_msg>remove some unnecessary nesting from test/rollback<commit_after>
require('./helpers').allDrivers("Rollback transaction", {autoEnd: false}, function (conn, t) {
	t.plan(2)

	conn.query("DROP TABLE transaction_test", function (err) {})
	conn.query("CREATE TABLE transaction_test (a int)")
	t.on('end', function dropTable () {
		conn.query('DROP TABLE transaction_test', function (err) {
			conn.end()
			if (err) t.emit('error', err)
		})
	})

	var tx = conn.begin()

	tx.query('INSERT INTO transaction_test (a) VALUES (1)')
	tx.query('SELECT * FROM transaction_test', function (err, res) {
		if (err) throw err
		t.deepEqual(res.rows, [{a: 1}])
		tx.rollback(function (err) {
			if (err) throw err
			conn.query('SELECT * FROM transaction_test', function (err, res) {
				if (err) throw err
				t.deepEqual(res.rows, [])
			})
		})
	})
})
<|endoftext|>


<commit_before>var assert = chai.assert;
var expect = chai.expect;
var sample_valid_contact = {
	"name":"Jon Snow",
	"age":15,
	"occupation":"Lord Commander of the Wall",
	"email":"jon@nightswatch.wl"
}

describe("The Address Book App",function(){

	beforeEach(function(done){

			module('AddressBook');
			module('ngMock');

			inject(function(_contactService_,$injector){
				contactService = _contactService_;
				$httpBackend = $injector.get('$httpBackend');

				/* Mocking data is fast and efficient, but can leave you blind to errors in your real server interactions */
				$httpBackend.whenGET('http://localhost:3000/contacts').respond(200,[sample_valid_contact]);
				done();

		})
	});
	describe("The Contact Service",function(){

		beforeEach(function(){
				inject(function($injector){
					contactService = $injector.get("contactService");
					$httpBackend = $injector.get('$httpBackend');
				})

		});

		describe('getting contacts',function(){
			it('should return an array of contacts asynchronously',function(done){
				$httpBackend.expectGET('http://localhost:3000/contacts');

				contactService.getContacts()
				.then(function(contacts){
					expect(contacts).to.be.an('array');
					done();
				});
				$httpBackend.flush();
			});
		});

		describe('adding contacts',function(){

			it ("should add a new contact if it is valid",function(done){
				$httpBackend.expectPOST('http://localhost:3000/contacts/new')
					.respond(201,{});

				contactService.addContact(sample_valid_contact)
					.then(function(){
						done();
					});
					$httpBackend.flush();
			});

			it ("shoud return an err if the method didn't work",function(done){
				var invalid_contact = {name:"Ramsay"};
				$httpBackend.expectPOST('http://localhost:3000/contacts/new')
					.respond(409,"Error");

				contactService.addContact(invalid_contact)
					.then(function(){
						throw new Error();
					},
					function(response){
						done();
					});
				$httpBackend.flush();
			});
		})
	});

	describe("The proper filter...",function(){
		/* how can you possibly test this? */

		beforeEach(function(){
			inject(function($injector){
				proper = $injector.get("$filter")("proper");
			});
		})

		it("should take any string and return that string in proper case (first letter of each word uppercase)",function(){
			expect(proper('danaerys')).to.equal("Danaerys");
			expect(proper('sour alyn')).to.equal("Sour Alyn");
		});

		it("should coerce a number into a string",function(){
				expect(proper(5323)).to.equal('5323');
				expect(proper(1236910)).to.equal('1236910');
				expect(proper(0x0eabbe)).to.equal('961470'); // no way that is so cool
		})

		it("should throw an error on any other value",function(){
			/* this is how to test for an error */;
			assert.throws(function(){ 	proper(undefined);  })
			assert.throws(function(){ 	proper({});  })
			assert.throws(function(){ 	proper([]);  })
		})
	});
	describe("The Avatar directive...",function(){

		it("should display a single letter which is the first letter of the contact's name.");
		it("should display a question mark if there is no associated contact.");
	})

	describe("The Contact List Controller",function(){
		beforeEach(function(){

			inject(function($rootScope,$injector){
				/* Create a new scope that we can assign as the controllers scope. By keeping a reference to it, we can run tests. */
				$scope = $rootScope.$new();
				contactService = $injector.get("contactService");
				$controller = $injector.get("$controller");
			})
		});

		it('should get a copy of the contact list on startup and store it in $scope',function(done){
			/* Create a new instance of the controller with the $controller service */
			contactListController = $controller("ContactList",{$scope:$scope,contactService:contactService});
			contactService.getContacts()
				.then(function(contacts){
					expect($scope.contacts).to.be.an('array');
					expect($scope.contacts).to.deep.equal(contacts);
					done();
				});

			$httpBackend.flush();
		});
	})
})<commit_msg>WIP: Got the directive test working!<commit_after>var assert = chai.assert;
var expect = chai.expect;
var sample_valid_contact = {
	"name":"Jon Snow",
	"age":15,
	"occupation":"Lord Commander of the Wall",
	"email":"jon@nightswatch.wl"
}

describe("The Address Book App",function(){

	beforeEach(function(done){

			module('AddressBook');
			module('ngMock');

			inject(function(_contactService_,$injector){
				contactService = _contactService_;
				$httpBackend = $injector.get('$httpBackend');

				/* Mocking data is fast and efficient, but can leave you blind to errors in your real server interactions */
				$httpBackend.whenGET('http://localhost:3000/contacts').respond(200,[sample_valid_contact]);
				done();

		})
	});
	describe("The Contact Service",function(){

		beforeEach(function(){
				inject(function($injector){
					contactService = $injector.get("contactService");
					$httpBackend = $injector.get('$httpBackend');
				})

		});

		describe('getting contacts',function(){
			it('should return an array of contacts asynchronously',function(done){
				$httpBackend.expectGET('http://localhost:3000/contacts');

				contactService.getContacts()
				.then(function(contacts){
					expect(contacts).to.be.an('array');
					done();
				});
				$httpBackend.flush();
			});
		});

		describe('adding contacts',function(){

			it ("should add a new contact if it is valid",function(done){
				$httpBackend.expectPOST('http://localhost:3000/contacts/new')
					.respond(201,{});

				contactService.addContact(sample_valid_contact)
					.then(function(){
						done();
					});
					$httpBackend.flush();
			});

			it ("shoud return an err if the method didn't work",function(done){
				var invalid_contact = {name:"Ramsay"};
				$httpBackend.expectPOST('http://localhost:3000/contacts/new')
					.respond(409,"Error");

				contactService.addContact(invalid_contact)
					.then(function(){
						throw new Error();
					},
					function(response){
						done();
					});
				$httpBackend.flush();
			});
		})
	});

	describe("The proper filter...",function(){
		/* how can you possibly test this? */

		beforeEach(function(){
			inject(function($injector){
				proper = $injector.get("$filter")("proper");
			});
		})

		it("should take any string and return that string in proper case (first letter of each word uppercase)",function(){
			expect(proper('danaerys')).to.equal("Danaerys");
			expect(proper('sour alyn')).to.equal("Sour Alyn");
		});

		it("should coerce a number into a string",function(){
				expect(proper(5323)).to.equal('5323');
				expect(proper(1236910)).to.equal('1236910');
				expect(proper(0x0eabbe)).to.equal('961470'); // no way that is so cool
		})

		it("should throw an error on any other value",function(){
			/* this is how to test for an error */;
			assert.throws(function(){ 	proper(undefined);  })
			assert.throws(function(){ 	proper({});  })
			assert.throws(function(){ 	proper([]);  })
		})
	});
	describe("The Avatar directive...",function(){
		beforeEach(function(){

		})
		it("should display a single letter which is the first letter of the contact's name.",function(){
			inject(function($rootScope,$compile){
				scope = $rootScope;
				scope.contact = {name:"Jon Arryn"};
				var element = $compile('<avatar name=contact.name/>')(scope)
				scope.$digest();
				expect(element.text()).to.equal("J");

//				var avatar = angular.element('<avatar name=contact.name/>');
//				var g = $compile(avatar,scope);
//				scope.$digest();
//				content = avatar.find('span');

//				debugger;
			})
		});
		it("should display a question mark if there is no associated contact.");
	})

	describe("The Contact List Controller",function(){
		beforeEach(function(){

			inject(function($rootScope,$injector){
				/* Create a new scope that we can assign as the controllers scope. By keeping a reference to it, we can run tests. */
				$scope = $rootScope.$new();
				contactService = $injector.get("contactService");
				$controller = $injector.get("$controller");
			})
		});

		it('should get a copy of the contact list on startup and store it in $scope',function(done){
			/* Create a new instance of the controller with the $controller service */
			contactListController = $controller("ContactList",{$scope:$scope,contactService:contactService});
			contactService.getContacts()
				.then(function(contacts){
					expect($scope.contacts).to.be.an('array');
					expect($scope.contacts).to.deep.equal(contacts);
					done();
				});

			$httpBackend.flush();
		});
	})
})<|endoftext|>


<commit_before>var s = require('../lib/strummer');

describe('strummer', function() {
  it('throws error when passing a empty definition', function() {
    (function() {
      s();
    }).should.throw();
  });

  it('passes null values to the matchers', function() {
    var schema = s({
      name: new s.string()
    });
    schema.match({
      name: null
    }).should.eql([
      {
        path: 'name',
        value: null,
        message: 'should be a string'
      }
    ]);
  });

  it('can handle a null obj', function() {
    var schema = s({
      name: new s.string()
    });
    schema.match('path', null).should.eql([
      {
        path: 'path',
        value: null,
        message: 'should be an object'
      }
    ]);
  });

  it('can handle an undefined obj', function() {
    var schema = s({
      name: new s.string()
    });
    schema.match('path', undefined).should.eql([
      {
        path: 'path',
        value: undefined,
        message: 'should be an object'
      }
    ]);
  });

  it('can handle null values', function() {
    var schema = s({
      name: new s.string()
    });
    schema.match('', {name: null}).should.eql([
      {
        path: 'name',
        value: null,
        message: 'should be a string'
      }
    ]);
  });

  it('can handle undefined values', function() {
    var schema = s({
      name: new s.string()
    });
    schema.match('', {name: undefined}).should.eql([
      {
        path: 'name',
        value: undefined,
        message: 'should be a string'
      }
    ]);
  });

  it('can specify a matcher is optional', function() {
    var schema = s({
      name: new s.optional(new s.string())
    });
    schema.match({
      name: null
    }).should.eql([]);
  });

  it('passes options to the matchers', function() {
    var schema = s({
      val: new s.number({min: 10})
    });
    schema.match({
      val: 5
    }).should.eql([{
      path: 'val',
      value: 5,
      message: 'should be a number >= 10'
    }]);
  });

  it('can define custom leaf matchers', function() {
    var greeting = s.createMatcher({
      initialize: function() {},
      match: function(path, val) {
        if (/hello [a-z]+/.test(val) === false) {
          return 'should be a greeting';
        }
      }
    });

    var schema = s({
      hello: new greeting()
    });
    schema.match({
      hello: 'bye'
    }).should.eql([
      {
        path: 'hello',
        value: 'bye',
        message: 'should be a greeting'
      }
    ]);
  });

  it('can assert on a matcher being successful', function() {
    var person = {
      name: 3,
      age: 'bob'
    };
    (function() {
      s.assert(person, {
        name: 'string',
        age: 'number'
      });
    }).should.throw(/name should be a string \(was 3\)/)
             .throw(/age should be a number \(was 'bob'\)/);
  });

  it('should stringify values when assertions fail', function() {
    var person = {
      name: { text: 'bob' }
    };
    (function() {
      s.assert(person, {
        name: 'string'
      });
    }).should.throw(/name should be a string \(was { text: 'bob' }\)/);
  });

  it('throws error when match is not implemented', function() {
    (function() {
      s.createMatcher({});
    }).should.throw(/match is not implemented/);
  });

  it('supports optional initialize method', function() {
    (function() {
      var m = s.createMatcher({
        match: function() {
          return;
       }
      });
      var schema = m();
      schema.match();
    }).should.not.throw();
  });

  it('supports initialize with name', function() {
    var m = s('User', {
      foo: 'string',
      bar: 'number'
    });

    var data = {
      foo: 123,
      bar: 'str'
    };

    m.name.should.equal('User');
    m.match(data).should.have.lengthOf(2);
  });
});
<commit_msg>Fix coverage<commit_after>var s = require('../lib/strummer');

describe('strummer', function() {
  it('throws error when passing a empty definition', function() {
    (function() {
      s();
    }).should.throw();
  });

  it('passes null values to the matchers', function() {
    var schema = s({
      name: new s.string()
    });
    schema.match({
      name: null
    }).should.eql([
      {
        path: 'name',
        value: null,
        message: 'should be a string'
      }
    ]);
  });

  it('can handle a null obj', function() {
    var schema = s({
      name: new s.string()
    });
    schema.match('path', null).should.eql([
      {
        path: 'path',
        value: null,
        message: 'should be an object'
      }
    ]);
  });

  it('can handle an undefined obj', function() {
    var schema = s({
      name: new s.string()
    });
    schema.match('path', undefined).should.eql([
      {
        path: 'path',
        value: undefined,
        message: 'should be an object'
      }
    ]);
  });

  it('can handle null values', function() {
    var schema = s({
      name: new s.string()
    });
    schema.match('', {name: null}).should.eql([
      {
        path: 'name',
        value: null,
        message: 'should be a string'
      }
    ]);
  });

  it('can handle undefined values', function() {
    var schema = s({
      name: new s.string()
    });
    schema.match('', {name: undefined}).should.eql([
      {
        path: 'name',
        value: undefined,
        message: 'should be a string'
      }
    ]);
  });

  it('can specify a matcher is optional', function() {
    var schema = s({
      name: new s.optional(new s.string())
    });
    schema.match({
      name: null
    }).should.eql([]);
  });

  it('passes options to the matchers', function() {
    var schema = s({
      val: new s.number({min: 10})
    });
    schema.match({
      val: 5
    }).should.eql([{
      path: 'val',
      value: 5,
      message: 'should be a number >= 10'
    }]);
  });

  it('can define custom leaf matchers', function() {
    var greeting = s.createMatcher({
      initialize: function() {},
      match: function(path, val) {
        if (/hello [a-z]+/.test(val) === false) {
          return 'should be a greeting';
        }
      }
    });

    var schema = s({
      hello: new greeting()
    });
    schema.match({
      hello: 'bye'
    }).should.eql([
      {
        path: 'hello',
        value: 'bye',
        message: 'should be a greeting'
      }
    ]);
  });

  it('can assert on a matcher being successful', function() {
    var person = {
      name: 'bob',
      age: 3
    };

    s.assert(person, {
      name: 'string',
      age: 'number'
    });
  });

  it('can assert on a matcher being unsuccessful', function() {
    var person = {
      name: 3,
      age: 'bob'
    };
    (function() {
      s.assert(person, {
        name: 'string',
        age: 'number'
      });
    }).should.throw(/name should be a string \(was 3\)/)
             .throw(/age should be a number \(was 'bob'\)/);
  });

  it('should stringify values when assertions fail', function() {
    var person = {
      name: { text: 'bob' }
    };
    (function() {
      s.assert(person, {
        name: 'string'
      });
    }).should.throw(/name should be a string \(was { text: 'bob' }\)/);
  });

  it('throws error when match is not implemented', function() {
    (function() {
      s.createMatcher({});
    }).should.throw(/match is not implemented/);
  });

  it('supports optional initialize method', function() {
    (function() {
      var m = s.createMatcher({
        match: function() {
          return;
       }
      });
      var schema = m();
      schema.match();
    }).should.not.throw();
  });

  it('supports initialize with name', function() {
    var m = s('User', {
      foo: 'string',
      bar: 'number'
    });

    var data = {
      foo: 123,
      bar: 'str'
    };

    m.name.should.equal('User');
    m.match(data).should.have.lengthOf(2);
  });
});
<|endoftext|>


<commit_before>QUnit.test("filter - map - toArray", function (assert) {
    var data = [1, 2, 3, 4];

    var result =
        Stream(data)
            .filter(function (num) {
                return num % 2 === 1;
            })
            .map(function (num) {
                return "obj" + num;
            })
            .toArray();

    assert.equal(result.length, 2);
    assert.equal(result[0], 'obj1');
    assert.equal(result[1], 'obj3');

    // assert original data is untouched
    assert.equal(data.length, 4);
    assert.equal(data[0], 1);
    assert.equal(data[1], 2);
    assert.equal(data[2], 3);
    assert.equal(data[3], 4);
});

QUnit.test("filter - map - toArray (correct invocation)", function (assert) {
    var numFilter = 0;
    var numMap = 0;

    var data = [1, 2, 3, 4];

    var result =
        Stream(data)
            .filter(function (num) {
                numFilter++;
                return num % 2 === 1;
            })
            .map(function (num) {
                numMap++;
                return "obj" + num;
            })
            .toArray();

    assert.equal(result.length, 2);
    assert.equal(result[0], 'obj1');
    assert.equal(result[1], 'obj3');
    assert.equal(numFilter, 4);
    assert.equal(numMap, 2);
});<commit_msg>Tests<commit_after>QUnit.test("filter - map - toArray", function (assert) {
    var data = [1, 2, 3, 4];

    var result =
        Stream(data)
            .filter(function (num) {
                return num % 2 === 1;
            })
            .map(function (num) {
                return "obj" + num;
            })
            .toArray();

    assert.equal(result.length, 2);
    assert.equal(result[0], 'obj1');
    assert.equal(result[1], 'obj3');

    // assert original data is untouched
    assert.equal(data.length, 4);
    assert.equal(data[0], 1);
    assert.equal(data[1], 2);
    assert.equal(data[2], 3);
    assert.equal(data[3], 4);
});

QUnit.test("filter - map - toArray (correct invocation)", function (assert) {
    var numFilter = 0;
    var numMap = 0;

    var data = [1, 2, 3, 4];

    var result =
        Stream(data)
            .filter(function (num) {
                numFilter++;
                return num % 2 === 1;
            })
            .map(function (num) {
                numMap++;
                return "obj" + num;
            })
            .toArray();

    assert.equal(result.length, 2);
    assert.equal(result[0], 'obj1');
    assert.equal(result[1], 'obj3');
    assert.equal(numFilter, 4);
    assert.equal(numMap, 2);
});

var createParents = function (numParents, numChildren) {
    return Stream
        .range(0, numParents)
        .map(function (num) {
            return {
                parentId: num,
                type: 'parent',
                children: []
            };
        })
        .peek(function (parent) {
            parent.children = Stream
                .range(0, numChildren)
                .map(function (num) {
                    return {
                        childId: num,
                        type: 'child',
                        parent: parent
                    };
                })
                .toArray();
        })
        .toArray();
};

QUnit.test("parent / children 1", function (assert) {
    var parents = createParents(5, 3);

    assert.equal(parents.length, 5);

    for (var i = 0; i < parents.length; i++) {
        var parent = parents[i];
        assert.equal(parent.parentId, i);
        assert.equal(parent.type, 'parent');
        assert.equal(parent.children.length, 3);
        for (var j = 0; j < parent.children.length; j++) {
            var child = parent.children[j];
            assert.equal(child.childId, j);
            assert.equal(child.type, 'child');
            assert.equal(child.parent, parent);
        }
    }
});

QUnit.test("parent / children 2", function (assert) {
    var parents = createParents(5, 3);

    var children = Stream(parents)
        .filter(function (p) {
            return p.parentId > 2;
        })
        .flatMap(function (p) {
            return p.children;
        })
        .toArray();

    assert.equal(children.length, 6);
    assert.equal(children[0].childId, 0);
    assert.equal(children[1].childId, 1);
    assert.equal(children[2].childId, 2);
    assert.equal(children[3].childId, 0);
    assert.equal(children[4].childId, 1);
    assert.equal(children[5].childId, 2);
});<|endoftext|>


<commit_before>/*global describe, beforeEach, it*/
'use strict';

var path    = require('path');
var helpers = require('yeoman-generator').test;

describe('verb', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:app', ['../../app']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = [
      'docs/README.tmpl.md',
      'package.json',
//      '.verbrc.yml',
      '.jshintrc',
      '.gitignore',
      '.gitattributes',
      'LICENSE-MIT',
    ];

    helpers.mockPrompt(this.app, {
      projectname: 'verb-project',
      projectdesc: 'The most interesting project in the world > Verb',
      username: 'jonschlinkert',
      authorname: 'Jon Schlinkert',
      authorurl: 'https://github.com/jonschlinkert',
    });

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

/**
 * Config
 */

describe('verb:config', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:config', ['../../config']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['.verbrc.yml'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

describe('verb:config verbfile', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:config', ['../../config'], ['verbfile']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['verbfile.js'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

describe('verb:config verbrc', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:config', ['../../config'], ['verbrc']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['.verbrc.yml'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

/**
 * Data
 */

describe('verb:data', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:data', ['../../data'], ['changelog']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['CHANGELOG'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

/**
 * doc
 */

describe('verb:doc', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:doc', ['../../doc'], ['footer']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['docs/footer.md'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

describe('verb:readme', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:readme', ['../../readme']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['docs/README.tmpl.md'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

describe('verb:vf', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:vf', ['../../vf']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['verbfile.js'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});
<commit_msg>add tests<commit_after>/*global describe, beforeEach, it*/
'use strict';

var path    = require('path');
var helpers = require('yeoman-generator').test;

describe('verb', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:app', ['../../app']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = [
      'package.json',
      '.verbrc.md',
      '.jshintrc',
      '.gitignore',
      '.gitattributes',
      'LICENSE-MIT',
    ];

    helpers.mockPrompt(this.app, {
      projectname: 'verb-project',
      projectdesc: 'The most interesting project in the world > Verb',
      username:    'jonschlinkert',
      authorname:  'Jon Schlinkert',
      authorurl:   'https://github.com/jonschlinkert',
    });

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

describe('verb', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:app', ['../../app']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = [
      'docs/README.tmpl.md',
      'package.json',
      '.jshintrc',
      '.gitignore',
      '.gitattributes',
      'LICENSE-MIT',
    ];

    helpers.mockPrompt(this.app, {
      projectname: 'verb-project',
      projectdesc: 'The most interesting project in the world > Verb',
      username:    'jonschlinkert',
      authorname:  'Jon Schlinkert',
      authorurl:   'https://github.com/jonschlinkert',
    });

    this.app.options['readme'] = true;
    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

/**
 * Config
 */

describe('verb:config', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:config', ['../../config']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['.verbrc.md'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

describe('verb:config verbfile', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:config', ['../../config'], ['verbfile']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['verbfile.js'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

describe('verb:config verbrc', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:config', ['../../config'], ['verbrc']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['.verbrc.yml'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

describe('verb:config verbrc', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:config', ['../../config'], ['md']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['.verbrc.md'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

/**
 * Data
 */

describe('verb:data', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:data', ['../../data'], ['changelog']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['CHANGELOG'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

/**
 * doc
 */

describe('verb:doc', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:doc', ['../../doc'], ['footer']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['docs/footer.md'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

describe('verb:doc', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:doc', ['../../doc'], ['install']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['docs/install.md'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

describe('verb:doc', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:doc', ['../../doc'], ['install-global']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['docs/install-global.md'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

describe('verb:readme', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:readme', ['../../readme']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['docs/README.tmpl.md'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});

describe('verb:readme', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {return done(err);}

      this.app = helpers.createGenerator('verb:readme', ['../../readme'], ['readme']);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = ['docs/README.tmpl.md'];

    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});
<|endoftext|>


<commit_before>/*global describe, beforeEach, it, xit */
'use strict';
var path = require('path');
var fs = require('fs-extra');
var exec = require('child_process').exec;

var helpers = require('yeoman-generator').test;
var assert = require('yeoman-generator').assert;
var chai = require('chai');
var expect = chai.expect;

describe('emberfs generator', function () {

    var defaultOptions = {
    };

    beforeEach(function() {
        this.app = helpers
            .run(path.join(__dirname, '../generators/app'))
            .inDir(path.join(__dirname, '.tmp'), function(dir) {
                //node_modulesx
                // fs.copySync(path.join(__dirname, 'fixtures/node_modules'),
                //             path.join(dir, 'node_modules'));
                //bower_components

                // node_modules
                fs.symlinkSync(path.join(__dirname, 'fixtures/node_modules'),
                               path.join(dir, 'node_modules'), 'dir');

                fs.mkdirpSync(path.join(dir, 'app/client'));

                // bower_components
                fs.symlinkSync(path.join(__dirname, 'fixtures/bower_components'),
                               path.join(dir, 'app/client/bower_components'), 'dir');

            });
    });

    describe('running app', function() {

        describe('with default options', function() {

            it('should pass jshint', function(done) {
                this.timeout(40000);
                this.app.withPrompt(defaultOptions)
                    .on('end', function() {
                        console.log('running jshint');
                        exec('gulp jshint', function(error, stdout, stderr) {
                            if (error) { console.log('Error: ' + error); }
                            expect(stdout).to.contain('Finished \'jshint\'');
                            expect(stdout).to.not.contain('problems');

                            done();
                        });
                    });
            });

            xit('should pass all client tests', function(done) {
                this.timeout(600000);
                this.app.withPrompt(defaultOptions)
                    .on('end', function() {
                        console.log('running client side tests');
                        exec('gulp test', function(error, stdout, stderr) {
                            expect(stdout).to.match(/# tests\s*3/);
                            expect(stdout).to.match(/# pass\s*3/);
                            expect(stdout).to.match(/# fail\s*0/);
                            done();
                        });
                    });
            });
        });
    });

});
<commit_msg>updated test-creation to npm install fixtures<commit_after>/*global describe, beforeEach, it, xit */
'use strict';
var path = require('path');
var fs = require('fs-extra');
var exec = require('child_process').exec;

var helpers = require('yeoman-generator').test;
var assert = require('yeoman-generator').assert;
var chai = require('chai');
var expect = chai.expect;

describe('emberfs generator', function () {

    var defaultOptions = {
    };

    beforeEach(function() {
        this.app = helpers
            .run(path.join(__dirname, '../generators/app'))
            .inDir(path.join(__dirname, '.tmp'), function(dir) {
                //node_modulesx
                // fs.copySync(path.join(__dirname, 'fixtures/node_modules'),
                //             path.join(dir, 'node_modules'));
                //bower_components

                // node_modules
                fs.symlinkSync(path.join(__dirname, 'fixtures/node_modules'),
                               path.join(dir, 'node_modules'), 'dir');

                fs.mkdirpSync(path.join(dir, 'app/client'));

                // bower_components
                fs.symlinkSync(path.join(__dirname, 'fixtures/bower_components'),
                               path.join(dir, 'app/client/bower_components'), 'dir');

                exec('npm install & bower install', { cwd: path.join(__dirname + 'fixtures') }, function(error) {
                    console.log('running npm install & bower install on fixtures');
                    if (error) { console.log('Error: ' + error); }
                });
            });
    });

    describe('running app', function() {

        describe('with default options', function() {

            it('should pass jshint', function(done) {
                this.timeout(40000);
                this.app.withPrompt(defaultOptions)
                    .on('end', function() {
                        console.log('running jshint');
                        exec('gulp jshint', function(error, stdout, stderr) {
                            if (error) { console.log('Error: ' + error); }
                            expect(stdout).to.contain('Finished \'jshint\'');
                            expect(stdout).to.not.contain('problems');

                            done();
                        });
                    });
            });
            // pending for now, because gulp test doesn't exit properly
            xit('should pass all client tests', function(done) {
                this.timeout(600000);
                this.app.withPrompt(defaultOptions)
                    .on('end', function() {
                        console.log('running client side tests');
                        exec('gulp test', function(error, stdout, stderr) {
                            expect(stdout).to.match(/# tests\s*3/);
                            expect(stdout).to.match(/# pass\s*3/);
                            expect(stdout).to.match(/# fail\s*0/);
                            done();
                        });
                    });
            });
        });
    });

});
<|endoftext|>


<commit_before>/*global describe, beforeEach, it*/
'use strict';

var path    = require('path');
var helpers = require('yeoman-generator').test;

describe('drupaltheme generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('drupaltheme:app', [
        '../../app'
      ]);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = [
      // add files you expect to exist here.
      ['bower.json', /"name": "testing-name"/],
      ['package.json', /"name": "testing-name"/],
      '.jshintrc',
      '.editorconfig',
      'temp.info',
      'css/editor.css',
      'css/style.css',
      'js/temp.js'
    ];

    helpers.mockPrompt(this.app, {
      'themeName': 'testing-name',
      'themeDesc': 'mock theme decription',
      'drupalVersion': 'd7',
      'themeStyles': 'n',
      'features': []
    });
    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expected);
      done();
    });
  });

  it('creates expected files for SASS support', function (done) {
    var expected = [
      // add files you expect to exist here.
      'sass/_config.scss',
      'sass/editor.scss',
      'sass/style.scss'
    ];

    helpers.mockPrompt(this.app, {
      'themeName': 'testing-name',
      'themeDesc': 'mock theme decription',
      'drupalVersion': 'd7',
      'themeStyles': 's',
      'features': []
    });
    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expected);
      done();
    });
  });

  it('creates expected files for COMPASS support', function (done) {
    var expected = [
      // add files you expect to exist here.
      'config.rb'
    ];

    helpers.mockPrompt(this.app, {
      'themeName': 'testing-name',
      'themeDesc': 'mock theme decription',
      'drupalVersion': 'd7',
      'themeStyles': 'c',
      'features': []
    });
    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expected);
      done();
    });
  });
});
<commit_msg>start fixing tests<commit_after>/*global describe, beforeEach, it*/
'use strict';

var path    = require('path');
var helpers = require('yeoman-generator').test;

describe('drupaltheme generator', function () {
  beforeEach(function (done) {
    var deps = [
      '../../app',
      '../../common',
      '../../default'
    ];
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('drupaltheme:app', deps);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = [
      // add files you expect to exist here.
      ['bower.json', /"name": "testing-name"/],
      ['package.json', /"name": "testing-name"/],
      '.jshintrc',
      '.editorconfig',
      'temp.info',
      'css/editor.css',
      'css/style.css',
      'js/temp.js'
    ];

    helpers.mockPrompt(this.app, {
      'themeName': 'testing-name',
      'themeDesc': 'mock theme decription',
      'drupalVersion': 'd7',
      'themeStyles': 'n',
      'features': []
    });
    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expected);
      done();
    });
  });

  it('creates expected files for SASS support', function (done) {
    var expected = [
      // add files you expect to exist here.
      'sass/_config.scss',
      'sass/editor.scss',
      'sass/style.scss'
    ];

    helpers.mockPrompt(this.app, {
      'themeName': 'testing-name',
      'themeDesc': 'mock theme decription',
      'drupalVersion': 'd7',
      'themeStyles': 's',
      'features': []
    });
    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expected);
      done();
    });
  });

  it('creates expected files for COMPASS support', function (done) {
    var expected = [
      // add files you expect to exist here.
      'config.rb'
    ];

    helpers.mockPrompt(this.app, {
      'themeName': 'testing-name',
      'themeDesc': 'mock theme decription',
      'drupalVersion': 'd7',
      'themeStyles': 'c',
      'features': []
    });
    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expected);
      done();
    });
  });
});
<|endoftext|>