Skip to content

Commit

Permalink
Ran "flynt" on the code base, changing all string handling to use f-s…
Browse files Browse the repository at this point in the history
…trings, instead having a mix of f-strings and %-formatted
  • Loading branch information
cyberw committed Feb 25, 2022
1 parent 6ec972f commit 313b80f
Show file tree
Hide file tree
Showing 16 changed files with 53 additions and 63 deletions.
12 changes: 5 additions & 7 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -29,19 +29,17 @@ 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 = []
for action in parser._actions:
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,
)
)
Expand Down
2 changes: 1 addition & 1 deletion examples/add_command_line_argument.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
8 changes: 1 addition & 7 deletions examples/extend_web_ui/extend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion generate_changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@
version,
]

print("Running command: %s\n" % " ".join(cmd))
print(f"Running command: {' '.join(cmd)}\n")
subprocess.run(cmd)
2 changes: 1 addition & 1 deletion locust/contrib/fasthttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion locust/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions locust/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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()

Expand Down
4 changes: 2 additions & 2 deletions locust/rpc/zmqrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
36 changes: 17 additions & 19 deletions locust/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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:
Expand All @@ -866,15 +866,15 @@ 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:
try:
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)"
Expand Down Expand Up @@ -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]
Expand All @@ -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"]
Expand All @@ -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()
Expand Down Expand Up @@ -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)

Expand All @@ -1137,15 +1135,15 @@ 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
while True:
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))
Expand Down Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion locust/test/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down
20 changes: 10 additions & 10 deletions locust/test/test_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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,
)

Expand Down Expand Up @@ -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:
Expand All @@ -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,
)
2 changes: 1 addition & 1 deletion locust/test/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading

0 comments on commit 313b80f

Please sign in to comment.