<commit_before>import { errors } from 'arsenal';

import collectCorsHeaders from '../utilities/collectCorsHeaders';
import collectResponseHeaders from '../utilities/collectResponseHeaders';
import services from '../services';
import validateHeaders from '../utilities/validateHeaders';
import { pushMetric } from '../utapi/utilities';

/**
 * HEAD Object - Same as Get Object but only respond with headers
 *(no actual body)
 * @param {AuthInfo} authInfo - Instance of AuthInfo class with requester's info
 * @param {object} request - normalized request object
 * @param {object} log - Werelogs logger
 * @param {function} callback - callback to function in route
 * @return {undefined}
 *
 */
export default function objectHead(authInfo, request, log, callback) {
    log.debug('processing request', { method: 'objectHead' });
    const bucketName = request.bucketName;
    const objectKey = request.objectKey;
    const metadataValParams = {
        authInfo,
        bucketName,
        objectKey,
        requestType: 'objectHead',
        log,
    };

    return services.metadataValidateAuthorization(metadataValParams,
        (err, bucket, objMD) => {
            const corsHeaders = collectCorsHeaders(request.headers.origin,
                request.method, bucket);
            if (err) {
                log.debug('error processing request', {
                    error: err,
                    method: 'metadataValidateAuthorization',
                });
                return callback(err, corsHeaders);
            }
            if (!objMD) {
                return callback(errors.NoSuchKey, corsHeaders);
            }
            const headerValResult = validateHeaders(objMD, request.headers);
            if (headerValResult.error) {
                return callback(headerValResult.error, corsHeaders);
            }
            const responseMetaHeaders = collectResponseHeaders(objMD,
                corsHeaders);
            pushMetric('headObject', log, {
                authInfo,
                bucket: bucketName,
            });
            return callback(null, responseMetaHeaders);
        });
}
<commit_msg>ft: versioning objectHead<commit_after>import { errors } from 'arsenal';

import { decryptVersionId } from './apiUtils/object/versioning';
import collectCorsHeaders from '../utilities/collectCorsHeaders';
import collectResponseHeaders from '../utilities/collectResponseHeaders';
import validateHeaders from '../utilities/validateHeaders';
import { pushMetric } from '../utapi/utilities';
import { getVersionIdResHeader } from './apiUtils/object/versioning';
import { metadataValidateBucketAndObj } from
'../metadata/metadataUtils';

/**
 * HEAD Object - Same as Get Object but only respond with headers
 *(no actual body)
 * @param {AuthInfo} authInfo - Instance of AuthInfo class with requester's info
 * @param {object} request - normalized request object
 * @param {object} log - Werelogs logger
 * @param {function} callback - callback to function in route
 * @return {undefined}
 *
 */
export default function objectHead(authInfo, request, log, callback) {
    log.debug('processing request', { method: 'objectHead' });
    const bucketName = request.bucketName;
    const objectKey = request.objectKey;

    const decryptVidResult = decryptVersionId(request.query);
    if (decryptVidResult instanceof Error) {
        log.trace('invalid versionId query', {
            versionId: request.query.versionId,
            error: decryptVidResult,
        });
        return callback(decryptVidResult);
    }
    const versionId = decryptVidResult;

    const mdValParams = {
        authInfo,
        bucketName,
        objectKey,
        versionId,
        requestType: 'objectHead',
    };

    return metadataValidateBucketAndObj(mdValParams, log,
        (err, bucket, objMD) => {
            const corsHeaders = collectCorsHeaders(request.headers.origin,
                request.method, bucket);
            if (err) {
                log.debug('error validating request', {
                    error: err,
                    method: 'objectHead',
                });
                return callback(err, corsHeaders);
            }
            if (!objMD) {
                const err = versionId ? errors.NoSuchVersion : errors.NoSuchKey;
                return callback(err, corsHeaders);
            }
            const verCfg = bucket.getVersioningConfiguration();
            if (objMD.isDeleteMarker) {
                const responseHeaders = Object.assign({},
                    { 'x-amz-delete-marker': true }, corsHeaders);
                if (!versionId) {
                    return callback(errors.NoSuchKey, responseHeaders);
                }
                // return MethodNotAllowed if requesting a specific
                // version that has a delete marker
                responseHeaders['x-amz-version-id'] =
                    getVersionIdResHeader(verCfg, objMD);
                return callback(errors.MethodNotAllowed, responseHeaders);
            }
            const headerValResult = validateHeaders(objMD, request.headers);
            if (headerValResult.error) {
                return callback(headerValResult.error, corsHeaders);
            }
            const responseHeaders =
                collectResponseHeaders(objMD, corsHeaders, verCfg);
            pushMetric('headObject', log, { authInfo, bucket: bucketName });
            return callback(null, responseHeaders);
        });
}
<|endoftext|>


<commit_before>const log = function(t) {
  process.stdout.write(t + '\n');
};

import {should} from 'chai';
should();

import MultiAvatar, {FacebookAvatarProvider, GoogleAvatarProvider} from '../src/';

