""" Unit tests for the metadata parts. """ import logging import sys from lxml import html from lxml.etree import XPath from trafilatura.json_metadata import normalize_authors, normalize_json from trafilatura.metadata import check_authors, extract_metadata, extract_metainfo, extract_url, normalize_tags logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) def test_titles(): '''Test the extraction of titles''' tests = [ ('

T

', None), ('Test Title

First

', 'First'), ('Test Title

First

', 'First'), ('Test Title', 'Test Title'), ('

First

Second

', 'First'), ('

Test Title
', 'Test Title'), ('

Main menu

Test Title

', 'Test Title'), ('

First

Second

', 'Second'), ('

First

Second

', 'First'), ('', None) ] for doc, expected_title in tests: metadata = extract_metadata(doc) assert metadata.title == expected_title metadata = extract_metadata(r''' ''') assert metadata.title == 'Semantic satiation' metadata = extract_metadata(' - Home') assert metadata.title == '- Home' metadata = extract_metadata('My Title » My Website') assert metadata.title == "My Title" # TODO: and metadata.sitename == "My Website" def test_authors(): '''Test the extraction of author names''' # normalization assert normalize_authors(None, 'abc') == 'Abc' assert normalize_authors(None, 'Steve Steve 123') == 'Steve Steve' assert normalize_authors(None, 'By Steve Steve') == 'Steve Steve' assert normalize_json('Test \\nthis') == 'Test this' assert normalize_json('\\uD800\\uDC00Hello\\uDBFF\\uDFFF') == 'Hello' assert normalize_json('Test \u3010ABC\u3011') == 'Test 【ABC】' assert normalize_json("Seán Federico O'Murchú") == "Seán Federico O'Murchú" # blacklist metadata = extract_metadata('', author_blacklist={'Jenny Smith'}) assert metadata.author is None # extraction begin, end = '', '' htmldocs = [ f'{begin}{end}', f'{begin}{end}', f'{begin}{end}', f'{begin}{end}', f'{begin}{end}', f'{begin}{end}', f'{begin}{end}', f'{begin}{end}', f'{begin}{end}', f'{begin}{end}', f'{begin}{end}', f'{begin}{end}', ] expected_authors = [ 'Jenny Smith', 'Jenny Smith; John Smith', 'Jenny Smith; John Smith', 'Jenny Smith; John Smith', 'Jenny Smith; John Smith', 'Jenny Smith', 'Hank O\'Hop', 'Jenny Smith', 'Jenny Smith; John Smith', 'Jenny Smith; John Smith', 'Jenny Smith; John Smith', 'Jenny Smith', ] for doc, expected_author in zip(htmldocs, expected_authors): metadata = extract_metadata(doc) assert metadata.author == expected_author begin, end = '', '' htmldocs = [ f'{begin}{end}', f'{begin}{end}', f'{begin}Jenny Smithf{end}', f'{begin}

Jenny Smith

f{end}', f'{begin}

Jenny Smith — Trafilatura

f{end}', f'{begin}Jenny Smithf{end}', f'{begin}Jenny Smithf{end}', f'{begin}
Jenny Smith
f{end}', f'{begin}