Skip to content

Commit

Permalink
Ran pyupgrade on the code base, removing various "Python2-isms".
Browse files Browse the repository at this point in the history
  • Loading branch information
cyberw committed Feb 25, 2022
1 parent d3b43c5 commit 6ec972f
Show file tree
Hide file tree
Showing 36 changed files with 91 additions and 132 deletions.
12 changes: 6 additions & 6 deletions benchmarks/dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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,
]
Expand All @@ -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())
1 change: 0 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing dir.
#
Expand Down
2 changes: 1 addition & 1 deletion examples/custom_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions examples/custom_shape/wait_user_count.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand All @@ -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):
Expand Down
2 changes: 0 additions & 2 deletions examples/events.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
6 changes: 2 additions & 4 deletions examples/extend_web_ui/extend.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
1 change: 0 additions & 1 deletion examples/grpc/hello_pb2.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions examples/grpc/hello_pb2_grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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):
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion examples/sdk_session_patching/session_patch_locustfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion locust/argument_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion locust/clients.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion locust/contrib/fasthttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down
2 changes: 1 addition & 1 deletion locust/dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
]
Expand Down
2 changes: 1 addition & 1 deletion locust/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion locust/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down
2 changes: 1 addition & 1 deletion locust/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
12 changes: 5 additions & 7 deletions locust/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)"
Expand Down
2 changes: 1 addition & 1 deletion locust/rpc/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def __init__(self, message_type, data, node_id):
self.node_id = node_id

def __repr__(self):
return "<Message %s:%s>" % (self.type, self.node_id)
return f"<Message {self.type}:{self.node_id}>"

def serialize(self):
return msgpack.dumps((self.type, self.data, self.node_id))
Expand Down
7 changes: 2 additions & 5 deletions locust/runners.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import functools
import json
import logging
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
12 changes: 6 additions & 6 deletions locust/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,)
)

Expand Down Expand Up @@ -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):
Expand All @@ -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 {
Expand Down Expand Up @@ -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()

Expand Down
Loading

0 comments on commit 6ec972f

Please sign in to comment.