<commit_before>'use strict';

var expect = require('chai').expect;
var nock = require('nock');
var Promise = require('es6-promise').Promise;
var testCredentials = require('../support/testCredentials');
var AuthService = require('../../services/authService');

describe('AuthService', function () {
  var mockToken = '<PASSWORD>',
      authService,
      credentials;

  beforeEach(function() {
    credentials = JSON.parse(JSON.stringify(testCredentials));
    authService = new AuthService(credentials);

    nock('https://my-eu.sapanywhere.com:443/oauth2', {
      reqheaders: { 'content-type': 'application/x-www-form-urlencoded' }
    })
      .post('/token?client_id=' + credentials.client_id
        + '&client_secret=' + credentials.client_secret
        + '&grant_type=refresh_token&refresh_token=' + credentials.refresh_token)
      .reply(200, {
        access_token: mockToken,
        expires_in: 43199
      });
  });

  afterEach(function () {
    nock.cleanAll();
  });

  describe('initialization', function () {
    it('sets credentials', function () {
      expect(authService.credentials).to.exist;
    });

    describe('when passed no credentials', function () {
      it('throws an error', function () {
        var initializer = function () { new AuthService(); };

        expect(initializer).to.throw(Error, /Please provide credentials/);
      });
    });

    describe('when passed insufficient credentials', function () {
      it('throws an error', function () {
        var badCredentials = { client_id: '1234' };
        var initializer = function () { new AuthService(badCredentials); };

        expect(initializer).to.throw(Error, /Insufficient credentials/);
      });
    });
  });

  describe('accessToken', function () {
    it('creates accessToken which resolves with a token', function (done) {
      authService.accessToken()
        .then(function(accessToken) {
          expect(accessToken).to.equal(mockToken);
          done();
        })
        .catch(done);
    });

    describe('when accessing tokenPromise multiple times', function() {
      it('does not make multiple accessToken requests', function(done) {
        // nock will throw an error if the request is made multiple times
        Promise.all([
          authService.accessToken(),
          authService.accessToken(),
        ])
          .then(function(results) {
            expect(results[0]).to.equal(mockToken);
            expect(results[1]).to.equal(mockToken);
            done();
          })
          .catch(done);
      });
    });

    describe('when token expiry has elapsed', function () {
      it('fetches and resolves with a new token', function (done) {
        var expiry = 1;
        credentials.client_id = 'short_expiry';

        var firstRequest = nock('https://my-eu.sapanywhere.com:443/oauth2', {
          reqheaders: { 'content-type': 'application/x-www-form-urlencoded' }
        })
          .post('/token?client_id=' + credentials.client_id
          + '&client_secret=' + credentials.client_secret
          + '&grant_type=refresh_token&refresh_token=' + credentials.refresh_token)
          .reply(200, {
            access_token: mockToken,<commit_msg>Add test to check wait flag logic<commit_after>'use strict';

var expect = require('chai').expect;
var nock = require('nock');
var Promise = require('es6-promise').Promise;
var testCredentials = require('../support/testCredentials');
var AuthService = require('../../services/authService');

describe('AuthService', function () {
  var mockToken = '<PASSWORD>',
      authService,
      credentials;

  beforeEach(function() {
    credentials = JSON.parse(JSON.stringify(testCredentials));
    authService = new AuthService(credentials);

    nock('https://my-eu.sapanywhere.com:443/oauth2', {
      reqheaders: { 'content-type': 'application/x-www-form-urlencoded' }
    })
      .post('/token?client_id=' + credentials.client_id
        + '&client_secret=' + credentials.client_secret
        + '&grant_type=refresh_token&refresh_token=' + credentials.refresh_token)
      .reply(200, {
        access_token: mockToken,
        expires_in: 43199
      });
  });

  afterEach(function () {
    nock.cleanAll();
  });

  describe('initialization', function () {
    it('sets credentials', function () {
      expect(authService.credentials).to.exist;
    });

    describe('when passed no credentials', function () {
      it('throws an error', function () {
        var initializer = function () { new AuthService(); };

        expect(initializer).to.throw(Error, /Please provide credentials/);
      });
    });

    describe('when passed insufficient credentials', function () {
      it('throws an error', function () {
        var badCredentials = { client_id: '1234' };
        var initializer = function () { new AuthService(badCredentials); };

        expect(initializer).to.throw(Error, /Insufficient credentials/);
      });
    });
  });

  describe('accessToken', function () {
    it('creates accessToken which resolves with a token', function (done) {
      authService.accessToken()
        .then(function(accessToken) {
          expect(accessToken).to.equal(mockToken);
          done();
        })
        .catch(done);
    });

    describe('when accessing tokenPromise multiple times', function() {
      it('does not make multiple accessToken requests', function(done) {
        // nock will throw an error if the request is made multiple times
        Promise.all([
          authService.accessToken(),
          authService.accessToken(),
        ])
          .then(function(results) {
            expect(results[0]).to.equal(mockToken);
            expect(results[1]).to.equal(mockToken);
            done();
          })
          .catch(done);
      });
    });

    describe('when attempting multiple authorization requests', function () {
      it('waits for 1s before re-attempting', function (done) {
        authService.isGettingAccessTokenFlag = true;
        var timerStart = new Date().getTime();

        authService.accessToken()
          .then(function (accessToken) {
            var duration = new Date().getTime() - timerStart;

            expect(accessToken).to.equal(mockToken);
            expect(duration).to.be.above(1000);
            done();
          });
      });
    });

    describe('when token expiry has elapsed', function () {
      it('fetches and resolves with a new token', function (done) {
        var expiry = 1;
        credentials.client_id = 'short_<PASSWORD>';

        var firstRequest = nock('https://my-eu.sapanywhere.com:443/oauth2', {
          reqheaders: { 'content-type': 'application/x-www-form-urlencoded' }
        })
          .post('/token?client_id=' + credentials.client_id
          + '&client_secret=' + credentials.client_secret
          + '&grant_type=refresh_token&refresh_token=' + credentials.refresh_token)
          .reply(200, {
            access_token: mockToken,
{'fraction_non_alphanumeric': 0.1422209452664847, 'fraction_numerical': 0.008475793707800603, 'mean_word_length': 2.7409994626544867, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 4, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3489826', 'n_tokens_mistral': 1971, 'n_tokens_neox': 1906, 'n_words': 387}