Skip to content

Commit

Permalink
Merge pull request #15 from TeskaLabs/Feature/Introduce-exceptions
Browse files Browse the repository at this point in the history
Introduce exception : PathError, FormatError
  • Loading branch information
mithunbharadwaj authored Mar 24, 2023
2 parents 173e305 + 7fdb154 commit 102361b
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 30 deletions.
35 changes: 35 additions & 0 deletions asabiris/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,37 @@
class SMTPDeliverError(Exception):
pass


class PathError(Exception):
"""
Equivalent to HTTP 404 Not-Found.
"""

def __init__(self, message=None, *args, path=None):
self.Path = path
if message is not None:
super().__init__(message, *args)
elif path is not None:
message = "Invalid path {!r}.".format(path)
super().__init__(message, *args)
else:
super().__init__(message, *args)


class FormatError(Exception):
"""
Equivalent to HTTP 400 Bad-request.
"""

def __init__(self, message=None, *args, format=None):
self.Format = format
if message is not None:
super().__init__(message, *args)
elif format is not None:
message = "Unsupported template format {!r}.".format(format)
super().__init__(message, *args)
else:
super().__init__(message, *args)

21 changes: 18 additions & 3 deletions asabiris/handlers/webhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from ..schemas.emailschema import email_schema
from ..schemas.slackschema import slack_schema

from ..exceptions import SMTPDeliverError
from ..exceptions import SMTPDeliverError, PathError, FormatError

#

Expand Down Expand Up @@ -112,6 +112,12 @@ async def send_email(self, request, *, json_data):
except SMTPDeliverError:
raise aiohttp.web.HTTPServiceUnavailable(text="SMTP error")

except PathError as e:
raise aiohttp.web.HTTPNotFound(text="{}".format(e))

except FormatError as e:
raise aiohttp.web.HTTPBadRequest(text="{}".format(e))

# More specific exception handling goes here so that the service provides nice output
return asab.web.rest.json_response(request, {"result": "OK"})

Expand Down Expand Up @@ -142,6 +148,12 @@ async def send_alert(self, request, *, json_data):
except jinja2.exceptions.UndefinedError as e:
raise aiohttp.web.HTTPBadRequest(text="Jinja2 error: {}".format(e))

except PathError as e:
raise aiohttp.web.HTTPNotFound(text="{}".format(e))

except FormatError as e:
raise aiohttp.web.HTTPBadRequest(text="{}".format(e))

# More specific exception handling goes here so that the service provides nice output

return asab.web.rest.json_response(request, {"result": "OK"})
Expand Down Expand Up @@ -175,7 +187,10 @@ async def render(self, request):
template_data = await request.json()

# Render a body
html = await self.App.RenderReportOrchestrator.render(template, template_data)
try:
html = await self.App.RenderReportOrchestrator.render(template, template_data)
except PathError as e:
raise aiohttp.web.HTTPNotFound(text="{}".format(e))

# get pdf from html if present.
if fmt == 'pdf':
Expand All @@ -184,7 +199,7 @@ async def render(self, request):
elif fmt == 'html':
content_type = "text/html"
else:
raise ValueError("Invalid/unknown format: '{}'".format(fmt))
raise aiohttp.web.HTTPBadRequest(text="Invalid/unknown conversion format: '{}'".format(fmt))

