~ubuntu-branches/ubuntu/quantal/virtinst/quantal-updates

« back to all changes in this revision

Viewing changes to tests/clitest.py

  • Committer: Package Import Robot
  • Author(s): Marc Deslauriers
  • Date: 2012-07-24 08:52:01 UTC
  • mfrom: (1.6.8 sid)
  • Revision ID: package-import@ubuntu.com-20120724085201-q3h0cbabg4t46gfm
Tags: 0.600.2-1ubuntu1
* Merge from debian unstable. Remaining changes:
  - debian/patches/9003-fix-path-to-hvmloader-in-testsuite.patch: adjust
    testsuite for 0001-fix-path-to-hvmloader.patch and
    0002-Fix-path-to-pygrub.patch.
  - debian/patches/9004_ubuntu_fix_tree_support.patch: Fix tree detection
    for all ISO/HTTP source, to not longer fail with cobbler/koan.
  - debian/patches/0004-Fix-path-to-qemu-dm.patch: fix the path to the
    qemu-dm binary.
  - debian/{control,rules,pyversions}: Build using dh_python2, use
    debhelper v8 instead of cdbs; for some reason the package build an
    empty binary package when using dh_python2.
  - debian/control: added acl package to depends.
  - debian/control: added libvirt-bin to recommends
* Dropped patches:
  - debian/patches/9005_ubuntu_releases.patch: Upstream

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
15
15
# MA 02110-1301 USA.
16
16
 
 
17
import logging
17
18
import os
 
19
import shlex
 
20
import subprocess
18
21
import sys
19
 
import commands
20
 
import subprocess
21
 
 
 
22
import time
 
23
import traceback
 
24
import unittest
 
25
import StringIO
 
26
 
 
27
import virtinst.cli
 
28
 
 
29
from scriptimports import virtinstall, virtimage, virtclone, virtconvert
22
30
import utils
23
31
 
24
32
os.environ["VIRTCONV_TEST_NO_DISK_CONVERSION"] = "1"
78
86
clean_files = (new_images + exist_images +
79
87
               virtimage_exist + virtimage_new + virtconv_dirs + [ro_dir])
80
88
 
 
89
promptlist = []
 
90
 
81
91
test_files = {
82
92
    'TESTURI'           : testuri,
83
93
    'REMOTEURI'         : remoteuri,
103
113
    'TREEDIR'           : treedir,
104
114
    'MANAGEDEXIST1'     : "/default-pool/testvol1.img",
105
115
    'MANAGEDEXIST2'     : "/default-pool/testvol2.img",
 
116
    'MANAGEDEXISTUPPER' : "/default-pool/UPPER",
106
117
    'MANAGEDNEW1'       : "/default-pool/clonevol",
107
118
    'MANAGEDNEW2'       : "/default-pool/clonevol",
108
119
    'MANAGEDDISKNEW1'   : "/disk-pool/newvol1.img",
115
126
    'VMX_IMG1'          : "%s/vmx/test1.vmx" % vcdir,
116
127
}
117
128
 
118
 
debug = False
119
 
 
120
 
class PromptCheck(object):
121
 
    def __init__(self, prompt, response=None):
122
 
        self.prompt = prompt
123
 
        self.response = response
124
 
        if self.response:
125
 
            self.response = self.response % test_files
126
 
 
127
 
    def check(self, proc):
128
 
        out = proc.stdout.readline()
129
 
 
130
 
        if not out.count(self.prompt):
131
 
            out += "\nContent didn't contain prompt '%s'" % (self.prompt)
132
 
            return False, out
133
 
 
134
 
        if self.response:
135
 
            proc.stdin.write(self.response + "\n")
136
 
 
137
 
        return True, out
138
 
 
139
 
class PromptTest(object):
140
 
    def __init__(self, cmd):
141
 
        cmd = cmd % test_files
142
 
        app, opts = cmd.split(" ", 1)
