|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | +import ormar |
| 4 | +import pytest |
| 5 | + |
| 6 | +from tests.lifespan import init_tests |
| 7 | +from tests.settings import create_config |
| 8 | + |
| 9 | +base_ormar_config = create_config() |
| 10 | + |
| 11 | + |
| 12 | +class Category(ormar.Model): |
| 13 | + ormar_config = base_ormar_config.copy(tablename="categories") |
| 14 | + |
| 15 | + id: int = ormar.Integer(primary_key=True) |
| 16 | + name: str = ormar.String(max_length=100) |
| 17 | + |
| 18 | + |
| 19 | +class Item(ormar.Model): |
| 20 | + ormar_config = base_ormar_config.copy(tablename="items") |
| 21 | + |
| 22 | + id: int = ormar.Integer(primary_key=True) |
| 23 | + name: str = ormar.String(max_length=100) |
| 24 | + price: float = ormar.Float(default=0) |
| 25 | + category: Optional[Category] = ormar.ForeignKey(Category, nullable=True) |
| 26 | + |
| 27 | + |
| 28 | +create_test_database = init_tests(base_ormar_config) |
| 29 | + |
| 30 | + |
| 31 | +@pytest.mark.asyncio |
| 32 | +async def test_arbitrary_sql_execution(): |
| 33 | + async with base_ormar_config.database: |
| 34 | + async with base_ormar_config.database.transaction(force_rollback=True): |
| 35 | + if not await Item.objects.count(): |
| 36 | + cat = await Category.objects.create(name="Electronics") |
| 37 | + await Item.objects.create(name="Tablet", price=449.99, category=cat) |
| 38 | + await Item.objects.create(name="Monitor", price=329.99, category=cat) |
| 39 | + |
| 40 | + column = "1 + 1" |
| 41 | + with pytest.raises(ormar.exceptions.QueryDefinitionError): |
| 42 | + await Item.objects.min(column) |
| 43 | + |
| 44 | + |
| 45 | +@pytest.mark.asyncio |
| 46 | +async def test_arbitrary_sql_execution_on_related_model(): |
| 47 | + async with base_ormar_config.database: |
| 48 | + async with base_ormar_config.database.transaction(force_rollback=True): |
| 49 | + if not await Item.objects.count(): |
| 50 | + cat = await Category.objects.create(name="Electronics") |
| 51 | + await Item.objects.create(name="Tablet", price=449.99, category=cat) |
| 52 | + await Item.objects.create(name="Monitor", price=329.99, category=cat) |
| 53 | + |
| 54 | + column = "category__1 + 1" |
| 55 | + with pytest.raises(ormar.exceptions.QueryDefinitionError): |
| 56 | + await Item.objects.min(column) |
| 57 | + |
| 58 | + |
| 59 | +@pytest.mark.asyncio |
| 60 | +async def test_schema_extraction(): |
| 61 | + async with base_ormar_config.database: |
| 62 | + async with base_ormar_config.database.transaction(force_rollback=True): |
| 63 | + if not await Item.objects.count(): |
| 64 | + cat = await Category.objects.create(name="Electronics") |
| 65 | + await Item.objects.create(name="Laptop", price=999.99, category=cat) |
| 66 | + |
| 67 | + column = "(SELECT GROUP_CONCAT(name) FROM sqlite_master WHERE type='table')" |
| 68 | + with pytest.raises(ormar.exceptions.QueryDefinitionError): |
| 69 | + await Item.objects.min(column) |
0 commit comments