Created
March 28, 2015 06:38
-
-
Save dahlia/38bdb90a868624dc9492 to your computer and use it in GitHub Desktop.
py.test + ngrok (localtunnel)
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
import contextlib | |
import distutils.spawn | |
import functools | |
import re | |
import signal | |
import subprocess | |
from pytest import fixture, skip | |
def pytest_addoption(parser): | |
parser.addoption( | |
'--ngrok', | |
default=distutils.spawn.find_executable('ngrok'), | |
help='path to ngrok [%default]' | |
) | |
NGROK_LOG_PATTERN = re.compile( | |
rb'\[client\]\s+Tunnel\s+established\s+at\s+(https?://\S+)', | |
re.IGNORECASE | |
) | |
@contextlib.contextmanager | |
def ngrok_context(ngrok_path, port): | |
p = subprocess.Popen( | |
[ngrok_path, '-proto=https', '-log=stdout', str(port)], | |
stderr=subprocess.DEVNULL, | |
stdout=subprocess.PIPE | |
) | |
# Detecting public address by grepping log | |
while True: | |
for line in p.stdout: | |
m = NGROK_LOG_PATTERN.search(line) | |
if m: | |
public_addr = m.group(1).decode() | |
print('ngrok_context:', public_addr) | |
yield public_addr | |
return | |
else: | |
try: | |
p.wait(0.5) | |
except subprocess.TimeoutExpired: | |
continue | |
else: | |
return | |
@fixture | |
def fx_ngrok_context(request): | |
ngrok_path = request.config.getoption('--ngrok') | |
if not ngrok_path: | |
skip('--ngrok is missing; skipped...') | |
return functools.partial(ngrok_context, ngrok_path) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment