コード例 #1
0
    def __init__(self, hass, host, port, version):
        """Initialize."""
        self.api = Api(host, str(port), version)
        self.platforms = []

        super().__init__(
            hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL,
        )
コード例 #2
0
    def setUp(self):
        """Setup all necessary instances nad mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
        ]

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        # patching ping method in IneslBus3. It will be executed every test
        for p in self.patches:
            p.start()
コード例 #3
0
    def setUp(self):
        """Setup all necesary instances and mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.getRoomDevicesRaw',
                  return_value=TEST_RAW_DEVICES)
        ]

        for p in self.patches:
            p.start()

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)
        self.devices = self.api.getRoomDevices('garage')
コード例 #4
0
    async def _test_credentials(self, host, port, version):
        """Return true if credentials is valid."""
        try:
            with async_timeout.timeout(5):
                _LOGGER.info("Testing connection")
                api = Api(host, str(port), version)

                if not api.ping():
                    raise Exception("not_available")

            return True
        except Exception:  # pylint: disable=broad-except
            pass
        return False
コード例 #5
0
ファイル: resource_test.py プロジェクト: carlodsk/pyinels
    def setUp(self):
        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.getRoomDevicesRaw',
                  return_value=TEST_RAW_DEVICES)
        ]

        for p in self.patches:
            p.start()

        self.res_list = self.api.getRoomDevices('garage')

        self.garage_door = self.res_list[0]
コード例 #6
0
    def setUp(self):
        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_ROOM_DEVICES}',
                  return_value=TEST_RAW_GARAGE_DOOR),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_READ_DATA}',
                  return_value=GARAGE_CLOSE)
        ]

        for p in self.patches:
            p.start()

        self.res_list = self.api.getRoomDevices('garage')
        self.garage_door = self.res_list[0]
コード例 #7
0
    def setUp(self):
        """Setup all necesary instances and mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_ROOM_DEVICES}',
                  return_value=TEST_RAW_GARAGE_DOOR),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_READ_DATA}',
                  return_value=DOOR_RETURN_OFF),
            patch(f'{TEST_API_CLASS_NAMESPACE}._Api__writeValues',
                  return_value=None)
        ]

        for p in self.patches:
            p.start()

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        doors = [device for device in self.api.getRoomDevices(
            'garage') if device.type == ATTR_DOOR]

        self.door = pyDoor(doors[0])
コード例 #8
0
    def setUp(self):
        """Setup all necesary instances and mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_ROOM_DEVICES}',
                  return_value=TEST_RAW_LIGHT),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_READ_DATA}',
                  return_value=LIGHT_RETURN_DIMMABLE_OFF),
            patch(f'{TEST_API_CLASS_NAMESPACE}._Api__writeValues',
                  return_value=None)
        ]

        for p in self.patches:
            p.start()

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        lights = [
            device for device in self.api.getRoomDevices('garage')
            if device.type == ATTR_LIGHT
        ]

        self.light = pyLight(lights[0])
コード例 #9
0
    def setUp(self):
        """Setup all necesary instances and mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_ROOM_DEVICES}',
                  return_value=TEST_RAW_SHUTTER),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_READ_DATA}',
                  return_value=TEST_RETURN_RESOURCE_SHUTTER),
            patch(f'{TEST_API_CLASS_NAMESPACE}._Api__writeValues',
                  return_value=None)
        ]

        for item in self.patches:
            item.start()

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        shutters = [
            device for device in self.api.getRoomDevices('garage')
            if device.type == ATTR_SHUTTER
        ]

        self.shutter = pyShutter(shutters[0])
コード例 #10
0
    def setUp(self):
        """Setup all necesary instances and mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_ROOM_DEVICES}',
                  return_value=TEST_RAW_SWITCH),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_READ_DATA}',
                  return_value=SWITCH_RETURN_OFF),
            patch(f'{TEST_API_CLASS_NAMESPACE}._Api__writeValues',
                  return_value=None)
        ]

        for p in self.patches:
            p.start()

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)
        """Setup all neccessary async stuff."""
        switches = [
            device for device in self.api.getRoomDevices('garage')
            if device.type == ATTR_SWITCH
        ]

        self.switch = pySwitch(switches[0])
