This file is indexed.

/usr/share/pyshared/glance/tests/functional/test_bin_glance.py is in python-glance 2012.1.3+stable~20120821-120fcf-0ubuntu1.5.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2011 OpenStack, LLC
# 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.

"""Functional test case that utilizes the bin/glance CLI tool"""

import datetime
import httplib2
import json
import os
import tempfile

from glance.common import utils
from glance.tests import functional
from glance.tests.utils import execute, requires, minimal_add_command
from glance.tests.functional.store_utils import (setup_http,
                                                 teardown_http,
                                                 get_http_uri)


class TestBinGlanceAuth(functional.FunctionalTest):
    """Functional tests for bin/glance with some amount of auth"""

    def assertIn(self, key, bag):
        msg = 'Expected to find substring "%s" in "%s"' % (key, bag)
        self.assertTrue(key in bag, msg)

    def assertNotIn(self, key, bag):
        msg = 'Expected not to find substring "%s" in "%s"' % (key, bag)
        self.assertFalse(key in bag, msg)

    def test_index_with_https_auth(self):
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        api_port = self.api_port
        cmd = ("bin/glance --port=%d -N https://this.url.doesnt.matter/ "
               "-A aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa index") % api_port
        exitcode, out, err = execute(cmd, raise_error=False)

        #NOTE(markwash): we should expect the command to fail because the
        # testing glance api server is not configured to authenticate, and the
        # token we provide is invalid. However, it should fail due to
        # NotAuthenticated, rather than because of an SSL error.

        self.assertNotEqual(0, exitcode)
        self.assertNotIn('SSL23_GET_SERVER_HELLO', out)
        self.assertIn('NotAuthenticated: You are not authenticated.', out)


