Repository navigation
Expand file tree
/
Copy pathtests.py
More file actions
2101 lines (1876 loc) · 94.9 KB
/
Copy pathtests.py
File metadata and controls
2101 lines (1876 loc) · 94.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
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
690
691
692
693
694
695
696
697
698
699
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import unittest
import os
import types
from importlib.machinery import SourceFileLoader
import werkzeug
import base64
import json
from io import BytesIO
from datetime import datetime, timedelta
from werkzeug.wrappers import Request
from werkzeug.test import EnvironBuilder, Client
from werkzeug.datastructures import MultiDict
from mock import Mock, patch
import conf
import time
import request_handler as handler
import captcha
import altcha
import rt
def setUpModule():
"""Give every test a configured captcha provider"""
# conf.py reads these from the environment, so a developer running the
# suite without them set would otherwise hit the startup check.
for name, value in (('TURNSTILE_SECRET', 'test-turnstile-secret'),
('ALTCHA_HMAC_KEY', 'test-altcha-key'),
('RECAPTCHA_SECRET', 'test-recaptcha-secret'),
('CAPTCHA_ALLOWED_HOSTNAMES', None),
('TRUSTED_PROXY_COUNT', 0)):
setattr(conf, name, value)
# The start of every ticket body
CONTACT = ("Contact\n=======\n\n"
"Name:\n Valid Guy\n\n"
"Email:\n example@osuosl.org\n\n")
class TestFormsender(unittest.TestCase):
def test_create_msg_with_content(self):
"""
Tests create_msg with content in the POST request
Checks that each element in the request is returned create_msg
"""
builder = EnvironBuilder(method='POST',
data={'foo': 'this is some text',
'file': 'my file contents',
'test': 'test.txt',
'redirect': 'http://www.example.com'})
env = builder.get_environ()
req = Request(env)
self.assertEqual(handler.create_msg(req)['foo'], builder.form['foo'])
self.assertEqual(handler.create_msg(req)['file'], builder.form['file'])
self.assertEqual(handler.create_msg(req)['test'], builder.form['test'])
def test_create_msg_no_content(self):
"""
Tests create_msg with no content in the POST request
Checks that create_msg returns None
"""
builder = EnvironBuilder(method='POST', data={})
env = builder.get_environ()
req = Request(env)
self.assertEqual(handler.create_msg(req), None)
def test_create_msg_with_content_get_method(self):
"""
Tests create_msg with content in a GET request
Checks that create_msg returns None
"""
builder = EnvironBuilder(method='GET',
data={'foo': 'this is some text',
'file': 'my file contents',
'test': 'test.txt'})
env = builder.get_environ()
req = Request(env)
self.assertEqual(handler.create_msg(req), None)
def test_send_email(self):
"""
Tests send_email
send_email returns True when it successfully sends an email to a
default address and errors out when unsuccessful.
"""
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'last_name': '',
'token': conf.TOKEN,
'redirect': 'http://www.example.com'})
env = builder.get_environ()
req = Request(env)
# Construct message for assertion
msg = handler.create_msg(req)
msg_subj = handler.set_mail_subject(msg)
# Mock create_ticket function
with patch('rt.rest2.Rt') as mock_rt:
instance = mock_rt.return_value
# Call send_ticket and assert ticket creation returns new ticket ID
handler.create_app()
handler.send_ticket(msg, msg_subj)
instance.create_ticket.assert_called_with(queue='General',
subject=msg_subj,
Requestor='noreply@osuosl.org',
content=msg)
def test_extract_attachments(self):
"""
Tests extract_attachments
An uploaded file becomes an rt.rest2.Attachment carrying the original
filename, content type, and bytes; empty file inputs are ignored.
"""
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'rfcfile': (BytesIO(b'proposal bytes'),
'proposal.pdf',
'application/pdf'),
'emptyfile': (BytesIO(b''), '')})
req = Request(builder.get_environ())
attachments = handler.extract_attachments(req)
self.assertEqual(len(attachments), 1)
self.assertEqual(attachments[0].file_name, 'proposal.pdf')
self.assertEqual(attachments[0].file_type, 'application/pdf')
self.assertEqual(attachments[0].file_content, b'proposal bytes')
def test_send_ticket_with_attachments(self):
"""
Tests send_ticket passes attachments through to create_ticket only when
files are present.
"""
attachment = rt.rest2.Attachment('proposal.pdf', 'application/pdf',
b'proposal bytes')
with patch('rt.rest2.Rt') as mock_rt:
instance = mock_rt.return_value
handler.send_ticket('body', 'subj', 'General',
'noreply@osuosl.org', [attachment])
instance.create_ticket.assert_called_with(
queue='General', subject='subj', content='body',
Requestor='noreply@osuosl.org', attachments=[attachment])
def test_send_ticket_dry_run(self):
"""
With DRY_RUN set, send_ticket logs the ticket and never contacts RT
"""
attachment = rt.rest2.Attachment('proposal.pdf', 'application/pdf',
b'proposal bytes')
with patch.object(conf, 'DRY_RUN', True, create=True), \
patch('rt.rest2.Rt') as mock_rt, \
self.assertLogs('formsender', level='INFO') as logs:
handler.send_ticket('the body', 'subj', 'HostingRequests',
'jane@example.org', [attachment],
{'CompanyName': 'OPF'})
mock_rt.assert_not_called()
logged = logs.output[0]
for text in ('Queue: HostingRequests', 'Subject: subj',
'Requestor: jane@example.org',
"Custom fields: {'CompanyName': 'OPF'}",
'Attachment: proposal.pdf', 'the body'):
self.assertIn(text, logged)
def test_send_ticket_dry_run_minimal(self):
"""
A dry-run ticket without custom fields or attachments logs neither
"""
with patch.object(conf, 'DRY_RUN', True, create=True), \
self.assertLogs('formsender', level='INFO') as logs:
handler.send_ticket('the body', 'subj')
self.assertNotIn('Custom fields', logs.output[0])
self.assertNotIn('Attachment', logs.output[0])
def test_conf_dist_dry_run(self):
"""
conf.py.dist reads DRY_RUN from the environment and no longer
requires RT_TOKEN
"""
path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'conf.py.dist')
def load(env):
with patch.dict(os.environ, env, clear=True):
loader = SourceFileLoader('conf_dist', path)
module = types.ModuleType(loader.name)
loader.exec_module(module)
return module
for value, expected in (('1', True), ('true', True), ('YES', True),
('', False), ('0', False), ('no', False)):
dist = load({'TOKEN': 't', 'DRY_RUN': value})
self.assertIs(dist.DRY_RUN, expected)
self.assertIsNone(dist.RT_TOKEN)
self.assertIs(load({'TOKEN': 't'}).DRY_RUN, False)
def test_extract_custom_fields(self):
"""
Tests extract_custom_fields
A declarative 'custom_fields' mapping turns form fields into an RT
CustomFields dict; single values stay scalar, repeated values (e.g.
checkbox groups) become a list, and consumed field names are returned.
"""
builder = EnvironBuilder(method='POST',
data=MultiDict([
('custom_fields',
'CompanyName:companyname,'
'WorkingGroups:workgroups'),
('companyname', 'OPF'),
('workgroups', 'AI'),
('workgroups', 'Hardware')]))
req = Request(builder.get_environ())
custom_fields, consumed = handler.extract_custom_fields(req)
self.assertEqual(custom_fields['CompanyName'], 'OPF')
self.assertEqual(custom_fields['WorkingGroups'], ['AI', 'Hardware'])
self.assertEqual(consumed, {'companyname', 'workgroups'})
def test_format_message_excludes_custom_fields(self):
"""
Tests format_message leaves excluded (custom-field) source fields out of
the ticket body.
"""
msg = {'name': 'Valid Guy', 'email': 'example@osuosl.org',
'companyname': 'OPF', 'message': 'hello'}
body = handler.format_message(msg, exclude={'companyname'})
self.assertNotIn('OPF', body)
self.assertIn('hello', body)
@patch('captcha.is_valid_captcha')
@patch('request_handler.validate_email')
def test_validations_valid_data(self, mock_validate_email,
mock_recaptcha):
"""
Tests the form validation with valid data.
on_form_page checks for valid fields in submitted form and
returns an error message if an invalid field is found.
"""
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'last_name': '',
'token': conf.TOKEN,
'redirect': 'http://www.example.com',
'g-recaptcha-response': ''})
env = builder.get_environ()
req = Request(env)
# Mock external services so they return valid in CI
mock_validate_email.return_value = True
mock_recaptcha.return_value = (True, 'test')
app = handler.create_app()
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
app.on_form_page(req)
self.assertEqual(app.error, None)
@patch('request_handler.validate_email')
def test_validations_invalid_name(self, mock_validate_email):
"""
Tests the form validation with an invalid name.
on_form_page checks for valid fields in submitted form and
returns an error message if an invalid field is found.
Invalid name field causes an 'Invalid Name' error.
"""
builder = EnvironBuilder(method='POST',
data={'name': ' ',
'email': 'example@osuosl.org',
'last_name': '',
'token': conf.TOKEN,
'redirect': 'http://www.example.com'})
env = builder.get_environ()
req = Request(env)
# Mock external validate_email so returns true in Travis
mock_validate_email.return_value = True
app = handler.create_app()
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
app.on_form_page(req)
self.assertEqual(app.error, 'Invalid Name')
@patch('request_handler.validate_email')
def test_validations_invalid_email(self, mock_validate_email):
"""
Tests the form validation with an invalid email.
on_form_page checks for valid fields in submitted form and
returns an error message if an invalid field is found.
Invalid email field causes an 'Invalid Email' error.
"""
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'invalid@example.com',
'last_name': '',
'token': conf.TOKEN,
'redirect': 'http://www.example.com'})
env = builder.get_environ()
req = Request(env)
# Mock external validate_email so returns false in Travis
mock_validate_email.return_value = False
app = handler.create_app()
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
app.on_form_page(req)
self.assertEqual(app.error, 'Invalid Email')
@patch('request_handler.validate_email')
def test_validations_invalid_hidden(self, mock_validate_email):
"""
Tests the form validation with content in the hidden last_name field.
on_form_page checks for valid fields in submitted form and
returns an error message if an invalid field is found.
Content in the hidden last_name field causes an 'Improper Form
Submission' error.
"""
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'last_name': '!',
'token': conf.TOKEN,
'redirect': 'http://www.example.com'})
env = builder.get_environ()
req = Request(env)
# Mock external validate_email so returns true in Travis
mock_validate_email.return_value = True
app = handler.create_app()
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
app.on_form_page(req)
self.assertEqual(app.error, 'Improper Form Submission')
@patch('request_handler.validate_email')
def test_validations_invalid_token(self, mock_validate_email):
"""
Tests the form validation with an invalid token.
on_form_page checks for valid fields in submitted form and
returns an error message if an invalid field is found.
An invalid token causes the 'Improper Form Submission' error.
"""
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'last_name': '',
'token': 'evilrobot',
'redirect': 'http://www.example.com'})
env = builder.get_environ()
req = Request(env)
# Mock external validate_email so returns true in Travis
mock_validate_email.return_value = True
app = handler.create_app()
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
app.on_form_page(req)
self.assertEqual(app.error, 'Improper Form Submission')
@patch('request_handler.validate_email')
def test_validations_invalid_fields_to_join(self, mock_validate_email):
"""
Tests the form validation with an invalid 'fields_to_join' field.
on_form_page checks for valid fields in submitted form and
returns an error message if an invalid field is found.
An invalid token causes the 'Improper Form Submission' error.
"""
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'last_name': '',
'token': conf.TOKEN,
'redirect': 'http://www.example.com',
'fields_to_join': 'name,missing,email'})
env = builder.get_environ()
req = Request(env)
# Mock external validate_email so returns true in Travis
mock_validate_email.return_value = True
app = handler.create_app()
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
app.on_form_page(req)
self.assertEqual(app.error, 'Improper Form Submission')
@patch('request_handler.validate_email')
def test_is_valid_email_with_valid(self, mock_validate_email):
"""
Tests is_valid_email with a valid email
is_valid_email checks that the email submitted to the form is
valid and exists. This function call should return true.
"""
builder = EnvironBuilder(method='POST',
data={'email': 'example@osuosl.org'})
env = builder.get_environ()
req = Request(env)
# Mock external validate_email so returns true in Travis
mock_validate_email.return_value = True
self.assertTrue(handler.is_valid_email(req))
def test_validate_name_with_valid(self):
"""
Tests validate_name with a valid name
validate_name checks that the name submitted to the form does
not contain disallowed characters. This function call should return
true.
"""
builder = EnvironBuilder(method='POST', data={'name': 'Matthew'})
env = builder.get_environ()
req = Request(env)
self.assertTrue(handler.validate_name(req))
def test_validate_name_with_invalid(self):
"""
Tests validate_name with an invalid name
validate_name checks that the name submitted to the form does
not contain disallowed characters. This function call should
return false.
"""
builder = EnvironBuilder(method='POST', data={'name': ' '})
env = builder.get_environ()
req = Request(env)
self.assertFalse(handler.validate_name(req))
def test_is_hidden_field_empty_empty(self):
"""
Tests is_hidden_field_empty with 'last_name' field empty
is_hidden_field_empty checks that the last_name field in the form
is empty. This function call should return true.
"""
builder = EnvironBuilder(method='POST', data={'last_name': ''})
env = builder.get_environ()
req = Request(env)
self.assertTrue(handler.is_hidden_field_empty(req))
def test_is_hidden_field_empty_full(self):
"""
Tests is_hidden_field_empty with contents in 'last_name' field
is_hidden_field_empty checks that the last_name field in the form
is empty. This function call should return false.
"""
builder = EnvironBuilder(method='POST', data={'last_name': 'nope'})
env = builder.get_environ()
req = Request(env)
self.assertFalse(handler.is_hidden_field_empty(req))
def test_is_valid_token_valid(self):
"""
Tests is_valid_token with TOKEN defined in conf.py
is_valid_token checks that the token provided by the form matches
token described in the settings file. This function call should
return true.
"""
builder = EnvironBuilder(method='POST', data={'token': conf.TOKEN})
env = builder.get_environ()
req = Request(env)
self.assertTrue(handler.is_valid_token(req))
def test_is_valid_token_invalid(self):
"""
Tests is_valid_token with invalid token
is_valid_token checks that the token provided by the form matches
token described in the settings file. This function call should
return false.
"""
builder = EnvironBuilder(method='POST', data={'token': 'imarobot'})
env = builder.get_environ()
req = Request(env)
self.assertFalse(handler.is_valid_token(req))
@patch('captcha.is_valid_captcha')
@patch('request_handler.validate_email')
def test_rate_limiter_valid_rate(self, mock_validate_email,
mock_recaptcha):
"""
Tests rate limiter with a valid rate
"""
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'last_name': '',
'token': conf.TOKEN,
'redirect': 'http://www.example.com',
'g-recaptcha-response': ''})
# Mock external services so they return valid in CI
mock_validate_email.return_value = True
mock_recaptcha.return_value = (True, 'test')
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
app = handler.create_app()
for i in range(conf.CEILING - 1):
env = builder.get_environ()
req = Request(env)
resp = app.on_form_page(req)
# Avoid duplicate form error
builder.form['name'] = str(i) + builder.form['name']
self.assertEqual(resp.status_code, 302)
self.assertEqual(app.error, None)
@patch('request_handler.validate_email')
def test_rate_limiter_invalid_rate(self, mock_validate_email):
"""
Tests rate limiter with an invalid rate
"""
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'last_name': '',
'token': conf.TOKEN,
'redirect': 'http://www.example.com',
'g-recaptcha-response': ''})
# Mock validate email so returns true in Travis
mock_validate_email.return_value = True
env = builder.get_environ()
req = Request(env)
app = handler.create_app()
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
for i in range(conf.CEILING + 1):
app.on_form_page(req)
# Avoid duplicate form error
builder.form['name'] = str(i) + builder.form['email']
self.assertEqual(app.error, 'Too Many Requests')
@patch('captcha.is_valid_captcha')
@patch('request_handler.validate_email')
def test_redirect_url_valid_data(self, mock_validate_email,
mock_recaptcha):
"""
Tests the user is redirected to appropriate location
"""
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'redirect': 'http://www.example.com',
'last_name': '',
'token': conf.TOKEN,
'g-recaptcha-response': ''})
env = builder.get_environ()
req = Request(env)
# Mock external services so they return valid in CI
mock_validate_email.return_value = True
mock_recaptcha.return_value = (True, 'test')
# Create app and mock redirect
app = handler.create_app()
werkzeug.utils.redirect = Mock('werkzeug.utils.redirect')
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
app.on_form_page(req)
werkzeug.utils.redirect.assert_called_with('http://www.example.com',
code=302)
@patch('request_handler.validate_email')
def test_redirect_url_error_1(self, mock_validate_email):
"""
Tests the user is redirected to appropriate location
"""
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'nope@example.com',
'redirect': 'http://www.example.com',
'last_name': '',
'token': conf.TOKEN})
env = builder.get_environ()
req = Request(env)
# Mock validate email so returns false in Travis
# Not technically necessary because this will return false in Travis
# regardless since it can't find the SMTP server, but kept here for
# consistency
mock_validate_email.return_value = False
# Create app and mock redirect
app = handler.create_app()
werkzeug.utils.redirect = Mock('werkzeug.utils.redirect')
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
app.on_form_page(req)
werkzeug.utils.redirect.assert_called_with(
'http://www.example.com?error=1&message=Invalid+Email',
code=302)
@patch('request_handler.validate_email')
def test_redirect_url_error_2(self, mock_validate_email):
"""
Tests the user is redirected to appropriate location
"""
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': '',
'email': 'example@osuosl.org',
'redirect': 'http://www.example.com',
'last_name': '',
'token': conf.TOKEN})
env = builder.get_environ()
req = Request(env)
# Mock validate email so returns true in Travis
mock_validate_email.return_value = True
# Create app and mock redirect
app = handler.create_app()
werkzeug.utils.redirect = Mock('werkzeug.utils.redirect')
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
app.on_form_page(req)
werkzeug.utils.redirect.assert_called_with(
'http://www.example.com?error=2&message=Invalid+Name',
code=302)
@patch('request_handler.validate_email')
def test_redirect_url_error_3(self, mock_validate_email):
"""
Tests the user is redirected to appropriate location
"""
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'redirect': 'http://www.example.com',
'last_name': '!',
'token': 'wrong token'})
env = builder.get_environ()
req = Request(env)
# Mock validate email so returns true in Travis
mock_validate_email.return_value = True
# Create app and mock redirect
app = handler.create_app()
werkzeug.utils.redirect = Mock('werkzeug.utils.redirect')
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
app.on_form_page(req)
werkzeug.utils.redirect.assert_called_with(
'http://www.example.com?error=3&message=Improper+Form+Submission',
code=302)
@patch('request_handler.validate_email')
def test_redirect_url_error_4(self, mock_validate_email):
"""
Tests the user is redirected to appropriate location
"""
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'redirect': 'http://www.example.com',
'last_name': '',
'token': conf.TOKEN,
'g-recaptcha-response': ''})
env = builder.get_environ()
req = Request(env)
# Mock validate email so returns true in Travis
mock_validate_email.return_value = True
app = handler.create_app()
werkzeug.utils.redirect = Mock('werkzeug.utils.redirect')
# Mock create_ticket function so it doesn't send an actual ticket
rt.rest2.Rt = Mock('rt.rest2.Rt')
for i in range(conf.CEILING + 1):
app.on_form_page(req)
# Avoid duplicate form error
builder.form['name'] = str(i) + builder.form['name']
werkzeug.utils.redirect.assert_called_with(
'http://www.example.com?error=4&message=Too+Many+Requests',
code=302)
def test_strip_incoming_redirect_query(self):
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'redirect': 'www.example.com?mal=param',
'last_name': '',
'token': conf.TOKEN})
env = builder.get_environ()
req = Request(env)
message = handler.create_msg(req)
self.assertEqual(message['redirect'], 'www.example.com')
def test_strip_incoming_redirect_no_query(self):
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'redirect': 'www.example.com',
'last_name': '',
'token': conf.TOKEN})
env = builder.get_environ()
req = Request(env)
message = handler.create_msg(req)
self.assertEqual(message['redirect'], builder.form['redirect'])
def test_format_message(self):
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'some_field': ("This is multi line and "
"should not be on the "
"same line as the title"),
'redirect': 'http://www.example.com',
'last_name': '',
'token': conf.TOKEN})
env = builder.get_environ()
req = Request(env)
target_message = (CONTACT +
"Information\n===========\n\n"
"Some Field:\n"
" This is multi line and should not be on the "
"same line as the title\n\n")
message = handler.create_msg(req)
formatted_message = handler.format_message(message)
self.assertEqual(formatted_message, target_message)
def test_format_message_uses_field_labels(self):
"""
Fields named in field_labels are written first, in that order, under
their labels. Anything else follows as before, title-cased and
sorted, and field_labels itself stays out of the body.
"""
labels = json.dumps([{'name': 'name', 'label': 'Name'},
{'name': 'instance_vcpus', 'label': 'vCPUs'},
{'name': 'ci_cd', 'label': 'CI/CD resources'},
{'name': 'unchecked_box', 'label': 'Not sent'},
{'name': 'deadline', 'label': 'Do you have a deadline?'},
{'name': 'costs', 'label': 'Contributions to cover costs.'}])
message = {'name': 'Valid Guy',
'email': 'example@osuosl.org',
'zebra_field': 'z',
'costs': 'None',
'deadline': 'No',
'ci_cd': 'requested',
'instance_vcpus': '8',
'field_labels': labels}
target_message = (CONTACT +
"Information\n===========\n\n"
"vCPUs:\n 8\n\n"
"CI/CD resources:\n requested\n\n"
"Do you have a deadline?\n No\n\n"
"Contributions to cover costs:\n None\n\n"
"Zebra Field:\n z\n\n")
self.assertEqual(handler.format_message(message), target_message)
def test_format_message_labelled_field_excluded(self):
"""
A labelled field consumed as an RT custom field stays out of the body
"""
labels = json.dumps([{'name': 'companyname', 'label': 'Company'},
{'name': 'other', 'label': 'Other'}])
message = {'name': 'Valid Guy',
'email': 'example@osuosl.org',
'companyname': 'OPF',
'other': 'x',
'field_labels': labels}
formatted = handler.format_message(message, exclude={'companyname'})
self.assertNotIn('OPF', formatted)
self.assertIn('Other:\n x\n\n', formatted)
def test_format_message_skips_blank_answers(self):
"""
Fields left blank, or holding only whitespace, are left out of the
body, whether or not the form labelled them. Defaults and zeros are
answers and stay.
"""
labels = json.dumps([{'name': 'sponsor', 'label': 'Sponsor'},
{'name': 'vms', 'label': 'Number of VMs'},
{'name': 'managed', 'label': 'Managed?'}])
message = {'name': 'Valid Guy',
'email': 'example@osuosl.org',
'sponsor': '',
'vms': '0',
'managed': 'Not sure',
'notes': ' \n ',
'unlabelled_blank': '',
'field_labels': labels}
target_message = (CONTACT +
"Information\n===========\n\n"
"Number of VMs:\n 0\n\n"
"Managed?\n Not sure\n\n")
self.assertEqual(handler.format_message(message), target_message)
def test_format_message_wraps_answers(self):
"""
Long answers and list items are wrapped to WRAP_WIDTH under their
heading, keeping the requester's line breaks. A line with a long word,
such as an SSH key, isn't wrapped, so it can still be copied. A
section inside one with no chooser of its own is listed in the summary
under both titles.
"""
labels = json.dumps([
{'name': 'mysql', 'label': 'MySQL', 'opens_section': True,
'section': ['Databases', 'MySQL']},
{'name': 'notes', 'label': 'Notes', 'section': ['Databases', 'MySQL']},
{'name': 'kind', 'label': 'A rather long option label that will '
'need to be wrapped onto a second line of text', 'group': 'Kind',
'section': ['Databases', 'MySQL']}])
key = 'ssh-ed25519 ' + 'A' * 68 + ' dana@kestrel.example'
message = {'name': 'Valid Guy',
'email': 'example@osuosl.org',
'mysql': 'requested',
'notes': ('word ' * 20).strip() + '\n' + key,
'kind': 'yes',
'field_labels': labels}
target_message = (CONTACT +
"Services requested\n==================\n\n"
" - Databases: MySQL\n\n"
"Databases\n=========\n\n"
"--- MySQL ---\n\n"
"Notes:\n"
" word word word word word word word word word "
"word word word word word word\n"
" word word word word word\n"
" " + key + "\n\n"
"Kind:\n"
" - A rather long option label that will need to "
"be wrapped onto a second line\n"
" of text\n\n")
self.assertEqual(handler.format_message(message), target_message)
def test_field_labels(self):
"""
field_labels returns the labels in order, fills in the optional
keys, and skips entries and section titles it can't use
"""
labels = json.dumps([{'name': 'a', 'label': ' First '},
'not a dict',
{'name': 'b'},
{'name': 'c', 'label': ' '},
{'name': 3, 'label': 'Bad name'},
{'name': 'd', 'label': 'Fourth',
'section': [' Email ', 3, ' ', 'Forwards'],
'opens_section': True, 'group': ' Which? '},
{'name': 'e', 'label': 'Fifth',
'section': 'not a list', 'opens_section': 'yes',
'group': 4}])
self.assertEqual(handler.field_labels({'field_labels': labels}), [
{'name': 'a', 'label': 'First', 'section': (),
'opens_section': False, 'group': ''},
{'name': 'd', 'label': 'Fourth', 'section': ('Email', 'Forwards'),
'opens_section': True, 'group': 'Which?'},
{'name': 'e', 'label': 'Fifth', 'section': (),
'opens_section': False, 'group': ''},
])
def test_format_message_sections_and_groups(self):
"""
Labelled fields are written under headings for their sections, a
chosen section checkbox shows only its heading, chosen checkbox-group
options are listed under the group's label, and multi-line answers are
indented line by line
"""
labels = json.dumps([
{'name': 'project', 'label': 'Project name'},
{'name': 'mail', 'label': 'Email', 'section': ['Email'],
'opens_section': True},
{'name': 'inbound', 'label': 'Receiving mail', 'group': 'What do you need?',
'section': ['Email']},
{'name': 'outbound', 'label': 'Sending mail', 'group': 'What do you need?',
'section': ['Email']},
{'name': 'forwards', 'label': 'Forwards', 'group': 'What do you need?',
'section': ['Email']},
{'name': 'domain', 'label': 'Domain(s)', 'section': ['Email']},
{'name': 'arch_x86', 'label': 'x86_64', 'group': 'Architectures',
'section': ['Email']},
{'name': 'tools', 'label': 'Collaboration tools',
'section': ['Collaboration tools'], 'opens_section': True},
{'name': 'gitlab', 'label': 'GitLab',
'section': ['Collaboration tools', 'GitLab'], 'opens_section': True},
{'name': 'gitlab_domain', 'label': 'Domain',
'section': ['Collaboration tools', 'GitLab']},
{'name': 'matrix_domain', 'label': 'Domain',
'section': ['Collaboration tools', 'Matrix']},
{'name': 'deadline', 'label': 'Do you have a hard deadline?',
'section': ['Other details']},
])
message = {'name': 'Valid Guy',
'email': 'example@osuosl.org',
'project': 'Kestrel',
'mail': 'requested',
'inbound': 'requested',
'forwards': 'requested',
'domain': 'kestrel.example',
'arch_x86': 'yes',
'tools': 'requested',
'gitlab': 'requested',
'gitlab_domain': 'git.kestrel.example',
'matrix_domain': 'matrix.kestrel.example',
'deadline': 'March 31\r\n\r\nOur VM contract ends.\r\n',
'field_labels': labels}
target_message = (CONTACT +
"Services requested\n==================\n\n"
" - Email\n"
" - Collaboration tools: GitLab\n\n"
"Information\n===========\n\n"
"Project name:\n Kestrel\n\n"
"Email\n=====\n\n"
"What do you need?\n"
" - Receiving mail\n"
" - Forwards\n\n"
"Domain(s):\n kestrel.example\n\n"
"Architectures:\n - x86_64\n\n"
"Collaboration tools\n===================\n\n"
"--- GitLab ---\n\n"
"Domain:\n git.kestrel.example\n\n"
"--- Matrix ---\n\n"
"Domain:\n matrix.kestrel.example\n\n"
"Other details\n=============\n\n"
"Do you have a hard deadline?\n"
" March 31\n\n Our VM contract ends.\n\n")
self.assertEqual(handler.format_message(message), target_message)
def test_field_labels_fallback(self):
"""
A missing, malformed or non-list field_labels gives no labels, so the
body falls back to title-cased, sorted field names
"""
for value in (None, '', 'not json', '{"name": "a"}'):
msg = {} if value is None else {'field_labels': value}
self.assertEqual(handler.field_labels(msg), [])
message = {'name': 'Valid Guy',
'email': 'example@osuosl.org',
'b_field': '2',
'a_field': '1',
'field_labels': 'not json'}
self.assertIn("A Field:\n 1\n\nB Field:\n 2\n\n",
handler.format_message(message))
def test_set_mail_subject_with_both_options(self):
"""
set_mail_subject(message) returns the string
"message['mail_subject_prefix']: message[message['mail_subject_key']"
when both are available
"""
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'redirect': 'http://www.example.com',
'last_name': '',
'mail_subject_prefix': 'Hosting',
'mail_subject_key': 'project',
'project': 'PGD',
'token': conf.TOKEN})
env = builder.get_environ()
req = Request(env)
# Create message from request and call set_mail_subject()
message = handler.create_msg(req)
self.assertEqual(handler.set_mail_subject(message), 'Hosting: PGD')
def test_set_mail_subject_with_subj_prefix(self):
"""
set_mail_subject(message) returns the string
"message['mail_subject_prefix']" when it is the only field available
"""
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': 'example@osuosl.org',
'redirect': 'http://www.example.com',
'last_name': '',
'mail_subject_prefix': 'Hosting',
'token': conf.TOKEN})
env = builder.get_environ()