Skip to content

Commit

Permalink
Remove all dependencies on mechanize (now - really)
Browse files Browse the repository at this point in the history
  • Loading branch information
kedder committed Mar 15, 2013
1 parent 1e11ced commit a888231
Show file tree
Hide file tree
Showing 7 changed files with 225 additions and 159 deletions.
7 changes: 1 addition & 6 deletions src/zope/testbrowser/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,7 @@
PYTHON3 = sys.version_info[0] == 3
PYTHON2 = sys.version_info[0] == 2

try:
import mechanize
HAVE_MECHANIZE = True
except ImportError:
mechanize = None
HAVE_MECHANIZE = False
HAVE_MECHANIZE = False

if PYTHON2:
import Cookie as httpcookies
Expand Down
4 changes: 1 addition & 3 deletions src/zope/testbrowser/browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -741,8 +741,6 @@ def value(self, value):
def displayValue(self):
"""See zope.testbrowser.interfaces.IListControl"""
# not implemented for anything other than select;
# would be nice if mechanize implemented for checkbox and radio.
# attribute error for all others.

if self._control.value is None:
return []
Expand Down Expand Up @@ -1088,7 +1086,7 @@ def __init__(self, browser, form):
"""Initialize the Form
browser - a Browser instance
form - a mechanize.HTMLForm instance
form - a webtest.Form instance
"""
self.browser = browser
self._form = form
Expand Down
15 changes: 8 additions & 7 deletions src/zope/testbrowser/cookies.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@
import time
import urllib

