Skip to content

Commit 1836f12

Browse files
authored
chore: add given then when and minor refactors (#741)
1 parent bc9c9ad commit 1836f12

19 files changed

+569
-424
lines changed

Makefile

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ dev:
1010
poetry install
1111
npm ci
1212

13+
format-fix:
14+
poetry run isort .
15+
poetry run yapf -vv --style=./.style -r --in-place .
16+
1317
format:
1418
poetry run isort .
1519
poetry run yapf -d -vv --style=./.style -r .
@@ -68,3 +72,7 @@ docs:
6872

6973
lint-docs:
7074
docker run -v ${PWD}:/markdown 06kellyjac/markdownlint-cli --fix "docs"
75+
76+
77+
watch:
78+
npx cdk watch

cdk.json

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,16 @@
11
{
2-
"app": "poetry run python app.py"
2+
"app": "poetry run python app.py",
3+
"watch": {
4+
"include": [
5+
"service/**",
6+
"cdk/service/**"
7+
],
8+
"exclude": [
9+
"service/**/*.pyc",
10+
"service/**/__pycache__",
11+
"cdk/**/*.pyc",
12+
"cdk/**/__pycache__"
13+
]
14+
},
15+
"build": "make build"
316
}

cdk/service/api_construct.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def _add_post_lambda_integration(self, api_name: aws_apigateway.Resource, role:
8787
constants.CREATE_LAMBDA,
8888
runtime=_lambda.Runtime.PYTHON_3_11,
8989
code=_lambda.Code.from_asset(constants.BUILD_FOLDER),
90-
handler='service.handlers.create_order.create_order',
90+
handler='service.handlers.create_order.lambda_handler',
9191
environment={
9292
constants.POWERTOOLS_SERVICE_NAME: constants.SERVICE_NAME, # for logger, tracer and metrics
9393
constants.POWER_TOOLS_LOG_LEVEL: 'DEBUG', # for logger

cdk/service/service_stack.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import os
1+
import getpass
22
from pathlib import Path
33

44
from aws_cdk import Aspects, Stack, Tags
@@ -13,7 +13,7 @@
1313

1414
def get_username() -> str:
1515
try:
16-
return os.getlogin().replace('.', '-')
16+
return getpass.getuser().replace('.', '-')
1717
except Exception:
1818
return 'github'
1919

@@ -22,8 +22,11 @@ def get_stack_name() -> str:
2222
repo = Repo(Path.cwd())
2323
username = get_username()
2424
try:
25-
return f'{username}-{repo.active_branch}-{SERVICE_NAME}'
25+
branch_name = f'{repo.active_branch}'.replace('/', '-').replace('_', '-')
26+
return f'{username}-{branch_name}-{SERVICE_NAME}'
2627
except TypeError:
28+
# we're running in detached mode (HEAD)
29+
# see https://github.com/gitpython-developers/GitPython/issues/633
2730
return f'{username}-{SERVICE_NAME}'
2831

2932

mypy.ini

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,12 @@ warn_unused_ignores=True
77
show_column_numbers = True
88
show_error_codes = True
99
show_error_context = True
10+
plugins = pydantic.mypy
1011

12+
[pydantic-mypy]
13+
init_forbid_extra = true
14+
init_typed = true
15+
warn_required_dynamic_aliases = true
1116

1217
# Disable specific error codes in the 'tests' package
1318
[mypy-tests.*]

package-lock.json

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"dependencies": {
3-
"aws-cdk": "^2.97.0"
3+
"aws-cdk": "^2.99.1"
44
}
55
}

poetry.lock

Lines changed: 401 additions & 383 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,11 @@ aws-lambda-env-modeler = "*"
2828
[tool.poetry.dev-dependencies]
2929
# CDK
3030
service-cdk = {path = "cdk", develop = true}
31-
aws-cdk-lib = ">=2.93.0"
31+
aws-cdk-lib = ">=2.99.0"
3232
constructs = ">=10.0.0"
3333
cdk-nag = ">2.0.0"
34-
"aws-cdk.aws-lambda-python-alpha" = "^2.93.0-alpha.0"
35-
"aws-cdk.aws-appconfig-alpha" = "^2.93.0-alpha.0"
34+
"aws-cdk.aws-lambda-python-alpha" = "^2.99.0-alpha.0"
35+
"aws-cdk.aws-appconfig-alpha" = "^2.99.0-alpha.0"
3636
# DEV
3737
pytest = "*"
3838
pytest-mock = "*"
@@ -74,3 +74,6 @@ skip = [
7474

7575
[tool.yapfignore]
7676
ignore_patterns = [".git", ".venv", ".build", "cdk.out", "node_modules"]
77+
78+
[tool.pytest.ini_options]
79+
testpaths = "tests"

service/handlers/create_order.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from service.handlers.utils.dynamic_configuration import parse_configuration
1414
from service.handlers.utils.http_responses import build_response
1515
from service.handlers.utils.observability import logger, metrics, tracer
16-
from service.logic.handle_create_request import handle_create_request
16+
from service.logic.create_order import create_order
1717
from service.schemas.exceptions import InternalServerException
1818
from service.schemas.input import CreateOrderRequest
1919
from service.schemas.output import CreateOrderOutput
@@ -22,7 +22,7 @@
2222
@init_environment_variables(model=MyHandlerEnvVars)
2323
@metrics.log_metrics
2424
@tracer.capture_lambda_handler(capture_response=False)
25-
def create_order(event: Dict[str, Any], context: LambdaContext) -> Dict[str, Any]:
25+
def lambda_handler(event: Dict[str, Any], context: LambdaContext) -> Dict[str, Any]:
2626
logger.set_correlation_id(context.aws_request_id)
2727

2828
env_vars: MyHandlerEnvVars = get_environment_variables(model=MyHandlerEnvVars)
@@ -45,7 +45,7 @@ def create_order(event: Dict[str, Any], context: LambdaContext) -> Dict[str, Any
4545

4646
metrics.add_metric(name='ValidCreateOrderEvents', unit=MetricUnit.Count, value=1)
4747
try:
48-
response: CreateOrderOutput = handle_create_request(
48+
response: CreateOrderOutput = create_order(
4949
order_request=create_input,
5050
table_name=env_vars.TABLE_NAME,
5151
context=context,

service/logic/handle_create_request.py renamed to service/logic/create_order.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
output_serializer=PydanticSerializer,
2121
)
2222
@tracer.capture_method(capture_response=False)
23-
def handle_create_request(order_request: CreateOrderRequest, table_name: str, context: LambdaContext) -> CreateOrderOutput:
23+
def create_order(order_request: CreateOrderRequest, table_name: str, context: LambdaContext) -> CreateOrderOutput:
2424
IDEMPOTENCY_CONFIG.register_lambda_context(context) # see Lambda timeouts section
2525

2626
logger.info('starting to handle create request', extra={

tests/integration/test_create_order.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ def call_create_order(body: Dict[str, Any]) -> Dict[str, Any]:
4848
# important is done here since idempotency decorator requires an env. variable during import time
4949
# conf.test sets that env. variable (table name) but it runs after imports
5050
# this way, idempotency import runs after conftest sets the values already
51-
from service.handlers.create_order import create_order
52-
return create_order(body, generate_context())
51+
from service.handlers.create_order import lambda_handler
52+
return lambda_handler(body, generate_context())
5353

5454

5555
def test_handler_200_ok(mocker, table_name: str):

tests/integration/test_feature_flags.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ def call_create_order(body: Dict[str, Any]) -> Dict[str, Any]:
6060
# important is done here since idempotency decorator requires an env. variable during import time
6161
# conf.test sets that env. variable (table name) but it runs after imports
6262
# this way, idempotency import runs after conftest sets the values already
63-
from service.handlers.create_order import create_order
64-
return create_order(body, generate_context())
63+
from service.handlers.create_order import lambda_handler
64+
return lambda_handler(body, generate_context())
6565

6666

6767
def assert_response(response: Dict[str, Any], expected_response_code: HTTPStatus, expected_customer_name: str, expected_order_item_count: int):
@@ -74,12 +74,12 @@ def assert_response(response: Dict[str, Any], expected_response_code: HTTPStatus
7474

7575

7676
def spy_on_campaign_logic(mocker):
77-
import service.logic.handle_create_request as cr
77+
import service.logic.create_order as cr
7878
return mocker.spy(cr, 'handle_campaign')
7979

8080

8181
def spy_on_premium_logic(mocker):
82-
import service.logic.handle_create_request as cr
82+
import service.logic.create_order as cr
8383
return mocker.spy(cr, 'apply_premium_user_discount')
8484

8585

tests/unit/test_create_order_input.py

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,53 @@
33

44
from service.schemas.input import CreateOrderRequest
55

6+
# ... potentially more imports based on your project ...
7+
68

79
def test_invalid_name():
10+
# Given: An empty customer_name
11+
customer_name = ''
12+
order_item_count = 4
13+
14+
# When & Then: CreateOrderRequest is initialized, expect a ValidationError
815
with pytest.raises(ValidationError):
9-
CreateOrderRequest(customer_name='', order_item_count=4)
16+
CreateOrderRequest(customer_name=customer_name, order_item_count=order_item_count)
1017

1118

1219
def test_invalid_name_too_long():
20+
# Given: A too long customer_name
21+
customer_name = '1' * 33 # or '1234567890112123423232323232323' based on your original code
22+
order_item_count = 4
23+
24+
# When & Then: CreateOrderRequest is initialized, expect a ValidationError
1325
with pytest.raises(ValidationError):
14-
CreateOrderRequest(customer_name='1234567890112123423232323232323', order_item_count=4)
26+
CreateOrderRequest(customer_name=customer_name, order_item_count=order_item_count)
1527

1628

1729
def test_missing_mandatory_fields():
30+
# Given: A missing order_item_count
31+
customer_name = 'a'
32+
33+
# When & Then: CreateOrderRequest is initialized, expect a ValidationError
1834
with pytest.raises(ValidationError):
19-
CreateOrderRequest(customer_name='a')
35+
CreateOrderRequest(customer_name=customer_name)
2036

2137

2238
def test_invalid_order_number():
39+
# Given: An invalid negative order_item_count
40+
customer_name = 'a'
41+
order_item_count = -1
42+
43+
# When & Then: CreateOrderRequest is initialized, expect a ValidationError
2344
with pytest.raises(ValidationError):
24-
CreateOrderRequest(customer_name='a', order_item_count=-1)
45+
CreateOrderRequest(customer_name=customer_name, order_item_count=order_item_count)
2546

2647

2748
def test_invalid_order_number_type():
49+
# Given: A non-integer order_item_count
50+
customer_name = 'a'
51+
order_item_count = 'a'
52+
53+
# When & Then: CreateOrderRequest is initialized, expect a ValidationError
2854
with pytest.raises(ValidationError):
29-
CreateOrderRequest(customer_name='a', order_item_count='a')
55+
CreateOrderRequest(customer_name=customer_name, order_item_count=order_item_count)

tests/unit/test_create_order_output.py

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,24 +9,51 @@
99

1010

1111
def test_invalid_items_type():
12+
# Given: An invalid non-integer order_item_count
13+
customer_name = '3333'
14+
order_item_count = 'a'
15+
16+
# When & Then: CreateOrderOutput is initialized, expect a ValidationError
1217
with pytest.raises(ValidationError):
13-
CreateOrderOutput(order_id=order_id, customer_name='3333', order_item_count='a')
18+
CreateOrderOutput(order_id=order_id, customer_name=customer_name, order_item_count=order_item_count)
1419

1520

1621
def test_invalid_items_negative():
22+
# Given: An invalid negative order_item_count
23+
customer_name = '3333'
24+
order_item_count = -1
25+
26+
# When & Then: CreateOrderOutput is initialized, expect a ValidationError
1727
with pytest.raises(ValidationError):
18-
CreateOrderOutput(order_id=order_id, customer_name='3333', order_item_count=-1)
28+
CreateOrderOutput(order_id=order_id, customer_name=customer_name, order_item_count=order_item_count)
1929

2030

2131
def test_invalid_items_zero():
32+
# Given: An invalid zero order_item_count
33+
customer_name = '3333'
34+
order_item_count = 0
35+
36+
# When & Then: CreateOrderOutput is initialized, expect a ValidationError
2237
with pytest.raises(ValidationError):
23-
CreateOrderOutput(order_id=order_id, customer_name='3333', order_item_count=0)
38+
CreateOrderOutput(order_id=order_id, customer_name=customer_name, order_item_count=order_item_count)
2439

2540

2641
def test_invalid_order_id():
42+
# Given: An invalid order_id
43+
order_id_invalid = '2'
44+
customer_name = '3333'
45+
order_item_count = 2
46+
47+
# When & Then: CreateOrderOutput is initialized, expect a ValidationError
2748
with pytest.raises(ValidationError):
28-
CreateOrderOutput(order_id='2', customer_name='3333', order_item_count=2)
49+
CreateOrderOutput(order_id=order_id_invalid, customer_name=customer_name, order_item_count=order_item_count)
2950

3051

3152
def test_valid_output():
32-
CreateOrderOutput(customer_name='222', order_item_count=4, order_id=order_id)
53+
# Given: Valid inputs
54+
customer_name = '222'
55+
order_item_count = 4
56+
57+
# When: CreateOrderOutput is initialized
58+
# Then: No exception should be raised
59+
CreateOrderOutput(order_id=order_id, customer_name=customer_name, order_item_count=order_item_count)

tests/unit/test_dal_schema.py

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,24 +9,51 @@
99

1010

1111
def test_invalid_items_type():
12+
# Given: An invalid non-integer order_item_count
13+
customer_name = '3333'
14+
order_item_count = 'a'
15+
16+
# When & Then: OrderEntry is initialized, expect a ValidationError
1217
with pytest.raises(ValidationError):
13-
OrderEntry(order_id=order_id, customer_name='3333', order_item_count='a')
18+
OrderEntry(order_id=order_id, customer_name=customer_name, order_item_count=order_item_count)
1419

1520

1621
def test_invalid_items_negative():
22+
# Given: An invalid negative order_item_count
23+
customer_name = '3333'
24+
order_item_count = -1
25+
26+
# When & Then: OrderEntry is initialized, expect a ValidationError
1727
with pytest.raises(ValidationError):
18-
OrderEntry(order_id=order_id, customer_name='3333', order_item_count=-1)
28+
OrderEntry(order_id=order_id, customer_name=customer_name, order_item_count=order_item_count)
1929

2030

2131
def test_invalid_items_zero():
32+
# Given: An invalid zero order_item_count
33+
customer_name = '3333'
34+
order_item_count = 0
35+
36+
# When & Then: OrderEntry is initialized, expect a ValidationError
2237
with pytest.raises(ValidationError):
23-
OrderEntry(order_id=order_id, customer_name='3333', order_item_count=0)
38+
OrderEntry(order_id=order_id, customer_name=customer_name, order_item_count=order_item_count)
2439

2540

2641
def test_invalid_order_id():
42+
# Given: An invalid order_id
43+
order_id_invalid = '2'
44+
customer_name = '3333'
45+
order_item_count = 2
46+
47+
# When & Then: OrderEntry is initialized, expect a ValidationError
2748
with pytest.raises(ValidationError):
28-
OrderEntry(order_id='2', customer_name='3333', order_item_count=2)
49+
OrderEntry(order_id=order_id_invalid, customer_name=customer_name, order_item_count=order_item_count)
2950

3051

3152
def test_valid_output():
32-
OrderEntry(customer_name='222', order_item_count=4, order_id=order_id)
53+
# Given: Valid inputs
54+
customer_name = '222'
55+
order_item_count = 4
56+
57+
# When: OrderEntry is initialized
58+
# Then: No exception should be raised
59+
OrderEntry(order_id=order_id, customer_name=customer_name, order_item_count=order_item_count)

0 commit comments

Comments
 (0)