def test_precheckFail(): '''Make sure esxupgrade parses all of the precheck failures correctly.''' fauxroot.resetLogs() failFile = open(os.path.join(TEST_DIR, "upgrade", "precheck.allfail.xml")) try: failOutput = failFile.read() finally: failFile.close() oldStderr = sys.stderr fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")] try: open("/esx4-upgrade/isoinfo", "w").write("# empty\n") open("/mnt/cdrom/initrd.img", "w").write("# empty\n") os.makedirs("/vmfs/volumes/Storage 1") def precheck(_argv): return (failOutput, 0) fauxroot.EXEC_FUNCTIONS["python"] = precheck sys.stderr = StringIO() esxupgrade.main(["esxupgrade.py", "Storage 1"]) actualOutput = sys.stderr.getvalue() print actualOutput assert actualOutput == EXPECTED_FAIL_OUTPUT finally: fauxroot.FAUXROOT = None sys.stderr = oldStderr
def test_migrate(): try: fauxroot.resetLogs() srcDir = os.path.join(TEST_DIR, "upgrade") root = os.path.join(TEST_DIR, "good-config.1") esx3 = consts.HOST_ROOT + consts.ESX3_INSTALLATION copyIntoRoot(os.path.join(srcDir, "xinetd.conf.1"), root, os.path.join(esx3, "etc/xinetd.conf")) copyIntoRoot(os.path.join(srcDir, "time"), root, os.path.join(esx3, "etc/xinetd.d/time")) copyIntoRoot(os.path.join(srcDir, "time"), root, os.path.join(consts.HOST_ROOT, "etc/xinetd.d/time-stream")) copyIntoRoot(os.path.join(srcDir, "vmware-authd"), root, os.path.join(esx3, "etc/xinetd.d/vmware-authd")) copyIntoRoot(os.path.join(srcDir, "vmware-authd"), root, os.path.join(consts.HOST_ROOT, "etc/xinetd.d/vmware-authd")) fauxroot.FAUXROOT = [root] migrate.migratePath("/etc/xinetd.conf") assert fauxroot.SYSTEM_LOG == [ ['/sbin/chkconfig', 'time-stream', 'off'], ['/sbin/chkconfig', 'vmware-authd', 'on'], ] finally: fauxroot.FAUXROOT = None
def test_extractBootFiles(): fauxroot.resetLogs() fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")] try: kernelPath, initrdPath = grubupdate.extractBootFiles("/installer.iso") assert kernelPath == "/esx4-upgrade/vmlinuz" assert initrdPath == "/esx4-upgrade/initrd.img" got = fauxroot.SYSTEM_LOG assert got == [[ '/esx4-upgrade/isoinfo', '-x', '/ISOLINUX/VMLINUZ.;1', '-i', '/installer.iso', '>', '/esx4-upgrade/vmlinuz' ], [ '/esx4-upgrade/isoinfo', '-x', '/ISOLINUX/INITRD.IMG;1', '-i', '/installer.iso', '>', '/esx4-upgrade/initrd.img' ]] assert fauxroot.WRITTEN_FILES[kernelPath].getvalue() == \ "# contents of /ISOLINUX/VMLINUZ.;1 from /installer.iso\n" assert fauxroot.WRITTEN_FILES[initrdPath].getvalue() == \ "# contents of /ISOLINUX/INITRD.IMG;1 from /installer.iso\n" finally: fauxroot.FAUXROOT = None
def test_extractBootFiles(): fauxroot.resetLogs() fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")] try: kernelPath, initrdPath = grubupdate.extractBootFiles("/installer.iso") assert kernelPath == "/esx4-upgrade/vmlinuz" assert initrdPath == "/esx4-upgrade/initrd.img" got = fauxroot.SYSTEM_LOG assert got == [ ['/esx4-upgrade/isoinfo', '-x', '/ISOLINUX/VMLINUZ.;1', '-i', '/installer.iso', '>', '/esx4-upgrade/vmlinuz'], ['/esx4-upgrade/isoinfo', '-x', '/ISOLINUX/INITRD.IMG;1', '-i', '/installer.iso', '>', '/esx4-upgrade/initrd.img'] ] assert fauxroot.WRITTEN_FILES[kernelPath].getvalue() == \ "# contents of /ISOLINUX/VMLINUZ.;1 from /installer.iso\n" assert fauxroot.WRITTEN_FILES[initrdPath].getvalue() == \ "# contents of /ISOLINUX/INITRD.IMG;1 from /installer.iso\n" finally: fauxroot.FAUXROOT = None
def test_failures(): lspciOutput = open(os.path.join( TEST_DIR, "upgrade", "lspci.unsupported")).read() def lspci(_argv): return (lspciOutput, 0) fauxroot.resetLogs() reload(fauxconfig) fauxroot.WRITTEN_FILES["/etc/vmware/esx.conf"] = fauxroot.CopyOnWriteFile( '/system/uuid = "473027ac-5705f21d-6d09-000c2918f3dd"\n') fauxroot.EXEC_FUNCTIONS['/sbin/lspci'] = lspci inventoryContent = open( os.path.join(TEST_DIR, "upgrade", "vmInventory-old.xml")).read() fauxroot.WRITTEN_FILES["/etc/vmware/hostd/vmInventory.xml"] = \ fauxroot.CopyOnWriteFile(inventoryContent) expected = open(os.path.join( TEST_DIR, "upgrade", "precheck-failures.xml")).read() try: got = _captureMain() print got finally: del fauxroot.EXEC_FUNCTIONS['/sbin/lspci'] assert got == expected
def test_downloadLocally_positive(): fauxroot.resetLogs() downloadLocally = remote_files.downloadLocally loc = downloadLocally('http://bad.mediaroot.returns.junk/packages.xml') assert loc.endswith('/tmp/packages.xml') assert loc in fauxroot.WRITTEN_FILES os.remove(loc) #clean up raises(RemoteFileError)(downloadLocally)('http://bad.mediaroot.returns.junk/packages.xml', integrityChecker=checkXML)
def test_uuidForDevice(): fauxroot.resetLogs() reload(fauxconfig) try: fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")] got = grubupdate.uuidForDevice("/dev/sda1") finally: fauxroot.FAUXROOT = [] print got assert got == '4aa8e7c6-24ef-4f3e-9986-e628f7d1d51b'
def test_hasEsxConf(): fauxroot.resetLogs() reload(fauxconfig) fauxroot.WRITTEN_FILES["/etc/vmware/esx.conf"] = fauxroot.CopyOnWriteFile( '/system/uuid = "473027ac-5705f21d-6d09-000c2918f3dd"\n') expected = open(os.path.join( TEST_DIR, "upgrade", "precheck-esxconf.xml")).read() got = _captureMain() print got assert got == expected
def playWrapper(filename): global singletons fauxroot.resetLogs() rpm.reset() vmkctl.reset() sys.path.append(os.path.join(TEST_DIR, DEFAULT_CONFIG_NAME)) reload(fauxconfig) sys.path.pop() reload(userchoices) import customdrivers reload(customdrivers) import networking reload(networking.networking_base) import media reload(media) import gui reload(gui) import installlocation_gui reload(installlocation_gui) import timezone_gui reload(timezone_gui) import timedate_gui reload(timedate_gui) import datastore_gui reload(datastore_gui) import setupvmdk_gui reload(setupvmdk_gui) import network_address_widgets reload(network_address_widgets) # XXX sucks to have to reload to reset global state like this... for singletonClass in singletons: singletonClass._the_only_instance = None singletons = [] oldDir = os.getcwd() try: os.chdir(os.path.join(TEST_DIR, os.pardir)) kiwi.ui.test.runner.play_file(filename, None) except SystemExit, e: pass
def test_noEsxConf(): fauxroot.resetLogs() reload(fauxconfig) expected = open(os.path.join( TEST_DIR, "upgrade", "precheck-noesxconf.xml")).read() inventoryContent = open( os.path.join(TEST_DIR, "upgrade", "vmInventory.xml")).read() fauxroot.WRITTEN_FILES["/etc/vmware/hostd/vmInventory.xml"] = \ fauxroot.CopyOnWriteFile(inventoryContent) got = _captureMain() print got assert got == expected
def test_notEnoughMemory(): def usrSbinEsxcfgInfo(_argv): return (" |---Physical Mem.............536870912\n" " |---Service Console Mem (Cfg)....272\n", 0) fauxroot.resetLogs() reload(fauxconfig) fauxroot.WRITTEN_FILES["/etc/vmware/esx.conf"] = fauxroot.CopyOnWriteFile( '/system/uuid = "473027ac-5705f21d-6d09-000c2918f3dd"\n') expected = open(os.path.join( TEST_DIR, "upgrade", "precheck-mem.xml")).read() fauxroot.EXEC_FUNCTIONS['/usr/sbin/esxcfg-info'] = usrSbinEsxcfgInfo got = _captureMain() print got assert got == expected
def test_netOptions(): def checkExpected(): expected = { 'gateway' : '192.168.2.254', 'nameserver1' : '', 'nameserver2' : '', 'hostname' : 'localhost' } actual = userchoices.getDownloadNetwork() assert actual == expected, actual actual = userchoices.getDownloadNic() assert actual['device'].name == 'vmnic32' assert actual['vlanID'] == '5' assert actual['bootProto'] == userchoices.NIC_BOOT_STATIC assert actual['ip'] == '192.168.2.1' assert actual['netmask'] == '255.255.255.0' try: fauxroot.resetLogs() reload(fauxconfig) fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")] translateBootCmdLine( "ip=192.168.2.1 gateway=192.168.2.254 " "vlanid=5 " "netmask=255.255.255.0 netdevice=00:50:56:C0:00:00") checkExpected() fauxroot.FAUXROOT = None fauxroot.resetLogs() reload(fauxconfig) fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")] translateBootCmdLine( "ip=192.168.2.1:192.168.2.2:192.168.2.254:255.255.255.0 " "vlanid=5 " "BOOTIF=01-00-50-56-C0-00-00") checkExpected() #TODO: we should really add a negative test case finally: fauxroot.FAUXROOT = None
def test_netOptions(): def checkExpected(): expected = { 'gateway': '192.168.2.254', 'nameserver1': '', 'nameserver2': '', 'hostname': 'localhost' } actual = userchoices.getDownloadNetwork() assert actual == expected, actual actual = userchoices.getDownloadNic() assert actual['device'].name == 'vmnic32' assert actual['vlanID'] == '5' assert actual['bootProto'] == userchoices.NIC_BOOT_STATIC assert actual['ip'] == '192.168.2.1' assert actual['netmask'] == '255.255.255.0' try: fauxroot.resetLogs() reload(fauxconfig) fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")] translateBootCmdLine( "ip=192.168.2.1 gateway=192.168.2.254 " "vlanid=5 " "netmask=255.255.255.0 netdevice=00:50:56:C0:00:00") checkExpected() fauxroot.FAUXROOT = None fauxroot.resetLogs() reload(fauxconfig) fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")] translateBootCmdLine( "ip=192.168.2.1:192.168.2.2:192.168.2.254:255.255.255.0 " "vlanid=5 " "BOOTIF=01-00-50-56-C0-00-00") checkExpected() #TODO: we should really add a negative test case finally: fauxroot.FAUXROOT = None
def test_remoteOpen_proxy(): fauxroot.resetLogs() remoteOpen = remote_files.remoteOpen raises(URLError)(remoteOpen)('http://requires.a.proxy/packages.xml') raises(IOError)(remoteOpen)('ftp://requires.a.proxy/packages.xml') import userchoices userchoices.setMediaProxy('proxy.vmware.com', '3128') fp = remoteOpen('http://requires.a.proxy/packages.xml') assert fp fp = remoteOpen('ftp://requires.a.proxy/packages.xml') assert fp userchoices.unsetMediaProxy() raises(URLError)(remoteOpen)('http://requires.a.proxy/packages.xml') raises(IOError)(remoteOpen)('ftp://requires.a.proxy/packages.xml')
def test_translateBootCmdLine(): reload(userchoices) try: fauxroot.resetLogs() reload(fauxconfig) fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")] open( "/mnt/by-uuid/4aa8e7c6-24ef-4f3e-9986-e628f7d1d51g/" "grub/grub.conf.esx3", 'w').close() translateBootCmdLine("bootpart=4aa8e7c6-24ef-4f3e-9986-e628f7d1d51b " "rootpart=4aa8e7c6-24ef-4f3e-9986-e628f7d1d61b") got = userchoices.getBootUUID()['uuid'] assert got == "4aa8e7c6-24ef-4f3e-9986-e628f7d1d51b" got = userchoices.getRootUUID()['uuid'] assert got == "4aa8e7c6-24ef-4f3e-9986-e628f7d1d61b" raises(SystemExit)(translateBootCmdLine)("bootpart=baduuid") translateBootCmdLine( "ks=UUID:4aa8e7c6-24ef-4f3e-9986-e628f7d1d51b:/ks.cfg") mntPath1 = '/mnt/by-uuid/4aa8e7c6-24ef-4f3e-9986-e628f7d1d51b' assert fauxroot.SYSTEM_LOG == [ ['/bin/bash', '/tmp/initscripts.sh'], ['cd', '/', '&&', 'INSTALLER=1', '/init', '14.foobar'], ['cd', '/', '&&', 'INSTALLER=1', '/init', '71.bogusipmi'], ['echo', 'mkblkdevs', '|', 'nash', '--force'], ['/usr/bin/mount', '/dev/sda1', mntPath1], ['/usr/bin/umount', mntPath1], ['/usr/bin/mount', '/dev/sda1', mntPath1] ] assert fauxroot.WRITTEN_FILES[mntPath1].getvalue() == "" finally: fauxroot.FAUXROOT = None
def test_translateBootCmdLine(): reload(userchoices) try: fauxroot.resetLogs() reload(fauxconfig) fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")] open("/mnt/by-uuid/4aa8e7c6-24ef-4f3e-9986-e628f7d1d51g/" "grub/grub.conf.esx3", 'w').close() translateBootCmdLine("bootpart=4aa8e7c6-24ef-4f3e-9986-e628f7d1d51b " "rootpart=4aa8e7c6-24ef-4f3e-9986-e628f7d1d61b") got = userchoices.getBootUUID()['uuid'] assert got == "4aa8e7c6-24ef-4f3e-9986-e628f7d1d51b" got = userchoices.getRootUUID()['uuid'] assert got == "4aa8e7c6-24ef-4f3e-9986-e628f7d1d61b" raises(SystemExit)(translateBootCmdLine)("bootpart=baduuid") translateBootCmdLine( "ks=UUID:4aa8e7c6-24ef-4f3e-9986-e628f7d1d51b:/ks.cfg") mntPath1 = '/mnt/by-uuid/4aa8e7c6-24ef-4f3e-9986-e628f7d1d51b' assert fauxroot.SYSTEM_LOG == [ ['/bin/bash', '/tmp/initscripts.sh'], ['cd', '/', '&&', 'INSTALLER=1', '/init', '14.foobar'], ['cd', '/', '&&', 'INSTALLER=1', '/init', '71.bogusipmi'], ['echo', 'mkblkdevs', '|', 'nash', '--force'], ['/usr/bin/mount', '/dev/sda1', mntPath1], ['/usr/bin/umount', mntPath1], ['/usr/bin/mount', '/dev/sda1', mntPath1]] assert fauxroot.WRITTEN_FILES[mntPath1].getvalue() == "" finally: fauxroot.FAUXROOT = None
def setup(): '''Setup the cage, but do not enable the faux chroot.''' global STEPPER, LAST_OUTPUT, NEXT_INPUT global oldStdout, newStdout, oldStderr, newStderr fauxroot.resetLogs() rpm.reset() vmkctl.reset() sys.path.append(os.path.join(TEST_DIR, DEFAULT_CONFIG_NAME)) import fauxconfig sys.path.pop() reload(fauxconfig) # XXX Need to reload modules with global data. import userchoices reload(userchoices) import remote_files remote_files.__cacher = None remote_files.__nfsMounter = None remote_files.NFSMounter._nfsUp = False import customdrivers reload(customdrivers) import media reload(media) import scui reload(scui) import networking reload(networking.networking_base) import boot_cmdline reload(boot_cmdline) import packages packages.__transactionSet = None textui.textengine._cons_input = _auto_input textui.textengine._password_cons_input = _auto_input textui.textengine._cons_output_oob = lambda x: x textui.textengine._cons_output = _auto_output STEPPER = Stepper() LAST_OUTPUT = "" NEXT_INPUT = None # Find the name of the doctest file that is being run. XXX Evil st = inspect.stack() oldStdout = sys.stdout newStdout = fauxroot.CopyOnWriteFile() oldStderr = sys.stderr newStderr = fauxroot.CopyOnWriteFile() doctestName = None for frame in st: if frame[1].endswith("doctest.py"): doctestName = frame[0].f_locals['test'].filename break if doctestName: testContents = open(doctestName).read() # Get the kickstart commands from the top of the file. ksEnd = testContents.find(">>>") ksFile = testContents[:ksEnd] fauxroot.WRITTEN_FILES["/ks.cfg"] = fauxroot.CopyOnWriteFile(ksFile)
def buildExpectedResultSet(fileName): warnings = [] errors = [] verify = [] readWarnings = readErrors = readVerify = False rootPath = None if fauxroot.FAUXROOT: fauxroot.FAUXROOT = None reload(preparser) configToLoad = DEFAULT_CONFIG_NAME fauxroot.resetLogs() sys.path.append(os.path.join(os.path.dirname(__file__), configToLoad)) reload(fauxconfig) sys.path.pop() fauxroot.EXEC_FUNCTIONS['chroot'] = scriptChroot fauxroot.EXEC_FUNCTIONS['/bin/bash'] = preScript f = open(fileName, 'r') lines = f.readlines() f.close() lineNum = 0 try: line = lines.pop(0) while True: print "line: " + str(lineNum) if line.find("start_warnings") > -1: print "Collecting Warnings" readWarnings = True readErrors = False readVerify = False line = lines.pop(0) lineNum +=1 print "Inspecting line" + str(lineNum) elif line.find("end_warnings") > -1: readWarnings = False print "No More Warnings" elif line.find("start_errors") > -1: print "Collecting Errors" readErrors = True readWarnings = False readVerify = False line = lines.pop(0) lineNum +=1 elif line.find("end_errors") > -1: readErrors = False print "No More Errors" elif line.find("start_verify") > -1: print "Collecting Verification" readVerify = True readWarnings = False readErrors = False line = lines.pop(0) lineNum +=1 elif line.find("end_verify") > -1: readVerify = False print "No More Verification" elif line.find("exec") > -1: # Capture the command to be overridden and the python function # name that imitates the cmd: 'exec <cmd-path> <python-func>'. # For example: # exec /bin/sh badPreScript m = re.match(r'^#\s+exec\s+([^\s]+)\s+(.+)', line) if m: fauxroot.EXEC_FUNCTIONS[m.group(1)] = globals()[m.group(2)] else: m = re.match(r'^#\s+chroot\s+(.+)', line) if m: rootPath = m.group(1) if not line.startswith('#'): pass elif readWarnings: line = line[1::] # remove leading comment token line = line.strip() #remove leading and trailing whitespace warnings.append(line) print "Warning Collected: " + line elif readErrors: line = line[1::] line = line.strip() errors.append(line) print "Error Collected: " + line elif readVerify: line = line[1::] line = line.strip() verify.append(line) print "Verify Collected: " + line line = lines.pop(0) lineNum +=1 except IndexError: pass result = Result.SUCCESS if warnings: result = Result.WARN if errors: result = Result.FAIL return (result, errors, warnings, verify)
def cmpMigratedFiles(func, hostPath, oldPath, newPath, expectedPath, sideEffects=None, setupFunc=None): '''Comparator for migration functions. This comparator will setup the fake environment with the given files, execute the migration function, and then check the resulting file to ensure it is correct. func - The host-action migration function to execute. hostPath - The path of the file on the host (e.g. "/etc/passwd"). oldPath - The path of the file in test/upgrade that contains the ESX v3 configuration. newPath - The path of the file in test/upgrade that contains the ESX v4 configuration or None for an empty file. expectedPath - The path of the file in test/upgrade that contains the expected result of the migration. sideEffects - An optional function that should be called to test for other side effects, like commands that needed to be executed. ''' # Read in the contents of the files oldContents = open(os.path.join(TEST_DIR, "upgrade", oldPath)).read() if newPath is not None: newContents = open(os.path.join(TEST_DIR, "upgrade", newPath)).read() else: newContents = "" expected = open(os.path.join(TEST_DIR, "upgrade", expectedPath)).read() try: fauxroot.resetLogs() # Set the fake chroot and fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")] # ... write the files to the fake environment. open(os.path.join(consts.HOST_ROOT + consts.ESX3_INSTALLATION, hostPath), 'w').write(oldContents) open(os.path.join(consts.HOST_ROOT, hostPath), 'w').write(newContents) if setupFunc: setupFunc() # Execute the migration in the fake environment. func(None) # Read back the file and actual = open(os.path.join(consts.HOST_ROOT, hostPath)).read() # ... produce a diff for easy reading. diffLines = [line for line in difflib.unified_diff( actual.split('\n'), expected.split('\n'))] if diffLines: print " ** DIFF **" print "\n".join(diffLines) assert actual == expected if sideEffects: sideEffects() finally: fauxroot.FAUXROOT = None
def cmpMigratedFiles(func, hostPath, oldPath, newPath, expectedPath, sideEffects=None, setupFunc=None): '''Comparator for migration functions. This comparator will setup the fake environment with the given files, execute the migration function, and then check the resulting file to ensure it is correct. func - The host-action migration function to execute. hostPath - The path of the file on the host (e.g. "/etc/passwd"). oldPath - The path of the file in test/upgrade that contains the ESX v3 configuration. newPath - The path of the file in test/upgrade that contains the ESX v4 configuration or None for an empty file. expectedPath - The path of the file in test/upgrade that contains the expected result of the migration. sideEffects - An optional function that should be called to test for other side effects, like commands that needed to be executed. ''' # Read in the contents of the files oldContents = open(os.path.join(TEST_DIR, "upgrade", oldPath)).read() if newPath is not None: newContents = open(os.path.join(TEST_DIR, "upgrade", newPath)).read() else: newContents = "" expected = open(os.path.join(TEST_DIR, "upgrade", expectedPath)).read() try: fauxroot.resetLogs() # Set the fake chroot and fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")] # ... write the files to the fake environment. open( os.path.join(consts.HOST_ROOT + consts.ESX3_INSTALLATION, hostPath), 'w').write(oldContents) open(os.path.join(consts.HOST_ROOT, hostPath), 'w').write(newContents) if setupFunc: setupFunc() # Execute the migration in the fake environment. func(None) # Read back the file and actual = open(os.path.join(consts.HOST_ROOT, hostPath)).read() # ... produce a diff for easy reading. diffLines = [ line for line in difflib.unified_diff(actual.split('\n'), expected.split('\n')) ] if diffLines: print " ** DIFF **" print "\n".join(diffLines) assert actual == expected if sideEffects: sideEffects() finally: fauxroot.FAUXROOT = None