Ejemplo n.º 1
0
def test_url_attributes_with_ssl(path, query, expected_url):
    app = Necktie('test_url_attrs_with_ssl')

    current_dir = os.path.dirname(os.path.realpath(__file__))
    context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
    context.load_cert_chain(
        os.path.join(current_dir, 'certs/selfsigned.cert'),
        keyfile=os.path.join(current_dir, 'certs/selfsigned.key'))

    async def handler(request):
        return text('OK')

    app.add_route(handler, path)

    request, response = app.test_client.get(
        'https://{}:{}'.format(HOST, app.test_port) + path + '?{}'.format(query),
        server_kwargs={'ssl': context})
    assert request.url == expected_url.format(HOST, app.test_port)

    parsed = urlparse(request.url)

    assert parsed.scheme == request.scheme
    assert parsed.path == request.path
    assert parsed.query == request.query_string
    assert parsed.netloc == request.host
Ejemplo n.º 2
0
def test_file_stream_head_response(file_name, static_file_directory):
    app = Necktie('test_file_helper')

    @app.route('/files/<filename>', methods=['GET', 'HEAD'])
    async def file_route(request, filename):
        file_path = os.path.join(static_file_directory, filename)
        file_path = os.path.abspath(unquote(file_path))
        headers = dict()
        headers['Accept-Ranges'] = 'bytes'
        if request.method == "HEAD":
            # Return a normal HTTPResponse, not a
            # StreamingHTTPResponse for a HEAD request
            stats = await async_os.stat(file_path)
            headers['Content-Length'] = str(stats.st_size)
            return HTTPResponse(headers=headers,
                                content_type=guess_type(file_path)[0]
                                or 'text/plain')
        else:
            return file_stream(file_path,
                               chunk_size=32,
                               headers=headers,
                               mime_type=guess_type(file_path)[0]
                               or 'text/plain')

    request, response = app.test_client.head('/files/{}'.format(file_name))
    assert response.status == 200
    # A HEAD request should never be streamed/chunked.
    if 'Transfer-Encoding' in response.headers:
        assert response.headers['Transfer-Encoding'] != "chunked"
    assert 'Accept-Ranges' in response.headers
    # A HEAD request should get the Content-Length too
    assert 'Content-Length' in response.headers
    assert int(response.headers['Content-Length']) == len(
        get_file_content(static_file_directory, file_name))
Ejemplo n.º 3
0
def test_file_head_response(file_name, static_file_directory):
    app = Necktie('test_file_helper')

    @app.route('/files/<filename>', methods=['GET', 'HEAD'])
    async def file_route(request, filename):
        file_path = os.path.join(static_file_directory, filename)
        file_path = os.path.abspath(unquote(file_path))
        stats = await async_os.stat(file_path)
        headers = dict()
        headers['Accept-Ranges'] = 'bytes'
        headers['Content-Length'] = str(stats.st_size)
        if request.method == "HEAD":
            return HTTPResponse(headers=headers,
                                content_type=guess_type(file_path)[0]
                                or 'text/plain')
        else:
            return file(file_path,
                        headers=headers,
                        mime_type=guess_type(file_path)[0] or 'text/plain')

    request, response = app.test_client.head('/files/{}'.format(file_name))
    assert response.status == 200
    assert 'Accept-Ranges' in response.headers
    assert 'Content-Length' in response.headers
    assert int(response.headers['Content-Length']) == len(
        get_file_content(static_file_directory, file_name))
Ejemplo n.º 4
0
def streaming_app():
    app = Necktie('streaming')

    @app.route("/")
    async def test(request):
        return stream(sample_streaming_fn, content_type='text/csv')

    return app
Ejemplo n.º 5
0
def json_app():
    app = Necktie('json')

    @app.route("/")
    async def test(request):
        return json(JSON_DATA)

    return app
Ejemplo n.º 6
0
def test_url_attributes_no_ssl(path, query, expected_url):
    app = Necktie('test_url_attrs_no_ssl')

    async def handler(request):
        return text('OK')

    app.add_route(handler, path)

    request, response = app.test_client.get(path + '?{}'.format(query))
    assert request.url == expected_url.format(HOST, app.test_port)

    parsed = urlparse(request.url)

    assert parsed.scheme == request.scheme
    assert parsed.path == request.path
    assert parsed.query == request.query_string
    assert parsed.netloc == request.host
Ejemplo n.º 7
0
def test_uri_template():
    app = Necktie('test_uri_template')

    @app.route('/foo/<id:int>/bar/<name:[A-z]+>')
    async def handler(request):
        return text('OK')

    request, response = app.test_client.get('/foo/123/bar/baz')
    assert request.uri_template == '/foo/<id:int>/bar/<name:[A-z]+>'