describe('Provider', function () {
  describe('#facebook', function () {
    it('should return only facebook picture URL', () => {

      return MultiAvatar([
        new FacebookAvatarProvider(100008343750912)
      ])
      .withSize(64)
      .then(function (value) {
        value.should.have.all.keys(['facebook']);
        value.facebook.should.be.a('string')
          .and.have.string('100008343750912');
      });

    });

    it('should return multiple avatar urls for different sizes', () => {

      return MultiAvatar([
        new FacebookAvatarProvider('100008343750912')
      ])
      .withSizes([64, 128])
      .then(function (value) {
        value.should.have.all.keys(['facebook']);
        value.facebook.should.have.all.keys(['64', '128']);
      });

    });
  });

  const googleAvatarProvider = new GoogleAvatarProvider('116933859726289749306');
  describe('#google', function() {
    it('should fetch google picture url by API and return avatar successfully', () => {
      this.timeout(5000);

      return MultiAvatar([
        googleAvatarProvider
      ])
      .withSize(256)
      .then(function (value) {
        value.should.have.all.keys(['google']);
        value.google.should.be.a('string')
          .and.have.string('s256');
      });

    });

    it('should contain cached url', () => {
      googleAvatarProvider.should.have.property('pictureUrl');
      googleAvatarProvider.pictureUrl.should.be.a('string')
        .and.have.string('s64');
    });

    it('should return avatar by url in cache immediately', () => {
      this.timeout(50);

      return MultiAvatar([
        googleAvatarProvider
      ])
      .withSize(512)
      .then(function (value) {
        value.should.have.all.keys(['google']);
        value.google.should.be.a('string')
          .and.have.string('s512');
      });

    });

    it('should return multiple pictures in the same time (or less) as it fetching url from API first time', () => {
      return MultiAvatar([
        new GoogleAvatarProvider('116933859726289749306')
      ])
      .withSizes([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
      .then(function (value) {
        value.should.have.all.keys(['google']);
        value.google.should.have.all.keys(['10', '20', '30', '40', '50', '60', '70', '80', '90', '100']);

      })
    });

  });

});
<commit_msg>Updated tests<commit_after>import chai, { should } from 'chai';
import spies from 'chai-spies';
chai.use(spies);
should();

import MultiAvatar, {FacebookAvatarProvider, GoogleAvatarProvider} from '../src/';

describe('Provider', function () {
  describe('#facebook', function () {
    it('should return only facebook picture URL', () => {

      return MultiAvatar([
        new FacebookAvatarProvider(100008343750912)
      ])
      .withSize(64)
      .then(function (value) {
        value.should.have.all.keys(['facebook']);
        value.facebook.should.be.a('string')
          .and.have.string('100008343750912');
      });

    });

    it('should return multiple avatar urls for different sizes', () => {

      return MultiAvatar([
        new FacebookAvatarProvider('100008343750912')
      ])
      .withSizes([64, 128])
      .then(function (value) {
        value.should.have.all.keys(['facebook']);
        value.facebook.should.have.all.keys(['64', '128']);
      });

    });
  });

  const googleAvatarProvider = new GoogleAvatarProvider('116933859726289749306');
  const googleAvatarProviderSpy = chai.spy.on(googleAvatarProvider, 'avatar');
  describe('#google', function() {
    it('should fetch google picture url by API and return avatar successfully', () => {
      this.timeout(5000);

      return MultiAvatar([
        googleAvatarProvider
      ])
      .withSize(256)
      .then(function (value) {
        value.should.have.all.keys(['google']);
        value.google.should.be.a('string')
          .and.have.string('s256');
        googleAvatarProviderSpy.should.have.been.called.once();
      });

    });

    it('should contain cached url', () => {
      googleAvatarProvider.should.have.property('pictureUrl');
      googleAvatarProvider.pictureUrl.should.be.a('string')
        .and.have.string('s64');
    });

    it('should return avatar by url in cache immediately', () => {
      this.timeout(50);

      return MultiAvatar([
        googleAvatarProvider
      ])
      .withSize(512)
      .then(function (value) {
        value.should.have.all.keys(['google']);
        value.google.should.be.a('string')
          .and.have.string('s512');
      });

    });

    it('should return multiple pictures in the same time (or less) as it fetching url from API first time', () => {
      return MultiAvatar([
        new GoogleAvatarProvider('116933859726289749306')
      ])
      .withSizes([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
      .then(function (value) {
        value.should.have.all.keys(['google']);
        value.google.should.have.all.keys(['10', '20', '30', '40', '50', '60', '70', '80', '90', '100']);

      })
    });

  });

});
<|endoftext|>


<commit_before>'use strict';
const path = require('path');
const express = require('express');
const request = require('supertest');

module.exports = function(router, {httpMethod, uri}, viewEngineStub) {
    const app = express();

    if (viewEngineStub) {
        viewEngineStub.callsArgWith(2, '');
        app.engine('ejs', viewEngineStub);
        app.set('views', path.join(__dirname, '..', 'backend', 'pages'));
        app.set('view engine', 'ejs');
    }
    app.use(router);

    return request(app)[httpMethod](uri);
};
<commit_msg>fixed unit tests<commit_after>'use strict';
const path = require('path');
const express = require('express');
const request = require('supertest');

module.exports = function(router, {httpMethod, uri}, viewEngineStub) {
    const app = express();

    if (viewEngineStub) {
        viewEngineStub.callsArgWith(2, '');
        app.engine('ejs', viewEngineStub);
        app.set('views', path.join(__dirname, '..', 'backend', 'pages'));
        app.set('view engine', 'ejs');
    }
    app.use((req, res, next) => {
        // to bypass login
        req.session = {};
        req.user = {};
        next();
    });
    app.use(router);

    return request(app)[httpMethod](uri);
};
<|endoftext|>


<commit_before>/* eslint-env node, mocha, jasmine */
import React, { Component, PropTypes } from 'react'
import _ from 'lodash'
import createMemoryHistory from 'react-router/lib/createMemoryHistory'
import { routerMiddleware, syncHistoryWithStore, routerActions, routerReducer } from 'react-router-redux'
import { Router, Route } from 'react-router'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware, combineReducers } from 'redux'
import sinon from 'sinon'
import { mount } from 'enzyme'

import { UserAuthWrapper } from '../src'

import { userLoggedOut, userLoggedIn, userLoggingIn, authSelector, userReducer, UnprotectedComponent, UnprotectedParentComponent, defaultConfig } from './helpers'
import baseTests from './base-test'

class App extends Component {
  static propTypes = {
    children: PropTypes.node
  };

  render() {
    return (

        {this.props.children}

    )
  }
}

const setupReactRouter3Test = (testRoutes) => {
  const history = createMemoryHistory()
  const rootReducer = combineReducers({ user: userReducer })
  const store = createStore(rootReducer)
  const routes = (
    <Route path="/" component={App}>
      {testRoutes.map((route, i) => <Route key={i} {...route} />)}
    </Route>
  )

  const wrapper = mount(
    <Provider store={store}>
      <Router history={history} >
        {routes}
      </Router>
    </Provider>
  )

  const getLocation = history.getCurrentLocation

  return {
    history,
    store,
    wrapper,
    getLocation
  }
}

const setupReactRouterReduxTest = (testRoutes) => {
  const baseHistory = createMemoryHistory()
  const middleware = routerMiddleware(baseHistory)
  const rootReducer = combineReducers({ user: userReducer, routing: routerReducer })
  const routes = (
    <Route path="/" component={App}>
      {testRoutes.map((route, i) => <Route key={i} {...route} />)}
    </Route>
  )

  const store = createStore(
    rootReducer,
    applyMiddleware(middleware)
  )
  const history = syncHistoryWithStore(baseHistory, store)

  const wrapper = mount(
    <Provider store={store}>
      <Router history={history} >
        {routes}
      </Router>
    </Provider>
  )

  const getLocation = history.getCurrentLocation

  return {
    history,
    store,
    wrapper,
    getLocation
  }
}

const getRouteParams = (ownProps) => ownProps.routeParams

baseTests(setupReactRouter3Test, 'React Router V3', getRouteParams)

describe('UserAuthWrapper React Router V3 Additions', () => {

  it('provides an onEnter static function', () => {
    let store
    const connect = (fn) => (nextState, replaceState) => fn(store, nextState, replaceState)
    const authSelectorSpy = sinon.spy(authSelector)
    const authenticatingSelectorSpy = sinon.spy(state => state.user.isAuthenticating)
    const failureRedirectSpy = sinon.spy(() => '/login')

    const UserIsAuthenticatedOnEnter = UserAuthWrapper({
      authSelector: authSelectorSpy,
      authenticatingSelector: authenticatingSelectorSpy,
      failureRedirectPath: failureRedirectSpy
    })

    const routesOnEnter = [
      { path: 'login', component: UnprotectedComponent },
      { path: 'onEnter', component: UnprotectedComponent, onEnter: connect(UserIsAuthenticatedOnEnter.onEnter) }
    ]

    const { history, store: createdStore, wrapper, getLocation } = setupReactRouter3Test(routesOnEnter)
    store = createdStore

    expect(getLocation().pathname).to.equal('/')
    expect(getLocation().search).to.equal('')

    // Supports isAuthenticating
    store.dispatch(userLoggingIn())
    history.push('/onEnter')
    const nextState = _.pick(wrapper.find(App).props(), [ 'location', 'params', 'routes' ])
    const storeState = store.getState()
    expect(authSelectorSpy.calledOnce).to.be.true
    // Passes store and nextState down to selectors and failureRedirectPath
    expect(authSelectorSpy.calledOnce).to.be.true
    expect(authSelectorSpy.firstCall.args).to.deep.equal([ storeState, nextState ])
    expect(authenticatingSelectorSpy.calledOnce).to.be.true
    expect(authenticatingSelectorSpy.firstCall.args).to.deep.equal([ storeState, nextState ])
    expect(getLocation().pathname).to.equal('/onEnter')

    // Redirects when not authorized
    store.dispatch(userLoggedOut())
    // Have to force re-check because wont recheck with store changes
    history.push('/')
    history.push('/onEnter')
    expect(authenticatingSelectorSpy.calledTwice).to.be.true
    expect(authSelectorSpy.calledTwice).to.be.true
    expect(failureRedirectSpy.calledOnce).to.be.true
    expect(failureRedirectSpy.firstCall.args[0].user).to.deep.equal(store.getState().user) // cant compare location because its changed
    expect(Object.keys(failureRedirectSpy.firstCall.args[1])).to.deep.equal([ 'routes', 'params', 'location' ]) // cant compare location because its changed
    expect(getLocation().pathname).to.equal('/login')
    expect(getLocation().search).to.equal('?redirect=%2FonEnter')
  })

  it('supports nested routes', () => {
    const auth = UserAuthWrapper(defaultConfig)

    const routes = [
      { path: 'login', component: UnprotectedComponent },
      { path: 'parent', component: auth(UnprotectedParentComponent), childRoutes: [
          { path: 'child', component: auth(UnprotectedComponent) }
      ] }
    ]

    const { history, store, getLocation } = setupReactRouter3Test(routes)

    history.push('/parent/child')
    expect(getLocation().pathname).to.equal('/login')
    expect(getLocation().search).to.equal('?redirect=%2Fparent%2Fchild')

    store.dispatch(userLoggedIn())

    history.push('/parent/child')
    expect(getLocation().pathname).to.equal('/parent/child')
    expect(getLocation().query).to.be.empty

    store.dispatch(userLoggedOut())
    expect(getLocation().pathname).to.equal('/login')
    expect(getLocation().search).to.equal('?redirect=%2Fparent%2Fchild')
  })

  it('redirects with react router redux', () => {
    const auth = UserAuthWrapper({
      ...defaultConfig,
      redirectAction: routerActions.replace
    })
    const routes = [
      { path: 'login', component: UnprotectedComponent },
      { path: 'auth', component: auth(UnprotectedComponent) }
    ]

    const { history, getLocation } = setupReactRouterReduxTest(routes)

    expect(getLocation().pathname).to.equal('/')
    expect(getLocation().search).to.equal('')
    history.push('/auth')
    expect(getLocation().pathname).to.equal('/login')
    expect(getLocation().search).to.equal('?redirect=%2Fauth')
  })
})
<commit_msg>Update rrv3 tests, only left out onEnter<commit_after>/* eslint-env node, mocha, jasmine */
import React, { Component, PropTypes } from 'react'
import _ from 'lodash'
import createMemoryHistory from 'react-router/lib/createMemoryHistory'
import { routerMiddleware, syncHistoryWithStore, routerActions, routerReducer } from 'react-router-redux'
import { Router, Route } from 'react-router'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware, combineReducers } from 'redux'
import sinon from 'sinon'
import { mount } from 'enzyme'

import { userLoggedOut, userLoggedIn, userLoggingIn, authSelector, userReducer, UnprotectedComponent, UnprotectedParentComponent, defaultConfig } from './helpers'
import baseTests from './base-test'

import { connectedRouterRedirect, connectedReduxRedirect } from '../src/history3/redirect'

class App extends Component {
  static propTypes = {
    children: PropTypes.node
  };

  render() {
    return (

        {this.props.children}

    )
  }
}

const setupReactRouter3Test = (testRoutes) => {
  const history = createMemoryHistory()
  const rootReducer = combineReducers({ user: userReducer })
  const store = createStore(rootReducer)
  const routes = (
    <Route path="/" component={App}>
      {testRoutes.map((route, i) => <Route key={i} {...route} />)}
    </Route>
  )

  const wrapper = mount(
    <Provider store={store}>
      <Router history={history} >
        {routes}
      </Router>
    </Provider>
  )

  const getLocation = history.getCurrentLocation

  return {
    history,
    store,
    wrapper,
    getLocation
  }
}

const setupReactRouterReduxTest = (testRoutes) => {
  const baseHistory = createMemoryHistory()
  const middleware = routerMiddleware(baseHistory)
  const rootReducer = combineReducers({ user: userReducer, routing: routerReducer })
  const routes = (
    <Route path="/" component={App}>
      {testRoutes.map((route, i) => <Route key={i} {...route} />)}
    </Route>
  )

  const store = createStore(
    rootReducer,
    applyMiddleware(middleware)
  )
  const history = syncHistoryWithStore(baseHistory, store)

  const wrapper = mount(
    <Provider store={store}>
      <Router history={history} >
        {routes}
      </Router>
    </Provider>
  )

  const getLocation = history.getCurrentLocation

  return {
    history,
    store,
    wrapper,
    getLocation
  }
}

const getRouteParams = (ownProps) => ownProps.routeParams
const getQueryParams = (location) => location.query

baseTests(setupReactRouter3Test, 'React Router V3', getRouteParams, getQueryParams, connectedRouterRedirect)

describe('UserAuthWrapper React Router V3 Additions', () => {

  /**
  it('provides an onEnter static function', () => {
    let store
    const connect = (fn) => (nextState, replaceState) => fn(store, nextState, replaceState)
    const authSelectorSpy = sinon.spy(authSelector)
    const authenticatingSelectorSpy = sinon.spy(state => state.user.isAuthenticating)
    const failureRedirectSpy = sinon.spy(() => '/login')

    const UserIsAuthenticatedOnEnter = UserAuthWrapper({
      authSelector: authSelectorSpy,
      authenticatingSelector: authenticatingSelectorSpy,
      failureRedirectPath: failureRedirectSpy
    })

    const routesOnEnter = [
      { path: 'login', component: UnprotectedComponent },
      { path: 'onEnter', component: UnprotectedComponent, onEnter: connect(UserIsAuthenticatedOnEnter.onEnter) }
    ]

    const { history, store: createdStore, wrapper, getLocation } = setupReactRouter3Test(routesOnEnter)
    store = createdStore

    expect(getLocation().pathname).to.equal('/')
    expect(getLocation().search).to.equal('')

    // Supports isAuthenticating
    store.dispatch(userLoggingIn())
    history.push('/onEnter')
    const nextState = _.pick(wrapper.find(App).props(), [ 'location', 'params', 'routes' ])
    const storeState = store.getState()
    expect(authSelectorSpy.calledOnce).to.be.true
    // Passes store and nextState down to selectors and failureRedirectPath
    expect(authSelectorSpy.calledOnce).to.be.true
    expect(authSelectorSpy.firstCall.args).to.deep.equal([ storeState, nextState ])
    expect(authenticatingSelectorSpy.calledOnce).to.be.true
    expect(authenticatingSelectorSpy.firstCall.args).to.deep.equal([ storeState, nextState ])
    expect(getLocation().pathname).to.equal('/onEnter')

    // Redirects when not authorized
    store.dispatch(userLoggedOut())
    // Have to force re-check because wont recheck with store changes
    history.push('/')
    history.push('/onEnter')
    expect(authenticatingSelectorSpy.calledTwice).to.be.true
    expect(authSelectorSpy.calledTwice).to.be.true
    expect(failureRedirectSpy.calledOnce).to.be.true
    expect(failureRedirectSpy.firstCall.args[0].user).to.deep.equal(store.getState().user) // cant compare location because its changed
    expect(Object.keys(failureRedirectSpy.firstCall.args[1])).to.deep.equal([ 'routes', 'params', 'location' ]) // cant compare location because its changed
    expect(getLocation().pathname).to.equal('/login')
    expect(getLocation().search).to.equal('?redirect=%2FonEnter')
  })
  **/

  it('supports nested routes', () => {
    const auth = connectedRouterRedirect(defaultConfig)

    const routes = [
      { path: 'login', component: UnprotectedComponent },
      { path: 'parent', component: auth(UnprotectedParentComponent), childRoutes: [
          { path: 'child', component: auth(UnprotectedComponent) }
      ] }
    ]

    const { history, store, getLocation } = setupReactRouter3Test(routes)

    history.push('/parent/child')
    expect(getLocation().pathname).to.equal('/login')
    expect(getLocation().search).to.equal('?redirect=%2Fparent%2Fchild')

    store.dispatch(userLoggedIn())

    history.push('/parent/child')
    expect(getLocation().pathname).to.equal('/parent/child')
    expect(getLocation().query).to.be.empty

    store.dispatch(userLoggedOut())
    expect(getLocation().pathname).to.equal('/login')
    expect(getLocation().search).to.equal('?redirect=%2Fparent%2Fchild')
  })

  it('redirects with react router redux', () => {
    const auth = connectedReduxRedirect({
      ...defaultConfig,
      redirectAction: routerActions.replace
    })
    const routes = [
      { path: 'login', component: UnprotectedComponent },
      { path: 'auth', component: auth(UnprotectedComponent) }
    ]

    const { history, getLocation } = setupReactRouterReduxTest(routes)

    expect(getLocation().pathname).to.equal('/')
    expect(getLocation().search).to.equal('')
    history.push('/auth')
    expect(getLocation().pathname).to.equal('/login')
    expect(getLocation().search).to.equal('?redirect=%2Fauth')
  })
})
<|endoftext|>


<commit_before>/*global describe, it, assert */

(function () {
	'use strict';
    describe('App loaded', function () {
        describe('Are dependencies available?', function () {
            it('should have jQuery, moment, twix, time, bible.math, ics, blob, filesaver available', function () {
                assert.ok($().jquery, 'jQuery not loaded');
                assert.ok(moment, 'moment not loaded');
                assert.ok(moment.twix, 'twix not loaded');
                assert.ok(time, 'time not loaded');
                assert.ok(bible, 'bible not loaded');
                assert.ok(ics, 'ics not loaded');
                assert.ok(Blob, 'ics not loaded');
                assert.ok(saveas, 'ics not loaded');
            });
        });
    });

    describe('Sequence parsing', function () {
        describe('Test each item in a sequence by parsing', function () {
            it('should have no errors', function () {
				var p = ["backtothebiblechronological.json", "esvchroniclesandprophets.json", "esvpsalmsandwisdomliterature.json", "esvgospelsandepistles.json", "esvpentateuchandhistoryofisrael.json", "esveverydayinword.json", "esvliterarystudybible.json", "esvthroughthebible.json", "heartlightotandnt.json", "mcheyne.json", "oneyearchronological.json"];

				for (var x = p.length - 1; x >= 0; x--) {
					planner.load(p[x], '/bower_components/readingplans');
					for (var i = planner.sequence.data.length - 1; i >= 0; i--) {
						var a = bible.parseReference(planner.sequence.data[i]);
						// if (a.bookIndex === -1 ) console.error('invalid reference: ' + planner.sequence.data[i] + ' key: ' + i + ' sequence: ' + planner.sequence.name + ' previous ref: ' + planner.sequence.data[i-1]);
						assert.notEqual(a.bookIndex, -1, planner.sequence.data[i].toString() + ' failed to parse. Object of ' + JSON.stringify(a));
					};
				};

            });
        });
    });

})();
<commit_msg>Fix test<commit_after>/*global describe, it, assert */

(function () {
	'use strict';
    describe('App loaded', function () {
        describe('Are dependencies available?', function () {
            it('should have jQuery, moment, twix, time, bible.math, ics, blob, filesaver available', function () {
                assert.ok($().jquery, 'jQuery not loaded');
                assert.ok(moment, 'moment not loaded');
                assert.ok(moment.twix, 'twix not loaded');
                assert.ok(time, 'time not loaded');
                assert.ok(bible, 'bible not loaded');
                assert.ok(ics, 'ics not loaded');
                assert.ok(Blob, 'ics not loaded');
                assert.ok(saveAs, 'ics not loaded');
            });
        });
    });

    describe('Sequence parsing', function () {
        describe('Test each item in a sequence by parsing', function () {
            it('should have no errors', function () {
				var p = ["backtothebiblechronological.json", "esvchroniclesandprophets.json", "esvpsalmsandwisdomliterature.json", "esvgospelsandepistles.json", "esvpentateuchandhistoryofisrael.json", "esveverydayinword.json", "esvliterarystudybible.json", "esvthroughthebible.json", "heartlightotandnt.json", "mcheyne.json", "oneyearchronological.json"];

				for (var x = p.length - 1; x >= 0; x--) {
					planner.load(p[x], '/bower_components/readingplans');
					for (var i = planner.sequence.data.length - 1; i >= 0; i--) {
						var a = bible.parseReference(planner.sequence.data[i]);
						// if (a.bookIndex === -1 ) console.error('invalid reference: ' + planner.sequence.data[i] + ' key: ' + i + ' sequence: ' + planner.sequence.name + ' previous ref: ' + planner.sequence.data[i-1]);
						assert.notEqual(a.bookIndex, -1, planner.sequence.data[i].toString() + ' failed to parse. Object of ' + JSON.stringify(a));
					};
				};

            });
        });
    });

})();
<|endoftext|>


<commit_before>/**
 * @title ID DataWeb Verification Workflow
 * @overview Verify your user's identity in 180+ countries with ID DataWeb's adaptive Verification Workflows.
 * @gallery true
 * @category marketplace
 *
 * This configuration allows you to add an ID DataWeb verification workflow to the user’s first time login experience. This will allow your organization to ensure the user is really who they claim to be, aligning with KYC/AML requirements, and mitigating fraud attempts.
 *
 */

function iddatawebVerificationWorkflow(user, context, callback) {
  const { Auth0RedirectRuleUtilities } = require("@auth0/rule-utilities@0.1.0");

  const ruleUtils = new Auth0RedirectRuleUtilities(
    user,
    context,
    configuration
  );

  const {
    IDDATAWEB_BASE_URL,
    IDDATAWEB_CLIENT_ID,
    IDDATAWEB_CLIENT_SECRET,
    IDDATAWEB_LOG_JWT,
    IDDATAWEB_ALWAYS_VERIFY,
    IDDATAWEB_PREFILL_ATTRIBUTES,
  } = configuration;

  const idwTokenEndpoint = `${IDDATAWEB_BASE_URL}/axn/oauth2/token`;
  const idwAuthorizeEndpoint = `${IDDATAWEB_BASE_URL}/axn/oauth2/authorize`;
  const auth0ContinueUrl = `https://${context.request.hostname}/continue`;

  // initialize app metadata
  user.app_metadata = user.app_metadata || {};
  user.app_metadata.iddataweb = user.app_metadata.iddataweb || {};

  // if the user is already verified and we don't need to check, exit
  if (
    user.app_metadata.iddataweb.verificationResult === "verified" &&
    IDDATAWEB_ALWAYS_VERIFY === "off"
  ) {
    console.log("user " + user.user_id + " has been previously verified.");
    return callback(null, user, context);
  }

  // if coming back from redirect - get token, make policy decision, and update user metadata.
  if (ruleUtils.isRedirectCallback) {
    console.log("code from IDW: " + ruleUtils.queryParams.code);

    let options = {
      method: "POST",
      url: idwTokenEndpoint,
      headers: {
        "Cache-Control": "no-cache",
        Authorization:
          "Basic " +
          Buffer.from(
            IDDATAWEB_CLIENT_ID + ":" + IDDATAWEB_CLIENT_SECRET
          ).toString("base64"),
        "Content-Type": "application/x-www-form-urlencoded",
      },
      form: {
        grant_type: "authorization_code",
        code: ruleUtils.queryParams.code,
        redirect_uri: auth0ContinueUrl,
      },
    };

    request(options, function (error, response, body) {
      if (error) {
        return callback(error);
      }

      let decodedToken;
      try {
        decodedToken = jwt.decode(JSON.parse(body).id_token);
      } catch (tokenError) {
        return callback(tokenError);
      }

      //check issuer, audience and experiation of ID DataWeb Token
      if (
        decodedToken.iss !== IDDATAWEB_BASE_URL ||
        decodedToken.aud !== IDDATAWEB_CLIENT_ID
      ) {
        console.log("issue with JWT validation.");
        return callback(error);
      }

      console.log("policy decision: " + decodedToken.policyDecision);
      console.log("score: " + decodedToken.idwTrustScore);
      console.log("IDW transaction ID: " + decodedToken.jti);

      if (IDDATAWEB_LOG_JWT === "on") {
        console.log(JSON.stringify(decodedToken));
      }

      // once verification is complete, update user's metadata in Auth0.
      //this could be used for downstream application authorization,
      //or mapping access to levels of assurance.
      user.app_metadata.iddataweb.verificationResult = {
        policyDecision: decodedToken.policyDecision,
        transactionid: decodedToken.jti,
        iat: decodedToken.iat,
      };
      auth0.users
        .updateAppMetadata(user.user_id, user.app_metadata)
        .then(function () {
          //include ID DataWeb results in Auth0 ID Token
          const namespace = "https://iddataweb.com/";
          context.idToken[namespace + "policyDecision"] =
            decodedToken.policyDecision;
          context.idToken[namespace + "transactionId"] = decodedToken.jti;
          context.idToken[namespace + "iat"] = decodedToken.iat;
          return callback(null, user, context);
        })
        .catch(function (err) {
          return callback(err);
        });
    });
  }

  // ... otherwise, redirect for verification.

  let idwRedirectUrl =
    idwAuthorizeEndpoint +
    "?client_id=" +
    IDDATAWEB_CLIENT_ID +
    "&redirect_uri=" +
    auth0ContinueUrl +
    "&scope=openid+country.US&response_type=code";

  // build and sign JWT and include in /auth request to ID DataWeb.
  if (IDDATAWEB_PREFILL_ATTRIBUTES === "on") {
    const prefillToken = jwt.sign(
      {
        sub: user.email,
        credential: user.email,
        email: user.email,
        fname: user.given_name,
        lname: user.family_name,
        phone: user.phone_number,
      },
      IDDATAWEB_CLIENT_SECRET,
      { expiresIn: "1h" }
    );

    idwRedirectUrl += `&login_hint=${prefillToken}`;
  }

  if (ruleUtils.canRedirect) {
    context.redirect = {
      url: idwRedirectUrl,
    };
  }

  return callback(null, user, context);
}
<commit_msg>Swap in axios for HTTP requests<commit_after>/**
 * @title ID DataWeb Verification Workflow
 * @overview Verify your user's identity in 180+ countries with ID DataWeb's adaptive Verification Workflows.
 * @gallery true
 * @category marketplace
 *
 * This configuration allows you to add an ID DataWeb verification workflow to the user’s first time login experience. This will allow your organization to ensure the user is really who they claim to be, aligning with KYC/AML requirements, and mitigating fraud attempts.
 *
 */

async function iddatawebVerificationWorkflow(user, context, callback) {
  const { Auth0RedirectRuleUtilities } = require("@auth0/rule-utilities@0.1.0");
  const axiosClient = require("axios@0.19.2");
  const url = require("url");

  const ruleUtils = new Auth0RedirectRuleUtilities(
    user,
    context,
    configuration
  );

  const {
    IDDATAWEB_BASE_URL,
    IDDATAWEB_CLIENT_ID,
    IDDATAWEB_CLIENT_SECRET,
    IDDATAWEB_LOG_JWT,
    IDDATAWEB_ALWAYS_VERIFY,
    IDDATAWEB_PREFILL_ATTRIBUTES,
  } = configuration;

  const idwBasicAuth = Buffer.from(
    IDDATAWEB_CLIENT_ID + ":" + IDDATAWEB_CLIENT_SECRET
  ).toString("base64");

  const idwTokenNamepsace = "https://iddataweb.com/";
  const idwTokenEndpoint = `${IDDATAWEB_BASE_URL}/axn/oauth2/token`;
  const idwAuthorizeEndpoint = `${IDDATAWEB_BASE_URL}/axn/oauth2/authorize`;
  const auth0ContinueUrl = `https://${context.request.hostname}/continue`;

  // initialize app metadata
  user.app_metadata = user.app_metadata || {};
  user.app_metadata.iddataweb = user.app_metadata.iddataweb || {};

  // if the user is already verified and we don't need to check, exit
  if (
    user.app_metadata.iddataweb.verificationResult === "verified" &&
    IDDATAWEB_ALWAYS_VERIFY === "off"
  ) {
    console.log("user " + user.user_id + " has been previously verified.");
    return callback(null, user, context);
  }

  // if coming back from redirect - get token, make policy decision, and update user metadata.
  if (ruleUtils.isRedirectCallback) {
    console.log("code from IDW: " + ruleUtils.queryParams.code);

    const formParams = new url.URLSearchParams({
      grant_type: "authorization_code",
      code: ruleUtils.queryParams.code,
      redirect_uri: auth0ContinueUrl,
    });

    const headers = {
      "Content-Type": "application/x-www-form-urlencoded",
      "Cache-Control": "no-cache",
      Authorization: `Basic ${idwBasicAuth}`,
    };

    let decodedToken;
    try {
      const tokenResponse = await axiosClient.post(
        idwTokenEndpoint,
        formParams.toString(),
        { headers }
      );
      decodedToken = jwt.decode(JSON.parse(tokenResponse.data).id_token);
    } catch (error) {
      return callback(error);
    }

    //check issuer, audience and experiation of ID DataWeb Token
    if (
      decodedToken.iss !== IDDATAWEB_BASE_URL ||
      decodedToken.aud !== IDDATAWEB_CLIENT_ID
    ) {
      console.log("ID token invalid.");
      return callback(error);
    }

    console.log("policy decision: " + decodedToken.policyDecision);
    console.log("score: " + decodedToken.idwTrustScore);
    console.log("IDW transaction ID: " + decodedToken.jti);

    if (IDDATAWEB_LOG_JWT === "on") {
      console.log(JSON.stringify(decodedToken));
    }

    // once verification is complete, update user's metadata in Auth0.
    //this could be used for downstream application authorization,
    //or mapping access to levels of assurance.
    user.app_metadata.iddataweb.verificationResult = {
      policyDecision: decodedToken.policyDecision,
      transactionid: decodedToken.jti,
      iat: decodedToken.iat,
    };

    try {
      auth0.users.updateAppMetadata(user.user_id, user.app_metadata);
    } catch (error) {
      return callback(err);
    }

    //include ID DataWeb results in Auth0 ID Token
    context.idToken[idwTokenNamepsace + "policyDecision"] =
      decodedToken.policyDecision;
    context.idToken[idwTokenNamepsace + "transactionId"] = decodedToken.jti;
    context.idToken[idwTokenNamepsace + "iat"] = decodedToken.iat;

    return callback(null, user, context);
  }

  // ... otherwise, redirect for verification.

  let idwRedirectUrl =
    idwAuthorizeEndpoint +
    "?client_id=" +
    IDDATAWEB_CLIENT_ID +
    "&redirect_uri=" +
    auth0ContinueUrl +
    "&scope=openid+country.US&response_type=code";

  // build and sign JWT and include in /auth request to ID DataWeb.
  if (IDDATAWEB_PREFILL_ATTRIBUTES === "on") {
    const prefillToken = jwt.sign(
      {
        sub: user.email,
        credential: user.email,
        email: user.email,
        fname: user.given_name,
        lname: user.family_name,
        phone: user.phone_number,
      },
      IDDATAWEB_CLIENT_SECRET,
      { expiresIn: "1h" }
    );

    idwRedirectUrl += `&login_hint=${prefillToken}`;
  }

  if (ruleUtils.canRedirect) {
    context.redirect = {
      url: idwRedirectUrl,
    };
  }

  return callback(null, user, context);
}
<|endoftext|>


<commit_before>$(function(){
  $('#search-result').hide();
  $('#search-no-result').hide();
  $('#search-loading').hide();
  $("#calculate-submit-info").hide();

  $("#task_name").change(function(){
    Calculate.task_name = $(this).val();
  });

  $("#task_notes").change(function(){
    Calculate.task_notes = $(this).val();
  });
});

//model choice
$(function () {
    $('.model-args').hide();
    $('.tree li:has(ul)').addClass('parent_li').find(' > span');
    $('.tree li.parent_li > span').on('click', function (e) {
        var children = $(this).parent('li.parent_li').find(' > ul > li');
        if (children.is(":visible")) {
            children.hide();
            $(this).find(' > i').addClass('glyphicon-plus-sign').removeClass('glyphicon-minus-sign');
        } else {
            children.show();
            $(this).find(' > i').addClass('glyphicon-minus-sign').removeClass('glyphicon-plus-sign');
        }
        e.stopPropagation();
    });

    $('.checkbox').click(function(){
      var model_args = $('#' + $(this).attr('model') + '_args');
      if($(this).find('input[type=checkbox]').is(':checked')){
        model_args.hide();
      }else{
        model_args.show();
      }
    });
});

function update_model(){
  Calculate.models = [];
  $(".checkbox").each(function(){
    var model = $(this).attr("model");
    var temperature = "#temperature_" + model;

    if($(this).find('input[type=checkbox]').is(':checked')){
      var data = {'model':model,
                 'temperature':$(temperature).val()};
      Calculate.models.push(data);
    }
  });
}

//chem structure draw
$(function(){
  $('#draw_btn').click(function(){
    var chem_iframe = $("#chemwriter_iframe");
    chemwriter_iframe.window.get_chem_draw_content();
    Calculate.draw_mol_data = chem_iframe.contents().find('#data').html();
    console.log(Calculate.draw_mol);
    $(this).text("已添加").addClass("btn-danger");
  });

  $("#upload_update").click(function(){
    Calculate.files = [];

    $("#files_table tr").each(function(trindex, tritem){
      $(tritem).find("td").each(function(tdindex, tditem){
        if($(tditem).attr("class") === "name")
          {
            Calculate.files[trindex] = $(tditem).children().attr("fid");
          }
      });
    });

    console.log(Calculate.files);
    $(this).text("文件添加完毕!")
           .toggleClass("btn-danger").toggleClass("btn-info");

  });
});

$('#calculate-submit-btn').click(function(){
  update_model();

  if (!(Calculate.smile || Calculate.draw_mol_data || Calculate.files)){
      $("#calculate-submit-info").show().text("至少选择一种输入方式!");
      return;
  }

  if (Calculate.task_name.length == 0){
      $("#calculate-submit-info").show().text("请输入计算任务名称!");
      return;
  }

  if (Calculate.task_notes == 0){
      $("#calculate-submit-info").show().text("请输入计算任务描述!");
      return;
  }

  if (Calculate.models.length == 0){
      $("#calculate-submit-info").show().text("请至少选择一种计算模型!");
      return;
  }

  var data = {
          "smile":Calculate.smile,
          "draw_mol_data":Calculate.draw_mol_data,
          "task_notes":Calculate.task_notes,
          "task_name":Calculate.task_name,
          "files_id_list":JSON.stringify(Calculate.files),
          "models":JSON.stringify(Calculate.models),
         };

  console.log(data);

  var url = '/api/task-submit/';

  $.post(url, data).done(function(content){
    if(content.status){
      window.location.href="/history/";
    }else{
      $("#calculate-submit-info").show().text(content.info);
    }
  });
});

$('#search-btn').click(function(){
  var data = {"cas":$("#query_input_cas").val(),
              "smile":$("#query_input_smile").val(),
              "common_name_en":$("#query_input_common_name_en").val(),
              "common_name_ch":$("#query_input_common_name_ch").val()}

  var url = "/api/smile-search/";

  $('#search-loading').show();

  $.post(url, data).done(function(content){
    var element = "#search-smile-content";
    $("#search-loading").hide();

    if(content.length !== 0){
      $("#search-result").show();
      $("#search-no-result").hide();
      $(element).find("tbody").html("");
      $.each(content, function(k,v){
        var row = "
"+ v.cas +"	"+
                  v.formula + "	" +
                  v.commonname + "	" +
                  v.smiles + "	" +
                  v.alogp + "	"+
                  "选择
";
        $(element).find("tbody").append(row);
      });

      $(".search-select").click(function(){
        var td = this.parentNode.parentNode;
        var smile = $(td).children(".smile").text();

        Calculate.smile = smile;
        console.log(smile);

        $(".search-content").removeClass("danger");
        $(".search-select").text('选择');
        $(td).addClass("danger");
        $(this).text('已选择');

      });
    }else{
      $("#search-result").hide();
      $("#search-no-result").show();
    }
  });
});
<commit_msg>fix calcaulte name and desc bug<commit_after>$(function(){
  $('#search-result').hide();
  $('#search-no-result').hide();
  $('#search-loading').hide();
  $("#calculate-submit-info").hide();
});

//model choice
$(function () {
    $('.model-args').hide();
    $('.tree li:has(ul)').addClass('parent_li').find(' > span');
    $('.tree li.parent_li > span').on('click', function (e) {
        var children = $(this).parent('li.parent_li').find(' > ul > li');
        if (children.is(":visible")) {
            children.hide();
            $(this).find(' > i').addClass('glyphicon-plus-sign').removeClass('glyphicon-minus-sign');
        } else {
            children.show();
            $(this).find(' > i').addClass('glyphicon-minus-sign').removeClass('glyphicon-plus-sign');
        }
        e.stopPropagation();
    });

    $('.checkbox').click(function(){
      var model_args = $('#' + $(this).attr('model') + '_args');
      if($(this).find('input[type=checkbox]').is(':checked')){
        model_args.hide();
      }else{
        model_args.show();
      }
    });
});

function update_model(){
  Calculate.models = [];
  $(".checkbox").each(function(){
    var model = $(this).attr("model");
    var temperature = "#temperature_" + model;

    if($(this).find('input[type=checkbox]').is(':checked')){
      var data = {'model':model,
                 'temperature':$(temperature).val()};
      Calculate.models.push(data);
    }
  });
}

//chem structure draw
$(function(){
  $('#draw_btn').click(function(){
    var chem_iframe = $("#chemwriter_iframe");
    chemwriter_iframe.window.get_chem_draw_content();
    Calculate.draw_mol_data = chem_iframe.contents().find('#data').html();
    console.log(Calculate.draw_mol);
    $(this).text("已添加").addClass("btn-danger");
  });

  $("#upload_update").click(function(){
    Calculate.files = [];

    $("#files_table tr").each(function(trindex, tritem){
      $(tritem).find("td").each(function(tdindex, tditem){
        if($(tditem).attr("class") === "name")
          {
            Calculate.files[trindex] = $(tditem).children().attr("fid");
          }
      });
    });

    console.log(Calculate.files);
    $(this).text("文件添加完毕!")
           .toggleClass("btn-danger").toggleClass("btn-info");

  });
});

$('#calculate-submit-btn').click(function(){
  Calculate.task_name = $("#task_name").val();
  Calculate.task_notes = $("#task_notes").val();
  update_model();

  if (!(Calculate.smile || Calculate.draw_mol_data || Calculate.files)){
      $("#calculate-submit-info").show().text("至少选择一种输入方式!");
      return;
  }

  if (Calculate.task_name.length == 0){
      $("#calculate-submit-info").show().text("请输入计算任务名称!");
      return;
  }

  if (Calculate.task_notes == 0){
      $("#calculate-submit-info").show().text("请输入计算任务描述!");
      return;
  }

  if (Calculate.models.length == 0){
      $("#calculate-submit-info").show().text("请至少选择一种计算模型!");
      return;
  }

  var data = {
          "smile":Calculate.smile,
          "draw_mol_data":Calculate.draw_mol_data,
          "task_notes":Calculate.task_notes,
          "task_name":Calculate.task_name,
          "files_id_list":JSON.stringify(Calculate.files),
          "models":JSON.stringify(Calculate.models),
         };

  console.log(data);

  var url = '/api/task-submit/';

  $.post(url, data).done(function(content){
    if(content.status){
      window.location.href="/history/";
    }else{
      $("#calculate-submit-info").show().text(content.info);
    }
  });
});

$('#search-btn').click(function(){
  var data = {"cas":$("#query_input_cas").val(),
              "smile":$("#query_input_smile").val(),
              "common_name_en":$("#query_input_common_name_en").val(),
              "common_name_ch":$("#query_input_common_name_ch").val()}

  var url = "/api/smile-search/";

  $('#search-loading').show();

  $.post(url, data).done(function(content){
    var element = "#search-smile-content";
    $("#search-loading").hide();

    if(content.length !== 0){
      $("#search-result").show();
      $("#search-no-result").hide();
      $(element).find("tbody").html("");
      $.each(content, function(k,v){
        var row = "
"+ v.cas +"	"+
                  v.formula + "	" +
                  v.commonname + "	" +
                  v.smiles + "	" +
                  v.alogp + "	"+
                  "选择
";
        $(element).find("tbody").append(row);
      });

      $(".search-select").click(function(){
        var td = this.parentNode.parentNode;
        var smile = $(td).children(".smile").text();

        Calculate.smile = smile;
        console.log(smile);

        $(".search-content").removeClass("danger");
        $(".search-select").text('选择');
        $(td).addClass("danger");
        $(this).text('已选择');

      });
    }else{
      $("#search-result").hide();
      $("#search-no-result").show();
    }
  });
});
<|endoftext|>


<commit_before>require([
  "./test-help",
  "./test-indexable-codemirror",
  "./test-parsing-codemirror",
  "./test-mark-tracker",
  "./test-live-preview",
  "./test-publisher"
], function() {
  QUnit.start();
});
<commit_msg>fixed weird race condition in unit test suite.<commit_after>require([
  "./test-help",
  "./test-indexable-codemirror",
  "./test-parsing-codemirror",
  "./test-mark-tracker",
  "./test-live-preview",
  "./test-publisher"
], function() {
  if (QUnit.config.blocking)
    QUnit.config.autostart = true;
  else
    QUnit.start();
});
<|endoftext|>


<commit_before>"use strict";

var all_tests_pass = true,
    fs = require("fs"),
    p = require("path"),
    my_lzma,
    lzma_norm = require("../src/lzma_worker" + (process.argv[2] === "unmin" ? "" : "-min") + ".js").LZMA,
    lzma_sep = {
        decompress: require("../src/lzma-d" + (process.argv[2] === "unmin" ? "" : "-min") + ".js").LZMA.decompress,
        compress:   require("../src/lzma-c" + (process.argv[2] === "unmin" ? "" : "-min") + ".js").LZMA.compress,
    },
    path_to_files = "files";

function display_result(str, pass) {
    ///NOTE: \u001B[32m makes green text.
    ///      \u001B[31m makes red text.
    ///      \u001B[0m  resets the text color.
    console.log("\u001B[3" + (pass ? "2" : "1") + "m" + str + "\u001B[0m");
}

function progress(percent)
{
    if (process.stdout.isTTY) {
        process.stdout.clearLine();
        process.stdout.cursorTo(0);
        if (percent > 0 && percent < 1) {
            process.stdout.write((percent * 100).toFixed(2) + "%");
        }
    }
}

function decompression_test(compressed_file, correct_filename, next) {
    fs.readFile(correct_filename, function (err, correct_buffer) {

        if (err) {
            console.log("Cannot open " + correct_filename);
            throw new Error(err);
        }

        fs.readFile(compressed_file, function (err, buffer) {
            var deco_start;

            if (err) {
                throw err;
            }

            deco_start = (new Date()).getTime();
            try {
                my_lzma.decompress(buffer, function (result) {
                    var deco_speed = (new Date()).getTime() - deco_start,
                        correct_result;

                    console.log("Decompressed size:", result.length);

                    if (typeof result === "string") {
                        correct_result = correct_buffer.toString();
                    } else {
                        correct_result = JSON.stringify(correct_buffer);
                        result = JSON.stringify(result);
                    }
                    if (correct_result !== result) {
                        display_result("ERROR: files do not match!", false);
                        console.log();
                        all_tests_pass = false;
                    } else {
                        display_result("Test passed", true);
                    }

                    console.log("Decompression time:", deco_speed);

                    console.log();
                    next();
                }, progress);
            } catch (e) {
                if (p.basename(correct_filename) === "error-" + e.detailMessage) {
                    display_result("Test passed", true);
                    console.log("threw correct error: " + e.detailMessage);
                } else {
                    display_result("ERROR: " + e.detailMessage, false);
                    all_tests_pass = false;
                }
                console.log();
                next();
            }
        });
    });
}

function compression_test(file, next) {
    fs.readFile(file, "utf8", function (err, content) {
        var comp_start = (new Date()).getTime(),
            compression_mode = 1,
            match;

        if (err) {
            throw err;
        }

        match = p.basename(file, p.extname(file)).match(/^level[ _](\d)/i)

        if (match) {
            compression_mode = Number(match[1]) || 1
        }

        console.log("     Initial size:", content.length);
        my_lzma.compress(content, compression_mode, function ondone(result) {
            var comp_speed = (new Date()).getTime() - comp_start,
                deco_start;

            console.log("  Compressed size:", result.length);

            deco_start = (new Date()).getTime();
            my_lzma.decompress(result, function (result) {
                var deco_speed = (new Date()).getTime() - deco_start;
                console.log("Decompressed size:", result.length);

                if (content !== result) {
                    display_result("ERROR: files do not match!", false);
                    console.log();
                    all_tests_pass = false;
                } else {
                    display_result("Test passed", true);
                }

                console.log("  Compression time:", comp_speed);
                console.log("Decompression time:", deco_speed);

                console.log();
                next();
            }, progress);
        }, progress);
    });
}

function run_tests(cb)
{
    fs.readdir(path_to_files, function (err, files) {
        var file_count = files.length;

        if (err) {
            throw err;
        }

        (function run_test(i) {
            var file;

            if (i >= file_count) {
                if (all_tests_pass) {
                    display_result("All tests completed sucessfully", true);
                } else {
                    display_result("An error was detected!", false);
                }

                return cb ? cb(all_tests_pass) : 0;
            }
            file = files[i];

            console.log(file);

            if (file.slice(-5) === ".lzma") {
                /// Preform a decompress test on *.lzma files.
                decompression_test(p.join(path_to_files, file), p.join(path_to_files, file.slice(0, -5)), function next()
                {
                    run_test(i + 1);
                });
            } else {
                /// Preform a compression/decompression test.
                compression_test(p.join(path_to_files, file), function next()
                {
                    run_test(i + 1);
                });
            }
        }(0));
    });
}

path_to_files = p.join(__dirname, path_to_files);

my_lzma = lzma_norm;

console.log("Testing lzma_worker" + (process.argv[2] === "unmin" ? "" : "-min") + ".js")
run_tests(function (tests_passed_norm) {
    if (!tests_passed_norm) {
        /// Fail.
        process.exit(1);
    }

    console.log("\nTesting lzma-c" + (process.argv[2] === "unmin" ? "" : "-min") + ".js and lzma-d" + (process.argv[2] === "unmin" ? "" : "-min") + ".js.")
    my_lzma = lzma_sep;

    run_tests(function (tests_passed_sep)
    {
        if (!tests_passed_sep) {
            /// Fail.
            process.exit(1);
        }
    });
});
<commit_msg>Improved test script.<commit_after>// jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, onevar:true, plusplus:true, quotmark:double, strict:true, undef:true, unused:strict, node:true

"use strict";

var all_tests_pass = true,
    fs = require("fs"),
    p = require("path"),
    my_lzma,
    lzma_norm = require("../src/lzma_worker" + (process.argv[2] === "unmin" ? "" : "-min") + ".js").LZMA,
    lzma_sep = {
        decompress: require("../src/lzma-d" + (process.argv[2] === "unmin" ? "" : "-min") + ".js").LZMA.decompress,
        compress:   require("../src/lzma-c" + (process.argv[2] === "unmin" ? "" : "-min") + ".js").LZMA.compress,
    },
    path_to_files = "files";

function announce(str)
{
    var stars = "****",
        i;

    for (i = str.length - 1; i >= 0; i -= 1) {
        stars += "*";
    }

    console.log(stars);
    console.log("* "+ str + " *");
    console.log(stars);
}

function display_result(str, pass) {
    ///NOTE: \u001B[32m makes green text.
    ///      \u001B[31m makes red text.
    ///      \u001B[0m  resets the text color.
    console.log("\u001B[3" + (pass ? "2" : "1") + "m" + str + "\u001B[0m");
}

function progress(percent)
{
    if (process.stdout.isTTY) {
        process.stdout.clearLine();
        process.stdout.cursorTo(0);
        if (percent > 0 && percent < 1) {
            process.stdout.write((percent * 100).toFixed(2) + "%");
        }
    }
}

function decompression_test(compressed_file, correct_filename, next) {
    fs.readFile(correct_filename, function (err, correct_buffer) {

        if (err) {
            console.log("Cannot open " + correct_filename);
            throw new Error(err);
        }

        fs.readFile(compressed_file, function (err, buffer) {
            var deco_start;

            if (err) {
                throw err;
            }

            deco_start = (new Date()).getTime();
            try {
                my_lzma.decompress(buffer, function (result) {
                    var deco_speed = (new Date()).getTime() - deco_start,
                        correct_result;

                    console.log("Decompressed size:", result.length);

                    if (typeof result === "string") {
                        correct_result = correct_buffer.toString();
                    } else {
                        correct_result = JSON.stringify(correct_buffer);
                        result = JSON.stringify(result);
                    }
                    if (correct_result !== result) {
                        display_result("ERROR: files do not match!", false);
                        console.log();
                        all_tests_pass = false;
                    } else {
                        display_result("Test passed", true);
                    }

                    console.log("Decompression time:", deco_speed);

                    console.log();
                    next();
                }, progress);
            } catch (e) {
                if (p.basename(correct_filename) === "error-" + e.detailMessage) {
                    display_result("Test passed", true);
                    console.log("threw correct error: " + e.detailMessage);
                } else {
                    display_result("ERROR: " + e.detailMessage, false);
                    all_tests_pass = false;
                }
                console.log();
                next();
            }
        });
    });
}

function compression_test(file, next) {
    fs.readFile(file, "utf8", function (err, content) {
        var comp_start = (new Date()).getTime(),
            compression_mode = 1,
            match;

        if (err) {
            throw err;
        }

        match = p.basename(file, p.extname(file)).match(/^level[ _](\d)/i);

        if (match) {
            compression_mode = Number(match[1]) || 1;
        }

        console.log("     Initial size:", content.length);
        my_lzma.compress(content, compression_mode, function ondone(result) {
            var comp_speed = (new Date()).getTime() - comp_start,
                deco_start;

            console.log("  Compressed size:", result.length);

            deco_start = (new Date()).getTime();
            my_lzma.decompress(result, function (result) {
                var deco_speed = (new Date()).getTime() - deco_start;
                console.log("Decompressed size:", result.length);

                if (content !== result) {
                    display_result("ERROR: files do not match!", false);
                    console.log();
                    all_tests_pass = false;
                } else {
                    display_result("Test passed", true);
                }

                console.log("  Compression time:", comp_speed);
                console.log("Decompression time:", deco_speed);

                console.log();
                next();
            }, progress);
        }, progress);
    });
}

function run_tests(cb)
{
    fs.readdir(path_to_files, function (err, files) {
        var file_count = files.length;

        if (err) {
            throw err;
        }

        (function run_test(i) {
            var file;

            if (i >= file_count) {
                if (all_tests_pass) {
                    display_result("All tests completed sucessfully", true);
                } else {
                    display_result("An error was detected!", false);
                }

                return cb ? cb(all_tests_pass) : 0;
            }
            file = files[i];

            console.log(file);

            if (file.slice(-5) === ".lzma") {
                /// Preform a decompress test on *.lzma files.
                decompression_test(p.join(path_to_files, file), p.join(path_to_files, file.slice(0, -5)), function next()
                {
                    run_test(i + 1);
                });
            } else {
                /// Preform a compression/decompression test.
                compression_test(p.join(path_to_files, file), function next()
                {
                    run_test(i + 1);
                });
            }
        }(0));
    });
}

path_to_files = p.join(__dirname, path_to_files);

my_lzma = lzma_norm;

announce("Testing lzma_worker" + (process.argv[2] === "unmin" ? "" : "-min") + ".js");
run_tests(function (tests_passed_norm) {
    if (!tests_passed_norm) {
        /// Fail.
        process.exit(1);
    }

    console.log("");
    announce("Testing lzma-c" + (process.argv[2] === "unmin" ? "" : "-min") + ".js and lzma-d" + (process.argv[2] === "unmin" ? "" : "-min") + ".js");
    my_lzma = lzma_sep;

    run_tests(function (tests_passed_sep)
    {
        if (!tests_passed_sep) {
            /// Fail.
            process.exit(1);
        }
    });
});
<|endoftext|>


<commit_before>var should = require('should');
var mongoose = require('mongoose');
var User = require('../user.js');
var db;

describe('User', function() {

  before(function(done) {
    db = mongoose.connect('mongodb://localhost/test');
    done();
  });

  after(function(done) {
    mongoose.connection.close();
    done();
  });

  beforeEach(function(done) {

    var user = new User({
      oauthID: 12345,
      name: 'testy',
      created: Date.now()
    });

    user.save(function(error) {
      if (error) console.log('error' + error.message);
      else console.log('no error');
      done();
    });

  });

  afterEach(function(done) {
    User.remove({}, function() {
      done();
    });
  });

  it('find a user by username', function(done) {
    User.findOne({ oauthID: 12345, name: "testy" }, function(err, user) {
      user.name.should.eql('testy');
      user.oauthID.should.eql(12345);
      console.log("   name: ", user.name);
      console.log("   oauthID: ", user.oauthID);
      done();
    });
  });

});
<commit_msg>Update test.user.js<commit_after>var should = require('should');
var mongoose = require('mongoose');
var User = require('../user.js');
var db;

describe('User', function() {

  before(function(done) {
    db = mongoose.connect('mongodb://localhost:12077/quiz');
    done();
  });

  after(function(done) {
    mongoose.connection.close();
    done();
  });

  beforeEach(function(done) {

    var user = new User({
      oauthID: 12345,
      name: 'testy',
      created: Date.now()
    });

    user.save(function(error) {
      if (error) console.log('error' + error.message);
      else console.log('no error');
      done();
    });

  });

  afterEach(function(done) {
    User.remove({}, function() {
      done();
    });
  });

  it('find a user by username', function(done) {
    User.findOne({ oauthID: 12345, name: "testy" }, function(err, user) {
      user.name.should.eql('testy');
      user.oauthID.should.eql(12345);
      console.log("   name: ", user.name);
      console.log("   oauthID: ", user.oauthID);
      done();
    });
  });

});
<|endoftext|>


<commit_before>'use strict';

const tap = require('tap');
const mediasoup = require('../');
const roomOptions = require('./data/options').roomOptions;
const peerOptions = require('./data/options').peerOptions;

tap.test('room.Peer() with peerName must succeed', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			let peer = room.Peer('alice', peerOptions);

			peer.on('close', (error) =>
			{
				t.error(error, 'peer must close cleanly');
				t.end();
			});

			// Wait a bit so Channel requests receive response
			setTimeout(() => peer.close(), 50);
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});

tap.test('room.Peer() without peerName must fail', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			t.throws(() =>
			{
				room.Peer();
			},
			TypeError,
			'room.Peer() must throw TypeError');

			t.end();
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});

