示例#1
0
    def test_valid(self):
        """Testing function valid."""
        # Initialize key variables
        devicename = self.data['devicename']
        id_agent = self.data['id_agent']
        last_timestamp = self.data['timestamp']

        # Drop the database and create tables
        unittest_setup_db.TestData()

        # Add record to the database
        record = Agent(id_agent=general.encode(id_agent))
        database = db.Database()
        database.add(record, 1040)

        # Test must be good as DeviceAgent last_timestamp not updated
        result = validate._CheckDuplicates(self.data)
        self.assertEqual(result.valid(), True)

        # Get idx_agent value from database
        data = db_agent.GetIDAgent(id_agent)
        idx_agent = data.idx_agent()

        # Add record to the database
        record = Device(devicename=general.encode(devicename))
        database = db.Database()
        database.add(record, 1024)

        # Test must be good as DeviceAgent last_timestamp not updated
        result = validate._CheckDuplicates(self.data)
        self.assertEqual(result.valid(), True)

        # Get idx of newly added device
        device_info = db_device.GetDevice(devicename)
        idx_device = device_info.idx_device()

        # Update DeviceAgent table
        if hagent.device_agent_exists(idx_device, idx_agent) is False:
            # Add to DeviceAgent table
            record = DeviceAgent(idx_device=idx_device, idx_agent=idx_agent)
            database = db.Database()
            database.add(record, 1055)

        # Test must be good as DeviceAgent last_timestamp not updated
        result = validate._CheckDuplicates(self.data)
        self.assertEqual(result.valid(), True)

        # Update database with timestamp
        database = db.Database()
        session = database.session()
        record = session.query(DeviceAgent).filter(
            and_(DeviceAgent.idx_device == idx_device,
                 DeviceAgent.idx_agent == idx_agent)).one()
        record.last_timestamp = last_timestamp
        database.commit(session, 1044)

        # Test must fail as DeviceAgent last_timestamp not updated
        result = validate._CheckDuplicates(self.data)
        self.assertEqual(result.valid(), False)
