๐Ÿ“ฆ aminalaee / mongox

๐Ÿ“„ test_indexes.py ยท 61 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61import asyncio
import os
import typing

import pytest

from mongox.database import Client
from mongox.exceptions import InvalidKeyException
from mongox.fields import ObjectId
from mongox.index import Index, IndexType, Order
from mongox.models import Model

pytestmark = pytest.mark.asyncio

database_uri = os.environ.get("DATABASE_URI", "mongodb://localhost:27017")
client = Client(database_uri, get_event_loop=asyncio.get_running_loop)
db = client.get_database("test_db")


indexes = [
    Index("name", unique=True),
    Index(keys=[("year", Order.DESCENDING), ("genre", IndexType.HASHED)]),
]


class Movie(Model, db=db, indexes=indexes):
    name: str
    year: int
    uuid: typing.Optional[ObjectId]


async def test_create_indexes() -> None:
    index_names = await Movie.create_indexes()
    assert index_names == ["name", "year_genre"]

    await Movie.drop_indexes()

    index = await Movie.create_index("name")
    assert index == "name"

    with pytest.raises(InvalidKeyException):
        await Movie.create_index("random_index")


async def test_drop_index() -> None:
    await Movie.drop_index("name")

    with pytest.raises(InvalidKeyException):
        await Movie.drop_index("random_index")


async def test_drop_indexes() -> None:
    await Movie.create_indexes()

    index_names = await Movie.drop_indexes()
    assert index_names == ["name", "year_genre"]

    await Movie.create_indexes()

    await Movie.drop_indexes(force=True)