Skip to content

Commit

Permalink
Merge pull request #48 from namaggarwal/ver-2.1.0
Browse files Browse the repository at this point in the history
Ver 2.1.0
  • Loading branch information
namaggarwal authored Jul 2, 2020
2 parents fa52ed0 + f4d1269 commit cba9b51
Show file tree
Hide file tree
Showing 12 changed files with 300 additions and 6 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/end_to_end_test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: End to End Tests

on:
pull_request:
types: [opened, reopened]
types: [opened, reopened, synchronize]

jobs:
build:
Expand Down
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ This is the python sdk for Splitwise APIs. Pull requests and bug reports are wel

## Latest Version

The latest version of splitwise SDK is Splitwise-2.0.2
The latest version of splitwise SDK is Splitwise-2.1.0

## Docs

Expand Down Expand Up @@ -113,6 +113,23 @@ id = 7123
user = sObj.getUser(id)
```

### Update User

You can use ```updateUser(user)``` to update the user. It takes in a partial `CurrentUser` object
with atleast `id` set. It returns a ```CurrentUser``` object.
Note that you can update anything for your user and `first_name`, `last_name` and `email` for
any acquaintances who has not created account yet.

```python
sObj = Splitwise(Config.consumer_key,Config.consumer_secret)
sObj.setAccessToken(session['access_token'])
user = User()
user.setId(10)
user.setFirstName("naman")
updated_user, error = sObj.updateUser(user)
print(updated_user.getFirstName())
```

### Get Friends

You can use ```getFriends()``` to get all the friends of the current user along with the balances. It returns a list of ```Friend``` objects.
Expand Down Expand Up @@ -293,6 +310,19 @@ success, errors = sObj.deleteGroup(4456)
print(success)
```

### Delete expense
You can use ```deleteExpense(expense_id)``` to delete an existing expense.

```python

sObj = Splitwise(Config.consumer_key,Config.consumer_secret)
sObj.setAccessToken(session['access_token'])

success, errors = sObj.deleteExpense(4456)

print(success)
```


## Objects

Expand Down
2 changes: 2 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,10 @@ splitwise SDK supports

- :ref:`Fetching current user info <exCurrentUser>`
- :ref:`Fetching user's friends <exFriends>`
- :ref:`Updating a user <exUpdateUser>`
- :ref:`Fetching user's expenses <exExpenses>`
- :ref:`Creating a new expense <exNExpense>`
- :ref:`Delete an expense <exDExpense>`
- :ref:`Fetching user's groups <exGroups>`
- :ref:`Creating a new group <exNGroup>`
- :ref:`Adding user to group <exAGroup>`
Expand Down
22 changes: 22 additions & 0 deletions docs/user/example.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,19 @@ Fetching user's friends
>>> print(friends[0].getFirstName())
Atul

.. _exUpdateUser:

Updating a user
^^^^^^^^^^^^^^^
>>> u = User()
>>> u.setId(10)
>>> u.setFirstName("Naman")
>>> updatedU, error = s.updateUser(u)
>>> print(updatedU.getFirstName())
10
>>> print(u.getFirstName())
Naman

.. _exExpenses:

Fetching user's expenses
Expand Down Expand Up @@ -123,6 +136,15 @@ Creating a new expense
>>> print(nExpense.getId())
123332

.. _exDExpense:

Delete an Expense
^^^^^^^^^^^^^^^^^

>>> success, errors = s.deleteExpense(123445)
>>> print(success)
True


UnAuthenticated APIs
--------------------
Expand Down
4 changes: 2 additions & 2 deletions docs/user/install.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ This covers the installation of splitwise
Using pip
---------

To install splitwise, simply run this simple command in your terminal of choice:
To install splitwise, simply run this simple command in your terminal of choice::

$ pip install splitwise
$ pip install splitwise

Get the source code
-------------------
Expand Down
38 changes: 38 additions & 0 deletions e2e-tests/test_expense.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import unittest
import os
from splitwise import Splitwise
from splitwise.expense import Expense
from splitwise.exception import SplitwiseUnauthorizedException