tap.test('room.Peer() with same peerName must fail', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			room.Peer('alice', peerOptions);

			t.throws(() =>
			{
				room.Peer('alice', peerOptions);
			},
			'room.Peer() must throw');

			t.end();
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});

tap.test('room.Peer() with same peerName must succeed if previous peer was closed before', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			let peer1 = room.Peer('alice', peerOptions);

			t.equal(room.getPeer('alice'), peer1, 'room.getPeer() must retrieve the first "alice"');
			t.equal(room.peers.length, 1, 'room.peers must retrieve one peer');

			peer1.close();

			t.notOk(room.getPeer('alice'), 'room.getPeer() must retrieve nothing');
			t.equal(room.peers.length, 0, 'room.peers must retrieve zero peers');

			let peer2 = room.Peer('alice', peerOptions);

			t.equal(room.getPeer('alice'), peer2, 'room.getPeer() must retrieve the new "alice"');
			t.equal(room.peers.length, 1, 'room.peers must retrieve one peer');

			peer2.on('close', (error) =>
			{
				t.error(error, 'peer must close cleanly');
				t.end();
			});

			// Wait a bit so Channel requests receive response
			setTimeout(() => peer2.close(), 50);
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});

tap.test('room.peers must retrieve existing peers', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			let alice = room.Peer('alice', peerOptions);
			let bob = room.Peer('bob', peerOptions);
			let carol = room.Peer('carol', peerOptions);

			bob.close();

			t.same(room.peers, [ alice, carol ], 'room.peers() must retrieve "alice" and "carol" peers');

			t.end();
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});

