Attention is currently required from: fixeria.
pespin has posted comments on this change. ( https://gerrit.osmocom.org/c/libosmo-gprs/+/35782?usp=email )
Change subject: rlcmac: Add new structure to allow passing FN+TN to TBF handling functions
......................................................................
Patch Set 2:
(1 comment)
Patchset:
PS2:
I plan to merge this whole patchset today so simplify going forward (more testing).
--
To view, visit https://gerrit.osmocom.org/c/libosmo-gprs/+/35782?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings
Gerrit-Project: libosmo-gprs
Gerrit-Branch: master
Gerrit-Change-Id: Ifa09cd70c915aa3a2b799412cb02315aaebc0503
Gerrit-Change-Number: 35782
Gerrit-PatchSet: 2
Gerrit-Owner: pespin <pespin(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-CC: fixeria <vyanitskiy(a)sysmocom.de>
Gerrit-Attention: fixeria <vyanitskiy(a)sysmocom.de>
Gerrit-Comment-Date: Mon, 05 Feb 2024 09:50:44 +0000
Gerrit-HasComments: Yes
Gerrit-Has-Labels: No
Gerrit-MessageType: comment
Attention is currently required from: laforge.
Hello Jenkins Builder,
I'd like you to reexamine a change. Please visit
https://gerrit.osmocom.org/c/pysim/+/35809?usp=email
to look at the new patch set (#2).
The following approvals got outdated and were removed:
Verified-1 by Jenkins Builder
Change subject: pylint: card_key_provider.py, card_handler.py, iso7816_4.py, jsonpath.py
......................................................................
pylint: card_key_provider.py, card_handler.py, iso7816_4.py, jsonpath.py
pySim/card_key_provider.py:57:0: C0325: Unnecessary parens after 'if' keyword (superfluous-parens)
pySim/card_key_provider.py:61:0: C0325: Unnecessary parens after 'if' keyword (superfluous-parens)
pySim/card_handler.py:100:0: C0325: Unnecessary parens after '=' keyword (superfluous-parens)
pySim/card_handler.py:100:24: C0121: Comparison 'self.cmds.get('verbose') == True' should be 'self.cmds.get('verbose') is True' if checking for the singleton value True, or 'bool(self.cmds.get('verbose'))' if testing for truthiness (singleton-comparison)
pySim/card_handler.py:29:0: C0411: standard import "import subprocess" should be placed before "from pySim.transport import LinkBase" (wrong-import-order)
pySim/card_handler.py:30:0: C0411: standard import "import sys" should be placed before "from pySim.transport import LinkBase" (wrong-import-order)
pySim/card_handler.py:31:0: C0411: third party import "import yaml" should be placed before "from pySim.transport import LinkBase" (wrong-import-order)
pySim/iso7816_4.py:20:0: W0401: Wildcard import construct (wildcard-import)
pySim/jsonpath.py:1:0: C0114: Missing module docstring (missing-module-docstring)
pySim/jsonpath.py:6:0: W0105: String statement has no effect (pointless-string-statement)
pySim/jsonpath.py:2:0: W0611: Unused import json (unused-import)
pySim/jsonpath.py:3:0: W0611: Unused import pprint (unused-import)
Change-Id: I780595d69000f727ad0fbaff4b89918b91b3122e
---
M pySim/card_handler.py
M pySim/card_key_provider.py
M pySim/iso7816_4.py
M pySim/jsonpath.py
4 files changed, 32 insertions(+), 11 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/09/35809/2
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/35809?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I780595d69000f727ad0fbaff4b89918b91b3122e
Gerrit-Change-Number: 35809
Gerrit-PatchSet: 2
Gerrit-Owner: laforge <laforge(a)osmocom.org>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Attention: laforge <laforge(a)osmocom.org>
Gerrit-MessageType: newpatchset
Attention is currently required from: laforge.
Hello Jenkins Builder,
I'd like you to reexamine a change. Please visit
https://gerrit.osmocom.org/c/pysim/+/35814?usp=email
to look at the new patch set (#2).
The following approvals got outdated and were removed:
Verified-1 by Jenkins Builder
Change subject: pylint: sms.py
......................................................................
pylint: sms.py
pySim/sms.py:23:0: W0404: Reimport 'Flag' (imported line 23) (reimported)
pySim/sms.py:54:4: C0103: Method name "fromBytes" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:60:4: C0103: Method name "toBytes" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:120:4: C0103: Method name "fromBytes" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:132:4: C0103: Method name "fromSmpp" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:137:4: C0103: Method name "toSmpp" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:141:4: C0103: Method name "toBytes" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:188:4: C0103: Method name "fromBytes" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:192:8: W0612: Unused variable 'flags' (unused-variable)
pySim/sms.py:209:4: C0103: Method name "toBytes" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:228:4: C0103: Method name "fromSmpp" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:236:4: C0103: Method name "fromSmppSubmit" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:279:4: C0103: Method name "fromBytes" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:306:12: W0107: Unnecessary pass statement (unnecessary-pass)
pySim/sms.py:311:12: W0107: Unnecessary pass statement (unnecessary-pass)
pySim/sms.py:319:4: C0103: Method name "toBytes" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:339:4: C0103: Method name "fromSmpp" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:347:4: C0103: Method name "fromSmppSubmit" doesn't conform to snake_case naming style (invalid-name)
pySim/sms.py:373:4: C0103: Method name "toSmpp" doesn't conform to snake_case naming style (invalid-nam
Change-Id: I8082a01443ef568eebda696239572f0af7b56f1b
---
M pySim/ota.py
M pySim/sms.py
M tests/test_ota.py
M tests/test_sms.py
4 files changed, 79 insertions(+), 53 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/14/35814/2
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/35814?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I8082a01443ef568eebda696239572f0af7b56f1b
Gerrit-Change-Number: 35814
Gerrit-PatchSet: 2
Gerrit-Owner: laforge <laforge(a)osmocom.org>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Attention: laforge <laforge(a)osmocom.org>
Gerrit-MessageType: newpatchset
laforge has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/35849?usp=email )
Change subject: pylint: utils.py
......................................................................
pylint: utils.py
pySim/utils.py:903:0: C0325: Unnecessary parens after 'if' keyword (superfluous-parens)
pySim/utils.py:153:16: R1719: The if expression can be replaced with 'bool(test)' (simplifiable-if-expression)
pySim/utils.py:158:16: R1719: The if expression can be replaced with 'bool(test)' (simplifiable-if-expression)
pySim/utils.py:166:16: R1719: The if expression can be replaced with 'bool(test)' (simplifiable-if-expression)
pySim/utils.py:222:19: R1719: The if expression can be replaced with 'not test' (simplifiable-if-expression)
pySim/utils.py:237:18: R1719: The if expression can be replaced with 'bool(test)' (simplifiable-if-expression)
pySim/utils.py:246:19: R1719: The if expression can be replaced with 'not test' (simplifiable-if-expression)
pySim/utils.py:279:11: W0612: Unused variable 'remainder' (unused-variable)
pySim/utils.py:541:7: R1714: Consider merging these comparisons with 'in' by using 'eutran_bits in (16384, 28672)'. Use a set instead if elements are hashable. (consider-using-in)
pySim/utils.py:550:7: R1714: Consider merging these comparisons with 'in' by using 'gsm_bits in (128, 140)'. Use a set instead if elements are hashable. (consider-using-in)
pySim/utils.py:614:7: C0121: Comparison 'imsi == None' should be 'imsi is None' (singleton-comparison)
pySim/utils.py:627:7: C0121: Comparison 'imsi == None' should be 'imsi is None' (singleton-comparison)
pySim/utils.py:733:7: R1714: Consider merging these comparisons with 'in' by using 'msisdn in ('', '+')'. Use a set instead if elements are hashable. (consider-using-in)
pySim/utils.py:774:8: W0612: Unused variable 'try_encode' (unused-variable)
pySim/utils.py:803:16: W0707: Consider explicitly re-raising using 'except ValueError as exc' and 'raise ValueError('PIN-ADM needs to be hex encoded using this option') from exc' (raise-missing-from)
pySim/utils.py:801:16: W0612: Unused variable 'try_encode' (unused-variable)
pySim/utils.py:821:7: C1802: Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty (use-implicit-booleaness-not-len)
pySim/utils.py:836:4: W0612: Unused variable 'e' (unused-variable)
pySim/utils.py:892:7: C0121: Comparison 'str_list == None' should be 'str_list is None' (singleton-comparison)
pySim/utils.py:991:11: R1701: Consider merging these isinstance calls to isinstance(o, (BytesIO, bytearray, bytes)) (consider-merging-isinstance)
Change-Id: I190ae75964ef6e0ed43fae994693a8bccd21c7f7
---
M pySim/utils.py
1 file changed, 51 insertions(+), 23 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/49/35849/1
diff --git a/pySim/utils.py b/pySim/utils.py
index 73e5040..86874ba 100644
--- a/pySim/utils.py
+++ b/pySim/utils.py
@@ -150,12 +150,12 @@
# three-byte tag
tag = (binary[1] & 0x7f) << 8
tag |= binary[2]
- compr = True if binary[1] & 0x80 else False
+ compr = bool(binary[1] & 0x80)
return ({'comprehension': compr, 'tag': tag}, binary[3:])
else:
# single byte tag
tag = binary[0] & 0x7f
- compr = True if binary[0] & 0x80 else False
+ compr = bool(binary[0] & 0x80)
return ({'comprehension': compr, 'tag': tag}, binary[1:])
@@ -163,7 +163,7 @@
"""Encode a single Tag according to ETSI TS 101 220 Section 7.1.1"""
# permit caller to specify tag also as integer value
if isinstance(tag, int):
- compr = True if tag < 0xff and tag & 0x80 else False
+ compr = bool(tag < 0xff and tag & 0x80)
tag = {'tag': tag, 'comprehension': compr}
compr = tag.get('comprehension', False)
if tag['tag'] in [0x00, 0x80, 0xff] or tag['tag'] > 0xff:
@@ -219,7 +219,7 @@
i = 1
last = False
while not last:
- last = False if binary[i] & 0x80 else True
+ last = not bool(binary[i] & 0x80)
tag <<= 8
tag |= binary[i]
i += 1
@@ -234,7 +234,7 @@
Tuple of ({class:int, constructed:bool, tag:int}, remainder:bytes)
"""
cls = binary[0] >> 6
- constructed = True if binary[0] & 0x20 else False
+ constructed = bool(binary[0] & 0x20)
tag = binary[0] & 0x1f
if tag <= 30:
return ({'class': cls, 'constructed': constructed, 'tag': tag}, binary[1:])
@@ -243,7 +243,7 @@
i = 1
last = False
while not last:
- last = False if binary[i] & 0x80 else True
+ last = not bool(binary[i] & 0x80)
tag <<= 7
tag |= binary[i] & 0x7f
i += 1
@@ -276,7 +276,7 @@
if isinstance(t, int):
# first convert to a dict representation
tag_size = count_int_bytes(t)
- t, remainder = bertlv_parse_tag(t.to_bytes(tag_size, 'big'))
+ t, _remainder = bertlv_parse_tag(t.to_bytes(tag_size, 'big'))
tag = t['tag']
constructed = t['constructed']
cls = t['class']
@@ -538,7 +538,7 @@
sel.add(a['name'])
# TS 31.102 Section 4.2.5 Table 4.2.5.1
eutran_bits = u16t & 0x7000
- if eutran_bits == 0x4000 or eutran_bits == 0x7000:
+ if eutran_bits in [0x4000, 0x7000]:
sel.add("E-UTRAN WB-S1")
sel.add("E-UTRAN NB-S1")
elif eutran_bits == 0x5000:
@@ -547,7 +547,7 @@
sel.add("E-UTRAN WB-S1")
# TS 31.102 Section 4.2.5 Table 4.2.5.2
gsm_bits = u16t & 0x008C
- if gsm_bits == 0x0080 or gsm_bits == 0x008C:
+ if gsm_bits in [0x0080, 0x008C]:
sel.add("GSM")
sel.add("EC-GSM-IoT")
elif u16t & 0x008C == 0x0084:
@@ -611,7 +611,7 @@
"""
Derive the MCC (Mobile Country Code) from the first three digits of an IMSI
"""
- if imsi == None:
+ if imsi is None:
return None
if len(imsi) > 3:
@@ -624,7 +624,7 @@
"""
Derive the MNC (Mobile Country Code) from the 4th to 6th digit of an IMSI
"""
- if imsi == None:
+ if imsi is None:
return None
if len(imsi) > 3:
@@ -730,7 +730,7 @@
"""
# If no MSISDN is supplied then encode the file contents as all "ff"
- if msisdn == "" or msisdn == "+":
+ if msisdn in ["", "+"]:
return "ff" * 14
# Leading '+' indicates International Number
@@ -771,7 +771,7 @@
# Try actual encoding to be sure
try:
- try_encode = h2b(string)
+ _try_encode = h2b(string)
return True
except:
return False
@@ -799,12 +799,10 @@
# Ensure that it's hex-encoded
try:
try_encode = h2b(pin_adm)
- except ValueError:
- raise ValueError(
- "PIN-ADM needs to be hex encoded using this option")
+ except ValueError as exc:
+ raise ValueError("PIN-ADM needs to be hex encoded using this option") from exc
else:
- raise ValueError(
- "PIN-ADM needs to be exactly 16 digits (hex encoded)")
+ raise ValueError("PIN-ADM needs to be exactly 16 digits (hex encoded)")
return pin_adm
@@ -818,7 +816,7 @@
"""
# Empty address string
- if not len(addr):
+ if len(addr) == 0:
return None
addr_list = addr.split('.')
@@ -833,7 +831,7 @@
return 0x01
elif ipa.version == 6:
return 0x02
- except Exception as e:
+ except Exception:
invalid_ipv4 = True
for i in addr_list:
# Invalid IPv4 may qualify for a valid FQDN, so make check here
@@ -889,7 +887,7 @@
Returns:
multi-line string containing formatted table
"""
- if str_list == None:
+ if str_list is None:
return ""
if len(str_list) <= 0:
return ""
@@ -900,7 +898,7 @@
table = []
for i in iter(range(rows)):
str_list_row = str_list[i::rows]
- if (align_left):
+ if align_left:
format_str_cell = '%%-%ds'
else:
format_str_cell = '%%%ds'
@@ -988,7 +986,7 @@
"""Extend the standard library JSONEncoder with support for more types."""
def default(self, o):
- if isinstance(o, BytesIO) or isinstance(o, bytes) or isinstance(o, bytearray):
+ if isinstance(o, (BytesIO, bytes, bytearray)):
return b2h(o)
elif isinstance(o, datetime.datetime):
return o.isoformat()
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/35849?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I190ae75964ef6e0ed43fae994693a8bccd21c7f7
Gerrit-Change-Number: 35849
Gerrit-PatchSet: 1
Gerrit-Owner: laforge <laforge(a)osmocom.org>
Gerrit-MessageType: newchange
laforge has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/35850?usp=email )
Change subject: pylint: tlv.py
......................................................................
pylint: tlv.py
pySim/tlv.py:29:0: W0401: Wildcard import pySim.exceptions (wildcard-import)
pySim/tlv.py:43:4: C0204: Metaclass class method __new__ should have 'mcs' as first argument (bad-mcs-classmethod-argument)
pySim/tlv.py:66:4: C0204: Metaclass class method __new__ should have 'mcs' as first argument (bad-mcs-classmethod-argument)
pySim/tlv.py:89:11: C0121: Comparison 'self.decoded == None' should be 'self.decoded is None' (singleton-comparison)
pySim/tlv.py:170:8: R1703: The if statement can be replaced with 'return bool(test)' (simplifiable-if-statement)
pySim/tlv.py:202:4: W0246: Useless parent or super() delegation in method '__init__' (useless-parent-delegation)
pySim/tlv.py:257:4: W0246: Useless parent or super() delegation in method '__init__' (useless-parent-delegation)
pySim/tlv.py:308:4: W0246: Useless parent or super() delegation in method '__init__' (useless-parent-delegation)
pySim/tlv.py:383:15: C0121: Comparison 'tag == None' should be 'tag is None' (singleton-comparison)
pySim/tlv.py:382:17: W0612: Unused variable 'r' (unused-variable)
pySim/tlv.py:389:16: W0612: Unused variable 'dec' (unused-variable)
pySim/tlv.py:461:22: R1718: Consider using a set comprehension (consider-using-set-comprehension)
pySim/tlv.py:473:0: C0206: Consider iterating with .items() (consider-using-dict-items)
pySim/tlv.py:473:58: C0201: Consider iterating the dictionary directly instead of calling .keys() (consider-iterating-dictionary)
pySim/tlv.py:20:0: W0611: Unused Optional imported from typing (unused-import)
pySim/tlv.py:20:0: W0611: Unused Dict imported from typing (unused-import)
pySim/tlv.py:20:0: W0611: Unused Any imported from typing (unused-import)
pySim/tlv.py:21:0: W0611: Unused bidict imported from bidict (unused-import)
pySim/tlv.py:28:0: W0611: Unused LV imported from pySim.construct (unused-import)
pySim/tlv.py:28:0: W0611: Unused HexAdapter imported from pySim.construct (unused-import)
pySim/tlv.py:28:0: W0611: Unused BcdAdapter imported from pySim.construct (unused-import)
pySim/tlv.py:28:0: W0611: Unused BitsRFU imported from pySim.construct (unused-import)
pySim/tlv.py:28:0: W0611: Unused GsmStringAdapter imported from pySim.construct (unused-import)
pySim/tlv.py:29:0: W0614: Unused import(s) NoCardError, ProtocolError, ReaderError and SwMatchError from wildcard import of pySim.exceptions (unused-wildcard-import)
Change-Id: Ic22d00d3ae73ad81167276d9482b7b86a04476ba
---
M pySim/tlv.py
1 file changed, 54 insertions(+), 35 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/50/35850/1
diff --git a/pySim/tlv.py b/pySim/tlv.py
index 0dfb858..26e624e 100644
--- a/pySim/tlv.py
+++ b/pySim/tlv.py
@@ -16,21 +16,18 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-from typing import Optional, List, Dict, Any, Tuple
-from bidict import bidict
+import inspect
+import abc
+import re
+from typing import List, Tuple
from pySim.utils import bertlv_encode_len, bertlv_parse_len, bertlv_encode_tag, bertlv_parse_tag
from pySim.utils import comprehensiontlv_encode_tag, comprehensiontlv_parse_tag
from pySim.utils import bertlv_parse_tag_raw, comprehensiontlv_parse_tag_raw
from pySim.utils import dgi_parse_tag_raw, dgi_parse_len, dgi_encode_tag, dgi_encode_len
-from pySim.construct import build_construct, parse_construct, LV, HexAdapter, BcdAdapter, BitsRFU, GsmStringAdapter
-from pySim.exceptions import *
+from pySim.construct import build_construct, parse_construct
-import inspect
-import abc
-import re
def camel_to_snake(name):
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
@@ -40,9 +37,9 @@
"""Metaclass which we use to set some class variables at the time of defining a subclass.
This allows us to create subclasses for each TLV/IE type, where the class represents fixed
parameters like the tag/type and instances of it represent the actual TLV data."""
- def __new__(metacls, name, bases, namespace, **kwargs):
- #print("TlvMeta_new_(metacls=%s, name=%s, bases=%s, namespace=%s, kwargs=%s)" % (metacls, name, bases, namespace, kwargs))
- x = super().__new__(metacls, name, bases, namespace)
+ def __new__(mcs, name, bases, namespace, **kwargs):
+ #print("TlvMeta_new_(mcs=%s, name=%s, bases=%s, namespace=%s, kwargs=%s)" % (mcs, name, bases, namespace, kwargs))
+ x = super().__new__(mcs, name, bases, namespace)
# this becomes a _class_ variable, not an instance variable
x.tag = namespace.get('tag', kwargs.get('tag', None))
x.desc = namespace.get('desc', kwargs.get('desc', None))
@@ -63,9 +60,9 @@
"""Metaclass which we use to set some class variables at the time of defining a subclass.
This allows us to create subclasses for each Collection type, where the class represents fixed
parameters like the nested IE classes and instances of it represent the actual TLV data."""
- def __new__(metacls, name, bases, namespace, **kwargs):
- #print("TlvCollectionMeta_new_(metacls=%s, name=%s, bases=%s, namespace=%s, kwargs=%s)" % (metacls, name, bases, namespace, kwargs))
- x = super().__new__(metacls, name, bases, namespace)
+ def __new__(mcs, name, bases, namespace, **kwargs):
+ #print("TlvCollectionMeta_new_(mcs=%s, name=%s, bases=%s, namespace=%s, kwargs=%s)" % (mcs, name, bases, namespace, kwargs))
+ x = super().__new__(mcs, name, bases, namespace)
# this becomes a _class_ variable, not an instance variable
x.possible_nested = namespace.get('nested', kwargs.get('nested', None))
return x
@@ -86,7 +83,7 @@
def to_bytes(self, context: dict = {}) -> bytes:
"""Convert from internal representation to binary bytes. Store the binary result
in the internal state and return it."""
- if self.decoded == None:
+ if self.decoded is None:
do = b''
elif self._construct:
do = build_construct(self._construct, self.decoded, context)
@@ -167,10 +164,7 @@
def is_constructed(self):
"""Is this IE constructed by further nested IEs?"""
- if len(self.children):
- return True
- else:
- return False
+ return bool(len(self.children) > 0)
@abc.abstractmethod
def to_ie(self, context: dict = {}) -> bytes:
@@ -199,9 +193,6 @@
class TLV_IE(IE):
"""Abstract base class for various TLV type Information Elements."""
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
-
def _compute_tag(self) -> int:
"""Compute the tag (sometimes the tag encodes part of the value)."""
return self.tag
@@ -254,9 +245,6 @@
class BER_TLV_IE(TLV_IE):
"""TLV_IE formatted as ASN.1 BER described in ITU-T X.690 8.1.2."""
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
-
@classmethod
def _decode_tag(cls, do: bytes) -> Tuple[dict, bytes]:
return bertlv_parse_tag(do)
@@ -305,9 +293,6 @@
class DGI_TLV_IE(TLV_IE):
"""TLV_IE formated as GlobalPlatform Systems Scripting Language Specification v1.1.0 Annex B."""
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
-
@classmethod
def _parse_tag_raw(cls, do: bytes) -> Tuple[int, bytes]:
return dgi_parse_tag_raw(do)
@@ -379,14 +364,14 @@
while len(remainder):
context['siblings'] = res
# obtain the tag at the start of the remainder
- tag, r = first._parse_tag_raw(remainder)
- if tag == None:
+ tag, _r = first._parse_tag_raw(remainder)
+ if tag is None:
break
if tag in self.members_by_tag:
cls = self.members_by_tag[tag]
# create an instance and parse accordingly
inst = cls()
- dec, remainder = inst.from_tlv(remainder, context=context)
+ _dec, remainder = inst.from_tlv(remainder, context=context)
res.append(inst)
else:
# unknown tag; create the related class on-the-fly using the same base class
@@ -397,7 +382,7 @@
cls._to_bytes = lambda s: bytes.fromhex(s.decoded['raw'])
# create an instance and parse accordingly
inst = cls()
- dec, remainder = inst.from_tlv(remainder, context=context)
+ _dec, remainder = inst.from_tlv(remainder, context=context)
res.append(inst)
self.children = res
return res
@@ -458,7 +443,7 @@
return True
def are_elements_unique(lod):
- set_of_keys = set([list(x.keys())[0] for x in lod])
+ set_of_keys = {list(x.keys())[0] for x in lod}
return len(lod) == len(set_of_keys)
if isinstance(inp, list):
@@ -470,10 +455,10 @@
newdict[key] = e[key]
inp = newdict
# process result as any native dict
- return {k:flatten_dict_lists(inp[k]) for k in inp.keys()}
+ return {k:flatten_dict_lists(v) for k,v in inp}
else:
return [flatten_dict_lists(x) for x in inp]
elif isinstance(inp, dict):
- return {k:flatten_dict_lists(inp[k]) for k in inp.keys()}
+ return {k:flatten_dict_lists(v) for k,v in inp}
else:
return inp
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/35850?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: Ic22d00d3ae73ad81167276d9482b7b86a04476ba
Gerrit-Change-Number: 35850
Gerrit-PatchSet: 1
Gerrit-Owner: laforge <laforge(a)osmocom.org>
Gerrit-MessageType: newchange
laforge has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/35851?usp=email )
Change subject: pylint: construct.py
......................................................................
pylint: construct.py
pySim/construct.py:47:0: W0311: Bad indentation. Found 16 spaces, expected 12 (bad-indentation)
pySim/construct.py:59:0: W0311: Bad indentation. Found 16 spaces, expected 12 (bad-indentation)
pySim/construct.py:82:0: W0311: Bad indentation. Found 16 spaces, expected 12 (bad-indentation)
pySim/construct.py:1:0: C0114: Missing module docstring (missing-module-docstring)
pySim/construct.py:14:0: W0105: String statement has no effect (pointless-string-statement)
pySim/construct.py:178:29: W0613: Unused argument 'instr' (unused-argument)
pySim/construct.py:199:15: C0121: Comparison 'codepoint_prefix == None' should be 'codepoint_prefix is None' (singleton-comparison)
pySim/construct.py:269:15: C0121: Comparison 'v == False' should be 'v is False' if checking for the singleton value False, or 'not v' if testing for falsiness (singleton-comparison)
pySim/construct.py:271:17: C0121: Comparison 'v == True' should be 'v is True' if checking for the singleton value True, or 'v' if testing for truthiness (singleton-comparison)
pySim/construct.py:385:15: C0123: Use isinstance() rather than type() for a typecheck. (unidiomatic-typecheck)
pySim/construct.py:392:15: C0123: Use isinstance() rather than type() for a typecheck. (unidiomatic-typecheck)
pySim/construct.py:408:11: C0123: Use isinstance() rather than type() for a typecheck. (unidiomatic-typecheck)
pySim/construct.py:421:7: R1701: Consider merging these isinstance calls to isinstance(c, (Container, dict)) (consider-merging-isinstance)
pySim/construct.py:444:11: R1729: Use a generator instead 'all(v == 255 for v in raw_bin_data)' (use-a-generator)
pySim/construct.py:434:81: W0613: Unused argument 'exclude_prefix' (unused-argument)
pySim/construct.py:544:12: W0707: Consider explicitly re-raising using 'raise IntegerError(str(e), path=path) from e' (raise-missing-from)
pySim/construct.py:561:8: R1731: Consider using 'nbytes = max(nbytes, minlen)' instead of unnecessary if block (consider-using-max-builtin)
pySim/construct.py:573:12: W0707: Consider explicitly re-raising using 'raise IntegerError(str(e), path=path) from e' (raise-missing-from)
pySim/construct.py:3:0: C0411: standard import "import typing" should be placed before "from construct.lib.containers import Container, ListContainer" (wrong-import-order)
pySim/construct.py:10:0: C0411: third party import "import gsm0338" should be placed before "from pySim.utils import b2h, h2b, swap_nibbles" (wrong-import-order)
pySim/construct.py:11:0: C0411: standard import "import codecs" should be placed before "from construct.lib.containers import Container, ListContainer" (wrong-import-order)
pySim/construct.py:12:0: C0411: standard import "import ipaddress" should be placed before "from construct.lib.containers import Container, ListContainer" (wrong-import-order)
pySim/construct.py:7:0: W0611: Unused BitwisableString imported from construct.core (unused-import)
Change-Id: Ic8a06d65a7bcff9ef399fe4e7e5d82f271c946bb
---
M pySim/construct.py
1 file changed, 63 insertions(+), 28 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/51/35851/1
diff --git a/pySim/construct.py b/pySim/construct.py
index 8ef7941..881f1f2 100644
--- a/pySim/construct.py
+++ b/pySim/construct.py
@@ -1,17 +1,20 @@
-from construct.lib.containers import Container, ListContainer
-from construct.core import EnumIntegerString
+"""Utility code related to the integration of the 'construct' declarative parser."""
+
import typing
-from construct import Adapter, Prefixed, Int8ub, GreedyBytes, Default, Flag, Byte, Construct, Enum
-from construct import BitsInteger, BitStruct, Bytes, StreamError, stream_read_entire, stream_write
-from construct import SizeofError, IntegerError, swapbytes
-from construct.core import evaluate, BitwisableString
-from construct.lib import integertypes
-from pySim.utils import b2h, h2b, swap_nibbles
-import gsm0338
import codecs
import ipaddress
-"""Utility code related to the integration of the 'construct' declarative parser."""
+import gsm0338
+
+from construct.lib.containers import Container, ListContainer
+from construct.core import EnumIntegerString
+from construct import Adapter, Prefixed, Int8ub, GreedyBytes, Default, Flag, Byte, Construct, Enum
+from construct import BitsInteger, BitStruct, Bytes, StreamError, stream_read_entire, stream_write
+from construct import SizeofError, IntegerError, swapbytes
+from construct.core import evaluate
+from construct.lib import integertypes
+
+from pySim.utils import b2h, h2b, swap_nibbles
# (C) 2021-2022 by Harald Welte <laforge(a)osmocom.org>
#
@@ -44,7 +47,7 @@
def _decode(self, obj, context, path):
# In case the string contains only 0xff bytes we interpret it as an empty string
if obj == b'\xff' * len(obj):
- return ""
+ return ""
return codecs.decode(obj, "utf-8")
def _encode(self, obj, context, path):
@@ -56,7 +59,7 @@
def _decode(self, obj, context, path):
# In case the string contains only 0xff bytes we interpret it as an empty string
if obj == b'\xff' * len(obj):
- return ""
+ return ""
# one of the magic bytes of TS 102 221 Annex A
if obj[0] in [0x80, 0x81, 0x82]:
ad = Ucs2Adapter(GreedyBytes)
@@ -79,7 +82,7 @@
def _decode(self, obj, context, path):
# In case the string contains only 0xff bytes we interpret it as an empty string
if obj == b'\xff' * len(obj):
- return ""
+ return ""
if obj[0] == 0x80:
# TS 102 221 Annex A Variant 1
return codecs.decode(obj[1:], 'utf_16_be')
@@ -177,7 +180,7 @@
def _encode_variant1(instr: str) -> bytes:
"""Encode according to TS 102 221 Annex A Variant 1"""
- return b'\x80' + codecs.encode(obj, 'utf_16_be')
+ return b'\x80' + codecs.encode(instr, 'utf_16_be')
def _encode_variant2(instr: str) -> bytes:
"""Encode according to TS 102 221 Annex A Variant 2"""
@@ -196,7 +199,7 @@
assert codepoint_prefix == c_prefix
enc = (0x80 + (c_codepoint & 0x7f)).to_bytes(1, byteorder='big')
chars += enc
- if codepoint_prefix == None:
+ if codepoint_prefix is None:
codepoint_prefix = 0
return hdr + codepoint_prefix.to_bytes(1, byteorder='big') + chars
@@ -266,9 +269,9 @@
# skip all private entries
if k.startswith('_'):
continue
- if v == False:
+ if v is False:
obj[k] = True
- elif v == True:
+ elif v is True:
obj[k] = False
return obj
@@ -382,14 +385,14 @@
self.min_len = min_len
def _decode(self, obj, context, path):
- assert type(obj) == bytes
+ assert isinstance(obj, bytes)
# pad with suppressed/missing bytes
if len(obj) < self.total_length:
obj += self.default_value * (self.total_length - len(obj))
return int.from_bytes(obj, 'big')
def _encode(self, obj, context, path):
- assert type(obj) == int
+ assert isinstance(obj, int)
obj = obj.to_bytes(self.total_length, 'big')
# remove trailing bytes if they are zero
while len(obj) > self.min_len and obj[-1] == self.default_value[0]:
@@ -405,20 +408,20 @@
for (key, value) in d.items():
if key.startswith(exclude_prefix):
continue
- if type(value) is dict:
+ if isinstance(value, dict):
res[key] = filter_dict(value)
else:
res[key] = value
return res
-def normalize_construct(c):
+def normalize_construct(c, exclude_prefix: str = '_'):
"""Convert a construct specific type to a related base type, mostly useful
so we can serialize it."""
# we need to include the filter_dict as we otherwise get elements like this
# in the dict: '_io': <_io.BytesIO object at 0x7fdb64e05860> which we cannot json-serialize
- c = filter_dict(c)
- if isinstance(c, Container) or isinstance(c, dict):
+ c = filter_dict(c, exclude_prefix)
+ if isinstance(c, (Container, dict)):
r = {k: normalize_construct(v) for (k, v) in c.items()}
elif isinstance(c, ListContainer):
r = [normalize_construct(x) for x in c]
@@ -441,11 +444,11 @@
# if the input is all-ff, this means the content is undefined. Let's avoid passing StreamError
# exceptions in those situations (which might occur if a length field 0xff is 255 but then there's
# actually less bytes in the remainder of the file.
- if all([v == 0xff for v in raw_bin_data]):
+ if all(v == 0xff for v in raw_bin_data):
return None
else:
raise e
- return normalize_construct(parsed)
+ return normalize_construct(parsed, exclude_prefix)
def build_construct(c, decoded_data, context: dict = {}):
"""Helper function to handle total_len."""
@@ -558,8 +561,7 @@
# round up to the minimum number
# of bytes we anticipate
- if nbytes < minlen:
- nbytes = minlen
+ nbytes = max(nbytes, minlen)
return nbytes
@@ -570,7 +572,7 @@
try:
data = obj.to_bytes(length, byteorder='big', signed=self.signed)
except ValueError as e:
- raise IntegerError(str(e), path=path)
+ raise IntegerError(str(e), path=path) from e
if evaluate(self.swapped, context):
data = swapbytes(data)
stream_write(stream, data, length, path)
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/35851?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: Ic8a06d65a7bcff9ef399fe4e7e5d82f271c946bb
Gerrit-Change-Number: 35851
Gerrit-PatchSet: 1
Gerrit-Owner: laforge <laforge(a)osmocom.org>
Gerrit-MessageType: newchange
laforge has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/35824?usp=email )
Change subject: pylint: transport/__init__.py
......................................................................
pylint: transport/__init__.py
pySim/transport/__init__.py:139:0: C0325: Unnecessary parens after 'if' keyword (superfluous-parens)
Change-Id: Ibeeb7d6fde40bb37774bbd09ad185203ac7bcb48
---
M pySim/transport/__init__.py
1 file changed, 12 insertions(+), 1 deletion(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/24/35824/1
diff --git a/pySim/transport/__init__.py b/pySim/transport/__init__.py
index dcecfdd..dd06af8 100644
--- a/pySim/transport/__init__.py
+++ b/pySim/transport/__init__.py
@@ -136,7 +136,7 @@
# available. There are two SWs commonly used for this 9fxx (sim) and 61xx (usim), where
# xx is the number of response bytes available.
# See also:
- if (sw is not None):
+ if sw is not None:
while ((sw[0:2] == '9f') or (sw[0:2] == '61')):
# SW1=9F: 3GPP TS 51.011 9.4.1, Responses to commands which are correctly executed
# SW1=61: ISO/IEC 7816-4, Table 5 — General meaning of the interindustry values of SW1-SW2
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/35824?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: Ibeeb7d6fde40bb37774bbd09ad185203ac7bcb48
Gerrit-Change-Number: 35824
Gerrit-PatchSet: 1
Gerrit-Owner: laforge <laforge(a)osmocom.org>
Gerrit-MessageType: newchange