# Path: deliver/tests/test_base.py
# class BaseTest(unittest.TestCase):
# 
#     def setUp(self):
#         from test_data.test_config import py
#         self.config = py.copy()
# 
#     def tearDown(self):
#         super(BaseTest,self).tearDown()
#         if os.path.isfile(self.config['db_name']):
#             os.remove(self.config['db_name'])
# 
# def open_data(fileName):
#     '''
#     Opens the given file, which resides in the folder where all the
#     test data is.
#     '''
#     return open(os.path.join('test_data', fileName))
# 
# Path: deliver/converter/download.py
# class DownloadMessage(UnicodeMessage):
#     '''
#     This class is used to build a mail that contains an attachment,
#     which is a website downloaded from the given url.
#     '''
# 
#     def __init__(self, url):
#         '''
#         Builds a mail, downloading the given url in the process and
#         saving it as an attachment.
#         '''
#         self.url = self._sanitize(url)
#         super(DownloadMessage,self).__init__(self._build_mail())
#         self._complete_headers()
#         pass
# 
#     def _sanitize(self, url):
#         '''
#         Returns the given url as something that can be used by
#         urlopen.
#         '''
#         if not url.startswith('http://'):
#             url = 'http://' + url
#         return url
# 
#     def _complete_headers(self):
#         '''Fill the headers of the mail'''
#         complete_headers(self, u'Download of %s' % self.url, 'download')
# 
#     def _build_mail(self):
#         '''
#         Download the given url and build an attachment with the
#         contents. In case that the download fails, a text mail with
#         the error is built instead.
#         '''
#         success, dl = self._download_url(self.url)
#         if not success:
#             return build_text_mail(dl)
# 
#         msg = MIMEMultipart()
#         msg.attach(build_text_mail(u'Downloaded website included as an attachment'))
#         part = MIMEBase('application', "octet-stream")
#         part.set_payload(dl)
#         email.Encoders.encode_base64(part)
#         part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'website.html')
#         msg.attach(part)
#         return msg
# 
#     def _download_url(self, url):
#         '''
#         Return a tuple (status, content), with content being the
#         content of the url as a string, and status a boolean marking
#         whether the download was succesful or not.'''
#         try:
#             web = urllib2.urlopen(url)
#         except Exception as e:
#             result = (False, to_unicode(str(e)))
#         else:
#             result = (True, web.read())
#         return result


import urllib2
from deliver.tests.test_base import BaseTest, open_data
from mock import patch, Mock
from deliver.converter.download import DownloadMessage


    @patch('urllib2.urlopen')
    def test_sanitize(self, urlopen):
        url = 'http://www.google.com'
        msg = self._msg(urlopen, url, '')
        self.assertEqual(msg._sanitize(url), url)

    @patch('urllib2.urlopen')
    def test_sanitize_add_protocol(self, urlopen):
        url = 'www.google.com'
        msg = self._msg(urlopen, url, '')
        self.assertEqual(msg._sanitize(url), 'http://' + url)

    @patch('urllib2.urlopen')
    def test_build_mail(self, urlopen):
        url = 'www.google.com'
        msg = self._msg(urlopen, url, open_data('google.html'))
        self.assertTrue('Download' in msg['Subject'])
        self.assertFalse(msg.id is None)
        self.assertFalse(msg['Date'] is None)
        self.assertTrue(u'multipart/mixed' in msg['Content-Type'] )

        attachment = msg.get_payload(i=1)
        self.assertEqual(attachment['Content-Transfer-Encoding'], 'base64')
        self.assertTrue(attachment.get_payload().startswith(
                u'PCFkb2N0eXBlIGh0bWw+PGh0bWw+PGhlYWQ+PG1ldGEgaHR0cC1lcXVpdj0iY29udGVudC10eXBl'))

    @patch('urllib2.urlopen')
    def test_build_mail_error(self, urlopen):
        urlopen.side_effect = urllib2.HTTPError('', 404, 'Not Found', None, None)

