WIP - Pydantic v2 support (#1238)

* WIP

* WIP - make test_model_definition tests pass

* WIP - make test_model_methods pass

* WIP - make whole test suit at least run - failing 49/443 tests

* WIP fix part of the getting pydantic tests as types of fields are now kept in core schema and not on fieldsinfo

* WIP fix validation in update by creating individual fields validators, failing 36/443

* WIP fix __pydantic_extra__ in intializing model, fix test related to pydantic config checks, failing 32/442

* WIP - fix enum schema in model_json_schema, failing 31/442

* WIP - fix copying through model, fix setting pydantic fields on through, fix default config and inheriting from it, failing 26/442

* WIP fix tests checking pydantic schema, fix excluding parent fields, failing 21/442

* WIP some missed files

* WIP - fix validators inheritance and fix validators in generated pydantic, failing 17/442

* WIP - fix through models setting - only on reverse side of relation, but always on reverse side, failing 15/442

* WIP - fix through models setting - only on reverse side of relation, but always on reverse side, failing 15/442

* WIP - working on proper populating __dict__ for relations for new schema dumping, some work on openapi docs, failing 13/442

* WIP - remove property fields as pydantic has now computed_field on its own, failing 9/442

* WIP - fixes in docs, failing 8/442

* WIP - fix tests for largebinary schema, wrapped bytes fields fail in pydantic, will be fixed in pydantic-core, remaining is circural schema for related models, failing 6/442

* WIP - fix to pk only models in schemas

* Getting test suites to pass (#1249)

* wip, fixing tests

* iteration, fixing some more tests

* iteration, fixing some more tests

* adhere to comments

* adhere to comments

* remove unnecessary dict call, re-add getattribute for testing

* todo for reverse relationship

* adhere to comments, remove prints

* solve circular refs

* all tests pass 🎉

* remove 3.7 from tests

* add lint and type check jobs

* reforat with ruff, fix jobs

* rename jobs

* fix imports

* fix evaluate in py3.8

* partially fix coverage

* fix coverage, add more tests

* fix test ids

* fix test ids

* fix lint, fix docs, make docs fully working scripts, add test docs job

* fix pyproject

* pin py ver in test docs

* change dir in test docs

* fix pydantic warning hack

* rm poetry call in test_docs

* switch to pathlib in test docs

* remove coverage req test docs

* fix type check tests, fix part of types

* fix/skip next part of types

* fix next part of types

* fix next part of types

* fix coverage

* fix coverage

* fix type (bit dirty 🤷)

* fix some code smells

* change pre-commit

* tweak workflows

* remove no root from tests

* switch to full python path by passing sys.executable

* some small refactor in new base model, one sample test, change makefile

* small refactors to reduce complexity of methods

* temp add tests for prs against pydantic_v2

* remove all references to __fields__

* remove all references to construct, deprecate the method and update model_construct to be in line with pydantic

* deprecate dict and add model_dump, todo switch to model_dict in calls

* fix tests

* change to union

* change to union

* change to model_dump and model_dump_json from dict and json deprecated methods, deprecate them in ormar too

* finish switching dict() -> model_dump()

* finish switching json() -> model_dump_json()

* remove fully pydantic_only

* switch to extra for payment card, change missed json calls

* fix coverage - no more warnings internal

* fix coverage - no more warnings internal - part 2

* split model_construct into own and pydantic parts

* split determine pydantic field type

* change to new field validators

* fix benchmarks, add codspeed instead of pytest-benchmark, add action and gh workflow

* restore pytest-benchmark

* remove codspeed

* pin pydantic version, restore codspeed

* change on push to pydantic_v2 to trigger first one

* Use lifespan function instead of event (#1259)

* check return types

* fix imports order, set warnings=False on json that passes the dict, fix unnecessary loop in one of the test

* remove references to model's meta as it's now ormar config, rename related methods too

* filter out pydantic serializer warnings

* remove choices leftovers

* remove leftovers after property_fields, keep only enough to exclude them in initialization

* add migration guide

* fix meta references

* downgrade databases for now

* Change line numbers in documentation (#1265)

* proofread and fix the docs, part 1

* proofread and fix the docs for models

* proofread and fix the docs for fields

* proofread and fix the docs for relations

* proofread and fix rest of the docs, add release notes for 0.20

* create tables in new docs src

* cleanup old deps, uncomment docs publish on tag

* fix import reorder

---------

Co-authored-by: TouwaStar <30479449+TouwaStar@users.noreply.github.com>
Co-authored-by: Goran Mekić <meka@tilda.center>
This commit is contained in:
collerek
2024-03-23 19:28:28 +01:00
committed by GitHub
parent 3a206dd8dc
commit 500625f0ec
294 changed files with 8132 additions and 9311 deletions

View File

@ -1,31 +1,23 @@
from typing import Optional
import databases
import pytest
import sqlalchemy
import asyncio
import ormar
import pytest
from tests.settings import DATABASE_URL
from tests.lifespan import init_tests
from tests.settings import create_config
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
base_ormar_config = create_config()
class Department(ormar.Model):
class Meta:
database = database
metadata = metadata
ormar_config = base_ormar_config.copy()
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
class Course(ormar.Model):
class Meta:
database = database
metadata = metadata
ormar_config = base_ormar_config.copy()
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
@ -33,18 +25,12 @@ class Course(ormar.Model):
department: Optional[Department] = ormar.ForeignKey(Department)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_adding_relation_to_reverse_saves_the_child():
async with database:
async with base_ormar_config.database:
department = await Department(name="Science").save()
course = Course(name="Math", completed=False)

View File

@ -1,36 +1,27 @@
from typing import Optional
import databases
import ormar
import pytest
import pytest_asyncio
import sqlalchemy
import ormar
from ormar.exceptions import QueryDefinitionError
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
class BaseMeta(ormar.ModelMeta):
metadata = metadata
database = database
base_ormar_config = create_config()
class Author(ormar.Model):
class Meta(BaseMeta):
tablename = "authors"
order_by = ["-name"]
ormar_config = base_ormar_config.copy(tablename="authors", order_by=["-name"])
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
class Book(ormar.Model):
class Meta(BaseMeta):
tablename = "books"
order_by = ["year", "-ranking"]
ormar_config = base_ormar_config.copy(
tablename="books", order_by=["year", "-ranking"]
)
id: int = ormar.Integer(primary_key=True)
author: Optional[Author] = ormar.ForeignKey(Author)
@ -39,19 +30,13 @@ class Book(ormar.Model):
ranking: int = ormar.Integer(nullable=True)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest_asyncio.fixture(autouse=True, scope="function")
async def cleanup():
yield
async with database:
async with base_ormar_config.database:
await Book.objects.delete(each=True)
await Author.objects.delete(each=True)
@ -65,7 +50,7 @@ async def sample_data():
@pytest.mark.asyncio
async def test_min_method():
async with database:
async with base_ormar_config.database:
await sample_data()
assert await Book.objects.min("year") == 1920
result = await Book.objects.min(["year", "ranking"])
@ -89,7 +74,7 @@ async def test_min_method():
@pytest.mark.asyncio
async def test_max_method():
async with database:
async with base_ormar_config.database:
await sample_data()
assert await Book.objects.max("year") == 1930
result = await Book.objects.max(["year", "ranking"])
@ -113,7 +98,7 @@ async def test_max_method():
@pytest.mark.asyncio
async def test_sum_method():
async with database:
async with base_ormar_config.database:
await sample_data()
assert await Book.objects.sum("year") == 5773
result = await Book.objects.sum(["year", "ranking"])
@ -138,7 +123,7 @@ async def test_sum_method():
@pytest.mark.asyncio
async def test_avg_method():
async with database:
async with base_ormar_config.database:
await sample_data()
assert round(float(await Book.objects.avg("year")), 2) == 1924.33
result = await Book.objects.avg(["year", "ranking"])
@ -166,7 +151,7 @@ async def test_avg_method():
@pytest.mark.asyncio
async def test_queryset_method():
async with database:
async with base_ormar_config.database:
await sample_data()
author = await Author.objects.select_related("books").get()
assert await author.books.min("year") == 1920
@ -180,7 +165,7 @@ async def test_queryset_method():
@pytest.mark.asyncio
async def test_count_method():
async with database:
async with base_ormar_config.database:
await sample_data()
count = await Author.objects.select_related("books").count()

View File

@ -1,20 +1,15 @@
import databases
import ormar
import pytest
from sqlalchemy import func
import ormar
import sqlalchemy
from tests.settings import DATABASE_URL
from tests.lifespan import init_tests
from tests.settings import create_config
database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()
base_ormar_config = create_config()
class Chart(ormar.Model):
class Meta(ormar.ModelMeta):
tablename = "charts"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="charts")
chart_id = ormar.Integer(primary_key=True, autoincrement=True)
name = ormar.String(max_length=200, unique=True, index=True)
@ -28,10 +23,7 @@ class Chart(ormar.Model):
class Report(ormar.Model):
class Meta(ormar.ModelMeta):
tablename = "reports"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="reports")
report_id = ormar.Integer(primary_key=True, autoincrement=True)
name = ormar.String(max_length=200, unique=True, index=True)
@ -40,10 +32,7 @@ class Report(ormar.Model):
class Language(ormar.Model):
class Meta(ormar.ModelMeta):
tablename = "languages"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="languages")
language_id = ormar.Integer(primary_key=True, autoincrement=True)
code = ormar.String(max_length=5)
@ -51,20 +40,14 @@ class Language(ormar.Model):
class TranslationNode(ormar.Model):
class Meta(ormar.ModelMeta):
tablename = "translation_nodes"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="translation_nodes")
node_id = ormar.Integer(primary_key=True, autoincrement=True)
node_type = ormar.String(max_length=200)
class Translation(ormar.Model):
class Meta(ormar.ModelMeta):
tablename = "translations"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="translations")
translation_id = ormar.Integer(primary_key=True, autoincrement=True)
node_id = ormar.ForeignKey(TranslationNode, related_name="translations")
@ -73,10 +56,7 @@ class Translation(ormar.Model):
class Filter(ormar.Model):
class Meta(ormar.ModelMeta):
tablename = "filters"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="filters")
filter_id = ormar.Integer(primary_key=True, autoincrement=True)
name = ormar.String(max_length=200, unique=True, index=True)
@ -90,10 +70,7 @@ class Filter(ormar.Model):
class FilterValue(ormar.Model):
class Meta(ormar.ModelMeta):
tablename = "filter_values"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="filter_values")
value_id = ormar.Integer(primary_key=True, autoincrement=True)
value = ormar.String(max_length=300)
@ -103,10 +80,7 @@ class FilterValue(ormar.Model):
class FilterXReport(ormar.Model):
class Meta(ormar.ModelMeta):
tablename = "filters_x_reports"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="filters_x_reports")
filter_x_report_id = ormar.Integer(primary_key=True)
filter = ormar.ForeignKey(Filter, name="filter_id", related_name="reports")
@ -117,10 +91,7 @@ class FilterXReport(ormar.Model):
class ChartXReport(ormar.Model):
class Meta(ormar.ModelMeta):
tablename = "charts_x_reports"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="charts_x_reports")
chart_x_report_id = ormar.Integer(primary_key=True)
chart = ormar.ForeignKey(Chart, name="chart_id", related_name="reports")
@ -130,10 +101,7 @@ class ChartXReport(ormar.Model):
class ChartColumn(ormar.Model):
class Meta(ormar.ModelMeta):
tablename = "charts_columns"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="charts_columns")
column_id = ormar.Integer(primary_key=True, autoincrement=True)
chart = ormar.ForeignKey(Chart, name="chart_id", related_name="columns")
@ -142,17 +110,11 @@ class ChartColumn(ormar.Model):
translation = ormar.ForeignKey(TranslationNode, name="translation_node_id")
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_saving_related_fk_rel():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
await Report.objects.select_all(follow=True).all()

