<commit_before>'use strict';

describe('angularStorage store', function() {

  beforeEach(function() {
    module('angular-storage.store');
  });

  it('should save items correctly in localStorage', inject(function(store) {
    var value = 1;
    store.set('gonto', value);
    expect(store.get('gonto')).to.equal(value);
  }));

  it('should save null items correctly in localStorage', inject(function(store) {
    store.set('gonto', null);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.equal(null);
  }));

  it('should save undefined items correctly in localStorage', inject(function(store) {
    store.set('gonto', undefined);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.equal(undefined);
  }));

  it('should delete items correctly from localStorage', inject(function(store) {
    var value = 1;
    store.set('gonto', value);
    expect(store.get('gonto')).to.equal(value);
    store.remove('gonto');
    expect(store.get('gonto')).to.not.exist;
  }));

  it('should save objects correctly', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    expect(store.get('gonto')).to.eql(value);
  }));

  it('should save objects correctly', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    expect(store.get('gonto')).to.eql(value);
  }));

  it('should save and objects correctly without cache', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.eql(value);
    expect(store.get('gonto')).not.to.equal(value);
  }));

  it('should save and objects correctly without cache', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.eql(value);
    expect(store.get('gonto')).not.to.equal(value);
  }));
});

describe('angularStorage storeProvider.setStore("sessionStorage")', function () {

  var provider;

  beforeEach(function() {
    module('angular-storage.store', function(storeProvider) {
      provider = storeProvider;
      provider.setStore('sessionStorage');
    });
  });

  it('should save items correctly in the sessionStorage', inject(function(store, $window) {
    var value = 99;
    store.set('gonto123', value);
    store.inMemoryCache = {};

    expect(store.get('gonto123')).to.equal(value);
    expect($window.sessionStorage.getItem('gonto123')).to.exist;
    expect($window.sessionStorage.getItem('gonto123')).to.equal(value.toString());

    store.remove('gonto123');

    expect(store.get('gonto123')).to.not.exist;
    expect($window.sessionStorage.getItem('gonto123')).to.not.exist;
  }));
});

describe('angularStorage storeProvider.setStore("sessionStorage")', function () {

  var provider, windowMock, $cookieStore;
  var mockCookieStore = {};

  beforeEach(function() {
    module('ngCookies', 'angular-storage.store', function(storeProvider, $provide) {

      // decorator to mock the methods of the cookieStore
      $provide.decorator('$cookieStore', function ($delegate) {
        $delegate.put = function (key, value) {
          mockCookieStore[key] = value;
        };
        $delegate.get = function (key) {
          return mockCookieStore[key];
        };
        return $delegate;
      });

      provider = storeProvider;
      provider.setStore('sessionStorage');

      windowMock = { sessionStorage: undefined };
      $provide.value('$window', windowMock);
    });
  });

  beforeEach(inject(function( _$cookieStore_) {
    $cookieStore = _$cookieStore_;
  }));

  it('should fallback to cookieStorage', inject(function(store) {
    var value = 99;
    store.set('gonto123', value);

    expect(store.get('gonto123')).to.equal(value);
    expect($cookieStore.get('gonto123')).to.equal(JSON.stringify(value));
  }));
});

describe('angularStorage storeProvider.setStore("localStorage")', function () {

  var provider;

  beforeEach(function() {
    module('angular-storage.store', function(storeProvider) {
      provider = storeProvider;
      provider.setStore('localStorage');
    });
  });

  it('should save items correctly in the localStorage', inject(function(store, $window) {
    var value = 55;
    store.set('gonto', value);

    expect(store.get('gonto')).to.equal(value);
    expect($window.localStorage.getItem('gonto')).to.exist;
    expect($window.localStorage.getItem('gonto')).to.equal(value.toString());
  }));
});

describe('angularStorage storeProvider.setStore("cookieStorage")', function () {

  var provider;
  var $cookieStore;

  beforeEach(function() {
    module('ngCookies', 'angular-storage.store', function(storeProvider) {
      provider = storeProvider;
      provider.setStore('cookieStorage');
    });
  });

  beforeEach(inject(function( _$cookieStore_) {
    $cookieStore = _$cookieStore_;
  }));

  it('should save items correctly in the cookieStorage', inject(function(store) {
    var value = 66;
    store.set('gonto', value);

    expect(store.get('gonto')).to.equal(value);
    expect($cookieStore.get('gonto')).to.equal(JSON.stringify(value));
  }));
});

describe('angularStorage storeProvider.setStore()', function () {

  var provider;

  beforeEach(function() {
    module('angular-storage.store', function(storeProvider) {
      provider = storeProvider;
      provider.setStore();
    });
  });

  it('should save items correctly in the localStorage', inject(function(store, $window) {
    var value = 77;
    store.set('gonto', value);

    expect(store.get('gonto')).to.equal(value);
    expect($window.localStorage.getItem('gonto')).to.exist;
    expect($window.localStorage.getItem('gonto')).to.equal(value.toString());
  }));
});

describe('angularStorage storeProvider.setStore(123)', function () {

  var provider;

  beforeEach(function() {
    module('angular-storage.store', function(storeProvider) {
      provider = storeProvider;
      provider.setStore(123);
    });
  });

  it('should save items correctly in the localStorage', inject(function(store, $window) {
    var value = 77;
    store.set('gonto', value);

    expect(store.get('gonto')).to.equal(value);
    expect($window.localStorage.getItem('gonto')).to.exist;
    expect($window.localStorage.getItem('gonto')).to.equal(value.toString());
  }));
});

describe('angularStorage storeProvider.setStore("abc")', function () {

  var provider;

  beforeEach(function() {
    module('angular-storage.store', function(storeProvider) {
      provider = storeProvider;
      provider.setStore('abc');
    });
  });

  it('should throw an error when the store is not found', function() {
    expect(function() { inject(function(store){ store.get('a');}); } ).to.throw();
  });
});

describe('angularStorage store: cookie fallback', function() {

    /* these tests ensure that the cookie fallback works correctly.
    *
    * note - to confirm that cookiestore was used we attempt to retrieve the value from the cookie
             since this bypasses our service, the result will not have been json parsed
             therefore we use JSON.stringify on the expected value, so comparing like for like
    *
    */

  var windowMock, $cookieStore;
  var mockCookieStore = {};

  /* provide a mock for $window where localStorage is not defined */
  beforeEach(module('ngCookies', 'angular-storage.store', function ($provide) {

    // decorator to mock the methods of the cookieStore
    $provide.decorator('$cookieStore', function ($delegate) {
      $delegate.put = function (key, value) {
        mockCookieStore[key] = value;
      };
      $delegate.get = function (key) {
        return mockCookieStore[key];
      };
      $delegate.remove = function (key) {
        delete mockCookieStore[key];
      };
      return $delegate;
    });

    windowMock = { localStorage: undefined };
    $provide.value('$window', windowMock);
  }));

  beforeEach(inject(function (_$cookieStore_) {
    $cookieStore = _$cookieStore_;
  }));

  it('should save items correctly in localStorage', inject(function(store) {
    var value = 1;
    store.set('gonto', value);
    expect(store.get('gonto')).to.equal(value); //this line asserts that value was saved by our service
    expect($cookieStore.get('gonto')).to.equal(JSON.stringify(value)); //this line asserts that cookie store was used
  }));

  it('should save null items correctly in localStorage', inject(function(store) {
    store.set('gonto', null);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.equal(null);
    expect($cookieStore.get('gonto')).to.equal(JSON.stringify(null));
  }));

  it('should save undefined items correctly in localStorage', inject(function(store) {
    store.set('gonto', undefined);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.equal(undefined);
    expect($cookieStore.get('gonto')).to.equal(JSON.stringify(undefined));
  }));

  it('should delete items correctly from localStorage', inject(function(store) {
    var value = 1;
    store.set('gonto', value);
    expect(store.get('gonto')).to.equal(value);
    store.remove('gonto');
    expect(store.get('gonto')).to.not.exist;
    expect($cookieStore.get('gonto')).to.not.exist;
  }));

  it('should save objects correctly', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    expect(store.get('gonto')).to.eql(value);
  }));

  it('should save objects correctly', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    expect(store.get('gonto')).to.eql(value);
    expect($cookieStore.get('gonto')).to.equal(JSON.stringify(value));
  }));

  it('should save objects correctly without cache', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.eql(value);
    expect(store.get('gonto')).not.to.equal(value);
  }));

  it('should save objects correctly without cache', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.eql(value);
    expect(store.get('gonto')).not.to.equal(value);
    expect($cookieStore.get('gonto')).to.eql(JSON.stringify(value));

  }));

});

describe('angularStorage new namespaced store', function() {
  beforeEach(function() {
    module('ngCookies', 'angular-storage.store');
  });

  var newStore = null;

  beforeEach(inject(function(store) {
    newStore = store.getNamespacedStore('auth0');
  }));

  it('should save items correctly', inject(function($window) {
    var value = 1;
    newStore.set('myCoolValue', value);
    expect(newStore.get('myCoolValue')).to.equal(value);
    expect($window.localStorage.getItem('auth0.myCoolValue')).to.exist;
    expect($window.localStorage.getItem('myCoolValue')).to.not.exist;
  }));

  it('should delete items correctly from localStorage', function() {
    var value = 1;
    newStore.set('gonto', value);
    expect(newStore.get('gonto')).to.equal(value);
    newStore.remove('gonto');
    expect(newStore.get('gonto')).to.not.exist;
  });

  it('should save objects correctly', function() {
    var value = {
      gonto: 'hola'
    };
    newStore.set('gonto', value);
    expect(newStore.get('gonto')).to.eql(value);
  });

  it('should save objects correctly', function() {
    var value = {
      gonto: 'hola'
    };
    newStore.set('gonto', value);
    expect(newStore.get('gonto')).to.eql(value);
  });

  it('should save and objects correctly without cache', function() {
    var value = {
      gonto: 'hola'
    };
    newStore.set('gonto', value);
    newStore.inMemoryCache = {};
    expect(newStore.get('gonto')).to.eql(value);
    expect(newStore.get('gonto')).not.to.equal(value);
  });

  it('should save and objects correctly without cache', function() {
    var value = {
      gonto: 'hola'
    };
    newStore.set('gonto', value);
    newStore.inMemoryCache = {};
    expect(newStore.get('gonto')).to.eql(value);
    expect(newStore.get('gonto')).not.to.equal(value);
  });

  it('should should save items correctly when the delimiter is set', inject(function(store, $window) {
    var value = 111;
    var aStore = store.getNamespacedStore('aa', 'sessionStorage', '-');
    aStore.set('wayne', value);

    expect(aStore.get('wayne')).to.equal(value);
    expect($window.sessionStorage.getItem('aa-wayne')).to.exist;
    expect($window.sessionStorage.getItem('aa-wayne')).to.equal(value.toString());
    expect($window.sessionStorage.getItem('wayne')).to.not.exist;
  }));

  describe('with param storage', function () {
    var $cookieStore;

    beforeEach(inject(function( _$cookieStore_) {
      $cookieStore = _$cookieStore_;
    }));

    it('should should save items correctly when the storage is set to sessionStorage', inject(function(store, $window) {
      var value = 111;
      var sessionStore = store.getNamespacedStore('aa', 'sessionStorage');
      sessionStore.set('wayne', value);

      expect(sessionStore.get('wayne')).to.equal(value);
      expect($window.sessionStorage.getItem('aa.wayne')).to.exist;
      expect($window.sessionStorage.getItem('aa.wayne')).to.equal(value.toString());
      expect($window.sessionStorage.getItem('wayne')).to.not.exist;
    }));

    it('should should save items correctly when the storage is set to localStorage', inject(function(store, $window) {
      var value = 222;
      var localStore = store.getNamespacedStore('bb', 'localStorage');
      localStore.set('wayne', value);

      expect(localStore.get('wayne')).to.equal(value);
      expect($window.localStorage.getItem('bb.wayne')).to.exist;
      expect($window.localStorage.getItem('bb.wayne')).to.equal(value.toString());
      expect($window.localStorage.getItem('wayne')).to.not.exist;
    }));

    it('should should save items correctly when the storage is set to cookieStorage', inject(function(store) {
      var value = 222;
      var cookieStore = store.getNamespacedStore('cc', 'cookieStorage');
      cookieStore.set('wayne', value);

      expect(cookieStore.get('wayne')).to.equal(value);
      expect($cookieStore.get('cc.wayne')).to.equal(JSON.stringify(value));
    }));
  });
});

