Skip to content

Commit

Permalink
Bck 69-43-65 / 500 (#111)
Browse files Browse the repository at this point in the history
* Решена проблема 500. Решена проблема падения тестов регистрации пользователя из-за ошибки отправки email (BCK-43).

* Решена проблема 500. Решена проблема падения тестов регистрации пользователя из-за ошибки отправки email (BCK-43).

* Решена проблема 500. Решена проблема падения тестов регистрации пользователя из-за ошибки отправки email (BCK-43).

* Решена проблема 500. Решена проблема падения тестов регистрации пользователя из-за ошибки отправки email (BCK-43).

* Решена проблема 500. Решена проблема падения тестов регистрации пользователя из-за ошибки отправки email (BCK-43).

* [add] logger

* [add] logger

* [add] logger

---------

Co-authored-by: mxnoob <[email protected]>
  • Loading branch information
CuriousGecko and mxnoob authored Aug 21, 2024
1 parent 257016c commit e79dc9c
Show file tree
Hide file tree
Showing 9 changed files with 51 additions and 30 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ jobs:
- name: Test with pytest
env:
DATABASE_URL: postgresql+asyncpg://${{ secrets.POSTGRES_USER }}:${{ secrets.POSTGRES_PASSWORD }}@${{ secrets.POSTGRES_HOST_TEST }}:5432/${{ secrets.POSTGRES_DB }}
EMAIL_MOCK_SERVER: ${{ secrets.EMAIL_MOCK_SERVER }}
EMAIL_FROM: ${{ secrets.EMAIL_FROM }}
EMAIL_HOST: ${{ secrets.EMAIL_HOST }}
EMAIL_PORT: ${{ secrets.EMAIL_PORT }}
Expand All @@ -79,6 +80,7 @@ jobs:
cd infra/
touch .env
echo DATABASE_URL=${{ secrets.DATABASE_URL }} >> .env
echo EMAIL_MOCK_SERVER =${{ secrets.EMAIL_MOCK_SERVER }} >> .env
echo EMAIL_FROM=${{ secrets.EMAIL_FROM }} >> .env
echo EMAIL_HOST=${{ secrets.EMAIL_HOST }} >> .env
echo EMAIL_PORT=${{ secrets.EMAIL_PORT }} >> .env
Expand Down
10 changes: 8 additions & 2 deletions app/api/endpoints/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ async def get_all_profiles(
@router.get(
'/me',
response_model=ProfileRead,
dependencies=[Depends(current_user)],
response_model_exclude_none=True,
**GET_ME_PROFILE,
)
Expand All @@ -59,10 +60,12 @@ async def get_current_user_profile(
user: User = Depends(current_user)
) -> ProfileRead:
"""Возвращает профиль текущего пользователя."""
return await profile_crud.get_users_obj(
obj = await profile_crud.get_users_obj(
user_id=user.id,
session=session
)
await check_obj_exists(obj=obj)
return obj


@router.get(
Expand Down Expand Up @@ -91,7 +94,9 @@ async def get_user_photo(
session: AsyncSession = Depends(get_async_session)
):
"""Возвращает фото профиля."""
return await profile_crud.get_user_photo(user_id=user.id, session=session)
obj = await profile_crud.get_user_photo(user_id=user.id, session=session)
await check_obj_exists(obj=obj)
return obj


@router.patch(
Expand All @@ -107,6 +112,7 @@ async def update_profile(
):
"""Обновить профиль текущего пользователя."""
obj = await profile_crud.get_users_obj(user_id=user.id, session=session)
await check_obj_exists(obj=obj)
return await profile_crud.update(
db_obj=obj,
obj_in=profile,
Expand Down
1 change: 1 addition & 0 deletions app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class Settings(BaseSettings):
limit: int = 10

# ======== email config ==========
EMAIL_MOCK_SERVER: bool
EMAIL_FROM: str
EMAIL_HOST: str
EMAIL_PORT: int
Expand Down
5 changes: 5 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from app.core.config import settings
from app.core.db import engine
from app.core.init_db import create_first_superuser
from app.services.mail import MockEmailServer


def swagger_monkey_patch(*args, **kwargs):
Expand Down Expand Up @@ -54,3 +55,7 @@ def swagger_monkey_patch(*args, **kwargs):
async def startup():
await create_first_superuser()
await add_admin_models(admin)

if settings.EMAIL_MOCK_SERVER:
email_server = MockEmailServer()
email_server.start()
3 changes: 2 additions & 1 deletion app/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
aiosmtpd==1.4.6
aiosmtplib==3.0.1
aiosqlite==0.17.0
alembic==1.13.0
Expand All @@ -19,4 +20,4 @@ SQLAlchemy==2.0.23
SQLAlchemy-Utils==0.41.2
starlette==0.27.0
typing_extensions==4.8.0
uvicorn==0.24.0.post1
uvicorn==0.24.0.post1
55 changes: 32 additions & 23 deletions app/services/mail.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
import logging
import re
from email.message import EmailMessage
from http import HTTPStatus

from aiosmtpd.controller import Controller
from aiosmtplib import SMTP, errors
from fastapi import HTTPException

from app.core.config import settings

logger = logging.getLogger(__name__)


class MockEmailServer:
def __init__(self, port=settings.EMAIL_PORT):
self.port = port
self.controller = Controller(handler=None, port=self.port)

def start(self):
"""Запустит почтовый сервер."""
self.controller.start()
logger.info('Email server started on port %s.', self.port)


class MailMessage:
def __init__(self, to=None, subject='', text=''):
Expand Down Expand Up @@ -37,28 +50,24 @@ async def send_email_message(self):
message['Subject'] = self.subject
message.set_content(self.text)

smtp_client = SMTP(
hostname=settings.EMAIL_HOST,
port=settings.EMAIL_PORT,
username=settings.EMAIL_HOST_USER,
password=settings.EMAIL_HOST_PASSWORD,
use_tls=settings.EMAIL_USE_TLS,
)
if settings.EMAIL_MOCK_SERVER:
smtp_client = SMTP(port=settings.EMAIL_PORT)
else:
smtp_client = SMTP(
hostname=settings.EMAIL_HOST,
port=settings.EMAIL_PORT,
username=settings.EMAIL_HOST_USER,
password=settings.EMAIL_HOST_PASSWORD,
use_tls=settings.EMAIL_USE_TLS,
)
try:
async with smtp_client:
await smtp_client.send_message(message)
except errors.SMTPConnectError:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail='Нет соединения с SMTP сервером.',
)
except errors.SMTPAuthenticationError:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail='Ошибка соединения с SMTP сервером.',
)
except Exception:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail='Увы, что-то пошло не так.',
except errors.SMTPConnectError as e:
logger.exception('Нет соединения с SMTP сервером. %s', e)
except errors.SMTPAuthenticationError as e:
logger.exception('Ошибка соединения с SMTP сервером. %s', e)
except Exception as e:
logger.exception(
'Во время отправки email что-то пошло не так: %s', e
)
1 change: 1 addition & 0 deletions infra/.env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
DATABASE_URL=sqlite+aiosqlite:///./fastapi.db
SECRET=MocSecret

EMAIL_MOCK_SERVER=False
EMAIL_FROM=[email protected]
EMAIL_HOST=email_host
EMAIL_PORT=64000
Expand Down
2 changes: 0 additions & 2 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import pytest
from fastapi import status

from tests.fixtures.user import USER_EMAIL, USER_PASSWORD, USER_USERNAME
Expand Down Expand Up @@ -45,7 +44,6 @@


class TestRegister:
@pytest.mark.skip
async def test_register_new_user(self, new_client):
"""Тест регистрации пользователя с корректными данными."""
response = await new_client.post(
Expand Down
2 changes: 0 additions & 2 deletions tests/test_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from pathlib import Path
from typing import AsyncGenerator

import pytest
from fastapi import Response, status
from fastapi.testclient import TestClient
from PIL import Image
Expand Down Expand Up @@ -47,7 +46,6 @@ async def _get_user(


class TestProfile:
@pytest.mark.skip
async def test_create_profile_with_create_user(
self, new_client,
db_session: AsyncSession
Expand Down

0 comments on commit e79dc9c

Please sign in to comment.