From 6ec972f4dbb880bf0c7a11809e6c1ba194c9784c Mon Sep 17 00:00:00 2001 From: Lars Holmberg Date: Fri, 25 Feb 2022 15:06:08 +0100 Subject: [PATCH 1/3] Ran pyupgrade on the code base, removing various "Python2-isms". --- benchmarks/dispatch.py | 12 ++--- docs/conf.py | 1 - examples/custom_messages.py | 2 +- examples/custom_shape/wait_user_count.py | 4 +- examples/events.py | 2 - examples/extend_web_ui/extend.py | 6 +-- examples/grpc/hello_pb2.py | 1 - examples/grpc/hello_pb2_grpc.py | 6 +-- .../session_patch_locustfile.py | 2 +- locust/argument_parser.py | 2 +- locust/clients.py | 2 +- locust/contrib/fasthttp.py | 2 +- locust/dispatch.py | 2 +- locust/env.py | 2 +- locust/html.py | 2 +- locust/log.py | 2 +- locust/main.py | 12 ++--- locust/rpc/protocol.py | 2 +- locust/runners.py | 7 +-- locust/stats.py | 12 ++--- locust/test/test_dispatch.py | 48 +++++-------------- locust/test/test_fasthttp.py | 2 +- locust/test/test_http.py | 2 +- locust/test/test_log.py | 2 +- locust/test/test_parser.py | 2 +- locust/test/test_runners.py | 16 +++---- locust/test/test_stats.py | 10 ++-- locust/test/test_tags.py | 34 ++++++------- locust/test/test_web.py | 7 ++- locust/test/testcases.py | 2 +- locust/user/inspectuser.py | 4 +- locust/user/task.py | 2 +- locust/user/users.py | 2 +- locust/util/cache.py | 2 - locust/web.py | 4 +- setup.py | 1 - 36 files changed, 91 insertions(+), 132 deletions(-) diff --git a/benchmarks/dispatch.py b/benchmarks/dispatch.py index f88a4e9643..3c5fed2fbc 100644 --- a/benchmarks/dispatch.py +++ b/benchmarks/dispatch.py @@ -539,7 +539,7 @@ class User100(User): itertools.product(worker_count_cases, user_count_cases, number_of_user_classes_cases, spawn_rate_cases) ): if user_count / spawn_rate > 1000: - print("Skipping user_count = {:,} - spawn_rate = {:,}".format(user_count, spawn_rate)) + print(f"Skipping user_count = {user_count:,} - spawn_rate = {spawn_rate:,}") continue workers = [WorkerNode(str(i + 1)) for i in range(worker_count)] @@ -614,10 +614,10 @@ class User100(User): table.add_rows( [ [ - "{:,}".format(worker_count), - "{:,}".format(user_count), + f"{worker_count:,}", + f"{user_count:,}", number_of_user_classes, - "{:,}".format(spawn_rate), + f"{spawn_rate:,}", cpu_ramp_up, cpu_ramp_down, ] @@ -632,8 +632,8 @@ class User100(User): print() print(table) - with open("results-dispatch-benchmarks-{}.txt".format(int(now)), "wt") as file: + with open(f"results-dispatch-benchmarks-{int(now)}.txt", "wt") as file: file.write(table.get_string()) - with open("results-dispatch-benchmarks-{}.json".format(int(now)), "wt") as file: + with open(f"results-dispatch-benchmarks-{int(now)}.json", "wt") as file: file.write(table.get_json_string()) diff --git a/docs/conf.py b/docs/conf.py index 27aa7e810e..f08aa4c3bb 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # This file is execfile()d with the current directory set to its containing dir. # diff --git a/examples/custom_messages.py b/examples/custom_messages.py index 3b12124781..31dd13f990 100644 --- a/examples/custom_messages.py +++ b/examples/custom_messages.py @@ -53,7 +53,7 @@ class WebsiteUser(HttpUser): def __init__(self, parent): self.username = usernames.pop() - super(WebsiteUser, self).__init__(parent) + super().__init__(parent) @task def task(self): diff --git a/examples/custom_shape/wait_user_count.py b/examples/custom_shape/wait_user_count.py index 1b5805c4a7..adef325c7c 100644 --- a/examples/custom_shape/wait_user_count.py +++ b/examples/custom_shape/wait_user_count.py @@ -23,7 +23,7 @@ def __init__(self, *args, **kwargs): # the User has a slow initialization for gathering data to randomly # select. time.sleep(random.randint(0, 5)) - super(WebsiteUser, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) Step = namedtuple("Step", ["users", "dwell"]) @@ -50,7 +50,7 @@ class StepLoadShape(LoadTestShape): def __init__(self, *args, **kwargs): self.step = 0 self.time_active = False - super(StepLoadShape, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def tick(self): if self.step >= len(self.targets_with_times): diff --git a/examples/events.py b/examples/events.py index dc312bf914..48de0b2933 100644 --- a/examples/events.py +++ b/examples/events.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ This is an example of a locustfile that uses Locust's built in event hooks to track the sum of the content-length header in all successful HTTP responses diff --git a/examples/extend_web_ui/extend.py b/examples/extend_web_ui/extend.py index a897289514..1caa2cf0b9 100644 --- a/examples/extend_web_ui/extend.py +++ b/examples/extend_web_ui/extend.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ This is an example of a locustfile that uses Locust's built in event and web UI extension hooks to track the sum of the content-length header in all @@ -91,8 +89,8 @@ def request_content_length_csv(): Add route to enable downloading of content-length stats as CSV """ response = make_response(content_length_csv()) - file_name = "content_length{0}.csv".format(time()) - disposition = "attachment;filename={0}".format(file_name) + file_name = f"content_length{time()}.csv" + disposition = f"attachment;filename={file_name}" response.headers["Content-type"] = "text/csv" response.headers["Content-disposition"] = disposition return response diff --git a/examples/grpc/hello_pb2.py b/examples/grpc/hello_pb2.py index 8bf74a3835..5cd7cd7ca8 100644 --- a/examples/grpc/hello_pb2.py +++ b/examples/grpc/hello_pb2.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: hello.proto """Generated protocol buffer code.""" diff --git a/examples/grpc/hello_pb2_grpc.py b/examples/grpc/hello_pb2_grpc.py index 5f523bf0b0..380e3ab537 100644 --- a/examples/grpc/hello_pb2_grpc.py +++ b/examples/grpc/hello_pb2_grpc.py @@ -5,7 +5,7 @@ import hello_pb2 as hello__pb2 -class HelloServiceStub(object): +class HelloServiceStub: """Missing associated documentation comment in .proto file.""" def __init__(self, channel): @@ -21,7 +21,7 @@ def __init__(self, channel): ) -class HelloServiceServicer(object): +class HelloServiceServicer: """Missing associated documentation comment in .proto file.""" def SayHello(self, request, context): @@ -44,7 +44,7 @@ def add_HelloServiceServicer_to_server(servicer, server): # This class is part of an EXPERIMENTAL API. -class HelloService(object): +class HelloService: """Missing associated documentation comment in .proto file.""" @staticmethod diff --git a/examples/sdk_session_patching/session_patch_locustfile.py b/examples/sdk_session_patching/session_patch_locustfile.py index 936e0c3235..e971219ae9 100644 --- a/examples/sdk_session_patching/session_patch_locustfile.py +++ b/examples/sdk_session_patching/session_patch_locustfile.py @@ -7,7 +7,7 @@ class ArchivistUser(locust.HttpUser): def on_start(self): AUTH_TOKEN = None - with open("auth.text", "r") as f: + with open("auth.text") as f: AUTH_TOKEN = f.read() # Start an instance of of the SDK diff --git a/locust/argument_parser.py b/locust/argument_parser.py index 41ce86ab05..f5b3ca1391 100644 --- a/locust/argument_parser.py +++ b/locust/argument_parser.py @@ -452,7 +452,7 @@ def setup_parser_arguments(parser): "-V", action="version", help="Show program's version number and exit", - version="%(prog)s {}".format(version), + version=f"%(prog)s {version}", ) other_group.add_argument( "--exit-code-on-error", diff --git a/locust/clients.py b/locust/clients.py index 8228e96d95..535933081f 100644 --- a/locust/clients.py +++ b/locust/clients.py @@ -75,7 +75,7 @@ def _build_url(self, path): if absolute_http_url_regexp.match(path): return path else: - return "%s%s" % (self.base_url, path) + return f"{self.base_url}{path}" @contextmanager def rename_request(self, name: str): diff --git a/locust/contrib/fasthttp.py b/locust/contrib/fasthttp.py index e81722dbd7..ad07380c16 100644 --- a/locust/contrib/fasthttp.py +++ b/locust/contrib/fasthttp.py @@ -99,7 +99,7 @@ def _build_url(self, path): if absolute_http_url_regexp.match(path): return path else: - return "%s%s" % (self.base_url, path) + return f"{self.base_url}{path}" def _send_request_safe_mode(self, method, url, **kwargs): """ diff --git a/locust/dispatch.py b/locust/dispatch.py index 3c9e703dba..0459738d93 100644 --- a/locust/dispatch.py +++ b/locust/dispatch.py @@ -355,7 +355,7 @@ def infinite_cycle_gen(users: List[Tuple[User, int]]) -> Generator[Optional[str] normalized_values = [ ( user.__name__, - round(target_min_weight * value / min([u[1] for u in users])), + round(target_min_weight * value / min(u[1] for u in users)), ) for user, value in users ] diff --git a/locust/env.py b/locust/env.py index a51f9e326c..3efe05ec03 100644 --- a/locust/env.py +++ b/locust/env.py @@ -92,7 +92,7 @@ def __init__( self._remove_user_classes_with_weight_zero() # Validate there's no class with the same name but in different modules - if len(set(user_class.__name__ for user_class in self.user_classes)) != len(self.user_classes): + if len({user_class.__name__ for user_class in self.user_classes}) != len(self.user_classes): raise ValueError( "The following user classes have the same class name: {}".format( ", ".join(map(methodcaller("fullname"), self.user_classes)) diff --git a/locust/html.py b/locust/html.py index 4970432685..46a7052220 100644 --- a/locust/html.py +++ b/locust/html.py @@ -33,7 +33,7 @@ def get_html_report(environment, show_download_link=True): if environment.host: host = environment.host elif environment.runner.user_classes: - all_hosts = set([l.host for l in environment.runner.user_classes]) + all_hosts = {l.host for l in environment.runner.user_classes} if len(all_hosts) == 1: host = list(all_hosts)[0] diff --git a/locust/log.py b/locust/log.py index 5336da765c..cfd93f5b9d 100644 --- a/locust/log.py +++ b/locust/log.py @@ -17,7 +17,7 @@ def setup_logging(loglevel, logfile=None): "disable_existing_loggers": False, "formatters": { "default": { - "format": "[%(asctime)s] {0}/%(levelname)s/%(name)s: %(message)s".format(HOSTNAME), + "format": f"[%(asctime)s] {HOSTNAME}/%(levelname)s/%(name)s: %(message)s", }, "plain": { "format": "%(message)s", diff --git a/locust/main.py b/locust/main.py index 367b49dfca..883c20ef55 100644 --- a/locust/main.py +++ b/locust/main.py @@ -196,11 +196,9 @@ def main(): resource.setrlimit(resource.RLIMIT_NOFILE, [minimum_open_file_limit, resource.RLIM_INFINITY]) except BaseException: logger.warning( - ( - f"System open file limit '{current_open_file_limit}' is below minimum setting '{minimum_open_file_limit}'. " - "It's not high enough for load testing, and the OS didn't allow locust to increase it by itself. " - "See https://github.com/locustio/locust/wiki/Installation#increasing-maximum-number-of-open-files-limit for more info." - ) + f"""System open file limit '{current_open_file_limit}' is below minimum setting '{minimum_open_file_limit}'. +It's not high enough for load testing, and the OS didn't allow locust to increase it by itself. +See https://github.com/locustio/locust/wiki/Installation#increasing-maximum-number-of-open-files-limit for more info.""" ) # create locust Environment @@ -237,7 +235,7 @@ def main(): try: runner = environment.create_worker_runner(options.master_host, options.master_port) logger.debug("Connected to locust master: %s:%s", options.master_host, options.master_port) - except socket.error as e: + except OSError as e: logger.error("Failed to connect to the Locust master: %s", e) sys.exit(-1) else: @@ -274,7 +272,7 @@ def main(): else: web_host = options.web_host if web_host: - logger.info("Starting web interface at %s://%s:%s" % (protocol, web_host, options.web_port)) + logger.info(f"Starting web interface at {protocol}://{web_host}:{options.web_port}") else: logger.info( "Starting web interface at %s://0.0.0.0:%s (accepting connections from all network interfaces)" diff --git a/locust/rpc/protocol.py b/locust/rpc/protocol.py index 008e5dda09..d53e91e361 100644 --- a/locust/rpc/protocol.py +++ b/locust/rpc/protocol.py @@ -8,7 +8,7 @@ def __init__(self, message_type, data, node_id): self.node_id = node_id def __repr__(self): - return "" % (self.type, self.node_id) + return f"" def serialize(self): return msgpack.dumps((self.type, self.data, self.node_id)) diff --git a/locust/runners.py b/locust/runners.py index 2410f42d2b..52f0b4eeaa 100644 --- a/locust/runners.py +++ b/locust/runners.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import functools import json import logging @@ -765,7 +764,7 @@ def start(self, user_count: int, spawn_rate: float, wait=False) -> None: self.environment.events.spawning_complete.fire(user_count=sum(self.target_user_classes_count.values())) self.spawning_completed = True - logger.info("%s: %s" % (msg_prefix, _format_user_classes_count_for_log(self.reported_user_classes_count))) + logger.info(f"{msg_prefix}: {_format_user_classes_count_for_log(self.reported_user_classes_count)}") @functools.lru_cache() def _wait_for_workers_report_after_ramp_up(self) -> float: @@ -930,9 +929,7 @@ def client_listener(self): c.heartbeat = HEARTBEAT_LIVENESS client_state = msg.data["state"] if c.state == STATE_MISSING: - logger.info( - "Worker %s self-healed with heartbeat, setting state to %s." % (str(c.id), client_state) - ) + logger.info(f"Worker {str(c.id)} self-healed with heartbeat, setting state to {client_state}.") if self._users_dispatcher is not None: self._users_dispatcher.add_worker(worker_node=c) if not self._users_dispatcher.dispatch_in_progress and self.state == STATE_RUNNING: diff --git a/locust/stats.py b/locust/stats.py index e565f8937b..324bf73715 100644 --- a/locust/stats.py +++ b/locust/stats.py @@ -89,7 +89,7 @@ def calculate_response_time_percentile(response_times, num_requests, percent): but we save some CPU cycles by using the value which we already store) percent: The percentile we want to calculate. Specified in range: 0.0 - 1.0 """ - num_of_request = int((num_requests * percent)) + num_of_request = int(num_requests * percent) processed_count = 0 for response_time in sorted(response_times.keys(), reverse=True): @@ -207,7 +207,7 @@ def serialize_stats(self): ] def serialize_errors(self): - return dict([(k, e.to_dict()) for k, e in self.errors.items()]) + return {k: e.to_dict() for k, e in self.errors.items()} class StatsEntry: @@ -598,7 +598,7 @@ def percentile(self): return tpl % ( (self.method, self.name) - + tuple([self.get_response_time_percentile(p) for p in PERCENTILES_TO_REPORT]) + + tuple(self.get_response_time_percentile(p) for p in PERCENTILES_TO_REPORT) + (self.num_requests,) ) @@ -643,7 +643,7 @@ def parse_error(cls, error): @classmethod def create_key(cls, method, name, error): - key = "%s.%s.%r" % (method, name, StatsError.parse_error(error)) + key = f"{method}.{name}.{StatsError.parse_error(error)!r}" return hashlib.md5(key.encode("utf-8")).hexdigest() def occurred(self): @@ -662,7 +662,7 @@ def to_name(self): # standalone, unwrapped exception unwrapped_error = repr(error) - return "%s %s: %s" % (self.method, self.name, unwrapped_error) + return f"{self.method} {self.name}: {unwrapped_error}" def to_dict(self): return { @@ -973,7 +973,7 @@ def stats_writer(self): self._failures_data_rows(self.failures_csv_writer) self.failures_csv_filehandle.truncate() - self.exceptions_csv_filehandle.seek((self.exceptions_csv_data_start)) + self.exceptions_csv_filehandle.seek(self.exceptions_csv_data_start) self._exceptions_data_rows(self.exceptions_csv_writer) self.exceptions_csv_filehandle.truncate() diff --git a/locust/test/test_dispatch.py b/locust/test/test_dispatch.py index 5ae192e645..0435b576eb 100644 --- a/locust/test/test_dispatch.py +++ b/locust/test/test_dispatch.py @@ -2333,9 +2333,7 @@ class User3(User): ts = time.perf_counter() dispatched_users = next(users_dispatcher) delta = time.perf_counter() - ts - self.assertTrue( - 0 <= delta <= _TOLERANCE, "Expected re-balance dispatch to be instantaneous but got {}s".format(delta) - ) + self.assertTrue(0 <= delta <= _TOLERANCE, f"Expected re-balance dispatch to be instantaneous but got {delta}s") self.assertDictEqual(_aggregate_dispatched_users(dispatched_users), {"User1": 2, "User2": 2, "User3": 2}) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[0].id), 3) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[2].id), 3) @@ -2403,9 +2401,7 @@ class User3(User): ts = time.perf_counter() dispatched_users = next(users_dispatcher) delta = time.perf_counter() - ts - self.assertTrue( - 0 <= delta <= _TOLERANCE, "Expected re-balance dispatch to be instantaneous but got {}s".format(delta) - ) + self.assertTrue(0 <= delta <= _TOLERANCE, f"Expected re-balance dispatch to be instantaneous but got {delta}s") self.assertDictEqual(_aggregate_dispatched_users(dispatched_users), {"User1": 2, "User2": 2, "User3": 2}) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[0].id), 6) @@ -2457,9 +2453,7 @@ class User3(User): ts = time.perf_counter() dispatched_users = next(users_dispatcher) delta = time.perf_counter() - ts - self.assertTrue( - 0 <= delta <= _TOLERANCE, "Expected re-balance dispatch to be instantaneous but got {}s".format(delta) - ) + self.assertTrue(0 <= delta <= _TOLERANCE, f"Expected re-balance dispatch to be instantaneous but got {delta}s") self.assertDictEqual(_aggregate_dispatched_users(dispatched_users), {"User1": 3, "User2": 3, "User3": 3}) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[0].id), 5) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[2].id), 4) @@ -2532,9 +2526,7 @@ class User3(User): ts = time.perf_counter() dispatched_users = next(users_dispatcher) delta = time.perf_counter() - ts - self.assertTrue( - 0 <= delta <= _TOLERANCE, "Expected re-balance dispatch to be instantaneous but got {}s".format(delta) - ) + self.assertTrue(0 <= delta <= _TOLERANCE, f"Expected re-balance dispatch to be instantaneous but got {delta}s") self.assertDictEqual(_aggregate_dispatched_users(dispatched_users), {"User1": 3, "User2": 3, "User3": 3}) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[0].id), 9) @@ -2619,9 +2611,7 @@ class User3(User): ts = time.perf_counter() dispatched_users = next(users_dispatcher) delta = time.perf_counter() - ts - self.assertTrue( - 0 <= delta <= _TOLERANCE, "Expected re-balance dispatch to be instantaneous but got {}s".format(delta) - ) + self.assertTrue(0 <= delta <= _TOLERANCE, f"Expected re-balance dispatch to be instantaneous but got {delta}s") self.assertDictEqual(_aggregate_dispatched_users(dispatched_users), {"User1": 4, "User2": 4, "User3": 4}) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[0].id), 6) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[2].id), 6) @@ -2693,9 +2683,7 @@ class User3(User): ts = time.perf_counter() dispatched_users = next(users_dispatcher) delta = time.perf_counter() - ts - self.assertTrue( - 0 <= delta <= _TOLERANCE, "Expected re-balance dispatch to be instantaneous but got {}s".format(delta) - ) + self.assertTrue(0 <= delta <= _TOLERANCE, f"Expected re-balance dispatch to be instantaneous but got {delta}s") self.assertDictEqual(_aggregate_dispatched_users(dispatched_users), {"User1": 4, "User2": 4, "User3": 4}) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[0].id), 12) @@ -2799,9 +2787,7 @@ class User3(User): ts = time.perf_counter() dispatched_users = next(users_dispatcher) delta = time.perf_counter() - ts - self.assertTrue( - 0 <= delta <= _TOLERANCE, "Expected re-balance dispatch to be instantaneous but got {}s".format(delta) - ) + self.assertTrue(0 <= delta <= _TOLERANCE, f"Expected re-balance dispatch to be instantaneous but got {delta}s") self.assertDictEqual(_aggregate_dispatched_users(dispatched_users), {"User1": 2, "User2": 2, "User3": 2}) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[0].id), 2) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[1].id), 2) @@ -2878,9 +2864,7 @@ class User3(User): ts = time.perf_counter() dispatched_users = next(users_dispatcher) delta = time.perf_counter() - ts - self.assertTrue( - 0 <= delta <= _TOLERANCE, "Expected re-balance dispatch to be instantaneous but got {}s".format(delta) - ) + self.assertTrue(0 <= delta <= _TOLERANCE, f"Expected re-balance dispatch to be instantaneous but got {delta}s") self.assertDictEqual(_aggregate_dispatched_users(dispatched_users), {"User1": 2, "User2": 2, "User3": 2}) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[0].id), 2) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[1].id), 2) @@ -2936,9 +2920,7 @@ class User3(User): ts = time.perf_counter() dispatched_users = next(users_dispatcher) delta = time.perf_counter() - ts - self.assertTrue( - 0 <= delta <= _TOLERANCE, "Expected re-balance dispatch to be instantaneous but got {}s".format(delta) - ) + self.assertTrue(0 <= delta <= _TOLERANCE, f"Expected re-balance dispatch to be instantaneous but got {delta}s") self.assertDictEqual(_aggregate_dispatched_users(dispatched_users), {"User1": 3, "User2": 3, "User3": 3}) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[0].id), 3) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[1].id), 3) @@ -3015,9 +2997,7 @@ class User3(User): ts = time.perf_counter() dispatched_users = next(users_dispatcher) delta = time.perf_counter() - ts - self.assertTrue( - 0 <= delta <= _TOLERANCE, "Expected re-balance dispatch to be instantaneous but got {}s".format(delta) - ) + self.assertTrue(0 <= delta <= _TOLERANCE, f"Expected re-balance dispatch to be instantaneous but got {delta}s") self.assertDictEqual(_aggregate_dispatched_users(dispatched_users), {"User1": 3, "User2": 3, "User3": 3}) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[0].id), 3) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[1].id), 3) @@ -3108,9 +3088,7 @@ class User3(User): ts = time.perf_counter() dispatched_users = next(users_dispatcher) delta = time.perf_counter() - ts - self.assertTrue( - 0 <= delta <= _TOLERANCE, "Expected re-balance dispatch to be instantaneous but got {}s".format(delta) - ) + self.assertTrue(0 <= delta <= _TOLERANCE, f"Expected re-balance dispatch to be instantaneous but got {delta}s") self.assertDictEqual(_aggregate_dispatched_users(dispatched_users), {"User1": 4, "User2": 4, "User3": 4}) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[0].id), 4) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[1].id), 4) @@ -3180,9 +3158,7 @@ class User3(User): ts = time.perf_counter() dispatched_users = next(users_dispatcher) delta = time.perf_counter() - ts - self.assertTrue( - 0 <= delta <= _TOLERANCE, "Expected re-balance dispatch to be instantaneous but got {}s".format(delta) - ) + self.assertTrue(0 <= delta <= _TOLERANCE, f"Expected re-balance dispatch to be instantaneous but got {delta}s") self.assertDictEqual(_aggregate_dispatched_users(dispatched_users), {"User1": 4, "User2": 4, "User3": 4}) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[0].id), 4) self.assertEqual(_user_count_on_worker(dispatched_users, worker_nodes[1].id), 4) diff --git a/locust/test/test_fasthttp.py b/locust/test/test_fasthttp.py index ae92be4068..7e92101a16 100644 --- a/locust/test/test_fasthttp.py +++ b/locust/test/test_fasthttp.py @@ -111,7 +111,7 @@ def test_options(self): self.assertEqual(200, r.status_code) self.assertEqual("", r.content.decode()) self.assertEqual( - set(["OPTIONS", "DELETE", "PUT", "GET", "POST", "HEAD", "PATCH"]), + {"OPTIONS", "DELETE", "PUT", "GET", "POST", "HEAD", "PATCH"}, set(r.headers["allow"].split(", ")), ) diff --git a/locust/test/test_http.py b/locust/test/test_http.py index fbdf049f2d..9be3241f4f 100644 --- a/locust/test/test_http.py +++ b/locust/test/test_http.py @@ -104,7 +104,7 @@ def test_options(self): self.assertEqual(200, r.status_code) self.assertEqual("", r.content.decode()) self.assertEqual( - set(["OPTIONS", "DELETE", "PUT", "GET", "POST", "HEAD", "PATCH"]), + {"OPTIONS", "DELETE", "PUT", "GET", "POST", "HEAD", "PATCH"}, set(r.headers["allow"].split(", ")), ) diff --git a/locust/test/test_log.py b/locust/test/test_log.py index 8c72ab5086..4f433f1f0d 100644 --- a/locust/test/test_log.py +++ b/locust/test/test_log.py @@ -1,4 +1,4 @@ -import mock +from unittest import mock import socket import subprocess import textwrap diff --git a/locust/test/test_parser.py b/locust/test/test_parser.py index e674c7d61f..2465627e41 100644 --- a/locust/test/test_parser.py +++ b/locust/test/test_parser.py @@ -1,7 +1,7 @@ import unittest import os import tempfile -import mock +from unittest import mock from io import StringIO import locust diff --git a/locust/test/test_runners.py b/locust/test/test_runners.py index b91b774a92..8981105e17 100644 --- a/locust/test/test_runners.py +++ b/locust/test/test_runners.py @@ -8,7 +8,7 @@ from operator import itemgetter import gevent -import mock +from unittest import mock import requests from gevent import sleep from gevent.pool import Group @@ -575,7 +575,7 @@ def my_task(self): ts = time.perf_counter() response = requests.post( - "http://127.0.0.1:{}/swarm".format(web_ui.server.server_port), + f"http://127.0.0.1:{web_ui.server.server_port}/swarm", data={"user_count": 20, "spawn_rate": 5, "host": "https://localhost"}, ) self.assertEqual(200, response.status_code) @@ -613,7 +613,7 @@ def my_task(self): ts = time.perf_counter() response = requests.post( - "http://127.0.0.1:{}/swarm".format(web_ui.server.server_port), + f"http://127.0.0.1:{web_ui.server.server_port}/swarm", data={"user_count": 20, "spawn_rate": 1, "host": "https://localhost"}, ) self.assertEqual(200, response.status_code) @@ -626,7 +626,7 @@ def my_task(self): ts = time.perf_counter() response = requests.get( - "http://127.0.0.1:{}/stop".format(web_ui.server.server_port), + f"http://127.0.0.1:{web_ui.server.server_port}/stop", ) self.assertEqual(200, response.status_code) self.assertTrue(stop_timeout <= time.perf_counter() - ts <= stop_timeout + 5, "stop endpoint took too long") @@ -1642,7 +1642,7 @@ def my_task(self): ts = time.perf_counter() response = requests.post( - "http://127.0.0.1:{}/swarm".format(web_ui.server.server_port), + f"http://127.0.0.1:{web_ui.server.server_port}/swarm", data={"user_count": 20, "spawn_rate": 5, "host": "https://localhost"}, ) self.assertEqual(200, response.status_code) @@ -1691,7 +1691,7 @@ def my_task(self): ts = time.perf_counter() response = requests.post( - "http://127.0.0.1:{}/swarm".format(web_ui.server.server_port), + f"http://127.0.0.1:{web_ui.server.server_port}/swarm", data={"user_count": 20, "spawn_rate": 1, "host": "https://localhost"}, ) self.assertEqual(200, response.status_code) @@ -1704,7 +1704,7 @@ def my_task(self): ts = time.perf_counter() response = requests.get( - "http://127.0.0.1:{}/stop".format(web_ui.server.server_port), + f"http://127.0.0.1:{web_ui.server.server_port}/stop", ) self.assertEqual(200, response.status_code) self.assertTrue(stop_timeout <= time.perf_counter() - ts <= stop_timeout + 5, "stop endpoint took too long") @@ -2904,7 +2904,7 @@ def my_task(self): self.assertLessEqual(time.perf_counter() - t0, 3) sleep(0.1) - message = next((m for m in reversed(client.outbox) if m.type == "heartbeat")) + message = next(m for m in reversed(client.outbox) if m.type == "heartbeat") self.assertEqual(len(message.data), 3) self.assertIn("state", message.data) self.assertIn("current_cpu_usage", message.data) diff --git a/locust/test/test_stats.py b/locust/test/test_stats.py index 94b9b05674..ea61fcba18 100644 --- a/locust/test/test_stats.py +++ b/locust/test/test_stats.py @@ -6,7 +6,7 @@ import json import gevent -import mock +from unittest import mock import locust from locust import HttpUser, TaskSet, task, User, constant, __version__ from locust.env import Environment @@ -319,10 +319,10 @@ def test_print_percentile_stats(self): class TestCsvStats(LocustTestCase): STATS_BASE_NAME = "test" - STATS_FILENAME = "{}_stats.csv".format(STATS_BASE_NAME) - STATS_HISTORY_FILENAME = "{}_stats_history.csv".format(STATS_BASE_NAME) - STATS_FAILURES_FILENAME = "{}_failures.csv".format(STATS_BASE_NAME) - STATS_EXCEPTIONS_FILENAME = "{}_exceptions.csv".format(STATS_BASE_NAME) + STATS_FILENAME = f"{STATS_BASE_NAME}_stats.csv" + STATS_HISTORY_FILENAME = f"{STATS_BASE_NAME}_stats_history.csv" + STATS_FAILURES_FILENAME = f"{STATS_BASE_NAME}_failures.csv" + STATS_EXCEPTIONS_FILENAME = f"{STATS_BASE_NAME}_exceptions.csv" def setUp(self): super().setUp() diff --git a/locust/test/test_tags.py b/locust/test/test_tags.py index f889ff41b9..636c51d33c 100644 --- a/locust/test/test_tags.py +++ b/locust/test/test_tags.py @@ -12,7 +12,7 @@ def tagged(): pass self.assertIn("locust_tag_set", dir(tagged)) - self.assertEqual(set(["tag1"]), tagged.locust_tag_set) + self.assertEqual({"tag1"}, tagged.locust_tag_set) @tag("tag2", "tag3") @task @@ -20,7 +20,7 @@ def tagged_multiple_args(): pass self.assertIn("locust_tag_set", dir(tagged_multiple_args)) - self.assertEqual(set(["tag2", "tag3"]), tagged_multiple_args.locust_tag_set) + self.assertEqual({"tag2", "tag3"}, tagged_multiple_args.locust_tag_set) @tag("tag4") @tag("tag5") @@ -29,7 +29,7 @@ def tagged_multiple_times(): pass self.assertIn("locust_tag_set", dir(tagged_multiple_times)) - self.assertEqual(set(["tag4", "tag5"]), tagged_multiple_times.locust_tag_set) + self.assertEqual({"tag4", "tag5"}, tagged_multiple_times.locust_tag_set) def test_tagging_taskset(self): @tag("taskset") @@ -53,15 +53,15 @@ def nested_task(self): # when tagging taskset, its tasks receive the tag self.assertIn("locust_tag_set", dir(MyTaskSet.tagged)) - self.assertEqual(set(["taskset"]), MyTaskSet.tagged.locust_tag_set) + self.assertEqual({"taskset"}, MyTaskSet.tagged.locust_tag_set) # tagging inner task receives both self.assertIn("locust_tag_set", dir(MyTaskSet.tagged_again)) - self.assertEqual(set(["taskset", "task"]), MyTaskSet.tagged_again.locust_tag_set) + self.assertEqual({"taskset", "task"}, MyTaskSet.tagged_again.locust_tag_set) # when tagging nested taskset, its tasks receives both self.assertIn("locust_tag_set", dir(MyTaskSet.NestedTaskSet.nested_task)) - self.assertEqual(set(["taskset", "taskset2"]), MyTaskSet.NestedTaskSet.nested_task.locust_tag_set) + self.assertEqual({"taskset", "taskset2"}, MyTaskSet.NestedTaskSet.nested_task.locust_tag_set) def test_tagging_without_args_fails(self): @task @@ -94,7 +94,7 @@ def dont_include_this_either(self): MyTaskSet.tasks, [MyTaskSet.included, MyTaskSet.not_included, MyTaskSet.dont_include_this_either] ) - filter_tasks_by_tags(MyTaskSet, tags=set(["include this"])) + filter_tasks_by_tags(MyTaskSet, tags={"include this"}) self.assertListEqual(MyTaskSet.tasks, [MyTaskSet.included]) def test_excluding_tags(self): @@ -117,7 +117,7 @@ def dont_exclude_this_either(self): MyTaskSet.tasks, [MyTaskSet.excluded, MyTaskSet.not_excluded, MyTaskSet.dont_exclude_this_either] ) - filter_tasks_by_tags(MyTaskSet, exclude_tags=set(["exclude this"])) + filter_tasks_by_tags(MyTaskSet, exclude_tags={"exclude this"}) self.assertListEqual(MyTaskSet.tasks, [MyTaskSet.not_excluded, MyTaskSet.dont_exclude_this_either]) def test_including_and_excluding(self): @@ -141,7 +141,7 @@ def excluded(self): def included_and_excluded(self): pass - filter_tasks_by_tags(MyTaskSet, tags=set(["included"]), exclude_tags=set(["excluded"])) + filter_tasks_by_tags(MyTaskSet, tags={"included"}, exclude_tags={"excluded"}) self.assertListEqual(MyTaskSet.tasks, [MyTaskSet.included]) def test_including_tasksets(self): @@ -170,7 +170,7 @@ class NormalNestedTaskSet(TaskSet): def not_included(self): pass - filter_tasks_by_tags(MyTaskSet, tags=set(["included"])) + filter_tasks_by_tags(MyTaskSet, tags={"included"}) self.assertListEqual(MyTaskSet.tasks, [MyTaskSet.MixedNestedTaskSet, MyTaskSet.TaggedNestedTaskSet]) self.assertListEqual(MyTaskSet.MixedNestedTaskSet.tasks, [MyTaskSet.MixedNestedTaskSet.included]) @@ -207,7 +207,7 @@ class NormalNestedTaskSet(TaskSet): def not_excluded(self): pass - filter_tasks_by_tags(MyTaskSet, exclude_tags=set(["excluded"])) + filter_tasks_by_tags(MyTaskSet, exclude_tags={"excluded"}) self.assertListEqual(MyTaskSet.tasks, [MyTaskSet.MixedNestedTaskSet, MyTaskSet.NormalNestedTaskSet]) self.assertListEqual(MyTaskSet.MixedNestedTaskSet.tasks, [MyTaskSet.MixedNestedTaskSet.not_excluded]) @@ -252,7 +252,7 @@ def dont_include_5_times(self): ], ) - filter_tasks_by_tags(MyTaskSet, tags=set(["included"])) + filter_tasks_by_tags(MyTaskSet, tags={"included"}) self.assertListEqual( MyTaskSet.tasks, @@ -306,7 +306,7 @@ def exclude_5_times(self): ], ) - filter_tasks_by_tags(MyTaskSet, exclude_tags=set(["excluded"])) + filter_tasks_by_tags(MyTaskSet, exclude_tags={"excluded"}) self.assertListEqual( MyTaskSet.tasks, @@ -339,12 +339,12 @@ class IncludeTaskSet(TaskSet): class ExcludeTaskSet(TaskSet): tasks = [shared_task, untagged_shared_task, SharedTaskSet] - filter_tasks_by_tags(IncludeTaskSet, tags=set(["tagged"])) + filter_tasks_by_tags(IncludeTaskSet, tags={"tagged"}) self.assertListEqual(IncludeTaskSet.tasks, [shared_task, SharedTaskSet]) self.assertListEqual(IncludeTaskSet.tasks[1].tasks, [SharedTaskSet.inner_task]) - filter_tasks_by_tags(ExcludeTaskSet, exclude_tags=set(["tagged"])) + filter_tasks_by_tags(ExcludeTaskSet, exclude_tags={"tagged"}) self.assertListEqual(ExcludeTaskSet.tasks, [untagged_shared_task]) @@ -364,7 +364,7 @@ def not_included(self): def dont_include_this_either(self): pass - filter_tasks_by_tags(MyUser, tags=set(["include this"])) + filter_tasks_by_tags(MyUser, tags={"include this"}) self.assertListEqual(MyUser.tasks, [MyUser.included]) @@ -384,7 +384,7 @@ def not_excluded(self): def dont_exclude_this_either(self): pass - filter_tasks_by_tags(MyUser, exclude_tags=set(["exclude this"])) + filter_tasks_by_tags(MyUser, exclude_tags={"exclude this"}) self.assertListEqual(MyUser.tasks, [MyUser.not_excluded, MyUser.dont_exclude_this_either]) diff --git a/locust/test/test_web.py b/locust/test/test_web.py index 2cff671330..ee8022f6d6 100644 --- a/locust/test/test_web.py +++ b/locust/test/test_web.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import csv import json import os @@ -477,9 +476,9 @@ def test_index_with_https(self): class TestWebUIFullHistory(LocustTestCase, _HeaderCheckMixin): STATS_BASE_NAME = "web_test" - STATS_FILENAME = "{}_stats.csv".format(STATS_BASE_NAME) - STATS_HISTORY_FILENAME = "{}_stats_history.csv".format(STATS_BASE_NAME) - STATS_FAILURES_FILENAME = "{}_failures.csv".format(STATS_BASE_NAME) + STATS_FILENAME = f"{STATS_BASE_NAME}_stats.csv" + STATS_HISTORY_FILENAME = f"{STATS_BASE_NAME}_stats_history.csv" + STATS_FAILURES_FILENAME = f"{STATS_BASE_NAME}_failures.csv" def setUp(self): super().setUp() diff --git a/locust/test/testcases.py b/locust/test/testcases.py index 747d66c3e2..078d389860 100644 --- a/locust/test/testcases.py +++ b/locust/test/testcases.py @@ -101,7 +101,7 @@ def basic_auth(): @app.route("/no_content_length") def no_content_length(): r = send_file( - BytesIO("This response does not have content-length in the header".encode("utf-8")), + BytesIO(b"This response does not have content-length in the header"), etag=False, mimetype="text/plain", ) diff --git a/locust/user/inspectuser.py b/locust/user/inspectuser.py index 748b798a31..e1a5cdb279 100644 --- a/locust/user/inspectuser.py +++ b/locust/user/inspectuser.py @@ -24,8 +24,8 @@ def print_task_ratio_json(user_classes, num_users): def _calc_distribution(user_classes, num_users): - fixed_count = sum([u.fixed_count for u in user_classes if u.fixed_count]) - total_weight = sum([u.weight for u in user_classes if not u.fixed_count]) + fixed_count = sum(u.fixed_count for u in user_classes if u.fixed_count) + total_weight = sum(u.weight for u in user_classes if not u.fixed_count) num_users = num_users or (total_weight if not fixed_count else 1) weighted_count = num_users - fixed_count weighted_count = weighted_count if weighted_count > 0 else 0 diff --git a/locust/user/task.py b/locust/user/task.py index c445b76a6e..b1d724a8d1 100644 --- a/locust/user/task.py +++ b/locust/user/task.py @@ -185,7 +185,7 @@ def __new__(mcs, classname, bases, class_dict): return type.__new__(mcs, classname, bases, class_dict) -class TaskSet(object, metaclass=TaskSetMeta): +class TaskSet(metaclass=TaskSetMeta): """ Class defining a set of tasks that a User will execute. diff --git a/locust/user/users.py b/locust/user/users.py index 96082f4edf..0d64776747 100644 --- a/locust/user/users.py +++ b/locust/user/users.py @@ -36,7 +36,7 @@ def __new__(mcs, classname, bases, class_dict): return type.__new__(mcs, classname, bases, class_dict) -class User(object, metaclass=UserMeta): +class User(metaclass=UserMeta): """ Represents a "user" which is to be spawned and attack the system that is to be load tested. diff --git a/locust/util/cache.py b/locust/util/cache.py index 8af2974e18..3546db40f4 100644 --- a/locust/util/cache.py +++ b/locust/util/cache.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import functools from time import time diff --git a/locust/web.py b/locust/web.py index 36471ff306..bb9d6b0f5a 100644 --- a/locust/web.py +++ b/locust/web.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import csv import datetime import logging @@ -406,7 +404,7 @@ def update_template_args(self): if self.environment.host: host = self.environment.host elif self.environment.runner.user_classes: - all_hosts = set([l.host for l in self.environment.runner.user_classes]) + all_hosts = {l.host for l in self.environment.runner.user_classes} if len(all_hosts) == 1: host = list(all_hosts)[0] else: diff --git a/setup.py b/setup.py index 78f2a55954..a1f6bfebfb 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import ast import os import re From 313b80f27f525441c449593a3aeaf38389f63c13 Mon Sep 17 00:00:00 2001 From: Lars Holmberg Date: Fri, 25 Feb 2022 15:32:45 +0100 Subject: [PATCH 2/3] Ran "flynt" on the code base, changing all string handling to use f-strings, instead having a mix of f-strings and %-formatted --- docs/conf.py | 12 ++++----- examples/add_command_line_argument.py | 2 +- examples/extend_web_ui/extend.py | 8 +----- generate_changelog.py | 2 +- locust/contrib/fasthttp.py | 2 +- locust/env.py | 2 +- locust/main.py | 10 ++++---- locust/rpc/zmqrpc.py | 4 +-- locust/runners.py | 36 +++++++++++++-------------- locust/test/test_http.py | 2 +- locust/test/test_log.py | 20 +++++++-------- locust/test/test_main.py | 2 +- locust/test/test_runners.py | 8 +++--- locust/test/test_stats.py | 2 +- locust/test/testcases.py | 2 +- locust/web.py | 2 +- 16 files changed, 53 insertions(+), 63 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index f08aa4c3bb..caa78ce5c4 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,7 +16,7 @@ # Run command `locust --help` and store output in cli-help-output.txt which is included in the docs def save_locust_help_output(): cli_help_output_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), "cli-help-output.txt") - print("Running `locust --help` command and storing output in %s" % cli_help_output_file) + print(f"Running `locust --help` command and storing output in {cli_help_output_file}") help_output = subprocess.check_output(["locust", "--help"]).decode("utf-8") with open(cli_help_output_file, "w") as f: f.write(help_output) @@ -29,7 +29,7 @@ def save_locust_help_output(): def save_locust_env_variables(): env_options_output_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), "config-options.rst") - print("Generating RST table for Locust environment variables and storing in %s" % env_options_output_file) + print(f"Generating RST table for Locust environment variables and storing in {env_options_output_file}") parser = get_empty_argument_parser() setup_parser_arguments(parser) table_data = [] @@ -37,11 +37,9 @@ def save_locust_env_variables(): if action.env_var: table_data.append( ( - ", ".join(["``%s``" % c for c in action.option_strings]), - "``%s``" % action.env_var, - ", ".join( - ["``%s``" % c for c in parser.get_possible_config_keys(action) if not c.startswith("--")] - ), + ", ".join([f"``{c}``" for c in action.option_strings]), + f"``{action.env_var}``", + ", ".join([f"``{c}``" for c in parser.get_possible_config_keys(action) if not c.startswith("--")]), action.help, ) ) diff --git a/examples/add_command_line_argument.py b/examples/add_command_line_argument.py index 47e949f05d..937f0872fb 100644 --- a/examples/add_command_line_argument.py +++ b/examples/add_command_line_argument.py @@ -10,7 +10,7 @@ def _(parser): @events.test_start.add_listener def _(environment, **kw): - print("Custom argument supplied: %s" % environment.parsed_options.my_argument) + print(f"Custom argument supplied: {environment.parsed_options.my_argument}") class WebsiteUser(HttpUser): diff --git a/examples/extend_web_ui/extend.py b/examples/extend_web_ui/extend.py index 1caa2cf0b9..86d573b30e 100644 --- a/examples/extend_web_ui/extend.py +++ b/examples/extend_web_ui/extend.py @@ -108,13 +108,7 @@ def content_length_csv(): if stats: for url, inner_stats in stats.items(): - rows.append( - '"%s",%.2f' - % ( - url, - inner_stats["content-length"], - ) - ) + rows.append(f"\"{url}\",{inner_stats['content-length']:.2f}") return "\n".join(rows) # register our new routes and extended UI with the Locust web UI diff --git a/generate_changelog.py b/generate_changelog.py index 294848ca04..134a734028 100755 --- a/generate_changelog.py +++ b/generate_changelog.py @@ -31,5 +31,5 @@ version, ] -print("Running command: %s\n" % " ".join(cmd)) +print(f"Running command: {' '.join(cmd)}\n") subprocess.run(cmd) diff --git a/locust/contrib/fasthttp.py b/locust/contrib/fasthttp.py index ad07380c16..f4d2de0e3b 100644 --- a/locust/contrib/fasthttp.py +++ b/locust/contrib/fasthttp.py @@ -303,7 +303,7 @@ def __init__(self, environment): "You must specify the base host. Either in the host attribute in the User class, or on the command line using the --host option." ) if not re.match(r"^https?://[^/]+", self.host, re.I): - raise LocustError("Invalid host (`%s`), must be a valid base URL. E.g. http://example.com" % self.host) + raise LocustError(f"Invalid host (`{self.host}`), must be a valid base URL. E.g. http://example.com") self.client = FastHttpSession( self.environment, diff --git a/locust/env.py b/locust/env.py index 3efe05ec03..f44369eb6f 100644 --- a/locust/env.py +++ b/locust/env.py @@ -111,7 +111,7 @@ def _create_runner( **kwargs, ) -> RunnerType: if self.runner is not None: - raise RunnerAlreadyExistsError("Environment.runner already exists (%s)" % self.runner) + raise RunnerAlreadyExistsError(f"Environment.runner already exists ({self.runner})") self.runner: RunnerType = runner_class(self, *args, **kwargs) # Attach the runner to the shape class so that the shape class can access user count state diff --git a/locust/main.py b/locust/main.py index 883c20ef55..79aac1ce16 100644 --- a/locust/main.py +++ b/locust/main.py @@ -173,7 +173,7 @@ def main(): if options.user_classes: missing = set(options.user_classes) - set(user_classes.keys()) if missing: - logger.error("Unknown User(s): %s\n" % (", ".join(missing))) + logger.error(f"Unknown User(s): {', '.join(missing)}\n") sys.exit(1) else: names = set(options.user_classes) & set(user_classes.keys()) @@ -314,7 +314,7 @@ def stop_and_optionally_quit(): logger.info("--run-time limit reached, stopping test") runner.stop() if options.autoquit != -1: - logger.debug("Autoquit time limit set to %s seconds" % options.autoquit) + logger.debug(f"Autoquit time limit set to {options.autoquit} seconds") time.sleep(options.autoquit) logger.info("--autoquit time reached, shutting down") runner.quit() @@ -376,7 +376,7 @@ def start_automatic_run(): headless_master_greenlet.link_exception(greenlet_exception_handler) if options.run_time: - logger.info("Run time limit set to %s seconds" % options.run_time) + logger.info(f"Run time limit set to {options.run_time} seconds") spawn_run_time_quit_greenlet() elif not options.worker and not environment.shape_class: logger.info("No run time limit set, use CTRL+C to interrupt") @@ -434,7 +434,7 @@ def shutdown(): else: code = 0 - logger.info("Shutting down (exit code %s)" % code) + logger.info(f"Shutting down (exit code {code})") if stats_printer_greenlet is not None: stats_printer_greenlet.kill(block=False) if headless_master_greenlet is not None: @@ -464,7 +464,7 @@ def save_html_report(): gevent.signal_handler(signal.SIGTERM, sig_term_handler) try: - logger.info("Starting Locust %s" % version) + logger.info(f"Starting Locust {version}") if options.autostart: start_automatic_run() diff --git a/locust/rpc/zmqrpc.py b/locust/rpc/zmqrpc.py index 6749846713..8a4634b3f3 100644 --- a/locust/rpc/zmqrpc.py +++ b/locust/rpc/zmqrpc.py @@ -57,13 +57,13 @@ class Server(BaseSocket): def __init__(self, host, port): BaseSocket.__init__(self, zmq.ROUTER) if port == 0: - self.port = self.socket.bind_to_random_port("tcp://%s" % host) + self.port = self.socket.bind_to_random_port(f"tcp://{host}") else: try: self.socket.bind("tcp://%s:%i" % (host, port)) self.port = port except zmqerr.ZMQError as e: - raise RPCError("Socket bind failure: %s" % (e)) + raise RPCError(f"Socket bind failure: {e}") class Client(BaseSocket): diff --git a/locust/runners.py b/locust/runners.py index 52f0b4eeaa..de98767415 100644 --- a/locust/runners.py +++ b/locust/runners.py @@ -218,7 +218,7 @@ def spawn(user_class: str, spawn_count: int): n += 1 if n % 10 == 0 or n == spawn_count: logger.debug("%i users spawned" % self.user_count) - logger.debug("All users of class %s spawned" % user_class) + logger.debug(f"All users of class {user_class} spawned") return new_users new_users = [] @@ -257,7 +257,7 @@ def stop_users(self, user_classes_stop_count: Dict[str, int]): while True: user_to_stop: User = to_stop.pop() - logger.debug("Stopping %s" % user_to_stop.greenlet.name) + logger.debug(f"Stopping {user_to_stop.greenlet.name}") if user_to_stop.greenlet is greenlet.getcurrent(): # User called runner.quit(), so don't block waiting for killing to finish user_to_stop.group.killone(user_to_stop.greenlet, block=False) @@ -338,7 +338,7 @@ def start(self, user_count: int, spawn_rate: float, wait: bool = False): user_classes_spawn_count = {} user_classes_stop_count = {} user_classes_count = dispatched_users[self._local_worker_node.id] - logger.debug("Ramping to %s" % _format_user_classes_count_for_log(user_classes_count)) + logger.debug(f"Ramping to {_format_user_classes_count_for_log(user_classes_count)}") for user_class, user_class_count in user_classes_count.items(): if self.user_classes_count[user_class] > user_class_count: user_classes_stop_count[user_class] = self.user_classes_count[user_class] - user_class_count @@ -363,7 +363,7 @@ def start(self, user_count: int, spawn_rate: float, wait: bool = False): # a gevent.sleep inside the dispatch_users function, locust won't gracefully shutdown. self.quit() - logger.info("All users spawned: %s" % _format_user_classes_count_for_log(self.user_classes_count)) + logger.info(f"All users spawned: {_format_user_classes_count_for_log(self.user_classes_count)}") self.target_user_classes_count = self.user_classes_count @@ -734,7 +734,7 @@ def start(self, user_count: int, spawn_rate: float, wait=False) -> None: dispatch_greenlets.join() logger.debug( - "Currently spawned users: %s" % _format_user_classes_count_for_log(self.reported_user_classes_count) + f"Currently spawned users: {_format_user_classes_count_for_log(self.reported_user_classes_count)}" ) self.target_user_classes_count = _aggregate_dispatched_users(dispatched_users) @@ -805,7 +805,7 @@ def stop(self, send_stop_to_client: bool = True): if send_stop_to_client: for client in self.clients.all: - logger.debug("Sending stop message to client %s" % client.id) + logger.debug(f"Sending stop message to client {client.id}") self.server.send_to_client(Message("stop", None, client.id)) # Give an additional 60s for all workers to stop @@ -824,7 +824,7 @@ def quit(self): self.stop(send_stop_to_client=False) logger.debug("Quitting...") for client in self.clients.all: - logger.debug("Sending quit message to client %s" % (client.id)) + logger.debug(f"Sending quit message to client {client.id}") self.server.send_to_client(Message("quit", None, client.id)) gevent.sleep(0.5) # wait for final stats report from all workers self.greenlet.kill(block=True) @@ -846,7 +846,7 @@ def heartbeat_worker(self): for client in self.clients.all: if client.heartbeat < 0 and client.state != STATE_MISSING: - logger.info("Worker %s failed to send heartbeat, setting state to missing." % str(client.id)) + logger.info(f"Worker {str(client.id)} failed to send heartbeat, setting state to missing.") client.state = STATE_MISSING client.user_classes_count = {} if self._users_dispatcher is not None: @@ -866,7 +866,7 @@ def reset_connection(self): self.server.close() self.server = rpc.Server(self.master_bind_host, self.master_bind_port) except RPCError as e: - logger.error("Temporary failure when resetting connection: %s, will retry later." % (e)) + logger.error(f"Temporary failure when resetting connection: {e}, will retry later.") def client_listener(self): while True: @@ -874,7 +874,7 @@ def client_listener(self): client_id, msg = self.server.recv_from_client() except RPCError as e: if self.clients.ready: - logger.error("RPCError found when receiving from client: %s" % (e)) + logger.error(f"RPCError found when receiving from client: {e}") else: logger.debug( "RPCError found when receiving from client: %s (but no clients were expected to be connected anyway)" @@ -922,7 +922,7 @@ def client_listener(self): if not self._users_dispatcher.dispatch_in_progress and self.state == STATE_RUNNING: # TODO: Test this situation self.start(self.target_user_count, self.spawn_rate) - logger.info("Removing %s client from running clients" % (msg.node_id)) + logger.info(f"Removing {msg.node_id} client from running clients") elif msg.type == "heartbeat": if msg.node_id in self.clients: c = self.clients[msg.node_id] @@ -941,7 +941,7 @@ def client_listener(self): self.worker_cpu_warning_emitted = True # used to fail the test in the end c.cpu_warning_emitted = True # used to suppress logging for this node logger.warning( - "Worker %s exceeded cpu threshold (will only log this once per worker)" % (msg.node_id) + f"Worker {msg.node_id} exceeded cpu threshold (will only log this once per worker)" ) if "current_memory_usage" in msg.data: c.memory_usage = msg.data["current_memory_usage"] @@ -961,9 +961,7 @@ def client_listener(self): if not self._users_dispatcher.dispatch_in_progress and self.state == STATE_RUNNING: # TODO: Test this situation self.start(self.target_user_count, self.spawn_rate) - logger.info( - "Client %r quit. Currently %i clients connected." % (msg.node_id, len(self.clients.ready)) - ) + logger.info(f"Client {msg.node_id!r} quit. Currently {len(self.clients.ready)} clients connected.") if self.worker_count - len(self.clients.missing) <= 0: logger.info("The last worker quit, stopping test.") self.stop() @@ -1127,7 +1125,7 @@ def heartbeat(self): ) ) except RPCError as e: - logger.error("RPCError found when sending heartbeat: %s" % (e)) + logger.error(f"RPCError found when sending heartbeat: {e}") self.reset_connection() gevent.sleep(HEARTBEAT_INTERVAL) @@ -1137,7 +1135,7 @@ def reset_connection(self): self.client.close() self.client = rpc.Client(self.master_host, self.master_port, self.client_id) except RPCError as e: - logger.error("Temporary failure when resetting connection: %s, will retry later." % (e)) + logger.error(f"Temporary failure when resetting connection: {e}, will retry later.") def worker(self): last_received_spawn_timestamp = 0 @@ -1145,7 +1143,7 @@ def worker(self): try: msg = self.client.recv() except RPCError as e: - logger.error("RPCError found when receiving from master: %s" % (e)) + logger.error(f"RPCError found when receiving from master: {e}") continue if msg.type == "spawn": self.client.send(Message("spawning", None, self.client_id)) @@ -1203,7 +1201,7 @@ def stats_reporter(self): try: self._send_stats() except RPCError as e: - logger.error("Temporary connection lost to master server: %s, will retry later." % (e)) + logger.error(f"Temporary connection lost to master server: {e}, will retry later.") gevent.sleep(WORKER_REPORT_INTERVAL) def send_message(self, msg_type, data=None): diff --git a/locust/test/test_http.py b/locust/test/test_http.py index 9be3241f4f..f12bd18a91 100644 --- a/locust/test/test_http.py +++ b/locust/test/test_http.py @@ -40,7 +40,7 @@ def test_wrong_url(self): try: self.assertRaises(exception, s.get, "/") except KeyError: - self.fail("Invalid URL %s was not propagated" % url) + self.fail(f"Invalid URL {url} was not propagated") def test_streaming_response(self): """ diff --git a/locust/test/test_log.py b/locust/test/test_log.py index 4f433f1f0d..6fbaeed133 100644 --- a/locust/test/test_log.py +++ b/locust/test/test_log.py @@ -71,15 +71,15 @@ def my_task(self): ).decode("utf-8") self.assertIn( - "%s/INFO/locust.main: Run time limit set to 1 seconds" % socket.gethostname(), + f"{socket.gethostname()}/INFO/locust.main: Run time limit set to 1 seconds", output, ) self.assertIn( - "%s/INFO/locust.main: --run-time limit reached. Stopping Locust" % socket.gethostname(), + f"{socket.gethostname()}/INFO/locust.main: --run-time limit reached. Stopping Locust", output, ) self.assertIn( - "%s/INFO/locust.main: Shutting down (exit code 0)" % socket.gethostname(), + f"{socket.gethostname()}/INFO/locust.main: Shutting down (exit code 0)", output, ) self.assertIn( @@ -88,12 +88,12 @@ def my_task(self): ) # check that custom message of root logger is also printed self.assertIn( - "%s/INFO/root: custom log message" % socket.gethostname(), + f"{socket.gethostname()}/INFO/root: custom log message", output, ) # check that custom message of custom_logger is also printed self.assertIn( - "%s/INFO/custom_logger: test" % socket.gethostname(), + f"{socket.gethostname()}/INFO/custom_logger: test", output, ) @@ -168,7 +168,7 @@ def my_task(self): ).decode("utf-8") except subprocess.CalledProcessError as e: raise AssertionError( - "Running locust command failed. Output was:\n\n%s" % e.stdout.decode("utf-8") + f"Running locust command failed. Output was:\n\n{e.stdout.decode('utf-8')}" ) from e with open(log_file_path, encoding="utf-8") as f: @@ -183,19 +183,19 @@ def my_task(self): # check that log messages goes into file self.assertIn( - "%s/INFO/locust.main: Run time limit set to 1 seconds" % socket.gethostname(), + f"{socket.gethostname()}/INFO/locust.main: Run time limit set to 1 seconds", log_content, ) self.assertIn( - "%s/INFO/locust.main: --run-time limit reached. Stopping Locust" % socket.gethostname(), + f"{socket.gethostname()}/INFO/locust.main: --run-time limit reached. Stopping Locust", log_content, ) self.assertIn( - "%s/INFO/locust.main: Shutting down (exit code 0)" % socket.gethostname(), + f"{socket.gethostname()}/INFO/locust.main: Shutting down (exit code 0)", log_content, ) # check that message of custom logger also went into log file self.assertIn( - "%s/INFO/root: custom log message" % socket.gethostname(), + f"{socket.gethostname()}/INFO/root: custom log message", log_content, ) diff --git a/locust/test/test_main.py b/locust/test/test_main.py index e34a77e039..41135f1246 100644 --- a/locust/test/test_main.py +++ b/locust/test/test_main.py @@ -709,7 +709,7 @@ def test_html_report_option(self): ) except subprocess.CalledProcessError as e: raise AssertionError( - "Running locust command failed. Output was:\n\n%s" % e.stdout.decode("utf-8") + f"Running locust command failed. Output was:\n\n{e.stdout.decode('utf-8')}" ) from e with open(html_report_file_path, encoding="utf-8") as f: diff --git a/locust/test/test_runners.py b/locust/test/test_runners.py index 8981105e17..7c593165df 100644 --- a/locust/test/test_runners.py +++ b/locust/test/test_runners.py @@ -404,7 +404,7 @@ def my_task(self): runner.spawning_greenlet.join() delta = time.time() - ts self.assertTrue( - 0 <= delta <= 0.05, "Expected user count to increase to 10 instantaneously, instead it took %f" % delta + 0 <= delta <= 0.05, f"Expected user count to increase to 10 instantaneously, instead it took {delta:f}" ) self.assertTrue( runner.user_count == 10, "User count has not decreased correctly to 2, it is : %i" % runner.user_count @@ -414,7 +414,7 @@ def my_task(self): runner.start(2, 4, wait=False) runner.spawning_greenlet.join() delta = time.time() - ts - self.assertTrue(0 <= delta <= 1.05, "Expected user count to decrease to 2 in 1s, instead it took %f" % delta) + self.assertTrue(0 <= delta <= 1.05, f"Expected user count to decrease to 2 in 1s, instead it took {delta:f}") self.assertTrue( runner.user_count == 2, "User count has not decreased correctly to 2, it is : %i" % runner.user_count ) @@ -3541,7 +3541,7 @@ class MyTestUser(User): runner.spawning_greenlet.join() delta = time.perf_counter() - ts self.assertTrue( - 0 <= delta <= 0.05, "Expected user count to increase to 10 instantaneously, instead it took %f" % delta + 0 <= delta <= 0.05, f"Expected user count to increase to 10 instantaneously, instead it took {delta:f}" ) self.assertTrue( runner.user_count == 10, "User count has not decreased correctly to 2, it is : %i" % runner.user_count @@ -3551,7 +3551,7 @@ class MyTestUser(User): runner.start(2, 4, wait=False) runner.spawning_greenlet.join() delta = time.perf_counter() - ts - self.assertTrue(2 <= delta <= 2.05, "Expected user count to decrease to 2 in 2s, instead it took %f" % delta) + self.assertTrue(2 <= delta <= 2.05, f"Expected user count to decrease to 2 in 2s, instead it took {delta:f}") self.assertTrue( runner.user_count == 2, "User count has not decreased correctly to 2, it is : %i" % runner.user_count ) diff --git a/locust/test/test_stats.py b/locust/test/test_stats.py index ea61fcba18..2ca7132b2e 100644 --- a/locust/test/test_stats.py +++ b/locust/test/test_stats.py @@ -282,7 +282,7 @@ def test_error_grouping_errors_with_memory_addresses(self): class Dummy: pass - self.stats.log_error("GET", "/", Exception("Error caused by %r" % Dummy())) + self.stats.log_error("GET", "/", Exception(f"Error caused by {Dummy()!r}")) self.assertEqual(1, len(self.stats.errors)) def test_serialize_through_message(self): diff --git a/locust/test/testcases.py b/locust/test/testcases.py index 078d389860..79fa58d79a 100644 --- a/locust/test/testcases.py +++ b/locust/test/testcases.py @@ -121,7 +121,7 @@ def streaming_response(iterations): def generate(): yield "

streaming response

" for i in range(iterations): - yield "%s\n" % i + yield f"{i}\n" time.sleep(0.01) yield "" diff --git a/locust/web.py b/locust/web.py index bb9d6b0f5a..82a684c54a 100644 --- a/locust/web.py +++ b/locust/web.py @@ -188,7 +188,7 @@ def stats_report(): res = get_html_report(self.environment, show_download_link=not request.args.get("download")) if request.args.get("download"): res = app.make_response(res) - res.headers["Content-Disposition"] = "attachment;filename=report_%s.html" % time() + res.headers["Content-Disposition"] = f"attachment;filename=report_{time()}.html" return res def _download_csv_suggest_file_name(suggest_filename_prefix): From 96e13d11698d5c714f1fbf93e173412437cbcc91 Mon Sep 17 00:00:00 2001 From: Lars Holmberg Date: Fri, 25 Feb 2022 15:43:16 +0100 Subject: [PATCH 3/3] Git-blame-ignore the change made by pyupgrade and flynt, because they (should) have no functional impact and may be confusing. --- .git-blame-ignore-revs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index c97121c523..b21c1f4a0a 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -1,3 +1,7 @@ # Migrate code style to Black 7c0fcc213d3988f6e7c6ffef63b24afe00e5fbd9 2e7a8b5697a98d1d314d6fc3ef0589f81f09d7fe +# upgrade code style to 3.6 using pyupgrade +6ec972f4dbb880bf0c7a11809e6c1ba194c9784c +# upgrade code style to use f-strings using flynt +313b80f27f525441c449593a3aeaf38389f63c13