diff options
Diffstat (limited to 'backend/tests')
30 files changed, 2115 insertions, 0 deletions
diff --git a/backend/tests/__init__.py b/backend/tests/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/backend/tests/__init__.py diff --git a/backend/tests/common.py b/backend/tests/common.py new file mode 100644 index 0000000..cb455e4 --- /dev/null +++ b/backend/tests/common.py @@ -0,0 +1,49 @@ +""" +Utilities for testing +""" + +from typing import Any +import bz2, gzip, sqlite3 + +def createTestFile(filename: str, content: str) -> None: + """ Creates a file with the given name and contents """ + with open(filename, 'w') as file: + file.write(content) + +def readTestFile(filename: str) -> str: + """ Returns the contents of a file with the given name """ + with open(filename) as file: + return file.read() + +def createTestBz2(filename: str, content: str) -> None: + """ Creates a bzip2 file with the given name and contents """ + with bz2.open(filename, mode='wb') as file: + file.write(content.encode()) + +def createTestGzip(filename: str, content: str) -> None: + """ Creates a gzip file with the given name and contents """ + with gzip.open(filename, mode='wt') as file: + file.write(content) + +TableRows = set[tuple[Any, ...]] +def createTestDbTable(filename: str, createCmd: str | None, insertCmd: str, rows: TableRows) -> None: + """ Creates an sqlite db with a table specified by creation+insertion commands and records. + If 'createCmd' is None, just insert into an existing table.""" + dbCon = sqlite3.connect(filename) + dbCur = dbCon.cursor() + if createCmd is not None: + dbCur.execute(createCmd) + for row in rows: + dbCur.execute(insertCmd, row) + dbCon.commit() + dbCon.close() + +def readTestDbTable(filename: str, selectCmd: str) -> TableRows: + """ Returns the records in a sqlite db with the given name, using the given select command """ + rows: set[tuple[Any, ...]] = set() + dbCon = sqlite3.connect(filename) + dbCur = dbCon.cursor() + for row in dbCur.execute(selectCmd): + rows.add(row) + dbCon.close() + return rows diff --git a/backend/tests/dbpedia/__init__.py b/backend/tests/dbpedia/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/backend/tests/dbpedia/__init__.py diff --git a/backend/tests/dbpedia/test_gen_desc_data.py b/backend/tests/dbpedia/test_gen_desc_data.py new file mode 100644 index 0000000..7d35677 --- /dev/null +++ b/backend/tests/dbpedia/test_gen_desc_data.py @@ -0,0 +1,107 @@ +import unittest +import tempfile, os + +from tests.common import createTestBz2, readTestDbTable +from tol_data.dbpedia.gen_desc_data import genData + +class TestGenData(unittest.TestCase): + def test_gen(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp labels file + labelsFile = os.path.join(tempDir, 'labels.ttl.bz2') + createTestBz2(labelsFile, ( + '<http://dbpedia.org/resource/One> <http://www.w3.org/2000/01/rdf-schema#label> "One"@en .\n' + '<http://dbpedia.org/resource/Two> <http://www.w3.org/2000/01/rdf-schema#label> "II"@en .\n' + '<http://dbpedia.org/resource/Three> <http://www.w3.org/2000/01/rdf-schema#label> "three"@en .\n' + '<http://dbpedia.org/resource/A_Hat> <http://www.w3.org/2000/01/rdf-schema#label> "A Hat"@en .\n' + )) + # Create temp ids file + idsFile = f'{tempDir}ids.ttl.bz2' + createTestBz2(idsFile, ( + '<http://dbpedia.org/resource/One> <http://dbpedia.org/ontology/wikiPageID>' + ' "1"^^<http://www.w3.org/2001/XMLSchema#integer> .\n' + '<http://dbpedia.org/resource/Two> <http://dbpedia.org/ontology/wikiPageID>' + ' "2"^^<http://www.w3.org/2001/XMLSchema#integer> .\n' + '<http://dbpedia.org/resource/Three> <http://dbpedia.org/ontology/wikiPageID>' + ' "3"^^<http://www.w3.org/2001/XMLSchema#integer> .\n' + '<http://dbpedia.org/resource/A_Hat> <http://dbpedia.org/ontology/wikiPageID>' + ' "210"^^<http://www.w3.org/2001/XMLSchema#integer> .\n' + )) + # Create temp redirects file + redirectsFile = os.path.join(tempDir, 'redirects.ttl.bz2') + createTestBz2(redirectsFile, ( + '<http://dbpedia.org/resource/Three> <http://dbpedia.org/ontology/wikiPageRedirects>' + ' <http://dbpedia.org/resource/A_Hat> .\n' + )) + # Create temp disambig file + disambigFile = os.path.join(tempDir, 'disambig.ttl.bz2') + createTestBz2(disambigFile, ( + '<http://dbpedia.org/resource/Two> <http://dbpedia.org/ontology/wikiPageDisambiguates>' + ' <http://dbpedia.org/resource/One> .\n' + '<http://dbpedia.org/resource/Two> <http://dbpedia.org/ontology/wikiPageDisambiguates>' + ' <http://dbpedia.org/resource/Three> .\n' + )) + # Create temp types file + typesFile = os.path.join(tempDir, 'types.ttl.bz2') + createTestBz2(typesFile, ( + '<http://dbpedia.org/resource/One> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>' + ' <http://dbpedia.org/ontology/Thing> .\n' + '<http://dbpedia.org/resource/Three> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>' + ' <http://dbpedia.org/ontology/Thing> .\n' + )) + # Create temp abstracts file + abstractsFile = os.path.join(tempDir, 'abstracts.ttl.bz2') + createTestBz2(abstractsFile, ( + '<http://dbpedia.org/resource/One> <http://www.w3.org/2000/01/rdf-schema#comment>' + ' "One is a number."@en .\n' + '<http://dbpedia.org/resource/A_Hat> <http://www.w3.org/2000/01/rdf-schema#comment>' + ' "Hats are not parrots, nor are they potatoes."@en .\n' + )) + # Run + dbFile = os.path.join(tempDir, 'descData.db') + genData(labelsFile, idsFile, redirectsFile, disambigFile, typesFile, abstractsFile, dbFile) + # Check + self.assertEqual( + readTestDbTable(dbFile, 'SELECT iri, label from labels'), + { + ('http://dbpedia.org/resource/One', 'One'), + ('http://dbpedia.org/resource/Two', 'II'), + ('http://dbpedia.org/resource/Three', 'three'), + ('http://dbpedia.org/resource/A_Hat', 'A Hat'), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT iri, id from ids'), + { + ('http://dbpedia.org/resource/One', 1), + ('http://dbpedia.org/resource/Two', 2), + ('http://dbpedia.org/resource/Three', 3), + ('http://dbpedia.org/resource/A_Hat', 210), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT iri, target from redirects'), + { + ('http://dbpedia.org/resource/Three', 'http://dbpedia.org/resource/A_Hat'), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT iri from disambiguations'), + { + ('http://dbpedia.org/resource/Two',), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT iri, type from types'), + { + ('http://dbpedia.org/resource/One', 'http://dbpedia.org/ontology/Thing'), + ('http://dbpedia.org/resource/Three', 'http://dbpedia.org/ontology/Thing'), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT iri, abstract from abstracts'), + { + ('http://dbpedia.org/resource/One', 'One is a number.'), + ('http://dbpedia.org/resource/A_Hat', 'Hats are not parrots, nor are they potatoes.'), + } + ) diff --git a/backend/tests/enwiki/__init__.py b/backend/tests/enwiki/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/backend/tests/enwiki/__init__.py diff --git a/backend/tests/enwiki/sample_enwiki_pages_articles.xml.bz2 b/backend/tests/enwiki/sample_enwiki_pages_articles.xml.bz2 Binary files differnew file mode 100644 index 0000000..2abfdaa --- /dev/null +++ b/backend/tests/enwiki/sample_enwiki_pages_articles.xml.bz2 diff --git a/backend/tests/enwiki/test_download_img_license_info.py b/backend/tests/enwiki/test_download_img_license_info.py new file mode 100644 index 0000000..ed6e426 --- /dev/null +++ b/backend/tests/enwiki/test_download_img_license_info.py @@ -0,0 +1,185 @@ +import unittest +from unittest.mock import Mock, patch +import tempfile, os + +from tests.common import createTestDbTable, readTestDbTable +from tol_data.enwiki.download_img_license_info import downloadInfo + +TEST_RESPONSE1 = { + 'batchcomplete': '', + 'query': { + 'normalized': [ + { + 'from': 'File:Georgia_Aquarium_-_Giant_Grouper_edit.jpg', + 'to': 'File:Georgia Aquarium - Giant Grouper edit.jpg' + } + ], + 'pages': { + '-1': { + 'ns': 6, + 'title': 'File:Octopus2.jpg', + 'missing': '', + 'known': '', + 'imagerepository': 'shared', + 'imageinfo': [ + { + 'url': 'https://upload.wikimedia.org/wikipedia/commons/5/57/Octopus2.jpg', + 'descriptionurl': 'https://commons.wikimedia.org/wiki/File:Octopus2.jpg', + 'descriptionshorturl': 'https://commons.wikimedia.org/w/index.php?curid=2795257', + 'extmetadata': { + 'Credit': { + 'value': '<span class=\\"int-own-work\\" lang=\\"en\\">Own work</span>', + 'source': 'commons-desc-page', + 'hidden': '' + }, + 'Artist': { + 'value': 'albert kok', + 'source': 'commons-desc-page' + }, + 'LicenseShortName': { + 'value': 'CC BY-SA 3.0', + 'source': 'commons-desc-page', + 'hidden': '' + }, + 'Restrictions': { + 'value': '', + 'source': 'commons-desc-page', + 'hidden': '' + } + } + } + ] + } + } + } +} +TEST_RESPONSE2 = { + 'batchcomplete': '', + 'query': { + 'normalized': [ + { + 'from': 'File:Georgia_Aquarium_-_Giant_Grouper_edit.jpg', + 'to': 'File:Georgia Aquarium - Giant Grouper edit.jpg' + } + ], + 'pages': { + '-1': { + 'ns': 6, + 'title': 'File:Octopus2.jpg', + 'missing': '', + 'known': '', + 'imagerepository': 'shared', + 'imageinfo': [ + { + 'url': 'https://upload.wikimedia.org/wikipedia/commons/5/57/Octopus2.jpg', + 'descriptionurl': 'https://commons.wikimedia.org/wiki/File:Octopus2.jpg', + 'descriptionshorturl': 'https://commons.wikimedia.org/w/index.php?curid=2795257', + 'extmetadata': { + 'Credit': { + 'value': '<span class=\\"int-own-work\\" lang=\\"en\\">Own work</span>', + 'source': 'commons-desc-page', + 'hidden': '' + }, + 'Artist': { + 'value': 'albert kok', + 'source': 'commons-desc-page' + }, + 'LicenseShortName': { + 'value': 'CC BY-SA 3.0', + 'source': 'commons-desc-page', + 'hidden': '' + }, + 'Restrictions': { + 'value': '', + 'source': 'commons-desc-page', + 'hidden': '' + } + } + } + ] + }, + '-2': { + 'ns': 6, + 'title': 'File:Georgia Aquarium - Giant Grouper edit.jpg', + 'missing': '', + 'known': '', + 'imagerepository': 'shared', + 'imageinfo': [ + { + 'url': 'https://upload.wikimedia.org/wikipedia/commons/2/23/Georgia_Aquarium_-_Giant_Grouper_edit.jpg', + 'descriptionurl': 'https://commons.wikimedia.org/wiki/File:Georgia_Aquarium_-_Giant_Grouper_edit.jpg', + 'descriptionshorturl': 'https://commons.wikimedia.org/w/index.php?curid=823649', + 'extmetadata': { + 'Credit': { + "value": "<a href=\"//commons.wikimedia.org/wiki/File:Georgia_Aquarium_-_Giant_Grouper.jpg\" title=\"File:Georgia Aquarium - Giant Grouper.jpg\">File:Georgia Aquarium - Giant Grouper.jpg</a>", + 'source': 'commons-desc-page', + 'hidden': '' + }, + 'Artist': { + "value": "Taken by <a href=\"//commons.wikimedia.org/wiki/User:Diliff\" title=\"User:Diliff\">Diliff</a> Edited by <a href=\"//commons.wikimedia.org/wiki/User:Fir0002\" title=\"User:Fir0002\">Fir0002</a>", + 'source': 'commons-desc-page' + }, + 'LicenseShortName': { + 'value': 'CC BY 2.5', + 'source': 'commons-desc-page', + 'hidden': '' + }, + 'Restrictions': { + 'value': '', + 'source': 'commons-desc-page', + 'hidden': '' + } + } + } + ] + } + } + } +} + +class TestDownloadInfo(unittest.TestCase): + @patch('requests.get', autospec=True) + def test_download(self, requestsGetMock): + requestsGetMock.side_effect = [Mock(json=lambda: TEST_RESPONSE1), Mock(json=lambda: TEST_RESPONSE2)] + with tempfile.TemporaryDirectory() as tempDir: + # Create temp image-data db + imgDb = os.path.join(tempDir, 'img_data.db') + createTestDbTable( + imgDb, + 'CREATE TABLE page_imgs (page_id INT PRIMARY KEY, img_name TEXT)', + 'INSERT into page_imgs VALUES (?, ?)', + { + (1, 'Octopus2.jpg'), + } + ) + # Run + downloadInfo(imgDb) + # Check + self.assertEqual( + readTestDbTable(imgDb, 'SELECT name, license, artist, credit, restrictions, url from imgs'), + { + ('Octopus2.jpg', 'CC BY-SA 3.0', 'albert kok', 'Own work', '', + 'https://upload.wikimedia.org/wikipedia/commons/5/57/Octopus2.jpg'), + } + ) + # Run with updated image-data db + createTestDbTable( + imgDb, + None, + 'INSERT into page_imgs VALUES (?, ?)', + { + (2, 'Georgia_Aquarium_-_Giant_Grouper_edit.jpg'), + } + ) + downloadInfo(imgDb) + # Check + self.assertEqual( + readTestDbTable(imgDb, 'SELECT name, license, artist, credit, restrictions, url from imgs'), + { + ('Octopus2.jpg', 'CC BY-SA 3.0', 'albert kok', 'Own work', '', + 'https://upload.wikimedia.org/wikipedia/commons/5/57/Octopus2.jpg'), + ('Georgia_Aquarium_-_Giant_Grouper_edit.jpg', 'CC BY 2.5', 'Taken by Diliff Edited by Fir0002', + 'File:Georgia Aquarium - Giant Grouper.jpg', '', 'https://upload.wikimedia.org/' \ + 'wikipedia/commons/2/23/Georgia_Aquarium_-_Giant_Grouper_edit.jpg'), + } + ) diff --git a/backend/tests/enwiki/test_download_imgs.py b/backend/tests/enwiki/test_download_imgs.py new file mode 100644 index 0000000..2618b8a --- /dev/null +++ b/backend/tests/enwiki/test_download_imgs.py @@ -0,0 +1,54 @@ +import unittest +from unittest.mock import Mock, patch +import tempfile, os + +from tests.common import readTestFile, createTestDbTable +from tol_data.enwiki.download_imgs import downloadImgs + +class TestDownloadInfo(unittest.TestCase): + @patch('requests.get', autospec=True) + def test_download(self, requestsGetMock): + requestsGetMock.side_effect = lambda url, **kwargs: Mock(content=('img:' + url).encode()) + with tempfile.TemporaryDirectory() as tempDir: + # Create temp image-data db + imgDb = os.path.join(tempDir, 'img_data.db') + createTestDbTable( + imgDb, + 'CREATE TABLE page_imgs (page_id INT PRIMARY KEY, img_name TEXT)', + 'INSERT into page_imgs VALUES (?, ?)', + { + (1, 'one'), + (2, 'two'), + (3, 'three'), + (4, 'four'), + (5, 'five'), + (6, 'six'), + (7, 'seven'), + } + ) + createTestDbTable( + imgDb, + 'CREATE TABLE imgs' \ + '(name TEXT PRIMARY KEY, license TEXT, artist TEXT, credit TEXT, restrictions TEXT, url TEXT)', + 'INSERT INTO imgs VALUES (?, ?, ?, ?, ?, ?)', + { + ('one','cc-by','alice','anna','','https://upload.wikimedia.org/1.jpg'), + ('two','???','bob','barbara','','https://upload.wikimedia.org/2.png'), + ('three','cc-by-sa','clare','File:?','','https://upload.wikimedia.org/3.gif'), + ('four','cc-by-sa 4.0','dave','dan','all','https://upload.wikimedia.org/4.jpeg'), + ('five','cc0','eve','eric',None,'https://upload.wikimedia.org/5.png'), + ('six','cc-by','','fred','','https://upload.wikimedia.org/6.png'), + } + ) + # Create temp output directory + with tempfile.TemporaryDirectory() as outDir: + # Run + downloadImgs(imgDb, outDir, 0) + # Check + expectedImgs = { + '1.jpg': 'img:https://upload.wikimedia.org/1.jpg', + '5.png': 'img:https://upload.wikimedia.org/5.png', + } + self.assertEqual(set(os.listdir(outDir)), set(expectedImgs.keys())) + for imgName, content in expectedImgs.items(): + self.assertEqual(readTestFile(os.path.join(outDir, imgName)), content) diff --git a/backend/tests/enwiki/test_gen_desc_data.py b/backend/tests/enwiki/test_gen_desc_data.py new file mode 100644 index 0000000..801aa69 --- /dev/null +++ b/backend/tests/enwiki/test_gen_desc_data.py @@ -0,0 +1,37 @@ +import unittest +import os, tempfile + +from tests.common import readTestDbTable +from tol_data.enwiki.gen_desc_data import genData + +TEST_DUMP_FILE = os.path.join(os.path.dirname(__file__), 'sample_enwiki_pages_articles.xml.bz2') + +class TestGenData(unittest.TestCase): + def test_gen(self): + with tempfile.TemporaryDirectory() as tempDir: + # Run + dbFile = os.path.join(tempDir, 'descData.db') + genData(TEST_DUMP_FILE, dbFile) + # Check + self.assertEqual( + readTestDbTable(dbFile, 'SELECT id, title FROM pages'), + { + (10, 'AccessibleComputing'), + (13, 'AfghanistanHistory'), + (25, 'Autism'), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT id, target FROM redirects'), + { + (10, 'Computer accessibility'), + (13, 'History of Afghanistan'), + } + ) + descsRows = readTestDbTable(dbFile, 'SELECT id, desc FROM descs') + expectedDescPrefixes = { + 25: 'Kanner autism, or classic autism, is a neurodevelopmental disorder', + } + self.assertEqual({row[0] for row in descsRows}, set(expectedDescPrefixes.keys())) + for id, desc in descsRows: + self.assertTrue(id in expectedDescPrefixes and desc.startswith(expectedDescPrefixes[id])) diff --git a/backend/tests/enwiki/test_gen_dump_index_db.py b/backend/tests/enwiki/test_gen_dump_index_db.py new file mode 100644 index 0000000..e0715f3 --- /dev/null +++ b/backend/tests/enwiki/test_gen_dump_index_db.py @@ -0,0 +1,39 @@ +import unittest +import tempfile, os + +from tests.common import createTestBz2, readTestDbTable +from tol_data.enwiki.gen_dump_index_db import genData + +def runGenData(indexFileContents: str): + """ Sets up index file to be read by genData(), runs it, reads the output database, and returns offset info. """ + with tempfile.TemporaryDirectory() as tempDir: + # Create temp index file + indexFile = os.path.join(tempDir, 'index.txt.bz2') + createTestBz2(indexFile, indexFileContents) + # Run + dbFile = os.path.join(tempDir, 'data.db') + genData(indexFile, dbFile) + # Read db + return readTestDbTable(dbFile, 'SELECT title, id, offset, next_offset FROM offsets') + +class TestGenData(unittest.TestCase): + def setUp(self): + self.maxDiff = None # Remove output-diff size limit + def test_index_file(self): + indexFileContents = ( + '100:10:apple\n' + '100:11:ant\n' + '300:99:banana ice-cream\n' + '1000:2030:Custard!\n' + ) + offsetsMap = runGenData(indexFileContents) + self.assertEqual(offsetsMap, { + ('apple', 10, 100, 300), + ('ant', 11, 100, 300), + ('banana ice-cream', 99, 300, 1000), + ('Custard!', 2030, 1000, -1), + }) + def test_emp_index(self): + offsetsMap = runGenData('') + self.assertEqual(offsetsMap, set()) + pass diff --git a/backend/tests/enwiki/test_gen_img_data.py b/backend/tests/enwiki/test_gen_img_data.py new file mode 100644 index 0000000..1703b78 --- /dev/null +++ b/backend/tests/enwiki/test_gen_img_data.py @@ -0,0 +1,64 @@ +import unittest +import tempfile, os + +from tests.common import createTestDbTable, readTestDbTable +from tol_data.enwiki.gen_img_data import getInputPageIdsFromDb, genData + +TEST_DUMP_FILE = os.path.join(os.path.dirname(__file__), 'sample_enwiki_pages_articles.xml.bz2') + +class TestGetInputPageIdsFromDb(unittest.TestCase): + def test_get(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp tree-of-life db + dbFile = os.path.join(tempDir, 'data.db') + createTestDbTable( + dbFile, + 'CREATE TABLE wiki_ids (name TEXT PRIMARY KEY, id INT)', + 'INSERT INTO wiki_ids VALUES (?, ?)', + { + ('one', 1), + ('and another', 2), + } + ) + # Run + pageIds = getInputPageIdsFromDb(dbFile) + # Check + self.assertEqual(pageIds, {1, 2}) + +class TestGenData(unittest.TestCase): + def test_gen(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp dump-index db + indexDb = os.path.join(tempDir, 'dump_index.db') + createTestDbTable( + indexDb, + 'CREATE TABLE offsets (title TEXT PRIMARY KEY, id INT UNIQUE, offset INT, next_offset INT)', + 'INSERT INTO offsets VALUES (?, ?, ?, ?)', + { + ('AccessibleComputing',10,0,-1), + ('AfghanistanHistory',13,0,-1), + ('Autism',25,0,-1), + } + ) + # Run + imgDb = os.path.join(tempDir, 'imgData.db') + genData({10, 25}, TEST_DUMP_FILE, indexDb, imgDb) + # Check + self.assertEqual( + readTestDbTable(imgDb, 'SELECT page_id, img_name from page_imgs'), + { + (10, None), + (25, 'Autism-stacking-cans 2nd edit.jpg'), + } + ) + # Run with updated page-ids set + genData({13, 10}, TEST_DUMP_FILE, indexDb, imgDb) + # Check + self.assertEqual( + readTestDbTable(imgDb, 'SELECT page_id, img_name from page_imgs'), + { + (10, None), + (13, None), + (25, 'Autism-stacking-cans 2nd edit.jpg'), + } + ) diff --git a/backend/tests/enwiki/test_gen_pageview_data.py b/backend/tests/enwiki/test_gen_pageview_data.py new file mode 100644 index 0000000..5002eb0 --- /dev/null +++ b/backend/tests/enwiki/test_gen_pageview_data.py @@ -0,0 +1,44 @@ +import unittest +import tempfile, os + +from tests.common import createTestBz2, createTestDbTable, readTestDbTable +from tol_data.enwiki.gen_pageview_data import genData + +class TestGenData(unittest.TestCase): + def test_gen(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp pageview files + pageviewFiles = [os.path.join(tempDir, 'pageviews1.bz2'), os.path.join(tempDir, 'pageviews2.bz2')] + createTestBz2(pageviewFiles[0], ( + 'aa.wikibooks One null desktop 1 W1\n' + 'en.wikipedia Two null mobile-web 10 A9B1\n' + 'en.wikipedia Three null desktop 4 D3\n' + )) + createTestBz2(pageviewFiles[1], ( + 'fr.wikipedia Four null desktop 12 T6U6\n' + 'en.wikipedia Three null desktop 10 E4G5Z61\n' + )) + # Create temp dump-index db + dumpIndexDb = os.path.join(tempDir, 'dump_index.db') + createTestDbTable( + dumpIndexDb, + 'CREATE TABLE offsets (title TEXT PRIMARY KEY, id INT UNIQUE, offset INT, next_offset INT)', + 'INSERT INTO offsets VALUES (?, ?, ?, ?)', + { + ('One', 1, 0, -1), + ('Two', 2, 0, -1), + ('Three', 3, 0, -1), + ('Four', 4, 0, -1), + } + ) + # Run + dbFile = os.path.join(tempDir, 'data.db') + genData(pageviewFiles, dumpIndexDb, dbFile) + # Check + self.assertEqual( + readTestDbTable(dbFile, 'SELECT title, id, views from views'), + { + ('Two', 2, 5), + ('Three', 3, 7), + } + ) diff --git a/backend/tests/eol/__init__.py b/backend/tests/eol/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/backend/tests/eol/__init__.py diff --git a/backend/tests/eol/test_download_imgs.py b/backend/tests/eol/test_download_imgs.py new file mode 100644 index 0000000..975d1c7 --- /dev/null +++ b/backend/tests/eol/test_download_imgs.py @@ -0,0 +1,74 @@ +import unittest +from unittest.mock import Mock, patch +import tempfile, os + +from tests.common import readTestFile, createTestDbTable +from tol_data.eol.download_imgs import getEolIdsFromDb, downloadImgs + +class TestGetEolIdsFromDb(unittest.TestCase): + def test_get(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp db + dbFile = os.path.join(tempDir, 'data.db') + createTestDbTable( + dbFile, + 'CREATE TABLE eol_ids (name TEXT PRIMARY KEY, id INT)', + 'INSERT INTO eol_ids VALUES (?, ?)', + { + ('one', 1), + ('a second', 2), + } + ) + # Run + eolIds = getEolIdsFromDb(dbFile) + # Check + self.assertEqual(eolIds, {1, 2}) + +class TestDownloadImgs(unittest.TestCase): + @patch('requests.get', autospec=True) + def test_gen(self, requestsGetMock): + requestsGetMock.side_effect = lambda url: Mock(content=('img:' + url).encode()) + with tempfile.TemporaryDirectory() as tempDir: + eolIds = {1, 2, 4} + # Create temp images-list db + imagesListDb = os.path.join(tempDir, 'images_list.db') + createTestDbTable( + imagesListDb, + 'CREATE TABLE images (content_id INT PRIMARY KEY, page_id INT, source_url TEXT,' \ + ' copy_url TEXT, license TEXT, copyright_owner TEXT)', + 'INSERT INTO images VALUES (?, ?, ?, ?, ?, ?)', + { + (10, 1, '???', 'https://content.eol.org/1.jpg', 'cc-by-sa', 'owner1'), + (20, 2, '', 'https://content.eol.org/2.jpg', 'cc-by', 'owner2'), + (21, 2, '', 'https://content.eol.org/2b.jpg', 'public domain', 'owner2'), + (22, 2, '', 'https://content.eol.org/2c.jpg', '???', 'owner3'), + (23, 2, '', 'data/2d.jpg', 'cc-by-nc', 'owner5'), + (24, 2, '', 'https://content.eol.org/2e', 'cc-by', 'owner6'), + (25, 2, '', 'https://content.eol.org/2f.gif', 'cc-by', 'owner7'), + (30, 3, '', 'https://content.eol.org/3.png', 'cc-by', 'owner3'), + } + ) + # Create temp output dir + with tempfile.TemporaryDirectory() as outDir: + # Run + downloadImgs(eolIds, imagesListDb, outDir) + # Check + expectedImgs1 = { + '1 10.jpg': 'img:https://content.eol.org/1.jpg', + '2 20.jpg': 'img:https://content.eol.org/2.jpg', + '2 23.jpg': 'img:https://content.eol.org/data/2d.jpg', + '2 25.gif': 'img:https://content.eol.org/2f.gif', + } + expectedImgs2 = { + '1 10.jpg': 'img:https://content.eol.org/1.jpg', + '2 21.jpg': 'img:https://content.eol.org/2b.jpg', + '2 23.jpg': 'img:https://content.eol.org/data/2d.jpg', + '2 25.gif': 'img:https://content.eol.org/2f.gif', + } + outImgSet = set(os.listdir(outDir)) + expectedImgSet1 = set(expectedImgs1.keys()) + expectedImgSet2 = set(expectedImgs2.keys()) + self.assertIn(outImgSet, (expectedImgSet1, expectedImgSet2)) + matchingImgs = expectedImgs1 if outImgSet == expectedImgSet1 else expectedImgs2 + for imgName, imgContent in matchingImgs.items(): + self.assertEqual(readTestFile(os.path.join(outDir, imgName)), imgContent) diff --git a/backend/tests/eol/test_gen_images_list_db.py b/backend/tests/eol/test_gen_images_list_db.py new file mode 100644 index 0000000..ca9b495 --- /dev/null +++ b/backend/tests/eol/test_gen_images_list_db.py @@ -0,0 +1,32 @@ +import unittest +import tempfile, os + +from tests.common import createTestFile, readTestDbTable +from tol_data.eol.gen_images_list_db import genData + +class TestGenData(unittest.TestCase): + def test_gen(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp images-list files + imageListsGlob = os.path.join(tempDir, 'imgs-*.csv') + createTestFile(os.path.join(tempDir, 'imgs-1.csv'), ( + 'EOL content ID,EOL page ID,Medium Source URL,EOL Full-Size Copy URL,License Name,Copyright Owner\n' + '1,10,https://example.com/1/,https://content.eol.org/1.jpg,cc-by,owner1\n' + '2,20,https://example2.com/2/,https://content.eol.org/2.jpg,cc-by-sa,owner2\n' + )) + createTestFile(os.path.join(tempDir, 'imgs-2.csv'), ( + '3,30,https://example.com/3/,https://content.eol.org/3.png,public,owner3\n' + )) + # Run + dbFile = os.path.join(tempDir, 'imagesList.db') + genData(imageListsGlob, dbFile) + # Check + self.assertEqual( + readTestDbTable( + dbFile, 'SELECT content_id, page_id, source_url, copy_url, license, copyright_owner from images'), + { + (1, 10, 'https://example.com/1/', 'https://content.eol.org/1.jpg', 'cc-by', 'owner1'), + (2, 20, 'https://example2.com/2/', 'https://content.eol.org/2.jpg', 'cc-by-sa', 'owner2'), + (3, 30, 'https://example.com/3/', 'https://content.eol.org/3.png', 'public', 'owner3'), + } + ) diff --git a/backend/tests/eol/test_review_imgs.py b/backend/tests/eol/test_review_imgs.py new file mode 100644 index 0000000..49c09bb --- /dev/null +++ b/backend/tests/eol/test_review_imgs.py @@ -0,0 +1,46 @@ +import unittest +import tempfile, os, shutil + +from tests.common import createTestDbTable +from tol_data.eol.review_imgs import reviewImgs + +CLICK_IMG = os.path.join(os.path.dirname(__file__), '..', 'green.png') +AVOID_IMG = os.path.join(os.path.dirname(__file__), '..', 'red.png') + +class TestReviewImgs(unittest.TestCase): + def test_review(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create input images + imgDir = os.path.join(tempDir, 'imgs_for_review') + os.mkdir(imgDir) + shutil.copy(CLICK_IMG, os.path.join(imgDir, '1 10.jpg')) + shutil.copy(CLICK_IMG, os.path.join(imgDir, '2 20.jpeg')) + shutil.copy(AVOID_IMG, os.path.join(imgDir, '2 21.gif')) + shutil.copy(AVOID_IMG, os.path.join(imgDir, '2 22.jpg')) + shutil.copy(AVOID_IMG, os.path.join(imgDir, '3 30.png')) + shutil.copy(AVOID_IMG, os.path.join(imgDir, '3 31.jpg')) + # Create temp extra-info db + extraInfoDb = os.path.join(tempDir, 'data.db') + createTestDbTable( + extraInfoDb, + 'CREATE TABLE eol_ids (name TEXT PRIMARY KEY, id INT)', + 'INSERT INTO eol_ids VALUES (?, ?)', + { + ('one', 1), + ('two', 2), + ('three', 3), + } + ) + createTestDbTable( + extraInfoDb, + 'CREATE TABLE names(name TEXT, alt_name TEXT, pref_alt INT, src TEXT, PRIMARY KEY(name, alt_name))', + 'INSERT OR IGNORE INTO names VALUES (?, ?, ?, ?)', + { + ('two','II',1,'eol'), + } + ) + # Run + outDir = os.path.join(tempDir, 'imgs') + reviewImgs(imgDir, outDir, extraInfoDb) + # Check + self.assertEqual(set(os.listdir(outDir)), {'1 10.jpg', '2 20.jpeg'}) diff --git a/backend/tests/green.png b/backend/tests/green.png Binary files differnew file mode 100644 index 0000000..d4f15c9 --- /dev/null +++ b/backend/tests/green.png diff --git a/backend/tests/red.png b/backend/tests/red.png Binary files differnew file mode 100644 index 0000000..7828e96 --- /dev/null +++ b/backend/tests/red.png diff --git a/backend/tests/test_gen_desc_data.py b/backend/tests/test_gen_desc_data.py new file mode 100644 index 0000000..cc0582d --- /dev/null +++ b/backend/tests/test_gen_desc_data.py @@ -0,0 +1,101 @@ +import unittest +import tempfile, os + +from tests.common import createTestDbTable, readTestDbTable +from tol_data.gen_desc_data import genData + +class TestGenData(unittest.TestCase): + def test_gen(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp dbpedia db + dbpediaDb = os.path.join(tempDir, 'dbp_descs.db') + createTestDbTable( + dbpediaDb, + 'CREATE TABLE ids (iri TEXT PRIMARY KEY, id INT)', + 'INSERT INTO ids VALUES (?, ?)', + { + ('<http://dbpedia.org/resource/One>', 1), + ('<http://dbpedia.org/resource/Two>', 2), + ('<http://dbpedia.org/resource/Three>', 3), + } + ) + createTestDbTable( + dbpediaDb, + 'CREATE TABLE redirects (iri TEXT PRIMARY KEY, target TEXT)', + 'INSERT INTO redirects VALUES (?, ?)', + { + ('<http://dbpedia.org/resource/Two>', '<http://dbpedia.org/resource/Three>'), + } + ) + createTestDbTable( + dbpediaDb, + 'CREATE TABLE abstracts (iri TEXT PRIMARY KEY, abstract TEXT)', + 'INSERT INTO abstracts VALUES (?, ?)', + { + ('<http://dbpedia.org/resource/One>', 'One from dbp'), + ('<http://dbpedia.org/resource/Two>', 'Two from dbp'), + ('<http://dbpedia.org/resource/Three>', 'Three from dbp'), + } + ) + # Create temp enwiki db + enwikiDb = os.path.join(tempDir, 'enwiki_descs.db') + createTestDbTable( + enwikiDb, + 'CREATE TABLE pages (id INT PRIMARY KEY, title TEXT UNIQUE)', + 'INSERT INTO pages VALUES (?, ?)', + { + (1, 'I'), + (3, 'III'), + (4, 'IV'), + (5, 'V'), + (6, 'VI'), + } + ) + createTestDbTable( + enwikiDb, + 'CREATE TABLE redirects (id INT PRIMARY KEY, target TEXT)', + 'INSERT INTO redirects VALUES (?, ?)', + { + (5, 'IV'), + } + ) + createTestDbTable( + enwikiDb, + 'CREATE TABLE descs (id INT PRIMARY KEY, desc TEXT)', + 'INSERT INTO descs VALUES (?, ?)', + { + (1, 'One from enwiki'), + (3, 'Three from enwiki'), + (4, 'Four from enwiki'), + (5, 'Five from enwiki'), + } + ) + # Create temp tree-of-life db + dbFile = os.path.join(tempDir, 'data.db') + createTestDbTable( + dbFile, + 'CREATE TABLE wiki_ids (name TEXT PRIMARY KEY, id INT)', + 'INSERT INTO wiki_ids VALUES (?, ?)', + { + ('first', 1), + ('second', 2), + ('third', 3), + ('fourth', 4), + ('fifth', 5), + ('sixth', 6), + ('seventh', 7), + } + ) + # Run + genData(dbpediaDb, enwikiDb, dbFile) + # Check + self.assertEqual( + readTestDbTable(dbFile, 'SELECT wiki_id, desc, from_dbp from descs'), + { + (1, 'One from dbp', 1), + (2, 'Three from dbp', 1), + (3, 'Three from dbp', 1), + (4, 'Four from enwiki', 0), + (5, 'Four from enwiki', 0), + } + ) diff --git a/backend/tests/test_gen_imgs.py b/backend/tests/test_gen_imgs.py new file mode 100644 index 0000000..1ddd438 --- /dev/null +++ b/backend/tests/test_gen_imgs.py @@ -0,0 +1,125 @@ +import unittest +from unittest.mock import patch +import tempfile, os, shutil + +from tests.common import createTestFile, createTestDbTable, readTestDbTable +from tol_data.gen_imgs import genImgs + +TEST_IMG = os.path.join(os.path.dirname(__file__), 'green.png') + +class TestGenImgs(unittest.TestCase): + @patch('tol_data.gen_imgs.convertImage', autospec=True) + def test_gen(self, convertImageMock): + with tempfile.TemporaryDirectory() as tempDir: + convertImageMock.side_effect = \ + lambda imgPath, outPath: shutil.copy(imgPath, outPath) + # Create temp EOL images + eolImgDir = os.path.join(tempDir, 'eol_imgs') + os.mkdir(eolImgDir) + shutil.copy(TEST_IMG, os.path.join(eolImgDir, '1 10.jpg')) + shutil.copy(TEST_IMG, os.path.join(eolImgDir, '2 20.png')) + shutil.copy(TEST_IMG, os.path.join(eolImgDir, '5 50.jpg')) + # Create temp EOL image db + eolImgDb = os.path.join(tempDir, 'eol_imgs.db') + createTestDbTable( + eolImgDb, + 'CREATE TABLE images (content_id INT PRIMARY KEY, page_id INT, source_url TEXT,' \ + ' copy_url TEXT, license TEXT, copyright_owner TEXT)', + 'INSERT INTO images VALUES (?, ?, ?, ?, ?, ?)', + { + (10, 1, 'https://example.com/1.jpg', '', 'cc-by', 'eol owner1'), + (20, 2, 'https://example.com/2.png', '', 'cc-by-sa', 'eol owner2'), + (50, 5, 'https://example.com/5.jpg', '', 'cc-by-sa', 'eol owner3'), + } + ) + # Create temp enwiki images + enwikiImgDir = os.path.join(tempDir, 'enwiki_imgs') + os.mkdir(enwikiImgDir) + shutil.copy(TEST_IMG, os.path.join(enwikiImgDir, '100.jpg')) + shutil.copy(TEST_IMG, os.path.join(enwikiImgDir, '200.jpeg')) + shutil.copy(TEST_IMG, os.path.join(enwikiImgDir, '400.png')) + # Create temp enwiki image db + enwikiImgDb = os.path.join(tempDir, 'enwiki_imgs.db') + createTestDbTable( + enwikiImgDb, + 'CREATE TABLE page_imgs (page_id INT PRIMARY KEY, img_name TEXT)', + 'INSERT INTO page_imgs VALUES (?, ?)', + { + (100, 'one.jpg'), + (200, 'two.jpeg'), + (300, 'two.jpeg'), + (400, 'two.jpeg'), + } + ) + createTestDbTable( + enwikiImgDb, + 'CREATE TABLE imgs (' \ + 'name TEXT PRIMARY KEY, license TEXT, artist TEXT, credit TEXT, restrictions TEXT, url TEXT)', + 'INSERT INTO imgs VALUES (?, ?, ?, ?, ?, ?)', + { + ('one.jpg', 'CC BY-SA 3.0', 'author1', 'credits1', '', 'https://upload.wikimedia.org/one.jpg'), + ('two.jpeg', 'cc-by', 'author2', 'credits2', '', 'https://upload.wikimedia.org/two.jpeg'), + ('four.png', 'cc0', 'author3', '', '', 'https://upload.wikimedia.org/x.png'), + } + ) + # Create temp picked-images file + pickedImgsFile = os.path.join(tempDir, 'img_data.txt') + createTestFile(pickedImgsFile, ( + 'node5.jpg|url1|cc-by-sa 4.0|artist1|credit1\n' + )) + # Create temp picked-images + pickedImgDir = os.path.join(tempDir, 'picked_imgs') + os.mkdir(pickedImgDir) + shutil.copy(TEST_IMG, os.path.join(pickedImgDir, 'node5.jpg')) + # Create temp img-list file + imgListFile = os.path.join(tempDir, 'img_list.txt') + createTestFile(imgListFile, ( + 'ott1 ' + os.path.join(eolImgDir, '1 10.jpg') + '\n' + 'ott2 ' + os.path.join(enwikiImgDir, '200.jpeg') + '\n' + 'ott3\n' + 'ott4 ' + os.path.join(enwikiImgDir, '400.png') + '\n' + 'ott5 ' + os.path.join(eolImgDir, '5 50.jpg') + '\n' + )) + # Create temp tree-of-life db + dbFile = os.path.join(tempDir, 'data.db') + createTestDbTable( + dbFile, + 'CREATE TABLE nodes (name TEXT PRIMARY KEY, id TEXT UNIQUE, tips INT)', + 'INSERT INTO nodes VALUES (?, ?, ?)', + { + ('node1', 'ott1', 1), + ('node2', 'ott2', 1), + ('node3', 'ott3', 2), + ('node4', 'ott4', 4), + ('node5', 'ott5', 1), + ('node6', 'ott6', 10), + } + ) + # Run + outDir = os.path.join(tempDir, 'img') + genImgs(imgListFile, eolImgDir, outDir, eolImgDb, enwikiImgDb, pickedImgDir, pickedImgsFile, dbFile) + # Check + self.assertEqual(set(os.listdir(outDir)), { + 'ott1.jpg', + 'ott2.jpg', + 'ott4.jpg', + 'ott5.jpg', + }) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT name, img_id, src from node_imgs'), + { + ('node1', 1, 'eol'), + ('node2', 200, 'enwiki'), + ('node4', 400, 'enwiki'), + ('node5', 1, 'picked'), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT id, src, url, license, artist, credit from images'), + { + (1, 'eol', 'https://example.com/1.jpg', 'cc-by', 'eol owner1', ''), + (200, 'enwiki', 'https://en.wikipedia.org/wiki/File:two.jpeg', 'cc-by', 'author2', 'credits2'), + (400, 'enwiki', 'https://en.wikipedia.org/wiki/File:two.jpeg', 'cc-by', 'author2', 'credits2'), + (1, 'picked', 'url1', 'cc-by-sa 4.0', 'artist1', 'credit1'), + } + ) diff --git a/backend/tests/test_gen_linked_imgs.py b/backend/tests/test_gen_linked_imgs.py new file mode 100644 index 0000000..b989407 --- /dev/null +++ b/backend/tests/test_gen_linked_imgs.py @@ -0,0 +1,84 @@ +import unittest +import tempfile, os + +from tests.common import createTestDbTable, readTestDbTable +from tol_data.gen_linked_imgs import genData + +class TestGenData(unittest.TestCase): + def test_gen(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp tree-of-life db + # Test tree ('I' means a node has an image): + # one -> two -> sixI + # -> seven + # -> eight + # -> threeI + # -> [nine + ten] -> nineI + # -> ten + # -> fiveI -> [twelve + thirteen] -> twelveI + # -> thirteenI + dbFile = os.path.join(tempDir, 'data.db') + createTestDbTable( + dbFile, + 'CREATE TABLE nodes (name TEXT PRIMARY KEY, id TEXT UNIQUE, tips INT)', + 'INSERT INTO nodes VALUES (?, ?, ?)', + { + ('one', 'ott1', 8), + ('two', 'ott2', 3), + ('three', 'ott3', 1), + ('[nine + ten]', 'ott4', 2), + ('five', 'ott5', 2), + ('six', 'ott6', 1), + ('seven', 'ott7', 1), + ('eight', 'ott8', 1), + ('nine', 'ott9', 1), + ('ten', 'ott10', 1), + ('[twelve + thirteen]', 'ott11', 2), + ('twelve', 'ott12', 1), + ('thirteen', 'ott13', 1), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE edges (parent TEXT, child TEXT, p_support INT, PRIMARY KEY (parent, child))', + 'INSERT INTO edges VALUES (?, ?, ?)', + { + ('one', 'two', 1), + ('one', 'three', 1), + ('one', '[nine + ten]', 0), + ('one', 'five', 1), + ('two', 'six', 1), + ('two', 'seven', 1), + ('two', 'eight', 0), + ('[nine + ten]', 'nine', 0), + ('[nine + ten]', 'ten', 1), + ('five', '[twelve + thirteen]', 1), + ('[twelve + thirteen]', 'twelve', 1), + ('[twelve + thirteen]', 'thirteen', 0), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE node_imgs (name TEXT PRIMARY KEY, img_id INT, src TEXT)', + 'INSERT INTO node_imgs VALUES (?, ?, ?)', + { + ('six', 1, 'eol'), + ('three', 10, 'enwiki'), + ('nine', 1, 'picked'), + ('five', 2, 'eol'), + ('twelve', 11, 'enwiki'), + ('thirteen', 12, 'enwiki'), + } + ) + # Run + genData(dbFile) + # Check + self.assertEqual( + readTestDbTable(dbFile, 'SELECT name, otol_ids from linked_imgs'), + { + ('one', 'ott6'), + ('two', 'ott6'), + ('[nine + ten]', 'ott9,'), + ('[twelve + thirteen]', 'ott12,ott13'), + } + ) diff --git a/backend/tests/test_gen_mapping_data.py b/backend/tests/test_gen_mapping_data.py new file mode 100644 index 0000000..9aa99b7 --- /dev/null +++ b/backend/tests/test_gen_mapping_data.py @@ -0,0 +1,302 @@ +import unittest +import tempfile, os + +from tests.common import createTestFile, createTestGzip, createTestDbTable, readTestDbTable +from tol_data.gen_mapping_data import \ + genData, readTaxonomyFile, readEolIdsFile, readWikidataDb, readPickedMappings, getEnwikiPageIds + +class TestReadTaxonomyFile(unittest.TestCase): + def test_read(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp taxonomy file + taxonomyFile = os.path.join(tempDir, 'taxonomy.tsv') + SEP = '\t|\t' + createTestFile(taxonomyFile, ''.join([ + SEP.join(['uid', 'parent_uid', 'name', 'rank', 'sourceinfo', 'uniqueName', 'flags', '\n']), + SEP.join(['1', '2', 'one', 'species', 'ncbi:10', '', '', '\n']), + SEP.join(['2', '3', 'two', 'genus', 'ncbi:20,gbif:1', 'bananas', '', '\n']), + SEP.join(['10', '20', 'ten', 'family', 'if:10,if:100', '', '', '\n']), + SEP.join(['11', '100', 'eleven', '', 'igloo:1,ncbi:?', '', '', '\n']) + ])) + # Run + nodeToSrcIds = {} + usedSrcIds = set() + readTaxonomyFile(taxonomyFile, nodeToSrcIds, usedSrcIds) + # Check + self.assertEqual(nodeToSrcIds, { + 1: {'ncbi': 10}, + 2: {'ncbi': 20, 'gbif': 1}, + 10: {'if': 10}, + }) + self.assertEqual(usedSrcIds, { + ('ncbi', 10), + ('ncbi', 20), + ('gbif', 1), + ('if', 10) + }) +class TestReadEolIdsFile(unittest.TestCase): + def test_read(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp EOL IDs file + eolIdsFile = os.path.join(tempDir, 'ids.csv.gz') + createTestGzip(eolIdsFile, ( + 'node_id,resource_pk,resource_id,page_id,preferred_canonical_for_page\n' + '0,10,676,1,rhubarb\n' # EOL ID 1 with ncbi ID 10 + '0,99,767,2,nothing\n' # EOL ID 2 with worms ID 99 + '0,234,459,100,goat\n' # EOL ID 100 with gbif ID 234 + '0,23,676,101,lemon\n' # EOL ID 101 with ncbi ID 23 + )) + # Create input maps + nodeToSrcIds = { + 10: {'ncbi': 10}, + 20: {'ncbi': 23, 'gbif': 234} + } + # Run + usedSrcIds = {('ncbi', 10), ('gbif', 234), ('ncbi', 23)} + nodeToEolId = {} + readEolIdsFile(eolIdsFile, nodeToSrcIds, usedSrcIds, nodeToEolId) + # Check + self.assertEqual(nodeToEolId, { + 10: 1, + 20: 101, + }) +class TestReadWikidataDb(unittest.TestCase): + def test_read(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp wikidata db + wikidataDb = os.path.join(tempDir, 'taxon_srcs.db') + createTestDbTable( + wikidataDb, + 'CREATE TABLE src_id_to_title (src TEXT, id INT, title TEXT, PRIMARY KEY(src, id))', + 'INSERT INTO src_id_to_title VALUES (?, ?, ?)', + [ + ('ncbi', 1, 'one'), + ('ncbi', 11, 'two'), + ('gbif', 21, 'three'), + ('if', 31, 'three'), + ('ncbi', 2, 'four'), + ('gbif', 1, 'five'), + ('eol', 1, 'one'), + ('eol', 2, 'three'), + ('ncbi', 100, 'six'), + ] + ) + createTestDbTable( + wikidataDb, + 'CREATE TABLE title_iucn (title TEXT PRIMARY KEY, status TEXT)', + 'INSERT INTO title_iucn VALUES (?, ?)', + [ + ('one', 'least concern'), + ('three', 'vulnerable'), + ('six', 'extinct in the wild'), + ] + ) + # Create input maps + nodeToSrcIds = { + 10: {'ncbi': 1}, + 20: {'ncbi': 11, 'gbif': 21, 'if': 31}, + 30: {'ncbi': 2, 'gbif': 1}, + 40: {'ncbi': 99}, + } + usedSrcIds = { + ('ncbi', 1), ('ncbi', 2), ('gbif', 1), ('ncbi', 11), ('gbif', 21), ('if', 31), + ('eol', 10), ('ncbi', 99) + } + nodeToEolId = { + 20: 100, + } + # Run + nodeToWikiTitle = {} + titleToIucnStatus = {} + readWikidataDb(wikidataDb, nodeToSrcIds, usedSrcIds, nodeToWikiTitle, titleToIucnStatus, nodeToEolId) + # Check + self.assertEqual(nodeToWikiTitle, { + 10: 'one', + 20: 'three', + 30: 'four', + }) + self.assertEqual(titleToIucnStatus, { + 'one': 'least concern', + 'three': 'vulnerable', + }) + self.assertEqual(nodeToEolId, { + 10: 1, + 20: 100, + }) +class TestReadPickedMappings(unittest.TestCase): + def test_read(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp picked-mappings files + pickedMappings = {'eol': ['1.txt'], 'enwiki': ['2.txt', '3.txt']} + pickedMappingsContent = {'eol': [''], 'enwiki': ['', '']} + pickedMappingsContent['eol'][0] = ( + '10|100\n' + '20|202\n' + ) + pickedMappingsContent['enwiki'][0] = ( + '12|abc\n' + '23|def\n' + ) + pickedMappingsContent['enwiki'][1] = ( + '15|ghi\n' + '35|jkl\n' + ) + for src in pickedMappings: + for idx in range(len(pickedMappings[src])): + pickedMappings[src][idx] = os.path.join(tempDir, pickedMappings[src][idx]) + createTestFile(pickedMappings[src][idx], pickedMappingsContent[src][idx]) + # Create input maps + nodeToEolId = { + 1: 1, + 10: 66, + } + nodeToWikiTitle = { + 10: 'one', + 12: 'two', + 35: 'goanna', + } + # Run + readPickedMappings(pickedMappings, nodeToEolId, nodeToWikiTitle) + # Check + self.assertEqual(nodeToEolId, { + 1: 1, + 10: 100, + 20: 202, + }) + self.assertEqual(nodeToWikiTitle, { + 10: 'one', + 12: 'abc', + 23: 'def', + 15: 'ghi', + 35: 'jkl', + }) +class TestReadGetEnwikiPageIds(unittest.TestCase): + def test_read(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp dump index + dumpIndexDb = os.path.join(tempDir, 'dump_index.db') + createTestDbTable( + dumpIndexDb, + 'CREATE TABLE offsets (title TEXT PRIMARY KEY, id INT UNIQUE, offset INT, next_offset INT)', + 'INSERT INTO offsets VALUES (?, ?, ?, ?)', + [ + ('one', 1, 10, 100), + ('two', 22, 10, 100), + ('four', 3, 1000, 2000), + ] + ) + # Create input maps + nodeToWikiTitle = { + 10: 'one', + 20: 'two', + 30: 'three', + } + # Run + titleToPageId = {} + getEnwikiPageIds(dumpIndexDb, nodeToWikiTitle, titleToPageId) + # Check + self.assertEqual(titleToPageId, { + 'one': 1, + 'two': 22, + }) +class TestGenData(unittest.TestCase): + def test_mapping(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp taxonomy file + taxonomyFile = os.path.join(tempDir, 'taxonomy.tsv') + SEP = '\t|\t' + createTestFile(taxonomyFile, ''.join([ + SEP.join(['uid', 'parent_uid', 'name', 'rank', 'sourceinfo', 'uniqueName', 'flags', '\n']), + SEP.join(['1', '', '', '', 'ncbi:10', '', '', '\n']), + SEP.join(['2', '', '', '', 'ncbi:20,gbif:1', '', '', '\n']), + SEP.join(['3', '', '', '', 'ncbi:30,if:2', '', '', '\n']), + ])) + # Create temp EOL IDs file + eolIdsFile = os.path.join(tempDir, 'ids.csv.gz') + createTestGzip(eolIdsFile, ( + 'node_id,resource_pk,resource_id,page_id,preferred_canonical_for_page\n' + '0,10,676,1,\n' # EOL ID 1 with ncbi ID 10 + '0,30,676,2,\n' # EOL ID 2 with ncbi ID 30 + )) + # Create temp wikidata db + wikidataDb = os.path.join(tempDir, 'taxon_srcs.db') + createTestDbTable( + wikidataDb, + 'CREATE TABLE src_id_to_title (src TEXT, id INT, title TEXT, PRIMARY KEY(src, id))', + 'INSERT INTO src_id_to_title VALUES (?, ?, ?)', + [ + ('ncbi', 10, 'one'), + ('gbif', 1, 'two'), + ('eol', 100, 'two'), + ('if', 2, 'three'), + ] + ) + createTestDbTable( + wikidataDb, + 'CREATE TABLE title_iucn (title TEXT PRIMARY KEY, status TEXT)', + 'INSERT INTO title_iucn VALUES (?, ?)', + [ + ('one', 'least concern'), + ('three', 'vulnerable'), + ] + ) + # Create temp picked-mappings files + pickedMappings = {'eol': [], 'enwiki': ['w_ids.txt']} + pickedMappingsContent = {'eol': [], 'enwiki': ['']} + pickedMappingsContent['enwiki'][0] = ( + '3|four\n' + ) + for src in pickedMappings: + for idx in range(len(pickedMappings[src])): + pickedMappings[src][idx] = os.path.join(tempDir, pickedMappings[src][idx]) + createTestFile(pickedMappings[src][idx], pickedMappingsContent[src][idx]) + # Create temp dump index + dumpIndexDb = os.path.join(tempDir, 'dump_index.db') + createTestDbTable( + dumpIndexDb, + 'CREATE TABLE offsets (title TEXT PRIMARY KEY, id INT UNIQUE, offset INT, next_offset INT)', + 'INSERT INTO offsets VALUES (?, ?, ?, ?)', + [ + ('one', 1000, 1, 2), + ('two', 2000, 1, 2), + ('three', 3000, 1, 2), + ('four', 4000, 1, 2), + ] + ) + # Create temp tree-of-life db + dbFile = os.path.join(tempDir, 'data.db') + createTestDbTable( + dbFile, + 'CREATE TABLE nodes (name TEXT PRIMARY KEY, id TEXT UNIQUE, tips INT)', + 'INSERT INTO nodes VALUES (?, ?, ?)', + [ + ('first', 'ott1', 10), + ('second', 'ott2', 1), + ('third', 'ott3', 2), + ] + ) + # Run + genData(taxonomyFile, eolIdsFile, wikidataDb, pickedMappings, dumpIndexDb, dbFile) + # Check + self.assertEqual( + readTestDbTable(dbFile, 'SELECT name, id from eol_ids'), + { + ('first', 1), + ('second', 100), + ('third', 2), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT name, id from wiki_ids'), + { + ('first', 1000), + ('second', 2000), + ('third', 4000), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT name, iucn from node_iucn'), + { + ('first', 'least concern'), + } + ) diff --git a/backend/tests/test_gen_name_data.py b/backend/tests/test_gen_name_data.py new file mode 100644 index 0000000..85e81d8 --- /dev/null +++ b/backend/tests/test_gen_name_data.py @@ -0,0 +1,93 @@ +import unittest +import tempfile, os + +from tests.common import createTestFile, createTestDbTable, readTestDbTable +from tol_data.gen_name_data import genData + +class TestGenData(unittest.TestCase): + def test_gen(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp eol names file + eolNamesFile = os.path.join(tempDir, 'vernacular_names.csv') + createTestFile(eolNamesFile, ( + 'page_id,,vernacular_string,language_code,,,is_preferred_by_eol\n' + '10,,cat,eng,,,preferred\n' + '10,,kitty,eng,,,\n' + '20,,apple,eng,,,preferred\n' + '20,,pomme,fr,,,preferred\n' + '20,,apples,eng,,,\n' + '30,,those things with wings,eng,,,\n' + )) + # Create temp enwiki db + enwikiDb = os.path.join(tempDir, 'desc_data.db') + createTestDbTable( + enwikiDb, + 'CREATE TABLE pages (id INT PRIMARY KEY, title TEXT UNIQUE)', + 'INSERT INTO pages VALUES (?, ?)', + [ + (1, 'abc'), + (2, 'def'), + (3, 'ghi'), + ] + ) + createTestDbTable( + enwikiDb, + 'CREATE TABLE redirects (id INT PRIMARY KEY, target TEXT)', + 'INSERT INTO redirects VALUES (?, ?)', + [ + (3, 'abc'), + (4, 'def'), + ] + ) + # Create temp picked-names file + pickedNamesFile = os.path.join(tempDir, 'picked_names.txt') + createTestFile(pickedNamesFile, ( + 'three|xxx|1\n' + 'one|kitty|\n' + 'two|two|\n' + )) + # Create temp db + dbFile = os.path.join(tempDir, 'data.db') + createTestDbTable( + dbFile, + 'CREATE TABLE nodes (name TEXT PRIMARY KEY, id TEXT UNIQUE, tips INT)', + 'INSERT INTO nodes VALUES (?, ?, ?)', + [ + ('one', 'ott1', 1), + ('two', 'ott2', 1), + ('three', 'ott3', 1), + ] + ) + createTestDbTable( + dbFile, + 'CREATE TABLE eol_ids (name TEXT PRIMARY KEY, id INT)', + 'INSERT INTO eol_ids VALUES (?, ?)', + [ + ('one', 10), + ('two', 20), + ('three', 30), + ] + ) + createTestDbTable( + dbFile, + 'CREATE TABLE wiki_ids (name TEXT PRIMARY KEY, id INT)', + 'INSERT INTO wiki_ids VALUES (?, ?)', + [ + ('one', 1), + ('two', 3), + ('three', 2), + ] + ) + # Run + genData(eolNamesFile, enwikiDb, pickedNamesFile, dbFile) + # Check + self.assertEqual( + readTestDbTable(dbFile, 'SELECT name, alt_name, pref_alt, src FROM names'), + { + ('one', 'cat', 1, 'eol'), + ('one', 'ghi', 0, 'enwiki'), + ('two', 'apple', 0, 'eol'), + ('two', 'apples', 0, 'eol'), + ('three', 'xxx', 1, 'picked'), + } + ) diff --git a/backend/tests/test_gen_otol_data.py b/backend/tests/test_gen_otol_data.py new file mode 100644 index 0000000..25e65e3 --- /dev/null +++ b/backend/tests/test_gen_otol_data.py @@ -0,0 +1,118 @@ +import unittest +import tempfile, os + +from tests.common import createTestFile, readTestDbTable +from tol_data.gen_otol_data import genData + +def runGenData(treeFileContents: str, annFileContents: str, pickedFileContents: str): + """ Sets up files to be read by genData(), runs it, reads the output database, and returns node+edge info """ + with tempfile.TemporaryDirectory() as tempDir: + # Create temp tree file + treeFile = os.path.join(tempDir, 'tree.tre') + createTestFile(treeFile, treeFileContents) + # Create temp annotations file + annFile = os.path.join(tempDir, 'ann.json') + createTestFile(annFile, annFileContents) + # Create temp picked names file + pickedFile = os.path.join(tempDir, 'pn.txt') + createTestFile(pickedFile, pickedFileContents) + # Run genData() + dbFile = os.path.join(tempDir, 'data.db') + genData(treeFile, annFile, pickedFile, dbFile) + # Read database + nodes = readTestDbTable(dbFile, 'SELECT name, id, tips FROM nodes') + edges = readTestDbTable(dbFile, 'SELECT parent, child, p_support FROM edges') + return nodes, edges + +class TestGenData(unittest.TestCase): + def setUp(self): + self.maxDiff = None # Remove output-diff size limit + def test_newick(self): + treeFileContents = """ + ( + 'land plants ott2', + ( + 'TRAVELLER''s tree ott100', + (domestic_banana_ott4, (lemon_ott6, orange_ott7)citrus_ott5)mrcaott4ott5 + ) mrcaott100ott4, + 'Highly Unu2u8| name!! ott999', + 'citrus ott230' + )cellular_organisms_ott1;""" + annFileContents = '{"nodes": {}}' + pickedFileContents = '' + nodes, edges = runGenData(treeFileContents, annFileContents, pickedFileContents) + self.assertEqual(nodes, { + ('land plants', 'ott2', 1), + ('traveller\'s tree', 'ott100', 1), + ('domestic banana', 'ott4', 1), + ('lemon', 'ott6', 1), + ('orange', 'ott7', 1), + ('citrus', 'ott5', 2), + ('[citrus + domestic banana]', 'mrcaott4ott5', 3), + ('[citrus + traveller\'s tree]', 'mrcaott100ott4', 4), + ('highly unu2u8| name!! ', 'ott999', 1), + ('citrus [2]', 'ott230', 1), + ('cellular organisms', 'ott1', 7), + }) + self.assertEqual(edges, { + ('cellular organisms', 'land plants', 0), + ('cellular organisms', '[citrus + traveller\'s tree]', 0), + ('cellular organisms', 'highly unu2u8| name!! ', 0), + ('cellular organisms', 'citrus [2]', 0), + ('[citrus + traveller\'s tree]', 'traveller\'s tree', 0), + ('[citrus + traveller\'s tree]', '[citrus + domestic banana]', 0), + ('[citrus + domestic banana]', 'domestic banana', 0), + ('[citrus + domestic banana]', 'citrus', 0), + ('citrus', 'lemon', 0), + ('citrus', 'orange', 0), + }) + def test_newick_invalid(self): + with self.assertRaises(Exception): + runGenData('(A,B,(C,D));', '{"nodes": {}}', '') + def test_annotations(self): + treeFileContents = '(two_ott2, three_ott3, four_ott4)one_ott1;' + annFileContents = """ + { + "date_completed": "xxx", + "nodes": { + "ott3": { + "supported_by": { + "tree1": "node1" + } + }, + "ott4": { + "supported_by": { + "tree1": "node2", + "tree2": "node100" + }, + "conflicts_with": { + "tree3": ["x", "y"] + } + } + } + }""" + nodes, edges = runGenData(treeFileContents, annFileContents, '') + self.assertEqual(nodes, { + ('one', 'ott1', 3), + ('two', 'ott2', 1), + ('three', 'ott3', 1), + ('four', 'ott4', 1), + }) + self.assertEqual(edges, { + ('one', 'two', 0), + ('one', 'three', 1), + ('one', 'four', 0), + }) + def test_picked_names_file(self): + treeFileContents = '(one_ott2, two_ott3)one_ott1;' + pickedFileContents = 'one|ott2' + nodes, edges = runGenData(treeFileContents, '{"nodes": {}}', pickedFileContents) + self.assertEqual(nodes, { + ('one [2]', 'ott1', 2), + ('one', 'ott2', 1), + ('two', 'ott3', 1), + }) + self.assertEqual(edges, { + ('one [2]', 'one', 0), + ('one [2]', 'two', 0), + }) diff --git a/backend/tests/test_gen_pop_data.py b/backend/tests/test_gen_pop_data.py new file mode 100644 index 0000000..dd1cb22 --- /dev/null +++ b/backend/tests/test_gen_pop_data.py @@ -0,0 +1,42 @@ +import unittest +import tempfile, os + +from tests.common import createTestDbTable, readTestDbTable +from tol_data.gen_pop_data import genData + +class TestGenData(unittest.TestCase): + def test_gen(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp pageviews db + pageviewsDb = os.path.join(tempDir, 'pageview_data.db') + createTestDbTable( + pageviewsDb, + 'CREATE TABLE views (title TEXT PRIMARY KEY, id INT, views INT)', + 'INSERT INTO views VALUES (?, ?, ?)', + { + ('one', 1, 10), + ('two', 2, 20), + ('three', 3, 30), + } + ) + # Create temp tree-of-life db + dbFile = os.path.join(tempDir, 'data.db') + createTestDbTable( + dbFile, + 'CREATE TABLE wiki_ids (name TEXT PRIMARY KEY, id INT)', + 'INSERT INTO wiki_ids VALUES (?, ?)', + { + ('node1', 1), + ('node3', 3), + } + ) + # Run + genData(pageviewsDb, dbFile) + # Check + self.assertEqual( + readTestDbTable(dbFile, 'SELECT name, pop from node_pop'), + { + ('node1', 10), + ('node3', 30) + } + ) diff --git a/backend/tests/test_gen_reduced_trees.py b/backend/tests/test_gen_reduced_trees.py new file mode 100644 index 0000000..2ae4dfd --- /dev/null +++ b/backend/tests/test_gen_reduced_trees.py @@ -0,0 +1,166 @@ +import unittest +import tempfile, os + +from tests.common import createTestFile, createTestDbTable, readTestDbTable +from tol_data.gen_reduced_trees import genData + +class TestGenData(unittest.TestCase): + def test_gen(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp tree-of-life db + # Test tree (P/I/L/D means picked/image/linked_image/desc): + # one -> two -> threeI -> four + # -> fiveP + # -> [seven + eight] -> sevenD + # -> eightP + # -> nine -> tenI + # -> elevenL + dbFile = os.path.join(tempDir, 'data.db') + createTestDbTable( + dbFile, + 'CREATE TABLE nodes (name TEXT PRIMARY KEY, id TEXT UNIQUE, tips INT)', + 'INSERT INTO nodes VALUES (?, ?, ?)', + { + ('one', 'ott1', 6), + ('two', 'ott2', 2), + ('three', 'ott3', 1), + ('four', 'ott4', 1), + ('five', 'ott5', 1), + ('[seven + eight]', 'ott6', 2), + ('seven', 'ott7', 1), + ('eight', 'ott8', 1), + ('nine', 'ott9', 1), + ('ten', 'ott10', 1), + ('eleven', 'ott11', 1), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE edges (parent TEXT, child TEXT, p_support INT, PRIMARY KEY (parent, child))', + 'INSERT INTO edges VALUES (?, ?, ?)', + { + ('one', 'two', 1), + ('two', 'three', 1), + ('three', 'four', 0), + ('two', 'five', 0), + ('one', '[seven + eight]', 1), + ('[seven + eight]', 'seven', 0), + ('[seven + eight]', 'eight', 1), + ('one', 'nine', 1), + ('nine', 'ten', 0), + ('one', 'eleven', 1), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE names(name TEXT, alt_name TEXT, pref_alt INT, src TEXT, PRIMARY KEY(name, alt_name))', + 'INSERT INTO names VALUES (?, ?, ?, ?)', + { + ('eight', 'VIII', 1, 'eol'), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE wiki_ids (name TEXT PRIMARY KEY, id INT)', + 'INSERT INTO wiki_ids VALUES (?, ?)', + { + ('seven', 10), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE descs (wiki_id INT PRIMARY KEY, desc TEXT, from_dbp INT)', + 'INSERT INTO descs VALUES (?, ?, ?)', + { + (10, 'Seven prefers orange juice', 1), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE node_imgs (name TEXT PRIMARY KEY, img_id INT, src TEXT)', + 'INSERT INTO node_imgs VALUES (?, ?, ?)', + { + ('three', 1, 'eol'), + ('ten', 10, 'enwiki'), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE linked_imgs (name TEXT PRIMARY KEY, otol_ids TEXT)', + 'INSERT INTO linked_imgs VALUES (?, ?)', + { + ('eleven', 'ott3'), + } + ) + # Create temp picked-nodes file + pickedNodesFile = os.path.join(tempDir, 'picked_nodes.txt') + createTestFile(pickedNodesFile, ( + 'five\n' + 'VIII\n' + )) + # Run + genData(None, dbFile, pickedNodesFile) + # Check + self.assertEqual( + readTestDbTable(dbFile, 'SELECT name, id, tips from nodes_p'), + { + ('one', 'ott1', 3), + ('five', 'ott5', 1), + ('eight', 'ott8', 1), + ('eleven', 'ott11', 1), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT parent, child, p_support from edges_p'), + { + ('one', 'five', 0), + ('one', 'eight', 1), + ('one', 'eleven', 1), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT name, id, tips from nodes_i'), + { + ('one', 'ott1', 4), + ('two', 'ott2', 2), + ('three', 'ott3', 1), + ('five', 'ott5', 1), + ('eight', 'ott8', 1), + ('ten', 'ott10', 1), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT parent, child, p_support from edges_i'), + { + ('one', 'two', 1), + ('two', 'three', 1), + ('two', 'five', 0), + ('one', 'eight', 1), + ('one', 'ten', 0), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT name, id, tips from nodes_t'), + { + ('one', 'ott1', 5), + ('two', 'ott2', 2), + ('three', 'ott3', 1), + ('five', 'ott5', 1), + ('[seven + eight]', 'ott6', 2), + ('seven', 'ott7', 1), + ('eight', 'ott8', 1), + ('ten', 'ott10', 1), + } + ) + self.assertEqual( + readTestDbTable(dbFile, 'SELECT parent, child, p_support from edges_t'), + { + ('one', 'two', 1), + ('two', 'three', 1), + ('two', 'five', 0), + ('one', '[seven + eight]', 1), + ('[seven + eight]', 'seven', 0), + ('[seven + eight]', 'eight', 1), + ('one', 'ten', 0), + } + ) diff --git a/backend/tests/test_review_imgs_to_gen.py b/backend/tests/test_review_imgs_to_gen.py new file mode 100644 index 0000000..d88523b --- /dev/null +++ b/backend/tests/test_review_imgs_to_gen.py @@ -0,0 +1,84 @@ +import unittest +import tempfile, os, shutil + +from tests.common import readTestFile, createTestDbTable +from tol_data.review_imgs_to_gen import reviewImgs + +CLICK_IMG = os.path.join(os.path.dirname(__file__), 'green.png') +AVOID_IMG = os.path.join(os.path.dirname(__file__), 'red.png') + +class TestReviewImgs(unittest.TestCase): + def test_review(self): + with tempfile.TemporaryDirectory() as tempDir: + # Create temp eol imgs + eolImgDir = os.path.join(tempDir, 'eol_imgs') + os.mkdir(eolImgDir) + shutil.copy(CLICK_IMG, os.path.join(eolImgDir, '1 10.jpg')) + shutil.copy(AVOID_IMG, os.path.join(eolImgDir, '2 20.gif')) + shutil.copy(AVOID_IMG, os.path.join(eolImgDir, '4 40.jpg')) + # Create temp enwiki imgs + enwikiImgDir = os.path.join(tempDir, 'enwiki_imgs') + os.mkdir(enwikiImgDir) + shutil.copy(AVOID_IMG, os.path.join(enwikiImgDir, '1.jpg')) + shutil.copy(CLICK_IMG, os.path.join(enwikiImgDir, '3.png')) + shutil.copy(CLICK_IMG, os.path.join(enwikiImgDir, '4.png')) + # Create temp tree-of-life db + dbFile = os.path.join(tempDir, 'data.db') + createTestDbTable( + dbFile, + 'CREATE TABLE nodes (name TEXT PRIMARY KEY, id TEXT UNIQUE, tips INT)', + 'INSERT INTO nodes VALUES (?, ?, ?)', + { + ('one', 'ott1', 1), + ('two', 'ott2', 10), + ('three', 'ott3', 2), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE names(name TEXT, alt_name TEXT, pref_alt INT, src TEXT, PRIMARY KEY(name, alt_name))', + 'INSERT OR IGNORE INTO names VALUES (?, ?, ?, ?)', + { + ('two', 'II', 1, 'eol'), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE eol_ids (name TEXT PRIMARY KEY, id INT)', + 'INSERT INTO eol_ids VALUES (?, ?)', + { + ('one', 1), + ('two', 2), + ('four', 4), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE wiki_ids (name TEXT PRIMARY KEY, id INT)', + 'INSERT INTO wiki_ids VALUES (?, ?)', + { + ('one', 1), + ('three', 3), + ('four', 4), + } + ) + # Run + outFile = os.path.join(tempDir, 'imgList.txt') + reviewImgs(eolImgDir, enwikiImgDir, dbFile, outFile, 'all') + # Check + self.assertEqual(set(readTestFile(outFile).splitlines()), { + 'ott1 ' + os.path.join(eolImgDir, '1 10.jpg'), + 'ott2', + 'ott3 ' + os.path.join(enwikiImgDir, '3.png'), + }) + # Add extra data + createTestDbTable(dbFile, None, 'INSERT INTO nodes VALUES (?, ?, ?)',{('four', 'ott4', 2)}) + # Run + reviewImgs(eolImgDir, enwikiImgDir, dbFile, outFile, 'all') + # Check + self.assertEqual(set(readTestFile(outFile).splitlines()), { + 'ott1 ' + os.path.join(eolImgDir, '1 10.jpg'), + 'ott2', + 'ott3 ' + os.path.join(enwikiImgDir, '3.png'), + 'ott4 ' + os.path.join(enwikiImgDir, '4.png'), + }) diff --git a/backend/tests/test_tilo.py b/backend/tests/test_tilo.py new file mode 100644 index 0000000..cfc719a --- /dev/null +++ b/backend/tests/test_tilo.py @@ -0,0 +1,160 @@ +import unittest +import tempfile, os + +from tests.common import createTestDbTable +from tilo import handleReq, TolNode, SearchSuggResponse, SearchSugg, InfoResponse, NodeInfo, DescInfo, ImgInfo + +def initTestDb(dbFile: str) -> None: + # Test tree (I/D means image/desc): + # oneI -> twoD -> threeD + # -> fourI + # -> fiveI -> sixID -> seven + createTestDbTable( + dbFile, + 'CREATE TABLE nodes_t (name TEXT PRIMARY KEY, id TEXT UNIQUE, tips INT)', + 'INSERT INTO nodes_t VALUES (?, ?, ?)', + { + ('one', 'ott1', 3), + ('two', 'ott2', 2), + ('three', 'ott3', 1), + ('four', 'ott4', 1), + ('five', 'ott5', 1), + ('six', 'ott6', 1), + ('seven', 'ott7', 1), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE edges_t (parent TEXT, child TEXT, p_support INT, PRIMARY KEY (parent, child))', + 'INSERT INTO edges_t VALUES (?, ?, ?)', + { + ('one', 'two', 1), + ('two', 'three', 0), + ('two', 'four', 1), + ('one', 'five', 0), + ('five', 'six', 1), + ('six', 'seven', 1), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE names(name TEXT, alt_name TEXT, pref_alt INT, src TEXT, PRIMARY KEY(name, alt_name))', + 'INSERT INTO names VALUES (?, ?, ?, ?)', + { + ('one', 'turtle', 1, 'eol'), + ('two', 'II', 1, 'eol'), + ('five', 'V', 0, 'enwiki'), + ('six', 'VI', 1, 'enwiki'), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE node_imgs (name TEXT PRIMARY KEY, img_id INT, src TEXT)', + 'INSERT INTO node_imgs VALUES (?, ?, ?)', + { + ('one', 1, 'eol'), + ('four', 10, 'enwiki'), + ('five', 10, 'enwiki'), + ('six', 1, 'picked'), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE linked_imgs (name TEXT PRIMARY KEY, otol_ids TEXT)', + 'INSERT INTO linked_imgs VALUES (?, ?)', + { + ('two', 'ott4'), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE images (' \ + 'id INT, src TEXT, url TEXT, license TEXT, artist TEXT, credit TEXT, PRIMARY KEY (id, src))', + 'INSERT INTO images VALUES (?, ?, ?, ?, ?, ?)', + { + (1, 'eol', 'url1', 'license1', 'artist1', 'credit1'), + (10, 'enwiki', 'url2', 'license2', 'artist2', 'credit2'), + (1, 'picked', 'url3', 'license3', 'artist3', 'credit3'), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE node_iucn (name TEXT PRIMARY KEY, iucn TEXT)', + 'INSERT INTO node_iucn VALUES (?, ?)', + { + ('one', 'vulnerable'), + ('six', 'endangered'), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE node_pop (name TEXT PRIMARY KEY, pop INT)', + 'INSERT INTO node_pop VALUES (?, ?)', + { + ('one', 10), + ('two', 20), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE wiki_ids (name TEXT PRIMARY KEY, id INT)', + 'INSERT INTO wiki_ids VALUES (?, ?)', + { + ('two', 200), + ('three', 300), + ('six', 600), + } + ) + createTestDbTable( + dbFile, + 'CREATE TABLE descs (wiki_id INT PRIMARY KEY, desc TEXT, from_dbp INT)', + 'INSERT INTO descs VALUES (?, ?, ?)', + { + (200, 'two is 2', 1), + (300, 'three is 3', 0), + (600, 'six is 6', 1), + } + ) + +class TestHandleReq(unittest.TestCase): + def setUp(self): + self.maxDiff = None + self.tempDir = tempfile.TemporaryDirectory() + self.dbFile = os.path.join(self.tempDir.name, 'data.db') + initTestDb(self.dbFile) + def tearDown(self): + self.tempDir.cleanup() + def test_node_req(self): + response = handleReq(self.dbFile, {'QUERY_STRING': 'name=two&type=node&tree=trimmed'}) + self.assertEqual(response, { + 'two': TolNode('ott2', ['three', 'four'], 'one', 2, True, 'II', 'ott4.jpg', None), + 'three': TolNode('ott3', [], 'two', 1, False, None, None, None), + 'four': TolNode('ott4', [], 'two', 1, True, None, 'ott4.jpg', None), + }) + def test_node_toroot_req(self): + response = handleReq(self.dbFile, {'QUERY_STRING': 'name=seven&type=node&toroot=1&excl=five&tree=trimmed'}) + self.assertEqual(response, { + 'five': TolNode('ott5', ['six'], 'one', 1, 0, None, 'ott5.jpg', None), + 'six': TolNode('ott6', ['seven'], 'five', 1, 1, 'VI', 'ott6.jpg', 'endangered'), + 'seven': TolNode('ott7', [], 'six', 1, 1, None, None, None), + }) + def test_sugg_req(self): + response = handleReq(self.dbFile, {'QUERY_STRING': 'name=t&type=sugg&tree=trimmed'}) + self.assertEqual(response, SearchSuggResponse( + [ + SearchSugg('turtle', 'one', 10), + SearchSugg('two', None, 20), + SearchSugg('three', None, 0), + ], + False + )) + def test_info_req(self): + response = handleReq(self.dbFile, {'QUERY_STRING': 'name=six&type=info&tree=trimmed'}) + self.assertEqual(response, InfoResponse( + NodeInfo( + TolNode('ott6', ['seven'], 'five', 1, True, 'VI', 'ott6.jpg', 'endangered'), + DescInfo('six is 6', 600, True), + ImgInfo(1, 'picked', 'url3', 'license3', 'artist3', 'credit3'), + ), + [] + )) diff --git a/backend/tests/wikidata/__init__.py b/backend/tests/wikidata/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/backend/tests/wikidata/__init__.py diff --git a/backend/tests/wikidata/test_gen_taxon_src_data.py b/backend/tests/wikidata/test_gen_taxon_src_data.py new file mode 100644 index 0000000..1f886b3 --- /dev/null +++ b/backend/tests/wikidata/test_gen_taxon_src_data.py @@ -0,0 +1,109 @@ +import unittest +import tempfile, os, json, bz2, pickle, indexed_bzip2 + +from tests.common import readTestDbTable +from tol_data.wikidata.gen_taxon_src_data import genData + +def runGenData(wikiItemArray: str, preGenOffsets: bool, nProcs: int): + """ Sets up wikidata file to be read by genData(), runs it, reads the output database, and returns src+iucn info. + If 'preGenOffsets' is True, generates a bz2 offsets file before running genData(). """ + with tempfile.TemporaryDirectory() as tempDir: + # Create temp wikidata file + wikidataFile = os.path.join(tempDir, 'dump.json.bz2') + with bz2.open(wikidataFile, mode='wb') as file: + file.write(b'[\n') + for i in range(len(wikiItemArray)): + file.write(json.dumps(wikiItemArray[i], separators=(',',':')).encode()) + if i < len(wikiItemArray) - 1: + file.write(b',') + file.write(b'\n') + file.write(b']\n') + # Create temp offsets file if requested + offsetsFile = os.path.join(tempDir, 'offsets.dat') + if preGenOffsets: + with indexed_bzip2.open(wikidataFile) as file: + with open(offsetsFile, 'wb') as file2: + pickle.dump(file.block_offsets(), file2) + # Run genData() + dbFile = os.path.join(tempDir, 'data.db') + genData(wikidataFile, offsetsFile, dbFile, nProcs) + # Read db + srcRows = readTestDbTable(dbFile, 'SELECT src, id, title FROM src_id_to_title') + iucnRows = readTestDbTable(dbFile, 'SELECT title, status FROM title_iucn') + return srcRows, iucnRows + +class TestGenData(unittest.TestCase): + def setUp(self): + self.maxDiff = None # Remove output-diff size limit + self.testWikiItems = [ + { + 'id': 'Q1', + 'claims': { + 'P31': [{'mainsnak': {'datavalue': {'value': {'id': 'Q16521'}}}}], # instance-of 'taxon' + 'P830': [{'mainsnak': {'datavalue': {'value': 100}}}], # EOL ID 100 + 'P685': [{'mainsnak': {'datavalue': {'value': 200}}}], # NCBI ID 200 + 'P141': [{'mainsnak': {'datavalue': {'value': {'id': 'Q211005'}}}}], # IUCN 'least concern' + }, + 'sitelinks': {'enwiki': {'title': 'eucalyptus'}}, + }, + { + 'id': 'Q2', + 'claims': { + 'P685': [{'mainsnak': {'datavalue': {'value': 101}}}], # NCBI ID 101 + 'P31': [{'mainsnak': {'datavalue': {'value': {'id': 'Q23038290'}}}}], # fossil taxon + }, + 'sitelinks': {'enwiki': {'title': 'dolphin'}}, + }, + { + 'id': 'Q30', + 'claims': { + 'P31': [{'mainsnak': {'datavalue': {'value': {'id': 'Q502895'}}}, # instance-of common name + 'qualifiers': {'P642': [{'datavalue': {'value': {'numeric-id': 100}}}]}}], # of Q100 + 'P685': [{'mainsnak': {'datavalue': {'value': 333}}}], # NCBI ID 333 + }, + 'sitelinks': {'enwiki': {'title': 'dog'}}, + }, + { + 'id': 'Q100', + 'claims': { + 'P31': [{'mainsnak': {'datavalue': {'value': {'id': 'Q16521'}}}}], # instance-of taxon + 'P5055': [{'mainsnak': {'datavalue': {'value': 9}}}], # IRMNG ID 9 + 'P141': [{'mainsnak': {'datavalue': {'value': {'id': 'Q11394'}}}}], # IUCN endangered + }, + }, + { + 'id': 'Q1', + 'claims': { + 'P31': [{'mainsnak': {'datavalue': {'value': {'id': 'Q16521'}}}}], # instance-of taxon + } + # No title + }, + {'id': 'Q932', 'claims': {}}, + ] + self.expectedSrcRows = { + ('eol', 100, 'eucalyptus'), + ('ncbi', 200, 'eucalyptus'), + ('ncbi', 101, 'dolphin'), + ('ncbi', 333, 'dog'), + ('irmng', 9, 'dog'), + } + self.expectedIucnRows = { + ('eucalyptus', 'least concern'), + ('dog', 'endangered'), + } + def test_wikiItems(self): + srcMap, iucnMap = runGenData(self.testWikiItems, False, 1) + self.assertEqual(srcMap, self.expectedSrcRows) + self.assertEqual(iucnMap, self.expectedIucnRows) + def test_empty_dump(self): + srcMap, iucnMap = runGenData([{}], False, 1) + self.assertEqual(srcMap, set()) + self.assertEqual(iucnMap, set()) + def test_multiprocessing(self): + srcMap, iucnMap = runGenData(self.testWikiItems, False, 4) + self.assertEqual(srcMap, self.expectedSrcRows) + self.assertEqual(iucnMap, self.expectedIucnRows) + def test_existing_offsets(self): + srcMap, iucnMap = runGenData(self.testWikiItems, True, 3) + self.assertEqual(srcMap, self.expectedSrcRows) + self.assertEqual(iucnMap, self.expectedIucnRows) |
