Skip to content

Commit ebdbddb

Browse files
refactoring
1 parent fd45145 commit ebdbddb

File tree

4 files changed

+100
-32
lines changed

4 files changed

+100
-32
lines changed

tests/step_defs/conftest.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
1+
"""
2+
conftest module
3+
"""
4+
from moto import mock_aws
15
import pytest
26
from utilities.classes.sqs_client import SQSClient
37
from utilities.classes.log import CustomLogger
48
from utilities.settings import QUEUE_NAME, SQS_BUCKET, REPORT_DIR
59
from utilities import os_funcs as cmd
6-
from moto import mock_aws
710

811
def pytest_addoption(parser: 'pytest.Parser') -> None:
912
"""
@@ -12,8 +15,8 @@ def pytest_addoption(parser: 'pytest.Parser') -> None:
1215
Args:
1316
parser (pytest.Parser): The pytest parser object.
1417
"""
15-
parser.addoption("--mock-aws",
16-
action="store",
18+
parser.addoption("--mock-aws",
19+
action="store",
1720
default="True",
1821
choices=["True", "False"],
1922
type=str,
@@ -32,9 +35,9 @@ def mock_aws_flag(request: 'pytest.FixtureRequest') -> bool:
3235
bool: Boolean indicating whether AWS should be mocked.
3336
"""
3437
mock_aws_value = request.config.getoption("--mock-aws")
35-
mock_aws_flag = mock_aws_value == "True"
38+
mock_aws_flag_value = mock_aws_value == "True"
3639

37-
return mock_aws_flag
40+
return mock_aws_flag_value
3841

3942
@pytest.fixture(scope='module')
4043
def log() -> CustomLogger:
@@ -57,7 +60,7 @@ def setup(request: 'pytest.FixtureRequest', mock_aws_flag: bool, log: CustomLogg
5760
log (CustomLogger): A CustomLogger instance.
5861
"""
5962
log.info(f"AWS Mock Flag: {mock_aws_flag}")
60-
63+
6164
if mock_aws_flag:
6265
# Setup mocked AWS environment
6366
log.info("Creating mocked SQS client")
@@ -94,8 +97,8 @@ def sqs_cli(mock_aws_flag: bool, log: CustomLogger) -> SQSClient:
9497
Returns:
9598
SQSClient: An SQSClient instance.
9699
"""
97-
sqs_cli = SQSClient(log=log, bucket=SQS_BUCKET, mock_aws_flag=mock_aws_flag)
98-
sqs_cli.create_queue(QUEUE_NAME)
99-
sqs_cli.get_queue_url(QUEUE_NAME)
100+
sqs_client_instance = SQSClient(log=log, bucket=SQS_BUCKET, mock_aws_flag=mock_aws_flag)
101+
sqs_client_instance.create_queue(QUEUE_NAME)
102+
sqs_client_instance.get_queue_url(QUEUE_NAME)
100103

101-
return sqs_cli
104+
return sqs_client_instance

tests/step_defs/test_messages_steps.py

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
1-
from pytest_bdd import scenarios, given, when, then
1+
"""
2+
steps to scenarios of cars_stream_processing feature
3+
"""
24
import json
5+
from pytest_bdd import scenarios, given, when, then
36
from utilities.settings import PROJECT_DIR
47

58
# Load feature files for pytest-bdd
69
scenarios('../features/cars_stream_processing.feature')
710

811
# Given Step
9-
@given('a list of cars are added to car queue', target_fixture='added_cars')
12+
@given('a list of cars are added to car queue', target_fixture='cars_list')
1013
def added_cars(sqs_cli: 'SQSClient', log: 'CustomLogger') -> list:
1114
"""
1215
Given step to add a list of cars to the car queue.
@@ -19,8 +22,10 @@ def added_cars(sqs_cli: 'SQSClient', log: 'CustomLogger') -> list:
1922
list: List of cars added to the queue.
2023
"""
2124
log.info("######## Start Step: 'Given a list of cars are added to car queue' ########")
22-
f = open(PROJECT_DIR + "\\test-data\\cars.json", "r")
23-
cars = json.loads(f.read())
25+
#f = open(PROJECT_DIR + "\\test-data\\cars.json", "r")
26+
#cars = json.loads(f.read())
27+
with open(PROJECT_DIR + "\\test-data\\cars.json", "r", encoding='utf-8') as f:
28+
cars = json.loads(f.read())
2429

2530
for car in cars:
2631
car_details = car["car detail"]
@@ -36,7 +41,7 @@ def added_cars(sqs_cli: 'SQSClient', log: 'CustomLogger') -> list:
3641
return cars
3742

3843
# When Step
39-
@when("the queue list is returned", target_fixture='queue_list')
44+
@when("the queue list is returned", target_fixture='messages')
4045
def queue_list(sqs_cli: 'SQSClient', log: 'CustomLogger') -> dict:
4146
"""
4247
When step to return the queue list.
@@ -58,38 +63,42 @@ def queue_list(sqs_cli: 'SQSClient', log: 'CustomLogger') -> dict:
5863

5964
# Then Step
6065
@then("the list contains the cars added")
61-
def assert_response_code(sqs_cli: 'SQSClient', added_cars: list, queue_list: dict, log: 'CustomLogger') -> None:
66+
def assert_response_code(sqs_cli: 'SQSClient',
67+
cars_list: list, messages: dict, log: 'CustomLogger') -> None:
6268
"""
6369
Then step to assert that the list contains the cars added.
6470
6571
Args:
6672
sqs_cli (SQSClient): An instance of SQSClient.
67-
added_cars (list): List of cars added to the queue.
68-
queue_list (dict): Queue list.
73+
cars_list (list): List of cars added to the queue.
74+
messages (dict): Queue list.
6975
log (CustomLogger): A CustomLogger instance.
7076
"""
7177
log.info("######## Start Step: 'Then the list contains the cars added' ########")
7278
messages_count = 0
73-
for message in queue_list["Messages"]:
79+
for message in messages["Messages"]:
7480
in_message_id = message["MessageId"]
7581
body = message["Body"]
7682
receipt_handle = message["ReceiptHandle"]
7783

7884
log.info(f"message body: {message}")
7985

80-
for car in added_cars:
86+
for car in cars_list:
8187

8288
car_details = car["car detail"]
8389
out_message_id = car["id"]
8490

8591
if in_message_id == out_message_id:
86-
87-
assert car_details == json.loads(body), f"body of the message {in_message_id} doesn't match car detail"
92+
error_msg = f"body of the message {in_message_id} doesn't match car detail"
93+
assert car_details == json.loads(body), error_msg
8894

8995
log.info(f"delete message with id {in_message_id}")
9096
sqs_cli.delete_message(receipt_handle)
9197
messages_count += 1
92-
93-
assert len(added_cars) == messages_count, f"Couldn't find all messages sent. Were sent {len(added_cars)} msgs, but found only {messages_count} msgs"
98+
99+
error_messages = f"""Couldn't find all messages sent.
100+
Were sent {len(cars_list)} msgs,
101+
but found only {messages_count} msgs"""
102+
assert len(cars_list) == messages_count, error_messages
94103

95104
log.info("######## End Step: 'Then the list contains the cars added' ########")

utilities/classes/log.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,26 @@
1+
"""
2+
A custom logger class that logs messages to both console and file with timed rotation.
3+
"""
14
import logging
25
import re
36
from logging import handlers, Logger
47

58

69
class CustomLogger(Logger):
10+
"""
11+
A custom logger class that logs messages to both console and file with timed rotation.
712
13+
This class extends the standard Logger class from the logging module and provides additional functionality
14+
for logging messages to both console and file. Log files are rotated daily, and old log files are automatically
15+
deleted after a specified number of days.
16+
17+
Attributes:
18+
log_folder (str): The directory where log files will be stored.
19+
backupCount_days (int): The number of days to keep backup log files.
20+
21+
Methods:
22+
__init__: Initializes the custom logger.
23+
"""
824
def __init__(self, log_folder: str, backupCount_days: int = 5):
925
"""
1026
Initialize the CustomLogger.
@@ -35,4 +51,4 @@ def __init__(self, log_folder: str, backupCount_days: int = 5):
3551
file_handler.suffix = '%Y_%m_%d.log'
3652
file_handler.extMatch = re.compile(r"^\d{4}_\d{2}_\d{2}.log$")
3753
file_handler.setFormatter(formatter)
38-
self.addHandler(file_handler)
54+
self.addHandler(file_handler)

utilities/classes/sqs_client.py

Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,42 @@
1+
"""
2+
SQSClient module
3+
4+
This module contains the SQSClient class which provides methods for interacting with Amazon SQS.
5+
6+
Classes:
7+
SQSClient: A class for interacting with Amazon SQS.
8+
9+
"""
10+
import json
111
import boto3
212
from botocore.exceptions import ClientError
3-
import json
413
from utilities.settings import LOCALHOST, REGION_NAME
514

615
class SQSClient:
7-
def __init__(self, log: 'CustomLogger', bucket: str, mock_aws_flag: bool, host: str = LOCALHOST, region_name: str = REGION_NAME):
16+
"""
17+
A class for interacting with Amazon SQS.
18+
19+
Attributes:
20+
log (CustomLogger): Logger object.
21+
bucket_name (str): Name of the AWS bucket.
22+
host (str): Host URL.
23+
region_name (str): AWS region name.
24+
mock_aws_flag (bool): Flag indicating whether to mock AWS or not.
25+
client (boto3.client): SQS client object.
26+
queue_url (str): URL of the SQS queue.
27+
28+
Methods:
29+
__init__: Initializes the SQSClient.
30+
create_client: Creates an SQS client based on mock_aws_flag.
31+
create_queue: Creates an SQS queue.
32+
get_queue_url: Gets the URL of an SQS queue.
33+
send_message: Sends a message to the SQS queue.
34+
receive_messages: Receives messages from the SQS queue.
35+
delete_message: Deletes a message from the SQS queue.
36+
"""
37+
38+
def __init__(self, log: 'CustomLogger', bucket: str,
39+
mock_aws_flag: bool, host: str = LOCALHOST, region_name: str = REGION_NAME):
840
"""
941
Initialize SQSClient.
1042
@@ -31,9 +63,14 @@ def create_client(self) -> boto3.client:
3163
boto3.client: SQS client object.
3264
"""
3365
if self.mock_aws_flag:
34-
return boto3.client(self.bucket_name, region_name=self.region_name)
35-
else:
36-
return boto3.client(self.bucket_name, endpoint_url=self.host, region_name=self.region_name)
66+
return boto3.client(self.bucket_name,
67+
region_name=self.region_name
68+
)
69+
70+
return boto3.client(self.bucket_name,
71+
endpoint_url=self.host,
72+
region_name=self.region_name
73+
)
3774

3875
def create_queue(self, queue_name: str) -> None:
3976
"""
@@ -82,7 +119,8 @@ def send_message(self, car: dict) -> dict:
82119
"""
83120
try:
84121
message = car
85-
response = self.client.send_message(QueueUrl=self.queue_url, MessageBody=json.dumps(message))
122+
response = self.client.send_message(QueueUrl=self.queue_url,
123+
MessageBody=json.dumps(message))
86124
self.log.info("Message sent")
87125
return response
88126
except ClientError as error:
@@ -97,7 +135,9 @@ def receive_messages(self) -> dict:
97135
dict: Messages received from the SQS service.
98136
"""
99137
try:
100-
messages = self.client.receive_message(QueueUrl=self.queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=10)
138+
messages = self.client.receive_message(QueueUrl=self.queue_url,
139+
MaxNumberOfMessages=10,
140+
WaitTimeSeconds=10)
101141
self.log.info("Messages received")
102142
return messages
103143
except ClientError as error:

0 commit comments

Comments
 (0)