-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpages.py
More file actions
2028 lines (1539 loc) · 75.8 KB
/
pages.py
File metadata and controls
2028 lines (1539 loc) · 75.8 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 datetime
import os
import re
import shutil
from typing import Literal
from urllib.parse import urljoin, urlparse, urlsplit
from retry import retry
from selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
TimeoutException,
WebDriverException,
)
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from config import config
from tests.decorators import retry_on_stale_element_exception
from tests.pages.element import (
BasePageElement,
EmailInputElement,
FileInputElement,
MobileInputElement,
NameInputElement,
NewPasswordInputElement,
PasswordInputElement,
ServiceInputElement,
ServiceJoinRequestChooseServiceInputElement,
ServiceJoinRequestJoinAskReasonTextAreaElement,
SmsInputElement,
SubjectInputElement,
TemplateContentElement,
)
from tests.pages.locators import (
AddFileToEmailTemplatePageLocators,
AddServicePageLocators,
ApiIntegrationPageLocators,
ChangeNameLocators,
CommonPageLocators,
EditTemplatePageLocators,
EmailReplyToLocators,
InviteUserPageLocators,
JobPageLocators,
LetterPreviewPageLocators,
MainPageLocators,
ManageEmailTemplateFilePageLocators,
ManageLetterAttachPageLocators,
NavigationLocators,
RenameTemplatePageLocators,
SendLetterPreviewPageLocators,
ServiceJoinRequestApprovePageLocators,
ServiceJoinRequestChoosePermissionsPageLocators,
ServiceJoinRequestChooseServicePageLocators,
ServiceJoinRequestJoinAskPageLocators,
ServiceSettingsLocators,
SignInPageLocators,
SingleRecipientLocators,
SmsSenderLocators,
TeamMembersPageLocators,
TemplatePageLocators,
VerifyPageLocators,
ViewEmailTemplatePageLocators,
ViewLetterTemplatePageLocators,
ViewTemplatePageLocators,
YourServicesPageLocators,
)
class RetryException(Exception):
pass
class AntiStale:
def __init__(self, driver, locator, webdriverwait_func):
"""
webdriverwait_func is a function that takes in a locator and returns an element. Probably a webdriverwait.
"""
self.driver = driver
self.webdriverwait_func = webdriverwait_func
self.locator = locator
# kick it off
self.element = self.webdriverwait_func(self.locator)
@retry(RetryException, tries=5)
def retry_on_stale(self, callable):
try:
return callable()
except StaleElementReferenceException:
self.reset_element()
def reset_element(self):
self.element = self.webdriverwait_func(self.locator)
raise RetryException(f"StaleElement {self.locator}")
class AntiStaleElement(AntiStale):
def click(self):
def _click():
# an element might be hidden underneath other elements (eg sticky nav items). To counter this, we can use
# the scrollIntoView function to bring it to the top of the page
self.driver.execute_script("arguments[0].scrollIntoViewIfNeeded()", self.element)
try:
self.element.click()
except WebDriverException:
self.driver.execute_script("arguments[0].scrollIntoView()", self.element)
self.element.click()
return self.retry_on_stale(_click)
def __getattr__(self, attr):
return self.retry_on_stale(lambda: getattr(self.element, attr))
class AntiStaleElementList(AntiStale):
def __getitem__(self, index):
class AntiStaleListItem:
def click(item_self):
return self.retry_on_stale(lambda: self.element[index].click())
def __getattr__(item_self, attr):
return self.retry_on_stale(lambda: getattr(self.element[index], attr))
return AntiStaleListItem()
def __len__(self):
return len(self.element)
class BasePage:
sign_out_link = NavigationLocators.SIGN_OUT_LINK
profile_page_link = NavigationLocators.PROFILE_LINK
h1_text = (By.CSS_SELECTOR, "h1")
templates_link = NavigationLocators.TEMPLATES_LINK
def __init__(self, driver):
self.base_url = config["notify_admin_url"]
self.driver = driver
def get(self, url=None):
if url:
self.driver.get(url)
else:
self.driver.get(self.base_url)
@property
def current_url(self):
return self.driver.current_url
def no_element_error_msg(self, locator):
return f"Could not locate element {locator} on URL {self.current_url}"
def wait_for_design_system_checkbox_or_radio(self, locator, time=10):
"""GOV.UK Design System 'hides' the original HTML input for checkboxes/radios to provide more accessible
visual alternatives. These end up making a `visibility_of_element_located` check fail, so for these specific
elements lets bypass that condition.
"""
return AntiStaleElement(
self.driver,
locator,
lambda locator: WebDriverWait(self.driver, time).until(
EC.presence_of_element_located(locator),
self.no_element_error_msg(locator),
),
)
def wait_for_element(self, locator, time=10):
return AntiStaleElement(
self.driver,
locator,
lambda locator: WebDriverWait(self.driver, time).until(
EC.visibility_of_element_located(locator),
self.no_element_error_msg(locator),
),
)
def wait_for_elements(self, locator, time=10):
return AntiStaleElementList(
self.driver,
locator,
lambda locator: WebDriverWait(self.driver, time).until(
EC.visibility_of_all_elements_located(locator),
self.no_element_error_msg(locator),
),
)
def wait_for_presence_of_element(self, locator, time=10):
return AntiStaleElementList(
self.driver,
locator,
lambda locator: WebDriverWait(self.driver, time).until(
EC.presence_of_all_elements_located(locator),
self.no_element_error_msg(locator),
),
)
def wait_for_element_to_be_clickable(self, locator, time=10):
return AntiStaleElement(
self.driver,
locator,
lambda locator: WebDriverWait(self.driver, time).until(
EC.element_to_be_clickable(locator),
self.no_element_error_msg(locator),
),
)
def wait_until_element_is_not_present(self, locator, time=10):
return WebDriverWait(self.driver, time).until(
EC.invisibility_of_element_located(locator),
f"Element {locator} still present on URL {self.current_url} after {time} seconds",
)
def sign_out(self):
profile_page_link = self.wait_for_element(BasePage.profile_page_link)
profile_page_link.click()
sign_out_link = self.wait_for_element(BasePage.sign_out_link)
sign_out_link.click()
self.driver.delete_all_cookies()
def wait_until_url_contains(self, url, time=10):
return WebDriverWait(self.driver, time).until(lambda _: url in self.driver.current_url)
def wait_until_url_doesnt_contain(self, url, time=10):
return WebDriverWait(self.driver, time).until(lambda _: url not in self.driver.current_url)
def wait_until_url_matches(self, pattern: str | re.Pattern, time=10):
p = pattern if isinstance(pattern, re.Pattern) else re.compile(pattern)
return WebDriverWait(self.driver, time).until(lambda _: p.search(self.driver.current_url))
def wait_until_url_doesnt_match(self, pattern: str | re.Pattern, time=10):
p = pattern if isinstance(pattern, re.Pattern) else re.compile(pattern)
return WebDriverWait(self.driver, time).until(lambda _: not p.search(self.driver.current_url))
def wait_until_contains_text(self, search_text, time=10):
return WebDriverWait(self.driver, time).until(lambda _: self.is_text_present_on_page(search_text))
def select_checkbox_or_radio(self, element=None, value=None):
if not element and value:
locator = (By.CSS_SELECTOR, f"[value={value}]")
element = self.wait_for_design_system_checkbox_or_radio(locator)
if not element.get_attribute("checked"):
element.click()
assert element.get_attribute("checked")
def unselect_checkbox(self, element):
if element.get_attribute("checked"):
element.click()
assert not element.get_attribute("checked")
def click_templates(self):
element = self.wait_for_element(NavigationLocators.TEMPLATES_LINK)
element.click()
def click_settings(self):
element = self.wait_for_element(NavigationLocators.SETTINGS_LINK)
element.click()
def click_save(self, time=10):
element = self.wait_for_element(CommonPageLocators.CONTINUE_BUTTON, time=time)
element.click()
def click_continue(self):
element = self.wait_for_element(CommonPageLocators.CONTINUE_BUTTON)
element.click()
def is_page_title(self, expected_page_title):
element = self.wait_for_element(CommonPageLocators.H1)
return element.text == expected_page_title
def is_text_present_on_page(self, search_text):
normalized_page_source = " ".join(self.driver.page_source.split())
return search_text in normalized_page_source
def get_template_id(self):
# Extract ID only once we're on a UUID-based template URL.
# This avoids races where current_url is still /templates/add-email.
template_id_pattern = re.compile(r"/templates/([0-9a-fA-F-]{36})(?:/|$)")
self.wait_until_url_matches(template_id_pattern)
match = template_id_pattern.search(self.driver.current_url)
assert match, f"Could not parse template ID from URL: {self.driver.current_url}"
return match.group(1)
def click_element_by_link_text(self, link_text):
element = self.wait_for_element((By.LINK_TEXT, link_text))
element.click()
def get_errors(self):
error_message = (By.CSS_SELECTOR, ".banner-dangerous")
errors = self.wait_for_element(error_message)
return errors.text.strip()
def click_back_link(self):
element = self.wait_for_element(CommonPageLocators.BACK_LINK)
element.click()
def get_h1_text(self):
element = self.wait_for_element(BasePage.h1_text)
return element.text.strip()
class PageWithStickyNavMixin:
def scrollToRevealElement(self, selector=None, xpath=None, stuckToBottom=True):
current_url = self.driver.current_url
if "staging-notify.works" in current_url:
base_url = "https://static.staging-notify.works"
else:
# Fallback to the url from the globally imported config
base_url = config["notify_admin_url"]
module_url = f"{base_url}/assets/javascripts/esm/stick-to-window-when-scrolling.mjs"
# Flattened directly onto window
prop_name = "stickAtBottomWhenScrolling" if stuckToBottom else "stickAtTopWhenScrolling"
namespace = f"window.{prop_name}"
if selector is not None:
element = f"document.querySelector('{selector}')"
elif xpath is not None:
element = f'(document.evaluate("{xpath}", document, null, XPathResult.ANY_TYPE, null)).iterateNext()'
else:
return
js_str = f"""
var callback = arguments[arguments.length - 1];
import('{module_url}')
.then(module => {{
window['{prop_name}'] = module.default || module;
if ({namespace} && typeof {namespace}.scrollToRevealElement === 'function') {{
var targetNode = {element};
if (targetNode) {namespace}.scrollToRevealElement(targetNode);
}}
callback(null);
}})
.catch(err => callback('JS Import Error: ' + err.message));
"""
error_msg = self.driver.execute_async_script(js_str)
if error_msg:
raise RuntimeError(error_msg)
class HomePage(BasePage):
def accept_cookie_warning(self):
# if the cookie warning isn't present, this does nothing
try:
self.wait_for_element(CommonPageLocators.ACCEPT_COOKIE_BUTTON, time=1).click()
except (NoSuchElementException, TimeoutException):
return
class MainPage(BasePage):
set_up_account_button = MainPageLocators.SETUP_ACCOUNT_BUTTON
def click_set_up_account(self):
element = self.wait_for_element(MainPage.set_up_account_button)
element.click()
class RegistrationPage(BasePage):
name_input = NameInputElement()
email_input = EmailInputElement()
mobile_input = MobileInputElement()
password_input = PasswordInputElement()
def wait_until_current(self):
return self.wait_until_url_contains(self.base_url + "/register")
def register(self):
self.name_input = config["user"]["name"]
self.email_input = config["user"]["email"]
self.mobile_input = config["user"]["mobile"]
self.password_input = config["user"]["password"]
self.click_continue()
class AddServicePage(BasePage):
service_input = ServiceInputElement()
org_type_input = AddServicePageLocators.ORG_TYPE_INPUT
add_service_button = AddServicePageLocators.ADD_SERVICE_BUTTON
trial_mode_page_continue_button = AddServicePageLocators.TRIAL_MODE_PAGE_CONTINUE_BUTTON
def wait_until_current(self):
return self.wait_until_url_contains(self.base_url + "/add-service")
def click_trial_page_continue__button(self):
element = self.wait_for_element(AddServicePage.trial_mode_page_continue_button)
element.click()
def wait_until_name_service_page(self):
return self.wait_until_url_contains(self.base_url + "/add-service/name-your-service")
def add_service(self, name):
self.service_input = name
try:
self.click_org_type_input()
except NoSuchElementException:
pass
self.click_add_service_button()
def click_add_service_button(self):
element = self.wait_for_element(AddServicePage.add_service_button)
element.click()
def click_org_type_input(self):
try:
element = self.wait_for_design_system_checkbox_or_radio(AddServicePage.org_type_input)
element.click()
except TimeoutException:
pass
class YourServicesPage(BasePage):
join_existing_service_button = YourServicesPageLocators.JOIN_EXISTING_SERVICE_BUTTON
add_a_new_service_button = YourServicesPageLocators.ADD_A_NEW_SERVICE_BUTTON
def wait_until_current(self):
return self.wait_until_url_contains(self.base_url + "/your-services")
def join_existing_service(self):
element = self.wait_for_element(YourServicesPage.join_existing_service_button)
element.click()
def add_new_service(self):
element = self.wait_for_element(YourServicesPage.add_a_new_service_button)
element.click()
class ServiceJoinRequestChooseServicePage(BasePage):
search_service_input = ServiceJoinRequestChooseServiceInputElement(clear=True)
select_service_name_link = ServiceJoinRequestChooseServicePageLocators.SELECT_SERVICE_NAME_LINK
def go_to_selected_service(self):
element = self.wait_for_element(ServiceJoinRequestChooseServicePage.select_service_name_link)
element.click()
def check_if_search_input_exists(self):
try:
self.wait_for_element(ServiceJoinRequestChooseServicePageLocators.SEARCH_SERVICE_INPUT)
return True
except TimeoutException:
return False
class ServiceJoinRequestJoinAskPage(BasePage):
request_reason_input = ServiceJoinRequestJoinAskReasonTextAreaElement(clear=True)
select_approver_user = ServiceJoinRequestJoinAskPageLocators.APPROVER_USER_CHECKBOX
ask_to_join_service_button = ServiceJoinRequestJoinAskPageLocators.ASK_TO_JOIN_SERVICE_BUTTON
def select_approver_user_checkbox(self):
element = self.wait_for_element(ServiceJoinRequestJoinAskPage.select_approver_user)
element.click()
def ask_to_join_service(self):
element = self.wait_for_element(ServiceJoinRequestJoinAskPage.ask_to_join_service_button)
element.click()
class ServiceJoinRequestApprovePage(BasePage):
continue_button = ServiceJoinRequestApprovePageLocators.CONTINUE_BUTTON
rejected_radio = ServiceJoinRequestApprovePageLocators.REJECTED_RADIO
def continue_to_next_step(self):
element = self.wait_for_element(ServiceJoinRequestApprovePage.continue_button)
element.click()
def select_rejected_option(self):
element = self.wait_for_design_system_checkbox_or_radio(ServiceJoinRequestApprovePage.rejected_radio)
self.select_checkbox_or_radio(element)
class ServiceJoinRequestChoosePermissionsPage(BasePage):
see_dashboard_check_box = ServiceJoinRequestChoosePermissionsPageLocators.SEE_DASHBOARD_CHECKBOX
send_messages_checkbox = ServiceJoinRequestChoosePermissionsPageLocators.SEND_MESSAGES_CHECKBOX
manage_services_checkbox = ServiceJoinRequestChoosePermissionsPageLocators.MANAGE_SERVICES_CHECKBOX
manage_api_keys_checkbox = ServiceJoinRequestChoosePermissionsPageLocators.MANAGE_API_KEYS_CHECKBOX
login_sms_auth_radio = ServiceJoinRequestChoosePermissionsPageLocators.LOGIN_SMS_AUTH_RADIO
save_permissions_button = ServiceJoinRequestChoosePermissionsPageLocators.SAVE_PERMISSIONS_BUTTON
def fill_invitation_form(self):
element = self.wait_for_design_system_checkbox_or_radio(
ServiceJoinRequestChoosePermissionsPage.see_dashboard_check_box
)
self.select_checkbox_or_radio(element)
element = self.wait_for_design_system_checkbox_or_radio(
ServiceJoinRequestChoosePermissionsPage.send_messages_checkbox
)
self.select_checkbox_or_radio(element)
element = self.wait_for_design_system_checkbox_or_radio(
ServiceJoinRequestChoosePermissionsPage.manage_services_checkbox
)
self.select_checkbox_or_radio(element)
element = self.wait_for_design_system_checkbox_or_radio(
ServiceJoinRequestChoosePermissionsPage.manage_api_keys_checkbox
)
self.select_checkbox_or_radio(element)
def select_sms_auth_form(self):
element = self.wait_for_design_system_checkbox_or_radio(
ServiceJoinRequestChoosePermissionsPage.login_sms_auth_radio
)
self.select_checkbox_or_radio(element)
def save_permissions(self):
element = self.wait_for_element(ServiceJoinRequestChoosePermissionsPage.save_permissions_button)
element.click()
class ForgotPasswordPage(BasePage):
email_input = EmailInputElement()
def input_email_address(self, email_address):
self.email_input = email_address
class NewPasswordPage(BasePage):
new_password_input = NewPasswordInputElement()
def input_new_password(self, password):
self.new_password_input = password
class SignInPage(BasePage):
email_input = EmailInputElement()
password_input = PasswordInputElement()
forgot_password_link = SignInPageLocators.FORGOT_PASSWORD_LINK
def get(self):
self.driver.get(self.base_url + "/sign-in")
def wait_until_current(self):
return self.wait_until_url_contains(self.base_url + "/sign-in")
def fill_login_form(self, email, password):
self.email_input = email
self.password_input = password
def click_forgot_password_link(self):
element = self.wait_for_element(SignInPage.forgot_password_link)
element.click()
def login(self, email, password):
self.fill_login_form(email, password)
self.click_continue()
class VerifyPage(BasePage):
sms_input = SmsInputElement()
def verify(self, code):
element = self.wait_for_element(VerifyPageLocators.SMS_INPUT)
element.clear()
self.sms_input = code
self.click_continue()
def verify_code_successful(self) -> bool:
try:
# override the default 10 seconds to keep things a bit snappier
self.wait_for_element((By.CLASS_NAME, "error-message"), time=2)
except (NoSuchElementException, TimeoutException):
# if we cant find the error message, it's probs because we succesfully redirected! but lets double check
try:
self.url_not_a_2fa_sms_page() # times out if we were unsuccesful
return True
except TimeoutException:
# we expect to have been redirected away from the `/verify` URL, so we should retry
return False
else:
# found an error message on the page, so should retry
return False
def url_not_a_2fa_sms_page(self):
# the page where you enter a 2fa code is one of two URLs:
# /verify for user registration, or /two-factor-sms for sign-in
current_path = urlsplit(self.driver.current_url)
WebDriverWait(self.driver, 10).until(
lambda _: not (current_path == "/verify" or current_path == "/two-factor-sms")
)
class DashboardPage(BasePage):
h2 = (By.CLASS_NAME, "navigation-service-name")
sms_templates_link = (By.LINK_TEXT, "Text message templates")
email_templates_link = (By.LINK_TEXT, "Email templates")
uploads_link = (By.LINK_TEXT, "Uploads")
team_members_link = (By.LINK_TEXT, "Team members")
api_keys_link = (By.LINK_TEXT, "API integration")
total_email_div = (By.CSS_SELECTOR, "#total-email .big-number-number")
total_sms_div = (By.CSS_SELECTOR, "#total-sms .big-number-number")
total_letter_div = (By.CSS_SELECTOR, "#total-letters .big-number-number")
inbox_link = (By.CSS_SELECTOR, "#total-received")
navigation = (By.CLASS_NAME, "navigation")
email_unsubscribe_requests_link = (By.CSS_SELECTOR, "#total-unsubscribe-requests")
email_unsubscribe_requests_count_link = (By.CSS_SELECTOR, "#total-unsubscribe-requests .banner-dashboard-count")
loading_indicator = (By.CSS_SELECTOR, ".big-number-with-status .big-number-smaller .loading-indicator")
def _message_count_for_template_div(self, template_id):
return (By.ID, template_id)
def is_current(self, service_id):
expected = f"/services/{service_id}/dashboard"
self.wait_until_url_contains(expected)
return True
def get_service_name(self):
element = self.wait_for_element(DashboardPage.h2)
return element.text
def click_sms_templates(self):
element = self.wait_for_element(DashboardPage.sms_templates_link)
element.click()
def click_email_templates(self):
element = self.wait_for_element(DashboardPage.email_templates_link)
element.click()
def click_uploads(self):
element = self.wait_for_element(DashboardPage.uploads_link)
element.click()
def click_team_members_link(self):
element = self.wait_for_element(DashboardPage.team_members_link)
element.click()
def click_inbox_link(self):
element = self.wait_for_element(DashboardPage.inbox_link)
element.click()
def click_email_unsubscribe_requests(self):
element = self.wait_for_element(DashboardPage.email_unsubscribe_requests_link)
element.click()
def get_service_id(self):
self.wait_until_url_contains("/services/")
return self.driver.current_url.split("/services/")[1].split("/")[0]
def get_navigation_list(self):
element = self.wait_for_element(DashboardPage.navigation)
return element.text
def get_notification_id(self):
self.wait_until_url_contains("/notification/")
return self.driver.current_url.split("notification/")[1].split("?")[0]
def go_to_dashboard_for_service(self, service_id=None):
if not service_id:
service_id = self.get_service_id()
url = f"{self.base_url}/services/{service_id}/dashboard"
self.driver.get(url)
@staticmethod
def _assert_strip_thousands_commas(s):
if not re.match(r"\s*\d{1,3}(,\d{3})*\s*$", s):
raise ValueError("Thousands separator pattern not matched")
return s.replace(",", "")
@retry(RetryException, tries=10, delay=10)
def get_total_message_count(self, message_type):
if message_type == "email":
target_div = DashboardPage.total_email_div
elif message_type == "letter":
target_div = DashboardPage.total_letter_div
else:
target_div = DashboardPage.total_sms_div
element = self.wait_for_element(target_div)
try:
return int(self._assert_strip_thousands_commas(element.text))
except ValueError as e:
raise RetryException("Count of messages on dashboard not loaded yet") from e
@retry(RetryException, tries=10, delay=10)
def get_template_message_count(self, template_id):
messages_sent_count_for_template_div = self._message_count_for_template_div(template_id)
element = self.wait_for_element(messages_sent_count_for_template_div)
try:
return int(self._assert_strip_thousands_commas(element.text))
except ValueError as e:
raise RetryException("Count of template messages on dashboard not loaded yet") from e
def get_email_unsubscribe_requests_count(self):
try:
element = self.wait_for_element(DashboardPage.email_unsubscribe_requests_count_link)
except (NoSuchElementException, TimeoutException):
return 0
return int(self._assert_strip_thousands_commas(element.text))
@retry_on_stale_element_exception
def get_stats(self, message_type, template_id):
# Wait until loading indicator disappears
self.wait_until_element_is_not_present(self.loading_indicator)
try:
template_messages_count = self.get_template_message_count(template_id)
except TimeoutException:
template_messages_count = 0 # template count may not exist yet if no messages sent
return {
"total_messages_sent": self.get_total_message_count(message_type),
"template_messages_sent": template_messages_count,
}
@staticmethod
def assert_stats_increased(stats_before, stats_after):
for k in stats_before.keys():
assert stats_after[k] > stats_before[k]
class ShowTemplatesPage(PageWithStickyNavMixin, BasePage):
add_new_template_link = (By.CSS_SELECTOR, "button[value='add-new-template']")
add_new_folder_link = (By.CSS_SELECTOR, "button[value='add-new-folder']")
add_to_new_folder_link = (By.CSS_SELECTOR, "button[value='move-to-new-folder']")
move_to_existing_folder_link = (
By.CSS_SELECTOR,
"button[value='move-to-existing-folder']",
)
email_filter_link = (By.LINK_TEXT, "Email")
email_radio = (By.CSS_SELECTOR, "input[type='radio'][value='email']")
text_message_radio = (By.CSS_SELECTOR, "input[type='radio'][value='sms']")
letter_radio = (By.CSS_SELECTOR, "input[type='radio'][value='letter']")
add_new_folder_textbox = BasePageElement(name="add_new_folder_name")
add_to_new_folder_textbox = BasePageElement(name="move_to_new_folder_name")
all_templates_listed = (By.CSS_SELECTOR, ".template-list-item-label .govuk-visually-hidden")
root_template_folder_radio = (
By.CSS_SELECTOR,
"input[type='radio'][value='__NONE__']",
)
@staticmethod
def template_link_text(link_text):
return (
By.XPATH,
f"//div[contains(@id,'template-list')]//a/span[contains(normalize-space(.), '{link_text}')]",
)
@staticmethod
def template_checkbox(template_id):
return (
By.CSS_SELECTOR,
f"input[type='checkbox'][value='{template_id}']",
)
def click_add_new_template(self):
element = self.wait_for_element(self.add_new_template_link)
element.click()
def click_add_new_folder(self, folder_name):
element = self.wait_for_element(self.add_new_folder_link)
element.click()
self.add_new_folder_textbox = folder_name
# green submit button
element = self.wait_for_element(self.add_new_folder_link)
element.click()
def click_template_by_link_text(self, link_text):
element = self.wait_for_element(self.template_link_text(link_text))
self.scrollToRevealElement(xpath=self.template_link_text(link_text)[1])
element.click()
def _select_template_type(self, type):
# wait for continue button to be displayed - sticky nav has rendered properly
# we've seen issues
radio_element = self.wait_for_design_system_checkbox_or_radio(type)
self.select_checkbox_or_radio(radio_element)
self.click_continue()
def select_email(self):
self._select_template_type(self.email_radio)
def select_text_message(self):
self._select_template_type(self.text_message_radio)
def select_letter(self):
self._select_template_type(self.letter_radio)
def select_template_checkbox(self, template_id):
element = self.wait_for_design_system_checkbox_or_radio(self.template_checkbox(template_id))
self.select_checkbox_or_radio(element)
def add_to_new_folder(self, folder_name):
# grey button to go to the name input box
element = self.wait_for_element(self.add_to_new_folder_link)
element.click()
self.add_to_new_folder_textbox = folder_name
# green submit button
element = self.wait_for_element(self.add_to_new_folder_link)
element.click()
def move_to_root_template_folder(self):
move_button = self.wait_for_element(self.move_to_existing_folder_link)
move_button.click()
# wait for continue button to be displayed - sticky nav has rendered properly
# we've seen issues
radio_element = self.wait_for_design_system_checkbox_or_radio(self.root_template_folder_radio)
self.select_checkbox_or_radio(radio_element)
self.click_continue()
def get_folder_by_name(self, folder_name):
try:
return self.wait_for_design_system_checkbox_or_radio(self.template_link_text(folder_name))
except TimeoutException:
return None
def get_all_listed_templates(self):
locator = (By.CLASS_NAME, "template-list-item-label")
WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(locator))
elements = self.driver.find_elements(*locator)
return [element.get_attribute("textContent").strip() for element in elements]
class SendSmsTemplatePage(BasePage):
new_sms_template_link = TemplatePageLocators.ADD_NEW_TEMPLATE_LINK
edit_sms_template_link = TemplatePageLocators.EDIT_TEMPLATE_LINK
def click_add_new_template(self):
element = self.wait_for_element(SendSmsTemplatePage.new_sms_template_link)
element.click()
class EditSmsTemplatePage(BasePage):
name_input = NameInputElement(clear=True)
template_content_input = TemplateContentElement(clear=True)
save_button = EditTemplatePageLocators.SAVE_BUTTON
def click_save(self):
element = self.wait_for_element(EditSmsTemplatePage.save_button)
element.click()
def fill_template(self, name="Test sms template", content=None):
self.name_input = name
if content:
self.template_content_input = content
else:
self.template_content_input = "The quick brown fox jumped over the lazy dog. Job id: ((build_id))"
self.click_save()
class ViewTemplatePage(BasePage):
h1 = (By.CSS_SELECTOR, "h1")
def wait_until_current(self, time=10):
return self.wait_until_url_matches(r"/templates/[^/]+(\?.*)?$", time=time)
def click_edit(self):
element = self.wait_for_element(ViewTemplatePageLocators.EDIT_BUTTON)
element.click()
def click_send(self):
element = self.wait_for_element(ViewTemplatePageLocators.SEND_BUTTON)
element.click()
def go_to_view_template_page_for_service_and_template(self, service_id, template_id):
url = f"{self.base_url}/services/{service_id}/templates/{template_id}"
self.driver.get(url)
def get_h1(self):
return self.wait_for_element(self.h1).text
class ViewLetterTemplatePage(ViewTemplatePage):
rename_link = ViewLetterTemplatePageLocators.RENAME_LINK
edit_welsh_body = ViewLetterTemplatePageLocators.EDIT_WELSH_BODY
edit_english_body = ViewLetterTemplatePageLocators.EDIT_ENGLISH_BODY
attach_button = ViewLetterTemplatePageLocators.ATTACH_BUTTON
change_language_button = ViewLetterTemplatePageLocators.CHANGE_LANGUAGE
def click_rename_link(self):
element = self.wait_for_element(ViewLetterTemplatePage.rename_link)
element.click()
def click_edit_welsh_body(self):
element = self.wait_for_element(ViewLetterTemplatePage.edit_welsh_body)
element.click()
def click_edit_english_body(self):
element = self.wait_for_element(ViewLetterTemplatePage.edit_english_body)
element.click()
def click_attachment_button(self):
element = self.wait_for_element(ViewLetterTemplatePage.attach_button)
element.click()
def click_change_language(self):
element = self.wait_for_element(self.change_language_button)
element.click()
class ViewEmailTemplatePage(ViewTemplatePage):
attach_files_button = ViewEmailTemplatePageLocators.ATTACH_FILES_BUTTON
manage_files_button = ViewEmailTemplatePageLocators.MANAGE_FILES_BUTTON
file_added_count_text = ViewEmailTemplatePageLocators.FILE_ADDED_COUNT_TEXT
page_banner_text = ViewEmailTemplatePageLocators.PAGE_BANNER_TEXT
delete_template_link = ViewEmailTemplatePageLocators.DELETE_TEMPLATE_LINK
template_deletion_confirmation_button = ViewEmailTemplatePageLocators.TEMPLATE_DELETION_CONFIRMATION_BUTTON
email_message_body_content = (By.XPATH, "//div[contains(@class, 'email-message-body')]")
def click_attach_files_button(self):
element = self.wait_for_element(ViewEmailTemplatePage.attach_files_button)
element.click()
def click_manage_files_button(self):
element = self.wait_for_element(ViewEmailTemplatePage.manage_files_button)
element.click()
def get_file_added_count_text(self):
element = self.wait_for_element(ViewEmailTemplatePage.file_added_count_text)
return element.text.strip()
def get_page_banner_text(self):
element = self.wait_for_element(ViewEmailTemplatePage.page_banner_text)
return element.text.strip()
def click_delete_template_link(self):
element = self.wait_for_element(ViewEmailTemplatePage.delete_template_link)
element.click()
def click_template_deletion_confirmation_button(self):
element = self.wait_for_element(ViewEmailTemplatePage.template_deletion_confirmation_button)
element.click()
def get_email_message_body_content(self):
element = self.wait_for_element(ViewEmailTemplatePage.email_message_body_content)
return element.text.strip()
def click_file_link_text(self, link_text):
element = self.wait_for_element((By.XPATH, f"//a[contains(text(), '{link_text}')]"))
element.click()
class AddFileToEmailTemplatePage(BasePage):
choose_file_button = AddFileToEmailTemplatePageLocators.CHOOSE_FILE_BUTTON
file_input = AddFileToEmailTemplatePageLocators.FILE_INPUT
submit_button = AddFileToEmailTemplatePageLocators.SUBMIT_BUTTON
def visible_choose_file_button(self):
element = self.wait_for_element(AddFileToEmailTemplatePage.choose_file_button)
return element
def click_submit_button(self):
element = self.wait_for_element(AddFileToEmailTemplatePage.submit_button)
element.click()
def upload_file(self, file_path):
element = self.wait_for_presence_of_element(AddFileToEmailTemplatePage.file_input)
# Fill in the hidden file input bypassing the OS file management dialog
element[0].send_keys(file_path)
class ManageEmailTemplateFilePage(BasePage):
file_link = ManageEmailTemplateFilePageLocators.REMOVE_FILE_LINK
add_to_template = ManageEmailTemplateFilePageLocators.ADD_TO_TEMPLATE_BUTTON
remove_file_dialog_button = ManageEmailTemplateFilePageLocators.REMOVE_FILE_DIALOG_BUTTON
change_link_text_change = (
By.XPATH,
"//div[contains(@class, 'govuk-summary-list__row')][dt[contains(., 'Link text')]]//a[contains(., 'Change')]",
)
def click_remove_file_link(self):
element = self.wait_for_element(ManageEmailTemplateFilePage.file_link)
element.click()
def click_add_to_template(self):
element = self.wait_for_element(ManageEmailTemplateFilePage.add_to_template)
element.click()
def click_remove_file_dialog_button(self):
element = self.wait_for_element(ManageEmailTemplateFilePage.remove_file_dialog_button)
element.click()
def get_file_setting_value(self, label):
xpath = (
f"//div[contains(@class, 'govuk-summary-list__row')]"
f"[dt[contains(., '{label}')]]"
f"//dd[contains(@class, 'govuk-summary-list__value')]"
)
element = self.wait_for_element((By.XPATH, xpath))
return element.get_attribute("textContent").strip()
def click_change_file_setting(self, label):