From 6e9d17d842f4ac27442168717050dbd378f71236 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damian=20Michalak-Szmaci=C5=84ski?= Date: Tue, 21 Feb 2023 14:59:00 +0100 Subject: [PATCH] Add flake8 and Fix exception in python files --- .flake8 | 5 ++ .github/workflows/lint.yml | 7 +++ .../rpc_console/py/chip_rpc/console.py | 4 +- .../nxp/k32w/k32w0/scripts/detokenizer.py | 6 +- scripts/codepregen.py | 4 +- scripts/helpers/bloat_check.py | 2 +- .../matter_idl/generators/java/__init__.py | 4 +- .../matter_idl/generators/types.py | 4 +- .../matter_idl/lint/lint_rules_parser.py | 8 +-- .../matter_idl/matter_idl_parser.py | 10 ++-- .../matter_idl/test_matter_idl_parser.py | 2 +- .../matter_idl/test_xml_parser.py | 2 +- .../matter_yamltests/fixes.py | 2 +- .../matter_yamltests/yaml_loader.py | 2 +- scripts/run-clang-tidy-on-compile-commands.py | 2 +- scripts/setup/nrfconnect/update_ncs.py | 2 +- .../yamltest_with_chip_repl_tester.py | 2 +- scripts/tests/java/base.py | 2 +- scripts/tests/run_python_test.py | 2 +- .../generate_nrfconnect_chip_factory_data.py | 4 +- scripts/tools/silabs/FactoryDataProvider.py | 2 +- scripts/tools/zap/generate.py | 2 +- scripts/tools/zap/test_generate.py | 2 +- scripts/tools/zap/zap_download.py | 2 +- src/controller/python/chip-device-ctrl.py | 8 +-- .../python/chip/CertificateAuthority.py | 2 +- src/controller/python/chip/ChipBleUtility.py | 2 +- src/controller/python/chip/ChipBluezMgr.py | 60 +++++++++---------- .../python/chip/ChipCoreBluetoothMgr.py | 4 +- src/controller/python/chip/ChipDeviceCtrl.py | 9 ++- .../python/chip/clusters/Attribute.py | 10 ++-- .../python/chip/clusters/Command.py | 2 +- .../python/chip/discovery/__init__.py | 2 +- src/controller/python/chip/tlv/__init__.py | 2 +- .../python/chip/yaml/format_converter.py | 2 +- src/controller/python/chip/yaml/runner.py | 7 +-- .../python/test/test_scripts/base.py | 6 +- .../test/test_scripts/cluster_objects.py | 2 +- .../test_scripts/network_commissioning.py | 15 ++--- .../efr32/py/nl_test_runner/nl_test_runner.py | 2 +- src/test_driver/esp32/run_qemu_image.py | 2 +- .../linux-cirque/helper/CHIPTestBase.py | 4 +- .../integration-tests/common/fixtures.py | 2 +- .../integration-tests/shell/test_app.py | 2 +- 44 files changed, 120 insertions(+), 109 deletions(-) diff --git a/.flake8 b/.flake8 index 28e6208b8c07ee..c1b4f9aff110e5 100644 --- a/.flake8 +++ b/.flake8 @@ -1,2 +1,7 @@ [flake8] max-line-length = 132 +exclude = third_party + .* + out/* + scripts/idl/* + ./examples/common/QRCode/* diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 57faedd89bb710..0c8992e6a26276 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -213,3 +213,10 @@ jobs: if: always() run: | git grep -n 'emberAfWriteAttribute' -- './*' ':(exclude).github/workflows/lint.yml' ':(exclude)src/app/util/af.h' ':(exclude)zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.cpp' ':(exclude)src/app/zap-templates/templates/app/attributes/Accessors-src.zapt' ':(exclude)src/app/util/attribute-table.cpp' ':(exclude)examples/common/pigweed/rpc_services/Attributes.h' ':(exclude)src/app/util/attribute-table.h' ':(exclude)src/app/util/ember-compatibility-functions.cpp' && exit 1 || exit 0 + + # Run python Linter (flake8) and verify python files + - name: Check for errors using flake8 Python linter + if: always() + ## This large number of arguments is temporary until the patch changes reported by the linter are fully merged (all fixes in PR#25193) + run: | + flake8 --extend-ignore=E501,W391,W291,F401,F405,F403,E711,E712,F841,E265,F541,E251,E303,F821,F402,E721,E122,W191,E122,W605,E101,E202,E201,E741,F811,E302,F523,E713 diff --git a/examples/common/pigweed/rpc_console/py/chip_rpc/console.py b/examples/common/pigweed/rpc_console/py/chip_rpc/console.py index 7df7214808f47c..474f286fff968a 100644 --- a/examples/common/pigweed/rpc_console/py/chip_rpc/console.py +++ b/examples/common/pigweed/rpc_console/py/chip_rpc/console.py @@ -304,11 +304,11 @@ def write_to_output(data: bytes, def _read_raw_serial(read: Callable[[], bytes], output): """Continuously read and pass to output.""" - with ThreadPoolExecutor() as executor: + with ThreadPoolExecutor(): while True: try: data = read() - except Exception as exc: # pylint: disable=broad-except + except Exception: # pylint: disable=broad-except continue if data: output(data) diff --git a/examples/platform/nxp/k32w/k32w0/scripts/detokenizer.py b/examples/platform/nxp/k32w/k32w0/scripts/detokenizer.py index 4ad1436a71fc8b..a4035d0655baa1 100644 --- a/examples/platform/nxp/k32w/k32w0/scripts/detokenizer.py +++ b/examples/platform/nxp/k32w/k32w0/scripts/detokenizer.py @@ -53,7 +53,7 @@ def decode_string(tstr, detok): if s.find('$') == 0: return None return s - except: + except ValueError: return None @@ -88,7 +88,7 @@ def decode_serial(serialport, outfile, database): print(line, file=sys.stdout) if output: print(line, file=output) - except: + except Exception: print("Serial error or program closed", file=sys.stderr) if output: @@ -120,7 +120,7 @@ def decode_file(infile, outfile, database): # ascii decode line # serial terminals may include non ascii characters line = line.decode('ascii').strip() - except: + except Exception: continue # find token start and detokenize idx = line.rfind(']') diff --git a/scripts/codepregen.py b/scripts/codepregen.py index 7c5bfd747295cd..543a9e0fe675a4 100755 --- a/scripts/codepregen.py +++ b/scripts/codepregen.py @@ -25,7 +25,7 @@ try: from pregenerate import FindPregenerationTargets, TargetFilter -except: +except ImportError: import os sys.path.append(os.path.abspath(os.path.dirname(__file__))) from pregenerate import FindPregenerationTargets, TargetFilter @@ -36,7 +36,7 @@ try: import coloredlogs _has_coloredlogs = True -except: +except ImportError: _has_coloredlogs = False # Supported log levels, mapping string values required for argument diff --git a/scripts/helpers/bloat_check.py b/scripts/helpers/bloat_check.py index 798df246b78554..72ad3705df2785 100755 --- a/scripts/helpers/bloat_check.py +++ b/scripts/helpers/bloat_check.py @@ -357,7 +357,7 @@ def main(): # Output processed. a.delete() - except Exception as e: + except Exception: tb = traceback.format_exc() logging.warning('Failed to process bloat report: %s', tb) diff --git a/scripts/py_matter_idl/matter_idl/generators/java/__init__.py b/scripts/py_matter_idl/matter_idl/generators/java/__init__.py index 3ea1a670492449..047a5d6cdeb156 100644 --- a/scripts/py_matter_idl/matter_idl/generators/java/__init__.py +++ b/scripts/py_matter_idl/matter_idl/generators/java/__init__.py @@ -240,7 +240,7 @@ def boxed_java_type(self): elif t == FundamentalType.DOUBLE: return "Double" else: - raise Error("Unknown fundamental type") + raise Exception("Unknown fundamental type") elif type(t) == BasicInteger: if t.byte_count >= 4: return "Long" @@ -277,7 +277,7 @@ def boxed_java_signature(self): elif t == FundamentalType.DOUBLE: return "Ljava/lang/Double;" else: - raise Error("Unknown fundamental type") + raise Exception("Unknown fundamental type") elif type(t) == BasicInteger: if t.byte_count >= 4: return "Ljava/lang/Long;" diff --git a/scripts/py_matter_idl/matter_idl/generators/types.py b/scripts/py_matter_idl/matter_idl/generators/types.py index 5d1930808e3b48..7dca586351a07f 100644 --- a/scripts/py_matter_idl/matter_idl/generators/types.py +++ b/scripts/py_matter_idl/matter_idl/generators/types.py @@ -80,7 +80,7 @@ def idl_name(self): elif self == FundamentalType.DOUBLE: return "double" else: - raise Error("Type not handled: %r" % self) + raise Exception("Type not handled: %r" % self) @property def byte_count(self): @@ -91,7 +91,7 @@ def byte_count(self): elif self == FundamentalType.DOUBLE: return 8 else: - raise Error("Type not handled: %r" % self) + raise Exception("Type not handled: %r" % self) @property def bits(self): diff --git a/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py b/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py index c03a0aa6806168..fd58a6d4a34b80 100755 --- a/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py +++ b/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py @@ -14,7 +14,7 @@ try: from .types import (AttributeRequirement, ClusterCommandRequirement, ClusterRequirement, RequiredAttributesRule, RequiredCommandsRule) -except: +except ImportError: import sys sys.path.append(os.path.join(os.path.abspath( @@ -102,7 +102,7 @@ def DecodeClusterFromXml(element: xml.etree.ElementTree.Element): required_attributes=required_attributes, required_commands=required_commands ) - except Exception as e: + except Exception: logging.exception("Failed to decode cluster %r" % element) return None @@ -204,7 +204,7 @@ def positive_integer(self, tokens): """Numbers in the grammar are integers or hex numbers. """ if len(tokens) != 1: - raise Error("Unexpected argument counts") + raise Exception("Unexpected argument counts") return parseNumberString(tokens[0].value) @@ -220,7 +220,7 @@ def id(self, tokens): """An id is a string containing an identifier """ if len(tokens) != 1: - raise Error("Unexpected argument counts") + raise Exception("Unexpected argument counts") return tokens[0].value def ESCAPED_STRING(self, s): diff --git a/scripts/py_matter_idl/matter_idl/matter_idl_parser.py b/scripts/py_matter_idl/matter_idl/matter_idl_parser.py index 4a3c0b47f33c96..357278dce6e3bd 100755 --- a/scripts/py_matter_idl/matter_idl/matter_idl_parser.py +++ b/scripts/py_matter_idl/matter_idl/matter_idl_parser.py @@ -9,7 +9,7 @@ try: from .matter_idl_types import * -except: +except ImportError: import os import sys sys.path.append(os.path.abspath(os.path.dirname(__file__))) @@ -91,7 +91,7 @@ def positive_integer(self, tokens): """Numbers in the grammar are integers or hex numbers. """ if len(tokens) != 1: - raise Error("Unexpected argument counts") + raise Exception("Unexpected argument counts") n = tokens[0].value if n.startswith('0x'): @@ -117,14 +117,14 @@ def id(self, tokens): """An id is a string containing an identifier """ if len(tokens) != 1: - raise Error("Unexpected argument counts") + raise Exception("Unexpected argument counts") return tokens[0].value def type(self, tokens): """A type is just a string for the type """ if len(tokens) != 1: - raise Error("Unexpected argument counts") + raise Exception("Unexpected argument counts") return tokens[0].value def data_type(self, tokens): @@ -134,7 +134,7 @@ def data_type(self, tokens): elif len(tokens) == 2: return DataType(name=tokens[0], max_length=tokens[1]) else: - raise Error("Unexpected size for data type") + raise Exception("Unexpected size for data type") @v_args(inline=True) def constant_entry(self, id, number): diff --git a/scripts/py_matter_idl/matter_idl/test_matter_idl_parser.py b/scripts/py_matter_idl/matter_idl/test_matter_idl_parser.py index be7bd82e0ee9c9..33da6a76196136 100755 --- a/scripts/py_matter_idl/matter_idl/test_matter_idl_parser.py +++ b/scripts/py_matter_idl/matter_idl/test_matter_idl_parser.py @@ -17,7 +17,7 @@ try: from .matter_idl_parser import CreateParser from .matter_idl_types import * -except: +except ImportError: import os import sys sys.path.append(os.path.abspath(os.path.dirname(__file__))) diff --git a/scripts/py_matter_idl/matter_idl/test_xml_parser.py b/scripts/py_matter_idl/matter_idl/test_xml_parser.py index 5d8d53201b2723..9380d5786bb014 100755 --- a/scripts/py_matter_idl/matter_idl/test_xml_parser.py +++ b/scripts/py_matter_idl/matter_idl/test_xml_parser.py @@ -20,7 +20,7 @@ try: from matter_idl.matter_idl_types import * from matter_idl.zapxml import ParseSource, ParseXmls -except: +except ImportError: import os import sys diff --git a/scripts/py_matter_yamltests/matter_yamltests/fixes.py b/scripts/py_matter_yamltests/matter_yamltests/fixes.py index 0223c2e1a486f1..72d588e56aa6ec 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/fixes.py +++ b/scripts/py_matter_yamltests/matter_yamltests/fixes.py @@ -60,7 +60,7 @@ def try_apply_yaml_unrepresentable_integer_for_javascript_fixes(value): if type(value) is str: try: value = int(value) - except: + except ValueError: pass return value diff --git a/scripts/py_matter_yamltests/matter_yamltests/yaml_loader.py b/scripts/py_matter_yamltests/matter_yamltests/yaml_loader.py index 543de252dc3820..e686efa50f7f97 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/yaml_loader.py +++ b/scripts/py_matter_yamltests/matter_yamltests/yaml_loader.py @@ -22,7 +22,7 @@ try: from yaml import CSafeLoader as SafeLoader -except: +except ImportError: from yaml import SafeLoader import yaml diff --git a/scripts/run-clang-tidy-on-compile-commands.py b/scripts/run-clang-tidy-on-compile-commands.py index 90ca9ed6cf9fac..c5eb22e979dbde 100755 --- a/scripts/run-clang-tidy-on-compile-commands.py +++ b/scripts/run-clang-tidy-on-compile-commands.py @@ -168,7 +168,7 @@ def Check(self): "Tidy %s ended with code %d", self.file, proc.returncode ) return TidyResult(self.full_path, False) - except: + except subprocess.SubprocessError: traceback.print_exc() return TidyResult(self.full_path, False) diff --git a/scripts/setup/nrfconnect/update_ncs.py b/scripts/setup/nrfconnect/update_ncs.py index b774b8690e3946..e9c62a6b0683e0 100755 --- a/scripts/setup/nrfconnect/update_ncs.py +++ b/scripts/setup/nrfconnect/update_ncs.py @@ -52,7 +52,7 @@ def get_ncs_recommended_revision(): try: with open(os.path.join(chip_root, 'config/nrfconnect/.nrfconnect-recommended-revision'), 'r') as f: return f.readline().strip() - except: + except OSError: raise RuntimeError( "Encountered problem when trying to read .nrfconnect-recommended-revision file.") diff --git a/scripts/tests/chiptest/yamltest_with_chip_repl_tester.py b/scripts/tests/chiptest/yamltest_with_chip_repl_tester.py index 625b4d95b149fa..d35ed8cbd8ca04 100644 --- a/scripts/tests/chiptest/yamltest_with_chip_repl_tester.py +++ b/scripts/tests/chiptest/yamltest_with_chip_repl_tester.py @@ -30,7 +30,7 @@ # ensure matter IDL is availale for import, otherwise set relative paths try: from matter_idl import matter_idl_types -except: +except ImportError: SCRIPT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')) import sys diff --git a/scripts/tests/java/base.py b/scripts/tests/java/base.py index ce0e04bbccceb7..7ab366582e031c 100755 --- a/scripts/tests/java/base.py +++ b/scripts/tests/java/base.py @@ -39,7 +39,7 @@ def EnqueueLogOutput(fp, tag, q): try: timestamp = float(line[1:18].decode()) line = line[19:] - except Exception as ex: + except Exception: pass sys.stdout.buffer.write( (f"[{datetime.datetime.fromtimestamp(timestamp).isoformat(sep=' ')}]").encode() + tag + line) diff --git a/scripts/tests/run_python_test.py b/scripts/tests/run_python_test.py index 4318ee1221da35..05285e1a39e8ce 100755 --- a/scripts/tests/run_python_test.py +++ b/scripts/tests/run_python_test.py @@ -44,7 +44,7 @@ def EnqueueLogOutput(fp, tag, q): try: timestamp = float(line[1:18].decode()) line = line[19:] - except Exception as ex: + except Exception: pass sys.stdout.buffer.write( (f"[{datetime.datetime.fromtimestamp(timestamp).isoformat(sep=' ')}]").encode() + tag + line) diff --git a/scripts/tools/nrfconnect/generate_nrfconnect_chip_factory_data.py b/scripts/tools/nrfconnect/generate_nrfconnect_chip_factory_data.py index 4eafc7b68f7cc8..2d831399419f23 100644 --- a/scripts/tools/nrfconnect/generate_nrfconnect_chip_factory_data.py +++ b/scripts/tools/nrfconnect/generate_nrfconnect_chip_factory_data.py @@ -338,7 +338,7 @@ def generate_json(self): try: if is_json_valid: json_file.write(json_object) - except IOError as e: + except IOError: log.error("Cannot save output file into directory: {}".format(self._args.output)) def _add_entry(self, name: str, value: any): @@ -372,7 +372,7 @@ def _validate_output_json(self, output_json: str): schema = json.loads(schema_file.read()) validator = jsonschema.Draft202012Validator(schema=schema) validator.validate(instance=json.loads(output_json)) - except IOError as e: + except IOError: log.error("Provided JSON schema file is wrong: {}".format(self._args.schema)) return False else: diff --git a/scripts/tools/silabs/FactoryDataProvider.py b/scripts/tools/silabs/FactoryDataProvider.py index 5d3ef39752d9d8..8aea39d4ff8175 100644 --- a/scripts/tools/silabs/FactoryDataProvider.py +++ b/scripts/tools/silabs/FactoryDataProvider.py @@ -212,7 +212,7 @@ def create_nvm3injected_image(self): inputImage = self.BASE_MG24_FILE else: raise Exception('Invalid MCU') - except: + except Exception: isDeviceConnected = False print("Device not connected") # When no device is connected user needs to provide the mcu family for which those credentials are to be created diff --git a/scripts/tools/zap/generate.py b/scripts/tools/zap/generate.py index a4d36a7cbc730e..fd5d0ca8ade34f 100755 --- a/scripts/tools/zap/generate.py +++ b/scripts/tools/zap/generate.py @@ -187,7 +187,7 @@ def extractGeneratedIdl(output_dir, zap_config_path): if not target_path.endswith(".matter"): # We expect "something.zap" and don't handle corner cases of # multiple extensions. This is to work with existing codebase only - raise Error("Unexpected input zap file %s" % self.zap_config) + raise Exception("Unexpected input zap file %s" % zap_config_path) shutil.move(idl_path, target_path) diff --git a/scripts/tools/zap/test_generate.py b/scripts/tools/zap/test_generate.py index f6ea2ab3d5abfb..065f24854ef169 100755 --- a/scripts/tools/zap/test_generate.py +++ b/scripts/tools/zap/test_generate.py @@ -116,7 +116,7 @@ def run_test_cases(self, checker: unittest.TestCase): try: subprocess.check_call(["diff", actual, expected]) - except: + except subprocess.CalledProcessError: if self.context.regenerate_golden: print( f"Copying updated golden image from {actual} to {expected}") diff --git a/scripts/tools/zap/zap_download.py b/scripts/tools/zap/zap_download.py index 951691d65fbd19..cc14730f12ea7b 100755 --- a/scripts/tools/zap/zap_download.py +++ b/scripts/tools/zap/zap_download.py @@ -32,7 +32,7 @@ try: import coloredlogs _has_coloredlogs = True -except: +except Exception: _has_coloredlogs = False # Supported log levels, mapping string values required for argument diff --git a/src/controller/python/chip-device-ctrl.py b/src/controller/python/chip-device-ctrl.py index e9022910e80667..4ad1b78134f050 100755 --- a/src/controller/python/chip-device-ctrl.py +++ b/src/controller/python/chip-device-ctrl.py @@ -661,7 +661,7 @@ def do_closesession(self, line): self.devCtrl.CloseSession(args.nodeid) except exceptions.ChipStackException as ex: print(str(ex)) - except: + except Exception: self.do_help("close-session") def do_resolve(self, line): @@ -782,7 +782,7 @@ def do_discover(self, line): print('exception') print(str(ex)) return - except: + except Exception: self.do_help("discover") return @@ -1021,7 +1021,7 @@ def do_opencommissioningwindow(self, line): except exceptions.ChipStackException as ex: print(str(ex)) return - except: + except Exception: self.do_help("open-commissioning-window") return @@ -1146,7 +1146,7 @@ def main(): else: try: adapterId = int(options.bluetoothAdapter[3:]) - except: + except ValueError: print( "Invalid bluetooth adapter: {}, adapter name looks like hci0, hci1 etc.") sys.exit(-1) diff --git a/src/controller/python/chip/CertificateAuthority.py b/src/controller/python/chip/CertificateAuthority.py index 084c028ee060a9..e11fe349b1d885 100644 --- a/src/controller/python/chip/CertificateAuthority.py +++ b/src/controller/python/chip/CertificateAuthority.py @@ -124,7 +124,7 @@ def NewFabricAdmin(self, vendorId: int, fabricId: int): f"CertificateAuthority object was previously shutdown and is no longer valid!") if (vendorId is None or fabricId is None): - raise ValueError(f"Invalid values for fabricId and vendorId") + raise ValueError("Invalid values for fabricId and vendorId") for existingAdmin in self._activeAdmins: if (existingAdmin.fabricId == fabricId): diff --git a/src/controller/python/chip/ChipBleUtility.py b/src/controller/python/chip/ChipBleUtility.py index 6d09dd1ae2b470..66bd0ecff33bdd 100644 --- a/src/controller/python/chip/ChipBleUtility.py +++ b/src/controller/python/chip/ChipBleUtility.py @@ -62,7 +62,7 @@ def VoidPtrToUUIDString(ptr, len): + ptr[20:] ) ptr = str(ptr) - except Exception as ex: + except Exception: print("ERROR: failed to convert void * to UUID") ptr = None diff --git a/src/controller/python/chip/ChipBluezMgr.py b/src/controller/python/chip/ChipBluezMgr.py index 33926b47b0e006..d26c2bf35a0cea 100644 --- a/src/controller/python/chip/ChipBluezMgr.py +++ b/src/controller/python/chip/ChipBluezMgr.py @@ -42,7 +42,7 @@ try: from gi.repository import GObject -except Exception as ex: +except Exception: logging.exception("Unable to find GObject from gi.repository") from pgi.repository import GObject @@ -180,7 +180,7 @@ def adapter_bg_scan(self, enable): except dbus.exceptions.DBusException as ex: self.adapter_event.clear() self.logger.debug(str(ex)) - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) @property @@ -191,7 +191,7 @@ def Address(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -202,7 +202,7 @@ def UUIDs(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -211,7 +211,7 @@ def SetDiscoveryFilter(self, dict): self.adapter.SetDiscoveryFilter(dict) except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) @property @@ -223,7 +223,7 @@ def Discovering(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -236,7 +236,7 @@ def DiscoverableTimeout(self, timeoutSec): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -248,7 +248,7 @@ def Powered(self, enable): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -285,7 +285,7 @@ def clear_adapter(self): if device.Connected: device.device_bg_connect(False) self.adapter.RemoveDevice(device.device.object_path) - except Exception as ex: + except Exception: pass @@ -393,7 +393,7 @@ def device_bg_connect(self, enable): except dbus.exceptions.DBusException as ex: self.device_event.clear() self.logger.info(str(ex)) - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) def service_discover(self, gatt_dic): @@ -420,7 +420,7 @@ def service_discover(self, gatt_dic): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -439,7 +439,7 @@ def uuids(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -450,7 +450,7 @@ def Address(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -462,7 +462,7 @@ def Name(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -474,7 +474,7 @@ def Connected(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -485,7 +485,7 @@ def TxPower(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -497,7 +497,7 @@ def RSSI(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -508,7 +508,7 @@ def Adapter(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -519,7 +519,7 @@ def ServiceData(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -532,7 +532,7 @@ def ServicesResolved(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -569,7 +569,7 @@ def uuid(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -582,7 +582,7 @@ def Primary(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -594,7 +594,7 @@ def Device(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -619,7 +619,7 @@ def find_characteristic(self, uuid): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -707,7 +707,7 @@ def WriteValue(self, value, options, reply_handler, error_handler, timeout): ) except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) @property @@ -723,7 +723,7 @@ def uuid(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -740,7 +740,7 @@ def StartNotify(self, cbfunct, reply_handler, error_handler, timeout): ) except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) def StopNotify(self, reply_handler, error_handler, timeout): @@ -755,7 +755,7 @@ def StopNotify(self, reply_handler, error_handler, timeout): self.received = None except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) @property @@ -768,7 +768,7 @@ def Notifying(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -889,7 +889,7 @@ def running_thread(self, target, kwargs): while not self.Gmainloop or not self.Gmainloop.is_running(): time.sleep(0.00001) target(**kwargs) - except Exception as err: + except Exception: traceback.print_exc() finally: self.Gmainloop.quit() diff --git a/src/controller/python/chip/ChipCoreBluetoothMgr.py b/src/controller/python/chip/ChipCoreBluetoothMgr.py index 5b744671394615..0ad911afc98d36 100644 --- a/src/controller/python/chip/ChipCoreBluetoothMgr.py +++ b/src/controller/python/chip/ChipCoreBluetoothMgr.py @@ -47,7 +47,7 @@ u"/System/Library/Frameworks/IOBluetooth.framework/Versions/A/Frameworks/CoreBluetooth.framework" ), ) -except Exception as ex: +except Exception: objc.loadBundle( "CoreBluetooth", globals(), @@ -86,7 +86,7 @@ def _VoidPtrToCBUUID(ptr, len): + ptr[20:] ) ptr = CBUUID.UUIDWithString_(ptr) - except Exception as ex: + except Exception: print("ERROR: failed to convert void * to CBUUID") ptr = None diff --git a/src/controller/python/chip/ChipDeviceCtrl.py b/src/controller/python/chip/ChipDeviceCtrl.py index 96e86adb090177..3b261ba2c42e82 100644 --- a/src/controller/python/chip/ChipDeviceCtrl.py +++ b/src/controller/python/chip/ChipDeviceCtrl.py @@ -1201,7 +1201,7 @@ def ZCLSend(self, cluster, command, nodeid, endpoint, groupid, args, blocking=Fa try: req = eval( f"GeneratedObjects.{cluster}.Commands.{command}")(**args) - except: + except SyntaxError: raise UnknownCommand(cluster, command) try: res = asyncio.run(self.SendCommand(nodeid, endpoint, req)) @@ -1213,13 +1213,12 @@ def ZCLSend(self, cluster, command, nodeid, endpoint, groupid, args, blocking=Fa def ZCLReadAttribute(self, cluster, attribute, nodeid, endpoint, groupid, blocking=True): self.CheckIsActive() - req = None clusterType = eval(f"GeneratedObjects.{cluster}") try: attributeType = eval( f"GeneratedObjects.{cluster}.Attributes.{attribute}") - except: + except SyntaxError: raise UnknownAttribute(cluster, attribute) result = asyncio.run(self.ReadAttribute( @@ -1233,7 +1232,7 @@ def ZCLWriteAttribute(self, cluster: str, attribute: str, nodeid, endpoint, grou try: req = eval( f"GeneratedObjects.{cluster}.Attributes.{attribute}")(value) - except: + except SyntaxError: raise UnknownAttribute(cluster, attribute) return asyncio.run(self.WriteAttribute(nodeid, [(endpoint, req, dataVersion)])) @@ -1244,7 +1243,7 @@ def ZCLSubscribeAttribute(self, cluster, attribute, nodeid, endpoint, minInterva req = None try: req = eval(f"GeneratedObjects.{cluster}.Attributes.{attribute}") - except: + except SyntaxError: raise UnknownAttribute(cluster, attribute) return asyncio.run(self.ReadAttribute(nodeid, [(endpoint, req)], None, False, reportInterval=(minInterval, maxInterval))) diff --git a/src/controller/python/chip/clusters/Attribute.py b/src/controller/python/chip/clusters/Attribute.py index 6a72469b4cf43e..29d84db9a0695a 100644 --- a/src/controller/python/chip/clusters/Attribute.py +++ b/src/controller/python/chip/clusters/Attribute.py @@ -653,7 +653,7 @@ def handleAttributeData(self, path: AttributePathWithListIndex, dataVersion: int imStatus = status try: imStatus = chip.interaction_model.Status(status) - except: + except chip.exceptions.ChipStackException: pass if (imStatus != chip.interaction_model.Status.Success): @@ -797,7 +797,7 @@ def handleResponse(self, path: AttributePath, status: int): try: imStatus = chip.interaction_model.Status(status) self._resultData.append(AttributeWriteResult(Path=path, Status=imStatus)) - except: + except chip.exceptions.ChipStackException: self._resultData.append(AttributeWriteResult(Path=path, Status=status)) def handleError(self, chipError: PyChipError): @@ -991,17 +991,17 @@ def Read(future: Future, eventLoop, device, devCtrl, attributes: List[AttributeP filter.EndpointId = f.EndpointId else: raise ValueError( - f"DataVersionFilter must provide EndpointId.") + "DataVersionFilter must provide EndpointId.") if f.ClusterId is not None: filter.ClusterId = f.ClusterId else: raise ValueError( - f"DataVersionFilter must provide ClusterId.") + "DataVersionFilter must provide ClusterId.") if f.DataVersion is not None: filter.DataVersion = f.DataVersion else: raise ValueError( - f"DataVersionFilter must provide DataVersion.") + "DataVersionFilter must provide DataVersion.") filter = chip.interaction_model.DataVersionFilterIBstruct.build( filter) readargs.append(ctypes.c_char_p(filter)) diff --git a/src/controller/python/chip/clusters/Command.py b/src/controller/python/chip/clusters/Command.py index 056688f5b572e3..0f4f970ba6ecf0 100644 --- a/src/controller/python/chip/clusters/Command.py +++ b/src/controller/python/chip/clusters/Command.py @@ -106,7 +106,7 @@ def _handleError(self, imError: Status, chipError: PyChipError, exception: Excep try: self._future.set_exception( chip.interaction_model.InteractionModelError(chip.interaction_model.Status(imError.IMStatus))) - except Exception as e2: + except Exception: logger.exception("Failed to map interaction model status received: %s. Remapping to Failure." % imError) self._future.set_exception(chip.interaction_model.InteractionModelError( chip.interaction_model.Status.Failure)) diff --git a/src/controller/python/chip/discovery/__init__.py b/src/controller/python/chip/discovery/__init__.py index e6a03466090c1c..bfc79577b75169 100644 --- a/src/controller/python/chip/discovery/__init__.py +++ b/src/controller/python/chip/discovery/__init__.py @@ -142,7 +142,7 @@ def ResolutionThread(self): if self.NeedsCallback(item): try: item.callback(item.result) - except: + except Exception: logging.exception("Node discovery callback failed") else: updatedDiscoveries.append(item) diff --git a/src/controller/python/chip/tlv/__init__.py b/src/controller/python/chip/tlv/__init__.py index 6b22fbb8536299..4b3bd10fd16634 100644 --- a/src/controller/python/chip/tlv/__init__.py +++ b/src/controller/python/chip/tlv/__init__.py @@ -649,7 +649,7 @@ def _decodeVal(self, tlv, decoding): ) try: decoding["value"] = str(val, "utf-8") - except Exception as ex: + except Exception: decoding["value"] = val self._bytesRead += decoding["strDataLen"] elif "Byte String" in decoding["type"]: diff --git a/src/controller/python/chip/yaml/format_converter.py b/src/controller/python/chip/yaml/format_converter.py index 551e1e398ef85b..a2fa5ac3f85bd4 100644 --- a/src/controller/python/chip/yaml/format_converter.py +++ b/src/controller/python/chip/yaml/format_converter.py @@ -178,7 +178,7 @@ def convert_to_data_model_type(field_value, field_type): field_descriptor = next( x for x in field_descriptors.Fields if x.Label.lower() == item.lower()) - except StopIteration as exc: + except StopIteration: raise ValidationError( f'Did not find field "{item}" in {str(field_type)}') from None diff --git a/src/controller/python/chip/yaml/runner.py b/src/controller/python/chip/yaml/runner.py index b3559a1e431956..1e47755c6dfd45 100644 --- a/src/controller/python/chip/yaml/runner.py +++ b/src/controller/python/chip/yaml/runner.py @@ -551,7 +551,7 @@ def __init__(self, test_step, cluster: str, context: _ExecutionContext): args = test_step.arguments['values'] if len(args) != 1: - raise UnexpectedParsingError(f'WriteAttribute is trying to write multiple values') + raise UnexpectedParsingError('WriteAttribute is trying to write multiple values') request_data_as_dict = args[0] try: # TODO this is an ugly hack @@ -600,12 +600,11 @@ def __init__(self, test_step, context: _ExecutionContext): elif test_step.event is not None: queue_name = stringcase.pascalcase(test_step.event) else: - raise UnexpectedParsingError( - f'WaitForReport needs to wait on either attribute or event, neither were provided') + raise UnexpectedParsingError('WaitForReport needs to wait on either attribute or event, neither were provided') self._output_queue = context.subscription_callback_result_queue.get(queue_name, None) if self._output_queue is None: - raise UnexpectedParsingError(f'Could not find output queue') + raise UnexpectedParsingError('Could not find output queue') def run_action(self, dev_ctrl: ChipDeviceController) -> _ActionResult: try: diff --git a/src/controller/python/test/test_scripts/base.py b/src/controller/python/test/test_scripts/base.py index 3188e310848ae7..56d86926424602 100644 --- a/src/controller/python/test/test_scripts/base.py +++ b/src/controller/python/test/test_scripts/base.py @@ -360,7 +360,7 @@ def TestFailsafe(self, nodeid: int): self.logger.error( 'Incorrectly succeeded in opening basic commissioning window') return False - except Exception as ex: + except Exception: pass # TODO: pipe through the commissioning window opener so we can test enhanced properly. The pake verifier is just garbage because none of of the functions to calculate @@ -379,7 +379,7 @@ def TestFailsafe(self, nodeid: int): self.logger.error( 'Incorrectly succeeded in opening enhanced commissioning window') return False - except Exception as ex: + except Exception: pass self.logger.info("Disarming failsafe on CASE connection") @@ -395,7 +395,7 @@ def TestFailsafe(self, nodeid: int): try: res = asyncio.run(self.devCtrl.SendCommand( nodeid, 0, Clusters.AdministratorCommissioning.Commands.OpenBasicCommissioningWindow(180), timedRequestTimeoutMs=10000)) - except Exception as ex: + except Exception: self.logger.error( 'Failed to open commissioning window after disarming failsafe') return False diff --git a/src/controller/python/test/test_scripts/cluster_objects.py b/src/controller/python/test/test_scripts/cluster_objects.py index 59b55a6a13bf86..f4c4031ceef010 100644 --- a/src/controller/python/test/test_scripts/cluster_objects.py +++ b/src/controller/python/test/test_scripts/cluster_objects.py @@ -104,7 +104,7 @@ async def TestCommandRoundTripWithBadEndpoint(cls, devCtrl): req = Clusters.OnOff.Commands.On() try: await devCtrl.SendCommand(nodeid=NODE_ID, endpoint=233, payload=req) - raise ValueError(f"Failure expected") + raise ValueError("Failure expected") except chip.interaction_model.InteractionModelError as ex: logger.info(f"Recevied {ex} from server.") return diff --git a/src/controller/python/test/test_scripts/network_commissioning.py b/src/controller/python/test/test_scripts/network_commissioning.py index 64c5510c4e9624..79e4806dd1e5fa 100644 --- a/src/controller/python/test/test_scripts/network_commissioning.py +++ b/src/controller/python/test/test_scripts/network_commissioning.py @@ -136,7 +136,7 @@ async def test_wifi(self, endpointId): res = await self.readLastNetworkingStateAttributes(endpointId=endpointId) if (res.lastNetworkID != NullValue) or (res.lastNetworkingStatus != NullValue) or (res.lastConnectErrorValue != NullValue): raise AssertionError( - f"LastNetworkID, LastNetworkingStatus and LastConnectErrorValue should be Null") + "LastNetworkID, LastNetworkingStatus and LastConnectErrorValue should be Null") # Scan networks logger.info(f"Scan networks") @@ -227,14 +227,15 @@ async def test_wifi(self, endpointId): f"Unexpected result: first network ID should be 'TestSSID' got {networkList[0].networkID}") if not networkList[0].connected: raise AssertionError( - f"Unexpected result: network is not marked as connected") + "Unexpected result: network is not marked as connected") # Verify Last* attributes logger.info(f"Read Last* attributes") res = await self.readLastNetworkingStateAttributes(endpointId=endpointId) if (res.lastNetworkID == NullValue) or (res.lastNetworkingStatus == NullValue) or (res.lastConnectErrorValue != NullValue): raise AssertionError( - f"LastNetworkID, LastNetworkingStatus should not be Null, LastConnectErrorValue should be Null for a successful network provision.") + "LastNetworkID, LastNetworkingStatus should not be Null, " + "LastConnectErrorValue should be Null for a successful network provision.") async def test_thread(self, endpointId): logger.info(f"Get basic information of the endpoint") @@ -257,13 +258,13 @@ async def test_thread(self, endpointId): Clusters.NetworkCommissioning.Commands.RemoveNetwork.command_id, Clusters.NetworkCommissioning.Commands.ConnectNetwork.command_id, Clusters.NetworkCommissioning.Commands.ReorderNetwork.command_id]: - raise AssertionError(f"Unexpected accepted command list for Thread interface") + raise AssertionError("Unexpected accepted command list for Thread interface") if res[endpointId][Clusters.NetworkCommissioning].generatedCommandList != [ Clusters.NetworkCommissioning.Commands.ScanNetworksResponse.command_id, Clusters.NetworkCommissioning.Commands.NetworkConfigResponse.command_id, Clusters.NetworkCommissioning.Commands.ConnectNetworkResponse.command_id]: - raise AssertionError(f"Unexpected generated command list for Thread interface") + raise AssertionError("Unexpected generated command list for Thread interface") logger.info(f"Finished getting basic information of the endpoint") @@ -272,7 +273,7 @@ async def test_thread(self, endpointId): res = await self.readLastNetworkingStateAttributes(endpointId=endpointId) if (res.lastNetworkID != NullValue) or (res.lastNetworkingStatus != NullValue) or (res.lastConnectErrorValue != NullValue): raise AssertionError( - f"LastNetworkID, LastNetworkingStatus and LastConnectErrorValue should be Null") + "LastNetworkID, LastNetworkingStatus and LastConnectErrorValue should be Null") # Scan networks logger.info(f"Scan networks") @@ -398,5 +399,5 @@ async def run(self): try: await self.Test() return True - except Exception as ex: + except Exception: return False diff --git a/src/test_driver/efr32/py/nl_test_runner/nl_test_runner.py b/src/test_driver/efr32/py/nl_test_runner/nl_test_runner.py index 01c124bb6bf2d9..b4f096afed100d 100644 --- a/src/test_driver/efr32/py/nl_test_runner/nl_test_runner.py +++ b/src/test_driver/efr32/py/nl_test_runner/nl_test_runner.py @@ -90,7 +90,7 @@ def read(): return serial_device.read(8192) def runner(client) -> int: """ Run the tests""" def on_error_callback(call_object, error): - raise Exception("Error running test RPC: {}".format(status)) + raise Exception("Error running test RPC: {}".format(error)) rpc = client.client.channel(1).rpcs.chip.rpc.NlTest.Run invoke = rpc.invoke(rpc.request(), on_error=on_error_callback) diff --git a/src/test_driver/esp32/run_qemu_image.py b/src/test_driver/esp32/run_qemu_image.py index 6d684c95ce7df1..c0a8086e2cfc26 100755 --- a/src/test_driver/esp32/run_qemu_image.py +++ b/src/test_driver/esp32/run_qemu_image.py @@ -147,7 +147,7 @@ def main(log_level, no_log_timestamps, image, file_image_list, qemu, verbose): print("========== TEST OUTPUT END ============") logging.info("Image %s PASSED", path) - except: + except Exception: # make sure output is visible in stdout print("========== TEST OUTPUT BEGIN ============") print(output) diff --git a/src/test_driver/linux-cirque/helper/CHIPTestBase.py b/src/test_driver/linux-cirque/helper/CHIPTestBase.py index 957c9187aa465f..9c669a976bd481 100644 --- a/src/test_driver/linux-cirque/helper/CHIPTestBase.py +++ b/src/test_driver/linux-cirque/helper/CHIPTestBase.py @@ -74,12 +74,12 @@ def run_test(self, save_logs=True): if save_logs: try: self.save_device_logs() - except: + except Exception: test_ret = TestResult.SYSTEM_FAILURE traceback.print_exc(file=sys.stderr) try: self.destroy_home() - except: + except requests.exceptions.RequestException: test_ret = TestResult.SYSTEM_FAILURE traceback.print_exc(file=sys.stderr) return test_ret diff --git a/src/test_driver/openiotsdk/integration-tests/common/fixtures.py b/src/test_driver/openiotsdk/integration-tests/common/fixtures.py index 510512ed0c1f01..3e67c80a4ddf99 100644 --- a/src/test_driver/openiotsdk/integration-tests/common/fixtures.py +++ b/src/test_driver/openiotsdk/integration-tests/common/fixtures.py @@ -113,7 +113,7 @@ def controller(vendor_id, fabric_id, node_id): except exceptions.ChipStackException as ex: log.error("Controller initialization failed {}".format(ex)) return None - except: + except Exception: log.error("Controller initialization failed") return None diff --git a/src/test_driver/openiotsdk/integration-tests/shell/test_app.py b/src/test_driver/openiotsdk/integration-tests/shell/test_app.py index 192257bceb0c3d..aa05daefba82a6 100644 --- a/src/test_driver/openiotsdk/integration-tests/shell/test_app.py +++ b/src/test_driver/openiotsdk/integration-tests/shell/test_app.py @@ -84,7 +84,7 @@ def test_command_check(device): except exceptions.ChipStackException as ex: log.error("CHIP initialization failed {}".format(ex)) assert False - except: + except Exception: log.error("CHIP initialization failed") assert False