aboutsummaryrefslogtreecommitdiff
path: root/ihatemoney/tests/main_test.py
blob: d495f3a970b6ef0b2a8c9c511f9f88b243328176 (plain)
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
import os
import smtplib
import socket
import unittest
from unittest.mock import MagicMock, patch

from sqlalchemy import orm
from werkzeug.security import check_password_hash

from ihatemoney import models
from ihatemoney.currency_convertor import CurrencyConverter
from ihatemoney.manage import delete_project, generate_config, password_hash
from ihatemoney.run import load_configuration
from ihatemoney.tests.common.ihatemoney_testcase import BaseTestCase, IhatemoneyTestCase

# Unset configuration file env var if previously set
os.environ.pop("IHATEMONEY_SETTINGS_FILE_PATH", None)

__HERE__ = os.path.dirname(os.path.abspath(__file__))


class ConfigurationTestCase(BaseTestCase):
    def test_default_configuration(self):
        """Test that default settings are loaded when no other configuration file is specified"""
        self.assertFalse(self.app.config["DEBUG"])
        self.assertEqual(
            self.app.config["SQLALCHEMY_DATABASE_URI"], "sqlite:////tmp/ihatemoney.db"
        )
        self.assertFalse(self.app.config["SQLALCHEMY_TRACK_MODIFICATIONS"])
        self.assertEqual(
            self.app.config["MAIL_DEFAULT_SENDER"],
            ("Budget manager", "budget@notmyidea.org"),
        )

    def test_env_var_configuration_file(self):
        """Test that settings are loaded from the specified configuration file"""
        os.environ["IHATEMONEY_SETTINGS_FILE_PATH"] = os.path.join(
            __HERE__, "ihatemoney_envvar.cfg"
        )
        load_configuration(self.app)
        self.assertEqual(self.app.config["SECRET_KEY"], "lalatra")

        # Test that the specified configuration file is loaded
        # even if the default configuration file ihatemoney.cfg exists
        os.environ["IHATEMONEY_SETTINGS_FILE_PATH"] = os.path.join(
            __HERE__, "ihatemoney_envvar.cfg"
        )
        self.app.config.root_path = __HERE__
        load_configuration(self.app)
        self.assertEqual(self.app.config["SECRET_KEY"], "lalatra")

        os.environ.pop("IHATEMONEY_SETTINGS_FILE_PATH", None)

    def test_default_configuration_file(self):
        """Test that settings are loaded from the default configuration file"""
        self.app.config.root_path = __HERE__
        load_configuration(self.app)
        self.assertEqual(self.app.config["SECRET_KEY"], "supersecret")


class ServerTestCase(IhatemoneyTestCase):
    def test_homepage(self):
        # See https://github.com/spiral-project/ihatemoney/pull/358
        self.app.config["APPLICATION_ROOT"] = "/"
        req = self.client.get("/")
        self.assertStatus(200, req)

    def test_unprefixed(self):
        self.app.config["APPLICATION_ROOT"] = "/"
        req = self.client.get("/foo/")
        self.assertStatus(303, req)

    def test_prefixed(self):
        self.app.config["APPLICATION_ROOT"] = "/foo"
        req = self.client.get("/foo/")
        self.assertStatus(200, req)


class CommandTestCase(BaseTestCase):
    def test_generate_config(self):
        """Simply checks that all config file generation
        - raise no exception
        - produce something non-empty
        """
        runner = self.app.test_cli_runner()
        for config_file in generate_config.params[0].type.choices:
            result = runner.invoke(generate_config, config_file)
            self.assertNotEqual(len(result.output.strip()), 0)

    def test_generate_password_hash(self):
        runner = self.app.test_cli_runner()
        with patch("getpass.getpass", new=lambda prompt: "secret"):
            result = runner.invoke(password_hash)
            self.assertTrue(check_password_hash(result.output.strip(), "secret"))

    def test_demo_project_deletion(self):
        self.create_project("demo")
        self.assertEquals(models.Project.query.get("demo").name, "demo")

        runner = self.app.test_cli_runner()
        runner.invoke(delete_project, "demo")

        self.assertEqual(len(models.Project.query.all()), 0)