<commit_msg>tests: make tests working with new $cookies service<commit_after>'use strict';

describe('angularStorage store', function() {

  beforeEach(function() {
    module('angular-storage.store');
  });

  it('should save items correctly in localStorage', inject(function(store) {
    var value = 1;
    store.set('gonto', value);
    expect(store.get('gonto')).to.equal(value);
  }));

  it('should save null items correctly in localStorage', inject(function(store) {
    store.set('gonto', null);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.equal(null);
  }));

  it('should save undefined items correctly in localStorage', inject(function(store) {
    store.set('gonto', undefined);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.equal(undefined);
  }));

  it('should delete items correctly from localStorage', inject(function(store) {
    var value = 1;
    store.set('gonto', value);
    expect(store.get('gonto')).to.equal(value);
    store.remove('gonto');
    expect(store.get('gonto')).to.not.exist;
  }));

  it('should save objects correctly', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    expect(store.get('gonto')).to.eql(value);
  }));

  it('should save objects correctly', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    expect(store.get('gonto')).to.eql(value);
  }));

  it('should save and objects correctly without cache', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.eql(value);
    expect(store.get('gonto')).not.to.equal(value);
  }));

  it('should save and objects correctly without cache', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.eql(value);
    expect(store.get('gonto')).not.to.equal(value);
  }));
});

describe('angularStorage storeProvider.setStore("sessionStorage")', function () {

  var provider;

  beforeEach(function() {
    module('angular-storage.store', function(storeProvider) {
      provider = storeProvider;
      provider.setStore('sessionStorage');
    });
  });

  it('should save items correctly in the sessionStorage', inject(function(store, $window) {
    var value = 99;
    store.set('gonto123', value);
    store.inMemoryCache = {};

    expect(store.get('gonto123')).to.equal(value);
    expect($window.sessionStorage.getItem('gonto123')).to.exist;
    expect($window.sessionStorage.getItem('gonto123')).to.equal(value.toString());

    store.remove('gonto123');

    expect(store.get('gonto123')).to.not.exist;
    expect($window.sessionStorage.getItem('gonto123')).to.not.exist;
  }));
});

describe('angularStorage storeProvider.setStore("sessionStorage")', function () {

  var provider, windowMock, $cookies;
  var mockCookieStore = {};

  beforeEach(function() {
    module('ngCookies', 'angular-storage.store', function(storeProvider, $provide) {

      // decorator to mock the methods of the cookieStore
      $provide.decorator('$cookies', function ($delegate) {
        $delegate.put = function (key, value) {
          mockCookieStore[key] = value;
        };
        $delegate.get = function (key) {
          return mockCookieStore[key];
        };
        return $delegate;
      });

      provider = storeProvider;
      provider.setStore('sessionStorage');

      windowMock = { sessionStorage: undefined };
      $provide.value('$window', windowMock);
    });
  });

  beforeEach(inject(function( _$cookies_) {
    $cookies = _$cookies_;
  }));

  it('should fallback to cookieStorage', inject(function(store) {
    var value = 99;
    store.set('gonto123', value);

    expect(store.get('gonto123')).to.equal(value);
    expect($cookies.get('gonto123')).to.equal(JSON.stringify(value));
  }));
});

describe('angularStorage storeProvider.setStore("localStorage")', function () {

  var provider;

  beforeEach(function() {
    module('angular-storage.store', function(storeProvider) {
      provider = storeProvider;
      provider.setStore('localStorage');
    });
  });

  it('should save items correctly in the localStorage', inject(function(store, $window) {
    var value = 55;
    store.set('gonto', value);

    expect(store.get('gonto')).to.equal(value);
    expect($window.localStorage.getItem('gonto')).to.exist;
    expect($window.localStorage.getItem('gonto')).to.equal(value.toString());
  }));
});

describe('angularStorage storeProvider.setStore("cookieStorage")', function () {

  var provider;
  var $cookies;

  beforeEach(function() {
    module('ngCookies', 'angular-storage.store', function(storeProvider) {
      provider = storeProvider;
      provider.setStore('cookieStorage');
    });
  });

  beforeEach(inject(function( _$cookies_) {
    $cookies = _$cookies_;
  }));

  it('should save items correctly in the cookieStorage', inject(function(store) {
    var value = 66;
    store.set('gonto', value);

    expect(store.get('gonto')).to.equal(value);
    expect($cookies.get('gonto')).to.equal(JSON.stringify(value));
  }));
});

describe('angularStorage storeProvider.setStore()', function () {

  var provider;

  beforeEach(function() {
    module('angular-storage.store', function(storeProvider) {
      provider = storeProvider;
      provider.setStore();
    });
  });

  it('should save items correctly in the localStorage', inject(function(store, $window) {
    var value = 77;
    store.set('gonto', value);

    expect(store.get('gonto')).to.equal(value);
    expect($window.localStorage.getItem('gonto')).to.exist;
    expect($window.localStorage.getItem('gonto')).to.equal(value.toString());
  }));
});

describe('angularStorage storeProvider.setStore(123)', function () {

  var provider;

  beforeEach(function() {
    module('angular-storage.store', function(storeProvider) {
      provider = storeProvider;
      provider.setStore(123);
    });
  });

  it('should save items correctly in the localStorage', inject(function(store, $window) {
    var value = 77;
    store.set('gonto', value);

    expect(store.get('gonto')).to.equal(value);
    expect($window.localStorage.getItem('gonto')).to.exist;
    expect($window.localStorage.getItem('gonto')).to.equal(value.toString());
  }));
});

describe('angularStorage storeProvider.setStore("abc")', function () {

  var provider;

  beforeEach(function() {
    module('angular-storage.store', function(storeProvider) {
      provider = storeProvider;
      provider.setStore('abc');
    });
  });

  it('should throw an error when the store is not found', function() {
    expect(function() { inject(function(store){ store.get('a');}); } ).to.throw();
  });
});

describe('angularStorage store: cookie fallback', function() {

    /* these tests ensure that the cookie fallback works correctly.
    *
    * note - to confirm that cookiestore was used we attempt to retrieve the value from the cookie
             since this bypasses our service, the result will not have been json parsed
             therefore we use JSON.stringify on the expected value, so comparing like for like
    *
    */

  var windowMock, $cookies;
  var mockCookieStore = {};

  /* provide a mock for $window where localStorage is not defined */
  beforeEach(module('ngCookies', 'angular-storage.store', function ($provide) {

    // decorator to mock the methods of the cookieStore
    $provide.decorator('$cookies', function ($delegate) {
      $delegate.put = function (key, value) {
        mockCookieStore[key] = value;
      };
      $delegate.get = function (key) {
        return mockCookieStore[key];
      };
      $delegate.remove = function (key) {
        delete mockCookieStore[key];
      };
      return $delegate;
    });

    windowMock = { localStorage: undefined };
    $provide.value('$window', windowMock);
  }));

  beforeEach(inject(function (_$cookies_) {
    $cookies = _$cookies_;
  }));

  it('should save items correctly in localStorage', inject(function(store) {
    var value = 1;
    store.set('gonto', value);
    expect(store.get('gonto')).to.equal(value); //this line asserts that value was saved by our service
    expect($cookies.get('gonto')).to.equal(JSON.stringify(value)); //this line asserts that cookie store was used
  }));

  it('should save null items correctly in localStorage', inject(function(store) {
    store.set('gonto', null);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.equal(null);
    expect($cookies.get('gonto')).to.equal(JSON.stringify(null));
  }));

  it('should save undefined items correctly in localStorage', inject(function(store) {
    store.set('gonto', undefined);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.equal(undefined);
    expect($cookies.get('gonto')).to.equal(JSON.stringify(undefined));
  }));

  it('should delete items correctly from localStorage', inject(function(store) {
    var value = 1;
    store.set('gonto', value);
    expect(store.get('gonto')).to.equal(value);
    store.remove('gonto');
    expect(store.get('gonto')).to.not.exist;
    expect($cookies.get('gonto')).to.not.exist;
  }));

  it('should save objects correctly', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    expect(store.get('gonto')).to.eql(value);
  }));

  it('should save objects correctly', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    expect(store.get('gonto')).to.eql(value);
    expect($cookies.get('gonto')).to.equal(JSON.stringify(value));
  }));

  it('should save objects correctly without cache', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.eql(value);
    expect(store.get('gonto')).not.to.equal(value);
  }));

  it('should save objects correctly without cache', inject(function(store) {
    var value = {
      gonto: 'hola'
    };
    store.set('gonto', value);
    store.inMemoryCache = {};
    expect(store.get('gonto')).to.eql(value);
    expect(store.get('gonto')).not.to.equal(value);
    expect($cookies.get('gonto')).to.eql(JSON.stringify(value));

  }));

});