class TestBinGlance(functional.FunctionalTest):
    """Functional tests for the bin/glance CLI tool"""

    def setUp(self):
        super(TestBinGlance, self).setUp()

        # NOTE(sirp): This is needed in case we are running the tests under an
        # environment in which OS_AUTH_STRATEGY=keystone. The test server we
        # spin up won't have keystone support, so we need to switch to the
        # NoAuth strategy.
        os.environ['OS_AUTH_STRATEGY'] = 'noauth'

    def _assertStartsWith(self, str, prefix):
        msg = 'expected "%s" to start with "%s"' % (str, prefix)
        self.assertTrue(str.startswith(prefix), msg)

    def test_add_with_location_and_id(self):
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        api_port = self.api_port
        registry_port = self.registry_port

        # 0. Verify no public images
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        image_id = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"

        # 1a. Add public image
        cmd = minimal_add_command(api_port,
                                  'MyImage',
                                  'id=%s' % image_id,
                                  'location=http://example.com')
        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        expected = 'Added new image with ID: %s' % image_id
        self.assertTrue(expected in out)

        # 1b. Add public image with non-uuid id
        cmd = minimal_add_command(api_port,
                                  'MyImage',
                                  'id=12345',
                                  'location=http://example.com')
        exitcode, out, err = execute(cmd, expected_exitcode=1)

        self.assertEqual(1, exitcode)
        self.assertTrue('Invalid image id format' in out)

        # 2. Verify image added as public image
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        lines = out.split("\n")[2:-1]
        self.assertEqual(1, len(lines))

        line = lines[0]

        image_id, name, disk_format, container_format, size = \
            [c.strip() for c in line.split()]
        self.assertEqual('MyImage', name)

        self.assertEqual('0', size, "Expected image to be 0 bytes in size, "
                                    "but got %s. " % size)

    def test_add_with_location(self):
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        api_port = self.api_port
        registry_port = self.registry_port

        # 0. Verify no public images
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        # 1. Add public image
        cmd = minimal_add_command(api_port,
                                  'MyImage',
                                  'location=http://example.com')
        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertTrue(out.strip().startswith('Added new image with ID:'))

        # 2. Verify image added as public image
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        lines = out.split("\n")[2:-1]
        self.assertEqual(1, len(lines))

        line = lines[0]

        image_id, name, disk_format, container_format, size = \
            [c.strip() for c in line.split()]
        self.assertEqual('MyImage', name)

        self.assertEqual('0', size, "Expected image to be 0 bytes in size, "
                                    "but got %s. " % size)

    def _verify_owner(self, owner, image_id):
        cmd = "bin/glance --port=%d show %s" % (self.api_port, image_id)
        exitcode, out, err = execute(cmd)
        self.assertEqual(0, exitcode)

        # verify expected owner as first class attribute
        self.assertTrue(('Owner: %s' % owner) in out)
        # ensure owner does not appear as a custom property
        self.assertFalse("Property 'owner':" in out)

    def test_add_with_owner_admin(self):
        """Test setting ownership of new image by admin user"""
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        # ownership set by admin user (defaults as such due to no-auth)
        cmd = minimal_add_command(self.api_port,
                                  'MyImage',
                                  '--silent-upload owner=42')
        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertTrue(out.strip().startswith('Added new image with ID:'))

        image_id = out.strip().replace('Added new image with ID: ', '')

        self._verify_owner('42', image_id)

    def test_add_with_owner_non_admin(self):
        """Test setting ownership of new image by non-admin user"""
        self.cleanup()
        self.api_server.deployment_flavor = 'fakeauth'
        self.registry_server.deployment_flavor = 'fakeauth'
        self.start_servers(**self.__dict__.copy())

        # ownership set by non-admin user (setup as such by fakeauth pipeline)
        headers = {'X-Image-Meta-Name': 'MyImage',
                   'X-Image-Meta-disk_format': 'raw',
                   'X-Image-Meta-container_format': 'ovf',
                   'X-Image-Meta-Is-Public': 'True',
                   'X-Image-Meta-Owner': '42',
                   'X-Auth-Token': 'Confirmed:pattieblack:froggy:demo',
        }

        path = "http://%s:%d/v1/images" % ("0.0.0.0", self.api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'POST', headers=headers)
        self.assertEqual(response.status, 201)
        data = json.loads(content)
        image_id = data['image']['id']

        self._verify_owner('froggy', image_id)

    def test_add_no_name(self):
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        api_port = self.api_port
        registry_port = self.registry_port

        # 0. Verify no public images
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        # 1. Add public image
        # Can't use minimal_add_command since that uses
        # name...
        cmd = ("bin/glance --port=%d add is_public=True"
               " disk_format=raw container_format=ovf"
               " %s" % (api_port, 'location=http://example.com'))
        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertTrue(out.strip().startswith('Added new image with ID:'))

        # 2. Verify image added as public image
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        lines = out.split("\n")[2:-1]
        self.assertEqual(1, len(lines))

        line = lines[0]

        image_id, name, disk_format, container_format, size = \
            [c.strip() for c in line.split()]
        self.assertEqual('None', name)

    @requires(teardown=teardown_http)
    def test_add_copying_from(self):
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        setup_http(self)

        api_port = self.api_port
        registry_port = self.registry_port

        # 0. Verify no public images
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        # 1. Add public image
        suffix = 'copy_from=%s' % get_http_uri(self, 'foobar')
        cmd = minimal_add_command(api_port, 'MyImage', suffix)
        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertTrue(out.strip().startswith('Added new image with ID:'))

        # 2. Verify image added as public image
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        lines = out.split("\n")[2:-1]
        self.assertEqual(1, len(lines))

        line = lines[0]

        image_id, name, disk_format, container_format, size = \
            [c.strip() for c in line.split()]
        self.assertEqual('MyImage', name)

        self.assertEqual('5120', size, "Expected image to be 5120 bytes "
                                       " in size, but got %s. " % size)

    def _do_test_update_external_source(self, source):
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        setup_http(self)

        api_port = self.api_port
        registry_port = self.registry_port

        # 1. Add public image with no image content
        headers = {'X-Image-Meta-Name': 'MyImage',
                   'X-Image-Meta-disk_format': 'raw',
                   'X-Image-Meta-container_format': 'ovf',
                   'X-Image-Meta-Is-Public': 'True'}
        path = "http://%s:%d/v1/images" % ("0.0.0.0", api_port)
        http = httplib2.Http()
        response, content = http.request(path, 'POST', headers=headers)
        self.assertEqual(response.status, 201)
        data = json.loads(content)
        self.assertEqual(data['image']['name'], 'MyImage')
        image_id = data['image']['id']

        # 2. Update image with external source
        source = '%s=%s' % (source, get_http_uri(self, 'foobar'))
        cmd = "bin/glance update %s %s -p %d" % (image_id, source, api_port)
        exitcode, out, err = execute(cmd, raise_error=False)

        self.assertEqual(0, exitcode)
        self.assertTrue(out.strip().endswith('Updated image %s' % image_id))

        # 3. Verify image is now active and of the correct size
        cmd = "bin/glance --port=%d show %s" % (api_port, image_id)

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)

        expected_lines = [
            'URI: http://0.0.0.0:%s/v1/images/%s' % (api_port, image_id),
            'Id: %s' % image_id,
            'Public: Yes',
            'Name: MyImage',
            'Status: active',
            'Size: 5120',
            'Disk format: raw',
            'Container format: ovf',
            'Minimum Ram Required (MB): 0',
            'Minimum Disk Required (GB): 0',
        ]
        lines = out.split("\n")
        self.assertTrue(set(lines) >= set(expected_lines))

    @requires(teardown=teardown_http)
    def test_update_copying_from(self):
        """
        Tests creating an queued image then subsequently updating
        with a copy-from source
        """
        self._do_test_update_external_source('copy_from')

    @requires(teardown=teardown_http)
    def test_update_location(self):
        """
        Tests creating an queued image then subsequently updating
        with a location source
        """
        self._do_test_update_external_source('location')

    def test_add_with_location_and_stdin(self):
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        api_port = self.api_port
        registry_port = self.registry_port

        # 0. Verify no public images
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        # 1. Add public image
        with tempfile.NamedTemporaryFile() as image_file:
            image_file.write("XXX")
            image_file.flush()
            file_name = image_file.name
            cmd = minimal_add_command(api_port,
                                     'MyImage',
                                     'location=http://example.com < %s' %
                                     file_name)
            exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertTrue(out.strip().startswith('Added new image with ID:'))

        # 2. Verify image added as public image
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        lines = out.split("\n")[2:-1]
        self.assertEqual(1, len(lines))

        line = lines[0]

        image_id, name, disk_format, container_format, size = \
            [c.strip() for c in line.split()]
        self.assertEqual('MyImage', name)

        self.assertEqual('0', size, "Expected image to be 0 bytes in size, "
                                    "but got %s. " % size)

    def test_add_list_delete_list(self):
        """
        We test the following:

            0. Verify no public images in index
            1. Add a public image
            2. Check that image exists in index
            3. Delete the image
            4. Verify no longer in index
        """
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        api_port = self.api_port
        registry_port = self.registry_port

        # 0. Verify no public images
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        # 1. Add public image
        with tempfile.NamedTemporaryFile() as image_file:
            image_file.write("XXX")
            image_file.flush()
            image_file_name = image_file.name
            suffix = '--silent-upload < %s' % image_file_name
            cmd = minimal_add_command(api_port, 'MyImage', suffix)

            exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        msg = out.split("\n")

        self._assertStartsWith(msg[0], 'Added new image with ID:')

        # 2. Verify image added as public image
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        lines = out.split("\n")[2:-1]
        self.assertEqual(1, len(lines))

        line = lines[0]

        image_id, name, disk_format, container_format, size = \
            [c.strip() for c in line.split()]
        self.assertEqual('MyImage', name)

        self.assertEqual('3', size,
                         "Expected image to be 3 bytes in size, but got %s. "
                         "Make sure you're running the correct version "
                         "of webob." % size)

        # 3. Delete the image
        cmd = "bin/glance --port=%d --force delete %s" % (api_port, image_id)

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('Deleted image %s' % image_id, out.strip())

        # 4. Verify no public images
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        self.stop_servers()

    def test_add_list_update_list(self):
        """
        Test for LP Bugs #736295, #767203
        We test the following:

            0. Verify no public images in index
            1. Add a NON-public image
            2. Check that image does not appear in index
            3. Update the image to be public
            4. Check that image now appears in index
            5. Update the image's Name attribute
            6. Verify the updated name is shown
        """
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        api_port = self.api_port
        registry_port = self.registry_port

        # 0. Verify no public images
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        # 1. Add public image
        cmd = minimal_add_command(api_port,
                                  'MyImage',
                                  'location=http://example.com',
                                  public=False)

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        msg = out.split('\n')
        self.assertTrue(msg[0].startswith('Added new image with ID:'))

        image_id = out.strip().split(':')[1].strip()

        # 2. Verify image does not appear as a public image
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        # 3. Update the image to make it public
        cmd = "bin/glance --port=%d update %s is_public=True" % (
            api_port, image_id)

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('Updated image %s' % image_id, out.strip())

        # 4. Verify image 1 in list of public images
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        lines = out.split("\n")[2:-1]
        self.assertEqual(len(lines), 1)
        self.assertTrue('MyImage' in lines[0])

        # 5. Update the image's Name attribute
        updated_image_name = "Updated image name"
        cmd = "bin/glance --port=%d update %s is_public=True name=\"%s\"" \
                % (api_port, image_id, updated_image_name)

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('Updated image %s' % image_id, out.strip())

        # 6. Verify updated name shown
        cmd = "bin/glance --port=%d index" % api_port
        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertTrue(updated_image_name in out,
                        "%s not found in %s" % (updated_image_name, out))

        self.stop_servers()

    def test_killed_image_not_in_index(self):
        """
        We test conditions that produced LP Bug #768969, where an image
        in the 'killed' status is displayed in the output of glance index,
        and the status column is not displayed in the output of
        glance show <ID>.

            Start servers with Swift backend and a bad auth URL, and then:
            0. Verify no public images in index
            1. Attempt to add an image
            2. Verify the image does NOT appear in the index output
        """
        self.cleanup()

        # Start servers with a Swift backend and a bad auth URL
        options = {'default_store': 'swift',
                   'swift_store_auth_address': 'badurl'}
        self.start_servers(**options)

        api_port = self.api_port
        registry_port = self.registry_port

        # 0. Verify no public images
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        # 1. Attempt to add an image
        with tempfile.NamedTemporaryFile() as image_file:
            image_file.write("XXX")
            image_file.flush()
            image_file_name = image_file.name
            cmd = ("bin/glance --port=%d add name=Jonas is_public=True "
                   "disk_format=qcow2 container_format=bare < %s"
                   % (api_port, image_file_name))

            exitcode, out, err = execute(cmd, raise_error=False)

            self.assertNotEqual(0, exitcode)
            self.assertTrue('Failed to add image.' in out)

        # 2. Verify image does not appear as public image
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        self.stop_servers()

    @functional.runs_sql
    def test_add_location_with_checksum(self):
        """
        We test the following:

            1. Add an image with location and checksum
            2. Run SQL against DB to verify checksum was entered correctly
        """
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        api_port = self.api_port
        registry_port = self.registry_port

        # 1. Add public image
        cmd = minimal_add_command(api_port,
                                 'MyImage',
                                 'location=http://example.com checksum=1')
        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertTrue(out.strip().startswith('Added new image with ID:'))

        image_id = out.split(":")[1].strip()

        sql = 'SELECT checksum FROM images WHERE id = "%s"' % image_id
        recs = self.run_sql_cmd(sql)

        self.assertEqual('1', recs.first()[0])

        self.stop_servers()

    @functional.runs_sql
    def test_add_location_without_checksum(self):
        """
        We test the following:

            1. Add an image with location and no checksum
            2. Run SQL against DB to verify checksum is NULL
        """
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        api_port = self.api_port
        registry_port = self.registry_port

        # 1. Add public image
        cmd = minimal_add_command(api_port,
                                 'MyImage',
                                 'location=http://example.com')
        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertTrue(out.strip().startswith('Added new image with ID:'))

        image_id = out.split(":")[1].strip()

        sql = 'SELECT checksum FROM images WHERE id = "%s"' % image_id
        recs = self.run_sql_cmd(sql)

        self.assertEqual(None, recs.first()[0])

        self.stop_servers()

    @functional.runs_sql
    def test_add_clear(self):
        """
        We test the following:

            1. Add a couple images with metadata
            2. Clear the images
            3. Verify no public images found
            4. Run SQL against DB to verify no undeleted properties
        """
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        api_port = self.api_port
        registry_port = self.registry_port

        # 1. Add some images
        for i in range(1, 5):
            cmd = minimal_add_command(api_port,
                                      'MyImage',
                                      'foo=bar')
            exitcode, out, err = execute(cmd)

            self.assertEqual(0, exitcode)
            self.assertTrue(out.strip().find('Added new image with ID:') > -1)

        # 2. Clear all images
        cmd = "bin/glance --port=%d --force clear" % api_port
        exitcode, out, err = execute(cmd)
        self.assertEqual(0, exitcode)

        # 3. Verify no public images are found
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        lines = out.split("\n")
        first_line = lines[0]
        self.assertEqual('', first_line)

        # 4. Lastly we manually verify with SQL that image properties are
        # also getting marked as deleted.
        sql = "SELECT COUNT(*) FROM image_properties WHERE deleted = 0"
        recs = self.run_sql_cmd(sql)
        for rec in recs:
            self.assertEqual(0, rec[0])

        self.stop_servers()

    def test_results_filtering(self):
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        api_port = self.api_port
        registry_port = self.registry_port

        # 1. Add some images
        _add_cmd = "bin/glance --port=%d add is_public=True" % api_port
        _add_args = [
            "name=Name1 disk_format=vhd container_format=ovf foo=bar",
            "name=Name2 disk_format=ami container_format=ami foo=bar",
            "name=Name3 disk_format=vhd container_format=ovf foo=baz "
            "min_disk=7 min_ram=256",
        ]

        image_ids = []
        for i, args in enumerate(_add_args):
            cmd = "%s %s" % (_add_cmd, args)
            exitcode, out, err = execute(cmd)
            self.assertEqual(0, exitcode)
            self.assertTrue(out.strip().find('Added new image with ID:') > -1)
            image_ids.append(out.strip().split(':')[1].strip())

        _base_cmd = "bin/glance --port=%d" % api_port
        _index_cmd = "%s index -f" % (_base_cmd,)

        # 2. Check name filter
        cmd = "name=Name2"
        exitcode, out, err = execute("%s %s" % (_index_cmd, cmd))
        image_lines = out.split("\n")[2:-1]

        self.assertEqual(0, exitcode)
        self.assertEqual(1, len(image_lines))
        self.assertEqual(image_lines[0].split()[0], image_ids[1])

        # 3. Check disk_format filter
        cmd = "disk_format=vhd"
        exitcode, out, err = execute("%s %s" % (_index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(2, len(image_lines))
        self.assertEqual(image_lines[0].split()[0], image_ids[2])
        self.assertEqual(image_lines[1].split()[0], image_ids[0])

        # 4. Check container_format filter
        cmd = "container_format=ami"
        exitcode, out, err = execute("%s %s" % (_index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(1, len(image_lines))
        self.assertEqual(image_lines[0].split()[0], image_ids[1])

        # 5. Check container_format filter
        cmd = "container_format=ami"
        exitcode, out, err = execute("%s %s" % (_index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(1, len(image_lines))
        self.assertEqual(image_lines[0].split()[0], image_ids[1])

        # 6. Check status filter
        cmd = "status=killed"
        exitcode, out, err = execute("%s %s" % (_index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(0, len(image_lines))

        # 7. Check property filter
        cmd = "foo=bar"
        exitcode, out, err = execute("%s %s" % (_index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(2, len(image_lines))
        self.assertEqual(image_lines[0].split()[0], image_ids[1])
        self.assertEqual(image_lines[1].split()[0], image_ids[0])

        # 8. Check multiple filters
        cmd = "name=Name2 foo=bar"
        exitcode, out, err = execute("%s %s" % (_index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(1, len(image_lines))
        self.assertEqual(image_lines[0].split()[0], image_ids[1])

        # 9. Check past changes-since
        dt1 = datetime.datetime.utcnow() - datetime.timedelta(1)
        iso1 = utils.isotime(dt1)
        cmd = "changes-since=%s" % iso1
        exitcode, out, err = execute("%s %s" % (_index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(3, len(image_lines))
        self.assertEqual(image_lines[0].split()[0], image_ids[2])
        self.assertEqual(image_lines[1].split()[0], image_ids[1])
        self.assertEqual(image_lines[2].split()[0], image_ids[0])

        # 10. Check future changes-since
        dt2 = datetime.datetime.utcnow() + datetime.timedelta(1)
        iso2 = utils.isotime(dt2)
        cmd = "changes-since=%s" % iso2
        exitcode, out, err = execute("%s %s" % (_index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(0, len(image_lines))

        # 11. Ensure details call also respects filters
        _details_cmd = "%s details" % (_base_cmd,)
        cmd = "foo=bar"
        exitcode, out, err = execute("%s %s" % (_details_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[1:-1]
        self.assertEqual(26, len(image_lines))
        self.assertEqual(image_lines[1].split()[1], image_ids[1])
        self.assertEqual(image_lines[14].split()[1], image_ids[0])

        # 12. Check min_ram filter
        cmd = "min_ram=256"
        exitcode, out, err = execute("%s %s" % (_details_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(12, len(image_lines))
        self.assertEqual(image_lines[0].split()[1], image_ids[2])

        # 13. Check min_disk filter
        cmd = "min_disk=7"
        exitcode, out, err = execute("%s %s" % (_details_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(12, len(image_lines))
        self.assertEqual(image_lines[0].split()[1], image_ids[2])

        self.stop_servers()

    def test_results_pagination(self):
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        _base_cmd = "bin/glance --port=%d" % self.api_port
        index_cmd = "%s index -f" % _base_cmd
        details_cmd = "%s details -f" % _base_cmd

        # 1. Add some images
        _add_cmd = "bin/glance --port=%d add is_public=True" % self.api_port
        _add_args = [
            "name=Name1 disk_format=ami container_format=ami",
            "name=Name2 disk_format=vhd container_format=ovf",
            "name=Name3 disk_format=ami container_format=ami",
            "name=Name4 disk_format=ami container_format=ami",
            "name=Name5 disk_format=vhd container_format=ovf",
        ]

        image_ids = []

        for i, args in enumerate(_add_args):
            cmd = "%s %s" % (_add_cmd, args)
            exitcode, out, err = execute(cmd)
            self.assertEqual(0, exitcode)
            expected_out = 'Added new image with ID: %d' % (i + 1,)
            self.assertTrue(out.strip().find('Added new image with ID:') > -1)
            image_ids.append(out.strip().split(':')[1].strip())

        # 2. Limit less than total
        cmd = "--limit=3"
        exitcode, out, err = execute("%s %s" % (index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(5, len(image_lines))
        self.assertTrue(image_lines[0].split()[0], image_ids[0])
        self.assertTrue(image_lines[1].split()[0], image_ids[1])
        self.assertTrue(image_lines[2].split()[0], image_ids[2])
        self.assertTrue(image_lines[3].split()[0], image_ids[3])
        self.assertTrue(image_lines[4].split()[0], image_ids[4])

        # 3. With a marker
        cmd = "--marker=%s" % image_ids[3]
        exitcode, out, err = execute("%s %s" % (index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(3, len(image_lines))
        self.assertTrue(image_lines[0].split()[0], image_ids[1])
        self.assertTrue(image_lines[1].split()[0], image_ids[2])
        self.assertTrue(image_lines[2].split()[0], image_ids[3])

        # 3. With a marker and limit
        cmd = "--marker=%s --limit=1" % image_ids[2]
        exitcode, out, err = execute("%s %s" % (index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(2, len(image_lines))
        self.assertTrue(image_lines[0].split()[0], image_ids[1])
        self.assertTrue(image_lines[1].split()[0], image_ids[2])

        # 4. Pagination params with filtered results
        cmd = "--marker=%s --limit=1 container_format=ami" % image_ids[3]
        exitcode, out, err = execute("%s %s" % (index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(2, len(image_lines))
        self.assertTrue(image_lines[0].split()[0], image_ids[2])
        self.assertTrue(image_lines[1].split()[0], image_ids[1])

        # 5. Pagination params with filtered results in a details call
        cmd = "--marker=%s --limit=1 container_format=ami" % image_ids[3]
        exitcode, out, err = execute("%s %s" % (details_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[1:-1]
        self.assertEqual(24, len(image_lines))
        self.assertTrue(image_lines[1].split()[1], image_ids[2])
        self.assertTrue(image_lines[13].split()[1], image_ids[1])

        self.stop_servers()

    def test_results_sorting(self):
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        _base_cmd = "bin/glance --port=%d" % self.api_port
        index_cmd = "%s index -f" % _base_cmd
        details_cmd = "%s details -f" % _base_cmd

        # 1. Add some images
        _add_cmd = "bin/glance --port=%d add is_public=True" % self.api_port
        _add_args = [
            "name=Name1 disk_format=ami container_format=ami",
            "name=Name4 disk_format=vhd container_format=ovf",
            "name=Name3 disk_format=ami container_format=ami",
            "name=Name2 disk_format=ami container_format=ami",
            "name=Name5 disk_format=vhd container_format=ovf",
        ]

        image_ids = []
        for i, args in enumerate(_add_args):
            cmd = "%s %s" % (_add_cmd, args)
            exitcode, out, err = execute(cmd)
            self.assertEqual(0, exitcode)
            expected_out = 'Added new image with ID: %d' % (i + 1,)
            self.assertTrue(out.strip().find('Added new image with ID:') > -1)
            image_ids.append(out.strip().split(':')[1].strip())

        # 2. Sort by name asc
        cmd = "--sort_key=name --sort_dir=asc"
        exitcode, out, err = execute("%s %s" % (index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(5, len(image_lines))
        self.assertTrue(image_lines[0].split()[0], image_ids[0])
        self.assertTrue(image_lines[1].split()[0], image_ids[1])
        self.assertTrue(image_lines[2].split()[0], image_ids[2])
        self.assertTrue(image_lines[3].split()[0], image_ids[3])
        self.assertTrue(image_lines[4].split()[0], image_ids[4])

        # 3. Sort by name asc with a marker
        cmd = "--sort_key=name --sort_dir=asc --marker=%s" % image_ids[3]
        exitcode, out, err = execute("%s %s" % (index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(3, len(image_lines))
        self.assertTrue(image_lines[0].split()[0], image_ids[2])
        self.assertTrue(image_lines[1].split()[0], image_ids[1])
        self.assertTrue(image_lines[2].split()[0], image_ids[4])

        # 4. Sort by container_format desc
        cmd = "--sort_key=container_format --sort_dir=desc --limit=10"
        exitcode, out, err = execute("%s %s" % (index_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[2:-1]
        self.assertEqual(5, len(image_lines))
        self.assertTrue(image_lines[0].split()[0], image_ids[4])
        self.assertTrue(image_lines[1].split()[0], image_ids[1])
        self.assertTrue(image_lines[2].split()[0], image_ids[3])
        self.assertTrue(image_lines[3].split()[0], image_ids[2])
        self.assertTrue(image_lines[4].split()[0], image_ids[0])

        # 5. Sort by name asc with a marker (details)
        cmd = "--sort_key=name --sort_dir=asc --marker=%s" % image_ids[3]
        exitcode, out, err = execute("%s %s" % (details_cmd, cmd))

        self.assertEqual(0, exitcode)
        image_lines = out.split("\n")[1:-1]
        self.assertEqual(36, len(image_lines))
        self.assertTrue(image_lines[1].split()[1], image_ids[2])
        self.assertTrue(image_lines[13].split()[1], image_ids[1])
        self.assertTrue(image_lines[25].split()[1], image_ids[4])

        self.stop_servers()

    def test_show_image_format(self):
        self.cleanup()
        self.start_servers(**self.__dict__.copy())

        api_port = self.api_port
        registry_port = self.registry_port

        # 1. Add public image
        with tempfile.NamedTemporaryFile() as image_file:
            image_file.write("XXX")
            image_file.flush()
            image_file_name = image_file.name
            suffix = ' --silent-upload < %s' % image_file_name
            cmd = minimal_add_command(api_port, 'MyImage', suffix)

            exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        image_id = out.strip().rsplit(' ', 1)[1]

        # 2. Verify image added as public image
        cmd = "bin/glance --port=%d show %s" % (api_port, image_id)

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        lines = out.split("\n")[:-1]

        expected_lines = [
            'URI: http://0.0.0.0:%s/v1/images/%s' % (api_port, image_id),
            'Id: %s' % image_id,
            'Public: Yes',
            'Name: MyImage',
            'Status: active',
            'Size: 3',
            'Disk format: raw',
            'Container format: ovf',
            'Minimum Ram Required (MB): 0',
            'Minimum Disk Required (GB): 0',
        ]

        self.assertTrue(set(lines) >= set(expected_lines))

        # 3. Delete the image
        cmd = "bin/glance --port=%d --force delete %s" % (api_port, image_id)

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('Deleted image %s' % image_id, out.strip())

    def test_protected_image(self):
        """
        We test the following:

            0. Verify no public images in index
            1. Add a public image with a location attr
               protected and no image data
            2. Check that image exists in index
            3. Attempt to delete the image
            4. Remove protection from image
            5. Delete the image
            6. Verify no longer in index
        """
        self.cleanup()
        self.start_servers()

        api_port = self.api_port
        registry_port = self.registry_port

        # 0. Verify no public images
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        # 1. Add public image
        cmd = ("echo testdata | " +
               minimal_add_command(api_port,
                                   'MyImage',
                                   'protected=True'))

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        msg = out.split("\n")
        self.assertTrue(msg[3].startswith('Added new image with ID:'))

        # 2. Verify image added as public image
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        lines = out.split("\n")[2:-1]
        self.assertEqual(1, len(lines))

        line = lines[0]

        image_id, name, disk_format, container_format, size = \
            [c.strip() for c in line.split()]
        self.assertEqual('MyImage', name)

        # 3. Delete the image
        cmd = "bin/glance --port=%d --force delete %s" % (api_port, image_id)

        exitcode, out, err = execute(cmd, raise_error=False)

        self.assertNotEqual(0, exitcode)
        self.assertTrue(out.startswith('You do not have permission'))

        # 4. Remove image protection
        cmd = "bin/glance --port=%d --force update %s" \
              " protected=False" % (api_port, image_id)

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertTrue(out.strip().startswith('Updated image'))

        # 5. Delete the image
        cmd = "bin/glance --port=%d --force delete %s" % (api_port, image_id)

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertTrue(out.strip().startswith('Deleted image'))

        # 6. Verify no public images
        cmd = "bin/glance --port=%d index" % api_port

        exitcode, out, err = execute(cmd)

        self.assertEqual(0, exitcode)
        self.assertEqual('', out.strip())

        self.stop_servers()