From 2c89cdc1b9a9f41a57816cabe5253ac90c035f23 Mon Sep 17 00:00:00 2001
From: Philip Sargent <philip.sargent@gmail.com>
Date: Sun, 3 Sep 2023 23:28:36 +0300
Subject: [PATCH] login fix for protected pages in tests

---
 core/TESTS/test_parsers.py | 77 ++++++++++++++++++++++++++++++++------
 urls.py                    |  2 +-
 2 files changed, 66 insertions(+), 13 deletions(-)

diff --git a/core/TESTS/test_parsers.py b/core/TESTS/test_parsers.py
index 9a77080..218e4fd 100644
--- a/core/TESTS/test_parsers.py
+++ b/core/TESTS/test_parsers.py
@@ -31,6 +31,8 @@ TEST_YEAR = "1986"
 lbp.ENTRIES[TEST_YEAR] = 4 # number of entries in the test logbook 
     
 class ImportTest(TestCase):
+    # see test_logins.py for the tests to check that logged-in users work
+    fixtures = ["auth_users"] # contains user 'expotest' with a hash => password = 'secretword'
     
     @classmethod
     def setUpTestData(cls):
@@ -64,9 +66,13 @@ class ImportTest(TestCase):
         dave = make_person("David", "Smartarse", "")
         mike = make_person("Michael", "Wideboy", "WB", vfho=True)
         # NOT created Kurt, as the whole point is that he is a guest.
- 
-    def setUp(self): 
-        pass
+         
+    def setUp(self):
+        from django.contrib.auth.models import User
+
+        self.user = User.objects.get(username="expotest") # has password 'secretword' from fixture
+        self.client = Client()
+
 
     def tearDown(self):
         pass
@@ -75,7 +81,9 @@ class ImportTest(TestCase):
         self.assertTrue(self.test_logbook.is_file())
         
     def test_logbook_parse(self):
-        lbp.LoadLogbook(self.test_expo)
+        """This is just testing the db not the web page
+        """
+        lbp.LoadLogbook(self.test_expo) # i.e. load the 1986 logbook
         
         issues = DataIssue.objects.all()
         messages = []
@@ -97,28 +105,73 @@ class ImportTest(TestCase):
         with open('_test_response.txt', 'w') as f:
             for m in messages:
                 f.write(m)  
+        messages_text = ", ".join(messages)
         for e in expected:
-            self.assertIn(e, messages)
+            phmatch = re.search(e, messages_text)
+            self.assertIsNotNone(phmatch, f"Failed to find expected text: '{e}' in\n{messages_text}")
         for e in not_expected:
-            self.assertNotIn(e, messages)
+            phmatch = re.search(e, messages_text)
+            self.assertIsNone(phmatch, f"Found unexpected text: '{e}' in\n{messages_text}")
             
     def test_lbe(self):
-        lbp.LoadLogbook(self.test_expo)
+        lbp.LoadLogbook(self.test_expo) # i.e. load the 1986 logbook, which has this logbook entry
         
-        response = self.client.get(f"/logbookentry/1986-07-27/1986-07-27b")
+        response = self.client.get(f"/logbookentry/1986-07-27/1986-07-27a")
         self.assertEqual(response.status_code, HTTPStatus.OK)
         content = response.content.decode()
-        with open('_test_response.html', 'w') as f:
-            f.write(content)        
+        # with open('_test_response.html', 'w') as f:
+            # f.write(content)        
         expected = [
-            "Logbook CUCC expo-test 1986 123  - 123 Wave 1",
+            "<title>Logbook CUCC expo-test 1986 123  - 123 Wave 1</title>",
             "Smartarse rig first section of new pitches. Second wave arrives and takes over rigging.",
         ]
         for ph in expected:
             phmatch = re.search(ph, content)
             self.assertIsNotNone(phmatch, "Failed to find expected text: '" + ph + "'")
-        
+
+    def test_lbe_new(self):
+        """This page requires the user to be logged in first, hence the extra shenanigans
+        """
+        c = self.client
+        u = self.user
+        c.login(username=u.username, password="secretword")
+
+        response = self.client.get(f"/logbookedit/")
+        self.assertEqual(response.status_code, HTTPStatus.OK)
+        content = response.content.decode()
+        with open('_test_response.html', 'w') as f:
+            f.write(content) 
+        expected = [
+            "New Logbook Entry in ",
+            "Other names (comma separated)",
+            "Place: cave name, or 'plateau', 'topcamp' etc.",
+        ]
+        for ph in expected:
+            phmatch = re.search(ph, content)
+            self.assertIsNotNone(phmatch, f"({response.status_code}) Failed to find expected text: '" + ph + "'")
+            
+
+    def test_lbe_edit(self):
+        c = self.client
+        u = self.user
+        c.login(username=u.username, password="secretword")
+         
+        response = self.client.get(f"/logbookedit/1986-07-27a")
+        self.assertEqual(response.status_code, HTTPStatus.OK)
+        content = response.content.decode()
+        with open('_test_response_edit.html', 'w') as f:
+            f.write(content)        
+        expected = [
+            "Edit Logbook Entry on 1986-07-27",
+            "Other names (comma separated)",
+            "Place: cave name, or 'plateau', 'topcamp' etc.",
+        ]
+        for ph in expected:
+            phmatch = re.search(ph, content)
+            self.assertIsNotNone(phmatch, f"({response.status_code}) Failed to find expected text: '" + ph + "'")
+            
     def test_aliases(self):
+        # FIX THIS
         # Problem: '' empty string appears as valid alias for David Smartarse
         response = self.client.get(f"/aliases/{TEST_YEAR}")
         self.assertEqual(response.status_code, HTTPStatus.OK)
diff --git a/urls.py b/urls.py
index e88df3b..f9e1b84 100644
--- a/urls.py
+++ b/urls.py
@@ -109,7 +109,7 @@ trogglepatterns = [
     path('dwgupload/',                   dwgupload,   name='dwgupload'), 
     path('dwguploadnogit/',              dwgupload,  {'gitdisable': 'yes'}, name='dwguploadnogit'), # used in testing
     path('dwguploadnogit/<path:folder>', dwgupload,  {'gitdisable': 'yes'}, name='dwguploadnogit'), # used in testing
-    path('logbookedit/',                logbookedit,  name='logbookedit'), 
+    path('logbookedit/',                 logbookedit,  name='logbookedit'), 
     path('logbookedit/<slug:slug>',      logbookedit,  name='logbookedit'), 
 
 # Renaming an uploaded file