def register(username: str, password: str, role: str, age: int): ''' Creates a new user.''' _id = _db.counter.find_one_and_update( {'_id': 'USER_COUNT'}, {'$inc': { 'count': 1 }}, return_document=pymongo.ReturnDocument.AFTER)['count'] _log.debug(_id) query = { "_id": _id, "username": username, "password": password, "role": role } user = User(_id, username, password, role, int(age)) _log.debug(query) try: _db.users.insert_one(user.to_dict()) except pymongo.errors.DuplicateKeyError: _log.info( 'Duplicate key error detected in the database for username %s', username) return 'Duplicate Username Error' except pymongo.errors.PyMongoError: _log.exception('register has failed in the db') return None return User.from_dict(_db.users.find_one({'_id': _id}))
def test_register(self, mock_db): ''' Tests the registration in Mongo ''' mock_db.counter.find_one_and_update.return_value = {'count': -1} username = '******' password = '******' role = 'TEST ROLE' age = 65 user = User(-1, username, password, role, age) mock_db.users.insert_one.return_value = user mock_db.users.find_one.return_value = user.to_dict() ret_user = src.data.mongo.register(username, password, role, age) _log.debug(ret_user) self.assertEqual(ret_user.username, user.username)
def test_user_by_id(self, mock_db): ''' Tests get user by id ''' user = User(-1, 'TEST', 'TEST', 'VOTER', -1) mock_db.users.find_one.return_value = user.to_dict() ret_user = src.data.mongo.get_user_by_id(-1) self.assertEqual(user.username, ret_user.username)