Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,6 @@ dmypy.json

# Pyre type checker
.pyre/

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нигде не используется в текущей реализации

# uv pocket manager
uv.lock
4 changes: 4 additions & 0 deletions rating_api/models/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ class Lecturer(BaseDbModel):
avatar_link: Mapped[str] = mapped_column(String, nullable=True, comment="Ссылка на аву препода")
timetable_id: Mapped[int]
comments: Mapped[list[Comment]] = relationship("Comment", back_populates="lecturer")
lecturer_user_comments: Mapped[list[LecturerUserComment]] = relationship(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

каскадное удаление нам не нужно, relationship можно не делать, предположительно проблема в самих эндпоинтах в этот раз
Честно немного не понял и запутался что не так с логикой и почему из-за этого 57 тестов падает, объясни пожалуйста)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

и еще, у нас же софтделиты, поэтому каскад точно не нужен
каскад это для хардделита

"LecturerUserComment", back_populates="lecturer", cascade="all, delete-orphan"
)
mark_weighted: Mapped[float] = mapped_column(
Float,
nullable=False,
Expand Down Expand Up @@ -288,6 +291,7 @@ class LecturerUserComment(BaseDbModel):
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int] = mapped_column(Integer, nullable=False)
lecturer_id: Mapped[int] = mapped_column(Integer, ForeignKey("lecturer.id"))
lecturer: Mapped[Lecturer] = relationship("Lecturer", back_populates="lecturer_user_comments")
create_ts: Mapped[datetime.datetime] = mapped_column(
DateTime, default=datetime.datetime.now(datetime.timezone.utc), nullable=False
)
Expand Down
50 changes: 39 additions & 11 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,16 +92,46 @@ def dbsession(db_container):


@pytest.fixture
def client(mocker):
user_mock = mocker.patch('auth_lib.fastapi.UnionAuth.__call__')
user_mock.return_value = {
"session_scopes": [{"id": 0, "name": "string", "comment": "string"}],
"user_scopes": [{"id": 0, "name": "string", "comment": "string"}],
"indirect_groups": [{"id": 0, "name": "string", "parent_id": 0}],
"groups": [{"id": 0, "name": "string", "parent_id": 0}],
def authlib_user():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

верни исходную структуру, как было все
надо добавить только
"userdata": [ {"category": "Личная информация", "param": "Полное имя", "value": "Тестовый Тест"}, ],
что собственно ты и сделал, остальное не нужно

"""
Данные о пользователе, возвращаемые сервисом auth.
"""
return {
"auth_methods": ["email", "github_auth"],
"session_scopes": [
{"id": 145, "name": "auth.session.create"},
{"id": 146, "name": "auth.session.update"},
{"id": 165, "name": "auth.user.selfdelete"},
],
"user_scopes": [
{"id": 145, "name": "auth.session.create"},
{"id": 146, "name": "auth.session.update"},
{"id": 165, "name": "auth.user.selfdelete"},
],
"indirect_groups": [99],
"groups": [99],
"id": 0,
"email": "string",
"email": "aslimbo2001@gmail.com",
"userdata": [
{"category": "Личная информация", "param": "Полное имя", "value": "Тестовый Тест"},
],
}


@pytest.fixture()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

на разные фикстуры тоже разбивать это не надо

def authlib_mock(mocker):
auth_mock = mocker.patch("auth_lib.fastapi.UnionAuth.__call__")
return auth_mock


@pytest.fixture()
def user_mock(authlib_mock, authlib_user):
authlib_mock.return_value = authlib_user
return authlib_mock


@pytest.fixture
def client(mocker, user_mock):
client = TestClient(app)
return client

Expand Down Expand Up @@ -214,11 +244,9 @@ def lecturers(dbsession):
Lecturer(id=4, first_name='test_fname3', last_name='test_lname3', middle_name='test_mname3', timetable_id=9903)
)
lecturers[-1].is_deleted = True
for lecturer in lecturers:
dbsession.add(lecturer)
dbsession.add_all(lecturers)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

думаю, что это можно не добавлять, зачем

dbsession.commit()
yield lecturers

for lecturer in lecturers:
for row in lecturer.comments:
dbsession.delete(row)
Expand Down
11 changes: 11 additions & 0 deletions tests/test_routes/test_comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging

import pytest
from auth_lib.fastapi import UnionAuth

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

надо будет убрать, см комменты ниже

from starlette import status

from rating_api.models import Comment, CommentReaction, LecturerUserComment, Reaction, ReviewStatus
Expand Down Expand Up @@ -177,6 +178,16 @@
def test_create_comment(client, dbsession, lecturers, body, lecturer_n, response_status):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

добавь здесь в конце assert на проверку грамотности некоторых полей по типу что действительно при неанонимном комменте ставится имя не null

params = {"lecturer_id": lecturers[lecturer_n].id}
post_response = client.post(url, json=body, params=params)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это не нужно будет при правильном моке(см ниже)

# Проверка корректности переданных в userdata "param"
user = UnionAuth.__call__(post_response)
acceptable_params = ["Полное имя", "Фото", "Имя пользователя GitHub", "Номер Телефона"]
real_params = [i["param"] for i in user.get("userdata")]
for param in real_params:
assert (
param in acceptable_params
), f"Не допустимый параметр: \"{i}\"! Список допустимых параметров: {acceptable_params}"

assert post_response.status_code == response_status
if response_status == status.HTTP_200_OK:
comment = Comment.query(session=dbsession).filter(Comment.uuid == post_response.json()["uuid"]).one_or_none()
Expand Down
Loading