File: test_m2m_fields.py

package info (click to toggle)
django-dirtyfields 1.3.1-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 276 kB
  • sloc: python: 812; makefile: 168
file content (53 lines) | stat: -rw-r--r-- 2,033 bytes parent folder | download | duplicates (4)
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
import pytest

from .models import TestModel, TestM2MModel, TestModelWithCustomPK, TestM2MModelWithCustomPKOnM2M, \
    TestModelWithoutM2MCheck, TestM2MModelWithoutM2MModeEnabled


@pytest.mark.django_db
def test_dirty_fields_on_m2m():
    tm = TestM2MModel.objects.create()
    tm2 = TestModel.objects.create()
    tm.m2m_field.add(tm2)

    assert tm._as_dict_m2m() == {'m2m_field': set([tm2.id])}

    # m2m check should be explicit: you have to give the values you want to compare with db state.
    # This first assertion means that m2m_field has one element of id tm2 in the database.
    assert tm.get_dirty_fields(check_m2m={'m2m_field': set([tm2.id])}) == {}

    # This second assertion means that I'm expecting a m2m_field that is related to an element with id 0
    # As it differs, we return the previous saved elements.
    assert tm.get_dirty_fields(check_m2m={'m2m_field': set([0])}) == {'m2m_field': set([tm2.id])}

    assert tm.get_dirty_fields(check_m2m={'m2m_field': set([0, tm2.id])}) == {'m2m_field': set([tm2.id])}


@pytest.mark.django_db
def test_dirty_fields_on_m2m_not_possible_if_not_enabled():
    tm = TestM2MModelWithoutM2MModeEnabled.objects.create()
    tm2 = TestModel.objects.create()
    tm.m2m_field.add(tm2)

    with pytest.raises(ValueError):
        assert tm.get_dirty_fields(check_m2m={'m2m_field': set([tm2.id])}) == {}


@pytest.mark.django_db
def test_m2m_check_with_custom_primary_key():
    # test for bug: https://github.com/romgar/django-dirtyfields/issues/74

    tm = TestModelWithCustomPK.objects.create(custom_primary_key='pk1')
    m2m_model = TestM2MModelWithCustomPKOnM2M.objects.create()

    # This line was triggering this error:
    # AttributeError: 'TestModelWithCustomPK' object has no attribute 'id'
    m2m_model.m2m_field.add(tm)


@pytest.mark.django_db
def test_m2m_disabled_does_not_allow_to_check_m2m_fields():
    tm = TestModelWithoutM2MCheck.objects.create()

    with pytest.raises(Exception):
        assert tm.get_dirty_fields(check_m2m={'dummy': True})