Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pytest anyio #101

Merged
merged 14 commits into from
Aug 24, 2021
26 changes: 26 additions & 0 deletions orm/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,10 @@ def __init__(
select_related=None,
limit_count=None,
offset=None,
order_args=None,
):
self.model_cls = model_cls
self.order_args = [] if order_args is None else order_args
self.filter_clauses = [] if filter_clauses is None else filter_clauses
self._select_related = [] if select_related is None else select_related
self.limit_count = limit_count
Expand Down Expand Up @@ -96,6 +98,10 @@ def build_select_expression(self):
clause = sqlalchemy.sql.and_(*self.filter_clauses)
expr = expr.where(clause)

if self.order_args:
order_args = self._prepare_order_args()
expr = expr.order_by(*order_args)

if self.limit_count:
expr = expr.limit(self.limit_count)

Expand Down Expand Up @@ -201,6 +207,16 @@ def select_related(self, related):
offset=self.query_offset,
)

def order_by(self, *args):
return self.__class__(
model_cls=self.model_cls,
filter_clauses=self.filter_clauses,
select_related=self._select_related,
limit_count=self.limit_count,
offset=self.query_offset,
order_args=args,
)

async def exists(self) -> bool:
expr = self.build_select_expression()
expr = sqlalchemy.exists(expr).select()
Expand Down Expand Up @@ -285,6 +301,16 @@ async def create(self, **kwargs):
instance.pk = await self.database.execute(expr)
return instance

def _prepare_order_args(self):
prepared_args = []
for order_arg in self.order_args:
is_desc = order_arg.startswith("-")
column_name = order_arg.lstrip("-") if is_desc else order_arg
column = self.model_cls.__table__.columns[column_name]
prepared_args.append(column.desc() if is_desc else column)

return prepared_args


class Model(typesystem.Schema, metaclass=ModelMetaclass):
__abstract__ = True
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ flake8
isort
mypy
pytest
pytest-asyncio
pytest-cov
18 changes: 1 addition & 17 deletions tests/test_columns.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import asyncio
import datetime
import functools
from enum import Enum

import databases
Expand Down Expand Up @@ -47,21 +45,7 @@ def create_test_database():
metadata.drop_all(engine)


def async_adapter(wrapped_func):
"""
Decorator used to run async test cases.
"""

@functools.wraps(wrapped_func)
def run_sync(*args, **kwargs):
loop = asyncio.new_event_loop()
task = wrapped_func(*args, **kwargs)
return loop.run_until_complete(task)

return run_sync


@async_adapter
@pytest.mark.asyncio
async def test_model_crud():
async with database:
await Example.objects.create()
Expand Down
25 changes: 4 additions & 21 deletions tests/test_foreignkey.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import asyncio
import functools

import databases
import pytest
import sqlalchemy
Expand Down Expand Up @@ -69,21 +66,7 @@ def create_test_database():
metadata.drop_all(engine)


def async_adapter(wrapped_func):
"""
Decorator used to run async test cases.
"""

@functools.wraps(wrapped_func)
def run_sync(*args, **kwargs):
loop = asyncio.new_event_loop()
task = wrapped_func(*args, **kwargs)
return loop.run_until_complete(task)

return run_sync


@async_adapter
@pytest.mark.asyncio
async def test_model_crud():
async with database:
album = await Album.objects.create(name="Malibu")
Expand All @@ -100,7 +83,7 @@ async def test_model_crud():
assert track.album.name == "Malibu"


@async_adapter
@pytest.mark.asyncio
async def test_select_related():
async with database:
album = await Album.objects.create(name="Malibu")
Expand All @@ -122,7 +105,7 @@ async def test_select_related():
assert len(tracks) == 6


@async_adapter
@pytest.mark.asyncio
async def test_fk_filter():
async with database:
malibu = await Album.objects.create(name="Malibu")
Expand Down Expand Up @@ -166,7 +149,7 @@ async def test_fk_filter():
assert track.album.name == "Malibu"


