Skip to content

Commit fe8f6fb

Browse files
authored
Run pyupgrade --py36-plus (#119)
Signed-off-by: Ciaran Evans <[email protected]>
1 parent fb16a98 commit fe8f6fb

28 files changed

+102
-141
lines changed

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,13 @@
1818
### Removed
1919
- Removed TravisCI related files
2020
- All `# -*- coding: utf-8 -*-` statements
21+
- Python 3.5 support
2122

2223
### Changed
2324
- update return value of asg action detach_random_instances to include instance IDs
2425
- switch from `pycodestyle` to `black`, `flake8`, and `isort` for linting/formatting
2526
- applied `black`, `flake8`, and `isort` across the codebase
27+
- applied `pyupgrade --py36-plus`
2628

2729
### Fixed
2830
- `chaosaws.route53.probes` now correctly exposes the `__all__` attribute

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ extension to the [Chaos Toolkit][chaostoolkit].
1212

1313
## Install
1414

15-
This package requires Python 3.5+
15+
This package requires Python 3.6+
1616

1717
To be used from your experiment, this package must be installed in the Python
1818
environment where [chaostoolkit][] already lives.

chaosaws/__init__.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def aws_client(
7272
raise InterruptExecution("AWS requires a region to be set!")
7373

7474
if region:
75-
logger.debug("Using AWS region '{}'".format(region))
75+
logger.debug(f"Using AWS region '{region}'")
7676
params["region_name"] = region
7777

7878
if boto3.DEFAULT_SESSION is None:
@@ -175,11 +175,11 @@ def signed_api_call(
175175
region = configuration.get("aws_region", "us-east-1") or ""
176176
host = configuration.get("aws_host", "amazonaws.com")
177177
scheme = configuration.get("aws_endpoint_scheme", "https")
178-
host = "{s}.{r}.{h}".format(s=service, r=region, h=host)
179-
endpoint = configuration.get(
180-
"aws_endpoint", "{scheme}://{h}".format(scheme=scheme, h=host)
181-
).replace("..", ".")
182-
endpoint = "{e}{p}".format(e=endpoint, p=path)
178+
host = f"{service}.{region}.{host}"
179+
endpoint = configuration.get("aws_endpoint", f"{scheme}://{host}").replace(
180+
"..", "."
181+
)
182+
endpoint = f"{endpoint}{path}"
183183
creds = get_credentials(secrets)
184184

185185
# when creds weren't provided via secrets, we let boto search for them

chaosaws/asg/actions.py

+9-13
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,7 @@ def terminate_random_instances(
7878
instances = [e for e in instances if e["AvailabilityZone"] == az]
7979

8080
if not instances:
81-
raise FailedActivity(
82-
"No instances found in Availability Zone: {}".format(az)
83-
)
81+
raise FailedActivity(f"No instances found in Availability Zone: {az}")
8482
else:
8583
if instance_percent:
8684
instance_count = int(
@@ -100,7 +98,7 @@ def terminate_random_instances(
10098
client = aws_client("ec2", configuration, secrets)
10199
try:
102100
response = client.terminate_instances(
103-
InstanceIds=sorted([e["InstanceId"] for e in instances])
101+
InstanceIds=sorted(e["InstanceId"] for e in instances)
104102
)
105103
results.append(
106104
{
@@ -172,9 +170,7 @@ def stop_random_instances(
172170
instances = [e for e in instances if e["AvailabilityZone"] == az]
173171

174172
if not instances:
175-
raise FailedActivity(
176-
"No instances found in Availability Zone: {}".format(az)
177-
)
173+
raise FailedActivity(f"No instances found in Availability Zone: {az}")
178174
else:
179175
if instance_percent:
180176
instance_count = int(
@@ -193,7 +189,7 @@ def stop_random_instances(
193189
client = aws_client("ec2", configuration, secrets)
194190
try:
195191
response = client.stop_instances(
196-
InstanceIds=sorted([e["InstanceId"] for e in instances]), Force=force
192+
InstanceIds=sorted(e["InstanceId"] for e in instances), Force=force
197193
)
198194
results.append(
199195
{
@@ -561,17 +557,17 @@ def validate_asgs(asg_names: List[str] = None, tags: List[Dict[str, str]] = None
561557

562558

563559
def get_asg_by_name(asg_names: List[str], client: boto3.client) -> AWSResponse:
564-
logger.debug("Searching for ASG(s): {}.".format(asg_names))
560+
logger.debug(f"Searching for ASG(s): {asg_names}.")
565561

566562
asgs = client.describe_auto_scaling_groups(AutoScalingGroupNames=asg_names)
567563

568564
if not asgs.get("AutoScalingGroups", []):
569-
raise FailedActivity("Unable to locate ASG(s): {}".format(asg_names))
565+
raise FailedActivity(f"Unable to locate ASG(s): {asg_names}")
570566

571567
found_asgs = [a["AutoScalingGroupName"] for a in asgs["AutoScalingGroups"]]
572568
invalid_asgs = [a for a in asg_names if a not in found_asgs]
573569
if invalid_asgs:
574-
raise FailedActivity("No ASG(s) found with name(s): {}".format(invalid_asgs))
570+
raise FailedActivity(f"No ASG(s) found with name(s): {invalid_asgs}")
575571
return asgs
576572

577573

@@ -593,7 +589,7 @@ def get_asg_by_tags(tags: List[Dict[str, str]], client: boto3.client) -> AWSResp
593589
results.add(a["ResourceId"])
594590

595591
if not results:
596-
raise FailedActivity("No ASG(s) found with matching tag(s): {}.".format(tags))
592+
raise FailedActivity(f"No ASG(s) found with matching tag(s): {tags}.")
597593
return get_asg_by_name(list(results), client)
598594

599595

@@ -704,7 +700,7 @@ def attach_instance_volume(
704700
response = client.attach_volume(
705701
Device=mount_point, InstanceId=instance_id, VolumeId=volume_id
706702
)
707-
logger.debug("Attached volume %s to instance %s" % (volume_id, instance_id))
703+
logger.debug(f"Attached volume {volume_id} to instance {instance_id}")
708704
except ClientError as e:
709705
raise FailedActivity(
710706
"Unable to attach volume %s to instance %s: %s"

chaosaws/asg/probes.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ def wait_desired_equals_healthy(
139139

140140
if result:
141141
waiting_time = int(time.time() - start)
142-
logger.debug("Waiting time was: {}".format(waiting_time))
142+
logger.debug(f"Waiting time was: {waiting_time}")
143143
return waiting_time
144144
time.sleep(0.1)
145145

@@ -185,7 +185,7 @@ def wait_desired_not_equals_healthy_tags(
185185

186186
if not result:
187187
waiting_time = int(time.time() - start)
188-
logger.debug("Waiting time was: {}".format(waiting_time))
188+
logger.debug(f"Waiting time was: {waiting_time}")
189189

190190
return waiting_time
191191
time.sleep(0.1)
@@ -232,7 +232,7 @@ def wait_desired_equals_healthy_tags(
232232

233233
if result:
234234
waiting_time = int(time.time() - start)
235-
logger.debug("Waiting time was: {}".format(waiting_time))
235+
logger.debug(f"Waiting time was: {waiting_time}")
236236

237237
return waiting_time
238238

@@ -263,10 +263,10 @@ def is_scaling_in_progress(
263263
or instance["HealthStatus"] != "Healthy"
264264
):
265265

266-
logger.debug("Scaling activities in progress: {}".format(True))
266+
logger.debug(f"Scaling activities in progress: {True}")
267267
return True
268268

269-
logger.debug("Scaling activities in progress: {}".format(False))
269+
logger.debug(f"Scaling activities in progress: {False}")
270270
return False
271271

272272

@@ -422,7 +422,7 @@ def get_asg_by_name(asg_names: List[str], client: boto3.client) -> AWSResponse:
422422
invalid_asgs = [a for a in asg_names if a not in valid_asgs]
423423

424424
if invalid_asgs:
425-
raise FailedActivity("No ASG(s) found matching: {}".format(invalid_asgs))
425+
raise FailedActivity(f"No ASG(s) found matching: {invalid_asgs}")
426426
return results
427427

428428

@@ -457,7 +457,7 @@ def get_asg_by_tags(
457457

458458
filtered_groups = [g["Name"] for g in group_sets if filter_set.issubset(g["Tags"])]
459459

460-
logger.debug("filtered groups: {}".format(filtered_groups))
460+
logger.debug(f"filtered groups: {filtered_groups}")
461461

462462
if filtered_groups:
463463
groups_descr = client.describe_auto_scaling_groups(

chaosaws/awslambda/actions.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,7 @@ def invoke_function(
5454
try:
5555
response = client.invoke(**request_kwargs)
5656
except Exception as x:
57-
raise FailedActivity(
58-
"failed invoking function '{}': '{}'".format(function_name, str(x))
59-
)
57+
raise FailedActivity(f"failed invoking function '{function_name}': '{str(x)}'")
6058
if "Payload" in response:
6159
# The payload is of type StreamingBody and
6260
# cannot be directly serialized into JSON
@@ -88,7 +86,7 @@ def put_function_concurrency(
8886
)
8987
except Exception as x:
9088
raise FailedActivity(
91-
"failed throttling lambda function '{}': '{}'".format(function_name, str(x))
89+
f"failed throttling lambda function '{function_name}': '{str(x)}'"
9290
)
9391

9492

chaosaws/cloudwatch/probes.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def get_alarm_state_value(
2222
client = aws_client("cloudwatch", configuration, secrets)
2323
response = client.describe_alarms(AlarmNames=[alarm_name])
2424
if len(response["MetricAlarms"]) == 0:
25-
raise FailedActivity("CloudWatch alarm name {} not found".format(alarm_name))
25+
raise FailedActivity(f"CloudWatch alarm name {alarm_name} not found")
2626
return response["MetricAlarms"][0]["StateValue"]
2727

2828

@@ -76,24 +76,22 @@ def get_metric_statistics(
7676
if unit is not None:
7777
request_kwargs["Unit"] = unit
7878

79-
logger.debug("Request arguments: {}".format(request_kwargs))
79+
logger.debug(f"Request arguments: {request_kwargs}")
8080
response = client.get_metric_statistics(**request_kwargs)
8181

8282
datapoints = response["Datapoints"]
8383
if not datapoints:
8484
return 0
8585

8686
datapoint = datapoints[0]
87-
logger.debug("Response: {}".format(response))
87+
logger.debug(f"Response: {response}")
8888
try:
8989
if statistic is not None:
9090
return datapoint[statistic]
9191
elif extended_statistic is not None:
9292
return datapoint["ExtendedStatistics"][extended_statistic]
9393
except Exception as x:
94-
raise FailedActivity(
95-
"Unable to parse response '{}': '{}'".format(response, str(x))
96-
)
94+
raise FailedActivity(f"Unable to parse response '{response}': '{str(x)}'")
9795

9896

9997
def get_metric_data(

chaosaws/ec2/actions.py

+13-15
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,11 @@ def stop_instance(
6363
instance_types = pick_random_instance(filters, client)
6464

6565
if not instance_types:
66-
raise FailedActivity("No instances in availability zone: {}".format(az))
66+
raise FailedActivity(f"No instances in availability zone: {az}")
6767
else:
6868
instance_types = get_instance_type_by_id([instance_id], client)
6969

70-
logger.debug(
71-
"Picked EC2 instance '{}' from AZ '{}' to be stopped".format(instance_types, az)
72-
)
70+
logger.debug(f"Picked EC2 instance '{instance_types}' from AZ '{az}' to be stopped")
7371

7472
return stop_instances_any_type(
7573
instance_types=instance_types, force=force, client=client
@@ -113,7 +111,7 @@ def stop_instances(
113111
instance_types = list_instances_by_type(filters, client)
114112

115113
if not instance_types:
116-
raise FailedActivity("No instances in availability zone: {}".format(az))
114+
raise FailedActivity(f"No instances in availability zone: {az}")
117115
else:
118116
instance_types = get_instance_type_by_id(instance_ids, client)
119117

@@ -228,7 +226,7 @@ def terminate_instances(
228226
"No instances found matching filters: %s" % str(filters)
229227
)
230228

231-
logger.debug("Instances in AZ %s selected: %s}." % (az, str(instance_types)))
229+
logger.debug(f"Instances in AZ {az} selected: {str(instance_types)}}}.")
232230
else:
233231
instance_types = get_instance_type_by_id(instance_ids, client)
234232

@@ -281,7 +279,7 @@ def start_instances(
281279
"No instances found matching filters: %s" % str(filters)
282280
)
283281

284-
logger.debug("Instances in AZ %s selected: %s}." % (az, str(instance_types)))
282+
logger.debug(f"Instances in AZ {az} selected: {str(instance_types)}}}.")
285283
else:
286284
instance_types = get_instance_type_by_id(instance_ids, client)
287285
return start_instances_any_type(instance_types, client)
@@ -333,7 +331,7 @@ def restart_instances(
333331
"No instances found matching filters: %s" % str(filters)
334332
)
335333

336-
logger.debug("Instances in AZ %s selected: %s}." % (az, str(instance_types)))
334+
logger.debug(f"Instances in AZ {az} selected: {str(instance_types)}}}.")
337335
else:
338336
instance_types = get_instance_type_by_id(instance_ids, client)
339337
return restart_instances_any_type(instance_types, client)
@@ -435,9 +433,9 @@ def list_instances_by_type(
435433
Return all instance ids matching the given filters by type
436434
(InstanceLifecycle) ie spot, on demand, etc.
437435
"""
438-
logger.debug("EC2 instances query: {}".format(str(filters)))
436+
logger.debug(f"EC2 instances query: {str(filters)}")
439437
res = client.describe_instances(Filters=filters)
440-
logger.debug("Instances matching the filter query: {}".format(str(res)))
438+
logger.debug(f"Instances matching the filter query: {str(res)}")
441439

442440
return get_instance_type_from_response(res)
443441

@@ -601,7 +599,7 @@ def stop_instances_any_type(
601599
client.describe_instances(InstanceIds=instance_types["spot"])
602600
)
603601

604-
logger.debug("Canceling spot requests: {}".format(spot_request_ids))
602+
logger.debug(f"Canceling spot requests: {spot_request_ids}")
605603
client.cancel_spot_instance_requests(SpotInstanceRequestIds=spot_request_ids)
606604
logger.debug("Terminating spot instances: {}".format(instance_types["spot"]))
607605

@@ -623,7 +621,7 @@ def terminate_instances_any_type(
623621
response = []
624622

625623
for k, v in instance_types.items():
626-
logger.debug("Terminating %s instance(s): %s" % (k, instance_types[k]))
624+
logger.debug(f"Terminating {k} instance(s): {instance_types[k]}")
627625
if k == "spot":
628626
instances = get_spot_request_ids_from_response(
629627
client.describe_instances(InstanceIds=v)
@@ -644,7 +642,7 @@ def start_instances_any_type(
644642
"""
645643
results = []
646644
for k, v in instance_types.items():
647-
logger.debug("Starting %s instance(s): %s" % (k, v))
645+
logger.debug(f"Starting {k} instance(s): {v}")
648646
response = client.start_instances(InstanceIds=v)
649647
results.extend(response.get("StartingInstances", []))
650648
return results
@@ -656,7 +654,7 @@ def restart_instances_any_type(instance_types: dict, client: boto3.client):
656654
"""
657655
results = []
658656
for k, v in instance_types.items():
659-
logger.debug("Restarting %s instance(s): %s" % (k, v))
657+
logger.debug(f"Restarting {k} instance(s): {v}")
660658
client.reboot_instances(InstanceIds=v)
661659
return results
662660

@@ -712,7 +710,7 @@ def attach_instance_volume(
712710
response = client.attach_volume(
713711
Device=mount_point, InstanceId=instance_id, VolumeId=volume_id
714712
)
715-
logger.debug("Attached volume %s to instance %s" % (volume_id, instance_id))
713+
logger.debug(f"Attached volume {volume_id} to instance {instance_id}")
716714
except ClientError as e:
717715
raise FailedActivity(
718716
"Unable to attach volume %s to instance %s: %s"

0 commit comments

Comments
 (0)