コード例 #11
0
class PySwitchTest(TestCase):
    """Class to test iNels switch library."""
    def setUp(self):
        """Setup all necesary instances and mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.getRoomDevicesRaw',
                  return_value=TEST_RAW_DEVICES)
        ]

        for p in self.patches:
            p.start()

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)
        switches = [
            device for device in self.api.getRoomDevices('garage')
            if device.type == ATTR_SWITCH
        ]

        self.device = switches[0]

    def tearDown(self):
        """Destroy all instances and mocks."""
        self.api = None
        self.device = None
        patch.stopall()
        self.patches = None

    def test_state(self):
        """Test the state of the pySwitch."""
        with patch.object(self.api,
                          '_Api__readDeviceData',
                          return_value={'ZA_01_GARAGE': 0}):
            p = pySwitch(self.device)

            # the switch at the beggining should be turned off
            self.assertFalse(p.state)
            self.assertTrue(self.device.has_switch_control)

            with patch.object(self.api, '_Api__writeValues',
                              return_value=None):
                # tur on the switch
                self.device.switch_control.toggle

                self.assertTrue(p.state)
コード例 #12
0
class InelsDataUpdateCoordinator(DataUpdateCoordinator):
    """Class to manage fetching data from the API."""

    def __init__(self, hass, host, port, version):
        """Initialize."""
        self.api = Api(host, str(port), version)
        self.platforms = []

        super().__init__(
            hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL,
        )

    async def _async_update_data(self):
        """Update data via library."""
        try:
            data = self.api.getAllDevices()
            return data
        except Exception as exception:
            raise UpdateFailed(exception)
コード例 #13
0
class DeviceTest(TestCase):
    """Class to test iNels device library."""

    def setUp(self):
        """Setup all necesary instances and mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.getRoomDevicesRaw',
                  return_value=TEST_RAW_DEVICES)
        ]

        for p in self.patches:
            p.start()

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)
        self.devices = self.api.getRoomDevices('garage')

    def tearDown(self):
        """Destroy all instances and mocks."""
        self.api = None
        self.devices = None
        patch.stopall()
        self.patches = None

    def test_has_switch_control(self):
        """Test when the current device has a switch control."""
        switches = [
            device for device in self.devices if device.type == ATTR_SWITCH]

        self.assertGreater(len(switches), 0)

        switch = switches[0]

        self.assertTrue(switch.has_switch_control)
        self.assertIsNotNone(switch.switch_control)
        self.assertTrue(isinstance(switch.switch_control, SwitchControl))
コード例 #14
0
"""Usaage examples."""
from pyinels.api import Api

# fill the IP address and Port of your iNels PLC
api = Api('http://localhost', '9000', 'CU3')

# checking when the connection is established successfuly
available = api.ping()

# get the list of all rooms from Connection server
rooms = api.getRooms()

# get all devices from current room. Room can be taken from rooms property
roomDevices = api.getRoomDevices('room name')

# get the raw data from the PLC formated in string. Each device is on
# separated line it's just used for developing and data checking purposes
raw = api.getRoomDevicesRaw('room name')

# get all devices from all rooms in one list. List contains
# object InelsDevice. This is the most used method.
devices = api.getAllDevices()

# get the value / state of the device. Some special devices like SHUTTERS or
# THERM does not have id. You need to use up/down/temp_current/temp_set as
# param. Method is used for getting the state. So this method will be
# the most offen called one
data = api.observe('InelsDevice.id')

