class zzzTestFrameworkKVADefault(unittest.TestCase): def tearDown(self): pass def setUp(self): kvtype = "defaults" data = {"CatalogURL": [APPLESOFTUPDATESERVER, APPLESOFTUPDATESERVER], "LastResultCode": ["100", "100"]} path = "/Library/Preferences/com.apple.SoftwareUpdate" self.environ = Environment() if not self.environ.getosfamily() == "darwin": return self.logger = LogDispatcher(self.environ) stchglogger = StateChgLogger(self.logger, self.environ) self.editor = KVEditorStonix.KVEditorStonix(stchglogger, self.logger, kvtype, path, path + ".tmp", data, "present", "openeq") def testSimple(self): if not self.environ.getosfamily() == "darwin": return data = {"GuestEnabled": "0"} self.assertTrue(self.editor.setData(data)) self.assertEqual(data, self.editor.getData()) path = "/Library/Preferences/com.apple.loginwindow.plist" self.assertTrue(self.editor.setPath(path)) self.assertEqual(path, self.editor.getPath())
class zzzTestFrameworkKVADefault(unittest.TestCase): def tearDown(self): pass def setUp(self): kvtype = "defaults" data = { "CatalogURL": [APPLESOFTUPDATESERVER, APPLESOFTUPDATESERVER], "LastResultCode": ["100", "100"] } path = "/Library/Preferences/com.apple.SoftwareUpdate" self.environ = Environment() if not self.environ.getosfamily() == "darwin": return self.logger = LogDispatcher(self.environ) stchglogger = StateChgLogger(self.logger, self.environ) self.editor = KVEditorStonix.KVEditorStonix(stchglogger, self.logger, kvtype, path, path + ".tmp", data, "present", "openeq") def testSimple(self): if not self.environ.getosfamily() == "darwin": return data = {"GuestEnabled": "0"} self.assertTrue(self.editor.setData(data)) self.assertEqual(data, self.editor.getData()) path = "/Library/Preferences/com.apple.loginwindow.plist" self.assertTrue(self.editor.setPath(path)) self.assertEqual(path, self.editor.getPath())
class zzzTestFrameworkServiceHelper(unittest.TestCase): def setUp(self): self.enviro = Environment() self.enviro.setdebugmode(False) self.logger = LogDispatcher(self.enviro) self.mysh = ServiceHelper(self.enviro, self.logger) self.myservice = 'crond' self.myservicename = "" if self.enviro.getosfamily() == 'darwin': self.myservice = "/System/Library/PrivateFrameworks/CalendarAgent.framework/Executables/CalendarAgent" self.myservicename = "com.apple.CalendarAgent" elif self.enviro.getosfamily() == 'solaris': self.myservice = 'svc:/system/cron:default' elif self.enviro.getosfamily() == 'freebsd': self.myservice = 'cron' elif os.path.exists('/usr/lib/systemd/system/cron.service'): self.myservice = 'cron.service' elif os.path.exists('/usr/lib/systemd/system/crond.service'): self.myservice = 'crond.service' elif os.path.exists('/etc/init.d/vixie-cron'): self.myservice = 'vixie-cron' elif os.path.exists('/etc/init.d/cron'): self.myservice = 'cron' def tearDown(self): pass def testListServices(self): svcslist = self.mysh.listservices() self.assertTrue(len(svcslist) > 0) def testDisableEnable(self): self.mysh.disableservice(self.myservice) auditresult = self.mysh.auditservice(self.myservice, self.myservicename) self.assertFalse(auditresult, "Service not disabled or return from audit not valid") time.sleep(3) self.assertFalse(self.mysh.isrunning(self.myservice, self.myservicename), "Service is still running or return from isrunning not valid") self.mysh.enableservice(self.myservice) self.assertTrue(self.mysh.auditservice(self.myservice, self.myservicename), "Service not enabled or return from audit not valid") time.sleep(3) self.assertTrue(self.mysh.isrunning(self.myservice, self.myservicename), "Service is not running or return from isrunning not valid") def testReloadService(self): self.assertTrue(self.mysh.reloadservice(self.myservice, self.myservicename), 'Service reload returned false')
class zzzTestFrameworkServiceHelper(unittest.TestCase): """ Class docs """ def setUp(self): """ initialize and set class variables and objects """ self.environ = Environment() self.environ.setdebugmode(True) self.logger = LogDispatcher(self.environ) self.mysh = ServiceHelper(self.environ, self.logger) # set service name self.myservice = 'crond' self.myservicename = "" if self.environ.getosfamily() == 'darwin': self.myservice = "/Library/LaunchDaemons/gov.lanl.stonix.report.plist" self.myservicename = "gov.lanl.stonix.report" elif self.environ.getosfamily() == 'solaris': self.myservice = 'svc:/system/cron:default' elif self.environ.getosfamily() == 'freebsd': self.myservice = 'cron' elif os.path.exists('/usr/lib/systemd/system/cron.service'): self.myservice = 'cron.service' elif os.path.exists('/usr/lib/systemd/system/crond.service'): self.myservice = 'crond.service' elif os.path.exists('/etc/init.d/vixie-cron'): self.myservice = 'vixie-cron' elif os.path.exists('/etc/init.d/cron'): self.myservice = 'cron' if self.environ.getosfamily() == "darwin": self.service = self.myservice, self.myservicename else: self.service = [self.myservice] # store system initial state self.orig_enabled = self.mysh.auditService(*self.service) def tearDown(self): """ restore system initial state """ if self.orig_enabled: self.mysh.enableService(*self.service) else: self.mysh.disableService(*self.service) def testListServices(self): """ test listing of services """ services = self.mysh.listServices() self.assertGreater(len(services), 0) self.assertIsInstance(services, list) def testDisable(self): """ test disabling a service from initial state: enabled """ # make sure service is started, so stopping it will be a valid test of the function if not self.mysh.auditService(*self.service): self.mysh.enableService(*self.service) disabled = self.mysh.disableService(*self.service) self.assertTrue(disabled) def testEnable(self): """ test enabling a service from initial state: disabled """ # make sure service is stopped, so starting it will be a valid test of the function if self.mysh.auditService(*self.service): self.mysh.disableService(*self.service) enabled = self.mysh.enableService(*self.service) self.assertTrue(enabled) def testReloadService(self): """ test reloading a service from both initial states: enabled disabled """ self.mysh.disableService(*self.service) reloaded1 = self.mysh.reloadService(*self.service) self.assertTrue(reloaded1) self.mysh.enableService(*self.service) reloaded2 = self.mysh.reloadService(*self.service) self.assertTrue(reloaded2) def testIsRunning(self): """ test status checking to see if a service is running (start and stop not implemented in all helpers) """ if self.mysh.startService(*self.service): self.assertTrue(self.mysh.isRunning(*self.service)) if self.mysh.stopService(*self.service): self.assertFalse(self.mysh.isRunning(*self.service))
class zzzTestFrameworkRamdisk(unittest.TestCase): @classmethod def setUpClass(self): '''Initializer''' self.environ = Environment() # Start timer in miliseconds self.test_start_time = datetime.now() self.logger = LogDispatcher(self.environ) ##### # setting up to call ctypes to do a filesystem sync if self.environ.getosfamily() == "redhat": self.libc = C.CDLL("/lib/libc.so.6") elif self.environ.getosfamily() == "darwin": self.libc = C.CDLL("/usr/lib/libc.dylib") else: self.libc = None self.subdirs = ["two", "three" "one/four"] """ Set up a ramdisk and use that random location as a root to test the filesystem functionality of what is being tested. """ #Calculate size of ramdisk to make for this unit test. size_in_mb = 1800 ramdisk_size = size = size_in_mb self.mnt_pnt_requested = "" self.success = False self.mountPoint = False self.ramdiskDev = False self.mnt_pnt_requested = False self.logger.log(LogPriority.DEBUG, "::::::::Ramdisk Mount Point: " + str(self.mountPoint)) self.logger.log(LogPriority.DEBUG, "::::::::Ramdisk Device : " + str(self.ramdiskDev)) if self.environ.getosfamily().lower() == "darwin": # import appropriate ramdisk library #from src.MacBuild.macRamdisk import Ramdisk, detach # get a ramdisk of appropriate size, with a secure random mountpoint self.my_ramdisk = RamDisk(str(ramdisk_size), self.mnt_pnt_requested) (self.success, self.mountPoint, self.ramdiskDev) = \ self.my_ramdisk.get_data() else: self.logger.log(LogPriority.INFO, "Not applicable to this OS") self.success = False if not self.success: raise IOError("Cannot get a ramdisk for some reason. . .") ##### # Create a temp location on disk to run benchmark tests against self.fs_dir = tempfile.mkdtemp() def setUp(self): '''This method runs before each test run. @author: Roy Nielsen ''' self.libcPath = None # initial initialization ##### # setting up to call ctypes to do a filesystem sync if sys.platform.startswith("darwin"): ##### # For Mac self.libc = C.CDLL("/usr/lib/libc.dylib") elif sys.platform.startswith("linux"): ##### # For Linux self.findLinuxLibC() self.libc = C.CDLL(self.libcPath) else: self.libc = self._pass() ############################################################################### ##### Helper Classes def findLinuxLibC(self): '''Find Linux Libc library... @author: Roy Nielsen ''' possible_paths = [ "/lib/x86_64-linux-gnu/libc.so.6", "/lib/i386-linux-gnu/libc.so.6" ] for path in possible_paths: if os.path.exists(path): self.libcPath = path break def _pass(self): '''Filler if a library didn't load properly''' pass def touch(self, fname="", message_level="normal"): '''Python implementation of the touch command.. inspiration: http://stackoverflow.com/questions/1158076/implement-touch-using-python @author: Roy Nielsen :param fname: (Default value = "") :param message_level: (Default value = "normal") ''' if re.match("^\s*$", str(fname)): self.logger.log(LogPriority.DEBUG, "Cannot touch a file without a filename....") else: try: os.utime(fname, None) except: try: open(fname, 'a').close() except Exception as err: self.logger.log(LogPriority.INFO, "Cannot open to touch: " + str(fname)) def mkdirs(self, path=""): '''A function to do an equivalent of "mkdir -p" :param path: (Default value = "") ''' if not path: self.logger.log(LogPriority.INFO, "Bad path...") else: if not os.path.exists(str(path)): try: os.makedirs(str(path)) except OSError as err1: self.logger.log( LogPriority.INFO, "OSError exception attempting to create directory: " + str(path)) self.logger.log(LogPriority.INFO, "Exception: " + str(err1)) except Exception as err2: self.logger.log( LogPriority.INFO, "Unexpected Exception trying to makedirs: " + str(err2)) def mkfile(self, file_path="", file_size=0, pattern="rand", block_size=512, mode=0o777): '''Create a file with "file_path" and "file_size". To be used in file creation benchmarking - filesystem vs ramdisk. :param eter: file_path - Full path to the file to create :param eter: file_size - Size of the file to create, in Mba :param eter: pattern - "rand": write a random pattern "0xXX": where XX is a hex value for a byte :param eter: block_size - size of blocks to write in bytes :param eter: mode - file mode, default 0o777 :param file_path: (Default value = "") :param file_size: (Default value = 0) :param pattern: (Default value = "rand") :param block_size: (Default value = 512) :param mode: (Default value = 0o777) :returns: s: time in miliseconds the write took @author: Roy Nielsen ''' total_time = 0 if file_path and file_size: self.libc.sync() file_size = file_size * 1024 * 1024 if os.path.isdir(file_path): tmpfile_path = os.path.join(file_path, "testfile") else: tmpfile_path = file_path self.logger.log(LogPriority.DEBUG, "Writing to: " + tmpfile_path) try: # Get the number of blocks to create blocks = file_size / block_size # Start timer in miliseconds start_time = datetime.now() # do low level file access... tmpfile = os.open(tmpfile_path, os.O_WRONLY | os.O_CREAT, mode) # do file writes... for i in range(blocks): tmp_buffer = os.urandom(block_size) os.write(tmpfile, str(tmp_buffer)) os.fsync(tmpfile) self.libc.sync() os.close(tmpfile) self.libc.sync() os.unlink(tmpfile_path) self.libc.sync() # capture end time end_time = datetime.now() except Exception as err: self.logger.log( LogPriority.INFO, "Exception trying to write temp file for benchmarking...") self.logger.log(LogPriority.INFO, "Exception thrown: " + str(err)) total_time = 0 else: total_time = end_time - start_time return total_time def format_ramdisk(self): '''Format Ramdisk''' self.my_ramdisk._format() ############################################################################### ##### Tests ################################## def test_files_n_dirs(self): '''Should work when files exist in ramdisk.''' # Do file setup for this test for subdir in self.subdirs: dirpath = self.mountPoint + "/" + subdir self.logger.log(LogPriority.DEBUG, "DIRPATH: : " + str(dirpath)) self.mkdirs(dirpath) self.touch(dirpath + "/" + "test") # Do the tests for subdir in self.subdirs: # CANNOT use os.path.join this way. os.path.join cannot deal with # absolute directories. May work with mounting ramdisk in local # relative directories. self.assertTrue( os.path.exists(self.mountPoint + "/" + subdir + "/" + "test")) ################################## def test_four_file_sizes(self): '''Test file creation of various sizes, ramdisk vs. filesystem''' ##### # Clean up the ramdisk self.my_ramdisk._format() ##### # 100Mb file size oneHundred = 100 ##### # 100Mb file size twoHundred = 200 ##### # 500Mb file size fiveHundred = 500 ##### # 1Gb file size oneGig = 1000 my_fs_array = [oneHundred, twoHundred, fiveHundred, oneGig] time.sleep(1) for file_size in my_fs_array: ##### # Create filesystem file and capture the time it takes... fs_time = self.mkfile(os.path.join(self.fs_dir, "testfile"), file_size) self.logger.log(LogPriority.DEBUG, "fs_time: " + str(fs_time)) time.sleep(1) ##### # get the time it takes to create the file in ramdisk... ram_time = self.mkfile(os.path.join(self.mountPoint, "testfile"), file_size) self.logger.log(LogPriority.DEBUG, "ram_time: " + str(ram_time)) time.sleep(1) speed = fs_time - ram_time self.logger.log(LogPriority.DEBUG, "ramdisk: " + str(speed) + " faster...") self.assertTrue((fs_time - ram_time).days > -1) def test_many_small_files_creation(self): ''' ''' ##### # Clean up the ramdisk self.my_ramdisk._format() ##### # ramdisk_starttime = datetime.now() for i in range(1000): self.mkfile(os.path.join(self.mountPoint, "testfile" + str(i)), 1) ramdisk_endtime = datetime.now() rtime = ramdisk_endtime - ramdisk_starttime fs_starttime = datetime.now() for i in range(1000): self.mkfile(os.path.join(self.fs_dir, "testfile" + str(i)), 1) fsdisk_endtime = datetime.now() fstime = fsdisk_endtime - fs_starttime self.assertTrue((fstime - rtime).days > -11) ############################################################################### ##### unittest Tear down @classmethod def tearDownClass(self): '''disconnect ramdisk''' if self.my_ramdisk.unmount(): self.logger.log(LogPriority.DEBUG, r"Successfully detached disk: " + \ str(self.my_ramdisk.mntPoint).strip()) else: self.logger.log(LogPriority.DEBUG,r"Couldn't detach disk: " + \ str(self.my_ramdisk.myRamdiskDev).strip() + \ " : mntpnt: " + str(self.my_ramdisk.mntPoint)) raise Exception(r"Cannot eject disk: " + \ str(self.my_ramdisk.myRamdiskDev).strip() + \ " : mntpnt: " + str(self.my_ramdisk.mntPoint)) ##### # capture end time test_end_time = datetime.now() ##### # Calculate and log how long it took... test_time = (test_end_time - self.test_start_time) self.logger.log(LogPriority.DEBUG,self.__module__ + " took " + str(test_time) + \ " time to complete...")
class zzzTestFrameworkRamdisk(unittest.TestCase): @classmethod def setUpClass(self): """ Initializer """ self.environ = Environment() # Start timer in miliseconds self.test_start_time = datetime.now() self.logger = LogDispatcher(self.environ) ##### # setting up to call ctypes to do a filesystem sync if self.environ.getosfamily() == "redhat" : self.libc = C.CDLL("/lib/libc.so.6") elif self.environ.getosfamily() == "darwin" : self.libc = C.CDLL("/usr/lib/libc.dylib") else: self.libc = None self.subdirs = ["two", "three" "one/four"] """ Set up a ramdisk and use that random location as a root to test the filesystem functionality of what is being tested. """ #Calculate size of ramdisk to make for this unit test. size_in_mb = 1800 ramdisk_size = size = size_in_mb self.mnt_pnt_requested = "" self.success = False self.mountPoint = False self.ramdiskDev = False self.mnt_pnt_requested = False self.logger.log(LogPriority.DEBUG, "::::::::Ramdisk Mount Point: " + str(self.mountPoint)) self.logger.log(LogPriority.DEBUG, "::::::::Ramdisk Device : " + str(self.ramdiskDev)) if self.environ.getosfamily().lower() == "darwin": # import appropriate ramdisk library #from src.MacBuild.macRamdisk import Ramdisk, detach # get a ramdisk of appropriate size, with a secure random mountpoint self.my_ramdisk = RamDisk(str(ramdisk_size), self.mnt_pnt_requested) (self.success, self.mountPoint, self.ramdiskDev) = \ self.my_ramdisk.get_data() else: self.logger.log(LogPriority.INFO, "Not applicable to this OS") self.success = False if not self.success: raise IOError("Cannot get a ramdisk for some reason. . .") ##### # Create a temp location on disk to run benchmark tests against self.fs_dir = tempfile.mkdtemp() def setUp(self): """ This method runs before each test run. @author: Roy Nielsen """ self.libcPath = None # initial initialization ##### # setting up to call ctypes to do a filesystem sync if sys.platform.startswith("darwin"): ##### # For Mac self.libc = C.CDLL("/usr/lib/libc.dylib") elif sys.platform.startswith("linux"): ##### # For Linux self.findLinuxLibC() self.libc = C.CDLL(self.libcPath) else: self.libc = self._pass() ############################################################################### ##### Helper Classes def findLinuxLibC(self): """ Find Linux Libc library... @author: Roy Nielsen """ possible_paths = ["/lib/x86_64-linux-gnu/libc.so.6", "/lib/i386-linux-gnu/libc.so.6"] for path in possible_paths: if os.path.exists(path): self.libcPath = path break def _pass(self): """ Filler if a library didn't load properly """ pass def touch(self, fname="", message_level="normal") : """ Python implementation of the touch command.. inspiration: http://stackoverflow.com/questions/1158076/implement-touch-using-python @author: Roy Nielsen """ if re.match("^\s*$", str(fname)): self.logger.log(LogPriority.DEBUG, "Cannot touch a file without a filename....") else : try: os.utime(fname, None) except: try : open(fname, 'a').close() except Exception, err: self.logger.log(LogPriority.INFO,"Cannot open to touch: " + str(fname))
class zzzTestFrameworkServiceHelper(unittest.TestCase): '''Class docs''' def setUp(self): '''initialize and set class variables and objects''' self.environ = Environment() self.environ.setdebugmode(True) self.logger = LogDispatcher(self.environ) self.mysh = ServiceHelper(self.environ, self.logger) # set service name self.myservice = 'crond' self.myservicename = "" if self.environ.getosfamily() == 'darwin': self.myservice = "/Library/LaunchDaemons/gov.lanl.stonix.report.plist" self.myservicename = "gov.lanl.stonix.report" elif self.environ.getosfamily() == 'solaris': self.myservice = 'svc:/system/cron:default' elif self.environ.getosfamily() == 'freebsd': self.myservice = 'cron' elif os.path.exists('/usr/lib/systemd/system/cron.service'): self.myservice = 'cron.service' elif os.path.exists('/usr/lib/systemd/system/crond.service'): self.myservice = 'crond.service' elif os.path.exists('/etc/init.d/vixie-cron'): self.myservice = 'vixie-cron' elif os.path.exists('/etc/init.d/cron'): self.myservice = 'cron' if self.environ.getosfamily() == "darwin": self.service = self.myservice, self.myservicename else: self.service = [self.myservice] # store system initial state self.orig_enabled = self.mysh.auditService(*self.service) def tearDown(self): '''restore system initial state''' if self.orig_enabled: self.mysh.enableService(*self.service) else: self.mysh.disableService(*self.service) def testListServices(self): '''test listing of services''' services = self.mysh.listServices() self.assertGreater(len(services), 0) self.assertIsInstance(services, list) def testDisable(self): '''test disabling a service from initial state: enabled ''' # make sure service is started, so stopping it will be a valid test of the function if not self.mysh.auditService(*self.service): self.mysh.enableService(*self.service) disabled = self.mysh.disableService(*self.service) self.assertTrue(disabled) def testEnable(self): '''test enabling a service from initial state: disabled ''' # make sure service is stopped, so starting it will be a valid test of the function if self.mysh.auditService(*self.service): self.mysh.disableService(*self.service) enabled = self.mysh.enableService(*self.service) self.assertTrue(enabled) def testReloadService(self): '''test reloading a service from both initial states: enabled disabled ''' self.mysh.disableService(*self.service) reloaded1 = self.mysh.reloadService(*self.service) self.assertTrue(reloaded1) self.mysh.enableService(*self.service) reloaded2 = self.mysh.reloadService(*self.service) self.assertTrue(reloaded2) def testIsRunning(self): '''test status checking to see if a service is running (start and stop not implemented in all helpers) ''' if self.mysh.startService(*self.service): self.assertTrue(self.mysh.isRunning(*self.service)) if self.mysh.stopService(*self.service): self.assertFalse(self.mysh.isRunning(*self.service))
class zzzTestFrameworkMacPkgr(unittest.TestCase): """ Class for testing the macpkgr. """ @classmethod def setUpClass(self): """ """ self.environ = Environment() self.logger = LogDispatcher(self.environ) self.osfamily = self.environ.getosfamily() self.logger.log(LogPriority.DEBUG, "##################################") self.logger.log(LogPriority.DEBUG, "### OS Family: " + str(self.osfamily)) self.logger.log(LogPriority.DEBUG, "##################################") self.libc = ctypes.CDLL("/usr/lib/libc.dylib") self.logger = LogDispatcher(self.environ) self.macPackageName = "testStonixMacPkgr-0.0.3.pkg" self.reporoot = MACREPOROOT ##### # Create a class variable that houses the whole URL if self.reporoot.endswith("/"): self.pkgUrl = self.reporoot + self.macPackageName else: self.pkgUrl = self.reporoot + "/" + self.macPackageName message = "self.pkgUrl: " + str(self.pkgUrl) self.pkgr = MacPkgr(self.environ, self.logger) self.pkg_dirs = ["/tmp/testStonixMacPkgr-0.0.3/one/two/three/3.5", \ "/tmp/testStonixMacPkgr-0.0.3/one/two/three", \ "/tmp/testStonixMacPkgr-0.0.3/one/two", \ "/tmp/testStonixMacPkgr-0.0.3/one", \ "/tmp/testStonixMacPkgr-0.0.3/one/two/four/five", \ "/tmp/testStonixMacPkgr-0.0.3/one/two/four", \ "/tmp/testStonixMacPkgr-0.0.3/one/two", \ "/tmp/testStonixMacPkgr-0.0.3/one/six/seven"] self.pkg_files = ["/tmp/testStonixMacPkgr-0.0.3/one/two/testfile1", \ "/tmp/testStonixMacPkgr-0.0.3/one/two/four/five/testfile2", \ "/tmp/testStonixMacPkgr-0.0.3/one/testfile3", \ "/tmp/testStonixMacPkgr-0.0.3/one/testfile4", \ "/tmp/testStonixMacPkgr-0.0.3/one/six/seven/testfile"] self.post_files = ["/tmp/testStonixMacPkgr-0.0.3/one/postfile2", \ "/tmp/testStonixMacPkgr-0.0.3/one/two/three/3.5/postfile3"] self.post_dirs = ["/tmp/testStonixMacPkgr-0.0.3/one/six/6.5"] self.all_files = [self.pkg_files, self.post_files] self.all_dirs = [self.pkg_dirs, self.post_dirs] self.allowed_files_and_dirs = [self.pkg_dirs, self.pkg_dirs, self.post_dirs] self.ch = CommandHelper(self.logger) self.connection = Connectivity(self.logger) self.testDomain = "gov.lanl.testStonixMacPkgr.0.0.3.testStonixMacPkgr" ############################################################################ """ def setUp(self): self.osfamily = self.environ.getosfamily() if re.match("^macosx$", self.osfamily.strip()): myos = self.environ.getosfamiliy() raise unittest.SkipTest("RamDisk does not support this OS" + \ " family: " + str(myos)) """ ############################################################################ @classmethod def tearDownClass(self): """ Make sure the appropriate files are removed.. """ pass ############################################################################ def test_inLinearFlow(self): """ Run methods or functionality that requires order, ie a happens before b Like ensure a package is installed before testing if uninstall works. @author: Roy Nielsen """ if sys.version_info < (2, 7): return if not self.connection.isPageAvailable(): self.logger.log(LogPriority.INFO, "This test fails without a " + \ "properly configured Mac " + \ "repository, so we are not " + \ "running actual tests...") else: ##### # Remove the package in case it is installed, so we have a sane, # consistent starting point for the test. self.removeCompletePackage() ##### # Install the package self.assertTrue(self.pkgr.installPackage(self.macPackageName), "Problem with pkgr.installpackage...") ##### # Use the macpkgr method to check if the package is installed self.assertTrue(self.pkgr.checkInstall(self.macPackageName), "Problem with pkgr.checkInstall...") ##### # Manual check to see if the package is installed self.assertTrue(self.isInstalled(), "Problem with installation...") ##### # Make sure it isn't a partial install... self.assertTrue(self.isFullInstall(), "Partial install...") ##### # Remove the package, assert that it worked. self.assertTrue(self.pkgr.removePackage(self.macPackageName), "Problem removing package...") ##### # Check that checkInstall returns the correct value self.assertFalse(self.pkgr.checkInstall(self.macPackageName), "Problem with pkgr.checkinstall...") ##### # Hand verify that self.pkgr.checkInstall worked. self.assertTrue(self.isMissing(), "Problem with package removal...") ##### # Remove any presence of the package installed. self.removeCompletePackage() ############################################################################ def testCheckInstall(self): """ Test the checkInstall method. 1 - make sure the test .pkg is NOT installed 2 - download the package and check the md5 3 - use custom installer command to install the package 4 - call the checkInstall method @author: Roy Nielsen """ if sys.version_info < (2, 7): return if not self.connection.isPageAvailable(): self.logger.log(LogPriority.INFO, "This test fails without a " + \ "properly configured Mac " + \ "repository, so we are not " + \ "running actual tests...") else: ##### # make sure the test .pkg is NOT installed self.pkgr.removePackage(self.macPackageName) ##### # Test the checkInstall with the package removed self.assertFalse(self.pkgr.checkInstall(self.macPackageName)) self.assertFalse(self.isInstalled()) ##### # Install the package self.pkgr.installPackage(self.macPackageName) ##### # run checkInstall again self.assertTrue(self.pkgr.checkInstall(self.macPackageName)) self.assertTrue(self.isInstalled()) ############################################################################ def testCheckAvailable(self): """ Check if a package is available on the reporoot. Must have both the file AND the md5 checksum file on the server of the format: .<filename>.<UPPER-md5sum> Steps for this test: 1 - set up self.pkgr.pkgUrl 2 - run self.pkgr.downloadPackage 3 - Make sure the checksum matches, otherwise there is a bad md5 for the download, and the package should not be trusted, let alone installed. This covers two test cases - checkAvailable downloadPackage @author: Roy Nielsen """ if sys.version_info < (2, 7): return if not self.connection.isPageAvailable(): self.logger.log(LogPriority.INFO, "This test fails without a " + \ "properly configured Mac " + \ "repository, so we are not " + \ "running actual tests...") else: self.assertTrue(self.reporoot + self.macPackageName) self.pkgr.setPkgUrl(self.reporoot + self.macPackageName) self.pkgr.package = self.macPackageName self.assertTrue(self.pkgr.downloadPackage(), "Package: " + \ str(self.pkgr.getPkgUrl()) + " FAILED download...") self.assertTrue(self.pkgr.checkMd5(), "MD5 checksum didn't match - " + \ "package: " + str(self.pkgr.hashUrl) + " is NOT " + \ "available...") ############################################################################ def testFindDomain(self): """ Test the findDomain function. The domain is required to do a reverse lookup in the local client package receipt database. It should find all the files that have been installed by the PACKAGE, not the postflight. Will remove the test package if it exists, install the package then use the test package to make sure the package file list is accurate. @author: Roy Nielsen """ if sys.version_info < (2, 7): return if not self.connection.isPageAvailable(): self.logger.log(LogPriority.INFO, "This test fails without a " + \ "properly configured Mac " + \ "repository, so we are not " + \ "running actual tests...") else: ##### # Make sure the package is installed self.pkgr.installPackage("testStonixMacPkgr-0.0.3.pkg") ##### # Assert findDomain works properly when the package is installed self.assertEqual(self.testDomain, self.pkgr.findDomain("testStonixMacPkgr-0.0.3.pkg")) ############################################################################ def testUnArchive(self): """ Download a tar package with the test pkg in it. Will test doing a download and checksum of the following by downloading the file and doing a checksum, then unzipping the file, and check the internal filename: testStonixMacPkgr.zip @Note: *** Functionality needs approval *** @author: Roy Nielsen """ pass ############################################################################ def testCopyInstall(self): """ Tests the copyInstall method. Will test by: Downloading the test .tar file with a .app in it, doing a checksum of the .tar file then performing a copyInstall. Will test by checking the existence of the .app being in the right place. @author: Roy Nielsen """ pass ############################################################################ def testInstallPkg(self): """ Tests the installPkg method. Will: Make sure the test pkg is not installed Download and checksum the file. install the .pkg with the installPkg method. @author: Roy Nielsen """ if sys.version_info < (2, 7): return success = False try: ##### # make sure the test .pkg is NOT installed self.pkgr.removePackage(self.macPackageName) except: pass ##### # Check the URL for validity, or make sure we can get there.. if self.connection.isPageAvailable(self.pkgUrl): ##### # Set the pkgurl in the package manager self.pkgr.setPkgUrl(self.pkgUrl) ##### # Download into a temporary directory success = self.pkgr.downloadPackage() if success: ##### # Apple operating systems have a lazy attitude towards # writing to disk - the package doesn't get fully # written to disk until the following method is called. # Otherwise when the downloaded package is further # manipulated, (uncompressed or installed) the # downloaded file is not there. There may be other # ways to get python to do the filesystem sync... try: self.libc.sync() except: pass ##### # Make sure the md5 of the file matches that of the # server if self.pkgr.checkMd5(): ##### # unarchive if necessary compressed = [".tar", ".tar.gz", ".tgz", ".tar.bz", ".tbz", ".zip"] for extension in compressed: if self.pkgUrl.endswith(extension): self.pkgr.unArchive() try: self.libc.sync() except: pass ##### # install - if extension is a .pkg or .mpkg use the # installer command if self.pkgUrl.endswith (".pkg") or \ self.pkgUrl.endswith (".mpkg"): success = self.pkgr.installPkg() self.assertTrue(success) else: self.assertTrue(False) else: self.assertTrue(False) else: self.assertTrue(False) else: self.logger.log(LogPriority.INFO, "Not able to connect to server...") self.assertTrue(True) if success: ##### # run checkInstall again self.assertTrue(self.pkgr.checkInstall(self.macPackageName)) self.assertTrue(self.isInstalled()) try: ##### # make sure the test .pkg is NOT installed self.pkgr.removePackage(self.macPackageName) except: pass ############################################################################ def testIsMacPlatform(self): """ Make sure we are on the Mac platform. @author: Roy Nielsen """ if sys.version_info < (2, 7): return if not self.connection.isPageAvailable(): self.logger.log(LogPriority.INFO, "This test fails without a " + \ "properly configured Mac " + \ "repository, so we are not " + \ "running actual tests...") else: self.assertTrue(self.environ.osfamily == "darwin", "Wrong OS...") ############################################################################ def isFullInstall(self): """ Make sure that all files and directories including those installed from the package and the postinstall script exist. @Note: In future, this should also do a receipt test as well. This would include getting the files from the receipt and checking for their existence and perhaps their permissions. @author: Roy Nielsen """ files = self.doFilesExistTest(self.all_files) dirs = self.doDirsExist(self.all_dirs) if files and dirs: return True return False ############################################################################ def isInstalled(self): """ Test to make sure just the files and directories installed by the package are installed. Doesn't care about the files and directories installed by the postinstall script. @author: Roy Nielsen """ files = self.doFilesExistTest([self.pkg_files]) dirs = self.doDirsExist([self.pkg_dirs]) if files and dirs: return True return False ############################################################################ def isMissing(self): """ Test to make sure all the files have been removed that were Installed by the package. Ignore, but note directories installed by the package that exist, as well as files and directories installed by the postinstall script. @Note: In future, this test should check for a package receipt, and make sure the files in the package receipt do not exist. This is only valid for this package, as in the case of some software, like Adobe products, some of the files are shared libraries between different products. @author: Roy Nielsen """ removed = [] exists = [] ##### # Cycle through each subset of files in the for myfile in self.pkg_files: if os.path.isfile(myfile): self.logger.log(LogPriority.WARNING, "File: " + \ str(myfile) + " exists...") removed.append(False) exists.append(myfile) self.assertFalse(False in removed, "Some files exist: " + str(exists)) ##### # cycle through each set of directories in all_dirs for myset in self.allowed_files_and_dirs: ##### # Cycle through each subset of files in the for myfile in myset: if os.path.isdir(myfile): self.logger.log(LogPriority.INFO, "Item: " + \ str(myfile) + " exists...") if False in removed: return False return True ############################################################################ def removeCompletePackage(self): """ Remove all files, used to set the stage for install tests. @author: Roy Nielsen """ success = False try: testPath = "/tmp/testStonixMacPkgr-0.0.3" if os.path.exists(testPath): shutil.rmtree(testPath) except Exception, err: self.logger.log(LogPriority.INFO, "Test set already missing?") raise err else: