<commit_before>var
  Promise = require('bluebird'),
  _ = require('lodash'),
  should = require('should'),
  Kuzzle = require.main.require('lib/api/kuzzle'),
  InternalError = require.main.require('kuzzle-common-objects').Errors.internalError,
  NotFoundError = require.main.require('kuzzle-common-objects').Errors.notFoundError,
  ResponseObject = require.main.require('kuzzle-common-objects').Models.responseObject,
  Profile = require.main.require('lib/api/core/models/security/profile'),
  User = require.main.require('lib/api/core/models/security/user'),
  UserRepository = require.main.require('lib/api/core/models/repositories/userRepository');

describe('Test: repositories/userRepository', () => {
  var
    kuzzle,
    userRepository,
    userInvalidProfile;

  before(() => {
    var
      encryptedPassword = '<PASSWORD>',
      mockCacheEngine,
      mockReadEngine,
      mockWriteLayer,
      mockProfileRepository,
      userInCache,
      userInDB;

    kuzzle = new Kuzzle();
    mockCacheEngine = {
      get: key => {
        if (key === userRepository.index + '/' + userRepository.collection + '/userInCache') {
          return Promise.resolve(JSON.stringify(userInCache));
        }
        return Promise.resolve(null);
      },
      volatileSet: () => {return Promise.resolve('OK');},
      expire: () => {return Promise.resolve('OK'); }
    };

    mockReadEngine = {
      get: requestObject => {
        if (requestObject.data._id === 'userInDB') {
          return Promise.resolve(new ResponseObject(requestObject, userInDB));
        }

        return Promise.resolve(new NotFoundError('User not found in db'));
      }
    };

    mockWriteLayer = {
      execute: () => Promise.resolve({})
    };

    mockProfileRepository = {
      loadProfile: profileKey => {
        var profile = new Profile();
        if (profileKey === 'notfound') {
          return Promise.resolve(null);
        }
        profile._id = profileKey;
        return Promise.resolve(profile);
      },
      loadProfiles: profileKeys => {
        var
          profile,
          profiles = [];

        profileKeys.forEach(profileKey => {
          profile = new Profile();
          if (profileKey !== 'notfound') {
            profile._id = profileKey;
            profiles.push(_.assignIn({}, profile));
          }
        });
        return Promise.resolve(profiles);
      }
    };
    userInCache = {
      _id: 'userInCache',
      name: '<NAME>',
      profilesIds: ['userincacheprofile'],
      password: <PASSWORD>
    };
    userInDB = {
      _id: 'userInDB',
      name: '<NAME>',
      profilesIds: ['userindbprofile']
    };
    userInvalidProfile = {
      _id: 'userInvalidProfile',
      profilesIds: ['notfound']
    };

    kuzzle.repositories.profile = mockProfileRepository;

    userRepository = new UserRepository(kuzzle);
    userRepository.cacheEngine = mockCacheEngine;
    userRepository.readEngine = mockReadEngine;
    userRepository.writeLayer = mockWriteLayer;

  });

  describe('#constructor', () => {
    it('should take into account the options given', () => {
      var repository = new UserRepository(kuzzle, { ttl: 1000 });

      should(repository.ttl).be.exactly(1000);
    });
  });

  describe('#anonymous', () => {
    it('should return a valid anonymous user', () => {
      return userRepository.anonymous()
        .then(user => assertIsAnonymous(user));
    });
  });

  describe('#hydrate', () => {
    it('should return the given user if the given data is not a valid object', () => {
      var
        u = new User();

      return Promise.all([
        userRepository.hydrate(u, null),
        userRepository.hydrate(u),
        userRepository.hydrate(u, 'a scalar')
      ])
        .then(results => {
          results.forEach(user => should(user).be.exactly(u));
        });
    });

    it('should return the anonymous user if no _id is set', () => {
      var user = new User();
      user.profilesIds = 'a profile';

      return userRepository.hydrate(user, {})
        .then(result => assertIsAnonymous(result));
    });

    it('should convert a profilesIds string into array', () => {
      var user = new User();
      user._id = 'admin';

      return userRepository.hydrate(user, {profilesIds: 'admin'})
        .then((result) => {
          should(result.profilesIds).be.an.instanceOf(Array);
          should(result.profilesIds[0]).be.exactly('admin');
        })
    });

    it('should reject the promise if the profile cannot be found', () => {
      var user = new User();
<commit_msg>Update userRepository.test.js<commit_after>var
  Promise = require('bluebird'),
  _ = require('lodash'),
  should = require('should'),
  Kuzzle = require.main.require('lib/api/kuzzle'),
  InternalError = require.main.require('kuzzle-common-objects').Errors.internalError,
  NotFoundError = require.main.require('kuzzle-common-objects').Errors.notFoundError,
  ResponseObject = require.main.require('kuzzle-common-objects').Models.responseObject,
  Profile = require.main.require('lib/api/core/models/security/profile'),
  User = require.main.require('lib/api/core/models/security/user'),
  UserRepository = require.main.require('lib/api/core/models/repositories/userRepository');

describe('Test: repositories/userRepository', () => {
  var
    kuzzle,
    userRepository,
    userInvalidProfile;

  before(() => {
    var
      encryptedPassword = '<PASSWORD>',
      mockCacheEngine,
      mockReadEngine,
      mockWriteLayer,
      mockProfileRepository,
      userInCache,
      userInDB;

    kuzzle = new Kuzzle();
    mockCacheEngine = {
      get: key => {
        if (key === userRepository.index + '/' + userRepository.collection + '/userInCache') {
          return Promise.resolve(JSON.stringify(userInCache));
        }
        return Promise.resolve(null);
      },
      volatileSet: () => {return Promise.resolve('OK');},
      expire: () => {return Promise.resolve('OK'); }
    };

    mockReadEngine = {
      get: requestObject => {
        if (requestObject.data._id === 'userInDB') {
          return Promise.resolve(new ResponseObject(requestObject, userInDB));
        }

        return Promise.resolve(new NotFoundError('User not found in db'));
      }
    };

    mockWriteLayer = {
      execute: () => Promise.resolve({})
    };

    mockProfileRepository = {
      loadProfile: profileKey => {
        var profile = new Profile();
        if (profileKey === 'notfound') {
          return Promise.resolve(null);
        }
        profile._id = profileKey;
        return Promise.resolve(profile);
      },
      loadProfiles: profileKeys => {
        var
          profile,
          profiles = [];

        profileKeys.forEach(profileKey => {
          profile = new Profile();
          if (profileKey !== 'notfound') {
            profile._id = profileKey;
            profiles.push(_.assignIn({}, profile));
          }
        });
        return Promise.resolve(profiles);
      }
    };
    userInCache = {
      _id: 'userInCache',
      name: '<NAME>',
      profilesIds: ['userincacheprofile'],
      password: <PASSWORD>
    };
    userInDB = {
      _id: 'userInDB',
      name: '<NAME>',
      profilesIds: ['userindbprofile']
    };
    userInvalidProfile = {
      _id: 'userInvalidProfile',
      profilesIds: ['notfound']
    };

    kuzzle.repositories.profile = mockProfileRepository;

    userRepository = new UserRepository(kuzzle);
    userRepository.cacheEngine = mockCacheEngine;
    userRepository.readEngine = mockReadEngine;
    userRepository.writeLayer = mockWriteLayer;

  });

  describe('#constructor', () => {
    it('should take into account the options given', () => {
      var repository = new UserRepository(kuzzle, { ttl: 1000 });

      should(repository.ttl).be.exactly(1000);
    });
  });

  describe('#anonymous', () => {
    it('should return a valid anonymous user', () => {
      return userRepository.anonymous()
        .then(user => assertIsAnonymous(user));
    });
  });

  describe('#hydrate', () => {
    it('should return the given user if the given data is not a valid object', () => {
      var
        u = new User();

      return Promise.all([
        userRepository.hydrate(u, null),
        userRepository.hydrate(u),
        userRepository.hydrate(u, 'a scalar')
      ])
        .then(results => {
          results.forEach(user => should(user).be.exactly(u));
        });
    });

    it('should return the anonymous user if no _id is set', () => {
      var user = new User();
      user.profilesIds = 'a profile';

      return userRepository.hydrate(user, {})
        .then(result => assertIsAnonymous(result));
    });

    it('should convert a profilesIds string into array', () => {
      var user = new User();
      user._id = 'admin';

      return userRepository.hydrate(user, {profilesIds: 'admin'})
        .then((result) => {
          should(result.profilesIds).be.an.instanceOf(Array);
          should(result.profilesIds[0]).be.exactly('admin');
        });
    });

    it('should reject the promise if the profile cannot be found', () => {
      var user = new User();

{'fraction_non_alphanumeric': 0.14576271186440679, 'fraction_numerical': 0.0019682886823400767, 'mean_word_length': 2.6093133385951064, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 59, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '2011021', 'n_tokens_mistral': 2655, 'n_tokens_neox': 2568, 'n_words': 511}