-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest_main.py
More file actions
295 lines (253 loc) · 11.5 KB
/
test_main.py
File metadata and controls
295 lines (253 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import pytest
from datetime import datetime, timedelta
from splitwise import Splitwise, Expense, User, Comment
from splitwise.user import ExpenseUser
from unittest.mock import MagicMock, patch
import requests
import importlib
@pytest.fixture(autouse=True)
def mock_requests():
with patch('requests.request') as mock:
mock.return_value.json.return_value = {'data': []}
yield mock
def load_main():
import main
return main
@pytest.fixture
def mock_splitwise():
mock_sw = MagicMock(spec=Splitwise)
mock_sw.getExpenses.return_value = []
return mock_sw
@pytest.fixture
def mock_user():
user = MagicMock(spec=User)
user.getId.return_value = "12345"
user.getFirstName.return_value = "Test"
return user
@pytest.fixture
def mock_expense():
expense = MagicMock(spec=Expense)
expense.getId.return_value = "67890"
expense.getDescription.return_value = "Test Expense"
expense.getCurrencyCode.return_value = "USD"
expense.getDate.return_value = "2023-09-10T12:00:00Z"
expense.getCreatedAt.return_value = "2023-09-10T12:00:00Z"
expense.getDetails.return_value = "Test details"
expense.getDeletedAt.return_value = None
expense.getPayment.return_value = False
expense.getUpdatedBy.return_value = None
expense.getCreatedBy.return_value = MagicMock(getId=MagicMock(return_value="12345"))
return expense
@pytest.fixture
def mock_expense_user():
expense_user = MagicMock(spec=ExpenseUser)
expense_user.getId.return_value = "12345"
expense_user.getOwedShare.return_value = "10.00"
expense_user.getPaidShare.return_value = "10.00"
return expense_user
def test_formatExpense(mock_expense, mock_expense_user):
formatExpense = load_main().formatExpense
result = formatExpense(mock_expense, mock_expense_user)
assert "Test Expense" in result
assert "USD" in result
assert "10.00" in result
assert "2023-09-10" in result
assert result == "Expense Test Expense for USD 10.00 on 2023-09-10T12:00:00Z"
def test_getSWUrlForExpense(mock_expense):
getSWUrlForExpense = load_main().getSWUrlForExpense
result = getSWUrlForExpense(mock_expense)
assert result == "https://secure.splitwise.com/expenses/67890"
def test_getDate():
getDate = load_main().getDate
date_str = "2023-09-10T12:00:00Z"
result = getDate(date_str)
assert isinstance(result, datetime)
assert result.year == 2023
assert result.month == 9
assert result.day == 10
@pytest.mark.parametrize("text,expected,separator", [
("firefly/category/description", ["category", "description"], None),
("firefly", [True], None),
("firefly|custom|sep", ["custom", "sep"], "|"),
("firefly,custom/with/slash,sep", ["custom/with/slash", "sep"], ","),
])
def test_processText(text, expected, separator):
main = load_main()
processText = main.processText
if separator:
main.conf["SPLITWISE_FIELD_SEPARATOR"] = separator
assert processText(text) == expected
main.conf["SPLITWISE_FIELD_SEPARATOR"] = "/"
@patch('requests.request')
def test_callApi(mock_request):
callApi = load_main().callApi
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {"data": "test"}
mock_request.return_value = mock_response
result = callApi("test_path", method="GET")
assert result.json() == {"data": "test"}
mock_request.assert_called_once()
@patch('main.callApi')
def test_searchTransactions(mock_callApi):
searchTransactions = load_main().searchTransactions
# Simulate pagination
mock_responses = [
MagicMock(json=lambda: {"data": [{"id": "1"}, {"id": "2"}]}),
MagicMock(json=lambda: {"data": [{"id": "3"}]}),
MagicMock(json=lambda: {"data": []}) # Empty response to end pagination
]
mock_callApi.side_effect = mock_responses
result = list(searchTransactions({"query": "test"}))
assert len(result) == 3
assert [r["id"] for r in result] == ["1", "2", "3"]
assert mock_callApi.call_count == 3
@patch('main.searchTransactions')
def test_getTransactionsAfter(mock_searchTransactions):
getTransactionsAfter = load_main().getTransactionsAfter
mock_searchTransactions.return_value = [
{"attributes": {"transactions": [{"external_url": "url1"}]}},
{"attributes": {"transactions": [{"external_url": "url2"}]}}
]
result = getTransactionsAfter(datetime.now().astimezone() - timedelta(days=1))
assert len(result) == 2
assert "url1" in result
assert "url2" in result
@patch('main.getAccountCurrencyCode')
def test_getExpenseTransactionBody(mock_getAccountCurrencyCode, mock_expense, mock_expense_user):
getExpenseTransactionBody = load_main().getExpenseTransactionBody
mock_getAccountCurrencyCode.return_value = "USD"
result = getExpenseTransactionBody(mock_expense, mock_expense_user, ["Dest", "Category", "Desc", "Amex"])
assert result["source_name"] == "Amex"
assert result["destination_name"] == "Dest"
assert result["category_name"] == "Category"
assert float(result["amount"]) == float("10.00")
assert result["description"] == "Desc"
@patch('main.callApi')
@patch('main.updateTransaction')
@patch('main.addTransaction')
@patch('main.searchTransactions')
@patch('main.getAccountCurrencyCode')
def test_processExpense_update(mock_getAccountCurrencyCode,
mock_searchTransactions,
mock_addTransaction,
mock_updateTransaction,
mock_callApi,
mock_expense,
mock_expense_user):
from main import Config
with patch.dict('main.conf', {'SW_BALANCE_ACCOUNT': ''}):
processExpense = load_main().processExpense
getSWUrlForExpense = load_main().getSWUrlForExpense
mock_getAccountCurrencyCode.return_value = "USD"
mock_callApi.return_value = MagicMock(json=lambda: {})
mock_searchTransactions.return_value = []
ff_txns = {getSWUrlForExpense(mock_expense): {"id": "123", "attributes": {}}}
processExpense(datetime.now().astimezone() - timedelta(days=1), ff_txns, mock_expense, mock_expense_user, [])
mock_updateTransaction.assert_called_once()
mock_addTransaction.assert_not_called()
@patch('main.callApi')
@patch('main.updateTransaction')
@patch('main.addTransaction')
@patch('main.searchTransactions')
@patch('main.getAccountCurrencyCode')
def test_processExpense_add_new(
mock_getAccountCurrencyCode,
mock_searchTransactions,
mock_addTransaction,
mock_updateTransaction,
mock_callApi,
mock_expense,
mock_expense_user):
processExpense = load_main().processExpense
mock_callApi.return_value = MagicMock(json=lambda: {})
mock_searchTransactions.return_value = []
mock_getAccountCurrencyCode.return_value = "USD"
ff_txns = {}
with patch.dict('main.conf', {'SW_BALANCE_ACCOUNT': ''}):
processExpense(datetime.now().astimezone() - timedelta(days=1), ff_txns, mock_expense, mock_expense_user, ["Dest", "Category", "Desc"])
mock_addTransaction.assert_called_once()
mock_updateTransaction.assert_not_called()
mock_searchTransactions.assert_called_once()
@pytest.fixture
def mock_splitwise():
return MagicMock()
def test_getExpensesAfter(mock_splitwise, mock_user):
getExpensesAfter = load_main().getExpensesAfter
# Setup
mock_expense1 = MagicMock(spec=Expense)
mock_expense1.getId.return_value = "1"
mock_expense1.getDescription.return_value = "Expense 1"
mock_expense1.getDeletedAt.return_value = None
mock_expense1.getPayment.return_value = False
mock_expense1.getUpdatedAt.return_value = "2023-09-10T12:00:00Z"
mock_expense1.getCreatedAt.return_value = "2023-09-10T12:00:00Z"
mock_expense1.getDate.return_value = "2023-09-10"
mock_expense1.getDetails.return_value = "firefly/Category1/Description1"
mock_expense1.getUpdatedBy.return_value = None
mock_expense1.getCreatedBy.return_value = MagicMock(getId=MagicMock(return_value="12345"))
mock_expense2 = MagicMock(spec=Expense)
mock_expense2.getId.return_value = "2"
mock_expense2.getDescription.return_value = "Expense 2"
mock_expense2.getDeletedAt.return_value = None
mock_expense2.getPayment.return_value = False
mock_expense2.getUpdatedAt.return_value = "2023-09-11T12:00:00Z"
mock_expense2.getCreatedAt.return_value = "2023-09-11T12:00:00Z"
mock_expense2.getDate.return_value = "2023-09-11"
mock_expense2.getDetails.return_value = "Regular expense details"
mock_expense2.getUpdatedBy.return_value = None
mock_expense2.getCreatedBy.return_value = MagicMock(getId=MagicMock(return_value="12345"))
mock_expense3 = MagicMock(spec=Expense)
mock_expense3.getId.return_value = "3"
mock_expense3.getDescription.return_value = "Expense 3"
mock_expense3.getDeletedAt.return_value = None
mock_expense3.getPayment.return_value = False
mock_expense3.getUpdatedAt.return_value = "2023-09-12T12:00:00Z"
mock_expense3.getCreatedAt.return_value = "2023-09-12T12:00:00Z"
mock_expense3.getDate.return_value = "2023-09-12"
mock_expense3.getDetails.return_value = "Another regular expense"
mock_expense3.getUpdatedBy.return_value = None
mock_expense3.getCreatedBy.return_value = MagicMock(getId=MagicMock(return_value="12345"))
mock_expense_user = MagicMock(spec=ExpenseUser)
mock_expense_user.getId.return_value = "12345"
mock_expense_user.getOwedShare.return_value = "10.00"
for expense in [mock_expense1, mock_expense2, mock_expense3]:
expense.getUsers.return_value = [mock_expense_user]
# Mock comments
mock_comment2 = MagicMock(spec=Comment)
mock_comment2.getCommentedUser.return_value = MagicMock(getId=MagicMock(return_value="12345"))
mock_comment2.getContent.return_value = "firefly/Category2/Description2"
mock_splitwise.getComments.side_effect = [
[], # For expense1 (already has Firefly data in details)
[mock_comment2], # For expense2
[] # For expense3
]
mock_splitwise.getExpenses.side_effect = [
[mock_expense1, mock_expense2, mock_expense3],
[] # Empty list to end pagination
]
# Call the function
date = datetime.now() - timedelta(days=7)
result = list(getExpensesAfter(mock_splitwise, date, mock_user))
# Assertions
assert len(result) == 2, "Should only return 2 expenses with Firefly data"
# Check first expense (with Firefly data in details)
assert result[0][0] == mock_expense1
assert result[0][1] == mock_expense_user
assert result[0][2] == ["Category1", "Description1"]
# Check second expense (with Firefly data in comment)
assert result[1][0] == mock_expense2
assert result[1][1] == mock_expense_user
assert result[1][2] == ["Category2", "Description2"]
# Check that getExpenses was called with correct parameters
mock_splitwise.getExpenses.assert_called_with(
updated_after=date.isoformat(),
offset=20, # This should match the 'limit' in your getExpensesAfter function
limit=20
)
# Ensure getComments was called for each expense
assert mock_splitwise.getComments.call_count == 3
# Verify that the third expense (without Firefly data) was not returned
assert all(r[0].getId() != "3" for r in result), "Expense without Firefly data should not be returned"
if __name__ == "__main__":
pytest.main([__file__])