Browse files

Fix PEP8 compliance

  • Loading branch information...
1 parent 4d33129 commit 4fd971315e8c6a5c72f4df019c06a017889123fb @jjmaestro jjmaestro committed Aug 23, 2012
Showing with 281 additions and 190 deletions.
  1. +15 −5 facepy/__init__.py
  2. +4 −2 facepy/exceptions.py
  3. +24 −25 facepy/graph_api.py
  4. +22 −19 facepy/signed_request.py
  5. +1 −0 facepy/test.py
  6. +15 −12 facepy/utils.py
  7. +11 −11 setup.py
  8. +6 −2 tests/test_exceptions.py
  9. +93 −55 tests/test_graph_api.py
  10. +41 −30 tests/test_signed_request.py
  11. +23 −18 tests/test_test.py
  12. +26 −11 tests/test_utils.py
View
20 facepy/__init__.py
@@ -1,5 +1,15 @@
-from .graph_api import GraphAPI
-from .signed_request import SignedRequest
-from .utils import get_application_access_token, get_extended_access_token
-from .exceptions import FacepyError
-from .version import __version__
+from facepy.exceptions import FacepyError
+from facepy.graph_api import GraphAPI
+from facepy.signed_request import SignedRequest
+from facepy.utils import get_application_access_token, get_extended_access_token
+from facepy.version import __version__
+
+
+__all__ = [
+ 'FacepyError',
+ 'GraphAPI',
+ 'SignedRequest',
+ 'get_application_access_token',
+ 'get_extended_access_token',
+ '__version__',
+]
View
6 facepy/exceptions.py
@@ -1,21 +1,23 @@
class FacepyError(Exception):
"""Base class for exceptions raised by Facepy."""
-
def __init__(self, message):
self.message = message
+
class FacebookError(FacepyError):
"""Exception for Facebook errors."""
-
def __init__(self, message=None, code=None):
self.message = message
self.code = code
+
class OAuthError(FacebookError):
"""Exception for Facebook errors specifically related to OAuth."""
+
class HTTPError(FacepyError):
"""Exception for transport errors."""
+
class SignedRequestError(FacepyError):
"""Exception for invalid signed requests."""
View
49 facepy/graph_api.py
@@ -1,16 +1,15 @@
-from urllib import urlencode
-from urlparse import urlparse, parse_qs
-import requests
-
-from .exceptions import *
-
try:
import simplejson as json
except ImportError:
- import json
+ import json # flake8: noqa
+import requests
+
+from urllib import urlencode
+
+from facepy.exceptions import *
-class GraphAPI(object):
+class GraphAPI(object):
def __init__(self, oauth_token=False, url='https://graph.facebook.com'):
"""
Initialize GraphAPI with an OAuth access token.
@@ -35,11 +34,11 @@ def get(self, path='', page=False, retry=3, **options):
for an exhaustive list of parameters.
"""
response = self._query(
- method = 'GET',
- path = path,
- data = options,
- page = page,
- retry = retry
+ method='GET',
+ path=path,
+ data=options,
+ page=page,
+ retry=retry
)
if response is False:
@@ -59,10 +58,10 @@ def post(self, path='', retry=0, **data):
for an exhaustive list of options.
"""
response = self._query(
- method = 'POST',
- path = path,
- data = data,
- retry = retry
+ method='POST',
+ path=path,
+ data=data,
+ retry=retry
)
if response is False:
@@ -78,9 +77,9 @@ def delete(self, path, retry=3):
:param retry: An integer describing how many times the request may be retried.
"""
response = self._query(
- method = 'DELETE',
- path = path,
- retry = retry
+ method='DELETE',
+ path=path,
+ retry=retry
)
if response is False:
@@ -105,6 +104,7 @@ def search(self, term, type, page=False, retry=3, **options):
for an exhaustive list of options.
"""
SUPPORTED_TYPES = ['post', 'user', 'page', 'event', 'group', 'place', 'checkin']
+
if type not in SUPPORTED_TYPES:
raise ValueError('Unsupported type "%s". Supported types are %s' % (type, ', '.join(SUPPORTED_TYPES)))
@@ -131,7 +131,7 @@ def batch(self, requests):
request['body'] = urlencode(request['body'])
responses = self.post(
- batch = json.dumps(requests)
+ batch=json.dumps(requests)
)
for response, request in zip(responses, requests):
@@ -160,9 +160,9 @@ def fql(self, query, retry=3):
for an exhaustive list of details.
"""
return self._query(
- method = 'GET',
- path = 'fql?%s' % urlencode({'q': query}),
- retry = retry
+ method='GET',
+ path='fql?%s' % urlencode({'q': query}),
+ retry=retry
)
def _query(self, method, path, data=None, page=False, retry=0):
@@ -179,7 +179,6 @@ def _query(self, method, path, data=None, page=False, retry=0):
data = data or {}
def load(method, url, data):
-
try:
if method in ['GET', 'DELETE']:
response = self.session.request(method, url, params=data, allow_redirects=True)
View
41 facepy/signed_request.py
@@ -1,16 +1,16 @@
-from datetime import datetime
-
import base64
import hashlib
import hmac
-import time
-
try:
import simplejson as json
except ImportError:
- import json
+ import json # flake8: noqa
+import time
+
+from datetime import datetime
+
+from facepy.exceptions import *
-from .exceptions import *
class SignedRequest(object):
"""
@@ -38,7 +38,6 @@ def __init__(self, signed_request=None, application_secret_key=None):
:param signed_request: A string describing a signed request.
:param application_secret_key: A string describing a Facebook application's secret key.
"""
-
self.signed_request = signed_request
self.application_secret_key = application_secret_key
@@ -47,23 +46,23 @@ def __init__(self, signed_request=None, application_secret_key=None):
self.data = self.raw.get('app_data', None)
self.page = self.Page(
- id = self.raw['page']['id'],
- is_liked = self.raw['page']['liked'],
- is_admin = self.raw['page']['admin']
+ id=self.raw['page']['id'],
+ is_liked=self.raw['page']['liked'],
+ is_admin=self.raw['page']['admin']
) if 'page' in self.raw else None
self.user = self.User(
- id = self.raw.get('user_id'),
- locale = self.raw['user'].get('locale', None),
- country = self.raw['user'].get('country', None),
- age = range(
+ id=self.raw.get('user_id'),
+ locale=self.raw['user'].get('locale', None),
+ country=self.raw['user'].get('country', None),
+ age=range(
self.raw['user']['age']['min'],
self.raw['user']['age']['max'] + 1 if 'max' in self.raw['user']['age'] else 100
) if 'age' in self.raw['user'] else None,
- oauth_token = self.User.OAuthToken(
- token = self.raw['oauth_token'],
- issued_at = datetime.fromtimestamp(self.raw['issued_at']),
- expires_at = datetime.fromtimestamp(self.raw['expires']) if self.raw['expires'] > 0 else None
+ oauth_token=self.User.OAuthToken(
+ token=self.raw['oauth_token'],
+ issued_at=datetime.fromtimestamp(self.raw['issued_at']),
+ expires_at=datetime.fromtimestamp(self.raw['expires']) if self.raw['expires'] > 0 else None
) if 'oauth_token' in self.raw else None,
)
@@ -149,7 +148,11 @@ def generate(self):
json.dumps(payload, separators=(',', ':'))
)
- encoded_signature = base64.urlsafe_b64encode(hmac.new(self.application_secret_key, encoded_payload, hashlib.sha256).digest())
+ encoded_signature = base64.urlsafe_b64encode(hmac.new(
+ self.application_secret_key,
+ encoded_payload,
+ hashlib.sha256
+ ).digest())
return '%(signature)s.%(payload)s' % {
'signature': encoded_signature,
View
1 facepy/test.py
@@ -1,5 +1,6 @@
from facepy import GraphAPI
+
class User(object):
"""Instances of the User class represent Facebook test users."""
View
27 facepy/utils.py
@@ -1,7 +1,8 @@
-from urlparse import parse_qs
from datetime import datetime, timedelta
+from urlparse import parse_qs
+
+from facepy.graph_api import GraphAPI
-from .graph_api import GraphAPI
def get_extended_access_token(access_token, application_id, application_secret_key):
"""
@@ -16,20 +17,22 @@ def get_extended_access_token(access_token, application_id, application_secret_k
"""
graph = GraphAPI()
- response = graph.get('oauth/access_token',
- client_id = application_id,
- client_secret = application_secret_key,
- grant_type = 'fb_exchange_token',
- fb_exchange_token = access_token
+ response = graph.get(
+ path='oauth/access_token',
+ client_id=application_id,
+ client_secret=application_secret_key,
+ grant_type='fb_exchange_token',
+ fb_exchange_token=access_token
)
components = parse_qs(response)
token = components['access_token'][0]
- expires_at = datetime.now() + timedelta(seconds = int(components['expires'][0]))
+ expires_at = datetime.now() + timedelta(seconds=int(components['expires'][0]))
return token, expires_at
+
def get_application_access_token(application_id, application_secret_key):
"""
Get an OAuth access token for the given application.
@@ -40,10 +43,10 @@ def get_application_access_token(application_id, application_secret_key):
graph = GraphAPI()
response = graph.get(
- path = 'oauth/access_token',
- client_id = application_id,
- client_secret = application_secret_key,
- grant_type = 'client_credentials'
+ path='oauth/access_token',
+ client_id=application_id,
+ client_secret=application_secret_key,
+ grant_type='client_credentials'
)
data = parse_qs(response)
View
22 setup.py
@@ -10,16 +10,16 @@
execfile('facepy/version.py')
setup(
- name = 'facepy',
- version = __version__,
- description = 'Facepy makes it really easy to interact with Facebook\'s Graph API',
- long_description = readme + '\n\n' + history,
- author = 'Johannes Gorset',
- author_email = 'jgorset@gmail.com',
- url = 'http://github.com/jgorset/facepy',
- packages = ['facepy'],
- install_requires = ['requests >=0.8'],
- classifiers = [
+ name='facepy',
+ version=__version__, # flake8: noqa
+ description='Facepy makes it really easy to interact with Facebook\'s Graph API',
+ long_description=readme + '\n\n' + history,
+ author='Johannes Gorset',
+ author_email='jgorset@gmail.com',
+ url='http://github.com/jgorset/facepy',
+ packages=['facepy'],
+ install_requires=['requests >=0.8'],
+ classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
@@ -28,5 +28,5 @@
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7'
],
- zip_safe = False
+ zip_safe=False
)
View
8 tests/test_exceptions.py
@@ -1,29 +1,33 @@
"""Tests for the ``exceptions`` module."""
+import cPickle
+
from nose.tools import *
from facepy import *
-from facepy.graph_api import GraphAPI
-import cPickle
+
def test_facepy_error():
try:
raise FacepyError('<message>')
except FacepyError as exception:
assert exception.message == '<message>'
+
def test_facebookerror_can_be_pickled():
try:
raise GraphAPI.FacebookError('<message>', '<code>')
except FacepyError as exception:
cPickle.dumps(exception)
+
def test_oautherror_can_be_pickled():
try:
raise GraphAPI.OAuthError('<message>', '<code>')
except FacepyError as exception:
cPickle.dumps(exception)
+
def test_httperror_can_be_pickled():
try:
raise GraphAPI.HTTPError('<message>')
View
148 tests/test_graph_api.py
@@ -1,23 +1,27 @@
"""Tests for the ``graph_api`` module."""
-import random
import json
-from mock import patch, call, Mock as mock, MagicMock
+
from nose.tools import *
+from mock import patch, MagicMock
from requests.exceptions import ConnectionError
from facepy import GraphAPI
+
patch = patch('requests.session')
+
def mock():
global mock_request
mock_request = patch.start()().request
+
def unmock():
patch.stop()
+
@with_setup(mock, unmock)
def test_get():
graph = GraphAPI('<access token>')
@@ -33,13 +37,16 @@ def test_get():
graph.get('me')
- mock_request.assert_called_with('GET', 'https://graph.facebook.com/me',
- allow_redirects = True,
- params = {
- 'access_token': '<access token>'
+ mock_request.assert_called_with(
+ 'GET',
+ 'https://graph.facebook.com/me',
+ allow_redirects=True,
+ params={
+ 'access_token': '<access token>'
}
)
+
@with_setup(mock, unmock)
def test_get_with_fields():
graph = GraphAPI('<access token>')
@@ -52,24 +59,29 @@ def test_get_with_fields():
graph.get('me', fields=['id', 'first_name', 'last_name'])
- mock_request.assert_called_with('GET', 'https://graph.facebook.com/me',
- allow_redirects = True,
- params = {
+ mock_request.assert_called_with(
+ 'GET',
+ 'https://graph.facebook.com/me',
+ allow_redirects=True,
+ params={
'access_token': '<access token>',
'fields': 'id,first_name,last_name'
}
)
graph.get('me', fields=('id', 'first_name', 'last_name'))
- mock_request.assert_called_with('GET', 'https://graph.facebook.com/me',
- allow_redirects = True,
- params = {
+ mock_request.assert_called_with(
+ 'GET',
+ 'https://graph.facebook.com/me',
+ allow_redirects=True,
+ params={
'access_token': '<access token>',
'fields': 'id,first_name,last_name'
}
)
+
@with_setup(mock, unmock)
def test_forbidden_get():
graph = GraphAPI('<access token>')
@@ -78,6 +90,7 @@ def test_forbidden_get():
assert_raises(GraphAPI.FacebookError, graph.get, 'me')
+
@with_setup(mock, unmock)
def test_paged_get():
graph = GraphAPI('<access token>')
@@ -121,9 +134,7 @@ def test_paged_get():
def side_effect(*args, **kwargs):
response = responses.pop(0)
- return MagicMock(
- content = json.dumps(response)
- )
+ return MagicMock(content=json.dumps(response))
mock_request.side_effect = side_effect
@@ -134,6 +145,7 @@ def side_effect(*args, **kwargs):
assert_equal(index, 2)
+
@with_setup(mock, unmock)
def test_pagination_without_paging_next():
graph = GraphAPI('<access token>')
@@ -156,6 +168,7 @@ def test_pagination_without_paging_next():
assert_equal(index, 0)
+
@with_setup(mock, unmock)
def test_get_with_errors():
graph = GraphAPI('<access token>')
@@ -185,6 +198,7 @@ def test_get_with_errors():
assert_raises(GraphAPI.FacebookError, graph.get, 'me')
+
@with_setup(mock, unmock)
def test_fql():
graph = GraphAPI('<access token>')
@@ -203,13 +217,16 @@ def test_fql():
except GraphAPI.FacebookError:
pass
- mock_request.assert_called_with('GET', 'https://graph.facebook.com/fql?q=SELECT+id%2Cname%2Cfirst_name%2Clast_name%2Cusername+FROM+user+WHERE+uid%3Dme%28%29',
- allow_redirects = True,
- params = {
+ mock_request.assert_called_with(
+ 'GET',
+ 'https://graph.facebook.com/fql?q=SELECT+id%2Cname%2Cfirst_name%2Clast_name%2Cusername+FROM+user+WHERE+uid%3Dme%28%29',
+ allow_redirects=True,
+ params={
'access_token': '<access token>'
}
)
+
@with_setup(mock, unmock)
def test_post():
graph = GraphAPI('<access token>')
@@ -219,29 +236,33 @@ def test_post():
})
graph.post(
- path = 'me/feed',
- message = 'He\'s a complicated man. And the only one that understands him is his woman'
+ path='me/feed',
+ message='He\'s a complicated man. And the only one that understands him is his woman'
)
- mock_request.assert_called_with('POST', 'https://graph.facebook.com/me/feed',
- files = {},
- data = {
+ mock_request.assert_called_with(
+ 'POST',
+ 'https://graph.facebook.com/me/feed',
+ files={},
+ data={
'message': 'He\'s a complicated man. And the only one that understands him is his woman',
'access_token': '<access token>'
}
)
+
@with_setup(mock, unmock)
def test_post_with_files():
graph = GraphAPI('<access token>')
mock_request.return_value.content = 'true'
graph.post(
- path = 'me/photos',
- source = open('tests/fixtures/parrot.jpg')
+ path='me/photos',
+ source=open('tests/fixtures/parrot.jpg')
)
+
@with_setup(mock, unmock)
def test_forbidden_post():
graph = GraphAPI('<access token>')
@@ -250,6 +271,7 @@ def test_forbidden_post():
assert_raises(GraphAPI.FacebookError, graph.post, 'me')
+
@with_setup(mock, unmock)
def test_delete():
graph = GraphAPI('<access token>')
@@ -258,13 +280,16 @@ def test_delete():
graph.delete(1)
- mock_request.assert_called_with('DELETE', 'https://graph.facebook.com/1',
- allow_redirects = True,
- params = {
+ mock_request.assert_called_with(
+ 'DELETE',
+ 'https://graph.facebook.com/1',
+ allow_redirects=True,
+ params={
'access_token': '<access token>'
}
)
+
@with_setup(mock, unmock)
def test_forbidden_delete():
graph = GraphAPI('<access token>')
@@ -273,6 +298,7 @@ def test_forbidden_delete():
assert_raises(GraphAPI.FacebookError, graph.delete, 'me')
+
@with_setup(mock, unmock)
def test_search():
graph = GraphAPI('<access token>')
@@ -289,25 +315,29 @@ def test_search():
})
graph.search(
- term = 'shaft quotes',
- type = 'post'
+ term='shaft quotes',
+ type='post'
)
- mock_request.assert_called_with('GET', 'https://graph.facebook.com/search',
- allow_redirects = True,
- params = {
+ mock_request.assert_called_with(
+ 'GET',
+ 'https://graph.facebook.com/search',
+ allow_redirects=True,
+ params={
'q': 'shaft quotes',
'type': 'post',
'access_token': '<access token>'
}
)
+
@with_setup(mock, unmock)
def test_invalid_search():
graph = GraphAPI('<access token>')
assert_raises(ValueError, graph.search, 'shaft', 'movies')
+
@with_setup(mock, unmock)
def test_batch():
graph = GraphAPI('<access token>')
@@ -316,37 +346,40 @@ def test_batch():
{
'code': 200,
'headers': [
- { 'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8' }
+ {'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8'}
],
'body': '{"foo": "bar"}'
}
])
requests = [
- { 'method': 'GET', 'relative_url': 'me/friends' },
- { 'method': 'GET', 'relative_url': 'me/photos' },
- { 'method': 'POST', 'relative_url': 'me/feed', 'body': { 'message': 'Hi me.' } }
+ {'method': 'GET', 'relative_url': 'me/friends'},
+ {'method': 'GET', 'relative_url': 'me/photos'},
+ {'method': 'POST', 'relative_url': 'me/feed', 'body': {'message': 'Hi me.'}}
]
batch = graph.batch(
- requests = requests
+ requests=requests
)
for item in batch:
pass
- mock_request.assert_called_with('POST', 'https://graph.facebook.com/',
- files = {},
- data = {
+ mock_request.assert_called_with(
+ 'POST',
+ 'https://graph.facebook.com/',
+ files={},
+ data={
'batch': json.dumps([
- { 'method': 'GET', 'relative_url': 'me/friends' },
- { 'method': 'GET', 'relative_url': 'me/photos' },
- { 'method': 'POST', 'relative_url': 'me/feed', 'body': 'message=Hi+me.' }
+ {'method': 'GET', 'relative_url': 'me/friends'},
+ {'method': 'GET', 'relative_url': 'me/photos'},
+ {'method': 'POST', 'relative_url': 'me/feed', 'body': 'message=Hi+me.'}
]),
'access_token': '<access token>'
}
)
+
@with_setup(mock, unmock)
def test_batch_with_empty_responses():
graph = GraphAPI('<access token>')
@@ -356,22 +389,23 @@ def test_batch_with_empty_responses():
{
'code': 200,
'headers': [
- { 'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8' }
+ {'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8'}
],
'body': '{"foo": "bar"}'
}
])
requests = [
- { 'method': 'GET', 'relative_url': 'me/friends' },
- { 'method': 'GET', 'relative_url': 'me/photos' }
+ {'method': 'GET', 'relative_url': 'me/friends'},
+ {'method': 'GET', 'relative_url': 'me/photos'}
]
batch = graph.batch(
- requests = requests
+ requests=requests
)
- assert list(batch) == [None, { 'foo': 'bar' }]
+ assert list(batch) == [None, {'foo': 'bar'}]
+
@with_setup(mock, unmock)
def test_batch_with_errors():
@@ -381,22 +415,22 @@ def test_batch_with_errors():
{
'code': 200,
'headers': [
- { 'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8' }
+ {'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8'}
],
'body': '{"foo": "bar"}'
},
{
'code': 500,
'headers': [
- { 'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8' }
+ {'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8'}
],
'body': '{"error_code": 1, "error_msg": "An unknown error occurred"}'
}
])
requests = [
- { 'method': 'GET', 'relative_url': 'me/friends' },
- { 'method': 'GET', 'relative_url': 'me' }
+ {'method': 'GET', 'relative_url': 'me/friends'},
+ {'method': 'GET', 'relative_url': 'me'}
]
batch = graph.batch(requests)
@@ -406,6 +440,7 @@ def test_batch_with_errors():
assert isinstance(responses[0], dict)
assert isinstance(responses[1], Exception)
+
@with_setup(mock, unmock)
def test_batch_error_references_request():
graph = GraphAPI('<access token>')
@@ -414,14 +449,14 @@ def test_batch_error_references_request():
{
'code': 500,
'headers': [
- { 'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8' }
+ {'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8'}
],
'body': '{"error_code": 1, "error_msg": "An unknown error occurred"}'
}
])
requests = [
- { 'method': 'GET', 'relative_url': 'me' }
+ {'method': 'GET', 'relative_url': 'me'}
]
batch = graph.batch(requests)
@@ -430,6 +465,7 @@ def test_batch_error_references_request():
assert_equal(responses[0].request, requests[0])
+
@with_setup(mock, unmock)
def test_oauth_error():
graph = GraphAPI('<access token>')
@@ -444,6 +480,7 @@ def test_oauth_error():
assert_raises(GraphAPI.OAuthError, graph.get, 'me')
+
@with_setup(mock, unmock)
def test_query_transport_error():
graph = GraphAPI('<access token>')
@@ -452,6 +489,7 @@ def test_query_transport_error():
assert_raises(GraphAPI.HTTPError, graph.get, 'me')
+
@with_setup(mock, unmock)
def test_retry():
graph = GraphAPI('<access token>')
View
71 tests/test_signed_request.py
@@ -1,11 +1,12 @@
"""Tests for the ``signed_request`` module."""
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta
from nose.tools import *
from facepy import SignedRequest
+
TEST_ACCESS_TOKEN = '181259711925270|1570a553ad6605705d1b7a5f.1-499729129|8XqMRhCWDKtpG-i_zRkHBDSsqqk'
TEST_SIGNED_REQUEST = u'mnrG8Wc9CH_rh-GCqq97GFAPOh6AY7cMO8IYVKb6Pa4.eyJhbGdvcml0aG0iOi' \
@@ -17,10 +18,11 @@
TEST_FACEBOOK_APPLICATION_SECRET_KEY = '214e4cb484c28c35f18a70a3d735999b'
+
def test_parse_signed_request():
signed_request = SignedRequest.parse(
- signed_request = TEST_SIGNED_REQUEST,
- application_secret_key = TEST_FACEBOOK_APPLICATION_SECRET_KEY
+ signed_request=TEST_SIGNED_REQUEST,
+ application_secret_key=TEST_FACEBOOK_APPLICATION_SECRET_KEY
)
assert signed_request == {
@@ -31,26 +33,30 @@ def test_parse_signed_request():
'user': {
'locale': 'en_US',
'country': 'no',
- 'age': { 'min': 21 }
+ 'age': {'min': 21}
},
'issued_at': 1306179904
}
+
def test_parse_invalid_signed_request():
- assert_raises(SignedRequest.Error, SignedRequest,
- signed_request = "<invalid signed request>",
- application_secret_key = TEST_FACEBOOK_APPLICATION_SECRET_KEY
+ assert_raises(
+ SignedRequest.Error,
+ SignedRequest,
+ signed_request="<invalid signed request>",
+ application_secret_key=TEST_FACEBOOK_APPLICATION_SECRET_KEY
)
+
def test_initialize_signed_request():
signed_request = SignedRequest(
- signed_request = TEST_SIGNED_REQUEST,
- application_secret_key = TEST_FACEBOOK_APPLICATION_SECRET_KEY
+ signed_request=TEST_SIGNED_REQUEST,
+ application_secret_key=TEST_FACEBOOK_APPLICATION_SECRET_KEY
)
assert signed_request.user.id == '499729129'
assert signed_request.user.oauth_token.token == TEST_ACCESS_TOKEN
- assert signed_request.user.oauth_token.expires_at == None
+ assert signed_request.user.oauth_token.expires_at is None
assert signed_request.raw == {
'user_id': '499729129',
@@ -60,69 +66,74 @@ def test_initialize_signed_request():
'user': {
'locale': 'en_US',
'country': 'no',
- 'age': { 'min': 21 }
+ 'age': {'min': 21}
},
'issued_at': 1306179904
}
+
def test_signed_request_page_url():
page = SignedRequest.Page(id=1)
assert page.url == 'http://facebook.com/1'
+
def test_signed_request_user_profile_url():
user = SignedRequest.User(id=1)
assert user.profile_url == 'http://facebook.com/1'
+
def test_signed_request_user_has_authorized_application():
oauth_token = SignedRequest.User.OAuthToken(
- token = '<token>',
- issued_at = datetime.now(),
- expires_at = None
+ token='<token>',
+ issued_at=datetime.now(),
+ expires_at=None
)
user = SignedRequest.User(id=1, oauth_token=oauth_token)
- assert user.has_authorized_application == True
+ assert user.has_authorized_application is True
user = SignedRequest.User(id=1, oauth_token=None)
- assert user.has_authorized_application == False
+ assert user.has_authorized_application is False
+
def test_signed_request_user_oauth_token_has_expired():
today = datetime.now()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)
oauth_token = SignedRequest.User.OAuthToken(
- token = '<token>',
- issued_at = yesterday,
- expires_at = None,
+ token='<token>',
+ issued_at=yesterday,
+ expires_at=None,
)
- assert oauth_token.has_expired == False
+ assert oauth_token.has_expired is False
oauth_token = SignedRequest.User.OAuthToken(
- token = '<token>',
- issued_at = yesterday,
- expires_at = tomorrow
+ token='<token>',
+ issued_at=yesterday,
+ expires_at=tomorrow
)
- assert oauth_token.has_expired == False
+ assert oauth_token.has_expired is False
oauth_token = SignedRequest.User.OAuthToken(
- token = '<token>',
- issued_at = yesterday,
- expires_at = yesterday
+ token='<token>',
+ issued_at=yesterday,
+ expires_at=yesterday
)
- assert oauth_token.has_expired == True
+ assert oauth_token.has_expired is True
+
def test_generate_signed_request():
signed_request = SignedRequest(
- signed_request = TEST_SIGNED_REQUEST,
- application_secret_key = TEST_FACEBOOK_APPLICATION_SECRET_KEY
+ signed_request=TEST_SIGNED_REQUEST,
+ application_secret_key=TEST_FACEBOOK_APPLICATION_SECRET_KEY
)
signed_request = signed_request.generate()
View
41 tests/test_test.py
@@ -1,10 +1,11 @@
"""Tests for the ``test`` module."""
-from mock import patch, DEFAULT
from nose.tools import *
+from mock import patch, DEFAULT
from facepy.test import *
+
@patch('facepy.GraphAPI.post')
def test_create_user(post):
"""Test creating a new test user."""
@@ -16,20 +17,23 @@ def test_create_user(post):
'password': '<password>'
}
- post.return_value = response
+ post.return_value = response
- user = User.create('<application id>', '<access token>',
- permissions = ['read_stream'],
- locale = 'en_US',
- name = 'John Doe',
- installed = True
+ user = User.create(
+ '<application id>',
+ '<access token>',
+ permissions=['read_stream'],
+ locale='en_US',
+ name='John Doe',
+ installed=True
)
- post.assert_called_with('<application id>/accounts/test-users',
- permissions = ['read_stream'],
- locale = 'en_US',
- name = 'John Doe',
- installed = True
+ post.assert_called_with(
+ '<application id>/accounts/test-users',
+ permissions=['read_stream'],
+ locale='en_US',
+ name='John Doe',
+ installed=True
)
assert_equal(user.id, response['id'])
@@ -58,16 +62,17 @@ def test_context_manager(post, delete):
assert_equal(user.password, post.return_value['password'])
delete.assert_called_with(post.return_value['id'])
-
+
+
@patch('facepy.GraphAPI.delete')
def test_delete_user(delete):
"""Test deleting a test user."""
user = User(
- id = '<id>',
- access_token = '<access token>',
- login_url = '<login url>',
- email = '<email>',
- password = '<password'
+ id='<id>',
+ access_token='<access token>',
+ login_url='<login url>',
+ email='<email>',
+ password='<password'
)
user.delete()
View
37 tests/test_utils.py
@@ -1,31 +1,40 @@
"""Tests for the ``utils`` module."""
from datetime import datetime
-
-from mock import patch
from nose.tools import *
+from mock import patch
from facepy import *
+
patch = patch('requests.session')
+
def mock():
global mock_request
mock_request = patch.start()().request
+
def unmock():
patch.stop()
+
@with_setup(mock, unmock)
def test_get_extended_access_token():
mock_request.return_value.content = 'access_token=<extended access token>&expires=5183994'
- access_token, expires_at = get_extended_access_token('<access token>', '<application id>', '<application secret key>')
+ access_token, expires_at = get_extended_access_token(
+ '<access token>',
+ '<application id>',
+ '<application secret key>'
+ )
- mock_request.assert_called_with('GET', 'https://graph.facebook.com/oauth/access_token',
- allow_redirects = True,
- params = {
+ mock_request.assert_called_with(
+ 'GET',
+ 'https://graph.facebook.com/oauth/access_token',
+ allow_redirects=True,
+ params={
'client_id': '<application id>',
'client_secret': '<application secret key>',
'grant_type': 'fb_exchange_token',
@@ -36,15 +45,18 @@ def test_get_extended_access_token():
assert_equal(access_token, '<extended access token>')
assert isinstance(expires_at, datetime)
+
@with_setup(mock, unmock)
def test_get_application_access_token():
mock_request.return_value.content = 'access_token=...'
access_token = get_application_access_token('<application id>', '<application secret key>')
- mock_request.assert_called_with('GET', 'https://graph.facebook.com/oauth/access_token',
- allow_redirects = True,
- params = {
+ mock_request.assert_called_with(
+ 'GET',
+ 'https://graph.facebook.com/oauth/access_token',
+ allow_redirects=True,
+ params={
'client_id': '<application id>',
'client_secret': '<application secret key>',
'grant_type': 'client_credentials'
@@ -53,11 +65,14 @@ def test_get_application_access_token():
assert_equal(access_token, '...')
+
@with_setup(mock, unmock)
def test_get_application_access_token_raises_error():
mock_request.return_value.content = 'An unknown error occurred'
assert_raises(
- GraphAPI.FacebookError, get_application_access_token,
- '<application id>', '<application secret key>'
+ GraphAPI.FacebookError,
+ get_application_access_token,
+ '<application id>',
+ '<application secret key>'
)

0 comments on commit 4fd9713

Please sign in to comment.