• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

gcivil-nyu-org / INET-Wednesday-Spring2024-Team-2 / 638

01 May 2024 07:15PM UTC coverage: 85.085% (+1.1%) from 83.958%
638

Pull #182

travis-pro

web-flow
Merge 3bef72187 into a04204438
Pull Request #182: add tests

15 of 43 new or added lines in 1 file covered. (34.88%)

530 existing lines in 18 files now uncovered.

1101 of 1294 relevant lines covered (85.09%)

1.26 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.17
/users/tests.py
1
from django.test import TestCase, SimpleTestCase, Client, RequestFactory
2✔
2
from django.urls import reverse
2✔
3

4
from .forms import User, UserSignUpForm, LandlordSignupForm, RentalListingForm
2✔
5
from .models import CustomUser, Rental_Listings, Favorite
2✔
6
from django.contrib.messages import get_messages
2✔
7
from datetime import date, timedelta
2✔
8
from django.core.files.uploadedfile import SimpleUploadedFile
2✔
9
from django.utils import timezone
2✔
10
import json
2✔
11
import os
2✔
12
import sys
2✔
13
import unittest
2✔
14
from unittest.mock import patch, MagicMock
2✔
15
from .views import landlord_profile_update, map_view, profile_view_edit, apply_filters
2✔
16
from .forms import User, UserSignUpForm, CustomUserEditForm
2✔
17
from .models import CustomUser, Rental_Listings
2✔
18
from .views import map_view, add_rental_listing
2✔
19

20

21
class CustomUserModelTests(TestCase):
2✔
22
    def test_create_user_with_default_user_type(self):
2✔
UNCOV
23
        user = CustomUser.objects.create_user(username="test_user", password="password")
1✔
UNCOV
24
        self.assertEqual(user.user_type, CustomUser.USER)
1✔
25

26
    def test_create_user_with_landlord_user_type(self):
2✔
UNCOV
27
        user = CustomUser.objects.create_user(
1✔
28
            username="landlord_user", password="password", user_type=CustomUser.LANDLORD
29
        )
UNCOV
30
        self.assertEqual(user.user_type, CustomUser.LANDLORD)
1✔
31

32
    def test_create_superuser_with_default_user_type(self):
2✔
UNCOV
33
        superuser = CustomUser.objects.create_superuser(
1✔
34
            username="superuser", password="password"
35
        )
UNCOV
36
        self.assertEqual(superuser.user_type, CustomUser.USER)
1✔
37

38
    def test_create_superuser_with_landlord_user_type(self):
2✔
UNCOV
39
        superuser = CustomUser.objects.create_superuser(
1✔
40
            username="superuser", password="password", user_type=CustomUser.LANDLORD
41
        )
UNCOV
42
        self.assertEqual(superuser.user_type, CustomUser.LANDLORD)
1✔
43

44

45
class UserSignUpTest(TestCase):
2✔
46
    def test_user_signup_form_display_on_get_request(self):
2✔
UNCOV
47
        response = self.client.get(reverse("user_signup"))
1✔
UNCOV
48
        self.assertEqual(response.status_code, 200)
1✔
UNCOV
49
        self.assertIsInstance(response.context["form"], UserSignUpForm)
1✔
UNCOV
50
        self.assertTemplateUsed(response, "users/signup/signup.html")
1✔
51

52
    def test_user_signup_success_on_valid_post_request(self):
2✔
UNCOV
53
        form_data = {
1✔
54
            "username": "testuser",
55
            "email": "testuser@nyu.edu",
56
            "full_name": "Test User",
57
            "phone_number": "1234567890",
58
            "city": "Test City",
59
            "s3_doclink": "http://example.com/doc",
60
            "password1": "testpassword123",
61
            "password2": "testpassword123",
62
        }
UNCOV
63
        response = self.client.post(reverse("user_signup"), form_data)
1✔
UNCOV
64
        self.assertEqual(User.objects.count(), 1)
1✔
UNCOV
65
        self.assertRedirects(response, reverse("user_homepage"))
1✔
66

67
    def test_user_signup_error_on_invalid_post_request(self):
2✔
UNCOV
68
        form_data = {
1✔
69
            "username": "testuser",
70
            "email": "invalid-email",
71
            "full_name": "Test User",
72
            "phone_number": "1234567890",
73
            "city": "Test City",
74
            "password1": "testpassword123",
75
            "password2": "wrongpassword",
76
        }
UNCOV
77
        response = self.client.post(reverse("user_signup"), form_data)
1✔
UNCOV
78
        self.assertEqual(User.objects.count(), 0)
1✔
UNCOV
79
        self.assertFormError(response, "form", "email", "Enter a valid email address.")
1✔
80

81

82
class LoginProcessTests(TestCase):
2✔
83
    @classmethod
2✔
84
    def setUpTestData(cls):
2✔
85
        # Create a user and a landlord for testing login
UNCOV
86
        cls.user = CustomUser.objects.create_user(
1✔
87
            username="testuser", password="testpassword", user_type=CustomUser.USER
88
        )
UNCOV
89
        cls.landlord = CustomUser.objects.create_user(
1✔
90
            username="testlandlord",
91
            password="testpassword",
92
            user_type=CustomUser.LANDLORD,
93
            verified=True,
94
        )
UNCOV
95
        cls.landlord.save()
1✔
96

97
    def test_user_login_success(self):
2✔
UNCOV
98
        response = self.client.post(
1✔
99
            reverse("user_login"), {"username": "testuser", "password": "testpassword"}
100
        )
UNCOV
101
        self.assertRedirects(response, reverse("user_homepage"))
1✔
102

103

104
class LogoutViewTest(TestCase):
2✔
105
    def test_logout_redirect(self):
2✔
UNCOV
106
        response = self.client.get(reverse("logout"))
1✔
UNCOV
107
        self.assertRedirects(response, "/")
1✔
108

109

110
class Custom404HandlerTest(TestCase):
2✔
111
    def test_redirect_for_authenticated_landlord(self):
2✔
112
        landlord = CustomUser.objects.create_user(
×
113
            username="landlord404", password="password", user_type=CustomUser.LANDLORD
114
        )
115
        self.client.login(username="landlord404", password="password")
