Shared below is a functionality test. I would love to get some review from the community. Thank you.
The idea of the system is a simple CLI application which can be used to download PDF from a given URL. For more information please visit https://github.com/PythonCheatsheet/downloadpdf.
Test Code
#!/usr/bin/env python3
import logging
import unittest
import os
import shutil
import tracemalloc
from util.log import initilaizeLog
from util.storage import storagePath
from util.header import setHeaders
from main.scrap import scrapHREF
from main.download import downloadPDF
class TestDownloadPDF(unittest.TestCase):
os.environ["DEBUG"] = "TRUE"
url = ''
folder = ''
pdfFileExists = False
def setUp(self):
super(TestDownloadPDF, self).setUp()
initilaizeLog()
def test_shouldDownloadFromAthena(self):
self.folder = 'athena.ecs.csus.edu'
self.url = 'http://athena.ecs.csus.edu/~buckley/CSc191/'
location = storagePath(self.url)
setHeaders(self.url)
pdfs = scrapHREF(self.url)
self.assertIsNone(downloadPDF(self.url, location, pdfs))
self.fileAndFolderExists(self.folder)
def test_shouldDownloadFromWTF(self):
self.folder = 'wtf.tw'
self.url = 'https://wtf.tw/ref/'
location = storagePath(self.url)
setHeaders(self.url)
pdfs = scrapHREF(self.url)
self.assertIsNone(downloadPDF(self.url, location, pdfs))
self.fileAndFolderExists(self.folder)
def fileAndFolderExists(self, folder):
self.assertTrue(os.path.exists('/tmp/' + folder))
for fname in os.listdir('/tmp/' + folder):
if fname.endswith('.pdf'):
self.pdfFileExists = True
break
self.assertTrue(self.pdfFileExists)
def tearDown(self):
super(TestDownloadPDF, self).tearDown()
urlPart = self.url.split("//")[1]
folderName = urlPart.split("/")[0]
location = '/tmp/' + folderName
if os.path.exists(location):
shutil.rmtree(location)
logging.shutdown()
self.url = ''
self.pdfFileExists = False
self.folder = ''
Core Logic
#!/usr/bin/env python3
import logging
import os
from urllib import request
from urllib.parse import unquote
def downloadPDF(url, storage, pdfs):
for link in pdfs:
decodedFileName = link.get('href')
unquoteFileName = unquote(decodedFileName)
request.urlretrieve(url + '/' + decodedFileName,
storage + '/' + unquoteFileName)
if (os.environ.get('DEBUG')):
break
Web Scraper
#!/usr/bin/env python3
import re
from urllib import request
from bs4 import BeautifulSoup
def scrapHREF(url):
html = request.urlopen(url).read()
soup = BeautifulSoup(html, features="html.parser")
pdfs = soup.findAll("a", href=re.compile("pdf"))
if len(pdfs) == 0:
raise Exception('No PDFs found at ' + url)
return pdfs