예제 #1
0
def test_lookups(books):
    assert books[F.last_modified.year == timezone.now().year].count() == 5
    assert isinstance(F.quantity.min(), models.Min)
    assert isinstance(F.quantity.max(), models.Max)
    assert isinstance(F.quantity.sum(), models.Sum)
    assert isinstance(F.quantity.mean(), models.Avg)
    assert str(F.quantity.count()).startswith('Count(F(quantity)')
    assert str(F.count(distinct=True)) == "Count('*', distinct=True)"
    assert isinstance(F.quantity.var(sample=True), models.Variance)
    assert isinstance(F.quantity.std(sample=True), models.StdDev)
    exprs = list(map(F.author.contains, 'AB'))
    assert str(F.any(
        exprs)) == "(OR: ('author__contains', 'A'), ('author__contains', 'B'))"
    assert str(
        F.all(exprs)
    ) == "(AND: ('author__contains', 'A'), ('author__contains', 'B'))"

    authors = books['author']
    assert set(authors.isin('AB')) == {'A', 'B'}
    assert set(authors.iexact('a')) == {'A'}
    assert set(authors.contains('A')) == {'A'}
    assert set(authors.icontains('a')) == {'A'}
    assert set(authors.startswith('A')) == {'A'}
    assert set(authors.istartswith('a')) == {'A'}
    assert set(authors.endswith('A')) == {'A'}
    assert set(authors.iendswith('a')) == {'A'}
    assert set(authors.range('A', 'B')) == {'A', 'B'}
    assert set(authors.regex('A')) == {'A'}
    assert set(authors.iregex('a')) == {'A'}
def test_3_2(books):
    assert isinstance(F.x.collate('nocase'), functions.Collate)
    assert isinstance(F.json(), functions.JSONObject)
    assert isinstance(F.random(), functions.Random)

    case = {
        F.quantity <= 1: 'low',
        F.quantity >= 10: 'high',
        'default': 'medium'
    }
    assert list(books.alias(amount=case).order_by('amount')['quantity']) == [
        10, 10, 1, 2, 2
    ]
    assert books.alias(name=F.author.lower()).annotate(name=F('name'))
예제 #3
0
def test_lookups(books):
    assert books[F.last_modified.year == timezone.now().year].count() == 5
    assert str(F.author.search("")) == "(AND: ('author__search', ''))"
    assert isinstance(F.quantity.min(), models.Min)
    assert isinstance(F.quantity.max(), models.Max)
    assert isinstance(F.quantity.sum(), models.Sum)
    assert isinstance(F.quantity.mean(), models.Avg)
    assert isinstance(F.count(distinct=True), models.Count)
    assert isinstance(F.quantity.var(sample=True), models.Variance)
    assert isinstance(F.quantity.std(sample=True), models.StdDev)
    ordering = -F.user.created
    assert ordering.expression.name == "user__created" and ordering.descending

    authors = books["author"]
    assert set(authors.in_("A", "B")) == {"A", "B"}
    assert set(authors.iexact("a")) == {"A"}
    assert set(authors.contains("A")) == {"A"}
    assert set(authors.icontains("a")) == {"A"}
    assert set(authors.startswith("A")) == {"A"}
    assert set(authors.istartswith("a")) == {"A"}
    assert set(authors.endswith("A")) == {"A"}
    assert set(authors.iendswith("a")) == {"A"}
    assert set(authors.range("A", "B")) == {"A", "B"}
    assert set(authors.regex("A")) == {"A"}
    assert set(authors.iregex("a")) == {"A"}
예제 #4
0
def test_aggregation(books):
    assert set(books['author'].annotate(models.Max('quantity'))) == {'A', 'B'}
    assert dict(books['author'].value_counts()) == {'A': 2, 'B': 3}

    assert books['author', 'quantity'].reduce(models.Max,
                                              models.Min) == ('B', 1)
    assert books['author', 'quantity'].min() == ('A', 1)
    assert books['quantity'].min() == 1
    assert books['quantity'].max() == 10
    assert books['quantity'].sum() == 25
    assert books['quantity'].mean() == 5.0

    groups = books['quantity'].groupby('author')
    assert {key: sorted(values)
            for key, values in groups} == {
                'A': [10, 10],
                'B': [1, 2, 2]
            }
    assert dict(groups.min()) == {'A': 10, 'B': 1}
    assert dict(groups.max()) == {'A': 10, 'B': 2}
    assert dict(groups.sum()) == {'A': 20, 'B': 5}
    assert dict(groups.mean()) == {'A': 10, 'B': 5.0 / 3}
    assert isinstance(groups.var(), models.QuerySet)
    assert isinstance(groups.std(), models.QuerySet)
    key, values = next(
        iter(
            books.values('title',
                         'last_modified').groupby('author', 'quantity')))
    assert key == ('A', 10) and next(values)[0] == ''

    groups = books['quantity'].groupby(author=F.author.lower())
    assert dict(groups.sum()) == {'a': 20, 'b': 5}
    counts = books[F.author.lower()].value_counts()
    assert dict(counts) == {'a': 2, 'b': 3}
    assert dict(counts[F('count') > 2]) == {'b': 3}
    amounts = books[{F.quantity <= 1: 'low', F.quantity >= 10: 'high'}]
    assert dict(amounts.value_counts()) == {'low': 1, None: 2, 'high': 2}
    groups = books.groupby(amount={
        F.quantity <= 1: 'low',
        F.quantity >= 10: 'high',
        'default': 'medium'
    })
    with pytest.raises(Exception):
        Case({models.Q(): None}).output_field

    expr = books.values_list(F.quantity * -1)
    assert type(expr.sum()) is tuple
    key, values = next(iter(expr.groupby('author')))
    assert set(map(type, values)) == {tuple}
