-
Notifications
You must be signed in to change notification settings - Fork 29
/
__init__.py
1693 lines (1413 loc) · 61 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""This package contains classes that represent widgets in Patternfly for Widgetastic"""
from __future__ import unicode_literals
import re
import six
import time
from cached_property import cached_property
from collections import namedtuple
from widgetastic.exceptions import NoSuchElementException, UnexpectedAlertPresentException, \
WidgetOperationFailed
from widgetastic.log import call_sig
from widgetastic.utils import ParametrizedLocator, VersionPick, partial_match
from widgetastic.widget import BaseInput, ClickableMixin, TextInput, Text, Widget, View, \
do_not_read_this_widget
from widgetastic.xpath import quote
from wait_for import wait_for, wait_for_decorator, TimedOutError
class CandidateNotFound(Exception):
"""
Raised if there is no candidate found whilst trying to traverse a tree.
"""
def __init__(self, d):
self.d = d
@property
def message(self):
return ", ".join("{}: {}".format(k, v) for k, v in six.iteritems(self.d))
def __str__(self):
return self.message
class DropdownDisabled(Exception):
pass
class DropdownItemDisabled(Exception):
pass
class DropdownItemNotFound(Exception):
pass
class Button(Widget, ClickableMixin):
"""A PatternFly/Bootstrap button
You can match by text, partial text or by attributes, you can also add the bootstrap classes
into the matching.
.. code-block:: python
Button('Text of button (unless it is an input ...)')
Button('contains', 'Text of button (unless it is an input ...)')
Button(title='Show xyz') # And such
Button('Add', classes=[Button.PRIMARY])
assert button.active
assert not button.disabled
"""
CHECK_VISIBILITY = True
# Classes usable in the constructor
# Button types
DEFAULT = 'btn-default'
PRIMARY = 'btn-primary'
SUCCESS = 'btn-success'
INFO = 'btn-info'
WARNING = 'btn-warning'
DANGER = 'btn-danger'
LINK = 'btn-link'
# Button sizes
LARGE = 'btn-lg'
MEDIUM = 'btn-md'
SMALL = 'btn-sm'
EXTRA_SMALL = 'btn-xs'
# Shape
BLOCK = 'btn-block'
def __init__(self, parent, *text, **kwargs):
logger = kwargs.pop('logger', None)
Widget.__init__(self, parent, logger=logger)
self.args = text
self.kwargs = kwargs
classes = kwargs.pop('classes', [])
if text:
if kwargs: # classes should have been the only kwarg combined with text args
raise TypeError('If you pass button text then only pass classes in addition')
if len(text) == 1:
self.locator_conditions = 'normalize-space(.)={}'.format(quote(text[0]))
elif len(text) == 2 and text[0].lower() == 'contains':
self.locator_conditions = 'contains(normalize-space(.), {})'.format(quote(text[1]))
else:
raise TypeError('An illegal combination of text params')
else:
# Join the kwargs, if any
self.locator_conditions = ' and '.join(
'@{}={}'.format(attr, quote(value)) for attr, value in kwargs.items())
if classes:
if self.locator_conditions:
self.locator_conditions += ' and '
self.locator_conditions += ' and '.join(
'contains(@class, {})'.format(quote(klass))
for klass in classes)
if self.locator_conditions:
self.locator_conditions = 'and ({})'.format(self.locator_conditions)
# TODO: Handle input value the same way as text for other tags
def __locator__(self):
return (
'.//*[(self::a or self::button or (self::input and (@type="button" or @type="submit")))'
' and contains(@class, "btn") {}]'.format(self.locator_conditions))
@property
def active(self):
return 'active' in self.browser.classes(self)
@property
def disabled(self):
return ('disabled' in self.browser.classes(self) or
self.browser.get_attribute('disabled', self) == 'disabled')
def __repr__(self):
return '{}{}'.format(type(self).__name__, call_sig(self.args, self.kwargs))
@property
def title(self):
return self.browser.get_attribute('title', self)
class ViewChangeButton(Widget, ClickableMixin):
"""A PatternFly/Bootstrap view selection button in CFME 56z
.. code-block:: python
ViewChangeButton(title='Grid View')
assert button.active
"""
CHECK_VISIBILITY = True
def __init__(self, parent, title, **kwargs):
Widget.__init__(self, parent, logger=kwargs.pop('logger', None))
self.title = title
def __locator__(self):
return './/a[(@title={}) and i[contains(@class, "fa")]]'.format(quote(self.title))
@property
def active(self):
return 'active' in self.browser.classes('..', parent=self)
class Input(TextInput):
"""Patternfly input
Has some additional methods.
"""
@property
def help_block(self):
e = self.browser.element(self)
try:
help_block = self.browser.element('./following-sibling::span', parent=e)
except NoSuchElementException:
return None
else:
return self.browser.text(help_block)
class FlashMessages(Widget):
"""Represents the block of flash messages."""
def __init__(self, parent, locator, logger=None):
Widget.__init__(self, parent, logger=logger)
self.locator = locator
def __locator__(self):
return self.locator
def read(self):
result = []
for message in self.messages:
result.append(message.read())
return result
@property
def messages(self):
result = []
try:
for flash_div in self.browser.elements(
'./div[contains(@class, "alert")]', parent=self, check_visibility=True):
result.append(FlashMessage(self, flash_div, logger=self.logger))
except NoSuchElementException:
pass
return result
def dismiss(self):
for message in self.messages:
message.dismiss()
def assert_no_error(self):
self.logger.info('asserting there are no error messages')
for message in self.messages:
if message.type not in {'success', 'info'}:
self.logger.error('%s: %r', message.type, message.text)
raise AssertionError('assert_no_error: {}: {}'.format(message.type, message.text))
else:
self.logger.info('%s: %r', message.type, message.text)
def assert_message(self, text, t=None, partial=False):
log_part = 'partial match of' if partial else ''
if t is not None:
self.logger.info('asserting %s the flash message %r of type %r', log_part, text, t)
else:
self.logger.info('asserting %s the flash message %r', log_part, text)
all_messages = self.messages # Store for logging on exception without querying twice
for message in all_messages:
if (partial and text in message.text) or (not partial and text == message.text):
if t is not None and message.type == t:
return True
elif t is None:
return True
else:
if t is not None:
e_text = '{}: {}'.format(t, text)
else:
e_text = text
raise AssertionError('assert {} message: {}. \n Available messages: {}'
.format(log_part, e_text, [msg.text for msg in all_messages]))
def assert_success_message(self, text, t=None, partial=False):
self.assert_no_error()
self.assert_message(text, t='success', partial=partial)
def __repr__(self):
return '{}({!r})'.format(type(self).__name__, self.locator)
class FlashMessage(Widget):
"""Not to be instantiated on View"""
TYPE_MAPPING = {
"alert-warning": "warning",
"alert-success": "success",
"alert-danger": "error",
"alert-info": "info"
}
def __init__(self, parent, flash_div, logger=None):
Widget.__init__(self, parent, logger=logger)
self.flash_div = flash_div
def __locator__(self):
return self.flash_div
def read(self):
return self.text
@property
def text(self):
return self.browser.text('./strong', parent=self)
def dismiss(self):
self.logger.info('dismissed %r', self.text)
return self.browser.click('./button[contains(@class, "close")]', parent=self)
@property
def icon(self):
try:
e = self.browser.element('./span[contains(@class, "pficon")]', parent=self)
except NoSuchElementException:
return None
for class_ in self.browser.classes(e):
if class_.startswith('pficon-'):
return class_[7:]
else:
return None
@property
def type(self):
for class_ in self.browser.classes(self):
if class_ in self.TYPE_MAPPING:
return self.TYPE_MAPPING[class_]
else:
raise ValueError(
'Could not find a proper alert type. Available classes: {!r} Alert has: {!r}'
.format(self.TYPE_MAPPING, self.browser.classes(self)))
class NavDropdown(Widget, ClickableMixin):
"""The dropdowns used eg. in navigation. Usually located in the top navbar."""
def __init__(self, parent, locator, logger=None):
Widget.__init__(self, parent, logger=logger)
self.locator = locator
def __locator__(self):
return self.locator
def read(self):
return self.text
@property
def expandable(self):
try:
self.browser.element('./a/span[contains(@class, "caret")]', parent=self)
except NoSuchElementException:
return False
else:
return True
@property
def expanded(self):
if not self.expandable:
return False
return 'open' in self.browser.classes(self)
@property
def collapsed(self):
return not self.expanded
def expand(self):
if not self.expandable:
raise ValueError('{} is not expandable'.format(self.locator))
if not self.expanded:
self.click()
if not self.expanded:
raise Exception('Could not expand {}'.format(self.locator))
else:
self.logger.info('expanded')
def collapse(self):
if not self.expandable:
return
if self.expanded:
self.click()
if self.expanded:
raise Exception('Could not collapse {}'.format(self.locator))
else:
self.logger.info('collapsed')
@property
def text(self):
try:
return self.browser.text('./a/p', parent=self)
except NoSuchElementException:
return None
@property
def icon(self):
try:
el = self.browser.element('./a/span[contains(@class, "pficon")]', parent=self)
for class_ in self.browser.classes(el):
if class_.startswith('pficon-'):
return class_[7:]
else:
return None
except NoSuchElementException:
return None
@property
def items(self):
return [
self.browser.text(element)
for element
in self.browser.elements('./ul/li[not(contains(@class, "divider"))]', parent=self)]
def has_item(self, item):
return item in self.items
def item_enabled(self, item):
if not self.has_item(item):
raise ValueError('There is not such item {}'.format(item))
element = self.browser.element(
'./ul/li[normalize-space(.)={}]'.format(quote(item)), parent=self)
return 'disabled' not in self.browser.classes(element)
def select_item(self, item):
if not self.item_enabled(item):
raise ValueError('Cannot click disabled item {}'.format(item))
self.expand()
self.logger.info('selecting item {}'.format(item))
self.browser.click('./ul/li[normalize-space(.)={}]'.format(quote(item)), parent=self)
def __repr__(self):
return '{}({!r})'.format(type(self).__name__, self.locator)
class BootstrapNav(Widget):
"""Encapsulate a Bootstrap nav component
PatternFly is based on Bootstrap, and thus many of the Bootstrap components are available to
PatternFly users. This widget provides convenience methods for the Bootstrap nav component for
clicking on links and determining if an item in the nav is disabled.
When instantiating this widget, use the XPath locator to point to exactly which Bootstrap nav
you wish to work with.
.. _code:: python
nav = BootstrapNav('//div[id="main"]/ul[@contains(@class, "nav")]')
See http://getbootstrap.com/components/#nav for more information on Bootstrap nav components.
"""
ROOT = ParametrizedLocator('{@locator}')
CURRENTLY_SELECTED = './/li[contains(@class, "active")]/a'
TEXT_MATCHING = './/li/a[text()={txt}]'
ATTR_MATCHING = './/li/a[@{attr}={txt}]'
TEXT_DISABLED = './/li[contains(@class, "disabled")]/a[text()={txt}]'
ATTR_DISABLED = './/li[contains(@class, "disabled")]/a[@{attr}={txt}]'
VALID_ATTRS = {'href', 'title', 'class', 'id'}
def __init__(self, parent, locator, logger=None):
"""Create the widget"""
Widget.__init__(self, parent, logger=logger)
self.locator = locator
def __repr__(self):
"""String representation of this object"""
return '{}({!r})'.format(type(self).__name__, self.locator)
@property
def currently_selected(self):
"""A property to return the currently selected menu item"""
return [self.browser.text(el)
for el in self.browser.elements(self.CURRENTLY_SELECTED)]
def read(self):
"""Implement read()"""
return self.currently_selected
def select(self, text=None, **kwargs):
"""Select/click an item from the menu"""
if text:
# Select an item based on the text of that item
xpath = self.TEXT_MATCHING.format(txt=quote(text))
elif self.VALID_ATTRS & set(kwargs.keys()):
# Select an item based on an attribute, if it is one of the VALID_ATTRS
attr = (self.VALID_ATTRS & set(kwargs.keys())).pop()
xpath = self.ATTR_MATCHING.format(attr=attr, txt=quote(kwargs[attr]))
else:
# If neither text, nor one of the VALID_ATTRS is supplied, raise a KeyError
raise KeyError(
'Either text or one of {} needs to be specified'.format(self.VALID_ATTRS))
link = self.browser.element(xpath)
self.browser.click(link)
def is_disabled(self, text=None, **kwargs):
"""Check if an item is disabled"""
if text:
# Check if an item is disabled based on the text of that item
xpath = self.TEXT_DISABLED.format(txt=quote(text))
elif self.VALID_ATTRS & set(kwargs.keys()):
# Check if an item is disabled based on an attribute, if it is one of the VALID_ATTRS
attr = (self.VALID_ATTRS & set(kwargs.keys())).pop()
xpath = self.ATTR_DISABLED.format(attr=attr, txt=quote(kwargs[attr]))
else:
# If neither text, nor one of the VALID_ATTRS is supplied, raise a KeyError
raise KeyError(
'Either text or one of {} needs to be specified'.format(self.VALID_ATTRS))
try:
self.browser.element(xpath)
return True
except NoSuchElementException:
return False
def has_item(self, text=None, **kwargs):
"""Check if an item with this name or attributes exists"""
if text:
# Check if an item exists based on the text of that item
xpath = self.TEXT_MATCHING.format(txt=quote(text))
elif self.VALID_ATTRS & set(kwargs.keys()):
# Check if an item exists based on an attribute, if it is one of the VALID_ATTRS
attr = (self.VALID_ATTRS & set(kwargs.keys())).pop()
xpath = self.ATTR_MATCHING.format(attr=attr, txt=quote(kwargs[attr]))
else:
# If neither text, nor one of the VALID_ATTRS is supplied, raise a KeyError
raise KeyError(
'Either text or one of {} needs to be specified'.format(self.VALID_ATTRS))
try:
self.browser.element(xpath)
return True
except NoSuchElementException:
return False
class VerticalNavigation(Widget):
"""The Patternfly Vertical navigation."""
CURRENTLY_SELECTED = './/li[contains(@class, "active")]/a'
LINKS = './li/a'
ITEMS_MATCHING = './li[a[normalize-space(.)={}]]'
DIV_LINKS_MATCHING = './ul/li/a[span[normalize-space(.)={txt}] or @href={txt}]'
SUB_LEVEL = './following-sibling::div[contains(@class, "nav-pf-")]'
SUB_ITEM_LIST = './div[contains(@class, "nav-pf-")]/ul'
CHILD_UL_FOR_DIV = './li[a[normalize-space(.)={}]]/div[contains(@class, "nav-pf-")]/ul'
MATCHING_LI_FOR_DIV = './ul/li[a[span[normalize-space(.)={}]]]'
def __init__(self, parent, locator, logger=None):
Widget.__init__(self, parent, logger=logger)
self.locator = locator
def __locator__(self):
return self.locator
def read(self):
return self.currently_selected
def nav_links(self, *levels):
if not levels:
return [self.browser.text(el) for el in self.browser.elements(self.LINKS, parent=self)]
# Otherwise
current_item = self
for i, level in enumerate(levels):
li = self.browser.element(
self.ITEMS_MATCHING.format(quote(level)),
parent=current_item)
try:
current_item = self.browser.element(self.SUB_ITEM_LIST, parent=li)
except NoSuchElementException:
if i == len(levels) - 1:
# It is the last one
return []
else:
raise
return [
self.browser.text(el) for el in self.browser.elements(self.LINKS, parent=current_item)]
def nav_item_tree(self, start=None):
start = start or []
result = {}
for item in self.nav_links(*start):
sub_items = self.nav_item_tree(start=start + [item])
result[item] = sub_items or None
if result and all(value is None for value in result.values()):
# If there are no child nodes, then just make it a list
result = list(six.iterkeys(result))
return result
@property
def currently_selected(self):
return [
self.browser.text(el)
for el
in self.browser.elements(self.CURRENTLY_SELECTED, parent=self)]
def select(self, *levels, **kwargs):
"""Select an item in the navigation.
Args:
*levels: Items to be clicked in the navigation.
Keywords:
anyway: Default behaviour is that if you try selecting an already selected item, it will
not do it. If you pass ``anyway=True``, it will click it anyway.
"""
levels = list(levels)
self.logger.info('Selecting %r in navigation', levels)
anyway = kwargs.pop('anyway', True)
if levels == self.currently_selected and not anyway:
return
passed_levels = []
current_div = self.get_child_div_for(*passed_levels)
for level in levels:
passed_levels.append(level)
finished = passed_levels == levels
link = self.browser.element(
self.DIV_LINKS_MATCHING.format(txt=quote(level)), parent=current_div)
expands = bool(
self.browser.elements(self.SUB_LEVEL, parent=link))
if expands and not finished:
self.logger.debug('moving to %s to open the next level', level)
# No safety check because previous command did it
self.browser.move_to_element(link, check_safe=False)
@wait_for_decorator(timeout='10s', delay=0.2)
def other_div_displayed():
return 'is-hover' in self.browser.classes(
self.MATCHING_LI_FOR_DIV.format(quote(level)),
parent=current_div)
new_div = self.get_child_div_for(*passed_levels)
# No safety check because previous command did it
self.browser.move_to_element(new_div, check_safe=False)
current_div = new_div
elif not expands and not finished:
raise ValueError(
'You are trying to expand {!r} which cannot be expanded'.format(passed_levels))
else:
# finished
self.logger.debug('finishing the menu selection by clicking on %s', level)
# No safety check because previous command did it
self.browser.click(link, ignore_ajax=True, check_safe=False)
self.browser.handle_alert(wait=2.0, squash=True)
def get_child_div_for(self, *levels):
current = self
for level in levels:
try:
current = self.browser.element(
self.CHILD_UL_FOR_DIV.format(quote(level)),
parent=current)
except NoSuchElementException:
return None
return self.browser.element('..', parent=current)
def __repr__(self):
return '{}({!r})'.format(type(self).__name__, self.locator)
class Tab(View, ClickableMixin):
"""Represents the Tab widget.
Selects itself automatically when any child widget gets accessed, ensuring that the widget is
visible.
"""
TAB_NAME = None
INDIRECT = True
ROOT = ParametrizedLocator(
'.//ul[contains(@class, "nav-tabs")]/li[normalize-space(.)={@tab_name|quote}]')
@property
def tab_name(self):
return self.TAB_NAME or type(self).__name__.capitalize()
def is_active(self):
return 'active' in self.browser.classes(self)
def is_disabled(self):
return 'disabled' in self.browser.classes(self)
def select(self):
if not self.is_active():
if self.is_disabled():
raise ValueError(
'The tab {} you are trying to select is disabled'.format(self.tab_name))
self.logger.info('opened the tab %s', self.tab_name)
self.click()
def child_widget_accessed(self, widget):
# Select the tab
self.select()
def __repr__(self):
return '<Tab {!r}>'.format(self.tab_name)
class Accordion(View, ClickableMixin):
"""Bootstrap/Patternfly accordions.
They are like views that contain widgets. If a widget is accessed in the accordion, the
accordion makes sure that it is open.
You need to set the ``ACCORDION_NAME`` to correspond with the text in the accordion.
If the accordion title is just a capitalized version of the accordion class name, you do not
need to set the ``ACCORDION_NAME``.
If the accordion is in an exotic location, you also have to change the ``ROOT``.
Accordions can contain trees. Basic ``TREE_LOCATOR`` is tuned after ManageIQ so if your UI has a
different structure, you should change this locator accordingly.
"""
ACCORDION_NAME = None
ROOT = ParametrizedLocator(
'.//div[contains(@class, "panel-group")]/div[contains(@class, "panel") and '
'./div/h4/a[normalize-space(.)={@accordion_name|quote}]]')
TREE_LOCATOR = '|'.join([
'.//miq-tree-view',
'.//div[contains(@class, "treeview") and ./ul]',
'.//div[./ul[contains(@class, "dynatree-container")]]'])
HEADER_LOCATOR = './div/h4/a'
@property
def accordion_name(self):
return self.ACCORDION_NAME or type(self).__name__.capitalize()
@property
def is_opened(self):
attr = self.browser.get_attribute('aria-expanded', self)
if attr is None:
# Try other way
panel = self.browser.element('./div[contains(@class, "panel-collapse")]')
classes = self.browser.classes(panel)
return 'collapse' in classes and 'in' in classes
else:
return attr.lower().strip() == 'true'
@property
def is_closed(self):
return not self.is_opened
def click(self):
"""Override Clickable's click."""
self.browser.click(self.HEADER_LOCATOR)
def open(self):
if self.is_closed:
self.logger.info('opening')
self.click()
try:
wait_for(lambda: self.is_opened, delay=0.1, num_sec=3)
except TimedOutError:
self.logger.warning('Could not open the accordion, trying clicking again')
# Workaround stupid pages, perhaps we put a try mechanism in here
if self.is_closed:
self.click()
try:
wait_for(lambda: self.is_opened, delay=0.1, num_sec=3)
except TimedOutError:
self.logger.error('Could not open the accordion')
raise Exception('Could not open accordion {}'.format(self.accordion_name))
def close(self):
if self.is_opened:
self.logger.info('closing')
self.click()
def child_widget_accessed(self, widget):
# Open the Accordion
self.open()
def read(self):
if self.is_closed:
do_not_read_this_widget()
return super(Accordion, self).read()
@cached_property
def tree_id(self):
try:
el = self.browser.element(self.TREE_LOCATOR)
except NoSuchElementException:
raise AttributeError('No tree in the accordion {}'.format(self.accordion_name))
else:
return self.browser.get_attribute('id', el) or self.browser.get_attribute('name', el)
def __repr__(self):
return '<Accordion {!r}>'.format(self.accordion_name)
class BootstrapSelect(Widget, ClickableMixin):
"""This class represents the Bootstrap Select widget.
Args:
id: id of the select, that is the ``data-id`` attribute on the ``button`` tag.
name: name of the select tag
locator: If none of above apply, you can also supply a full locator.
can_hide_on_select: Whether the select can hide after selection, important for
:py:meth:`close` to work properly.
"""
Option = namedtuple("Option", ["text", "value"])
LOCATOR_START = './/div[contains(@class, "bootstrap-select")]'
ROOT = ParametrizedLocator('{@locator}')
BY_VISIBLE_TEXT = '//div/ul/li/a[./span[contains(@class, "text") and normalize-space(.)={}]]'
BY_PARTIAL_VISIBLE_TEXT = (
'.//div/ul/li/a[./span[contains(@class, "text") and contains(normalize-space(.), {})]]')
def __init__(
self, parent, id=None, name=None, locator=None, can_hide_on_select=False, logger=None):
Widget.__init__(self, parent, logger=logger)
if id is not None:
self.locator = self.LOCATOR_START + '/button[normalize-space(@data-id)={}]/..'.format(
quote(id))
elif name is not None:
self.locator = self.LOCATOR_START + '/select[normalize-space(@name)={}]/..'.format(
quote(name))
elif locator is not None:
self.locator = locator
else:
raise TypeError('You need to specify either, id, name or locator for BootstrapSelect')
self.id = id
self.can_hide_on_select = can_hide_on_select
@property
def is_open(self):
return 'open' in self.browser.classes(self)
@property
def is_multiple(self):
return 'show-tick' in self.browser.classes(self)
def open(self):
if not self.is_open:
self.click()
self.logger.debug('opened')
def close(self):
try:
if self.is_open:
self.click()
self.logger.debug('closed')
except NoSuchElementException:
if self.can_hide_on_select:
self.logger.info('While closing %r it disappeared, but ignoring.', self)
else:
raise
def select_by_visible_text(self, *items):
"""Selects items in the select.
Args:
*items: Items to be selected. If the select does not support multiple selections and you
pass more than one item, it will raise an exception. If you want to select using
partial match, use the :py:class:`BootstrapSelect.partial` to wrap the value.
"""
if len(items) > 1 and not self.is_multiple:
raise ValueError(
'The BootstrapSelect {} does not allow multiple selections'.format(self.locator))
self.open()
for item in items:
if isinstance(item, partial_match):
item = item.item
self.logger.info('selecting by partial visible text: %r', item)
try:
self.browser.click(
self.BY_PARTIAL_VISIBLE_TEXT.format(quote(item)), parent=self)
except NoSuchElementException:
try:
# Added this as for some views(some tags pages) dropdown is separated from
# button and doesn't have exact id or name
self.browser.click(
self.BY_PARTIAL_VISIBLE_TEXT.format(quote(item)))
except NoSuchElementException:
raise NoSuchElementException(
'Could not find {!r} in {!r} using partial match'.format(item, self))
else:
self.logger.info('selecting by visible text: %r', item)
try:
self.browser.click(self.BY_VISIBLE_TEXT.format(quote(item)), parent=self)
except NoSuchElementException:
try:
# Added this as for some views(some tags pages) dropdown is separated from
# button and doesn't have exact id or name
self.browser.click(self.BY_VISIBLE_TEXT.format(quote(item)))
except NoSuchElementException:
raise NoSuchElementException(
'Could not find {!r} in {!r}'.format(item, self))
self.close()
@property
def all_selected_options(self):
return [
self.browser.text(e)
for e in self.browser.elements(
'./div/ul/li[contains(@class, "selected")]/a/span[contains(@class, "text")]',
parent=self)]
@property
def all_options(self):
b = self.browser
return [
self.Option(
b.text(b.element('.//span[contains(@class, "text")]', parent=e)),
e.get_attribute("data-original-index")
)
for e in b.elements('./div/ul/li', parent=self)
]
@property
def selected_option(self):
return self.all_selected_options[0]
def read(self):
if self.is_multiple:
return self.all_selected_options
else:
return self.selected_option
def fill(self, items):
if not isinstance(items, (list, tuple, set)):
items = {items}
elif not isinstance(items, set):
items = set(items)
if set(self.all_selected_options) == items:
return False
else:
self.select_by_visible_text(*items)
return True
def __repr__(self):
return '{}(locator={!r})'.format(type(self).__name__, self.locator)
class BootstrapTreeview(Widget):
"""A class representing the Bootstrap treeview used in newer builds.
Implements ``expand_path``, ``click_path``, ``read_contents``. All are implemented in manner
very similar to the original :py:class:`Tree`.
You don't have to specify the ``tree_id`` if the hosting object implements ``tree_id``.
Args:
tree_id: Id of the tree, the closest div or ``miq-tree-view`` to the root ``ul`` element.
"""
ROOT = ParametrizedLocator('|'.join([
'.//miq-tree-view[@name={@tree_id|quote}]/div',
'.//div[@id={@tree_id|quote}]'
]))
ROOT_ITEM = './ul/li[1]'
ROOT_ITEMS = './ul/li[not(./span[contains(@class, "indent")])]'
ROOT_ITEMS_WITH_TEXT = (
'./ul/li[not(./span[contains(@class, "indent")]) and contains(normalize-space(.), {text})]')
SELECTED_ITEM = './ul/li[contains(@class, "node-selected")]'
CHILD_ITEMS = (
'./ul/li[starts-with(@data-nodeid, {id}) and not(@data-nodeid={id})'
' and count(./span[contains(@class, "indent")])={indent}]')
CHILD_ITEMS_TEXT = (
'./ul/li[starts-with(@data-nodeid, {id}) and not(@data-nodeid={id})'
' and (contains(@title, {text}) or contains(normalize-space(.), {text}))'
' and count(./span[contains(@class, "indent")])={indent}]')
ITEM_BY_NODEID = './ul/li[@data-nodeid={}]'
IS_EXPANDABLE = './span[contains(@class, "expand-icon")]'
IS_EXPANDED = './span[contains(@class, "expand-icon") and contains(@class, "fa-angle-down")]'
IS_LOADING = './span[contains(@class, "expand-icon") and contains(@class, "fa-spinner")]'
INDENT = './span[contains(@class, "indent")]'
def __init__(self, parent, tree_id=None, logger=None):
Widget.__init__(self, parent, logger=logger)
self._tree_id = tree_id
@property
def tree_id(self):
"""If you did not specify the tree_id when creating the tree, it will try to pull it out of
the parent object.
This is useful if some kinds of objects contain trees regularly, then the definition gets
simpler and the tree id is not neded to be specified.
"""
if self._tree_id is not None:
return self._tree_id
else:
try:
return self.parent.tree_id
except AttributeError:
raise NameError(
'You have to specify tree_id to BootstrapTreeview if the parent object does '
'not implement .tree_id!')
def image_getter(self, item):
"""Look up the image that is hidden in the style tag or as a tag.
Returns:
The name of the image without the hash, path and extension.
"""
try:
image_node = self.browser.element(
'./span[contains(@class, "node-image") or contains(@class, "node-icon")]',
parent=item)
except NoSuchElementException:
self.logger.warning('No image tag found')
return None
style = self.browser.get_attribute('style', image_node)
if style:
image_href = re.search(r'url\("([^"]+)"\)', style).groups()[0]
try:
return re.search(r'/([^/]+)-[0-9a-f]+\.(?:png|svg)$', image_href).groups()[0]
except AttributeError:
return None
else:
classes = self.browser.classes(image_node)
try:
return [c for c in classes if c.startswith(('fa-', 'product-', 'vendor-'))][0]
except IndexError:
return None
def read(self):
return self.currently_selected
def fill(self, value):
if self.currently_selected == value:
return False
self.click_path(*value)
return True
@property
def currently_selected(self):
if self.selected_item is not None:
nodeid = self.get_nodeid(self.selected_item).split('.')
root_id_len = len(self.get_nodeid(self.root_item).split('.'))
result = []
for end in range(root_id_len, len(nodeid) + 1):
current_nodeid = '.'.join(nodeid[:end])
text = self.browser.text(self.get_item_by_nodeid(current_nodeid))
result.append(text)
return result
else:
return None
@property
def root_item_count(self):
return len(self.browser.elements(self.ROOT_ITEMS, parent=self))