View File

@ -1,31 +1,22 @@
from typing import Optional
import databases
import sqlalchemy
import ormar
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
class BaseMeta(ormar.ModelMeta):
metadata = metadata
database = database
base_ormar_config = create_config()
class Author(ormar.Model):
class Meta(BaseMeta):
tablename = "authors"
ormar_config = base_ormar_config.copy(tablename="authors")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
class Book(ormar.Model):
class Meta(BaseMeta):
tablename = "books"
ormar_config = base_ormar_config.copy(tablename="books")
id: int = ormar.Integer(primary_key=True)
author: Optional[Author] = ormar.ForeignKey(Author)
@ -33,6 +24,9 @@ class Book(ormar.Model):
year: int = ormar.Integer(nullable=True)
create_test_database = init_tests(base_ormar_config)
def test_or_group():
result = ormar.or_(name="aa", books__title="bb")
result.resolve(model_cls=Author)

View File

@ -1,21 +1,16 @@
from datetime import datetime
import databases
import pytest
import sqlalchemy
import ormar
from tests.settings import DATABASE_URL
import pytest
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
base_ormar_config = create_config()
class Node(ormar.Model):
class Meta(ormar.ModelMeta):
tablename = "node"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="node")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=120)
@ -24,10 +19,7 @@ class Node(ormar.Model):
class Edge(ormar.Model):
class Meta(ormar.ModelMeta):
tablename = "edge"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="edge")
id: str = ormar.String(primary_key=True, max_length=12)
src_node: Node = ormar.ForeignKey(Node, related_name="next_edges")
@ -36,18 +28,12 @@ class Edge(ormar.Model):
created_at: datetime = ormar.DateTime(timezone=True, default=datetime.now)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_sort_order_on_main_model():
async with database:
async with base_ormar_config.database:
node1 = await Node(name="Node 1").save()
node2 = await Node(name="Node 2").save()
node3 = await Node(name="Node 3").save()

