diff --git a/Final_Task.md b/Final_Task.md new file mode 100644 index 00000000..2e2e618a --- /dev/null +++ b/Final_Task.md @@ -0,0 +1,195 @@ +# Introduction to Python. Final task. +You are proposed to implement Python RSS-reader using **python 3.9**. + +The task consists of few iterations. Do not start new iteration if the previous one is not implemented yet. + +## Common requirements. +* It is mandatory to use `argparse` module. +* Codebase must be covered with unit tests with at least 50% coverage. It's a mandatory requirement. +* Yor script should **not** require installation of other services such as mysql server, +postgresql and etc. (except Iteration 6). If it does require such programs, +they should be installed automatically by your script, without user doing anything. +* In case of any mistakes utility should print human-readable. +error explanation. Exception tracebacks in stdout are prohibited in final version of application. +* Docstrings are mandatory for all methods, classes, functions and modules. +* Code must correspond to `pep8` (use `pycodestyle` utility for self-check). + * You can set line length up to 120 symbols. +* Commit messages should provide correct and helpful information about changes in commit. Messages like `Fix bug`, +`Tried to make workable`, `Temp commit` and `Finally works` are prohibited. +* All used third-party packages should be written in the `requirements.txt` file and in installation files (`setup.py`, `setup.cfg`, etc.). +* You have to write a file with documentation. Everything must be documented: how to run scripts, how to run tests, how to install the library and etc. + +## [Iteration 1] One-shot command-line RSS reader. +RSS reader should be a command-line utility which receives [RSS](wikipedia.org/wiki/RSS) URL and prints results in human-readable format. + +You are free to choose format of the news console output. The textbox below provides an example of how it can be implemented: + +```shell +$ rss_reader.py "https://news.yahoo.com/rss/" --limit 1 + +Feed: Yahoo News - Latest News & Headlines + +Title: Nestor heads into Georgia after tornados damage Florida +Date: Sun, 20 Oct 2019 04:21:44 +0300 +Link: https://news.yahoo.com/wet-weekend-tropical-storm-warnings-131131925.html + +[image 2: Nestor heads into Georgia after tornados damage Florida][2]Nestor raced across Georgia as a post-tropical cyclone late Saturday, hours after the former tropical storm spawned a tornado that damaged +homes and a school in central Florida while sparing areas of the Florida Panhandle devastated one year earlier by Hurricane Michael. The storm made landfall Saturday on St. Vincent Island, a nature preserve +off Florida's northern Gulf Coast in a lightly populated area of the state, the National Hurricane Center said. Nestor was expected to bring 1 to 3 inches of rain to drought-stricken inland areas on its +march across a swath of the U.S. Southeast. + + +Links: +[1]: https://news.yahoo.com/wet-weekend-tropical-storm-warnings-131131925.html (link) +[2]: http://l2.yimg.com/uu/api/res/1.2/Liyq2kH4HqlYHaS5BmZWpw--/YXBwaWQ9eXRhY2h5b247aD04Njt3PTEzMDs-/https://media.zenfs.com/en/ap.org/5ecc06358726cabef94585f99050f4f0 (image) + +``` + +Utility should provide the following interface: +```shell +usage: rss_reader.py [-h] [--version] [--json] [--verbose] [--limit LIMIT] + source + +Pure Python command-line RSS reader. + +positional arguments: + source RSS URL + +optional arguments: + -h, --help show this help message and exit + --version Print version info + --json Print result as JSON in stdout + --verbose Outputs verbose status messages + --limit LIMIT Limit news topics if this parameter provided + +``` + +In case of using `--json` argument your utility should convert the news into [JSON](https://en.wikipedia.org/wiki/JSON) format. +You should come up with the JSON structure on you own and describe it in the README.md file for your repository or in a separate documentation file. + + + +With the argument `--verbose` your program should print all logs in stdout. + +### Task clarification (I) + +1) If `--version` option is specified app should _just print its version_ and stop. +2) User should be able to use `--version` option without specifying RSS URL. For example: +``` +> python rss_reader.py --version +"Version 1.4" +``` +3) The version is supposed to change with every iteration. +4) If `--limit` is not specified, then user should get _all_ available feed. +5) If `--limit` is larger than feed size then user should get _all_ available news. +6) `--verbose` should print logs _in the process_ of application running, _not after everything is done_. +7) Make sure that your app **has no encoding issues** (meaning symbols like `'` and etc) when printing news to _stdout_. +8) Make sure that your app **has no encoding issues** (meaning symbols like `'` and etc) when printing news to _stdout in JSON format_. +9) It is preferrable to have different custom exceptions for different situations(If needed). +10) The `--limit` argument should also affect JSON generation. + + +## [Iteration 2] Distribution. + +* Utility should be wrapped into distribution package with `setuptools`. +* This package should export CLI utility named `rss-reader`. + + +### Task clarification (II) + +1) User should be able to run your application _both_ with and without installation of CLI utility, +meaning that this should work: + +``` +> python rss_reader.py ... +``` + +as well as this: + +``` +> rss_reader ... +``` +2) Make sure your second iteration works on a clean machie with python 3.9. (!) +3) Keep in mind that installed CLI utility should have the same functionality, so do not forget to update dependencies and packages. + + +## [Iteration 3] News caching. +The RSS news should be stored in a local storage while reading. The way and format of this storage you can choose yourself. +Please describe it in a separate section of README.md or in the documentation. + +New optional argument `--date` must be added to your utility. It should take a date in `%Y%m%d` format. +For example: `--date 20191020` +Here date means actual *publishing date* not the date when you fetched the news. + +The cashed news can be read with it. The new from the specified day will be printed out. +If the news are not found return an error. + +If the `--date` argument is not provided, the utility should work like in the previous iterations. + +### Task clarification (III) +1) Try to make your application crossplatform, meaning that it should work on both Linux and Windows. +For example when working with filesystem, try to use `os.path` lib instead of manually concatenating file paths. +2) `--date` should **not** require internet connection to fetch news from local cache. +3) User should be able to use `--date` without specifying RSS source. For example: +``` +> python rss_reader.py --date 20191206 +...... +``` +Or for second iteration (when installed using setuptools): +``` +> rss_reader --date 20191206 +...... +``` +4) If `--date` specified _together with RSS source_, then app should get news _for this date_ from local cache that _were fetched from specified source_. +5) `--date` should work correctly with both `--json`, `--limit`, `--verbose` and their different combinations. + +## [Iteration 4] Format converter. + +You should implement the conversion of news in at least two of the suggested format: `.mobi`, `.epub`, `.fb2`, `.html`, `.pdf` + +New optional argument must be added to your utility. This argument receives the path where new file will be saved. The arguments should represents which format will be generated. + +For example: `--to-mobi` or `--to-fb2` or `--to-epub` + +You can choose yourself the way in which the news will be displayed, but the final text result should contain pictures and links, if they exist in the original article and if the format permits to store this type of data. + +### Task clarification (IV) + +Convertation options should work correctly together with all arguments that were implemented in Iterations 1-3. For example: +* Format convertation process should be influenced by `--limit`. +* If `--json` is specified together with convertation options, then JSON news should +be printed to stdout, and converted file should contain news in normal format. +* Logs from `--verbose` should be printed in stdout and not added to the resulting file. +* `--date` should also work correctly with format converter and to not require internet access. + +## * [Iteration 5] Output colorization. +> Note: An optional iteration, it is not necessary to implement it. You can move on with it only if all the previous iterations (from 1 to 4) are completely implemented. + +You should add new optional argument `--colorize`, that will print the result of the utility in colorized mode. + +*If the argument is not provided, the utility should work like in the previous iterations.* + +> Note: Take a look at the [colorize](https://pypi.org/project/colorize/) library + +## * [Iteration 6] Web-server. +> Note: An optional iteration, it is not necessary to implement it. You can move on with it only if all the previous iterations (from 1 to 4) are completely implemented. Introduction to Python course does not cover the topics that are needed for the implementation of this part. + +There are several mandatory requirements in this iteration: +* `Docker` + `docker-compose` usage (at least 2 containers: one for web-application, one for DB) +* Web application should provide all the implemented in the previous parts of the task functionality, using the REST API: + * One-shot conversion from RSS to Human readable format + * Server-side news caching + * Conversion in epub, mobi, fb2 or other formats + +Feel free to choose the way of implementation, libraries and frameworks. (We suggest you `Django Rest Framework` + `PostgreSQL` combination) + +You can implement any functionality that you want. The only requirement is to add the description into README file or update project documentation, for example: +* authorization/authentication +* automatic scheduled news update +* adding new RSS sources using API + +--- +Implementations will be checked with the latest cPython interpreter of 3.9 branch. +--- + +> Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability. **John F. Woods** diff --git a/README.md b/README.md index c86d1e65..80786371 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,56 @@ -# How to create a PR with a homework task - -1. Create fork from the following repo: https://github.com/E-P-T/Homework. (Docs: https://docs.github.com/en/get-started/quickstart/fork-a-repo ) -2. Clone your forked repo in your local folder. -3. Create separate branches for each session.Example(`session_2`, `session_3` and so on) -4. Create folder with you First and Last name in you forked repo in the created session. -5. Add your task into created folder -6. Push finished session task in the appropriate branch in accordance with written above. - You should get the structure that looks something like that - -``` - Branch: Session_2 - DzmitryKolb - |___Task1.py - |___Task2.py - Branch: Session_3 - DzmitryKolb - |___Task1.py - |___Task2.py -``` - -7. When you finish your work on task you should create Pull request to the appropriate branch of the main repo https://github.com/E-P-T/Homework (Docs: https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork). -Please use the following instructions to prepare good description of the pull request: - - Pull request header should be: `Session - `. - Example: `Session 2 - Dzmitry Kolb` - - Pull request body: You should write here what tasks were implemented. - Example: `Finished: Task 1.2, Task 1.3, Task 1.6` - +## How to run +### Install requirements +```shell +pip install -r .\requirements.txt +``` +### Application +```shell +python .\src\rss_reader.py +``` +### Tests +```shell +python .\src\test_all.py +``` +--- +## Print format +### JSON +#### News: +``` +{ + "feed": string, + "items": array of Items +} +``` +#### Item: +``` +{ + "title": string, + "date": datetime, + "link": string, + "images": array of strings +} +``` +### String +Same as JSON but without brackets and quotes +#### News: +```yaml +feed: string +items: + array of Items +``` +#### Item: +```yaml +title: string +date: datetime +link: string +images: + array of strings +``` +--- +## Caching system +All items were fetched +will be stored in cached.json +which is located +(will be created if it doesn't exist) +in source folder and will be stored +in JSON format with checking for duplicates diff --git a/RULES.md b/RULES.md new file mode 100644 index 00000000..9a72034f --- /dev/null +++ b/RULES.md @@ -0,0 +1,12 @@ +# Final task +Final task (`FT`) for EPAM Python Training 2022.03 + +## Rules +* All work has to be implemented in the `master` branch in forked repository. If you think that `FT` is ready, please open a pull request (`PR`) to our repo. +* When a `PR` will be ready, please mark it with the `final_task` label. +* You have one month to finish `FT`. Commits commited after deadline will be ignored. +* At least the first 4 iterations must be done. +* `FT` you can find in the `Final_Task.md` file. + +### Good luck! + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..e7e9990e --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +colorama +Pillow +python_dateutil +setuptools diff --git a/setup.py b/setup.py new file mode 100644 index 00000000..83693558 --- /dev/null +++ b/setup.py @@ -0,0 +1,20 @@ +from setuptools import setup, find_packages + +import src.info as info + +setup( + name=info.shortname, + version=info.version, + package_dir={'': 'src'}, + packages=find_packages().append(''), + install_requres=[ + 'colorama', + 'Pillow', + 'python_dateutil' + ], + entry_points={ + 'console_scripts': [ + 'rss_reader = rss_reader:main', + ] + } +) diff --git a/src/Arguments.py b/src/Arguments.py new file mode 100644 index 00000000..07aa4b7e --- /dev/null +++ b/src/Arguments.py @@ -0,0 +1,50 @@ +from argparse import ArgumentParser, Namespace +from datetime import datetime +from pathlib import Path + + +class Arguments(ArgumentParser): + class Exception(ValueError): + def __init__(self, message: str): + self.message = message + + def __init__(self, name: str, version: float): + super().__init__(description=name) + + self.add_argument('source', type=str, help='RSS URL', nargs='?') + self.add_argument('--version', action='version', version=f'v{version}') + self.add_argument('--json', action='store_true', help='show in JSON format') + self.add_argument('--verbose', action='store_true', help='show detailed information') + self.add_argument('--limit', type=int, help='limit the items') + self.add_argument('--date', type=str, help='show items from specified date') + self.add_argument('--to-fb2', type=str, help='save in fb2 format to specified path') + self.add_argument('--to-html', type=str, help='save in html format to specified path') + self.add_argument('--colorize', action='store_true', help='show items as colorized') + + def parse(self) -> Namespace: + try: + args = self.parse_args() + + if args.source is None and args.date is None: + raise self.Exception('Either source or date should be specified') + + if args.date is not None: + try: + args.date = datetime.strptime(args.date, '%Y%m%d') + except ValueError: + raise self.Exception('Date must be in %Y%m%d format') + + self.check_absolute(args.to_fb2, '.fb2') + self.check_absolute(args.to_html, '.html') + + return args + except self.Exception as e: + self.error(e.message) + + def check_absolute(self, path: str, ext: str) -> None: + if path is None: + return + if not Path(path).is_absolute(): + raise self.Exception(path + ': should be absolute') + if not path.endswith(ext): + raise self.Exception(path + ': extension should be ' + ext) diff --git a/src/Logger.py b/src/Logger.py new file mode 100644 index 00000000..2e662d61 --- /dev/null +++ b/src/Logger.py @@ -0,0 +1,30 @@ +from enum import Enum +from typing import Callable + +from colorama import Fore + +from Util import Util + + +class Level(Enum): + INFO: Fore = Fore.GREEN + WARNING: Fore = Fore.YELLOW + ERROR: Fore = Fore.RED + + +class Logger: + __logger: Callable + + @classmethod + def verbose(cls, is_verbose: bool): + cls.__logger = print if is_verbose else lambda *args: None + + @classmethod + def log(cls, level: Level, message: str) -> None: + message = Util.colorize(f'[{level.name}] {message}', level.value) + + if level is Level.ERROR: + print(message) + exit(-1) + + cls.__logger(message) diff --git a/src/Util.py b/src/Util.py new file mode 100644 index 00000000..ecc9a17e --- /dev/null +++ b/src/Util.py @@ -0,0 +1,119 @@ +import base64 +import io +import json +import re +from pathlib import Path +from typing import Union +from urllib.request import urlopen +from xml.etree.ElementTree import Element, parse as parse_xml + +from PIL import Image +from colorama import Fore + + +class UtilException(Exception): + def __init__(self, message): + self.message = message + + +class Util: + indent = ' ' + cached_file = Path(__file__).parent.joinpath('cached.json') + + @classmethod + def colorize(cls, message: str, color: str, back_color: str = None) -> str: + message = color + message + Fore.RESET + if back_color is not None: + message = Fore.RESET + message + back_color + return message + + @classmethod + def to_element(cls, url: str) -> Element: + with urlopen(url) as content: + return parse_xml(content).getroot().find('channel') + + @classmethod + def to_json(cls, obj: object) -> str: + string = json.dumps(obj, indent=Util.indent, default=cls.safe_vars) + return string + + @classmethod + def safe_vars(cls, obj: object) -> Union[dict, str]: + try: + return vars(obj) + except: + return str(obj) + + @classmethod + def vars_to_string(cls, obj: object): + items = [] + for key, value in vars(obj).items(): + if isinstance(value, list): + continue + items.append(f'{key.capitalize()}: {value}') + + return '\n'.join(items) + + @classmethod + def make_indent(cls, string: str): + return re.sub( + '^', cls.indent, string, + flags=re.MULTILINE + ) + + @classmethod + def get_cached(cls) -> str: + content: str + try: + with open(cls.cached_file, 'r') as file: + content = file.read() + except: + content = '' + + return content + + @classmethod + def save_cache(cls, content: str) -> None: + with open(cls.cached_file, 'w+') as file: + file.write(content) + + @classmethod + def unique(cls, items: list) -> list: + unique = [] + for item in items: + if item in unique: + continue + unique.append(item) + + return unique + + @classmethod + def save(cls, content: str, path: str): + with open(path, 'w+') as file: + file.write(content) + + @classmethod + def to_base64(cls, url: str) -> str: + with urlopen(url) as content: + with io.BytesIO(content.read()) as buf: + with io.BytesIO() as image_buf: + with Image.open(buf) as image: + image.thumbnail((500, 500), Image.ANTIALIAS) + image.save(image_buf, 'PNG') + + return base64.b64encode(image_buf.getvalue()).decode() + + @classmethod + def colorize_object(cls, string: str): + main = Fore.CYAN + key = Fore.YELLOW + curly = Fore.WHITE + square = Fore.WHITE + string = Util.regex(r'[\[\]]', cls.colorize(r'\g<0>', square, main), string) + string = Util.regex(r'[\{\}]', cls.colorize(r'\g<0>', curly, main), string) + string = Util.regex(r'^ *(\"|\w)+:', cls.colorize(r'\g<0>', key, main), string) + return string + Fore.RESET + + @classmethod + def regex(cls, pattern: str, replace: str, string: str) -> str: + return re.sub(pattern, replace, string, flags=re.MULTILINE) diff --git a/src/info.py b/src/info.py new file mode 100644 index 00000000..0ca87267 --- /dev/null +++ b/src/info.py @@ -0,0 +1,3 @@ +fullname = 'Pure Python command-line RSS reader' +shortname = 'RSS Reader' +version = 0.1 diff --git a/src/main.py b/src/main.py new file mode 100644 index 00000000..9bd320b0 --- /dev/null +++ b/src/main.py @@ -0,0 +1,80 @@ +import json +from datetime import datetime +from xml.etree.ElementTree import ParseError + +import info +from Arguments import Arguments +from Logger import Logger, Level +from Util import Util +from news.News import News + +args = Arguments(info.fullname, info.version).parse() +Logger.verbose(args.verbose) + + +def get_news(source: str, limit: int, date: datetime) -> News: + Logger.log(Level.INFO, 'Downloading and parsing ' + source) + try: + element = Util.to_element(source) + except ValueError: + Logger.log(Level.ERROR, 'Invalid URL') + except ParseError: + Logger.log(Level.ERROR, 'Invalid XML') + + return News.parse_element(element, limit, date) + + +def print_news(news_to_print: News, to_json: bool, to_colorize: bool) -> None: + string = Util.to_json(news_to_print) \ + if to_json else str(news_to_print) + string = '\n' + string + print( + Util.colorize_object(string) if to_colorize + else string + ) + + +def get_cached_news(cached: str) -> News: + Logger.log(Level.INFO, 'Getting cached items and parsing') + if cached: + news_cached = News.parse_json(json.loads(cached)) + else: + Logger.log(Level.WARNING, 'Cached items are empty') + news_cached = News() + news_cached.feed = 'Cached news' + news_cached.items = [] + + return news_cached + + +def save_cached_news(news_to_cache: News) -> None: + Logger.log(Level.INFO, 'Caching news') + Util.save_cache(Util.to_json(news_to_cache)) + + +def save_to_files(to_save: News, html: str, fb2: str) -> None: + if html is not None: + Logger.log(Level.INFO, 'Saving as html') + Util.save(to_save.to_html(), html) + if fb2 is not None: + Logger.log(Level.INFO, 'Saving as fb2') + Util.save(to_save.to_fb2(), fb2) + + +cached_news = get_cached_news(Util.get_cached()) + +to_print: News + +if args.source: + news = get_news(args.source, args.limit, args.date) + cached_news.items += news.items + cached_news.items = Util.unique(cached_news.items) + save_cached_news(cached_news) + + to_print = news +else: + cached_news.items = News.date_filter(cached_news.items, args.date)[:args.limit] + to_print = cached_news + +save_to_files(to_print, args.to_html, args.to_fb2) +print_news(to_print, args.json, args.colorize) diff --git a/src/news/Item.py b/src/news/Item.py new file mode 100644 index 00000000..a34a0c94 --- /dev/null +++ b/src/news/Item.py @@ -0,0 +1,90 @@ +from datetime import datetime +from xml.etree.ElementTree import Element + +from dateutil.parser import parse as parse_date + +from Util import Util + + +class Item: + title: str + date: datetime + link: str + images: list[str] + + @classmethod + def parse_element(cls, element: Element) -> 'Item': + item = cls() + + item.title = element.find('title').text + item.date = parse_date(element.find('pubDate').text) + item.link = element.find('link').text + item.images = [ + image.attrib['url'] for image in + element.findall('*[@width][@height]') + ] + + return item + + @classmethod + def parse_json(cls, obj: dict) -> 'Item': + item = cls() + item.title = obj['title'] + item.date = parse_date(obj['date']) + item.link = obj['link'] + item.images = obj['images'] + + return item + + def __str__(self) -> str: + items = [Util.vars_to_string(self), 'Images:', + Util.make_indent('\n'.join(self.images))] + + return '\n'.join(items) + + def __eq__(self, o: object) -> bool: + return isinstance(o, Item) and \ + Util.vars_to_string(self) \ + == Util.vars_to_string(o) + + def to_fb2(self, images_id: str) -> str: + content = '
' \ + '' \ + f'<p>{self.title}</p>' \ + '' \ + f'