×
116
        self.assertIsNotNone(landlord.id)
×
117
        response = self.client.get("/nonexistentpage")
×
118
        self.assertRedirects(response, reverse("landlord_homepage"))
×
119

120
    def test_redirect_for_authenticated_user(self):
2✔
121
        user = CustomUser.objects.create_user(
×
122
            username="user404", password="password", user_type=CustomUser.USER
123
        )
124
        self.client.login(username="user404", password="password")
×
125
        self.assertIsNotNone(user.id)
×
126
        response = self.client.get("/nonexistentpage")
×
127
        self.assertRedirects(response, reverse("user_homepage"))
×
128

129
    def test_redirect_for_unauthenticated_user(self):
2✔
130
        response = self.client.get("/nonexistentpage")
×
131
        self.assertRedirects(response, reverse("index"))
×
132

133

134
class LandlordSignUpTest(TestCase):
2✔
135
    def test_landlord_signup_form_display_on_get_request(self):
2✔
UNCOV
136
        response = self.client.get(reverse("landlord_signup"))
1✔
UNCOV
137
        self.assertEqual(response.status_code, 200)
1✔
UNCOV
138
        self.assertTemplateUsed(response, "signup/landlord_signup.html")
1✔
139

140
    def test_landlord_signup_success_on_valid_post_request(self):
2✔
UNCOV
141
        form_data = {
1✔
142
            "username": "landlorduser",
143
            "email": "landlord@nyu.edu",
144
            "full_name": "Landlord User",
145
            "phone_number": "0987654321",
146
            "city": "Landlord City",
147
            "password1": "landlordpassword123",
148
            "password2": "landlordpassword123",
149
            # Assume "pdf_file" is optional for simplicity; otherwise,
150
            # use SimpleUploadedFile for tests
151
        }
UNCOV
152
        response = self.client.post(reverse("landlord_signup"), form_data)
1✔
UNCOV
153
        self.assertEqual(
1✔
154
            CustomUser.objects.filter(user_type=CustomUser.LANDLORD).count(), 1
155
        )
UNCOV
156
        self.assertRedirects(response, reverse("landlord_login"))
1✔
157

158
    def test_landlord_signup_error_on_invalid_post_request(self):
2✔
UNCOV
159
        form_data = {
1✔
160
            "username": "landlorduser",
161
            "email": "landlorduser@nyu.edu",
162
            # Missing fields
163
            "password1": "landlordpassword123",
164
            "password2": "landlordpassword123",
165
        }
UNCOV
166
        response = self.client.post(reverse("landlord_signup"), form_data)
1✔
UNCOV
167
        self.assertEqual(CustomUser.objects.count(), 0)
1✔
UNCOV
168
        self.assertTrue(response.context["form"].errors)
1✔
169

170

171
class UserSignUpFormTest(TestCase):
2✔
172
    def test_invalid_email_domain(self):
2✔
UNCOV
173
        form_data = {
1✔
174
            "email": "user@example.com",  # Invalid email domain
175
            "full_name": "Test User",
176
            "phone_number": "1234567890",
177
            "city": "New York",
178
            "password1": "strongpassword",
179
            "password2": "strongpassword",
180
        }
UNCOV
181
        form = UserSignUpForm(data=form_data)
1✔
UNCOV
182
        self.assertFalse(form.is_valid())
1✔
UNCOV
183
        self.assertIn("email", form.errors)
1✔
184

185

186
class CustomUserModelStrTest(TestCase):
2✔
187
    def test_custom_user_str(self):
2✔
UNCOV
188
        user = CustomUser.objects.create_user(
1✔
189
            username="testuser", email="testuser@nyu.edu"
190
        )
UNCOV
191
        self.assertEqual(str(user), "testuser")
1✔
192

193

194
class LandingPageViewTest(TestCase):
2✔
195
    def test_landing_page_status_code(self):
2✔
UNCOV
196
        response = self.client.get(reverse("index"))
1✔
UNCOV
197
        self.assertEqual(response.status_code, 200)
1✔
198

199

200
class LogoutTest(TestCase):
2✔
201
    def test_logout_functionality(self):
2✔
UNCOV
202
        user = CustomUser.objects.create_user(username="testuser", password="password")
1✔
UNCOV
203
        self.client.login(username="testuser", password="password")
1✔
UNCOV
204
        response = self.client.get(reverse("logout"))
1✔
UNCOV
205
        self.assertNotIn("_auth_user_id", self.client.session)
1✔
206

207

208
class UserAccessTest(TestCase):
2✔
209
    def test_protected_view_access(self):
2✔
UNCOV
210
        response = self.client.get(reverse("user_homepage"))
1✔
UNCOV
211
        self.assertEqual(response.status_code, 302)  # Redirect to login page
1✔
212

213

214
class PasswordResetViewTest(TestCase):
2✔
215
    def test_password_reset_page(self):
2✔
UNCOV
216
        response = self.client.get(reverse("password_reset_form"))
1✔
UNCOV
217
        self.assertEqual(response.status_code, 200)
1✔
218

219

220
# class RentalsPageViewTest(TestCase):
221
#     def test_rentals_page_view(self):
222
#         response = self.client.get(reverse('rentalspage'))
223
#         self.assertEqual(response.status_code, 302)
224
#         self.assertTemplateUsed(response, 'users/searchRental/rentalspage.html')
225

226

227
class RentalListingsModelTests(TestCase):
2✔
228
    def setUp(self):
2✔
229
        self.user = CustomUser.objects.create_user(
×
230
            username="testuser", email="test@nyu.edu", password="testpass123"
231
        )
232

233
    # def test_rental_listing_creation(self):
234
    #     listing = Rental_Listings.objects.create(
235
    #         address='123 Test St',
236
    #         price=2000.00,
237
    #         Landlord=self.user,
238
    #         Submitted_date=date.today()
239
    #     )
240
    #     self.assertEqual(Rental_Listings.objects.count(), 1)
241
    #     self.assertEqual(listing.address, '123 Test St')
242
    #     self.assertEqual(listing.Landlord, self.user)
243

244

245
class UserSignUpFormTests(TestCase):
2✔
246
    def test_clean_email_valid(self):
