tests.py 37.9 KB
Newer Older
1
from django.conf import settings
2
from django.test import SimpleTestCase, Client, tag
3
4
from test_plus.test import TestCase, CBVTestCase
from django.urls import reverse, resolve
5
from anonticket.models import UserIdentifier, Project, Issue
6
7
from django.contrib.auth.models import User, Group, Permission
# from django.views.generic import TemplateView, DetailView, CreateView, UpdateView
8
from anonticket.views import *
9
10
11
12
13
from anonticket.forms import (
    LoginForm, 
    Anonymous_Ticket_Base_Search_Form,
    Anonymous_Ticket_Project_Search_Form, 
    CreateIssueForm)
14
15
import pprint
pp = pprint.PrettyPrinter(indent=4)
ViolanteCodes's avatar
ViolanteCodes committed
16
17

# Create your tests here.
ViolanteCodes's avatar
ViolanteCodes committed
18

ViolanteCodes's avatar
ViolanteCodes committed
19
# Note: If you run tests with --tag prefix, you can test a small suite
ViolanteCodes's avatar
ViolanteCodes committed
20
21
22
23
# of tests with one of the tags below (registered with '@tag'.)
#   Examples:
#   $ python manage.py test --tag url 
#   (or with coverage) $ coverage run manage.py --tag url.)
ViolanteCodes's avatar
ViolanteCodes committed
24

25
26
27
28
# ---------------------------URL TESTS----------------------------------
# URL Tests using Django SimpleTestCase (no need for database.)
# ----------------------------------------------------------------------

29
@tag('urls')
30
31
class TestUrls(SimpleTestCase):
    """Test that the URLS in the anonticket resolve."""
32
33
34
    def setUp(self):
        self.new_user = 'duo-atlas-hypnotism-curry-creatable-rubble'
        self.project_slug = 'a-project-slug'
35
36
37
38
39

    def test_home_url_is_resolved(self):
        """Test the 'home' URL."""
        url = reverse('home')
        self.assertEqual(resolve(url).func.view_class, TemplateView)
40
  
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    def test_create_identifier_url_is_resolved(self):
        """Test the 'create-identifier' URL."""
        url = reverse('create-identifier')
        self.assertEqual(resolve(url).func.view_class, CreateIdentifierView)

    def test_login_url_is_resolved(self):
        """Test the 'login' URL."""
        url = reverse('login')
        self.assertEqual(resolve(url).func, login_view)

    def test_user_login_error_url_is_resolved(self):
        """Test the 'user-login-error URL."""
        url = reverse('user-login-error', args=["bad-identifier"])
        self.assertEqual(resolve(url).func.view_class, UserLoginErrorView)

56
57
58
59
60
61
    def test_create_note_url_is_resolved(self):
        """Test the 'create-note' URL."""
        url = reverse('create-note', args=[
            self.new_user, self.project_slug, 1
        ])
        self.assertEqual(resolve(url).func.view_class, NoteCreateView)
62
63
64
65
66
67
68
69

    def test_issue_detail_view_is_resolved(self):
        """Test the 'issue-detail-view' URL."""
        url = reverse('issue-detail-view', args=[
            'duo-atlas-hypnotism-curry-creatable-rubble',
            740, 1])
        self.assertEqual(resolve(url).func, issue_detail_view)

70
71
72
73
74
75
76
    def test_pending_issue_detail_view_is_resolved(self):
        """Test the 'pending-issue-detail-view' URL."""
        url = reverse('pending-issue-detail-view', args = [
            'duo-atlas-hypnotism-curry-creatable-rubble',
            747, 
            13])
        self.assertEqual(resolve(url).func.view_class, PendingIssueDetailView)
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

    def test_issue_search_url_is_resolved(self):
        """Test the 'issue-search' URL."""
        url = reverse('issue-search', args = [
            self.new_user
        ])
        self.assertEqual(resolve(url).func, issue_search_view)

    def test_project_detail_view_url_is_resolved(self):
        """Test the 'project-detail' URL."""
        url = reverse('project-detail', args= [
            self.new_user, self.project_slug
        ])
        self.assertEqual(resolve(url).func.view_class, ProjectDetailView)

    def test_project_list_is_resolved(self):
        """Test the 'project-list' URL."""
        url = reverse('project-list', args=[
            self.new_user
        ])
        self.assertEqual(resolve(url).func.view_class, ProjectListView)

    def test_issue_created_url_is_resolved(self):
        """Test the 'issue-created' URL."""
        url = reverse('issue-created', args=['duo-atlas-hypnotism-curry-creatable-rubble'])
        self.assertEqual(resolve(url).func.view_class, IssueSuccessView)

    def test_create_issue_url_is_resolved(self):
        """Test the 'create-issue' URL."""
        url = reverse('create-issue', args=['duo-atlas-hypnotism-curry-creatable-rubble'])
        self.assertEqual(resolve(url).func, create_issue_view)