describe('angularStorage new namespaced store', function() {
  beforeEach(function() {
    module('ngCookies', 'angular-storage.store');
  });

  var newStore = null;

  beforeEach(inject(function(store) {
    newStore = store.getNamespacedStore('auth0');
  }));

  it('should save items correctly', inject(function($window) {
    var value = 1;
    newStore.set('myCoolValue', value);
    expect(newStore.get('myCoolValue')).to.equal(value);
    expect($window.localStorage.getItem('auth0.myCoolValue')).to.exist;
    expect($window.localStorage.getItem('myCoolValue')).to.not.exist;
  }));

  it('should delete items correctly from localStorage', function() {
    var value = 1;
    newStore.set('gonto', value);
    expect(newStore.get('gonto')).to.equal(value);
    newStore.remove('gonto');
    expect(newStore.get('gonto')).to.not.exist;
  });

  it('should save objects correctly', function() {
    var value = {
      gonto: 'hola'
    };
    newStore.set('gonto', value);
    expect(newStore.get('gonto')).to.eql(value);
  });

  it('should save objects correctly', function() {
    var value = {
      gonto: 'hola'
    };
    newStore.set('gonto', value);
    expect(newStore.get('gonto')).to.eql(value);
  });

  it('should save and objects correctly without cache', function() {
    var value = {
      gonto: 'hola'
    };
    newStore.set('gonto', value);
    newStore.inMemoryCache = {};
    expect(newStore.get('gonto')).to.eql(value);
    expect(newStore.get('gonto')).not.to.equal(value);
  });

  it('should save and objects correctly without cache', function() {
    var value = {
      gonto: 'hola'
    };
    newStore.set('gonto', value);
    newStore.inMemoryCache = {};
    expect(newStore.get('gonto')).to.eql(value);
    expect(newStore.get('gonto')).not.to.equal(value);
  });

  it('should should save items correctly when the delimiter is set', inject(function(store, $window) {
    var value = 111;
    var aStore = store.getNamespacedStore('aa', 'sessionStorage', '-');
    aStore.set('wayne', value);

    expect(aStore.get('wayne')).to.equal(value);
    expect($window.sessionStorage.getItem('aa-wayne')).to.exist;
    expect($window.sessionStorage.getItem('aa-wayne')).to.equal(value.toString());
    expect($window.sessionStorage.getItem('wayne')).to.not.exist;
  }));

  describe('with param storage', function () {
    var $cookies;

    beforeEach(inject(function( _$cookies_) {
      $cookies = _$cookies_;
    }));

    it('should should save items correctly when the storage is set to sessionStorage', inject(function(store, $window) {
      var value = 111;
      var sessionStore = store.getNamespacedStore('aa', 'sessionStorage');
      sessionStore.set('wayne', value);

      expect(sessionStore.get('wayne')).to.equal(value);
      expect($window.sessionStorage.getItem('aa.wayne')).to.exist;
      expect($window.sessionStorage.getItem('aa.wayne')).to.equal(value.toString());
      expect($window.sessionStorage.getItem('wayne')).to.not.exist;
    }));

    it('should should save items correctly when the storage is set to localStorage', inject(function(store, $window) {
      var value = 222;
      var localStore = store.getNamespacedStore('bb', 'localStorage');
      localStore.set('wayne', value);

      expect(localStore.get('wayne')).to.equal(value);
      expect($window.localStorage.getItem('bb.wayne')).to.exist;
      expect($window.localStorage.getItem('bb.wayne')).to.equal(value.toString());
      expect($window.localStorage.getItem('wayne')).to.not.exist;
    }));

    it('should should save items correctly when the storage is set to cookieStorage', inject(function(store) {
      var value = 222;
      var cookieStore = store.getNamespacedStore('cc', 'cookieStorage');
      cookieStore.set('wayne', value);

      expect(cookieStore.get('wayne')).to.equal(value);
      expect($cookies.get('cc.wayne')).to.equal(JSON.stringify(value));
    }));
  });
});

<|endoftext|>


<commit_before>import $ from "jquery";
import React from "react";
import {
  ApolloProvider,
  ApolloClient,
  createNetworkInterface,
  gql,
  graphql
} from "react-apollo";
import StudentContextTray from "jsx/context_cards/StudentContextTray";

const client = new ApolloClient({
  networkInterface: createNetworkInterface({
    uri: "/api/graphql",
    opts: {
      headers: {
        "X-Requested-With": "XMLHttpRequest",
        "X-CSRF-Token": $.cookie("_csrf_token") // TODO: probably need to move this io a middleware (http://dev.apollodata.com/core/network.html)
      },
      credentials: "same-origin"
    }
  })
});

/*
 * TODO: is loading grades or enrollments slowing this query way down?
 */
const GraphQLStudentContextCard = graphql(
  gql`
    query StudentContextCard(
      $courseId: ID!
      $studentId: ID!
    ) {
      course: legacyNode(type: Course, _id: $courseId) {
        ... on Course {
          _id
          name
          permissions {
            become_user: becomeUser
            manage_grades: manageGrades
            send_messages: sendMessages
            view_all_grades: viewAllGrades
            view_analytics: viewAnalytics
          }
          submissionsConnection(
            first: 10
            orderBy: [{ field: gradedAt, direction: descending }]
            studentIds: [$studentId]
          ) {
            edges {
              submission: node {
                id
                score
                grade
                excused
                user { _id }
                assignment {
                  name
                  html_url: htmlUrl
                  points_possible: pointsPossible
                }
              }
            }
          }
        }
      }
      user: legacyNode(type: User, _id: $studentId) {
        ... on User {
          _id
          short_name: shortName
          avatar_url: avatarUrl
          enrollments(courseId: $courseId) {
            last_activity_at: lastActivityAt
            section { name }
            grades {
              current_grade: currentGrade
              current_score: currentScore
            }
          }
          analytics: summaryAnalytics(courseId: $courseId) {
            page_views: pageViews {
              total
              max
              level
            }
            participations {
              total
              max
              level
            }
            tardiness_breakdown: tardinessBreakdown {
              late
              missing
              on_time: onTime
            }
          }
        }
      }
    }
  `,
  {
    options: props => ({
      variables: {
        courseId: props.courseId,
        studentId: props.studentId,
      }
    })
  }
)(StudentContextTray);

export default props => {
  return (
    <ApolloProvider client={client}>
      <GraphQLStudentContextCard {...props} />
    </ApolloProvider>
  );
};
<commit_msg>load user from Course instead of legacyNode<commit_after>import $ from 'jquery'
import _ from 'underscore'
import React from 'react'
import {ApolloProvider, ApolloClient, createNetworkInterface, gql, graphql} from 'react-apollo'
import StudentContextTray from 'jsx/context_cards/StudentContextTray'

const client = new ApolloClient({
  networkInterface: createNetworkInterface({
    uri: '/api/graphql',
    opts: {
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-Token': $.cookie('_csrf_token') // TODO: probably need to move this io a middleware (http://dev.apollodata.com/core/network.html)
      },
      credentials: 'same-origin'
    }
  })
})

/*
 * TODO: is loading grades or enrollments slowing this query way down?
 */
const GraphQLStudentContextCard = graphql(
  gql`
    query StudentContextCard($courseId: ID!, $studentId: ID!) {
      course: legacyNode(type: Course, _id: $courseId) {
        ... on Course {
          _id
          name
          permissions {
            become_user: becomeUser
            manage_grades: manageGrades
            send_messages: sendMessages
            view_all_grades: viewAllGrades
            view_analytics: viewAnalytics
          }
          usersConnection(userIds: [$studentId]) {
            edges {
              node {
                _id
                short_name: shortName
                avatar_url: avatarUrl
                enrollments(courseId: $courseId) {
                  last_activity_at: lastActivityAt
                  section {
                    name
                  }
                  grades {
                    current_grade: currentGrade
                    current_score: currentScore
                  }
                }
                analytics: summaryAnalytics(courseId: $courseId) {
                  page_views: pageViews {
                    total
                    max
                    level
                  }
                  participations {
                    total
                    max
                    level
                  }
                  tardiness_breakdown: tardinessBreakdown {
                    late
                    missing
                    on_time: onTime
                  }
                }
              }
            }
          }
          submissionsConnection(
            first: 10
            orderBy: [{field: gradedAt, direction: descending}]
            studentIds: [$studentId]
          ) {
            edges {
              submission: node {
                id
                score
                grade
                excused
                user {
                  _id
                }
                assignment {
                  name
                  html_url: htmlUrl
                  points_possible: pointsPossible
                }
              }
            }
          }
        }
      }
    }
  `,
  {
    options: props => ({
      variables: {
        courseId: props.courseId,
        studentId: props.studentId
      }
    }),

    // move user to top-level
    props: props => {
      const {course} = props.data
      let edge, user
      if (course && (edge = course.usersConnection.edges[0])) {
        user = edge.node
        return {
          ...props,
          data: {
            ...props.data,
            course: _.omit(course, 'usersConnection'),
            user
          }
        }
      } else {
        return props
      }
    }
  }
)(StudentContextTray)

export default props => {
  return (
    <ApolloProvider client={client}>
      <GraphQLStudentContextCard {...props} />
    </ApolloProvider>
  )
}
<|endoftext|>


<commit_before>var obj_canvas,
obj_c,
cp_canvas = null;

var canvas
var video_canvas,
vid_c;

var brown_const=0;

var vid_width = 640;
var vid_height = 480;
var n_object = 20;
var m_object = 5;

var canvas;
var context;

function setupD3(){
	var w = 640,
    	h = 480,
    	n = 20,
    	m = 12,
    	l = 80,
    	degrees = 180 / Math.PI;

	var objects = d3.range(n).map(function() {
  		var x = Math.random() * w, y = Math.random() * h;
  		var active = true;
  		var radius = 50;
  		return {
    		vx: Math.random() * 2 - 1,
    		vy: Math.random() * 2 - 1,
    		path: d3.range(m).map(function() { return [x, y]; }),
    		count: 0
  		};
	});

	var svg = d3.select("#canvasArea").append("svg:svg")
    	.attr("width", vid_width)
    	.attr("height", vid_height);

	var image = svg.append("image")
    	.attr("xlink:href", "http://171.65.102.132:8080/?action=snapshot?t=" + new Date().getTime())
    	.attr("width", vid_width)
    	.attr("height", vid_height);

	var g = svg.selectAll("g")
    	.data(objects)
		.enter().append("svg:g");

	var box = g.append("svg:rect")
    	.attr("width", l)
    	.attr("height", l);

	function getVideo(){
		var frameURL = "http://171.65.102.132:8080/?action=snapshot?t=" + new Date().getTime();
		image.attr('onload', function() {
         		compareFrame(image);
    		})
    		.attr("xlink:href", frameURL)
    		.attr("width", vid_width)
    		.attr("height", vid_height);
	}

	function drawObjects(){
		for (var i = -1; ++i < n;) {
    		var object = objects[i],
        		path = object.path,
        		dx = object.vx,
        		dy = object.vy,
        		x = path[0][0] += dx,
        		y = path[0][1] += dy,
        		speed = Math.sqrt(dx * dx + dy * dy),
        		count = speed * 10,
        		k1 = -5 - speed / 3;

    		// Bounce off the walls.
    		if (x < 0 || x > w) object.vx *= -1;
    		if (y < 0 || y > h) object.vy *= -1;

    		// Swim!
    		for (var j = 0; ++j < m;) {
      			var vx = x - path[j][0],
          			vy = y - path[j][1],
          			k2 = Math.sin(((object.count += count) + j * 3) / 300) / speed;
      			path[j][0] = (x += dx / speed * k1) - dy * k2;
      			path[j][1] = (y += dy / speed * k1) + dx * k2;
      			speed = Math.sqrt((dx = vx) * dx + (dy = vy) * dy);
    		}
  		}

  		box.attr("transform", function(d) {
    		return "translate(" + d.path[0] + ")";
    		//return "translate(" + d.path[0] + ")rotate(" + Math.atan2(d.vy, d.vx) * degrees + ")";
  		});
  	}

d3.timer(function() {
	getVideo();
	//console.log(hit);
  	drawObjects();
});

}