2✔
UNCOV
247
        form_data = {
1✔
248
            "username": "valid@nyu.edu",
249
            "email": "valid@nyu.edu",
250
            "password1": "testpassword",
251
            "password2": "testpassword",
252
            "full_name": "Valid User",
253
            "phone_number": "1234567890",
254
            "city": "New York",
255
        }
UNCOV
256
        form = UserSignUpForm(data=form_data)
1✔
UNCOV
257
        self.assertTrue(form.is_valid())
1✔
258

259
    def test_clean_email_invalid_domain(self):
2✔
UNCOV
260
        form_data = {
1✔
261
            "username": "invalid@gmail.com",
262
            "email": "invalid@gmail.com",
263
            "password1": "testpassword",
264
            "password2": "testpassword",
265
            "full_name": "Invalid User",
266
            "phone_number": "1234567890",
267
            "city": "New York",
268
        }
UNCOV
269
        form = UserSignUpForm(data=form_data)
1✔
UNCOV
270
        self.assertFalse(form.is_valid())
1✔
UNCOV
271
        self.assertIn("email", form.errors)
1✔
272

273

274
class LandlordSignupFormTests(TestCase):
2✔
275
    def test_form_save(self):
2✔
UNCOV
276
        form_data = {
1✔
277
            "username": "landlord@nyu.edu",
278
            "email": "landlord@nyu.edu",
279
            "password1": "landlordpassword",
280
            "password2": "landlordpassword",
281
            "full_name": "Landlord User",
282
            "phone_number": "9876543210",
283
            "city": "New York",
284
        }
UNCOV
285
        form = LandlordSignupForm(data=form_data)
1✔
UNCOV
286
        self.assertTrue(form.is_valid())
1✔
UNCOV
287
        landlord = form.save()
1✔
UNCOV
288
        self.assertEqual(landlord.email, "landlord@nyu.edu")
1✔
UNCOV
289
        self.assertEqual(landlord.user_type, CustomUser.LANDLORD)
1✔
290

291

292
class FavoriteModelTests(TestCase):
2✔
293
    def setUp(self):
2✔
UNCOV
294
        self.user = CustomUser.objects.create_user(
1✔
295
            username="favuser", email="favuser@nyu.edu", password="testpass123"
296
        )
UNCOV
297
        self.listing = Rental_Listings.objects.create(
1✔
298
            address="123 Fav St", price=1500.00, baths=1, Landlord=self.user
299
        )
UNCOV
300
        self.client = Client()
1✔
UNCOV
301
        self.client.login(username="favuser", password="testpass123")
1✔
UNCOV
302
        self.toggle_favorite_url = reverse("toggle_favorite")
1✔
303

304
    def test_toggle_favorite_add(self):
2✔
UNCOV
305
        response = self.client.post(
1✔
306
            self.toggle_favorite_url, {"listing_id": self.listing.id}
307
        )
UNCOV
308
        self.assertEqual(response.status_code, 200)
1✔
UNCOV
309
        self.assertEqual(Favorite.objects.count(), 1)
1✔
UNCOV
310
        self.assertJSONEqual(
1✔
311
            str(response.content, encoding="utf8"), {"status": "added"}
312
        )
313

314
    def test_toggle_favorite_remove(self):
2✔
UNCOV
315
        Favorite.objects.create(user=self.user, listing=self.listing)
1✔
UNCOV
316
        response = self.client.post(
1✔
317
            self.toggle_favorite_url, {"listing_id": self.listing.id}
318
        )
UNCOV
319
        self.assertEqual(response.status_code, 200)
1✔
UNCOV
320
        self.assertEqual(Favorite.objects.count(), 0)
1✔
UNCOV
321
        self.assertJSONEqual(
1✔
322
            str(response.content, encoding="utf8"), {"status": "removed"}
323
        )
324

325
    def test_toggle_favorite_with_invalid_listing(self):
2✔
UNCOV
326
        response = self.client.post(
1✔
327
            self.toggle_favorite_url, {"listing_id": 9999}
328
        )  # Assuming 9999 is an invalid ID
UNCOV
329
        self.assertEqual(response.status_code, 404)
1✔
UNCOV
330
        self.assertJSONEqual(
1✔
331
            str(response.content, encoding="utf8"), {"error": "Listing not found"}
332
        )
333

334
    def test_toggle_favorite_without_listing_id(self):
2✔
UNCOV
335
        response = self.client.post(self.toggle_favorite_url, {})
1✔
UNCOV
336
        self.assertEqual(response.status_code, 400)
1✔
UNCOV
337
        self.assertJSONEqual(
1✔
338
            str(response.content, encoding="utf8"), {"error": "Listing ID is required"}
339
        )
340

341

342
class LogoutViewTests(TestCase):
2✔
343
    def test_logout(self):
2✔
UNCOV
344
        self.client.login(username="testuser", password="testpass123")
1✔
UNCOV
345
        response = self.client.get(reverse("logout"))
1✔
UNCOV
346
        self.assertRedirects(response, "/")
1✔
347

348

349
class HomeViewTests(TestCase):
2✔
350
    def test_home_view_status_code(self):
2✔
UNCOV
351
        response = self.client.get(reverse("index"))
1✔
UNCOV
352
        self.assertEqual(response.status_code, 200)
1✔
353

354

355
# class UserHomeViewTests(TestCase):
356
#     def test_user_home_redirect_for_anonymous(self):
357
#         response = self.client.get(reverse('user_homepage'), follow=True)
358
#         self.assertRedirects(response, '/login/user_login?next=/user/home/')
359

360
# class LandlordHomeViewTests(TestCase):
361
#     def test_landlord_home_redirect_for_anonymous(self):
362
#         response = self.client.get(reverse('landlord_homepage'), follow=True)
363
#         self.assertRedirects(response, '/login/landlord_login?next=/landlord/home/')
364

365

366
class RentalsPageViewTests(TestCase):
2✔
367
    def test_rentals_page_for_user(self):
2✔
UNCOV
368
        self.client.login(username="testuser", password="testpass123")
1✔
UNCOV
369
        response = self.client.get(reverse("rentalspage"))
1✔
UNCOV
370
        self.assertEqual(response.status_code, 302)
