From 3f856408d70439062e156d86523373aec7948ea4 Mon Sep 17 00:00:00 2001 From: Charles Haley Date: Mon, 10 Oct 2022 21:25:06 +0100 Subject: [PATCH] Add some tests for python templates --- src/calibre/db/tests/reading.py | 36 +++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/calibre/db/tests/reading.py b/src/calibre/db/tests/reading.py index 5a46bcca4e..30c68cdaf4 100644 --- a/src/calibre/db/tests/reading.py +++ b/src/calibre/db/tests/reading.py @@ -811,3 +811,39 @@ class ReadingTest(BaseTest): v = formatter.safe_format('program: book_values("rating", "title:true", ",", 0)', {}, 'TEMPLATE ERROR', mi) self.assertEqual(set(v.split(',')), {'4', '6'}) # }}} + + def test_python_templates(self): # {{{ + from calibre.ebooks.metadata.book.formatter import SafeFormat + formatter = SafeFormat() + + # need an empty metadata object to pass to the formatter + db = self.init_legacy(self.library_path) + mi = db.get_metadata(1) + + # test counting books matching a search + template = '''python: +def evaluate(book, db, **kwargs): + ids = db.new_api.search("series:true") + return str(len(ids)) +''' + v = formatter.safe_format(template, {}, 'TEMPLATE ERROR', mi) + self.assertEqual(v, '2') + + # test counting books when none match the search + template = '''python: +def evaluate(book, db, **kwargs): + ids = db.new_api.search("series:afafaf") + return str(len(ids)) +''' + v = formatter.safe_format(template, {}, 'TEMPLATE ERROR', mi) + self.assertEqual(v, '0') + + # test is_multiple values + template = '''python: +def evaluate(book, db, **kwargs): + tags = db.new_api.all_field_names('tags') + return ','.join(list(tags)) +''' + v = formatter.safe_format(template, {}, 'TEMPLATE ERROR', mi) + self.assertEqual(set(v.split(',')), {'Tag One', 'News', 'Tag Two'}) + # }}}