summaryrefslogtreecommitdiffstats
path: root/core/TESTS/test_logins.py
blob: 9602b947211497976534fabda20b001a9fda2d74 (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
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
"""
Originally written for CUYC 
Philip Sargent (Feb.2021)

Modified for Expo April 2021.

To run just these, do 
uv run  manage.py test -v 3 troggle.core.TESTS.test_logins
"""

import pathlib
import re
from http import HTTPStatus

from django.contrib.auth.models import User
from django.test import Client, TestCase

import troggle.settings as settings
from troggle.core.models.troggle import Expedition
from troggle.core.models.wallets import Wallet
from troggle.core.utils import current_expo

current_year = current_expo()


def create_user(name=None, last_name="Caver", is_superuser=False):
    u = User()
    u.username = name
    u.email = f"philip.sargent+{name}@gmail.com"
    u.first_name, u.last_name = name, last_name
    u.set_password("secretword") # all test users have same password
    u.save()
    return u
    

class DataTests(TestCase):
    """These check that the NULL and NON-UNIQUE constraints are working in the database
    
    no tests here... !"""

    @classmethod
    def setUpTestData(cls):
        pass

    def setUp(self):
        create_user(name="expo")
 
    def tearDown(self):
        Users.objects.all().delete()


class LoginTests(TestCase):

    def setUp(self):
        create_user(name="expo")
        create_user(name="expotest")
        create_user(name="expotestadmin",  is_superuser = True)

    def tearDown(self):
        User.objects.all().delete()

    def test_fix_admin_login_fail(self):
        c = self.client
        u = User.objects.get(username="expotest")

 
        response = c.get("/admin/")
        content = response.content.decode()
        # with open('admin-op.html', 'w') as f:
        # f.write(content)
        t = re.search(r"Troggle administration", content)
        self.assertIsNone(t, "Logged in as '" + u.username + "' (not staff) but still managed to get the Admin page")


class PostTests(TestCase):
    """Tests walletedit form"""

    @classmethod
    def setUpTestData(cls):
        pass

    def setUp(self):
        create_user(name="expo")
        create_user(name="expotestadmin",  is_superuser = True)
        self.user = create_user(name="expotest")
        
        c = self.client

        testyear = "2022"
        wname = f"{testyear}:00"
        self.testyear = testyear
        w = Wallet()
        w.pk = 9100
        w.fpath = str(pathlib.Path(settings.SCANS_ROOT, wname))
        w.walletname = wname
        w.save()
        self.wallet = w

        e = Expedition()
        e.year = testyear
        e.save()
        self.expedition = e

    def tearDown(self):
        User.objects.all().delete()
        Wallet.objects.all().delete()
        Expedition.objects.all().delete()

    def test_file_permissions(self):
        """Expect to be allowed to write to SCANS_ROOT, DRAWINGS_DATA, SURVEX_DATA, EXPOWEB
        Need to login first.
        """
        c = self.client
        u = self.user
        testyear = self.testyear

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        for p in [settings.SCANS_ROOT, 
                settings.DRAWINGS_DATA / "walletjson", 
                settings.EXPOWEB / "documents", 
                settings.SURVEX_DATA / "docs"
                ]:
            
            _test_file_path = pathlib.Path(p, "_created_by_test_suite.txt")
            self.assertEqual(_test_file_path.is_file(), False)

            with open(_test_file_path, "w") as f:
                f.write("test string: can we write to this directory?")
            self.assertEqual(_test_file_path.is_file(), True)
            _test_file_path.unlink()
                
    def test_scan_upload(self):
        """Expect scan upload to wallet to work on any file
        Need to login first.

        This upload form looks for the Cave and the Wallet, so the test fails if the database is not loaded with the cave
        identified in the wallet
        """
        c = self.client
        from django.contrib.auth.models import User

        u = User.objects.get(username="expotest")
        testyear = self.testyear

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        with open("core/fixtures/test_upload_file.txt", "r") as testf:
            response = self.client.post(
                f"/walletedit/{testyear}:00", data={"name": "test_upload_file.txt", "uploadfiles": testf, "who_are_you": "Gumby <gumby@tent.expo>"}
            )
            content = response.content.decode()
            self.assertEqual(response.status_code, HTTPStatus.OK)
            # with open('_test_response__scan_upload.html', 'w') as f:
                # f.write(content)
            for ph in [
                r"test_upload_",
                rf"&larr; {testyear}#00 &rarr;",
                r"description written",
                r"Plan not required",
                r"edit settings or upload a file",
            ]:
                phmatch = re.search(ph, content)
                self.assertIsNotNone(phmatch, "Failed to find expected text: '" + ph + "'")

        # Does not use the filename Django actually uses, assumes it is unchanged.  Bug: accumulates one file with random name 
        # added each time it is run. The name of the uploaded file is only available within the code where it happens 
        remove_file = pathlib.Path(settings.SCANS_ROOT) / f'{testyear}' / f'{testyear}#00'/ 'test_upload_file.txt'
        remove_file.unlink()
        
        # Just uploading a file does NOT do any git commit.
        # You need to create or edit a contents.json file for that to happen.

    def test_photo_upload(self):
        """Expect photo upload to work on any file (contrary to msg on screen)
        Upload into current default year. 
        Deletes file afterwards
        Need to login first.
        """
        c = self.client
        u = self.user

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        with open("core/fixtures/test_upload_file.txt", "r") as testf:
            response = self.client.post(
                "/photoupload", data={"name": "test_upload_file.txt", "renameto": "", "uploadfiles": testf}
            )
            content = response.content.decode()
            self.assertEqual(response.status_code, HTTPStatus.OK)
            self.assertEqual(response.status_code, HTTPStatus.OK)
            # with open('_test_response_photo_upload.html', 'w') as f:
                # f.write(content)
            for ph in [
                r"test_upload_",
                r"Upload photos into /photos/" + str(current_year),
                r" you can create a new folder in your name",
                r"Create new Photographer folder",
                r"only photo image files are accepted",
            ]:
                phmatch = re.search(ph, content)
                self.assertIsNotNone(phmatch, "Failed to find expected text: '" + ph + "'")

        # Does not use the filename Django actually uses, assumes it is unchanged.  Bug: accumulates one file with random name 
        # added each time it is run. The name of the uploaded file is only available within the code where it happens 
        remove_file = pathlib.Path(settings.PHOTOS_ROOT, current_year) / "test_upload_file.txt"
        remove_file.unlink()

    def test_photo_upload_rename(self):
        """Expect photo upload to work on any file (contrary to msg on screen)
        Upload into current default year. 
        Deletes file afterwards
        Need to login first.
        """
        c = self.client
        u = self.user

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        rename = "RENAMED-FILE.JPG"
        with open("core/fixtures/test_upload_file.txt", "r") as testf:
            response = self.client.post(
                "/photoupload", data={"name": "test_upload_file.txt", "renameto": rename, "uploadfiles": testf}
            )
            content = response.content.decode()
            self.assertEqual(response.status_code, HTTPStatus.OK)
            self.assertEqual(response.status_code, HTTPStatus.OK)
            # with open('_test_response.html', 'w') as f:
            # f.write(content)
            for ph in [rename]:
                phmatch = re.search(ph, content)
                self.assertIsNotNone(phmatch, "Failed to find expected text: '" + ph + "'")

        # Does not use the filename Django actually uses, assumes it is unchanged.  Bug: accumulates one file with random name 
        # added each time it is run. The name of the uploaded file is only available within the code where it happens 
        remove_file = pathlib.Path(settings.PHOTOS_ROOT, current_year) / rename
        if remove_file.is_file():
            remove_file.unlink()
        
        

    def test_photo_folder_create(self):
        """Create folder for new user
        Create in current year.
        Deletes folder afterwards
        Need to login first.
        """
        c = self.client
        u = self.user

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        response = self.client.post("/photoupload", data={"photographer": "GussieFinkNottle"})
        content = response.content.decode()
        self.assertEqual(response.status_code, HTTPStatus.OK)
        # with open('_test_response.html', 'w') as f:
            # f.write(content)
        for ph in [r"Create new Photographer folder", r"/GussieFinkNottle/"]:
            phmatch = re.search(ph, content)
            self.assertIsNotNone(phmatch, "Failed to find expected text: '" + ph + "'")

        # Does not use the filename Django actually uses, assumes it is unchanged.  Bug: accumulates one file with random name 
        # added each time it is run. The name of the uploaded file is only available within the code where it happens 
        remove_dir = pathlib.Path(settings.PHOTOS_ROOT, current_year) / "GussieFinkNottle"
        if remove_dir.is_dir():
            print(f"{remove_dir} was created, now removing it.")
            remove_dir.rmdir()

    def test_dwg_upload_txt(self):
        """Expect .pdf file to be refused upload
        Need to login first.
        """
        c = self.client
        u = self.user


        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        with open("core/fixtures/test_upload_file.pdf", "r") as testf:
            response = self.client.post(
                "/dwgupload/uploads", data={"name": "test_upload_file.txt", "uploadfiles": testf, "who_are_you": "Gumby <gumby@tent.expo>"}
            )
            content = response.content.decode()
            # with open('_test_response_dwg_upload_txt.html', 'w') as f:
                # f.write(content)            
            self.assertEqual(response.status_code, HTTPStatus.OK)
            t = re.search("Files refused:", content)
            self.assertIsNotNone(t, 'Logged in but failed to see "Files refused:"')


    def test_dwg_upload_drawing(self):
        """Expect no-suffix file to upload
        Note that this skips the git commit process. That would need a new test.
        Need to login first.
        """
        c = self.client
        u = self.user


        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        with open("core/fixtures/test_upload_nosuffix", "r") as testf:
            response = self.client.post(
                "/dwguploadnogit/uploads", data={"name": "test_upload_nosuffix", "uploadfiles": testf, "who_are_you": "Gumby <gumby@tent.expo>"}
            )
            content = response.content.decode()
            # with open('_test_response_dwg_upload_drawing.html', 'w') as f:
                # f.write(content)
            self.assertEqual(response.status_code, HTTPStatus.OK)
            for ph in [
                r"test_upload_nosuffix",
                r"You cannot create folders here",
                r"Creating a folder is done by a nerd",
            ]:
                phmatch = re.search(ph, content)
                self.assertIsNotNone(
                    phmatch, "Expect no-suffix file to upload OK. Failed to find expected text: '" + ph + "'"
                )

        # Does not use the filename Django actually uses, assumes it is unchanged.  Bug: accumulates one file with random name 
        # added each time it is run. The name of the uploaded file is only available within the code where it happens 
        # UploadedFile.name see https://docs.djangoproject.com/en/4.1/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile
        remove_file = pathlib.Path(settings.DRAWINGS_DATA) / "uploads" / "test_upload_nosuffix"
        if remove_file.is_file():
            remove_file.unlink()


class ComplexLoginTests(TestCase):
    """These test the login and capabilities of logged-in users, they do not use fixtures"""

    def setUp(self):
        """setUp runs once for each test in this class"""
        create_user(name="expo")
        create_user(name="expotest")
        create_user(name="expotestadmin",  is_superuser = True)

    def tearDown(self):
        self.client.logout()  # not needed as each test creates a new self.client
        User.objects.all().delete()


    # def test_login_redirect_for_non_logged_on_user(self): # need to fix this in real system
    # c = self.client
    # # Need to login first. Tests that we are redirected to login page if not logged in
    # response = c.get('noinfo/cave-number-index')
    # self.assertRedirects(response, "/login/?next=/committee/appointments/")

    def test_ordinary_login(self):
        c = self.client
        u = User.objects.get(username="expotest")

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")

        logged_in = c.login(username=u.username, password="secretword")  
        self.assertTrue(logged_in, "FAILED to login as '" + u.username + "'")

        response = c.get("/accounts/login/")  # defined by auth system
        content = response.content.decode()
        t = re.search(r"You are now logged in", content)
        self.assertIsNotNone(t, "Logged in as '" + u.username + "' but failed to get 'Now you can' greeting")

    def test_authentication_login(self):
        c = self.client
        u = User.objects.get(username="expotest")

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")

        # This is weird. I thought that the user had to login before she was in the authenticated state
        self.assertTrue(u.is_authenticated, "User '" + u.username + "' is NOT AUTHENTICATED before login")

        logged_in = c.login(username=u.username, password="secretword")  
        self.assertTrue(logged_in, "FAILED to login as '" + u.username + "'")

        self.assertTrue(u.is_authenticated, "User '" + u.username + "' is NOT AUTHENTICATED after login")

        # c.logout() # This next test always means user is still authenticated after logout. Surely not?
        # self.assertFalse(u.is_authenticated, 'User \'' + u.username + '\' is STILL AUTHENTICATED after logout')

    def test_admin_login(self):
        c = self.client
        u = User.objects.get(username="expotestadmin")

        logged_in = c.login(username=u.username, password="secretword")  
        self.assertTrue(logged_in, "FAILED to login as '" + u.username + "'")

        response = c.get("/admin/login/")
        content = response.content.decode()
        # fn='admin-op.html'
        # print(f"Writing {fn}")
        # with open(fn, 'w') as f:
            # f.write(content)
        t = re.search(r"Troggle database administration", content)
        self.assertIsNotNone(t, "Logged in as '" + u.username + "' but failed to get the Troggle Admin page")

    def test_noinfo_login(self):

        c = self.client  # inherited from TestCase
        u = User.objects.get(username="expotest")

        logged_in = c.login(username=u.username, password="secretword")  
        self.assertTrue(logged_in, "FAILED to login as '" + u.username + "'")
        response = c.get("/stats")  # a page with the Troggle menus
        content = response.content.decode()
        t = re.search(r"User\:expotest", content)
        self.assertIsNotNone(t, "Logged in as '" + u.username + "' but failed to get 'User:expotest' heading")

        response = c.get("/noinfo/cave-number-index")
        content = response.content.decode()
        t = re.search(r"2001-07 Hoffnungschacht", content)
        self.assertIsNotNone(t, "Logged in as '" + u.username + "' but failed to get /noinfo/ content")

    def test_user_force(self):

        c = self.client
        u = User.objects.get(username="expotest")

        try:
            c.force_login(u)
        except:
            self.assertIsNotNone(
                None,
                "Unexpected exception trying to force_login as '"
                + u.username
                + "' but failed (Bad Django documentation?)",
            )

        response = c.get("/stats")  # a page with the Troggle menus
        content = response.content.decode()
        t = re.search(r"Log out", content)
        self.assertIsNotNone(t, "Forced logged in as '" + u.username + "' but failed to get Log out heading")

        response = c.get("/accounts/login/")
        content = response.content.decode()
        t = re.search(r"You are now logged in", content)
        self.assertIsNotNone(t, "Forced logged in as '" + u.username + "' but failed to get /accounts/profile/ content")