1✔
371

372

373
# class FavoritesPageViewTests(TestCase):
374
#     def test_favorites_page_for_user(self):
375
#         self.client.login(username='testuser', password='testpass123')  # Make sure the user is logged in
376
#         response = self.client.get(reverse('favorites_page'))
377
#         self.assertEqual(response.status_code, 200)
378

379

380
class UserSignUpViewTests(TestCase):
2✔
381
    def test_user_signup_with_invalid_data(self):
2✔
UNCOV
382
        response = self.client.post(reverse("user_signup"), {})
1✔
UNCOV
383
        self.assertEqual(response.status_code, 200)
1✔
UNCOV
384
        self.assertTrue(response.context["form"].errors)
1✔
385

386

387
class LandlordSignUpViewTests(TestCase):
2✔
388
    def test_landlord_signup_with_valid_data(self):
2✔
UNCOV
389
        form_data = {
1✔
390
            "username": "newlandlord",
391
            "email": "newlandlord@nyu.edu",
392
            "password1": "landlordpassword123",
393
            "password2": "landlordpassword123",
394
            "full_name": "New Landlord",
395
            "phone_number": "1234567890",
396
            "city": "New York City",
397
        }
UNCOV
398
        response = self.client.post(reverse("landlord_signup"), form_data)
1✔
UNCOV
399
        self.assertRedirects(response, reverse("landlord_login"))
1✔
UNCOV
400
        self.assertEqual(
1✔
401
            CustomUser.objects.filter(user_type=CustomUser.LANDLORD).count(), 1
402
        )
403

404

405
class UserLoginViewTests(TestCase):
2✔
406
    def test_user_login_redirect(self):
2✔
UNCOV
407
        user = CustomUser.objects.create_user(
1✔
408
            username="loginuser", email="loginuser@nyu.edu", password="password"
409
        )
UNCOV
410
        response = self.client.post(
1✔
411
            reverse("user_login"), {"username": "loginuser", "password": "password"}
412
        )
UNCOV
413
        self.assertRedirects(response, reverse("user_homepage"))
1✔
414

415

416
# class UserHomePageViewTests(TestCase):
417
#     def test_user_homepage_access_unauthenticated(self):
418
#         response = self.client.get(reverse("user_homepage"))
419
#         self.assertEqual(response.status_code, 302)
420
#         self.assertTrue(reverse("user_login") in response.url)
421

422

423
class UserHomePageAuthenticatedAccessTests(TestCase):
2✔
424
    def test_user_homepage_access_authenticated(self):
2✔
UNCOV
425
        user = CustomUser.objects.create_user(
1✔
426
            username="testuserhome", email="testuserhome@nyu.edu", password="password"
427
        )
UNCOV
428
        self.client.login(username="testuserhome", password="password")
1✔
UNCOV
429
        response = self.client.get(reverse("user_homepage"))
1✔
UNCOV
430
        self.assertEqual(response.status_code, 200)
1✔
431

432

433
class LogoutFunctionalityTests(TestCase):
2✔
434
    def test_logout_redirects_to_home(self):
2✔
UNCOV
435
        self.client.login(username="testuser", password="testpass123")
1✔
UNCOV
436
        response = self.client.get(reverse("logout"))
1✔
UNCOV
437
        self.assertRedirects(response, reverse("index"))
1✔
438

439

440
class RentalListingsAccessTests(TestCase):
2✔
441
    def test_rental_listings_access_by_authenticated_user(self):
2✔
UNCOV
442
        self.client.login(username="testuser", password="testpass123")
1✔
UNCOV
443
        response = self.client.get(reverse("rentalspage"))
1✔
UNCOV
444
        self.assertEqual(response.status_code, 302)
1✔
445

446

447
class LandlordSignupWithFileTest(TestCase):
2✔
448
    @patch("users.views.boto3.client")
2✔
449
    def test_landlord_signup_with_file(self, mock_boto3_client):
2✔
UNCOV
450
        mock_s3_client = mock_boto3_client.return_value
1✔
UNCOV
451
        mock_s3_client.upload_fileobj.return_value = None  # Simulate successful upload
1✔
452

UNCOV
453
        form_data = {
1✔
454
            "username": "landlordfile@nyu.edu",
455
            "email": "landlordfile@nyu.edu",
456
            "password1": "landlordpassword",
457
            "password2": "landlordpassword",
458
            "full_name": "Landlord File",
459
            "phone_number": "9876543210",
460
            "city": "New York",
461
            "pdf_file": SimpleUploadedFile(
462
                "test_file.pdf",
463
                b"These are the file contents.",
464
                content_type="application/pdf",
465
            ),
466
        }
UNCOV
467
        response = self.client.post(reverse("landlord_signup"), form_data)
1✔
UNCOV
468
        self.assertRedirects(response, reverse("landlord_login"))
1✔
UNCOV
469
        self.assertTrue(
1✔
470
            CustomUser.objects.filter(email="landlordfile@nyu.edu").exists()
471
        )
472

473

474
class UserLoginRedirectTest(TestCase):
2✔
475
    @classmethod
2✔
476
    def setUpTestData(cls):
2✔
UNCOV
477
        cls.user = CustomUser.objects.create_user(
1✔
478
            username="testuserredirect",
479
            email="userredirect@nyu.edu",
480
            password="password123",
481
            user_type=CustomUser.USER,
482
        )
483

484
    def test_user_login_redirect_to_user_homepage(self):
2✔
UNCOV
485
        self.client.login(username="testuserredirect", password="password123")
1✔
UNCOV
486
        response = self.client.get(reverse("user_homepage"))
1✔
UNCOV
487
        self.assertEqual(response.status_code, 200)
1✔
488

489

490
class Custom404HandlerTest(TestCase):
2✔
491
    def test_404_redirect_for_anonymous_user(self):
2✔
UNCOV
492
        response = self.client.get("/thispagedoesnotexist")
1✔
UNCOV
493
        self.assertRedirects(response, reverse("index"))
1✔
494

495
    def test_404_redirect_for_authenticated_user(self):
2✔
UNCOV
496
        user = CustomUser.objects.create_user(
1✔
497
            username="user404test", password="password"
498
        )
UNCOV
499
        self.client.login(username="user404test", password="password")
1✔
UNCOV
500
        response = self.client.get("/thispagedoesnotexist")
1✔
UNCOV
501
        self.assertRedirects(response, reverse("user_homepage"))
1✔
502

503

504
class ToggleFavoriteTest(TestCase):
2✔
505
    @classmethod
2✔
506
    def setUpTestData(cls):
2✔
507
        cls.user = CustomUser.objects.create_user(
×
508
            username="favuser",
509
            email="favuser@nyu.edu",
510
            password="testpass123",
511
            user_type=CustomUser.USER,
512
        )
513
        cls.listing = Rental_Listings.objects.create(
×
514
            address="123 Fav St", price=1500.00, baths=1, Landlord=cls.user
515
        )
516

517
    # def test_toggle_favorite_add(self):
518
    #     self.client.login(username='favuser', password='testpass123')
519
    #     response = self.client.post(reverse('toggle_favorite'), json.dumps({'listing_id': self.listing.id}), content_type='application/json')
520
    #     self.assertEqual(response.status_code, 400)
521
    #     self.assertTrue(Favorite.objects.filter(user=self.user, listing=self.listing).exists())
522

523

524
class LandlordUserPageAccessTest(TestCase):
2✔
525
    @classmethod
2✔
526
    def setUpTestData(cls):
2✔
UNCOV
527
        cls.landlord_user = CustomUser.objects.create_user(
1✔
528
            username="landlorduser",
529
            email="landlorduser@nyu.edu",
530
            password="testpass123",
531
            user_type=CustomUser.LANDLORD,
532
        )
UNCOV
533
        cls.user = CustomUser.objects.create_user(
1✔
534
            username="normaluser",
535
            email="normaluser@nyu.edu",
536
            password="testpass123",
537
            user_type=CustomUser.USER,
538
        )
539

540
    def test_landlord_accessing_user_page(self):
2✔
UNCOV
541
        self.client.login(username="landlorduser", password="testpass123")
1✔
UNCOV
542
        response = self.client.get(reverse("user_homepage"))
1✔
UNCOV
543
        self.assertNotEqual(response.status_code, 200)
1✔
544

545
    def test_user_accessing_landlord_page(self):
2✔
UNCOV
546
        self.client.login(username="normaluser", password="testpass123")
1✔
UNCOV
547
        response = self.client.get(reverse("landlord_homepage"))
1✔
UNCOV
548
        self.assertNotEqual(response.status_code, 200)
1✔
549

550

551
class ListingDetailViewTest(TestCase):
2✔
552
    def setUp(self):
2✔
UNCOV
553
        self.client = Client()
1✔
UNCOV
554
        self.user = User.objects.create_user(username="testuser", password="password")
1✔
UNCOV
555
        self.client.login(username="testuser", password="password")
1✔
556

UNCOV
557
        self.listing = Rental_Listings.objects.create(
1✔
558
            address="123 Main St",
559
            beds=2,
560
            baths=2,
561
            price=2000,
562
            borough="Brooklyn",
563
            neighborhood="Park Slope",
564
            sq_ft=1000,
565
            Availability_Date="2024-04-03",
566
            latitude=40.1234,
567
            longitude=-73.5678,
568
        )
569

570
    # def test_listing_detail_view(self):
571
    #     response = self.client.get(
572
    #         reverse("listing_detail", kwargs={"listing_id": self.listing.pk})
573
    #     )
574
    #     self.assertEqual(response.status_code, 200)
575
    #     self.assertContains(response, self.listing.address)
576
    #     self.assertContains(response, self.listing.beds)
577
    #     self.assertContains(response, self.listing.baths)
578

579
    def test_toggle_favorite_ajax(self):
2✔
UNCOV
580
        response = self.client.post(
1✔
581
            reverse("toggle_favorite"), {"listing_id": self.listing.pk}
582
        )
UNCOV
583
        self.assertEqual(response.status_code, 200)
1✔
584

585
    def test_listing_detail_not_found(self):
2✔
UNCOV
586
        non_existent_listing_id = 99999  # Assuming this ID does not exist
1✔
UNCOV
587
        response = self.client.get(
1✔
588
            reverse("listing_detail", kwargs={"listing_id": non_existent_listing_id})
589
        )
UNCOV
590
        self.assertEqual(response.status_code, 302)
1✔
591

592

593
# class InitTestCase(TestCase):
594
#     def test_default_settings(self):
595
#         # Do not set ENV_NAME or set it to a value other than "prod" or "develop"
596
#         from rent_wise_nyc import settings
597
#         # Assert that settings imported from local.py are correctly applied
598
#         self.assertEqual(settings.ALLOWED_HOSTS, ["127.0.0.1"])
599

600

601
class ManagePyTestCase(unittest.TestCase):
2✔
602
    @patch.dict(os.environ, {"DJANGO_SETTINGS_MODULE": "rent_wise_nyc.settings"})
2✔
603
    @patch("django.core.management.execute_from_command_line")
2✔
604
    def test_main_success(self, mock_execute_from_command_line):
2✔
UNCOV
605
        from manage import main
1✔
606

UNCOV
607
        main()
1✔
UNCOV
608
        mock_execute_from_command_line.assert_called_once_with(sys.argv)
1✔
609

610
    @patch("django.core.management.execute_from_command_line", side_effect=ImportError)
2✔
611
    def test_main_import_error(self, mock_execute_from_command_line):
2✔
UNCOV
612
        from manage import main
1✔
613

UNCOV
614
        with self.assertRaises(ImportError):
1✔
UNCOV
615
            main()
1✔
616

617

618
class ProfileUpdateTestCase(TestCase):
2✔
619
    def setUp(self):
2✔
620
        # Create a test user
UNCOV
621
        self.user = CustomUser.objects.create_user(
1✔
622
            username="testuser",
623
            email="test@example.com",
624
            password="testpassword123",
625
            user_type="user",
626
        )
UNCOV
627
        self.client.login(username="testuser", password="testpassword123")
1✔
628

629
    def test_profile_update_form_loads_correctly(self):
2✔
630
        """Test that the profile update form loads with the correct initial data."""
UNCOV
631
        response = self.client.get(reverse("profile_view_edit"))
1✔
UNCOV
632
        self.assertEqual(response.status_code, 200)
1✔
UNCOV
633
        self.assertContains(
1✔
634
            response, 'value="test@example.com"'
635
        )  # Check for pre-filled email
UNCOV
636
        self.assertContains(
1✔
637
            response, 'value="testuser"'
638
        )  # Check for pre-filled username
639

640
    def test_unauthenticated_access_redirects_to_login(self):
2✔
641
        """Test that unauthenticated users are redirected to the login page."""
UNCOV
642
        self.client.logout()  # Log out to test unauthenticated access
1✔
UNCOV
643
        response = self.client.get(reverse("profile_view_edit"))
1✔
UNCOV
644
        self.assertRedirects(
1✔
645
            response, f"/accounts/login/?next={reverse('profile_view_edit')}"
646
        )
647

648
    def test_successful_profile_update(self):
2✔
649
        """Test submitting the form with valid data updates the user's profile."""
UNCOV
650
        data = {
1✔
651
            "full_name": "Test User",
652
            "phone_number": 9876543211,
653
            "city": "New York",
654
        }
UNCOV
655
        response = self.client.post(reverse("profile_view_edit"), data)
1✔
UNCOV
656
        self.assertEqual(response.status_code, 302)
1✔
UNCOV
657
        self.user.refresh_from_db()
1✔
UNCOV
658
        self.assertEqual(self.user.full_name, "Test User")
1✔
UNCOV
659
        messages = [msg.message for msg in get_messages(response.wsgi_request)]
1✔
UNCOV
660
        self.assertIn("Your profile was successfully updated!", messages)
1✔
661

662
    def test_invalid_form_submission(self):
2✔
663
        """Test that invalid form submissions are handled correctly."""
UNCOV
664
        data = {
1✔
665
            "full_name": "",
666
        }
UNCOV
667
        response = self.client.post(reverse("profile_view_edit"), data)
1✔
UNCOV
668
        self.assertEqual(response.status_code, 200)  # Page reloads with form errors
1✔
UNCOV
669
        self.assertFormError(response, "form", "full_name", "This field is required.")
1✔
670

671

672
class LandlordProfileUpdateTestCase(TestCase):
2✔
673
    def setUp(self):
2✔
674
        # Create a test user
UNCOV
675
        self.user = CustomUser.objects.create_user(
1✔
676
            username="testlandlord",
677
            email="test@example.com",
678
            password="testpassword123",
679
            user_type="landlord",
680
        )
UNCOV
681
        self.client.login(username="testlandlord", password="testpassword123")
1✔
682

683
    def test_profile_update_form_loads_correctly(self):
2✔
684
        """Test that the profile update form loads with the correct initial data."""
UNCOV
685
        response = self.client.get(reverse("landlord_profile_update"))
1✔
UNCOV
686
        self.assertEqual(response.status_code, 200)
1✔
UNCOV
687
        self.assertContains(
1✔
688
            response, 'value="test@example.com"'
689
        )  # Check for pre-filled email
UNCOV
690
        self.assertContains(
1✔
691
            response, 'value="testlandlord"'
692
        )  # Check for pre-filled username
693

694
    def test_unauthenticated_access_redirects_to_login(self):
2✔
695
        """Test that unauthenticated users are redirected to the login page."""
UNCOV
696
        self.client.logout()  # Log out to test unauthenticated access
1✔
UNCOV
697
        response = self.client.get(reverse("landlord_profile_update"))
1✔
UNCOV
698
        self.assertRedirects(
1✔
699
            response, f"/accounts/login/?next={reverse('landlord_profile_update')}"
700
        )
701

702
    def test_successful_profile_update(self):
2✔
703
        """Test submitting the form with valid data updates the user's profile."""
UNCOV
704
        data = {
1✔
705
            "full_name": "Test Landlord",
706
            "phone_number": 9876543211,
707
            "city": "New York",
708
        }
UNCOV
709
        response = self.client.post(reverse("landlord_profile_update"), data)
1✔
UNCOV
710
        self.assertEqual(response.status_code, 302)
1✔
UNCOV
711
        self.user.refresh_from_db()
1✔
UNCOV
712
        self.assertEqual(self.user.full_name, "Test Landlord")
1✔
UNCOV
713
        messages = [msg.message for msg in get_messages(response.wsgi_request)]
1✔
UNCOV
714
        self.assertIn("Your profile was successfully updated!", messages)
1✔
715

716
    def test_invalid_form_submission(self):
2✔
717
        """Test that invalid form submissions are handled correctly."""
UNCOV
718
        data = {
1✔
719
            "full_name": "",
720
        }
UNCOV
721
        response = self.client.post(reverse("landlord_profile_update"), data)
1✔
UNCOV
722
        self.assertEqual(response.status_code, 200)  # Page reloads with form errors
1✔
UNCOV
723
        self.assertFormError(response, "form", "full_name", "This field is required.")
1✔
724

725

726
class RentalListingsFormTests(TestCase):
2✔
727
    def setUp(self):
2✔
UNCOV
728
        self.user = CustomUser.objects.create_user(
1✔
729
            username="testuser", email="test@nyu.edu", password="testpass123"
730
        )
731

UNCOV
732
        self.common_data = {
1✔
733
            "address": "123 Main St",
734
            "zipcode": "10001",
735
            "price": 1500,
736
            "sq_ft": 500,
737
            "rooms": 3,
738
            "beds": 2,
739
            "baths": 1.5,
740
            "unit_type": "Apartment",
741
            "neighborhood": "Midtown",
742
            "borough": "Manhattan",
743
            "broker_fee": False,
744
            "central_air_conditioning": True,
745
            "dishwasher": True,
746
            "doorman": False,
747
            "elevator": True,
748
            "furnished": False,
749
            "parking_available": True,
750
            "washer_dryer_in_unit": False,
751
            "Submitted_date": date.today(),
752
            "Availability_Date": date.today() + timedelta(days=10),
753
        }
754

755
    def test_form_with_valid_data(self):
2✔
UNCOV
756
        form = RentalListingForm(data=self.common_data)
1✔
757