Ejemplo n.º 8
0
def test_remote_address():
    app = Necktie('test_text')

    @app.route('/')
    def handler(request):
        return text("{}".format(request.ip))

    request, response = app.test_client.get('/')

    assert response.text == '127.0.0.1'
Ejemplo n.º 9
0
def test_text():
    app = Necktie('test_text')

    @app.route('/')
    async def handler(request):
        return text('Hello')

    request, response = app.test_client.get('/')

    assert response.text == 'Hello'
Ejemplo n.º 10
0
def test_match_info():
    app = Necktie('test_match_info')

    @app.route('/api/v1/user/<user_id>/')
    async def handler(request, user_id):
        return json(request.match_info)

    request, response = app.test_client.get('/api/v1/user/sanic_user/')

    assert request.match_info == {"user_id": "sanic_user"}
    assert json_loads(response.text) == {"user_id": "sanic_user"}
Ejemplo n.º 11
0
def test_headers():
    app = Necktie('test_text')

    @app.route('/')
    async def handler(request):
        headers = {"spam": "great"}
        return text('Hello', headers=headers)

    request, response = app.test_client.get('/')

    assert response.headers.get('spam') == 'great'
Ejemplo n.º 12
0
def test_invalid_json():
    app = Necktie('test_json')

    @app.route('/')
    async def handler(request):
        return json(request.json)

    data = "I am not json"
    request, response = app.test_client.get('/', data=data)

    assert response.status == 400
Ejemplo n.º 13
0
def test_empty_json():
    app = Necktie('test_json')

    @app.route('/')
    async def handler(request):
        assert request.json == None
        return json(request.json)

    request, response = app.test_client.get('/')
    assert response.status == 200
    assert response.text == 'null'
Ejemplo n.º 14
0
def test_non_str_headers():
    app = Necktie('test_text')

    @app.route('/')
    async def handler(request):
        headers = {"answer": 42}
        return text('Hello', headers=headers)

    request, response = app.test_client.get('/')

    assert response.headers.get('answer') == '42'
Ejemplo n.º 15
0
def test_response_body_not_a_string():
    """Test when a response body sent from the application is not a string"""
    app = Necktie('response_body_not_a_string')
    random_num = choice(range(1000))

    @app.route('/hello')
    async def hello_route(request):
        return HTTPResponse(body=random_num)

    request, response = app.test_client.get('/hello')
    assert response.text == str(random_num)
Ejemplo n.º 16
0
def test_json():
    app = Necktie('test_json')

    @app.route('/')
    async def handler(request):
        return json({"test": True})

    request, response = app.test_client.get('/')

    results = json_loads(response.text)

    assert results.get('test') == True
Ejemplo n.º 17
0
def test_query_string():
    app = Necktie('test_query_string')

    @app.route('/')
    async def handler(request):
        return text('OK')

    request, response = app.test_client.get(
        '/', params=[("test1", "1"), ("test2", "false"), ("test2", "true")])

    assert request.args.get('test1') == '1'
    assert request.args.get('test2') == 'false'
Ejemplo n.º 18
0
def test_post_form_multipart_form_data(payload):
    app = Necktie('test_post_form_multipart_form_data')

    @app.route('/', methods=['POST'])
    async def handler(request):
        return text('OK')

    headers = {'content-type': 'multipart/form-data; boundary=----sanic'}

    request, response = app.test_client.post(data=payload, headers=headers)

    assert request.form.get('test') == 'OK'
Ejemplo n.º 19
0
def test_post_form_urlencoded():
    app = Necktie('test_post_form_urlencoded')

    @app.route('/', methods=['POST'])
    async def handler(request):
        return text('OK')

    payload = 'test=OK'
    headers = {'content-type': 'application/x-www-form-urlencoded'}

    request, response = app.test_client.post('/', data=payload, headers=headers)

    assert request.form.get('test') == 'OK'
Ejemplo n.º 20
0
def test_invalid_response():
    app = Necktie('test_invalid_response')

    @app.exception(ServerError)
    def handler_exception(request, exception):
        return text('Internal Server Error.', 500)

    @app.route('/')
    async def handler(request):
        return 'This should fail'

    request, response = app.test_client.get('/')
    assert response.status == 500
    assert response.text == "Internal Server Error."