# Write state/data to the PLC.
# You need to change the value of the object device to what ever you want
コード例 #15
0
ファイル: resource_test.py プロジェクト: carlodsk/pyinels
class ResourceTest(TestCase):
    """Class to test resource of api iNels BUS."""
    def setUp(self):
        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.getRoomDevicesRaw',
                  return_value=TEST_RAW_DEVICES)
        ]

        for p in self.patches:
            p.start()

        self.res_list = self.api.getRoomDevices('garage')

        self.garage_door = self.res_list[0]

    def tearDown(self):
        """Destroy all instances and mocks."""
        self.api = None
        self.res_list = None
        self.garage_door = None
        patch.stopall()
        self.patches = None

    @patch(f'{TEST_API_NAMESPACE}.resources.ApiResource')
    def test_load_resource_object(self, mock_class):
        """Test to load resource object."""
        mock_class(TEST_RESOURCE_SWITCH, self.api)

        mock_class.assert_called()
        mock_class.assert_called_once()

        self.assertEqual(mock_class.call_count, 1)

        res = ApiResource(TEST_RESOURCE_SWITCH, self.api)

        self.assertIsInstance(res, ApiResource)

        self.assertEqual(TEST_RESOURCE_SWITCH['type'], res.type)
        # inels is raw data id from iNels BUS
        self.assertEqual(TEST_RESOURCE_SWITCH['inels'], res.id)
        self.assertEqual(TEST_RESOURCE_SWITCH['name'], res.title)
        self.assertEqual(TEST_RESOURCE_SWITCH['read_only'], res.read_only)
        # should be none, because it does not get the observe
        self.assertIsNone(res.value)

    @patch(f'{TEST_API_CLASS_NAMESPACE}.read')
    def test_observe(self, mock_room_devices):
        """Test the observe method of the Api resources. It should touche
        the iNels BUS."""
        mock_room_devices.return_value = {'Doors_Garage': 0}

        self.assertEqual(len(self.res_list), 4)
        self.assertEqual(self.garage_door.title, 'Doors')

        value = self.garage_door.observe()

        self.assertEqual(value, 0)

        self.assertIsNotNone(self.garage_door.value)
        self.assertEqual(self.garage_door.value, 0)

    def test_set_value(self):
        """Test set value to the iNels BUS."""
        with patch.object(self.api, '_Api__writeValues', return_value=None):
            # set int
            self.garage_door.set_value(1)
            self.assertEqual(self.garage_door.value, 1)

            # change int to another value
            self.garage_door.set_value(0)
            self.assertEqual(self.garage_door.value, 0)

            # change to float with different value
            self.garage_door.set_value(25.0)
            self.assertEqual(self.garage_door.value, 25.0)

            # change to int with same value
            self.garage_door.set_value(25)
            self.assertEqual(self.garage_door.value, 25)

    def test_is_available(self):
        """Test when the resource object is available."""
        with patch.object(self.api, '_Api__writeValues', return_value=None):
            # not set value of the ApiResource object then is not available
            self.assertFalse(self.garage_door.is_available)

            # set the value of the ApiResource then it should be available
            self.garage_door.set_value(1)
            self.assertTrue(self.garage_door.is_available)
