File: test_query_values.py

package info (click to toggle)
python-django-postgres-extra 2.0.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,096 kB
  • sloc: python: 9,057; makefile: 17; sh: 7; sql: 1
file content (75 lines) | stat: -rw-r--r-- 2,282 bytes parent folder | download | duplicates (3)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import django
import pytest

from django.db import models

from psqlextra.fields import HStoreField

from .fake_model import get_fake_model


@pytest.fixture
def model():
    """Test models, where the first model has a foreign key relationship to the
    second."""

    return get_fake_model({"title": HStoreField()})


@pytest.fixture
def modelobj(model):
    """Data for the test models, one row per model."""

    return model.objects.create(title={"en": "english", "ar": "arabic"})


def test_query_values_hstore(model, modelobj):
    """Tests that selecting all the keys properly works and returns a.

    :see:LocalizedValue instance.
    """

    result = list(model.objects.values("title"))[0]
    assert result["title"] == modelobj.title


def test_query_values_hstore_key(model, modelobj):
    """Tests whether selecting a single key from a :see:HStoreField using the
    query set's .values() works properly."""

    result = list(model.objects.values("title__en", "title__ar"))[0]
    assert result["title__en"] == modelobj.title["en"]
    assert result["title__ar"] == modelobj.title["ar"]


def test_query_values_list_hstore_key(model, modelobj):
    """Tests that selecting a single key from a :see:HStoreField using the
    query set's .values_list() works properly."""

    result = list(model.objects.values_list("title__en", "title__ar"))[0]
    assert result[0] == modelobj.title["en"]
    assert result[1] == modelobj.title["ar"]


@pytest.mark.skipif(
    django.VERSION < (2, 1), reason="requires django 2.1 or newer"
)
def test_query_values_hstore_key_through_fk():
    """Tests whether selecting a single key from a :see:HStoreField using the
    query set's .values() works properly when there's a foreign key
    relationship involved."""

    # this starting working in django 2.1
    # see: https://github.com/django/django/commit/20bab2cf9d02a5c6477d8aac066a635986e0d3f3

    fmodel = get_fake_model({"name": HStoreField()})

    model = get_fake_model(
        {"fk": models.ForeignKey(fmodel, on_delete=models.CASCADE)}
    )

    fobj = fmodel.objects.create(name={"en": "swen", "ar": "arabic swen"})
    model.objects.create(fk=fobj)

    result = list(model.objects.values("fk__name__ar"))[0]
    assert result["fk__name__ar"] == fobj.name["ar"]