return aiohttp.web.Response(
content_type=content_type,
Expand Down
7 changes: 4 additions & 3 deletions asabiris/orchestration/render.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
import logging

from .. exceptions import PathError, FormatError
from .. import utils

#
Expand All @@ -26,8 +27,8 @@ async def render(self, template, params):
# - if absolute path is used, check it start with "/Templates"
# - if it is not absolute path, it is file name - assume it's a file in Templates folder
# templates must be stores in /Templates/General
if not template.startswith("/Templates/General"):
raise ValueError("Template must be stored in /Templates/General directory")
if not template.startswith("/Templates/General/"):
raise PathError(path=template)

html = await self.JinjaService.format(template, params)
_, extension = os.path.splitext(template)
Expand All @@ -42,4 +43,4 @@ async def render(self, template, params):

return html

raise RuntimeError("Failed to render templates. Reason: Unknown extention '{}'".format(extension))
raise FormatError(format=extension)
14 changes: 7 additions & 7 deletions asabiris/orchestration/sendemail.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import logging

from .. import utils

from .. exceptions import PathError, FormatError
#

L = logging.getLogger(__name__)
Expand Down Expand Up @@ -70,8 +70,8 @@ async def send_email(
if template is not None:
params = a.get('params', {})
# templates must be stores in /Templates/Emails
if not template.startswith("/Templates/Email"):
raise ValueError("Template must be stored in /Templates/Email directory")
if not template.startswith("/Templates/Email/"):
raise PathError(path=template)

# get file-name of the attachment
file_name = self.get_file_name(a)
Expand All @@ -86,7 +86,7 @@ async def send_email(
result = jinja_output.encode("utf-8")
content_type = "text/html"
else:
raise ValueError("Invalid/unknown format '{}'".format(fmt))
raise FormatError(format=fmt)

atts.append((result, content_type, file_name))
continue
Expand Down Expand Up @@ -122,8 +122,8 @@ async def render(self, template, params):
jinja_output will be used for extracting subject.
"""
# templates must be stores in /Templates/Emails
if not template.startswith("/Templates/Email"):
raise ValueError("Template must be stored in /Templates/Email directory")
if not template.startswith("/Templates/Email/"):
raise PathError(path=template)

try:
jinja_output = await self.JinjaService.format(template, params)
Expand All @@ -144,7 +144,7 @@ async def render(self, template, params):
return html_output, subject

else:
raise RuntimeError("Failed to render templates. Reason: Unknown extention '{}'".format(extension))
raise FormatError(format=extension)

def get_file_name(self, attachment):
"""
Expand Down
5 changes: 3 additions & 2 deletions asabiris/orchestration/sendslack.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
import fastjsonschema

from .. exceptions import PathError
from ..schemas import slack_schema

L = logging.getLogger(__name__)
Expand Down Expand Up @@ -35,8 +36,8 @@ async def send_to_slack(self, msg):
# - if it is not absolute path, it is file name - assume it's a file in Templates folder

# templates must be stores in /Templates/Slack
if not body['template'].startswith("/Templates/Slack"):
raise ValueError("Template must be stored in /Templates/Slack directory")
if not body['template'].startswith("/Templates/Slack/"):
raise PathError(path=body['template'])

body["params"] = body.get("params", {})
output = await self.JinjaService.format(body["template"], body["params"])
Expand Down
30 changes: 15 additions & 15 deletions qa.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@



## TSM005: Try to send an email with template as body and attachment.
## TSM005: Try to send an email with template as body and attachment.(Format=pdf)

`PUT /send_mail`

Expand All @@ -112,7 +112,7 @@
```


## TSM005: Try to send an email with template as body and attachment.
## TSM006: Try to send an email with template as body and attachment.(Format=html)

`PUT /send_mail`

Expand All @@ -138,7 +138,7 @@
}
```

## TSM006: Try to send an email with template as body and a missing html attachment.
## TSM007: Try to send an email with template as body and a missing html attachment.

`PUT /send_mail`

Expand All @@ -165,7 +165,7 @@
```

## TSM007: Try to send an email with template as body and a missing html attachment.
## TSM008: Try to send an email with template as body and a missing html attachment.


`PUT /send_mail`
Expand Down Expand Up @@ -193,7 +193,7 @@
```


## TSM008: Try to send an email with missing template
## TSM009: Try to send an email with missing template

`PUT /send_mail`

Expand All @@ -207,7 +207,7 @@
```

## TSM009: Try to send an email with no template
## TSM0010: Try to send an email with no template

`PUT /send_mail`

Expand All @@ -226,7 +226,7 @@ EXPECTED RESPONSE:
}
```

## TSM010: Try to send an email with base64 attachment.
## TSM011: Try to send an email with base64 attachment.

`PUT /send_mail`

Expand All @@ -244,7 +244,7 @@ EXPECTED RESPONSE:
}
```

## TSM011: Try to render PDF report using html template
## TSM012: Try to render PDF report using html template

`PUT /render?format=html&template=/Templates/General/hello.html`

Expand All @@ -254,7 +254,7 @@ EXPECTED RESPONSE:
}
```

## TSM012: Try to render PDF report using html template
## TSM013: Try to render PDF report using html template

`PUT /render?format=pdf&template=/Templates/General/hello.html`

Expand All @@ -264,7 +264,7 @@ EXPECTED RESPONSE:
}
```

## TSM013: Try to render PDF report using markdown template
## TSM014: Try to render PDF report using markdown template

`PUT /render?format=pdf&template=/Templates/General/hello.md`

Expand All @@ -274,7 +274,7 @@ EXPECTED RESPONSE:
}
```

## TSM014: Try to render PDF report using html template
## TSM015: Try to render PDF report using html template

`PUT /render?format=html&template=/Templates/General/hello.md`

Expand All @@ -284,7 +284,7 @@ EXPECTED RESPONSE:
}
```

## TSM015: Try to render PDF using missing template
## TSM016: Try to render PDF using missing template

`PUT /render?format=pdf&template=/Templates/MISSING.html`

Expand All @@ -300,7 +300,7 @@ EXPECTED RESPONSE:
}
```

## TSM016: Try to render HTML using missing template
## TSM017: Try to render HTML using missing template

`PUT /render?format=html&template=/Templates/MISSING.html`

Expand All @@ -317,7 +317,7 @@ EXPECTED RESPONSE:
}
```

## TSM017: Try to send Slack message using markdown template
## TSM018: Try to send Slack message using markdown template

`PUT /send_slack`

Expand All @@ -333,7 +333,7 @@ EXPECTED RESPONSE:
}
```

## TSM018: Try to send Slack message using missing template
## TSM019: Try to send Slack message using missing template

`PUT /send_slack`

Expand Down

0 comments on commit 102361b

Please sign in to comment.