示例#1
0
    def __init__(self, userName="", userShell="/bin/bash",
                       userComment="", userUid=10000, userPriGid=20,
                       userHomeDir="/tmp", logger=False):
        self.module_version = '20160225.125554.540679'

        #####
        # Set up logging
        self.logger = LogDispatcher()
        #####
        # THIS IS A LIBRARY, SO LOGS SHOULD BE INITIALIZED ELSEWHERE...
        # self.logger.initializeLogs()
        self.logger.log(lp.INFO, "Logger: " + str(self.logger))
        """
        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...")
示例#3
0
 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):
        '''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)
示例#5
0
    def setUp(self):
        ''' '''

        self.enviro = Environment()
        self.enviro.setdebugmode(True)
        self.logger = LogDispatcher(self.enviro)
        self.commandhelper = CommandHelper(self.logger)
示例#6
0
    def __init__(self, userName="", userShell="/bin/bash",
                       userComment="", userUid=10000, userPriGid=20,
                       userHomeDir="/tmp", logger=False):
        self.module_version = '20160225.125554.540679'

        #####
        # Set up logging
        self.logger = LogDispatcher()
        #####
        # THIS IS A LIBRARY, SO LOGS SHOULD BE INITIALIZED ELSEWHERE...
        # self.logger.initializeLogs()
        self.logger.log(lp.INFO, "Logger: " + str(self.logger))
        """
    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)
示例#8
0
 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 = ""
示例#9
0
 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):
        """
        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 = urllib2.ProxyHandler({"http": PROXY,
                                          "https": PROXY})
            opener = urllib2.build_opener(urllib2.HTTPHandler(), urllib2.HTTPSHandler(context=context), proxy)
        else:
            opener = urllib2.build_opener(urllib2.HTTPHandler(), urllib2.HTTPSHandler(context=context))

        urllib2.install_opener(opener)
示例#12
0
 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 setUpClass(self):
        """
        """
        self.macPackageName = "testStonixMacPkgr-0.0.3.pkg"
        self.reporoot = MACREPOROOT
        self.environ = Environment()
        self.logger = LogDispatcher(self.environ)
        self.pkgr = MacPkgr(self.environ, self.logger)
        if not self.environ.osfamily == "darwin":
            sys.exit(255)
        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 zzzTestFrameworkMacPkgr(unittest.TestCase):
    """
    Class for testing the macpkgr.
    """
    @classmethod
    def setUpClass(self):
        """
        """
        self.macPackageName = "testStonixMacPkgr-0.0.3.pkg"
        self.reporoot = MACREPOROOT
        self.environ = Environment()
        self.logger = LogDispatcher(self.environ)
        self.pkgr = MacPkgr(self.environ, self.logger)
        if not self.environ.osfamily == "darwin":
            sys.exit(255)
        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"

    @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 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 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 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 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
        """
        pass
        
    def testIsMacPlatform(self):
        """
        Make sure we are on the Mac platform.
        
        @author: Roy Nielsen
        """
        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:
 def setUp(self):
     self.environ = Environment()
     self.logdispatcher = LogDispatcher(self.environ)
     self.conn = Connectivity(self.logdispatcher)
    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"

    ############################################################################
    
        """
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.
    """
    def setUp(self):
    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...")