コード例 #16
0
class PyLightTest(TestCase):
    """Class to test iNels light library."""
    def setUp(self):
        """Setup all necesary instances and mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_ROOM_DEVICES}',
                  return_value=TEST_RAW_LIGHT),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_READ_DATA}',
                  return_value=LIGHT_RETURN_OFF),
            patch(f'{TEST_API_CLASS_NAMESPACE}._Api__writeValues',
                  return_value=None)
        ]

        for p in self.patches:
            p.start()

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        lights = [
            device for device in self.api.getRoomDevices('garage')
            if device.type == ATTR_LIGHT
        ]

        self.light = pyLight(lights[0])

    def tearDown(self):
        """Destroy all instances and mocks."""
        self.api = None
        self.light = None
        patch.stopall()
        self.patches = None

    def test_title_and_id(self):
        """Test the name of the entity."""
        lg = self.light

        self.assertIsNotNone(lg.name)
        self.assertEqual(lg.name, LIGHT_NAME)

        self.assertIsNotNone(lg.unique_id)
        self.assertEqual(lg.unique_id, LIGHT_ID)

    def test_state(self):
        """Test the state of the pyLight."""
        lg = self.light

        lg.update()
        # the light at the beggining should be turned off
        self.assertFalse(lg.state)

    def test_unique_id_and_name_presented(self):
        """Test when the unique id is presented."""
        lg = self.light

        self.assertIsNotNone(lg.unique_id)
        self.assertIsNotNone(lg.name)

    def test_turn_on(self):
        """Test turn on the light."""
        lg = self.light

        lg.update()
        self.assertFalse(lg.state)

        with patch.object(self.api,
                          TEST_API_READ_DATA,
                          return_value=LIGHT_RETURN_ON):
            lg.turn_on()

            lg.update()
            self.assertTrue(lg.state)

        lg.turn_off()

        lg.update()
        self.assertFalse(lg.state)

    def test_turn_off(self):
        """Test turn off the light."""
        lg = self.light

        with patch.object(self.api,
                          TEST_API_READ_DATA,
                          return_value=LIGHT_RETURN_ON):
            lg.turn_on()

            lg.update()
            self.assertTrue(lg.state)

        lg.turn_off()

        lg.update()
        self.assertFalse(lg.state)
コード例 #17
0
class PyLightDimmableTest(TestCase):
    """Class to test iNels light library."""
    def setUp(self):
        """Setup all necesary instances and mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_ROOM_DEVICES}',
                  return_value=TEST_RAW_LIGHT),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_READ_DATA}',
                  return_value=LIGHT_RETURN_DIMMABLE_OFF),
            patch(f'{TEST_API_CLASS_NAMESPACE}._Api__writeValues',
                  return_value=None)
        ]

        for p in self.patches:
            p.start()

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        lights = [
            device for device in self.api.getRoomDevices('garage')
            if device.type == ATTR_LIGHT
        ]

        self.light = pyLight(lights[0])

    def tearDown(self):
        """Destroy all instances and mocks."""
        self.api = None
        self.light = None
        patch.stopall()
        self.patches = None

    def test_turn_on_with_brightness_option(self):
        """Test the light to turn on when the brightness exists."""

        lg = self.light

        lg.update()
        self.assertFalse(lg.state)
        self.assertTrue(lg.has_brightness)

        with patch.object(self.api,
                          TEST_API_READ_DATA,
                          return_value=LIGHT_RETURN_DIMMABLE_ON):
            lg.turn_on()

            lg.update()
            self.assertTrue(lg.state)

    def test_set_brightness_to_50_percent(self):
        """Test the brightnes to some value."""

        lg = self.light

        lg.update()
        self.assertFalse(lg.state)
        self.assertTrue(lg.has_brightness)

        with patch.object(self.api,
                          TEST_API_READ_DATA,
                          return_value=LIGHT_RETURN_DIMMABLE_50):

            lg.set_brightness(50)

            self.assertEqual(lg.brightness(), 50)
            self.assertTrue(lg.state)

    @patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_READ_DATA}')
    def test_turn_off_with_brightness_option(self, mock_room_devices):
        """Test the light to turn off when the brightness exsists."""
        mock_room_devices.return_value = LIGHT_RETURN_DIMMABLE_ON

        lg = self.light

        self.assertTrue(lg.has_brightness)

        lg.update()
        self.assertTrue(lg.state)

        with patch.object(self.api,
                          TEST_API_READ_DATA,
                          return_value=LIGHT_RETURN_DIMMABLE_OFF):
            lg.turn_off()
            self.assertTrue(lg.has_brightness)

            lg.update()
            self.assertFalse(lg.state)