# Path: deliver/tests/test_base.py
# class BaseTest(unittest.TestCase):
# 
#     def setUp(self):
#         from test_data.test_config import py
#         self.config = py.copy()
# 
#     def tearDown(self):
#         super(BaseTest,self).tearDown()
#         if os.path.isfile(self.config['db_name']):
#             os.remove(self.config['db_name'])
# 
# def open_data(fileName):
#     '''
#     Opens the given file, which resides in the folder where all the
#     test data is.
#     '''
#     return open(os.path.join('test_data', fileName))
# 
# Path: deliver/converter/download.py
# class DownloadMessage(UnicodeMessage):
#     '''
#     This class is used to build a mail that contains an attachment,
#     which is a website downloaded from the given url.
#     '''
# 
#     def __init__(self, url):
#         '''
#         Builds a mail, downloading the given url in the process and
#         saving it as an attachment.
#         '''
#         self.url = self._sanitize(url)
#         super(DownloadMessage,self).__init__(self._build_mail())
#         self._complete_headers()
#         pass
# 
#     def _sanitize(self, url):
#         '''
#         Returns the given url as something that can be used by
#         urlopen.
#         '''
#         if not url.startswith('http://'):
#             url = 'http://' + url
#         return url
# 
#     def _complete_headers(self):
#         '''Fill the headers of the mail'''
#         complete_headers(self, u'Download of %s' % self.url, 'download')
# 
#     def _build_mail(self):
#         '''
#         Download the given url and build an attachment with the
#         contents. In case that the download fails, a text mail with
#         the error is built instead.
#         '''
#         success, dl = self._download_url(self.url)
#         if not success:
#             return build_text_mail(dl)
# 
#         msg = MIMEMultipart()
#         msg.attach(build_text_mail(u'Downloaded website included as an attachment'))
#         part = MIMEBase('application', "octet-stream")
#         part.set_payload(dl)
#         email.Encoders.encode_base64(part)
#         part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'website.html')
#         msg.attach(part)
#         return msg
# 
#     def _download_url(self, url):
#         '''
#         Return a tuple (status, content), with content being the
#         content of the url as a string, and status a boolean marking
#         whether the download was succesful or not.'''
#         try:
#             web = urllib2.urlopen(url)
#         except Exception as e:
#             result = (False, to_unicode(str(e)))
#         else:
#             result = (True, web.read())
#         return result


# Path: deliver/tests/converter/test_converter_download.py
import urllib2
from deliver.tests.test_base import BaseTest, open_data
from mock import patch, Mock
from deliver.converter.download import DownloadMessage


    @patch('urllib2.urlopen')
    def test_sanitize(self, urlopen):
        url = 'http://www.google.com'
        msg = self._msg(urlopen, url, '')
        self.assertEqual(msg._sanitize(url), url)

    @patch('urllib2.urlopen')
    def test_sanitize_add_protocol(self, urlopen):
        url = 'www.google.com'
        msg = self._msg(urlopen, url, '')
        self.assertEqual(msg._sanitize(url), 'http://' + url)

    @patch('urllib2.urlopen')
    def test_build_mail(self, urlopen):
        url = 'www.google.com'
        msg = self._msg(urlopen, url, open_data('google.html'))
        self.assertTrue('Download' in msg['Subject'])
        self.assertFalse(msg.id is None)
        self.assertFalse(msg['Date'] is None)
        self.assertTrue(u'multipart/mixed' in msg['Content-Type'] )

        attachment = msg.get_payload(i=1)
        self.assertEqual(attachment['Content-Transfer-Encoding'], 'base64')
        self.assertTrue(attachment.get_payload().startswith(
                u'PCFkb2N0eXBlIGh0bWw+PGh0bWw+PGhlYWQ+PG1ldGEgaHR0cC1lcXVpdj0iY29udGVudC10eXBl'))

    @patch('urllib2.urlopen')
    def test_build_mail_error(self, urlopen):
        urlopen.side_effect = urllib2.HTTPError('', 404, 'Not Found', None, None)

        msg = DownloadMessage('')
