def test_sia_account_validation(self, key, account_id, error_type): """Test sia account validation.""" try: SIAAccount.validate_account(account_id, key) assert True if error_type is None else False except Exception as exp: assert isinstance(exp, error_type)
def test_accounts_get_set(self, account_list, unused_tcp_port): """Test the account getting and setting.""" siac = SIAClient( host="", port=unused_tcp_port, accounts=account_list, function=(lambda ev: print(ev)), ) assert siac.accounts == account_list acc_list2 = [ SIAAccount(account_id=ACCOUNT, key=KEY, allowed_timeband=(None, None)), SIAAccount(account_id="1112", key=KEY, allowed_timeband=(None, None)), ] siac.accounts = acc_list2 assert siac.accounts == acc_list2
def test_sia_account_setup( self, unused_tcp_port_factory, key, account_id, error_type ): """Test sia client behaviour.""" try: SIAAccount.validate_account(account_id, key) SIAClient( host="", port=unused_tcp_port_factory(), accounts=[SIAAccount(account_id=account_id, key=key)], function=get_func("sync"), ) assert True if error_type is None else False except Exception as exp: assert isinstance(exp, error_type)
def test_event_parsing( self, line, account_id, type, code, error_type, extended_data_flag ): """Test event parsing methods.""" catch = error_type if error_type is not None else Exception try: if extended_data_flag: event = SIAEvent.from_line(line, {account_id: SIAAccount( account_id, KEY, allowed_timeband=None )}) else: event = SIAEvent.from_line(line) assert event.code == code if code: assert event.sia_code.type == type assert event.account == account_id if extended_data_flag: _LOGGER.warning("CRC: %s", event.calc_crc) assert event.extended_data is not None if event.extended_data[0].identifier == "K": _LOGGER.debug("RSP Response: %s", event.create_response()) assert event.response == ResponseType.RSP else: assert event.response == ResponseType.ACK except AssertionError as e: raise e except catch as e: if error_type is None: _LOGGER.debug("Error thrown: %s", e) assert False if isinstance(e, error_type): assert True
def validate_input(data: dict[str, Any]) -> dict[str, str] | None: """Validate the input by the user.""" try: SIAAccount.validate_account(data[CONF_ACCOUNT], data.get(CONF_ENCRYPTION_KEY)) except InvalidKeyFormatError: return {"base": "invalid_key_format"} except InvalidKeyLengthError: return {"base": "invalid_key_length"} except InvalidAccountFormatError: return {"base": "invalid_account_format"} except InvalidAccountLengthError: return {"base": "invalid_account_length"} except Exception as exc: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception from SIAAccount: %s", exc) return {"base": "unknown"} if not 1 <= data[CONF_PING_INTERVAL] <= 1440: return {"base": "invalid_ping"} return validate_zones(data)
def test_sia_key_account_errors(self, key, account, port, error): """Test sia client behaviour.""" try: SIAClient( host="", port=port, accounts=[SIAAccount(account_id=account, key=key)], function=func, ) assert False if error else True except Exception as exp: assert isinstance(exp, error)
def create_client( unused_tcp_port_factory, event_handler, async_event_handler, bad_handler, async_bad_handler, key, good, protocol, sync, ): """Fixture to create a SIA Client.""" config = { "host": HOST, "port": unused_tcp_port_factory(), "account_id": ACCOUNT, "key": key, "protocol": protocol, } if sync: client = SIAClient( host=config["host"], port=config["port"], accounts=[SIAAccount(config["account_id"], config["key"])], function=event_handler if good else bad_handler, protocol=config["protocol"], ) else: client = SIAClientA( host=config["host"], port=config["port"], accounts=[SIAAccount(config["account_id"], config["key"])], function=async_event_handler if good else async_bad_handler, protocol=config["protocol"], ) return (client, config, good, sync)
def validate_input(data: dict) -> bool: """Validate the input by the user.""" SIAAccount(data[CONF_ACCOUNT], data.get(CONF_ENCRYPTION_KEY)) try: ping = int(data[CONF_PING_INTERVAL]) assert 1 <= ping <= 1440 except AssertionError: raise InvalidPing try: zones = int(data[CONF_ZONES]) assert zones > 0 except AssertionError: raise InvalidZones return True
def test_parse_and_check( self, unused_tcp_port_factory, event_handler, key, code, msg_type, alter_key, wrong_event, response, ): """Test the server parsing.""" if msg_type in ("ADM-CID", "NULL") and code == "ZX": pytest.skip( "Unknown code is not usefull to test in ADM-CID and NULL messages." ) return if alter_key and key is None: pytest.skip("Alter key is not usefull to test when not encrypted.") return siac = SIAClient( HOST, unused_tcp_port_factory(), [SIAAccount(ACCOUNT, key)], event_handler ) line = create_test_line( account=ACCOUNT, key=key, code=code, msg_type=msg_type, wrong_event=wrong_event, alter_key=alter_key, ) _LOGGER.warning("Line to parse: %s", line) event = siac.sia_server.parse_and_check_event(line) _LOGGER.warning("Event received: %s", event) assert event.response == response if wrong_event or alter_key: assert isinstance(event, NAKEvent) else: assert event.account == ACCOUNT assert event.code == "RP" if msg_type == "NULL" else code
from pysiaalarm import SIAClient from pysiaalarm import SIAEvent logging.basicConfig(level=logging.DEBUG) events = [] def func(event: SIAEvent): events.append(event) with open("unencrypted_config.json", "r") as f: config = json.load(f) account = [SIAAccount(config["account_id"], config["key"])] client = SIAClient(config["host"], config["port"], account, function=func) sleep_time = 120 client.start() time.sleep(20) print(f"Client started... adding extra account") accounts = client.accounts accounts.append(SIAAccount("FFFFFFFFF", config["key"])) client.accounts = accounts print("--------------------------------------------------") print(f"Running for another {sleep_time} seconds") time.sleep(sleep_time) print(f"Client will stop now...") print("--------------------------------------------------")
def test_client(self, config_file): """Test the client. Arguments: config_file {str} -- Filename of the config. """ try: with open(config_file, "r") as f: config = json.load(f) except: # noqa: E722 config = { "host": HOST, "port": PORT, "account_id": ACCOUNT, "key": None } events = [] def func_append(event: SIAEvent): events.append(event) siac = SIAClient( host="", port=config["port"], accounts=[ SIAAccount(account_id=config["account_id"], key=config["key"]) ], function=func_append, ) siac.start() tests = [ { "code": False, "crc": False, "account": False, "time": False }, { "code": True, "crc": False, "account": False, "time": False }, { "code": False, "crc": True, "account": False, "time": False }, { "code": False, "crc": False, "account": True, "time": False }, { "code": False, "crc": False, "account": False, "time": True }, ] t = threading.Thread(target=client_program, name="test_client", args=(config, 1, tests)) t.daemon = True t.start() # stops after the five events have been sent. # run for 30 seconds time.sleep(30) siac.stop() assert siac.counts == { "events": 5, "valid_events": 1, "errors": { "crc": 1, "timestamp": 1, "account": 1, "code": 1, "format": 0, "user_code": 0, }, } assert len(events) == 1
import logging import time from pysiaalarm import SIAAccount, SIAClient, SIAEvent logging.basicConfig(level=logging.DEBUG) events = [] def func(event: SIAEvent): events.append(event) with open("local_config.json", "r") as f: config = json.load(f) print("Config: ", config) account = [SIAAccount(config["account_id"], config["key"])] sleep_time = 1200 with SIAClient(config["host"], config["port"], account, function=func) as client: time.sleep(sleep_time) counts = client.counts # for ev in events: # print(ev) print("--------------------------------------------------") print("Number of events: ", len(events)) print("Counts: ", counts) print("--------------------------------------------------")
def account(): """Return default account.""" return SIAAccount(ACCOUNT, KEY)