View File

@ -1,32 +1,23 @@
from typing import Optional
import databases
import pytest
import sqlalchemy
import ormar
from tests.settings import DATABASE_URL
import pytest
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
class BaseMeta(ormar.ModelMeta):
metadata = metadata
database = database
base_ormar_config = create_config()
class Author(ormar.Model):
class Meta(BaseMeta):
tablename = "authors"
ormar_config = base_ormar_config.copy(tablename="authors")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
class Book(ormar.Model):
class Meta(BaseMeta):
tablename = "books"
ormar_config = base_ormar_config.copy(tablename="books")
id: int = ormar.Integer(primary_key=True)
author: Optional[Author] = ormar.ForeignKey(Author)
@ -35,10 +26,7 @@ class Book(ormar.Model):
class JsonModel(ormar.Model):
class Meta(ormar.ModelMeta):
metadata = metadata
database = database
tablename = "jsons"
ormar_config = base_ormar_config.copy(tablename="jsons")
id = ormar.Integer(primary_key=True)
text_field = ormar.Text(nullable=True)
@ -46,18 +34,12 @@ class JsonModel(ormar.Model):
json_not_null = ormar.JSON()
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_is_null():
async with database:
async with base_ormar_config.database:
tolkien = await Author.objects.create(name="J.R.R. Tolkien")
await Book.objects.create(author=tolkien, title="The Hobbit")
await Book.objects.create(
@ -99,7 +81,7 @@ async def test_is_null():
@pytest.mark.asyncio
async def test_isnull_json():
async with database:
async with base_ormar_config.database:
author = await JsonModel.objects.create(json_not_null=None)
assert author.json_field is None
non_null_text_fields = await JsonModel.objects.all(text_field__isnull=False)

View File

@ -1,32 +1,23 @@
from typing import Optional
import databases
import pytest
import sqlalchemy
import ormar
from tests.settings import DATABASE_URL
import pytest
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
class BaseMeta(ormar.ModelMeta):
metadata = metadata
database = database
base_ormar_config = create_config()
class DataSource(ormar.Model):
class Meta(BaseMeta):
tablename = "datasources"
ormar_config = base_ormar_config.copy(tablename="datasources")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=200, unique=True, index=True)
class DataSourceTable(ormar.Model):
class Meta(BaseMeta):
tablename = "source_tables"
ormar_config = base_ormar_config.copy(tablename="source_tables")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=200, index=True)
@ -36,8 +27,7 @@ class DataSourceTable(ormar.Model):
class DataSourceTableColumn(ormar.Model):
class Meta(BaseMeta):
tablename = "source_columns"
ormar_config = base_ormar_config.copy(tablename="source_columns")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=200, index=True)
@ -47,18 +37,12 @@ class DataSourceTableColumn(ormar.Model):
)
@pytest.fixture(autouse=True, scope="module")
def create_test_database(): # pragma: no cover
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_double_nested_reverse_relation():
async with database:
async with base_ormar_config.database:
data_source = await DataSource(name="local").save()
test_tables = [
{

View File

@ -1,49 +1,34 @@
from typing import Dict, List, Optional
import databases
import pytest
import sqlalchemy
from typing import Optional
import ormar
from tests.settings import DATABASE_URL
import pytest
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
class BaseMeta(ormar.ModelMeta):
metadata = metadata
database = database
base_ormar_config = create_config()
class Chart(ormar.Model):
class Meta(BaseMeta):
tablename = "authors"
ormar_config = base_ormar_config.copy(tablename="authors")
id: int = ormar.Integer(primary_key=True)
datasets = ormar.JSON()
class Config(ormar.Model):
class Meta(BaseMeta):
tablename = "books"
ormar_config = base_ormar_config.copy(tablename="books")
id: int = ormar.Integer(primary_key=True)
chart: Optional[Chart] = ormar.ForeignKey(Chart)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_list_field_that_is_not_relation_is_not_merged():
async with database:
async with base_ormar_config.database:
chart = await Chart.objects.create(datasets=[{"test": "ok"}])
await Config.objects.create(chart=chart)
await Config.objects.create(chart=chart)

View File

@ -1,33 +1,24 @@
from typing import Optional
import databases
import pytest
import sqlalchemy
import ormar
import pytest
from ormar.exceptions import QueryDefinitionError
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
class BaseMeta(ormar.ModelMeta):
metadata = metadata
database = database
base_ormar_config = create_config()
class Author(ormar.Model):
class Meta(BaseMeta):
tablename = "authors"
ormar_config = base_ormar_config.copy(tablename="authors")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
class Book(ormar.Model):
class Meta(BaseMeta):
tablename = "books"
ormar_config = base_ormar_config.copy(tablename="books")
id: int = ormar.Integer(primary_key=True)
author: Optional[Author] = ormar.ForeignKey(Author)
@ -35,18 +26,12 @@ class Book(ormar.Model):
year: int = ormar.Integer(nullable=True)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_or_filters():
async with database:
async with base_ormar_config.database:
tolkien = await Author(name="J.R.R. Tolkien").save()
await Book(author=tolkien, title="The Hobbit", year=1933).save()
await Book(author=tolkien, title="The Lord of the Rings", year=1955).save()

View File

@ -1,21 +1,16 @@
from typing import List, Optional
import databases
import pytest
import sqlalchemy
import ormar
from tests.settings import DATABASE_URL
import pytest
database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
base_ormar_config = create_config()
class Song(ormar.Model):
class Meta:
tablename = "songs"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="songs")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
@ -23,30 +18,21 @@ class Song(ormar.Model):
class Owner(ormar.Model):
class Meta:
tablename = "owners"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="owners")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
class AliasNested(ormar.Model):
class Meta:
tablename = "aliases_nested"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="aliases_nested")
id: int = ormar.Integer(name="alias_id", primary_key=True)
name: str = ormar.String(name="alias_name", max_length=100)
class AliasTest(ormar.Model):
class Meta:
tablename = "aliases"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="aliases")
id: int = ormar.Integer(name="alias_id", primary_key=True)
name: str = ormar.String(name="alias_name", max_length=100)
@ -54,10 +40,7 @@ class AliasTest(ormar.Model):
class Toy(ormar.Model):
class Meta:
tablename = "toys"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="toys")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
@ -65,20 +48,14 @@ class Toy(ormar.Model):
class Factory(ormar.Model):
class Meta:
tablename = "factories"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="factories")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
class Car(ormar.Model):
class Meta:
tablename = "cars"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="cars")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
@ -86,28 +63,19 @@ class Car(ormar.Model):
class User(ormar.Model):
class Meta:
tablename = "users"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="users")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
cars: List[Car] = ormar.ManyToMany(Car)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_sort_order_on_main_model():
async with database:
async with base_ormar_config.database:
await Song.objects.create(name="Song 3", sort_order=3)
await Song.objects.create(name="Song 1", sort_order=1)
await Song.objects.create(name="Song 2", sort_order=2)
@ -166,7 +134,7 @@ async def test_sort_order_on_main_model():
@pytest.mark.asyncio
async def test_sort_order_on_related_model():
async with database:
async with base_ormar_config.database:
aphrodite = await Owner.objects.create(name="Aphrodite")
hermes = await Owner.objects.create(name="Hermes")
zeus = await Owner.objects.create(name="Zeus")
@ -252,7 +220,7 @@ async def test_sort_order_on_related_model():
@pytest.mark.asyncio
async def test_sort_order_on_many_to_many():
async with database:
async with base_ormar_config.database:
factory1 = await Factory.objects.create(name="Factory 1")
factory2 = await Factory.objects.create(name="Factory 2")
@ -326,7 +294,7 @@ async def test_sort_order_on_many_to_many():
@pytest.mark.asyncio
async def test_sort_order_with_aliases():
async with database:
async with base_ormar_config.database:
al1 = await AliasTest.objects.create(name="Test4")
al2 = await AliasTest.objects.create(name="Test2")
al3 = await AliasTest.objects.create(name="Test1")