143
 
        self.cmd = [os.path.abspath(app)] + opts.split(" ")
144
 
        self.cmdstr = cmd
145
 
        self.debug = False
146
 
 
147
 
        self.prompt_list = []
148
 
 
149
 
    def add(self, *args, **kwargs):
150
 
        self.prompt_list.append(PromptCheck(*args, **kwargs))
151
 
 
152
 
    def run(self):
153
 
        proc = subprocess.Popen(self.cmd,
154
 
                stdin=subprocess.PIPE,
155
 
                stdout=subprocess.PIPE,
156
 
                stderr=subprocess.STDOUT)
157
 
 
158
 
        out = "Running %s\n" % self.cmdstr
159
 
 
160
 
        for p in self.prompt_list:
161
 
            ret, content = p.check(proc)
162
 
            out += content
163
 
            if not ret:
164
 
                # Since we didn't match output, process might be hung
165
 
                proc.kill()
166
 
                break
167
 
 
168
 
        return proc.wait(), out
169
129
 
170
130
"""
171
131
CLI test matrix
172
132
 
 
133
Any global args for every invocation should be added to default_args
 
134
function, so that individual tests can easily overwrite them.
 
135
 
173
136
Format:
174
137
 
175
138
"appname" {
176
 
  "globalargs" : Arguments to be passed to every app invocation
177
 
 
178
139
  "categoryfoo" : { Some descriptive test catagory name (e.g. storage)
179
140
 
180
141
    "args" : Args to be applied to all invocations in category
193
154
}
194
155
  "
195
156
"""
 
157
 
 
158
 
 
159
def default_args(app, cli, testtype):
 
160
    args = ""
 
161
    iscompare = testtype in ["compare"]
 
162
 
 
163
    if not iscompare:
 
164
        args = "--debug"
 
165
 
 
166
    if app in ["virt-install", "virt-clone", "virt-image"] and not iscompare:
 
167
        if "--connect " not in cli:
 
168
            args += " --connect %(TESTURI)s"
 
169
 
 
170
    if app in ["virt-install"]:
 
171
        if "--name " not in cli:
 
172
            args += " --name foobar"
 
173
        if "--ram " not in cli:
 
174
            args += " --ram 64"
 
175
 
 
176
    if testtype in ["compare"]:
 
177
        if app == "virt-install":
 
178
            if (not cli.count("--print-xml") and
 
179
                not cli.count("--print-step") and
 
180
                not cli.count("--quiet")):
 
181
                args += " --print-step all"
 
182
 
 
183
        elif app == "virt-image":
 
184
            if not cli.count("--print"):
 
185
                args += " --print"
 
186
 
 
187
        elif app == "virt-clone":
 
188
            if not cli.count("--print-xml"):
 
189
                args += " --print-xml"
 
190
 
 
191
        if app != "virt-convert" and not "--connect " in cli:
 
192
            args += " --connect %s" % fakeuri
 
193
 
 
194
    return args
 
195
 
