예제 #1
0
    async def test_update_user_update_all_fields(self):
        expected_new_name = "Novo Nome"
        expected_new_email = "*****@*****.**"

        new_user = User(**USER_WITH_MULTIPLE_ACCOUNTS_DICT)
        new_user.name = expected_new_name
        new_user.email = expected_new_email

        resp = await self.client.patch(
            f"/users/{USER_WITH_MULTIPLE_ACCOUNTS_ID}",
            headers={
                "Authorization":
                f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            json=new_user.dict(),
        )
        self.assertEqual(HTTPStatus.ACCEPTED, resp.status)
        user_data = await resp.json()

        self.assertEqual(UserResource(user=new_user).dict(), user_data)

        resp = await self.client.get(
            f"/users/{USER_WITH_MULTIPLE_ACCOUNTS_ID}",
            headers={
                "Authorization":
                f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
        )
        updated_user_data = await resp.json()
        self.assertEqual(UserResource(user=new_user).dict(), updated_user_data)
예제 #2
0
async def delete_user(user_id: str):

    user = await UsersService.get_user_by_id(int(user_id), UsersBackend())
    status_code = HTTPStatus.OK if user else HTTPStatus.NOT_FOUND

    if user:
        await UsersService.delete_user(user, UsersBackend())
        return web.json_response(UserResource(user=user).dict(),
                                 status=status_code)

    return web.json_response(UserResource().dict(), status=status_code)
    async def test_serialize_all_fields(self):
        """
        Confere que é possível serializar um UsersMeResources a apartir dos
        outros modelos necessários.
        data = UsersMeResources(user=..., current_account=..., accounts=...)
        """
        async with AsgardDBSession() as s:
            account = (await
                       s.query(AccountDB).filter(AccountDB.id == ACCOUNT_DEV_ID
                                                 ).one())
            other_accounts = (await s.query(AccountDB).filter(
                AccountDB.id == ACCOUNT_INFRA_ID).one())
            user = (await s.query(UserDB).filter(
                UserDB.id == USER_WITH_MULTIPLE_ACCOUNTS_ID).one())

            users_me_resource = UserResource(
                user=await User.from_alchemy_obj(user),
                current_account=await Account.from_alchemy_obj(account),
                accounts=[await Account.from_alchemy_obj(other_accounts)],
            )

            self.assertDictEqual(
                {
                    "accounts": [{
                        "errors": {},
                        "id": ACCOUNT_INFRA_ID,
                        "name": ACCOUNT_INFRA_NAME,
                        "namespace": ACCOUNT_INFRA_NAMESPACE,
                        "owner": ACCOUNT_INFRA_OWNER,
                        "type": "ASGARD",
                    }],
                    "current_account": {
                        "errors": {},
                        "id": ACCOUNT_DEV_ID,
                        "name": ACCOUNT_DEV_NAME,
                        "namespace": ACCOUNT_DEV_NAMESPACE,
                        "owner": ACCOUNT_DEV_OWNER,
                        "type": "ASGARD",
                    },
                    "user": {
                        "email": USER_WITH_MULTIPLE_ACCOUNTS_EMAIL,
                        "errors": {},
                        "id": USER_WITH_MULTIPLE_ACCOUNTS_ID,
                        "name": USER_WITH_MULTIPLE_ACCOUNTS_NAME,
                        "type": "ASGARD",
                    },
                },
                users_me_resource.dict(),
            )
예제 #4
0
async def whoami(request):
    user = await User.from_alchemy_obj(request.user)
    current_account = await Account.from_alchemy_obj(
        request.user.current_account
    )

    alternate_accounts = await UsersService.get_alternate_accounts(
        user, current_account, UsersBackend()
    )

    resource_response = UserResource(
        user=user, current_account=current_account, accounts=alternate_accounts
    )

    return json_response(resource_response.dict())
예제 #5
0
    async def test_delete_user_user_with_accounts(self):
        resp = await self.client.delete(
            f"/users/{USER_WITH_MULTIPLE_ACCOUNTS_ID}",
            headers={
                "Authorization":
                f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
        )
        self.assertEqual(200, resp.status)
        resp_data = await resp.json()
        self.assertEqual(
            UserResource(user=User(**USER_WITH_MULTIPLE_ACCOUNTS_DICT)).dict(),
            resp_data,
        )
        other_users = await self.client.get(
            f"/users",
            headers={
                "Authorization": f"Token {USER_WITH_ONE_ACCOUNT_AUTH_KEY}"
            },
        )

        other_users_data = await other_users.json()
        self.assertCountEqual(
            UserListResource(users=[
                User(**USER_WITH_NO_ACCOUNTS_DICT),
                User(**USER_WITH_ONE_ACCOUNT_DICT),
            ]).dict(),
            other_users_data,
        )
예제 #6
0
async def user_by_id(request: web.Request):

    user_id: str = request.match_info["user_id"]
    user = await UsersService.get_user_by_id(int(user_id), UsersBackend())
    status_code = HTTPStatus.OK if user else HTTPStatus.NOT_FOUND
    return web.json_response(UserResource(user=user).dict(),
                             status=status_code)
예제 #7
0
async def update_user_partial(request: web.Request):
    user_id: str = request.match_info["user_id"]

    try:
        body_data = await request.json()
    except JSONDecodeError as e:
        return web.json_response(
            ErrorResource(errors=[ErrorDetail(msg=str(e))]).dict(),
            status=HTTPStatus.UNPROCESSABLE_ENTITY,
        )

    user = await UsersService.get_user_by_id(int(user_id), UsersBackend())
    status_code = HTTPStatus.ACCEPTED if user else HTTPStatus.NOT_FOUND

    try:
        if user:
            body_user = User(**body_data)
            user.name = body_user.name if body_user.name else user.name
            user.email = body_user.email if body_user.email else user.email
            updated_user = await UsersService.update_user(user, UsersBackend())
    except DuplicateEntity as de:
        return web.json_response(
            ErrorResource(errors=[ErrorDetail(msg=str(de))]).dict(),
            status=status_code,
        )

    return web.json_response(UserResource(user=updated_user).dict(),
                             status=status_code)
예제 #8
0
    async def test_update_user_duplicate_email(self):
        expected_new_email = USER_WITH_NO_ACCOUNTS_EMAIL
        new_user_data = {"email": expected_new_email}

        resp = await self.client.patch(
            f"/users/{USER_WITH_MULTIPLE_ACCOUNTS_ID}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            json=new_user_data,
        )
        self.assertEqual(HTTPStatus.ACCEPTED, resp.status)
        user_data = await resp.json()

        new_user = User(**USER_WITH_MULTIPLE_ACCOUNTS_DICT)
        new_user.name = expected_new_email
        expected_error_message = """ERROR:  duplicate key value violates unique constraint "user_tx_email_key"\nDETAIL:  Key (tx_email)=([email protected]) already exists.\n"""
        self.assertEqual(
            ErrorResource(
                errors=[ErrorDetail(msg=expected_error_message)]
            ).dict(),
            user_data,
        )

        resp = await self.client.get(
            f"/users/{USER_WITH_MULTIPLE_ACCOUNTS_ID}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
        )
        updated_user_data = await resp.json()
        self.assertEqual(
            UserResource(user=User(**USER_WITH_MULTIPLE_ACCOUNTS_DICT)).dict(),
            updated_user_data,
        )
예제 #9
0
    async def test_update_user_cant_update_another_user(self):
        """
        Dado um request 
          PATCH /users/42
          {"id": 50, "name": "Nome", "email": "email"}

        Não podemos, no final das contas ter atualizado o user id=50. Temos que atualizar o user id=42
        """
        expected_new_name = "Novo Nome"
        expected_new_email = "*****@*****.**"

        new_user = User(**USER_WITH_MULTIPLE_ACCOUNTS_DICT)
        new_user.name = expected_new_name
        new_user.email = expected_new_email
        new_user.id = USER_WITH_NO_ACCOUNTS_ID

        resp = await self.client.patch(
            f"/users/{USER_WITH_MULTIPLE_ACCOUNTS_ID}",
            headers={
                "Authorization":
                f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            json=new_user.dict(),
        )
        self.assertEqual(HTTPStatus.ACCEPTED, resp.status)
        user_data = await resp.json()

        expected_returned_user = User(**USER_WITH_MULTIPLE_ACCOUNTS_DICT)
        expected_returned_user.name = expected_new_name
        expected_returned_user.email = expected_new_email
        self.assertEqual(
            UserResource(user=expected_returned_user).dict(), user_data)

        resp = await self.client.get(
            f"/users/{USER_WITH_NO_ACCOUNTS_ID}",
            headers={
                "Authorization":
                f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
        )
        updated_user_data = await resp.json()
        self.assertEqual(
            UserResource(user=User(**USER_WITH_NO_ACCOUNTS_DICT)).dict(),
            updated_user_data,
        )
예제 #10
0
async def create_user(request: web.Request):
    status_code = HTTPStatus.CREATED
    try:
        user = User(**await request.json())
    except ValueError:
        return web.json_response(UserResource().dict(),
                                 status=HTTPStatus.BAD_REQUEST)

    try:
        created_user = await UsersService.create_user(user, UsersBackend())
    except DuplicateEntity as de:
        return web.json_response(
            ErrorResource(errors=[ErrorDetail(msg=str(de))]).dict(),
            status=HTTPStatus.UNPROCESSABLE_ENTITY,
        )

    return web.json_response(UserResource(user=created_user).dict(),
                             status=status_code)
예제 #11
0
 async def test_delete_user_user_not_fount(self):
     resp = await self.client.delete(
         f"/users/99",
         headers={
             "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
         },
     )
     self.assertEqual(404, resp.status)
     resp_data = await resp.json()
     self.assertEqual(UserResource().dict(), resp_data)
예제 #12
0
 async def test_get_user_by_id_user_not_found(self):
     resp = await self.client.get(
         f"/users/99",
         headers={
             "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
         },
     )
     self.assertEqual(404, resp.status)
     user_data = await resp.json()
     self.assertEqual(UserResource(), user_data)
예제 #13
0
 async def test_get_user_by_id_user_exists(self):
     resp = await self.client.get(
         f"/users/{USER_WITH_MULTIPLE_ACCOUNTS_ID}",
         headers={
             "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
         },
     )
     self.assertEqual(200, resp.status)
     user_data = await resp.json()
     self.assertEqual(
         UserResource(user=User(**USER_WITH_MULTIPLE_ACCOUNTS_DICT)),
         user_data,
     )
예제 #14
0
    async def test_create_user_all_OK(self):
        user = User(name="New User", email="*****@*****.**")
        resp = await self.client.post(
            f"/users",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            json=user.dict(),
        )
        self.assertEqual(201, resp.status)
        user_data = await resp.json()

        expected_result = UserResource(user=user).dict()
        expected_result["user"]["id"] = ANY
        self.assertEqual(expected_result, user_data)