Handles the situation where no posts exist

This commit is contained in:
asdf 2020-01-16 14:08:42 +11:00
parent d6e8020fef
commit 9546ab87dc
4 changed files with 80 additions and 15 deletions

View File

@ -78,9 +78,10 @@ def init():
USER.datadir.mkdir(mode=0o755, exist_ok=True) USER.datadir.mkdir(mode=0o755, exist_ok=True)
if not USER.settingsfile.is_file(): if not USER.settingsfile.is_file():
with open(USER.settingsfile, 'w+') as the_file: with open(USER.settingsfile, "w+") as the_file:
the_file.write("[User Status]\nlastlogin = 0.0\n\n[User Settings]\nbrowser = lynx") the_file.write(
"[User Status]\nlastlogin = 0.0\n\n[User Settings]\nbrowser = lynx"
)
if not is_readable(USER.datadir.stat().st_mode): if not is_readable(USER.datadir.stat().st_mode):
print( print(

14
data.py
View File

@ -158,7 +158,13 @@ class LinkData:
new_post_id = -1 new_post_id = -1
if record.category: if record.category:
new_post_id = max([record[0] for record in self.link_data if record[0]]) + 1 if self.link_data:
new_post_id = (
max([record[0] if record[0] else 0 for record in self.link_data])
+ 1
)
else:
new_post_id = 1
record = record._replace(ID_if_parent=new_post_id) record = record._replace(ID_if_parent=new_post_id)
self.link_data.insert(0, list(record)) self.link_data.insert(0, list(record))
self.generate_category_data() self.generate_category_data()
@ -190,7 +196,11 @@ class LinkData:
if keyword == "": if keyword == "":
raise ValueError("a search keyword must be specified") raise ValueError("a search keyword must be specified")
query = (record for record in self.link_data if keyword.lower() in str(record).lower()) query = (
record
for record in self.link_data
if keyword.lower() in str(record).lower()
)
if query: if query:
search_results: set = set() search_results: set = set()

View File

@ -24,18 +24,23 @@ categories: list = LinkData.categories
def print_categories(): def print_categories():
"""Prints the list of categories with an indicator for new activity""" """Prints the list of categories with an indicator for new activity"""
print("\n{:>4s} New {:<25s}".format("ID#", "Category")) header = "\n{:>4s} New {:<25s}".format("ID#", "Category")
out = ""
for i, record in enumerate(categories): for i, record in enumerate(categories):
print( out += "{:4d} {} {} ({})\n".format(
"{:4d} {} {} ({})".format( i + 1,
i + 1, "x" if record["last_updated"] >= config.USER.lastlogin else " ",
"x" if record["last_updated"] >= config.USER.lastlogin else " ", record["name"],
record["name"], record["count"],
record["count"],
)
) )
if len(out) > 0:
print(header)
print(out)
else:
print("\n There are no posts yet - enter p to post a new link\n")
def print_category_details(view_cat): def print_category_details(view_cat):
"""produces category detail data, prints it to the console. returns dict """produces category detail data, prints it to the console. returns dict
@ -90,7 +95,9 @@ def print_thread_details(post_id) -> tuple:
raise ValueError("Sorry, no thread found with that ID.") raise ValueError("Sorry, no thread found with that ID.")
# get replies data # get replies data
replies = sorted([line for line in link_data if line[3] == parent_id], key=lambda x: x[2]) replies = sorted(
[line for line in link_data if line[3] == parent_id], key=lambda x: x[2]
)
# post detail view # post detail view
print("\n\n{:<17}: {}".format(style_text("Title", "bold"), post_title)) print("\n\n{:<17}: {}".format(style_text("Title", "bold"), post_title))
@ -173,6 +180,7 @@ def search():
# Catch a Post ID that is not in the thread list or is not a number # Catch a Post ID that is not in the thread list or is not a number
print("\n{}\n".format(style_text("Invalid entry", "bold"))) print("\n{}\n".format(style_text("Invalid entry", "bold")))
def view_link_in_browser(url): def view_link_in_browser(url):
"""Attempts to view the specified URL in the configured browser""" """Attempts to view the specified URL in the configured browser"""
if which(config.USER.browser) is None: if which(config.USER.browser) is None:
@ -443,7 +451,12 @@ def main():
py_ver = str(sys.version_info[0]) + "." + str(sys.version_info[1]) py_ver = str(sys.version_info[0]) + "." + str(sys.version_info[1])
py_ver = float(py_ver) py_ver = float(py_ver)
if py_ver < low_py_ver: if py_ver < low_py_ver:
raise Exception("Must be using Python " + str(low_py_ver) + " or higher. Instead you're using " + str(py_ver)) raise Exception(
"Must be using Python "
+ str(low_py_ver)
+ " or higher. Instead you're using "
+ str(py_ver)
)
signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGINT, signal_handler)
args = sys.argv[1:] args = sys.argv[1:]

View File

@ -1,6 +1,7 @@
"""unit tests for the data module""" """unit tests for the data module"""
import unittest import unittest
import unittest.mock import unittest.mock
from unittest.mock import mock_open
from time import time from time import time
import data import data
@ -214,5 +215,45 @@ class TestLinkDataSearch(unittest.TestCase):
self.assertEqual(link_data.search("keyword"), test_results) self.assertEqual(link_data.search("keyword"), test_results)
class TestAddLink(unittest.TestCase):
"""Tests Add method of LinkData class"""
@unittest.mock.patch.object(data.LinkData, "get")
def test_add_to_empty_db(self, mock_get):
"""Tests adding to an empty db as per issue #76"""
link_data = data.LinkData()
mock_get.assert_called()
link_data.link_data = []
test_record = data.LinkDataRecord(
username="testuser",
timestamp="1000",
category="test_category",
link_URL="test_url",
link_title_or_comment="test_title",
)
with unittest.mock.patch("builtins.open", mock_open()) as mock_file:
result = link_data.add(test_record)
mock_file.assert_called()
self.assertEqual(1, result)
self.assertListEqual(
link_data.link_data,
[
[
1,
"testuser",
"1000",
"",
"test_category",
"test_url",
"test_title",
]
],
)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()