@async_adapter
@pytest.mark.asyncio
async def test_multiple_fk():
async with database:
acme = await Organisation.objects.create(ident="ACME Ltd")
Expand Down
75 changes: 49 additions & 26 deletions tests/test_models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import asyncio
import functools

import databases
import pytest
import sqlalchemy
Expand Down Expand Up @@ -40,20 +37,6 @@ def create_test_database():
metadata.drop_all(engine)


def async_adapter(wrapped_func):
"""
Decorator used to run async test cases.
"""

@functools.wraps(wrapped_func)
def run_sync(*args, **kwargs):
loop = asyncio.new_event_loop()
task = wrapped_func(*args, **kwargs)
return loop.run_until_complete(task)

return run_sync


def test_model_class():
assert list(User.fields.keys()) == ["id", "name"]
assert isinstance(User.fields["id"], orm.Integer)
Expand All @@ -69,7 +52,7 @@ def test_model_pk():
assert user.id == 1


@async_adapter
@pytest.mark.asyncio
async def test_model_crud():
async with database:
users = await User.objects.all()
Expand All @@ -95,7 +78,7 @@ async def test_model_crud():
assert users == []


@async_adapter
@pytest.mark.asyncio
async def test_model_get():
async with database:
with pytest.raises(orm.NoMatch):
Expand All @@ -114,7 +97,7 @@ async def test_model_get():
assert same_user.pk == user.pk


@async_adapter
@pytest.mark.asyncio
async def test_model_filter():
async with database:
await User.objects.create(name="Tom")
Expand Down Expand Up @@ -174,15 +157,55 @@ async def test_model_filter():
assert await products.count() == 3


@async_adapter
@pytest.mark.asyncio
async def test_model_order_by():
async with database:
await User.objects.create(name="Tom")
await User.objects.create(name="Allen")
await User.objects.create(name="Bob")
users = await User.objects.order_by("name").all()
assert len(users) == 3
assert users[0].name == "Allen"
assert users[1].name == "Bob"
assert users[2].name == "Tom"


@pytest.mark.asyncio
async def test_model_order_by_desc():
async with database:
await User.objects.create(name="Tom")
await User.objects.create(name="Allen")
await User.objects.create(name="Bob")
users = await User.objects.order_by("-name").all()
assert len(users) == 3
assert users[0].name == "Tom"
assert users[1].name == "Bob"
assert users[2].name == "Allen"


@pytest.mark.asyncio
async def test_model_order_by_multi():
async with database:
await User.objects.create(name="Tom")
await User.objects.create(name="Tom")
await User.objects.create(name="Allen")
users = await User.objects.order_by("name", "-id").all()
assert len(users) == 3
assert users[0].name == "Allen"
assert users[0].id == 3
assert users[1].name == "Tom"
assert users[1].id == 2


@pytest.mark.asyncio
async def test_model_exists():
async with database:
await User.objects.create(name="Tom")
assert await User.objects.filter(name="Tom").exists() is True
assert await User.objects.filter(name="Jane").exists() is False


@async_adapter
@pytest.mark.asyncio
async def test_model_count():
async with database:
await User.objects.create(name="Tom")
Expand All @@ -193,7 +216,7 @@ async def test_model_count():
assert await User.objects.filter(name__icontains="T").count() == 1


@async_adapter
@pytest.mark.asyncio
async def test_model_limit():
async with database:
await User.objects.create(name="Tom")
Expand All @@ -203,7 +226,7 @@ async def test_model_limit():
assert len(await User.objects.limit(2).all()) == 2


@async_adapter
@pytest.mark.asyncio
async def test_model_limit_with_filter():
async with database:
await User.objects.create(name="Tom")
Expand All @@ -213,7 +236,7 @@ async def test_model_limit_with_filter():
assert len(await User.objects.limit(2).filter(name__iexact="Tom").all()) == 2


@async_adapter
@pytest.mark.asyncio
async def test_offset():
async with database:
await User.objects.create(name="Tom")
Expand All @@ -223,7 +246,7 @@ async def test_offset():
assert users[0].name == "Jane"


@async_adapter
@pytest.mark.asyncio
async def test_model_first():
async with database:
tom = await User.objects.create(name="Tom")
Expand Down