klen / muffin

Muffin is a fast, simple and asyncronous web-framework for Python 3

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Newbie having trouble getting test client working (also trio).

scherrey opened this issue · comments

I don't see anywhere in the docs where one should go for tech support. I'm trying out muffin with trio and my first test case fails with "PytestCollectionWarning: cannot collect test class 'ASGITestClient' because it has a init constructor (from: apisla/_tests/test_example.py)". I know I'm just doing something stupid but it's not apparent which stupid thing that is. Code repo is here: https://github.com/ActorForth/apisla Is there a public place I should goto for Q&A or support?

Code under test is:

import time
import datetime

#import trio
from muffin import Application, Request, ResponseJSON

app = Application()

origin_clock_start = datetime.datetime.now().timestamp() - time.perf_counter()

def pretty_time(seconds : float) -> str:
	present = time.localtime(origin_clock_start + seconds)
	return str(datetime.datetime(present.tm_year, present.tm_mon, 
			   present.tm_mday, present.tm_hour, present.tm_min, present.tm_sec))

@app.route("/")
async def timed_api(request: Request): # Callable?
	received = time.perf_counter() # trio.current_time()
	scheduled = received + 5

	print(f"Request received @ {pretty_time(received)} scheduled to reply @ {pretty_time(scheduled_response)}.")
	#trio.sleep_until(scheduled_response)
	time.sleep(5)
	handled = time.perf_counter() # trio.current_time()
	response = { 	'received': received,
					'scheduled': scheduled,
					'handled': handled,
					'delta': handled-scheduled 
				}

	return ResponseJSON(response)	

Test code:

async def test_app():
	client = TestClient(app)
	response = await client.get('/')
	assert response.status_code == 200
	assert await response.text() == 'OK'

@scherrey Hello Ben, thank you for the question. It's the right place for Q&A.

PytestCollectionWarning: cannot collect test class 'ASGITestClient'

It's a warning from pytest, because the pytest tries to collect the class as UnitTestClass. If you change the import like:

    from muffin import TestClient as Client

    ....
        client = Client(app)

the warning will disappear. You are able to define the client automatically as a pytest.fixture inside your conftest.

time.sleep(5)

should it be await trio.sleep(5)?

response = await client.get('/')

you endpoint is waiting for 5 seconds, it will raise a timeout, consider to use await client.get('/', timeout=6)

	response = { 	'received': received,
					'scheduled': scheduled,
					'handled': handled,
					'delta': handled-scheduled 
				}

	return ResponseJSON(response)

Muffin can handle JSON response automatically if you return dict/list objects.

	return { 	'received': received,
					'scheduled': scheduled,
					'handled': handled,
					'delta': handled-scheduled 
				}