Last active
April 28, 2020 10:48
-
-
Save ryanc414/e5e9f0a7b705bbb6720c0de1d420d37d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
"""Example usage of pytest fixtures.""" | |
import subprocess | |
import re | |
import pytest | |
import requests | |
class App: | |
"""Manages starting and stopping my app for testing.""" | |
def __init__(self, port=None): | |
self.proc = None | |
self.listen_addr = None | |
self._port = port | |
def start(self): | |
""" | |
Start my app in a subprocess. Extracts the listening address from the | |
stdout - necessary because the app binds to port 0. | |
""" | |
# Ensure app binary is built first. | |
subprocess.run(["go", "build"], check=True) | |
cmd = ["./app"] | |
if self._port is not None: | |
cmd.extend(["-port", str(self._port)]) | |
self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True) | |
stdout_line = self.proc.stdout.readline() | |
match = re.match(r"listening on (.*)", stdout_line) | |
if not match: | |
self.proc.terminate() | |
raise RuntimeError( | |
f"Could not extract listen address from stdout: {stdout_line}" | |
) | |
self.listen_addr = match.group(1) | |
def stop(self): | |
"""Stop the app by sending SIGTERM.""" | |
if not self.proc: | |
raise RuntimeError("No process to stop") | |
self.proc.terminate() | |
self.proc.wait() | |
def test_app(): | |
"""Test making an HTTP request to my app.""" | |
app = App() | |
app.start() | |
rsp = requests.get(f"{app.listen_addr}/hello") | |
assert rsp.status_code == 200 | |
assert rsp.text == 'Hello, "/hello"' | |
app.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment