-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path__init__.py
More file actions
3107 lines (2773 loc) · 122 KB
/
Copy path__init__.py
File metadata and controls
3107 lines (2773 loc) · 122 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 re
import time
from collections import namedtuple
from contextlib import suppress
from datetime import datetime, timedelta, timezone
from enum import Enum, auto
from itertools import count
from pathlib import Path
from typing import Any, ClassVar, Dict, Generator, List, Optional, Union
from robot.api import SkipExecution, logger
from robot.api.deco import library
from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
from robot.libraries.DateTime import convert_date
from robot.result.model import Message
from robot.result.model import TestCase as ResultTestCase
from robot.running import EXECUTION_CONTEXTS
from robot.running.model import TestCase
from robot.utils import DotDict, secs_to_timestr, timestr_to_secs
from robotlibcore import DynamicCore, keyword
from Browser import Browser, SupportedBrowsers
from Browser.assertion_engine import AssertionOperator as AO
from Browser.base import LibraryComponent
from Browser.generated.playwright_pb2 import Request
from Browser.utils.data_types import (
AutoClosingLevel,
BoundingBoxFields,
CookieType,
ElementState,
KeyAction,
KeyboardInputAction,
MouseButton,
MouseButtonAction,
Scope,
SelectAttribute,
SelectionType,
)
from SeleniumLibraryToBrowser.keys import Keys
from .errors import (
CookieNotFound,
ElementNotFound,
InvalidArgumentException,
NoSuchElementException,
NoSuchFrameException,
WindowNotFound,
)
try:
from SeleniumLibrary import SeleniumLibrary
except ImportError:
SeleniumLibrary = None
EQUALS = AO["=="]
NOT_EQUALS = AO["!="]
CONTAINS = AO["*="]
NOT_CONTAINS = AO["not contains"]
STARTS_WITH = AO["^="]
ENDS_WITH = AO["$="]
THEN = AO["then"]
VALIDATE = AO["validate"]
GREATER_THAN = AO[">"]
DEFAULT_FILENAME_PAGE = "selenium-screenshot-{index}.png"
DEFAULT_FILENAME_ELEMENT = "selenium-element-screenshot-{index}.png"
EMBED = "EMBED"
__version__ = "1.0.0"
class CookieInformation:
def __init__(
self,
name,
value,
path=None,
domain=None,
secure=False,
httpOnly: bool = False,
expires: Optional[datetime] = None,
**extra,
):
self.name: str = name
self.value: str = value
self.path: str = path
self.domain: str = domain
self.secure: str = secure
self.httpOnly: bool = httpOnly
self.expiry: datetime = (
expires.replace(tzinfo=timezone.utc).astimezone(tz=None).replace(tzinfo=None)
if expires is not None
else None
)
self.extra = extra
def __str__(self):
items = "name value path domain secure httpOnly expiry".split()
string = "\n".join(f"{item}={getattr(self, item)}" for item in items)
if self.extra:
string = f"{string}\nextra={self.extra}\n"
return string
class WebElement(str):
@staticmethod
def _data_parser(loc):
try:
name, value = loc.split(":")
if "" in [name, value]:
raise ValueError
return f'//*[@data-{name}="{value}"]'
except ValueError:
raise ValueError(f"Provided selector ({loc}) is malformed. Correct format: name:value.")
LOCATORS: ClassVar[Dict[str, str]] = {
"id": lambda loc: f"id={loc}",
"name": lambda loc: f"css=[name={loc}]",
"identifier": lambda loc: f"css=[id={loc}], [name={loc}]",
"class": lambda loc: f"css=.{loc}",
"tag": lambda loc: f"css={loc}",
"xpath": lambda loc: f"xpath={loc}",
"css": lambda loc: f"css={loc}",
"jquery": lambda loc: f"css={loc}",
"sizzle": lambda loc: f"css={loc}",
"link": lambda loc: f'css=a >> text="{loc}"',
"partial link": lambda loc: f"css=a >> text={loc}",
"text": lambda loc: f"text={loc}",
"data": _data_parser,
"element": lambda loc: f"element={loc}",
"default": lambda loc: f"css=[id={loc}], [name={loc}]",
"nth": lambda loc: f"nth={loc}",
}
original_locator: Union[str, tuple] = ""
@classmethod
def from_any(cls, locator: Union[list, tuple, str]) -> "WebElement":
if isinstance(locator, (list, tuple)):
return cls.from_list(locator)
return cls.from_string(locator)
@classmethod
def from_string(cls, locator: str) -> "WebElement":
if " >> " in locator:
web_elem = cls(" >> ".join(cls.from_string(loc) for loc in locator.split(" >> ")))
else:
web_elem = cls.get_single_locator(locator)
web_elem.original_locator = locator
return web_elem
@classmethod
def from_list(cls, locator: List[str]) -> "WebElement":
web_elem = cls(" >> ".join(cls.from_string(loc) for loc in locator))
web_elem.original_locator = " >> ".join(locator)
return web_elem
@classmethod
def get_single_locator(cls, locator: str) -> "WebElement":
for illegal_loc in ["dom"]:
match = re.match(f"{illegal_loc} ?[:=] ?", locator, flags=re.IGNORECASE)
if match:
raise ValueError(
f"Invalid locator strategy '{illegal_loc}'.\n"
f"Please use a supported locator strategy instead.\n"
f"{list(cls.LOCATORS.keys())}"
)
for strategy, selector in cls.LOCATORS.items():
match = re.match(f"{strategy} ?[:=] ?", locator, flags=re.IGNORECASE)
if match:
loc = locator[match.end() :]
return cls(selector(loc))
if re.match(r"\(*//", locator):
return cls(f"xpath={locator}")
return cls(f"[id='{locator}'], [name='{locator}']")
@staticmethod
def is_default(locator: str):
match = re.fullmatch(r"\[id='(.*)'], \[name='(.*)']", locator)
if match and match.group(1) == match.group(2):
return match.group(1)
return None
BROWSERS = {
"firefox": (SupportedBrowsers.firefox, False),
"ff": (SupportedBrowsers.firefox, False),
"headlessfirefox": (SupportedBrowsers.firefox, True),
"chromium": (SupportedBrowsers.chromium, False),
"chrome": (SupportedBrowsers.chromium, False),
"googlechrome": (SupportedBrowsers.chromium, False),
"headlesschrome": (SupportedBrowsers.chromium, True),
"gc": (SupportedBrowsers.chromium, False),
"edge": (SupportedBrowsers.chromium, False),
"webkit": (SupportedBrowsers.webkit, False),
"safari": (SupportedBrowsers.webkit, False),
}
class V3Listener:
ROBOT_LISTENER_API_VERSION = 3
def __init__(self, library):
self.library = library
self.depr = False
def start_test(self, _test: TestCase, _result: ResultTestCase):
self.depr = False
def end_test(self, _test: TestCase, result: ResultTestCase):
if self.depr and BuiltIn()._context.dry_run:
result.status = "SKIP"
def log_message(self, message: Message):
if (
message.level == "WARN"
and "is deprecated" in message.message
and BuiltIn()._context.dry_run
):
self.depr = True
class PriorityLibrary(Enum):
SeleniumLibraryToBrowser = auto()
Browser = auto()
@library(converters={WebElement: WebElement.from_any})
class SeleniumLibraryToBrowser(DynamicCore):
"""_*SeleniumLibraryToBrowser*_ is a compatibility layer between [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] keyword design
and [https://robotframework-browser.org/|Robot Framework Browser]'s [https://playwright.dev|Playwright] based technology.
%TOC%
= Usage =
The usage of this library needs some consideration.
The library is designed to use [https://robotframework-browser.org|Browser] library internally and be mostly compatible to [https://robotframework.org/SeleniumLibrary|SeleniumLibrary]'s keywords.
However some keywords are impossible to be implement with [https://playwright.dev|Playwright], like all Alert handling keywords.
All *IMPLEMENTED* keywords are tagged as such and can be filtered in the keyword list.
== Unimplemented Keywords ==
This library cause a test to be skipped, when it calls an unimplemented keyword.
Also all unimplemented keywords are marked as *DEPRECATED*, so that IDEs can mark them.
== Dry Run ==
If a dry run is executed, all keywords that do exist but are not implemented will cause a fail.
= Overview =
_*SeleniumLibraryToBrowser*_ is an innovative project designed to bridge the gap between two prominent libraries in the Robot Framework community: [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] and [https://robotframework-browser.org|Browser] library. This library is crafted to facilitate a smooth transition for users who wish to upgrade their web automation capabilities by leveraging the advanced features of the [https://robotframework-browser.org|Browser] library, while maintaining compatibility with the existing keyword design of [https://robotframework.org/SeleniumLibrary|SeleniumLibrary].
== Purpose ==
The primary objective of _*SeleniumLibraryToBrowser*_ is to enable seamless migration from [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] to [https://robotframework-browser.org|Browser] library without the need for extensive rewrites of existing test suites. It recognizes the significant investment users have made in [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] and respects the history and value it has brought to the Robot Framework community. This library is not intended as a replacement for [https://robotframework.org/SeleniumLibrary|SeleniumLibrary], but as a complementary tool that offers additional options and flexibility for test automation.
== Key Features ==
Compatibility with [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] Keywords: _*SeleniumLibraryToBrowser*_ allows existing test scripts, which use [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] keywords, to function with minimal changes, thereby reducing migration effort and time.
Leveraging [https://robotframework-browser.org|Browser] Library Advantages: Users can benefit from the speed, stability, and modern web technology support of the [https://robotframework-browser.org|Browser] library, especially in handling complex elements like WebComponents and ShadowDOM.
Coexistence and Support: This project emphasizes the coexistence and mutual respect between [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] and [https://robotframework-browser.org|Browser] library. It is not a hostile takeover but a supportive extension, offering more choices to the Robot Framework community.
== Usage Scenario ==
_*SeleniumLibraryToBrowser*_ is ideal for teams and projects that have an extensive codebase using [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] and are seeking to upgrade to the [https://robotframework-browser.org|Browser] library's advanced features without disrupting their existing test automation infrastructure. It is particularly beneficial for those who aim to gradually transition to the [https://robotframework-browser.org|Browser] library while continuing to develop and maintain their current test suites.
== Importing the Library ==
To use _*SeleniumLibraryToBrowser*_ in your Robot Framework projects, you can import it in your test suites as you would with any other library. Below is an example of how to import the library:
| ***** Settings *****
| Library SeleniumLibraryToBrowser
This simple example may probably not be sufficient in practice.
Please see `Migration Guide` for more details on how to import the library.
== Configuration ==
Upon import, _*SeleniumLibraryToBrowser*_ initializes with default settings that ensure compatibility with [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] keywords. However, users can configure it to take advantage of specific features of the [https://robotframework-browser.org|Browser] library as needed.
== Conclusion ==
_*SeleniumLibraryToBrowser*_ represents a thoughtful and user-centric approach to evolving test automation practices within the Robot Framework community. It respects the legacy of [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] while embracing the future potential of the [https://robotframework-browser.org|Browser] library, offering a balanced solution for users at different stages of their automation journey.
= Limitations =
The _*SeleniumLibraryToBrowser*_ project, while offering numerous advantages, also comes with certain limitations. These are primarily due to the underlying technology differences between the Selenium and [https://robotframework-browser.org|Browser] libraries.
1. Get WebElement(s) Behavior:
- SeleniumLibrary: Returns the Selenium WebElement object, allowing for direct Python evaluations on this object.
- [https://robotframework-browser.org|Browser] Library (via _*SeleniumLibraryToBrowser*_): Returns a Selector instead, which can be used in subsequent keywords but does not support direct Python evaluations like the WebElement object.
2. Execute JavaScript Keyword:
- In _*SeleniumLibraryToBrowser*_, the `Execute JavaScript` keyword only accepts a `WebElement` as the first argument. This is a direct carry-over from the [https://robotframework.org/SeleniumLibrary|SeleniumLibrary]'s implementation and may limit the usage in contexts specific to the [https://robotframework-browser.org|Browser] library.
3. Implicit Wait and Selenium Timeout:
- Implicit Wait: In _*SeleniumLibraryToBrowser*_, Selenium's implicit wait is translated to Browser's general timeout setting.
- Selenium Timeout: This is used for all `Wait Until ...` keywords. It's important to note that the Selenium Timeout and the Implicit Wait do not cumulatively extend waiting periods.
4. Set Window Size and Maximize Browser Window:
- `Set Window Size`: This keyword behaves differently in _*SeleniumLibraryToBrowser*_ compared to [https://robotframework.org/SeleniumLibrary|SeleniumLibrary]. It only sets the viewport size, not the actual window size.
- `Maximize Browser Window`: This keyword sets the viewport to Full HD resolution. The underlying reason for this behavior is that Playwright, which powers the [https://robotframework-browser.org|Browser] library, cannot modify the actual browser size or position.
5. Open Browser and Create Webdriver:
- `Open Browser`: This keyword has only basic compatibility in _*SeleniumLibraryToBrowser*_. It does not fully utilize the advanced features available in the [https://robotframework-browser.org|Browser] library.
- `Create Webdriver`: This function is not implemented in _*SeleniumLibraryToBrowser*_. Users are advised to replace the `Open Browser` keyword with the `New Persistent Context` from the [https://robotframework-browser.org|Browser] library for enhanced functionality.
---
*Note*: These limitations highlight the technology-specific differences and are crucial for users to understand when transitioning from [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] to _*SeleniumLibraryToBrowser*_. Users should consider these factors during migration to ensure optimal use of the new library capabilities.
= Migration Guide =
== Introduction ==
_*SeleniumLibraryToBrowser*_ is designed to facilitate a smooth transition from [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] to [https://robotframework-browser.org|Browser] library.
You can either use it as is alone or use [https://robotframework-browser.org|Browser] library together with _*SeleniumLibraryToBrowser*_.
In our estimation, stand-alone operation will realistically rarely be possible,
due to limitations of `Open Browser` and that `Create Webdriver` is not implemented.
Therefore you will need to use [https://robotframework-browser.org|Browser] library together with _*SeleniumLibraryToBrowser*_.
Please read `Importing` carefully to understand how to deal with library search order.
== Import Order ==
[https://robotframework-browser.org|Browser] library shall be imported first and _*SeleniumLibraryToBrowser*_ shall be configured to prioritize one library.
Example:
| ***** Settings *****
| Library Browser
| Library SeleniumLibraryToBrowser prioritize_library=SeleniumLibraryToBrowser
This will ensure that _*SeleniumLibraryToBrowser*_ will be used for all keywords that are implemented in both libraries.
You can refactor your code to use [https://robotframework-browser.org|Browser] library keywords instead of _*SeleniumLibraryToBrowser*_ keywords by
prefixing the [https://robotframework-browser.org|Browser] keywords with ``Browser.`` like ``Browser.Get Text``.
Once all conflicting keywords are replaced by [https://robotframework-browser.org|Browser] library keywords,
you can switch the ``prioritize_library`` argument to ``prioritize_library=Browser``
so that [https://robotframework-browser.org|Browser] library keywords will be used instead of _*SeleniumLibraryToBrowser*_ keywords.
== Keyword Conflicts ==
Obviously all _*SeleniumLibraryToBrowser*_ keywords do conflict with [https://robotframework.org/SeleniumLibrary|SeleniumLibrary] and these libraries can not be used together.
There are also some keywords that do conflict with [https://robotframework-browser.org|Browser] library keywords.
The following keywords are affected:
- `Add Cookie`
- `Close Browser`
- `Delete All Cookies`
- `Drag And Drop`
- `Get Browser Ids`
- `Get Cookie`
- `Get Cookies`
- `Get Element Count`
- `Get Text`
- `Get Title`
- `Go Back`
- `Go To`
- `Open Browser`
- `Press Keys`
- `Register Keyword To Run On Failure`
- `Switch Browser`
- `Wait For Condition`
Please see `Importing` section for more information on how to resolve these conflicts with prioritizing libraries.
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_VERSION = __version__
def __init__(
self,
timeout=timedelta(seconds=5.0),
implicit_wait=timedelta(seconds=10.0),
run_on_failure="Capture Page Screenshot",
screenshot_root_directory: Optional[str] = None,
plugins: Optional[str] = None,
event_firing_webdriver: Optional[str] = None,
page_load_timeout=timedelta(minutes=5),
*,
prioritize_library: Optional[PriorityLibrary] = None,
**browser_args: Optional[Dict],
):
"""_*SeleniumLibraryToBrowser*_ uses Robot Framework [https://robotframework-browser.org|Browser] library internally.
Therefore it is required to import [https://robotframework-browser.org|Browser] library either before this library,
or _*SeleniumLibraryToBrowser*_ will import [https://robotframework-browser.org|Browser] library itself.
You shall not import [https://robotframework-browser.org|Browser] library after.
If you plan to use [https://robotframework-browser.org|Browser] keywords as well as _*SeleniumLibrary(ToBrowser)*_ keywords,
you have to decide if you want to prioritize [https://robotframework-browser.org|Browser] library or _*SeleniumLibraryToBrowser*_.
Both Libraries do have some keywords with the same name, but different functionality,
which would cause conflicts, if no library search order is set.
See `Keyword Conflicts` for more information.
Therefore you can either set the library search order yourself,
or let _*SeleniumLibraryToBrowser*_ do it for you, which would be recommended.
Use the argument ``prioritize_library`` to set which ones keywords should be prioritized.
If one library is prioritized, no keyword conflicts will occur during runtime.
However most IDEs may still report these keywords as conflicts which can be mitigated by
using the library name as prefix like ``Browser.Get Text``.
| =Arguments= | =Description= |
| ``timeout`` | This timeout is used by all ``Wait Until ...`` keywords as a default waiting time. |
| ``implicit_wait`` | This timeout sets the Browser timeout which is used to wait until elements get actionable or visible. |
| ``run_on_failure`` | This keyword is executed when a SeleniumLibraryToBrowser keyword fails. Arguments are not possible. |
| ``screenshot_root_directory`` | This directory is used to store screenshots. If not set, the log directory is used. |
| ``plugins`` | *NOT IMPLEMENTED* Because _*SeleniumLibraryToBrowser*_ works internally totally different as SeleniumLibrary, it can obviously not use any SeleniumLibrary plugins. |
| ``event_firing_webdriver`` | *NOT IMPLEMENTED* Because _*SeleniumLibraryToBrowser*_ works internally totally different as SeleniumLibrary, it can not use any SeleniumLibrary event_firing_webdriver. |
| ``page_load_timeout`` | This timeout is used by `Open Browser`, `Go To`, `Reload` keyword as timeout for the page loading. |
| ``prioritize_library`` | This argument can be used to set which library should be prioritized. See `Keyword Conflicts` for more information. |
| ``browser_args`` | All other named arguments will be used to hand over to [https://robotframework-browser.org|Browser] library if it has not been imported before. |
"""
self.sl2b = SLtoB(
timeout=timeout,
implicit_wait=implicit_wait,
screenshot_root_directory=screenshot_root_directory,
browser_args=browser_args,
library=self,
page_load_timeout=page_load_timeout,
prioritize_library=prioritize_library,
)
self.run_on_failure_keyword = self.sl2b.resolve_keyword(run_on_failure)
components = [self.sl2b]
super().__init__(components)
self.sl = SeleniumLibrary() if SeleniumLibrary else None
self._running_on_failure_keyword = False
@property
def dry_run(self):
ctx = EXECUTION_CONTEXTS.current
return ctx.dry_run if ctx else False
def keyword_implemented(self, name):
return "IMPLEMENTED" in self.get_keyword_tags(name)
def run_keyword(self, name, args, kwargs=None):
if not self.keyword_implemented(name):
raise SkipExecution(f"Keyword '{name.replace('_', ' ').title() }' is not implemented")
try:
retun_value = super().run_keyword(name, args, kwargs)
self.sleep_selenium_speed(name)
return retun_value
except Exception as e:
self.failure_occurred()
raise e
def failure_occurred(self):
"""Method that is executed when a SeleniumLibrary keyword fails.
By default, executes the registered run-on-failure keyword.
Libraries extending SeleniumLibrary can overwrite this hook
method if they want to provide custom functionality instead.
"""
if self._running_on_failure_keyword or not self.run_on_failure_keyword:
return
try:
self._running_on_failure_keyword = True
if self.run_on_failure_keyword.lower() == "capture page screenshot":
self.sl2b.capture_page_screenshot()
else:
BuiltIn().run_keyword(self.run_on_failure_keyword)
except Exception as err:
logger.warn(
f"Keyword '{self.run_on_failure_keyword}' could not be run on failure: {err}"
)
finally:
self._running_on_failure_keyword = False
def sleep_selenium_speed(self, kw_name: str):
checks = [
lambda name: name.startswith("capture"),
lambda name: "should" in name,
lambda name: "close" in name,
lambda name: name.startswith("get"),
lambda name: name.startswith("log"),
lambda name: name
in [
"maximize_browser_window",
"open_browser",
"reload_page",
"select_frame",
"set_screenshot_directory",
"set_selenium_implicit_wait",
"set_selenium_page_load_timeout",
"set_selenium_speed",
"set_selenium_timeout",
"switch_browser",
"switch_window",
],
]
for check in checks:
if check(kw_name.lower()):
return
time.sleep(self.sl2b.selenium_speed.total_seconds())
def get_keyword_names(self):
if self.dry_run:
return [kw for kw in super().get_keyword_names() if self.keyword_implemented(kw)]
return super().get_keyword_names()
def get_keyword_documentation(self, name):
if name == "__intro__":
return self.__doc__
if name == "__init__":
return self.__init__.__doc__
if not EXECUTION_CONTEXTS.current and not self.keyword_implemented(name):
return "*DEPRECATED* keyword is not implemented yet."
if not self.keyword_implemented(name):
return "KEYWORD IS NOT YET IMPLEMENTED."
try:
name = getattr(self.sl, name).robot_name or name
return self.sl.get_keyword_documentation(name)
except Exception:
pass
return super().get_keyword_documentation(name)
class SLtoB:
def __init__(
self,
timeout=timedelta(seconds=5.0),
implicit_wait=timedelta(seconds=10.0),
screenshot_root_directory: Optional[str] = None,
browser_args: Optional[Dict] = None,
library: SeleniumLibraryToBrowser = None,
page_load_timeout=timedelta(minutes=5),
prioritize_library: Optional[PriorityLibrary] = None,
):
self.timeout = timeout
self.screenshot_root_directory = screenshot_root_directory
self.library = library
self.page_load_timeout = page_load_timeout
self._browser: Optional[Browser] = None
self._browser_args = browser_args or {}
self._context_indexes = {}
self._context_aliases = {}
self._browser_index = count(1)
self._context_page_catalog = {}
self._selenium_speed = timedelta(seconds=0.0)
self._implicit_wait = implicit_wait
self.prioritize_library = prioritize_library
if prioritize_library and BuiltIn().robot_running:
_b = self.b
@property
def implicit_wait(self):
to = self.b.get_timeout(None)
return timedelta(milliseconds=to)
@property
def selenium_speed(self) -> timedelta:
return self._selenium_speed
@selenium_speed.setter
def selenium_speed(self, value: Union[float, str, timedelta]):
if isinstance(value, (int, float)):
self._selenium_speed = timedelta(seconds=value)
elif isinstance(value, str):
self._selenium_speed = timedelta(seconds=timestr_to_secs(value))
elif isinstance(value, timedelta):
self._selenium_speed = value
else:
raise TypeError(f"Value '{value}' is not a valid type.")
@property
def b(self) -> Browser:
current_suite = BuiltIn().get_variable_value("${SUITE_SOURCE}")
if not hasattr(self, '_suite') or self._suite != current_suite:
self._browser_lib = None
browser_lib_name = None
sl2b_name = None
for name, lib in BuiltIn().get_library_instance(all=True).items():
if isinstance(lib, Browser):
browser_lib_name = name
self._browser_lib = lib
elif isinstance(lib, SeleniumLibraryToBrowser):
sl2b_name = name
if self._browser_lib is None:
self._browser_args["timeout"] = self._implicit_wait
self._browser_lib = Browser(**self._browser_args)
self._browser_lib.set_strict_mode(False, Scope.Global)
self._browser_lib._auto_closing_level = AutoClosingLevel.MANUAL
self.b.set_browser_timeout(self.implicit_wait, scope=Scope.Global)
if self.prioritize_library == PriorityLibrary.Browser:
BuiltIn().set_library_search_order(browser_lib_name or "Browser")
elif self.prioritize_library == PriorityLibrary.SeleniumLibraryToBrowser:
BuiltIn().set_library_search_order(sl2b_name or "SeleniumLibraryToBrowser")
self._suite = BuiltIn().get_variable_value("${SUITE_SOURCE}")
return self._browser_lib @property
def library_comp(self) -> LibraryComponent:
return LibraryComponent(self.b)
@property
def log_dir(self) -> Path:
try:
logfile = BuiltIn().get_variable_value("${LOG FILE}", None)
if logfile is None or logfile == "NONE":
return Path(BuiltIn().get_variable_value("${OUTPUTDIR}", Path.cwd()))
return Path(logfile).parent
except RobotNotRunningError:
return Path.cwd()
def get_button_locator(self, locator: WebElement) -> WebElement:
original_locator = locator.original_locator
loc = WebElement.is_default(locator)
if loc:
loc = loc.replace('"', '\\"')
locator = WebElement(
"xpath="
f'//button[@id="{loc}"]|'
f'//button[@name="{loc}"]|'
f'//button[@value="{loc}"]|'
f'//button[.="{loc}"]|'
f'//input[@id="{loc}"]|'
f'//input[@name="{loc}"]|'
f'//input[@value="{loc}"]|'
f'//input[@src="{loc}"]'
)
locator.original_locator = original_locator
return locator
def get_input_locator(self, locator: WebElement) -> WebElement:
original_locator = locator.original_locator
loc = WebElement.is_default(locator)
if loc:
loc = loc.replace('"', '\\"')
locator = WebElement(
"xpath="
f'//input[@id="{loc}"]|'
f'//input[@name="{loc}"]|'
f'//input[@value="{loc}"]|'
f'//input[@src="{loc}"]'
)
locator.original_locator = original_locator
return locator
def get_link_locator(self, locator: WebElement) -> WebElement:
original_locator = locator.original_locator
loc = WebElement.is_default(locator)
if loc:
xpath = (
'xpath=//a[@id="{loc}"] | '
'//a[@name="{loc}"] | '
'//a[@href="{loc}"] | '
'//a[normalize-space(descendant-or-self::text())="{loc}"]'
)
if '"' in loc:
xpath = xpath.replace('"', "'")
locator = WebElement(xpath.format(loc=loc))
locator.original_locator = original_locator
return locator
def get_image_locator(self, locator: WebElement) -> WebElement:
original_locator = locator.original_locator
loc = WebElement.is_default(locator)
if loc:
locator = WebElement(
f'xpath=//img[@id="{loc}"] | '
f'//img[@name="{loc}"] | '
f'//img[@src="{loc}"] | '
f'//img[@alt="{loc}"]'
)
locator.original_locator = original_locator
return locator
def get_list_locator(self, locator: WebElement) -> WebElement:
original_locator = locator.original_locator
loc = WebElement.is_default(locator)
if loc:
locator = WebElement(
f'xpath=//select[@id="{loc}"] | '
f'//select[@name="{loc}"] | '
f'//select[@value="{loc}"]'
)
locator.original_locator = original_locator
return locator
def page_contains(self, locator):
self.b.set_selector_prefix(None, scope=Scope.Global)
if self.b.get_element_count(locator):
return True
cnt = self.b.get_element_count("iframe, frame")
for index in range(cnt):
if self.b.get_element_count(f"iframe, frame >> nth={index} >>> {locator}"):
return True
return False
def type_converter(self, argument: Any) -> str:
return type(argument).__name__.lower()
@keyword(tags=("IMPLEMENTED",))
def add_cookie(
self,
name: str,
value: str,
path: str = "/",
domain: Optional[str] = None,
secure: bool = False,
expiry: Union[None, int, str] = None,
):
if domain is None:
domain = self.b.evaluate_javascript(None, "window.location.hostname")
if expiry is not None:
expiry = self._expiry(expiry)
self.b.add_cookie(name, value, domain=domain, path=path, secure=secure, expires=expiry)
def _expiry(self, expiry):
try:
return int(expiry)
except (ValueError, TypeError):
return int(convert_date(expiry, result_format="epoch"))
@keyword
def add_location_strategy(
self, strategy_name: str, strategy_keyword: str, persist: bool = False
):
...
@keyword
def alert_should_be_present(
self,
text: str = "",
action: str = "ACCEPT",
timeout: Optional[timedelta] = None,
):
...
@keyword
def alert_should_not_be_present(
self, action: str = "ACCEPT", timeout: Optional[timedelta] = None
):
...
@keyword(tags=("IMPLEMENTED",))
def assign_id_to_element(self, locator: WebElement, id: str): # noqa: A002
self.b.evaluate_javascript(locator, f"element => element.id = '{id}'")
@keyword(tags=("IMPLEMENTED",))
def capture_element_screenshot(
self,
locator: WebElement,
filename: str = DEFAULT_FILENAME_ELEMENT,
) -> str:
if not self.b.get_page_ids():
logger.info("Cannot capture screenshot from element because no browser is open.")
return None
try:
self.b.get_element_states(locator, CONTAINS, "attached")
except AssertionError:
raise ElementNotFound(f"Element with locator '{locator.original_locator}' not found.")
embedding = self._decide_embedded(filename)
screenshot_file = (
EMBED
if embedding
else re.sub(".png$", "", self._get_screenshot_path(filename, embedding))
)
screenshot_path = self.b.take_screenshot(filename=screenshot_file, selector=locator)
return EMBED if embedding else screenshot_path
@keyword(tags=("IMPLEMENTED",))
def capture_page_screenshot(self, filename: str = DEFAULT_FILENAME_PAGE) -> str:
if not self.b.get_page_ids():
logger.info("Cannot capture screenshot from element because no browser is open.")
return None
embedding = self._decide_embedded(filename)
screenshot_file = (
EMBED
if embedding
else re.sub(".png$", "", self._get_screenshot_path(filename, embedding))
)
screenshot_path = self.b.take_screenshot(filename=screenshot_file)
return EMBED if embedding else screenshot_path
@keyword(tags=("IMPLEMENTED",))
def checkbox_should_be_selected(self, locator: WebElement):
logger.info(f"Verifying checkbox '{locator.original_locator}' is selected.")
if not (
self.b.get_attribute(locator, "type").lower() == "checkbox"
and self.b.get_property(locator, "nodeName") == "INPUT"
):
raise ElementNotFound(f"Checkbox with locator '{locator.original_locator}' not found.")
try:
self.b.get_checkbox_state(locator, EQUALS, True)
except AssertionError as e:
raise AssertionError(
f"Checkbox '{locator.original_locator}' should have been selected but was not."
) from e
@keyword(tags=("IMPLEMENTED",))
def checkbox_should_not_be_selected(self, locator: WebElement):
if not (
self.b.get_attribute(locator, "type").lower() == "checkbox"
and self.b.get_property(locator, "nodeName") == "INPUT"
):
raise ElementNotFound(f"Checkbox with locator '{locator.original_locator}' not found.")
try:
self.b.get_checkbox_state(locator, EQUALS, False)
except AssertionError as e:
raise AssertionError(
f"Checkbox '{locator.original_locator}' should not have been selected."
) from e
@keyword(tags=("IMPLEMENTED",))
def choose_file(self, locator: WebElement, file_path: str):
file = Path(file_path).resolve()
logger.info(f"Sending {file} to browser.")
if not file.exists():
raise InvalidArgumentException(f"Message: File not found: {file}")
# self.b.upload_file_by_selector(locator, file_path)
with self.b.playwright.grpc_channel() as stub:
response = stub.UploadFileBySelector(
Request().FileBySelector(
path=str(file),
selector=locator,
strict=self.library_comp.strict_mode,
)
)
logger.debug(response.log)
@keyword(tags=("IMPLEMENTED",))
def clear_element_text(self, locator: WebElement):
self.b.clear_text(locator)
@keyword(tags=("IMPLEMENTED",))
def click_button(self, locator: WebElement, modifier: Union[bool, str] = False):
locator = self.get_button_locator(locator)
self.click_element(locator, modifier)
@keyword(tags=("IMPLEMENTED",))
def click_element(
self,
locator: WebElement,
modifier: Union[bool, str] = False,
action_chain: bool = False,
):
modifiers = []
if modifier and modifier.upper() != "FALSE":
modifiers = modifier.split("+")
else:
logger.info(f"Clicking element '{locator.original_locator}'.")
try:
for mod in modifiers:
if mod.upper() not in dict(Keys.__members__):
raise ValueError(f"'{mod.upper()}' modifier does not match to Selenium Keys")
self.b.keyboard_key(KeyAction.down, Keys[mod.upper()].value)
node = self.b.get_property(locator, "nodeName")
if node == "OPTION":
value = self.b.get_property(locator, "value")
self.b.select_options_by(f"{locator} >> ..", SelectAttribute.value, value)
else:
self.b.click_with_options(locator, MouseButton.left)
except ValueError as e:
raise e
except Exception as e:
raise ElementNotFound(
f"Element with locator '{locator.original_locator}' not found."
) from e
finally:
for mod in reversed(modifiers):
with suppress(Exception):
self.b.keyboard_key(KeyAction.up, Keys[mod.upper()].value)
@keyword(tags=("IMPLEMENTED",))
def click_element_at_coordinates(self, locator: WebElement, xoffset: int, yoffset: int):
bbox = self.b.get_boundingbox(selector=locator) # {x, y, width, height}
# calculates the half of the width and height of the element
x = bbox["width"] / 2 + xoffset
y = bbox["height"] / 2 + yoffset
self.b.click_with_options(selector=locator, position_x=x, position_y=y)
@keyword(tags=("IMPLEMENTED",))
def click_image(self, locator: WebElement, modifier: Union[bool, str] = False):
"""See the Locating elements section for details about the locator syntax.
When using the default locator strategy, images are searched using id, name, src and alt.
"""
img_locator = self.get_image_locator(locator)
try:
self.b.get_element_count(img_locator, GREATER_THAN, 0)
locator = img_locator
except AssertionError as e:
input_locator = self.get_input_locator(locator)
try:
self.b.get_element_count(input_locator, GREATER_THAN, 0)
locator = input_locator
except AssertionError:
raise ElementNotFound(
f"Element with locator '{locator.original_locator}' not found."
) from e
self.click_element(locator, modifier)
@keyword(tags=("IMPLEMENTED",))
def click_link(self, locator: WebElement, modifier: Union[bool, str] = False):
"""See the Locating elements section for details about the locator syntax.
When using the default locator strategy, links are searched using id, name,
href and the link text.
"""
locator = self.get_link_locator(locator)
for e in self.get_webelements(locator):
if self.b.get_property(e, "nodeName") == "A":
self.click_element(e, modifier)
return
raise ElementNotFound(f"Element with locator '{locator.original_locator}' not found.")
@keyword(tags=("IMPLEMENTED",))
def close_all_browsers(self):
self.b.close_browser(SelectionType.ALL)
self._context_page_catalog = {}
self._context_aliases = {}
self._context_indexes = {}
self._browser_index = count(1)
@keyword(tags=("IMPLEMENTED",))
def close_browser(self):
context_ids = self.b.get_context_ids(SelectionType.CURRENT, browser=SelectionType.CURRENT)
if not context_ids:
return self.close_all_browsers()
current_id = context_ids[0]
for index, ctx_id in self._context_indexes.items():
if ctx_id == current_id:
self._context_page_catalog.pop(ctx_id)
self._context_indexes.pop(index)
for alias, idx in self._context_aliases.items():
if idx == index:
self._context_aliases.pop(alias)
break
break
self.b.close_context()
if not self.b.get_context_ids(context=SelectionType.ALL, browser=SelectionType.CURRENT):
self.b.close_browser(SelectionType.CURRENT)
return None
return None
@keyword(tags=("IMPLEMENTED",))
def close_window(self):
self.b.close_page(SelectionType.CURRENT)
@keyword(tags=("IMPLEMENTED",))
def cover_element(self, locator: WebElement):
count = self.b.get_element_count(locator)
if not count:
raise ElementNotFound(f"No element with locator '{locator.original_locator}' found.")
self.b.evaluate_javascript(
locator,
"elements => {",
" for (let old_element of elements) {"
" let newDiv = document.createElement('div');",
" newDiv.setAttribute('name', 'covered');",
" newDiv.style.backgroundColor = 'blue';",
" newDiv.style.zIndex = '999';",
" newDiv.style.top = old_element.offsetTop + 'px';",
" newDiv.style.left = old_element.offsetLeft + 'px';",
" newDiv.style.height = old_element.offsetHeight + 'px';",
" newDiv.style.width = old_element.offsetWidth + 'px';",
" old_element.parentNode.insertBefore(newDiv, old_element);",
" old_element.remove();",
" newDiv.parentNode.style.overflow = 'hidden';",
" }",
"}",
all_elements=True,
)
@keyword
def create_webdriver(
self, driver_name: str, alias: Optional[str] = None, kwargs=None, **init_kwargs
):
...
@keyword(tags=("IMPLEMENTED",))
def current_frame_should_contain(self, text: str, loglevel: str = "TRACE"):
try:
self.b.get_element_count(
f"text=/.*{text}.*/",
GREATER_THAN,
0,
f"Frame should have contained text '{text}' but did not.",
)
except AssertionError as e:
self.log_source(loglevel)
raise e
logger.info(f"Current frame contains text '{text}'.")
@keyword(tags=("IMPLEMENTED",))
def current_frame_should_not_contain(self, text: str, loglevel: str = "TRACE"):