from nose.tools import raises
from unittest.case import SkipTest
from urllib2 import urlopen
import StringIO

import mock
import datetime, md5

import harvestmedia.api.exceptions
import harvestmedia.api.config
import harvestmedia.api.client

api_key = '12345'
webservice_url = 'https://service.harvestmedia.net/HMP-WS.svc'

@mock.patch('harvestmedia.api.client.urlopen')
@raises(harvestmedia.api.exceptions.InvalidAPIResponse)
def test_xml_failure(urlopen_mock):
    urlopen_mock.return_value = StringIO.StringIO('<xml><this xml is malformed</xml>')

    hmconfig = harvestmedia.api.config.Config()
    hmconfig.api_key = api_key
    hmconfig.webservice_url = webservice_url
    client = harvestmedia.api.client.Client()

@mock.patch('harvestmedia.api.client.urlopen')
def test_get_service_token(UrlOpenMock):
    u = UrlOpenMock()
    expiry = datetime.datetime.today().isoformat()
    test_token = md5.md5(expiry).hexdigest() # generate an md5 from the date for testing
    u.read.return_value = '<?xml version="1.0" encoding="utf-8"?><responseservicetoken><token value="%s" expiry="%s"/></responseservicetoken>' % (test_token, expiry)
    
    hmconfig = harvestmedia.api.config.Config()
    hmconfig.api_key = api_key
    hmconfig.webservice_url = webservice_url
    client = harvestmedia.api.client.Client()
    
    assert client.service_token == test_token
    assert client.service_token_expires == expiry


@@ -233,16 +233,61 @@
 i.client
+%0Afrom harvestmedia.api.library import Library
 %0A%0Aapi_ke
@@ -1449,12 +1449,1094 @@
  == expiry%0A%0A
+@mock.patch('harvestmedia.api.client.urlopen')%0Adef test_get_libraries(UrlOpenMock):%0A    u = UrlOpenMock()%0A    expiry = datetime.datetime.today().isoformat()%0A    test_token = md5.md5(expiry).hexdigest() # generate an md5 from the date for testing%0A    u.read.return_value = '%3C?xml version=%221.0%22 encoding=%22utf-8%22?%3E%3Cresponseservicetoken%3E%3Ctoken value=%22%25s%22 expiry=%22%25s%22/%3E%3C/responseservicetoken%3E' %25 (test_token, expiry)%0A    %0A    hmconfig = harvestmedia.api.config.Config()%0A    hmconfig.api_key = api_key%0A    hmconfig.webservice_url = webservice_url%0A    client = harvestmedia.api.client.Client()%0A    u.read.return_value = %22%22%22%0A        %3CResponseLibraries%3E%0A            %3Clibraries%3E %0A                %3Clibrary id=%22abc123%22 name=%22VIDEOHELPER%22 detail=%22Library description%22 /%3E%0A                %3Clibrary id=%22abc125%22 name=%22MODULES%22 detail=%22Library description%22 /%3E%0A            %3C/libraries%3E%0A        %3C/ResponseLibraries%3E%22%22%22%0A%0A    libraries = Library.get_libraries()%0A    assert isinstance(libraries, list)%0A%0A    library = libraries%5B0%5D%0A    assert library.id == 'abc123'%0A    assert library.name == 'VIDEOHELPER'%0A

add test for get_libraries