Skip to content

Commit

Permalink
Split Authorization class into it's own module.
Browse files Browse the repository at this point in the history
Because of this, create tests for it and documentation.
  • Loading branch information
sigmavirus24 committed Oct 3, 2012
1 parent c2bf97f commit 8dc24b2
Show file tree
Hide file tree
Showing 7 changed files with 190 additions and 85 deletions.
11 changes: 11 additions & 0 deletions docs/auths.rst
@@ -0,0 +1,11 @@
.. module:: github3
.. module:: github3.auths

Authorization
=============

This part of the documentation covers the
:class:`Authorization <Authorization>` object.

.. autoclass:: Authorization
:inherited-members:
5 changes: 0 additions & 5 deletions docs/github.rst
Expand Up @@ -22,10 +22,5 @@ GitHub Object
.. autoclass:: GitHub
:inherited-members:

------

.. autoclass:: Authorization
:inherited-members:

.. links
.. _here: examples/githubex.html
7 changes: 5 additions & 2 deletions docs/index.rst
Expand Up @@ -62,6 +62,7 @@ Modules
:maxdepth: 1

api
auths
events
gists
git
Expand Down Expand Up @@ -205,7 +206,7 @@ To run the tests as they would be run by Travis CI::

CI=true ./unittests.py

To test functions that require proper authorization::
To test functions that require proper authentication::

./unittests.py

Expand All @@ -214,7 +215,9 @@ The latter will prompt you for your username and password, e.g.::
[ sigma: ~/sandbox/github3.py ] ./unittests.py
Enter GitHub username: sigmavirus24
Password for sigmavirus24:
=== Starting unittest suite ===

This will generally fail until we can generalize the authenticated tests via a
config file.


Contact
Expand Down
88 changes: 88 additions & 0 deletions github3/auths.py
@@ -0,0 +1,88 @@
"""
github3.auths
=============
This module contains the Authorization object.
"""

from github3.models import GitHubCore
from json import dumps


class Authorization(GitHubCore):
"""The :class:`Authorization <Authorization>` object."""
def __init__(self, auth, session):
super(Authorization, self).__init__(auth, session)
#: Details about the application (name, url)
self.app = auth.get('app', {})
#: Returns the Authorization token
self.token = auth.get('token', '')
#: App name
self.name = auth.app.get('name', '')
#: URL about the note
self.note_url = auth.get('note_url', '')
#: Note about the authorization
self.note = auth.get('note', '')
#: List of scopes this applies to
self.scopes = auth.get('scopes', [])
#: Unique id of the authorization
self.id = auth.get('id', 0)
self._api = self._build_url('authorizations', str(self.id))
#: datetime object representing when the authorization was created.
self.created_at = None
if auth.get('created_at'):
self.created_at = self._strptime(auth.get('created_at'))
#: datetime object representing when the authorization was created.
self.updated_at = None
if auth.get('updated_at'):
self.updated_at = self._strptime(auth.get('updated_at'))

def __repr__(self):
return '<Authorization [{0}]>'.format(self.name)

def _update_(self, auth):
self.__init__(auth, self._session)

def delete(self):
"""delete this authorization"""
return self._boolean(self._delete(self._api), 204, 404)

def update(self, scopes=[], add_scopes=[], rm_scopes=[], note='',
note_url=''):
"""Update this authorization.
:param scopes: (optional), replaces the authorization scopes with these
:type scopes: list
:param add_scopes: (optional), scopes to be added
:type add_scopes: list
:param rm_scopes: (optional), scopes to be removed
:type rm_scopes: list
:param note: (optional), new note about authorization
:type note: str
:param note_url: (optional), new note URL about this authorization
:type note_url: str
:returns: bool
"""
success = False
if scopes:
d = dumps({'scopes': scopes})
json = self._json(self._get(self._api, data=d), 200)
self._update_(json)
success = True
if add_scopes:
d = dumps({'add_scopes': add_scopes})
json = self._json(self._get(self._api, data=d), 200)
self._update_(json)
success = True
if rm_scopes:
d = dumps({'remove_scopes': rm_scopes})
json = self._json(self._get(self._api, data=d), 200)
self._update_(json)
success = True
if note or note_url:
d = dumps({'note': note, 'note_url': note_url})
json = self._json(self._get(self._api, data=d), 200)
self._update_(json)
success = True
return success
80 changes: 3 additions & 77 deletions github3/github.py
Expand Up @@ -8,6 +8,7 @@

from requests import session
from json import dumps
from github3.auths import Authorization
from github3.events import Event
from github3.gists import Gist
from github3.issues import Issue, issue_params
Expand Down Expand Up @@ -677,7 +678,8 @@ def list_repos(self, login=None, type='', sort='', direction=''):
json = self._json(self._get(url, params=params), 200)
return [Repository(repo, self) for repo in json]

