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

Test starlette client #1326

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
from urllib import parse
from urllib.request import urlopen

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')


import pytest

from tests.fake_webapp_server import start_server, stop_server
Expand Down
54 changes: 54 additions & 0 deletions tests/test_starletteclient.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from fastapi import FastAPI
from starlette.responses import HTMLResponse
from splinter import Browser
import pytest
import logging

# ----- Step 1: Define a minimal FastAPI application -----
app = FastAPI()

@app.get("/", response_class=HTMLResponse)
def read_root():
# Return an HTML page with a title set to "Example Domain"
return """
<!doctype html>
<html>
<head>
<title>Example Domain</title>
</head>
<body>
<h1>Welcome to Example Domain</h1>
<p>This is a sample page for testing.</p>
</body>
</html>
"""

# ----- Step 2: Write the test function using the StarletteClient -----
def test_starlette_client():
browser = Browser("starlette", app=app)

try:
# Visit the local route "/" served by our FastAPI app.
browser.visit("/")

# Check the title to match the expected "Example Domain"
assert browser.title == "Example Domain"

# Assert that some content is present on the page (the header in this case)
assert browser.is_text_present("Welcome to Example Domain")

# Check for the presence of a paragraph (new test case)
assert browser.is_text_present("This is a sample page for testing.")

# Optionally, check that the number of <h1> tags is exactly one
assert len(browser.find_by_tag("h1")) == 1

except ValueError as e:
logging.error(f"Test failed: {e}") # Log the error if we catch it

except Exception as e:
logging.error(f"Unexpected error: {e}")

finally:
# Clean up (quit() is a no-op for the StarletteClient)
browser.quit()