{self.date}

' \ + f'

{self.link}

' + for i in range(len(self.images)): + image_id = f'{images_id}{i}' + content += f'

' + content += '
' + + return content + + def to_fb2_images(self, images_id: str) -> str: + content = '' + i = 0 + for image in self.images: + image_id = f'{images_id}{i}' + content += f'' \ + f'{Util.to_base64(image)}' \ + '' + i += 1 + + return content + + def to_html(self) -> str: + content = '
' \ + '
' \ + f'

{self.title}

' \ + f'

{self.date}

' \ + '
' + for image in self.images: + content += '
' \ + f'' \ + '
' + content += '
' \ + '
' \ + '
' + + return content diff --git a/src/news/News.py b/src/news/News.py new file mode 100644 index 00000000..351958d4 --- /dev/null +++ b/src/news/News.py @@ -0,0 +1,93 @@ +from datetime import datetime +from xml.etree.ElementTree import Element + +from Util import Util +from news.Item import Item + + +class News: + feed: str + items: list[Item] + + @classmethod + def parse_element(cls, element: Element, limit: int, date: datetime) -> 'News': + news = cls() + news.feed = element.find('title').text + + items = [Item.parse_element(item) for item in element.findall('item')] + if date is not None: + items = cls.date_filter(items, date) + + news.items = items[:limit] + + return news + + @classmethod + def parse_json(cls, obj: dict) -> 'News': + news = cls() + news.feed = obj['feed'] + news.items = list(map( + lambda item: Item.parse_json(item), + obj['items'] + )) + + return news + + def __str__(self) -> str: + items = [Util.vars_to_string(self), 'Items:', + Util.make_indent('\n\n'.join(map(str, self.items)))] + return '\n'.join(items) + + @classmethod + def date_filter(cls, items: list[Item], date: datetime) -> list[Item]: + date_format = '%Y-%m-%d' + return list(filter( + lambda item: + item.date.strftime(date_format) == date.strftime(date_format), + items + )) + + def to_fb2(self) -> str: + content = '' \ + '' \ + '' \ + '' \ + f'{self.feed}' \ + '' \ + '' \ + '' + i = 0 + for item in self.items: + content += item.to_fb2(i) + i += 1 + content += '' + i = 0 + for item in self.items: + content += item.to_fb2_images(i) + i += 1 + content += '' + + return content + + def to_html(self) -> str: + content = '' \ + '' \ + '' \ + '' \ + '' \ + 'News' \ + '' \ + '' \ + '' \ + '
' \ + '
' \ + f'

