Completed
Push — main ( 6df2be...e961c2 )
by Rami
13s queued 11s
created

tests.model.test_indexes   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 34
dl 0
loc 50
rs 10
c 0
b 0
f 0

2 Functions

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