Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help.txt path update and new tests #62

Merged
merged 5 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 76 additions & 57 deletions src/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,65 +18,84 @@

from src.settings import ServerSettings

# Load environment variables from .env file
env = ServerSettings()

app = Flask(__name__)
CORS(app)


@app.route("/help")
def serve_help():
return send_from_directory(f"{str(Path(__file__).parent)}/", "help.txt")


@app.route("/home")
def serve_index():
return render_template("index.html", env_vars=env.model_dump())


@app.route("/script.js")
def serve_script():
return send_file("static/script.js")


@app.route("/")
def default_route():
query_parameters = urllib.parse.parse_qsl(
request.query_string.decode(), keep_blank_values=True
)
parsed_parameters = []

for key, value in query_parameters:
if value:
parsed_parameters.append(f"{key}={value}")
else:
parsed_parameters.append(key)

# Join the parsed parameters list into a single string
args = ",".join(parsed_parameters)

async def run_subprocess():
try:
result = subprocess.run(
["python3", "src/cli.py", args],
capture_output=True,
text=True,
check=True,
)
return result.stdout
except subprocess.CalledProcessError as e:
# Print the error message from the subprocess
print("Error message from subprocess:", e.stderr)
# Raise the error again to propagate it
raise e

# Run subprocess asynchronously
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
result = loop.run_until_complete(run_subprocess())
return result
def create_app(env):
"""
Application factory function
"""

# Load environment variables from .env file

app = Flask(__name__)
CORS(app)

@app.route("/help")
def serve_help():
"""
Servers the help.txt file
"""
return send_from_directory(
Path(__file__).resolve().parents[1], "help.txt"
)

@app.route("/home")
def serve_index():
"""
Servers index.html
"""
return render_template("index.html", env_vars=env.model_dump())

@app.route("/script.js")
def serve_script():
"""
Servers javascript
"""
return send_file("static/script.js")

@app.route("/")
def default_route():
"""
Default route, serves surf report
"""
query_parameters = urllib.parse.parse_qsl(
request.query_string.decode(), keep_blank_values=True
)
parsed_parameters = []

for key, value in query_parameters:
if value:
parsed_parameters.append(f"{key}={value}")
else:
parsed_parameters.append(key)

# Join the parsed parameters list into a single string
args = ",".join(parsed_parameters)

async def run_subprocess():
try:
result = subprocess.run(
["python3", "src/cli.py", args],
capture_output=True,
text=True,
check=True,
)
return result.stdout
except subprocess.CalledProcessError as e:
# Print the error message from the subprocess
print("Error message from subprocess:", e.stderr)
# Raise the error again to propagate it
raise e

# Run subprocess asynchronously
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
result = loop.run_until_complete(run_subprocess())
return result

return app


if __name__ == "__main__":
env = ServerSettings()
K-dash marked this conversation as resolved.
Show resolved Hide resolved
app = create_app(env)
app.run(host="0.0.0.0", port=env.PORT, debug=env.DEBUG)
26 changes: 26 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,29 @@
Make sure pytest is installed: pip install pytest
Run pytest: pytest
"""

from src import settings
from src.server import create_app


def test_routes():
"""
Test that the routes are able to be retrieved
/home, /help, /
When a page is requested (GET)
THEN check if the response is valid (200)
"""
env = settings.ServerSettings()
flask_app = create_app(env)
OK = 200

# Create a test client using the Flask application configured for testing
with flask_app.test_client() as test_client:
response_help = test_client.get("/help")
assert response_help.status_code == OK

response_home = test_client.get("/home")
assert response_home.status_code == OK

response_root = test_client.get("/")
assert response_root.status_code == OK
Loading