Esempio n. 1
0
def test_get_relations():
    """Test relations can be resolved in json-formatted collections."""
    with get_fixture_uri(
        ('collections/artists.json', 'collections/albums.json',
         'collections/tracks.json')) as (artists_uri, albums_uri, tracks_uri):
        # Artists
        artists = Collection(Artist,
                             artists_uri,
                             plugins=[
                                 byte.compilers.operation, byte.executors.file,
                                 byte.formats.json
                             ])

        # Albums
        albums = Collection(Album,
                            albums_uri,
                            plugins=[
                                byte.compilers.operation, byte.executors.file,
                                byte.formats.json
                            ])

        albums.connect(Album.Properties.artist, artists)

        # Tracks
        tracks = Collection(Track,
                            tracks_uri,
                            plugins=[
                                byte.compilers.operation, byte.executors.file,
                                byte.formats.json
                            ])

        tracks.connect(Track.Properties.album, albums)
        tracks.connect(Track.Properties.artist, artists)

        # Fetch track, and ensure relations can be resolved
        assert_that(
            tracks.get(Track['id'] == 1),
            has_properties({
                'id':
                1,
                'title':
                'Ascension (feat. Vince Staples)',
                'artist':
                has_properties({
                    'id': 1,
                    'title': 'Gorillaz'
                }),
                'album':
                has_properties({
                    'id':
                    1,
                    'title':
                    'Humanz',
                    'artist':
                    has_properties({
                        'id': 1,
                        'title': 'Gorillaz'
                    })
                })
            }))
Esempio n. 2
0
def test_relations():
    """Test collection relations with dynamic models."""
    # Artists
    artists = Collection(Artist, 'memory://', plugins=[
        byte.compilers.operation,
        byte.executors.memory
    ])

    # Albums
    albums = Collection(Album, 'memory://', plugins=[
        byte.compilers.operation,
        byte.executors.memory
    ])

    albums.connect(Album.Properties.artist, artists)

    # Tracks
    tracks = Collection(Track, 'memory://', plugins=[
        byte.compilers.operation,
        byte.executors.memory
    ])

    tracks.connect(Track.Properties.album, albums)
    tracks.connect(Track.Properties.artist, artists)

    # Create objects
    artists.create(
        id=1,
        title='Daft Punk'
    )

    albums.create(
        id=1,
        artist_id=1,

        title='Discovery'
    )

    tracks.create(
        id=1,
        artist_id=1,
        album_id=1,

        title='One More Time'
    )

    # Fetch track, and ensure relations can be resolved
    track = tracks.get(Track['id'] == 1)

    assert track.id == 1

    assert track.artist.id == 1

    assert track.album.id == 1
    assert track.album.artist.id == 1
Esempio n. 3
0
def test_all():
    """Test all items are returned from json-formatted collection."""
    with get_fixture_uri('collections/artists.json') as artists_uri:
        artists = Collection(Artist,
                             artists_uri,
                             plugins=[
                                 byte.compilers.operation, byte.executors.file,
                                 byte.formats.json
                             ])

        # Fetch artists, and validate properties
        assert_that(
            list(artists.all().iterator()),
            all_of(
                has_length(5),
                has_items(
                    has_properties({
                        'id': 1,
                        'title': 'Gorillaz'
                    }), has_properties({
                        'id': 2,
                        'title': 'Daft Punk'
                    }), has_properties({
                        'id': 3,
                        'title': 'Friendly Fires'
                    }), has_properties({
                        'id': 4,
                        'title': 'Miike Snow'
                    }), has_properties({
                        'id': 5,
                        'title': 'LCD Soundsystem'
                    }))))
Esempio n. 4
0
def test_multiple_legacy():
    """Test legacy insert query for multiple items is complied correctly."""
    users = Collection(User, 'sqlite://:memory:?table=users')

    compiler = SqliteCompiler(users.executor, version=(3, 6, 0))

    statements = list(
        compiler.compile(
            users.insert(User['username'], User['password']).items(
                {
                    'username': '******',
                    'password': '******'
                }, {
                    'username': '******',
                    'password': '******'
                })))

    assert_that(
        statements,
        equal_to([
            ('INSERT INTO "users" ("username", "password") VALUES (?, ?);',
             ('one', 'alpha')),
            ('INSERT INTO "users" ("username", "password") VALUES (?, ?);',
             ('two', 'beta'))
        ]))
