commit 9ce7ca3a62c6890ca556f664a5876177fb945d8e parent 54c38b7e364be47910470b1455c90a8954528bd8 Author: Alex Hochheiden <ahochheiden@mozilla.com> Date: Wed, 10 Dec 2025 06:03:22 +0000 Bug 2003412 - Fix PLR1714 warnings: Use in operator for repeated equality comparisons r=emilio,mozperftest-reviewers,geckoview-reviewers,taskgraph-reviewers,android-reviewers,layout-reviewers,jdescottes,bhearsum,tcampbell,sparky https://docs.astral.sh/ruff/rules/repeated-equality-comparison/ Differential Revision: https://phabricator.services.mozilla.com/D274689 Diffstat:
53 files changed, 119 insertions(+), 150 deletions(-)
diff --git a/config/make-system-wrappers.py b/config/make-system-wrappers.py @@ -20,7 +20,7 @@ def gen_wrappers(unused, outdir, *header_list): for header in header_list: with FileAvoidWrite(os.path.join(outdir, header)) as f: includes = include_next_template.format(header=header) - if header == "wayland-util.h" or header == "pipewire/pipewire.h": + if header in {"wayland-util.h", "pipewire/pipewire.h"}: # wayland-util.h in Wayland < 1.12 and pipewire.h > 1.4 include # math.h inside an extern "C" block, which breaks including the # header from C++. This was fixed in Wayland 1.12, but for versions diff --git a/dom/bindings/parser/tests/test_distinguishability.py b/dom/bindings/parser/tests/test_distinguishability.py @@ -224,8 +224,7 @@ def WebIDLTest(parser, harness): return [ a for a in list1 - if a not in list2 - and (a != "any" and a != "Promise<any>" and a != "Promise<any>?") + if a not in list2 and a not in {"any", "Promise<any>", "Promise<any>?"} ] unionsWithCallback = ["(long or Callback)"] diff --git a/dom/websocket/tests/file_websocket_wsh.py b/dom/websocket/tests/file_websocket_wsh.py @@ -20,7 +20,7 @@ def web_socket_do_extra_handshake(request): time.sleep(3) elif request.ws_protocol == "test-19": raise ValueError("Aborting (test-19)") - elif request.ws_protocol == "test-20" or request.ws_protocol == "test-17": + elif request.ws_protocol in {"test-20", "test-17"}: time.sleep(3) elif request.ws_protocol == "test-22": # The timeout is 5 seconds @@ -49,10 +49,10 @@ def web_socket_passive_closing_handshake(request): def web_socket_transfer_data(request): - if request.ws_protocol == "test-1" or request.ws_protocol == "test-4": + if request.ws_protocol in {"test-1", "test-4"}: msgutil.send_message(request, "server data") msgutil.close_connection(request) - elif request.ws_protocol == "test-2.1" or request.ws_protocol == "test-2.2": + elif request.ws_protocol in {"test-2.1", "test-2.2"}: msgutil.close_connection(request) elif request.ws_protocol == "test-6": resp = "wrong message" @@ -109,7 +109,7 @@ def web_socket_transfer_data(request): raise RuntimeError("test-15 should be disabled for now") # msgutil.close_connection(request, True) # OBSOLETE 2nd arg # return - elif request.ws_protocol == "test-17" or request.ws_protocol == "test-21": + elif request.ws_protocol in {"test-17", "test-21"}: time.sleep(2) resp = "wrong message" if msgutil.receive_message(request) == "client data": diff --git a/js/src/builtin/intl/make_intl_data.py b/js/src/builtin/intl/make_intl_data.py @@ -1067,12 +1067,10 @@ def readSupplementalData(core_file): # subtags are present. A single variant subtags may be present # in |type|. And |i_type| definitely has a single variant subtag. # Should this ever change, update this code accordingly. - assert type == (Any, None, None, None) or type == ( - Any, - None, - None, - Any, - ) + assert type in { + (Any, None, None, None), + (Any, None, None, Any), + } assert replacement == (Any, None, None, None) assert i_type == (Any, None, None, Any) assert i_replacement == (Any, None, None, None) @@ -1157,12 +1155,10 @@ def readSupplementalData(core_file): if modified_rules and loop_count > 1: new_rules = {k for k in transitive_rules.keys() if k not in rules} for k in new_rules: - assert k == (Any, None, None, "guoyu-hakka") or k == ( - Any, - None, - None, - "guoyu-xiang", - ) + assert k in { + (Any, None, None, "guoyu-hakka"), + (Any, None, None, "guoyu-xiang"), + } # Merge the transitive rules. rules.update(transitive_rules) @@ -1446,9 +1442,7 @@ def readUnicodeExtensions(core_file): tree = ET.parse(file) for keyword in tree.iterfind(".//keyword/key"): extension = keyword.get("extension", "u") - assert ( - extension == "u" or extension == "t" - ), f"unknown extension type: {extension}" + assert extension in {"u", "t"}, f"unknown extension type: {extension}" extension_name = keyword.get("name") @@ -3496,7 +3490,7 @@ def readICUUnitResourceFile(filepath): for unit_display in ("units", "unitsNarrow", "unitsShort") if unit_display in unit_table for (unit_type, unit_names) in unit_table[unit_display].items() - if unit_type != "compound" and unit_type != "coordinate" + if unit_type not in {"compound", "coordinate"} for unit_name in unit_names.keys() } diff --git a/js/src/gdb/mozilla/unwind.py b/js/src/gdb/mozilla/unwind.py @@ -174,10 +174,10 @@ class JitFrameDecorator(FrameDecorator): calleetoken = calleetoken ^ tag function = None script = None - if ( - tag == self.cache.CalleeToken_Function - or tag == self.cache.CalleeToken_FunctionConstructing - ): + if tag in { + self.cache.CalleeToken_Function, + self.cache.CalleeToken_FunctionConstructing, + }: value = gdb.Value(calleetoken) function = get_function_name(value, self.cache) script = get_function_script(value, self.cache) diff --git a/js/src/tests/lib/jittests.py b/js/src/tests/lib/jittests.py @@ -508,7 +508,7 @@ def check_output(out, err, rc, timed_out, test, options): # When running jittests on Android, SEGV results in a return code of # 128 + 11 = 139. Due to a bug in tinybox, we have to check for 138 as # well. - if rc == 139 or rc == 138: + if rc in {139, 138}: return OutputStatus.OK # Crashing test should always crash as expected, otherwise this is an diff --git a/js/src/tests/lib/manifest.py b/js/src/tests/lib/manifest.py @@ -288,12 +288,10 @@ def _build_manifest_script_entry(script_name, test): term for term in test.terms.split() if not ( - term == "module" - or term == "async" + term in {"module", "async", "test262-raw"} or term.startswith("error:") or term.startswith("ignore-flag(") or term.startswith("shell-option(") - or term == "test262-raw" ) ] ) diff --git a/js/src/tests/test262-export.py b/js/src/tests/test262-export.py @@ -676,7 +676,7 @@ def exportTest262( for fileName in fileNames: # Skip browser.js files - if fileName == "browser.js" or fileName == "shell.js": + if fileName in {"browser.js", "shell.js"}: continue if fileName.endswith("~"): diff --git a/js/src/tests/test262-update.py b/js/src/tests/test262-update.py @@ -785,12 +785,7 @@ def fetch_pr_files(inDir, outDir, prNumber, strictTests): assert pageUrl.startswith("https://api.github.com/") # Ensure the relative URL marker has the expected format. - assert ( - rel == 'rel="prev"' - or rel == 'rel="next"' - or rel == 'rel="first"' - or rel == 'rel="last"' - ) + assert rel in {'rel="prev"', 'rel="next"', 'rel="first"', 'rel="last"'} # We only need the URL for the next page. if rel == 'rel="next"': diff --git a/js/src/vm/jsopcode.py b/js/src/vm/jsopcode.py @@ -341,13 +341,13 @@ def get_opcodes(dir): stack_nuses = get_stack_count(opcode.stack_uses) stack_ndefs = get_stack_count(opcode.stack_defs) - if nuses != -1 and stack_nuses != -1 and nuses != stack_nuses: + if (nuses != -1 and stack_nuses != -1) and nuses != stack_nuses: raise Exception( f"nuses should match stack notation: {op}: " f"{nuses} != {stack_nuses} " "(stack_nuses)" ) - if ndefs != -1 and stack_ndefs != -1 and ndefs != stack_ndefs: + if (ndefs != -1 and stack_ndefs != -1) and ndefs != stack_ndefs: raise Exception( f"ndefs should match stack notation: {op}: " f"{ndefs} != {stack_ndefs} " diff --git a/js/src/wasm/GenerateBuiltinModules.py b/js/src/wasm/GenerateBuiltinModules.py @@ -49,15 +49,11 @@ def cppBool(v): def specTypeToMIRType(specType): - if specType == "i32" or specType == "i64" or specType == "f32" or specType == "f64": + if isinstance(specType, dict): + return "MIRType::WasmAnyRef" + if specType in {"i32", "i64", "f32", "f64"}: return f"ValType::{specType}().toMIRType()" - if ( - specType == "externref" - or specType == "anyref" - or specType == "funcref" - or specType == "exnref" - or isinstance(specType, dict) - ): + if specType in {"externref", "anyref", "funcref", "exnref"}: return "MIRType::WasmAnyRef" raise ValueError() @@ -79,7 +75,16 @@ def specHeapTypeToTypeCode(specHeapType): def specTypeToValType(specType): - if specType == "i32" or specType == "i64" or specType == "f32" or specType == "f64": + if isinstance(specType, dict): + nullable = cppBool(specType["nullable"]) + if "type" in specType: + ref = specType["type"] + return f"ValType(RefType::fromTypeDef({ref}, {nullable}))" + else: + code = specType["code"] + return f"ValType(RefType::fromTypeCode(TypeCode(RefType::{specHeapTypeToTypeCode(code)}), {nullable}))" + + if specType in {"i32", "i64", "f32", "f64"}: return f"ValType::{specType}()" if specType == "externref": @@ -94,15 +99,6 @@ def specTypeToValType(specType): if specType == "funcref": return "ValType(RefType::func())" - if isinstance(specType, dict): - nullable = cppBool(specType["nullable"]) - if "type" in specType: - ref = specType["type"] - return f"ValType(RefType::fromTypeDef({ref}, {nullable}))" - else: - code = specType["code"] - return f"ValType(RefType::fromTypeCode(TypeCode(RefType::{specHeapTypeToTypeCode(code)}), {nullable}))" - raise ValueError() diff --git a/layout/tools/reftest/reftest/__init__.py b/layout/tools/reftest/reftest/__init__.py @@ -201,11 +201,11 @@ class ReftestManifest: self.load(os.path.join(mdir, items[j + 1]), skip_if) break - if item == "load" or item == "script": + if item in {"load", "script"}: add_test(items[j + 1], annotations, None, parent_skip_if) break - if item == "==" or item == "!=" or item == "print": + if item in {"==", "!=", "print"}: add_test(items[j + 1], annotations, None, parent_skip_if) add_test(items[j + 2], annotations, items[j + 1], parent_skip_if) break diff --git a/mobile/android/fenix/tools/data_renewal_generate.py b/mobile/android/fenix/tools/data_renewal_generate.py @@ -41,7 +41,7 @@ def response(last_key, content, expire_version, writer, renewal): global write_header global total_count for key, value in content.items(): - if (key == "$schema") or (key == "no_lint"): + if key in {"$schema", "no_lint"}: continue if key == "disabled": continue diff --git a/mobile/android/focus-android/tools/data_renewal_generate.py b/mobile/android/focus-android/tools/data_renewal_generate.py @@ -43,7 +43,7 @@ def response(last_key, content, expire_version, writer, renewal): global write_header global total_count for key, value in content.items(): - if (key == "$schema") or (key == "no_lint"): + if key in {"$schema", "no_lint"}: continue if key == "disabled": continue diff --git a/mobile/android/gradle/plugins/apilint/apilint/src/main/resources/apilint.py b/mobile/android/gradle/plugins/apilint/apilint/src/main/resources/apilint.py @@ -765,7 +765,7 @@ def verify_actions(clazz): continue if f.name.startswith("EXTRA_"): continue - if f.name == "SERVICE_INTERFACE" or f.name == "PROVIDER_INTERFACE": + if f.name in {"SERVICE_INTERFACE", "PROVIDER_INTERFACE"}: continue if "INTERACTION" in f.name: continue @@ -789,10 +789,10 @@ def verify_actions(clazz): prefix = "android.intent.action" elif clazz.fullname == "android.provider.Settings": prefix = "android.settings" - elif ( - clazz.fullname == "android.app.admin.DevicePolicyManager" - or clazz.fullname == "android.app.admin.DeviceAdminReceiver" - ): + elif clazz.fullname in { + "android.app.admin.DevicePolicyManager", + "android.app.admin.DeviceAdminReceiver", + }: prefix = "android.app.action" else: prefix = clazz.pkg.name + ".action" @@ -1769,12 +1769,12 @@ def verify_files(clazz): for a in m.args: if "java.io.File" == a.typ: has_file.add(m) - if ( - "java.io.FileDescriptor" == a.typ - or "android.os.ParcelFileDescriptor" == a.typ - or "java.io.InputStream" == a.typ - or "java.io.OutputStream" == a.typ - ): + if a.typ in { + "java.io.FileDescriptor", + "android.os.ParcelFileDescriptor", + "java.io.InputStream", + "java.io.OutputStream", + }: has_stream.add(m.name) for m in has_file: @@ -2300,10 +2300,10 @@ def verify_deprecated_annotations(clazz): def is_deprecated(subject): for a in subject.annotations: - if ( - a.typ.name == DEPRECATED_ANNOTATION - or a.typ.name == DEPRECATION_SCHEDULE_ANNOTATION - ): + if a.typ.name in { + DEPRECATED_ANNOTATION, + DEPRECATION_SCHEDULE_ANNOTATION, + }: return True return False diff --git a/modules/libpref/init/generate_static_pref_list.py b/modules/libpref/init/generate_static_pref_list.py @@ -184,7 +184,7 @@ def check_pref_list(pref_list): if "value" not in pref: error(f"missing `value` key for pref `{name}`") value = pref["value"] - if typ == "String" or typ == "DataMutexString": + if typ in {"String", "DataMutexString"}: if type(value) is not str: error( f"non-string `value` value `{value}` for `{typ}` pref `{name}`; " diff --git a/python/gdbpp/gdbpp/thashtable.py b/python/gdbpp/gdbpp/thashtable.py @@ -90,7 +90,7 @@ class thashtable_printer: if f.is_base_class: continue # ...just to skip the fields we know exist... - if f.name == "mKeyHash" or f.name == "mData": + if f.name in {"mKeyHash", "mData"}: continue # ...and assume the first one we find is the key. self.key_field_name = f.name diff --git a/python/mozboot/mozboot/osx.py b/python/mozboot/mozboot/osx.py @@ -38,7 +38,7 @@ NO_BREW_INSTALLED = "It seems you don't have Homebrew installed." class OSXAndroidBootstrapper: def install_mobile_android_packages(self, mozconfig_builder, artifact_mode=False): os_arch = platform.machine() - if os_arch != "x86_64" and os_arch != "arm64": + if os_arch not in {"x86_64", "arm64"}: raise Exception( "You need a 64-bit version of Mac OS X to build " "GeckoView/Firefox for Android." @@ -46,7 +46,7 @@ class OSXAndroidBootstrapper: from mozboot import android - if os_arch == "x86_64" or os_arch == "x86": + if os_arch in {"x86_64", "x86"}: avd_manifest_path = android.AVD_MANIFEST_X86_64 else: avd_manifest_path = android.AVD_MANIFEST_ARM64 @@ -65,7 +65,7 @@ class OSXAndroidBootstrapper: arch = platform.machine() android.ensure_java("macosx", arch) - if arch == "x86_64" or arch == "x86": + if arch in {"x86_64", "x86"}: self.install_toolchain_artifact(android.X86_64_ANDROID_AVD) elif arch == "arm64": self.install_toolchain_artifact(android.ARM64_ANDROID_AVD) diff --git a/python/mozbuild/mozbuild/backend/clangd.py b/python/mozbuild/mozbuild/backend/clangd.py @@ -16,7 +16,7 @@ from mozbuild.compilation.database import CompileDBBackend def find_vscode_or_vscodium_cmd(ide): - if ide != "vscode" and ide != "vscodium": + if ide not in {"vscode", "vscodium"}: return None import shutil diff --git a/python/mozbuild/mozbuild/backend/cpp_eclipse.py b/python/mozbuild/mozbuild/backend/cpp_eclipse.py @@ -339,7 +339,7 @@ class CppEclipseBackend(CommonBackend): for i in args["includes"]: dirsettings += add_abs_include_path(i) for d in args["defines"]: - assert d[:2] == "-D" or d[:2] == "-U" + assert d[:2] in {"-D", "-U"} if d[:2] == "-U": # gfx/harfbuzz/src uses -UDEBUG, at least on Mac # netwerk/sctp/src uses -U__APPLE__ on Mac diff --git a/python/mozbuild/mozbuild/backend/mach_commands.py b/python/mozbuild/mozbuild/backend/mach_commands.py @@ -78,7 +78,7 @@ def run(command_context, ide, no_interactive, args): backend = "CppEclipse" elif ide == "visualstudio": backend = "VisualStudio" - elif ide == "vscode" or ide == "vscodium": + elif ide in {"vscode", "vscodium"}: if not command_context.config_environment.is_artifact_build: backend = "Clangd" @@ -97,7 +97,7 @@ def run(command_context, ide, no_interactive, args): elif ide == "visualstudio": visual_studio_workspace_dir = get_visualstudio_workspace_path(command_context) subprocess.call(["explorer.exe", visual_studio_workspace_dir]) - elif ide == "vscode" or ide == "vscodium": + elif ide in {"vscode", "vscodium"}: return setup_vscode_or_vscodium(ide, command_context, interactive) diff --git a/python/mozbuild/mozbuild/backend/recursivemake.py b/python/mozbuild/mozbuild/backend/recursivemake.py @@ -1513,7 +1513,7 @@ class RecursiveMakeBackend(MakeBackend): backend_file.write_once("%s: %s\n" % (obj_target, obj.symbols_file)) for lib in shared_libs: - assert obj.KIND != "host" and obj.KIND != "wasm" + assert obj.KIND not in {"host", "wasm"} backend_file.write_once( "SHARED_LIBS += %s\n" % self._pretty_path(lib.import_path, backend_file) ) diff --git a/python/mozbuild/mozbuild/doctor.py b/python/mozbuild/mozbuild/doctor.py @@ -398,10 +398,10 @@ def check_mount_lastaccess(mount: str) -> DoctorCheck: else: option = "noatime" desc = "%s has no explicit %s mount option" % (mount, option) - elif option == "atime" or option == "norelatime": + elif option in {"atime", "norelatime"}: status = CheckStatus.WARNING desc = "%s has %s mount option" % (mount, option) - elif option == "noatime" or option == "relatime": + elif option in {"noatime", "relatime"}: status = CheckStatus.OK desc = "%s has %s mount option" % (mount, option) diff --git a/python/mozbuild/mozbuild/frontend/emitter.py b/python/mozbuild/mozbuild/frontend/emitter.py @@ -1421,10 +1421,7 @@ class TreeMetadataEmitter(LoggingMixin): "(resolved to %s)" % (local_include, full_path), context, ) - if ( - full_path == context.config.topsrcdir - or full_path == context.config.topobjdir - ): + if full_path in {context.config.topsrcdir, context.config.topobjdir}: raise SandboxValidationError( "Path specified in LOCAL_INCLUDES " "(%s) resolves to the topsrcdir or topobjdir (%s), which is " diff --git a/python/mozbuild/mozbuild/mach_commands.py b/python/mozbuild/mozbuild/mach_commands.py @@ -682,7 +682,7 @@ def show_log(command_context, log_file=None): except OSError as os_error: # (POSIX) errno.EPIPE: BrokenPipeError: [Errno 32] Broken pipe # (Windows) errno.EINVAL: OSError: [Errno 22] Invalid argument - if os_error.errno == errno.EPIPE or os_error.errno == errno.EINVAL: + if os_error.errno in {errno.EPIPE, errno.EINVAL}: # If the user manually terminates 'less' before the entire log file # is piped (without scrolling close enough to the bottom) we will get # one of these errors (depends on the OS) because the logger will still diff --git a/python/mozbuild/mozbuild/repackaging/desktop_file.py b/python/mozbuild/mozbuild/repackaging/desktop_file.py @@ -164,7 +164,7 @@ def _get_en_US_brand_fluent_filename( ) if release_type == "nightly": return branding_fluent_filename_template.format(brand="nightly") - elif release_type == "release" or release_type == "release-rc": + elif release_type in {"release", "release-rc"}: return branding_fluent_filename_template.format(brand="official") elif release_type == "beta" and release_product == "firefox": return branding_fluent_filename_template.format(brand="official") diff --git a/python/mozbuild/mozbuild/vendor/host_angle.py b/python/mozbuild/mozbuild/vendor/host_angle.py @@ -20,7 +20,7 @@ class AngleHost(BaseHost): if version["channel"] == "beta": branch = "chromium/" + version["true_branch"] - if revision != "HEAD" and revision != branch: + if revision not in {"HEAD", branch}: raise Exception( "Passing a --revision for Angle that is not HEAD " + "or the true branch is not supported." diff --git a/python/mozperftest/mozperftest/test/alert.py b/python/mozperftest/mozperftest/test/alert.py @@ -85,7 +85,7 @@ class RaptorTestCommand: if "MOZ_FETCHES_DIR" in str(value): # Skip CI-specific options continue - if arg == "t" or arg == "test": + if arg in {"t", "test"}: # Don't add the test argument, it's added # by setup_test continue diff --git a/taskcluster/gecko_taskgraph/main.py b/taskcluster/gecko_taskgraph/main.py @@ -354,11 +354,9 @@ def show_taskgraph(options): # Reload taskgraph modules to pick up changes and clear global state. for mod in sys.modules.copy(): - if ( - mod != __name__ - and mod != "taskgraph.main" - and mod.split(".", 1)[0].endswith(("taskgraph", "mozbuild")) - ): + if mod not in {__name__, "taskgraph.main"} and mod.split(".", 1)[ + 0 + ].endswith(("taskgraph", "mozbuild")): del sys.modules[mod] # Ensure gecko_taskgraph is ahead of taskcluster_taskgraph in sys.path. diff --git a/taskcluster/gecko_taskgraph/transforms/artifact.py b/taskcluster/gecko_taskgraph/transforms/artifact.py @@ -70,12 +70,12 @@ def set_artifact_expiration(config, jobs): plat = platform.lower() if "plain" in plat or "ccov" in plat or "rusttest" in plat: art_dict = None - elif ( - plat == "toolchain-wasm32-wasi-compiler-rt-trunk" - or plat == "toolchain-linux64-x64-compiler-rt-trunk" - or plat == "toolchain-linux64-x86-compiler-rt-trunk" - or plat == "android-geckoview-docs" - ): + elif plat in { + "toolchain-wasm32-wasi-compiler-rt-trunk", + "toolchain-linux64-x64-compiler-rt-trunk", + "toolchain-linux64-x86-compiler-rt-trunk", + "android-geckoview-docs", + }: art_dict = None elif plat.startswith("win"): art_dict = manifest["win"] diff --git a/taskcluster/gecko_taskgraph/util/perfile.py b/taskcluster/gecko_taskgraph/util/perfile.py @@ -68,7 +68,7 @@ def perfile_number_of_chunks(is_try, try_task_config, files_changed, type): if mozpackmatch(path, pattern): gpu = False - if type == "test-verify-e10s" or type == "test-coverage-e10s": + if type in {"test-verify-e10s", "test-coverage-e10s"}: # file_patterns for test-verify will pick up some gpu tests, lets ignore # in the case of reftest, we will not have any in the regular case gpu_dirs = [ diff --git a/taskcluster/scripts/misc/fetch-cft-chromedriver.py b/taskcluster/scripts/misc/fetch-cft-chromedriver.py @@ -129,7 +129,7 @@ def fetch_chromedriver(download_url, cft_dir): cd_path = None for dirpath, _, filenames in os.walk(tmppath): for filename in filenames: - if filename == "chromedriver" or filename == "chromedriver.exe": + if filename in {"chromedriver", "chromedriver.exe"}: cd_path = os.path.join(dirpath, filename) break if cd_path is not None: diff --git a/taskcluster/scripts/misc/fetch-chromium.py b/taskcluster/scripts/misc/fetch-chromium.py @@ -134,7 +134,7 @@ def fetch_chromedriver(platform, revision, chromium_dir): cd_path = None for dirpath, _, filenames in os.walk(tmppath): for filename in filenames: - if filename == "chromedriver" or filename == "chromedriver.exe": + if filename in {"chromedriver", "chromedriver.exe"}: cd_path = os.path.join(dirpath, filename) break if cd_path is not None: diff --git a/testing/marionette/client/marionette_driver/marionette.py b/testing/marionette/client/marionette_driver/marionette.py @@ -2125,7 +2125,7 @@ class Marionette: data = self._send_message("WebDriver:TakeScreenshot", body, key="value") - if format == "base64" or format == "hash": + if format in {"base64", "hash"}: return data elif format == "binary": return base64.b64decode(data.encode("ascii")) diff --git a/testing/mozbase/mozdevice/mozdevice/adb.py b/testing/mozbase/mozdevice/mozdevice/adb.py @@ -1329,7 +1329,7 @@ class ADBDevice(ADBCommand): char = file_obj.read(1).decode() if not char: break - if char != "\r" and char != "\n": + if char not in {"\r", "\n"}: line = char + line elif line: # we have collected everything up to the beginning of the line diff --git a/testing/mozbase/mozinfo/mozinfo/mozinfo.py b/testing/mozbase/mozinfo/mozinfo/mozinfo.py @@ -65,7 +65,7 @@ if system in ["Microsoft", "Windows"]: # 2009 == 22H2 software update. These are the build numbers # we use 2009 as the "build" which maps to what taskcluster tasks see - if build_number in [22621, 19045]: + if build_number in {22621, 19045}: build_number = 2009 os_version = f"{major}.{build_number}" diff --git a/testing/mozbase/mozlog/mozlog/formatters/process.py b/testing/mozbase/mozlog/mozlog/formatters/process.py @@ -22,8 +22,7 @@ def strsig(n): if ( k.startswith("SIG") and not k.startswith("SIG_") - and k != "SIGCLD" - and k != "SIGPOLL" + and k not in {"SIGCLD", "SIGPOLL"} ): _SIG_NAME[getattr(signal, k)] = k diff --git a/testing/mozbase/mozlog/mozlog/formatters/unittest.py b/testing/mozbase/mozlog/mozlog/formatters/unittest.py @@ -32,7 +32,7 @@ class UnittestFormatter(base.BaseFormatter): status ] - if status == "FAIL" or status == "PRECONDITION_FAILED": + if status in {"FAIL", "PRECONDITION_FAILED"}: self.fails.append(data) elif status == "ERROR": self.errors.append(data) diff --git a/testing/mozbase/mozrunner/mozrunner/devices/android_device.py b/testing/mozbase/mozrunner/mozrunner/devices/android_device.py @@ -297,11 +297,11 @@ def metadata_for_app(app, aab=False): activity_name = None subcommand = None - if app == "org.mozilla.fenix.release" or app == "org.mozilla.firefox": + if app in {"org.mozilla.fenix.release", "org.mozilla.firefox"}: package_name = "org.mozilla.firefox" activity_name = "org.mozilla.firefox.App" subcommand = "installFenixRelease" - elif app == "org.mozilla.fenix.nightly" or app == "fenix.nightly": + elif app in {"org.mozilla.fenix.nightly", "fenix.nightly"}: # Likely only works for --no-install. package_name = "org.mozilla.fenix" activity_name = "org.mozilla.fenix.App" diff --git a/testing/mozharness/mozharness/base/script.py b/testing/mozharness/mozharness/base/script.py @@ -390,7 +390,7 @@ class ScriptMixin(PlatformMixin): for ffrec in win32api.FindFiles("\\\\?\\" + path + "\\*.*"): file_attr = ffrec[0] name = ffrec[8] - if name == "." or name == "..": + if name in {".", ".."}: continue full_name = os.path.join(path, name) @@ -1039,7 +1039,7 @@ class ScriptMixin(PlatformMixin): if overwrite == "clobber" or not os.path.exists(dest): self.rmtree(dest) shutil.copytree(src, dest) - elif overwrite == "no_overwrite" or overwrite == "overwrite_if_exists": + elif overwrite in {"no_overwrite", "overwrite_if_exists"}: files = os.listdir(src) for f in files: abs_src_f = os.path.join(src, f) diff --git a/testing/mozharness/mozharness/mozilla/testing/codecoverage.py b/testing/mozharness/mozharness/mozilla/testing/codecoverage.py @@ -72,7 +72,7 @@ class CodeCoverageMixin(SingleTestMixin): per_test_reports = {} def __init__(self, **kwargs): - if mozinfo.os == "linux" or mozinfo.os == "mac": + if mozinfo.os in {"linux", "mac"}: self.grcov_bin = "grcov" elif mozinfo.os == "win": self.grcov_bin = "grcov.exe" @@ -324,7 +324,7 @@ class CodeCoverageMixin(SingleTestMixin): if merge: grcov_command += [jsvm_output_file] - if mozinfo.os == "win" or mozinfo.os == "mac": + if mozinfo.os in {"win", "mac"}: grcov_command += ["--llvm"] if filter_covered: diff --git a/testing/web-platform/mozilla/tests/mathml/fonts/generate.py b/testing/web-platform/mozilla/tests/mathml/fonts/generate.py @@ -261,7 +261,7 @@ largeop = [0x2A1B, 0x2A1C] # integral with overbar/underbar # Draw boxes of size 1, 2, 7, 8, 9em. for i in [1, 2, 7, 8, 9]: s = em * i - if i == 1 or i == 2: + if i in {1, 2}: g = f.createChar(largeop[i - 1]) else: g = f.createChar(-1, "L%d" % i) diff --git a/toolkit/xre/test/marionette/test_win32k_enrollment.py b/toolkit/xre/test/marionette/test_win32k_enrollment.py @@ -101,9 +101,7 @@ class TestWin32kAutostart(MarionetteTestCase): self.marionette.set_pref(Prefs.ENROLLMENT_STATUS, status, default_branch=True) updated_status = self.marionette.get_pref(Prefs.ENROLLMENT_STATUS) - self.assertTrue( - status == updated_status or updated_status == ExperimentStatus.DISQUALIFIED - ) + self.assertTrue(updated_status in {status, ExperimentStatus.DISQUALIFIED}) startup_status = self.marionette.get_pref(Prefs.STARTUP_ENROLLMENT_STATUS) self.assertEqual( startup_status, diff --git a/toolkit/xre/test/marionette/test_win32k_enrollment.template.py b/toolkit/xre/test/marionette/test_win32k_enrollment.template.py @@ -101,9 +101,7 @@ class TestWin32kAutostart(MarionetteTestCase): self.marionette.set_pref(Prefs.ENROLLMENT_STATUS, status, default_branch=True) updated_status = self.marionette.get_pref(Prefs.ENROLLMENT_STATUS) - self.assertTrue( - status == updated_status or updated_status == ExperimentStatus.DISQUALIFIED - ) + self.assertTrue(updated_status in {status, ExperimentStatus.DISQUALIFIED}) startup_status = self.marionette.get_pref(Prefs.STARTUP_ENROLLMENT_STATUS) self.assertEqual( startup_status, diff --git a/tools/lint/clippy/__init__.py b/tools/lint/clippy/__init__.py @@ -25,9 +25,9 @@ def handle_clippy_msg(config, line, log, base_path, files, lint_results): p = detail["target"]["src_path"] detail = detail["message"] if "level" in detail: - if ( - detail["level"] == "error" or detail["level"] == "failure-note" - ) and not detail["code"]: + if (detail["level"] in {"error", "failure-note"}) and not detail[ + "code" + ]: log.debug( "Error outside of clippy." "This means that the build failed. Therefore, skipping this" diff --git a/tools/lint/fluent-lint/__init__.py b/tools/lint/fluent-lint/__init__.py @@ -127,12 +127,9 @@ class Linter(visitor.Visitor): self.state["node_can_be_resource_comment"] = self.state[ "node_can_be_resource_comment" ] and ( - # This is the root node. - node_name == "Resource" - # Empty space is allowed. - or node_name == "Span" - # Comments are allowed - or node_name == "Comment" + # This is the root node, empty space is allowed, comments are allowed + node_name + in {"Resource", "Span", "Comment"} ) if self.debug_print_json: diff --git a/tools/lint/perfdocs/gatherer.py b/tools/lint/perfdocs/gatherer.py @@ -94,7 +94,7 @@ class Gatherer: for file in files: # Add the yml/rst/static file to its key if re finds the searched file - if file == "config.yml" or file == "config.yaml": + if file in {"config.yml", "config.yaml"}: matched["yml"] = file elif file == "index.rst": matched["rst"] = file diff --git a/tools/lint/stylelint/__init__.py b/tools/lint/stylelint/__init__.py @@ -171,7 +171,7 @@ def run(cmd_args, config, fix): # 0 is success, 2 is there was at least 1 rule violation. Anything else # is more serious. - if proc.returncode != 0 and proc.returncode != 2: + if proc.returncode not in {0, 2}: if proc.returncode == 78: print("Stylelint reported an issue with its configuration file.") print(errors) diff --git a/tools/lint/test/test_file_whitespace.py b/tools/lint/test/test_file_whitespace.py @@ -43,7 +43,7 @@ def test_lint_file_whitespace_fix(lint, paths, create_temp_file): path = create_temp_file(contents, "bad.cpp") lint([path], fix=True) # Gives a different answer on Windows. Probably because of Windows CR - assert fixed == 3 or fixed == 2 + assert fixed in {2, 3} if __name__ == "__main__": diff --git a/tools/signing/macos/mach_commands.py b/tools/signing/macos/mach_commands.py @@ -513,7 +513,7 @@ def sign_with_codesign( entitlement_file = signing_group["entitlements"][ "by-build-platform" ][".*devedition.*"] - elif channel == "release" or channel == "beta": + elif channel in {"release", "beta"}: entitlement_file = signing_group["entitlements"][ "by-build-platform" ]["default"]["by-project"]["default"] @@ -649,7 +649,7 @@ def sign_with_rcodesign( entitlement_file = signing_group["entitlements"][ "by-build-platform" ][".*devedition.*"] - elif channel == "release" or channel == "beta": + elif channel in {"release", "beta"}: entitlement_file = signing_group["entitlements"][ "by-build-platform" ]["default"]["by-project"]["default"] diff --git a/xpcom/idl-parser/xpidl/header.py b/xpcom/idl-parser/xpidl/header.py @@ -195,7 +195,7 @@ def paramlistAsNative(m, empty="void", return_param=True): ): t = m.params[paramIter].type # Strings can't be optional, so this shouldn't happen, but let's make sure: - if t == "AString" or t == "ACString" or t == "AUTF8String": + if t in {"AString", "ACString", "AUTF8String"}: break l[paramIter] += " = nullptr" paramIter -= 1 @@ -448,7 +448,7 @@ def infallibleDecl(member): realtype = member.realtype.nativeType("in") tmpl = builtin_infallible_tmpl - if member.realtype.kind != "builtin" and member.realtype.kind != "cenum": + if member.realtype.kind not in {"builtin", "cenum"}: assert realtype.endswith(" *"), "bad infallible type" tmpl = refcnt_infallible_tmpl realtype = realtype[:-2] # strip trailing pointer diff --git a/xpcom/idl-parser/xpidl/rust.py b/xpcom/idl-parser/xpidl/rust.py @@ -61,9 +61,9 @@ class AutoIndent: self.fd.write(" " * indent + s + "\n") for c in s: - if c == "(" or c == "{" or c == "[": + if c in {"(", "{", "["}: self.indent += 1 - elif c == ")" or c == "}" or c == "]": + elif c in {")", "}", "]"}: self.indent -= 1 @@ -354,7 +354,7 @@ def print_rust_bindings(idl, fd, relpath): # import statements for p in idl.productions: - if p.kind == "include" or p.kind == "cdata" or p.kind == "forward": + if p.kind in {"include", "cdata", "forward"}: continue if p.kind == "interface": diff --git a/xpcom/reflect/xptinfo/xptcodegen.py b/xpcom/reflect/xptinfo/xptcodegen.py @@ -273,7 +273,7 @@ def link_to_cpp(interfaces, fd, header_fd): return "%s[size_is=%d]" % (describe_type(type["element"]), type["size_is"]) elif tag == "array": return "Array<%s>" % describe_type(type["element"]) - elif tag == "interface_type" or tag == "domobject": + elif tag in {"interface_type", "domobject"}: return type["name"] elif tag == "interface_is_type": return "iid_is(%d)" % type["iid_is"]