def iter_repos(self, login=None, type='', sort='', direction='', number=-1):
def iter_repos(self, login=None, type='', sort='', direction='',
number=-1):
"""List public repositories for the specified ``login`` or all
repositories for the authenticated user if ``login`` is not
provided.
Expand Down Expand Up @@ -1039,79 +1041,3 @@ def watch(self, login, repo):
def unwatch(self, login, repo):
"""DEPRECATED: Use unsubscribe/unstar instead."""
raise DeprecationWarning('Use unsubscribe/unstar instead.')


class Authorization(GitHubCore):
"""The :class:`Authorization <Authorization>` object."""
def __init__(self, auth, session):
super(Authorization, self).__init__(auth, session)
#: Details about the application
self.app = auth.get('app', {})
#: Returns the Authorization token
self.token = auth.get('token', '')
#: URL about the note
self.note_url = auth.get('note_url', '')
#: Note about the authorization
self.note = auth.get('note', '')
#: List of scopes this applies to
self.scopes = auth.get('scopes', [])
#: Unique id of the authorization
self.id = auth.get('id', 0)
self._api = self._build_url('authorizations', str(self.id))
#: datetime object representing when the authorization was created.
self.created_at = None
if auth.get('created_at'):
self.created_at = self._strptime(auth.get('created_at'))
#: datetime object representing when the authorization was created.
self.updated_at = None
if auth.get('updated_at'):
self.updated_at = self._strptime(auth.get('updated_at'))

def __repr__(self):
return '<Authorization [{0}]>'.format(self.app.get('name', ''))

def _update_(self, auth):
self.__init__(auth, self._session)

def delete(self):
"""delete this authorization"""
return self._boolean(self._delete(self._api), 204, 404)

def update(self, scopes=[], add_scopes=[], rm_scopes=[], note='',
note_url=''):
"""Update this authorization.
:param scopes: (optional), replaces the authorization scopes with these
:type scopes: list
:param add_scopes: (optional), scopes to be added
:type add_scopes: list
:param rm_scopes: (optional), scopes to be removed
:type rm_scopes: list
:param note: (optional), new note about authorization
:type note: str
:param note_url: (optional), new note URL about this authorization
:type note_url: str
:returns: bool
"""
success = False
if scopes:
d = dumps({'scopes': scopes})
json = self._json(self._get(self._api, data=d), 200)
self._update_(json)
success = True
if add_scopes:
d = dumps({'add_scopes': add_scopes})
json = self._json(self._get(self._api, data=d), 200)
self._update_(json)
success = True
if rm_scopes:
d = dumps({'remove_scopes': rm_scopes})
json = self._json(self._get(self._api, data=d), 200)
self._update_(json)
success = True
if note or note_url:
d = dumps({'note': note, 'note_url': note_url})
json = self._json(self._get(self._api, data=d), 200)
self._update_(json)
success = True
return success
66 changes: 66 additions & 0 deletions tests/test_auths.py
@@ -0,0 +1,66 @@
from .base import expect, BaseTest
from datetime import datetime
from github3.auths import Authorization


class TestAuthorization(BaseTest):
def __init__(self, methodName='runTest'):
if not self.auth:
json = {'scopes': ['public_repo'],
'url': 'https://api.github.com',
'app': {'url': 'travis-ci.org', 'name': 'Travis'},
'updated_at': '2012-09-28T03:43:11Z',
'id': 0,
'note': None,
'note_url': None,
'token': 'upupdowndownleftrightba',
'created_at': '2012-02-28T01:45:49Z',
}
self.authorization = Authorization(json)
else:
self.authorization = self.g.authorize(self.user, self.pw, [])
self.deleted = False

def test_authorization(self):
expect(self.authorization).isinstance(Authorization)
expect(repr(self.authorization)) != ''

def test_app(self):
expect(self.authorization.app).isinstance(dict)

def test_name(self):
expect(self.authorization.name) == self.authorization.app.get('name',
'')

def test_token(self):
expect(self.authorization.token) != ''

def test_updated_at(self):
expect(self.authorization.updated_at).isinstance(datetime)

def test_created_at(self):
expect(self.authorization.created_at).isinstance(datetime)

def test_note(self):
expect(self.authorization.note) >= ''

def test_note_url(self):
expect(self.authorization.note_url) >= ''

def test_scopes(self):
expect(self.authorization.scopes).isinstance(list)

def test_update(self):
if not self.auth:
return
if self.deleted:
self.authorization = self._g.authorize(None, None, [])
self.authorization.update(['repo', 'repo:status'], ['user'],
['repo:status'], 'https://github.com/sigmavirus24/github3.py')
if self.deleted:
self.authorization.delete()

def test_delelte(self):
if not self.auth:
return
expect(self.authorization.delete()).is_True()
18 changes: 17 additions & 1 deletion tests/test_github.py
Expand Up @@ -2,6 +2,7 @@
from .base import expect, expect_str, BaseTest
from github3.repos import Repository
from github3.events import Event
from github3.auths import Authorization


class TestGitHub(BaseTest):
Expand Down Expand Up @@ -223,10 +224,25 @@ def test_create_repo(self):
r.delete()

def test_authorizations_requires_auth(self):
self.raisesGHE(self.g.list_authorizations)
self.raisesGHE(self.g.authorization, -1)
self.raisesGHE(self.g.authorize, 'foo', 'bar', ['gist', 'user'])

def test_iter_authorizations(self):
self.raisesGHE(self.g.iter_authorizations)

if not self.auth:
return

expect(next(self._g.iter_authorizations())).isinstance(Authorization)

def test_list_authorizations(self):
self.raisesGHE(self.g.list_authorizations)

if not self.auth:
return

expect(self._g.list_authorizations()).list_of(Authorization)

def test_list_emails(self):
self.raisesGHE(self.g.list_emails)

Expand Down

0 comments on commit 8dc24b2

Please sign in to comment.