示例#2
0
class TestFunctions(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['id_datapoint'] = database.id_datapoint()
    expected['last_timestamp'] = database.timestamp()
    expected['idx_deviceagent'] = database.idx_deviceagent()
    expected['idx_datapoint'] = database.idx_datapoint()
    expected['idx_department'] = database.idx_department()
    expected['idx_billcode'] = database.idx_billcode()
    expected['agent_label'] = database.agent_label()
    expected['agent_source'] = database.agent_source()
    expected['enabled'] = True
    expected['exists'] = True
    expected['billable'] = False
    expected['base_type'] = 1
    expected['timefixed_value'] = None

    def test_id_datapoint_exists(self):
        """Testing function id_datapoint_exists."""
        # Testing with known good value
        expected = True
        result = db_datapoint.id_datapoint_exists(
            self.expected['id_datapoint'])
        self.assertEqual(result, expected)

        # Testing with known bad value
        expected = False
        result = db_datapoint.id_datapoint_exists('bogus')
        self.assertEqual(result, expected)

    def test_idx_datapoint_exists(self):
        """Testing function idx_datapoint_exists."""
        # Testing with known good value
        expected = True
        result = db_datapoint.idx_datapoint_exists(
            self.expected['idx_datapoint'])
        self.assertEqual(result, expected)

        # Testing with known bad value
        expected = False
        result = db_datapoint.idx_datapoint_exists(None)
        self.assertEqual(result, expected)

    def test_listing(self):
        """Testing function listing."""
        # Testing with known good value
        results = db_datapoint.listing(self.expected['idx_deviceagent'])
        for result in results:
            for key, _ in result.items():
                self.assertEqual(result[key], self.expected[key])
示例#3
0
class TestFunctions(unittest.TestCase):
    """Checks all functions."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_deviceagent'] = database.idx_deviceagent()
    expected['idx_device'] = database.idx_device()
    expected['idx_agent'] = database.idx_agent()
    expected['last_timestamp'] = database.timestamp()
    expected['enabled'] = True
    expected['exists'] = True

    def test_device_agent_exists(self):
        """Testing function device_agent_exists."""
        # Testing with known good value
        result = db_deviceagent.device_agent_exists(
            self.expected['idx_device'], self.expected['idx_agent'])
        self.assertEqual(result, True)

        # Testing with known good value
        result = db_deviceagent.device_agent_exists(None, None)
        self.assertEqual(result, False)

    def test_all_device_indices(self):
        """Testing function all_device_indices."""
        # Testing with known good value
        result = db_deviceagent.all_device_indices()
        self.assertEqual(result, [1])

    def test_device_indices(self):
        """Testing function device_indices."""
        # Testing with known good value
        result = db_deviceagent.device_indices(self.expected['idx_agent'])
        self.assertEqual(result, [1])

    def test_agent_indices(self):
        """Testing function agent_indices."""
        # Testing with known good value
        result = db_deviceagent.agent_indices(self.expected['idx_device'])
        self.assertEqual(result, [1])

    def test_get_all_device_agents(self):
        """Testing function get_all_device_agents."""
        results = db_deviceagent.get_all_device_agents()

        # There should only be one item in the result list
        self.assertEqual(len(results), 1)

        # Verify values in only result item
        for result in results:
            for key, _ in result.items():
                self.assertEqual(result[key], self.expected[key])
示例#4
0
    def test_valid(self):
        """Testing function valid."""
        # Drop the database and create tables
        unittest_setup_db.TestData()

        # Test with valid data
        result = validate.ValidateCache(data=self.data)
        self.assertEqual(result.valid(), True)

        # Test with invalid data (string)
        result = validate.ValidateCache(data='string')
        self.assertEqual(result.valid(), False)
示例#5
0
    def test_getinfo(self):
        """Testing function getinfo."""
        # Drop the database and create tables
        unittest_setup_db.TestData()

        # Test with valid data
        result = validate.ValidateCache(data=self.data)
        data_dict = result.getinfo()

        # Check main keys
        for key, _ in self.data.items():
            self.assertEqual(self.data[key], data_dict[key])
示例#6
0
class APITestCase(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_agent'] = database.idx_agent()

    # Retrieve data
    good_agent = db_agent.GetIDXAgent(expected['idx_agent'])

    def setUp(self):
        """Setup the environment prior to testing."""
        API.config['TESTING'] = True
        self.API = API.test_client()

    def test_agents(self):
        """Testing method / function agents."""
        # Initializing key variables
        response = self.API.get(
            '/infoset/api/v1/agents/{}'.format(self.expected['idx_agent']))
        data = json.loads(response.get_data(as_text=True))

        # Verify reponse code
        self.assertEqual(response.status_code, 200)

        # Verify response content
        self.assertEqual(isinstance(data, dict), True)
        self.assertEqual(data['id_agent'], self.good_agent.id_agent())
        self.assertEqual(data['exists'], self.good_agent.exists())
        self.assertEqual(data['enabled'], self.good_agent.enabled())

    def test_agents_query(self):
        """Testing method / function agents_query."""
        # Initializing key variables
        response = self.API.get('/infoset/api/v1/agents')
        data = json.loads(response.get_data(as_text=True))

        # Verify reponse code
        self.assertEqual(response.status_code, 200)

        # Verify response content
        self.assertEqual(isinstance(data, list), True)
        self.assertEqual(data[0]['id_agent'], self.good_agent.id_agent())
        self.assertEqual(data[0]['exists'], self.good_agent.exists())
        self.assertEqual(data[0]['enabled'], self.good_agent.enabled())
示例#7
0
class Other(unittest.TestCase):
    """Checks all functions and methods."""

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_agent'] = database.idx_agent()
    expected['idx_agentname'] = database.idx_agentname()
    expected['id_agent'] = database.id_agent()
    expected['enabled'] = True
    expected['exists'] = True

    # Retrieve data
    good_agent = db_agent.GetIDXAgent(expected['idx_agent'])

    def test_id_agent_exists(self):
        """Testing function id_agent_exists."""
        # Testing with known good value
        expected = True
        result = db_agent.id_agent_exists(self.expected['id_agent'])
        self.assertEqual(result, expected)

        # Testing with known bad value
        expected = False
        result = db_agent.id_agent_exists('bogus')
        self.assertEqual(result, expected)

    def test_idx_agent_exists(self):
        """Testing function idx_agent_exists."""
        # Testing with known good value
        expected = True
        result = db_agent.idx_agent_exists(self.expected['idx_agent'])
        self.assertEqual(result, expected)

        # Testing with known bad value
        expected = False
        result = db_agent.idx_agent_exists(None)
        self.assertEqual(result, expected)

    def test_get_all_agents(self):
        """Testing function get_all_agents."""
        # Testing with known good value
        result = db_agent.get_all_agents()
        self.assertEqual(isinstance(result, list), True)
        self.assertEqual(result[0]['idx_agent'], self.expected['idx_agent'])
        self.assertEqual(result[0]['exists'], self.expected['exists'])
        self.assertEqual(result[0]['enabled'], self.expected['enabled'])
        self.assertEqual(result[0]['idx_agentname'],
                         self.expected['idx_agentname'])
示例#8
0
class TestFunctions(unittest.TestCase):
    """Checks all functions."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_device'] = database.idx_device()
    expected['devicename'] = database.devicename()
    expected['description'] = database.device_description()
    expected['enabled'] = True
    expected['exists'] = True

    def test_all_devices(self):
        """Testing function all_devices."""
        # Test known working value
        results = db_device.all_devices()
        for result in results:
            for key, _ in result.items():
                self.assertEqual(result[key], self.expected[key])

    def test_devicename_exists(self):
        """Testing function devicename_exists."""
        # Test known working value
        result = db_device.devicename_exists(self.expected['devicename'])
        self.assertEqual(result, True)

        # Test known false value
        result = db_device.devicename_exists(False)
        self.assertEqual(result, False)

    def test_idx_device_exists(self):
        """Testing function idx_exists."""
        # Test known working value
        result = db_device.idx_device_exists(self.expected['idx_device'])
        self.assertEqual(result, True)

        # Test known false value
        result = db_device.idx_device_exists(-1)
        self.assertEqual(result, False)
class TestFunctions(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_datapoint'] = database.idx_datapoint()
    expected['id_agent'] = database.id_agent()
    expected['devicename'] = database.devicename()
    expected['agent_label'] = database.agent_label()
    expected['agent_source'] = database.agent_source()
    expected['agent'] = database.agent()
    expected['idx_deviceagent'] = database.idx_deviceagent()

    def test_datapoint_summary_list(self):
        """Testing function datapoint_summary_list."""
        # Start testing
        results = db_multitable.datapoint_summary_list()
        for data_dict in results:
            for key, _ in data_dict.items():
                self.assertEqual(data_dict[key], self.expected[key])

    def test_datapoint_summary(self):
        """Testing function datapoint_summary."""
        # Start testing
        result = db_multitable.datapoint_summary()
        for idx_datapoint, _ in result.items():
            data_dict = result[idx_datapoint]
            for key, _ in data_dict.items():
                self.assertEqual(data_dict[key], self.expected[key])

    def test__datapoint_summary(self):
        """Testing function _datapoint_summary."""
        # Tested by test_datapoint_summary and test_datapoint_summary_list
        pass
示例#10
0
class TestFunctions(unittest.TestCase):
    """Checks all functions and methods."""

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_department'] = database.idx_department()
    expected['name'] = database.department_name()
    expected['code'] = database.department_code()
    expected['enabled'] = True
    expected['exists'] = True

    def test_code_exists(self):
        """Testing function code_exists."""
        # Testing with known good value
        expected = True
        result = db_department.code_exists(self.expected['code'])
        self.assertEqual(result, expected)

        # Testing with known bad value
        expected = False
        result = db_department.code_exists('bogus')
        self.assertEqual(result, expected)

    def test_idx_department_exists(self):
        """Testing function idx_department_exists."""
        # Testing with known good value
        expected = True
        result = db_department.idx_department_exists(
            self.expected['idx_department'])
        self.assertEqual(result, expected)

        # Testing with known bad value
        expected = False
        result = db_department.idx_department_exists(None)
        self.assertEqual(result, expected)
示例#11
0
class TestGetCodeBillcode(unittest.TestCase):
    """Checks all functions and methods."""

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_billcode'] = database.idx_billcode()
    expected['name'] = database.billcode_name()
    expected['code'] = database.billcode_code()
    expected['enabled'] = True
    expected['exists'] = True

    # Retrieve data
    good_agent = db_billcode.GetCodeBillcode(expected['code'])

    def test_init_getcode(self):
        """Testing method __init__."""
        # Test with non existent AgentID
        record = db_billcode.GetCodeBillcode('bogus')
        self.assertEqual(record.enabled(), None)
        self.assertEqual(record.idx_billcode(), None)
        self.assertEqual(record.code(), None)
        self.assertEqual(record.name(), None)
        self.assertEqual(record.exists(), False)

    def test_idx_billcode(self):
        """Testing method idx_billcode."""
        # Testing with known good value
        result = self.good_agent.idx_billcode()
        self.assertEqual(result, self.expected['idx_billcode'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.idx_billcode()
        self.assertNotEqual(result, expected)

    def test_name(self):
        """Testing method name."""
        # Testing with known good value
        result = self.good_agent.name()
        self.assertEqual(result, self.expected['name'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.name()
        self.assertNotEqual(result, expected)

    def test_code(self):
        """Testing method code."""
        # Testing with known good value
        result = self.good_agent.code()
        self.assertEqual(result, self.expected['code'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.code()
        self.assertNotEqual(result, expected)

    def test_exists(self):
        """Testing method exists."""
        # Testing with known good value
        result = self.good_agent.exists()
        self.assertEqual(result, True)

    def test_enabled(self):
        """Testing method enabled."""
        # Testing with known good value
        result = self.good_agent.enabled()
        self.assertEqual(result, self.expected['enabled'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.enabled()
        self.assertNotEqual(result, expected)

    def test_everything(self):
        """Testing method everything."""
        # Testing with known good value
        result = self.good_agent.everything()
        for key, _ in self.expected.items():
            self.assertEqual(result[key], self.expected[key])

        # Test the number and names of keys
        keys = ['idx_billcode', 'code', 'name', 'enabled', 'exists']
        self.assertEqual(len(result), len(keys))
        for key in keys:
            self.assertEqual(key in result, True)
示例#12
0
class APITestCase(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_deviceagent'] = database.idx_deviceagent()

    # Retrieve data
    test_object = db_deviceagent.GetIDXDeviceAgent(expected['idx_deviceagent'])

    def setUp(self):
        """Setup the environment prior to testing."""
        # Test mode
        API.config['TESTING'] = True
        self.API = API.test_client()

    def test_deviceagents_query(self):
        """Testing method / function db_getidxdeviceagent."""
        # Clear the memory cache
        CACHE.clear()

        # Get results
        uri = ('/infoset/api/v1/deviceagents/{}'
               ''.format(self.expected['idx_deviceagent']))
        response = self.API.get(uri)
        result = json.loads(response.get_data(as_text=True))

        # Verify reponse code
        self.assertEqual(response.status_code, 200)

        # Verify response content
        self.assertEqual(isinstance(result, dict), True)
        self.assertEqual(result['idx_device'], self.test_object.idx_device())
        self.assertEqual(result['exists'], self.test_object.exists())
        self.assertEqual(result['enabled'], self.test_object.enabled())
        self.assertEqual(result['idx_agent'], self.test_object.idx_agent())
        self.assertEqual(result['last_timestamp'],
                         self.test_object.last_timestamp())
        self.assertEqual(result['idx_deviceagent'],
                         self.test_object.idx_deviceagent())

        # Test the number and names of keys
        keys = [
            'last_timestamp', 'idx_deviceagent', 'idx_agent', 'idx_device',
            'enabled', 'exists'
        ]
        self.assertEqual(len(result), len(keys))
        for key in keys:
            self.assertEqual(key in result, True)

    def test_deviceagents(self):
        """Testing method / function db_devagt_get_all_device_agents."""
        # Clear the memory cache
        CACHE.clear()

        # Get results
        response = self.API.get('/infoset/api/v1/deviceagents')
        data = json.loads(response.get_data(as_text=True))
        result = data[0]

        # Verify reponse code
        self.assertEqual(response.status_code, 200)

        # Verify response content
        self.assertEqual(isinstance(data, list), True)
        self.assertEqual(result['idx_device'], self.test_object.idx_device())
        self.assertEqual(result['exists'], self.test_object.exists())
        self.assertEqual(result['enabled'], self.test_object.enabled())
        self.assertEqual(result['idx_agent'], self.test_object.idx_agent())
        self.assertEqual(result['last_timestamp'],
                         self.test_object.last_timestamp())
        self.assertEqual(result['idx_deviceagent'],
                         self.test_object.idx_deviceagent())

        # Test the number and names of keys
        keys = [
            'last_timestamp', 'idx_deviceagent', 'idx_agent', 'idx_device',
            'enabled', 'exists'
        ]
        self.assertEqual(len(result), len(keys))
        for key in keys:
            self.assertEqual(key in result, True)
示例#13
0
class TestGetIDXDevice(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_device'] = database.idx_device()
    expected['devicename'] = database.devicename()
    expected['description'] = database.device_description()
    expected['enabled'] = True
    expected['exists'] = True

    # Create device object
    good_device = db_device.GetIDXDevice(expected['idx_device'])

    def test_init(self):
        """Testing method __init__."""
        # Test with non existent IDXDevice
        record = db_device.GetIDXDevice('bogus')
        self.assertEqual(record.exists(), False)
        self.assertEqual(record.devicename(), None)
        self.assertEqual(record.enabled(), None)
        self.assertEqual(record.description(), None)
        self.assertEqual(record.idx_device(), None)

    def test_devicename(self):
        """Testing method devicename."""
        # Testing with known good value
        result = self.good_device.devicename()
        self.assertEqual(result, self.expected['devicename'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_device.devicename()
        self.assertNotEqual(result, expected)

    def test_description(self):
        """Testing function description."""
        # Testing with known good value
        result = self.good_device.description()
        self.assertEqual(result, self.expected['description'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_device.description()
        self.assertNotEqual(result, expected)

    def test_enabled(self):
        """Testing function enabled."""
        # Testing with known good value
        result = self.good_device.enabled()
        self.assertEqual(result, self.expected['enabled'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_device.enabled()
        self.assertNotEqual(result, expected)

    def test_exists(self):
        """Testing function exists."""
        # Testing with known good value
        result = self.good_device.exists()
        self.assertEqual(result, True)

    def test_everything(self):
        """Testing method everything."""
        # Testing with known good value
        result = self.good_device.everything()
        for key, _ in self.expected.items():
            self.assertEqual(result[key], self.expected[key])

        # Test the number and names of keys
        keys = ['idx_device', 'devicename', 'description', 'enabled', 'exists']
        self.assertEqual(len(result), len(keys))
        for key in keys:
            self.assertEqual(key in result, True)
示例#14
0
class TestGetDevice(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_device'] = database.idx_device()
    expected['devicename'] = database.devicename()
    expected['description'] = database.device_description()
    expected['enabled'] = True
    expected['exists'] = True

    # Create device object
    good_device = db_device.GetDevice(expected['devicename'])

    def test___init__(self):
        """Testing function __init__."""
        # Test with non existent DeviceIDX
        record = db_device.GetDevice('bogus')
        self.assertEqual(record.exists(), False)
        self.assertEqual(record.devicename(), None)
        self.assertEqual(record.enabled(), None)
        self.assertEqual(record.description(), None)
        self.assertEqual(record.idx_device(), None)

    def test_idx_device(self):
        """Testing method idx_device."""
        # Testing with known good value
        result = self.good_device.idx_device()
        self.assertEqual(result, self.expected['idx_device'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_device.devicename()
        self.assertNotEqual(result, expected)

    def test_exists(self):
        """Testing function exists."""
        # Testing with known good value
        result = self.good_device.exists()
        self.assertEqual(result, True)

    def test_description(self):
        """Testing function description."""
        # Testing with known good value
        result = self.good_device.description()
        self.assertEqual(result, self.expected['description'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_device.description()
        self.assertNotEqual(result, expected)

    def test_enabled(self):
        """Testing function enabled."""
        # Testing with known good value
        result = self.good_device.enabled()
        self.assertEqual(result, self.expected['enabled'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_device.enabled()
        self.assertNotEqual(result, expected)
示例#15
0
class APITestCase(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_datapoint'] = database.idx_datapoint()
    expected['id_datapoint'] = database.id_datapoint()
    expected['idx_deviceagent'] = database.idx_deviceagent()
    expected['id_agent'] = database.id_agent()
    expected['devicename'] = database.devicename()
    expected['agent'] = database.agent()
    expected['values'] = database.values()

    # Retrieve data
    test_object = db_datapoint.GetIDXDatapoint(expected['idx_datapoint'])

    def setUp(self):
        """Setup the environment prior to testing."""
        # Test mode
        API.config['TESTING'] = True
        self.API = API.test_client()

    def test_datapoints(self):
        """Testing method / function datapoints."""
        # Clear the memory cache
        CACHE.clear()

        # Get results
        uri = ('/infoset/api/v1/datapoints/{}'.format(
            self.expected['idx_datapoint']))
        response = self.API.get(uri)
        result = json.loads(response.get_data(as_text=True))

        # Verify reponse code
        self.assertEqual(response.status_code, 200)

        # Verify response content
        self.assertEqual(isinstance(result, dict), True)
        self.assertEqual(result['idx_datapoint'],
                         self.test_object.idx_datapoint())
        self.assertEqual(result['id_datapoint'],
                         self.test_object.id_datapoint())
        self.assertEqual(result['idx_deviceagent'],
                         self.test_object.idx_deviceagent())
        self.assertEqual(result['idx_department'],
                         self.test_object.idx_department())
        self.assertEqual(result['idx_billcode'],
                         self.test_object.idx_billcode())
        self.assertEqual(result['agent_label'], self.test_object.agent_label())
        self.assertEqual(result['agent_source'],
                         self.test_object.agent_source())
        self.assertEqual(result['billable'], self.test_object.billable())
        self.assertEqual(result['base_type'], self.test_object.base_type())
        self.assertEqual(result['timefixed_value'],
                         self.test_object.timefixed_value())
        self.assertEqual(result['last_timestamp'],
                         self.test_object.last_timestamp())
        self.assertEqual(result['exists'], self.test_object.exists())
        self.assertEqual(result['enabled'], self.test_object.enabled())

        # Test the number and names of keys
        keys = [
            'idx_datapoint', 'id_datapoint', 'idx_deviceagent',
            'idx_department', 'idx_billcode', 'agent_label', 'agent_source',
            'enabled', 'billable', 'base_type', 'timefixed_value',
            'last_timestamp', 'exists'
        ]
        self.assertEqual(len(result), len(keys))
        for key in keys:
            self.assertEqual(key in result, True)

    def test_datapoints_query_1(self):
        """Testing method / function datapoints_query."""
        # Clear the memory cache
        CACHE.clear()

        #######################################################################
        # Try with id_datapoint in query string
        #######################################################################

        # Get results
        uri = ('/infoset/api/v1/datapoints?id_datapoint={}'
               ''.format(self.expected['id_datapoint']))
        response = self.API.get(uri)
        data = json.loads(response.get_data(as_text=True))
        result = data[0]

        # Verify reponse code
        self.assertEqual(response.status_code, 200)

        # Verify response content
        self.assertEqual(isinstance(data, list), True)
        self.assertEqual(result['idx_datapoint'],
                         self.test_object.idx_datapoint())
        self.assertEqual(result['id_datapoint'],
                         self.test_object.id_datapoint())
        self.assertEqual(result['idx_deviceagent'],
                         self.test_object.idx_deviceagent())
        self.assertEqual(result['idx_department'],
                         self.test_object.idx_department())
        self.assertEqual(result['idx_billcode'],
                         self.test_object.idx_billcode())
        self.assertEqual(result['agent_label'], self.test_object.agent_label())
        self.assertEqual(result['agent_source'],
                         self.test_object.agent_source())
        self.assertEqual(result['billable'], self.test_object.billable())
        self.assertEqual(result['base_type'], self.test_object.base_type())
        self.assertEqual(result['timefixed_value'],
                         self.test_object.timefixed_value())
        self.assertEqual(result['last_timestamp'],
                         self.test_object.last_timestamp())
        self.assertEqual(result['exists'], self.test_object.exists())
        self.assertEqual(result['enabled'], self.test_object.enabled())

        # Test the number and names of keys
        keys = [
            'idx_datapoint', 'id_datapoint', 'idx_deviceagent',
            'idx_department', 'idx_billcode', 'agent_label', 'agent_source',
            'enabled', 'billable', 'base_type', 'timefixed_value',
            'last_timestamp', 'exists'
        ]
        self.assertEqual(len(result), len(keys))
        for key in keys:
            self.assertEqual(key in result, True)

        #######################################################################
        # Try with idx_deviceagent in query string
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results
        uri = ('/infoset/api/v1/datapoints?idx_deviceagent={}'
               ''.format(self.expected['idx_deviceagent']))
        response = self.API.get(uri)
        data = json.loads(response.get_data(as_text=True))
        result = data[0]

        # Verify reponse code
        self.assertEqual(response.status_code, 200)

        # Verify response content
        self.assertEqual(isinstance(data, list), True)
        self.assertEqual(result['idx_datapoint'],
                         self.test_object.idx_datapoint())
        self.assertEqual(result['id_datapoint'],
                         self.test_object.id_datapoint())
        self.assertEqual(result['idx_deviceagent'],
                         self.test_object.idx_deviceagent())
        self.assertEqual(result['idx_department'],
                         self.test_object.idx_department())
        self.assertEqual(result['idx_billcode'],
                         self.test_object.idx_billcode())
        self.assertEqual(result['agent_label'], self.test_object.agent_label())
        self.assertEqual(result['agent_source'],
                         self.test_object.agent_source())
        self.assertEqual(result['billable'], self.test_object.billable())
        self.assertEqual(result['base_type'], self.test_object.base_type())
        self.assertEqual(result['timefixed_value'],
                         self.test_object.timefixed_value())
        self.assertEqual(result['last_timestamp'],
                         self.test_object.last_timestamp())
        self.assertEqual(result['exists'], self.test_object.exists())
        self.assertEqual(result['enabled'], self.test_object.enabled())

        # Test the number and names of keys
        keys = [
            'idx_datapoint', 'id_datapoint', 'idx_deviceagent',
            'idx_department', 'idx_billcode', 'agent_label', 'agent_source',
            'enabled', 'billable', 'base_type', 'timefixed_value',
            'last_timestamp', 'exists'
        ]
        self.assertEqual(len(result), len(keys))
        for key in keys:
            self.assertEqual(key in result, True)

    def test_getdata_secondsago_1(self):
        """Testing method / function getdata."""
        # Clear the memory cache
        CACHE.clear()

        # Initialize key variables
        precision = 5

        #######################################################################
        # Try an hour ago
        #######################################################################

        # Get results for up to an hour ago
        uri = ('/infoset/api/v1/datapoints/{}/data?secondsago=3600'
               ''.format(self.expected['idx_datapoint']))
        response = self.API.get(uri)
        result = json.loads(response.get_data(as_text=True))

        # Convert the list of expected values to an easy to compare dict
        check_dict = {}
        for item in self.expected['values']:
            check_dict[str(item['timestamp'])] = item['value']

        # Verify the expected data is there
        for timestamp, value in sorted(result.items()):
            if timestamp in check_dict:
                self.assertEqual(round(result[timestamp], precision),
                                 round(check_dict[timestamp], precision))
            else:
                self.assertEqual(value, 0)

        #######################################################################
        # Try an 1/4 ago. No data should be present
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results
        uri = ('/infoset/api/v1/datapoints/{}/data?secondsago=900'
               ''.format(self.expected['idx_datapoint']))
        response = self.API.get(uri)
        result = json.loads(response.get_data(as_text=True))

        # Go through the results
        for timestamp, value in sorted(result.items()):
            self.assertEqual(result[timestamp], 0)
            self.assertEqual(value, 0)

    def test_getdata_timestamp(self):
        """Testing method / function getdata."""
        # Clear the memory cache
        CACHE.clear()

        # Initialize key variables
        precision = 5
        ts_stop = int(datetime.utcnow().timestamp())
        ts_start = ts_stop - 3600

        # Get results for up to 1/4 hour ago - No data should be present
        uri = ('/infoset/api/v1/datapoints/{}/data?ts_start={}&ts_stop={}'
               ''.format(self.expected['idx_datapoint'], ts_start, ts_stop))
        response = self.API.get(uri)
        result = json.loads(response.get_data(as_text=True))

        # Convert the list of expected values to an easy to compare dict
        check_dict = {}
        for item in self.expected['values']:
            check_dict[str(item['timestamp'])] = item['value']

        # Verify the expected data is there
        for timestamp, value in sorted(result.items()):
            if timestamp in check_dict:
                self.assertEqual(round(result[timestamp], precision),
                                 round(check_dict[timestamp], precision))
            else:
                self.assertEqual(value, 0)

    def test_db_datapoint_summary(self):
        """Testing method / function db_datapoint_summary."""
        # Clear the memory cache
        CACHE.clear()

        # Get results
        uri = '/infoset/api/v1/datapoints/all/summary'
        response = self.API.get(uri)
        data = json.loads(response.get_data(as_text=True))

        # Verify reponse code
        self.assertEqual(response.status_code, 200)

        # Verify response content
        self.assertEqual(isinstance(data, dict), True)
        self.assertEqual(len(data), 1)

        for idx_datapoint, result in data.items():
            self.assertEqual(int(idx_datapoint),
                             self.test_object.idx_datapoint())

            self.assertEqual(result['idx_deviceagent'],
                             self.test_object.idx_deviceagent())
            self.assertEqual(result['agent_label'],
                             self.test_object.agent_label())
            self.assertEqual(result['agent_source'],
                             self.test_object.agent_source())

            # Get remaining values
            self.assertEqual(result['devicename'], self.expected['devicename'])
            self.assertEqual(result['id_agent'], self.expected['id_agent'])
            self.assertEqual(result['agent'], self.expected['agent'])

            # Test the number and names of keys
            keys = [
                'idx_deviceagent', 'agent_label', 'agent_source', 'devicename',
                'id_agent', 'agent'
            ]
            self.assertEqual(len(result), len(keys))
            for key in keys:
                self.assertEqual(key in result, True)

            # All done
            break

    def test_db_datapoint_summary_list(self):
        """Testing method / function db_datapoint_summary_list."""
        # Clear the memory cache
        CACHE.clear()

        # Get results
        uri = '/infoset/api/v1/datapoints/all/summarylist'
        response = self.API.get(uri)
        data = json.loads(response.get_data(as_text=True))
        result = data[0]

        # Verify reponse code
        self.assertEqual(response.status_code, 200)

        # Verify response content
        self.assertEqual(isinstance(data, list), True)
        self.assertEqual(result['idx_datapoint'],
                         self.test_object.idx_datapoint())
        self.assertEqual(result['idx_deviceagent'],
                         self.test_object.idx_deviceagent())
        self.assertEqual(result['agent_label'], self.test_object.agent_label())
        self.assertEqual(result['agent_source'],
                         self.test_object.agent_source())

        # Get remaining values
        self.assertEqual(result['devicename'], self.expected['devicename'])
        self.assertEqual(result['id_agent'], self.expected['id_agent'])
        self.assertEqual(result['agent'], self.expected['agent'])

        # Test the number and names of keys
        keys = [
            'idx_datapoint', 'idx_deviceagent', 'agent_label', 'agent_source',
            'devicename', 'id_agent', 'agent'
        ]
        self.assertEqual(len(result), len(keys))
        for key in keys:
            self.assertEqual(key in result, True)
示例#16
0
class APITestCase(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['values'] = database.values()
    expected['idx_device'] = database.idx_device()
    expected['idx_deviceagent'] = database.idx_deviceagent()
    expected['agent'] = database.agent()
    expected['devicename'] = database.devicename()
    expected['id_agent'] = database.id_agent()
    expected['agent_label'] = database.agent_label()

    # Retrieve data
    test_object = db_device.GetIDXDevice(expected['idx_device'])

    def setUp(self):
        """Setup the environment prior to testing."""
        # Test mode
        API.config['TESTING'] = True
        self.API = API.test_client()

    def test_lastcontacts(self):
        """Testing method / function lastcontacts."""
        # Initialize key variables
        precision = 5

        #######################################################################
        # Try with secondsago = 3600
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        uri = '/infoset/api/v1/lastcontacts?secondsago=3600'
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]
        result = results[0]

        self.assertEqual(result['timestamp'], expected['timestamp'])
        self.assertEqual(
            round(result['value'], precision),
            round(expected['value'], precision))

        #######################################################################
        # Try with secondsago = 60 (No values expected)
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to a minute ago
        uri = '/infoset/api/v1/lastcontacts?secondsago=60'
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)
        self.assertEqual(bool(results), False)

        #######################################################################
        # Try with ts_start = 0
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results
        uri = '/infoset/api/v1/lastcontacts?ts_start=0'
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]
        result = results[0]

        self.assertEqual(result['timestamp'], expected['timestamp'])
        self.assertEqual(
            round(result['value'], precision),
            round(expected['value'], precision))

        #######################################################################
        # Try with ts_start = an hour ago
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        ts_start = int(datetime.utcnow().timestamp()) - 3600
        uri = '/infoset/api/v1/lastcontacts?ts_start={}'.format(ts_start)
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]
        result = results[0]

        self.assertEqual(result['timestamp'], expected['timestamp'])
        self.assertEqual(
            round(result['value'], precision),
            round(expected['value'], precision))

        #######################################################################
        # Try with ts_start = a minute ago
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        ts_start = int(datetime.utcnow().timestamp()) - 60
        uri = '/infoset/api/v1/lastcontacts?ts_start={}'.format(ts_start)
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test type of result
        self.assertEqual(isinstance(results, list), True)
        self.assertEqual(bool(results), False)

    def test_id_agents(self):
        """Testing method / function id_agents."""
        # Initialize key variables
        precision = 5

        #######################################################################
        # Try with default values
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        uri = '/infoset/api/v1/lastcontacts/id_agents'
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Further testing
        result = results[0]
        self.assertEqual(result['agent'], self.expected['agent'])
        self.assertEqual(result['devicename'], self.expected['devicename'])
        self.assertEqual(result['id_agent'], self.expected['id_agent'])
        self.assertEqual('timeseries' in result, True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]

        # We should only have a single result to test
        for agent_label, data_dict in result['timeseries'].items():
            # Test match for agent_label
            self.assertEqual(agent_label, self.expected['agent_label'])

            for key, value in data_dict.items():
                # Test presence of timeseries values
                if key == 'timestamp':
                    self.assertEqual(value, expected['timestamp'])
                elif key == 'value':
                    self.assertEqual(
                        round(value, precision),
                        round(expected['value'], precision))

        #######################################################################
        # Try with secondsago = 3600
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        uri = '/infoset/api/v1/lastcontacts/id_agents?secondsago=3600'
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Further testing
        result = results[0]
        self.assertEqual(result['agent'], self.expected['agent'])
        self.assertEqual(result['devicename'], self.expected['devicename'])
        self.assertEqual(result['id_agent'], self.expected['id_agent'])
        self.assertEqual('timeseries' in result, True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]

        # We should only have a single result to test
        for agent_label, data_dict in result['timeseries'].items():
            # Test match for agent_label
            self.assertEqual(agent_label, self.expected['agent_label'])

            for key, value in data_dict.items():
                # Test presence of timeseries values
                if key == 'timestamp':
                    self.assertEqual(value, expected['timestamp'])
                elif key == 'value':
                    self.assertEqual(
                        round(value, precision),
                        round(expected['value'], precision))

        #######################################################################
        # Try with secondsago = 60 (No response expected)
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        uri = '/infoset/api/v1/lastcontacts/id_agents?secondsago=60'
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)
        self.assertEqual(bool(results), False)

        #######################################################################
        # Try with ts_star = 0
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        uri = '/infoset/api/v1/lastcontacts/id_agents?ts_start=0'
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Further testing
        result = results[0]
        self.assertEqual(result['agent'], self.expected['agent'])
        self.assertEqual(result['devicename'], self.expected['devicename'])
        self.assertEqual(result['id_agent'], self.expected['id_agent'])
        self.assertEqual('timeseries' in result, True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]

        # We should only have a single result to test
        for agent_label, data_dict in result['timeseries'].items():
            # Test match for agent_label
            self.assertEqual(agent_label, self.expected['agent_label'])

            for key, value in data_dict.items():
                # Test presence of timeseries values
                if key == 'timestamp':
                    self.assertEqual(value, expected['timestamp'])
                elif key == 'value':
                    self.assertEqual(
                        round(value, precision),
                        round(expected['value'], precision))

        #######################################################################
        # Try with ts_start = an hour ago
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        ts_start = int(datetime.utcnow().timestamp()) - 3600
        uri = (
            '/infoset/api/v1/lastcontacts/id_agents?ts_start={}'
            ''.format(ts_start))
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Further testing
        result = results[0]
        self.assertEqual(result['agent'], self.expected['agent'])
        self.assertEqual(result['devicename'], self.expected['devicename'])
        self.assertEqual(result['id_agent'], self.expected['id_agent'])
        self.assertEqual('timeseries' in result, True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]

        # We should only have a single result to test
        for agent_label, data_dict in result['timeseries'].items():
            # Test match for agent_label
            self.assertEqual(agent_label, self.expected['agent_label'])

            for key, value in data_dict.items():
                # Test presence of timeseries values
                if key == 'timestamp':
                    self.assertEqual(value, expected['timestamp'])
                elif key == 'value':
                    self.assertEqual(
                        round(value, precision),
                        round(expected['value'], precision))

        #######################################################################
        # Try with ts_start = 15 minutes ago (No values expected)
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        ts_start = int(datetime.utcnow().timestamp()) - 900
        uri = (
            '/infoset/api/v1/lastcontacts/id_agents?ts_start={}'
            ''.format(ts_start))
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)
        self.assertEqual(bool(results), False)

    def test_deviceagents(self):
        """Testing method / function deviceagents."""
        # Initialize key variables
        precision = 5

        #######################################################################
        # Try with secondsago = 3600
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        uri = (
            '/infoset/api/v1/lastcontacts/deviceagents/{}?secondsago=3600'
            ''.format(self.expected['idx_deviceagent']))
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]
        result = results[0]

        self.assertEqual(result['timestamp'], expected['timestamp'])
        self.assertEqual(
            round(result['value'], precision),
            round(expected['value'], precision))

        #######################################################################
        # Try with secondsago = 60 (No response expected)
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        uri = (
            '/infoset/api/v1/lastcontacts/deviceagents/{}?secondsago=60'
            ''.format(self.expected['idx_deviceagent']))
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)
        self.assertEqual(bool(results), False)

        #######################################################################
        # Try with ts_star = 0
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        uri = (
            '/infoset/api/v1/lastcontacts/deviceagents/{}?ts_start=0'
            ''.format(self.expected['idx_deviceagent']))
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]
        result = results[0]

        self.assertEqual(result['timestamp'], expected['timestamp'])
        self.assertEqual(
            round(result['value'], precision),
            round(expected['value'], precision))

        #######################################################################
        # Try with ts_start = an hour ago
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        ts_start = int(datetime.utcnow().timestamp()) - 3600
        uri = (
            '/infoset/api/v1/lastcontacts/deviceagents/{}?ts_start={}'
            ''.format(self.expected['idx_deviceagent'], ts_start))
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]
        result = results[0]

        self.assertEqual(result['timestamp'], expected['timestamp'])
        self.assertEqual(
            round(result['value'], precision),
            round(expected['value'], precision))

        #######################################################################
        # Try with ts_start = 15 minutes ago (No values expected)
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        ts_start = int(datetime.utcnow().timestamp()) - 900
        uri = (
            '/infoset/api/v1/lastcontacts/deviceagents/{}?ts_start={}'
            ''.format(self.expected['idx_deviceagent'], ts_start))
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)
        self.assertEqual(bool(results), False)

    def test_devicename_agents(self):
        """Testing method / function devicename_agents."""
        # Initialize key variables
        precision = 5

        #######################################################################
        # Try with secondsago = 3600
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        uri = (
            '/infoset/api/v1/lastcontacts/devicenames/{}/id_agents/{}'
            '?secondsago=3600'
            ''.format(self.expected['devicename'], self.expected['id_agent']))
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]
        result = results[0]

        self.assertEqual(result['timestamp'], expected['timestamp'])
        self.assertEqual(
            round(result['value'], precision),
            round(expected['value'], precision))

        #######################################################################
        # Try with secondsago = 60 (No response expected)
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        uri = (
            '/infoset/api/v1/lastcontacts/devicenames/{}/id_agents/{}'
            '?secondsago=60'
            ''.format(self.expected['devicename'], self.expected['id_agent']))
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)
        self.assertEqual(bool(results), False)

        #######################################################################
        # Try with ts_star = 0
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        uri = (
            '/infoset/api/v1/lastcontacts/devicenames/{}/id_agents/{}'
            '?ts_start=0'
            ''.format(self.expected['devicename'], self.expected['id_agent']))
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]
        result = results[0]

        self.assertEqual(result['timestamp'], expected['timestamp'])
        self.assertEqual(
            round(result['value'], precision),
            round(expected['value'], precision))

        #######################################################################
        # Try with ts_start = an hour ago
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        ts_start = int(datetime.utcnow().timestamp()) - 3600
        uri = (
            '/infoset/api/v1/lastcontacts/devicenames/{}/id_agents/{}'
            '?ts_start={}'
            ''.format(
                self.expected['devicename'],
                self.expected['id_agent'],
                ts_start))
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)

        # First item in expected should be the most recent contact.
        # Expected['values'] is sorted by timestamp.
        expected = self.expected['values'][0]
        result = results[0]

        self.assertEqual(result['timestamp'], expected['timestamp'])
        self.assertEqual(
            round(result['value'], precision),
            round(expected['value'], precision))

        #######################################################################
        # Try with ts_start = 15 minutes ago (No values expected)
        #######################################################################

        # Clear the memory cache
        CACHE.clear()

        # Get results for up to an hour ago
        ts_start = int(datetime.utcnow().timestamp()) - 900
        uri = (
            '/infoset/api/v1/lastcontacts/devicenames/{}/id_agents/{}'
            '?ts_start={}'
            ''.format(
                self.expected['devicename'],
                self.expected['id_agent'],
                ts_start))
        response = self.API.get(uri)
        results = json.loads(response.get_data(as_text=True))

        # Test
        self.assertEqual(isinstance(results, list), True)
        self.assertEqual(bool(results), False)

    def test__start_timestamp(self):
        """Testing method / function _start_timestamp."""
        # Tested by other unittests here
        pass
示例#17
0
class TestGetDeviceAgent(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_deviceagent'] = database.idx_deviceagent()
    expected['idx_device'] = database.idx_device()
    expected['idx_agent'] = database.idx_agent()
    expected['last_timestamp'] = database.last_timestamp()
    expected['enabled'] = True
    expected['exists'] = True

    # Create device object
    good_device = db_deviceagent.GetDeviceAgent(expected['idx_device'],
                                                expected['idx_agent'])

    def test___init__(self):
        """Testing method __init__."""
        # Test with non existent IDXDevice
        record = db_deviceagent.GetDeviceAgent('bogus', 'bogus')
        self.assertEqual(record.exists(), False)
        self.assertEqual(record.enabled(), None)
        self.assertEqual(record.idx_agent(), None)
        self.assertEqual(record.idx_device(), None)
        self.assertEqual(record.idx_deviceagent(), None)
        self.assertEqual(record.last_timestamp(), None)

    def test_exists(self):
        """Testing method exists."""
        # Testing with known good value
        result = self.good_device.exists()
        self.assertEqual(result, True)

        # Test with known bad value
        expected = db_deviceagent.GetDeviceAgent(None, None)
        result = expected.exists()
        self.assertEqual(result, False)

    def test_enabled(self):
        """Testing method enabled."""
        # Testing with known good value
        result = self.good_device.enabled()
        self.assertEqual(result, True)

    def test_last_timestamp(self):
        """Testing method last_timestamp."""
        # Testing with known good value
        result = self.good_device.last_timestamp()
        self.assertEqual(result, self.expected['last_timestamp'])

    def test_idx_deviceagent(self):
        """Testing method idx_deviceagent."""
        # Testing with known good value
        result = self.good_device.idx_deviceagent()
        self.assertEqual(result, self.expected['idx_deviceagent'])

    def test_idx_agent(self):
        """Testing method idx_agent."""
        # Testing with known good value
        result = self.good_device.idx_agent()
        self.assertEqual(result, self.expected['idx_agent'])

    def test_idx_device(self):
        """Testing method idx_device."""
        # Testing with known good value
        result = self.good_device.idx_device()
        self.assertEqual(result, self.expected['idx_device'])

    def test_everything(self):
        """Testing method everything."""
        # Testing with known good value
        result = self.good_device.everything()
        for key, _ in self.expected.items():
            self.assertEqual(result[key], self.expected[key])

        # Test the number and names of keys
        keys = [
            'last_timestamp', 'idx_deviceagent', 'idx_agent', 'idx_device',
            'enabled', 'exists'
        ]
        self.assertEqual(len(result), len(keys))
        for key in keys:
            self.assertEqual(key in result, True)
示例#18
0
class TestGetIDX(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['id_datapoint'] = database.id_datapoint()
    expected['last_timestamp'] = database.timestamp()
    expected['idx_deviceagent'] = database.idx_deviceagent()
    expected['idx_datapoint'] = database.idx_datapoint()
    expected['idx_department'] = database.idx_department()
    expected['idx_billcode'] = database.idx_billcode()
    expected['agent_label'] = database.agent_label()
    expected['agent_source'] = database.agent_source()
    expected['enabled'] = True
    expected['exists'] = True
    expected['billable'] = False
    expected['base_type'] = 1
    expected['timefixed_value'] = None

    # Retriev edata
    testing = db_datapoint.GetIDXDatapoint(expected['idx_datapoint'])

    def test___init__(self):
        """Testing function __init__."""
        # Test with non existent AgentIDX
        record = db_datapoint.GetIDXDatapoint(-1)
        self.assertEqual(record.exists(), False)
        self.assertEqual(record.enabled(), None)
        self.assertEqual(record.last_timestamp(), None)
        self.assertEqual(record.timefixed_value(), None)
        self.assertEqual(record.base_type(), None)
        self.assertEqual(record.billable(), None)
        self.assertEqual(record.agent_source(), None)
        self.assertEqual(record.idx_deviceagent(), None)
        self.assertEqual(record.id_datapoint(), None)
        self.assertEqual(record.idx_datapoint(), None)
        self.assertEqual(record.idx_department(), None)
        self.assertEqual(record.idx_billcode(), None)
        self.assertEqual(record.agent_label(), None)

    def test_exists(self):
        """Testing function exists."""
        # Testing with known good value
        result = self.testing.exists()
        self.assertEqual(result, self.expected['exists'])

    def test_everything(self):
        """Testing function everything."""
        # Testing with known good value
        result = self.testing.everything()
        for key, _ in result.items():
            self.assertEqual(result[key], self.expected[key])

    def test_last_timestamp(self):
        """Testing function last_timestamp."""
        # Testing with known good value
        result = self.testing.last_timestamp()
        self.assertEqual(result, self.expected['last_timestamp'])

    def test_timefixed_value(self):
        """Testing function timefixed_value."""
        # Testing with known good value
        result = self.testing.timefixed_value()
        self.assertEqual(result, self.expected['timefixed_value'])

    def test_base_type(self):
        """Testing function base_type."""
        # Testing with known good value
        result = self.testing.base_type()
        self.assertEqual(result, self.expected['base_type'])

    def test_enabled(self):
        """Testing function enabled."""
        # Testing with known good value
        result = self.testing.base_type()
        self.assertEqual(result, self.expected['enabled'])

    def test_billable(self):
        """Testing function billable."""
        # Testing with known good value
        result = self.testing.billable()
        self.assertEqual(result, self.expected['billable'])

    def test_agent_source(self):
        """Testing function agent_source."""
        # Testing with known good value
        result = self.testing.agent_source()
        self.assertEqual(result, self.expected['agent_source'])

    def test_idx_deviceagent(self):
        """Testing function idx_deviceagent."""
        # Testing with known good value
        result = self.testing.idx_deviceagent()
        self.assertEqual(result, self.expected['idx_deviceagent'])

    def test_id_datapoint(self):
        """Testing function id_datapoint."""
        # Testing with known good value
        result = self.testing.id_datapoint()
        self.assertEqual(result, self.expected['id_datapoint'])

    def test_idx_datapoint(self):
        """Testing function idx_datapoint."""
        # Testing with known good value
        result = self.testing.idx_datapoint()
        self.assertEqual(result, self.expected['idx_datapoint'])

    def test_idx_department(self):
        """Testing function idx_department."""
        # Testing with known good value
        result = self.testing.idx_department()
        self.assertEqual(result, self.expected['idx_department'])

    def test_idx_billcode(self):
        """Testing function idx_billcode."""
        # Testing with known good value
        result = self.testing.idx_billcode()
        self.assertEqual(result, self.expected['idx_billcode'])

    def test_agent_label(self):
        """Testing function agent_label."""
        # Testing with known good value
        result = self.testing.agent_label()
        self.assertEqual(result, self.expected['agent_label'])
示例#19
0
class TestGetCodeDepartment(unittest.TestCase):
    """Checks all functions and methods."""

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_department'] = database.idx_department()
    expected['name'] = database.department_name()
    expected['code'] = database.department_code()
    expected['enabled'] = True
    expected['exists'] = True

    # Retrieve data
    good_agent = db_department.GetCodeDepartment(expected['code'])

    def test_init_getcode(self):
        """Testing method __init__."""
        # Test with non existent AgentID
        record = db_department.GetCodeDepartment('bogus')
        self.assertEqual(record.exists(), False)

    def test_idx_department(self):
        """Testing method idx_department."""
        # Testing with known good value
        result = self.good_agent.idx_department()
        self.assertEqual(result, self.expected['idx_department'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.idx_department()
        self.assertNotEqual(result, expected)

    def test_name(self):
        """Testing method name."""
        # Testing with known good value
        result = self.good_agent.name()
        self.assertEqual(result, self.expected['name'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.name()
        self.assertNotEqual(result, expected)

    def test_code(self):
        """Testing method code."""
        # Testing with known good value
        result = self.good_agent.code()
        self.assertEqual(result, self.expected['code'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.code()
        self.assertNotEqual(result, expected)

    def test_exists(self):
        """Testing method exists."""
        # Testing with known good value
        result = self.good_agent.exists()
        self.assertEqual(result, True)

    def test_enabled(self):
        """Testing method enabled."""
        # Testing with known good value
        result = self.good_agent.enabled()
        self.assertEqual(result, self.expected['enabled'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.enabled()
        self.assertNotEqual(result, expected)
示例#20
0
class TestGetIDXDeviceAgent(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_deviceagent'] = database.idx_deviceagent()
    expected['idx_device'] = database.idx_device()
    expected['idx_agent'] = database.idx_agent()
    expected['timestamp'] = database.timestamp()
    expected['enabled'] = True
    expected['exists'] = True

    # Create device object
    good_device = db_deviceagent.GetIDXDeviceAgent(expected['idx_deviceagent'])

    def test___init__(self):
        """Testing method __init__."""
        # Test with non existent IDXDevice
        record = db_deviceagent.GetIDXDeviceAgent('bogus')
        self.assertEqual(record.exists(), False)
        self.assertEqual(record.enabled(), None)
        self.assertEqual(record.idx_agent(), None)
        self.assertEqual(record.idx_device(), None)
        self.assertEqual(record.idx_deviceagent(), None)
        self.assertEqual(record.last_timestamp(), None)

        record = db_deviceagent.GetIDXDeviceAgent(-1)
        self.assertEqual(record.exists(), False)
        self.assertEqual(record.enabled(), None)
        self.assertEqual(record.idx_agent(), None)
        self.assertEqual(record.idx_device(), None)
        self.assertEqual(record.idx_deviceagent(), None)
        self.assertEqual(record.last_timestamp(), None)

    def test_exists(self):
        """Testing method exists."""
        # Testing with known good value
        result = self.good_device.exists()
        self.assertEqual(result, True)

        # Test with known bad value
        expected = db_deviceagent.GetIDXDeviceAgent(None)
        result = expected.exists()
        self.assertEqual(result, False)

    def test_enabled(self):
        """Testing method enabled."""
        # Testing with known good value
        result = self.good_device.enabled()
        self.assertEqual(result, True)

    def test_last_timestamp(self):
        """Testing method last_timestamp."""
        # Testing with known good value
        result = self.good_device.last_timestamp()
        self.assertEqual(result, self.expected['timestamp'])

    def test_idx_deviceagent(self):
        """Testing method idx_deviceagent."""
        # Testing with known good value
        result = self.good_device.idx_deviceagent()
        self.assertEqual(result, self.expected['idx_deviceagent'])

    def test_idx_agent(self):
        """Testing method idx_agent."""
        # Testing with known good value
        result = self.good_device.idx_agent()
        self.assertEqual(result, self.expected['idx_agent'])

    def test_idx_device(self):
        """Testing method idx_device."""
        # Testing with known good value
        result = self.good_device.idx_device()
        self.assertEqual(result, self.expected['idx_device'])
示例#21
0
    def test___init__(self):
        """Testing function __init__."""
        # Initialize key variables
        directory = tempfile.mkdtemp()
        id_agent = self.data['id_agent']
        last_timestamp = self.data['timestamp']
        filepath = ('%s/%s_%s_%s.json') % (directory, last_timestamp, id_agent,
                                           general.hashstring(
                                               general.randomstring()))

        # Drop the database and create tables
        unittest_setup_db.TestData()

        # Test with valid data
        result = validate.ValidateCache(data=self.data)
        self.assertEqual(result.valid(), True)

        # Test with invalid data (string)
        result = validate.ValidateCache(data='string')
        self.assertEqual(result.valid(), False)

        # Test with invalid data (string)
        data_dict = copy.deepcopy(self.data)
        data_dict.pop('agent', None)
        result = validate.ValidateCache(data=data_dict)
        self.assertEqual(result.valid(), False)

        # Write good data to file and test
        with open(filepath, 'w') as f_handle:
            json.dump(self.data, f_handle)
        result = validate.ValidateCache(filepath=filepath)
        self.assertEqual(result.valid(), True)

        #################################################################
        #################################################################
        # Add record to DeviceAgent table and test for validity with the
        # same data, which should be False
        #################################################################
        #################################################################

        data_dict = copy.deepcopy(self.data)

        # Populate dictionary with data values of prior entries
        database = unittest_setup_db.TestData()
        data_dict['timestamp'] = database.timestamp()
        data_dict['devicename'] = database.devicename()
        data_dict['agent'] = database.agent()
        data_dict['id_agent'] = database.id_agent()

        # Attempting to insert duplicate data should fail
        with open(filepath, 'w') as f_handle:
            json.dump(data_dict, f_handle)
        result = validate.ValidateCache(filepath=filepath)
        self.assertEqual(result.valid(), False)

        #################################################################
        #################################################################
        # Test with invalid data in file
        #################################################################
        #################################################################

        # Drop the database and create tables
        unittest_setup_db.TestData()

        # Write bad data to file and test
        data_dict = copy.deepcopy(self.data)
        data_dict.pop('agent', None)
        with open(filepath, 'w') as f_handle:
            json.dump(data_dict, f_handle)
        result = validate.ValidateCache(filepath=filepath)
        self.assertEqual(result.valid(), False)

        # Cleanup
        os.remove(filepath)
        os.removedirs(directory)
示例#22
0
class TestGetIdentifier(unittest.TestCase):
    """Checks all functions and methods."""

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_agent'] = database.idx_agent()
    expected['id_agent'] = database.id_agent()
    expected['idx_agentname'] = database.idx_agentname()
    expected['enabled'] = True
    expected['exists'] = True

    # Retrieve data
    good_agent = db_agent.GetIDAgent(expected['id_agent'])

    def test_init(self):
        """Testing method __init__."""
        # Test with non existent AgentID
        record = db_agent.GetIDAgent('bogus')
        self.assertEqual(record.exists(), False)
        self.assertEqual(record.enabled(), None)
        self.assertEqual(record.idx_agent(), None)
        self.assertEqual(record.idx_agentname(), None)

    def test_exists(self):
        """Testing method exists."""
        # Testing with known good value
        result = self.good_agent.exists()
        self.assertEqual(result, True)

    def test_idx_agentname(self):
        """Testing method idx_agentname."""
        # Testing with known good value
        result = self.good_agent.idx_agentname()
        self.assertEqual(result, True)

    def test_idx_agent(self):
        """Testing method idx."""
        # Testing with known good value
        result = self.good_agent.idx_agent()
        self.assertEqual(result, self.expected['idx_agent'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.idx_agent()
        self.assertNotEqual(result, expected)

    def test_enabled(self):
        """Testing method enabled."""
        # Testing with known good value
        result = self.good_agent.enabled()
        self.assertEqual(result, self.expected['enabled'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.enabled()
        self.assertNotEqual(result, expected)

    def test_everything(self):
        """Testing method everything."""
        # Testing with known good value
        result = self.good_agent.everything()
        for key, _ in self.expected.items():
            self.assertEqual(result[key], self.expected[key])
示例#23
0
class TestGetIDX(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_agent'] = database.idx_agent()
    expected['idx_agentname'] = database.idx_agentname()
    expected['id_agent'] = database.id_agent()
    expected['agent'] = database.agent()
    expected['enabled'] = True
    expected['exists'] = True

    # Retrieve data
    good_agent = db_agent.GetIDXAgent(expected['idx_agent'])

    def test_init(self):
        """Testing method init."""
        # Test with non existent AgentIDX
        record = db_agent.GetIDXAgent(-1)
        self.assertEqual(record.exists(), False)
        self.assertEqual(record.enabled(), None)
        self.assertEqual(record.idx_agent(), None)
        self.assertEqual(record.agent(), None)
        self.assertEqual(record.idx_agentname(), None)

    def test_id_agent(self):
        """Testing method id_agent."""
        # Testing with known good value
        result = self.good_agent.id_agent()
        self.assertEqual(result, self.expected['id_agent'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.id_agent()
        self.assertNotEqual(result, expected)

    def test_idx_agent(self):
        """Testing method idx."""
        # Testing with known good value
        result = self.good_agent.idx_agent()
        self.assertEqual(result, self.expected['idx_agent'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.idx_agent()
        self.assertNotEqual(result, expected)

    def test_exists(self):
        """Testing method exists."""
        # Testing with known good value
        result = self.good_agent.exists()
        self.assertEqual(result, True)

    def test_idx_agentname(self):
        """Testing method idx_agentname."""
        # Testing with known good value
        result = self.good_agent.idx_agentname()
        self.assertEqual(result, self.expected['idx_agentname'])

    def test_agent(self):
        """Testing method name."""
        # Testing with known good value
        result = self.good_agent.agent()
        self.assertEqual(result, self.expected['agent'])

    def test_enabled(self):
        """Testing method enabled."""
        # Testing with known good value
        result = self.good_agent.enabled()
        self.assertEqual(result, self.expected['enabled'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.enabled()
        self.assertNotEqual(result, expected)

    def test_everything(self):
        """Testing method everything."""
        # Testing with known good value
        result = self.good_agent.everything()
        for key, _ in self.expected.items():
            self.assertEqual(result[key], self.expected[key])

        # Test the number and names of keys
        keys = [
            'idx_agent', 'idx_agentname', 'id_agent', 'enabled', 'agent',
            'exists'
        ]
        self.assertEqual(len(result), len(keys))
        for key in keys:
            self.assertEqual(key in result, True)
示例#24
0
class TestGetIDXBillcode(unittest.TestCase):
    """Checks all functions and methods."""

    #########################################################################
    # General object setup
    #########################################################################

    # Setup database based on the config
    database = unittest_setup_db.TestData()

    # Define expected values
    expected = {}
    expected['idx_billcode'] = database.idx_billcode()
    expected['name'] = database.billcode_name()
    expected['code'] = database.billcode_code()
    expected['enabled'] = True
    expected['exists'] = True

    # Retrieve data
    good_agent = db_billcode.GetIDXBillcode(expected['idx_billcode'])

    def test_init_(self):
        """Testing method init."""
        # Test with non existent AgentIDX
        record = db_billcode.GetIDXBillcode(-1)
        self.assertEqual(record.exists(), False)
        self.assertEqual(record.enabled(), None)
        self.assertEqual(record.idx_billcode(), None)
        self.assertEqual(record.code(), None)
        self.assertEqual(record.name(), None)

    def test_idx_billcode(self):
        """Testing method idx_billcode."""
        # Testing with known good value
        result = self.good_agent.idx_billcode()
        self.assertEqual(result, self.expected['idx_billcode'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.idx_billcode()
        self.assertNotEqual(result, expected)

    def test_name(self):
        """Testing method name."""
        # Testing with known good value
        result = self.good_agent.name()
        self.assertEqual(result, self.expected['name'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.name()
        self.assertNotEqual(result, expected)

    def test_code(self):
        """Testing method code."""
        # Testing with known good value
        result = self.good_agent.code()
        self.assertEqual(result, self.expected['code'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.code()
        self.assertNotEqual(result, expected)

    def test_exists(self):
        """Testing method exists."""
        # Testing with known good value
        result = self.good_agent.exists()
        self.assertEqual(result, True)

    def test_enabled(self):
        """Testing method enabled."""
        # Testing with known good value
        result = self.good_agent.enabled()
        self.assertEqual(result, self.expected['enabled'])

        # Testing with known bad value
        expected = ('bogus')
        result = self.good_agent.enabled()
        self.assertNotEqual(result, expected)