-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest_cronjobs.py
More file actions
2519 lines (2098 loc) · 84 KB
/
Copy pathtest_cronjobs.py
File metadata and controls
2519 lines (2098 loc) · 84 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 json
import logging
import os
from pathlib import Path
from unittest.mock import patch, Mock
import pytest
import requests
import transaction
from datetime import datetime, timedelta, timezone
from freezegun import freeze_time
from onegov.core.utils import Bunch, normalize_for_url
from onegov.directory import (DirectoryEntryCollection,
DirectoryConfiguration,
DirectoryCollection)
from onegov.directory.collections.directory import EntryRecipientCollection
from onegov.event import EventCollection, OccurrenceCollection, Event
from onegov.event.utils import as_rdates
from onegov.form import FormSubmissionCollection
from onegov.org.models import (
ResourceRecipientCollection, News, PushNotification)
from onegov.org.models.page import NewsCollection
from onegov.org.models.resource import RoomResource
from onegov.org.models.ticket import ReservationHandler, DirectoryEntryHandler
from onegov.org.notification_service import (
TestNotificationService, set_test_notification_service)
from onegov.page import PageCollection
from onegov.ticket import Handler, Ticket, TicketCollection
from onegov.user import UserCollection
from onegov.newsletter import (Newsletter, NewsletterCollection,
RecipientCollection)
from onegov.reservation import ResourceCollection
from onegov.user.collections import TANCollection
from sedate import ensure_timezone, utcnow
from sqlalchemy.orm import close_all_sessions
from tests.onegov.org.common import get_cronjob_by_name, get_cronjob_url
from decimal import Decimal
from tests.shared import Client
from tests.shared.utils import add_reservation
class EchoTicket(Ticket):
__mapper_args__ = {'polymorphic_identity': 'EHO'}
es_type_name = 'echo_tickets'
class EchoHandler(Handler):
handler_title = "Echo"
@property
def deleted(self):
return False
@property
def email(self):
return self.data.get('email')
@property
def title(self):
return self.data.get('title')
@property
def subtitle(self):
return self.data.get('subtitle')
@property
def group(self):
return self.data.get('group')
def get_summary(self, request):
return self.data.get('summary')
def get_links(self, request):
return self.data.get('links')
def register_echo_handler(handlers):
handlers.register('EHO', EchoHandler)
def register_reservation_handler(handlers):
handlers.register('RSV', ReservationHandler)
def register_directory_handler(handlers):
handlers.register('DIR', DirectoryEntryHandler)
def test_daily_ticket_statistics(org_app, handlers):
register_echo_handler(handlers)
client = Client(org_app)
job = get_cronjob_by_name(org_app, 'daily_ticket_statistics')
job.app = org_app
url = get_cronjob_url(job)
tz = ensure_timezone('Europe/Zurich')
assert len(os.listdir(client.app.maildir)) == 0
transaction.begin()
session = org_app.session()
collection = TicketCollection(session)
tickets = [
collection.open_ticket(
handler_id='1',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 2, 10, tzinfo=tz),
),
collection.open_ticket(
handler_id='2',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 2, 10, tzinfo=tz)
),
collection.open_ticket(
handler_id='3',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 2, 10, tzinfo=tz)
),
collection.open_ticket(
handler_id='4',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 2, 10, tzinfo=tz)
),
collection.open_ticket(
handler_id='5',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 2, 10, tzinfo=tz)
),
collection.open_ticket(
handler_id='6',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 2, 10, tzinfo=tz)
)
]
# those will be ignored as they are inactive or not editors/admins
request = Bunch(client_addr='127.0.0.1')
UserCollection(session).register('a', 'p@ssw0rd', request, role='editor')
UserCollection(session).register('b', 'p@ssw0rd', request, role='member')
users = UserCollection(session).query().all()
user = users[0]
users[0].data = {'ticket_statistics': 'daily'}
for ticket in tickets:
ticket.created = datetime(2016, 1, 2, 10, tzinfo=tz)
for pending in tickets[1:3]:
pending.accept_ticket(user)
pending.modified = datetime(2016, 1, 2, 10, tzinfo=tz)
for closed in tickets[3:6]:
closed.accept_ticket(user)
closed.close_ticket()
closed.modified = datetime(2016, 1, 2, 10, tzinfo=tz)
transaction.commit()
with freeze_time(datetime(2016, 1, 4, tzinfo=tz)):
client.get(url)
assert len(os.listdir(client.app.maildir)) == 1
message = client.get_email(0)
headers = {h['Name']: h['Value'] for h in message['Headers']}
assert 'List-Unsubscribe' in headers
assert 'List-Unsubscribe-Post' in headers
unsubscribe = headers['List-Unsubscribe'].strip('<>')
assert message['Subject'] == 'Govikon OneGov Cloud Status'
txt = message['TextBody']
assert "Folgendes ist während des Wochenendes auf der Govikon" in txt
assert "6 Tickets wurden eröffnet." in txt
assert "2 Tickets wurden angenommen." in txt
assert "3 Tickets wurden geschlossen." in txt
assert "Zur Zeit ist 1 Ticket " in txt
assert "/tickets/ALL/open?page=0" in txt
assert "2 Tickets sind " in txt
assert "/tickets/ALL/pending?page=0" in txt
assert "Wir wünschen Ihnen eine schöne Woche!" in txt
assert "/unsubscribe?token=" in txt
assert "abmelden" in txt
assert unsubscribe in txt
# do not run on the weekends
with freeze_time(datetime(2016, 1, 2, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 1, 3, tzinfo=tz)):
client.get(url)
# no additional mails have been sent
assert len(os.listdir(client.app.maildir)) == 1
def test_weekly_ticket_statistics(org_app, handlers):
register_echo_handler(handlers)
client = Client(org_app)
job = get_cronjob_by_name(org_app, 'weekly_ticket_statistics')
job.app = org_app
url = get_cronjob_url(job)
tz = ensure_timezone('Europe/Zurich')
assert len(os.listdir(client.app.maildir)) == 0
transaction.begin()
session = org_app.session()
collection = TicketCollection(session)
tickets = [
collection.open_ticket(
handler_id='1',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 5, 10, tzinfo=tz),
),
collection.open_ticket(
handler_id='2',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 6, 10, tzinfo=tz)
),
collection.open_ticket(
handler_id='3',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 7, 10, tzinfo=tz)
),
collection.open_ticket(
handler_id='4',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 8, 10, tzinfo=tz)
),
collection.open_ticket(
handler_id='5',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 9, 10, tzinfo=tz)
),
collection.open_ticket(
handler_id='6',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 10, 10, tzinfo=tz)
)
]
# those will be ignored as they are inactive or not editors/admins
request = Bunch(client_addr='127.0.0.1')
UserCollection(session).register('a', 'p@ssw0rd', request, role='editor')
UserCollection(session).register('b', 'p@ssw0rd', request, role='member')
users = UserCollection(session).query().all()
user = users[0]
users[1].data = {'ticket_statistics': 'never'}
for index, ticket in enumerate(tickets):
ticket.created = datetime(2016, 1, 5 + index, 10, tzinfo=tz)
for pending in tickets[1:3]:
pending.accept_ticket(user)
pending.modified = datetime(2016, 1, 9, 10, tzinfo=tz)
for closed in tickets[3:6]:
closed.accept_ticket(user)
closed.close_ticket()
closed.modified = datetime(2016, 1, 10, 10, tzinfo=tz)
transaction.commit()
with freeze_time(datetime(2016, 1, 11, tzinfo=tz)):
client.get(url)
assert len(os.listdir(client.app.maildir)) == 1
message = client.get_email(0)
headers = {h['Name']: h['Value'] for h in message['Headers']}
assert 'List-Unsubscribe' in headers
assert 'List-Unsubscribe-Post' in headers
unsubscribe = headers['List-Unsubscribe'].strip('<>')
assert message['Subject'] == 'Govikon OneGov Cloud Status'
txt = message['TextBody']
assert "Folgendes ist während der letzten Woche auf der Govikon" in txt
assert "6 Tickets wurden eröffnet." in txt
assert "2 Tickets wurden angenommen." in txt
assert "3 Tickets wurden geschlossen." in txt
assert "Zur Zeit ist 1 Ticket " in txt
assert "/tickets/ALL/open?page=0" in txt
assert "2 Tickets sind " in txt
assert "/tickets/ALL/pending?page=0" in txt
assert "Wir wünschen Ihnen eine schöne Woche!" in txt
assert "/unsubscribe?token=" in txt
assert "abmelden" in txt
assert unsubscribe in txt
# we only run on mondays
with freeze_time(datetime(2016, 1, 5, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 1, 6, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 1, 7, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 1, 8, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 1, 9, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 1, 10, tzinfo=tz)):
client.get(url)
# no additional mails have been sent
assert len(os.listdir(client.app.maildir)) == 1
def test_monthly_ticket_statistics(org_app, handlers):
register_echo_handler(handlers)
client = Client(org_app)
job = get_cronjob_by_name(org_app, 'monthly_ticket_statistics')
job.app = org_app
url = get_cronjob_url(job)
tz = ensure_timezone('Europe/Zurich')
assert len(os.listdir(client.app.maildir)) == 0
transaction.begin()
session = org_app.session()
collection = TicketCollection(session)
tickets = [
collection.open_ticket(
handler_id='1',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 4, 10, tzinfo=tz),
),
collection.open_ticket(
handler_id='2',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 9, 10, tzinfo=tz)
),
collection.open_ticket(
handler_id='3',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 14, 10, tzinfo=tz)
),
collection.open_ticket(
handler_id='4',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 19, 10, tzinfo=tz)
),
collection.open_ticket(
handler_id='5',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 24, 10, tzinfo=tz)
),
collection.open_ticket(
handler_id='6',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
created=datetime(2016, 1, 29, 10, tzinfo=tz)
)
]
# those will be ignored as they are inactive or not editors/admins
request = Bunch(client_addr='127.0.0.1')
UserCollection(session).register('a', 'p@ssw0rd', request, role='editor')
UserCollection(session).register('b', 'p@ssw0rd', request, role='member')
users = UserCollection(session).query().all()
user = users[0]
users[0].data = {'ticket_statistics': 'monthly'}
for index, ticket in enumerate(tickets):
ticket.created = datetime(2016, 1, 4 + index * 5, 10, tzinfo=tz)
for pending in tickets[2:3]:
pending.accept_ticket(user)
pending.modified = datetime(2016, 1, 22, 10, tzinfo=tz)
for closed in tickets[3:6]:
closed.accept_ticket(user)
closed.close_ticket()
closed.modified = datetime(2016, 1, 31, 10, tzinfo=tz)
transaction.commit()
with freeze_time(datetime(2016, 2, 1, tzinfo=tz)):
client.get(url)
assert len(os.listdir(client.app.maildir)) == 1
message = client.get_email(0)
headers = {h['Name']: h['Value'] for h in message['Headers']}
assert 'List-Unsubscribe' in headers
assert 'List-Unsubscribe-Post' in headers
unsubscribe = headers['List-Unsubscribe'].strip('<>')
assert message['Subject'] == 'Govikon OneGov Cloud Status'
txt = message['TextBody']
assert "Folgendes ist während des letzten Monats auf der Govikon" in txt
assert "6 Tickets wurden eröffnet." in txt
assert "1 Ticket wurde angenommen." in txt
assert "3 Tickets wurden geschlossen." in txt
assert "Zur Zeit sind 2 Tickets " in txt
assert "/tickets/ALL/open?page=0" in txt
assert "1 Ticket ist " in txt
assert "/tickets/ALL/pending?page=0" in txt
assert "Wir wünschen Ihnen eine schöne Woche!" in txt
assert "/unsubscribe?token=" in txt
assert "abmelden" in txt
assert unsubscribe in txt
# we only run on first monday of the month
with freeze_time(datetime(2016, 2, 2, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 2, 3, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 2, 4, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 2, 5, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 2, 6, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 2, 7, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 2, 8, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 2, 15, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 2, 22, tzinfo=tz)):
client.get(url)
with freeze_time(datetime(2016, 2, 29, tzinfo=tz)):
client.get(url)
# no additional mails have been sent
assert len(os.listdir(client.app.maildir)) == 1
def test_daily_reservation_overview(org_app):
resources = ResourceCollection(org_app.libres_context)
gymnasium = resources.add('Gymnasium', 'Europe/Zurich', type='room')
dailypass = resources.add('Dailypass', 'Europe/Zurich', type='daypass')
assert isinstance(gymnasium, RoomResource)
gymnasium.definition = """
Name = ___
"""
gym_allocation = gymnasium.scheduler.allocate(
(datetime(2017, 1, 6, 12), datetime(2017, 1, 6, 16)),
partly_available=True,
)[0]
day_allocation = dailypass.scheduler.allocate(
(datetime(2017, 1, 6, 12), datetime(2017, 1, 6, 16)),
partly_available=False,
whole_day=True
)[0]
gym_reservation_token = gymnasium.scheduler.reserve(
'gym-reservation@example.org',
(gym_allocation.start, gym_allocation.end),
)
day_reservation_token = dailypass.scheduler.reserve(
'day-reservation@example.org',
(day_allocation.start, day_allocation.end)
)
gymnasium.scheduler.approve_reservations(gym_reservation_token)
dailypass.scheduler.approve_reservations(day_reservation_token)
submissions = FormSubmissionCollection(org_app.session())
submissions.add_external(
form=gymnasium.form_class(data={'name': '0xdeadbeef'}),
state='complete',
id=gym_reservation_token
)
recipients = ResourceRecipientCollection(org_app.session())
recipients.add(
name='Gym',
medium='email',
address='gym@example.org',
daily_reservations=True,
send_on=['FR'],
resources=[
gymnasium.id.hex
]
)
recipients.add(
name='Day',
medium='email',
address='day@example.org',
daily_reservations=True,
send_on=['FR'],
resources=[
dailypass.id.hex
]
)
recipients.add(
name='Both',
medium='email',
address='both@example.org',
daily_reservations=True,
send_on=['SA'],
resources=[
dailypass.id.hex,
gymnasium.id.hex
]
)
transaction.commit()
client = Client(org_app)
job = get_cronjob_by_name(org_app, 'daily_resource_usage')
job.app = org_app
url = get_cronjob_url(job)
tz = ensure_timezone('Europe/Zurich')
# do not send an e-mail outside the selected days
for day in [2, 3, 4, 5, 8]:
with freeze_time(datetime(2017, 1, day, tzinfo=tz), tick=True):
client.get(url)
assert len(os.listdir(client.app.maildir)) == 0
# only send e-mails to the users with the right selection
with freeze_time(datetime(2017, 1, 6, tzinfo=tz), tick=True):
client.get(url)
assert len(os.listdir(client.app.maildir)) == 2
with freeze_time(datetime(2017, 1, 7, tzinfo=tz), tick=True):
client.get(url)
assert len(os.listdir(client.app.maildir)) == 3
# there are no really confirmed reservations at this point, so the
# e-mail will not contain any information info
client.flush_email_queue()
with freeze_time(datetime(2017, 1, 6, tzinfo=tz), tick=True):
client.get(url)
mails = [client.get_email(i) for i in range(2)]
for mail in mails:
assert "Heute keine Reservationen" in mail['TextBody']
assert "-reservation" not in mail['TextBody']
# NOTE: These seem to not always get sent in the same order...
# technically we don't really care so let's determine order
if mails[0]['To'] == 'gym@example.org':
gym_mail, day_mail = mails
else:
day_mail, gym_mail = mails
assert gym_mail['To'] == 'gym@example.org'
assert "Allgemein - Gymnasium" in gym_mail['TextBody']
assert "Allgemein - Dailypass" not in gym_mail['TextBody']
assert day_mail['To'] == 'day@example.org'
assert "Allgemein - Dailypass" in day_mail['TextBody']
assert "Allgemein - Gymnasium" not in day_mail['TextBody']
# once we confirm the reservation it shows up in the e-mail
client.flush_email_queue()
gymnasium = resources.by_name('gymnasium')
r = gymnasium.scheduler.reservations_by_token(gym_reservation_token)[0]
r.data = {'accepted': True}
transaction.commit()
with freeze_time(datetime(2017, 1, 6, tzinfo=tz), tick=True):
client.get(url)
with freeze_time(datetime(2017, 1, 7, tzinfo=tz), tick=True):
client.get(url)
# NOTE: These seem to not always get sent in the same order...
# technically we don't really care so let's determine order
if '0xdeadbeef' in client.get_email(0)['TextBody']:
assert '0xdeadbeef' not in client.get_email(1)['TextBody']
else:
assert '0xdeadbeef' in client.get_email(1)['TextBody']
mail = client.get_email(2)
assert mail['To'] == 'both@example.org'
assert 'Gymnasium' in mail['TextBody']
assert 'Dailypass' in mail['TextBody']
assert '0xdeadbeef' not in mail['TextBody'] # diff. day
# this also works for the other reservation which has no data
client.flush_email_queue()
dailypass = resources.by_name('dailypass')
r = dailypass.scheduler.reservations_by_token(day_reservation_token)[0]
r.data = {'accepted': True}
transaction.commit()
with freeze_time(datetime(2017, 1, 6, tzinfo=tz), tick=True):
client.get(url)
# NOTE: These seem to not always get sent in the same order...
# technically we don't really care so let's determine order
text = client.get_email(0)['TextBody']
if 'day-reservation' in text:
assert 'gym-reservation' not in text
else:
assert 'gym-reservation' in text
text = client.get_email(1)['TextBody']
if 'gym-reservation' in text:
assert 'day-reservation' not in text
else:
assert 'day-reservation' in text
@pytest.mark.parametrize('secret_content_allowed', [False, True])
def test_send_scheduled_newsletters(client, org_app, secret_content_allowed):
def create_scheduled_newsletter():
with freeze_time('2018-05-31 12:00'):
news_public = news.add(
news_parent, 'Public News', 'public-news',
type='news', access='public')
news_public_2 = news.add(
news_parent,
'Public News - not published',
'public-news-not-published',
type='news', access='public',
publication_start=utcnow() + timedelta(days=1),
publication_end=utcnow() + timedelta(days=2))
news_secret = news.add(
news_parent, 'Secret News', 'secret-news',
type='news', access='secret')
news_private = news.add(
news_parent, 'Private News', 'private-news',
type='news', access='private')
newsletters.add(
"Latest News",
"<h1>Latest News</h1>",
content={"news": [
str(news_public.id),
str(news_public_2.id),
str(news_secret.id),
str(news_private.id)
]},
scheduled=utcnow()
)
transaction.commit()
session = org_app.session()
news = PageCollection(session)
news_parent = news.query().filter_by(name='news').one()
newsletters = NewsletterCollection(session)
recipients = RecipientCollection(session)
recipient = recipients.add('info@example.org')
recipient.confirmed = True
org_app.org.secret_content_allowed = secret_content_allowed
org_app.org.enable_automatic_newsletters = True
create_scheduled_newsletter()
job = get_cronjob_by_name(org_app, 'hourly_maintenance_tasks')
job.app = org_app
with freeze_time('2018-05-31 11:00'):
client = Client(org_app)
client.get(get_cronjob_url(job))
newsletter = newsletters.query().one()
assert newsletter.scheduled # still scheduled, not sent yet
assert len(os.listdir(client.app.maildir)) == 0
with freeze_time('2018-05-31 12:00'):
client = Client(org_app)
client.get(get_cronjob_url(job))
newsletter = newsletters.query().one()
assert not newsletter.scheduled
assert len(os.listdir(client.app.maildir)) == 1
mail_file = Path(client.app.maildir) / os.listdir(client.app.maildir)[
0]
with open(mail_file, 'r') as file:
mail = json.loads(file.read())[0]
assert "info@example.org" == mail['To']
assert "Latest News" in mail['Subject']
assert "Public News" in mail['TextBody']
assert "Public News - not published" not in mail['TextBody']
if secret_content_allowed:
assert "Secret News" in mail['TextBody']
assert "Private News" not in mail['TextBody']
def test_send_daily_newsletter(es_org_app):
org_app = es_org_app
tz = ensure_timezone('Europe/Zurich')
session = org_app.session()
org_app.org.enable_automatic_newsletters = True
org_app.org.show_news_as_tiles = False
org_app.org.newsletter_times = '10', '11', '16'
news = PageCollection(session)
news_parent = news.query().filter_by(name='news').one()
recipients = RecipientCollection(session)
recipient = recipients.add('daily@example.org', confirmed=True)
recipient.daily_newsletter = True
recipient = recipients.add('info@example.org', confirmed=True)
recipient.daily_newsletter = False
with freeze_time(datetime(2018, 3, 2, 17, 0, tzinfo=tz)):
# Created three days ago, published yesterday at 17:00
news.add(
parent=news_parent, title='News1', type='news', access='public',
publication_start=utcnow() + timedelta(days=2))
with freeze_time(datetime(2018, 3, 4, 17, 0, tzinfo=tz)):
# Created yesterday at 17:00, published immediately
news.add(
parent=news_parent, title='News2', type='news', access='public')
with freeze_time(datetime(2018, 3, 5, 10, 0, tzinfo=tz)):
# Created today at 10:00, published immediately
news.add(
parent=news_parent, title='News3', type='news', access='public',
lead='Lead of News 3',
)
# Created today at 10:00, published today 10:01
news.add(
parent=news_parent, title='News4', type='news', access='public',
publication_start=utcnow() + timedelta(minutes=1),
lead='Lead of News 4',
)
transaction.commit()
job = get_cronjob_by_name(org_app, 'hourly_maintenance_tasks')
job.app = org_app
client = Client(org_app)
with freeze_time(datetime(2018, 3, 5, 10, 0, tzinfo=tz)):
client.get(get_cronjob_url(job))
newsletter = NewsletterCollection(session).query().one()
assert newsletter.title == 'Täglicher Newsletter 05.03.2018, 10:00'
assert len(os.listdir(client.app.maildir)) == 1
mail = client.get_email(0)
assert 'News1' in mail['TextBody']
assert 'News2' in mail['TextBody']
assert 'News3' not in mail['TextBody']
assert 'News4' not in mail['TextBody']
org_app.org.show_news_as_tiles = True
transaction.commit()
with freeze_time(datetime(2018, 3, 5, 11, 0, tzinfo=tz)):
client.get(get_cronjob_url(job))
newsletter = NewsletterCollection(session).query().filter(
Newsletter.title.like('%Täglicher Newsletter 05.03.2018, 11:00%'
)).one()
assert 'Täglicher Newsletter 05.03.2018, 11:00' in newsletter.title
assert len(os.listdir(client.app.maildir)) == 2
mail = client.get_email(1)
assert 'News1' not in mail['TextBody']
assert 'News2' not in mail['TextBody']
assert 'News3' in mail['TextBody']
assert 'Lead of News 3' in mail['TextBody']
assert 'News4' in mail['TextBody']
assert 'Lead of News 4' in mail['TextBody']
with freeze_time(datetime(2018, 3, 5, 16, 0, tzinfo=tz)):
client.get(get_cronjob_url(job))
assert NewsletterCollection(session).query().count() == 2
assert len(os.listdir(client.app.maildir)) == 2
def test_auto_archive_tickets_and_delete(org_app, handlers):
register_echo_handler(handlers)
session = org_app.session()
transaction.begin()
with freeze_time('2022-08-17 04:30'):
collection = TicketCollection(session)
tickets = [
collection.open_ticket(
handler_id='1',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
),
collection.open_ticket(
handler_id='2',
handler_code='EHO',
title="Title",
group="Group",
email="citizen@example.org",
),
]
request = Bunch(client_addr='127.0.0.1')
UserCollection(session).register(
'b', 'p@ssw0rd', request, role='admin'
)
users = UserCollection(session).query().all()
user = users[0]
for t in tickets:
t.accept_ticket(user)
t.close_ticket()
org_app.org.auto_archive_timespan = 30 # days
org_app.org.auto_delete_timespan = 30 # days
transaction.commit()
close_all_sessions()
# now we go forward a month for archival
with freeze_time('2022-09-17 04:30'):
query = session.query(Ticket)
query = query.filter_by(state='closed')
assert query.count() == 2
job = get_cronjob_by_name(org_app, 'archive_old_tickets')
job.app = org_app
client = Client(org_app)
client.get(get_cronjob_url(job))
query = session.query(Ticket)
query = query.filter(Ticket.state == 'archived')
assert query.count() == 2
# this delete cronjob should have no effect (yet), since archiving
# resets the `last_change`
job = get_cronjob_by_name(org_app, 'delete_old_tickets')
job.app = org_app
client = Client(org_app)
client.get(get_cronjob_url(job))
query = session.query(Ticket)
query = query.filter(Ticket.state == 'archived')
assert query.count() == 2
# and another month for deletion
with freeze_time('2022-10-17 05:30'):
session.flush()
assert org_app.org.auto_delete_timespan is not None
job = get_cronjob_by_name(org_app, 'delete_old_tickets')
job.app = org_app
client = Client(org_app)
client.get(get_cronjob_url(job))
# should be deleted
assert session.query(Ticket).count() == 0
def test_respect_recent_reservation_for_archive(org_app, handlers):
register_echo_handler(handlers)
register_reservation_handler(handlers)
transaction.begin()
resources = ResourceCollection(org_app.libres_context)
dailypass = resources.add(
'Dailypass',
'Europe/Zurich',
type='daypass'
)
recipients = ResourceRecipientCollection(org_app.session())
recipients.add(
name='John',
medium='email',
address='john@example.org',
rejected_reservations=True,
resources=[
dailypass.id.hex,
],
)
with freeze_time('2022-06-06 01:00'):
# First we add some random ticket. Acts Kind of like a 'control
# group', this is not reservation)
collection = TicketCollection(org_app.session())
collection.open_ticket(
handler_id='1',
handler_code='EHO',
title="Control Ticket",
group="Group",
email="citizen@example.org",
)
# Secondly we add a reservation for one year in advance (indeed not
# uncommon in practice)
add_reservation(
dailypass,
org_app.session(),
start=datetime(2023, 6, 6, 4, 30),
end=datetime(2023, 6, 6, 5, 0),
)
# close all the tickets
tickets_query = TicketCollection(org_app.session()).query()
assert tickets_query.count() == 2
user = UserCollection(org_app.session()).query().first()
for ticket in tickets_query:
ticket.accept_ticket(user)
ticket.close_ticket()
org_app.org.auto_archive_timespan = 365 # days
org_app.org.auto_delete_timespan = 365 # days
transaction.commit()