def test_updateExpense_exception(self, mockMakeRequest): mockMakeRequest.side_effect = Exception( "Invalid response %s. Please check your consumer key and secret." % 404) expense = Expense() expense.id = 1010934284 expense.setCost('10') expense.setDescription("Testing") user1 = ExpenseUser() user1.setId(79774) user1.setPaidShare('10.00') user1.setOwedShare('2.0') user2 = ExpenseUser() user2.setId(281236) user2.setPaidShare('0.00') user2.setOwedShare('8.00') users = [] users.append(user1) users.append(user2) expense.setUsers(users) with self.assertRaises(Exception): expenseRes, errors = self.sObj.updateExpense(expense) mockMakeRequest.assert_called_with( "https://secure.splitwise.com/api/v3.0/update_expense/1010934284", "POST", { 'cost': '10', 'description': 'Testing', 'users__0__user_id': 79774, 'users__0__paid_share': '10.00', 'users__0__owed_share': '2.0', 'users__1__user_id': 281236, 'users__1__paid_share': '0.00', 'users__1__owed_share': '8.00' }, files=None)
def test_updateExpense_missingExpenseId_Exception(self, mockMakeRequest): mockMakeRequest.side_effect = SplitwiseBadRequestException( "Incorrect query parameters sent. Expense Id cannot be null") expense = Expense() expense.setCost('10') expense.setDescription("Testing") user1 = ExpenseUser() user1.setId(79774) user1.setPaidShare('10.00') user1.setOwedShare('2.0') user2 = ExpenseUser() user2.setId(281236) user2.setPaidShare('0.00') user2.setOwedShare('8.00') users = [] users.append(user1) users.append(user2) expense.setUsers(users) with self.assertRaises(SplitwiseBadRequestException): expenseRes, errors = self.sObj.updateExpense(expense)
def test_updateExpense_error(self, mockMakeRequest): mockMakeRequest.return_value = '{"expenses":[],"errors":{"base":["An unknown error occurred. Please try again or contact [email protected] if you experience repeated issues. Sorry for the trouble!"]}}' # noqa: E501 expense = Expense() expense.id = 1010934284 expense.setCost('10') expense.setDescription("Testing") user1 = ExpenseUser() user1.setId(79774) user1.setPaidShare('10.00') user1.setOwedShare('2.0') user2 = ExpenseUser() user2.setId(281236) user2.setPaidShare('0.00') user2.setOwedShare('8.00') users = [] users.append(user1) users.append(user2) expense.setUsers(users) expenseRes, errors = self.sObj.updateExpense(expense) mockMakeRequest.assert_called_with( "https://secure.splitwise.com/api/v3.0/update_expense/1010934284", "POST", { 'cost': '10', 'description': 'Testing', 'users__0__user_id': 79774, 'users__0__paid_share': '10.00', 'users__0__owed_share': '2.0', 'users__1__user_id': 281236, 'users__1__paid_share': '0.00', 'users__1__owed_share': '8.00' }, files=None) self.assertEqual( errors.getErrors(), { 'base': [ 'An unknown error occurred. Please try again or contact [email protected] if you experience repeated issues. \ Sorry for the trouble!' ] })
def pay_bill(self, paying_user_id: int, bill: CoffeeBill) -> str: """ Pay a bill by creating an expense for `paying_user` with respect to logged in splitwise user. :param paying_user_id: Splitwise id of paying user :param bill: CoffeeBill to be payed :return: Splitwise transaction id """ # Convert amount to string amount_str = f"{bill.sum:.2f}" # User which will pay money paying_user = ExpenseUser() paying_user.setId(paying_user_id) paying_user.setOwedShare(amount_str) # User which will receive money my_user = ExpenseUser() my_user.setId(self.user.getId()) my_user.setPaidShare(amount_str) # Create Expense/Transaction expense = Expense() expense.setCost(amount_str) expense.setDescription(f"CoffeeTracker, Rechnung {bill.id}") expense.addUser(paying_user) expense.addUser(my_user) # Execute transaction expense_response, errors = self.s.createExpense(expense) if errors is not None: raise RuntimeError( "An error occured while processing the transaction with Splitwise: " f"{errors.errors}") return f"{expense_response.getId()}"
def test_updateExpense_split_manually_success(self, mockMakeRequest): mockMakeRequest.return_value = '{"expenses":[{"id":1010934284,"group_id":null,"friendship_id":null,"expense_bundle_id":null,"description":"Testing","repeats":false,"repeat_interval":"never","email_reminder":false,"email_reminder_in_advance":-1,"next_repeat":null,"details":null,"comments_count":0,"payment":false,"creation_method":null,"transaction_method":"offline","transaction_confirmed":false,"transaction_id":null,"cost":"10.0","currency_code":"SGD","repayments":[{"from":281236,"to":79774,"amount":"8.0"}],"date":"2020-06-24T08:14:07Z","created_at":"2020-06-24T08:14:07Z","created_by":{"id":79774,"first_name":"Naman","last_name":"Aggarwal","picture":{"medium":"https://splitwise.s3.amazonaws.com/uploads/user/avatar/79774/medium_mypic.jpg"},"custom_picture":true},"updated_at":"2020-06-24T08:14:07Z","updated_by":null,"deleted_at":null,"deleted_by":null,"category":{"id":18,"name":"General"},"receipt":{"large":null,"original":null},"users":[{"user":{"id":79774,"first_name":"Naman","last_name":"Aggarwal","picture":{"medium":"https://splitwise.s3.amazonaws.com/uploads/user/avatar/79774/medium_mypic.jpg"}},"user_id":79774,"paid_share":"10.0","owed_share":"2.0","net_balance":"8.0"},{"user":{"id":281236,"first_name":"Siddharth","last_name":"Goel","picture":{"medium":"https://splitwise.s3.amazonaws.com/uploads/user/avatar/281236/medium_f5fccc37-0a88-4519-9398-59c8c19b92aa.jpeg"}},"user_id":281236,"paid_share":"0.0","owed_share":"8.0","net_balance":"-8.0"}]}],"errors":{}}' # noqa: E501 expense = Expense() expense.id = 1010934284 expense.setCost('10') expense.setDescription("Testing") user1 = ExpenseUser() user1.setId(79774) user1.setPaidShare('10.00') user1.setOwedShare('2.0') user2 = ExpenseUser() user2.setId(281236) user2.setPaidShare('0.00') user2.setOwedShare('8.00') users = [] users.append(user1) users.append(user2) expense.setUsers(users) expenseRes, errors = self.sObj.updateExpense(expense) mockMakeRequest.assert_called_with( "https://secure.splitwise.com/api/v3.0/update_expense/1010934284", "POST", { 'cost': '10', 'description': 'Testing', 'users__0__user_id': 79774, 'users__0__paid_share': '10.00', 'users__0__owed_share': '2.0', 'users__1__user_id': 281236, 'users__1__paid_share': '0.00', 'users__1__owed_share': '8.00' }, files=None) self.assertIsNone(errors) self.assertEqual(expenseRes.getId(), 1010934284) self.assertEqual(expenseRes.getGroupId(), None) self.assertEqual(expenseRes.getFriendshipId(), None) self.assertEqual(expenseRes.getExpenseBundleId(), None) self.assertEqual(expenseRes.getDescription(), "Testing") self.assertEqual(expenseRes.getRepeatInterval(), "never") self.assertEqual(expenseRes.getEmailReminderInAdvance(), -1) self.assertEqual(expenseRes.getNextRepeat(), None) self.assertEqual(expenseRes.getDetails(), None) self.assertEqual(expenseRes.getCommentsCount(), 0) self.assertEqual(expenseRes.getCreationMethod(), None) self.assertEqual(expenseRes.getTransactionMethod(), "offline") self.assertEqual(expenseRes.getTransactionId(), None) self.assertEqual(expenseRes.getCost(), "10.0") self.assertEqual(expenseRes.getCurrencyCode(), "SGD") self.assertEqual(len(expenseRes.getRepayments()), 1) self.assertEqual(expenseRes.getRepayments()[0].getFromUser(), 281236) self.assertEqual(expenseRes.getRepayments()[0].getToUser(), 79774) self.assertEqual(expenseRes.getRepayments()[0].getAmount(), "8.0") self.assertEqual(expenseRes.getDate(), "2020-06-24T08:14:07Z") self.assertEqual(expenseRes.getCreatedAt(), "2020-06-24T08:14:07Z") self.assertEqual(expenseRes.getCreatedBy().getId(), 79774) self.assertEqual(expenseRes.getCreatedBy().getFirstName(), "Naman") self.assertEqual(expenseRes.getCreatedBy().getLastName(), "Aggarwal") self.assertEqual( expenseRes.getCreatedBy().getPicture().getMedium(), "https://splitwise.s3.amazonaws.com/uploads/user/avatar/79774/medium_mypic.jpg" ) self.assertEqual(expenseRes.getUpdatedAt(), "2020-06-24T08:14:07Z") self.assertEqual(expenseRes.getUpdatedBy(), None) self.assertEqual(expenseRes.getDeletedAt(), None) self.assertEqual(expenseRes.getDeletedBy(), None) self.assertEqual(expenseRes.getCategory().getId(), 18) self.assertEqual(expenseRes.getCategory().getName(), "General") self.assertEqual(expenseRes.getReceipt().getLarge(), None) self.assertEqual(expenseRes.getReceipt().getOriginal(), None) self.assertEqual(len(expenseRes.getUsers()), 2) self.assertEqual(expenseRes.getUsers()[0].getId(), 79774) self.assertEqual(expenseRes.getUsers()[0].getFirstName(), "Naman") self.assertEqual(expenseRes.getUsers()[0].getLastName(), "Aggarwal") self.assertEqual( expenseRes.getUsers()[0].getPicture().getMedium(), "https://splitwise.s3.amazonaws.com/uploads/user/avatar/79774/medium_mypic.jpg" ) self.assertEqual(expenseRes.getUsers()[0].getPaidShare(), "10.0") self.assertEqual(expenseRes.getUsers()[0].getOwedShare(), "2.0") self.assertEqual(expenseRes.getUsers()[0].getNetBalance(), "8.0") self.assertEqual(expenseRes.getUsers()[1].getId(), 281236) self.assertEqual(expenseRes.getUsers()[1].getFirstName(), "Siddharth") self.assertEqual(expenseRes.getUsers()[1].getLastName(), "Goel") self.assertEqual( expenseRes.getUsers()[1].getPicture().getMedium(), "https://splitwise.s3.amazonaws.com/uploads/user/avatar/281236/medium_f5fccc37-0a88-4519-9398-59c8c19b92aa.jpeg" ) self.assertEqual(expenseRes.getUsers()[1].getPaidShare(), "0.0") self.assertEqual(expenseRes.getUsers()[1].getOwedShare(), "8.0") self.assertEqual(expenseRes.getUsers()[1].getNetBalance(), "-8.0")
def add_group_expense(exp_data: dict): """ Utility function to add multiple expenses at once. Pass in a dict of user_ids -> amount owed """ try: total = float(exp_data['total']) group_id = exp_data['group_id'] desc = exp_data['desc'] except KeyError: print("total, group_id and desc are required fields in the expense") return expense = Expense() expense.setCost(total) expense.setDescription(desc) expense.setGroupId(group_id) sum = 0 for user_id, details in exp_data['users'].items(): try: amt = float(details["amt"]) except KeyError: print("'amt' is a required field") return except ValueError: print(f"invalid amount {details['amt']}") return user = ExpenseUser() user.setId(user_id) user.setPaidShare(0) user.setOwedShare(amt) sum += amt expense.addUser(user) me = ExpenseUser() me.setId(s.getCurrentUser().getId()) me.setPaidShare(total) me.setOwedShare(total - sum) expense.addUser(me) if DRY_RUN: print("--- dry run ---") print_expense_details(expense) return resp, err = s.createExpense(expense) # handle err if err is not None: print(err.getErrors()) return print("Expense created!") timestamp_comment = f"added at {datetime.datetime.now()} :)" add_comment_to_expense(resp.getId(), timestamp_comment) # extra comments if "comment" in exp_data and exp_data["comment"] != "": add_comment_to_expense(resp.getId(), comment)