import unittest
import os
import base64
import inary.context as ctx
import inary.api
from inary.data.specfile import SpecFile
from inary.fetcher import Fetcher
from inary import util
from inary import uri

class FetchTestCase(unittest.TestCase):

    def setUp(self):
        unittest.TestCase.setUp(self)
        self.spec = SpecFile()
        self.spec.read('../repos/repo1/system/base/openssl/pspec.xml')
        self.url = uri.URI(self.spec.source.archive[0].uri)
        self.url.set_auth_info(("user", "pass"))
        self.destpath = ctx.config.archives_dir()
        self.fetch = Fetcher(self.url, self.destpath)

    def testFetch(self):
        self.fetch.fetch()
        fetchedFile = os.path.join(self.destpath, self.url.filename())
        if os.access(fetchedFile, os.R_OK):
            self.assertEqual(util.sha1_file(fetchedFile),self.spec.source.archive[0].sha1sum)
        os.remove(fetchedFile)

    def testFetcherFunctions(self):
        enc = base64.encodestring('{0}:{0}'.format(self.url.auth_info()))
        self.assertEqual(self.fetch._get_http_headers(),(('Authorization', 'Basic {}'.format(enc)),))
        assert not self.fetch._get_ftp_headers()



