-
Notifications
You must be signed in to change notification settings - Fork 16
/
browser.py
1482 lines (1187 loc) · 47.5 KB
/
browser.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
##############################################################################
#
# Copyright (c) 2005 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Webtest-based Functional Doctest interfaces
"""
import sys
import re
import time
import io
from contextlib import contextmanager
from six.moves import urllib_robotparser
from six import string_types
from zope.interface import implementer
from zope.cachedescriptors.property import Lazy
from wsgiproxy.proxies import TransparentProxy
from bs4 import BeautifulSoup
from soupsieve import escape as css_escape
from zope.testbrowser import interfaces
from zope.testbrowser._compat import httpclient, PYTHON2
from zope.testbrowser._compat import urllib_request, urlparse
import zope.testbrowser.cookies
import webtest
__docformat__ = "reStructuredText"
HTTPError = urllib_request.HTTPError
RegexType = type(re.compile(''))
_compress_re = re.compile(r"\s+")
class HostNotAllowed(Exception):
pass
class RobotExclusionError(HTTPError):
def __init__(self, *args):
super(RobotExclusionError, self).__init__(*args)
# RFC 2606
_allowed_2nd_level = set(['example.com', 'example.net', 'example.org'])
_allowed = set(['localhost', '127.0.0.1'])
_allowed.update(_allowed_2nd_level)
REDIRECTS = (301, 302, 303, 307)
class TestbrowserApp(webtest.TestApp):
_last_fragment = ""
restricted = False
def _assertAllowed(self, url):
parsed = urlparse.urlparse(url)
if self.restricted:
# We are in restricted mode, check host part only
host = parsed.netloc.partition(':')[0]
if host in _allowed:
return
for dom in _allowed_2nd_level:
if host.endswith('.%s' % dom):
return
raise HostNotAllowed(url)
else:
# Unrestricted mode: retrieve robots.txt and check against it
robotsurl = urlparse.urlunsplit((parsed.scheme, parsed.netloc,
'/robots.txt', '', ''))
rp = urllib_robotparser.RobotFileParser()
rp.set_url(robotsurl)
rp.read()
if not rp.can_fetch("*", url):
msg = "request disallowed by robots.txt"
raise RobotExclusionError(url, 403, msg, [], None)
def do_request(self, req, status, expect_errors):
self._assertAllowed(req.url)
response = super(TestbrowserApp, self).do_request(req, status,
expect_errors)
# Store _last_fragment in response to preserve fragment for history
# (goBack() will not lose fragment).
response._last_fragment = self._last_fragment
return response
def _remove_fragment(self, url):
# HACK: we need to preserve fragment part of url, but webtest strips it
# from url on every request. So we override this protected method,
# assuming it is called on every request and therefore _last_fragment
# will not get outdated. ``getRequestUrlWithFragment()`` will
# reconstruct url with fragment for the last request.
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
self._last_fragment = fragment
return super(TestbrowserApp, self)._remove_fragment(url)
def getRequestUrlWithFragment(self, response):
url = response.request.url
if not self._last_fragment:
return url
return "%s#%s" % (url, response._last_fragment)
class SetattrErrorsMixin(object):
_enable_setattr_errors = False
def __setattr__(self, name, value):
if self._enable_setattr_errors:
# cause an attribute error if the attribute doesn't already exist
getattr(self, name)
# set the value
object.__setattr__(self, name, value)
@implementer(interfaces.IBrowser)
class Browser(SetattrErrorsMixin):
"""A web user agent."""
_contents = None
_controls = None
_counter = 0
_response = None
_req_headers = None
_req_content_type = None
_history = None
__html = None
def __init__(self, url=None, wsgi_app=None):
self.timer = Timer()
self.raiseHttpErrors = True
self.handleErrors = True
if wsgi_app is None:
self.testapp = TestbrowserApp(TransparentProxy())
else:
self.testapp = TestbrowserApp(wsgi_app)
self.testapp.restricted = True
self._req_headers = {}
self._history = History()
self._enable_setattr_errors = True
self._controls = {}
if url is not None:
self.open(url)
@property
def url(self):
"""See zope.testbrowser.interfaces.IBrowser"""
if self._response is None:
return None
return self.testapp.getRequestUrlWithFragment(self._response)
@property
def isHtml(self):
"""See zope.testbrowser.interfaces.IBrowser"""
return self._response and 'html' in self._response.content_type
@property
def lastRequestSeconds(self):
"""See zope.testbrowser.interfaces.IBrowser"""
return self.timer.elapsedSeconds
@property
def title(self):
"""See zope.testbrowser.interfaces.IBrowser"""
if not self.isHtml:
raise BrowserStateError('not viewing HTML')
titles = self._html.find_all('title')
if not titles:
return None
return self.toStr(titles[0].text)
def reload(self):
"""See zope.testbrowser.interfaces.IBrowser"""
if self._response is None:
raise BrowserStateError("no URL has yet been .open()ed")
req = self._response.request
with self._preparedRequest(self.url):
resp = self.testapp.request(req)
self._setResponse(resp)
def goBack(self, count=1):
"""See zope.testbrowser.interfaces.IBrowser"""
resp = self._history.back(count, self._response)
self._setResponse(resp)
@property
def contents(self):
"""See zope.testbrowser.interfaces.IBrowser"""
if self._response is not None:
return self.toStr(self._response.body)
else:
return None
@property
def headers(self):
"""See zope.testbrowser.interfaces.IBrowser"""
resptxt = []
resptxt.append('Status: %s' % self._response.status)
for h, v in sorted(self._response.headers.items()):
resptxt.append(str("%s: %s" % (h, v)))
inp = '\n'.join(resptxt)
stream = io.BytesIO(inp.encode('latin1'))
if PYTHON2:
return httpclient.HTTPMessage(stream)
else:
return httpclient.parse_headers(stream)
@property
def cookies(self):
if self.url is None:
raise RuntimeError("no request found")
return zope.testbrowser.cookies.Cookies(self.testapp, self.url,
self._req_headers)
def addHeader(self, key, value):
"""See zope.testbrowser.interfaces.IBrowser"""
if (self.url and key.lower() in ('cookie', 'cookie2') and
self.cookies.header):
raise ValueError('cookies are already set in `cookies` attribute')
self._req_headers[key] = value
def open(self, url, data=None):
"""See zope.testbrowser.interfaces.IBrowser"""
url = self._absoluteUrl(url)
if data is not None:
def make_request(args):
return self.testapp.post(url, data, **args)
else:
def make_request(args):
return self.testapp.get(url, **args)
self._processRequest(url, make_request)
def post(self, url, data, content_type=None):
if content_type is not None:
self._req_content_type = content_type
return self.open(url, data)
def _clickSubmit(self, form, control=None, coord=None):
# find index of given control in the form
url = self._absoluteUrl(form.action)
if control:
def make_request(args):
index = form.fields[control.name].index(control)
return self._submit(
form, control.name, index, coord=coord, **args)
else:
def make_request(args):
return self._submit(form, coord=coord, **args)
self._processRequest(url, make_request)
def _processRequest(self, url, make_request):
with self._preparedRequest(url) as reqargs:
self._history.add(self._response)
resp = make_request(reqargs)
remaining_redirects = 100 # infinite loops protection
while resp.status_int in REDIRECTS and remaining_redirects:
remaining_redirects -= 1
url = urlparse.urljoin(url, resp.headers['location'])
with self._preparedRequest(url) as reqargs:
resp = self.testapp.get(url, **reqargs)
assert remaining_redirects > 0, "redirects chain looks infinite"
self._setResponse(resp)
self._checkStatus()
def _checkStatus(self):
# if the headers don't have a status, I suppose there can't be an error
if 'Status' in self.headers:
code, msg = self.headers['Status'].split(' ', 1)
code = int(code)
if self.raiseHttpErrors and code >= 400:
raise HTTPError(self.url, code, msg, [], None)
def _submit(self, form, name=None, index=None, coord=None, **args):
# A reimplementation of webtest.forms.Form.submit() to allow to insert
# coords into the request
fields = form.submit_fields(name, index=index)
if coord is not None:
fields.extend([('%s.x' % name, coord[0]),
('%s.y' % name, coord[1])])
url = self._absoluteUrl(form.action)
if form.method.upper() != "GET":
args.setdefault("content_type", form.enctype)
else:
parsed = urlparse.urlparse(url)._replace(query='', fragment='')
url = urlparse.urlunparse(parsed)
return form.response.goto(url, method=form.method,
params=fields, **args)
def _setResponse(self, response):
self._response = response
def getLink(self, text=None, url=None, id=None, index=0):
"""See zope.testbrowser.interfaces.IBrowser"""
qa = 'a' if id is None else 'a#%s' % css_escape(id)
qarea = 'area' if id is None else 'area#%s' % css_escape(id)
html = self._html
links = html.select(qa)
links.extend(html.select(qarea))
matching = []
for elem in links:
matches = (isMatching(elem.text, text) and
isMatching(elem.get('href', ''), url))
if matches:
matching.append(elem)
if index >= len(matching):
raise LinkNotFoundError()
elem = matching[index]
baseurl = self._getBaseUrl()
return Link(elem, self, baseurl)
def follow(self, *args, **kw):
"""Select a link and follow it."""
self.getLink(*args, **kw).click()
def _getBaseUrl(self):
# Look for <base href> tag and use it as base, if it exists
url = self._response.request.url
if b"<base" not in self._response.body:
return url
# we suspect there is a base tag in body, try to find href there
html = self._html
if not html.head:
return url
base = html.head.base
if not base:
return url
return base['href'] or url
def getForm(self, id=None, name=None, action=None, index=None):
"""See zope.testbrowser.interfaces.IBrowser"""
zeroOrOne([id, name, action], '"id", "name", and "action"')
matching_forms = []
allforms = self._getAllResponseForms()
for form in allforms:
if ((id is not None and form.id == id) or
(name is not None and form.html.form.get('name') == name) or
(action is not None and re.search(action, form.action)) or
id == name == action is None):
matching_forms.append(form)
if index is None and not any([id, name, action]):
if len(matching_forms) == 1:
index = 0
else:
raise ValueError(
'if no other arguments are given, index is required.')
form = disambiguate(matching_forms, '', index)
return Form(self, form)
def getControl(self, label=None, name=None, index=None):
"""See zope.testbrowser.interfaces.IBrowser"""
intermediate, msg, available = self._getAllControls(
label, name, self._getAllResponseForms(),
include_subcontrols=True)
control = disambiguate(intermediate, msg, index,
controlFormTupleRepr,
available)
return control
def _getAllResponseForms(self):
""" Return set of response forms in the order they appear in
``self._response.form``."""
respforms = self._response.forms
idxkeys = [k for k in respforms.keys() if isinstance(k, int)]
return [respforms[k] for k in sorted(idxkeys)]
def _getAllControls(self, label, name, forms, include_subcontrols=False):
onlyOne([label, name], '"label" and "name"')
# might be an iterator, and we need to iterate twice
forms = list(forms)
available = None
if label is not None:
res = self._findByLabel(label, forms, include_subcontrols)
msg = 'label %r' % label
elif name is not None:
include_subcontrols = False
res = self._findByName(name, forms)
msg = 'name %r' % name
if not res:
available = list(self._findAllControls(forms, include_subcontrols))
return res, msg, available
def _findByLabel(self, label, forms, include_subcontrols=False):
# forms are iterable of mech_forms
matches = re.compile(r'(^|\b|\W)%s(\b|\W|$)'
% re.escape(normalizeWhitespace(label))).search
found = []
for wtcontrol in self._findAllControls(forms, include_subcontrols):
control = getattr(wtcontrol, 'control', wtcontrol)
if control.type == 'hidden':
continue
for l in wtcontrol.labels:
if matches(l):
found.append(wtcontrol)
break
return found
def _indexControls(self, form):
# Unfortunately, webtest will remove all 'name' attributes from
# form.html after parsing. But we need them (at least to locate labels
# for radio buttons). So we are forced to reparse part of html, to
# extract elements.
html = BeautifulSoup(form.text, 'html.parser')
tags = ('input', 'select', 'textarea', 'button')
return html.find_all(tags)
def _findByName(self, name, forms):
return [c for c in self._findAllControls(forms) if c.name == name]
def _findAllControls(self, forms, include_subcontrols=False):
res = []
for f in forms:
if f not in self._controls:
fc = []
allelems = self._indexControls(f)
already_processed = set()
for cname, wtcontrol in f.field_order:
# we need to group checkboxes by name, but leave
# the other controls in the original order,
# even if the name repeats
if isinstance(wtcontrol, webtest.forms.Checkbox):
if cname in already_processed:
continue
already_processed.add(cname)
wtcontrols = f.fields[cname]
else:
wtcontrols = [wtcontrol]
for c in controlFactory(cname, wtcontrols, allelems, self):
fc.append((c, False))
for subcontrol in c.controls:
fc.append((subcontrol, True))
self._controls[f] = fc
controls = [c for c, subcontrol in self._controls[f]
if not subcontrol or include_subcontrols]
res.extend(controls)
return res
def _changed(self):
self._counter += 1
self._contents = None
self._controls = {}
self.__html = None
self._req_content_type = None
@contextmanager
def _preparedRequest(self, url):
self.timer.start()
headers = {}
if self.url:
headers['Referer'] = self.url
if self._req_content_type:
headers['Content-Type'] = self._req_content_type
headers['Connection'] = 'close'
headers['Host'] = urlparse.urlparse(url).netloc
headers['User-Agent'] = 'Python-urllib/2.4'
headers.update(self._req_headers)
extra_environ = {}
if self.handleErrors:
extra_environ['paste.throw_errors'] = None
headers['X-zope-handle-errors'] = 'True'
else:
extra_environ['wsgi.handleErrors'] = False
extra_environ['paste.throw_errors'] = True
extra_environ['x-wsgiorg.throw_errors'] = True
headers.pop('X-zope-handle-errors', None)
kwargs = {'headers': sorted(headers.items()),
'extra_environ': extra_environ,
'expect_errors': True}
yield kwargs
self._changed()
self.timer.stop()
def _absoluteUrl(self, url):
absolute = url.startswith('http://') or url.startswith('https://')
if absolute:
return str(url)
if self._response is None:
raise BrowserStateError(
"can't fetch relative reference: not viewing any document")
return str(urlparse.urljoin(self._getBaseUrl(), url))
def toStr(self, s):
"""Convert possibly unicode object to native string using response
charset"""
if not self._response.charset:
return s
if s is None:
return None
# Might be an iterable, especially the 'class' attribute.
if isinstance(s, (list, tuple)):
subs = [self.toStr(sub) for sub in s]
if isinstance(s, tuple):
return tuple(subs)
return subs
if PYTHON2 and not isinstance(s, bytes):
return s.encode(self._response.charset)
if not PYTHON2 and isinstance(s, bytes):
return s.decode(self._response.charset)
return s
@property
def _html(self):
if self.__html is None:
self.__html = self._response.html
return self.__html
def controlFactory(name, wtcontrols, elemindex, browser):
assert len(wtcontrols) > 0
first_wtc = wtcontrols[0]
checkbox = isinstance(first_wtc, webtest.forms.Checkbox)
# Create control list
if checkbox:
ctrlelems = [(wtc, elemindex[wtc.pos]) for wtc in wtcontrols]
controls = [CheckboxListControl(name, ctrlelems, browser)]
else:
controls = []
for wtc in wtcontrols:
controls.append(simpleControlFactory(
wtc, wtc.form, elemindex, browser))
return controls
def simpleControlFactory(wtcontrol, form, elemindex, browser):
if isinstance(wtcontrol, webtest.forms.Radio):
elems = [e for e in elemindex
if e.attrs.get('name') == wtcontrol.name]
return RadioListControl(wtcontrol, form, elems, browser)
elem = elemindex[wtcontrol.pos]
if isinstance(wtcontrol, (webtest.forms.Select,
webtest.forms.MultipleSelect)):
return ListControl(wtcontrol, form, elem, browser)
elif isinstance(wtcontrol, webtest.forms.Submit):
if wtcontrol.attrs.get('type', 'submit') == 'image':
return ImageControl(wtcontrol, form, elem, browser)
else:
return SubmitControl(wtcontrol, form, elem, browser)
else:
return Control(wtcontrol, form, elem, browser)
@implementer(interfaces.ILink)
class Link(SetattrErrorsMixin):
def __init__(self, link, browser, baseurl=""):
self._link = link
self.browser = browser
self._baseurl = baseurl
self._browser_counter = self.browser._counter
self._enable_setattr_errors = True
def click(self):
if self._browser_counter != self.browser._counter:
raise interfaces.ExpiredError
self.browser.open(self.url)
@property
def url(self):
relurl = self._link['href']
return self.browser._absoluteUrl(relurl)
@property
def text(self):
txt = normalizeWhitespace(self._link.text)
return self.browser.toStr(txt)
@property
def tag(self):
return str(self._link.name)
@property
def attrs(self):
toStr = self.browser.toStr
return dict((toStr(k), toStr(v)) for k, v in self._link.attrs.items())
def __repr__(self):
return "<%s text='%s' url='%s'>" % (
self.__class__.__name__, normalizeWhitespace(self.text), self.url)
def controlFormTupleRepr(wtcontrol):
return wtcontrol.mechRepr()
@implementer(interfaces.IControl)
class Control(SetattrErrorsMixin):
_enable_setattr_errors = False
def __init__(self, control, form, elem, browser):
self._control = control
self._form = form
self._elem = elem
self.browser = browser
self._browser_counter = self.browser._counter
# disable addition of further attributes
self._enable_setattr_errors = True
@property
def disabled(self):
return 'disabled' in self._control.attrs
@property
def readonly(self):
return 'readonly' in self._control.attrs
@property
def type(self):
typeattr = self._control.attrs.get('type', None)
if typeattr is None:
# try to figure out type by tag
if self._control.tag == 'textarea':
return 'textarea'
else:
# By default, inputs are of 'text' type
return 'text'
return self.browser.toStr(typeattr)
@property
def name(self):
if self._control.name is None:
return None
return self.browser.toStr(self._control.name)
@property
def multiple(self):
return 'multiple' in self._control.attrs
@property
def value(self):
if self.type == 'file':
if not self._control.value:
return None
if self.type == 'image':
if not self._control.value:
return ''
if isinstance(self._control, webtest.forms.Submit):
return self.browser.toStr(self._control.value_if_submitted())
val = self._control.value
if val is None:
return None
return self.browser.toStr(val)
@value.setter
def value(self, value):
if self._browser_counter != self.browser._counter:
raise interfaces.ExpiredError
if self.readonly:
raise AttributeError("Trying to set value of readonly control")
if self.type == 'file':
self.add_file(value, content_type=None, filename=None)
else:
self._control.value = value
def add_file(self, file, content_type, filename):
if self.type != 'file':
raise TypeError("Can't call add_file on %s controls"
% self.mech_control.type)
if hasattr(file, 'read'):
contents = file.read()
else:
contents = file
self._form[self.name] = webtest.forms.Upload(filename or '', contents,
content_type)
def clear(self):
if self._browser_counter != self.browser._counter:
raise zope.testbrowser.interfaces.ExpiredError
self.value = None
def __repr__(self):
return "<%s name='%s' type='%s'>" % (
self.__class__.__name__, self.name, self.type)
@Lazy
def labels(self):
return [self.browser.toStr(l)
for l in getControlLabels(self._elem, self._form.html)]
@property
def controls(self):
return []
def mechRepr(self):
# emulate mechanize control representation
toStr = self.browser.toStr
ctrl = self._control
if isinstance(ctrl, (webtest.forms.Text, webtest.forms.Email)):
tp = ctrl.attrs.get('type')
infos = []
if 'readonly' in ctrl.attrs or tp == 'hidden':
infos.append('readonly')
if 'disabled' in ctrl.attrs:
infos.append('disabled')
classnames = {'password': "PasswordControl",
'hidden': "HiddenControl",
'email': "EMailControl",
}
clname = classnames.get(tp, "TextControl")
return "<%s(%s=%s)%s>" % (
clname, toStr(ctrl.name), toStr(ctrl.value),
' (%s)' % (', '.join(infos)) if infos else '')
if isinstance(ctrl, webtest.forms.File):
return repr(ctrl) + "<-- unknown"
raise NotImplementedError(str((self, ctrl)))
@implementer(interfaces.ISubmitControl)
class SubmitControl(Control):
def click(self):
if self._browser_counter != self.browser._counter:
raise interfaces.ExpiredError
self.browser._clickSubmit(self._form, self._control)
@Lazy
def labels(self):
labels = super(SubmitControl, self).labels
labels.append(self._control.value_if_submitted())
if self._elem.text:
labels.append(normalizeWhitespace(self._elem.text))
return [l for l in labels if l]
def mechRepr(self):
name = self.name if self.name is not None else "<None>"
value = self.value if self.value is not None else "<None>"
extra = ' (disabled)' if self.disabled else ''
# Mechanize explicitly told us submit controls were readonly, as
# if they could be any other way.... *sigh* Let's take this
# opportunity and strip that off.
return "<SubmitControl(%s=%s)%s>" % (name, value, extra)
@implementer(interfaces.IListControl)
class ListControl(Control):
def __init__(self, control, form, elem, browser):
super(ListControl, self).__init__(control, form, elem, browser)
# HACK: set default value of a list control and then forget about
# initial default values. Otherwise webtest will not allow to set None
# as a value of select and radio controls.
v = control.value
if v:
control.value = v
# Uncheck all the options Carefully: WebTest used to have
# 2-tuples here before commit 1031d82e, and 3-tuples since then.
control.options = [option[:1] + (False,) + option[2:]
for option in control.options]
@property
def type(self):
return 'select'
@property
def value(self):
val = self._control.value
if val is None:
return []
if self.multiple and isinstance(val, (list, tuple)):
return [self.browser.toStr(v) for v in val]
else:
return [self.browser.toStr(val)]
@value.setter
def value(self, value):
if not value:
self._set_falsy_value(value)
else:
if not self.multiple and isinstance(value, (list, tuple)):
value = value[0]
self._control.value = value
@property
def _selectedIndex(self):
return self._control.selectedIndex
@_selectedIndex.setter
def _selectedIndex(self, index):
self._control.force_value(webtest.forms.NoValue)
self._control.selectedIndex = index
def _set_falsy_value(self, value):
self._control.force_value(value)
@property
def displayValue(self):
"""See zope.testbrowser.interfaces.IListControl"""
# not implemented for anything other than select;
cvalue = self._control.value
if cvalue is None:
return []
if not isinstance(cvalue, list):
cvalue = [cvalue]
alltitles = []
for key, titles in self._getOptions():
if key in cvalue:
alltitles.append(titles[0])
return alltitles
@displayValue.setter
def displayValue(self, value):
if self._browser_counter != self.browser._counter:
raise interfaces.ExpiredError
if isinstance(value, string_types):
value = [value]
values = []
for key, titles in self._getOptions():
if any(v in t
for t in titles
for v in value):
values.append(key)
self.value = values
@property
def displayOptions(self):
"""See zope.testbrowser.interfaces.IListControl"""
return [titles[0] for key, titles in self._getOptions()]
@property
def options(self):
"""See zope.testbrowser.interfaces.IListControl"""
return [key for key, title in self._getOptions()]
def getControl(self, label=None, value=None, index=None):
if self._browser_counter != self.browser._counter:
raise interfaces.ExpiredError
return getControl(self.controls, label, value, index)
@property
def controls(self):
if self._browser_counter != self.browser._counter:
raise interfaces.ExpiredError
ctrls = []
for idx, elem in enumerate(self._elem.select('option')):
ctrls.append(ItemControl(self, elem, self._form, self.browser,
idx))
return ctrls
def _getOptions(self):
return [(c.optionValue, c.labels) for c in self.controls]
def mechRepr(self):
# TODO: figure out what is replacement for "[*, ambiguous])"
return "<SelectControl(%s=[*, ambiguous])>" % self.name
@implementer(interfaces.IListControl)
class RadioListControl(ListControl):
_elems = None
def __init__(self, control, form, elems, browser):
super(RadioListControl, self).__init__(
control, form, elems[0], browser)
self._elems = elems
@property
def type(self):
return 'radio'
def __repr__(self):
# Return backwards compatible representation
return "<ListControl name='%s' type='radio'>" % self.name
@property
def controls(self):
if self._browser_counter != self.browser._counter:
raise interfaces.ExpiredError
for idx, opt in enumerate(self._elems):
yield RadioItemControl(self, opt, self._form, self.browser, idx)
@Lazy
def labels(self):
# Parent radio button control has no labels. Children are labeled.
return []
def _set_falsy_value(self, value):
# HACK: Force unsetting selected value, by avoiding validity check.
# Note, that force_value will not work for webtest.forms.Radio
# controls.
self._control.selectedIndex = None
@implementer(interfaces.IListControl)
class CheckboxListControl(SetattrErrorsMixin):
def __init__(self, name, ctrlelems, browser):
self.name = name
self.browser = browser
self._browser_counter = self.browser._counter
self._ctrlelems = ctrlelems
self._enable_setattr_errors = True
@property
def options(self):
opts = [self._trValue(c.optionValue) for c in self.controls]
return opts
@property
def displayOptions(self):
return [c.labels[0] for c in self.controls]
@property
def value(self):
ctrls = self.controls
val = [self._trValue(c.optionValue) for c in ctrls if c.selected]
if len(self._ctrlelems) == 1 and val == [True]:
return True
return val
@value.setter
def value(self, value):
ctrls = self.controls
if isinstance(value, (list, tuple)):
for c in ctrls:
c.selected = c.optionValue in value
else:
ctrls[0].selected = value
@property
def displayValue(self):
return [c.labels[0] for c in self.controls if c.selected]
@displayValue.setter
def displayValue(self, value):
for c in self.controls:
c.selected = any(v in c.labels for v in value)
@property
def multiple(self):
return True
@property