View File

@ -1,56 +1,39 @@
import databases
import pytest
import sqlalchemy
import ormar
from ormar import ModelMeta
import pytest
from ormar.exceptions import QueryDefinitionError
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
class BaseMeta(ModelMeta):
metadata = metadata
database = database
base_ormar_config = create_config()
class Car(ormar.Model):
class Meta(BaseMeta):
pass
ormar_config = base_ormar_config.copy()
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
class UsersCar(ormar.Model):
class Meta(BaseMeta):
tablename = "cars_x_users"
ormar_config = base_ormar_config.copy(tablename="cars_x_users")
class User(ormar.Model):
class Meta(BaseMeta):
pass
ormar_config = base_ormar_config.copy()
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
cars = ormar.ManyToMany(Car, through=UsersCar)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_limit_zero():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
for i in range(5):
await Car(name=f"{i}").save()
@ -61,8 +44,8 @@ async def test_limit_zero():
@pytest.mark.asyncio
async def test_pagination_errors():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
with pytest.raises(QueryDefinitionError):
await Car.objects.paginate(0).all()
@ -72,8 +55,8 @@ async def test_pagination_errors():
@pytest.mark.asyncio
async def test_pagination_on_single_model():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
for i in range(20):
await Car(name=f"{i}").save()
@ -96,8 +79,8 @@ async def test_pagination_on_single_model():
@pytest.mark.asyncio
async def test_proxy_pagination():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
user = await User(name="Jon").save()
for i in range(20):

