File: test_search_vectors.py

package info (click to toggle)
python-sqlalchemy-utils 0.41.2-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 1,252 kB
  • sloc: python: 13,566; makefile: 141
file content (66 lines) | stat: -rw-r--r-- 1,711 bytes parent folder | download | duplicates (2)
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
import pytest
import sqlalchemy as sa

from sqlalchemy_utils import aggregated, TSVectorType


def tsvector_reduce_concat(vectors):
    return sa.sql.expression.cast(
        sa.func.coalesce(
            sa.func.array_to_string(sa.func.array_agg(vectors), ' ')
        ),
        TSVectorType
    )


@pytest.fixture
def Product(Base):
    class Product(Base):
        __tablename__ = 'product'
        id = sa.Column(sa.Integer, primary_key=True)
        name = sa.Column(sa.Unicode(255))
        price = sa.Column(sa.Numeric)

        catalog_id = sa.Column(sa.Integer, sa.ForeignKey('catalog.id'))
    return Product


@pytest.fixture
def Catalog(Base, Product):
    class Catalog(Base):
        __tablename__ = 'catalog'
        id = sa.Column(sa.Integer, primary_key=True)
        name = sa.Column(sa.Unicode(255))

        @aggregated('products', sa.Column(TSVectorType))
        def product_search_vector(self):
            return tsvector_reduce_concat(
                sa.func.to_tsvector(Product.name)
            )

        products = sa.orm.relationship('Product', backref='catalog')
    return Catalog


@pytest.fixture
def init_models(Product, Catalog):
    pass


@pytest.mark.usefixtures('postgresql_dsn')
class TestSearchVectorAggregates:

    def test_assigns_aggregates_on_insert(self, session, Product, Catalog):
        catalog = Catalog(
            name='Some catalog'
        )
        session.add(catalog)
        session.commit()
        product = Product(
            name='Product XYZ',
            catalog=catalog
        )
        session.add(product)
        session.commit()
        session.refresh(catalog)
        assert catalog.product_search_vector == "'product':1 'xyz':2"