class ExpenseTestCase(unittest.TestCase):

def setUp(self):
consumer_key = os.environ['CONSUMER_KEY']
consumer_secret = os.environ['CONSUMER_SECRET']
oauth_token = os.environ['OAUTH_TOKEN']
oauth_token_secret = os.environ['OAUTH_TOKEN_SECRET']

self.sObj = Splitwise(consumer_key, consumer_secret)
self.sObj.setAccessToken({'oauth_token': oauth_token, 'oauth_token_secret': oauth_token_secret})

def test_expense_flow(self):
expense = Expense()
expense.setDescription("End2EndTest")
expense.setCost('10')
expense.setGroupId(19571167)
expense.setSplitEqually()
# create expense
expense, error = self.sObj.createExpense(expense)
self.assertIsNone(error)
self.assertIsNotNone(expense.getId())
# delete expense
success, error = self.sObj.deleteExpense(expense.getId())
self.assertIsNone(error)
self.assertTrue(success)

def test_expense_invalidkeys_fail(self):
sObj = Splitwise('consumerkey', 'consumersecret', {"oauth_token": "sdsd", "oauth_token_secret": "sdsdd"})
expense = Expense()
with self.assertRaises(SplitwiseUnauthorizedException):
sObj.createExpense(expense)
78 changes: 78 additions & 0 deletions splitwise/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ class Splitwise(object):
"api/"+SPLITWISE_VERSION+"/get_current_user"
GET_USER_URL = SPLITWISE_BASE_URL + \
"api/"+SPLITWISE_VERSION+"/get_user"
UPDATE_USER_URL = SPLITWISE_BASE_URL + \
"api/"+SPLITWISE_VERSION+"/update_user"
GET_FRIENDS_URL = SPLITWISE_BASE_URL + \
"api/"+SPLITWISE_VERSION+"/get_friends"
GET_GROUPS_URL = SPLITWISE_BASE_URL + \
Expand All @@ -86,6 +88,8 @@ class Splitwise(object):
"api/"+SPLITWISE_VERSION+"/get_expense"
CREATE_EXPENSE_URL = SPLITWISE_BASE_URL + \
"api/"+SPLITWISE_VERSION+"/create_expense"
DELETE_EXPENSE_URL = SPLITWISE_BASE_URL + \
"api/"+SPLITWISE_VERSION+"/delete_expense"
CREATE_GROUP_URL = SPLITWISE_BASE_URL + \
"api/"+SPLITWISE_VERSION+"/create_group"
ADD_USER_TO_GROUP_URL = SPLITWISE_BASE_URL + \
Expand Down Expand Up @@ -309,6 +313,46 @@ def getUser(self, id):
content = json.loads(content)
return User(content["user"])

def updateUser(self, user):
""" Updates the user.
Args:
:obj:`splitwise.user.CurrentUser`: User object with atleast id set
Returns:
tuple: tuple containing:
user(:obj:`splitwise.user.CurrentUser`): Object with User detail
errors(:obj:`splitwise.error.SplitwiseError`): Object representing errors
"""

if user.getId() is None:
raise SplitwiseBadRequestException("User ID is required to update user")

user_data = user.__dict__

try:
content = self.__makeRequest(Splitwise.UPDATE_USER_URL, 'POST', user_data)
except SplitwiseNotAllowedException as e:
e.setMessage("You are not allowed to access user with id %d" % user.getId())
raise
except SplitwiseNotFoundException as e:
e.setMessage("User with id %d does not exist" % user.getId())
raise
content = json.loads(content)

user = None
errors = None
if "user" in content:
if content["user"] is not None:
user = CurrentUser(content["user"])

if "errors" in content:
if len(content['errors']) != 0:
errors = SplitwiseError(content["errors"])

return user, errors

