Skip to content

Commit

Permalink
util: testing: consoletest: commands: Support for http.server
Browse files Browse the repository at this point in the history
Signed-off-by: John Andersen <[email protected]>
  • Loading branch information
pdxjohnny committed Mar 18, 2021
1 parent 41fcd7e commit 04401c2
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
46 changes: 46 additions & 0 deletions dffml/util/testing/consoletest/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,14 @@
import pathlib
import inspect
import tempfile
import functools
import contextlib
import subprocess
import http.server
from typing import IO, Any, Dict, List, Union, Optional

import httptest

from .... import plugins


Expand Down Expand Up @@ -585,6 +589,45 @@ async def __aexit__(self, _exc_type, _exc_value, _traceback):
self.cleanup()


class SimpleHTTPServerCommand(ConsoleCommand):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ts = None

async def __aenter__(self) -> "OperationImplementationContext":
self.ts = None

async def run(self, ctx):
# Default the port to 8000
given_port = "8000"
# Grab port number if given
if self.cmd[-1].isdigit():
given_port = self.cmd[-1]
if "--cgi" in self.cmd:
# Start CGI server if requseted
handler_class = http.server.CGIHTTPRequestHandler
else:
# Default to simple http server
handler_class = http.server.SimpleHTTPRequestHandler
# Specify directory if given
directory = ctx["cwd"]
if "--directory" in self.cmd:
directory = self.cmd[self.cmd.index("--directory") + 1]
# Ensure handler is relative to directory
handler_class = functools.partial(handler_class, directory=directory)

# Start a server with a random port
self.ts = httptest.Server(handler_class).__enter__()
# Map the port that was given to the port that was used
ctx.setdefault("HTTP_SERVER", {})
ctx["HTTP_SERVER"][given_port] = self.ts.server_port
return self

async def __aexit__(self, exc_type, exc_value, traceback):
self.ts.__exit__(None, None, None)
self.ts = None


def within_qoute(current, qoute=('"', "'")):
within = False
for i, char in enumerate(current):
Expand Down Expand Up @@ -668,6 +711,9 @@ def build_command(cmd):
# Handle docker commands
if cmd[:2] == ["docker", "run"]:
return DockerRunCommand(cmd)
# Handle simple http server
if cmd[1:3] == ["-m", "http.server"]:
return SimpleHTTPServerCommand(cmd)
# Regular console command
return ConsoleCommand(cmd)

Expand Down
2 changes: 2 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ class InstallException(Exception):
packages=find_packages(),
include_package_data=True,
zip_safe=False,
# Temporary until we split consoletest into it's own package
install_requires=["httptest>=0.0.17"],
extras_require={
"dev": DEV_REQUIRES,
**plugins.PACKAGE_NAMES_BY_PLUGIN_INSTALLABLE,
Expand Down

0 comments on commit 04401c2

Please sign in to comment.