コード例 #18
0
class PyShutterTest(TestCase):
    """Class to test iNels shutter library."""
    def setUp(self):
        """Setup all necesary instances and mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_ROOM_DEVICES}',
                  return_value=TEST_RAW_SHUTTER),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_READ_DATA}',
                  return_value=TEST_RETURN_RESOURCE_SHUTTER),
            patch(f'{TEST_API_CLASS_NAMESPACE}._Api__writeValues',
                  return_value=None)
        ]

        for item in self.patches:
            item.start()

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        shutters = [
            device for device in self.api.getRoomDevices('garage')
            if device.type == ATTR_SHUTTER
        ]

        self.shutter = pyShutter(shutters[0])

    def tearDown(self):
        """Destroy all instances and mocks."""
        self.api = None
        self.shutter = None
        patch.stopall()
        self.patches = None

    def test_state_after_initialization(self):
        """Test the state of the pyShutter."""
        shutt = self.shutter

        shutt.update()
        # the shutter at the beggining should be open. There will be
        # calibration
        self.assertIs(shutt.state, STATE_OPEN)

    def test_opening(self):
        """Check up and down when opening."""
        shutt = self.shutter

        shutt.pull_up()

        self.assertEqual(shutt.up, 1)
        self.assertEqual(shutt.down, 0)
        self.assertEqual(shutt.current_position, 100)
        self.assertEqual(shutt.state, STATE_OPENING)

        shutt.stop()

        self.assertEqual(shutt.up, 0)
        self.assertEqual(shutt.down, 0)
        self.assertEqual(shutt.current_position, 100)
        self.assertEqual(shutt.state, STATE_OPEN)

    def test_closing(self):
        """Check up and down when closing."""
        shutt = self.shutter

        shutt.pull_down()

        self.assertEqual(shutt.up, 0)
        self.assertEqual(shutt.down, 1)
        self.assertEqual(shutt.current_position, 0)
        self.assertEqual(shutt.state, STATE_CLOSING)

        shutt.stop()

        self.assertEqual(shutt.up, 0)
        self.assertEqual(shutt.down, 0)
        self.assertEqual(shutt.current_position, 0)
        self.assertEqual(shutt.state, STATE_CLOSED)

    def test_unique_id_and_name_presented(self):
        """Test when the unique id is presented."""
        shutt = self.shutter

        self.assertIsNotNone(shutt.unique_id)
        self.assertIsNotNone(shutt.name)

        self.assertEqual(shutt.unique_id, TEST_SHUTTER_ID)
        self.assertEqual(shutt.name, TEST_SHUTTER_NAME)
コード例 #19
0
ファイル: api_test.py プロジェクト: carlodsk/pyinels
class ApiTest(TestCase):
    """Class to test pyInels api library."""
    def setUp(self):
        """Setup all necessary instances nad mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.read',
                  return_value={TEST_DATA_SWITCH['id']: 1}),
        ]

        self.proxy = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        # patching ping method in IneslBus3. It will be executed every test
        for p in self.patches:
            p.start()

    def tearDown(self):
        """Destroy all instances and mocks."""
        self.proxy = None
        patch.stopall()
        self.patches = None

    @patch(TEST_API_CLASS_NAMESPACE)
    def test_class_calling(self, mock_class):
        """Class instance test."""
        mock_class(TEST_HOST, TEST_PORT, TEST_VERSION)

        mock_class.assert_called()
        mock_class.assert_called_once()
        mock_class.assert_called_with(TEST_HOST, TEST_PORT, TEST_VERSION)

        self.assertEqual(mock_class.call_count, 1)

    @patch('xmlrpc.client.ServerProxy')
    def test_connection_failed(self, mock_server):
        """Test proxy connection."""
        mock_server.return_value = Mock()
        mock_server.side_effect = ApiException('common_exception',
                                               'Exception occur')

        ret = self.proxy.ping()
        self.assertEqual(True, ret)
        self.assertEqual(mock_server.call_count, 0)

    @patch(f'{TEST_API_CLASS_NAMESPACE}.ping')
    def test_ping_failed(self, mock_method):
        """Test ping method."""
        mock_method.return_value = False
        ret = self.proxy.ping()

        self.assertEqual(mock_method.call_count, 1)
        self.assertFalse(ret)

    @patch(f'{TEST_API_CLASS_NAMESPACE}.getPlcIp')
    def test_getPlcIp_success(self, mock_method):
        """Test Ip address of the PLC."""
        mock_method.return_value = "192.168.2.10"

        ret = self.proxy.getPlcIp()

        self.assertEqual(mock_method.call_count, 1)
        self.assertEqual(ret, "192.168.2.10")

    @patch(f'{TEST_API_CLASS_NAMESPACE}.getRooms')
    def test_getRoomsRaw_list(self, mock_method):
        """Test list of rooms defined on Connection server."""
        mock_method.return_value = TEST_ROOMS

        ret = self.proxy.getRooms()

        self.assertEqual(mock_method.call_count, 1)
        self.assertEqual(len(ret), 6)
        self.assertEqual(ret[1], 'First floor')

    @patch(f'{TEST_API_CLASS_NAMESPACE}.getRoomDevicesRaw')
    def test_getRoomDevices_list(self, mock_method):
        """Test list of all devices in room."""
        mock_method.return_value = TEST_RAW_DEVICES
        raw = self.proxy.getRoomDevicesRaw('room')

        self.assertEqual(mock_method.call_count, 1)
        self.assertEqual(len(raw), len(mock_method.return_value))

        # this is the way how to mock private method
        with patch.object(self.proxy,
                          '_Api__readDeviceData',
                          return_value={'Doors_Garage': 0}):
            with patch.object(self.proxy, 'ping', return_value=True):
                obj_list = self.proxy.getRoomDevices('room')

                device = obj_list[0]

                self.assertGreater(len(obj_list), 0)
                self.assertEqual(device.id, 'Doors_Garage')
                self.assertEqual(device.title, 'Doors')

                patch.stopall()
                device_value = self.proxy.read([device.id])
                self.assertEqual(device_value, {'Doors_Garage': 0})
コード例 #20
0
class ProductionTest():
    """Library used agains production server."""
    def setUp(self):
        """Setup all necessary instances nad mocks."""
        self.api = Api(f'http://{MMS_IP_ADDRESS}', 8001, "CU3")

    async def asyncSetUp(self):
        """Setup all neccessary async stuff."""
        devices = await self.api.getAllDevices()
        self.api.set_devices(devices)

    def tearDown(self):
        """Remove all attached properties."""
        self.api = None

    async def test_ping_success(self):
        """Ping test."""
        ping = await self.api.ping()

        self.assertEqual(ping, True)

    async def test_plcIp_address(self):
        """Get Ip address of the PLC."""
        ip = await self.api.getPlcIp()

        self.assertEqual(PLC_IP_ADDRESS, ip)

    def test_loaded_devices(self):
        """Are devices from api loaded?"""
        self.assertGreater(len(self.api.devices), 0)

    async def test_create_light(self):
        """create and test light."""
        devices = [x for x in self.api.devices if x.id == "SV_7_Pokoj_dole"]

        light = await pyLight(devices[0])
        self.assertEqual(light.state, False)

        await light.turn_on()
        self.assertEqual(light.state, True)
        asyncio.sleep(4)
        await light.turn_off()
        self.assertEqual(light.state, False)
        asyncio.sleep(4)

        await light.set_brightness(50)
        self.assertEqual(light.state, True)
        asyncio.sleep(4)
        await light.set_brightness(100)
        self.assertEqual(light.state, True)
        asyncio.sleep(4)
        await light.set_brightness(0)
        self.assertEqual(light.state, False)

    async def test_create_switch(self):
        """create and test switch."""
        devices = [x for x in self.api.devices if x.id == "ZAS_1B_Pokoj_dole"]

        switch = await pySwitch(devices[0])

        await switch.turn_off()
        self.assertEqual(switch.state, False)
        asyncio.sleep(4)
        await switch.turn_on()
        self.assertEqual(switch.state, True)

    async def test_create_door(self):
        """crate and test door."""
        devices = [x for x in self.api.devices if x.id == "Vrata_Garaz"]

        door = await pyDoor(devices[0])

        await door.turn_on()
        asyncio.sleep(30)
        await door.turn_off()

    async def test_create_shutter(self):
        """create and test shutter."""
        devices = [
            x for x in self.api.devices
            if x.id == "ROL_Pokoj_host_nahoru_ROL_Pokoj_host_dolu"
        ]

        shutter = await pyShutter(devices[0])

        await shutter.pull_up()
        asyncio.sleep(20)
        await shutter.stop()
        await shutter.pull_down()
        asyncio.sleep(10)
        await shutter.stop()
コード例 #21
0
 def setUp(self):
     self.api = Api("http://192.168.2.102", 8001, "CU3")