class ModelsTestCase(IhatemoneyTestCase):
    def test_bill_pay_each(self):

        self.post_project("raclette")

        # add members
        self.client.post("/raclette/members/add", data={"name": "zorglub", "weight": 2})
        self.client.post("/raclette/members/add", data={"name": "fred"})
        self.client.post("/raclette/members/add", data={"name": "tata"})
        # Add a member with a balance=0 :
        self.client.post("/raclette/members/add", data={"name": "pépé"})

        # create bills
        self.client.post(
            "/raclette/add",
            data={
                "date": "2011-08-10",
                "what": "fromage à raclette",
                "payer": 1,
                "payed_for": [1, 2, 3],
                "amount": "10.0",
            },
        )

        self.client.post(
            "/raclette/add",
            data={
                "date": "2011-08-10",
                "what": "red wine",
                "payer": 2,
                "payed_for": [1],
                "amount": "20",
            },
        )

        self.client.post(
            "/raclette/add",
            data={
                "date": "2011-08-10",
                "what": "delicatessen",
                "payer": 1,
                "payed_for": [1, 2],
                "amount": "10",
            },
        )

        project = models.Project.query.get_by_name(name="raclette")
        zorglub = models.Person.query.get_by_name(name="zorglub", project=project)
        zorglub_bills = models.Bill.query.options(
            orm.subqueryload(models.Bill.owers)
        ).filter(models.Bill.owers.contains(zorglub))
        for bill in zorglub_bills.all():
            if bill.what == "red wine":
                pay_each_expected = 20 / 2
                self.assertEqual(bill.pay_each(), pay_each_expected)
            if bill.what == "fromage à raclette":
                pay_each_expected = 10 / 4
                self.assertEqual(bill.pay_each(), pay_each_expected)
            if bill.what == "delicatessen":
                pay_each_expected = 10 / 3
                self.assertEqual(bill.pay_each(), pay_each_expected)


class EmailFailureTestCase(IhatemoneyTestCase):
    def test_creation_email_failure_smtp(self):
        self.login("raclette")
        with patch.object(
            self.app.mail, "send", MagicMock(side_effect=smtplib.SMTPException)
        ):
            resp = self.post_project("raclette")
        # Check that an error message is displayed
        self.assertIn(
            "We tried to send you an reminder email, but there was an error",
            resp.data.decode("utf-8"),
        )
        # Check that we were redirected to the home page anyway
        self.assertIn(
            'You probably want to <a href="/raclette/members/add"',
            resp.data.decode("utf-8"),
        )

    def test_creation_email_failure_socket(self):
        self.login("raclette")
        with patch.object(self.app.mail, "send", MagicMock(side_effect=socket.error)):
            resp = self.post_project("raclette")
        # Check that an error message is displayed
        self.assertIn(
            "We tried to send you an reminder email, but there was an error",
            resp.data.decode("utf-8"),
        )
        # Check that we were redirected to the home page anyway
        self.assertIn(
            'You probably want to <a href="/raclette/members/add"',
            resp.data.decode("utf-8"),
        )

    def test_password_reset_email_failure(self):
        self.create_project("raclette")
        for exception in (smtplib.SMTPException, socket.error):
            with patch.object(self.app.mail, "send", MagicMock(side_effect=exception)):
                resp = self.client.post(
                    "/password-reminder", data={"id": "raclette"}, follow_redirects=True
                )
            # Check that an error message is displayed
            self.assertIn(
                "there was an error while sending you an email",
                resp.data.decode("utf-8"),
            )
            # Check that we were not redirected to the success page
            self.assertNotIn(
                "A link to reset your password has been sent to you",
                resp.data.decode("utf-8"),
            )

    def test_invitation_email_failure(self):
        self.login("raclette")
        self.post_project("raclette")
        for exception in (smtplib.SMTPException, socket.error):
            with patch.object(self.app.mail, "send", MagicMock(side_effect=exception)):
                resp = self.client.post(
                    "/raclette/invite",
                    data={"emails": "toto@notmyidea.org"},
                    follow_redirects=True,
                )
            # Check that an error message is displayed
            self.assertIn(
                "there was an error while trying to send the invitation emails",
                resp.data.decode("utf-8"),
            )
            # Check that we are still on the same page (no redirection)
            self.assertIn(
                "Invite people to join this project", resp.data.decode("utf-8")
            )


class TestCurrencyConverter(unittest.TestCase):
    converter = CurrencyConverter()
    mock_data = {"USD": 1, "EUR": 0.8115}
    converter.get_rates = MagicMock(return_value=mock_data)

    def test_only_one_instance(self):
        one = id(CurrencyConverter())
        two = id(CurrencyConverter())
        self.assertEqual(one, two)

    def test_get_currencies(self):
        self.assertCountEqual(self.converter.get_currencies(), ["USD", "EUR"])

    def test_exchange_currency(self):
        result = self.converter.exchange_currency(100, "USD", "EUR")
        self.assertEqual(result, 81.15)


if __name__ == "__main__":
    unittest.main()