async def update_todo(id: str, request: Request, todo: UpdateTodo): async with request.app.pool.acquire() as con: result = await con.fetchrow( ''' SELECT * FROM todos WHERE id = $1 ''', int(id)) if not result: raise HTTPException(status_code=404, detail='Todo with ID ' + id + ' not found!') result_todo = Todo(**dict(result)) update_data = todo.dict(exclude_unset=True) updated_todo = result_todo.copy(update=update_data) result = await con.execute( ''' UPDATE todos SET name = $1, description = $2 WHERE id = $3 RETURNING name ''', updated_todo.name, updated_todo.description, int(id)) return updated_todo
def test_get_list_with_multiple_todos(repository: Repository) -> None: id_1, text_1 = _insert_todo(repository, "This is a Todo!") id_2, text_2 = _insert_todo(repository, "This is a ANOTHER Todo!") todos = repository.list() assert todos == tuple( sorted((Todo(id=id_1, text=text_1, active=True), Todo(id=id_2, text=text_2, active=True))))
def test_mark_complete_existing_todo(repository: Repository) -> None: id_1, text_1 = _insert_todo(repository, "This is a Todo!") id_2, text_2 = _insert_todo(repository, "This is a ANOTHER Todo!") result = repository.deactivate(id_2) assert result todos = repository.list() assert todos == tuple( sorted((Todo(id=id_1, text=text_1, active=True), Todo(id=id_2, text=text_2, active=False))))
def test_edit_text_existing_todo(repository: Repository) -> None: id_1, text_1 = _insert_todo(repository, "This is a Todo!") id_2, text_2 = _insert_todo(repository, "This is a ANOTHER Todo!") result = repository.edit_text(id_2, "Hello") assert result todos = repository.list() assert todos == tuple( sorted((Todo(id=id_1, text=text_1, active=True), Todo(id=id_2, text="Hello", active=True))))
def current_user(): from faker import Faker from app.helpers.session_helper import hash_password from app.models.user import User from app.models.todo import Todo fake = Faker() email = f"test_user_{fake.random_number(digits=10)}@test.com" user = User( name=fake.name(), email=email, encrypted_password=hash_password("password"), location=f"{fake.city()} {fake.country()}", profile=fake.paragraph(), ) user.todos.append( Todo( title="Test Todo", status="none", description="test todo", ) ) session = db_helper.session() session.add(user) session.commit() user = session.query(User).filter(User.email == email).first() session.close() api = app.main.api api.requests.post("/login", {"email": user.email, "password": "******"}) return user
def run(self): """ Run TodosSeeder actions. """ # Drop all collections db.session.query(Todo).delete() # Generate cards id list cards = Card.query.all() card_ids = list(map(lambda card: card.id, cards)) # Generate fake data faker = Faker() for todo in range(180): card = random.choice(cards) todo = Todo( **{ 'owner_id': card.owner_id, 'title': faker.sentence(), 'note': faker.paragraph(nb_sentences=2), 'card_id': card.id, }) db.session.add(todo) # Commit db session db.session.commit()
async def get_todos(request: Request): async with request.app.pool.acquire() as con: result = await con.fetch(''' SELECT * FROM todos; ''') return [Todo(**dict(record)) for record in result]
def get(self, id_: UUID) -> Optional[Todo]: with self._cursor() as curs: curs.execute(self.SQL.GET, {"id": id_}) row = curs.fetchone() if row is None: return None else: return Todo(id=id_, text=row[0], active=row[1])
def post(self): """ Add todo item """ args = self.post_parser.parse_args() todo = Todo(name=args['name'], done=args['done']) return store_todos(todo)
def test_edit_text_not_existing_todo(repository: Repository) -> None: id_, text = _insert_todo(repository, "This is a Todo!") result = repository.edit_text(_random_id(), "Hello World") assert not result todo = repository.get(id_) assert todo == Todo(id=id_, text=text, active=True)
def test_delete_not_existing_todo(repository: Repository) -> None: id_, text = _insert_todo(repository, "This is a Todo!") result = repository.delete(_random_id()) assert not result todo = repository.get(id_) assert todo == Todo(id=id_, text=text, active=True)
def get(self, id: UUID) -> Todo: doc_ref = db.collection(self.collection_name).document(str(id)) doc = doc_ref.get() if doc.exists: return Todo(**doc.to_dict()) return None
def test_delete_existing_todo(repository: Repository) -> None: id_1, _ = _insert_todo(repository, "This is a Todo!") id_2, text_2 = _insert_todo(repository, "This is a ANOTHER Todo!") result = repository.delete(id_1) assert result todos = repository.list() assert todos == (Todo(id=id_2, text=text_2, active=True), )
def list(self) -> Tuple[Todo, ...]: todos = [] with self._cursor() as curs: curs.execute(self.SQL.LIST) for row in curs: todo = Todo(id=row[0], text=row[1], active=row[2]) todos.append(todo) return tuple(todos)
def create(self, args): """ Create new todo. :param args: New todo validated information :return: New todo data """ # Create new todo args['owner_id'] = current_user.id todo = Todo(**args) todo.save() db.session.commit() # Respond with new todo data todo_schema = TodoSchema() return json_response(code=201, message='Successfully created a new todo.', data=[todo_schema.dump(todo).data])
def post(self): json_data = request.get_json(force=True) if not json_data: return {'message': 'No input data provided'}, 400 # Validate and deserialize input data, erros = todo_schema.load(json_data) if erros: return erros, 422 todo = Todo.query.filter_by(title=data['title']).first() if todo: return {'message': 'Todo already exists'}, 400 todo = Todo(title=json_data['title']) db.session.add(todo) db.session.commit() result = todo_schema.dump(todo).data return {'status': 'success', 'data': result}, 201
def test_get_existing_todo(repository: Repository) -> None: id_1, text_1 = _insert_todo(repository, "This is a Todo!") _insert_todo(repository, "This is a ANOTHER Todo!") todo = repository.get(id_1) assert todo == Todo(id=id_1, text=text_1, active=True)
def deactivate(self, id_: UUID) -> bool: delta = lambda todo: Todo(id=id_, text=todo.text, active=False) return self._update(id_=id_, delta=delta)
def update(self, request): r = Todo.save_from_message(request) return messages.RetrieveResponse(item=r.to_message())
def list(self) -> List[Todo]: todos_ref = db.collection(self.collection_name) return [Todo(**doc.get().to_dict()) for doc in todos_ref.list_documents() if doc.get().to_dict()]
def list(self, request): items = [r.to_message() for r in Todo.query().fetch()] return messages.ListResponse(items=items)
async def get_list(user: User = Depends(get_current_user)): return await Todo_Pydantic.from_queryset(Todo.filter(user=user))
def retrieve(self, request): r = Todo.get_by_id(request.id) return messages.RetrieveResponse(item=r.to_message())
def test_get_list_with_single_todo(repository: Repository) -> None: id_, text = _insert_todo(repository, "This is a Todo!") todos = repository.list() assert todos == (Todo(id=id_, text=text, active=True), )
import pytest import pysnooper import mock from alchemy_mock.mocking import UnifiedAlchemyMagicMock from app.services.todo_service import get_todos from app.repository.database import db from app.models.todo import Todo from app.constants import STATUS_CODE mockTodo = Todo(name="name", done=False) # db.session mocking session = UnifiedAlchemyMagicMock(data=[ ( [mock.call.query(Todo), mock.call.filter(Todo.name == mockTodo.name, Todo.done == mockTodo.done) ], [mockTodo] ) ]) # class TestTodoService: # @pysnooper.snoop() # @mock.patch('app.repository.database.db.session', new=session) # def test_테스트(self, flask_app): # response = get_todos(name=mockTodo.name, done=mockTodo.done) # assert response.status_code == STATUS_CODE.OK.value
def insert(self, text: str) -> UUID: id_ = uuid1() todo = Todo(id=id_, text=text, active=True) assert self._todos.get(id_) is None self._todos[id_] = todo return id_
def edit_text(self, id_: UUID, text: str) -> bool: delta = lambda todo: Todo(id=id_, text=text, active=todo.active) return self._update(id_=id_, delta=delta)
def delete(self, request): Todo.get_by_id(request.id).key.delete() return messages.DeleteResponse()