108
        
109
110
111
112
    def test_user_landing_url_is_resolved(self):
        """Test the 'user-landing' URL."""
        url = reverse('user-landing', args=['duo-atlas-hypnotism-curry-creatable-rubble'])
        self.assertEqual(resolve(url).func, user_landing_view)
113

114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
    def test_moderator_url_is_resolved(self):
        """Test the 'moderator' URL."""
        url  = reverse('moderator')
        self.assertEqual(resolve(url).func, moderator_view)

    def test_mod_update_issue_url_is_resolved(self):
        """Test the 'mod-update-issue' url."""
        url = reverse('mod-update-issue', args=[1])
        self.assertEqual(resolve(url).func.view_class, ModeratorIssueUpdateView)
    
    def test_mod_update_note_url_is_resolved(self):
        """Test the 'mod-update-note' url."""
        url = reverse('mod-update-note', args=[1])
        self.assertEqual(resolve(url).func.view_class, ModeratorNoteUpdateView)

129
# --------------------------VIEW TESTS----------------------------------
ViolanteCodes's avatar
ViolanteCodes committed
130
131
# Tests for views: (generally for status = 200, template correct,
# although some POST views also test for redirects, etc.
132
133
# ----------------------------------------------------------------------

134
@tag('id_no_db')
135
class TestIdentifierAndLoginViewsWithoutDatabase(SimpleTestCase):
136
    """Test the functions in views.py under the Identifier and Login
137
    views section that do not require database."""
ViolanteCodes's avatar
ViolanteCodes committed
138
139

    def setUp(self):
140
        # Create a user
141
        self.new_user = 'duo-atlas-hypnotism-curry-creatable-rubble'
142
143
144
145
        self.client = Client()
        self.home_url = reverse('home')
        self.create_identifier_url = reverse('create-identifier')
        self.login_url = reverse('login')
146
        self.user_landing_url = reverse('user-landing', args=[self.new_user])
147
        self.user_login_error_url = reverse('user-login-error', args=["bad-identifier"])
148