View File

@ -1,33 +1,24 @@
import asyncio
from typing import List, Optional, Union
import databases
import pytest
import sqlalchemy
import ormar
import pytest
from ormar.exceptions import QueryDefinitionError
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
base_ormar_config = create_config()
class Subject(ormar.Model):
class Meta:
tablename = "subjects"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="subjects")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=80)
class Author(ormar.Model):
class Meta:
tablename = "authors"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="authors")
id: int = ormar.Integer(primary_key=True)
first_name: str = ormar.String(max_length=80)
@ -35,10 +26,7 @@ class Author(ormar.Model):
class Category(ormar.Model):
class Meta:
tablename = "categories"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="categories")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=40)
@ -47,17 +35,11 @@ class Category(ormar.Model):
class PostCategory(ormar.Model):
class Meta:
tablename = "posts_categories"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="posts_categories")
class Post(ormar.Model):
class Meta:
tablename = "posts"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="posts")
id: int = ormar.Integer(primary_key=True)
title: str = ormar.String(max_length=200)
@ -67,18 +49,13 @@ class Post(ormar.Model):
author: Optional[Author] = ormar.ForeignKey(Author)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_queryset_methods():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
guido = await Author.objects.create(
first_name="Guido", last_name="Van Rossum"
)
@ -183,8 +160,8 @@ async def test_queryset_methods():
@pytest.mark.asyncio
async def test_queryset_update():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
guido = await Author.objects.create(
first_name="Guido", last_name="Van Rossum"
)

View File