function game(){
	switch(gamephase)
	{
		case 'pre-game':
			// draw intro
		break;
		case 'game-rest':
    		vid_c.fillStyle = "#fff";
    		vid_c.font="14px sans-serif";
    		vid_c.fillText('New target ...',200,20);
    		vid_c.fillText('player : ' + username + '  score : ' +score_val ,20,20);
		break;
		case 'game-action':
    		vid_c.fillStyle = "#fff";
    		vid_c.font="14px sans-serif";
    		vid_c.fillText('Run! Run! Run!',200,20);
    		vid_c.fillText('player : ' + username + '  score : ' +score_val ,20,20);
		break;
		case 'gameover':
    		vid_c.fillStyle = "#fff";
    		vid_c.font="14px sans-serif";
    		vid_c.textAlign="start";
    		vid_c.fillText('player : ' + username + '  score : ' +score_val ,20,20);
    		vid_c.fillStyle = "rgba(253,172,13,1)";
    		vid_c.font="40pt sans-serif";
    		vid_c.textAlign="center";
    		vid_c.fillText('GAME OVER',vid_width/2,vid_height/2-100);
    		vid_c.fillStyle = "#fff";
    		vid_c.font="20pt sans-serif";
    		vid_c.fillText(username+' scored '+score_val,vid_width/2,vid_height/2);
		break;
		default:
			vid_c.fillStyle = "#fff";
			vid_c.font="14px sans-serif";
    		vid_c.fillText('player : ' + username + '  score : ' +score_val ,20,20);
	}
}

var shipX=vid_width/2,
	shipY=vid_height/2,
	shipRad,
	shipL=20,
	starX=40,
	starY=20;
var gamelevel;
var int_star=-1;
var int_engine=-1;
var engine = false;
var rest = false;
var starTimer;
var enginerTimer;
var gamephase;
var score_val = 0;
var actionTimer;
var hit = new Array();
var unit=30;

function setGameAction(){
	actionTimer = window.requestAnimationFrame(actionLoop);
}

function setbackPreGame(){
    score_val = 0;
    hit = new Array();
    gamelevel=1;

	shipX = vid_width/2;
    shipY = vid_height/2;

    gamephase='pre-game';
}

function setGameOver(){
  	window.cancelAnimationFrame(actionTimer);
    actionTimer = undefined;
}

function actionLoop(){
	switch(gamephase)
	{
		case 'rest':
  			if(rest==false)
			{
				rest=true;
				int_star=gamelevel+6;
				getStarLocation(); // get new starX, starY, shipRad
				starTimer=window.setInterval(showStar,500);
			}
			drawStar(shipX,shipY,starX,starY,gamelevel-(int_star-6));
			drawShip(shipX,shipY,shipRad);
			actionTimer = window.requestAnimationFrame(gameLoop);
  		break;
		case 'engine':
			console.log(hit);
  			if(hit>0)
			{
				window.clearInterval(engineTimer);
				engine=false;
				rest=false;
				int_star=-1;
				int_engine=-1;
				gamephase='gameover';
				gamelevel=-1;
			}
			else
			{
				score_val=score_val+10;
				if(engine==false)
				{
					engine=true;
					int_engine=gamelevel+4;
					engineTimer=window.setInterval(runEngine,500);
				}
			}
			drawStar(shipX,shipY,starX,starY,gamelevel-(int_star-6));
			drawShip(shipX,shipY,shipRad);

  		break;
	}
}

function getStarLocation(){
	shipRad=Math.random()*Math.PI*2;
	starX=shipX+unit*(Math.cos(shipRad))*gamelevel;
	starY=shipY+unit*(Math.sin(shipRad))*gamelevel;
}

function getShipLocation(){
	var step = gamelevel-(int_engine-4);
	var u = (step > gamelevel - 1) ? 0 : 1;
	shipX=shipX+unit*(Math.cos(shipRad))*u;
	shipY=shipY+unit*(Math.sin(shipRad))*u;
}

function showStar(){
	if(int_star>0)
	{
		int_star=int_star-1;
	}
	else
	{
		window.clearInterval(starTimer);
		rest=false;
		gamephase='engine';
	}
}

function runEngine(){
	if(int_engine>0)
	{
		getShipLocation();
		int_engine=int_engine-1;
	}
	else
	{
		window.clearInterval(engineTimer);
		engine=false;
		gamephase='rest';
		if(gamelevel<10)
		{
			gamelevel=gamelevel+1;
		}
	}
}

function gameOver(){
    var msg = {type:'sendscore', user:username, score:score_val};
    socket.json.send(msg);
}

/*******************************************************************************
  Copyright (C) 2009 Tom Stoeveken
  This program is free software;
  you can redistribute it and/or modify it under the terms of the
  GNU General Public License, version 2.
  See the file COPYING for details.
*******************************************************************************/

var img1 = null;
var img2 = null;
var md_canvas = null;

function setupMotionDetection() {
  md_canvas = document.getElementById('mdCanvas');
  test_canvas = document.getElementById('testCanvas');
  md_canvas.width = vid_width;
  md_canvas.height = vid_height;
}

/*
  compare two images and count the differences

  input.: image1 and image2 are Image() objects
  input.: threshold specifies by how much the color value of a pixel
          must differ before they are regarded to be different

  return: number of different pixels
*/

function compare(image1, image2, ptX, ptY, threshold, ObjR) {
  var movement = new Array(0,0,0,0);
  var md_ctx = md_canvas.getContext("2d");
  var width = md_canvas.width/2, height = md_canvas.height/2;

  // copy images into canvas element
  // these steps scale the images and decodes the image data
  md_ctx.drawImage(image1, 0, 0, width, height);
  md_ctx.drawImage(image2, width, 0, width, height);

  // this makes r,g,b,alpha data of images available
  var pixels1 = md_ctx.getImageData(0, 0, width, height);
  var pixels2 = md_ctx.getImageData(width, 0, width, height);

  // substract picture1 from picture2
  // if they differ set color value to max,
  // if the difference is below threshold set difference to 0.
  for (var x = Math.round((ptX-ObjR)/2); x < Math.round((ptX+ObjR)/2); x++) {
    for (var y = Math.round((ptY-ObjR)/2); y < Math.round((ptY+ObjR)/2); y++) {

      // each pixel has a red, green, blue and alpha value
      // all values are stored in a linear array
      var i = x*4 + y*4*pixels1.width;

      var ch0 = ((pixels1.data[i] - pixels2.data[i])>threshold)?255:0;
      var ch1 = ((pixels1.data[i] - pixels2.data[i])>threshold)?255:0;
      var ch2 = ((pixels1.data[i] - pixels2.data[i])>threshold)?255:0;

      // count differing pixels
      var n = (x<Math.round(ptX/2))?0:1;
      var m = (y<Math.round(ptY/2))?0:2;
      movement[n+m] += Math.min(1, ch0 + ch1 + ch2);
    }
  }
  return movement;
}

function compareFrame(img1,arrObject) {
  // just compare if there are two pictures
  if ( img2 != null ) {
    var res=[0,0,0,0];
    var ObjR=10;

    try {
    		for (var n=0; n<arrMotion.length; n++){
    			// arrObject [active, position_x, position_y, detection_radius]
    			res = compare(img1, img2, arrObject[n][1], arrObject[n][2], 10, arrObject[n][3]);
    			    if ((res[0]>400)||(res[1]>400)||(res[2]>400)||(res[3]>400)){
            			res[0]=0;res[1]=0;res[2]=0;res[3]=0;
    				}
				hit[n]=res[0]+res[1]+res[2]+res[3];
    		}
    	}
    catch(e) {
    		// errors
    	}
	}
	img2 = img1;
}
<commit_msg>revert to canvas<commit_after>var obj_canvas,
obj_c,
cp_canvas = null;

var canvas
var video_canvas,
vid_c;

var brown_const=0;

var vid_width = 640;
var vid_height = 480;
var n_object = 20;
var m_object = 5;

var canvas;
var context;

var vid_width = 640;
var vid_height = 480;

function setupD3() {
    canvas = d3.select("#canvasArea").append("canvas")
        .attr("width", vid_width)
        .attr("height", vid_height);

    context = canvas.node().getContext("2d");

    d3.timer(getVideo);

    function getVideo(){
            getVidFrame("http://171.65.102.132:8080/?action=snapshot?t=" + new Date().getTime(), function(image) {
                        context.clearRect(0, 0, vid_width, vid_height);
                        context.drawImage(image, 0, 0, vid_width, vid_height);
                });

                function getVidFrame(path, callback) {
                          var image = new Image;
                          image.onload = function() {
                                  callback(image);
                                  compareFrame(image);
                                  console.log(hit);
                          };
                          image.src = path;
                }
        }
}

/*function setupD3(){
	var w = 640,
    	h = 480,
    	n = 20,
    	m = 12,
    	l = 80,
    	degrees = 180 / Math.PI;

	var objects = d3.range(n).map(function() {
  		var x = Math.random() * w, y = Math.random() * h;
  		var active = true;
  		var radius = 50;
  		return {
    		vx: Math.random() * 2 - 1,
    		vy: Math.random() * 2 - 1,
    		path: d3.range(m).map(function() { return [x, y]; }),
    		count: 0
  		};
	});

	var svg = d3.select("#canvasArea").append("svg:svg")
    	.attr("width", vid_width)
    	.attr("height", vid_height);

	var image = svg.append("image")
    	.attr("xlink:href", "http://171.65.102.132:8080/?action=snapshot?t=" + new Date().getTime())
    	.attr("width", vid_width)
    	.attr("height", vid_height);

	var g = svg.selectAll("g")
    	.data(objects)
		.enter().append("svg:g");

	var box = g.append("svg:rect")
    	.attr("width", l)
    	.attr("height", l);

	function getVideo(){
		var frameURL = "http://171.65.102.132:8080/?action=snapshot?t=" + new Date().getTime();
		image.attr('onload', function() {
         		compareFrame(image);
    		})
    		.attr("xlink:href", frameURL)
    		.attr("width", vid_width)
    		.attr("height", vid_height);
	}

	function drawObjects(){
		for (var i = -1; ++i < n;) {
    		var object = objects[i],
        		path = object.path,
        		dx = object.vx,
        		dy = object.vy,
        		x = path[0][0] += dx,
        		y = path[0][1] += dy,
        		speed = Math.sqrt(dx * dx + dy * dy),
        		count = speed * 10,
        		k1 = -5 - speed / 3;

    		// Bounce off the walls.
    		if (x < 0 || x > w) object.vx *= -1;
    		if (y < 0 || y > h) object.vy *= -1;

    		// Swim!
    		for (var j = 0; ++j < m;) {
      			var vx = x - path[j][0],
          			vy = y - path[j][1],
          			k2 = Math.sin(((object.count += count) + j * 3) / 300) / speed;
      			path[j][0] = (x += dx / speed * k1) - dy * k2;
      			path[j][1] = (y += dy / speed * k1) + dx * k2;
      			speed = Math.sqrt((dx = vx) * dx + (dy = vy) * dy);
    		}
  		}

  		box.attr("transform", function(d) {
    		return "translate(" + d.path[0] + ")";
    		//return "translate(" + d.path[0] + ")rotate(" + Math.atan2(d.vy, d.vx) * degrees + ")";
  		});
  	}

d3.timer(function() {
	getVideo();
	//console.log(hit);
  	drawObjects();
});

}

*/

