-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_reg_system.py
13074 lines (12770 loc) · 677 KB
/
test_reg_system.py
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
# Test matholymp registration system.
# Copyright 2018-2020 Joseph Samuel Myers.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <https://www.gnu.org/licenses/>.
# Additional permission under GNU GPL version 3 section 7:
# If you modify this program, or any covered work, by linking or
# combining it with the OpenSSL project's OpenSSL library (or a
# modified version of that library), containing parts covered by the
# terms of the OpenSSL or SSLeay licenses, the licensors of this
# program grant you additional permission to convey the resulting
# work. Corresponding Source for a non-source form of such a
# combination shall include the source code for the parts of OpenSSL
# used as well as that of the covered work.
"""
Tests for matholymp registration system.
"""
import base64
import codecs
import io
import os
import os.path
import random
import re
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import traceback
import unittest
import zipfile
try:
import mechanicalsoup
from PIL import Image
import roundup.instance
import roundup.password
# roundup_server modifies sys.path on import, so save and restore it.
_save_path = list(sys.path)
from roundup.scripts import roundup_server
sys.path = _save_path
_skip_test = False
except ImportError:
_skip_test = True
from matholymp.fileutil import read_utf8_csv, write_utf8_csv_bytes, \
write_utf8_csv, write_bytes_to_file, write_text_to_file, \
replace_text_in_file, read_config_raw, write_config_raw
__all__ = ['gen_image', 'gen_image_file', 'gen_pdf_file',
'RoundupTestInstance', 'RoundupTestSession', 'RegSystemTestCase']
def gen_image(size_x, size_y, scale, mode):
"""Generate an image with random blocks scale by scale of pixels."""
mode_bytes = {'L': 1,
'LA': 2,
'RGB': 3,
'RGBA': 4}
nbytes = mode_bytes[mode]
data = bytearray(size_x * size_y * scale * scale * nbytes)
line_size = size_x * scale * nbytes
for y in range(size_y):
for x in range(size_x):
for color in range(nbytes):
pixel = random.randint(0, 255)
for y_sub in range(scale):
for x_sub in range(scale):
x_pos = color + nbytes * (x_sub + scale * x)
y_pos = y_sub + scale * y
pos = x_pos + line_size * y_pos
data[pos] = pixel
data = memoryview(data).tobytes()
return Image.frombytes(mode, (size_x * scale, size_y * scale), data)
def gen_image_file(size_x, size_y, scale, filename, fmt, mode='RGB',
**kwargs):
"""Generate an image, in a file."""
image = gen_image(size_x, size_y, scale, mode)
image.save(filename, fmt, **kwargs)
def gen_pdf_file(dirname, suffix):
"""Generate a PDF file in the given empty directory and return its name."""
tex_file = os.path.join(dirname, 'test.tex')
rand_nums = [random.randint(0, 9) for n in range(20)]
rand_text = ''.join([str(n) for n in rand_nums])
tex_text = ('\\documentclass[a4paper]{article}\n'
'\\begin{document}\n'
'%s\n'
'\\end{document}\n'
% rand_text)
write_text_to_file(tex_text, tex_file)
subprocess.run(['pdflatex', tex_file], cwd=dirname,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, check=True)
pdf_file = os.path.join(dirname, 'test.pdf')
ret_file = os.path.join(dirname, 'test%s' % suffix)
if ret_file != pdf_file:
os.rename(pdf_file, ret_file)
return ret_file
class RoundupTestInstance:
"""
A RoundupTestInstance provides a temporary Roundup installation
used for testing.
"""
def __init__(self, top_dir, temp_dir, config, coverage):
"""Initialise a RoundupTestInstance."""
self.pid = None
self.port = None
self.example_dir = os.path.join(top_dir, 'examples',
'online-registration')
self.temp_dir = temp_dir
self.instance_dir = os.path.join(self.temp_dir, 'instance')
self.mail_file = os.path.join(self.temp_dir, 'mail')
# Create mail file as empty to avoid needing to check for
# existence later when checking size.
with open(self.mail_file, 'w') as f:
pass
self.log_file = os.path.join(self.temp_dir, 'log')
self.html_dir = os.path.join(self.instance_dir, 'html')
shutil.copytree(self.example_dir, self.instance_dir)
self.config_ini = os.path.join(self.instance_dir, 'config.ini')
self.ext_config_ini = os.path.join(self.instance_dir, 'extensions',
'config.ini')
# Ensure that example.org references cannot leak out as actual
# network access attempts during testing, if anything
# mistakenly tries to send email or access CSS / favicon
# links.
subst_files = [self.config_ini, self.ext_config_ini,
os.path.join(self.html_dir, 'page.html'),
os.path.join(self.html_dir, 'dpage.html')]
if config and 'static_site_directory' in config:
# Construct a static site directory. We assume it is to
# be called 'static-site' relative to the Roundup
# instance.
self.static_example_dir = os.path.join(top_dir, 'test-data',
'mo-static-generate',
'basic', 'in')
self.static_site_dir = os.path.join(self.instance_dir,
'static-site')
shutil.copytree(self.static_example_dir, self.static_site_dir)
# Ensure the static site directory has a country without a
# flag. Ensure flags and photos listed in the .csv files
# are present.
countries_csv = os.path.join(self.static_site_dir, 'data',
'countries.csv')
replace_text_in_file(
countries_csv,
'https://www.example.org/countries/country3/flag1.png', '')
static_base = 'https://www.example.org/'
for country in read_utf8_csv(countries_csv):
url = country['Flag URL']
if url.startswith(static_base):
url_rest = url[len(static_base):]
url_dirs = url_rest.split('/')
image_file = os.path.join(self.static_site_dir, *url_dirs)
os.makedirs(os.path.dirname(image_file))
gen_image_file(2, 2, 2, image_file, 'PNG')
people_csv = os.path.join(self.static_site_dir, 'data',
'people.csv')
for person in read_utf8_csv(people_csv):
url = person['Photo URL']
if url.startswith(static_base):
url_rest = url[len(static_base):]
url_dirs = url_rest.split('/')
image_file = os.path.join(self.static_site_dir, *url_dirs)
os.makedirs(os.path.dirname(image_file))
gen_image_file(2, 2, 2, image_file, 'JPEG')
subst_files.extend([countries_csv, people_csv])
if config and 'docgen_directory' in config:
# Construct a document generation directory. We assume it
# is to be called 'docgen' relative to the Roundup
# instance.
self.docgen_example_dir = os.path.join(top_dir, 'examples',
'document-generation')
self.docgen_dir = os.path.join(self.instance_dir, 'docgen')
shutil.copytree(self.docgen_example_dir, self.docgen_dir)
# We don't create a badge background PDF here, to allow
# testing the case where it is missing, but some tests
# need to create one.
self.docgen_badge_background_pdf = os.path.join(
self.docgen_dir, 'templates', 'lanyard-generic.pdf')
os.makedirs(os.path.join(self.instance_dir, 'db'))
self.passwords = {'admin': roundup.password.generatePassword()}
self.userids = {'admin': '1'}
self.num_users = 2
for f in subst_files:
replace_text_in_file(f, 'example.org', 'example.invalid')
replace_text_in_file(self.config_ini, '\nbackend = postgresql\n',
'\nbackend = anydbm\n')
replace_text_in_file(self.ext_config_ini,
'\nmatholymp_static_site_directory = '
'/some/where\n',
'\nmatholymp_static_site_directory =\n')
replace_text_in_file(self.ext_config_ini,
'\nmatholymp_docgen_directory = '
'/some/where\n',
'\nmatholymp_docgen_directory =\n')
if config:
cfg = read_config_raw(self.ext_config_ini)
for key, value in config.items():
cfg.set('main', 'matholymp_%s' % key, value)
write_config_raw(cfg, self.ext_config_ini)
if coverage:
# Record code coverage; arrange for the data to be saved
# on exit. Exit occurs both from this code and from
# forked children handling requests, so _exit and fork
# need to be wrapped.
# pylint: disable=import-outside-toplevel
from coverage import Coverage
cov_base = os.path.join(self.temp_dir, '.coverage.reg-system')
self.cov = Coverage(data_file=cov_base, data_suffix=True)
self.cov.start()
orig_exit = os._exit
orig_fork = os.fork
def wrap_fork():
self.cov.stop()
pid = orig_fork()
if pid == 0:
self.cov = Coverage(data_file=cov_base, data_suffix=True)
self.cov.start()
return pid
def wrap_exit(status):
os._exit = orig_exit
try:
self.cov.stop()
self.cov.save()
finally:
os._exit(status)
os.fork = wrap_fork
os._exit = wrap_exit
instance = roundup.instance.open(self.instance_dir)
instance.init(roundup.password.Password(self.passwords['admin']))
# Start up a server in a forked child, which reports back the
# port number used to the parent (repeatedly trying random
# ports as needed until one is free).
read_fd, write_fd = os.pipe()
sys.stdout.flush()
sys.stderr.flush()
self.pid = os.fork()
if self.pid == 0:
# Child.
try:
web_text = ('\nweb = https://www.example.invalid/'
'registration/2015/\n')
retry = True
while retry:
retry = False
self.port = random.SystemRandom().randrange(32768, 65536)
self.url = 'http://localhost:%d/xmo/' % self.port
web_text_new = '\nweb = %s\n' % self.url
replace_text_in_file(self.config_ini, web_text,
web_text_new)
web_text = web_text_new
config = roundup_server.ServerConfig()
config.add_option(roundup_server.TrackerHomeOption(
config, 'trackers', 'xmo'))
config['TRACKERS_XMO'] = self.instance_dir
config.PORT = self.port
config['LOGFILE'] = self.log_file
config.set_logging()
os.environ['SENDMAILDEBUG'] = self.mail_file
try:
server = config.get_server()
except socket.error as e:
if 'port already in use' in str(e.args[0]):
retry = True
else:
raise
os.close(read_fd)
os.write(write_fd, str(self.port).encode('utf-8'))
os.close(write_fd)
except Exception: # pylint: disable=broad-except
sys.stdout.flush()
sys.stderr.flush()
traceback.print_exc()
# Avoid cleanups running in child process.
os._exit(1)
try:
server.serve_forever()
except KeyboardInterrupt:
sys.stdout.flush()
sys.stderr.flush()
print('Test server requested to exit')
os._exit(0)
except Exception: # pylint: disable=broad-except
sys.stdout.flush()
sys.stderr.flush()
traceback.print_exc()
os._exit(1)
else:
# Parent.
if coverage:
# Code coverage in the parent, beyond the code read at
# Roundup instance initialisation before forking, is
# not of interest.
self.cov.stop()
self.cov.save()
os._exit = orig_exit
os.fork = orig_fork
os.close(write_fd)
self.port = int(os.read(read_fd, 5))
os.close(read_fd)
self.url = 'http://localhost:%d/xmo/' % self.port
def stop_server(self):
"""Stop the server started for a RoundupTestInstance."""
if self.pid:
os.kill(self.pid, signal.SIGINT)
os.waitpid(self.pid, 0)
def static_site_bytes(self, filename):
"""Return the byte content of a file in the static site."""
with open(os.path.join(self.static_site_dir, filename),
'rb') as in_file:
return in_file.read()
class RoundupTestSession:
"""
A RoundupTestSession automates interation with a RoundupTestInstance.
"""
def __init__(self, instance, username=None):
"""Initialise a RoundupTestSession."""
self.instance = instance
self.b = mechanicalsoup.StatefulBrowser(raise_on_404=True)
self.last_mail_bin = None
self.last_mail_dec = None
self.num_people = 0
self.check_open(self.instance.url)
if username is not None:
self.login(username)
def close(self):
"""Close this session."""
self.b.close()
def __getattr__(self, name):
"""Do a computed attribute lookup.
check_* method names call the corresponding StatefulBrowser
methods, which are expected to return a Response object, and
carry out checks on both that object and the resulting
page.
"""
if name.startswith('check_'):
sb_name = name[len('check_'):]
sb_method = getattr(self.b, sb_name)
old_mail_size = os.stat(self.instance.mail_file).st_size
def fn(*args, mail=False, error=False, status=None, login=False,
html=True, **kwargs):
response = sb_method(*args, **kwargs)
if status is None:
response.raise_for_status()
else:
if response.status_code != status:
raise ValueError('request generated status %d '
'instead of %d'
% (response.status_code, status))
mail_size = os.stat(self.instance.mail_file).st_size
mail_generated = mail_size > old_mail_size
if mail_generated:
with open(self.instance.mail_file, 'rb') as f:
mail_bin = f.read()[old_mail_size:]
self.last_mail_bin = mail_bin
if b'Content-Transfer-Encoding: base64' in mail_bin:
content_idx = mail_bin.index(b'\n\n') + 2
mail_bin = mail_bin[content_idx:]
self.last_mail_dec = base64.b64decode(mail_bin)
else:
self.last_mail_dec = mail_bin
if mail and not mail_generated:
raise ValueError('request failed to generate mail')
elif mail_generated and not mail:
raise ValueError('request generated mail: %s'
% str(self.last_mail_bin))
if hasattr(response, 'soup') and html:
soup = response.soup
error_p = soup.find('p', class_='error-message')
error_generated = error_p is not None
if error and not error_generated:
raise ValueError('request did not produce error: %s'
% str(soup))
elif error_generated and not error:
raise ValueError('request produced error: %s'
% str(soup))
elif error and error_generated:
if isinstance(error, str):
if not error_p.find(string=re.compile(error)):
raise ValueError('request did not produce '
'expected error: %s'
% str(soup))
if soup.find('title',
string=re.compile('An error has occurred')):
raise ValueError('request produced internal error: %s'
% str(soup))
# Page templates should not try to format output
# at all for any fields the user lacks permission
# to see, so Roundup's [hidden] should never
# appear in the output.
if soup.find(string=re.compile(r'\[hidden\]')):
raise ValueError('request produced [hidden] text: %s'
% str(soup))
wants_login = soup.find(string=re.compile(
'You are not allowed to view this page'
'|Please login with your username and password'))
wants_login = wants_login is not None
if login and not wants_login:
raise ValueError('request did not ask for login: %s'
% str(soup))
elif wants_login and not login:
raise ValueError('request asked for login: %s'
% str(soup))
return response
return fn
else:
raise AttributeError(name)
def get_sidebar(self):
"""Get the sidebar from the current page."""
return self.b.get_current_page().find(id='xmo-sidebar')
def get_main(self):
"""Get the main contents from the current page."""
return self.b.get_current_page().find(id='xmo-main')
def get_download(self, url, content_type, filename):
"""Get a downloadable file and verify its content-type and filename."""
response = self.check_get(self.instance.url + url, html=False)
if response.headers['content-type'] != content_type:
raise ValueError('request for %s produced content type %s, not %s'
% (url, response.headers['content-type'],
content_type))
expected_disposition = 'attachment; filename=%s' % filename
if response.headers['content-disposition'] != expected_disposition:
raise ValueError('request for %s produced content disposition '
'%s, not %s'
% (url, response.headers['content-disposition'],
expected_disposition))
return response.content
def get_download_file(self, url, content_type, filename):
"""Get a download in a temporary file."""
content = self.get_download(url, content_type, filename)
temp_file = tempfile.NamedTemporaryFile(dir=self.instance.temp_dir,
delete=False)
temp_file.write(content)
name = temp_file.name
temp_file.close()
return name
def get_download_csv(self, url, filename):
"""Get the contents of a CSV download."""
temp_name = self.get_download_file(url, 'text/csv; charset=UTF-8',
filename)
return read_utf8_csv(temp_name)
def get_countries_csv(self):
"""Get the CSV file of countries."""
return self.get_download_csv('country?@action=country_csv',
'countries.csv')
def get_countries_csv_public_only(self):
"""Get the CSV file of countries, public data only."""
countries_csv = self.get_download_csv('country?@action=country_csv',
'countries.csv')
# For convenience in testing when non-public data is
# irrelevant for what is being tested.
for entry in countries_csv:
del entry['Contact Emails']
del entry['Expected Leaders']
del entry['Expected Deputies']
del entry['Expected Contestants']
del entry['Expected Observers with Leader']
del entry['Expected Observers with Deputy']
del entry['Expected Observers with Contestants']
del entry['Expected Single Rooms']
del entry['Expected Numbers Confirmed']
return countries_csv
def get_people_csv(self):
"""Get the CSV file of people."""
return self.get_download_csv('person?@action=people_csv',
'people.csv')
def get_scores_csv(self):
"""Get the CSV file of scores."""
return self.get_download_csv('person?@action=scores_csv',
'scores.csv')
def get_people_csv_scores(self):
"""Get the scores from the CSV file of people."""
people_csv = self.get_people_csv()
cols = {'Country Name', 'Country Code', 'Contestant Code',
'Given Name', 'Family Name', 'P1', 'P2', 'P3', 'P4', 'P5',
'P6', 'Total', 'Award', 'Extra Awards'}
people_csv = [entry for entry in people_csv
if entry['Contestant Code']]
for entry in people_csv:
for column in list(entry.keys()):
if column not in cols:
del entry[column]
return people_csv
def get_download_zip(self, url, filename):
"""Get the contents of a ZIP download."""
temp_name = self.get_download_file(url, 'application/zip', filename)
return zipfile.ZipFile(temp_name, 'r')
def get_flags_zip(self):
"""Get the ZIP file of flags."""
return self.get_download_zip('country?@action=flags_zip', 'flags.zip')
def get_photos_zip(self):
"""Get the ZIP file of photos."""
return self.get_download_zip('person?@action=photos_zip', 'photos.zip')
def get_consent_forms_zip(self):
"""Get the ZIP file of consent forms."""
return self.get_download_zip('person?@action=consent_forms_zip',
'consent-forms.zip')
def get_bytes(self, url):
"""Get the bytes contents of a non-HTML URL."""
return self.check_get(url, html=False).content
def get_img(self):
"""Get the (first) img tag from the current page."""
return self.get_main().find('img')
def get_img_contents(self):
"""Get the contents of the (first) img tag from the current page."""
img_src = self.get_img()['src']
img_src = self.b.absolute_url(img_src)
return self.check_get(img_src, html=False).content
def get_link(self, text):
"""Get the (first) link from the current page with given text."""
return self.get_main().find('a', string=re.compile(text))
def get_link_contents(self, text):
"""Get the target of the (first) link from the current page with the
given text."""
url = self.get_link(text)['href']
url = self.b.absolute_url(url)
return self.check_get(url, html=False).content
def login(self, username):
"""Log in as the specified user."""
self.b.select_form(self.get_sidebar().find('form'))
self.b['__login_name'] = username
self.b['__login_password'] = self.instance.passwords[username]
self.check_submit_selected()
def get_main_form(self):
"""Select the main form from the current page."""
return self.get_main().find('form')
def select_main_form(self):
"""Select the main form from the current page."""
self.b.select_form(self.get_main_form())
def workaround_ms_issue_242(self):
"""Work around MechanicalSoup issue 242."""
ms_version = mechanicalsoup.__version__.split('.')
if (int(ms_version[0]), int(ms_version[1])) > (0, 11):
# 0.11.0 buggy, later versions fixed.
return
# Dummy file upload to work around a MechanicalSoup issue when
# some field values are deliberately blank,
# <https://github.com/MechanicalSoup/MechanicalSoup/issues/242>).
form = self.b.get_current_form().form
dummy = form.find('input', attrs={'name': 'dummy'})
if dummy:
# Dummy input already present.
return
temp_file = tempfile.NamedTemporaryFile(dir=self.instance.temp_dir,
delete=False)
filename = temp_file.name
temp_file.close()
self.b.new_control('file', 'dummy', '')
self.b['dummy'] = filename
def set(self, data):
"""Set the contents of fields in the selected form.
Unlike the MechanicalSoup interfaces, 'select' fields are set
by the labels on those fields, not their values.
"""
form = self.b.get_current_form().form
any_empty = False
for key in data:
value = data[key]
select = form.find('select', attrs={'name': key})
if select:
if not isinstance(value, (list, tuple)):
value = (value,)
new_value = []
for v in value:
option = select.find('option', string=v)
new_value.append(option['value'])
if len(new_value) == 1:
new_value = new_value[0]
value = new_value
self.b[key] = value
if value == '':
any_empty = True
if any_empty:
self.workaround_ms_issue_242()
def create(self, cls, data, error=False, mail=False):
"""Create some kind of entity through the corresponding form."""
self.check_open_relative('%s?@template=item' % cls)
self.select_main_form()
self.set(data)
self.check_submit_selected(error=error, mail=mail)
def create_defaults(self, cls, data, defaults, error=False, mail=False):
"""Create some kind of entity with default settings for some fields.
Where a default setting is specified, it is used if no
explicit setting is specified in data. If None is specified
in data, that setting is removed but the default is not
applied.
"""
new_data = dict(data)
for key in defaults:
if key in data:
if data[key] is None:
del new_data[key]
else:
new_data[key] = defaults[key]
self.create(cls, new_data, error=error, mail=mail)
def create_user(self, username, country, roles, other=None):
"""Create a new user account."""
password = roundup.password.generatePassword()
data = {'username': username,
'password': password,
'@confirm@password': password,
'country': country,
'roles': roles}
if other is not None:
data.update(other)
defaults = {'realname': username, 'address': 'test@example.invalid'}
self.create_defaults('user', data, defaults)
self.instance.passwords[username] = password
self.instance.num_users += 1
self.instance.userids[username] = str(self.instance.num_users)
# Verify the id is as expected.
expected_url = '%suser%s' % (self.instance.url,
self.instance.userids[username])
url = self.b.get_url().split('?')[0]
if url != expected_url:
raise ValueError('expected user URL %s, got %s'
% (expected_url, url))
def create_scoring_user(self):
"""Create a scoring user."""
self.create_user('scoring', 'XMO 2015 Staff', 'User,Score')
def create_country(self, code, name, other=None, error=False):
"""Create a country and corresponding user account."""
data = {'code': code, 'name': name}
if other is not None:
data.update(other)
auto_user = 'contact_email' in data and not error
self.create('country', data, error=error, mail=auto_user)
if auto_user:
mail_dec = self.last_mail_dec
username_idx = mail_dec.rindex(b'Username: ')
mail_dec = mail_dec[username_idx:]
mail_data = mail_dec.split(b'\n')
username_str = mail_data[0][len(b'Username: '):]
password_str = mail_data[1]
if not password_str.startswith(b'Password: '):
raise ValueError('unexpected password line: %s'
% str(password_str))
password_str = password_str[len(b'Password: '):]
username = username_str.decode()
password = password_str.decode()
self.instance.passwords[username] = password
self.instance.num_users += 1
self.instance.userids[username] = str(self.instance.num_users)
elif not error:
self.create_user('%s_reg' % code, name, 'User,Register')
def create_country_generic(self):
"""Create a generic country for testing."""
self.create_country('ABC', 'Test First Country')
def create_person(self, country, role, other=None, error=False,
mail=False):
"""Create a person."""
data = {'country': country, 'primary_role': role}
if other is not None:
data.update(other)
self.num_people += 1
defaults = {'given_name': 'Given %d' % self.num_people,
'family_name': 'Family %d' % self.num_people,
'gender': 'Female',
'date_of_birth_year': '2000',
'date_of_birth_month': 'January',
'date_of_birth_day': '1',
'language_1': 'English',
'tshirt': 'S'}
self.create_defaults('person', data, defaults, error=error, mail=mail)
def edit(self, cls, entity_id, data, error=False, mail=False, status=None):
"""Edit some kind of entity through the corresponding form."""
self.check_open_relative('%s%s' % (cls, entity_id))
self.select_main_form()
self.set(data)
self.check_submit_selected(error=error, mail=mail, status=status)
def enter_scores(self, country_name, country_code, problem, scores,
error=False):
"""Enter some scores through the corresponding form."""
self.check_open_relative('person?@template=scoreselect')
self.select_main_form()
self.set({'country': country_name, 'problem': problem})
self.check_submit_selected()
self.select_main_form()
for num, score in enumerate(scores, start=1):
if score is not None:
self.set({'%s%d' % (country_code, num): score})
self.workaround_ms_issue_242()
self.check_submit_selected(error=error)
def edit_prereg(self, entity_id, data, error=False, mail=False):
"""Edit preregistration data through the corresponding form."""
self.check_open_relative('country%s?@template=prereg'
% entity_id)
self.select_main_form()
self.set(data)
self.check_submit_selected(error=error, mail=mail)
def _with_config(**kwargs):
"""A decorator to add a config attribute to a test method."""
def decorator(test_fn):
test_fn.config = kwargs
return test_fn
return decorator
@unittest.skipIf(_skip_test, 'required modules not installed')
class RegSystemTestCase(unittest.TestCase):
"""
A RegSystemTestCase verifies the operation of the matholymp
registration system.
"""
def __init__(self, method_name='runTest'):
"""Initialise a RegSystemTestCase."""
# Save the method name for use in __str__ without relying on
# unittest internals of how it stores the method name.
self.method_name = method_name
method = getattr(self, method_name)
self.config = getattr(method, 'config', {})
self.coverage = False
super(RegSystemTestCase, self).__init__(method_name)
def __str__(self):
# Generate test names similar to those for script tests.
test_name = self.method_name
if test_name.startswith('test_'):
test_name = test_name[len('test_'):]
test_name = test_name.replace('_', '-')
return 'registration-system ' + test_name
def setUp(self):
self.sessions = []
self.temp_dir_td = tempfile.TemporaryDirectory()
self.temp_dir = self.temp_dir_td.name
self.instance = RoundupTestInstance(sys.path[0], self.temp_dir,
self.config, self.coverage)
def tearDown(self):
for s in self.sessions:
s.close()
self.instance.stop_server()
if self.coverage:
# pylint: disable=import-outside-toplevel
from coverage import Coverage
cov_base = os.path.join(sys.path[0], '.coverage.reg-system')
cov = Coverage(data_file=cov_base)
cov.load()
cov.combine(data_paths=[self.temp_dir])
cov.save()
self.temp_dir_td.cleanup()
def get_session(self, username=None):
"""Get a session for the specified username."""
session = RoundupTestSession(self.instance, username)
self.sessions.append(session)
return session
def gen_test_image(self, size_x, size_y, scale, suffix, fmt, mode='RGB'):
"""Generate a test image and return a tuple of the filename and the
contents."""
temp_file = tempfile.NamedTemporaryFile(suffix=suffix,
dir=self.temp_dir,
delete=False)
filename = temp_file.name
temp_file.close()
gen_image_file(size_x, size_y, scale, filename, fmt, mode)
with open(filename, 'rb') as f:
contents = f.read()
return filename, contents
def gen_test_pdf(self, suffix='.pdf'):
"""Generate a test PDF and return a tuple of the filename and the
contents."""
temp_dir = tempfile.mkdtemp(dir=self.temp_dir)
filename = gen_pdf_file(temp_dir, suffix)
with open(filename, 'rb') as f:
contents = f.read()
return filename, contents
def gen_test_csv(self, rows, keys, delimiter=','):
"""Generate a CSV file with specified contents."""
temp_file = tempfile.NamedTemporaryFile(suffix='.csv',
dir=self.temp_dir,
delete=False)
filename = temp_file.name
temp_file.close()
write_utf8_csv(filename, rows, keys, delimiter=delimiter)
return filename
def gen_test_csv_no_bom(self, rows, keys):
"""Generate a CSV file with specified contents and no BOM."""
temp_file = tempfile.NamedTemporaryFile(suffix='.csv',
dir=self.temp_dir,
delete=False)
filename = temp_file.name
temp_file.close()
file_contents = write_utf8_csv_bytes(rows, keys)
file_contents = file_contents[len(codecs.BOM_UTF8):]
write_bytes_to_file(file_contents, filename)
return filename
def gen_test_zip(self, data):
"""Generate a ZIP file with specified contents."""
temp_file = tempfile.NamedTemporaryFile(suffix='.zip',
dir=self.temp_dir,
delete=False)
filename = temp_file.name
temp_file.close()
with zipfile.ZipFile(filename, 'w') as zip_zip:
for member_filename, contents in data.items():
zip_zip.writestr(member_filename, contents)
return filename
def all_templates_test(self, session, forbid_classes, forbid_templates,
allow_templates, can_score, admin_user):
"""Test that all page templates load without errors."""
for t in sorted(os.listdir(self.instance.html_dir)):
if t.startswith('_generic') or not t.endswith('.html'):
continue
m = re.fullmatch(r'([a-z_]+)\.([a-z_]+)\.html', t)
if not m:
continue
# country.bulkconfirm.html and person.bulkconfirm.html
# should given an error, if an admin user, unless used
# with an upload of a CSV file. person.scoreenter.html
# should give an error, if able to enter scores, unless
# country and problem are specified.
error = ((can_score and t == 'person.scoreenter.html')
or (admin_user and t.endswith('.bulkconfirm.html')))
login = ((m.group(1) in forbid_classes or t in forbid_templates)
and t not in allow_templates)
session.check_open_relative('%s?@template=%s'
% (m.group(1), m.group(2)),
error=error, login=login)
def test_all_templates_admin(self):
"""
Test that all page templates load without errors, for the admin user.
"""
session = self.get_session('admin')
# This one gives an error when used without a particular
# country specified.
forbid_templates = {'country.prereg.html'}
self.all_templates_test(session, forbid_classes=set(),
forbid_templates=forbid_templates,
allow_templates=set(), can_score=True,
admin_user=True)
def test_all_templates_anon(self):
"""
Test that all page templates load without errors, not logged in.
"""
session = self.get_session()
forbid_classes = {'event', 'rss', 'arrival', 'badge_type',
'consent_form', 'gender', 'language', 'room_type',
'tshirt', 'user'}
forbid_templates = {'country.bulkconfirm.html',
'country.bulkregister.html',
'country.retireconfirm.html',
'person.bulkconfirm.html',
'person.bulkregister.html',
'person.retireconfirm.html',
'person.rooms.html',
'person.scoreenter.html',
'person.scoreselect.html',
'person.status.html'}
self.all_templates_test(session, forbid_classes=forbid_classes,
forbid_templates=forbid_templates,
allow_templates={'user.forgotten.html'},
can_score=False, admin_user=False)
def test_all_templates_score(self):
"""
Test that all page templates load without errors, for a scoring user.
"""
admin_session = self.get_session('admin')
admin_session.create_scoring_user()
session = self.get_session('scoring')
forbid_classes = {'event', 'rss', 'arrival', 'badge_type',
'consent_form', 'gender', 'language', 'room_type',
'tshirt'}
forbid_templates = {'country.bulkconfirm.html',
'country.bulkregister.html',
'country.prereg.html',
'country.retireconfirm.html',
'person.bulkconfirm.html',
'person.bulkregister.html',
'person.retireconfirm.html',
'person.rooms.html',
'person.status.html'}
self.all_templates_test(session, forbid_classes=forbid_classes,
forbid_templates=forbid_templates,
allow_templates=set(),
can_score=True, admin_user=False)
def test_all_templates_register(self):
"""
Test that all page templates load without errors, for a
registering user.
"""
admin_session = self.get_session('admin')
admin_session.create_country_generic()
session = self.get_session('ABC_reg')
forbid_classes = {'badge_type', 'event', 'rss'}
forbid_templates = {'country.bulkconfirm.html',
'country.bulkregister.html',
'country.prereg.html',
'country.retireconfirm.html',
'person.bulkconfirm.html',
'person.bulkregister.html',
'person.retireconfirm.html',
'person.rooms.html',
'person.scoreenter.html',
'person.scoreselect.html'}
self.all_templates_test(session, forbid_classes=forbid_classes,
forbid_templates=forbid_templates,
allow_templates=set(),
can_score=False, admin_user=False)
def all_templates_item_test(self, admin_session, session, forbid_classes):
"""Test that all page templates for existing items load without
errors."""