def begin(self): from django.conf import settings from django.core.handlers.wsgi import WSGIHandler from django.test.simple import TEST_MODULE from tddspry.django.settings import IP, PORT from twill import add_wsgi_intercept log.debug('DjangoPlugin start') # Find to Django models in tests modules for each of ``INSTALLED_APPS`` for label in settings.INSTALLED_APPS: tests = label + '.' + TEST_MODULE try: self.load_tests(tests) except (AttributeError, ImportError): pass # Setup Django test environment and test database self.setup_django() # Setup Twill for testing with Django try: from django.contrib.staticfiles.handlers import StaticFilesHandler if 'django.contrib.staticfiles' in settings.INSTALLED_APPS: app = StaticFilesHandler(WSGIHandler()) else: app = WSGIHandler() except ImportError: # django < 1.5 from django.core.servers.basehttp import AdminMediaHandler app = AdminMediaHandler(WSGIHandler()) add_wsgi_intercept(IP, PORT, lambda: app)
def run_server_wsgi_intercept(dbfilename): host = 'localhost' port = 80 from pony_build import server, coordinator, dbsqlite from pony_build.web import create_publisher, urls dbfile = dbsqlite.open_shelf(dbfilename) dbfile = coordinator.IntDictWrapper(dbfile) ### pbs_app = coordinator.PonyBuildCoordinator(db=dbfile) wsgi_app = create_publisher(pbs_app) #the_server = server.create(host, port, pbs_app, wsgi_app) url = urls.calculate_base_url(host, port) urls.set_base_url(url) twill.add_wsgi_intercept('localhost', port, lambda: wsgi_app) global _server_url, _server_host, _server_port _server_host = host _server_port = port _server_url = 'http://%s:%d/' % (host, port)
def test_not_found(): """The "not found" handler return a 404.""" twill.add_wsgi_intercept('not-found-host', 80, lambda: not_found) browser = twill.get_browser() browser.go('http://not-found-host/') assert browser.result.page.startswith("404 Not Found") assert browser.result.http_code == 404
def test_refeed(self): """ Try refeeding the content into the app. """ recorder = scotch.recorder.Recorder(simple_app.iter_app) # first, record. twill.add_wsgi_intercept('localhost', 80, lambda: recorder) try: twill.commands.go('http://localhost:80/') output1 = twill.commands.show() assert simple_app.success() finally: simple_app.reset() twill.remove_wsgi_intercept('localhost', 80) # get the recorded bit. assert len(recorder.record_holder) == 1 record = recorder.record_holder[0] try: response = record.refeed(simple_app.iter_app) assert simple_app.success() output2 = response.get_output() assert output1 == output2 finally: simple_app.reset()
def test_multirefeed(self): """ Test playback of multiple requests. """ recorder = scotch.recorder.Recorder(simple_app.post_app) # first, record. twill.add_wsgi_intercept('localhost', 80, lambda: recorder) try: twill.commands.go('http://localhost:80/') assert simple_app.success() simple_app.reset() twill.commands.fv('1', 'test', 'howdy world') twill.commands.submit() twill.commands.find("VALUE WAS: howdy world") assert simple_app.success() finally: simple_app.reset() twill.remove_wsgi_intercept('localhost', 80) # check the length of the recorded bit. assert len(recorder.record_holder) == 2 # play it all back. try: assert not simple_app.success() for record in recorder.record_holder: record.refeed(simple_app.post_app) assert simple_app.success() finally: simple_app.reset()
def test_middleware_composer(): """Middleware stack should alter return in order..""" def make_middleware(txt): def middleware(app): def wrappedapp(environ, start_response): res = app(environ, start_response) res.append(txt) return res return wrappedapp return middleware # Environ predicates t = lambda x: True f = lambda x: False rules = [(t, make_middleware('a')), (f, make_middleware('b')), (t, make_middleware('c')), (f, make_middleware('d')), (t, make_middleware('e'))] def app(environ, start_response): start_response("200 OK", [('Content-type', 'text/plain')]) return ["ok "] composed = selector.MiddlewareComposer(app, rules) twill.add_wsgi_intercept('simple-host', 80, lambda: composed) browser = twill.get_browser() browser.go('http://simple-host/endpoint') assert browser.result.page.startswith("ok eca") assert browser.result.http_code == 200
def setUp(self): '''Create the app''' test_path = os.path.abspath(os.path.dirname(__file__)) testpath_command = "setglobal test_path " + test_path twill.execute_string(testpath_command) fixtures = os.path.join(test_path, 'fixtures') for to_delete in [fname for fname in os.listdir(fixtures) if fname.startswith('Data.fs') or fname in ['blobs']]: _rm(os.path.join(fixtures, to_delete)) os.mkdir(os.path.join(fixtures, 'blobs')) wsgi_app = get_app(os.path.join(test_path, 'fixtures', 'karl.ini'), 'main') def build_app(): return wsgi_app twill.add_wsgi_intercept('localhost', 6543, build_app) # XXX How do we suppress the annoying "AT LINE: " output? twill.set_output(open('/dev/null', 'wb')) twill.execute_string("extend_with karl.twillcommands") # mostly the same as karl3.conf without extending with flunc # and few other adjustments. twill.execute_string("runfile '" + os.path.abspath(os.path.dirname(__file__)) + "/test_twill_wsgi_karl3.conf'")
def __enter__(self): twill.set_output(StringIO.StringIO()) twill.commands.clear_cookies() twill.add_wsgi_intercept(self.host, self.port, lambda: self.app) return self
def _pre_setup(self): super(TwillTestCase, self)._pre_setup() twill.set_output(StringIO.StringIO()) twill.commands.clear_cookies() twill.add_wsgi_intercept(self.twill_host, self.twill_port, lambda: self.app) self.browser = twill.get_browser()
def install_twill(self): wsgi_app = self.wsgi_request # TODO: we should run all requests through the validator. For now it's # disabled because it mysteriously breaks some tests. #if wsgiref: # wsgi_app = wsgiref.validate.validator(wsgi_app) twill.add_wsgi_intercept('localhost', 80, lambda: wsgi_app) self.browser = twill.browser.TwillBrowser() self.divert_twill_output()
def setup(self): """ setup twill virtual web server and fill db with test data """ sys.path.insert(0, test_settings.PROJECT_DIR) app = AdminMediaHandler(WSGIHandler()) add_wsgi_intercept(IP, PORT, lambda: app) try: call_command('syncdb', verbosity=0, interactive=False) except SystemExit: pass
def setup(self): ''' - setup twill virtual web server ''' from django.core.servers.basehttp import AdminMediaHandler from django.core.handlers.wsgi import WSGIHandler app = AdminMediaHandler(WSGIHandler()) twill.add_wsgi_intercept(IP, PORT, lambda: app)
def test_method_not_allowed(): """The "method not allowed" handler return a 405.""" def app(environ, start_response): environ['selector.methods'] = ['GET', 'PUT'] return method_not_allowed(environ, start_response) twill.add_wsgi_intercept('not-found-host', 80, lambda: app) browser = twill.get_browser() browser.go('http://not-found-host/') assert browser.result.page.startswith("405 Method Not Allowed") assert browser.result.http_code == 405
def setUp(self): from django.contrib.auth.models import User user = User.objects.create_user("john", "*****@*****.**", "johnpassword") user.save() from whosendsignal.who_do import * auth = LoggedInUser() auth.user = user twill.add_wsgi_intercept("twilltest", 80, WSGIHandler)
def test_iter_stuff(): twill.add_wsgi_intercept('localhost', 80, iterator_app) print 'go' twill.commands.go('http://localhost:80/') print 'find' twill.commands.show() twill.commands.find("Hello, world") twill.commands.notfind("Hello, worldHello, world") print 'remove' twill.remove_wsgi_intercept('localhost', 80)
def setup(self): wsgi_app = None x = sys.stdout # Quixote mangles sys.stdout; save. try: publisher = create_publisher() wsgi_app = quixote.get_wsgi_app() finally: sys.stdout = x # restore. twill.add_wsgi_intercept("localhost", 80, lambda: wsgi_app, "/qx_test")
def setup(): cpy.config.update("site.conf") cpy.config.update("basic.conf") wsgi = cpy.tree.mount(blox.BlogRoot(), "/", "basic.conf") wsgi = cpy.tree.mount(blox.BlogRoot(), "/", "basic.conf") twill.add_wsgi_intercept('localhost', 4444, lambda: wsgi) syserr, sys.stderr = sys.stderr, StringIO() try: cpy.engine.start(blocking=False) finally: sys.stderr = syserr
def setup(self): wsgi_app = None x = sys.stdout # Quixote mangles sys.stdout; save. try: publisher = create_publisher() wsgi_app = quixote.get_wsgi_app() finally: sys.stdout = x # restore. twill.add_wsgi_intercept('localhost', 80, lambda: wsgi_app, '/qx_test')
def setup(): """ Set up a wsgi intercept """ import os os.environ["DJANGO_SETTINGS_MODULE"] = "simpletest.settings" from django.core.servers.basehttp import AdminMediaHandler from django.core.handlers.wsgi import WSGIHandler app = AdminMediaHandler(WSGIHandler()) add_wsgi_intercept("127.0.0.1", 9876, lambda: app)
def before_all(context): context.baseurl = 'http://127.0.0.1:8000' twill.set_output(StringIO.StringIO()) twill.commands.clear_cookies() context.app = beer_app.create_app() context.app.config['TESTING'] = True # fn=(lambda : context.app), it help create the WSGI app object only once, # because function passed into wsgi_intercept is called # once for each intercepted connection # more here: http://ivory.idyll.org/articles/twill-and-wsgi_intercept.html twill.add_wsgi_intercept('127.0.0.1', 8000, lambda : context.app) context.browser = twill.get_browser()
def setUp(self): import sys import twill from pyramid.configuration import Configurator config = Configurator(root_factory=self.root_factory) config.load_zcml(self.config) twill.add_wsgi_intercept('localhost', 6543, config.make_wsgi_app) if sys.platform is 'win32': # pragma: no cover out = open('nul:', 'wb') else: out = open('/dev/null', 'wb') twill.set_output(out) testing.setUp(registry=config.registry)
def setUp(self): super(AdminSurveyTwillTest, self).setUp() self.old_propagate = settings.DEBUG_PROPAGATE_EXCEPTIONS settings.DEBUG_PROPAGATE_EXCEPTIONS = True signals.request_finished.disconnect(close_connection) twill.set_output(StringIO()) twill.add_wsgi_intercept(TWILL_TEST_HOST, 80, WSGIHandler) self.browser = twill.get_browser() self.browser.go(reverse_for_twill('admin:index')) twill.commands.formvalue(1, 'username', self.username) twill.commands.formvalue(1, 'password', self.pw) self.browser.submit() twill.commands.find('Welcome')
def test_basic(self): """ Test the basic setup (iter_app, twill, and wsgi_intercept). """ twill.add_wsgi_intercept('localhost', 80, lambda:simple_app.iter_app) try: twill.commands.go('http://localhost:80/') twill.commands.find('WSGI intercept') assert simple_app.success() finally: simple_app.reset() twill.remove_wsgi_intercept('localhost', 80)
def test_intercept(): global _app_was_hit _app_was_hit = False twill.add_wsgi_intercept('localhost', 80, lambda: wsgi_lint(simple_app)) assert not _app_was_hit print 'go' twill.commands.go('http://localhost:80/') twill.commands.show() print 'find' twill.commands.find("WSGI intercept successful") assert _app_was_hit print 'remove' twill.remove_wsgi_intercept('localhost', 80)
def _pre_setup(self): app = AdminMediaHandler(WSGIHandler()) add_wsgi_intercept(self.domain, self.port, lambda: app) prefix = "http://%s:%d"%(self.domain,self.port) self.client = self._Client(self.hook and prefix or '', getattr(self, 'url', None)) self.client.reset_browser() hook_twill_command('go', self.client.go) hook_twill_command('url', self.client.url) self._fixture_setup() self._urlconf_setup()
def _twill_selector_browser(id_): """Uses host to avoid collisions in the globalness of twill.""" host = "testhost-%s" % id_ s = Selector() twill.add_wsgi_intercept(host, 80, lambda: s) b = twill.get_browser() def go(path): b.go('http://%s%s' % (host, path)) headers = b._browser._response._headers.headers print s return (b.result.http_code, headers, b.result.page) return dict(selector=s, browser=b, go=go)
def setUp(self): webapp.web.db.open_database("sqlite://") cherrypy.config.update( { "environment": "embedded", "global" : { "tools.auth.on" : True, "tools.sessions.on" : True, } }) wsgiApp = cherrypy.tree.mount(webapp.web.root.Root()) cherrypy.server.start() twill.add_wsgi_intercept('localhost', 8080, lambda : wsgiApp) self.outp = StringIO() twill.set_output(self.outp)
def test_passthru(self): """ Make sure that the recorder actually calls the app correctly, etc. """ recorder = scotch.recorder.Recorder(simple_app.iter_app) twill.add_wsgi_intercept('localhost', 80, lambda: recorder) try: twill.commands.go('http://localhost:80/') twill.commands.find('WSGI intercept') assert simple_app.success() finally: simple_app.reset() twill.remove_wsgi_intercept('localhost', 80)
def test_basic(self): """ Test the basic setup (post_app, twill, and wsgi_intercept). """ twill.add_wsgi_intercept('localhost', 80, lambda:simple_app.post_app) try: twill.commands.go('http://localhost:80/') assert simple_app.success() twill.commands.fv('1', 'test', 'howdy world') twill.commands.submit() twill.commands.find("VALUE WAS: howdy world") finally: simple_app.reset() twill.remove_wsgi_intercept('localhost', 80)
def setUp(self): """Setup an authorized user so we can test app functionality""" # Handles setting the state once for the all tests in this class # http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest/402492#402492 if not self.browser: twill.set_output(StringIO()) twill.commands.clear_cookies() twill.add_wsgi_intercept(TWILLHOST, 80, lambda:app) self.__class__.browser = twill.get_browser() # authorize user against Gmail for our app self.__class__.browser.go(url_for_twill('/')) twill.commands.formvalue(1, 'search', 'test') self.__class__.browser.submit() twill.commands.formvalue(1, 'Passwd', secrets.TEST_GOOGLE_PASSWORD) twill.commands.formvalue(1, 'Email', secrets.TEST_GOOGLE_EMAIL) self.__class__.browser.submit() self.__class__.browser.submit('allow')
def test_passthru(self): """ Make sure that the recorder actually calls the app correctly, etc. """ recorder = scotch.recorder.Recorder(simple_app.post_app) twill.add_wsgi_intercept('localhost', 80, lambda: recorder) try: twill.commands.go('http://localhost:80/') assert simple_app.success() twill.commands.fv('1', 'test', 'howdy world') twill.commands.submit() twill.commands.find("VALUE WAS: howdy world") finally: simple_app.reset() twill.remove_wsgi_intercept('localhost', 80)
def setup(host=None, port=None, allow_xhtml=True, propagate=True): """Install the WSGI hook for ``host`` and ``port``. The default values will be used if host or port are not specified. ``allow_xhtml`` enables a workaround for the "not viewer HTML" error when browsing sites that are determined to be XHTML, e.g. featuring xhtml-ish mimetypes. Unless ``propagate specifies otherwise``, the ``DEBUG_PROPAGATE_EXCEPTIONS`` will be enabled for better debugging: when using twill, we don't really want to see 500 error pages, but rather directly the exceptions that occured on the view side. Multiple calls to this function will only result in one handler for each host/port combination being installed. """ host = host or DEFAULT_HOST port = port or DEFAULT_PORT key = (host, port) if not key in INSTALLED: # installer wsgi handler app = DjangoWsgiFix(AdminMediaHandler(WSGIHandler())) twill.add_wsgi_intercept(host, port, lambda: app) # start browser fresh browser = get_browser() browser.diverged = False # enable xhtml mode if requested _enable_xhtml(browser, allow_xhtml) # init debug propagate setting, and remember old value if propagate: old_propgate_setting = settings.DEBUG_PROPAGATE_EXCEPTIONS settings.DEBUG_PROPAGATE_EXCEPTIONS = True else: old_propgate_setting = None INSTALLED[key] = (app, old_propgate_setting) return browser return False
def test_environ_dispatcher(): """Dispatcher chooses an app basen on env.""" def make_app(name): def app(environ, start_response): start_response("200 OK", [('Content-type', 'text/plain')]) return [name] return app t = lambda env: env['PATH_INFO'] == '/foo' f = lambda env: env['PATH_INFO'] == '/bar' rules = [(f, make_app('a')), (f, make_app('b')), (t, make_app('c')), (f, make_app('d')), (t, make_app('e'))] dispatcher = selector.EnvironDispatcher(rules) twill.add_wsgi_intercept('simple-host', 80, lambda: dispatcher) browser = twill.get_browser() browser.go('http://simple-host/foo') assert browser.result.page.startswith("c") assert browser.result.http_code == 200
def test_multirecord(self): """ Test recording of multiple requests. """ recorder = scotch.recorder.Recorder(simple_app.iter_app) # first, record. twill.add_wsgi_intercept('localhost', 80, lambda: recorder) try: twill.commands.go('http://localhost:80/') assert simple_app.success() simple_app.reset() twill.commands.go('./') assert simple_app.success() finally: simple_app.reset() twill.remove_wsgi_intercept('localhost', 80) # check the length of recorded bit. assert len(recorder.record_holder) == 2
def test_wrapper_intercept(): """ This tests a tricky wsgi_intercept interaction between the 'write' fn passed back from the start_response function in WSGI, and the generator data yielded from the initial app call. See wsgi_intercept.py, section containing 'generator_data', for more info. """ global _app_was_hit _app_was_hit = False wrap_app = wrapper_app(write_app) twill.add_wsgi_intercept('localhost', 80, lambda: wsgi_lint(wrap_app)) assert not _app_was_hit print 'go' twill.commands.go('http://localhost:80/') print 'find' twill.commands.find("WSGI intercept successful") assert _app_was_hit print 'remove' twill.remove_wsgi_intercept('localhost', 80)
def pytest_funcarg__env(request): tmpdir = request.getfuncargvalue("tmpdir") from pypiserver import app a = app(root=tmpdir.strpath) if loadapp: pini = tmpdir.join(".paste.ini") pini.write(""" [composite:main] use = egg:Paste#urlmap /priv/ = private [app:private] paste.app_factory = pypiserver:paste_app_factory root = %s [server:main] use = egg:gunicorn#main host = 0.0.0.0 port = 8001 workers = 5 accesslog = - """ % tmpdir) twill.add_wsgi_intercept("nonroot", 80, lambda: loadapp("config:%s" % pini)) twill.add_wsgi_intercept("localhost", 8080, lambda: a) twill.add_wsgi_intercept("systemexit.de", 80, lambda: a) twill.add_wsgi_intercept("pypi.python.org", 80, lambda: fallback_app) def cleanup(): twill.remove_wsgi_intercept("localhost", 8080) twill.remove_wsgi_intercept("systemexit.de", 80) twill.remove_wsgi_intercept("pypi.python.org", 80) if loadapp: twill.remove_wsgi_intercept("nonroot", 80) request.addfinalizer(cleanup) go("http://localhost:8080/") return dict(root=tmpdir, app=a, _app=a.module)
def twill_setup(): app = AdminMediaHandler(WSGIHandler()) twill.add_wsgi_intercept("127.0.0.1", 8080, lambda: app)
#! /usr/bin/env python import twill def simple_app(environ, start_response): status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) return ['Hello world!\n'] if __name__ == '__main__': print '*** installing WSGI intercept hook ***\n' twill.add_wsgi_intercept('localhost', 80, lambda: simple_app) twill.shell.main()
def setUp(self): app = AdminMediaHandler(WSGIHandler()) twill.add_wsgi_intercept(self.HOST, self.PORT, lambda: app) twill.set_output(StringIO()) self.command = twill.commands
def _twill_setup(): app = StaticFilesHandler(WSGIHandler()) twill.add_wsgi_intercept("127.0.0.1", 8080, lambda: app)