test_index_different_user()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nop 2
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
@pytest.fixture()
13
def repo():
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
    return UserRepository
25
26
27
def test_index_creation(mongodb, repo):
28
    indexes = repo._get_collection().index_information()
29
30
    assert indexes["email_1"]["unique"]
31
    assert indexes["email_1"]["key"] == [("email", 1)]
32
33
    assert indexes["age_1_name_-1"]["unique"]
34
    assert indexes["age_1_name_-1"]["key"] == [("age", 1), ("name", -1)]
35
36
37
def test_index_duplicate_user(mongodb, repo):
38
    user = User(name="John", age=23, email="[email protected]")
39
    repo.save(user)
40
41
    with pytest.raises(WriteError):
42
        repo.save(user)
43
44
45
def test_index_duplicate_email(mongodb, repo):
46
    user = User(name="John", age=23, email="[email protected]")
47
    repo.save(user)
48
49
    same_email_user = User(name="John", age=2, email="[email protected]")
50
    with pytest.raises(WriteError):
51
        repo.save(same_email_user)
52
53
54
def test_index_duplicate_name_age(mongodb, repo):
55
    user = User(name="John", age=23, email="[email protected]")
56
    repo.save(user)
57
58
    similar_user = User(name="John", age=23, email="[email protected]")
59
    with pytest.raises(WriteError):
60
        repo.save(similar_user)
61
62
63
def test_index_different_user(mongodb, repo):
64
    user = User(name="John", age=23, email="[email protected]")
65
    repo.save(user)
66
67
    ok_user = User(name="John", age=30, email="[email protected]")
68
    assert repo.save(ok_user)
69