Skip to content
This repository was archived by the owner on May 23, 2023. It is now read-only.

Commit a49ffe0

Browse files
Merge pull request #7 from madeiramadeirabr/unit_tests
Adição de testes de unidade e mocks
2 parents 236db4b + 15d5c8b commit a49ffe0

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+1834
-114
lines changed

examples/lambda_api/app.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,6 @@ def alive():
7070
application/json:
7171
schema: HealthCheckSchema
7272
"""
73-
# body = {"app": "I'm alive!"}
74-
# return http_helper.create_response(body=body, status_code=200)
7573
service = HealthCheckService()
7674
service.add_check("self", SelfConnectionHealthCheck(logger, config), [])
7775
service.add_check("mysql", MysqlConnectionHealthCheck(logger, config), ["db"])

examples/lambda_api/env/development.env

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ LOCAL_API_SERVER=http://localhost:5000
1212
LOCAL_API_SERVER_DESCRIPTION=Development server
1313
REDIS_HOST=redis
1414
REDIS_PORT=6379
15-
DB_HOST = mysql
16-
DB_USER = root
17-
DB_PASSWORD = store
18-
DB = store
15+
DB_HOST=mysql
16+
DB_USER=root
17+
DB_PASSWORD=store
18+
DB=store
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import os
2+
from time import sleep
3+
4+
import boto3
5+
6+
from chalicelib.logging import get_logger
7+
8+
logger = get_logger()
9+
10+
_CONNECTION = False
11+
_RETRY_COUNT = 0
12+
_MAX_RETRY_ATTEMPTS = 3
13+
14+
15+
def reset():
16+
global _CONNECTION
17+
_CONNECTION = False
18+
19+
20+
def get_connection(connect=True, retry=False):
21+
global _CONNECTION, _RETRY_COUNT, _MAX_RETRY_ATTEMPTS
22+
if not _CONNECTION:
23+
connection = None
24+
try:
25+
profile = os.environ['AWS_PROFILE'] if 'AWS_PROFILE' in os.environ else None
26+
logger.info('profile: {}'.format(profile))
27+
if profile:
28+
session = boto3.session.Session(profile_name=profile)
29+
connection = session.resource(
30+
'dynamodb',
31+
region_name="sa-east-1"
32+
)
33+
else:
34+
connection = boto3.resource(
35+
'dynamodb',
36+
region_name="sa-east-1"
37+
)
38+
39+
_CONNECTION = connection
40+
_RETRY_COUNT = 0
41+
logger.info('Connected')
42+
43+
except Exception as err:
44+
if _RETRY_COUNT == _MAX_RETRY_ATTEMPTS:
45+
_RETRY_COUNT = 0
46+
logger.error(err)
47+
return connection
48+
else:
49+
logger.error(err)
50+
logger.info('Trying to reconnect... {}'.format(_RETRY_COUNT))
51+
52+
sleep(0.1)
53+
# retry
54+
if not retry:
55+
_RETRY_COUNT += 1
56+
return get_connection(True)
57+
else:
58+
connection = _CONNECTION
59+
60+
return connection

examples/lambda_api/lambda_app/database/mysql.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from lambda_app.config import get_config
44
from lambda_app.logging import get_logger
5-
from vendor import pymysql
5+
import pymysql
66

77
logger = get_logger()
88

examples/lambda_api/lambda_app/events/aws/sqs.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,30 +9,37 @@
99
_RETRY_COUNT = 0
1010
_MAX_RETRY_ATTEMPTS = 3
1111

12+
1213
class SQSEvents:
1314

14-
def __init__(self, logger=None, config=None):
15+
def __init__(self, logger=None, config=None, profile=None, session=None):
1516
# logger
1617
self.logger = logger if logger is not None else get_logger()
1718
# configurations
1819
self.config = config if config is not None else get_config()
1920
# last_exception
2021
self.exception = None
22+
# profile
23+
self.profile = profile if profile is not None else \
24+
os.environ['AWS_PROFILE'] if 'AWS_PROFILE' in os.environ else None
25+
# session
26+
self.session = session if session is not None else \
27+
boto3.session.Session(profile_name=self.profile)
2128

2229
def connect(self, retry=False):
2330
global _RETRY_COUNT, _MAX_RETRY_ATTEMPTS
2431
connection = None
2532
try:
2633
endpoint_url = self.config.SQS_ENDPOINT
27-
profile = os.environ['AWS_PROFILE'] if 'AWS_PROFILE' in os.environ else None
34+
2835
queue_name = os.path.basename(os.environ['APP_QUEUE']) if 'APP_QUEUE' in os.environ else None
29-
self.logger.info('SQSEvents - profile: {}'.format(profile))
36+
self.logger.info('SQSEvents - profile: {}'.format(self.profile))
3037
self.logger.info('SQSEvents - endpoint_url: {}'.format(endpoint_url))
3138
self.logger.info('SQSEvents - queue_name: {}'.format(queue_name))
3239
self.logger.info('SQSEvents - self.config.REGION_NAME: {}'.format(self.config.REGION_NAME))
3340

34-
if profile:
35-
session = boto3.session.Session(profile_name=profile)
41+
if self.profile:
42+
session = self.session
3643
connection = session.resource(
3744
'sqs',
3845
endpoint_url=endpoint_url,
@@ -70,10 +77,12 @@ def connect(self, retry=False):
7077
if not retry:
7178
_RETRY_COUNT += 1
7279
# Fix para tratar diff entre docker/local
73-
if self.config.SQS_ENDPOINT == 'http://0.0.0.0:4566' or self.config.SQS_ENDPOINT == 'http://localstack:4566':
80+
if self.config.SQS_ENDPOINT == 'http://0.0.0.0:4566' or \
81+
self.config.SQS_ENDPOINT == 'http://localstack:4566':
7482
old_value = self.config.SQS_ENDPOINT
7583
self.config.SQS_ENDPOINT = 'http://localhost:4566'
76-
self.logger.info('Changing the endpoint from {} to {}'.format(old_value, self.config.SQS_ENDPOINT))
84+
self.logger.info(
85+
'Changing the endpoint from {} to {}'.format(old_value, self.config.SQS_ENDPOINT))
7786
connection = self.connect(retry=True)
7887
return connection
7988

@@ -166,7 +175,3 @@ def delete_queue(self, queue_name):
166175
result = False
167176

168177
return result
169-
170-
171-
172-

examples/lambda_api/lambda_app/repositories/mysql/__init__.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from lambda_app.database.mysql import get_connection
22
from lambda_app.logging import get_logger
3-
from vendor import pymysql
3+
import pymysql
44

55

66
class AbstractRepository:
@@ -21,7 +21,9 @@ def _execute(self, sql, params=None):
2121
self.logger.info("SQL: {}".format(sql))
2222
self.logger.info("SQL Values: {}".format(params))
2323

24-
if isinstance(self.connection, pymysql.connections.Connection):
24+
# issubclass(connection_mock.__class__, pymysql.connections.Connection)
25+
if isinstance(self.connection, pymysql.connections.Connection) \
26+
or issubclass(self.connection.__class__, pymysql.connections.Connection):
2527
# always connect because is treadsafe
2628
self.connection.connect()
2729
# with self.connection.cursor() as cursor:
@@ -36,3 +38,5 @@ def _execute(self, sql, params=None):
3638

3739
def _close(self):
3840
self.connection.close()
41+
42+

examples/lambda_api/lambda_app/repositories/mysql/product_repository.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from lambda_app.logging import get_logger
66
from lambda_app.repositories.mysql import AbstractRepository
77
from lambda_app.vos.product import ProductVO
8-
from vendor import pymysql
8+
import pymysql
99

1010

1111
class ProductRepository(AbstractRepository):

examples/lambda_api/lambda_app/services/v1/healthcheck/__init__.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,18 @@ def unhealthy(description):
3636
def degraded(description):
3737
return HealthCheckResult(HealthStatus.DEGRADED, description)
3838

39+
def __str__(self):
40+
return self.to_dict()
41+
42+
def __repr__(self):
43+
return self.to_json()
44+
45+
def to_dict(self):
46+
return {'status': self.status, 'description': self.description}
47+
48+
def to_json(self):
49+
return json.dumps(self.to_dict())
50+
3951

4052
class EntrySchema(Schema):
4153
status = fields.Str(example=HealthStatus.HEALTHY.value)

examples/lambda_api/lambda_app/services/v1/healthcheck/resources.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,20 +9,20 @@
99

1010

1111
class SelfConnectionHealthCheck(AbstractHealthCheck):
12-
def __init__(self, logger=None, config=None):
12+
def __init__(self, logger=None, config=None, http_client=None):
1313
super().__init__(logger=logger, config=config)
14+
self.http_client = http_client if http_client is not None else requests
1415

1516
def check_health(self):
1617
result = False
1718
description = "Unable to connect"
1819
check_result = HealthCheckResult.unhealthy(description)
19-
response = None
2020
try:
2121
result = True
2222
url = os.environ["API_SERVER"] if "API_SERVER" in os.environ else None
2323
url = url + "/docs"
2424
self.logger.info("requesting url: {}".format(url))
25-
response = requests.get(url)
25+
response = self.http_client.get(url)
2626
if response:
2727
if response.status_code == 200:
2828
result = True

examples/lambda_api/requirements-tests.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
serverless-wsgi
12
unittest-data-provider
23
coverage
34
coverage2clover

0 commit comments

Comments
 (0)