class zzzTestFrameworkServiceHelper(unittest.TestCase):

    def setUp(self):
        self.enviro = Environment()
        self.enviro.setdebugmode(False)
        self.logger = LogDispatcher(self.enviro)
        self.mysh = ServiceHelper(self.enviro, self.logger)
        self.myservice = 'crond'
        self.myservicename = ""
        if self.enviro.getosfamily() == 'darwin':
            self.myservice = "/System/Library/PrivateFrameworks/CalendarAgent.framework/Executables/CalendarAgent"
            self.myservicename = "com.apple.CalendarAgent"
        elif self.enviro.getosfamily() == 'solaris':
            self.myservice = 'svc:/system/cron:default'
        elif self.enviro.getosfamily() == 'freebsd':
            self.myservice = 'cron'
        elif os.path.exists('/usr/lib/systemd/system/cron.service'):
            self.myservice = 'cron.service'
        elif os.path.exists('/usr/lib/systemd/system/crond.service'):
            self.myservice = 'crond.service'
        elif os.path.exists('/etc/init.d/vixie-cron'):
            self.myservice = 'vixie-cron'
        elif os.path.exists('/etc/init.d/cron'):
            self.myservice = 'cron'

    def tearDown(self):
        pass

    def testListServices(self):
        svcslist = self.mysh.listservices()
        self.assertTrue(len(svcslist) > 0)

    def testDisableEnable(self):
        self.mysh.disableservice(self.myservice)
        auditresult = self.mysh.auditservice(self.myservice,
                                             self.myservicename)
        self.assertFalse(auditresult,
                         "Service not disabled or return from audit not valid")
        time.sleep(3)
        self.assertFalse(self.mysh.isrunning(self.myservice,
                                             self.myservicename),
                         "Service is still running or return from isrunning not valid")
        self.mysh.enableservice(self.myservice)
        self.assertTrue(self.mysh.auditservice(self.myservice,
                                               self.myservicename),
                        "Service not enabled or return from audit not valid")
        time.sleep(3)
        self.assertTrue(self.mysh.isrunning(self.myservice,
                                            self.myservicename),
                        "Service is not running or return from isrunning not valid")

    def testReloadService(self):
        self.assertTrue(self.mysh.reloadservice(self.myservice,
                                                self.myservicename),
                        'Service reload returned false')
class 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!")
Esempio n. 5
0
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!")
Esempio n. 6
0
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")
Esempio n. 7
0
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...")
    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 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))
Esempio n. 11
0
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
Esempio n. 12
0
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 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))
Esempio n. 14
0
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")