commit 7054a1ab49dd2a76cd3bb8714d6622574bfd84d0 parent 2bb010077c16c4a00959d8ca643b831586fecf64 Author: Alex Hochheiden <ahochheiden@mozilla.com> Date: Wed, 10 Dec 2025 06:03:22 +0000 Bug 2003412 - PLR warnings auto-fixed by `./mach lint --fix .` r=emilio,geckoview-reviewers,taskgraph-reviewers,releng-reviewers,toolkit-telemetry-reviewers,layout-reviewers,jdescottes,bhearsum,nalexander,perftest-reviewers,sparky Differential Revision: https://phabricator.services.mozilla.com/D274687 Diffstat:
89 files changed, 370 insertions(+), 447 deletions(-)
diff --git a/browser/components/sessionstore/test/marionette/test_log_files.py b/browser/components/sessionstore/test/marionette/test_log_files.py @@ -173,7 +173,6 @@ class TestSessionRestoreLogging(WindowManagerMixin, MarionetteTestCase): self.getLineCount(logFile) > startLineCount, "Debug log messages got flushed to disk", ) - # self.assertEqual( len(self.getLogFiles()), logFileCount, diff --git a/docs/_addons/bzlink.py b/docs/_addons/bzlink.py @@ -30,7 +30,6 @@ class ConvertBugsToLinks(SphinxTransform): changed = True while changed: changed = self.textToReferences(check_if_paragraph, check_if_text) - return def textToReferences(self, check_if_paragraph, check_if_text): # Analyses the document and replaces from the paragraph nodes @@ -60,4 +59,3 @@ class ConvertBugsToLinks(SphinxTransform): def setup(app): app.add_transform(ConvertBugsToLinks) - return diff --git a/dom/bindings/Configuration.py b/dom/bindings/Configuration.py @@ -727,19 +727,18 @@ class Descriptor(DescriptorProvider): # test bindings, which don't export, will work correctly. basename = os.path.basename(self.interface.filename) headerDefault = basename.replace(".webidl", "Binding.h") + elif not self.interface.isExternal() and self.interface.getExtendedAttribute( + "HeaderFile" + ): + headerDefault = self.interface.getExtendedAttribute("HeaderFile")[0] + elif ( + self.interface.isIteratorInterface() + or self.interface.isAsyncIteratorInterface() + ): + headerDefault = "mozilla/dom/IterableIterator.h" else: - if not self.interface.isExternal() and self.interface.getExtendedAttribute( - "HeaderFile" - ): - headerDefault = self.interface.getExtendedAttribute("HeaderFile")[0] - elif ( - self.interface.isIteratorInterface() - or self.interface.isAsyncIteratorInterface() - ): - headerDefault = "mozilla/dom/IterableIterator.h" - else: - headerDefault = self.nativeType - headerDefault = headerDefault.replace("::", "/") + ".h" + headerDefault = self.nativeType + headerDefault = headerDefault.replace("::", "/") + ".h" self.headerFile = desc.get("headerFile", headerDefault) self.headerIsDefault = self.headerFile == headerDefault if self.jsImplParent == self.nativeType: diff --git a/js/src/devtools/gc/gc-test.py b/js/src/devtools/gc/gc-test.py @@ -70,11 +70,10 @@ def run_test(test): for i, currItem in enumerate(float_array): if i % 3 == 0: total.append(currItem) + elif i % 3 == 1: + mark.append(currItem) else: - if i % 3 == 1: - mark.append(currItem) - else: - sweep.append(currItem) + sweep.append(currItem) return max(total), avg(total), max(mark), avg(mark), max(sweep), avg(sweep) diff --git a/js/src/devtools/rootAnalysis/mach_commands.py b/js/src/devtools/rootAnalysis/mach_commands.py @@ -551,7 +551,7 @@ def annotated_source(filename, query): out = "<pre>" for lineno, line in enumerate(fh, 1): processed = f"{lineno} <span id='{lineno}'" - if line0 <= lineno and lineno <= line1: + if line0 <= lineno <= line1: processed += " style='background: yellow'" processed += ">" + html.escape(line.rstrip()) + "</span>\n" out += processed diff --git a/js/src/gdb/mozilla/Interpreter.py b/js/src/gdb/mozilla/Interpreter.py @@ -6,7 +6,7 @@ import gdb -import mozilla.prettyprinters as prettyprinters +from mozilla import prettyprinters prettyprinters.clear_module_printers(__name__) diff --git a/js/src/gdb/mozilla/JSObject.py b/js/src/gdb/mozilla/JSObject.py @@ -8,7 +8,7 @@ import re import gdb -import mozilla.prettyprinters as prettyprinters +from mozilla import prettyprinters from mozilla.CellHeader import get_header_ptr from mozilla.jsval import JSValue from mozilla.prettyprinters import ptr_pretty_printer, ref_pretty_printer diff --git a/js/src/gdb/mozilla/JSString.py b/js/src/gdb/mozilla/JSString.py @@ -69,11 +69,10 @@ class JSStringPtr(Common): chars = d["inlineStorageLatin1"] else: chars = d["inlineStorageTwoByte"] + elif is_latin1: + chars = d["s"]["u2"]["nonInlineCharsLatin1"] else: - if is_latin1: - chars = d["s"]["u2"]["nonInlineCharsLatin1"] - else: - chars = d["s"]["u2"]["nonInlineCharsTwoByte"] + chars = d["s"]["u2"]["nonInlineCharsTwoByte"] for i in range(int(length)): yield chars[i] diff --git a/js/src/gdb/mozilla/jsop.py b/js/src/gdb/mozilla/jsop.py @@ -39,7 +39,7 @@ class JSOp: # # https://sourceware.org/bugzilla/show_bug.cgi?id=25325 idx = int(self.value.cast(self.jotc.tJSOp.target())) - assert 0 <= idx and idx <= 255 + assert 0 <= idx <= 255 fields = self.jotc.tJSOp.fields() if idx < len(fields): return fields[idx].name diff --git a/js/src/gdb/mozilla/jsval.py b/js/src/gdb/mozilla/jsval.py @@ -150,7 +150,7 @@ class JSValue: return "$JS::BooleanValue(%s)" % str(self.box.as_uint32() != 0).lower() if tag == self.jtc.MAGIC: value = self.box.as_uint32() - if 0 <= value and value < len(self.jtc.magic_names): + if 0 <= value < len(self.jtc.magic_names): return "$JS::MagicValue(%s)" % (self.jtc.magic_names[value],) else: return "$JS::MagicValue(%d)" % (value,) diff --git a/js/src/gdb/mozilla/unwind.py b/js/src/gdb/mozilla/unwind.py @@ -239,8 +239,7 @@ class JitFrameDecorator(FrameDecorator): num_args = long(this_frame["numActualArgs_"]) # Sometimes we see very large values here, so truncate it to # bypass the damage. - if num_args > 10: - num_args = 10 + num_args = min(num_args, 10) args_ptr = (this_frame + 1).cast(self.cache.Value.pointer()) for i in range(num_args + 1): # Synthesize names, since there doesn't seem to be @@ -341,7 +340,7 @@ class UnwinderState: return False # If allocated, then we allocated MaxCodeBytesPerProcess. - return base <= pc and pc < base + length + return base <= pc < base + length # Check whether |self| is valid for the selected thread. def check(self): diff --git a/js/src/gdb/taskpool.py b/js/src/gdb/taskpool.py @@ -169,7 +169,6 @@ class TaskPool: # Remove the finished tasks from the running set. (Do this here # to avoid mutating the set while iterating over it.) running -= finished - return None def get_cpu_count(): diff --git a/js/src/jit/arm/gen-double-encoder-table.py b/js/src/jit/arm/gen-double-encoder-table.py @@ -22,7 +22,7 @@ def encodeDouble(value): aBbbbbbb bbcdefgh 000... We will return the top 32 bits of the double; the rest are 0.""" - assert (0 <= value) and (value <= 255) + assert 0 <= value <= 255 a = value >> 7 b = (value >> 6) & 1 B = int(b == 0) diff --git a/js/src/tests/jstests.py b/js/src/tests/jstests.py @@ -670,7 +670,7 @@ def load_tests(options, requested_paths, excluded_paths): test_count: [int] Number of tests that will be in test_gen test_gen: [iterable<Test>] Tests found that should be run. """ - import lib.manifest as manifest + from lib import manifest if options.js_shell is None: xul_tester = manifest.NullXULInfoTester() diff --git a/js/src/tests/lib/jittests.py b/js/src/tests/lib/jittests.py @@ -313,56 +313,48 @@ class JitTest: f"{path}: warning: unrecognized |jit-test| attribute" f" {part}" ) + elif name == "slow": + test.slow = True + elif name == "heavy": + test.heavy = True + elif name == "allow-oom": + test.allow_oom = True + elif name == "allow-unhandlable-oom": + test.allow_unhandlable_oom = True + elif name == "allow-overrecursed": + test.allow_overrecursed = True + elif name == "valgrind": + test.valgrind = options.valgrind + elif name == "tz-pacific": + test.tz_pacific = True + elif name.startswith("test-also="): + test.test_also.append(re.split(r"\s+", name[len("test-also=") :])) + elif name.startswith("test-join="): + test.test_join.append(re.split(r"\s+", name[len("test-join=") :])) + elif name == "module": + test.is_module = True + elif name == "crash": + # Crashes are only allowed in self-test, as it is + # intended to verify that our testing infrastructure + # works, and not meant as a way to accept temporary + # failing tests. These tests should either be fixed or + # skipped. + assert ( + "self-test" in path + ), f"{path}: has an unexpected crash annotation." + test.expect_crash = True + elif name.startswith("--"): + # // |jit-test| --ion-gvn=off; --no-sse4 + test.jitflags.append(name) + elif name.startswith("-P"): + prefAndValue = name.split() + assert len(prefAndValue) == 2, f"{name}: failed to parse preference" + # // |jit-test| -P pref(=value)? + test.jitflags.append("--setpref=" + prefAndValue[1]) else: - if name == "slow": - test.slow = True - elif name == "heavy": - test.heavy = True - elif name == "allow-oom": - test.allow_oom = True - elif name == "allow-unhandlable-oom": - test.allow_unhandlable_oom = True - elif name == "allow-overrecursed": - test.allow_overrecursed = True - elif name == "valgrind": - test.valgrind = options.valgrind - elif name == "tz-pacific": - test.tz_pacific = True - elif name.startswith("test-also="): - test.test_also.append( - re.split(r"\s+", name[len("test-also=") :]) - ) - elif name.startswith("test-join="): - test.test_join.append( - re.split(r"\s+", name[len("test-join=") :]) - ) - elif name == "module": - test.is_module = True - elif name == "crash": - # Crashes are only allowed in self-test, as it is - # intended to verify that our testing infrastructure - # works, and not meant as a way to accept temporary - # failing tests. These tests should either be fixed or - # skipped. - assert ( - "self-test" in path - ), f"{path}: has an unexpected crash annotation." - test.expect_crash = True - elif name.startswith("--"): - # // |jit-test| --ion-gvn=off; --no-sse4 - test.jitflags.append(name) - elif name.startswith("-P"): - prefAndValue = name.split() - assert ( - len(prefAndValue) == 2 - ), f"{name}: failed to parse preference" - # // |jit-test| -P pref(=value)? - test.jitflags.append("--setpref=" + prefAndValue[1]) - else: - print( - f"{path}: warning: unrecognized |jit-test| attribute" - f" {part}" - ) + print( + f"{path}: warning: unrecognized |jit-test| attribute" f" {part}" + ) if options.valgrind_all: test.valgrind = True diff --git a/js/src/tests/lib/results.py b/js/src/tests/lib/results.py @@ -190,11 +190,10 @@ class TestResult: result = cls.FAIL else: result = cls.CRASH + elif (rc or passes > 0) and failures == 0: + result = cls.PASS else: - if (rc or passes > 0) and failures == 0: - result = cls.PASS - else: - result = cls.FAIL + result = cls.FAIL return cls(test, result, results) diff --git a/js/src/tests/lib/tasks_unix.py b/js/src/tests/lib/tasks_unix.py @@ -70,8 +70,7 @@ def get_max_wait(tasks, timeout): timeout_delta = timedelta(seconds=timeout) for task in tasks: remaining = task.start + timeout_delta - now - if remaining < wait: - wait = remaining + wait = min(wait, remaining) # Return the wait time in seconds, clamped between zero and max_wait. return max(wait.total_seconds(), 0) diff --git a/js/src/util/make_unicode.py b/js/src/util/make_unicode.py @@ -923,7 +923,7 @@ def write_ascii_lookup_tables(table, index, write, println): def write_latin1_lookup_tables(table, index, write, println): def case_info(code): - assert 0 <= code and code <= MAX_BMP + assert 0 <= code <= MAX_BMP (upper, lower, flags) = table[index[code]] return ((code + upper) & 0xFFFF, (code + lower) & 0xFFFF, flags) diff --git a/layout/tools/reftest/remotereftest.py b/layout/tools/reftest/remotereftest.py @@ -92,13 +92,10 @@ class ReftestServer: if sys.platform in ("win32", "msys", "cygwin"): env["PATH"] = env["PATH"] + ";" + self.xrePath bin_suffix = ".exe" + elif "LD_LIBRARY_PATH" not in env or env["LD_LIBRARY_PATH"] is None: + env["LD_LIBRARY_PATH"] = self.xrePath else: - if "LD_LIBRARY_PATH" not in env or env["LD_LIBRARY_PATH"] is None: - env["LD_LIBRARY_PATH"] = self.xrePath - else: - env["LD_LIBRARY_PATH"] = ":".join( - [self.xrePath, env["LD_LIBRARY_PATH"]] - ) + env["LD_LIBRARY_PATH"] = ":".join([self.xrePath, env["LD_LIBRARY_PATH"]]) args = [ "-g", diff --git a/memory/replace/dmd/block_analyzer.py b/memory/replace/dmd/block_analyzer.py @@ -214,7 +214,6 @@ def show_block_info(args, blocks, stacks, block): sys.stdout.write("\n\n") sys.stdout.write("allocation stack:\n") print_trace_segment(args, stacks, b) - return def cleanupTraceTable(args, frameTable, traceTable): 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 @@ -1263,9 +1263,8 @@ def verify_layering(clazz): for j in ranking[i]: if p.startswith(j): return i - else: - if p.startswith(ranking[i]): - return i + elif p.startswith(ranking[i]): + return i cr = rank(clazz.pkg.name) if cr is None: diff --git a/python/mozbuild/mozbuild/action/tooltool.py b/python/mozbuild/mozbuild/action/tooltool.py @@ -99,8 +99,7 @@ def retrier(attempts=5, sleeptime=10, max_sleeptime=300, sleepscale=1.5, jitter= sleeptime *= sleepscale - if sleeptime_real > max_sleeptime: - sleeptime_real = max_sleeptime + sleeptime_real = min(sleeptime_real, max_sleeptime) # Don't need to sleep the last time if _ < attempts - 1: diff --git a/python/mozbuild/mozbuild/analyze/hg.py b/python/mozbuild/mozbuild/analyze/hg.py @@ -106,11 +106,10 @@ class Report: if path is not None: with gzip.open(path) as file: return json.loads(file.read()) + elif cost_dict is not None: + return cost_dict else: - if cost_dict is not None: - return cost_dict - else: - raise Exception + raise Exception def organize_data(self): costs = self.cost_dict diff --git a/python/mozbuild/mozbuild/backend/base.py b/python/mozbuild/mozbuild/backend/base.py @@ -164,11 +164,10 @@ class BuildBackend(LoggingMixin): if backend_output_list != self._backend_output_files: with self._write_file(list_file) as fh: fh.write("\n".join(sorted(self._backend_output_files))) - else: - # Always update its mtime if we're not in dry-run mode. - if not self.dry_run: - with open(list_file, "a"): - os.utime(list_file, None) + # Always update its mtime if we're not in dry-run mode. + elif not self.dry_run: + with open(list_file, "a"): + os.utime(list_file, None) # Write out the list of input files for the backend with self._write_file("%s.in" % list_file) as fh: diff --git a/python/mozbuild/mozbuild/backend/common.py b/python/mozbuild/mozbuild/backend/common.py @@ -576,11 +576,10 @@ class CommonBackend(BuildBackend): localized_files_pp[path] += [src] else: files_pp[path] += [src] + elif e.is_locale: + localized_files[path] += [src] else: - if e.is_locale: - localized_files[path] += [src] - else: - files[path] += [src] + files[path] += [src] if files: self.consume_object(FinalTargetFiles(jar_context, files)) diff --git a/python/mozbuild/mozbuild/backend/mach_commands.py b/python/mozbuild/mozbuild/backend/mach_commands.py @@ -344,11 +344,10 @@ def setup_clangd_rust_in_vscode(command_context): cargo_check_command = [sys.executable, "../../mach"] else: cargo_check_command = ["../../mach"] + elif sys.platform == "win32": + cargo_check_command = [sys.executable, "mach"] else: - if sys.platform == "win32": - cargo_check_command = [sys.executable, "mach"] - else: - cargo_check_command = ["./mach"] + cargo_check_command = ["./mach"] cargo_check_command += [ "--log-no-times", diff --git a/python/mozbuild/mozbuild/code_analysis/mach_commands.py b/python/mozbuild/mozbuild/code_analysis/mach_commands.py @@ -1630,10 +1630,9 @@ def _generate_path_list(command_context, paths, verbose=True): ): # Supported extension and accepted path path_list.append(f_in_dir) - else: - # Make sure that the file exists and it has a supported extension - if os.path.isfile(f) and f.endswith(extensions): - path_list.append(f) + # Make sure that the file exists and it has a supported extension + elif os.path.isfile(f) and f.endswith(extensions): + path_list.append(f) return path_list diff --git a/python/mozbuild/mozbuild/frontend/emitter.py b/python/mozbuild/mozbuild/frontend/emitter.py @@ -1565,18 +1565,17 @@ class TreeMetadataEmitter(LoggingMixin): % (var, f), context, ) - else: - # Additionally, don't allow LOCALIZED_GENERATED_FILES to be used - # in anything *but* LOCALIZED_FILES. - if f.target_basename in localized_generated_files: - raise SandboxValidationError( - ( - "Outputs of LOCALIZED_GENERATED_FILES cannot " - "be used in %s: %s" - ) - % (var, f), - context, + # Additionally, don't allow LOCALIZED_GENERATED_FILES to be used + # in anything *but* LOCALIZED_FILES. + elif f.target_basename in localized_generated_files: + raise SandboxValidationError( + ( + "Outputs of LOCALIZED_GENERATED_FILES cannot " + "be used in %s: %s" ) + % (var, f), + context, + ) # Addons (when XPI_NAME is defined) and Applications (when # DIST_SUBDIR is defined) use a different preferences directory diff --git a/python/mozbuild/mozbuild/jar.py b/python/mozbuild/mozbuild/jar.py @@ -47,7 +47,6 @@ class ZipEntry: """Append the given content to this zip entry""" self._inner.write(ensure_bytes(content)) - return def close(self): """The close method writes the content back to the zip file.""" diff --git a/python/mozbuild/mozbuild/mach_commands.py b/python/mozbuild/mozbuild/mach_commands.py @@ -1278,8 +1278,7 @@ def gtest( # Clamp error code to 255 to prevent overflowing multiple of # 256 into 0 - if exit_code > 255: - exit_code = 255 + exit_code = min(exit_code, 255) # Show aggregated report information and any test errors. command_context.log( diff --git a/python/mozbuild/mozbuild/preprocessor.py b/python/mozbuild/mozbuild/preprocessor.py @@ -184,7 +184,6 @@ class Expression: def __ignore_whitespace(self): ws_len = re.match(r"\s*", self.content).end() self.__strip(ws_len) - return def __strip(self, length): """ @@ -815,7 +814,6 @@ class Preprocessor: if f in current: del current[f] self.filters = [(fn, current[fn]) for fn in sorted(current.keys())] - return # Filters # diff --git a/python/mozbuild/mozbuild/test/action/test_process_install_manifest.py b/python/mozbuild/mozbuild/test/action/test_process_install_manifest.py @@ -7,7 +7,7 @@ import mozunit from mozpack.manifests import InstallManifest from mozpack.test.test_files import TestWithTmpDir -import mozbuild.action.process_install_manifest as process_install_manifest +from mozbuild.action import process_install_manifest class TestGenerateManifest(TestWithTmpDir): diff --git a/python/mozbuild/mozbuild/vendor/rewrite_mozbuild.py b/python/mozbuild/mozbuild/vendor/rewrite_mozbuild.py @@ -695,7 +695,7 @@ def guess_best_assignment(source_assignments, filename_normalized): length_of_longest_match = len(prefix) source_assignment_location_of_longest_match = key elif len(prefix) == length_of_longest_match and len( - source_assignments[key] + list_of_normalized_filenames ) > len(source_assignments[source_assignment_location_of_longest_match]): statistic_number_refinements += 1 statistic_length_logic += 1 diff --git a/python/mozbuild/mozpack/copier.py b/python/mozbuild/mozpack/copier.py @@ -2,12 +2,12 @@ # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. -import concurrent.futures as futures import errno import os import stat import sys from collections import Counter, OrderedDict, defaultdict +from concurrent import futures import mozpack.path as mozpath from mozpack.errors import errors diff --git a/python/mozbuild/mozpack/files.py b/python/mozbuild/mozpack/files.py @@ -20,8 +20,8 @@ from tempfile import NamedTemporaryFile, mkstemp from jsmin import JavascriptMinify -import mozbuild.makeutil as makeutil import mozpack.path as mozpath +from mozbuild import makeutil from mozbuild.preprocessor import Preprocessor from mozbuild.util import FileAvoidWrite, ensure_unicode, memoize from mozpack.chrome.manifest import ManifestEntry, ManifestInterfaces diff --git a/python/mozperftest/mozperftest/test/browsertime/runner.py b/python/mozperftest/mozperftest/test/browsertime/runner.py @@ -299,22 +299,21 @@ class BrowsertimeRunner(NodeRunner): binary = self.get_arg("browsertime_binary") if binary is not None: extra_args.extend(("--firefox.binaryPath", binary)) - else: - # If --firefox.binaryPath is not specified, default to the objdir binary - # Note: --firefox.release is not a real browsertime option, but it will - # silently ignore it instead and default to a release installation. - if ( - not matches( - args, - "--firefox.binaryPath", - "--firefox.release", - "--firefox.nightly", - "--firefox.beta", - "--firefox.developer", - ) - and extract_browser_name(args) != "chrome" - ): - extra_args.extend(("--firefox.binaryPath", self.get_binary_path())) + # If --firefox.binaryPath is not specified, default to the objdir binary + # Note: --firefox.release is not a real browsertime option, but it will + # silently ignore it instead and default to a release installation. + elif ( + not matches( + args, + "--firefox.binaryPath", + "--firefox.release", + "--firefox.nightly", + "--firefox.beta", + "--firefox.developer", + ) + and extract_browser_name(args) != "chrome" + ): + extra_args.extend(("--firefox.binaryPath", self.get_binary_path())) geckodriver = self.get_arg("geckodriver") if geckodriver is not None: diff --git a/python/mozperftest/mozperftest/test/webpagetest.py b/python/mozperftest/mozperftest/test/webpagetest.py @@ -7,7 +7,7 @@ from threading import Thread import requests -import mozperftest.utils as utils +from mozperftest import utils from mozperftest.layers import Layer from mozperftest.runner import HERE diff --git a/python/mozperftest/mozperftest/tests/__init__.py b/python/mozperftest/mozperftest/tests/__init__.py @@ -1 +0,0 @@ -# diff --git a/python/mozperftest/mozperftest/tests/test_perfherder.py b/python/mozperftest/mozperftest/tests/test_perfherder.py @@ -249,7 +249,7 @@ def test_perfherder_simple_names(): assert "statistics" in subtest["name"] for entry, value in found_all.items(): - assert found_all[entry], f"Failed finding metric simplification for {entry}" + assert value, f"Failed finding metric simplification for {entry}" # Statistics are not simplified by default assert ( @@ -321,7 +321,7 @@ def test_perfherder_names_simplified_with_no_exclusions(): continue for entry, value in found_all.items(): - assert found_all[entry], f"Failed finding metric simplification for {entry}" + assert value, f"Failed finding metric simplification for {entry}" # Only a portion of the metrics should still have statistics in # their name due to a naming conflict that only emits a warning diff --git a/python/mozperftest/mozperftest/tests/test_webpagetest.py b/python/mozperftest/mozperftest/tests/test_webpagetest.py @@ -5,7 +5,7 @@ from unittest import mock import pytest import requests -import mozperftest.test.webpagetest as webpagetest +from mozperftest.test import webpagetest from mozperftest.test.webpagetest import ( ACCEPTED_STATISTICS, WPT_API_EXPIRED_MESSAGE, diff --git a/python/mozrelease/mozrelease/update_verify.py b/python/mozrelease/mozrelease/update_verify.py @@ -118,7 +118,7 @@ class UpdateVerifyConfig: releaseKeys = {} for k, v in entry.items(): if k in self.global_keys: - setattr(self, k, entry[k]) + setattr(self, k, v) elif k in self.release_keys: # "from" is reserved in Python if k == "from": diff --git a/taskcluster/gecko_taskgraph/actions/cancel_all.py b/taskcluster/gecko_taskgraph/actions/cancel_all.py @@ -3,9 +3,9 @@ # file, You can obtain one at http://mozilla.org/MPL/2.0/. -import concurrent.futures as futures import logging import os +from concurrent import futures from taskcluster.exceptions import TaskclusterRestFailure from taskgraph.util.taskcluster import CONCURRENCY, cancel_task diff --git a/taskcluster/gecko_taskgraph/actions/util.py b/taskcluster/gecko_taskgraph/actions/util.py @@ -3,11 +3,11 @@ # file, You can obtain one at http://mozilla.org/MPL/2.0/. -import concurrent.futures as futures import copy import logging import os import re +from concurrent import futures from functools import reduce import jsone diff --git a/taskcluster/gecko_taskgraph/transforms/task.py b/taskcluster/gecko_taskgraph/transforms/task.py @@ -1455,7 +1455,7 @@ def build_treescript_payload(config, task, task_def): if "l10n-repo-url" in lbi: l10n_repo_urls.add(lbi["l10n-repo-url"]) for k, v in lbi.items(): - new_lbi[k.replace("-", "_")] = lbi[k] + new_lbi[k.replace("-", "_")] = v l10n_bump_info.append(new_lbi) task_def["payload"]["l10n_bump_info"] = l10n_bump_info @@ -1638,7 +1638,7 @@ def build_landoscript_payload(config, task, task_def): if "l10n-repo-url" in lbi: l10n_repo_urls.add(lbi["l10n-repo-url"]) for k, v in lbi.items(): - new_lbi[k.replace("-", "_")] = lbi[k] + new_lbi[k.replace("-", "_")] = v l10n_bump_info.append(new_lbi) task_def["payload"]["l10n_bump_info"] = l10n_bump_info diff --git a/taskcluster/gecko_taskgraph/transforms/test/chunk.py b/taskcluster/gecko_taskgraph/transforms/test/chunk.py @@ -54,8 +54,7 @@ def set_test_verify_chunks(config, tasks): # >30 tests changed, this is probably an import of external tests, # or a patch renaming/moving files in bulk maximum_number_verify_chunks = 3 - if task["chunks"] > maximum_number_verify_chunks: - task["chunks"] = maximum_number_verify_chunks + task["chunks"] = min(task["chunks"], maximum_number_verify_chunks) yield task diff --git a/taskcluster/gecko_taskgraph/util/verify.py b/taskcluster/gecko_taskgraph/util/verify.py @@ -439,21 +439,20 @@ def verify_test_packaging(task, taskgraph, scratch_pad, graph_config, parameters f"Build job {task.label} has tests dependent on it and does not specify " "MOZ_AUTOMATION_PACKAGE_TESTS=1 in the environment" ) - else: - # Build tasks that aren't in the scratch pad have no - # dependent tests, so we shouldn't package tests. - # With the caveat that we expect shippable jobs to always - # produce tests. - if not build_has_tests and not shippable: - # If we have not generated all task kinds, we can't verify that - # there are no dependent tests. - if not missing_tests_allowed: - exceptions.append( - f"Build job {task.label} has no tests, but specifies " - f"MOZ_AUTOMATION_PACKAGE_TESTS={package_tests} in the environment. " - "Unset MOZ_AUTOMATION_PACKAGE_TESTS in the task definition " - "to fix." - ) + # Build tasks that aren't in the scratch pad have no + # dependent tests, so we shouldn't package tests. + # With the caveat that we expect shippable jobs to always + # produce tests. + elif not build_has_tests and not shippable: + # If we have not generated all task kinds, we can't verify that + # there are no dependent tests. + if not missing_tests_allowed: + exceptions.append( + f"Build job {task.label} has no tests, but specifies " + f"MOZ_AUTOMATION_PACKAGE_TESTS={package_tests} in the environment. " + "Unset MOZ_AUTOMATION_PACKAGE_TESTS in the task definition " + "to fix." + ) if exceptions: raise Exception("\n".join(exceptions)) return diff --git a/testing/addtest.py b/testing/addtest.py @@ -161,12 +161,11 @@ testing/web-platform/mozilla/tests for Gecko-only tests""" if self.kwargs["wait"]: print("--wait only makes sense for a reftest") return False - else: - # Set the ref to a url relative to the test - if self.kwargs["ref"]: - if self.ref_path(self.kwargs["ref"]) is None: - print("--ref doesn't refer to a path inside web-platform-tests") - return False + # Set the ref to a url relative to the test + elif self.kwargs["ref"]: + if self.ref_path(self.kwargs["ref"]) is None: + print("--ref doesn't refer to a path inside web-platform-tests") + return False def __iter__(self): yield (self.test, self._get_template_contents()) @@ -250,15 +249,14 @@ testing/web-platform/mozilla/tests for Gecko-only tests""" return os.path.join(base, path) else: return self.src_rel_path(path) + elif self.wpt_type(path) is not None: + return path else: - if self.wpt_type(path) is not None: - return path - else: - test_rel_path = self.src_rel_path( - os.path.join(os.path.dirname(self.test), path) - ) - if self.wpt_type(test_rel_path) is not None: - return test_rel_path + test_rel_path = self.src_rel_path( + os.path.join(os.path.dirname(self.test), path) + ) + if self.wpt_type(test_rel_path) is not None: + return test_rel_path # Returning None indicates that the path wasn't valid def ref_url(self, path): diff --git a/testing/condprofile/condprof/tests/test_runner.py b/testing/condprofile/condprof/tests/test_runner.py @@ -32,8 +32,7 @@ ADDON = re.compile("https://addons.mozilla.org/.*/.*xpi") async def fakesleep(duration): - if duration > 1: - duration = 1 + duration = min(duration, 1) await asyncio.realsleep(duration) diff --git a/testing/marionette/harness/marionette_harness/runner/base.py b/testing/marionette/harness/marionette_harness/runner/base.py @@ -767,7 +767,7 @@ class BaseMarionetteTestRunner: if isinstance(v, dict) and isinstance(o, dict): d[k] = update(d.get(k, {}), v) else: - d[k] = u[k] + d[k] = v return d json_testvars = self._load_testvars() diff --git a/testing/mochitest/runtests.py b/testing/mochitest/runtests.py @@ -2488,21 +2488,20 @@ toolbar#nav-bar { if options.flavor == "browser": if options.timeout: test_timeout = options.timeout + elif mozinfo.info["asan"] or mozinfo.info["debug"]: + # browser-chrome tests use a fairly short default timeout of 45 seconds; + # this is sometimes too short on asan and debug, where we expect reduced + # performance. + self.log.info( + "Increasing default timeout to 90 seconds (asan or debug)" + ) + test_timeout = 90 + elif mozinfo.info["tsan"]: + # tsan builds need even more time + self.log.info("Increasing default timeout to 120 seconds (tsan)") + test_timeout = 120 else: - if mozinfo.info["asan"] or mozinfo.info["debug"]: - # browser-chrome tests use a fairly short default timeout of 45 seconds; - # this is sometimes too short on asan and debug, where we expect reduced - # performance. - self.log.info( - "Increasing default timeout to 90 seconds (asan or debug)" - ) - test_timeout = 90 - elif mozinfo.info["tsan"]: - # tsan builds need even more time - self.log.info("Increasing default timeout to 120 seconds (tsan)") - test_timeout = 120 - else: - test_timeout = 45 + test_timeout = 45 elif options.flavor in ("a11y", "chrome"): test_timeout = 45 @@ -3323,8 +3322,7 @@ toolbar#nav-bar { for key in self.expectedError: full_key = [x for x in testsToRun if key in x] if full_key: - if testsToRun.index(full_key[0]) < firstFail: - firstFail = testsToRun.index(full_key[0]) + firstFail = min(firstFail, testsToRun.index(full_key[0])) testsToRun = testsToRun[firstFail + 1 :] if testsToRun == []: status = -1 diff --git a/testing/mochitest/tests/python/test_create_directories.py b/testing/mochitest/tests/python/test_create_directories.py @@ -3,10 +3,10 @@ # file, You can obtain one at http://mozilla.org/MPL/2.0/. import os -import unittest.mock as mock from argparse import Namespace from collections import defaultdict from textwrap import dedent +from unittest import mock import mozunit import pytest diff --git a/testing/mozbase/mozdebug/mozdebug/mozdebug.py b/testing/mozbase/mozdebug/mozdebug/mozdebug.py @@ -164,9 +164,8 @@ def get_debugger_info(debugger, debuggerArgs=None, debuggerInteractive=False): if os.path.exists(candidate): debuggerPath = candidate break - else: - if os.path.exists(debugger): - debuggerPath = debugger + elif os.path.exists(debugger): + debuggerPath = debugger if not debuggerPath: print("Error: Could not find debugger %s." % debugger) diff --git a/testing/mozbase/mozlog/mozlog/formatters/html/html.py b/testing/mozbase/mozlog/mozlog/formatters/html/html.py @@ -218,14 +218,13 @@ class HTMLFormatter(base.BaseFormatter): separator = line.startswith(" " * 10) if separator: log.append(line[:80]) + elif ( + line.lower().find("error") != -1 + or line.lower().find("exception") != -1 + ): + log.append(html.span(raw(escape(line)), class_="error")) else: - if ( - line.lower().find("error") != -1 - or line.lower().find("exception") != -1 - ): - log.append(html.span(raw(escape(line)), class_="error")) - else: - log.append(raw(escape(line))) + log.append(raw(escape(line))) log.append(html.br()) additional_html.append(log) diff --git a/testing/mozbase/mozlog/mozlog/formatters/machformatter.py b/testing/mozbase/mozlog/mozlog/formatters/machformatter.py @@ -174,14 +174,13 @@ class MachFormatter(base.BaseFormatter): if expected not in ("PASS", "OK"): color = self.color_formatter.log_test_status_fail status = "EXPECTED-%s" % status + elif status in known_intermittent: + color = self.color_formatter.log_test_status_known_intermittent + status = "KNOWN-INTERMITTENT-%s" % status else: - if status in known_intermittent: - color = self.color_formatter.log_test_status_known_intermittent - status = "KNOWN-INTERMITTENT-%s" % status - else: - color = self.color_formatter.log_test_status_fail - if status in ("PASS", "OK"): - status = "UNEXPECTED-%s" % status + color = self.color_formatter.log_test_status_fail + if status in ("PASS", "OK"): + status = "UNEXPECTED-%s" % status return color(status) def _format_status(self, test, data): diff --git a/testing/mozbase/mozlog/mozlog/scripts/unstable.py b/testing/mozbase/mozlog/mozlog/scripts/unstable.py @@ -132,11 +132,10 @@ def main(**kwargs): if kwargs["json"]: print(json.dumps(unstable)) + elif not kwargs["group"]: + print_results(unstable) else: - if not kwargs["group"]: - print_results(unstable) - else: - print_run(unstable) + print_run(unstable) if __name__ == "__main__": diff --git a/testing/mozbase/mozproxy/mozproxy/backends/mitm/android.py b/testing/mozbase/mozproxy/mozproxy/backends/mitm/android.py @@ -235,12 +235,11 @@ class MitmproxyAndroid(Mitmproxy): LOG.info("Certutil returncode: %s" % cmd_proc.returncode) LOG.info("Certutil output: %s" % cmd_output) return cmd_output + elif raise_exception: + LOG.critical("Certutil command failed!!") + LOG.info("Certutil returncode: %s" % cmd_proc.returncode) + LOG.info("Certutil output: %s" % cmd_output) + LOG.info("Certutil error: %s" % errs) + raise Exception("Certutil command failed!!") else: - if raise_exception: - LOG.critical("Certutil command failed!!") - LOG.info("Certutil returncode: %s" % cmd_proc.returncode) - LOG.info("Certutil output: %s" % cmd_output) - LOG.info("Certutil error: %s" % errs) - raise Exception("Certutil command failed!!") - else: - return False + return False diff --git a/testing/mozbase/mozproxy/mozproxy/backends/mitm/mitm.py b/testing/mozbase/mozproxy/mozproxy/backends/mitm/mitm.py @@ -315,78 +315,77 @@ class Mitmproxy(Playback): self.recording.set_metadata( "proxy_version", self.config["playback_version"] ) - else: - # playback mode - if len(self.playback_files) > 0: - if self.config["playback_version"] in ["8.1.1", "11.0.0"]: - command.extend( - [ - "--set", - "websocket=false", - "--set", - "connection_strategy=lazy", - "--set", - "alt_server_replay_nopop=true", - "--set", - "alt_server_replay_kill_extra=true", - "--set", - "alt_server_replay_order_reversed=true", - "--set", - "tls_version_client_min=TLS1_2", - "--set", - "alt_server_replay={}".format( - ",".join( - [ - os.path.normpath(playback_file.recording_path) - for playback_file in self.playback_files - ] - ) - ), - "--scripts", - os.path.normpath( - os.path.join( - mitm_folder, "scripts", "alt-serverplayback.py" - ) - ), - ] - ) - elif self.config["playback_version"] in [ - "4.0.4", - "5.1.1", - "6.0.2", - ]: - command.extend( - [ - "--set", - "upstream_cert=false", - "--set", - "upload_dir=" + os.path.normpath(self.upload_dir), - "--set", - "websocket=false", - "--set", - "server_replay_files={}".format( - ",".join( - [ - os.path.normpath(playback_file.recording_path) - for playback_file in self.playback_files - ] - ) - ), - "--scripts", - os.path.normpath( - os.path.join( - mitm_folder, "scripts", "alternate-server-replay.py" - ) - ), - ] - ) - else: - raise Exception("Mitmproxy version is unknown!") - - else: - raise Exception( - "Mitmproxy can't start playback! Playback settings missing." + # playback mode + elif len(self.playback_files) > 0: + if self.config["playback_version"] in ["8.1.1", "11.0.0"]: + command.extend( + [ + "--set", + "websocket=false", + "--set", + "connection_strategy=lazy", + "--set", + "alt_server_replay_nopop=true", + "--set", + "alt_server_replay_kill_extra=true", + "--set", + "alt_server_replay_order_reversed=true", + "--set", + "tls_version_client_min=TLS1_2", + "--set", + "alt_server_replay={}".format( + ",".join( + [ + os.path.normpath(playback_file.recording_path) + for playback_file in self.playback_files + ] + ) + ), + "--scripts", + os.path.normpath( + os.path.join( + mitm_folder, "scripts", "alt-serverplayback.py" + ) + ), + ] ) + elif self.config["playback_version"] in [ + "4.0.4", + "5.1.1", + "6.0.2", + ]: + command.extend( + [ + "--set", + "upstream_cert=false", + "--set", + "upload_dir=" + os.path.normpath(self.upload_dir), + "--set", + "websocket=false", + "--set", + "server_replay_files={}".format( + ",".join( + [ + os.path.normpath(playback_file.recording_path) + for playback_file in self.playback_files + ] + ) + ), + "--scripts", + os.path.normpath( + os.path.join( + mitm_folder, "scripts", "alternate-server-replay.py" + ) + ), + ] + ) + else: + raise Exception("Mitmproxy version is unknown!") + + else: + raise Exception( + "Mitmproxy can't start playback! Playback settings missing." + ) # mitmproxy needs some DLL's that are a part of Firefox itself, so add to path env = os.environ.copy() diff --git a/testing/mozbase/mozproxy/tests/__init__.py b/testing/mozbase/mozproxy/tests/__init__.py @@ -1 +0,0 @@ -# diff --git a/testing/mozbase/mozrunner/mozrunner/base/runner.py b/testing/mozbase/mozrunner/mozrunner/base/runner.py @@ -247,15 +247,14 @@ class BaseRunner(metaclass=ABCMeta): ) else: self.logger.warning("Can not log crashes without mozcrash") - else: - if mozcrash: - crash_count = mozcrash.check_for_crashes( - dump_directory, - self.symbols_path, - dump_save_path=dump_save_path, - test_name=test_name, - quiet=quiet, - ) + elif mozcrash: + crash_count = mozcrash.check_for_crashes( + dump_directory, + self.symbols_path, + dump_save_path=dump_save_path, + test_name=test_name, + quiet=quiet, + ) self.crashed += crash_count except Exception: diff --git a/testing/mozbase/moztest/moztest/resolve.py b/testing/mozbase/moztest/moztest/resolve.py @@ -1225,9 +1225,7 @@ class TestResolver(MozbuildObject): full_path = mozpath.join(tests_root, path) # absolute path on disk src_path = mozpath.relpath(full_path, self.topsrcdir) - test_tags = self.get_test_tags( - [], manifests[manifest].get("metadata_path", ""), path - ) + test_tags = self.get_test_tags([], data.get("metadata_path", ""), path) for test in tests: testobj = { diff --git a/testing/mozharness/mozharness/base/config.py b/testing/mozharness/mozharness/base/config.py @@ -213,8 +213,7 @@ def download_config_file(url, file_name): print("Sleeping %d seconds before retrying" % sleeptime) time.sleep(sleeptime) sleeptime = sleeptime * 2 - if sleeptime > max_sleeptime: - sleeptime = max_sleeptime + sleeptime = min(sleeptime, max_sleeptime) n += 1 try: diff --git a/testing/mozharness/mozharness/base/script.py b/testing/mozharness/mozharness/base/script.py @@ -1337,8 +1337,7 @@ class ScriptMixin(PlatformMixin): ) time.sleep(sleeptime) sleeptime = sleeptime * 2 - if sleeptime > max_sleeptime: - sleeptime = max_sleeptime + sleeptime = min(sleeptime, max_sleeptime) def query_env( self, @@ -1594,12 +1593,11 @@ class ScriptMixin(PlatformMixin): if partial_env: self.info("Using partial env: %s" % pprint.pformat(partial_env)) env = self.query_env(partial_env=partial_env) + elif hasattr(self, "previous_env") and env == self.previous_env: + self.info("Using env: (same as previous command)") else: - if hasattr(self, "previous_env") and env == self.previous_env: - self.info("Using env: (same as previous command)") - else: - self.info("Using env: %s" % pprint.pformat(env)) - self.previous_env = env + self.info("Using env: %s" % pprint.pformat(env)) + self.previous_env = env if output_parser is None: parser = OutputParser( diff --git a/testing/mozharness/mozharness/mozilla/building/buildbase.py b/testing/mozharness/mozharness/mozilla/building/buildbase.py @@ -211,7 +211,7 @@ class BuildingConfig(BaseConfig): # importance for i, cf in enumerate(all_config_files): if cf == options.build_variant: - variant_cfg_file = all_config_files[i] + variant_cfg_file = cf # now remove it from the list if variant_cfg_file: diff --git a/testing/mozharness/mozharness/mozilla/testing/per_test_base.py b/testing/mozharness/mozharness/mozilla/testing/per_test_base.py @@ -570,13 +570,12 @@ class SingleTestMixin: if key in all_suites.keys() ) self.info("Per-test suites: %s" % suites) - else: - # Until test zips are downloaded, manifests are not available, - # so it is not possible to determine which suites are active/ - # required for per-test mode; assume all suites from supported - # suite categories are required. - if category in ["mochitest", "xpcshell", "reftest"]: - suites = all_suites + # Until test zips are downloaded, manifests are not available, + # so it is not possible to determine which suites are active/ + # required for per-test mode; assume all suites from supported + # suite categories are required. + elif category in ["mochitest", "xpcshell", "reftest"]: + suites = all_suites return suites def log_per_test_status(self, test_name, tbpl_status, log_level): diff --git a/testing/mozharness/mozharness/mozilla/testing/testbase.py b/testing/mozharness/mozharness/mozilla/testing/testbase.py @@ -334,17 +334,16 @@ class TestingMixin( # URLs to the right place and enable http authentication if "developer_config.py" in self.config["config_files"]: return _urlopen_basic_auth(url, **kwargs) + # windows certificates need to be refreshed (https://bugs.python.org/issue36011) + elif self.platform_name() in ("win64",) and platform.architecture()[0] in ( + "x64", + ): + if self.ssl_context is None: + self.ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS) + self.ssl_context.load_default_certs() + return urllib.request.urlopen(url, context=self.ssl_context, **kwargs) else: - # windows certificates need to be refreshed (https://bugs.python.org/issue36011) - if self.platform_name() in ("win64",) and platform.architecture()[0] in ( - "x64", - ): - if self.ssl_context is None: - self.ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS) - self.ssl_context.load_default_certs() - return urllib.request.urlopen(url, context=self.ssl_context, **kwargs) - else: - return urllib.request.urlopen(url, **kwargs) + return urllib.request.urlopen(url, **kwargs) def _query_binary_version(self, regex, cmd): output = self.get_output_from_command(cmd, silent=False) diff --git a/testing/mozharness/scripts/desktop_partner_repacks.py b/testing/mozharness/scripts/desktop_partner_repacks.py @@ -86,7 +86,6 @@ class DesktopPartnerRepacks(AutomationMixin, BaseScript, VirtualenvMixin, Secret "workdir": "partner-repacks", }, } - # BaseScript.__init__( self, config_options=self.config_options, **buildscript_kwargs diff --git a/testing/mozharness/scripts/fx_desktop_build.py b/testing/mozharness/scripts/fx_desktop_build.py @@ -14,7 +14,7 @@ import sys # load modules from parent dir sys.path.insert(1, os.path.dirname(sys.path[0])) -import mozharness.base.script as script +from mozharness.base import script from mozharness.mozilla.building.buildbase import ( BUILD_BASE_CONFIG_OPTIONS, BuildingConfig, diff --git a/testing/mozharness/scripts/release/bouncer_check.py b/testing/mozharness/scripts/release/bouncer_check.py @@ -176,7 +176,7 @@ class BouncerCheck(BaseScript): yield url def check_bouncer(self): - import concurrent.futures as futures + from concurrent import futures import requests diff --git a/testing/mozharness/test/test_base_config.py b/testing/mozharness/test/test_base_config.py @@ -16,7 +16,7 @@ except ImportError: else: JSON_TYPE = "simplejson" -import mozharness.base.config as config +from mozharness.base import config MH_DIR = os.path.dirname(os.path.dirname(__file__)) diff --git a/testing/mozharness/test/test_base_log.py b/testing/mozharness/test/test_base_log.py @@ -2,8 +2,8 @@ import os import shutil import unittest -import mozharness.base.log as log import mozunit +from mozharness.base import log tmp_dir = "test_log_dir" log_name = "test" diff --git a/testing/mozharness/test/test_base_python.py b/testing/mozharness/test/test_base_python.py @@ -1,8 +1,8 @@ import os import unittest -import mozharness.base.python as python import mozunit +from mozharness.base import python here = os.path.dirname(os.path.abspath(__file__)) diff --git a/testing/mozharness/test/test_base_script.py b/testing/mozharness/test/test_base_script.py @@ -19,9 +19,7 @@ if os.name == "nt": pass -import mozharness.base.errors as errors -import mozharness.base.log as log -import mozharness.base.script as script +from mozharness.base import errors, log, script from mozharness.base.config import parse_config_file from mozharness.base.log import CRITICAL, DEBUG, ERROR, FATAL, IGNORE, INFO, WARNING diff --git a/testing/mozharness/test/test_base_vcs_mercurial.py b/testing/mozharness/test/test_base_vcs_mercurial.py @@ -4,8 +4,8 @@ import shutil import tempfile import unittest -import mozharness.base.vcs.mercurial as mercurial import mozunit +from mozharness.base.vcs import mercurial test_string = """foo bar diff --git a/testing/mozharness/test/test_l10n_locales.py b/testing/mozharness/test/test_l10n_locales.py @@ -3,9 +3,9 @@ import shutil import unittest from unittest import mock -import mozharness.base.script as script -import mozharness.mozilla.l10n.locales as locales import mozunit +from mozharness.base import script +from mozharness.mozilla.l10n import locales ALL_LOCALES = ["ar", "be", "de", "es-ES"] diff --git a/testing/raptor/browsertime/support-scripts/network_bench.py b/testing/raptor/browsertime/support-scripts/network_bench.py @@ -308,8 +308,7 @@ class NetworkBench(BasePythonSupport): bandwidth_kbps = bandwidth_mbit * 1_000 bdp_bits = bandwidth_kbps * rtt_ms bdp_bytes = bdp_bits / 8 - if bdp_bytes < 1500: - bdp_bytes = 1500 + bdp_bytes = max(bdp_bytes, 1500) return int(bdp_bytes) bandwidth_str, rtt_ms = self.network_type_to_bandwidth_rtt(network_type) diff --git a/testing/raptor/raptor/manifest.py b/testing/raptor/raptor/manifest.py @@ -441,11 +441,10 @@ def get_raptor_test_list(args, oskey): next_test["playback_pageset_manifest"], next_test["name"] ) - else: - if next_test.get("playback") is not None: - next_test["playback_pageset_manifest"] = transform_subtest( - next_test["playback_pageset_manifest"], next_test["name"] - ) + elif next_test.get("playback") is not None: + next_test["playback_pageset_manifest"] = transform_subtest( + next_test["playback_pageset_manifest"], next_test["name"] + ) # Check if either --gecko-profiler or --extra-profiler-run is enabled. if args.gecko_profile or ( diff --git a/testing/talos/talos/output.py b/testing/talos/talos/output.py @@ -169,11 +169,10 @@ class Output: if test.using_xperf: if len(vals) > 0: subtest["value"] = vals[0] - else: - # calculate mean value - if len(vals) > 0: - varray = [float(v) for v in vals] - subtest["value"] = filter.mean(varray) + # calculate mean value + elif len(vals) > 0: + varray = [float(v) for v in vals] + subtest["value"] = filter.mean(varray) if counter_subtests: suites.append( { diff --git a/testing/talos/talos/run_tests.py b/testing/talos/talos/run_tests.py @@ -73,20 +73,18 @@ def set_tp_preferences(test, browser_config): _pref_name = "talos.%s" % key if key in test: test["preferences"][_pref_name] = test.get(key) - else: - # current test doesn't use this setting, remove it from our prefs - if _pref_name in test["preferences"]: - del test["preferences"][_pref_name] + # current test doesn't use this setting, remove it from our prefs + elif _pref_name in test["preferences"]: + del test["preferences"][_pref_name] for key in CLI_options: value = test.get(key) _pref_name = "talos.%s" % key if value: test["preferences"][_pref_name] = value - else: - # current test doesn't use this setting, remove it from our prefs - if _pref_name in test["preferences"]: - del test["preferences"][_pref_name] + # current test doesn't use this setting, remove it from our prefs + elif _pref_name in test["preferences"]: + del test["preferences"][_pref_name] def setup_webserver(webserver): diff --git a/testing/talos/talos/xtalos/xperf_analyzer.py b/testing/talos/talos/xtalos/xperf_analyzer.py @@ -207,11 +207,10 @@ class XPerfInterval(XPerfAttribute): super().__init__([startevt, endevt], **kwargs) if not attrs: self.attrs_during_interval = [] + elif isinstance(attrs, list): + self.attrs_during_interval = attrs else: - if isinstance(attrs, list): - self.attrs_during_interval = attrs - else: - self.attrs_during_interval = [attrs] + self.attrs_during_interval = [attrs] def on_event_matched(self, evt): if evt == self.evtlist[0]: @@ -681,13 +680,12 @@ class ProcessStart(XPerfEvent): if quoted: if c == '"': quoted = False - else: - if c == '"': - quoted = True - elif c == " ": - result.append(current) - current = "" - continue + elif c == '"': + quoted = True + elif c == " ": + result.append(current) + current = "" + continue current += c diff --git a/testing/tps/tps/cli.py b/testing/tps/tps/cli.py @@ -122,13 +122,12 @@ def main(): extensionDir = os.path.join( os.getcwd(), "..", "..", "services", "sync", "tps", "extensions" ) - else: - if sys.platform == "win32": - # replace msys-style paths with proper Windows paths - m = re.match(r"^\/\w\/", extensionDir) - if m: - extensionDir = "%s:/%s" % (m.group(0)[1:2], extensionDir[3:]) - extensionDir = extensionDir.replace("/", "\\") + elif sys.platform == "win32": + # replace msys-style paths with proper Windows paths + m = re.match(r"^\/\w\/", extensionDir) + if m: + extensionDir = "%s:/%s" % (m.group(0)[1:2], extensionDir[3:]) + extensionDir = extensionDir.replace("/", "\\") if sys.platform == "darwin": # Needed to avoid tab crashes on mac due to level 3 sandboxing sourceRoot = os.path.join(extensionDir, "..", "..", "..", "..") diff --git a/testing/xpcshell/runxpcshelltests.py b/testing/xpcshell/runxpcshelltests.py @@ -1452,13 +1452,12 @@ class XPCShellTests: self.env["DYLD_LIBRARY_PATH"] = os.path.join( os.path.dirname(self.xrePath), "MacOS" ) - else: # unix or linux? - if "LD_LIBRARY_PATH" not in self.env or self.env["LD_LIBRARY_PATH"] is None: - self.env["LD_LIBRARY_PATH"] = self.xrePath - else: - self.env["LD_LIBRARY_PATH"] = ":".join( - [self.xrePath, self.env["LD_LIBRARY_PATH"]] - ) + elif "LD_LIBRARY_PATH" not in self.env or self.env["LD_LIBRARY_PATH"] is None: + self.env["LD_LIBRARY_PATH"] = self.xrePath + else: + self.env["LD_LIBRARY_PATH"] = ":".join( + [self.xrePath, self.env["LD_LIBRARY_PATH"]] + ) usingASan = "asan" in self.mozInfo and self.mozInfo["asan"] usingTSan = "tsan" in self.mozInfo and self.mozInfo["tsan"] @@ -1497,16 +1496,15 @@ class XPCShellTests: if self.interactive: pStdout = None pStderr = None + elif self.debuggerInfo and self.debuggerInfo.interactive: + pStdout = None + pStderr = None else: - if self.debuggerInfo and self.debuggerInfo.interactive: + if sys.platform == "os2emx": pStdout = None - pStderr = None else: - if sys.platform == "os2emx": - pStdout = None - else: - pStdout = PIPE - pStderr = STDOUT + pStdout = PIPE + pStderr = STDOUT return pStdout, pStderr def verifyDirPath(self, dirname): diff --git a/toolkit/components/extensions/webidl-api/GenerateWebIDLBindings.py b/toolkit/components/extensions/webidl-api/GenerateWebIDLBindings.py @@ -856,9 +856,8 @@ class APIEntry: return [] if "allowedContexts" in self.schema_data_by_group[schema_group]: return self.schema_data_by_group[schema_group]["allowedContexts"] - else: - if "allowedContexts" in self.schema_data_list[0]: - return self.schema_data_list[0]["allowedContexts"] + elif "allowedContexts" in self.schema_data_list[0]: + return self.schema_data_list[0]["allowedContexts"] if self.parent: return self.parent.default_contexts diff --git a/toolkit/components/telemetry/tests/python/test_mirrors.py b/toolkit/components/telemetry/tests/python/test_mirrors.py @@ -27,8 +27,8 @@ from run_glean_parser import GIFFT_TYPES MIRROR_TYPES = { metric_type: [ probe_type - for probe_type in GIFFT_TYPES.keys() - if metric_type in GIFFT_TYPES[probe_type] + for probe_type, probe_metric_types in GIFFT_TYPES.items() + if metric_type in probe_metric_types ] for (probe_type, metric_types) in GIFFT_TYPES.items() for metric_type in metric_types diff --git a/tools/browsertime/mach_commands.py b/tools/browsertime/mach_commands.py @@ -679,9 +679,8 @@ def browsertime( should_clobber=clobber, install_vismet_reqs=install_vismet_reqs, ) - else: - if not _verify_node_install(command_context): - return 1 + elif not _verify_node_install(command_context): + return 1 if check_browsertime: return check(command_context) diff --git a/tools/fuzzing/smoke/smoke.py b/tools/fuzzing/smoke/smoke.py @@ -34,9 +34,8 @@ def run_jsshell(command, label=None): shell = shutil.which("js") if shell is None: raise FileNotFoundError(shell) - else: - if not os.path.exists(shell) or not os.path.isfile(shell): - raise FileNotFoundError(shell) + elif not os.path.exists(shell) or not os.path.isfile(shell): + raise FileNotFoundError(shell) if label is None: label = command diff --git a/tools/lint/file-whitespace/__init__.py b/tools/lint/file-whitespace/__init__.py @@ -92,9 +92,8 @@ def lint(paths, config, fix=None, **lintargs): "lineno": i + 1, } results.append(result.from_config(config, **res)) - else: - if fix: - content_to_write.append(line) + elif fix: + content_to_write.append(line) if hasFix: # Only update the file when we found a change to make with open(f, "wb") as open_file_to_write: diff --git a/tools/mach_commands.py b/tools/mach_commands.py @@ -189,12 +189,11 @@ class PypiBasedTool: "%s was updated to version %s. please" " re-run your command." % (self.pypi_name, release) ) + # Tool is up to date, return the parser. + elif subcommand: + return tool.parser(subcommand) else: - # Tool is up to date, return the parser. - if subcommand: - return tool.parser(subcommand) - else: - return tool.parser() + return tool.parser() # exit if we updated or installed mozregression because # we may have already imported mozregression and running it # as this may cause issues. diff --git a/tools/tryselect/util/dicttools.py b/tools/tryselect/util/dicttools.py @@ -20,7 +20,7 @@ def merge_to(source, dest): for key, value in source.items(): # Override mismatching or empty types if type(value) != type(dest.get(key)): # noqa - dest[key] = source[key] + dest[key] = value continue # Merge dict @@ -29,10 +29,10 @@ def merge_to(source, dest): continue if isinstance(value, list): - dest[key] = dest[key] + source[key] + dest[key] = dest[key] + value continue - dest[key] = source[key] + dest[key] = value return dest diff --git a/tools/vcs/mach_commands.py b/tools/vcs/mach_commands.py @@ -200,7 +200,6 @@ def _split_patches(patchfile, bug_number, pull_request, reviewer): patch += line + b"\n" if len(patch) > 0: yield _parse_patch(patch, bug_number, pull_request, reviewer) - return def _parse_patch(patch, bug_number, pull_request, reviewer):