function game(){
	switch(gamephase)
	{
		case 'pre-game':
			// draw intro
		break;
		case 'game-rest':
    		vid_c.fillStyle = "#fff";
    		vid_c.font="14px sans-serif";
    		vid_c.fillText('New target ...',200,20);
    		vid_c.fillText('player : ' + username + '  score : ' +score_val ,20,20);
		break;
		case 'game-action':
    		vid_c.fillStyle = "#fff";
    		vid_c.font="14px sans-serif";
    		vid_c.fillText('Run! Run! Run!',200,20);
    		vid_c.fillText('player : ' + username + '  score : ' +score_val ,20,20);
		break;
		case 'gameover':
    		vid_c.fillStyle = "#fff";
    		vid_c.font="14px sans-serif";
    		vid_c.textAlign="start";
    		vid_c.fillText('player : ' + username + '  score : ' +score_val ,20,20);
    		vid_c.fillStyle = "rgba(253,172,13,1)";
    		vid_c.font="40pt sans-serif";
    		vid_c.textAlign="center";
    		vid_c.fillText('GAME OVER',vid_width/2,vid_height/2-100);
    		vid_c.fillStyle = "#fff";
    		vid_c.font="20pt sans-serif";
    		vid_c.fillText(username+' scored '+score_val,vid_width/2,vid_height/2);
		break;
		default:
			vid_c.fillStyle = "#fff";
			vid_c.font="14px sans-serif";
    		vid_c.fillText('player : ' + username + '  score : ' +score_val ,20,20);
	}
}

var shipX=vid_width/2,
	shipY=vid_height/2,
	shipRad,
	shipL=20,
	starX=40,
	starY=20;
var gamelevel;
var int_star=-1;
var int_engine=-1;
var engine = false;
var rest = false;
var starTimer;
var enginerTimer;
var gamephase;
var score_val = 0;
var actionTimer;
var hit = new Array();
var unit=30;

function setGameAction(){
	actionTimer = window.requestAnimationFrame(actionLoop);
}

function setbackPreGame(){
    score_val = 0;
    hit = new Array();
    gamelevel=1;

	shipX = vid_width/2;
    shipY = vid_height/2;

    gamephase='pre-game';
}

function setGameOver(){
  	window.cancelAnimationFrame(actionTimer);
    actionTimer = undefined;
}

function actionLoop(){
	switch(gamephase)
	{
		case 'rest':
  			if(rest==false)
			{
				rest=true;
				int_star=gamelevel+6;
				getStarLocation(); // get new starX, starY, shipRad
				starTimer=window.setInterval(showStar,500);
			}
			drawStar(shipX,shipY,starX,starY,gamelevel-(int_star-6));
			drawShip(shipX,shipY,shipRad);
			actionTimer = window.requestAnimationFrame(gameLoop);
  		break;
		case 'engine':
			console.log(hit);
  			if(hit>0)
			{
				window.clearInterval(engineTimer);
				engine=false;
				rest=false;
				int_star=-1;
				int_engine=-1;
				gamephase='gameover';
				gamelevel=-1;
			}
			else
			{
				score_val=score_val+10;
				if(engine==false)
				{
					engine=true;
					int_engine=gamelevel+4;
					engineTimer=window.setInterval(runEngine,500);
				}
			}
			drawStar(shipX,shipY,starX,starY,gamelevel-(int_star-6));
			drawShip(shipX,shipY,shipRad);

  		break;
	}
}

function getStarLocation(){
	shipRad=Math.random()*Math.PI*2;
	starX=shipX+unit*(Math.cos(shipRad))*gamelevel;
	starY=shipY+unit*(Math.sin(shipRad))*gamelevel;
}

function getShipLocation(){
	var step = gamelevel-(int_engine-4);
	var u = (step > gamelevel - 1) ? 0 : 1;
	shipX=shipX+unit*(Math.cos(shipRad))*u;
	shipY=shipY+unit*(Math.sin(shipRad))*u;
}

function showStar(){
	if(int_star>0)
	{
		int_star=int_star-1;
	}
	else
	{
		window.clearInterval(starTimer);
		rest=false;
		gamephase='engine';
	}
}

function runEngine(){
	if(int_engine>0)
	{
		getShipLocation();
		int_engine=int_engine-1;
	}
	else
	{
		window.clearInterval(engineTimer);
		engine=false;
		gamephase='rest';
		if(gamelevel<10)
		{
			gamelevel=gamelevel+1;
		}
	}
}

function gameOver(){
    var msg = {type:'sendscore', user:username, score:score_val};
    socket.json.send(msg);
}

/*******************************************************************************
  Copyright (C) 2009 Tom Stoeveken
  This program is free software;
  you can redistribute it and/or modify it under the terms of the
  GNU General Public License, version 2.
  See the file COPYING for details.
*******************************************************************************/

var img1 = null;
var img2 = null;
var md_canvas = null;

function setupMotionDetection() {
  md_canvas = document.getElementById('mdCanvas');
  test_canvas = document.getElementById('testCanvas');
  md_canvas.width = vid_width;
  md_canvas.height = vid_height;
}

/*
  compare two images and count the differences

  input.: image1 and image2 are Image() objects
  input.: threshold specifies by how much the color value of a pixel
          must differ before they are regarded to be different

  return: number of different pixels
*/

function compare(image1, image2, ptX, ptY, threshold, ObjR) {
  var movement = new Array(0,0,0,0);
  var md_ctx = md_canvas.getContext("2d");
  var width = md_canvas.width/2, height = md_canvas.height/2;

  // copy images into canvas element
  // these steps scale the images and decodes the image data
  md_ctx.drawImage(image1, 0, 0, width, height);
  md_ctx.drawImage(image2, width, 0, width, height);

  // this makes r,g,b,alpha data of images available
  var pixels1 = md_ctx.getImageData(0, 0, width, height);
  var pixels2 = md_ctx.getImageData(width, 0, width, height);

  // substract picture1 from picture2
  // if they differ set color value to max,
  // if the difference is below threshold set difference to 0.
  for (var x = Math.round((ptX-ObjR)/2); x < Math.round((ptX+ObjR)/2); x++) {
    for (var y = Math.round((ptY-ObjR)/2); y < Math.round((ptY+ObjR)/2); y++) {

      // each pixel has a red, green, blue and alpha value
      // all values are stored in a linear array
      var i = x*4 + y*4*pixels1.width;

      var ch0 = ((pixels1.data[i] - pixels2.data[i])>threshold)?255:0;
      var ch1 = ((pixels1.data[i] - pixels2.data[i])>threshold)?255:0;
      var ch2 = ((pixels1.data[i] - pixels2.data[i])>threshold)?255:0;

      // count differing pixels
      var n = (x<Math.round(ptX/2))?0:1;
      var m = (y<Math.round(ptY/2))?0:2;
      movement[n+m] += Math.min(1, ch0 + ch1 + ch2);
    }
  }
  return movement;
}

function compareFrame(img1,arrObject) {
  // just compare if there are two pictures
  if ( img2 != null ) {
    var res=[0,0,0,0];
    var ObjR=10;

    try {
    		for (var n=0; n<arrMotion.length; n++){
    			// arrObject [active, position_x, position_y, detection_radius]
    			res = compare(img1, img2, arrObject[n][1], arrObject[n][2], 10, arrObject[n][3]);
    			    if ((res[0]>400)||(res[1]>400)||(res[2]>400)||(res[3]>400)){
            			res[0]=0;res[1]=0;res[2]=0;res[3]=0;
    				}
				hit[n]=res[0]+res[1]+res[2]+res[3];
    		}
    	}
    catch(e) {
    		// errors
    	}
	}
	img2 = img1;
}
<|endoftext|>


<commit_before>const request = require('supertest');
const chai = require('chai');
chai.use(require('chai-string'));

const Sandbox = require('@globocom/backstage-functions-sandbox');

const expect = chai.expect;
const routes = require('../../../../lib/http/routes');
const FakeStorage = require('../../../fakes/FakeStorage');

describe('GET /functions', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
  });

  it('should return namespaces with their functions', (done) => {
    request(routes)
      .get('/functions')
      .expect((res) => {
        expect(res.body.items[0].namespace).to.be.eql('namespace1');
        expect(res.body.items[0].id).to.be.eql('function');
        expect(res.body.items[1].namespace).to.be.eql('namespace2');
        expect(res.body.items[1].id).to.be.eql('function');
        expect(res.body.items[2].namespace).to.be.eql('namespace3');
        expect(res.body.items[2].id).to.be.eql('function');
        expect(res.profile).to.endsWith('/_schemas/functions/list');
      })
      .expect(200, done);
  });

  it('search by namespace', (done) => {
    request(routes)
      .get('/functions?namespace=namespace1')
      .expect('Content-Type', /json/)
      .expect(200, {
        items: [
          { namespace: 'namespace1', id: 'function1' },
          { namespace: 'namespace1', id: 'function2' },
        ],
      }, done);
  });

  it('search by namespace and function id', (done) => {
    request(routes)
      .get('/functions?namespace=namespace1&id=function1')
      .expect('Content-Type', /json/)
      .expect(200, {
        items: [
          { namespace: 'namespace1', id: 'function1' },
        ],
      }, done);
  });

  it('should fail the request with 500 error', (done) => {
    request(routes)
      .get('/functions?namespace=error')
      .expect(500, {
        error: 'Storage error',
      }, done);
  });
});

describe('PUT /functions/:namespace/:id', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
  });

  describe('when code is correct', () => {
    it('should return the code', (done) => {
      const code = 'function main() {}';

      request(routes)
        .put('/functions/backstage/correct')
        .send({ code })
        .expect('Content-Type', /json/)
        .expect(() => {
          const memoryStorage = routes.get('memoryStorage');
          expect(memoryStorage.lastPutCode).to.be.eql({
            id: 'correct',
            hash: 'c177063dc3780c2fe9b4fdc913650e8147c9b8b0',
            code,
          });
        })
        .expect(200, {
          id: 'correct',
          code: 'function main() {}',
          hash: 'c177063dc3780c2fe9b4fdc913650e8147c9b8b0',
        }, done);
    });
  });

  describe('when return any error from storage', () => {
    it('should return the code', (done) => {
      const code = 'function main() {}';

      request(routes)
        .put('/functions/backstage/error')
        .send({ code })
        .expect('Content-Type', /json/)
        .expect(500, {
          error: 'Storage error',
        }, done);
    });
  });

  describe('when code has a syntax error', () => {
    it('should return a error', (done) => {
      request(routes)
        .put('/functions/backstage/invalid')
        .send({ code: '{)' })
        .expect('Content-Type', /application\/json/)
        .expect(400, {
          error: 'SyntaxError: Unexpected token )',
          stack: '',
        }, done);
    });
  });

  describe('when code has a logic error', () => {
    it('should return a error', (done) => {
      const code = `let a = {};
            function c() {
                a.b();
            };
            c()`;

      request(routes)
        .put('/functions/codes/crazy')
        .send({ code })
        .expect('Content-Type', /json/)
        .expect(400, {
          error: 'TypeError: a.b is not a function',
          stack: 'at c (codes/crazy.js:3)\nat codes/crazy.js:5\nat codes/crazy.js:6',
        }, done);
    });
  });

  describe('when code has a timeout error', () => {
    it('should return a error', (done) => {
      const code = 'while(1) {};';

      request(routes)
        .put('/functions/codes/timeout')
        .send({ code })
        .expect('Content-Type', /json/)
        .expect((res) => {
          expect(res.body.error).to.include('Error: Script execution timed out');
        })
        .expect(400, done);
    });
  });

  describe('when code is not a string', () => {
    it('should return a error', (done) => {
      const code = { wrong: 'yes' };

      request(routes)
        .put('/functions/codes/invalid')
        .send({ code })
        .expect('Content-Type', /^application\/json/)
        .expect(400, {
          error: 'Invalid instance',
          details: [
            'instance.code is not of a type(s) string',
          ],
        }, done);
    });
  });
});

describe('GET /functions/:namespace/:id', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
  });

  describe('when code is not found', () => {
    it('should return 404 error', (done) => {
      request(routes)
        .get('/functions/backstage/not-found')
        .expect((res) => {
          expect(res.body.error).to.be.eql('Code not found');
        })
        .expect(404, done);
    });
  });

  describe('when code is found', () => {
    it('should return the code', (done) => {
      request(routes)
        .get('/functions/backstage/found')
        .expect('ETag', 'my-hash-123')
        .expect((res) => {
          expect(res.body.hash).to.be.eql('my-hash-123');
        })
        .expect(200, done);
    });
  });
});

describe('DELETE /functions/:namespace/:id', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
  });

  describe('when delete is not sucessfully', () => {
    it('should return 500 error', (done) => {
      request(routes)
        .delete('/functions/backstage/error')
        .expect((res) => {
          expect(res.body.error).to.be.eql('Storage error');
        })
        .expect(500, done);
    });
  });

  describe('when delete is successfully', () => {
    it('should return 204', (done) => {
      request(routes)
        .delete('/functions/backstage/found')
        .expect(204, done);
    });
  });
});

describe('PUT /functions/:namespace/:id/run', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
    routes.set('sandbox', new Sandbox({}));
  });

  describe('when code is found in cache', () => {
    it('should reuse compiled code from storage cache', (done) => {
      request(routes)
        .put('/functions/backstage/cached/run')
        .send({ args: [1, 2] })
        .expect(200, {
          result: 'cached',
          body: { args: [1, 2] },
        }, done);
    });
  });

  describe('when code is found in cache', () => {
    it('should reuse compiled code from storage cache', (done) => {
      request(routes)
        .put('/functions/backstage/send-string/run')
        .send({ args: [1, 2] })
        .expect('content-type', /json/)
        .expect(200, '"this is an alert"', done);
    });
  });

  describe('when code is not found in cache', () => {
    it('should compile code from storage', (done) => {
      request(routes)
        .put('/functions/backstage/fresh/run')
        .send({ args: [3, 4] })
        .expect(200, {
          result: 'fresh',
          body: { args: [3, 4] },
          env: { MY_FOO: 'bar' },
        }, done);
    });
  });
  describe('when code is not found in storage', () => {
    it('should return a 404 error', (done) => {
      request(routes)
        .put('/functions/backstage/not-found/run')
        .send({ args: [] })
        .expect(404, {
          error: 'Code \'backstage/not-found\' is not found',
        }, done);
    });
  });

  describe('when error is found', () => {
    it('should return a 500 error', (done) => {
      request(routes)
        .put('/functions/backstage/error/run')
        .send({ args: [] })
        .expect(500, {
          error: 'Storage error',
        }, done);
    });
  });

  describe('when error with custom status code is found', () => {
    it('should return a custom status code', (done) => {
      request(routes)
        .put('/functions/backstage/customError/run')
        .send({ args: [] })
        .expect(422, {
          error: 'Custom error',
        }, done);
    });
  });
});

describe('PUT /functions/pipeline', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
    routes.set('sandbox', new Sandbox({}));
  });

  describe('when there are no steps', () => {
    it('should return a bad request', (done) => {
      request(routes)
        .put('/functions/pipeline')
        .expect(400, {
          error: 'Pass step by querystring is required',
        }, done);
    });
  });

  describe('when step does not exists', () => {
    it('should return a not found request', (done) => {
      request(routes)
        .put('/functions/pipeline?steps[0]=backstage/not-found')
        .expect(404, {
          error: 'Code \'backstage/not-found\' is not found',
        }, done);
    });
  });

  describe('when step use two steps', () => {
    it('should return a result', (done) => {
      request(routes)
        .put('/functions/pipeline?steps[0]=backstage/step1&steps[1]=backstage/step2')
        .send({ x: 1 })
        .expect(200, { x: 200 }, done);
    });
  });
});

describe('PUT /functions/:namespace/:id/env/:env', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
  });

  describe('when pass a json string on body', () => {
    it('should create an enviroment variable', (done) => {
      request(routes)
        .put('/functions/backstage/correct/env/MY_VAR')
        .set('content-type', 'application/json')
        .send('"MY VALUE"')
        .expect(() => {
          const memoryStorage = routes.get('memoryStorage');
          expect(memoryStorage.lastEnvSet).to.be.eql({
            namespace: 'backstage',
            id: 'correct',
            env: 'MY_VAR',
            value: 'MY VALUE',
          });
        })
        .expect(204, done);
    });
  });

  describe('when the target function it\'s not exist', () => {
    it('should fail the request with 404 error', (done) => {
      request(routes)
        .put('/functions/backstage/not-found/env/MY_VAR')
        .set('content-type', 'application/json')
        .send('"MY VALUE"')
        .expect(404, {
          error: 'Function not found',
        }, done);
    });
  });

  describe('when not pass a json string on body', () => {
    it('should validate', (done) => {
      request(routes)
        .put('/functions/backstage/correct/env/MY_VAR')
        .send('wrong string')
        .expect('Content-Type', /json/)
        .expect(400, {
          error: 'Invalid instance',
          details: [
            'instance is not of a type(s) string',
          ],
        }, done);
    });
  });
});

describe('DELETE /functions/:namespace/:id/env/:env', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
  });

  describe('when sucessfully', () => {
    it('should delete an enviroment variable', (done) => {
      request(routes)
        .delete('/functions/backstage/correct/env/MY_VAR')
        .expect(() => {
          const memoryStorage = routes.get('memoryStorage');
          expect(memoryStorage.lastEnvUnset).to.be.eql({
            namespace: 'backstage',
            id: 'correct',
            env: 'MY_VAR',
          });
        })
        .expect(204, {}, done);
    });
  });

  describe('when the target function it\'s not exist', () => {
    it('should fail the request with 404 error', (done) => {
      request(routes)
        .delete('/functions/backstage/not-found/env/MY_VAR')
        .expect(404, {
          error: 'Function not found',
        }, done);
    });
  });
});

<commit_msg>test/unit/http/routers/FunctionsRouter.test: fix test to run equal in all versions of node<commit_after>const request = require('supertest');
const chai = require('chai');
chai.use(require('chai-string'));

const Sandbox = require('@globocom/backstage-functions-sandbox');

const expect = chai.expect;
const routes = require('../../../../lib/http/routes');
const FakeStorage = require('../../../fakes/FakeStorage');

describe('GET /functions', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
  });

  it('should return namespaces with their functions', (done) => {
    request(routes)
      .get('/functions')
      .expect((res) => {
        expect(res.body.items[0].namespace).to.be.eql('namespace1');
        expect(res.body.items[0].id).to.be.eql('function');
        expect(res.body.items[1].namespace).to.be.eql('namespace2');
        expect(res.body.items[1].id).to.be.eql('function');
        expect(res.body.items[2].namespace).to.be.eql('namespace3');
        expect(res.body.items[2].id).to.be.eql('function');
        expect(res.profile).to.endsWith('/_schemas/functions/list');
      })
      .expect(200, done);
  });

  it('search by namespace', (done) => {
    request(routes)
      .get('/functions?namespace=namespace1')
      .expect('Content-Type', /json/)
      .expect(200, {
        items: [
          { namespace: 'namespace1', id: 'function1' },
          { namespace: 'namespace1', id: 'function2' },
        ],
      }, done);
  });

  it('search by namespace and function id', (done) => {
    request(routes)
      .get('/functions?namespace=namespace1&id=function1')
      .expect('Content-Type', /json/)
      .expect(200, {
        items: [
          { namespace: 'namespace1', id: 'function1' },
        ],
      }, done);
  });

  it('should fail the request with 500 error', (done) => {
    request(routes)
      .get('/functions?namespace=error')
      .expect(500, {
        error: 'Storage error',
      }, done);
  });
});

describe('PUT /functions/:namespace/:id', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
  });

  describe('when code is correct', () => {
    it('should return the code', (done) => {
      const code = 'function main() {}';

      request(routes)
        .put('/functions/backstage/correct')
        .send({ code })
        .expect('Content-Type', /json/)
        .expect(() => {
          const memoryStorage = routes.get('memoryStorage');
          expect(memoryStorage.lastPutCode).to.be.eql({
            id: 'correct',
            hash: 'c177063dc3780c2fe9b4fdc913650e8147c9b8b0',
            code,
          });
        })
        .expect(200, {
          id: 'correct',
          code: 'function main() {}',
          hash: 'c177063dc3780c2fe9b4fdc913650e8147c9b8b0',
        }, done);
    });
  });

  describe('when return any error from storage', () => {
    it('should return the code', (done) => {
      const code = 'function main() {}';

      request(routes)
        .put('/functions/backstage/error')
        .send({ code })
        .expect('Content-Type', /json/)
        .expect(500, {
          error: 'Storage error',
        }, done);
    });
  });

  describe('when code has a syntax error', () => {
    it('should return a error', (done) => {
      request(routes)
        .put('/functions/backstage/invalid')
        .send({ code: '{)' })
        .expect('Content-Type', /application\/json/)
        .expect((res) => {
          expect(res.body.error).to.deep.include('Unexpected token');
          expect(res.body.stack).to.be.equal('');
        })
        .expect(400, done);
    });
  });

  describe('when code has a logic error', () => {
    it('should return a error', (done) => {
      const code = `let a = {};
            function c() {
                a.b();
            };
            c()`;

      request(routes)
        .put('/functions/codes/crazy')
        .send({ code })
        .expect('Content-Type', /json/)
        .expect(400, {
          error: 'TypeError: a.b is not a function',
          stack: 'at c (codes/crazy.js:3)\nat codes/crazy.js:5\nat codes/crazy.js:6',
        }, done);
    });
  });

  describe('when code has a timeout error', () => {
    it('should return a error', (done) => {
      const code = 'while(1) {};';

      request(routes)
        .put('/functions/codes/timeout')
        .send({ code })
        .expect('Content-Type', /json/)
        .expect((res) => {
          expect(res.body.error).to.include('Error: Script execution timed out');
        })
        .expect(400, done);
    });
  });

  describe('when code is not a string', () => {
    it('should return a error', (done) => {
      const code = { wrong: 'yes' };

      request(routes)
        .put('/functions/codes/invalid')
        .send({ code })
        .expect('Content-Type', /^application\/json/)
        .expect(400, {
          error: 'Invalid instance',
          details: [
            'instance.code is not of a type(s) string',
          ],
        }, done);
    });
  });
});

describe('GET /functions/:namespace/:id', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
  });

  describe('when code is not found', () => {
    it('should return 404 error', (done) => {
      request(routes)
        .get('/functions/backstage/not-found')
        .expect((res) => {
          expect(res.body.error).to.be.eql('Code not found');
        })
        .expect(404, done);
    });
  });

  describe('when code is found', () => {
    it('should return the code', (done) => {
      request(routes)
        .get('/functions/backstage/found')
        .expect('ETag', 'my-hash-123')
        .expect((res) => {
          expect(res.body.hash).to.be.eql('my-hash-123');
        })
        .expect(200, done);
    });
  });
});

describe('DELETE /functions/:namespace/:id', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
  });

  describe('when delete is not sucessfully', () => {
    it('should return 500 error', (done) => {
      request(routes)
        .delete('/functions/backstage/error')
        .expect((res) => {
          expect(res.body.error).to.be.eql('Storage error');
        })
        .expect(500, done);
    });
  });

  describe('when delete is successfully', () => {
    it('should return 204', (done) => {
      request(routes)
        .delete('/functions/backstage/found')
        .expect(204, done);
    });
  });
});

describe('PUT /functions/:namespace/:id/run', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
    routes.set('sandbox', new Sandbox({}));
  });

  describe('when code is found in cache', () => {
    it('should reuse compiled code from storage cache', (done) => {
      request(routes)
        .put('/functions/backstage/cached/run')
        .send({ args: [1, 2] })
        .expect(200, {
          result: 'cached',
          body: { args: [1, 2] },
        }, done);
    });
  });

  describe('when code is found in cache', () => {
    it('should reuse compiled code from storage cache', (done) => {
      request(routes)
        .put('/functions/backstage/send-string/run')
        .send({ args: [1, 2] })
        .expect('content-type', /json/)
        .expect(200, '"this is an alert"', done);
    });
  });

  describe('when code is not found in cache', () => {
    it('should compile code from storage', (done) => {
      request(routes)
        .put('/functions/backstage/fresh/run')
        .send({ args: [3, 4] })
        .expect(200, {
          result: 'fresh',
          body: { args: [3, 4] },
          env: { MY_FOO: 'bar' },
        }, done);
    });
  });
  describe('when code is not found in storage', () => {
    it('should return a 404 error', (done) => {
      request(routes)
        .put('/functions/backstage/not-found/run')
        .send({ args: [] })
        .expect(404, {
          error: 'Code \'backstage/not-found\' is not found',
        }, done);
    });
  });

  describe('when error is found', () => {
    it('should return a 500 error', (done) => {
      request(routes)
        .put('/functions/backstage/error/run')
        .send({ args: [] })
        .expect(500, {
          error: 'Storage error',
        }, done);
    });
  });

  describe('when error with custom status code is found', () => {
    it('should return a custom status code', (done) => {
      request(routes)
        .put('/functions/backstage/customError/run')
        .send({ args: [] })
        .expect(422, {
          error: 'Custom error',
        }, done);
    });
  });
});

describe('PUT /functions/pipeline', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
    routes.set('sandbox', new Sandbox({}));
  });

  describe('when there are no steps', () => {
    it('should return a bad request', (done) => {
      request(routes)
        .put('/functions/pipeline')
        .expect(400, {
          error: 'Pass step by querystring is required',
        }, done);
    });
  });

  describe('when step does not exists', () => {
    it('should return a not found request', (done) => {
      request(routes)
        .put('/functions/pipeline?steps[0]=backstage/not-found')
        .expect(404, {
          error: 'Code \'backstage/not-found\' is not found',
        }, done);
    });
  });

  describe('when step use two steps', () => {
    it('should return a result', (done) => {
      request(routes)
        .put('/functions/pipeline?steps[0]=backstage/step1&steps[1]=backstage/step2')
        .send({ x: 1 })
        .expect(200, { x: 200 }, done);
    });
  });
});

describe('PUT /functions/:namespace/:id/env/:env', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
  });

  describe('when pass a json string on body', () => {
    it('should create an enviroment variable', (done) => {
      request(routes)
        .put('/functions/backstage/correct/env/MY_VAR')
        .set('content-type', 'application/json')
        .send('"MY VALUE"')
        .expect(() => {
          const memoryStorage = routes.get('memoryStorage');
          expect(memoryStorage.lastEnvSet).to.be.eql({
            namespace: 'backstage',
            id: 'correct',
            env: 'MY_VAR',
            value: 'MY VALUE',
          });
        })
        .expect(204, done);
    });
  });

  describe('when the target function it\'s not exist', () => {
    it('should fail the request with 404 error', (done) => {
      request(routes)
        .put('/functions/backstage/not-found/env/MY_VAR')
        .set('content-type', 'application/json')
        .send('"MY VALUE"')
        .expect(404, {
          error: 'Function not found',
        }, done);
    });
  });

  describe('when not pass a json string on body', () => {
    it('should validate', (done) => {
      request(routes)
        .put('/functions/backstage/correct/env/MY_VAR')
        .send('wrong string')
        .expect('Content-Type', /json/)
        .expect(400, {
          error: 'Invalid instance',
          details: [
            'instance is not of a type(s) string',
          ],
        }, done);
    });
  });
});

describe('DELETE /functions/:namespace/:id/env/:env', () => {
  before(() => {
    routes.set('memoryStorage', new FakeStorage());
  });

  describe('when sucessfully', () => {
    it('should delete an enviroment variable', (done) => {
      request(routes)
        .delete('/functions/backstage/correct/env/MY_VAR')
        .expect(() => {
          const memoryStorage = routes.get('memoryStorage');
          expect(memoryStorage.lastEnvUnset).to.be.eql({
            namespace: 'backstage',
            id: 'correct',
            env: 'MY_VAR',
          });
        })
        .expect(204, {}, done);
    });
  });

  describe('when the target function it\'s not exist', () => {
    it('should fail the request with 404 error', (done) => {
      request(routes)
        .delete('/functions/backstage/not-found/env/MY_VAR')
        .expect(404, {
          error: 'Function not found',
        }, done);
    });
  });
});

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import $ from 'jquery'
import _ from 'underscore'
import React from 'react'
import StudentContextTray from './StudentContextTray'
import {client, ApolloProvider, Query, gql} from '../canvas-apollo'

const SCC_QUERY = gql`
  query StudentContextCard($courseId: ID!, $studentId: ID!) {
    course: legacyNode(type: Course, _id: $courseId) {
      ... on Course {
        _id
        name
        permissions {
          become_user: becomeUser
          manage_grades: manageGrades
          send_messages: sendMessages
          view_all_grades: viewAllGrades
          view_analytics: viewAnalytics
        }
        submissionsConnection(
          first: 10
          orderBy: [{field: gradedAt, direction: descending}]
          studentIds: [$studentId]
        ) {
          edges {
            submission: node {
              id
              score
              grade
              excused
              user {
                _id
              }
              assignment {
                name
                html_url: htmlUrl
                points_possible: pointsPossible
              }
            }
          }
        }
      }
    }
    user: legacyNode(type: User, _id: $studentId) {
      ... on User {
        _id
        short_name: shortName
        avatar_url: avatarUrl
        enrollments(courseId: $courseId) {
          last_activity_at: lastActivityAt
          section {
            name
          }
          grades {
            current_grade: currentGrade
            current_score: currentScore
          }
        }
        analytics: summaryAnalytics(courseId: $courseId) {
          page_views: pageViews {
            total
            max
            level
          }
          participations {
            total
            max
            level
          }
          tardiness_breakdown: tardinessBreakdown {
            late
            missing
            on_time: onTime
          }
        }
      }
    }
  }
`

export default props => {
  return (
    <ApolloProvider client={client}>
      <Query query={SCC_QUERY} variables={{courseId: props.courseId, studentId: props.studentId}}>
        {({data, loading}) => {
          const {course, user} = data
          return <StudentContextTray data={{loading, course, user}} {...props} />
        }}
      </Query>
    </ApolloProvider>
  )
}
<commit_msg>use new course field for context cards<commit_after>/*
 * Copyright (C) 2018 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import $ from 'jquery'
import _ from 'underscore'
import React from 'react'
import StudentContextTray from './StudentContextTray'
import {client, ApolloProvider, Query, gql} from '../canvas-apollo'

const SCC_QUERY = gql`
  query StudentContextCard($courseId: ID!, $studentId: ID!) {
    course(id: $courseId) {
      _id
      name
      permissions {
        become_user: becomeUser
        manage_grades: manageGrades
        send_messages: sendMessages
        view_all_grades: viewAllGrades
        view_analytics: viewAnalytics
      }
      submissionsConnection(
        first: 10
        orderBy: [{field: gradedAt, direction: descending}]
        studentIds: [$studentId]
      ) {
        edges {
          submission: node {
            id
            score
            grade
            excused
            user {
              _id
            }
            assignment {
              name
              html_url: htmlUrl
              points_possible: pointsPossible
            }
          }
        }
      }
    }
    user: legacyNode(type: User, _id: $studentId) {
      ... on User {
        _id
        short_name: shortName
        avatar_url: avatarUrl
        enrollments(courseId: $courseId) {
          last_activity_at: lastActivityAt
          section {
            name
          }
          grades {
            current_grade: currentGrade
            current_score: currentScore
          }
        }
        analytics: summaryAnalytics(courseId: $courseId) {
          page_views: pageViews {
            total
            max
            level
          }
          participations {
            total
            max
            level
          }
          tardiness_breakdown: tardinessBreakdown {
            late
            missing
            on_time: onTime
          }
        }
      }
    }
  }
`

export default props => {
  return (
    <ApolloProvider client={client}>
      <Query query={SCC_QUERY} variables={{courseId: props.courseId, studentId: props.studentId}}>
        {({data, loading}) => {
          const {course, user} = data
          return <StudentContextTray data={{loading, course, user}} {...props} />
        }}
      </Query>
    </ApolloProvider>
  )
}
<|endoftext|>


<commit_before>var daemonize = function (method, period, reinitializer) {
	var
		delayedFunction = null,
		keepRunning = true,
		postStop = null;

	if (typeof method !== 'function') {
		throw new TypeError('Argument 0 (Method) should be a function');
	}

	if (typeof period !== 'number') {
		throw new TypeError('Argument 1 (Period) should be a number');
	}

	if (!reinitalizer && typeof reinitializer !== 'function') {
		throw new TypeError('Argument 2 (Method) should be a function');
	}

	reinitializer = reinitializer || function () {};

	return {
		start: function () {
			var me = this;
			if (keepRunning) {
				postStop = null;
				method();
				delayedFunction = setTimeout(me.start, period);
			} else {
				if (postStop) {
					setTimeout(postStop(), period);
				}
			}
		},
		stop: function () {
			keepRunning = false;
			if (delayedFunction) cancelTimeout(delayedFunction);
		},
		restart: function () {
			var me = this;
			if (!keepRunning) {
				me.start();
			} else {
				postStop = function () {
					reinitializer();
					keepRunning = true;
					me.start();
				};
				me.stop();
			}
		},
		status: function () {
			return keepRunning;
		}
	};
};<commit_msg>Formatting<commit_after>var daemonize = function ( method, period, reinitializer ) {
		var
			delayedFunction = null,
			keepRunning = true,
			postStop = null;

		if ( typeof method !== 'function' ) {
			throw new TypeError( 'Argument 0 ( Method ) should be a function' );
		}

		if ( typeof period !== 'number' ) {
			throw new TypeError( 'Argument 1 ( Period ) should be a number' );
		}

		if ( !reinitalizer && typeof reinitializer !== 'function' ) {
			throw new TypeError( 'Argument 2 ( Method ) should be a function' );
		}

		reinitializer = reinitializer || function () {};

		return {
			start: function () {
				var me = this;
				if ( keepRunning ) {
					postStop = null;
					method();
					delayedFunction = setTimeout( me.start, period );
				} else {
					if ( postStop ) {
						setTimeout( postStop(), period );
					}
				}
			},
			stop: function () {
				keepRunning = false;
				if ( delayedFunction ) cancelTimeout( delayedFunction );
			},
			restart: function () {
				var me = this;
				if ( !keepRunning ) {
					me.start();
				} else {
					postStop = function () {
						reinitializer();
						keepRunning = true;
						me.start();
					};
					me.stop();
				}
			},
			status: function () {
				return keepRunning;
			}
		};
	};<|endoftext|>


<commit_before>const kuzzleWrapperInjector = require('inject!../../../../src/services/kuzzleWrapper')

let sandbox = sinon.sandbox.create()

describe('Kuzzle wrapper service', () => {
  describe('performSearch tests', () => {
    let triggerError = true
    let fakeResponse = {
      total: 42,
      documents: [{
        content: {
          name: {
            first: 'toto'
          }
        },
        id: 'id'
      }]
    }
    let responseWithAdditionalAttr = {
      documents: [{
        content: {name: {first: 'toto'}},
        id: 'id',
        additionalAttribute: {name: 'name.first', value: 'toto'}
      }],
      total: 42
    }
    let kuzzleWrapper

    beforeEach(() => {
      kuzzleWrapper = kuzzleWrapperInjector({
        './kuzzle': {
          dataCollectionFactory () {
            return {
              advancedSearch (filters, cb) {
                if (triggerError) {
                  cb(new Error('error'))
                } else {
                  cb(null, fakeResponse)
                }
              }
            }
          }
        }
      })
    })

    it('should reject a promise as there is no collection nor index', (done) => {
      kuzzleWrapper.performSearch()
        .then(() => {})
        .catch(err => {
          expect(err.message).to.equals('Missing collection or index')
          done()
        })
    })

    it('should reject a promise', (done) => {
      kuzzleWrapper.performSearch('collection', 'index')
        .then(() => {})
        .catch(e => {
          expect(e.message).to.equals('error')
          done()
        })
    })

    it('should receive documents', (done) => {
      triggerError = false
      kuzzleWrapper.performSearch('collection', 'index')
        .then(res => {
          expect(res).to.deep.equals(fakeResponse)
          done()
        }).catch(() => {})
    })

    it('should receive sorted documents with additional attributes for the sort array', (done) => {
      triggerError = false
      kuzzleWrapper.performSearch('collection', 'index', {}, {}, [{'name.first': 'asc'}])
        .then(res => {
          expect(res).to.deep.equals(responseWithAdditionalAttr)
          done()
        }).catch(() => {})
    })
  })

  describe('deleteDocuments tests', () => {
    let triggerError = true
    let kuzzleWrapper

    beforeEach(() => {
      kuzzleWrapper = kuzzleWrapperInjector({
        './kuzzle': {
          dataCollectionFactory () {
            return {
              deleteDocument (filters, cb) {
                if (triggerError) {
                  cb(new Error('error'))
                } else {
                  cb(null)
                }
              }
            }
          },
          refreshIndex (index, cb) {
            cb()
          }
        }
      })
    })

    it('should do nothing if there is no ids nor index and collection', () => {
      kuzzleWrapper.deleteDocuments()
    })

    it('should reject a promise', (done) => {
      kuzzleWrapper.deleteDocuments('index', 'collection', [42])
        .then(() => {})
        .catch(e => {
          expect(e.message).to.equals('error')
          done()
        })
    })

    it('should delete a document and refresh the index, then resolve a promise', (done) => {
      triggerError = false
      kuzzleWrapper.deleteDocuments('index', 'collection', [42])
        .then(() => {
          done()
        })
    })
  })

  describe('isConnected', () => {
    let kuzzleWrapper
    let removeListener = sandbox.stub()

    it('should resolve if kuzzle is connected', (done) => {
      kuzzleWrapper = kuzzleWrapperInjector({
        './kuzzle': {
          state: 'connected'
        }
      })

      kuzzleWrapper.isConnected()
        .then(() => done())
        .catch(e => done(e))
    })

    it('should resolve if kuzzle trigger event connected', (done) => {
      kuzzleWrapper = kuzzleWrapperInjector({
        './kuzzle': {
          state: 'connecting',
          addListener (event, cb) {
            cb()
          },
          removeListener
        }
      })

      kuzzleWrapper.isConnected()
        .then(() => {
          expect(removeListener.called).to.be.equal(true)
          done()
        })
        .catch(e => done(e))
    })

    it('should reject if kuzzle never trigger event connected', (done) => {
      kuzzleWrapper = kuzzleWrapperInjector({
        './kuzzle': {
          state: 'connecting',
          addListener: sandbox.stub(),
          removeListener
        }
      })

      kuzzleWrapper.isConnected(10)
        .then(() => {
          done(new Error('Promise was resolved'))
        })
        .catch(() => done())
    })
  })

  describe('initStoreWithKuzzle', () => {
    let kuzzleWrapper
    let removeAllListeners = sandbox.stub()
    let setConnection = sandbox.stub()
    let setTokenValid = sandbox.stub()
    let setKuzzleHostPort = sandbox.stub()

    it('should call removeListeners and addListeners with right params', () => {
      kuzzleWrapper = kuzzleWrapperInjector({
        './kuzzle': {
          host: 'toto',
          wsPort: 8888,
          state: 'connecting',
          addListener (event, cb) {
            cb()
          },
          removeAllListeners
        },
        '../vuex/modules/common/kuzzle/actions': {
          setConnection,
          setKuzzleHostPort
        },
        '../vuex/modules/auth/actions': {
          setTokenValid
        }
      })

      let store = {store: 'mystore'}
      kuzzleWrapper.initStoreWithKuzzle(store)

      expect(setKuzzleHostPort.calledWith(store, 'toto', 8888)).to.be.equal(true)

      expect(removeAllListeners.calledWith('jwtTokenExpired'))
      expect(removeAllListeners.calledWith('disconnected'))
      expect(removeAllListeners.calledWith('reconnected'))

      expect(setTokenValid.calledWithMatch(store, false))
      expect(setConnection.calledWithMatch(store, true))
      expect(setConnection.calledWithMatch(store, false))
    })
  })
})

<commit_msg>fix catch error in unit test<commit_after>const kuzzleWrapperInjector = require('inject!../../../../src/services/kuzzleWrapper')

let sandbox = sinon.sandbox.create()

describe('Kuzzle wrapper service', () => {
  describe('performSearch tests', () => {
    let triggerError = true
    let fakeResponse = {
      total: 42,
      documents: [{
        content: {
          name: {
            first: 'toto'
          }
        },
        id: 'id'
      }]
    }
    let responseWithAdditionalAttr = {
      documents: [{
        content: {name: {first: 'toto'}},
        id: 'id',
        additionalAttribute: {name: 'name.first', value: 'toto'}
      }],
      total: 42
    }
    let kuzzleWrapper

    beforeEach(() => {
      kuzzleWrapper = kuzzleWrapperInjector({
        './kuzzle': {
          dataCollectionFactory () {
            return {
              advancedSearch (filters, cb) {
                if (triggerError) {
                  cb(new Error('error'))
                } else {
                  cb(null, fakeResponse)
                }
              }
            }
          }
        }
      })
    })

    it('should reject a promise as there is no collection nor index', (done) => {
      kuzzleWrapper.performSearch()
        .then(() => {})
        .catch(err => {
          expect(err.message).to.equals('Missing collection or index')
          done()
        })
    })

    it('should reject a promise', (done) => {
      kuzzleWrapper.performSearch('collection', 'index')
        .then(() => {})
        .catch(e => {
          expect(e.message).to.equals('error')
          done()
        })
    })

    it('should receive documents', (done) => {
      triggerError = false
      kuzzleWrapper.performSearch('collection', 'index')
        .then(res => {
          expect(res).to.deep.equals(fakeResponse)
          done()
        })
        .catch((e) => done(e))
    })

    it('should receive sorted documents with additional attributes for the sort array', (done) => {
      triggerError = false
      kuzzleWrapper.performSearch('collection', 'index', {}, {}, [{'name.first': 'asc'}])
        .then(res => {
          expect(res).to.deep.equals(responseWithAdditionalAttr)
          done()
        }).catch(() => {})
    })
  })

  describe('deleteDocuments tests', () => {
    let triggerError = true
    let kuzzleWrapper

    beforeEach(() => {
      kuzzleWrapper = kuzzleWrapperInjector({
        './kuzzle': {
          dataCollectionFactory () {
            return {
              deleteDocument (filters, cb) {
                if (triggerError) {
                  cb(new Error('error'))
                } else {
                  cb(null)
                }
              }
            }
          },
          refreshIndex (index, cb) {
            cb()
          }
        }
      })
    })

    it('should do nothing if there is no ids nor index and collection', () => {
      kuzzleWrapper.deleteDocuments()
    })

    it('should reject a promise', (done) => {
      kuzzleWrapper.deleteDocuments('index', 'collection', [42])
        .then(() => {})
        .catch(e => {
          expect(e.message).to.equals('error')
          done()
        })
    })

    it('should delete a document and refresh the index, then resolve a promise', (done) => {
      triggerError = false
      kuzzleWrapper.deleteDocuments('index', 'collection', [42])
        .then(() => {
          done()
        })
    })
  })

  describe('isConnected', () => {
    let kuzzleWrapper
    let removeListener = sandbox.stub()

    it('should resolve if kuzzle is connected', (done) => {
      kuzzleWrapper = kuzzleWrapperInjector({
        './kuzzle': {
          state: 'connected'
        }
      })

      kuzzleWrapper.isConnected()
        .then(() => done())
        .catch(e => done(e))
    })

    it('should resolve if kuzzle trigger event connected', (done) => {
      kuzzleWrapper = kuzzleWrapperInjector({
        './kuzzle': {
          state: 'connecting',
          addListener (event, cb) {
            cb()
          },
          removeListener
        }
      })

      kuzzleWrapper.isConnected()
        .then(() => {
          expect(removeListener.called).to.be.equal(true)
          done()
        })
        .catch(e => done(e))
    })

    it('should reject if kuzzle never trigger event connected', (done) => {
      kuzzleWrapper = kuzzleWrapperInjector({
        './kuzzle': {
          state: 'connecting',
          addListener: sandbox.stub(),
          removeListener
        }
      })

      kuzzleWrapper.isConnected(10)
        .then(() => {
          done(new Error('Promise was resolved'))
        })
        .catch(() => done())
    })
  })

  describe('initStoreWithKuzzle', () => {
    let kuzzleWrapper
    let removeAllListeners = sandbox.stub()
    let setConnection = sandbox.stub()
    let setTokenValid = sandbox.stub()
    let setKuzzleHostPort = sandbox.stub()

    it('should call removeListeners and addListeners with right params', () => {
      kuzzleWrapper = kuzzleWrapperInjector({
        './kuzzle': {
          host: 'toto',
          wsPort: 8888,
          state: 'connecting',
          addListener (event, cb) {
            cb()
          },
          removeAllListeners
        },
        '../vuex/modules/common/kuzzle/actions': {
          setConnection,
          setKuzzleHostPort
        },
        '../vuex/modules/auth/actions': {
          setTokenValid
        }
      })

      let store = {store: 'mystore'}
      kuzzleWrapper.initStoreWithKuzzle(store)

      expect(setKuzzleHostPort.calledWith(store, 'toto', 8888)).to.be.equal(true)

      expect(removeAllListeners.calledWith('jwtTokenExpired'))
      expect(removeAllListeners.calledWith('disconnected'))
      expect(removeAllListeners.calledWith('reconnected'))

      expect(setTokenValid.calledWithMatch(store, false))
      expect(setConnection.calledWithMatch(store, true))
      expect(setConnection.calledWithMatch(store, false))
    })
  })
})

<|endoftext|>