196
196
args_dict = {
197
197
 
198
198
 
199
199
  "virt-install" : {
200
 
    "globalargs" : " --connect %(TESTURI)s -d --name foobar --ram 64",
201
 
 
202
200
    "storage" : {
203
201
      "args": "--pxe --nographics --noautoconsole --hvm",
204
202
 
570
568
        "--hvm --pxe --filesystem template_name,/,type=template",
571
569
        # no networks
572
570
        "--hvm --nodisks --nonetworks --cdrom %(EXISTIMG1)s",
 
571
        # --memballoon use virtio
 
572
        "--hvm --nodisks --pxe --memballoon virtio",
 
573
        # --memballoon disabled
 
574
        "--hvm --nodisks --pxe --memballoon none",
573
575
      ],
574
576
 
575
577
      "invalid": [
589
591
        "--paravirt --import --disk path=virt-install --print-step 2",
590
592
        # 2 stage install with --print-xml
591
593
        "--hvm --nodisks --pxe --print-xml",
 
594
        # Busted --memballoon
 
595
        "--hvm --nodisks --pxe --memballoon foobar",
592
596
      ],
593
597
 
594
598
      "compare": [
604
608
         "--controller usb,model=ich9-uhci1,address=0:0:4.0,index=0,master=0 "
605
609
         "--controller usb,model=ich9-uhci2,address=0:0:4.1,index=0,master=2 "
606
610
         "--controller usb,model=ich9-uhci3,address=0:0:4.2,index=0,master=4 "
607
 
         "--disk %(EXISTIMG1)s,cache=writeback,io=threads,perms=sh,serial=WD-WMAP9A966149 "
 
611
         "--disk %(MANAGEDEXISTUPPER)s,cache=writeback,io=threads,perms=sh,serial=WD-WMAP9A966149 "
608
612
         "--disk %(NEWIMG1)s,sparse=false,size=.001,perms=ro,error_policy=enospace "
609
613
         "--disk device=cdrom,bus=sata "
610
614
         "--serial tcp,host=:2222,mode=bind,protocol=telnet "
614
618
         "--channel spicevmc "
615
619
         "--smartcard passthrough,type=spicevmc "
616
620
         "--security type=static,label='system_u:object_r:svirt_image_t:s0:c100,c200',relabel=yes "
617
 
         """ --numatune \\"1-3,5\\",mode=preferred """,
 
621
         """ --numatune \\"1-3,5\\",mode=preferred """
 
622
         "--boot loader=/foo/bar ",
618
623
         "many-devices"),
619
624
      ],
620
625
 
625
630
 
626
631
      "valid": [
627
632
        # Just a macaddr
628
 
        "--mac 11:22:33:44:55:AF",
 
633
        "--mac 22:22:33:44:55:AF",
629
634
        # user networking
630
635
        "--network=user",
631
636
        # Old bridge option
632
637
        "--bridge mybr0",
633
638
        # Old bridge w/ mac
634
 
        "--bridge mybr0 --mac 11:22:33:44:55:AF",
 
639
        "--bridge mybr0 --mac 22:22:33:44:55:AF",
635
640
        # --network bridge:
636
641
        "--network bridge:mybr0,model=e1000",
637
642
        # VirtualNetwork with a random macaddr
639
644
        # VirtualNetwork with a random macaddr
640
645
        "--network network:default --mac 00:11:22:33:44:55",
641
646
        # Using '=' as the net type delimiter
642
 
        "--network network=default,mac=11:00:11:00:11:00",
 
647
        "--network network=default,mac=22:00:11:00:11:00",
643
648
        # with NIC model
644
649
        "--network=user,model=e1000",
645
650
        # several networks
646
 
        "--network=network:default,model=e1000 --network=user,model=virtio,mac=11:22:33:44:55:AF",
 
651
        "--network=network:default,model=e1000 --network=user,model=virtio,mac=22:22:33:44:55:AF",
647
652
      ],
648
653
      "invalid": [
649
654
        # Nonexistent network
653
658
        # Mixing bridge and network
654
659
        "--network user --bridge foo0",
655
660
        # Colliding macaddr
656
 
        "--mac 11:22:33:12:34:AB",
 
661
        "--mac 22:22:33:12:34:AB",
657
662
      ],
658
663
 
659
664
     }, # category "network"
851
856
 
852
857
 
