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
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def get_packages(package):
packages=get_packages(PACKAGE),
package_data={PACKAGE: ["py.typed"]},
data_files=[("", ["LICENSE.md"])],
install_requires=["databases>=0.2.1", "typesystem"],
install_requires=["anyio>=3.0.0,<4", "databases>=0.2.1", "typesystem"],
aminalaee marked this conversation as resolved.
Show resolved Hide resolved
extras_require={
"postgresql": ["asyncpg"],
aminalaee marked this conversation as resolved.
Show resolved Hide resolved
"mysql": ["aiomysql"],
Expand Down
6 changes: 6 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import pytest


@pytest.fixture
def anyio_backend():
return ("asyncio", {"debug": True})
19 changes: 2 additions & 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 All @@ -10,6 +8,8 @@
import orm
from tests.settings import DATABASE_URL

pytestmark = pytest.mark.anyio

database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()

Expand Down Expand Up @@ -47,21 +47,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


@async_adapter
async def test_model_crud():
async with database:
await Example.objects.create()
Expand Down
23 changes: 2 additions & 21 deletions tests/test_foreignkey.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import asyncio
import functools

import databases
import pytest
import sqlalchemy

import orm
from tests.settings import DATABASE_URL

pytestmark = pytest.mark.anyio

database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()

Expand Down Expand Up @@ -69,21 +68,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


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


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


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


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

import databases
import pytest
import sqlalchemy

import orm
from tests.settings import DATABASE_URL

pytestmark = pytest.mark.anyio

database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()

Expand Down Expand Up @@ -40,20 +39,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 +54,6 @@ def test_model_pk():
assert user.id == 1


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


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


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


@async_adapter
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"


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"


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


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
async def test_model_count():
async with database:
await User.objects.create(name="Tom")
Expand All @@ -193,7 +210,6 @@ async def test_model_count():
assert await User.objects.filter(name__icontains="T").count() == 1


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


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


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


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