def getFriends(self):
""" Gets the list of users friends.
Expand Down Expand Up @@ -509,6 +553,40 @@ def createExpense(self, expense):

return expense, errors

def deleteExpense(self, id):
""" Deletes the expense with given id.
Args:
id(long): ID of the expense to be deleted.
Returns:
tuple: tuple containing:
success(bool): True if group deleted, False otherwise
errors(:obj:`splitwise.error.SplitwiseError`): Object representing errors
"""
errors = None
success = False
try:
content = self.__makeRequest(
Splitwise.DELETE_EXPENSE_URL+"/"+str(id), "POST")
except SplitwiseNotAllowedException as e:
e.setMessage("You are not allowed to access expense with id %d" % id)
raise
except SplitwiseNotFoundException as e:
e.setMessage("Expense with id %d does not exist" % id)
raise

content = json.loads(content)
if 'success' in content:
success = content["success"]

if 'errors' in content:
if len(content['errors']) != 0:
errors = SplitwiseError(content['errors'])

return success, errors

def createGroup(self, group):
""" Creates a new Group.
Expand Down
2 changes: 1 addition & 1 deletion splitwise/__version__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
__title__ = 'splitwise'
__description__ = 'Splitwise Python SDK'
__version__ = '2.0.2'
__version__ = '2.1.0'
__url__ = 'https://github.com/namaggarwal/splitwise'
__download_url__ = 'https://github.com/namaggarwal/splitwise/tarball/v'+__version__
__build__ = 0x022400
Expand Down
2 changes: 1 addition & 1 deletion splitwise/expense.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,7 @@ def addUser(self, user):
self.users.append(user)

def setSplitEqually(self, should_split=True):
""" Set if expense should be split equally
""" Set if expense should be split equally. Note that group_id should be set to use this
Args:
should_split(bool, optional): Should the expense be split equally. Default value is True
Expand Down
3 changes: 3 additions & 0 deletions splitwise/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ def setId(self, id):
"""
self.id = id

def __getattr__(self, item):
return None


class CurrentUser(User):
""" Represents the current logged in user.
Expand Down
52 changes: 52 additions & 0 deletions tests/test_deleteExpense.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from splitwise import Splitwise
from splitwise.exception import SplitwiseNotFoundException, SplitwiseNotAllowedException
import unittest
try:
from unittest.mock import patch
except ImportError: # Python 2
from mock import patch


@patch('splitwise.Splitwise._Splitwise__makeRequest')
class DeleteExpenseTestCase(unittest.TestCase):

def setUp(self):
self.sObj = Splitwise('consumerkey', 'consumersecret')

def test_deleteExpense_success(self, mockMakeRequest):
mockMakeRequest.return_value = '{"success":true}' # noqa: E501
success, errors = self.sObj.deleteExpense(19481273)
mockMakeRequest.assert_called_with(
"https://secure.splitwise.com/api/v3.0/delete_expense/19481273", "POST")
self.assertTrue(success)
self.assertIsNone(errors)

def test_deleteExpense_error(self, mockMakeRequest):
mockMakeRequest.return_value = '{"success":false, "errors": {"base": ["some error occured"]}}' # noqa: E501
success, errors = self.sObj.deleteExpense(19481273)
mockMakeRequest.assert_called_with(
"https://secure.splitwise.com/api/v3.0/delete_expense/19481273", "POST")
self.assertFalse(success)
self.assertIsNotNone(errors)

def test_deleteExpense_notallowed_exception(self, mockMakeRequest):
mockMakeRequest.side_effect = SplitwiseNotAllowedException(
"message"
)

with self.assertRaises(SplitwiseNotAllowedException):
self.sObj.deleteExpense(19481273)

mockMakeRequest.assert_called_with(
"https://secure.splitwise.com/api/v3.0/delete_expense/19481273", "POST")

def test_deleteExpense_notfound_exception(self, mockMakeRequest):
mockMakeRequest.side_effect = SplitwiseNotFoundException(
"message"
)

with self.assertRaises(SplitwiseNotFoundException):
self.sObj.deleteExpense(19481273)

mockMakeRequest.assert_called_with(
"https://secure.splitwise.com/api/v3.0/delete_expense/19481273", "POST")
Loading

0 comments on commit cba9b51

Please sign in to comment.