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)
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())
def setUp(self): ''' ''' self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.commandhelper = CommandHelper(self.logger)
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')
def setUpClass(self): '''Test initializer''' self.environ = Environment() self.environ.setdebugmode(True) # Start timer in miliseconds self.test_start_time = datetime.now() self.logger = LogDispatcher(self.environ) self.logger.initializeLogs() self.sh = SHlaunchdTwo(self.environ, self.logger) self.logger.log(lp.DEBUG, "test " + __file__ + " initialized...")
def setUp(self): ''' Setup what we need for the test. @author: ekkehard j. koch @param self:essential if you override this definition ''' self.environ = Environment() self.environ.setverbosemode(True) self.environ.setdebugmode(True) self.config = Configuration(self.environ) self.logdispatch = LogDispatcher(self.environ) self.statechglogger = StateChgLogger(self.logdispatch, self.environ) self.rule = None self.rulename = "" self.rulenumber = ""
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")
class zzzTestFrameworkCommandHelper(unittest.TestCase): ''' Perform tests on different parts of the functionality for framework CommandHelper @param unittest.TestCase: unittest TestCase class inheritance object reference @author: ekkehard @change: Breen Malmberg - 04/11/2018 - removed assertion tests - you can't test for exception assertions in code that is wrapped by try except because the try except intercepts the exception and throws it and it never gets back to the assertraises call (see tf ticket for documentation) ''' def setUp(self): ''' ''' self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.commandhelper = CommandHelper(self.logger) def tearDown(self): ''' ''' pass def testExecuteValidCommand(self): ''' ''' self.assertTrue(self.commandhelper.executeCommand("ls -l /"), "Execute Valid Command string Failed!") self.assertTrue(self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute Valid Command List Failed!") def testSetLogPriority(self): ''' ''' self.assertTrue(self.commandhelper.setLogPriority(LogPriority.INFO), "Execute setLogPriority(0) Command string Failed!") self.assertTrue(self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute commandhelper.executeCommand(['ls','-l','/'])" + " Command List Failed!")
class zzzTestFrameworkCommandHelper(unittest.TestCase): def setUp(self): self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.commandhelper = CommandHelper(self.logger) def tearDown(self): pass def testBlankCommand(self): self.assertRaises(ValueError, self.commandhelper.setCommand, "") self.assertRaises(TypeError, self.commandhelper.executeCommand, None) self.assertRaises(ValueError, self.commandhelper.executeCommand, "") self.assertRaises(ValueError, self.commandhelper.setCommand, []) self.assertRaises(TypeError, self.commandhelper.executeCommand, None) self.assertRaises(ValueError, self.commandhelper.executeCommand, []) def testExecuteValidCommand(self): self.assertTrue(self.commandhelper.executeCommand("ls -l /"), "Execute Valid Command string Failed!") self.assertTrue(self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute Valid Command List Failed!") def testExecuteInvalidCommand(self): self.assertRaises(TypeError, self.commandhelper.executeCommand, 0) self.assertRaises(TypeError, self.commandhelper.executeCommand, ['ls', 0, '/']) def testSetLogPriority(self): self.assertRaises(TypeError, self.commandhelper.setLogPriority, 0) self.assertTrue(self.commandhelper.setLogPriority(LogPriority.INFO), "Execute setLogPriority(0) Command string Failed!") self.assertTrue(self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute commandhelper.executeCommand(['ls','-l','/'])" + " Command List Failed!")
class zzzTestFrameworkCommandHelper(unittest.TestCase): def setUp(self): self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.commandhelper = CommandHelper(self.logger) def tearDown(self): pass def testBlankCommand(self): self.assertRaises(ValueError, self.commandhelper.setCommand, "") self.assertRaises(TypeError, self.commandhelper.executeCommand, None) self.assertRaises(ValueError, self.commandhelper.executeCommand, "") self.assertRaises(ValueError, self.commandhelper.setCommand, []) self.assertRaises(TypeError, self.commandhelper.executeCommand, None) self.assertRaises(ValueError, self.commandhelper.executeCommand, []) def testExecuteValidCommand(self): self.assertTrue(self.commandhelper.executeCommand("ls -l /"), "Execute Valid Command string Failed!") self.assertTrue(self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute Valid Command List Failed!") def testExecuteInvalidCommand(self): self.assertRaises(TypeError, self.commandhelper.executeCommand, 0) self.assertRaises(TypeError, self.commandhelper.executeCommand, ['ls', 0, '/']) def testSetLogPriority(self): self.assertRaises(TypeError, self.commandhelper.setLogPriority, 0) self.assertTrue(self.commandhelper.setLogPriority(LogPriority.INFO), "Execute setLogPriority(0) Command string Failed!") self.assertTrue( self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute commandhelper.executeCommand(['ls','-l','/'])" + " Command List Failed!")
def setUp(self): self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.ch = CommandHelper(self.logger) self.changedDir = False # stonixtest must currently be run from the stonixroot directory, so # that is the best bet for the cwd if os.path.exists("src/Macbuild"): os.chdir("src/Macbuild") self.changedDir = True # Cannot guarantee that test will end in self.myDir = os.getcwd() # this dir, so we record it first self.mb = build.SoftwareBuilder(options=optparse.Values({ "compileGui": True, "version": "0.dev-UT", "clean": False, "test": True }))
class zzzTestFrameworkCommandHelper(unittest.TestCase): '''Perform tests on different parts of the functionality for framework CommandHelper :param unittest: TestCase: unittest TestCase class inheritance object reference @author: ekkehard @change: Breen Malmberg - 04/11/2018 - removed assertion tests - you can't test for exception assertions in code that is wrapped by try except because the try except intercepts the exception and throws it and it never gets back to the assertraises call (see tf ticket for documentation) ''' def setUp(self): ''' ''' self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.commandhelper = CommandHelper(self.logger) def tearDown(self): ''' ''' pass def testExecuteValidCommand(self): ''' ''' self.assertTrue(self.commandhelper.executeCommand("ls -l /"), "Execute Valid Command string Failed!") self.assertTrue(self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute Valid Command List Failed!") def testSetLogPriority(self): ''' ''' self.assertTrue(self.commandhelper.setLogPriority(LogPriority.INFO), "Execute setLogPriority(0) Command string Failed!") self.assertTrue( self.commandhelper.executeCommand(["ls", "-l", "/"]), "Execute commandhelper.executeCommand(['ls','-l','/'])" + " Command List Failed!")
def setUp(self): kvpath = "/tmp/kvaconfUT" open(kvpath, "w").write("I'm a test file!") kvpath2 = "/tmp/sysctl.bak" open(kvpath2, "w").write("I'm another test file!") env = Environment() logger = LogDispatcher(env) scl = StateChgLogger(logger, env) self.editor = KVEditorStonix.KVEditorStonix(scl, logger, "conf", kvpath, kvpath + ".tmp", {}, "present", "openeq")
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 setUpClass(self): ''' Test initializer ''' self.environ = Environment() self.environ.setdebugmode(True) # Start timer in miliseconds self.test_start_time = datetime.now() self.logger = LogDispatcher(self.environ) self.logger.initializeLogs() self.sh = SHlaunchdTwo(self.environ, self.logger) self.logger.log(lp.DEBUG, "test " + __file__ + " initialized...")
def setUp(self): self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.ch = CommandHelper(self.logger) self.changedDir = False # stonixtest must currently be run from the stonixroot directory, so # that is the best bet for the cwd if os.path.exists("src/Macbuild"): os.chdir("src/Macbuild") self.changedDir = True # Cannot guarantee that test will end in self.myDir = os.getcwd() # this dir, so we record it first self.mb = build.SoftwareBuilder(options=optparse.Values({"compileGui": True, "version": "0.dev-UT", "clean": False, "test": True}))
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 setUp(self): '''set up handlers and objects and any other conditions for use in the class''' self.environ = Environment() self.logger = LogDispatcher(self.environ) # build proxy (if needed), handlers and opener for urllib2.urlopen connections context = ssl._create_unverified_context() if PROXY: proxy = urllib.request.ProxyHandler({ "http": PROXY, "https": PROXY }) opener = urllib.request.build_opener( urllib.request.HTTPHandler(), urllib.request.HTTPSHandler(context=context), proxy) else: opener = urllib.request.build_opener( urllib.request.HTTPHandler(), urllib.request.HTTPSHandler(context=context)) urllib.request.install_opener(opener)
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)
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))
def setUp(self): ''' ''' self.environ = Environment() self.logdispatcher = LogDispatcher(self.environ) self.conn = Connectivity(self.logdispatcher, use_proxy=True)
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" ############################################################################ """
class zzzTestFrameworkmacbuild(unittest.TestCase): def setUp(self): self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.ch = CommandHelper(self.logger) self.changedDir = False # stonixtest must currently be run from the stonixroot directory, so # that is the best bet for the cwd if os.path.exists("src/Macbuild"): os.chdir("src/Macbuild") self.changedDir = True # Cannot guarantee that test will end in self.myDir = os.getcwd() # this dir, so we record it first self.mb = build.SoftwareBuilder(options=optparse.Values({ "compileGui": True, "version": "0.dev-UT", "clean": False, "test": True })) def tearDown(self): if self.changedDir: os.chdir(self.myDir) self.ch.executeCommand(["./build.py", "-c"]) os.chdir("../..") def testSetupAndDetachRamdisk(self): path = "/tmp/mount_ramdisk_for_ut" if os.path.exists(path): rmtree(path) os.mkdir(path) device = self.mb.setupRamdisk(512, path) self.assertRegex(device, "/dev/disk\d+", "Unexpected return from setupRamdisk") self.assertTrue(self.mb.detachRamdisk(device), "Did not successfully detach ramdisk") def testExitMethod(self): ramdiskPath = "/tmp/mount_ramdisk_for_ut" luggagePath = "/tmp/luggage_ramdisk_for_ut" ramdisk = self.mb.setupRamdisk(1024, ramdiskPath) luggage = self.mb.setupRamdisk(1024, luggagePath) self.assertRaises(SystemExit, self.mb.exit, ramdisk, luggage, 999) def testCompileStonix4MacAppUiFilesMethod(self): self.mb.compileStonix4MacAppUiFiles("./stonix4mac") try: adminCred = open("stonix4mac/admin_credentials_ui.py", "r").read() stonixWrapper = open("stonix4mac/stonix_wrapper_ui.py", "r").read() generalWarning = open("stonix4mac/general_warning_ui.py", "r").read() except OSError: self.assertTrue(False, "One or more UI files could not be found") else: self.assertTrue(adminCred, "admin_credentials_ui.py file is empty") self.assertTrue(stonixWrapper, "stonix_wrapper_ui.py file is empty") self.assertTrue(generalWarning, "general_warning_ui.py file is empty") self.assertRaises(OSError, self.mb.compileStonix4MacAppUiFiles, "thisdirdoesnotexist") def testSetProgramArgumentsVersionMethod(self): path = "../stonix_resources/localize.py" self.mb.setProgramArgumentsVersion(path) version = self.mb.APPVERSION localizeContents = open(path, "r").read() self.assertTrue(re.search(version, localizeContents), "Could not find correct version in localize.py") self.assertRaises(IOError, self.mb.setProgramArgumentsVersion, "badpath.py") def testPrepStonixBuildMethod(self): self.mb.prepStonixBuild(".") stonixDirList = os.listdir("stonix") self.assertTrue(stonixDirList, "No files found in stonix directory") self.assertRaises(OSError, self.mb.prepStonixBuild, "thisdirisfake") def testDriverAndBuildMethods(self): # Due to issues with dependencies, several methods cannot be easily # tested as units. Therefore, the "driver" method is run, and artifacts # from each method are checked. self.mb.driver() # Check compileApp artifacts try: stonixSpec = open("stonix/stonix.spec", "r").read() stonix4macSpec = open("stonix4mac/stonix4mac.spec", "r").read() except IOError: self.assertTrue(False, "One or more spec files not found") else: self.assertTrue(stonixSpec, "stonix.spec file is empty") self.assertTrue(stonix4macSpec, "stonix4mac.spec file is empty") # Check buildStonix4MacAppResources artifacts self.assertTrue( os.path.exists("stonix4mac/dist/stonix4mac.app/" + "Contents/Resources/stonix.conf"), "Could not find stonix.conf file in package") self.assertTrue( os.path.exists("stonix4mac/dist/stonix4mac.app/" + "Contents/Resources/stonix.app"), "Could not find stonix.app in stonix4mac.app Resources") # Check buildStonix4MacAppPkg artifacts self.assertTrue(os.path.exists("dmgs/stonix4mac-0.dev-UT.pkg"), "Could not find stonix4mac pkg file")
class RuleTest(unittest.TestCase): def setUp(self): '''Setup what we need for the test. @author: ekkehard j. koch :param self: essential if you override this definition ''' self.environ = Environment() self.environ.setverbosemode(True) self.environ.setdebugmode(True) self.config = Configuration(self.environ) self.logdispatch = LogDispatcher(self.environ) self.statechglogger = StateChgLogger(self.logdispatch, self.environ) self.rule = None self.rulename = "" self.rulenumber = "" self.checkUndo = False self.ignoreresults = False ############################################################################### def tearDown(self): '''Release anything we no longer need what we need for the test. @author: ekkehard j. koch :param self: essential if you override this definition ''' pass ############################################################################### def simpleRuleTest(self): '''Run a simple Report, Fix, Report Cycle @author: ekkehard j. koch :param self: essential if you override this definition ''' nextstep = True prefixHeadline = "################################################### " prefixRuleInfo = self.rulename + "(" + str(self.rulenumber) + "): " messagestring = "" # Make Rule Is supposed to run in this environment if nextstep: messagestring = "Make sure Rule Is supposed to run in this " + \ "environment" self.logdispatch.log( LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) isapplicable = self.rule.isapplicable() messagestring = "rule.isapplicable() = " + str(isapplicable) self.logdispatch.log(LogPriority.DEBUG, prefixRuleInfo + messagestring) valueIsInList = isapplicable in [True, False] messagestring = "Invalid isapplicable Type!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) messagestring = "rule.isapplicable() = " + str(isapplicable) + \ " and should be True." self.assertTrue(isapplicable, prefixRuleInfo + messagestring) nextstep = isapplicable # Check to see if we are running in the right context if nextstep: messagestring = "Check to see if we are running in the " + \ "right context" self.logdispatch.log( LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) effectiveUserID = self.environ.geteuid() messagestring = "environ.geteuid() = " + str(effectiveUserID) self.logdispatch.log(LogPriority.DEBUG, prefixRuleInfo + messagestring) isRootRequired = self.rule.getisrootrequired() messagestring = "rule.getisrootrequired() = " + str(isRootRequired) self.logdispatch.log(LogPriority.DEBUG, prefixRuleInfo + messagestring) if effectiveUserID == 0 and isRootRequired: nextstep = True elif not isRootRequired: nextstep = True else: nextstep = False messagestring = "Rule requires root and effective uid ='" + \ str(effectiveUserID) + "'" self.assertTrue(nextstep, prefixRuleInfo + messagestring) # Run setConditionsForRule to configure system for test if nextstep: messagestring = "Run setConditionsForRule to configure " + \ "system for test" self.logdispatch.log( LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) setTestConditions = self.setConditionsForRule() self.logdispatch.log( LogPriority.DEBUG, "setConditionsForRule()" + " = " + str(setTestConditions)) if setTestConditions: nextstep = True else: nextstep = False messagestring = "setConditionsForRule() = " + \ str(setTestConditions) + "." self.assertTrue(setTestConditions, prefixRuleInfo + messagestring) # Run rule.report() if nextstep: messagestring = "Run rule.report()" self.logdispatch.log( LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) report = self.rule.report() self.logdispatch.log(LogPriority.DEBUG, "rule.report() = " + str(report)) rulesuccess = self.rule.getrulesuccess() originalResults = self.rule.getdetailedresults() self.logdispatch.log(LogPriority.DEBUG, "rule.getrulesuccess() = " + str(rulesuccess)) valueIsInList = rulesuccess in [True, False] messagestring = "Invalid rule.getrulesuccess() Value'" + \ str(rulesuccess) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) if not rulesuccess: nextstep = False messagestring = ": rule.getrulesuccess() is '" + \ str(rulesuccess) + "'" self.assertTrue(rulesuccess, prefixRuleInfo + messagestring) rulecompliance = self.rule.iscompliant() self.logdispatch.log(LogPriority.DEBUG, "rule.iscompliant() = " + str(rulecompliance)) valueIsInList = rulecompliance in [True, False] messagestring = "Invalid rule.iscompliant() Value'" + \ str(rulecompliance) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) # Run checkReportForRule() messagestring = "Run checkReportForRule(" + str(rulecompliance) + \ ", " + str(rulesuccess) + ")" self.logdispatch.log( LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) checkReportConditions = self.checkReportForRule( rulecompliance, rulesuccess) self.logdispatch.log( LogPriority.DEBUG, "checkReportForRule() = " + str(checkReportConditions)) if checkReportConditions and not rulecompliance: nextstep = True else: nextstep = False messagestring = ": Rule checkReportForRule() = " + \ str(checkReportConditions) + "." self.assertTrue( checkReportConditions, self.rulename + "(" + str(self.rulenumber) + "): Rule checkReportForRule() = " + str(checkReportConditions) + ".") # Run rule.fix() if nextstep: messagestring = "Run rule.fix()" self.logdispatch.log( LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) fix = self.rule.fix() self.logdispatch.log(LogPriority.DEBUG, "rule.fix() = " + str(fix)) rulesuccess = self.rule.getrulesuccess() self.logdispatch.log(LogPriority.DEBUG, "rule.getrulesuccess() = " + str(rulesuccess)) valueIsInList = rulesuccess in [True, False] messagestring = "Invalid rule.rulesuccess() Value'" + \ str(rulesuccess) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) messagestring = "rule.getrulesuccess() = '" + \ str(rulesuccess) + "'" self.assertTrue(rulesuccess, prefixRuleInfo + messagestring) # Run checkFixForRule() messagestring = "Run checkFixForRule(" + str(rulesuccess) + ")" self.logdispatch.log( LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) checkFixConditions = self.checkFixForRule(rulesuccess) self.logdispatch.log( LogPriority.DEBUG, "checkFixForRule(" + str(rulesuccess) + ")" + " = " + str(checkFixConditions)) if checkFixConditions and rulesuccess: nextstep = True else: nextstep = False messagestring = "Rule checkFixForRule() = " + \ str(checkFixConditions) + "." self.assertTrue(nextstep, prefixRuleInfo + messagestring) # Run rule.report() if nextstep: messagestring = "Run rule.report()" self.logdispatch.log( LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) report = self.rule.report() self.logdispatch.log(LogPriority.DEBUG, "rule.report() = " + str(report)) rulesuccess = self.rule.getrulesuccess() self.logdispatch.log(LogPriority.DEBUG, "rule.getrulesuccess() = " + str(rulesuccess)) valueIsInList = rulesuccess in [True, False] messagestring = "Invalid rule.getrulesuccess() Value'" + \ str(rulesuccess) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) if not rulesuccess: nextstep = False self.assertTrue( rulesuccess, self.rulename + "(" + str(self.rulenumber) + "): rule.getrulesuccess() is '" + str(rulesuccess) + "' with reported error '" + str(self.rule.getdetailedresults()) + "'") rulecompliance = self.rule.iscompliant() self.logdispatch.log(LogPriority.DEBUG, "rule.iscompliant() = " + str(rulecompliance)) valueIsInList = rulecompliance in [True, False] messagestring = "Invalid rule.iscompliant() Value'" + \ str(rulecompliance) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) messagestring = "rule.iscompliant() is '" + \ str(rulecompliance) + "' after rule.fix() and " + \ "rule.report() have run." if not self.ignoreresults: self.assertTrue(rulecompliance, prefixRuleInfo + messagestring) # Run checkReportFinalForRule() messagestring = "Run checkReportFinalForRule(" + \ str(rulecompliance) + ", " + str(rulesuccess) + ")" self.logdispatch.log( LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) checkReportFinalConditions = self.checkReportFinalForRule( rulecompliance, rulesuccess) self.logdispatch.log( LogPriority.DEBUG, "checkReportFinalForRule() = " + str(checkReportFinalConditions)) if checkReportFinalConditions and rulecompliance: nextstep = True else: nextstep = False self.assertTrue( checkReportFinalConditions, self.rulename + "(" + str(self.rulenumber) + "): Rule checkReportFinalForRule() = " + str(checkReportFinalConditions) + ".") # Run rule.undo() if nextstep and self.checkUndo: messagestring = "Run rule.undo()" self.logdispatch.log( LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) undo = self.rule.undo() self.logdispatch.log(LogPriority.DEBUG, "rule.undo() = " + str(undo)) self.rule.report() postUndoResults = self.rule.getdetailedresults() # In order to get detailed, well-formatted error information, this # has been turned into a short procedure to produce the most # helpful information, rather than simply using the assert # statement if originalResults != postUndoResults: orlines = originalResults.splitlines() pulines = postUndoResults.splitlines() orlinestmp = orlines[:] # [:] to copy by value r/t reference for line in orlinestmp: if line in pulines: orlines.remove(line) pulines.remove(line) error = "After undo, the report results were not the same " + \ "as the initial pre-fix report." if orlines: error += "\nOnly in original:\n" + "\n".join(orlines) if pulines: error += "\nOnly in post-undo:\n" + "\n".join(pulines) self.assertTrue(False, error) # Run checkUndoForRule() messagestring = "Run checkUndoForRule(" + str(rulesuccess) + ")" self.logdispatch.log( LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) checkUndoConditions = self.checkUndoForRule(rulesuccess) self.logdispatch.log( LogPriority.DEBUG, "checkUndoForRule()" + " = " + str(checkUndoConditions)) if checkUndoConditions and not rulecompliance: nextstep = True else: nextstep = False self.assertTrue( checkUndoConditions, self.rulename + "(" + str(self.rulenumber) + "): Rule checkUndoForRule() = " + str(checkUndoConditions) + ".") return nextstep ############################################################################### def setConditionsForRule(self): return True ############################################################################### def checkReportForRule(self, pCompliance, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") return True ############################################################################### def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") return True ############################################################################### def checkReportFinalForRule(self, pCompliance, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") return True ############################################################################### def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") return True ############################################################################### def setCheckUndo(self, checkUndo): self.checkUndo = checkUndo ############################################################################### def getCheckUndo(self): return self.checkUndo ############################################################################### def runDestructive(self): return os.path.exists("/etc/stonix-destructive")
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 """ 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))
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()
class RuleTest(unittest.TestCase): ############################################################################### def setUp(self): ''' Setup what we need for the test. @author: ekkehard j. koch @param self:essential if you override this definition ''' self.environ = Environment() self.environ.setverbosemode(True) self.environ.setdebugmode(True) self.config = Configuration(self.environ) self.logdispatch = LogDispatcher(self.environ) self.statechglogger = StateChgLogger(self.logdispatch, self.environ) self.rule = None self.rulename = "" self.rulenumber = "" ############################################################################### def tearDown(self): ''' Release anything we no longer need what we need for the test. @author: ekkehard j. koch @param self:essential if you override this definition ''' pass ############################################################################### def simpleRuleTest(self): ''' Run a simple Report, Fix, Report Cycle @author: ekkehard j. koch @param self:essential if you override this definition ''' nextstep = True prefixHeadline = "################################################### " prefixRuleInfo = self.rulename + "(" + str(self.rulenumber) + "): " messagestring = "" # Make Rule Is supposed to run in this environment if nextstep: messagestring = "Make sure Rule Is supposed to run in this " + \ "environment" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) isapplicable = self.rule.isapplicable() messagestring = "rule.isapplicable() = " + str(isapplicable) self.logdispatch.log(LogPriority.DEBUG, prefixRuleInfo + \ messagestring) valueIsInList = isapplicable in [True, False] messagestring = "Invalid isapplicable Type!" self.assertTrue(valueIsInList, prefixRuleInfo + \ messagestring) messagestring = "rule.isapplicable() = " + str(isapplicable) + \ " and should be True." self.assertTrue(isapplicable, prefixRuleInfo + \ messagestring) nextstep = isapplicable # Check to see if we are running in the right context if nextstep: messagestring = "Check to see if we are running in the " + \ "right context" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) effectiveUserID = self.environ.geteuid() messagestring = "environ.geteuid() = " + str(effectiveUserID) self.logdispatch.log(LogPriority.DEBUG, prefixRuleInfo + \ messagestring) isRootRequired = self.rule.getisrootrequired() messagestring = "rule.getisrootrequired() = " + str(isRootRequired) self.logdispatch.log(LogPriority.DEBUG, prefixRuleInfo + \ messagestring) if effectiveUserID == 0 and isRootRequired: nextstep = True elif not isRootRequired: nextstep = True else: nextstep = False messagestring = "Rule requires root and effective uid ='" + \ str(effectiveUserID) + "'" self.assertTrue(nextstep, prefixRuleInfo + \ messagestring) # Run setConditionsForRule to configure system for test if nextstep: messagestring = "Run setConditionsForRule to configure " + \ "system for test" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) setTestConditions = self.setConditionsForRule() self.logdispatch.log(LogPriority.DEBUG, "setConditionsForRule()" + \ " = " + \ str(setTestConditions)) if setTestConditions: nextstep = True else: nextstep = False messagestring = "setConditionsForRule() = " + \ str(setTestConditions) + "." self.assertTrue(setTestConditions, prefixRuleInfo + \ messagestring) # Run rule.report() if nextstep: messagestring = "Run rule.report()" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) report = self.rule.report() self.logdispatch.log(LogPriority.DEBUG, "rule.report() = " + \ str(report)) rulesuccess = self.rule.getrulesuccess() self.logdispatch.log(LogPriority.DEBUG, "rule.getrulesuccess() = " + \ str(rulesuccess)) valueIsInList = rulesuccess in [True, False] messagestring = "Invalid rule.getrulesuccess() Value'" + \ str(rulesuccess) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) if not rulesuccess: nextstep = False messagestring = ": rule.getrulesuccess() is '" + \ str(rulesuccess) + "'" self.assertTrue(rulesuccess, prefixRuleInfo + messagestring) rulecompliance = self.rule.iscompliant() self.logdispatch.log(LogPriority.DEBUG, "rule.iscompliant() = " + \ str(rulecompliance)) valueIsInList = rulecompliance in [True, False] messagestring = "Invalid rule.iscompliant() Value'" + \ str(rulecompliance) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) # Run checkReportForRule() messagestring = "Run checkReportForRule(" + str(rulecompliance) + \ ", " + str(rulesuccess) + ")" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) checkReportConditions = self.checkReportForRule(rulecompliance, rulesuccess) self.logdispatch.log(LogPriority.DEBUG, "checkReportForRule()" + \ " = " + \ str(checkReportConditions)) if checkReportConditions and not rulecompliance: nextstep = True else: nextstep = False messagestring = ": Rule checkReportForRule() = " + \ str(checkReportConditions) + "." self.assertTrue(checkReportConditions, prefixRuleInfo + \ messagestring) self.assertTrue(checkReportConditions, self.rulename + "(" + str(self.rulenumber) + ")" + ": Rule " + \ "checkReportForRule() = " + \ str(checkReportConditions) + ".") # Run rule.fix() if nextstep: messagestring = "Run rule.fix()" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) fix = self.rule.fix() self.logdispatch.log(LogPriority.DEBUG, "rule.fix() = " + \ str(fix)) rulesuccess = self.rule.getrulesuccess() self.logdispatch.log(LogPriority.DEBUG, "rule.getrulesuccess() = " + \ str(rulesuccess)) valueIsInList = rulesuccess in [True, False] messagestring = "Invalid rule.rulesuccess() Value'" + \ str(rulesuccess) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) messagestring = "rule.getrulesuccess() = '" + \ str(rulesuccess) + "'" self.assertTrue(rulesuccess, prefixRuleInfo + messagestring) # Run checkFixForRule() messagestring = "Run checkFixForRule(" + str(rulesuccess) + ")" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) checkFixConditions = self.checkFixForRule(rulesuccess) self.logdispatch.log(LogPriority.DEBUG, "checkFixForRule(" + str(rulesuccess) + \ ")" + " = " + \ str(checkFixConditions)) if checkFixConditions and rulesuccess: nextstep = True else: nextstep = False messagestring = "Rule checkFixForRule() = " + \ str(checkFixConditions) + "." self.assertTrue(nextstep, prefixRuleInfo + messagestring) # Run rule.report() if nextstep: messagestring = "Run rule.report()" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) report = self.rule.report() self.logdispatch.log(LogPriority.DEBUG, "rule.report() = " + \ str(report)) rulesuccess = self.rule.getrulesuccess() self.logdispatch.log(LogPriority.DEBUG, "rule.getrulesuccess() = " + \ str(rulesuccess)) valueIsInList = rulesuccess in [True, False] messagestring = "Invalid rule.getrulesuccess() Value'" + \ str(rulesuccess) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) if not rulesuccess: nextstep = False self.assertTrue(rulesuccess, self.rulename + "(" + str(self.rulenumber) + ")" + ": rule.getrulesuccess() is '" + \ str(rulesuccess) + "' with reported error '" + \ str(self.rule.getdetailedresults())) rulecompliance = self.rule.iscompliant() self.logdispatch.log(LogPriority.DEBUG, "rule.iscompliant() = " + \ str(rulecompliance)) valueIsInList = rulecompliance in [True, False] messagestring = "Invalid rule.iscompliant() Value'" + \ str(rulecompliance) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) messagestring = "rule.iscompliant() is '" + \ str(rulecompliance) + "' after rule.fix() and rule.report() " + \ "have run." self.assertTrue(rulecompliance, prefixRuleInfo + messagestring) if rulecompliance: nextstep = False return nextstep ############################################################################### def setConditionsForRule(self): return True ############################################################################### def checkReportForRule(self, pCompliance, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \ str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") return True ############################################################################### def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") return True ############################################################################### def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") return True
def setUp(self): self.environ = Environment() self.logdispatcher = LogDispatcher(self.environ) self.conn = Connectivity(self.logdispatcher)
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:
import filecmp import unittest from distutils.version import LooseVersion sys.path.append("../../../..") from src.stonix_resources.FileStateManager import FileStateManager from src.stonix_resources.environment import Environment from src.stonix_resources.CommandHelper import CommandHelper from src.tests.lib.logdispatcher_lite import LogDispatcher, LogPriority from src.stonix_resources.get_libc import getLibc lp = LogPriority LIBC = getLibc() environ = Environment() environ.stonixversion = "1.2.3" logger = LogDispatcher(debug_mode=True) logger.initializeLogs("/tmp/zzzTestFrameworkFileStateManager", extension_type="time", syslog=False, myconsole=False) class NotApplicableToThisOS(Exception): """ Custom Exception """ def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class zzzTestFrameworkFileStateManager(unittest.TestCase): """ Class for testing the FileStateManager.
class zzzTestFrameworkSHlaunchdTwoHelperMethods(unittest.TestCase): '''Test the launchd version 2 service helper. @author: Roy Nielsen ''' @classmethod def setUpClass(self): '''Test initializer''' self.environ = Environment() self.environ.setdebugmode(True) # Start timer in miliseconds self.test_start_time = datetime.now() self.logger = LogDispatcher(self.environ) self.logger.initializeLogs() self.sh = SHlaunchdTwo(self.environ, self.logger) self.logger.log(lp.DEBUG, "test " + __file__ + " initialized...") def test_isValidServicePath(self): ''' ''' for test_key, test_values in list(service_path_test_data.items()): if re.match("^valid_service_paths", test_key): for test_item in test_values: self.assertTrue( self.sh.isValidServicePath(test_item), "Invalid service path: " + str(test_item)) if re.match("^invalid_service_paths", test_key): for test_item in test_values: self.assertFalse( self.sh.isValidServicePath(test_item), "Valid service path: " + str(test_item)) def test_getServiceNameFromService(self): ''' ''' for test_key, test_values in list( name_from_service_test_data.items()): if re.match("^valid_service_plists", test_key): for test_item in test_values: self.assertTrue( self.sh.isValidServicePath(test_item), "Invalid service plist: " + str(test_item)) if re.match("^invalid_service_plists", test_key): for test_item in test_values: self.assertFalse( self.sh.isValidServicePath(test_item), "Valid service plist: " + str(test_item)) def test_targetValid(self): ''' ''' for test_key, test_values in list(target_valid_test_data.items()): if re.match("^valid_target_data", test_key): for test_item in test_values: params = { test_item[1]['serviceName'][0]: test_item[1]['serviceName'][1] } self.assertEqual( self.sh.targetValid(test_item[0], **params), test_item[2], "Target data: " + str(test_item) + " is not valid.") if re.match("^invalid_target_data", test_key): for test_item in test_values: params = { test_item[1]['serviceName'][0]: test_item[1]['serviceName'][1] } self.assertNotEqual( self.sh.targetValid(test_item[0], **params), test_item[2], "Target data: " + str(test_item) + " is good!") @classmethod def tearDownClass(self): '''Test destructor''' ##### # 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( lp.DEBUG, self.__module__ + " took " + str(test_time) + " time to complete...")
class RuleTest(unittest.TestCase): ############################################################################### def setUp(self): ''' Setup what we need for the test. @author: ekkehard j. koch @param self:essential if you override this definition ''' self.environ = Environment() self.environ.setverbosemode(True) self.environ.setdebugmode(True) self.config = Configuration(self.environ) self.logdispatch = LogDispatcher(self.environ) self.statechglogger = StateChgLogger(self.logdispatch, self.environ) self.rule = None self.rulename = "" self.rulenumber = "" ############################################################################### def tearDown(self): ''' Release anything we no longer need what we need for the test. @author: ekkehard j. koch @param self:essential if you override this definition ''' pass ############################################################################### def simpleRuleTest(self): ''' Run a simple Report, Fix, Report Cycle @author: ekkehard j. koch @param self:essential if you override this definition ''' nextstep = True prefixHeadline = "################################################### " prefixRuleInfo = self.rulename + "(" + str(self.rulenumber) + "): " messagestring = "" # Make Rule Is supposed to run in this environment if nextstep: messagestring = "Make sure Rule Is supposed to run in this " + \ "environment" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) isapplicable = self.rule.isapplicable() messagestring = "rule.isapplicable() = " + str(isapplicable) self.logdispatch.log(LogPriority.DEBUG, prefixRuleInfo + \ messagestring) valueIsInList = isapplicable in [True, False] messagestring = "Invalid isapplicable Type!" self.assertTrue(valueIsInList, prefixRuleInfo + \ messagestring) messagestring = "rule.isapplicable() = " + str(isapplicable) + \ " and should be True." self.assertTrue(isapplicable, prefixRuleInfo + \ messagestring) nextstep = isapplicable # Check to see if we are running in the right context if nextstep: messagestring = "Check to see if we are running in the " + \ "right context" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) effectiveUserID = self.environ.geteuid() messagestring = "environ.geteuid() = " + str(effectiveUserID) self.logdispatch.log(LogPriority.DEBUG, prefixRuleInfo + \ messagestring) isRootRequired = self.rule.getisrootrequired() messagestring = "rule.getisrootrequired() = " + str(isRootRequired) self.logdispatch.log(LogPriority.DEBUG, prefixRuleInfo + \ messagestring) if effectiveUserID == 0 and isRootRequired: nextstep = True elif not isRootRequired: nextstep = True else: nextstep = False messagestring = "Rule requires root and effective uid ='" + \ str(effectiveUserID) + "'" self.assertTrue(nextstep, prefixRuleInfo + \ messagestring) # Run setConditionsForRule to configure system for test if nextstep: messagestring = "Run setConditionsForRule to configure " + \ "system for test" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) setTestConditions = self.setConditionsForRule() self.logdispatch.log(LogPriority.DEBUG, "setConditionsForRule()" + \ " = " + \ str(setTestConditions)) if setTestConditions: nextstep = True else: nextstep = False messagestring = "setConditionsForRule() = " + \ str(setTestConditions) + "." self.assertTrue(setTestConditions, prefixRuleInfo + \ messagestring) # Run rule.report() if nextstep: messagestring = "Run rule.report()" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) report = self.rule.report() self.logdispatch.log(LogPriority.DEBUG, "rule.report() = " + \ str(report)) rulesuccess = self.rule.getrulesuccess() self.logdispatch.log(LogPriority.DEBUG, "rule.getrulesuccess() = " + \ str(rulesuccess)) valueIsInList = rulesuccess in [True, False] messagestring = "Invalid rule.getrulesuccess() Value'" + \ str(rulesuccess) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) if not rulesuccess: nextstep = False messagestring = ": rule.getrulesuccess() is '" + \ str(rulesuccess) + "'" self.assertTrue(rulesuccess, prefixRuleInfo + messagestring) rulecompliance = self.rule.iscompliant() self.logdispatch.log(LogPriority.DEBUG, "rule.iscompliant() = " + \ str(rulecompliance)) valueIsInList = rulecompliance in [True, False] messagestring = "Invalid rule.iscompliant() Value'" + \ str(rulecompliance) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) # Run checkReportForRule() messagestring = "Run checkReportForRule(" + str(rulecompliance) + \ ", " + str(rulesuccess) + ")" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) checkReportConditions = self.checkReportForRule( rulecompliance, rulesuccess) self.logdispatch.log(LogPriority.DEBUG, "checkReportForRule()" + \ " = " + \ str(checkReportConditions)) if checkReportConditions and not rulecompliance: nextstep = True else: nextstep = False messagestring = ": Rule checkReportForRule() = " + \ str(checkReportConditions) + "." self.assertTrue(checkReportConditions, prefixRuleInfo + \ messagestring) self.assertTrue(checkReportConditions, self.rulename + "(" + str(self.rulenumber) + ")" + ": Rule " + \ "checkReportForRule() = " + \ str(checkReportConditions) + ".") # Run rule.fix() if nextstep: messagestring = "Run rule.fix()" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) fix = self.rule.fix() self.logdispatch.log(LogPriority.DEBUG, "rule.fix() = " + \ str(fix)) rulesuccess = self.rule.getrulesuccess() self.logdispatch.log(LogPriority.DEBUG, "rule.getrulesuccess() = " + \ str(rulesuccess)) valueIsInList = rulesuccess in [True, False] messagestring = "Invalid rule.rulesuccess() Value'" + \ str(rulesuccess) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) messagestring = "rule.getrulesuccess() = '" + \ str(rulesuccess) + "'" self.assertTrue(rulesuccess, prefixRuleInfo + messagestring) # Run checkFixForRule() messagestring = "Run checkFixForRule(" + str(rulesuccess) + ")" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) checkFixConditions = self.checkFixForRule(rulesuccess) self.logdispatch.log(LogPriority.DEBUG, "checkFixForRule(" + str(rulesuccess) + \ ")" + " = " + \ str(checkFixConditions)) if checkFixConditions and rulesuccess: nextstep = True else: nextstep = False messagestring = "Rule checkFixForRule() = " + \ str(checkFixConditions) + "." self.assertTrue(nextstep, prefixRuleInfo + messagestring) # Run rule.report() if nextstep: messagestring = "Run rule.report()" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + \ prefixRuleInfo + messagestring) report = self.rule.report() self.logdispatch.log(LogPriority.DEBUG, "rule.report() = " + \ str(report)) rulesuccess = self.rule.getrulesuccess() self.logdispatch.log(LogPriority.DEBUG, "rule.getrulesuccess() = " + \ str(rulesuccess)) valueIsInList = rulesuccess in [True, False] messagestring = "Invalid rule.getrulesuccess() Value'" + \ str(rulesuccess) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) if not rulesuccess: nextstep = False self.assertTrue(rulesuccess, self.rulename + "(" + str(self.rulenumber) + ")" + ": rule.getrulesuccess() is '" + \ str(rulesuccess) + "' with reported error '" + \ str(self.rule.getdetailedresults())) rulecompliance = self.rule.iscompliant() self.logdispatch.log(LogPriority.DEBUG, "rule.iscompliant() = " + \ str(rulecompliance)) valueIsInList = rulecompliance in [True, False] messagestring = "Invalid rule.iscompliant() Value'" + \ str(rulecompliance) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) messagestring = "rule.iscompliant() is '" + \ str(rulecompliance) + "' after rule.fix() and rule.report() " + \ "have run." self.assertTrue(rulecompliance, prefixRuleInfo + messagestring) if rulecompliance: nextstep = False return nextstep ############################################################################### def setConditionsForRule(self): return True ############################################################################### def checkReportForRule(self, pCompliance, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + \ str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") return True ############################################################################### def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") return True ############################################################################### def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + \ str(pRuleSuccess) + ".") return True
class zzzTestFrameworkSHlaunchdTwoHelperMethods(unittest.TestCase): ''' Test the launchd version 2 service helper. @author: Roy Nielsen ''' @classmethod def setUpClass(self): ''' Test initializer ''' self.environ = Environment() self.environ.setdebugmode(True) # Start timer in miliseconds self.test_start_time = datetime.now() self.logger = LogDispatcher(self.environ) self.logger.initializeLogs() self.sh = SHlaunchdTwo(self.environ, self.logger) self.logger.log(lp.DEBUG, "test " + __file__ + " initialized...") def test_isValidServicePath(self): ''' ''' for test_key, test_values in service_path_test_data.iteritems(): if re.match("^valid_service_paths", test_key): for test_item in test_values: self.assertTrue(self.sh.isValidServicePath(test_item), "Invalid service path: " + str(test_item)) if re.match("^invalid_service_paths", test_key): for test_item in test_values: self.assertFalse(self.sh.isValidServicePath(test_item), "Valid service path: " + str(test_item)) def test_getServiceNameFromService(self): ''' ''' for test_key, test_values in name_from_service_test_data.iteritems(): if re.match("^valid_service_plists", test_key): for test_item in test_values: self.assertTrue(self.sh.isValidServicePath(test_item), "Invalid service plist: " + str(test_item)) if re.match("^invalid_service_plists", test_key): for test_item in test_values: self.assertFalse(self.sh.isValidServicePath(test_item), "Valid service plist: " + str(test_item)) def test_targetValid(self): ''' ''' for test_key, test_values in target_valid_test_data.iteritems(): if re.match("^valid_target_data", test_key): for test_item in test_values: params = {test_item[1]['serviceName'][0]: test_item[1]['serviceName'][1]} self.assertEqual(self.sh.targetValid(test_item[0], **params), test_item[2], "Target data: " + str(test_item) + " is not valid.") if re.match("^invalid_target_data", test_key): for test_item in test_values: params = {test_item[1]['serviceName'][0]: test_item[1]['serviceName'][1]} self.assertNotEqual(self.sh.targetValid(test_item[0], **params), test_item[2], "Target data: " + str(test_item) + " is good!") @classmethod def tearDownClass(self): ''' Test destructor ''' ##### # 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(lp.DEBUG, self.__module__ + " took " + str(test_time) + " time to complete...")
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()
import filecmp import unittest from distutils.version import LooseVersion sys.path.append("../../../..") from src.stonix_resources.FileStateManager import FileStateManager from src.stonix_resources.environment import Environment from src.stonix_resources.CommandHelper import CommandHelper from src.tests.lib.logdispatcher_lite import LogDispatcher, LogPriority from src.stonix_resources.get_libc import getLibc lp = LogPriority LIBC = getLibc() environ = Environment() environ.stonixversion = "1.2.3" logger = LogDispatcher(debug_mode=True) logger.initializeLogs("/tmp/zzzTestFrameworkFileStateManager", extension_type="time", syslog=False, myconsole=False) class NotApplicableToThisOS(Exception): '''Custom Exception''' def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class zzzTestFrameworkFileStateManager(unittest.TestCase):
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 RuleTest(unittest.TestCase): def setUp(self): ''' Setup what we need for the test. @author: ekkehard j. koch @param self:essential if you override this definition ''' self.environ = Environment() self.environ.setverbosemode(True) self.environ.setdebugmode(True) self.config = Configuration(self.environ) self.logdispatch = LogDispatcher(self.environ) self.statechglogger = StateChgLogger(self.logdispatch, self.environ) self.rule = None self.rulename = "" self.rulenumber = "" self.checkUndo = False self.ignoreresults = False ############################################################################### def tearDown(self): ''' Release anything we no longer need what we need for the test. @author: ekkehard j. koch @param self:essential if you override this definition ''' pass ############################################################################### def simpleRuleTest(self): ''' Run a simple Report, Fix, Report Cycle @author: ekkehard j. koch @param self:essential if you override this definition ''' nextstep = True prefixHeadline = "################################################### " prefixRuleInfo = self.rulename + "(" + str(self.rulenumber) + "): " messagestring = "" # Make Rule Is supposed to run in this environment if nextstep: messagestring = "Make sure Rule Is supposed to run in this " + \ "environment" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) isapplicable = self.rule.isapplicable() messagestring = "rule.isapplicable() = " + str(isapplicable) self.logdispatch.log(LogPriority.DEBUG, prefixRuleInfo + messagestring) valueIsInList = isapplicable in [True, False] messagestring = "Invalid isapplicable Type!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) messagestring = "rule.isapplicable() = " + str(isapplicable) + \ " and should be True." self.assertTrue(isapplicable, prefixRuleInfo + messagestring) nextstep = isapplicable # Check to see if we are running in the right context if nextstep: messagestring = "Check to see if we are running in the " + \ "right context" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) effectiveUserID = self.environ.geteuid() messagestring = "environ.geteuid() = " + str(effectiveUserID) self.logdispatch.log(LogPriority.DEBUG, prefixRuleInfo + messagestring) isRootRequired = self.rule.getisrootrequired() messagestring = "rule.getisrootrequired() = " + str(isRootRequired) self.logdispatch.log(LogPriority.DEBUG, prefixRuleInfo + messagestring) if effectiveUserID == 0 and isRootRequired: nextstep = True elif not isRootRequired: nextstep = True else: nextstep = False messagestring = "Rule requires root and effective uid ='" + \ str(effectiveUserID) + "'" self.assertTrue(nextstep, prefixRuleInfo + messagestring) # Run setConditionsForRule to configure system for test if nextstep: messagestring = "Run setConditionsForRule to configure " + \ "system for test" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) setTestConditions = self.setConditionsForRule() self.logdispatch.log(LogPriority.DEBUG, "setConditionsForRule()" + " = " + str(setTestConditions)) if setTestConditions: nextstep = True else: nextstep = False messagestring = "setConditionsForRule() = " + \ str(setTestConditions) + "." self.assertTrue(setTestConditions, prefixRuleInfo + messagestring) # Run rule.report() if nextstep: messagestring = "Run rule.report()" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) report = self.rule.report() self.logdispatch.log(LogPriority.DEBUG, "rule.report() = " + str(report)) rulesuccess = self.rule.getrulesuccess() originalResults = self.rule.getdetailedresults() self.logdispatch.log(LogPriority.DEBUG, "rule.getrulesuccess() = " + str(rulesuccess)) valueIsInList = rulesuccess in [True, False] messagestring = "Invalid rule.getrulesuccess() Value'" + \ str(rulesuccess) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) if not rulesuccess: nextstep = False messagestring = ": rule.getrulesuccess() is '" + \ str(rulesuccess) + "'" self.assertTrue(rulesuccess, prefixRuleInfo + messagestring) rulecompliance = self.rule.iscompliant() self.logdispatch.log(LogPriority.DEBUG, "rule.iscompliant() = " + str(rulecompliance)) valueIsInList = rulecompliance in [True, False] messagestring = "Invalid rule.iscompliant() Value'" + \ str(rulecompliance) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) # Run checkReportForRule() messagestring = "Run checkReportForRule(" + str(rulecompliance) + \ ", " + str(rulesuccess) + ")" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) checkReportConditions = self.checkReportForRule(rulecompliance, rulesuccess) self.logdispatch.log(LogPriority.DEBUG, "checkReportForRule() = " + str(checkReportConditions)) if checkReportConditions and not rulecompliance: nextstep = True else: nextstep = False messagestring = ": Rule checkReportForRule() = " + \ str(checkReportConditions) + "." self.assertTrue(checkReportConditions, self.rulename + "(" + str(self.rulenumber) + "): Rule checkReportForRule() = " + str(checkReportConditions) + ".") # Run rule.fix() if nextstep: messagestring = "Run rule.fix()" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) fix = self.rule.fix() self.logdispatch.log(LogPriority.DEBUG, "rule.fix() = " + str(fix)) rulesuccess = self.rule.getrulesuccess() self.logdispatch.log(LogPriority.DEBUG, "rule.getrulesuccess() = " + str(rulesuccess)) valueIsInList = rulesuccess in [True, False] messagestring = "Invalid rule.rulesuccess() Value'" + \ str(rulesuccess) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) messagestring = "rule.getrulesuccess() = '" + \ str(rulesuccess) + "'" self.assertTrue(rulesuccess, prefixRuleInfo + messagestring) # Run checkFixForRule() messagestring = "Run checkFixForRule(" + str(rulesuccess) + ")" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) checkFixConditions = self.checkFixForRule(rulesuccess) self.logdispatch.log(LogPriority.DEBUG, "checkFixForRule(" + str(rulesuccess) + ")" + " = " + str(checkFixConditions)) if checkFixConditions and rulesuccess: nextstep = True else: nextstep = False messagestring = "Rule checkFixForRule() = " + \ str(checkFixConditions) + "." self.assertTrue(nextstep, prefixRuleInfo + messagestring) # Run rule.report() if nextstep: messagestring = "Run rule.report()" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) report = self.rule.report() self.logdispatch.log(LogPriority.DEBUG, "rule.report() = " + str(report)) rulesuccess = self.rule.getrulesuccess() self.logdispatch.log(LogPriority.DEBUG, "rule.getrulesuccess() = " + str(rulesuccess)) valueIsInList = rulesuccess in [True, False] messagestring = "Invalid rule.getrulesuccess() Value'" + \ str(rulesuccess) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) if not rulesuccess: nextstep = False self.assertTrue(rulesuccess, self.rulename + "(" + str(self.rulenumber) + "): rule.getrulesuccess() is '" + str(rulesuccess) + "' with reported error '" + str(self.rule.getdetailedresults()) + "'") rulecompliance = self.rule.iscompliant() self.logdispatch.log(LogPriority.DEBUG, "rule.iscompliant() = " + str(rulecompliance)) valueIsInList = rulecompliance in [True, False] messagestring = "Invalid rule.iscompliant() Value'" + \ str(rulecompliance) + "'!" self.assertTrue(valueIsInList, prefixRuleInfo + messagestring) messagestring = "rule.iscompliant() is '" + \ str(rulecompliance) + "' after rule.fix() and " + \ "rule.report() have run." if not self.ignoreresults: self.assertTrue(rulecompliance, prefixRuleInfo + messagestring) # Run checkReportFinalForRule() messagestring = "Run checkReportFinalForRule(" + \ str(rulecompliance) + ", " + str(rulesuccess) + ")" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) checkReportFinalConditions = self.checkReportFinalForRule(rulecompliance, rulesuccess) self.logdispatch.log(LogPriority.DEBUG, "checkReportFinalForRule() = " + str(checkReportFinalConditions)) if checkReportFinalConditions and rulecompliance: nextstep = True else: nextstep = False self.assertTrue(checkReportFinalConditions, self.rulename + "(" + str(self.rulenumber) + "): Rule checkReportFinalForRule() = " + str(checkReportFinalConditions) + ".") # Run rule.undo() if nextstep and self.checkUndo: messagestring = "Run rule.undo()" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) undo = self.rule.undo() self.logdispatch.log(LogPriority.DEBUG, "rule.undo() = " + str(undo)) self.rule.report() postUndoResults = self.rule.getdetailedresults() # In order to get detailed, well-formatted error information, this # has been turned into a short procedure to produce the most # helpful information, rather than simply using the assert # statement if originalResults != postUndoResults: orlines = originalResults.splitlines() pulines = postUndoResults.splitlines() orlinestmp = orlines[:] # [:] to copy by value r/t reference for line in orlinestmp: if line in pulines: orlines.remove(line) pulines.remove(line) error = "After undo, the report results were not the same " + \ "as the initial pre-fix report." if orlines: error += "\nOnly in original:\n" + "\n".join(orlines) if pulines: error += "\nOnly in post-undo:\n" + "\n".join(pulines) self.assertTrue(False, error) # Run checkUndoForRule() messagestring = "Run checkUndoForRule(" + str(rulesuccess) + ")" self.logdispatch.log(LogPriority.DEBUG, prefixHeadline + prefixRuleInfo + messagestring) checkUndoConditions = self.checkUndoForRule(rulesuccess) self.logdispatch.log(LogPriority.DEBUG, "checkUndoForRule()" + " = " + str(checkUndoConditions)) if checkUndoConditions and not rulecompliance: nextstep = True else: nextstep = False self.assertTrue(checkUndoConditions, self.rulename + "(" + str(self.rulenumber) + "): Rule checkUndoForRule() = " + str(checkUndoConditions) + ".") return nextstep ############################################################################### def setConditionsForRule(self): return True ############################################################################### def checkReportForRule(self, pCompliance, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") return True ############################################################################### def checkFixForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") return True ############################################################################### def checkReportFinalForRule(self, pCompliance, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pCompliance = " + str(pCompliance) + ".") self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") return True ############################################################################### def checkUndoForRule(self, pRuleSuccess): self.logdispatch.log(LogPriority.DEBUG, "pRuleSuccess = " + str(pRuleSuccess) + ".") return True ############################################################################### def setCheckUndo(self, checkUndo): self.checkUndo = checkUndo ############################################################################### def getCheckUndo(self): return self.checkUndo ############################################################################### def runDestructive(self): return os.path.exists("/etc/stonix-destructive")
class zzzTestFrameworkmacbuild(unittest.TestCase): def setUp(self): self.enviro = Environment() self.enviro.setdebugmode(True) self.logger = LogDispatcher(self.enviro) self.ch = CommandHelper(self.logger) self.changedDir = False # stonixtest must currently be run from the stonixroot directory, so # that is the best bet for the cwd if os.path.exists("src/Macbuild"): os.chdir("src/Macbuild") self.changedDir = True # Cannot guarantee that test will end in self.myDir = os.getcwd() # this dir, so we record it first self.mb = build.SoftwareBuilder(options=optparse.Values({"compileGui": True, "version": "0.dev-UT", "clean": False, "test": True})) def tearDown(self): if self.changedDir: os.chdir(self.myDir) self.ch.executeCommand(["./build.py", "-c"]) os.chdir("../..") def testSetupAndDetachRamdisk(self): path = "/tmp/mount_ramdisk_for_ut" if os.path.exists(path): rmtree(path) os.mkdir(path) device = self.mb.setupRamdisk(512, path) self.assertRegexpMatches(device, "/dev/disk\d+", "Unexpected return from setupRamdisk") self.assertTrue(self.mb.detachRamdisk(device), "Did not successfully detach ramdisk") def testExitMethod(self): ramdiskPath = "/tmp/mount_ramdisk_for_ut" luggagePath = "/tmp/luggage_ramdisk_for_ut" ramdisk = self.mb.setupRamdisk(1024, ramdiskPath) luggage = self.mb.setupRamdisk(1024, luggagePath) self.assertRaises(SystemExit, self.mb.exit, ramdisk, luggage, 999) def testCompileStonix4MacAppUiFilesMethod(self): self.mb.compileStonix4MacAppUiFiles("./stonix4mac") try: adminCred = open("stonix4mac/admin_credentials_ui.py", "r").read() stonixWrapper = open("stonix4mac/stonix_wrapper_ui.py", "r").read() generalWarning = open("stonix4mac/general_warning_ui.py", "r").read() except OSError: self.assertTrue(False, "One or more UI files could not be found") else: self.assertTrue(adminCred, "admin_credentials_ui.py file is empty") self.assertTrue(stonixWrapper, "stonix_wrapper_ui.py file is empty") self.assertTrue(generalWarning, "general_warning_ui.py file is empty") self.assertRaises(OSError, self.mb.compileStonix4MacAppUiFiles, "thisdirdoesnotexist") def testSetProgramArgumentsVersionMethod(self): path = "../stonix_resources/localize.py" self.mb.setProgramArgumentsVersion(path) version = self.mb.APPVERSION localizeContents = open(path, "r").read() self.assertTrue(re.search(version, localizeContents), "Could not find correct version in localize.py") self.assertRaises(IOError, self.mb.setProgramArgumentsVersion, "badpath.py") def testPrepStonixBuildMethod(self): self.mb.prepStonixBuild(".") stonixDirList = os.listdir("stonix") self.assertTrue(stonixDirList, "No files found in stonix directory") self.assertRaises(OSError, self.mb.prepStonixBuild, "thisdirisfake") def testDriverAndBuildMethods(self): # Due to issues with dependencies, several methods cannot be easily # tested as units. Therefore, the "driver" method is run, and artifacts # from each method are checked. self.mb.driver() # Check compileApp artifacts try: stonixSpec = open("stonix/stonix.spec", "r").read() stonix4macSpec = open("stonix4mac/stonix4mac.spec", "r").read() except IOError: self.assertTrue(False, "One or more spec files not found") else: self.assertTrue(stonixSpec, "stonix.spec file is empty") self.assertTrue(stonix4macSpec, "stonix4mac.spec file is empty") # Check buildStonix4MacAppResources artifacts self.assertTrue(os.path.exists("stonix4mac/dist/stonix4mac.app/" + "Contents/Resources/stonix.conf"), "Could not find stonix.conf file in package") self.assertTrue(os.path.exists("stonix4mac/dist/stonix4mac.app/" + "Contents/Resources/stonix.app"), "Could not find stonix.app in stonix4mac.app Resources") # Check buildStonix4MacAppPkg artifacts self.assertTrue(os.path.exists("dmgs/stonix4mac-0.dev-UT.pkg"), "Could not find stonix4mac pkg file")