示例#20
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")
示例#21
0
class ManageUser(object):
    """
    Class to manage user properties.

    @author: Roy Nielsen
    """
    def __init__(self, userName="", userShell="/bin/bash",
                       userComment="", userUid=10000, userPriGid=20,
                       userHomeDir="/tmp", logger=False):
        self.module_version = '20160225.125554.540679'

        #####
        # Set up logging
        self.logger = LogDispatcher()
        #####
        # THIS IS A LIBRARY, SO LOGS SHOULD BE INITIALIZED ELSEWHERE...
        # self.logger.initializeLogs()
        self.logger.log(lp.INFO, "Logger: " + str(self.logger))
        """
        if self.isSaneUserName(userName):
            self.userName = userName
        else:
            raise BadUserInfoError("Need a valid user name...")

        if self.isSaneUserShell(userShell):
            self.userShell = userShell
        else:
            raise BadUserInfoError("Need a valid user shell...")

        if self.isSaneUserComment(userComment):
            self.userComment = userComment
        else:
            self.userComment=""

        if self.isSaneUserUid(str(userUid)):
            self.userUid = self.userUid
        else:
            raise BadUserInfoError("Need a valid user UID...")

        if self.isSaneUserPriGid(str(userPriGid)):
            self.userUid = userUid
        else:
            raise BadUserInfoError("Need a valid user Primary GID...")

        if self.isSaneUserHomeDir(userHomeDir):
            self.userHomeDir = userHomeDir
        else:
            raise BadUserInfoError("Need a user Home Directory...")
        """

    def isSaneUserName(self, userName=""):
        """
        """
        sane = False
        if userName and isinstance(userName, basestring):
            if re.match("^[A-Za-z][A-Za-z0-9]*", userName):
                sane = True
        return sane

    def isSaneGroupName(self, groupName=""):
        """
        """
        sane = False
        if groupName and isinstance(groupName, basestring):
            if re.match("^[A-Za-z][A-Za-z0-9]*", groupName):
                sane = True
        return sane

    def isSaneUserShell(self, userShell=""):
        """
        """
        sane = False
        if userShell and isinstance(userShell, basestring):
            if re.match("^[A-Za-z/][A-Za-z0-9/]*", userShell):
                sane = True
        return sane

    def isSaneUserComment(self, userComment=""):
        """
        """
        sane = False
        if userComment and isinstance(userComment, basestring):
            if re.match("^[A-Za-z][A-Za-z0-9]*", userComment):
                sane = True
        return sane

 
    def isSaneUserUid(self, userUid=""):
        """
        """
        sane = False
        if userUid and isinstance(userUid, [basestring, int]):
            if re.match("^\d+", str(userUid)):
                sane = True
        return sane

    def isSaneUserPriGid(self, userPriGid=1000):
        """
        """
        sane = False
        if userPriGid and isinstance(userPriGid, [basestring, int]):
            if re.match("^\d+", str(userPriGid)):
                sane = True
        return sane

    def isSaneUserHomeDir(self, userHomeDir=""):
        """
        """
        sane = False
        if userHomeDir and isinstance(userHomeDir, basestring):
            if re.match("^[A-Za-z/][A-Za-z0-9/]*", userHomeDir):
                sane = True
        return sane


    def setUserName(self, userName=""):
        """
        """
        sane = False
        if self.isSaneUserName(userName):
            sane = True
            self.userName = userName
        return sane

    def setUserShell(self, user="", shell=""):
        """
        """
        pass

    def setUserComment(self, user="", comment=""):
        """
        """
        pass

    def setUserUid(self, user="", uid=""):
        """
        """
        pass

    def setUserPriGid(self, user="", priGid=""):
        """
        """
        pass

    def setUserHomeDir(self, user="", userHome = ""):
        """
        """
        pass

    def addUserToGroup(self, user="", group=""):
        """
        """
        pass

    def setUserPassword(self, user="", password=""):
        """
        """
        pass
class zzzTestFrameworkRamdisk(unittest.TestCase):

    @classmethod
    def setUpClass(self):
        """
        Initializer
        """

        self.environ = Environment()

        # Start timer in miliseconds
        self.test_start_time = datetime.now()

        self.logger = LogDispatcher(self.environ)

        #####
        # setting up to call ctypes to do a filesystem sync 
        if self.environ.getosfamily() == "redhat" :
            self.libc = C.CDLL("/lib/libc.so.6")
        elif self.environ.getosfamily() == "darwin" :
            self.libc = C.CDLL("/usr/lib/libc.dylib")
        else:
            self.libc = None

        self.subdirs = ["two", "three" "one/four"]

        """
        Set up a ramdisk and use that random location as a root to test the
        filesystem functionality of what is being tested.
        """
        #Calculate size of ramdisk to make for this unit test.
        size_in_mb = 1800
        ramdisk_size = size = size_in_mb
        self.mnt_pnt_requested = ""

        self.success = False
        self.mountPoint = False
        self.ramdiskDev = False
        self.mnt_pnt_requested = False

        self.logger.log(LogPriority.DEBUG, "::::::::Ramdisk Mount Point: " + str(self.mountPoint))
        self.logger.log(LogPriority.DEBUG, "::::::::Ramdisk Device     : " + str(self.ramdiskDev))

        if self.environ.getosfamily().lower() == "darwin":
            
            # import appropriate ramdisk library
            #from src.MacBuild.macRamdisk import Ramdisk, detach 

            # get a ramdisk of appropriate size, with a secure random mountpoint
            self.my_ramdisk = RamDisk(str(ramdisk_size), self.mnt_pnt_requested)
            
            (self.success, self.mountPoint, self.ramdiskDev) = \
            self.my_ramdisk.get_data()
            
        else:
            self.logger.log(LogPriority.INFO, "Not applicable to this OS")
            self.success = False

        if not self.success:
            raise IOError("Cannot get a ramdisk for some reason. . .")

        #####
        # Create a temp location on disk to run benchmark tests against
        self.fs_dir = tempfile.mkdtemp()

    def setUp(self):
        """
        This method runs before each test run.

        @author: Roy Nielsen
        """
        self.libcPath = None # initial initialization
        #####
        # setting up to call ctypes to do a filesystem sync
        if sys.platform.startswith("darwin"):
            #####
            # For Mac
            self.libc = C.CDLL("/usr/lib/libc.dylib")
        elif sys.platform.startswith("linux"):
            #####
            # For Linux
            self.findLinuxLibC()
            self.libc = C.CDLL(self.libcPath)
        else:
            self.libc = self._pass()

        

###############################################################################
##### Helper Classes

    def findLinuxLibC(self):
        """
        Find Linux Libc library...

        @author: Roy Nielsen
        """
        possible_paths = ["/lib/x86_64-linux-gnu/libc.so.6",
                          "/lib/i386-linux-gnu/libc.so.6"]
        for path in possible_paths:

            if os.path.exists(path):
                self.libcPath = path
                break

    def _pass(self):
        """
        Filler if a library didn't load properly
        """
        pass

    def touch(self, fname="", message_level="normal") :
        """
        Python implementation of the touch command..

        inspiration: http://stackoverflow.com/questions/1158076/implement-touch-using-python

        @author: Roy Nielsen
        """
        if re.match("^\s*$", str(fname)):
            self.logger.log(LogPriority.DEBUG, "Cannot touch a file without a filename....")
        else :
            try:
                os.utime(fname, None)
            except:
                try :
                    open(fname, 'a').close()
                except Exception, err:
                    self.logger.log(LogPriority.INFO,"Cannot open to touch: " + str(fname))
class zzzTestFrameworkHelpLinks(unittest.TestCase):
    """
    Class for testing the HelpLinks
    """

    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 = urllib2.ProxyHandler({"http": PROXY,
                                          "https": PROXY})
            opener = urllib2.build_opener(urllib2.HTTPHandler(), urllib2.HTTPSHandler(context=context), proxy)
        else:
            opener = urllib2.build_opener(urllib2.HTTPHandler(), urllib2.HTTPSHandler(context=context))

        urllib2.install_opener(opener)

    def get_links(self):
        """
        return a (unique) list of all web links in all html help files in
        stonix help folder

        @return: help_files_list
        @rtype: list
        @author: Breen Malmberg
        """

        help_files_list = self.get_help_files()
        help_links = []

        # search each file for web links
        for hf in help_files_list:
            f = open(hf, "r")
            contentlines = f.readlines()
            f.close()

            # append web link help_links when found
            for line in contentlines:
                urls = re.findall("https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+", line)
                for u in urls:
                    help_links.append(u)

        # remove any duplicates from links list
        # (we don't need to check each link more than once...)
        help_links = list(dict.fromkeys(help_links))

        return help_links

    def get_help_files(self):
        """
        return a list of all html help files within stonix help folder

        @return: help_files_list
        @rtype: list
        @author: Breen Malmberg
        """

        help_files_list = []

        # set help directory path from stonix source tree
        currpath = os.path.abspath(os.path.dirname(__file__))
        helpdir = os.path.join(currpath, "../../../stonix_resources/help/")

        # add all html files in help directory
        for dir,_,filen in os.walk(helpdir):
            for f in filen:
                full_file_path = os.path.join(dir, f)
                try:
                    if os.path.splitext(full_file_path)[1] == ".html":
                        help_files_list.append(full_file_path)
                except IndexError:
                    pass
                except:
                    raise

        return help_files_list

    def test_links(self):
        """
        test all web links to make sure each one is reachable/valid

        @author: Breen Malmberg
        """

        help_links = self.get_links()

        try:

            for link in help_links:
                connection = urllib2.urlopen(link)
                print("\nTESTING CONNECTION TO: " + link + "\n")
                if not self.assertIsNotNone(connection):
                    print("connection established\n")
                print("\nTESTING GETURL() OF CONNECTION\n")
                url = connection.geturl()
                self.assertNotEqual(url, "")
                self.assertIsNotNone(url)
                print("url = " + url + "\n")
                # close each connection after use
                if connection:
                    connection.close()
                # test output separator
                print("=================================================")

        except AttributeError:
            # python version 2.6* and earlier does not support assertIsNotNone()
            self.logger.log(LogPriority.DEBUG, "Current system's version of python does not support the assertion calls used in this unit test")
            pass
        except:
            raise
示例#24
0
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.'''
    def setUp(self):
    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...")
示例#26
0
class zzzTestFrameworkHelpLinks(unittest.TestCase):
    '''Class for testing the HelpLinks'''
    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 get_links(self):
        '''return a (unique) list of all web links in all html help files in
        stonix help folder


        :returns: help_files_list

        :rtype: list
@author: Breen Malmberg

        '''

        help_files_list = self.get_help_files()
        help_links = []

        # search each file for web links
        for hf in help_files_list:
            f = open(hf, "r")
            contentlines = f.readlines()
            f.close()

            # append web link help_links when found
            for line in contentlines:
                urls = re.findall("https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+",
                                  line)
                for u in urls:
                    help_links.append(u)

        # remove any duplicates from links list
        # (we don't need to check each link more than once...)
        help_links = list(dict.fromkeys(help_links))

        return help_links

    def get_help_files(self):
        '''return a list of all html help files within stonix help folder


        :returns: help_files_list

        :rtype: list
@author: Breen Malmberg

        '''

        help_files_list = []

        # set help directory path from stonix source tree
        currpath = os.path.abspath(os.path.dirname(__file__))
        helpdir = os.path.join(currpath, "../../../stonix_resources/help/")

        # add all html files in help directory
        for dir, _, filen in os.walk(helpdir):
            for f in filen:
                full_file_path = os.path.join(dir, f)
                try:
                    if os.path.splitext(full_file_path)[1] == ".html":
                        help_files_list.append(full_file_path)
                except IndexError:
                    pass
                except:
                    raise

        return help_files_list

    def test_links(self):
        '''test all web links to make sure each one is reachable/valid
        
        @author: Breen Malmberg


        '''

        help_links = self.get_links()

        try:

            for link in help_links:
                connection = urllib.request.urlopen(link)
                print(("\nTESTING CONNECTION TO: " + link + "\n"))
                if not self.assertIsNotNone(connection):
                    print("connection established\n")
                print("\nTESTING GETURL() OF CONNECTION\n")
                url = connection.geturl()
                self.assertNotEqual(url, "")
                self.assertIsNotNone(url)
                print(("url = " + url + "\n"))
                # close each connection after use
                if connection:
                    connection.close()
                # test output separator
                print("=================================================")

        except AttributeError:
            # python version 2.6* and earlier does not support assertIsNotNone()
            self.logger.log(
                LogPriority.DEBUG,
                "Current system's version of python does not support the assertion calls used in this unit test"
            )
            pass
        except:
            raise
示例#27
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")
示例#28
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
示例#29
0
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...")
    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()
示例#31
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
示例#32
0
    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):
     self.enviro = environment.Environment()
     self.logger = LogDispatcher(self.enviro)
     self.helper = pkghelper.Pkghelper(self.logger, self.enviro)
     self.pkg = "zsh"
示例#34
0
class ManageUser(object):
    '''Class to manage user properties.
    
    @author: Roy Nielsen


    '''
    def __init__(self, userName="", userShell="/bin/bash",
                       userComment="", userUid=10000, userPriGid=20,
                       userHomeDir="/tmp", logger=False):
        self.module_version = '20160225.125554.540679'

        #####
        # Set up logging
        self.logger = LogDispatcher()
        #####
        # THIS IS A LIBRARY, SO LOGS SHOULD BE INITIALIZED ELSEWHERE...
        # self.logger.initializeLogs()
        self.logger.log(lp.INFO, "Logger: " + str(self.logger))
        """
        if self.isSaneUserName(userName):
            self.userName = userName
        else:
            raise BadUserInfoError("Need a valid user name...")

        if self.isSaneUserShell(userShell):
            self.userShell = userShell
        else:
            raise BadUserInfoError("Need a valid user shell...")

        if self.isSaneUserComment(userComment):
            self.userComment = userComment
        else:
            self.userComment=""

        if self.isSaneUserUid(str(userUid)):
            self.userUid = self.userUid
        else:
            raise BadUserInfoError("Need a valid user UID...")

        if self.isSaneUserPriGid(str(userPriGid)):
            self.userUid = userUid
        else:
            raise BadUserInfoError("Need a valid user Primary GID...")

        if self.isSaneUserHomeDir(userHomeDir):
            self.userHomeDir = userHomeDir
        else:
            raise BadUserInfoError("Need a user Home Directory...")
        """

    def isSaneUserName(self, userName=""):
        '''

        :param userName:  (Default value = "")

        '''
        sane = False
        if userName and isinstance(userName, str):
            if re.match("^[A-Za-z][A-Za-z0-9]*", userName):
                sane = True
        return sane

    def isSaneGroupName(self, groupName=""):
        '''

        :param groupName:  (Default value = "")

        '''
        sane = False
        if groupName and isinstance(groupName, str):
            if re.match("^[A-Za-z][A-Za-z0-9]*", groupName):
                sane = True
        return sane

    def isSaneUserShell(self, userShell=""):
        '''

        :param userShell:  (Default value = "")

        '''
        sane = False
        if userShell and isinstance(userShell, str):
            if re.match("^[A-Za-z/][A-Za-z0-9/]*", userShell):
                sane = True
        return sane

    def isSaneUserComment(self, userComment=""):
        '''

        :param userComment:  (Default value = "")

        '''
        sane = False
        if userComment and isinstance(userComment, str):
            if re.match("^[A-Za-z][A-Za-z0-9]*", userComment):
                sane = True
        return sane

 
    def isSaneUserUid(self, userUid=""):
        '''

        :param userUid:  (Default value = "")

        '''
        sane = False
        if userUid and isinstance(userUid, [str, int]):
            if re.match("^\d+", str(userUid)):
                sane = True
        return sane

    def isSaneUserPriGid(self, userPriGid=1000):
        '''

        :param userPriGid:  (Default value = 1000)

        '''
        sane = False
        if userPriGid and isinstance(userPriGid, [str, int]):
            if re.match("^\d+", str(userPriGid)):
                sane = True
        return sane

    def isSaneUserHomeDir(self, userHomeDir=""):
        '''

        :param userHomeDir:  (Default value = "")

        '''
        sane = False
        if userHomeDir and isinstance(userHomeDir, str):
            if re.match("^[A-Za-z/][A-Za-z0-9/]*", userHomeDir):
                sane = True
        return sane


    def setUserName(self, userName=""):
        '''

        :param userName:  (Default value = "")

        '''
        sane = False
        if self.isSaneUserName(userName):
            sane = True
            self.userName = userName
        return sane

    def setUserShell(self, user="", shell=""):
        '''

        :param user:  (Default value = "")
        :param shell:  (Default value = "")

        '''
        pass

    def setUserComment(self, user="", comment=""):
        '''

        :param user:  (Default value = "")
        :param comment:  (Default value = "")

        '''
        pass

    def setUserUid(self, user="", uid=""):
        '''

        :param user:  (Default value = "")
        :param uid:  (Default value = "")

        '''
        pass

    def setUserPriGid(self, user="", priGid=""):
        '''

        :param user:  (Default value = "")
        :param priGid:  (Default value = "")

        '''
        pass

    def setUserHomeDir(self, user="", userHome = ""):
        '''

        :param user:  (Default value = "")
        :param userHome:  (Default value = "")

        '''
        pass

    def addUserToGroup(self, user="", group=""):
        '''

        :param user:  (Default value = "")
        :param group:  (Default value = "")

        '''
        pass

    def setUserPassword(self, user="", password=""):
        '''

        :param user:  (Default value = "")
        :param password:  (Default value = "")

        '''
        pass