Skip to content

Commit 1af69b9

Browse files
authored
Remove asserts from non tests (#250)
* Replace assert statements with if/else statements Fix for #215 * Change ValueErrors to better type TypeErrors * Fix wrong isinstance request back to "not in" check Fix tests to await correct Error * Fix wrong Error types Replace "is False" with a better "not" statement * Fix wrong errortype * Use Snap7Exception to use unified error messages * Fix expected exception to Snap7Exception to be consistent. * Replace TypeError with Snap7Exception to seperate python- and snap7 type errors * Replace Snap7Exceptions with better ValueError * Change Snap7Exception with excepted ValueError * Remove unuesed imports replace Snap7Exception with ValueError
1 parent 0447d40 commit 1af69b9

File tree

7 files changed

+43
-26
lines changed

7 files changed

+43
-26
lines changed

snap7/client.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -244,8 +244,9 @@ def read_area(self, area: str, dbnumber: int, start: int, size: int) -> bytearra
244244
:param start: offset to start writing
245245
:param size: number of units to read
246246
"""
247-
assert area in snap7.types.areas.values()
248-
if area == snap7.types.S7AreaTM:
247+
if area not in snap7.types.areas.values():
248+
raise ValueError(f"{area} is not implemented in snap7.types")
249+
elif area == snap7.types.S7AreaTM:
249250
wordlen = snap7.types.S7WLTimer
250251
elif area == snap7.types.S7AreaCT:
251252
wordlen = snap7.types.S7WLCounter
@@ -349,7 +350,8 @@ def get_block_info(self, blocktype: str, db_number: int) -> TS7BlockInfo:
349350
@error_wrap
350351
def set_session_password(self, password: str) -> int:
351352
"""Send the password to the PLC to meet its security level."""
352-
assert len(password) <= 8, 'maximum password length is 8'
353+
if len(password) > 8:
354+
raise ValueError("Maximum password length is 8")
353355
return self._library.Cli_SetSessionPassword(self._pointer,
354356
c_char_p(password.encode()))
355357

@@ -367,7 +369,8 @@ def set_connection_params(self, address: str, local_tsap: int, remote_tsap: int)
367369
:param local_tsap: Local TSAP (PC TSAP)
368370
:param remote_tsap: Remote TSAP (PLC TSAP)
369371
"""
370-
assert re.match(ipv4, address), f'{address} is invalid ipv4'
372+
if not re.match(ipv4, address):
373+
raise ValueError(f"{address} is invalid ipv4")
371374
result = self._library.Cli_SetConnectionParams(self._pointer, address,
372375
c_uint16(local_tsap),
373376
c_uint16(remote_tsap))
@@ -620,8 +623,8 @@ def wait_as_completion(self, timeout: int) -> int:
620623

621624
def _prepare_as_read_area(self, area: str, size: int) -> Tuple[int, Array]:
622625
if area not in snap7.types.areas.values():
623-
raise NotImplementedError(f"{area} is not implemented in snap7.types")
624-
if area == snap7.types.S7AreaTM:
626+
raise ValueError(f"{area} is not implemented in snap7.types")
627+
elif area == snap7.types.S7AreaTM:
625628
wordlen = snap7.types.S7WLTimer
626629
elif area == snap7.types.S7AreaCT:
627630
wordlen = snap7.types.S7WLCounter
@@ -649,8 +652,8 @@ def as_read_area(self, area: str, dbnumber: int, start: int, size: int, wordlen:
649652

650653
def _prepare_as_write_area(self, area: str, data: bytearray) -> Tuple[int, Array]:
651654
if area not in snap7.types.areas.values():
652-
raise NotImplementedError(f"{area} is not implemented in snap7.types")
653-
if area == snap7.types.S7AreaTM:
655+
raise ValueError(f"{area} is not implemented in snap7.types")
656+
elif area == snap7.types.S7AreaTM:
654657
wordlen = snap7.types.S7WLTimer
655658
elif area == snap7.types.S7AreaCT:
656659
wordlen = snap7.types.S7WLCounter

snap7/common.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,8 @@ def error_text(error, context: str = "client") -> bytes:
7373
:param context: server, client or partner
7474
:returns: the error string
7575
"""
76-
assert context in ("client", "server", "partner")
76+
if context not in ("client", "server", "partner"):
77+
raise TypeError(f"Unkown context {context} used, should be either client, server or partner")
7778
logger.debug(f"error text for {hex(error)}")
7879
len_ = 1024
7980
text_type = c_char * len_

snap7/logo.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,8 @@ def set_connection_params(self, ip_address: str, tsap_snap7: int, tsap_logo: int
248248
:param tsap_snap7: TSAP SNAP7 Client (e.g. 10.00 = 0x1000)
249249
:param tsap_logo: TSAP Logo Server (e.g. 20.00 = 0x2000)
250250
"""
251-
assert re.match(ipv4, ip_address), f'{ip_address} is invalid ipv4'
251+
if not re.match(ipv4, ip_address):
252+
raise ValueError(f"{ip_address} is invalid ipv4")
252253
result = self.library.Cli_SetConnectionParams(self.pointer, ip_address.encode(),
253254
c_uint16(tsap_snap7),
254255
c_uint16(tsap_logo))

snap7/partner.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -209,8 +209,11 @@ def start_to(self, local_ip: str, remote_ip: str, local_tsap: int, remote_tsap:
209209
:param local_tsap: Local TSAP
210210
:param remote_tsap: PLC TSAP
211211
"""
212-
assert re.match(ipv4, local_ip), f'{local_ip} is invalid ipv4'
213-
assert re.match(ipv4, remote_ip), f'{remote_ip} is invalid ipv4'
212+
213+
if not re.match(ipv4, local_ip):
214+
raise ValueError(f"{local_ip} is invalid ipv4")
215+
if not re.match(ipv4, remote_ip):
216+
raise ValueError(f"{remote_ip} is invalid ipv4")
214217
logger.info(f"starting partnering from {local_ip} to {remote_ip}")
215218
return self._library.Par_StartTo(self._pointer, local_ip, remote_ip,
216219
c_uint16(local_tsap),

snap7/server.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,8 @@ def start_to(self, ip: str, tcpport: int = 102):
219219
if tcpport != 102:
220220
logger.info(f"setting server TCP port to {tcpport}")
221221
self.set_param(snap7.types.LocalPort, tcpport)
222-
assert re.match(ipv4, ip), f'{ip} is invalid ipv4'
222+
if not re.match(ipv4, ip):
223+
raise ValueError(f"{ip} is invalid ipv4")
223224
logger.info(f"starting server to {ip}:102")
224225
return self.library.Srv_StartTo(self.pointer, ip)
225226

@@ -242,7 +243,8 @@ def set_mask(self, kind: int, mask: int):
242243
def set_cpu_status(self, status: int):
243244
"""Sets the Virtual CPU status.
244245
"""
245-
assert status in snap7.types.cpu_statuses, f'unknown cpu state {status}'
246+
if status not in snap7.types.cpu_statuses:
247+
raise ValueError(f"The cpu state ({status}) is invalid")
246248
logger.debug(f"setting cpu status to {status}")
247249
return self.library.Srv_SetCpuStatus(self.pointer, status)
248250

snap7/util.py

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,9 @@ def set_bool(bytearray_: bytearray, byte_index: int, bool_index: int, value: boo
106106
"""
107107
Set boolean value on location in bytearray
108108
"""
109-
assert value in [0, 1, True, False]
109+
if value not in {0, 1, True, False}:
110+
raise TypeError(f"Value value:{value} is not a boolean expression.")
111+
110112
current_value = get_bool(bytearray_, byte_index, bool_index)
111113
index_value = 1 << bool_index
112114

@@ -200,7 +202,8 @@ def set_string(bytearray_: bytearray, byte_index: int, value: str, max_size: int
200202
:params value: string data
201203
:params max_size: max possible string size
202204
"""
203-
assert isinstance(value, str)
205+
if not isinstance(value, str):
206+
raise TypeError(f"Value value:{value} is not from Type string")
204207

205208
size = len(value)
206209
# FAIL HARD WHEN trying to write too much data into PLC
@@ -487,7 +490,8 @@ def __len__(self):
487490
return len(self.index)
488491

489492
def set_data(self, bytearray_: bytearray):
490-
assert (isinstance(bytearray_, bytearray))
493+
if not isinstance(bytearray_, bytearray):
494+
raise TypeError(f"Value bytearray_: {bytearray_} is not from type bytearray")
491495
self._bytearray = bytearray_
492496

493497

@@ -505,7 +509,8 @@ def __init__(self, bytearray_, _specification, row_size=0, db_offset=0, layout_o
505509
self.row_size = row_size
506510
self.row_offset = row_offset # start of writable part of row
507511

508-
assert (isinstance(bytearray_, (bytearray, DB)))
512+
if not isinstance(bytearray_, (bytearray, DB)):
513+
raise TypeError(f"Value bytearray_ {bytearray_} is not from type (bytearray, DB)")
509514
self._bytearray = bytearray_
510515
self._specification = parse_specification(_specification)
511516

@@ -530,12 +535,10 @@ def __getitem__(self, key):
530535
"""
531536
Get a specific db field
532537
"""
533-
assert key in self._specification
534538
index, _type = self._specification[key]
535539
return self.get_value(index, _type)
536540

537541
def __setitem__(self, key, value):
538-
assert key in self._specification
539542
index, _type = self._specification[key]
540543
self.set_value(index, _type, value)
541544

@@ -675,8 +678,10 @@ def write(self, client):
675678
"""
676679
Write current data to db in plc
677680
"""
678-
assert (isinstance(self._bytearray, DB))
679-
assert (self.row_size >= 0)
681+
if not isinstance(self._bytearray, DB):
682+
raise TypeError(f"Value self._bytearray: {self._bytearray} is not from type DB.")
683+
if self.row_size < 0:
684+
raise ValueError("row_size must be greater equal zero.")
680685

681686
db_nr = self._bytearray.db_number
682687
offset = self.db_offset
@@ -694,8 +699,10 @@ def read(self, client):
694699
"""
695700
read current data of db row from plc
696701
"""
697-
assert (isinstance(self._bytearray, DB))
698-
assert (self.row_size >= 0)
702+
if not isinstance(self._bytearray, DB):
703+
raise TypeError(f"Value self._bytearray:{self._bytearray} is not from type DB.")
704+
if self.row_size < 0:
705+
raise ValueError("row_size must be greater equal zero.")
699706
db_nr = self._bytearray.db_number
700707
bytearray_ = client.db_read(db_nr, self.db_offset, self.row_size)
701708

test/test_server.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def test_set_cpu_status(self):
6767
self.server.set_cpu_status(0)
6868
self.server.set_cpu_status(4)
6969
self.server.set_cpu_status(8)
70-
self.assertRaises(AssertionError, self.server.set_cpu_status, -1)
70+
self.assertRaises(ValueError, self.server.set_cpu_status, -1)
7171

7272
def test_set_mask(self):
7373
self.server.set_mask(kind=snap7.types.mkEvent, mask=10)
@@ -115,7 +115,7 @@ def test_clear_events(self):
115115

116116
def test_start_to(self):
117117
self.server.start_to('0.0.0.0')
118-
self.assertRaises(AssertionError, self.server.start_to, 'bogus')
118+
self.assertRaises(ValueError, self.server.start_to, 'bogus')
119119

120120
def test_get_param(self):
121121
# check the defaults

0 commit comments

Comments
 (0)