Ejemplo n.º 1
0
def dump_user(user: User) -> Dict:
    schema = UserSchema()
    try:
        data, errors = schema.dump(user)
        return data
    except ValidationError as err:
        return err.messages
Ejemplo n.º 2
0
    def put(self) -> Iterable[Union[Mapping, int, None]]:
        """
        Create or update a user. Serializes the data in the request body
        using the UserSchema, validating the inputs in the process to ensure
        all downstream processes leverage clean data, and passes the User
        object to the client to create or update the user record.
        """
        if not request.data:
            return {
                'message': 'No user information provided in the request.'
            }, HTTPStatus.BAD_REQUEST

        try:
            user_attributes = json.loads(request.data)
            schema = UserSchema()
            user = schema.load(user_attributes)

            new_user, user_created = self.client.create_update_user(user=user)
            resp_code = HTTPStatus.CREATED if user_created else HTTPStatus.OK
            return schema.dumps(new_user), resp_code

        except SchemaValidationError as schema_err:
            err_msg = 'User inputs provided are not valid: %s' % schema_err
            return {'message': err_msg}, HTTPStatus.BAD_REQUEST

        except Exception:
            LOGGER.exception('UserDetailAPI PUT Failed')
            return {
                'message': 'Internal server error!'
            }, HTTPStatus.INTERNAL_SERVER_ERROR
Ejemplo n.º 3
0
 def test_get_users(self) -> None:
     with patch.object(GraphDatabase, 'driver'), patch.object(
             Neo4jProxy, '_execute_cypher_query') as mock_execute:
         test_user = {
             'employee_type': 'teamMember',
             'full_name': 'test_full_name',
             'is_active': True,
             'github_username': '******',
             'slack_id': 'test_id',
             'last_name': 'test_last_name',
             'first_name': 'test_first_name',
             'team_name': 'test_team',
             'email': 'test_email',
             'manager_fullname': 'test_manager',
         }
         mock_execute.return_value.single.return_value = {
             'users': [test_user]
         }
         neo4j_proxy = Neo4jProxy(host='DOES_NOT_MATTER', port=0000)
         users = neo4j_proxy.get_users()
         actual_data = UserSchema(many=True).load([test_user]).data
         for attr in [
                 'employee_type', 'full_name', 'is_active',
                 'github_username', 'slack_id', 'last_name', 'first_name',
                 'team_name', 'email', 'manager_fullname'
         ]:
             self.assertEquals(getattr(users[0], attr),
                               getattr(actual_data[0], attr))
Ejemplo n.º 4
0
def load_user(user_data: Dict) -> User:
    try:
        schema = UserSchema()
        # In order to call 'GET_PROFILE_URL' we make sure the user id exists
        if _str_no_value(user_data.get('user_id')):
            user_data['user_id'] = user_data.get('email')
        # Add profile_url from optional 'GET_PROFILE_URL' configuration method.
        # This methods currently exists for the case where the 'profile_url' is not included
        # in the user metadata.
        if _str_no_value(user_data.get(
                'profile_url')) and app.config['GET_PROFILE_URL']:
            user_data['profile_url'] = app.config['GET_PROFILE_URL'](
                user_data['user_id'])
        return schema.load(user_data)
    except ValidationError as err:
        return err.messages
Ejemplo n.º 5
0
 def test_raise_error_if_no_user_id(self) -> None:
     """
     Error is raised if deserialization of Dict will not generate a user_id
     :return:
     """
     with app.test_request_context():
         with self.assertRaises(ValidationError):
             UserSchema().load({"display_name": "Test User"})
Ejemplo n.º 6
0
 def test_extra_key_does_not_raise(self) -> None:
     """
     Handle extra keys in the user data
     :return:
     """
     test_user = {"email": "*****@*****.**", "foo": "bar"}
     with app.test_request_context():
         self.assertEqual(UserSchema().load(test_user).email,
                          "*****@*****.**")
Ejemplo n.º 7
0
 def get(self, *, id: Optional[str] = None) -> Iterable[Union[Mapping, int, None]]:
     if app.config['USER_DETAIL_METHOD']:
         try:
             user_data = app.config['USER_DETAIL_METHOD'](id)
             return UserSchema().dump(user_data), HTTPStatus.OK
         except Exception:
             LOGGER.exception('UserDetailAPI GET Failed - Using "USER_DETAIL_METHOD" config variable')
             return {'message': 'user_id {} fetch failed'.format(id)}, HTTPStatus.NOT_FOUND
     else:
         return super().get(id=id)
Ejemplo n.º 8
0
 def test_set_display_name_from_email_if_full_name_empty(self) -> None:
     """
     Deserialization and serialization sets display_name from email if no display_name and
     full_name is ''
     :return:
     """
     test_user = {"email": "*****@*****.**", "full_name": ""}
     with app.test_request_context():
         self.assertEqual(UserSchema().load(test_user).display_name,
                          "*****@*****.**")
Ejemplo n.º 9
0
 def test_set_display_name_from_full_name(self) -> None:
     """
     Deserialization and serialization sets display_name from full_name if no display_name and
     full_name is a non-empty string
     :return:
     """
     test_user = {"email": "*****@*****.**", "full_name": "Test User"}
     with app.test_request_context():
         self.assertEqual(UserSchema().load(test_user).display_name,
                          "Test User")
Ejemplo n.º 10
0
 def test_set_user_id_from_email(self) -> None:
     """
     Deserialization and serialization sets user_id from email if no user_id
     :return:
     """
     with app.test_request_context():
         self.assertEqual(
             UserSchema().load({
                 "email": "*****@*****.**"
             }).user_id, "*****@*****.**")
Ejemplo n.º 11
0
 def test_set_display_name_from_email(self) -> None:
     """
     Deserialization and serialization sets display_name from email if no display_name and
     full_name is None
     :return:
     """
     with app.test_request_context():
         self.assertEqual(
             UserSchema().load({
                 "email": "*****@*****.**"
             }).display_name,
             "*****@*****.**",
         )
Ejemplo n.º 12
0
    def test_profile_url(self) -> None:
        """
        Deserialization and serialization sets profile_url from function defined at GET_PROFILE_URL
        if no profile_url provided'
        :return:
        """
        test_user = {
            "email": "*****@*****.**",
            "GET_PROFILE_URL": lambda _: "testUrl"
        }

        with app.test_request_context():
            self.assertEqual(UserSchema().load(test_user).profile_url,
                             "testUrl")
Ejemplo n.º 13
0
 def test_str_no_value(self) -> None:
     """
     Test _str_no_value returns True for a string of spaces
     :return:
     """
     self.assertEqual(UserSchema()._str_no_value(" "), True)
Ejemplo n.º 14
0
def dump_user(user: User) -> Dict:
    schema = UserSchema()
    return schema.dump(user)