758
    def test_form_with_negative_price(self):
2✔
UNCOV
759
        data = self.common_data.copy()
1✔
UNCOV
760
        data["price"] = -100
1✔
UNCOV
761
        form = RentalListingForm(data=data)
1✔
UNCOV
762
        self.assertFalse(form.is_valid())
1✔
UNCOV
763
        self.assertIn("price", form.errors)
1✔
UNCOV
764
        self.assertEqual(form.errors["price"], ["Price cannot be negative."])
1✔
765

766
    def test_form_with_invalid_zipcode(self):
2✔
UNCOV
767
        data = self.common_data.copy()
1✔
UNCOV
768
        data["zipcode"] = "123"
1✔
UNCOV
769
        form = RentalListingForm(data=data)
1✔
UNCOV
770
        self.assertFalse(form.is_valid())
1✔
UNCOV
771
        self.assertIn("zipcode", form.errors)
1✔
UNCOV
772
        self.assertEqual(
1✔
773
            form.errors["zipcode"], ["Please enter a valid 5-digit zip code."]
774
        )
775

776
    def test_form_with_invalid_availability_date(self):
2✔
UNCOV
777
        data = self.common_data.copy()
1✔
UNCOV
778
        data["Availability_Date"] = date.today() - timedelta(days=1)
1✔
UNCOV
779
        form = RentalListingForm(data=data)
1✔
UNCOV
780
        self.assertFalse(form.is_valid())
1✔
UNCOV
781
        self.assertIn("Availability_Date", form.errors)
1✔
UNCOV
782
        self.assertEqual(
1✔
783
            form.errors["Availability_Date"],
784
            ["The availability date cannot be in the past."],
785
        )
786

787
    def test_form_with_rooms_less_than_beds(self):
2✔
UNCOV
788
        data = self.common_data.copy()
1✔
UNCOV
789
        data["rooms"] = 1
1✔
UNCOV
790
        data["beds"] = 2
1✔
UNCOV
791
        form = RentalListingForm(data=data)
1✔
UNCOV
792
        self.assertFalse(form.is_valid())
1✔
793

794
    def test_form_with_large_address(self):
2✔
UNCOV
795
        data = self.common_data.copy()
1✔
UNCOV
796
        data["address"] = "x" * 256
1✔
UNCOV
797
        form = RentalListingForm(data=data)
1✔
UNCOV
798
        self.assertFalse(form.is_valid())
1✔
799

800

801
class TestApplyFilters(TestCase):
2✔
802
    def setUp(self):
2✔
803
        # Creating test listings
UNCOV
804
        self.listing1 = Rental_Listings.objects.create(
1✔
805
            neighborhood="Manhattan",
806
            borough="Manhattan",
807
            price=2000,
808
            beds=2,
809
            baths=1,
810
            elevator=True,
811
            washer_dryer_in_unit=False,
812
            broker_fee=0,
813
            unit_type="Apartment",
814
            address="123 Main Street",
815
        )
UNCOV
816
        self.listing2 = Rental_Listings.objects.create(
1✔
817
            neighborhood="Brooklyn",
818
            borough="Brooklyn",
819
            price=1500,
820
            beds=1,
821
            baths=1,
822
            elevator=False,
823
            washer_dryer_in_unit=True,
824
            broker_fee=500,
825
            unit_type="House",
826
            address="124 Main Street",
827
        )
UNCOV
828
        self.listing3 = Rental_Listings.objects.create(
1✔
829
            neighborhood="Queens",
830
            borough="Queens",
831
            price=1000,
832
            beds=3,
833
            baths=2,
834
            elevator=True,
835
            washer_dryer_in_unit=True,
836
            broker_fee=300,
837
            unit_type="Apartment",
838
            address="125 Main Street",
839
        )
840

841
    def test_filter_by_borough(self):
2✔
UNCOV
842
        filter_params = {"borough": "Manhattan"}
1✔
UNCOV
843
        filtered_listings = apply_filters(Rental_Listings.objects.all(), filter_params)
1✔
UNCOV
844
        self.assertTrue(self.listing1 in filtered_listings)
1✔
UNCOV
845
        self.assertFalse(self.listing2 in filtered_listings)
1✔
UNCOV
846
        self.assertFalse(self.listing3 in filtered_listings)
1✔
847

848
    def test_filter_by_price_range(self):
2✔
UNCOV
849
        filter_params = {"min_price": 1200, "max_price": 2500}
1✔
UNCOV
850
        filtered_listings = apply_filters(Rental_Listings.objects.all(), filter_params)
1✔
UNCOV
851
        self.assertTrue(self.listing1 in filtered_listings)
1✔
UNCOV
852
        self.assertTrue(self.listing2 in filtered_listings)
1✔
UNCOV
853
        self.assertFalse(self.listing3 in filtered_listings)
1✔
854

855
    def test_filter_by_bedrooms(self):
2✔
UNCOV
856
        filter_params = {"bedrooms": "2"}
1✔
UNCOV
857
        filtered_listings = apply_filters(Rental_Listings.objects.all(), filter_params)
1✔
UNCOV
858
        self.assertTrue(self.listing1 in filtered_listings)
1✔
UNCOV
859
        self.assertFalse(self.listing2 in filtered_listings)
1✔
860

861
    def test_filter_by_elevator(self):
2✔
UNCOV
862
        filter_params = {"elevator": True}
1✔
UNCOV
863
        filtered_listings = apply_filters(Rental_Listings.objects.all(), filter_params)
1✔
UNCOV
864
        self.assertTrue(self.listing1 in filtered_listings)
1✔
UNCOV
865
        self.assertFalse(self.listing2 in filtered_listings)
1✔
UNCOV
866
        self.assertTrue(self.listing3 in filtered_listings)
1✔
867

868
    def test_no_filters(self):
2✔
UNCOV
869
        filter_params = {}
1✔
UNCOV
870
        filtered_listings = apply_filters(Rental_Listings.objects.all(), filter_params)
1✔
UNCOV
871
        self.assertEqual(len(filtered_listings), 3)
1✔
872

873
    def test_filter_no_fee(self):
2✔
UNCOV
874
        filter_params = {"no_fee": True}