コード例 #22
0
class PyDoorTest(TestCase):
    """Class to test iNels door library."""

    def setUp(self):
        """Setup all necesary instances and mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_ROOM_DEVICES}',
                  return_value=TEST_RAW_GARAGE_DOOR),
            patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_READ_DATA}',
                  return_value=DOOR_RETURN_OFF),
            patch(f'{TEST_API_CLASS_NAMESPACE}._Api__writeValues',
                  return_value=None)
        ]

        for p in self.patches:
            p.start()

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        doors = [device for device in self.api.getRoomDevices(
            'garage') if device.type == ATTR_DOOR]

        self.door = pyDoor(doors[0])

    def tearDown(self):
        """Destroy all instances and mocks."""
        self.api = None
        self.door = None
        patch.stopall()
        self.patches = None

    def test_state(self):
        """Test the state of the pyDoor."""
        s = self.door

        s.update()
        # the door at the beggining should be turned off
        self.assertFalse(s.state)

    def test_unique_id_and_name_presented(self):
        """Test when the unique id is presented."""
        s = self.door

        self.assertIsNotNone(s.unique_id)
        self.assertIsNotNone(s.name)

        self.assertEqual(s.unique_id, DOOR_ID)
        self.assertEqual(s.name, DOOR_NAME)

    def test_turn_on(self):
        """Test turn on the door."""
        s = self.door

        s.update()
        self.assertFalse(s.state)

        with patch.object(self.api, TEST_API_READ_DATA,
                          return_value=DOOR_RETURN_ON):
            s.turn_on()

            s.update()
            self.assertFalse(s.state)

    def test_turn_off(self):
        """Test turn off the door."""
        s = self.door

        with patch.object(self.api, TEST_API_READ_DATA,
                          return_value=DOOR_RETURN_ON):
            s.turn_on()

            s.update()
            self.assertFalse(s.state)

        s.turn_off()

        s.update()
        self.assertFalse(s.state)
コード例 #23
0
class ApiTest(TestCase):
    """Class to test pyInels api library."""

    def setUp(self):
        """Setup all necessary instances nad mocks."""
        self.patches = [
            patch(f'{TEST_API_CLASS_NAMESPACE}.ping', return_value=True),
        ]

        self.api = Api(TEST_HOST, TEST_PORT, TEST_VERSION)

        # patching ping method in IneslBus3. It will be executed every test
        for p in self.patches:
            p.start()

    def tearDown(self):
        """Destroy all instances and mocks."""
        self.api = None
        patch.stopall()
        self.patches = None

    @patch(TEST_API_CLASS_NAMESPACE)
    def test_class_calling(self, mock_class):
        """Class instance test."""
        mock_class(TEST_HOST, TEST_PORT, TEST_VERSION)

        mock_class.assert_called()
        mock_class.assert_called_once()
        mock_class.assert_called_with(TEST_HOST, TEST_PORT, TEST_VERSION)

        self.assertEqual(mock_class.call_count, 1)

    @patch('xmlrpc.client.ServerProxy')
    def test_connection_failed(self, mock_server):
        """Test api connection."""
        mock_server.return_value = Mock()
        mock_server.side_effect = ApiException(
            'common_exception', 'Exception occur')

        ret = self.api.ping()
        self.assertEqual(True, ret)
        self.assertEqual(mock_server.call_count, 0)

    @patch(f'{TEST_API_CLASS_NAMESPACE}.ping')
    def test_ping_failed(self, mock_method):
        """Test ping method."""
        mock_method.return_value = False
        ret = self.api.ping()

        self.assertEqual(mock_method.call_count, 1)
        self.assertFalse(ret)

    @patch(f'{TEST_API_CLASS_NAMESPACE}.getPlcIp')
    def test_getPlcIp_success(self, mock_method):
        """Test Ip address of the PLC."""
        RET_VAL = "192.168.2.10"

        mock_method.return_value = RET_VAL
        ret = self.api.getPlcIp()

        self.assertEqual(mock_method.call_count, 1)
        self.assertEqual(ret, RET_VAL)

    @patch(f'{TEST_API_CLASS_NAMESPACE}.getRooms')
    def test_getRoomsRaw_list(self, mock_method):
        """Test list of rooms defined on Connection server."""
        mock_method.return_value = TEST_ROOMS

        ret = self.api.getRooms()

        self.assertEqual(mock_method.call_count, 1)
        self.assertEqual(len(ret), 6)
        self.assertEqual(ret[1], 'First floor')

    @patch(f'{TEST_API_CLASS_NAMESPACE}.{TEST_API_ROOM_DEVICES}')
    def test_getRoomDevices_list(self, mock_method):
        """Test list of all devices in room."""
        mock_method.return_value = TEST_RAW_LIGHT
        raw = self.api.getRoomDevicesRaw('room')

        self.assertEqual(mock_method.call_count, 1)
        self.assertEqual(len(raw), len(mock_method.return_value))

        # this is the way how to mock private method
        with patch.object(
            self.api,
            TEST_API_READ_DATA,
            return_value=LIGHT_RETURN_OFF
        ):
            with patch.object(self.api, 'ping', return_value=True):
                obj_list = self.api.getRoomDevices('room')

                device = obj_list[0]

                self.assertGreater(len(obj_list), 0)
                self.assertEqual(device.id, LIGHT_ID)
                self.assertEqual(device.title, LIGHT_NAME)

                patch.stopall()
                device_value = self.api.read([device.id])
                self.assertEqual(device_value, LIGHT_RETURN_OFF)

    @patch(f'{TEST_API_NAMESPACE}.resources.ApiResource.get_value')
    def test_not_duplicit_entries(self, mock_method_get_value):
        """Test duplicit entries inside of device list."""
        mock_method_get_value.return_value = 0

        with patch.object(self.api, 'ping', return_value=True):
            with patch.object(self.api, TEST_API_ROOM_DEVICES,
                              return_value=TEST_RAW_DUPLICIT_DEVICES):
                obj_list = self.api.getRoomDevices('room')

                with patch.object(self.api, "getRooms", return_value=["room"]):

                    with patch.object(self.api, "getRoomDevices",
                                      return_value=obj_list):
                        devices = self.api.getAllDevices()

                        self.assertEqual(len(devices), 48)
                        self.assertGreater(len(obj_list), len(devices))

    @patch(f'{TEST_API_NAMESPACE}.resources.ApiResource.get_value')
    def test_fetch_all_data_sutters(self, mocked):
        """Testing all data fetch from inels."""
        mocked.return_value = TEST_RETURN_RESOURCE_SHUTTER_UP

        with patch.object(self.api, 'ping', return_value=True):
            with patch.object(self.api, TEST_API_ROOM_DEVICES,
                              return_value=TEST_RAW_SHUTTER):
                obj_list = self.api.getRoomDevices('room')

                with patch.object(self.api, "getRooms",
                                  return_value=["room"]):
                    with patch.object(self.api, "getRoomDevices",
                                      return_value=obj_list):
                        devices = self.api.getAllDevices()

                        with patch.object(self.api, "read",
                                          return_value=mocked.return_value):
                            shutt = pyShutter(devices[0])

                            with patch.object(self.api, "write",
                                              return_value=None):
                                shutt.pull_up()

                                fetch = self.api.fetch_all_devices()
                                self.assertEqual(shutt.value, fetch)

    @patch(f'{TEST_API_NAMESPACE}.resources.ApiResource.get_value')
    def test_create_unknown_device(self, mocked):
        """Testing not known device were created by API."""
        mocked.return_value = TEST_RETURN_RESOURCE_SHUTTER_UP

        with patch.object(self.api, 'ping', return_value=True):
            with patch.object(self.api, TEST_API_ROOM_DEVICES,
                              return_value=TEST_RAW_SCENE):
                obj_list = self.api.getRoomDevices('room')

                with patch.object(self.api, "getRooms", return_value=["room"]):

                    with patch.object(self.api, "getRoomDevices",
                                      return_value=obj_list):
                        devices = self.api.getAllDevices()

                        self.assertEqual(1, len(devices))
コード例 #24
0
 def setUp(self):
     """Setup all necessary instances nad mocks."""
     self.api = Api(f'http://{MMS_IP_ADDRESS}', 8001, "CU3")