Esempio n. 5
0
def test_simple():
    """Test items can be retrieved by primary key."""
    users = Collection(User, 'apsw://:memory:?table=users', plugins=[
        byte.compilers.sqlite,
        byte.executors.apsw
    ])

    # Create table, and add items directly to database
    with users.executor.connection() as connection:
        with connection.cursor() as cursor:
            cursor.execute("""
                CREATE TABLE users (
                    id          INTEGER         PRIMARY KEY AUTOINCREMENT NOT NULL,
                    username    VARCHAR(255),
                    password    VARCHAR(255)
                );
            """)

            cursor.execute("INSERT INTO users (id, username, password) VALUES (1, 'one', 'alpha');")
            cursor.execute("INSERT INTO users (id, username, password) VALUES (2, 'two', 'beta');")
            cursor.execute("INSERT INTO users (id, username, password) VALUES (3, 'three', 'charlie');")

    # Validate items
    user = users.select().where(User['id'] == 2).first()

    assert_that(user, all_of(
        not_none(),
        has_properties({
            'username': '******',
            'password': '******'
        })
    ))
Esempio n. 6
0
def test_all():
    """Test select query can be compiled to return all items."""
    users = Collection(User, 'sqlite://:memory:?table=users')

    statements = list(users.executor.compiler.compile(users.all()))

    assert_that(statements, equal_to([('SELECT * FROM "users";', ())]))
Esempio n. 7
0
def test_single():
    """Test single item can be inserted into a database."""
    users = Collection(User, 'pysqlite://:memory:?table=users', plugins=[
        byte.compilers.sqlite,
        byte.executors.pysqlite
    ])

    # Create table
    with users.executor.connection() as connection:
        with connection.cursor() as cursor:
            cursor.execute("""
                CREATE TABLE users (
                    id          INTEGER         PRIMARY KEY AUTOINCREMENT NOT NULL,
                    username    VARCHAR(255),
                    password    VARCHAR(255)
                );
            """)

    # Insert item
    users.insert().items(
        {'username': '******', 'password': '******'}
    ).execute()

    # Validate items
    assert_that(list(users.all()), only_contains(
        has_properties({
            'username': '******',
            'password': '******'
        })
    ))
Esempio n. 8
0
def test_and():
    """Test AND expression inside string can be compiled and executed."""
    users = Collection(User,
                       'sqlite://:memory:?table=users',
                       plugins=[byte.compilers.sqlite, byte.executors.sqlite])

    # Create table, and add items directly to database
    with users.executor.connection() as connection:
        with connection.cursor() as cursor:
            cursor.execute("""
                CREATE TABLE users (
                    id          INTEGER         PRIMARY KEY AUTOINCREMENT NOT NULL,
                    username    VARCHAR(255),
                    password    VARCHAR(255)
                );
            """)

            cursor.execute(
                "INSERT INTO users (id, username, password) VALUES (1, 'one', 'alpha');"
            )
            cursor.execute(
                "INSERT INTO users (id, username, password) VALUES (2, 'two', 'beta');"
            )
            cursor.execute(
                "INSERT INTO users (id, username, password) VALUES (3, 'three', 'charlie');"
            )

    # Validate items
    users = list(users.select().where('id > 1 and password != ?',
                                      'charlie').execute())

    assert_that(users, has_length(1))
Esempio n. 9
0
def test_rollback():
    """Test transaction is committed correctly."""
    users = Collection(User, 'pysqlite://:memory:?table=users', plugins=[
        byte.compilers.sqlite,
        byte.executors.pysqlite
    ])

    # Create table
    with users.executor.connection() as connection:
        with connection.cursor() as cursor:
            cursor.execute("""
                CREATE TABLE users (
                    id          INTEGER         PRIMARY KEY AUTOINCREMENT NOT NULL,
                    username    VARCHAR(255),
                    password    VARCHAR(255)
                );
            """)

    # Insert multiple items (with conflict) inside transaction
    with pytest.raises(sqlite3.IntegrityError):
        with users.transaction():
            users.insert().items({'id': 1, 'username': '******', 'password': '******'}).execute()
            users.insert().items({'id': 2, 'username': '******', 'password': '******'}).execute()
            users.insert().items({'id': 1, 'username': '******', 'password': '******'}).execute()
            users.insert().items({'id': 3, 'username': '******', 'password': '******'}).execute()

    # Ensure items were inserted
    assert_that(list(users.all()), has_length(0))

    # Validate executor state
    assert_that(users.executor.transactions, has_length(0))
    assert_that(users.executor.connections.active, equal_to(0))
Esempio n. 10
0
def test_already_inside_transaction():
    """Ensure an exception is raised while attempting to create a transaction while already in a transaction."""
    users = Collection(User,
                       'apsw://:memory:?table=users',
                       plugins=[byte.compilers.sqlite, byte.executors.apsw])

    # Insert multiple items (with conflict) inside transaction
    with pytest.raises(Exception):
        with users.transaction():
            with users.transaction():
                pass
Esempio n. 11
0
def test_where():
    """Test select query with where expressions can be compiled."""
    users = Collection(User, 'sqlite://:memory:?table=users')

    statements = list(
        users.executor.compiler.compile(
            users.select().where(User['id'] == 142)))

    assert_that(
        statements,
        equal_to([('SELECT * FROM "users" WHERE "users"."id" == ?;', (142, ))
                  ]))