from zope.testbrowser._compat import (mechanize, httpcookies, urlparse,
from zope.testbrowser._compat import (httpcookies, urlparse,
MutableMapping, urllib_request)
import pytz
import zope.interface
from zope.testbrowser import interfaces
from zope.testbrowser import interfaces, utils

# Cookies class helpers

class BrowserStateError(Exception): pass

class _StubHTTPMessage(object):
def __init__(self, cookies):
Expand Down Expand Up @@ -62,7 +63,7 @@ def setter(self, f):

@zope.interface.implementer(interfaces.ICookies)
class Cookies(MutableMapping):
"""Cookies for mechanize browser.
"""Cookies for testbrowser.
"""

def __init__(self, testapp, url=None, req_headers=None):
Expand Down Expand Up @@ -265,7 +266,7 @@ def _verifyDomain(self, domain, ck):
tmp_domain = domain
if domain is not None and domain.startswith('.'):
tmp_domain = domain[1:]
self_host = mechanize.effective_request_host(self._request)
self_host = utils.effective_request_host(self._request)
if (self_host != tmp_domain and
not self_host.endswith('.' + tmp_domain)):
raise ValueError('current url must match given domain')
Expand Down Expand Up @@ -306,7 +307,7 @@ def _setCookie(self, name, value, domain, expires, path, secure, comment,
request = self._request
if request is None:
# TODO: fix exception
raise mechanize.BrowserStateError(
raise BrowserStateError(
'cannot create cookie without request or domain')
c = httpcookies.SimpleCookie()
name = str(name)
Expand Down Expand Up @@ -337,7 +338,7 @@ def _setCookie(self, name, value, domain, expires, path, secure, comment,
policy = self._jar._policy
if now is None:
now = int(time.time())
policy._now = self._jar._now = now # TODO get mechanize to expose this
policy._now = self._jar._now = now
if not policy.set_ok(cookies[0], request):
raise ValueError('policy does not allow this cookie')
if ck is not None:
Expand All @@ -361,7 +362,7 @@ def _is_expired(self, value, now): # now = int(time.time())
return True
elif isinstance(value, basestring):
if datetime.datetime.fromtimestamp(
mechanize.str2time(value),
utils.http2time(value),
pytz.UTC) <= dnow:
return True
return False
Expand Down
1 change: 0 additions & 1 deletion src/zope/testbrowser/fixed-bugs.txt
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ Labeled Radio Buttons

The .getControl() method was sometimes unable to find radio buttons by label.

>>> # import mechanize._form; mechanize._form._show_debug_messages()
>>> browser.open('http://localhost/@@/testbrowser/radio.html')
>>> browser.getControl('One').optionValue
'1'
Expand Down
4 changes: 2 additions & 2 deletions src/zope/testbrowser/interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,14 +310,14 @@ class IListControl(IControl):
required=True)

displayOptions = zope.schema.List(
# TODO: currently only implemented for select by mechanize
# TODO: currently only implemented for select
title=u"Options",
description=u"""\
A list of possible display values for the control.""",
required=True)

displayValue = zope.schema.Field(
# TODO: currently only implemented for select by mechanize
# TODO: currently only implemented for select
title=u"Value",
description=u"The value of the control, as rendered by the display",
default=None,
Expand Down
142 changes: 2 additions & 140 deletions src/zope/testbrowser/tests/test_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,150 +14,12 @@
"""Real test for file-upload and beginning of a better internal test framework
"""
from __future__ import print_function

import io
import doctest
import mechanize
import socket
import sys

from zope.testbrowser.browser import Browser
import zope.testbrowser.tests.helper
from zope.testbrowser._compat import httpclient


## def set_next_response(body, headers=None, status='200', reason='OK'):
## global next_response_body
## global next_response_headers
## global next_response_status
## global next_response_reason
## if headers is None:
## headers = (
## 'Content-Type: text/html\r\n'
## 'Content-Length: %s\r\n'
## % len(body))
## next_response_body = body
## next_response_headers = headers
## next_response_status = status
## next_response_reason = reason


## class FauxConnection(object):
## """A ``mechanize`` compatible connection object."""
##
## def __init__(self, host, timeout=None):
## pass
##
## def set_debuglevel(self, level):
## pass
##
## def _quote(self, url):
## # the publisher expects to be able to split on whitespace, so we have
## # to make sure there is none in the URL
## return url.replace(' ', '%20')
##
## def request(self, method, url, body=None, headers=None):
## if body is None:
## body = ''
##
## if url == '':
## url = '/'
##
## url = self._quote(url)
##
## # Construct the headers.
## header_chunks = []
## if headers is not None:
## for header in headers.items():
## header_chunks.append('%s: %s' % header)
## headers = '\n'.join(header_chunks) + '\n'
## else:
## headers = ''
##
## # Construct the full HTTP request string, since that is what the
## # ``HTTPCaller`` wants.
## request_string = (method + ' ' + url + ' HTTP/1.1\n'
## + headers + '\n' + body)
##
## print(request_string.replace('\r', ''))
##
## def getresponse(self):
## """Return a ``mechanize`` compatible response.
##
## The goal of this method is to convert the Zope Publisher's response to
## a ``mechanize`` compatible response, which is also understood by
## mechanize.
## """
## return FauxResponse(next_response_body,
## next_response_headers,
## next_response_status,
## next_response_reason,
## )
##
##
## class FauxResponse(object):
##
## def __init__(self, content, headers, status, reason):
## self.content = content
## self.status = status
## self.reason = reason
## self.msg = httpclient.HTTPMessage(io.BytesIO(headers), 0)
## self.content_as_file = io.BytesIO(self.content)
##
## def read(self, amt=None):
## return self.content_as_file.read(amt)
##
## def close(self):
## """To overcome changes in mechanize and socket in python2.5"""
## pass
##
##
## class FauxHTTPHandler(mechanize.HTTPHandler):
##
## http_request = mechanize.HTTPHandler.do_request_
##
## def http_open(self, req):
## """Open an HTTP connection having a ``mechanize`` request."""
## # Here we connect to the publisher.
##
## if sys.version_info > (2, 6) and not hasattr(req, 'timeout'):
## # Workaround mechanize incompatibility with Python
## # 2.6. See: LP #280334
## req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
## return self.do_open(FauxConnection, req)
##
##
## class FauxMechanizeBrowser(mechanize.Browser):
##
## handler_classes = {
## # scheme handlers
## "http": FauxHTTPHandler,
##
## "_http_error": mechanize.HTTPErrorProcessor,
## "_http_default_error": mechanize.HTTPDefaultErrorHandler,
##
## # feature handlers
## "_authen": mechanize.HTTPBasicAuthHandler,
## "_redirect": mechanize.HTTPRedirectHandler,
## "_cookies": mechanize.HTTPCookieProcessor,
## "_refresh": mechanize.HTTPRefreshProcessor,
## "_referer": mechanize.Browser.handler_classes['_referer'],
## "_equiv": mechanize.HTTPEquivProcessor,
## }
##
## default_schemes = ["http"]
## default_others = ["_http_error", "_http_default_error"]
## default_features = ["_authen", "_redirect", "_cookies"]
##

## class Browser(TestBrowser):
##
## def __init__(self, url=None):
## mech_browser = FauxMechanizeBrowser()
## super(Browser, self).__init__(url=url, mech_browser=mech_browser)
##
## def open(self, body, headers=None, status=200, reason='OK',
## url='http://localhost/'):
## set_next_response(body, headers, status, reason)
## TestBrowser.open(self, url)

class TestApp(object):
next_response_body = None
Expand Down
Loading

0 comments on commit a888231

Please sign in to comment.