@ -1,23 +1,21 @@
from enum import Enum
from typing import Optional
import databases
import ormar
import pydantic
import pytest
import sqlalchemy
from pydantic import Json
import ormar
from ormar import QuerySet
from ormar.exceptions import (
ModelListEmptyError,
ModelPersistenceError,
QueryDefinitionError,
ModelListEmptyError,
)
from tests.settings import DATABASE_URL
from pydantic import Json
database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
base_ormar_config = create_config(force_rollback=True)
class MySize(Enum):
@ -26,10 +24,7 @@ class MySize(Enum):
class Book(ormar.Model):
class Meta:
tablename = "books"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="books")
id: int = ormar.Integer(primary_key=True)
title: str = ormar.String(max_length=200)
@ -37,15 +32,11 @@ class Book(ormar.Model):
genre: str = ormar.String(
max_length=100,
default="Fiction",
choices=["Fiction", "Adventure", "Historic", "Fantasy"],
)
class ToDo(ormar.Model):
class Meta:
tablename = "todos"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="todos")
id: int = ormar.Integer(primary_key=True)
text: str = ormar.String(max_length=500)
@ -55,20 +46,14 @@ class ToDo(ormar.Model):
class Category(ormar.Model):
class Meta:
tablename = "categories"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="categories")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=500)
class Note(ormar.Model):
class Meta:
tablename = "notes"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="notes")
id: int = ormar.Integer(primary_key=True)
text: str = ormar.String(max_length=500)
@ -76,10 +61,7 @@ class Note(ormar.Model):
class ItemConfig(ormar.Model):
class Meta(ormar.ModelMeta):
metadata = metadata
database = database
tablename = "item_config"
ormar_config = base_ormar_config.copy(tablename="item_config")
id: Optional[int] = ormar.Integer(primary_key=True)
item_id: str = ormar.String(max_length=32, index=True)
@ -97,39 +79,29 @@ class QuerySetCls(QuerySet):
class Customer(ormar.Model):
class Meta:
metadata = metadata
database = database
tablename = "customer"
queryset_class = QuerySetCls
ormar_config = base_ormar_config.copy(
tablename="customer",
queryset_class=QuerySetCls,
)
id: Optional[int] = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=32)
class JsonTestModel(ormar.Model):
class Meta(ormar.ModelMeta):
metadata = metadata
database = database
tablename = "test_model"
ormar_config = base_ormar_config.copy(tablename="test_model")
id: int = ormar.Integer(primary_key=True)
json_field: Json = ormar.JSON()
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_delete_and_update():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
await Book.objects.create(
title="Tom Sawyer", author="Twain, Mark", genre="Adventure"
)
@ -184,7 +156,7 @@ async def test_delete_and_update():
@pytest.mark.asyncio
async def test_get_or_create():
async with database:
async with base_ormar_config.database:
tom, created = await Book.objects.get_or_create(
title="Volume I", author="Anonymous", genre="Fiction"
)
@ -210,7 +182,7 @@ async def test_get_or_create():
@pytest.mark.asyncio
async def test_get_or_create_with_defaults():
async with database:
async with base_ormar_config.database:
book, created = await Book.objects.get_or_create(
title="Nice book", _defaults={"author": "Mojix", "genre": "Historic"}
)
@ -246,7 +218,7 @@ async def test_get_or_create_with_defaults():
@pytest.mark.asyncio
async def test_update_or_create():
async with database:
async with base_ormar_config.database:
tom = await Book.objects.update_or_create(
title="Volume I", author="Anonymous", genre="Fiction"
)
@ -269,7 +241,7 @@ async def test_update_or_create():
@pytest.mark.asyncio
async def test_bulk_create():
async with database:
async with base_ormar_config.database:
await ToDo.objects.bulk_create(
[
ToDo(text="Buy the groceries."),
@ -292,7 +264,7 @@ async def test_bulk_create():
@pytest.mark.asyncio
async def test_bulk_create_json_field():
async with database:
async with base_ormar_config.database:
json_value = {"a": 1}
test_model_1 = JsonTestModel(id=1, json_field=json_value)
test_model_2 = JsonTestModel(id=2, json_field=json_value)
@ -308,11 +280,11 @@ async def test_bulk_create_json_field():
assert test_model_1.json_field == test_model_2.json_field # True
# try to query the json field
table = JsonTestModel.Meta.table
table = JsonTestModel.ormar_config.table
query = table.select().where(table.c.json_field["a"].as_integer() == 1)
res = [
JsonTestModel.from_row(record, source_model=JsonTestModel)
for record in await database.fetch_all(query)
for record in await base_ormar_config.database.fetch_all(query)
]
assert test_model_1 in res
@ -322,7 +294,7 @@ async def test_bulk_create_json_field():
@pytest.mark.asyncio
async def test_bulk_create_with_relation():
async with database:
async with base_ormar_config.database:
category = await Category.objects.create(name="Sample Category")
await Note.objects.bulk_create(
@ -340,7 +312,7 @@ async def test_bulk_create_with_relation():
@pytest.mark.asyncio
async def test_bulk_update():
async with database:
async with base_ormar_config.database:
await ToDo.objects.bulk_create(
[
ToDo(text="Buy the groceries."),
@ -371,7 +343,7 @@ async def test_bulk_update():
@pytest.mark.asyncio
async def test_bulk_update_with_only_selected_columns():
async with database:
async with base_ormar_config.database:
await ToDo.objects.bulk_create(
[
ToDo(text="Reset the world simulation.", completed=False),
@ -400,7 +372,7 @@ async def test_bulk_update_with_only_selected_columns():
@pytest.mark.asyncio
async def test_bulk_update_with_relation():
async with database:
async with base_ormar_config.database:
category = await Category.objects.create(name="Sample Category")
category2 = await Category.objects.create(name="Sample II Category")
@ -429,7 +401,7 @@ async def test_bulk_update_with_relation():
@pytest.mark.asyncio
async def test_bulk_update_not_saved_objts():
async with database:
async with base_ormar_config.database:
category = await Category.objects.create(name="Sample Category")
with pytest.raises(ModelPersistenceError):
await Note.objects.bulk_update(
@ -445,7 +417,7 @@ async def test_bulk_update_not_saved_objts():
@pytest.mark.asyncio
async def test_bulk_operations_with_json():
async with database:
async with base_ormar_config.database:
items = [
ItemConfig(item_id="test1"),
ItemConfig(item_id="test2"),
@ -469,18 +441,18 @@ async def test_bulk_operations_with_json():
items = await ItemConfig.objects.filter(ItemConfig.id > 1).all()
assert all(x.pairs == {"b": 2} for x in items)
table = ItemConfig.Meta.table
table = ItemConfig.ormar_config.table
query = table.select().where(table.c.pairs["b"].as_integer() == 2)
res = [
ItemConfig.from_row(record, source_model=ItemConfig)
for record in await database.fetch_all(query)
for record in await base_ormar_config.database.fetch_all(query)
]
assert len(res) == 2
@pytest.mark.asyncio
async def test_custom_queryset_cls():
async with database:
async with base_ormar_config.database:
with pytest.raises(ValueError):
await Customer.objects.first_or_404(id=1)
@ -491,7 +463,7 @@ async def test_custom_queryset_cls():
@pytest.mark.asyncio
async def test_filter_enum():
async with database:
async with base_ormar_config.database:
it = ItemConfig(item_id="test_1")
await it.save()

View File

@ -2,24 +2,17 @@ import datetime
import uuid
from typing import Dict, Optional, Union
import databases
import pytest
import sqlalchemy
from sqlalchemy import create_engine
import ormar
from tests.settings import DATABASE_URL
import pytest
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
engine = create_engine(DATABASE_URL)
from tests.lifespan import init_tests
from tests.settings import create_config
base_ormar_config = create_config()
class Team(ormar.Model):
class Meta:
tablename: str = "team"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="team")
id: uuid.UUID = ormar.UUID(default=uuid.uuid4, primary_key=True, index=True)
name = ormar.Text(nullable=True)
@ -29,10 +22,7 @@ class Team(ormar.Model):
class User(ormar.Model):
class Meta:
tablename: str = "user"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="user")
id: uuid.UUID = ormar.UUID(default=uuid.uuid4, primary_key=True, index=True)
client_user_id = ormar.Text()
@ -41,23 +31,16 @@ class User(ormar.Model):
class Order(ormar.Model):
class Meta:
tablename: str = "order"
database = database
metadata = metadata
ormar_config = base_ormar_config.copy(tablename="order")
id: uuid.UUID = ormar.UUID(default=uuid.uuid4, primary_key=True, index=True)
user: Optional[Union[User, Dict]] = ormar.ForeignKey(User)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_quoting_on_clause_without_prefix():
async with database:
async with base_ormar_config.database:
await User.objects.select_related("orders").all()

View File

@ -1,23 +1,14 @@
import databases
import pytest
import sqlalchemy
import ormar
import pytest
from tests.settings import DATABASE_URL
from tests.lifespan import init_tests
from tests.settings import create_config
database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()
class BaseMeta(ormar.ModelMeta):
metadata = metadata
database = database
base_ormar_config = create_config(force_rollback=True)
class User(ormar.Model):
class Meta(BaseMeta):
tablename = "user"
ormar_config = base_ormar_config.copy(tablename="user")
id: int = ormar.Integer(primary_key=True, autoincrement=True, nullable=False)
user: str = ormar.String(
@ -33,26 +24,19 @@ class User(ormar.Model):
class Task(ormar.Model):
class Meta(BaseMeta):
tablename = "task"
ormar_config = base_ormar_config.copy(tablename="task")
id: int = ormar.Integer(primary_key=True, autoincrement=True, nullable=False)
from_: str = ormar.String(name="from", nullable=True, max_length=200)
user = ormar.ForeignKey(User)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_single_model_quotes():
async with database:
async with base_ormar_config.database:
await User.objects.create(
user="test",
first="first",
@ -68,7 +52,7 @@ async def test_single_model_quotes():
@pytest.mark.asyncio
async def test_two_model_quotes():
async with database:
async with base_ormar_config.database:
user = await User.objects.create(
user="test",
first="first",

View File

@ -1,22 +1,17 @@
from typing import Optional
import databases
import pytest
import sqlalchemy
import ormar
import pytest
from ormar import NoMatch
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
base_ormar_config = create_config()
class Album(ormar.Model):
class Meta:
tablename = "albums"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="albums")
id: int = ormar.Integer(primary_key=True, name="album_id")
name: str = ormar.String(max_length=100)
@ -24,20 +19,14 @@ class Album(ormar.Model):
class Writer(ormar.Model):
class Meta:
tablename = "writers"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="writers")
id: int = ormar.Integer(primary_key=True, name="writer_id")
name: str = ormar.String(max_length=100)
class Track(ormar.Model):
class Meta:
tablename = "tracks"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="tracks")
id: int = ormar.Integer(primary_key=True)
album: Optional[Album] = ormar.ForeignKey(Album, name="album_id")
@ -67,19 +56,13 @@ async def get_sample_data():
return album, [track1, track2, tracks3]
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.mark.asyncio
async def test_quering_by_reverse_fk():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
sample_data = await get_sample_data()
track1 = sample_data[1][0]
album = await Album.objects.first()
@ -133,8 +116,8 @@ async def test_quering_by_reverse_fk():
@pytest.mark.asyncio
async def test_getting():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
sample_data = await get_sample_data()
album = sample_data[0]
track1 = await album.tracks.fields(["album", "title", "position"]).get(
@ -203,8 +186,8 @@ async def test_getting():
@pytest.mark.asyncio
async def test_cleaning_related():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
sample_data = await get_sample_data()
album = sample_data[0]
await album.tracks.clear(keep_reversed=False)
@ -218,8 +201,8 @@ async def test_cleaning_related():
@pytest.mark.asyncio
async def test_loading_related():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
sample_data = await get_sample_data()
album = sample_data[0]
tracks = await album.tracks.select_related("written_by").all()
@ -237,8 +220,8 @@ async def test_loading_related():
@pytest.mark.asyncio
async def test_adding_removing():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
sample_data = await get_sample_data()
album = sample_data[0]
track_new = await Track(title="Rainbow", position=5, play_count=300).save()

View File

@ -1,25 +1,20 @@
import asyncio
import itertools
from typing import Optional, List
from typing import List, Optional
import databases
import ormar
import pydantic
import pytest
import pytest_asyncio
import sqlalchemy
import ormar
from tests.settings import DATABASE_URL
from tests.lifespan import init_tests
from tests.settings import create_config
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
base_ormar_config = create_config()
class NickNames(ormar.Model):
class Meta:
tablename = "nicks"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="nicks")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100, nullable=False, name="hq_name")
@ -27,17 +22,11 @@ class NickNames(ormar.Model):
class NicksHq(ormar.Model):
class Meta:
tablename = "nicks_x_hq"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="nicks_x_hq")
class HQ(ormar.Model):
class Meta:
tablename = "hqs"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="hqs")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100, nullable=False, name="hq_name")
@ -45,10 +34,7 @@ class HQ(ormar.Model):
class Company(ormar.Model):
class Meta:
tablename = "companies"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="companies")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100, nullable=False, name="company_name")
@ -57,10 +43,7 @@ class Company(ormar.Model):
class Car(ormar.Model):
class Meta:
tablename = "cars"
metadata = metadata
database = database
ormar_config = base_ormar_config.copy(tablename="cars")
id: int = ormar.Integer(primary_key=True)
manufacturer: Optional[Company] = ormar.ForeignKey(Company)
@ -71,13 +54,7 @@ class Car(ormar.Model):
aircon_type: str = ormar.String(max_length=20, nullable=True)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.fixture(scope="module")
@ -89,7 +66,7 @@ def event_loop():
@pytest_asyncio.fixture(autouse=True, scope="module")
async def sample_data(event_loop, create_test_database):
async with database:
async with base_ormar_config.database:
nick1 = await NickNames.objects.create(name="Nippon", is_lame=False)
nick2 = await NickNames.objects.create(name="EroCherry", is_lame=True)
hq = await HQ.objects.create(name="Japan")
@ -126,8 +103,8 @@ async def sample_data(event_loop, create_test_database):
@pytest.mark.asyncio
async def test_selecting_subset():
async with database:
async with database.transaction(force_rollback=True):
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
all_cars = (
await Car.objects.select_related(["manufacturer__hq__nicks"])
.fields(
@ -226,7 +203,7 @@ async def test_selecting_subset():
assert all_cars_dummy[0].manufacturer.founded is None
with pytest.raises(pydantic.error_wrappers.ValidationError):
with pytest.raises(pydantic.ValidationError):
# cannot exclude mandatory model columns - company__name in this example
await Car.objects.select_related("manufacturer").fields(
["id", "name", "manufacturer__founded"]
@ -235,7 +212,7 @@ async def test_selecting_subset():
@pytest.mark.asyncio
async def test_selecting_subset_of_through_model():
async with database:
async with base_ormar_config.database:
car = (
await Car.objects.select_related(["manufacturer__hq__nicks"])
.fields(

View File

@ -1,35 +1,26 @@
import asyncio
from typing import List, Optional
import databases
import ormar
import pytest
import pytest_asyncio
import sqlalchemy
import ormar
from ormar.exceptions import QueryDefinitionError
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
from tests.lifespan import init_tests
from tests.settings import create_config
class BaseMeta(ormar.ModelMeta):
database = database
metadata = metadata
base_ormar_config = create_config()
class User(ormar.Model):
class Meta(BaseMeta):
pass
ormar_config = base_ormar_config.copy()
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
class Role(ormar.Model):
class Meta(BaseMeta):
pass
ormar_config = base_ormar_config.copy()
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
@ -37,8 +28,7 @@ class Role(ormar.Model):
class Category(ormar.Model):
class Meta(BaseMeta):
tablename = "categories"
ormar_config = base_ormar_config.copy(tablename="categories")
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=40)
@ -47,20 +37,14 @@ class Category(ormar.Model):
class Post(ormar.Model):
class Meta(BaseMeta):
tablename = "posts"
ormar_config = base_ormar_config.copy()
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=200)
category: Optional[Category] = ormar.ForeignKey(Category)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
create_test_database = init_tests(base_ormar_config)
@pytest.fixture(scope="module")
@ -72,7 +56,7 @@ def event_loop():
@pytest_asyncio.fixture(autouse=True, scope="module")
async def sample_data(event_loop, create_test_database):
async with database:
async with base_ormar_config.database:
creator = await User(name="Anonymous").save()
admin = await Role(name="admin").save()
editor = await Role(name="editor").save()
@ -86,7 +70,7 @@ async def sample_data(event_loop, create_test_database):
@pytest.mark.asyncio
async def test_simple_queryset_values():
async with database:
async with base_ormar_config.database:
posts = await Post.objects.values()
assert posts == [
{"id": 1, "name": "Ormar strikes again!", "category": 1},
@ -97,7 +81,7 @@ async def test_simple_queryset_values():
@pytest.mark.asyncio
async def test_queryset_values_nested_relation():
async with database:
async with base_ormar_config.database:
posts = await Post.objects.select_related("category__created_by").values()
assert posts == [
{
@ -138,7 +122,7 @@ async def test_queryset_values_nested_relation():
@pytest.mark.asyncio
async def test_queryset_values_nested_relation_subset_of_fields():
async with database:
async with base_ormar_config.database:
posts = await Post.objects.select_related("category__created_by").values(
["name", "category__name", "category__created_by__name"]
)
@ -163,7 +147,7 @@ async def test_queryset_values_nested_relation_subset_of_fields():
@pytest.mark.asyncio
async def test_queryset_simple_values_list():
async with database:
async with base_ormar_config.database:
posts = await Post.objects.values_list()
assert posts == [
(1, "Ormar strikes again!", 1),
@ -174,7 +158,7 @@ async def test_queryset_simple_values_list():
@pytest.mark.asyncio
async def test_queryset_nested_relation_values_list():
async with database:
async with base_ormar_config.database:
posts = await Post.objects.select_related("category__created_by").values_list()
assert posts == [
(1, "Ormar strikes again!", 1, 1, "News", 0, 1, 1, "Anonymous"),
@ -195,7 +179,7 @@ async def test_queryset_nested_relation_values_list():
@pytest.mark.asyncio
async def test_queryset_nested_relation_subset_of_fields_values_list():
async with database:
async with base_ormar_config.database:
posts = await Post.objects.select_related("category__created_by").values_list(
["name", "category__name", "category__created_by__name"]
)
@ -208,7 +192,7 @@ async def test_queryset_nested_relation_subset_of_fields_values_list():
@pytest.mark.asyncio
async def test_m2m_values():
async with database:
async with base_ormar_config.database:
user = await User.objects.select_related("roles").values()
assert user == [
{
@ -234,7 +218,7 @@ async def test_m2m_values():
@pytest.mark.asyncio
async def test_nested_m2m_values():
async with database:
async with base_ormar_config.database:
user = (
await Role.objects.select_related("users__categories")
.filter(name="admin")
@ -259,7 +243,7 @@ async def test_nested_m2m_values():
@pytest.mark.asyncio
async def test_nested_m2m_values_without_through_explicit():
async with database:
async with base_ormar_config.database:
user = (
await Role.objects.select_related("users__categories")
.filter(name="admin")
@ -278,7 +262,7 @@ async def test_nested_m2m_values_without_through_explicit():
@pytest.mark.asyncio
async def test_nested_m2m_values_without_through_param():
async with database:
async with base_ormar_config.database:
user = (
await Role.objects.select_related("users__categories")
.filter(name="admin")
@ -296,7 +280,7 @@ async def test_nested_m2m_values_without_through_param():
@pytest.mark.asyncio
async def test_nested_m2m_values_no_through_and_m2m_models_but_keep_end_model():
async with database:
async with base_ormar_config.database:
user = (
await Role.objects.select_related("users__categories")
.filter(name="admin")
@ -309,7 +293,7 @@ async def test_nested_m2m_values_no_through_and_m2m_models_but_keep_end_model():
@pytest.mark.asyncio
async def test_nested_flatten_and_exception():
async with database:
async with base_ormar_config.database:
with pytest.raises(QueryDefinitionError):
(await Role.objects.fields({"name", "id"}).values_list(flatten=True))
@ -319,7 +303,7 @@ async def test_nested_flatten_and_exception():
@pytest.mark.asyncio
async def test_empty_result():
async with database:
async with base_ormar_config.database:
roles = await Role.objects.filter(Role.name == "test").values_list()
roles2 = await Role.objects.filter(Role.name == "test").values()
assert roles == roles2 == []
@ -327,7 +311,7 @@ async def test_empty_result():
@pytest.mark.asyncio
async def test_queryset_values_multiple_select_related():
async with database:
async with base_ormar_config.database:
posts = (
await Category.objects.select_related(["created_by__roles", "posts"])
.filter(Category.created_by.roles.name == "editor")
@ -360,7 +344,7 @@ async def test_queryset_values_multiple_select_related():
@pytest.mark.asyncio
async def test_querysetproxy_values():
async with database:
async with base_ormar_config.database:
role = (
await Role.objects.select_related("users__categories")
.filter(name="admin")
@ -406,7 +390,7 @@ async def test_querysetproxy_values():
@pytest.mark.asyncio
async def test_querysetproxy_values_list():
async with database:
async with base_ormar_config.database:
role = (
await Role.objects.select_related("users__categories")
.filter(name="admin")