Esempio n. 12
0
def test_where():
    """Test json-formatted collections can be filtered with expressions."""
    with get_fixture_uri('collections/cities.json') as cities_uri:
        cities = Collection(City,
                            cities_uri,
                            plugins=[
                                byte.compilers.operation, byte.executors.file,
                                byte.formats.json
                            ])

        # Fetch cities, and validate properties
        items = list(
            cities.select().where(City['country'] == 'New Zealand').iterator())

        assert_that(
            items,
            all_of(
                has_length(35),
                has_items(
                    has_properties({
                        'id': '2179537',
                        'name': 'Wellington',
                        'country': 'New Zealand',
                        'subcountry': 'Wellington'
                    }),
                    has_properties({
                        'id': '2179670',
                        'name': 'Wanganui',
                        'country': 'New Zealand',
                        'subcountry': 'Manawatu-Wanganui'
                    }),
                    has_properties({
                        'id': '2181133',
                        'name': 'Timaru',
                        'country': 'New Zealand',
                        'subcountry': 'Canterbury'
                    }),
                    has_properties({
                        'id': '2181742',
                        'name': 'Taupo',
                        'country': 'New Zealand',
                        'subcountry': 'Waikato'
                    }),
                    has_properties({
                        'id': '2184155',
                        'name': 'Pukekohe East',
                        'country': 'New Zealand',
                        'subcountry': 'Auckland'
                    }),
                )))
Esempio n. 13
0
def test_get_basic():
    """Test items can be retrieved from json-formatted collections."""
    with get_fixture_uri('collections/artists.json') as artists_uri:
        artists = Collection(Artist,
                             artists_uri,
                             plugins=[
                                 byte.compilers.operation, byte.executors.file,
                                 byte.formats.json
                             ])

        # Fetch artist, and validate properties
        assert_that(artists.get(Artist['id'] == 1),
                    has_properties({
                        'id': 1,
                        'title': 'Gorillaz'
                    }))
Esempio n. 14
0
def test_create():
    """Test items can be created on json-formatted collections."""
    with get_fixture_uri('collections/artists.json') as artists_uri:
        artists = Collection(Artist,
                             artists_uri,
                             plugins=[
                                 byte.compilers.operation, byte.executors.file,
                                 byte.formats.json
                             ])

        # Create artist
        artists.create(id=123, title='Fenech-Soler')

        # Fetch artist, and validate properties
        assert_that(artists.get(Artist['id'] == 123),
                    has_properties({
                        'id': 123,
                        'title': 'Fenech-Soler'
                    }))
Esempio n. 15
0
def test_all():
    """Test all items can be retrieved from database."""
    users = Collection(User,
                       'apsw://:memory:?table=users',
                       plugins=[byte.compilers.sqlite, byte.executors.apsw])

    # Create table, and add items directly to database
    with users.executor.connection() as connection:
        with connection.cursor() as cursor:
            cursor.execute("""
                CREATE TABLE users (
                    id          INTEGER         PRIMARY KEY AUTOINCREMENT NOT NULL,
                    username    VARCHAR(255),
                    password    VARCHAR(255)
                );
            """)

            cursor.execute(
                "INSERT INTO users (username, password) VALUES ('one', 'alpha');"
            )
            cursor.execute(
                "INSERT INTO users (username, password) VALUES ('two', 'beta');"
            )
            cursor.execute(
                "INSERT INTO users (username, password) VALUES ('three', 'charlie');"
            )

    # Validate items
    assert_that(
        users.all(),
        only_contains(
            has_properties({
                'username': '******',
                'password': '******'
            }), has_properties({
                'username': '******',
                'password': '******'
            }), has_properties({
                'username': '******',
                'password': '******'
            })))
Esempio n. 16
0
def test_basic():
    """Test collection with dynamic models."""
    artists = Collection(Artist, 'memory://', plugins=[
        byte.compilers.operation,
        byte.executors.memory
    ])

    # Update memory collection
    artists.executor.update({
        1: {
            'id': 1,
            'title': 'Daft Punk'
        }
    })

    # Fetch artist, and validate properties
    artist = artists.get(Artist['id'] == 1)

    assert artist
    assert artist.id == 1
    assert artist.title == 'Daft Punk'
Esempio n. 17
0
from __future__ import absolute_import, division, print_function

from byte.collection import Collection
from byte.core.models.expressions.proxy import ProxyEqual, ProxyLessThan, ProxyNotEqual, ProxyOr
from tests.base.models.dynamic.user import User

from hamcrest import *

users = Collection(User)


def test_or():
    """Test select() query can be created with an OR operator inside a string expression."""
    query = users.select().where('id < 35 or username == "alpha"')

    assert_that(
        query,
        has_property(
            'state',
            has_entries({
                # where()
                'where':
                all_of(
                    has_length(1),
                    has_items(
                        # id < 35 or username == "alpha"
                        all_of(
                            instance_of(ProxyOr),
                            has_properties({
                                'values':
                                all_of(