Skip to content

Commit

Permalink
Fix for missing netrc.
Browse files Browse the repository at this point in the history
  • Loading branch information
bentappin committed Oct 11, 2015
1 parent 2c2f086 commit 106fe90
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 17 deletions.
27 changes: 17 additions & 10 deletions mixcloud/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@
import yaml

try:
from urllib import urlencode
from urllib.parse import urlencode
except ImportError:
# Python 2 fallback.
from urllib.parse import urlencode
from urllib import urlencode
FileNotFoundError = IOError


NETRC_MACHINE = 'mixcloud-api'
Expand Down Expand Up @@ -76,15 +77,21 @@ def __init__(self, api_root=API_ROOT, access_token=None):
self.api_root = api_root
if access_token is None:
try:
# Attempt netrc lookup.
netrc_auth = netrc.netrc().authenticators(NETRC_MACHINE)
if netrc_auth:
access_token = netrc_auth[2]
except netrc.NetrcParseError:
# Configuration errors unrelated to the Mixcloud entry will
# cause this exception to be thrown, whether or not there is a
# Mixcloud entry.
# Check there is a netrc file.
netrc_auth = netrc.netrc()
except FileNotFoundError:
pass
else:
try:
# Attempt netrc lookup.
credentials = netrc_auth.authenticators(NETRC_MACHINE)
if netrc_auth:
access_token = credentials[2]
except netrc.NetrcParseError:
# Configuration errors unrelated to the Mixcloud entry
# will cause this exception to be thrown, whether or not
# there is a Mixcloud entry.
pass
self.access_token = access_token

def artist(self, key):
Expand Down
15 changes: 8 additions & 7 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import dateutil.tz
import httpretty
import mixcloud
import netrc
import io
import unittest
from mixcloud.mock import MockServer, parse_headers, parse_multipart
Expand Down Expand Up @@ -238,9 +237,11 @@ def testOauthExchangeServerFail(self):
with self.assertRaises(mixcloud.MixcloudOauthError):
self.o.exchange_token('my_code')

def testNetrc(self):
ret_value = ('', None, 'my_access_token')
with mock.patch.object(netrc.netrc, 'authenticators',
return_value=ret_value):
m = mixcloud.Mixcloud()
self.assertEqual(m.access_token, ret_value[2])
@mock.patch('netrc.netrc.authenticators')
@mock.patch('netrc.netrc.__init__')
def testNetrc(self, netrc_init, netrc_authenticators):
netrc_init.return_value = None # Don't blow up when netrc missing.
netrc_authenticators.return_value = ('', None, 'my_access_token')

m = mixcloud.Mixcloud()
self.assertEqual(m.access_token, 'my_access_token')

0 comments on commit 106fe90

Please sign in to comment.