Created
August 12, 2015 05:49
-
-
Save miohtama/12beaa08b6c1857c1df1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ServerThread(threading.Thread): | |
""" Run WSGI server on a background thread. | |
Pass in WSGI app object and serve pages from it for Selenium browser. | |
""" | |
def __init__(self, app, hostbase=HOST_BASE): | |
threading.Thread.__init__(self) | |
self.app = app | |
self.srv = None | |
self.daemon = True | |
self.hostbase = hostbase | |
def run(self): | |
""" | |
Open WSGI server to listen to HOST_BASE address | |
""" | |
parts = urlparse(self.hostbase) | |
domain, port = parts.netloc.split(":") | |
self.srv = make_server(domain, int(port), self.app) | |
try: | |
self.srv.serve_forever() | |
except Exception as e: | |
# We are a background thread so we have problems to interrupt tests in the case of error | |
import traceback | |
traceback.print_exc() | |
# Failed to start | |
self.srv = None | |
def quit(self): | |
"""Stop test webserver.""" | |
if self.srv: | |
self.srv.shutdown() | |
@pytest.fixture(scope='session') | |
def web_server(request, app) -> str: | |
"""py.test fixture to create a WSGI web server for functional tests. | |
:param app: py.test fixture for constructing a WSGI application | |
:return: localhost URL where the web server is running. | |
""" | |
server = ServerThread(app) | |
server.start() | |
# Wait randomish time to allows SocketServer to initialize itself. | |
# TODO: Replace this with proper event telling the server is up. | |
time.sleep(0.1) | |
assert server.srv is not None, "Could not start the test web server" | |
host_base = HOST_BASE | |
def teardown(): | |
server.quit() | |
request.addfinalizer(teardown) | |
return host_base |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment