示例#1
0
def db_0006(tmp_path):
    path = tmp_path / "foo.db"
    manager = DatabaseManager(SqliteDatabase(str(path)))
    manager.upgrade("0006")
    print(path)
    yield path
    path.unlink()
示例#2
0
def test_downgrade_not_applied(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    migrations = manager.migration_files

    manager.downgrade(migrations[0])
    assert 'not yet applied: {}'.format(migrations[0]) in caplog.text
示例#3
0
def test_create_module(tmpdir, caplog):
    manager = DatabaseManager(models.database, directory=tmpdir)
    manager.create(models)
    migrations = manager.migration_files

    assert len(migrations) == 7

    assert migrations[0].endswith('create_table_basicfields')
    assert 'created: {}'.format(migrations[0]) in caplog.text

    assert migrations[1].endswith('create_table_hascheckconstraint')
    assert 'created: {}'.format(migrations[1]) in caplog.text

    assert migrations[2].endswith('create_table_organization')
    assert 'created: {}'.format(migrations[2]) in caplog.text

    assert migrations[3].endswith('create_table_complexperson')
    assert 'created: {}'.format(migrations[3]) in caplog.text

    assert migrations[4].endswith('create_table_person')
    assert 'created: {}'.format(migrations[4]) in caplog.text

    assert migrations[5].endswith('create_table_hasuniqueforeignkey')
    assert 'created: {}'.format(migrations[5]) in caplog.text

    assert migrations[6].endswith('create_table_relatestoname')
    assert 'created: {}'.format(migrations[6]) in caplog.text
示例#4
0
def test_create_module(tmpdir, caplog):
    """Test module creations.

    peewee handles the model creation sequentially in prior versions of 2.10

    Refer to:
    https://github.com/coleifer/peewee/compare/2.9.2...2.10.0
    """
    manager = DatabaseManager(models.database, directory=tmpdir)
    manager.create(models)
    migrations = manager.migration_files

    assert len(migrations) == 7

    assert migrations[0].endswith('create_table_basicfields')
    assert 'created: {}'.format(migrations[0]) in caplog.text

    assert migrations[1].endswith('create_table_hascheckconstraint')
    assert 'created: {}'.format(migrations[1]) in caplog.text

    assert migrations[2].endswith('create_table_organization')
    assert 'created: {}'.format(migrations[2]) in caplog.text

    assert migrations[3].endswith('create_table_complexperson')
    assert 'created: {}'.format(migrations[3]) in caplog.text

    assert migrations[4].endswith('create_table_person')
    assert 'created: {}'.format(migrations[4]) in caplog.text

    assert migrations[5].endswith('create_table_hasuniqueforeignkey')
    assert 'created: {}'.format(migrations[5]) in caplog.text

    assert migrations[6].endswith('create_table_relatestoname')
    assert 'created: {}'.format(migrations[6]) in caplog.text
示例#5
0
def test_migration_0006_to_0005(db_0006_with_data):
    # Verify we have data
    with orm.db:
        metric_0006 = orm.db.execute_sql('SELECT * FROM "Metric"').fetchall()
        data_0006 = orm.db.execute_sql('SELECT * FROM "Datapoint"').fetchall()
        migrations = orm.db.execute_sql(
            'SELECT * FROM "migration_history"').fetchall()

    assert len(metric_0006) != 0
    assert len(data_0006) != 0
    # Make sure we have migration 0006 applied.
    msg = "Migration 0006 is not applied, it should be."
    assert any("0006" in m[1] for m in migrations), msg

    # Then downgrade to 0005. `orm.create_db` doesn't have any downgrade
    # capability, so we need to use `manager.downgrade()`
    manager = DatabaseManager(SqliteDatabase(str(db_0006_with_data)))
    manager.downgrade("0005")

    with orm.db:
        metric_0005 = orm.db.execute_sql('SELECT * FROM "Metric"').fetchall()
        data_0005 = orm.db.execute_sql('SELECT * FROM "Datapoint"').fetchall()
        migrations = orm.db.execute_sql(
            'SELECT * FROM "migration_history"').fetchall()

    # Ensure that migration 0006 *is not* applied.
    msg = "Migration 0006 applied when it shouldn't be."
    assert not any("0006" in m[1] for m in migrations), msg

    # And that data still matches.
    assert len(metric_0005) != 0
    assert metric_0005 == metric_0006
    assert len(data_0005) != 0
    assert data_0005 == data_0006
示例#6
0
def up_to_date_db(tmp_path):
    """
    Return a database that has all migrations applied.
    """
    path = tmp_path / "foo.db"
    manager = DatabaseManager(SqliteDatabase(str(path)))
    manager.upgrade()
    yield path
    path.unlink()
示例#7
0
def outdated_db(up_to_date_db):
    """
    Return a database file that is missing some migrations.
    """
    # Rename things to avoid confusion
    path = up_to_date_db
    # Start with an up-to-date database, then downgrade
    manager = DatabaseManager(SqliteDatabase(str(path)))
    manager.downgrade()
    yield path
示例#8
0
def test_revision(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    assert manager.revision()
    first = manager.migration_files[0]
    assert 'created: {}'.format(first) in caplog.text

    assert manager.revision('Custom Name')
    first = manager.migration_files[1]
    assert 'created: {}'.format(first) in caplog.text
示例#9
0
def test_revision(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    assert manager.revision()
    first = manager.migration_files[0]
    assert 'created: {}'.format(first) in caplog.text

    assert manager.revision('Custom Name')
    first = manager.migration_files[1]
    assert 'created: {}'.format(first) in caplog.text
示例#10
0
def test_open_migration(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    first = manager.migration_files[0]

    with manager.open_migration(first) as handle:
        content = handle.read()

    assert content.startswith('"""\nauto migration')
    assert 'def upgrade(migrator):\n    pass' in content
    assert 'def downgrade(migrator):\n    pass' in content
示例#11
0
def test_upgrade_target(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    manager.revision()
    migrations = manager.migration_files

    manager.upgrade(migrations[0])
    assert 'upgrade: {}'.format(migrations[0]) in caplog.text

    assert manager.db_migrations == (migrations[0],)
    assert manager.diff == (migrations[1],)
示例#12
0
def test_open_migration(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    first = manager.migration_files[0]

    with manager.open_migration(first) as handle:
        content = handle.read()

    assert content.startswith('"""\nauto migration')
    assert 'def upgrade(migrator):\n    pass' in content
    assert 'def downgrade(migrator):\n    pass' in content
示例#13
0
def test_database_creation_error(tmpdir):
    db = {'name': ':memory:'}
    with pytest.raises(peewee.DatabaseError):
        DatabaseManager(db, directory=tmpdir)

    db = {'engine': 'peewee.SqliteDatabase'}
    with pytest.raises(peewee.DatabaseError):
        DatabaseManager(db, directory=tmpdir)

    db = {'engine': 'unknown.FakeDatabase', 'name': ':memory:'}
    with pytest.raises(peewee.DatabaseError):
        DatabaseManager(db, directory=tmpdir)
示例#14
0
def test_database_creation(tmpdir):
    db = peewee.SqliteDatabase(':memory:')
    manager = DatabaseManager(db, directory=tmpdir)
    assert isinstance(manager.database, peewee.SqliteDatabase)

    db = {'engine': 'peewee.SqliteDatabase', 'name': ':memory:'}
    manager = DatabaseManager(db, directory=tmpdir)
    assert isinstance(manager.database, peewee.SqliteDatabase)

    db = 'sqlite:///:memory:'
    manager = DatabaseManager(db, directory=tmpdir)
    assert isinstance(manager.database, peewee.SqliteDatabase)
示例#15
0
def test_delete_not_found(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    manager.upgrade()

    manager.delete('does-not-exist')
    assert 'could not find migration: does-not-exist' in caplog.text
示例#16
0
def test_files_and_diff(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    manager.revision('custom name')
    migrations = manager.migration_files

    rv = manager.db_migrations
    assert not rv

    rv = manager.migration_files
    assert rv == (migrations[0], migrations[1],)

    rv = manager.diff
    assert rv == (migrations[0], migrations[1],)
示例#17
0
def test_foreign_key(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    with manager.migrator.create_table('basic') as table:
        table.primary_key('id')
        table.char('username')

    with manager.migrator.create_table('related1') as table:
        table.primary_key('id')
        table.foreign_key('int', 'basic_id', 'basic')

    with manager.migrator.create_table('related2') as table:
        table.primary_key('id')
        table.foreign_key('int', 'basic_id', 'basic.id')

    with manager.migrator.create_table('related3') as table:
        table.primary_key('id')
        table.foreign_key('int', 'basic', 'basic')

    with manager.migrator.create_table('related4') as table:
        table.primary_key('id')
        table.foreign_key('int', 'basic', 'basic.id')

    with manager.migrator.create_table('related5') as table:
        table.primary_key('id')
        table.foreign_key('char', 'basic', 'basic.username')
示例#18
0
def test_create_table(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    with manager.migrator.create_table('awesome') as table:
        table.primary_key('id')
        table.bare('col_bare')
        table.biginteger('col_biginteger')
        table.binary('col_binary')
        table.blob('col_blob')
        table.bool('col_bool')
        table.char('col_char')
        table.date('col_date')
        table.datetime('col_datetime')
        table.decimal('col_decimal')
        table.double('col_double')
        table.fixed('col_fixed')
        table.float('col_float')
        table.int('col_int')
        table.integer('col_integer')
        table.smallint('col_smallint')
        table.smallinteger('col_smallinteger')
        table.text('col_text')
        table.time('col_time')
        table.uuid('col_uuid')
        table.bin_uuid('col_bin_uuid')
        table.add_index(('col_char', 'col_integer'), unique=True)

    assert 'awesome' in manager.database.get_tables()
示例#19
0
def test_rename_table(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    with manager.migrator.create_table('awesome') as table:
        table.primary_key('id')

    manager.migrator.rename_table('awesome', 'more_awesome')
示例#20
0
def test_create_module(tmpdir, caplog):
    """Test module creations.

    peewee changed the migration creation order in:
    https://github.com/coleifer/peewee/compare/2.9.2...2.10.0

    First create models on which current model depends
    (either through foreign keys or through depends_on),
    then create current model itself.
    """
    manager = DatabaseManager(models.database, directory=tmpdir)
    manager.create(models)
    migrations = manager.migration_files

    assert len(migrations) == 8

    # basicfields has no relationship
    assert migrations[0].endswith('create_table_basicfields')
    assert 'created: {}'.format(migrations[0]) in caplog.text

    # organization has no relationships
    assert migrations[1].endswith('create_table_organization')
    assert 'created: {}'.format(migrations[1]) in caplog.text

    # since complexpersion relates to organization is then now created
    assert migrations[2].endswith('create_table_complexperson')
    assert 'created: {}'.format(migrations[2]) in caplog.text

    # HasCheckConstraint has no relationships
    assert migrations[3].endswith('create_table_hascheckconstraint')
    assert 'created: {}'.format(migrations[3]) in caplog.text

    # Person has no relationship
    assert migrations[4].endswith('create_table_person')
    assert 'created: {}'.format(migrations[4]) in caplog.text

    # HasUniqueForeignKey relates to Person
    assert migrations[5].endswith('create_table_hasuniqueforeignkey')
    assert 'created: {}'.format(migrations[5]) in caplog.text

    # ModelWithTimestamp
    assert migrations[6].endswith('create_table_modelwithtimestamp')
    assert 'created: {}'.format(migrations[6]) in caplog.text

    # RelatesToName relates to Person
    assert migrations[7].endswith('create_table_relatestoname')
    assert 'created: {}'.format(migrations[7]) in caplog.text
示例#21
0
def test_drop_table(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    with manager.migrator.create_table('awesome') as table:
        table.primary_key('id')

    manager.migrator.drop_table('awesome')
    assert 'awesome' not in manager.database.get_tables()
示例#22
0
def test_rename_column(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    with manager.migrator.create_table('awesome') as table:
        table.primary_key('id')

    manager.migrator.add_column('awesome', 'name', 'char', null=True)
    manager.migrator.rename_column('awesome', 'name', 'newname')
示例#23
0
def peewee_moves_cli_proxy(ctx, **kwargs):
    class ScriptInfo:
        def __init__(self):
            self.data = {'manager': None}

    ctx.obj = ctx.obj or ScriptInfo()
    ctx.obj.data['manager'] = DatabaseManager(database=persist.get_database(),
                                              directory=persist.get_migrations_dir())
示例#24
0
def test_already_upgraded(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    migrations = manager.migration_files

    manager.upgrade(migrations[0])
    assert 'upgrade: {}'.format(migrations[0]) in caplog.text

    manager.upgrade(migrations[0])
    assert 'already applied: {}'.format(migrations[0]) in caplog.text
示例#25
0
def test_delete_not_found(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    manager.upgrade()

    manager.delete('does-not-exist')
    assert 'could not find migration: does-not-exist' in caplog.text
示例#26
0
def test_index(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    with manager.migrator.create_table('awesome') as table:
        table.primary_key('id')
        table.char('name')

    manager.migrator.add_index('awesome', ('name', ), unique=True)
    manager.migrator.drop_index('awesome', 'awesome_name')
示例#27
0
def test_not_null(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    with manager.migrator.create_table('awesome') as table:
        table.primary_key('id')
        table.char('name')

    manager.migrator.add_not_null('awesome', 'name')
    manager.migrator.drop_not_null('awesome', 'name')
示例#28
0
def test_delete(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    manager.upgrade()
    migrations = manager.migration_files

    manager.delete(migrations[0])
    assert 'deleted: {}'.format(migrations[0]) in caplog.text

    assert not manager.db_migrations
    assert not manager.migration_files
示例#29
0
def test_execute_sql(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    with manager.migrator.create_table('awesome') as table:
        table.primary_key('id')
        table.char('name')

    manager.migrator.execute_sql('select * from awesome')
    with pytest.raises(peewee.OperationalError):
        manager.migrator.execute_sql('select * from notable')
示例#30
0
def test_status(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    manager.status()
    assert 'no migrations found' in caplog.text

    manager.revision()
    first = manager.migration_files[0]
    assert 'created: {}'.format(first) in caplog.text

    manager.status()
    assert '[ ] {}'.format(first) in caplog.text
示例#31
0
def test_str_constraints(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    with manager.migrator.create_table('awesome') as table:
        table.primary_key('id')
        table.char('username',
                   constraints=[
                       "check (username in ('tim', 'bob'))",
                       peewee.Check("username in ('tim', 'bob')")
                   ])
示例#32
0
def test_already_upgraded(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    migrations = manager.migration_files

    manager.upgrade(migrations[0])
    assert 'upgrade: {}'.format(migrations[0]) in caplog.text

    manager.upgrade(migrations[0])
    assert 'already applied: {}'.format(migrations[0]) in caplog.text
示例#33
0
def test_downgrade_not_applied(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    migrations = manager.migration_files

    manager.downgrade(migrations[0])
    assert 'not yet applied: {}'.format(migrations[0]) in caplog.text
示例#34
0
def test_delete(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    manager.upgrade()
    migrations = manager.migration_files

    manager.delete(migrations[0])
    assert 'deleted: {}'.format(migrations[0]) in caplog.text

    assert not manager.db_migrations
    assert not manager.migration_files
示例#35
0
def test_run_migration_exception(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()

    # Open the migration file and write lines to it that will error when we try to run it.
    with manager.open_migration('0001_auto_migration', 'w') as handle:
        handle.write('def upgrade(migrator):\n    undefined\n')

    manager.upgrade()
    assert "upgrade: 0001_auto_migration" in caplog.text
    assert "'undefined' is not defined" in caplog.text
示例#36
0
def test_status(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    manager.status()
    assert 'no migrations found' in caplog.text

    manager.revision()
    first = manager.migration_files[0]
    assert 'created: {}'.format(first) in caplog.text

    manager.status()
    assert '[ ] {}'.format(first) in caplog.text
示例#37
0
def test_find_migration(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()

    # find the first migration name
    first = manager.migration_files[0]
    first_id = first.split('_')[0]

    rv = manager.find_migration(first_id)
    assert rv == first

    rv = manager.find_migration(first)
    assert rv == first

    with pytest.raises(ValueError):
        manager.find_migration('does_not_exist')
示例#38
0
def test_upgrade_all(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    manager.revision()
    migrations = manager.migration_files

    manager.upgrade()
    assert 'upgrade: {}'.format(migrations[0]) in caplog.text
    assert 'upgrade: {}'.format(migrations[1]) in caplog.text

    assert manager.db_migrations == (migrations[0], migrations[1])
    assert not manager.diff

    # All migrations applied now...
    manager.upgrade()
    assert 'all migrations applied!' in caplog.text
示例#39
0
def test_downgrade_single(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    manager.revision()
    manager.upgrade()
    migrations = manager.migration_files

    assert manager.db_migrations == (
        migrations[0],
        migrations[1],
    )
    assert not manager.diff

    manager.downgrade()
    assert 'downgrade: {}'.format(migrations[1]) in caplog.text

    assert manager.db_migrations == (migrations[0], )
    assert manager.diff == (migrations[1], )
示例#40
0
def test_run_migration_exception(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()

    # Open the migration file and write lines to it that will error when we try to run it.
    with manager.open_migration('0001_auto_migration', 'w') as handle:
        handle.write('def upgrade(migrator):\n    undefined\n')

    manager.upgrade()
    assert "upgrade: 0001_auto_migration" in caplog.text
    assert "'undefined' is not defined" in caplog.text
示例#41
0
def test_downgrade_single(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    manager.revision()
    manager.upgrade()
    migrations = manager.migration_files

    assert manager.db_migrations == (migrations[0], migrations[1],)
    assert not manager.diff

    manager.downgrade()
    assert 'downgrade: {}'.format(migrations[1]) in caplog.text

    assert manager.db_migrations == (migrations[0],)
    assert manager.diff == (migrations[1],)
示例#42
0
def test_find_migration(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()

    # find the first migration name
    first = manager.migration_files[0]
    first_id = first.split('_')[0]

    rv = manager.find_migration(first_id)
    assert rv == first

    rv = manager.find_migration(first)
    assert rv == first

    with pytest.raises(ValueError):
        manager.find_migration('does_not_exist')
示例#43
0
def test_upgrade_all(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()
    manager.revision()
    migrations = manager.migration_files

    manager.upgrade()
    assert 'upgrade: {}'.format(migrations[0]) in caplog.text
    assert 'upgrade: {}'.format(migrations[1]) in caplog.text

    assert manager.db_migrations == (migrations[0], migrations[1])
    assert not manager.diff

    # All migrations applied now...
    manager.upgrade()
    assert 'all migrations applied!' in caplog.text
示例#44
0
def test_info(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    manager.info()
    assert 'driver: SqliteDatabase' in caplog.text
    assert 'database: :memory:' in caplog.text
示例#45
0
def test_downgrade_target_error(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.revision()

    manager.downgrade('does-not-exist')
    assert 'could not find migration: does-not-exist' in caplog.text
示例#46
0
def test_revision_error(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    assert not manager.revision('Bad Characters: \0')
    assert 'embedded' in caplog.text
示例#47
0
def test_downgrade_nodiff(tmpdir, caplog):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)
    manager.downgrade()
    assert 'migrations not yet applied!' in caplog.text