{self.feed}

' + for item in self.items: + content += item.to_html() + content += '
' \ + '
' \ + '' \ + '' + + return content diff --git a/src/rss_reader.py b/src/rss_reader.py new file mode 100644 index 00000000..3f7582ba --- /dev/null +++ b/src/rss_reader.py @@ -0,0 +1,9 @@ +import runpy + + +def main(): + runpy.run_module('main') + + +if __name__ == '__main__': + main() diff --git a/src/test/test_Logger.py b/src/test/test_Logger.py new file mode 100644 index 00000000..1ebba14a --- /dev/null +++ b/src/test/test_Logger.py @@ -0,0 +1,30 @@ +import io +from contextlib import redirect_stdout +from unittest import TestCase +from Logger import Logger, Level + + +class TestLogger(TestCase): + def test_log(self): + Logger.verbose(True) + string = 'test' + + with io.StringIO() as buf1: + with redirect_stdout(buf1): + Logger.log(Level.INFO, string) + Logger.log(Level.WARNING, string) + self.assertRaises(SystemExit, Logger.log, Level.ERROR, string) + for line in buf1.getvalue().strip().split('\n'): + self.assertRegex(line, string) + + Logger.verbose(False) + with io.StringIO() as buf2: + with redirect_stdout(buf2): + Logger.log(Level.INFO, string) + Logger.log(Level.WARNING, string) + self.assertEqual(len(buf2.getvalue()), 0) + + with io.StringIO() as buf3: + with redirect_stdout(buf3): + self.assertRaises(SystemExit, Logger.log, Level.ERROR, string) + self.assertRegex(buf3.getvalue(), string) diff --git a/src/test/test_News.py b/src/test/test_News.py new file mode 100644 index 00000000..1b4654fe --- /dev/null +++ b/src/test/test_News.py @@ -0,0 +1,32 @@ +import datetime +from unittest import TestCase +from news.News import News + + +class TestNews(TestCase): + def test_parse_json(self): + feed = 'test_feed' + title = 'test_title' + date = datetime.datetime.today() + link = 'test_link' + images = ['test_image'] + obj = { + 'feed': feed, + 'items': [{ + 'title': title, + 'date': str(date), + 'link': link, + 'images': images + }] + } + + news = News.parse_json(obj) + self.assertEqual(news.feed, feed) + self.assertEqual(len(news.items), 1) + + item = news.items[0] + self.assertEqual(item.title, title) + self.assertEqual(item.date, date) + self.assertEqual(item.link, link) + self.assertEqual(item.images, images) + diff --git a/src/test/test_Util.py b/src/test/test_Util.py new file mode 100644 index 00000000..161b96df --- /dev/null +++ b/src/test/test_Util.py @@ -0,0 +1,36 @@ +import datetime +import json +from unittest import TestCase +from Util import Util +from colorama import Fore + + +class TestUtil(TestCase): + def test_colorize(self): + string = 'dsa' + self.assertRegex(Util.colorize(string, Fore.GREEN), string) + + def test_safe_vars(self): + for item in ['a', {'a': 'a'}, self, datetime.date.today()]: + try: + Util.safe_vars(item) + except: + self.fail() + + def test_to_json(self): + obj = {'a': 1, 'b': 2} + self.assertEqual(obj, json.loads(Util.to_json(obj))) + + def test_make_intend(self): + string = 'test' + self.assertEqual(Util.make_indent(string), Util.indent + string) + + def test_unique(self): + unique = [1, 2, 3, 4, 5] + self.assertEqual(unique, Util.unique(unique + [1, 2, 4])) + + def test_regex(self): + string = 'test' + pattern = '^t' + replace = 'the t' + self.assertEqual(Util.regex(pattern, replace, string), 'the ' + string) diff --git a/src/test_all.py b/src/test_all.py new file mode 100644 index 00000000..6e0bf49c --- /dev/null +++ b/src/test_all.py @@ -0,0 +1,9 @@ +import unittest +from pathlib import Path + +if __name__ == '__main__': + path = Path(__file__).parent.joinpath('test') + tests = unittest.TestLoader().discover(path) + unittest.TextTestRunner().run(tests) + +