From: Christian Heller Date: Sun, 17 Mar 2024 00:24:00 +0000 (+0100) Subject: Re-structure for unittest usage. X-Git-Url: https://plomlompom.com/repos/%22https:/validator.w3.org/%7B%7Bdb.prefix%7D%7D/%27%29;%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20chunks.push%28escapeHTML%28span%5B2%5D%29%29;%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20chunks.push%28%27?a=commitdiff_plain;h=4546631ed7cc59f3e66a1902b28930f955b2b03f;p=plomtask Re-structure for unittest usage. --- diff --git a/.pylintrc b/.pylintrc index 45e0778..8033983 100644 --- a/.pylintrc +++ b/.pylintrc @@ -1,3 +1,3 @@ [BASIC] - -good-names-rgx=do_(GET|POST)(_[a-z]+)? +init-hook='import sys; sys.path.append(".")' +good-names-rgxs=do_(GET|POST)(_[a-z]+)?,test_[A-Z]+ diff --git a/days.py b/days.py deleted file mode 100644 index 8db9f15..0000000 --- a/days.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python3 -"""Collecting Day and date-related items.""" -from datetime import datetime - -DATE_FORMAT = '%Y-%m-%d' - - -class Day: - """Individual days defined by their dates.""" - - def __init__(self, date: str): - self.date = date - self.datetime = datetime.strptime(date, DATE_FORMAT) - - @property - def weekday(self): - """Return what weekday matches self.date.""" - return self.datetime.strftime('%A') - - def __eq__(self, other: object): - return isinstance(other, self.__class__) and self.date == other.date - - def __lt__(self, other): - return self.date < other.date diff --git a/plomtask/days.py b/plomtask/days.py new file mode 100644 index 0000000..8db9f15 --- /dev/null +++ b/plomtask/days.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +"""Collecting Day and date-related items.""" +from datetime import datetime + +DATE_FORMAT = '%Y-%m-%d' + + +class Day: + """Individual days defined by their dates.""" + + def __init__(self, date: str): + self.date = date + self.datetime = datetime.strptime(date, DATE_FORMAT) + + @property + def weekday(self): + """Return what weekday matches self.date.""" + return self.datetime.strftime('%A') + + def __eq__(self, other: object): + return isinstance(other, self.__class__) and self.date == other.date + + def __lt__(self, other): + return self.date < other.date diff --git a/plomtask/task.py b/plomtask/task.py new file mode 100755 index 0000000..49ca883 --- /dev/null +++ b/plomtask/task.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""plom's task manager""" +from http.server import BaseHTTPRequestHandler +from http.server import HTTPServer +from urllib.parse import urlparse +from os.path import split as path_split +from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader +from .days import Day + +HTTP_PORT = 8082 +TEMPLATES_DIR = 'templates' + + +class HandledException(Exception): + """To identify Exceptions based on expected (if faulty) user behavior.""" + + +class TaskServer(HTTPServer): + """Variant of HTTPServer that knows .jinja as Jinja Environment.""" + + def __init__(self, *args, **kwargs): + super().__init__(self, *args, **kwargs) + self.jinja = JinjaEnv(loader=JinjaFSLoader(TEMPLATES_DIR)) + + +class TaskHandler(BaseHTTPRequestHandler): + """Handles single HTTP request.""" + server: TaskServer + + def send_html(self, html: str, code: int = 200): + """Send HTML as proper HTTP response.""" + self.send_response(code) + self.end_headers() + self.wfile.write(bytes(html, 'utf-8')) + + def send_msg(self, msg: str, code: int = 400): + """Send message in HTML formatting as HTTP response.""" + html = self.server.jinja.get_template('msg.html').render(msg=msg) + self.send_html(html, code) + + def do_GET(self): + """Handle any GET request.""" + try: + parsed_url = urlparse(self.path) + site = path_split(parsed_url.path)[1] + if 'calendar' == site: + html = self.do_GET_calendar() + else: + raise HandledException('Test!') + self.send_html(html) + except HandledException as error: + self.send_msg(error) + + def do_GET_calendar(self): + """Show sorted Days.""" + days = [Day('2024-01-03'), Day('2024-01-01'), Day('2024-01-02')] + days.sort() + return self.server.jinja.get_template('calendar.html').render( + days=days) + + +def main(): + """Main loop.""" + server = TaskServer(('localhost', HTTP_PORT), TaskHandler) + print(f'running at port {HTTP_PORT}') + try: + server.serve_forever() + except KeyboardInterrupt: + print('aborting due to keyboard interrupt') + server.server_close() + + +if __name__ == '__main__': + from sys import exit as sys_exit + try: + main() + except HandledException as e: + print(f'Aborting due to: {e}') + sys_exit(1) diff --git a/scripts/pre-commit b/scripts/pre-commit index 9400e92..813455c 100755 --- a/scripts/pre-commit +++ b/scripts/pre-commit @@ -1,6 +1,10 @@ #!/bin/sh set -e -python3 -m mypy *.py -python3 -m flake8 *.py -python3 -m pylint *.py +python3 -m mypy plomtask/*.py +python3 -m flake8 plomtask/*.py +python3 -m pylint plomtask/*.py +python3 -m mypy tests/*.py +python3 -m flake8 tests/*.py +python3 -m pylint tests/*.py +python3 -m unittest tests/*.py exit 0 diff --git a/task.py b/task.py deleted file mode 100755 index 9631434..0000000 --- a/task.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python3 -"""plom's task manager""" -from http.server import BaseHTTPRequestHandler -from http.server import HTTPServer -from urllib.parse import urlparse -from os.path import split as path_split -from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader -from days import Day - -HTTP_PORT = 8082 -TEMPLATES_DIR = 'templates' - - -class HandledException(Exception): - """To identify Exceptions based on expected (if faulty) user behavior.""" - - -class TaskServer(HTTPServer): - """Variant of HTTPServer that knows .jinja as Jinja Environment.""" - - def __init__(self, *args, **kwargs): - super().__init__(self, *args, **kwargs) - self.jinja = JinjaEnv(loader=JinjaFSLoader(TEMPLATES_DIR)) - - -class TaskHandler(BaseHTTPRequestHandler): - """Handles single HTTP request.""" - server: TaskServer - - def send_html(self, html: str, code: int = 200): - """Send HTML as proper HTTP response.""" - self.send_response(code) - self.end_headers() - self.wfile.write(bytes(html, 'utf-8')) - - def send_msg(self, msg: str, code: int = 400): - """Send message in HTML formatting as HTTP response.""" - html = self.server.jinja.get_template('msg.html').render(msg=msg) - self.send_html(html, code) - - def do_GET(self): - """Handle any GET request.""" - try: - parsed_url = urlparse(self.path) - site = path_split(parsed_url.path)[1] - if 'calendar' == site: - html = self.do_GET_calendar() - else: - raise HandledException('Test!') - self.send_html(html) - except HandledException as error: - self.send_msg(error) - - def do_GET_calendar(self): - """Show sorted Days.""" - days = [Day('2024-01-03'), Day('2024-01-01'), Day('2024-01-02')] - days.sort() - return self.server.jinja.get_template('calendar.html').render( - days=days) - - -def main(): - """Main loop.""" - server = TaskServer(('localhost', HTTP_PORT), TaskHandler) - print(f'running at port {HTTP_PORT}') - try: - server.serve_forever() - except KeyboardInterrupt: - print('aborting due to keyboard interrupt') - server.server_close() - - -if __name__ == '__main__': - from sys import exit as sys_exit - try: - main() - except HandledException as e: - print(f'Aborting due to: {e}') - sys_exit(1) diff --git a/tests/test_days.py b/tests/test_days.py new file mode 100644 index 0000000..c799f06 --- /dev/null +++ b/tests/test_days.py @@ -0,0 +1,11 @@ +"""Test days module.""" +from unittest import TestCase +from plomtask.days import Day + + +class DayTests(TestCase): + """Tests for testing the days module.""" + + def test_Day_weekday(self): + """Test Day.weekday.""" + self.assertEqual(Day('2024-03-17').weekday, 'Sunday')