Exemplo n.º 1
0
    def test__lock(self):
        """Testing method / function _lock."""
        # Initialize key variables
        config = ServerConfig()
        lockfile = files.lock_file(PATTOO_INGESTER_NAME, config)

        # Test
        self.assertFalse(os.path.isfile(lockfile))
        result = files_test._lock()
        self.assertTrue(os.path.isfile(lockfile))
        self.assertTrue(result)

        # Should fail
        result = files_test._lock()
        self.assertFalse(result)

        # Remove and test again
        result = files_test._lock(delete=True)
        self.assertTrue(result)
        self.assertFalse(os.path.isfile(lockfile))
        result = files_test._lock()
        self.assertTrue(result)
        self.assertTrue(os.path.isfile(lockfile))

        # Delete again to revert to known working state
        result = files_test._lock(delete=True)
        self.assertTrue(result)
Exemplo n.º 2
0
    def test_encrypted_post(self):
        """Test that the API can receive and decrypt
        encrypted data from agent"""

        # Initialize key variables
        config = ServerConfig()
        agent_name = 'test_encrypted_agent'

        # Create a directory for the Agent keyring as by default the
        # API and agent use the same keyring directory
        keyring_directory = tempfile.mkdtemp()

        # Make agent data
        agent_data = _make_agent_data()

        # Turn agent data into a dict to be compared to
        # the data received by the API
        expected = converter.posting_data_points(
            converter.agentdata_to_post(agent_data))

        # Make encrypted post
        encrypted_agent = EncryptedAgent(agent_name,
                                         directory=keyring_directory)
        post_encrypted = EncryptedPostAgent(agent_data,
                                            encrypted_agent.encryption)
        post_encrypted.post()

        # Read data from directory
        cache_directory = config.agent_cache_directory(PATTOO_API_AGENT_NAME)
        cache_data = files.read_json_files(cache_directory)

        # Test
        self.assertEqual(len(cache_data), 1)
        self.assertEqual(len(cache_data[0]), 2)
        result = cache_data[0][1]

        # Result and expected are not quite the same. 'expected' will have
        # lists of tuples where 'result' will have lists of lists
        for key, value in result.items():
            if key not in ['pattoo_agent_timestamp', 'pattoo_datapoints']:
                self.assertEqual(value, expected[key])
        self.assertEqual(result['pattoo_datapoints']['datapoint_pairs'],
                         expected['pattoo_datapoints']['datapoint_pairs'])

        # Test list of tuples
        for key, value in result['pattoo_datapoints']['key_value_pairs'].items(
        ):
            self.assertEqual(
                tuple(value),
                expected['pattoo_datapoints']['key_value_pairs'][int(key)])

        # Revert cache_directory
        for filename in os.listdir(cache_directory):
            # Examine all the '.json' files in directory
            if filename.endswith('.json'):
                # Read file and add to string
                filepath = '{}{}{}'.format(cache_directory, os.sep, filename)
                os.remove(filepath)
Exemplo n.º 3
0
    def test_encrypted_post(self):
        """Test that the API can receive and decrypt
        encrypted data from agent"""

        # Initialize key variables
        config = ServerConfig()

        # Get Pgpier object
        gconfig = Config()  # Get config for Pgpier

        # Create Pgpier object for the agent
        agent_gpg = files.set_gnupg("test_encrypted_agent", gconfig,
                                    "*****@*****.**")

        # Make agent data
        agent_data = _make_agent_data()

        # Turn agent data into a dict to be compared to
        # the data received by the API
        expected = converter.posting_data_points(
            converter.agentdata_to_post(agent_data))

        # Make encrypted post
        post_encrypted = EncryptedPostAgent(agent_data, agent_gpg)
        post_encrypted.post()

        # Read data from directory
        cache_directory = config.agent_cache_directory(PATTOO_API_AGENT_NAME)
        cache_data = files.read_json_files(cache_directory)

        # Test
        self.assertEqual(len(cache_data), 1)
        self.assertEqual(len(cache_data[0]), 2)
        result = cache_data[0][1]

        # Result and expected are not quite the same. 'expected' will have
        # lists of tuples where 'result' will have lists of lists
        for key, value in result.items():
            if key != 'pattoo_datapoints':
                self.assertEqual(value, expected[key])
        self.assertEqual(result['pattoo_datapoints']['datapoint_pairs'],
                         expected['pattoo_datapoints']['datapoint_pairs'])

        # Test list of tuples
        for key, value in result['pattoo_datapoints']['key_value_pairs'].items(
        ):
            self.assertEqual(
                tuple(value),
                expected['pattoo_datapoints']['key_value_pairs'][int(key)])

        # Revert cache_directory
        for filename in os.listdir(cache_directory):
            # Examine all the '.json' files in directory
            if filename.endswith('.json'):
                # Read file and add to string
                filepath = '{}{}{}'.format(cache_directory, os.sep, filename)
                os.remove(filepath)