Ejemplo n.º 21
0
def test_file_response_custom_filename(source, dest, static_file_directory):
    app = Necktie('test_file_helper')

    @app.route('/files/<filename>', methods=['GET'])
    def file_route(request, filename):
        file_path = os.path.join(static_file_directory, filename)
        file_path = os.path.abspath(unquote(file_path))
        return file(file_path, filename=dest)

    request, response = app.test_client.get('/files/{}'.format(source))
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, source)
    assert response.headers[
        'Content-Disposition'] == 'attachment; filename="{}"'.format(dest)
Ejemplo n.º 22
0
def test_file_response(file_name, static_file_directory):
    app = Necktie('test_file_helper')

    @app.route('/files/<filename>', methods=['GET'])
    def file_route(request, filename):
        file_path = os.path.join(static_file_directory, filename)
        file_path = os.path.abspath(unquote(file_path))
        return file(file_path,
                    mime_type=guess_type(file_path)[0] or 'text/plain')

    request, response = app.test_client.get('/files/{}'.format(file_name))
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)
    assert 'Content-Disposition' not in response.headers
Ejemplo n.º 23
0
def test_post_json():
    app = Necktie('test_post_json')

    @app.route('/', methods=['POST'])
    async def handler(request):
        return text('OK')

    payload = {'test': 'OK'}
    headers = {'content-type': 'application/json'}

    request, response = app.test_client.post(
        '/', data=json_dumps(payload), headers=headers)

    assert request.json.get('test') == 'OK'
    assert response.text == 'OK'
Ejemplo n.º 24
0
def test_content_type():
    app = Necktie('test_content_type')

    @app.route('/')
    async def handler(request):
        return text(request.content_type)

    request, response = app.test_client.get('/')
    assert request.content_type == DEFAULT_HTTP_CONTENT_TYPE
    assert response.text == DEFAULT_HTTP_CONTENT_TYPE

    headers = {
        'content-type': 'application/json',
    }
    request, response = app.test_client.get('/', headers=headers)
    assert request.content_type == 'application/json'
    assert response.text == 'application/json'
Ejemplo n.º 25
0
def test_token():
    app = Necktie('test_post_token')

    @app.route('/')
    async def handler(request):
        return text('OK')

    # uuid4 generated token.
    token = 'a1d895e0-553a-421a-8e22-5ff8ecb48cbf'
    headers = {
        'content-type': 'application/json',
        'Authorization': '{}'.format(token)
    }

    request, response = app.test_client.get('/', headers=headers)

    assert request.token == token

    token = 'a1d895e0-553a-421a-8e22-5ff8ecb48cbf'
    headers = {
        'content-type': 'application/json',
        'Authorization': 'Token {}'.format(token)
    }

    request, response = app.test_client.get('/', headers=headers)

    assert request.token == token

    token = 'a1d895e0-553a-421a-8e22-5ff8ecb48cbf'
    headers = {
        'content-type': 'application/json',
        'Authorization': 'Bearer {}'.format(token)
    }

    request, response = app.test_client.get('/', headers=headers)

    assert request.token == token

    # no Authorization headers
    headers = {
        'content-type': 'application/json'
    }

    request, response = app.test_client.get('/', headers=headers)

    assert request.token is None
Ejemplo n.º 26
0
def test_method_not_allowed():
    app = Necktie('method_not_allowed')

    @app.get('/')
    async def test(request):
        return response.json({'hello': 'world'})

    request, response = app.test_client.head('/')
    assert response.headers['Allow'] == 'GET'

    @app.post('/')
    async def test(request):
        return response.json({'hello': 'world'})

    request, response = app.test_client.head('/')
    assert response.status == 405
    assert set(response.headers['Allow'].split(', ')) == set(['GET', 'POST'])
    assert response.headers['Content-Length'] == '0'
Ejemplo n.º 27
0
def test_remote_addr():
    app = Necktie('test_content_type')

    @app.route('/')
    async def handler(request):
        return text(request.remote_addr)

    headers = {
        'X-Forwarded-For': '127.0.0.1, 127.0.1.2'
    }
    request, response = app.test_client.get('/', headers=headers)
    assert request.remote_addr == '127.0.0.1'
    assert response.text == '127.0.0.1'

    request, response = app.test_client.get('/')
    assert request.remote_addr == ''
    assert response.text == ''

    headers = {
        'X-Forwarded-For': '127.0.0.1, ,   ,,127.0.1.2'
    }
    request, response = app.test_client.get('/', headers=headers)
    assert request.remote_addr == '127.0.0.1'
    assert response.text == '127.0.0.1'
Ejemplo n.º 28
0
from pynecktie import Necktie
from pynecktie.response import text

app = Necktie(__name__)

@app.route("/test1")
async def test1(request):
    return text("hello worlds")

if __name__ == "__main__":
    app.run("127.0.0.1", 9002, debug=True, auto_reload=True)