Passed
Pull Request — main (#32)
by Rami
59s
created

tests.model.test_indexes.test_index_creation()   A

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nop 1
1
from typing import Generator
2
3
import pytest
4
from mongomantic import BaseRepository, Index, MongoDBModel
5
from mongomantic.core.errors import WriteError
6
7
8
class User(MongoDBModel):
9
    name: str
10
    email: str
11
    age: int
12
13
14
class UserRepository(BaseRepository):
15
    class Meta:
16
        model = User
17
        collection = "user"
18
19
        indexes = [
20
            Index(name="email_index", unique=True, fields=["+email"]),
21
            Index(name="name_age", unique=True, fields=["+age", "-name"]),
22
        ]
23
24
25
def test_index_creation(mongodb):
26
    indexes = UserRepository._get_collection().index_information()
27
28
    assert indexes["email_1"]["unique"]
29
    assert indexes["email_1"]["key"] == ("email", 1)
30
31
    assert indexes["age_1_name_-1"]["unique"]
32
    assert indexes["age_1_name_-1"]["key"] == [("age", 1), ("name", -1)]
33
34
35
def test_index_uniqueness(mongodb):
36
    user = User(name="John", age=23, email="[email protected]")
37
38
    UserRepository.save(user)
39
    with pytest.raises(WriteError):
40
        UserRepository.save(user)
41
42
    same_email_user = User(name="John", age=2, email="[email protected]")
43
    with pytest.raises(WriteError):
44
        UserRepository.save(same_email_user)
45
46
    similar_user = User(name="John", age=23, email="[email protected]")
47
    with pytest.raises(WriteError):
48
        UserRepository.save(similar_user)
49
50
    ok_user = User(name="John", age=30, email="[email protected]")
51
    assert UserRepository.save(ok_user)
52