예제 #5
0
def test_functions(books):
    book = Book.objects[1]
    assert book['quantity'].first() == 10
    book['quantity'] += 1
    assert book['quantity'].first() == 11
    book['quantity'] -= 1
    assert book['quantity'].first() == 10
    book['quantity'] *= 2
    assert book['quantity'].first() == 20
    book['quantity'] /= 2
    assert book['quantity'].first() == 10
    book['quantity'] %= 7
    assert book['quantity'].first() == 3
    book['quantity'] **= 2
    assert book['quantity'].first() == 9

    assert (F.author != None) == models.Q(author__isnull=False)  # noqa: E711
    assert isinstance(F.coalesce('author', 'title'), functions.Coalesce)
    assert isinstance(F.author.concat('title'), functions.Concat)
    assert isinstance(F.author.length(), functions.Length)
    assert isinstance(F.title.lower(), functions.Lower)
    assert isinstance(F.title.upper(), functions.Upper)
    assert isinstance(F.title[:10], functions.Substr)
    with pytest.raises(AssertionError):
        F.title[:-10]
    with pytest.raises(AttributeError):
        F.name
    with pytest.raises(TypeError):
        iter(F.title)
    assert hash(F.title)
    assert not (F.author == models.F('title'))
    ((field, values), ) = transform('op', F.author.coalesce('title'),
                                    None).children
    assert field == 'author__op' and values == (F.title, None)

    assert isinstance(F.title.greatest('author'), functions.Greatest)
    assert isinstance(F.title.least('author'), functions.Least)
    assert F.now is functions.Now
    assert isinstance(F.quantity.cast(models.FloatField()), functions.Cast)
    assert isinstance(F.last_modified.extract('year'), functions.Extract)
    assert isinstance(F.last_modified.trunc('year'), functions.Trunc)

    for name, func in F.lookups.items():
        models.CharField.register_lookup(func, name)
    assert books[F.author.length <= 1]
    assert books[F.author.lower == 'a']
    assert books[F.author.upper == 'A']
예제 #6
0
def test_spatial_functions(books):
    from django.contrib.gis.geos import Point

    point = Point(0, 0, srid=4326)

    assert isinstance(F.location.area, gis.functions.Area)
    assert isinstance(F.location.geojson(), gis.functions.AsGeoJSON)
    assert isinstance(F.location.gml(), gis.functions.AsGML)
    assert isinstance(F.location.kml(), gis.functions.AsKML)
    assert isinstance(F.location.svg(), gis.functions.AsSVG)
    assert isinstance(F.location.bounding_circle(),
                      gis.functions.BoundingCircle)
    assert isinstance(F.location.centroid, gis.functions.Centroid)
    assert isinstance(F.location.envelope, gis.functions.Envelope)
    assert isinstance(F.location.geohash(), gis.functions.GeoHash)
    assert isinstance(F.location.make_valid(), gis.functions.MakeValid)
    assert isinstance(F.location.mem_size, gis.functions.MemSize)
    assert isinstance(F.location.num_geometries, gis.functions.NumGeometries)
    assert isinstance(F.location.num_points, gis.functions.NumPoints)
    assert isinstance(F.location.perimeter, gis.functions.Perimeter)
    assert isinstance(F.location.point_on_surface,
                      gis.functions.PointOnSurface)
    assert isinstance(F.location.reverse(), gis.functions.Reverse)
    assert isinstance(F.location.scale(0, 0), gis.functions.Scale)
    assert isinstance(F.location.snap_to_grid(0), gis.functions.SnapToGrid)
    assert isinstance(F.location.transform(point.srid),
                      gis.functions.Transform)
    assert isinstance(F.location.translate(0, 0), gis.functions.Translate)

    dist = F.location.distance(point)
    assert isinstance(dist, gis.functions.Distance)
    fields, items = zip(
        *F.all([(dist < 0), (dist <= 0), (dist > 0), (dist >= 0),
                dist.within(0)]).children)
    assert fields == (
        'location__distance_lt',
        'location__distance_lte',
        'location__distance_gt',
        'location__distance_gte',
        'location__dwithin',
    )
    assert items == ((point, 0), ) * 5
    ((field, values), ) = (F.location.distance(point) > 0).children
    assert values == (point, 0)

    assert isinstance(F.location.difference(point), gis.functions.Difference)
    assert isinstance(F.location.intersection(point),
                      gis.functions.Intersection)
    assert isinstance(F.location.symmetric_difference(point),
                      gis.functions.SymDifference)
    assert isinstance(F.location.union(point), gis.functions.Union)

    assert type(books).collect.__name__ == 'Collect'
    assert type(books).extent.__name__ == 'Extent'
    assert type(books).extent3d.__name__ == 'Extent3D'
    assert type(books).make_line.__name__ == 'MakeLine'
    assert type(books).union.__name__ == 'Union'
    with pytest.raises(
            ValueError,
            match="Geospatial aggregates only allowed on geometry fields."):
        books['id'].collect()