149
150
151
152
153
154
    def test_home_view_GET(self):
        """Test the response for home_view"""
        response = self.client.get(self.home_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/index.html')

ViolanteCodes's avatar
ViolanteCodes committed
155
156
157
158
159
    def test_create_identifier_view_GET(self):
        """Test the response for create_identifier_view"""
        response = self.client.get(self.create_identifier_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/create_identifier.html')
160
161
162
163
164
165
166
    
    def test_login_view_GET(self):
        """Test the response for login_view"""
        response = self.client.get(self.login_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/user_login.html')

167
    def test_login_view_GET_with_data(self):
168
169
170
171
172
173
174
175
176
177
178
        """Test the response for the login_view with data."""
        response = self.client.get(self.login_url, data={
            'word_1': 'duo',
            'word_2': 'atlas',
            'word_3': 'hypnotism',
            'word_4': 'curry',
            'word_5': 'creatable',
            'word_6': 'rubble',
        })
        self.assertEqual(response.status_code, 302)

179
    def test_user_landing_view_GET(self):
180
        """Test the response for user_landing_view with known good user_identifier."""
181
182
183
184
        response = self.client.get(self.user_landing_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/user_landing.html')

185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
    def test_user_landing_view_GET_seven_words(self):
        """Test the user_landing_view with a known bad identifier 
        (seven words) and verify decorator redirect"""
        too_many_words_url = reverse(
            'user-landing', args=[
                'duo-atlas-hypnotism-curry-creatable-rubble-brunch'])
        response = self. client.get(too_many_words_url)
        self.assertEqual(response.status_code, 302)
    
    def test_user_landing_view_GET_bad_word(self):
        """Test the user_landing_view with a known bad identifier 
        (wrong word) and verify decorator redirect"""
        too_many_words_url = reverse(
            'user-landing', args=[
                'duo-atlas-hypnotism-curry-creatable-moxie'])
        response = self. client.get(too_many_words_url)
        self.assertEqual(response.status_code, 302)

    def test_user_landing_view_GET_repeated_word(self):
        """Test the user_landing_view with a known bad identifier 
        (repeated word) and verify decorator redirect"""
206
        repeated_words_url = reverse(
207
208
            'user-landing', args=[
                'duo-atlas-hypnotism-curry-creatable-creatable'])
209
        response = self.client.get(repeated_words_url)
210
211
        self.assertEqual(response.status_code, 302)

212
213
214
215
216
217
    def test_user_login_error_view_GET(self):
        """Test the response for user_login_error view"""
        response = self.client.get(self.user_login_error_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/user_login_error.html')

218
@tag('id_with_db')
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
class TestIdentifierAndLoginViewsWithDatabase(TestCase):
    """ Test the functions in views.py under the Identifier and Login
    views section that require database."""

    def setUp(self):
        """Set up a project, user identifier, and issue in the test database."""
        # Setup project
        new_project = Project(gitlab_id=747)
        # Should fetch gitlab details on save.
        new_project.save()
        # Create a user
        new_user = UserIdentifier.objects.create(
            user_identifier = 'duo-atlas-hypnotism-curry-creatable-rubble'
        )
        # Create a pending issue.
        pending_issue = Issue.objects.create (
            title = 'A Pending Issue',
            linked_project = new_project,
            linked_user = new_user,
            description= 'A description of a pending issue'
        )
        # Create a posted issue.
        posted_issue = Issue.objects.create (  
            title = 'A posted issue',
            description = 'A posted issue description',
            linked_project = new_project,
            linked_user = new_user,
            gitlab_iid = 1,
            reviewer_status = 'A',
            posted_to_GitLab = True
        )
        self.client=Client()
        self.user_landing_url = reverse('user-landing', args=[new_user])

    def test_user_landing_view_GET_with_data(self):
        """Test the response for user_landing_view with known good user_identifier."""
        response = self.client.get(self.user_landing_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/user_landing.html')

259
@tag('project')
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
class TestProjectViews(TestCase):
    """Test the project functions in views.py"""

    def setUp(self):
        """Set up a project, user identifier, and issue in the test database."""
        # Setup project
        new_project = Project(gitlab_id=747)
        # Should fetch gitlab details on save.
        new_project.save()
        # Create a user
        new_user = UserIdentifier.objects.create(
            user_identifier = 'duo-atlas-hypnotism-curry-creatable-rubble'
        )
        self.client=Client()
        self.project_list_view_url = reverse('project-list', args=[new_user])
        self.project_detail_view_url = reverse('project-detail', args=[
            new_user, new_project.slug])
        self.new_user = new_user
    
    def test_project_list_GET(self):
        """Test the response for the ProjectListView"""
        response = self.client.get(self.project_list_view_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/project_list.html')

    def test_project_detail_GET(self):
        """Test the response for the ProjectDetailView"""
        response = self.client.get(self.project_detail_view_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/project_detail.html')

291
@tag('issues')
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
class TestIssuesViews(TestCase):
    """Test the issues functions in views.py"""

    def setUp(self):
        """Set up a project, user identifier, and issue in the test database."""
        # Setup project
        new_project = Project(gitlab_id=747)
        # Should fetch gitlab details on save.
        new_project.save()
        # Create a user
        new_user = UserIdentifier.objects.create(
            user_identifier = 'duo-atlas-hypnotism-curry-creatable-rubble'
        )
        # Create a pending issue.
        pending_issue = Issue.objects.create (
            title = 'A Pending Issue',
            linked_project = new_project,
            linked_user = new_user,
            description= 'A description of a pending issue'
        )
        # Create a posted issue.
        posted_issue = Issue.objects.create (  
            title = 'A posted issue',
            description = 'A posted issue description',
            linked_project = new_project,
            linked_user = new_user,
            gitlab_iid = 1,
            reviewer_status = 'A',
            posted_to_GitLab = True
        )
        self.client=Client()
        self.create_issue_url = reverse('create-issue', args=[new_user])
        self.issue_success_url =  reverse('issue-created', args=[new_user])
        self.pending_issue_url =  reverse('pending-issue-detail-view', args = [
            new_user, new_project.slug, pending_issue.pk])
        self.issue_detail_url = reverse('issue-detail-view', args=[
            new_user, new_project.slug, posted_issue.gitlab_iid])
329
        self.issue_search_url = reverse('issue-search', args=[new_user])
330
        self.new_user = new_user
331
        self.project = new_project
332

333
334
335
336
337
338
    def test_create_issue_GET(self):
        """Test the response for create_issue view"""
        response = self.client.get(self.create_issue_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/create_new_issue.html')

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
    def test_create_issue_POST_current_user(self):
        """Test the response for create_issue view with a current user."""
        form_data = {
            'linked_project': self.project.pk,
            'title':'A new descriptive issue title',
            'description': 'Yet another description of the issue.'
        }
        form=CreateIssueForm(form_data)
        expected_url = reverse('issue-created', args=[self.new_user])
        response = self.client.post(self.create_issue_url, form=form, data=form_data, follow=False)
        self.assertRedirects(response, expected_url)

    def test_create_issue_POST_new_user(self):
        """Test the response for create_issue view with a new user."""
        create_url = reverse('create-issue', args=[
            'autopilot-stunt-unfasten-dirtiness-wipe-blissful'
        ])
        form_data = {
            'linked_project': self.project.pk,
            'title':'A new descriptive issue title',
            'description': 'Yet another description of the issue.'
        }
        form=CreateIssueForm(form_data)
        expected_url = reverse('issue-created', args=[
            'autopilot-stunt-unfasten-dirtiness-wipe-blissful'])
        response = self.client.post(create_url, form=form, data=form_data, follow=False)
        self.assertRedirects(response, expected_url)
366

367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
    def test_issue_success_view_GET(self):
        """Test the response for IssueSuccessView"""
        response = self.client.get(self.issue_success_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/create_issue_success.html')
    
    def test_pending_issue_detail_view_GET(self):
        """Test the response for PendingIssueDetailView"""
        response = self.client.get(self.pending_issue_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/issue_pending.html')

    def test_issue_detail_view_GET(self):
        """Test the response for issue_detail_view"""
        response = self.client.get(self.issue_detail_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/issue_detail.html')
ViolanteCodes's avatar
ViolanteCodes committed
384

ViolanteCodes's avatar
ViolanteCodes committed
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
    def test_issue_search_view_GET_valid_data(self):
        """Test the reponse for the issue_search_view"""
        url = reverse('issue-search', args=[self.new_user])
        form_data = {
            'choose_project': self.project.pk,
            'search_terms': 'issue'
        }
        response = self.client.get(url, form_data)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/issue_search.html')

    def test_issue_search_view_GET_invalid_data(self):
        """Test the response for the issue_search_view with no search_terms."""
        url = reverse('issue-search', args=[self.new_user])
        form_data = {
            'choose_project': self.project.pk,
        }
        response = self.client.get(url, form_data)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/issue_search.html')

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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
    def test_issue_search_view_GET_no_matches(self):
        """Test the reponse for the issue_search_view"""
        url = reverse('issue-search', args=[self.new_user])
        form_data = {
            'choose_project': self.project.pk,
            'search_terms': 'i-dont-match-anything'
        }
        response = self.client.get(url, form_data)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/issue_search.html')  

@tag('notes')
class TestNotesViews(TestCase):
    """Test the notes functions in views.py."""

    def setUp(self):
        """Set up a project, user identifier, and issue in the test database."""
        # Setup project
        new_project = Project(gitlab_id=747)
        # Should fetch gitlab details on save.
        new_project.save()
        # Create a user
        new_user = UserIdentifier.objects.create(
            user_identifier = 'duo-atlas-hypnotism-curry-creatable-rubble'
        )
        # Create a pending issue.
        pending_issue = Issue.objects.create (
            title = 'A Pending Issue',
            linked_project = new_project,
            linked_user = new_user,
            description= 'A description of a pending issue'
        )
        # Create a posted issue.
        posted_issue = Issue.objects.create (  
            title = 'A posted issue',
            description = 'A posted issue description',
            linked_project = new_project,
            linked_user = new_user,
            gitlab_iid = 1,
            reviewer_status = 'A',
            posted_to_GitLab = True
        )
        self.client=Client()
        self.new_user = new_user
        self.project = new_project
        self.issue = posted_issue

    def test_note_create_view_POST_existing_user(self):
        """Test the note create view with valid data, with a 
        user that already exists."""
        url = reverse('create-note', args=[
            self.new_user, self.project.slug, self.issue.gitlab_iid])
        form_data = {
            'body': """A new note body."""
        }
        expected_url = reverse('issue-created', args=[self.new_user])
        response = self.client.post(url, form_data)
        self.assertRedirects(response, expected_url)

    def test_note_create_view_POST_new_user(self):
        """Test the note create view with valid_data, with a
        user that doesn't get exist."""
        new_user = 'autopilot-stunt-unfasten-dirtiness-wipe-blissful'
        url = reverse('create-note', args=[
            new_user, self.project.slug, self.issue.gitlab_iid])
        form_data = {
            'body': """A new note body."""
        }
        expected_url = reverse('issue-created', args=[new_user])
        response = self.client.post(url, form_data)
        self.assertRedirects(response, expected_url)

@tag('other_with_db')
479
480
481
482
483
484
485
486
487
488
class TestViewsOtherWithDatabase(TestCase):
    """Test the functions in views.py not directly related to one of the above
    that require a database."""

    def setUp(self):
        """Set up a project, user identifier, and issue in the test database."""
        new_user = UserIdentifier.objects.create(
            user_identifier = 'duo-atlas-hypnotism-curry-creatable-rubble'
        )
        self.new_user = new_user
489

490
491
    def test_user_identifier_in_database(self):
        """Test user_identifier_in_database function"""
492
        test_known_good_user = user_identifier_in_database(self.new_user.user_identifier)
493
494
495
496
497
        self.assertEqual(test_known_good_user, True)
        known_bad_user = 'test-test-test-test-test-test'
        test_known_bad_user = user_identifier_in_database(known_bad_user)
        self.assertEqual(test_known_bad_user, False)

498
@tag('other_no_db')
499
500
501
502
503
504
505
506
507
508
509
510
class TestViewsOtherWithoutDatabase(SimpleTestCase):
    """Test the functions in views.py not directly related to one of the above
    that do NOT require a database (simpletestcase)."""
    
    def test_get_wordlist(self):
        """Test get_wordlist function."""
        word_list_path = settings.WORD_LIST_PATH
        with open(word_list_path) as f:
            known_wordlist = f.read().splitlines()
        test_wordlist = get_wordlist()
        self.assertEqual(known_wordlist, test_wordlist)

511
512
    def test_generate_user_identifier_list(self):
        """Test the generate_user_identifier_list function from CreateIdentifierView."""
513
514
        word_list = get_wordlist()
        list_to_test = CreateIdentifierView.generate_user_identifier_list(self)
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
        for word in list_to_test:
            self.assertIn(word, word_list)
    
    def test_context_dict(self):
        """Tests the context_dict function from CreateIdentifierView."""
        words_to_test = [
            'word1',
            'word2',
            'word3',
            'word4',
            'word5',
            'word6',
        ]
        test_context = CreateIdentifierView.context_dict(self, word_list = words_to_test)
        known_context = {
            'chosen_words': words_to_test,            
            'user_identifier_string': 'word1-word2-word3-word4-word5-word6',
        }
        self.assertEqual(test_context, known_context)

    def test_get_context_data(self):
        """Tests the get_context_data function from CreateIdentifierView by verifying the 
        returned results is a dictionary with key['chosen_words'], value = list of 
        settings.DICE_ROLLS words, with all words from wordlist, and key['user_identifier_string'],
        the value of which contains all chosen words. Also asserts that key['user_found'] is 
        not returned (unique user.)"""
        word_list_path = settings.WORD_LIST_PATH
        with open(word_list_path) as f:
            known_wordlist = f.read().splitlines()
        test_create_identifier_view = CreateIdentifierView()
        test_get_context = test_create_identifier_view.get_context_data()
        self.assertTrue(len(test_get_context['chosen_words']) == settings.DICE_ROLLS)
        for word in test_get_context['chosen_words']:
            self.assertIn(word, known_wordlist)
            self.assertIn(word, test_get_context['user_identifier_string'])
        self.assertNotIn('user_found', test_get_context.keys())

ViolanteCodes's avatar
ViolanteCodes committed
552
# --------------------------FORM TESTS----------------------------------
ViolanteCodes's avatar
ViolanteCodes committed
553
554
# Tests for forms.py: basic tests to see that form_is_valid(). Testing
# for integration with views, etc., is done in views.py above.
ViolanteCodes's avatar
ViolanteCodes committed
555
556
# ----------------------------------------------------------------------

557
@tag('login')
558
559
class TestLoginForm(SimpleTestCase):
    """Test the Login Form from forms.py."""
ViolanteCodes's avatar
ViolanteCodes committed
560

561
562
563
564
565
566
567
568
569
570
571
572
    def test_login_valid_data(self):
        """Test login form with valid data."""
        # duo-atlas-hypnotism-curry-creatable-rubble
        form = LoginForm(data = {
            'word_1': 'duo',
            'word_2': 'atlas',
            'word_3': 'hypnotism',
            'word_4': 'curry',
            'word_5': 'creatable',
            'word_6': 'rubble',
        })
        self.assertTrue(form.is_valid())
ViolanteCodes's avatar
ViolanteCodes committed
573
    
574
575
576
577
578
579
580
581
582
583
584
585
586
    def test_login_invalid_data(self):
        """Test login form with invalid data."""
        # duo-atlas-hypnotism-curry-creatable-rubble
        form = LoginForm(data = {
            'word_1': 'duo',
            'word_2': 'atlas',
            'word_3': 'hypnotism',
            'word_4': 'curry',
            'word_5': 'creatable',
        })
        self.assertFalse(form.is_valid())
        self.assertEquals(len(form.errors), 1)

587
@tag('search_form')
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
class TestAnonymousTicketProjectSearchForm(TestCase):
    """Test the Anonymous_Ticket_Project_Search_Form"""

    def setUp(self):
        # Setup project
        new_project = Project(gitlab_id=747)
        # Should fetch gitlab details on save.
        new_project.save()
        self.project = new_project

    def test_project_search_form_valid_data(self):
        """Test the Project Search Form with valid data."""
        form=Anonymous_Ticket_Project_Search_Form(data={
            'choose_project':self.project,
            'search_terms':'issue'
        })
        self.assertTrue(form.is_valid())

    def test_project_search_form_invalid_data(self):
        """Test the Project Search Form with valid data."""
        form=Anonymous_Ticket_Project_Search_Form(data={
        })
        self.assertFalse(form.is_valid())
        self.assertEquals(len(form.errors), 2)

613
@tag('create_issue_form')
614
615
616
617
618
619
620
621
622
class TestCreateIssueForm(TestCase):
    """Test the CreateIssueForm"""

    def setUp(self):
        # Setup project
        new_project = Project(gitlab_id=747)
        # Should fetch gitlab details on save.
        new_project.save()
        self.project = new_project
623
624
625
626
627
628
        new_user = UserIdentifier.objects.create(
            user_identifier = 'duo-atlas-hypnotism-curry-creatable-rubble'
        )
        self.new_user = new_user
        self.create_issue_url = reverse('create-issue', args=[new_user])
        client=Client()
629
630
631

    def test_create_issue_form_valid_data(self):
        """Test the Project Search Form with valid data."""
632
        form_data = {
633
634
635
            'linked_project': self.project,
            'title':'A descriptive issue title',
            'description': 'A description of the issue.'
636
637
        }
        form=CreateIssueForm(form_data)
638
639
640
641
642
643
644
645
646
        self.assertTrue(form.is_valid())

    def test_create_issue_form_invalid_data(self):
        """Test the Project Search Form with valid data."""
        form=CreateIssueForm(data={
        })
        self.assertFalse(form.is_valid())
        self.assertEquals(len(form.errors), 3)

647
648
649
650
651
652
653
654
655
656
657
658
659
# ---------------------MODERATOR PORTAL TESTS---------------------------
# Tests for views, etc. associated with the moderator panel.
# ----------------------------------------------------------------------

@tag('moderators')
class TestModeratorViews(TestCase):
    """Test the Views associated with Moderators."""

    def setUp(self):
        # Set Up Moderators group using the create_groups.py file. This
        # will allow test group permissions to exactly match those from file.
        from anonticket.management.commands.create_groups import GROUPS
        from anonticket.management.commands.create_groups import Command as create_groups
660
661
        # Add a bad permission call so that you can test this part of the code.
        GROUPS["Account Approvers"]["user identifier"].append("smash")
662
663
        create_groups.handle(create_groups)
        self.Moderators = Group.objects.get(name="Moderators")
664
        self.AccountApprovers = Group.objects.get(name="Account Approvers")
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689

        # Set up users to test the staff decorator and is_mod decorator.
        UserStaffNoGroup = User.objects.create(
            username='UserStaffNoGroup', 
            password='IAmATestPassword',
            is_staff=True
        )
        self.UserStaffNoGroup = UserStaffNoGroup

        UserGroupNoStaff = User.objects.create(
            username='UserGroupNoStaff', 
            password='IAmATestPassword',
            is_staff=False,
        )
        self.UserGroupNoStaff = UserGroupNoStaff
        self.Moderators.user_set.add(UserGroupNoStaff)

        UserGroupAndStaff = User.objects.create(
            username='UserGroupAndStaff', 
            password='IAmATestPassword',
            is_staff=True,
        )
        self.UserGroupAndStaff = UserGroupAndStaff
        self.Moderators.user_set.add(UserGroupAndStaff)

690
691
692
693
694
695
696
697
        UserAccountApprover = User.objects.create(
            username='UserAccountApprover', 
            password='IAmATestPassword',
            is_staff=True,
        )
        self.UserAccountApprover = UserAccountApprover
        self.AccountApprovers.user_set.add(UserAccountApprover)

698
        # set the login redirect url for views testing
699
        from anonticket.views import login_redirect_url as login_redirect_url
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
        self.login_redirect_url = login_redirect_url
        self.admin_url = '/tor_admin/'
    
    def test_moderators_created_successfully(self):
        """Test that there's a group called Moderators."""
        self.assertEqual(self.Moderators.name, "Moderators")

    def test_user_staff_no_group_created_successfully(self):
        """Check that the username exists, that the user is
        staff, and that the user is NOT part of the Moderators group."""
        self.assertEqual(self.UserStaffNoGroup.username, "UserStaffNoGroup")
        self.assertTrue(self.UserStaffNoGroup.is_staff)
        self.assertFalse(self.UserStaffNoGroup.groups.filter(name="Moderators").exists())

    def test_user_group_no_staff_created_successfully(self):
        """Test that the username exists, that the user is NOT staff, 
        and that the user IS part of the Moderators group."""
        self.assertEqual(self.UserGroupNoStaff.username, "UserGroupNoStaff")
        self.assertFalse(self.UserGroupNoStaff.is_staff)
        self.assertTrue(self.UserGroupNoStaff.groups.filter(name="Moderators").exists())

    def test_user_group_and_staff_created_successfully(self):
        """Test that the username exists, that the user IS staff, and that
        the user IS part of the Moderators group."""
        self.assertEqual(self.UserGroupAndStaff.username, "UserGroupAndStaff")
        self.assertTrue(self.UserGroupAndStaff.is_staff)
        self.assertTrue(self.UserGroupAndStaff.groups.filter(name="Moderators").exists())
727
728
729
730
731
732
733
734
735

    def test_user_account_approver_created_successfully(self):
        """Tese that the username exists, that the user is staff, and that
        the user is part of the Account Approvers group."""
        self.assertEqual(self.UserAccountApprover.username, "UserAccountApprover")
        self.assertTrue(self.UserAccountApprover.is_staff)
        self.assertTrue(
        self.UserAccountApprover.groups.filter(name="Account Approvers").exists())

736
737
738
739
740
741
742
743
744
745
    def test_moderator_view_GET_not_logged_in(self):
        """Test that the moderator view redirects to a login form
        if there is no logged in user."""
        url = reverse('moderator')
        response = self.client.get(url)
        self.assertRedirects(response, self.login_redirect_url)

    def test_moderator_view_GET_no_group(self):
        """Test that the moderator view redirects to the admin site 
        with no permissions if a user is logged in and a staff member 
746
747
748
749
750
751
752
        but is not part of the Moderators or Account Approvers Group."""
        current_user = self.UserStaffNoGroup
        self.client.force_login(current_user)
        url = reverse('moderator')
        response = self.client.get(url, follow=False)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, self.login_redirect_url)
753
754
        self.assertTemplateNotUsed(response, 'anonticket/moderator.html')

755
        # print(response)
756
757

    def test_moderator_view_GET_no_staff(self):
758
759
760
761
762
763
764
        """Test that the moderator view fails if a user has moderator
        permissions but is not staff."""
        current_user = self.UserGroupNoStaff
        self.client.force_login(current_user)
        url = reverse('moderator')
        response = self.client.get(url)
        self.assertTemplateNotUsed(response, 'anonticket/moderator.html')
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780

    def test_moderator_view_GET_account_approver(self):
        """Test that the moderator view loads if a user is an account
        approver."""
        current_user = self.UserAccountApprover
        self.client.force_login(current_user)
        url = reverse('moderator')
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        # Assert that the correct template loaded
        self.assertTemplateUsed(response, 'anonticket/moderator.html')
        # But that users in Account Approvers Group and not in Moderators
        # Group do not have access to pending issues.
        self.assertInHTML(
            "You do not have permission to view pending issues at this time.",
            '<p>You do not have permission to view pending issues at this time.</p>')
781

782
783
784
785
786
787
788
789
790
    def test_moderator_view_GET_valid_moderator(self):
        """Test that the moderator view displays correctly if
        the user has moderator permissions and is staff."""
        current_user = self.UserGroupAndStaff
        self.client.force_login(current_user)
        url = reverse('moderator')
        response = self.client.get(url, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'anonticket/moderator.html')
791

792
793
794
795
796
797
# --------------------------OTHER TESTS---------------------------------
# Tests for filters, custom template tags, etc.
# ----------------------------------------------------------------------

@tag('filters')
class TestFilters(SimpleTestCase):
798
799
    """Test custom filters."""
    
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
    def test_pretty_datetime_january(self):
        """Test the pretty_datetime filter for january."""
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-01-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
        self.assertEqual(pretty_iso_string, '19 January, 2020 - 14:09 UTC')

    def test_pretty_datetime_february(self):
        """Test the pretty_datetime filter for february."""
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-02-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
        self.assertEqual(pretty_iso_string, '19 February, 2020 - 14:09 UTC')
    
    def test_pretty_datetime_march(self):
        """Test the pretty_datetime filter for march."""
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-03-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
        self.assertEqual(pretty_iso_string, '19 March, 2020 - 14:09 UTC')

    def test_pretty_datetime_april(self):
        """Test the pretty_datetime filter for april."""
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-04-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
        self.assertEqual(pretty_iso_string, '19 April, 2020 - 14:09 UTC')

    def test_pretty_datetime_may(self):
        """Test the pretty_datetime filter for may."""
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-05-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
        self.assertEqual(pretty_iso_string, '19 May, 2020 - 14:09 UTC')

    def test_pretty_datetime_june(self):
        """Test the pretty_datetime filter for june."""
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-06-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
        self.assertEqual(pretty_iso_string, '19 June, 2020 - 14:09 UTC')

    def test_pretty_datetime_july(self):
        """Test the pretty_datetime filter for july."""
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-07-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
        self.assertEqual(pretty_iso_string, '19 July, 2020 - 14:09 UTC')

    def test_pretty_datetime_august(self):
        """Test the pretty_datetime filter for march."""
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-08-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
        self.assertEqual(pretty_iso_string, '19 August, 2020 - 14:09 UTC')

    def test_pretty_datetime_september(self):
        """Test the pretty_datetime filter for september."""
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-09-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
        self.assertEqual(pretty_iso_string, '19 September, 2020 - 14:09 UTC')
    
    def test_pretty_datetime_october(self):
        """Test the pretty_datetime filter for october."""
865
866
867
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-10-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
        self.assertEqual(pretty_iso_string, '19 October, 2020 - 14:09 UTC')

    def test_pretty_datetime_november(self):
        """Test the pretty_datetime filter for november."""
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-11-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
        self.assertEqual(pretty_iso_string, '19 November, 2020 - 14:09 UTC')
    
    def test_pretty_datetime_december(self):
        """Test the pretty_datetime filter for december."""
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-12-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
        self.assertEqual(pretty_iso_string, '19 December, 2020 - 14:09 UTC')

    def test_pretty_datetime_undefined_month(self):
        """Test the pretty_datetime filter for a bad month."""
        from shared.templatetags.custom_filters import pretty_datetime
        iso_test_string = "2020-13-19T14:09:46.500Z"
        pretty_iso_string = pretty_datetime(iso_test_string)
        self.assertEqual(pretty_iso_string, '19 undefined, 2020 - 14:09 UTC')