2016-10-18 09:22:49 +01:00
|
|
|
from multiprocessing import Array, Event, Process
|
2016-12-26 22:37:05 +00:00
|
|
|
from time import sleep, time
|
2016-10-18 09:22:49 +01:00
|
|
|
from ujson import loads as json_loads
|
|
|
|
|
2017-01-08 17:55:08 +00:00
|
|
|
import pytest
|
|
|
|
|
2016-10-18 09:22:49 +01:00
|
|
|
from sanic import Sanic
|
2017-01-07 23:46:43 +00:00
|
|
|
from sanic.response import json
|
2016-10-18 09:22:49 +01:00
|
|
|
from sanic.utils import local_request, HOST, PORT
|
|
|
|
|
|
|
|
|
|
|
|
# ------------------------------------------------------------ #
|
|
|
|
# GET
|
|
|
|
# ------------------------------------------------------------ #
|
|
|
|
|
|
|
|
# TODO: Figure out why this freezes on pytest but not when
|
|
|
|
# executed via interpreter
|
2017-01-08 17:55:08 +00:00
|
|
|
@pytest.mark.skip(
|
|
|
|
reason="Freezes with pytest not on interpreter")
|
|
|
|
def test_multiprocessing():
|
2016-10-18 09:22:49 +01:00
|
|
|
app = Sanic('test_json')
|
|
|
|
|
|
|
|
response = Array('c', 50)
|
|
|
|
@app.route('/')
|
|
|
|
async def handler(request):
|
|
|
|
return json({"test": True})
|
|
|
|
|
|
|
|
stop_event = Event()
|
|
|
|
async def after_start(*args, **kwargs):
|
|
|
|
http_response = await local_request('get', '/')
|
|
|
|
response.value = http_response.text.encode()
|
|
|
|
stop_event.set()
|
|
|
|
|
|
|
|
def rescue_crew():
|
|
|
|
sleep(5)
|
|
|
|
stop_event.set()
|
|
|
|
|
|
|
|
rescue_process = Process(target=rescue_crew)
|
|
|
|
rescue_process.start()
|
|
|
|
|
|
|
|
app.serve_multiple({
|
|
|
|
'host': HOST,
|
|
|
|
'port': PORT,
|
|
|
|
'after_start': after_start,
|
|
|
|
'request_handler': app.handle_request,
|
|
|
|
'request_max_size': 100000,
|
|
|
|
}, workers=2, stop_event=stop_event)
|
|
|
|
|
|
|
|
rescue_process.terminate()
|
|
|
|
|
|
|
|
try:
|
|
|
|
results = json_loads(response.value)
|
|
|
|
except:
|
|
|
|
raise ValueError("Expected JSON response but got '{}'".format(response))
|
|
|
|
|
|
|
|
assert results.get('test') == True
|
2016-12-26 22:37:05 +00:00
|
|
|
|
2017-01-08 17:55:08 +00:00
|
|
|
@pytest.mark.skip(
|
|
|
|
reason="Freezes with pytest not on interpreter")
|
|
|
|
def test_drain_connections():
|
2017-01-07 23:46:43 +00:00
|
|
|
app = Sanic('test_json')
|
2016-12-26 22:37:05 +00:00
|
|
|
|
|
|
|
@app.route('/')
|
|
|
|
async def handler(request):
|
|
|
|
return json({"test": True})
|
|
|
|
|
|
|
|
stop_event = Event()
|
|
|
|
async def after_start(*args, **kwargs):
|
|
|
|
http_response = await local_request('get', '/')
|
|
|
|
stop_event.set()
|
|
|
|
|
|
|
|
start = time()
|
|
|
|
app.serve_multiple({
|
|
|
|
'host': HOST,
|
|
|
|
'port': PORT,
|
|
|
|
'after_start': after_start,
|
|
|
|
'request_handler': app.handle_request,
|
|
|
|
}, workers=2, stop_event=stop_event)
|
|
|
|
end = time()
|
|
|
|
|
|
|
|
assert end - start < 0.05
|