tap.test('room.getCapabilities() must retrieve current room capabilities', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			// TODO: REMOVE
			console.log(JSON.stringify(room.getCapabilities('audio'), null, '\t'));
			console.log(JSON.stringify(room.getCapabilities('video'), null, '\t'));
			console.log(JSON.stringify(room.getCapabilities('depth'), null, '\t'));

			t.ok(room.getCapabilities('audio'), 'room.getCapabilities("audio") returns an object');
			t.ok(room.getCapabilities('video'), 'room.getCapabilities("video") returns an object');
			t.ok(room.getCapabilities('depth'), 'room.getCapabilities("depth") returns an object');
			t.end();
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});

tap.test('room.dump() must succeed', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			room.Peer('alice', peerOptions);
			room.Peer('bob', peerOptions);

			room.dump()
				.then((data) =>
				{
					t.pass('room.dump() succeeded');
					t.equal(Object.keys(data.peers).length, 2, 'room.dump() must retrieve two peers');
					t.end();
				})
				.catch((error) => t.fail(`room.dump() failed: ${error}`));
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});
<commit_msg>Remove debug.<commit_after>'use strict';

const tap = require('tap');
const mediasoup = require('../');
const roomOptions = require('./data/options').roomOptions;
const peerOptions = require('./data/options').peerOptions;

tap.test('room.Peer() with peerName must succeed', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			let peer = room.Peer('alice', peerOptions);

			peer.on('close', (error) =>
			{
				t.error(error, 'peer must close cleanly');
				t.end();
			});

			// Wait a bit so Channel requests receive response
			setTimeout(() => peer.close(), 50);
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});

tap.test('room.Peer() without peerName must fail', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			t.throws(() =>
			{
				room.Peer();
			},
			TypeError,
			'room.Peer() must throw TypeError');

			t.end();
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});

tap.test('room.Peer() with same peerName must fail', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			room.Peer('alice', peerOptions);

			t.throws(() =>
			{
				room.Peer('alice', peerOptions);
			},
			'room.Peer() must throw');

			t.end();
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});

tap.test('room.Peer() with same peerName must succeed if previous peer was closed before', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			let peer1 = room.Peer('alice', peerOptions);

			t.equal(room.getPeer('alice'), peer1, 'room.getPeer() must retrieve the first "alice"');
			t.equal(room.peers.length, 1, 'room.peers must retrieve one peer');

			peer1.close();

			t.notOk(room.getPeer('alice'), 'room.getPeer() must retrieve nothing');
			t.equal(room.peers.length, 0, 'room.peers must retrieve zero peers');

			let peer2 = room.Peer('alice', peerOptions);

			t.equal(room.getPeer('alice'), peer2, 'room.getPeer() must retrieve the new "alice"');
			t.equal(room.peers.length, 1, 'room.peers must retrieve one peer');

			peer2.on('close', (error) =>
			{
				t.error(error, 'peer must close cleanly');
				t.end();
			});

			// Wait a bit so Channel requests receive response
			setTimeout(() => peer2.close(), 50);
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});

