Skip to content

Commit

Permalink
Add test for Starlette client
Browse files Browse the repository at this point in the history
  • Loading branch information
anisjellazi committed Feb 6, 2025
1 parent c6c4202 commit fc592db
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 6 deletions.
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
55 changes: 49 additions & 6 deletions tests/test_starletteclient.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,54 @@
from splinter import Browser
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():
app = FastAPI()
browser = Browser("starlette", app=app) # Create the browser instance
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

browser.visit("http://example.com") # Try to visit a page
assert browser.title == "Example Domain" # Check if title is correct
except Exception as e:
logging.error(f"Unexpected error: {e}")

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

0 comments on commit fc592db

Please sign in to comment.