Exemplo n.º 4
0
def create_cache():
    """Testing method / function records."""
    # Initialize key variables
    config = ServerConfig()
    polling_interval = 20
    cache_directory = config.agent_cache_directory(PATTOO_API_AGENT_NAME)
    result = {
        'pattoo_agent_program': data.hashstring(str(random())),
        'pattoo_agent_polled_target': socket.getfqdn(),
        'pattoo_key': data.hashstring(str(random())),
        'pattoo_value': round(uniform(1, 100), 5),
        'pattoo_agent_hostname': socket.getfqdn()
    }

    # We want to make sure we get a different AgentID each time
    filename = files.agent_id_file(
        result['pattoo_agent_program'],
        config)
    if os.path.isfile(filename) is True:
        os.remove(filename)
    result['pattoo_agent_id'] = files.get_agent_id(
        result['pattoo_agent_program'],
        config)

    # Setup AgentPolledData
    apd = AgentPolledData(result['pattoo_agent_program'], polling_interval)

    # Initialize TargetDataPoints
    ddv = TargetDataPoints(result['pattoo_agent_hostname'])

    # Setup DataPoint
    data_type = DATA_INT
    variable = DataPoint(
        result['pattoo_key'], result['pattoo_value'], data_type=data_type)

    # Add data to TargetDataPoints
    ddv.add(variable)

    # Write data to cache
    apd.add(ddv)
    cache_dict = converter.posting_data_points(
        converter.agentdata_to_post(apd))
    cache_file = '{}{}cache_test.json'.format(cache_directory, os.sep)
    with open(cache_file, 'w') as _fp:
        json.dump(cache_dict, _fp)

    return result
Exemplo n.º 5
0
    def test_receive(self):
        """Testing method / function receive."""
        # Initialize key variables
        config = ServerConfig()
        apd = _create_apd()
        expected = converter.posting_data_points(
            converter.agentdata_to_post(apd))

        # Post data
        post = PostAgent(apd)
        post.post()

        # Read data from directory
        cache_directory = config.agent_cache_directory(PATTOO_API_AGENT_NAME)
        cache_data = files.read_json_files(cache_directory)

        # Test
        self.assertEqual(len(cache_data), 1)
        self.assertEqual(len(cache_data[0]), 2)
        result = cache_data[0][1]

        # Result and expected are not quite the same. 'expected' will have
        # lists of tuples where 'result' will have lists of lists
        for key, value in result.items():
            if key != 'pattoo_datapoints':
                self.assertEqual(value, expected[key])
        self.assertEqual(
            result['pattoo_datapoints']['datapoint_pairs'],
            expected['pattoo_datapoints']['datapoint_pairs'])

        # Test list of tuples
        for key, value in result[
                'pattoo_datapoints']['key_value_pairs'].items():
            self.assertEqual(
                tuple(value),
                expected['pattoo_datapoints']['key_value_pairs'][int(key)])

        # Revert cache_directory
        for filename in os.listdir(cache_directory):
            # Examine all the '.json' files in directory
            if filename.endswith('.json'):
                # Read file and add to string
                filepath = '{}{}{}'.format(cache_directory, os.sep, filename)
                os.remove(filepath)
Exemplo n.º 6
0
    def test_purge(self):
        """Testing method / function purge."""
        # Initialize key variables
        config = ServerConfig()
        cache_directory = config.agent_cache_directory(PATTOO_API_AGENT_NAME)

        # Initialize key variables
        _ = create_cache()

        # Test
        result = files.read_json_files(cache_directory)
        self.assertTrue(bool(result))

        # Test - Purge
        cache = Cache()
        cache.purge()

        # Test
        result = files.read_json_files(cache_directory, die=False)
        self.assertFalse(bool(result))