853
858
  "virt-clone": {
854
 
    "globalargs" : " --connect %(TESTURI)s -d",
855
 
 
856
859
    "general" : {
857
860
      "args": "-n clonetest",
858
861
 
931
934
      ],
932
935
 
933
936
      "compare" : [
934
 
        ("-o test-for-clone --auto-clone --clone-running", "clone-auto1"),
 
937
        ("--connect %(KVMURI)s -o test-for-clone --auto-clone --clone-running", "clone-auto1"),
935
938
        ("-o test-clone-simple --name newvm --auto-clone --clone-running",
936
939
         "clone-auto2"),
937
940
      ],
959
962
 
960
963
 
961
964
  'virt-image': {
962
 
    "globalargs" : " --connect %(TESTURI)s --debug",
963
 
 
964
965
    "general" : {
965
966
      "args" : "--name test-image %(IMAGE_XML)s",
966
967
 
1054
1055
 
1055
1056
 
1056
1057
  "virt-convert" : {
1057
 
    "globalargs" : "--debug",
1058
 
 
1059
1058
    "misc" : {
1060
1059
     "args": "",
1061
1060
 
1094
1093
  }, # app 'virt-convert'
1095
1094
}
1096
1095
 
1097
 
promptlist = []
 
1096
_conns = {}
 
1097
def open_conn(uri):
 
1098
    #if uri not in _conns:
 
1099
    #    _conns[uri] = virtinst.cli.getConnection(uri)
 
1100
    #return _conns[uri]
 
1101
    return virtinst.cli.getConnection(uri)
 
1102
 
 
1103
######################
 
1104
# Test class helpers #
 
1105
######################
 
1106
 
 
1107
class Command(object):
 
1108
    """
 
1109
    Instance of a single cli command to test
 
1110
    """
 
1111
    def __init__(self, cmd):
 
1112
        self.cmdstr = cmd % test_files
 
1113
        self.check_success = True
 
1114
        self.compare_file = None
 
1115
 
 
1116
        app, opts = self.cmdstr.split(" ", 1)
 
1117
        self.argv = [os.path.abspath(app)] + shlex.split(opts)
 
1118
 
 
1119
    def _launch_command(self):
 
1120
        logging.debug(self.cmdstr)
 
1121
 
 
1122
        uri = None
 
1123
        conn = None
 
1124
        app = self.argv[0]
 
1125
 
 
1126
        for idx in reversed(range(len(self.argv))):
 
1127
            if self.argv[idx] == "--connect":
 
1128
                uri = self.argv[idx + 1]
 
1129
                break
 
1130
 
 
1131
        if uri:
 
1132
            conn = open_conn(uri)
 
1133
 
 
1134
        oldstdout = sys.stdout
 
1135
        oldstderr = sys.stderr
 
1136
        oldargv = sys.argv
 
1137
        try:
 
1138
            out = StringIO.StringIO()
 
1139
            sys.stdout = out
 
1140
            sys.stderr = out
 
1141
            sys.argv = self.argv
 
1142
 
 
1143
            try:
 
1144
                if app.count("virt-install"):
 
1145
                    ret = virtinstall.main(conn=conn)
 
1146
                elif app.count("virt-clone"):
 
1147
                    ret = virtclone.main(conn=conn)
 
1148
                elif app.count("virt-image"):
 
1149
                    ret = virtimage.main(conn=conn)
 
1150
                elif app.count("virt-convert"):
 
1151
                    ret = virtconvert.main()
 
1152
            except SystemExit, sys_e:
 
1153
                ret = sys_e.code
 
1154
 
 
1155
            if ret != 0:
 
1156
                ret = -1
 
1157
            outt = out.getvalue()
 
1158
            if outt.endswith("\n"):
 
1159
                outt = outt[:-1]
 
1160
            return (ret, outt)
 
1161
        finally:
 
1162
            sys.stdout = oldstdout
 
1163
            sys.stderr = oldstderr
 
1164
            sys.argv = oldargv
 
1165
 
 
1166
 
 
1167
    def _get_output(self):
 
1168
        try:
 
1169
            for i in new_files:
 
1170
                os.system("rm %s > /dev/null 2>&1" % i)
 
1171
 
 
1172
            code, output = self._launch_command()
 
1173
 
 
1174
            logging.debug(output + "\n")
 
1175
            return code, output
 
1176
        except Exception, e:
 
1177
            return (-1, "".join(traceback.format_exc()) + str(e))
 
1178
 
 
1179
    def run(self):
 
1180
        filename = self.compare_file
 
1181
        err = None
 
1182
 
 
1183
        try:
 
1184
            code, output = self._get_output()
 
1185
 
 
1186
            if bool(code) == self.check_success:
 
1187
                raise AssertionError(
 
1188
                    ("Expected command to %s, but failed.\n" %
 
1189
                     (self.check_success and "pass" or "fail")) +
 
1190
                     ("Command was: %s\n" % self.cmdstr) +
 
1191
                     ("Error code : %d\n" % code) +
 
1192
                     ("Output was:\n%s" % output))
 
1193
 
 
1194
            if filename:
 
1195
                # Generate test files that don't exist yet
 
1196
                if not os.path.exists(filename):
 
1197
                    file(filename, "w").write(output)
 
1198
 
 
1199
                utils.diff_compare(output, filename)
 
1200
 
 
1201
        except AssertionError, e:
 
1202
            err = self.cmdstr + "\n" + str(e)
 
1203
 
 
1204
        return err
 
1205
 
 
1206
 
 
1207
class PromptCheck(object):
 
1208
    """
 
1209
    Individual question/response pair for automated --prompt tests
 
1210
    """
 
1211
    def __init__(self, prompt, response=None):
 
1212
        self.prompt = prompt
 
1213
        self.response = response
 
1214
        if self.response:
 
1215
            self.response = self.response % test_files
 
1216
 
 
1217
    def check(self, proc):
 
1218
        out = proc.stdout.readline()
 
1219
 
 
1220
        if not out.count(self.prompt):
 
1221
            out += "\nContent didn't contain prompt '%s'" % (self.prompt)
 
1222
            return False, out
 
1223
 
 
1224
        if self.response:
 
1225
            proc.stdin.write(self.response + "\n")
 
1226
 
 
1227
        return True, out
 
1228
 
 
1229
 
 
1230
class PromptTest(Command):
 
1231
    """
 
1232
    Fully automated --prompt test
 
1233
    """
 
1234
    def __init__(self, cmdstr):
 
1235
        Command.__init__(self, cmdstr)
 
1236
 
 
1237
        self.prompt_list = []
 
1238
 
 
1239
    def add(self, *args, **kwargs):
 
1240
        self.prompt_list.append(PromptCheck(*args, **kwargs))
 
1241
 
 
1242
    def _launch_command(self):
 
1243
        proc = subprocess.Popen(self.argv,
 
1244
                stdin=subprocess.PIPE,
 
1245
                stdout=subprocess.PIPE,
 
1246
                stderr=subprocess.STDOUT)
 
1247
 
 
1248
        out = "Running %s\n" % self.cmdstr
 
1249
 
 
1250
        for p in self.prompt_list:
 
1251
            ret, content = p.check(proc)
 
1252
            out += content
 
1253
            if not ret:
 
1254
                # Since we didn't match output, process might be hung
 
1255
                proc.kill()
 
1256
                break
 
1257
 
 
1258
        exited = False
 
1259
        for ignore in range(30):
 
1260
            if proc.poll() is not None:
 
1261
                exited = True
 
1262
                break
 
1263
            time.sleep(.1)
 
1264
 
 
1265
        if not exited:
 
1266
            proc.kill()
 
1267
            out += "\nProcess was killed by test harness"
 
1268
 
 
1269
        return proc.wait(), out
 
1270
 
 
1271
 
 
1272
##########################
 
1273
# Automated prompt tests #
 
1274
##########################
1098
1275
 
1099
1276
# Basic virt-install prompting
1100
1277
p1 = PromptTest("virt-install --connect %(TESTURI)s --prompt --quiet "
1145
1322
p6.add("use as the cloned disk", "%(NEWIMG2)s")
1146
1323
promptlist.append(p6)
1147
1324
 
1148
 
def runcomm(comm):
1149
 
    try:
1150
 
        for i in new_files:
1151
 
            os.system("rm %s > /dev/null 2>&1" % i)
1152
 
 
1153
 
        if type(comm) is str:
1154
 
            if debug:
1155
 
                print comm % test_files
1156
 
 
1157
 
            code, output = commands.getstatusoutput(comm % test_files)
1158
 
 
1159
 
        else:
1160
 
            if debug:
1161
 
                print comm.cmdstr
1162
 
            code, output = comm.run()
1163
 
 
1164
 
        if debug:
1165
 
            print output
1166
 
            print "\n"
1167
 
 
1168
 
        return code, output
1169
 
    except Exception, e:
1170
 
        return (-1, str(e))
1171
 
 
1172
 
def write_pass():
1173
 
    if not debug:
1174
 
        sys.stdout.write(".")
1175
 
        sys.stdout.flush()
1176
 
 
1177
 
def write_fail():
1178
 
    if not debug:
1179
 
        sys.stdout.write("F")
1180
 
        sys.stdout.flush()
1181
 
 
1182
 
class Command(object):
1183
 
    def __init__(self, cmd):
1184
 
        self.cmdstr = cmd
1185
 
        self.cmd = None
1186
 
        self.check_success = True
1187
 
        self.compare_file = None
1188
 
 
1189
 
        if type(cmd) is not str:
1190
 
            self.cmd = cmd
1191
 
            self.cmdstr = " ".join(self.cmd.cmd)
1192
 
 
1193
 
    def run(self):
1194
 
        filename = self.compare_file
1195
 
        err = None
1196
 
 
1197
 
        try:
1198
 
            code, output = runcomm(self.cmd or self.cmdstr)
1199
 
 
1200
 
            if bool(code) == self.check_success:
1201
 
                raise AssertionError(
1202
 
                    ("Expected command to %s, but failed.\n" %
1203
 
                     (self.check_success and "pass" or "fail")) +
1204
 
                     ("Command was: %s\n" % self.cmdstr) +
1205
 
                     ("Error code : %d\n" % code) +
1206
 
                     ("Output was:\n%s" % output))
1207
 
 
1208
 
            if filename:
1209
 
                # Uncomment to generate new test files
1210
 
                if not os.path.exists(filename):
1211
 
                    file(filename, "w").write(output)
1212
 
 
1213
 
                utils.diff_compare(output, filename)
1214
 
 
1215
 
            write_pass()
1216
 
        except AssertionError, e:
1217
 
            write_fail()
1218
 
            err = self.cmdstr + "\n" + str(e)
1219
 
 
1220
 
        return err
1221
 
 
1222
 
# Setup: build cliarg dict, which uses
1223
 
def run_tests(do_app, do_category, error_ret):
1224
 
    if do_app and do_app not in args_dict.keys():
1225
 
        raise ValueError("Unknown app '%s'" % do_app)
1226
 
 
1227
 
    cmdlist = []
1228
 
 
1229
 
    # Prompt tests upfront
1230
 
    for cmd in promptlist:
1231
 
        cmdlist.append(Command(cmd))
 
1325
# Basic virt-clone prompting with disk failure handling
 
1326
p7 = PromptTest("virt-clone --connect %(TESTURI)s --prompt --quiet "
 
1327
               "--clone-running -o test-clone-simple -n test-clone-new")
 
1328
p7.add("use as the cloned disk", "/root")
 
1329
p7.add("'/root' must be a file or a device")
 
1330
p7.add("use as the cloned disk", "%(MANAGEDNEW1)s")
 
1331
promptlist.append(p7)
 
1332
 
 
1333
 
 
1334
#########################
 
1335
# Test runner functions #
 
1336
#########################
 
1337
 
 
1338
def build_cmd_list():
 
1339
    cmdlist = promptlist
1232
1340
 
1233
1341
    for app in args_dict:
1234
 
        if do_app and app != do_app:
1235
 
            continue
1236
 
 
1237
1342
        unique = {}
1238
 
        globalargs = ""
1239
1343
 
1240
1344
        # Build default command line dict
1241
1345
        for option in args_dict.get(app):
1242
 
            if option == "globalargs":
1243
 
                globalargs = args_dict[app][option]
1244
 
                continue
1245
 
 
1246
1346
            # Default is a unique cmd string
1247
1347
            unique[option] = args_dict[app][option]
1248
1348
 
1249
 
 
1250
 
        if do_category and do_category not in unique.keys():
1251
 
            raise ValueError("Unknown category %s" % do_category)
1252
 
 
1253
1349
        # Build up unique command line cases
1254
1350
        for category in unique.keys():
1255
 
            if do_category and category != do_category:
1256
 
                continue
1257
1351
            catdict = unique[category]
1258
1352
            category_args = catdict["args"]
1259
1353
 
1260
 
            for optstr in catdict["valid"]:
1261
 
                cmdstr = "./%s %s %s %s" % (app, globalargs,
1262
 
                                            category_args, optstr)
1263
 
                cmd = Command(cmdstr)
1264
 
                cmd.check_success = True
1265
 
                cmdlist.append(cmd)
1266
 
 
1267
 
            for optstr in catdict["invalid"]:
1268
 
                cmdstr = "./%s %s %s %s" % (app, globalargs,
1269
 
                                            category_args, optstr)
1270
 
                cmd = Command(cmdstr)
1271
 
                cmd.check_success = False
1272
 
                cmdlist.append(cmd)
1273
 
 
1274
 
            for optstr, filename in catdict.get("compare") or []:
1275
 
                filename = "%s/%s.xml" % (compare_xmldir, filename)
1276
 
                cmdstr = "./%s %s %s %s" % (app, globalargs,
1277
 
                                            category_args, optstr)
1278
 
                cmdstr = cmdstr % test_files
1279
 
 
1280
 
                # Strip --debug to get reasonable output
1281
 
                cmdstr = cmdstr.replace("--debug ", "").replace("-d ", "")
1282
 
                if app == "virt-install":
1283
 
                    if (not cmdstr.count("--print-xml") and
1284
 
                        not cmdstr.count("--print-step") and
1285
 
                        not cmdstr.count("--quiet")):
1286
 
                        cmdstr += " --print-step all"
1287
 
 
1288
 
                elif app == "virt-image":
1289
 
                    if not cmdstr.count("--print"):
1290
 
                        cmdstr += " --print"
1291
 
 
1292
 
                elif app == "virt-clone":
1293
 
                    if not cmdstr.count("--print-xml"):
1294
 
                        cmdstr += " --print-xml"
1295
 
 
1296
 
                if app != "virt-convert" and not cmdstr.count(fakeuri):
1297
 
                    cmdstr += " --connect %s" % fakeuri
1298
 
 
1299
 
                cmd = Command(cmdstr)
1300
 
                cmd.check_success = not filename.endswith("fail.xml")
1301
 
                cmd.compare_file = filename
1302
 
                cmdlist.append(cmd)
1303
 
 
1304
 
    # Run commands
1305
 
    for cmd in cmdlist:
1306
 
        err = cmd.run()
1307
 
        if err:
1308
 
            error_ret.append(err)
1309
 
 
1310
 
def main():
1311
 
    # CLI Args
1312
 
    global debug
1313
 
 
1314
 
    do_app = None
1315
 
    do_category = None
1316
 
 
1317
 
    if len(sys.argv) > 1:
1318
 
        for i in range(1, len(sys.argv)):
1319
 
            if sys.argv[i].count("debug"):
1320
 
                debug = True
1321
 
            elif sys.argv[i].count("--app"):
1322
 
                do_app = sys.argv[i + 1]
1323
 
            elif sys.argv[i].count("--category"):
1324
 
                do_category = sys.argv[i + 1]
1325
 
 
1326
 
    # Setup needed files
1327
 
    for i in exist_files:
1328
 
        if os.path.exists(i):
1329
 
            raise ValueError("'%s' will be used by testsuite, can not already"
1330
 
                             " exist." % i)
1331
 
 
 
1354
            for testtype in ["valid", "invalid", "compare"]:
 
1355
                for optstr in catdict.get(testtype) or []:
 
1356
                    if testtype == "compare":
 
1357
                        optstr, filename = optstr
 
1358
                        filename = "%s/%s.xml" % (compare_xmldir, filename)
 
1359
 
 
1360
                    args = category_args + " " + optstr
 
1361
                    args = default_args(app, args, testtype) + " " + args
 
1362
                    cmdstr = "./%s %s" % (app, args)
 
1363
 
 
1364
                    cmd = Command(cmdstr)
 
1365
                    if testtype == "compare":
 
1366
                        cmd.check_success = not filename.endswith("fail.xml")
 
1367
                        cmd.compare_file = filename
 
1368
                    else:
 
1369
                        cmd.check_success = bool(testtype == "valid")
 
1370
 
 
1371
                    cmdlist.append(cmd)
 
1372
 
 
1373
    return cmdlist
 
1374
 
 
1375
newidx = 0
 
1376
curtest = 0
 
1377
old_bridge = virtinst._util.default_bridge2
 
1378
 
 
1379
def setup():
 
1380
    """
 
1381
    Create initial test files/dirs
 
1382
    """
1332
1383
    os.system("mkdir %s" % ro_dir)
1333
1384
 
1334
1385
    for i in exist_files:
1338
1389
    os.system("chmod 444 %s" % ro_img)
1339
1390
    os.system("chmod 555 %s" % ro_dir)
1340
1391
 
1341
 
    error_ret = []
1342
 
    try:
1343
 
        run_tests(do_app, do_category, error_ret)
1344
 
    finally:
1345
 
        cleanup()
1346
 
        for err in error_ret:
1347
 
            print err + "\n\n"
 
1392
    virtinst._util.default_bridge2 = lambda ignore: None
1348
1393
 
1349
 
    if not error_ret:
1350
 
        print "\nAll tests completed successfully."
1351
1394
 
1352
1395
def cleanup():
1353
 
    # Cleanup files
 
1396
    """
 
1397
    Cleanup temporary files used for testing
 
1398
    """
1354
1399
    for i in clean_files:
1355
1400
        os.system("chmod 777 %s > /dev/null 2>&1" % i)
1356
1401
        os.system("rm -rf %s > /dev/null 2>&1" % i)
1357
1402
 
1358
 
if __name__ == "__main__":
1359
 
    try:
1360
 
        main()
1361
 
    except KeyboardInterrupt:
1362
 
        print "Tests interrupted"
1363
 
        if debug:
1364
 
            raise
 
1403
    virtinst._util.default_bridge2 = old_bridge
 
1404
 
 
1405
class CLITests(unittest.TestCase):
 
1406
    def __init__(self, *args, **kwargs):
 
1407
        unittest.TestCase.__init__(self, *args, **kwargs)
 
1408
 
 
1409
    def setUp(self):
 
1410
        global curtest
 
1411
        curtest += 1
 
1412
        # Only run this for first test
 
1413
        if curtest == 1:
 
1414
            setup()
 
1415
 
 
1416
    def tearDown(self):
 
1417
        # Only run this on the last test
 
1418
        if curtest == newidx:
 
1419
            cleanup()
 
1420
 
 
1421
def maketest(cmd):
 
1422
    def cmdtemplate(self, c):
 
1423
        err = c.run()
 
1424
        if err:
 
1425
            self.fail(err)
 
1426
    return lambda s: cmdtemplate(s, cmd)
 
1427
 
 
1428
_cmdlist = build_cmd_list()
 
1429
for _cmd in _cmdlist:
 
1430
    newidx += 1
 
1431
    setattr(CLITests, "testCLI%d" % newidx, maketest(_cmd))