1
0
mirror of https://github.com/GNS3/gns3-server synced 2024-11-25 01:38:08 +00:00
gns3-server/tests/handlers/api/base.py

153 lines
5.8 KiB
Python
Raw Normal View History

2015-01-14 00:26:24 +00:00
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
2015-01-20 12:04:20 +00:00
2015-01-14 00:26:24 +00:00
"""Base code use for all API tests"""
import json
import re
import asyncio
import aiohttp
import os
2015-01-14 00:26:24 +00:00
class Query:
"""
Helper to make query againt the test server
"""
2015-01-20 12:24:00 +00:00
def __init__(self, loop, host='localhost', port=8001, prefix='', api_version=None):
"""
2016-04-15 15:57:06 +00:00
:param prefix: Prefix added before path (ex: /compute)
:param api_version: Version of the api
"""
2015-01-14 00:26:24 +00:00
self._loop = loop
self._port = port
self._host = host
self._prefix = prefix
self._api_version = api_version
2016-03-17 14:15:30 +00:00
self._session = None
@asyncio.coroutine
def close(self):
yield from self._session.close()
2015-01-14 00:26:24 +00:00
def post(self, path, body={}, **kwargs):
2015-01-14 00:26:24 +00:00
return self._fetch("POST", path, body, **kwargs)
2015-01-21 20:46:16 +00:00
def put(self, path, body={}, **kwargs):
return self._fetch("PUT", path, body, **kwargs)
2015-01-14 00:26:24 +00:00
def get(self, path, **kwargs):
return self._fetch("GET", path, **kwargs)
2015-01-16 20:39:58 +00:00
def delete(self, path, **kwargs):
return self._fetch("DELETE", path, **kwargs)
def get_url(self, path):
if self._api_version is None:
return "http://{}:{}{}{}".format(self._host, self._port, self._prefix, path)
return "http://{}:{}/v{}{}{}".format(self._host, self._port, self._api_version, self._prefix, path)
2015-01-14 00:26:24 +00:00
2016-03-17 14:15:30 +00:00
def websocket(self, path):
"""
Return a websocket connected to the path
"""
self._session = aiohttp.ClientSession()
2016-03-17 14:16:09 +00:00
2016-03-17 14:15:30 +00:00
@asyncio.coroutine
def go_request(future):
response = yield from self._session.ws_connect(self.get_url(path))
future.set_result(response)
future = asyncio.Future()
asyncio.ensure_future(go_request(future))
2016-03-17 14:15:30 +00:00
self._loop.run_until_complete(future)
return future.result()
def _fetch(self, method, path, body=None, **kwargs):
2015-01-14 00:26:24 +00:00
"""Fetch an url, parse the JSON and return response
Options:
- example if True the session is included inside documentation
- raw do not JSON encode the query
"""
return self._loop.run_until_complete(asyncio.ensure_future(self._async_fetch(method, path, body=body, **kwargs)))
2017-05-16 17:28:47 +00:00
@asyncio.coroutine
def _async_fetch(self, method, path, body=None, **kwargs):
2015-01-14 00:26:24 +00:00
if body is not None and not kwargs.get("raw", False):
body = json.dumps(body)
2017-05-16 17:28:47 +00:00
connector = aiohttp.TCPConnector()
response = yield from aiohttp.request(method, self.get_url(path), data=body, loop=self._loop, connector=connector)
response.body = yield from response.read()
x_route = response.headers.get('X-Route', None)
if x_route is not None:
response.route = x_route.replace("/v{}".format(self._api_version), "")
response.route = response.route .replace(self._prefix, "")
2015-01-14 00:26:24 +00:00
2016-04-15 15:57:06 +00:00
response.json = {}
response.html = ""
2015-01-14 00:26:24 +00:00
if response.body is not None:
if response.headers.get("CONTENT-TYPE", "") == "application/json":
try:
response.json = json.loads(response.body.decode("utf-8"))
except ValueError:
response.json = None
else:
try:
response.html = response.body.decode("utf-8")
except UnicodeDecodeError:
response.html = None
2016-04-15 15:57:06 +00:00
if kwargs.get('example') and os.environ.get("PYTEST_BUILD_DOCUMENTATION") == "1":
self._dump_example(method, response.route, path, body, response)
2015-01-14 00:26:24 +00:00
return response
def _dump_example(self, method, route, path, body, response):
2015-01-14 00:26:24 +00:00
"""Dump the request for the documentation"""
if path is None:
return
with open(self._example_file_path(method, route), 'w+') as f:
2016-04-08 15:40:27 +00:00
f.write("curl -i -X {} 'http://localhost:3080/v{}{}{}'".format(method, self._api_version, self._prefix, path))
2015-01-14 00:26:24 +00:00
if body:
f.write(" -d '{}'".format(re.sub(r"\n", "", json.dumps(json.loads(body), sort_keys=True))))
f.write("\n\n")
f.write("{} /v{}{}{} HTTP/1.1\n".format(method, self._api_version, self._prefix, path))
2015-01-14 00:26:24 +00:00
if body:
f.write(json.dumps(json.loads(body), sort_keys=True, indent=4))
f.write("\n\n\n")
f.write("HTTP/1.1 {}\n".format(response.status))
for header, value in sorted(response.headers.items()):
if header == 'DATE':
# We fix the date otherwise the example is always different and create change in git
2015-01-14 00:26:24 +00:00
value = "Thu, 08 Jan 2015 16:09:15 GMT"
f.write("{}: {}\n".format(header, value))
f.write("\n")
if response.body:
f.write(json.dumps(json.loads(response.body.decode('utf-8')), sort_keys=True, indent=4))
f.write("\n")
2015-01-14 00:26:24 +00:00
def _example_file_path(self, method, path):
path = re.sub('[^a-z0-9]', '', path)
2016-03-11 16:20:09 +00:00
if len(self._prefix) > 0:
prefix = self._prefix.replace('/', '')
return "docs/api/examples/{}_{}_{}.txt".format(prefix, method.lower(), path)
else:
return "docs/api/examples/controller_{}_{}.txt".format(method.lower(), path)