tap.test('room.peers must retrieve existing peers', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			let alice = room.Peer('alice', peerOptions);
			let bob = room.Peer('bob', peerOptions);
			let carol = room.Peer('carol', peerOptions);

			bob.close();

			t.same(room.peers, [ alice, carol ], 'room.peers() must retrieve "alice" and "carol" peers');

			t.end();
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});

tap.test('room.getCapabilities() must retrieve current room capabilities', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			t.ok(room.getCapabilities('audio'), 'room.getCapabilities("audio") returns an object');
			t.ok(room.getCapabilities('video'), 'room.getCapabilities("video") returns an object');
			t.ok(room.getCapabilities('depth'), 'room.getCapabilities("depth") returns an object');
			t.end();
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});

tap.test('room.dump() must succeed', { timeout: 2000 }, (t) =>
{
	let server = mediasoup.Server();

	t.tearDown(() => server.close());

	server.createRoom(roomOptions)
		.then((room) =>
		{
			room.Peer('alice', peerOptions);
			room.Peer('bob', peerOptions);

			room.dump()
				.then((data) =>
				{
					t.pass('room.dump() succeeded');
					t.equal(Object.keys(data.peers).length, 2, 'room.dump() must retrieve two peers');
					t.end();
				})
				.catch((error) => t.fail(`room.dump() failed: ${error}`));
		})
		.catch((error) => t.fail(`server.createRoom() failed: ${error}`));
});
<|endoftext|>