1✔
UNCOV
875
        filtered_listings = apply_filters(Rental_Listings.objects.all(), filter_params)
1✔
UNCOV
876
        self.assertIn(
1✔
877
            self.listing1, filtered_listings
878
        )  # Assuming listing1 has no broker fee
UNCOV
879
        self.assertNotIn(
1✔
880
            self.listing2, filtered_listings
881
        )  # Assuming listing2 has a broker fee
882

883
    def test_filter_laundry(self):
2✔
UNCOV
884
        filter_params = {"laundry": True}
1✔
UNCOV
885
        filtered_listings = apply_filters(Rental_Listings.objects.all(), filter_params)
1✔
UNCOV
886
        self.assertNotIn(
1✔
887
            self.listing1, filtered_listings
888
        )  # Assuming listing1 does not have laundry
UNCOV
889
        self.assertIn(self.listing2, filtered_listings)  # Assuming listing2 has laundry
1✔
890

891
    def test_filter_building_type(self):
2✔
UNCOV
892
        filter_params = {"building_type": "Apartment"}
1✔
UNCOV
893
        filtered_listings = apply_filters(Rental_Listings.objects.all(), filter_params)
1✔
UNCOV
894
        self.assertIn(self.listing1, filtered_listings)
1✔
UNCOV
895
        self.assertNotIn(self.listing2, filtered_listings)
1✔
896

897
    def test_filter_parking(self):
2✔
UNCOV
898
        filter_params = {"parking": True}
1✔
UNCOV
899
        filtered_listings = apply_filters(Rental_Listings.objects.all(), filter_params)
1✔
900

901
    def test_filter_search_query(self):
2✔
UNCOV
902
        filter_params = {"search_query": "Main Street"}
1✔
UNCOV
903
        filtered_listings = apply_filters(Rental_Listings.objects.all(), filter_params)
1✔
UNCOV
904
        pass
1✔
905

906
    def test_filter_bathrooms(self):
2✔
UNCOV
907
        filter_params = {"bathrooms": "Any"}
1✔
UNCOV
908
        filtered_listings = apply_filters(Rental_Listings.objects.all(), filter_params)
1✔
UNCOV
909
        self.assertEqual(len(filtered_listings), Rental_Listings.objects.count())
1✔
UNCOV
910
        filter_params = {"bathrooms": "1"}
1✔
UNCOV
911
        filtered_listings = apply_filters(Rental_Listings.objects.all(), filter_params)
1✔
912

913

914
class EditRentalListingViewTestCase(TestCase):
2✔
915
    def setUp(self):
2✔
NEW
916
        self.user = CustomUser.objects.create_user(
1✔
917
            username="landlord_user", password="password", user_type=CustomUser.LANDLORD
918
        )
NEW
919
        self.client.force_login(self.user)
1✔
NEW
920
        self.rental_listing = Rental_Listings.objects.create(
1✔
921
            Landlord=self.user,
922
            address="Test Address",
923
            price=1000,
924
            baths=2,
925
            beds=1,
926
            rooms=4,
927
        )
928

929
    def test_edit_rental_listing_view_get(self):
2✔
NEW
930
        response = self.client.get(
1✔
931
            reverse("edit_rental_listing", args=[self.rental_listing.id])
932
        )
NEW
933
        self.assertEqual(response.status_code, 200)
1✔
NEW
934
        self.assertTemplateUsed(response, "edit_rental_listing.html")
1✔
935

936

937
class DeleteRentalListingViewTestCase(TestCase):
2✔
938
    def setUp(self):
2✔
NEW
939
        self.user = CustomUser.objects.create_user(
×
940
            username="landlord_user", password="password", user_type=CustomUser.LANDLORD
941
        )
NEW
942
        self.client.force_login(self.user)
×
NEW
943
        self.rental_listing = Rental_Listings.objects.create(
×
944
            Landlord=self.user,
945
            address="Test Address",
946
            price=1000,
947
            baths=2,
948
            beds=1,
949
            rooms=4,
950
        )
951

952

953
class LandlordProfileUpdateViewTestCase(TestCase):
2✔
954
    def setUp(self):
2✔
NEW
955
        self.user = CustomUser.objects.create_user(
1✔
956
            username="landlord_user", password="password", user_type=CustomUser.LANDLORD
957
        )
NEW
958
        self.client.force_login(self.user)
1✔
959

960
    def test_landlord_profile_update_view_get(self):
2✔
NEW
961
        response = self.client.get(reverse("landlord_profile_update"))
1✔
NEW
962
        self.assertEqual(response.status_code, 200)
1✔
NEW
963
        self.assertTemplateUsed(response, "users/Profile/landlord_profile_update.html")
1✔
NEW
964
        self.assertIsInstance(response.context["form"], CustomUserEditForm)
1✔
NEW
965
        self.assertEqual(response.context["user"], self.user)
1✔
966

967

968
class AddRentalListingViewTestCase(TestCase):
2✔
969
    def setUp(self):
2✔
NEW
970
        self.factory = RequestFactory()
1✔
NEW
971
        self.user = CustomUser.objects.create_user(
1✔
972
            username="landlord_user", password="password", user_type=CustomUser.LANDLORD
973
        )
NEW
974
        self.user.user_type = (
1✔
975
            "landlord"  # Assuming you have a custom user model with a user_type field
976
        )
NEW
977
        self.client.force_login(self.user)
1✔
978

979
    def test_add_rental_listing_view_get(self):
2✔
NEW
980
        request = self.factory.get(reverse("post_new_listings"))
1✔
NEW
981
        request.user = self.user
1✔
NEW
982
        response = add_rental_listing(request)
1✔
983

984
    def test_add_rental_listing_view_post(self):
2✔
NEW
985
        post_data = {
1✔
986
            "address": "Test Address",
987
            "price": 1000,
988
            "baths": 2,
989
            "beds": 1,
990
            "rooms": 4,
991
        }
NEW
992
        request = self.factory.post(reverse("post_new_listings"), post_data)
1✔
NEW
993
        request.user = self.user
1✔
NEW
994
        response = add_rental_listing(request)
1✔
NEW
995
        self.assertEqual(response.status_code, 200)  # Redirect expected
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc