summaryrefslogtreecommitdiff
path: root/ironic/tests/unit/db/sqlalchemy/test_migrations.py
blob: e7c6be4a0034587ebca2ef9e29c31af4e82bd185 (plain)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
# Copyright 2010-2011 OpenStack Foundation
# Copyright 2012-2013 IBM Corp.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
Tests for database migrations. There are "opportunistic" tests for both mysql
and postgresql in here, which allows testing against these databases in a
properly configured unit test environment.

For the opportunistic testing you need to set up a db named 'openstack_citest'
with user 'openstack_citest' and password 'openstack_citest' on localhost.
The test will then use that db and u/p combo to run the tests.

For postgres on Ubuntu this can be done with the following commands:

::

 sudo -u postgres psql
 postgres=# create user openstack_citest with createdb login password
      'openstack_citest';
 postgres=# create database openstack_citest with owner openstack_citest;

"""

import collections
import contextlib

from alembic import script
import fixtures
import mock
from oslo_db import exception as db_exc
from oslo_db.sqlalchemy import enginefacade
from oslo_db.sqlalchemy import test_fixtures
from oslo_db.sqlalchemy import test_migrations
from oslo_db.sqlalchemy import utils as db_utils
from oslo_log import log as logging
from oslo_utils import uuidutils
from oslotest import base as test_base
import sqlalchemy
import sqlalchemy.exc

from ironic.conf import CONF
from ironic.db.sqlalchemy import migration
from ironic.db.sqlalchemy import models
from ironic.tests import base

LOG = logging.getLogger(__name__)

# NOTE(vdrok): This was introduced after migration tests started taking more
# time in gate. Timeout value in seconds for tests performing migrations.
MIGRATIONS_TIMEOUT = 300


@contextlib.contextmanager
def patch_with_engine(engine):
    with mock.patch.object(enginefacade.writer,
                           'get_engine') as patch_engine:
        patch_engine.return_value = engine
        yield


class WalkVersionsMixin(object):
    def _walk_versions(self, engine=None, alembic_cfg=None):
        # Determine latest version script from the repo, then
        # upgrade from 1 through to the latest, with no data
        # in the databases. This just checks that the schema itself
        # upgrades successfully.

        # Place the database under version control
        with patch_with_engine(engine):

            script_directory = script.ScriptDirectory.from_config(alembic_cfg)

            self.assertIsNone(self.migration_api.version(alembic_cfg))

            versions = [ver for ver in script_directory.walk_revisions()]

            for version in reversed(versions):
                self._migrate_up(engine, alembic_cfg,
                                 version.revision, with_data=True)

    def _migrate_up(self, engine, config, version, with_data=False):
        """migrate up to a new version of the db.

        We allow for data insertion and post checks at every
        migration version with special _pre_upgrade_### and
        _check_### functions in the main test.
        """
        # NOTE(sdague): try block is here because it's impossible to debug
        # where a failed data migration happens otherwise
        try:
            if with_data:
                data = None
                pre_upgrade = getattr(
                    self, "_pre_upgrade_%s" % version, None)
                if pre_upgrade:
                    data = pre_upgrade(engine)

            self.migration_api.upgrade(version, config=config)
            self.assertEqual(version, self.migration_api.version(config))
            if with_data:
                check = getattr(self, "_check_%s" % version, None)
                if check:
                    check(engine, data)
        except Exception:
            LOG.error("Failed to migrate to version %(version)s on engine "
                      "%(engine)s",
                      {'version': version, 'engine': engine})
            raise


class TestWalkVersions(base.TestCase, WalkVersionsMixin):
    def setUp(self):
        super(TestWalkVersions, self).setUp()
        self.migration_api = mock.MagicMock()
        self.engine = mock.MagicMock()
        self.config = mock.MagicMock()
        self.versions = [mock.Mock(revision='2b2'), mock.Mock(revision='1a1')]

    def test_migrate_up(self):
        self.migration_api.version.return_value = 'dsa123'

        self._migrate_up(self.engine, self.config, 'dsa123')

        self.migration_api.upgrade.assert_called_with('dsa123',
                                                      config=self.config)
        self.migration_api.version.assert_called_with(self.config)

    def test_migrate_up_with_data(self):
        test_value = {"a": 1, "b": 2}
        self.migration_api.version.return_value = '141'
        self._pre_upgrade_141 = mock.MagicMock()
        self._pre_upgrade_141.return_value = test_value
        self._check_141 = mock.MagicMock()

        self._migrate_up(self.engine, self.config, '141', True)

        self._pre_upgrade_141.assert_called_with(self.engine)
        self._check_141.assert_called_with(self.engine, test_value)

    @mock.patch.object(script, 'ScriptDirectory')
    @mock.patch.object(WalkVersionsMixin, '_migrate_up')
    def test_walk_versions_all_default(self, _migrate_up, script_directory):
        fc = script_directory.from_config()
        fc.walk_revisions.return_value = self.versions
        self.migration_api.version.return_value = None

        self._walk_versions(self.engine, self.config)

        self.migration_api.version.assert_called_with(self.config)

        upgraded = [mock.call(self.engine, self.config, v.revision,
                    with_data=True) for v in reversed(self.versions)]
        self.assertEqual(self._migrate_up.call_args_list, upgraded)

    @mock.patch.object(script, 'ScriptDirectory')
    @mock.patch.object(WalkVersionsMixin, '_migrate_up')
    def test_walk_versions_all_false(self, _migrate_up, script_directory):
        fc = script_directory.from_config()
        fc.walk_revisions.return_value = self.versions
        self.migration_api.version.return_value = None

        self._walk_versions(self.engine, self.config)

        upgraded = [mock.call(self.engine, self.config, v.revision,
                    with_data=True) for v in reversed(self.versions)]
        self.assertEqual(upgraded, self._migrate_up.call_args_list)


class MigrationCheckersMixin(object):

    def setUp(self):
        super(MigrationCheckersMixin, self).setUp()
        self.engine = enginefacade.writer.get_engine()
        self.config = migration._alembic_config()
        self.migration_api = migration
        self.useFixture(fixtures.Timeout(MIGRATIONS_TIMEOUT,
                                         gentle=True))

    def test_walk_versions(self):
        self._walk_versions(self.engine, self.config)

    def _check_21b331f883ef(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]
        self.assertIn('provision_updated_at', col_names)
        self.assertIsInstance(nodes.c.provision_updated_at.type,
                              sqlalchemy.types.DateTime)

    def _check_3cb628139ea4(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]

        self.assertIn('console_enabled', col_names)
        # in some backends bool type is integer
        self.assertIsInstance(nodes.c.console_enabled.type,
                              (sqlalchemy.types.Boolean,
                               sqlalchemy.types.Integer))

    def _check_31baaf680d2b(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]
        self.assertIn('instance_info', col_names)
        self.assertIsInstance(nodes.c.instance_info.type,
                              sqlalchemy.types.TEXT)

    def _check_3bea56f25597(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        instance_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        data = {'driver': 'fake',
                'uuid': uuidutils.generate_uuid(),
                'instance_uuid': instance_uuid}
        nodes.insert().values(data).execute()
        data['uuid'] = uuidutils.generate_uuid()
        self.assertRaises(db_exc.DBDuplicateEntry,
                          nodes.insert().execute, data)

    def _check_487deb87cc9d(self, engine, data):
        conductors = db_utils.get_table(engine, 'conductors')
        column_names = [column.name for column in conductors.c]

        self.assertIn('online', column_names)
        self.assertIsInstance(conductors.c.online.type,
                              (sqlalchemy.types.Boolean,
                               sqlalchemy.types.Integer))
        nodes = db_utils.get_table(engine, 'nodes')
        column_names = [column.name for column in nodes.c]
        self.assertIn('conductor_affinity', column_names)
        self.assertIsInstance(nodes.c.conductor_affinity.type,
                              sqlalchemy.types.Integer)

        data_conductor = {'hostname': 'test_host'}
        conductors.insert().execute(data_conductor)
        conductor = conductors.select(
            conductors.c.hostname ==
            data_conductor['hostname']).execute().first()

        data_node = {'uuid': uuidutils.generate_uuid(),
                     'conductor_affinity': conductor['id']}
        nodes.insert().execute(data_node)
        node = nodes.select(
            nodes.c.uuid == data_node['uuid']).execute().first()
        self.assertEqual(conductor['id'], node['conductor_affinity'])

    def _check_242cc6a923b3(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]
        self.assertIn('maintenance_reason', col_names)
        self.assertIsInstance(nodes.c.maintenance_reason.type,
                              sqlalchemy.types.String)

    def _pre_upgrade_5674c57409b9(self, engine):
        # add some nodes in various states so we can assert that "None"
        # was replaced by "available", and nothing else changed.
        nodes = db_utils.get_table(engine, 'nodes')
        data = [{'uuid': uuidutils.generate_uuid(),
                 'provision_state': 'fake state'},
                {'uuid': uuidutils.generate_uuid(),
                 'provision_state': 'active'},
                {'uuid': uuidutils.generate_uuid(),
                 'provision_state': 'deleting'},
                {'uuid': uuidutils.generate_uuid(),
                 'provision_state': None}]
        nodes.insert().values(data).execute()
        return data

    def _check_5674c57409b9(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        result = engine.execute(nodes.select())

        def _get_state(uuid):
            for row in data:
                if row['uuid'] == uuid:
                    return row['provision_state']

        for row in result:
            old = _get_state(row['uuid'])
            new = row['provision_state']
            if old is None:
                self.assertEqual('available', new)
            else:
                self.assertEqual(old, new)

    def _check_bb59b63f55a(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]
        self.assertIn('driver_internal_info', col_names)
        self.assertIsInstance(nodes.c.driver_internal_info.type,
                              sqlalchemy.types.TEXT)

    def _check_3ae36a5f5131(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        column_names = [column.name for column in nodes.c]
        self.assertIn('name', column_names)
        self.assertIsInstance(nodes.c.name.type,
                              sqlalchemy.types.String)
        data = {'driver': 'fake',
                'uuid': uuidutils.generate_uuid(),
                'name': 'node'
                }
        nodes.insert().values(data).execute()
        data['uuid'] = uuidutils.generate_uuid()
        self.assertRaises(db_exc.DBDuplicateEntry,
                          nodes.insert().execute, data)

    def _check_1e1d5ace7dc6(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        column_names = [column.name for column in nodes.c]
        self.assertIn('inspection_started_at', column_names)
        self.assertIn('inspection_finished_at', column_names)
        self.assertIsInstance(nodes.c.inspection_started_at.type,
                              sqlalchemy.types.DateTime)
        self.assertIsInstance(nodes.c.inspection_finished_at.type,
                              sqlalchemy.types.DateTime)

    def _check_4f399b21ae71(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]
        self.assertIn('clean_step', col_names)
        self.assertIsInstance(nodes.c.clean_step.type,
                              sqlalchemy.types.String)

    def _check_789acc877671(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]
        self.assertIn('raid_config', col_names)
        self.assertIn('target_raid_config', col_names)
        self.assertIsInstance(nodes.c.raid_config.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(nodes.c.target_raid_config.type,
                              sqlalchemy.types.String)

    def _check_2fb93ffd2af1(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        bigstring = 'a' * 255
        uuid = uuidutils.generate_uuid()
        data = {'uuid': uuid, 'name': bigstring}
        nodes.insert().execute(data)
        node = nodes.select(nodes.c.uuid == uuid).execute().first()
        self.assertEqual(bigstring, node['name'])

    def _check_516faf1bb9b1(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        bigstring = 'a' * 255
        uuid = uuidutils.generate_uuid()
        data = {'uuid': uuid, 'driver': bigstring}
        nodes.insert().execute(data)
        node = nodes.select(nodes.c.uuid == uuid).execute().first()
        self.assertEqual(bigstring, node['driver'])

    def _check_48d6c242bb9b(self, engine, data):
        node_tags = db_utils.get_table(engine, 'node_tags')
        col_names = [column.name for column in node_tags.c]
        self.assertIn('tag', col_names)
        self.assertIsInstance(node_tags.c.tag.type,
                              sqlalchemy.types.String)
        nodes = db_utils.get_table(engine, 'nodes')
        data = {'id': '123', 'name': 'node1'}
        nodes.insert().execute(data)
        data = {'node_id': '123', 'tag': 'tag1'}
        node_tags.insert().execute(data)
        tag = node_tags.select(node_tags.c.node_id == '123').execute().first()
        self.assertEqual('tag1', tag['tag'])

    def _check_5ea1b0d310e(self, engine, data):
        portgroup = db_utils.get_table(engine, 'portgroups')
        col_names = [column.name for column in portgroup.c]
        expected_names = ['created_at', 'updated_at', 'id', 'uuid', 'name',
                          'node_id', 'address', 'extra']
        self.assertEqual(sorted(expected_names), sorted(col_names))

        self.assertIsInstance(portgroup.c.created_at.type,
                              sqlalchemy.types.DateTime)
        self.assertIsInstance(portgroup.c.updated_at.type,
                              sqlalchemy.types.DateTime)
        self.assertIsInstance(portgroup.c.id.type,
                              sqlalchemy.types.Integer)
        self.assertIsInstance(portgroup.c.uuid.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(portgroup.c.name.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(portgroup.c.node_id.type,
                              sqlalchemy.types.Integer)
        self.assertIsInstance(portgroup.c.address.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(portgroup.c.extra.type,
                              sqlalchemy.types.TEXT)

        ports = db_utils.get_table(engine, 'ports')
        col_names = [column.name for column in ports.c]
        self.assertIn('pxe_enabled', col_names)
        self.assertIn('portgroup_id', col_names)
        self.assertIn('local_link_connection', col_names)
        self.assertIsInstance(ports.c.portgroup_id.type,
                              sqlalchemy.types.Integer)
        # in some backends bool type is integer
        self.assertIsInstance(ports.c.pxe_enabled.type,
                              (sqlalchemy.types.Boolean,
                               sqlalchemy.types.Integer))

    def _pre_upgrade_f6fdb920c182(self, engine):
        # add some ports.
        ports = db_utils.get_table(engine, 'ports')
        data = [{'uuid': uuidutils.generate_uuid(), 'pxe_enabled': None},
                {'uuid': uuidutils.generate_uuid(), 'pxe_enabled': None}]
        ports.insert().values(data).execute()
        return data

    def _check_f6fdb920c182(self, engine, data):
        ports = db_utils.get_table(engine, 'ports')
        result = engine.execute(ports.select())

        def _was_inserted(uuid):
            for row in data:
                if row['uuid'] == uuid:
                    return True

        for row in result:
            if _was_inserted(row['uuid']):
                self.assertTrue(row['pxe_enabled'])

    def _check_e294876e8028(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]
        self.assertIn('network_interface', col_names)
        self.assertIsInstance(nodes.c.network_interface.type,
                              sqlalchemy.types.String)

    def _check_10b163d4481e(self, engine, data):
        ports = db_utils.get_table(engine, 'ports')
        portgroups = db_utils.get_table(engine, 'portgroups')
        port_col_names = [column.name for column in ports.c]
        portgroup_col_names = [column.name for column in portgroups.c]
        self.assertIn('internal_info', port_col_names)
        self.assertIn('internal_info', portgroup_col_names)
        self.assertIsInstance(ports.c.internal_info.type,
                              sqlalchemy.types.TEXT)
        self.assertIsInstance(portgroups.c.internal_info.type,
                              sqlalchemy.types.TEXT)

    def _check_dd34e1f1303b(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]
        self.assertIn('resource_class', col_names)
        self.assertIsInstance(nodes.c.resource_class.type,
                              sqlalchemy.types.String)

    def _pre_upgrade_c14cef6dfedf(self, engine):
        # add some nodes.
        nodes = db_utils.get_table(engine, 'nodes')
        data = [{'uuid': uuidutils.generate_uuid(),
                 'network_interface': None},
                {'uuid': uuidutils.generate_uuid(),
                 'network_interface': None},
                {'uuid': uuidutils.generate_uuid(),
                 'network_interface': 'neutron'}]
        nodes.insert().values(data).execute()
        return data

    def _check_c14cef6dfedf(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        result = engine.execute(nodes.select())
        counts = collections.defaultdict(int)

        def _was_inserted(uuid):
            for row in data:
                if row['uuid'] == uuid:
                    return True

        for row in result:
            if _was_inserted(row['uuid']):
                counts[row['network_interface']] += 1

        # using default config values, we should have 2 flat and one neutron
        self.assertEqual(2, counts['flat'])
        self.assertEqual(1, counts['neutron'])
        self.assertEqual(0, counts[None])

    def _check_60cf717201bc(self, engine, data):
        portgroups = db_utils.get_table(engine, 'portgroups')
        col_names = [column.name for column in portgroups.c]
        self.assertIn('standalone_ports_supported', col_names)
        self.assertIsInstance(portgroups.c.standalone_ports_supported.type,
                              (sqlalchemy.types.Boolean,
                               sqlalchemy.types.Integer))

    def _check_bcdd431ba0bf(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]
        added_ifaces = ['boot', 'console', 'deploy', 'inspect',
                        'management', 'power', 'raid', 'vendor']
        for iface in added_ifaces:
            name = '%s_interface' % iface
            self.assertIn(name, col_names)
            self.assertIsInstance(getattr(nodes.c, name).type,
                                  sqlalchemy.types.String)

    def _check_daa1ba02d98(self, engine, data):
        connectors = db_utils.get_table(engine, 'volume_connectors')
        col_names = [column.name for column in connectors.c]
        expected_names = ['created_at', 'updated_at', 'id', 'uuid', 'node_id',
                          'type', 'connector_id', 'extra']
        self.assertEqual(sorted(expected_names), sorted(col_names))

        self.assertIsInstance(connectors.c.created_at.type,
                              sqlalchemy.types.DateTime)
        self.assertIsInstance(connectors.c.updated_at.type,
                              sqlalchemy.types.DateTime)
        self.assertIsInstance(connectors.c.id.type,
                              sqlalchemy.types.Integer)
        self.assertIsInstance(connectors.c.uuid.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(connectors.c.node_id.type,
                              sqlalchemy.types.Integer)
        self.assertIsInstance(connectors.c.type.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(connectors.c.connector_id.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(connectors.c.extra.type,
                              sqlalchemy.types.TEXT)

    def _check_1a59178ebdf6(self, engine, data):
        targets = db_utils.get_table(engine, 'volume_targets')
        col_names = [column.name for column in targets.c]
        expected_names = ['created_at', 'updated_at', 'id', 'uuid', 'node_id',
                          'boot_index', 'extra', 'properties', 'volume_type',
                          'volume_id']
        self.assertEqual(sorted(expected_names), sorted(col_names))

        self.assertIsInstance(targets.c.created_at.type,
                              sqlalchemy.types.DateTime)
        self.assertIsInstance(targets.c.updated_at.type,
                              sqlalchemy.types.DateTime)
        self.assertIsInstance(targets.c.id.type,
                              sqlalchemy.types.Integer)
        self.assertIsInstance(targets.c.uuid.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(targets.c.node_id.type,
                              sqlalchemy.types.Integer)
        self.assertIsInstance(targets.c.boot_index.type,
                              sqlalchemy.types.Integer)
        self.assertIsInstance(targets.c.extra.type,
                              sqlalchemy.types.TEXT)
        self.assertIsInstance(targets.c.properties.type,
                              sqlalchemy.types.TEXT)
        self.assertIsInstance(targets.c.volume_type.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(targets.c.volume_id.type,
                              sqlalchemy.types.String)

    def _pre_upgrade_493d8f27f235(self, engine):
        portgroups = db_utils.get_table(engine, 'portgroups')
        data = [{'uuid': uuidutils.generate_uuid()},
                {'uuid': uuidutils.generate_uuid()}]
        portgroups.insert().values(data).execute()
        return data

    def _check_493d8f27f235(self, engine, data):
        portgroups = db_utils.get_table(engine, 'portgroups')
        col_names = [column.name for column in portgroups.c]
        self.assertIn('properties', col_names)
        self.assertIsInstance(portgroups.c.properties.type,
                              sqlalchemy.types.TEXT)
        self.assertIn('mode', col_names)
        self.assertIsInstance(portgroups.c.mode.type,
                              sqlalchemy.types.String)

        result = engine.execute(portgroups.select())
        for row in result:
            self.assertEqual(CONF.default_portgroup_mode, row['mode'])

    def _check_1d6951876d68(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]
        self.assertIn('storage_interface', col_names)
        self.assertIsInstance(nodes.c.storage_interface.type,
                              sqlalchemy.types.String)

    def _check_2353895ecfae(self, engine, data):
        ifaces = db_utils.get_table(engine, 'conductor_hardware_interfaces')
        col_names = [column.name for column in ifaces.c]
        expected_names = ['created_at', 'updated_at', 'id', 'conductor_id',
                          'hardware_type', 'interface_type', 'interface_name']
        self.assertEqual(sorted(expected_names), sorted(col_names))

        self.assertIsInstance(ifaces.c.created_at.type,
                              sqlalchemy.types.DateTime)
        self.assertIsInstance(ifaces.c.updated_at.type,
                              sqlalchemy.types.DateTime)
        self.assertIsInstance(ifaces.c.id.type,
                              sqlalchemy.types.Integer)
        self.assertIsInstance(ifaces.c.conductor_id.type,
                              sqlalchemy.types.Integer)
        self.assertIsInstance(ifaces.c.hardware_type.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(ifaces.c.interface_type.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(ifaces.c.interface_name.type,
                              sqlalchemy.types.String)

    def _check_dbefd6bdaa2c(self, engine, data):
        ifaces = db_utils.get_table(engine, 'conductor_hardware_interfaces')
        col_names = [column.name for column in ifaces.c]
        self.assertIn('default', col_names)
        self.assertIsInstance(ifaces.c.default.type,
                              (sqlalchemy.types.Boolean,
                               sqlalchemy.types.Integer))

    def _check_3d86a077a3f2(self, engine, data):
        ports = db_utils.get_table(engine, 'ports')
        col_names = [column.name for column in ports.c]
        self.assertIn('physical_network', col_names)
        self.assertIsInstance(ports.c.physical_network.type,
                              sqlalchemy.types.String)

    def _check_868cb606a74a(self, engine, data):
        for table in ['chassis', 'conductors', 'node_tags', 'nodes',
                      'portgroups', 'ports', 'volume_connectors',
                      'volume_targets', 'conductor_hardware_interfaces']:
            table = db_utils.get_table(engine, table)
            col_names = [column.name for column in table.c]
            self.assertIn('version', col_names)
            self.assertIsInstance(table.c.version.type,
                                  sqlalchemy.types.String)

    def _check_405cfe08f18d(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]
        self.assertIn('rescue_interface', col_names)
        self.assertIsInstance(nodes.c.rescue_interface.type,
                              sqlalchemy.types.String)

    def _pre_upgrade_b4130a7fc904(self, engine):
        # Create a node to which traits can be added.
        data = {'uuid': uuidutils.generate_uuid()}
        nodes = db_utils.get_table(engine, 'nodes')
        nodes.insert().execute(data)
        node = nodes.select(nodes.c.uuid == data['uuid']).execute().first()
        data['id'] = node['id']
        return data

    def _check_b4130a7fc904(self, engine, data):
        node_traits = db_utils.get_table(engine, 'node_traits')
        col_names = [column.name for column in node_traits.c]
        self.assertIn('node_id', col_names)
        self.assertIsInstance(node_traits.c.node_id.type,
                              sqlalchemy.types.Integer)
        self.assertIn('trait', col_names)
        self.assertIsInstance(node_traits.c.trait.type,
                              sqlalchemy.types.String)

        trait = {'node_id': data['id'], 'trait': 'trait1'}
        node_traits.insert().execute(trait)
        trait = node_traits.select(
            node_traits.c.node_id == data['id']).execute().first()
        self.assertEqual('trait1', trait['trait'])

    def _pre_upgrade_82c315d60161(self, engine):
        # Create a node to which bios setting can be added.
        data = {'uuid': uuidutils.generate_uuid()}
        nodes = db_utils.get_table(engine, 'nodes')
        nodes.insert().execute(data)
        node = nodes.select(nodes.c.uuid == data['uuid']).execute().first()
        data['id'] = node['id']
        return data

    def _check_82c315d60161(self, engine, data):
        bios_settings = db_utils.get_table(engine, 'bios_settings')
        col_names = [column.name for column in bios_settings.c]
        expected_names = ['node_id', 'created_at', 'updated_at',
                          'name', 'value', 'version']
        self.assertEqual(sorted(expected_names), sorted(col_names))
        self.assertIsInstance(bios_settings.c.node_id.type,
                              sqlalchemy.types.Integer)
        self.assertIsInstance(bios_settings.c.created_at.type,
                              sqlalchemy.types.DateTime)
        self.assertIsInstance(bios_settings.c.updated_at.type,
                              sqlalchemy.types.DateTime)
        self.assertIsInstance(bios_settings.c.name.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(bios_settings.c.version.type,
                              sqlalchemy.types.String)
        self.assertIsInstance(bios_settings.c.value.type,
                              sqlalchemy.types.Text)

        setting = {'node_id': data['id'],
                   'name': 'virtualization',
                   'value': 'on'}
        bios_settings.insert().execute(setting)
        setting = bios_settings.select(
            sqlalchemy.sql.and_(
                bios_settings.c.node_id == data['id'],
                bios_settings.c.name == setting['name'])).execute().first()
        self.assertEqual('on', setting['value'])

    def _check_2d13bc3d6bba(self, engine, data):
        nodes = db_utils.get_table(engine, 'nodes')
        col_names = [column.name for column in nodes.c]
        self.assertIn('bios_interface', col_names)
        self.assertIsInstance(nodes.c.bios_interface.type,
                              sqlalchemy.types.String)

    def test_upgrade_and_version(self):
        with patch_with_engine(self.engine):
            self.migration_api.upgrade('head')
            self.assertIsNotNone(self.migration_api.version())

    def test_create_schema_and_version(self):
        with patch_with_engine(self.engine):
            self.migration_api.create_schema()
            self.assertIsNotNone(self.migration_api.version())

    def test_upgrade_and_create_schema(self):
        with patch_with_engine(self.engine):
            self.migration_api.upgrade('31baaf680d2b')
            self.assertRaises(db_exc.DBMigrationError,
                              self.migration_api.create_schema)

    def test_upgrade_twice(self):
        with patch_with_engine(self.engine):
            self.migration_api.upgrade('31baaf680d2b')
            v1 = self.migration_api.version()
            self.migration_api.upgrade('head')
            v2 = self.migration_api.version()
            self.assertNotEqual(v1, v2)


class TestMigrationsMySQL(MigrationCheckersMixin,
                          WalkVersionsMixin,
                          test_fixtures.OpportunisticDBTestMixin,
                          test_base.BaseTestCase):
    FIXTURE = test_fixtures.MySQLOpportunisticFixture

    def _pre_upgrade_e918ff30eb42(self, engine):

        nodes = db_utils.get_table(engine, 'nodes')

        # this should always fail pre-upgrade
        mediumtext = 'a' * (pow(2, 16) + 1)
        uuid = uuidutils.generate_uuid()
        expected_to_fail_data = {'uuid': uuid, 'instance_info': mediumtext}
        self.assertRaises(db_exc.DBError,
                          nodes.insert().execute, expected_to_fail_data)

        # this should always work pre-upgrade
        text = 'a' * (pow(2, 16) - 1)
        uuid = uuidutils.generate_uuid()
        valid_pre_upgrade_data = {'uuid': uuid, 'instance_info': text}
        nodes.insert().execute(valid_pre_upgrade_data)

        return valid_pre_upgrade_data

    def _check_e918ff30eb42(self, engine, data):

        nodes = db_utils.get_table(engine, 'nodes')

        # check that the data for the successful pre-upgrade
        # entry didn't change
        node = nodes.select(nodes.c.uuid == data['uuid']).execute().first()
        self.assertIsNotNone(node)
        self.assertEqual(data['instance_info'], node['instance_info'])

        # now this should pass post-upgrade
        test = 'b' * (pow(2, 16) + 1)
        uuid = uuidutils.generate_uuid()
        data = {'uuid': uuid, 'instance_info': test}
        nodes.insert().execute(data)

        node = nodes.select(nodes.c.uuid == uuid).execute().first()
        self.assertEqual(test, node['instance_info'])


class TestMigrationsPostgreSQL(MigrationCheckersMixin,
                               WalkVersionsMixin,
                               test_fixtures.OpportunisticDBTestMixin,
                               test_base.BaseTestCase):
    FIXTURE = test_fixtures.PostgresqlOpportunisticFixture


class ModelsMigrationSyncMixin(object):

    def setUp(self):
        super(ModelsMigrationSyncMixin, self).setUp()
        self.engine = enginefacade.writer.get_engine()
        self.useFixture(fixtures.Timeout(MIGRATIONS_TIMEOUT,
                                         gentle=True))

    def get_metadata(self):
        return models.Base.metadata

    def get_engine(self):
        return self.engine

    def db_sync(self, engine):
        with patch_with_engine(engine):
            migration.upgrade('head')


class ModelsMigrationsSyncMysql(ModelsMigrationSyncMixin,
                                test_migrations.ModelsMigrationsSync,
                                test_fixtures.OpportunisticDBTestMixin,
                                test_base.BaseTestCase):
    FIXTURE = test_fixtures.MySQLOpportunisticFixture


class ModelsMigrationsSyncPostgres(ModelsMigrationSyncMixin,
                                   test_migrations.ModelsMigrationsSync,
                                   test_fixtures.OpportunisticDBTestMixin,
                                   test_base.BaseTestCase):
    FIXTURE = test_fixtures.PostgresqlOpportunisticFixture