Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_authentication(self):
"""Test whether the client authenticates on a SortingHat server"""
MockSortingHatServer(SORTINGHAT_SERVER_URL)
client = SortingHatClient('localhost', user='admin', password='admin', ssl=False)
client.connect()
self.assertIsInstance(client.gqlc, sgqlc.endpoint.http.HTTPEndpoint)
latest_requests = httpretty.latest_requests()
self.assertEqual(len(latest_requests), 2)
request = latest_requests[0]
self.assertEqual(request.method, 'GET')
self.assertEqual(dict(request.headers)['Host'], 'localhost:9314')
request = latest_requests[1]
self.assertEqual(request.method, 'POST')
self.assertEqual(dict(request.headers)['Host'], 'localhost:9314')
# Connection was established and authorization was completed
expected = {
'Authorization': 'JWT 12345678',
'X-CSRFToken': 'ABCDEFGHIJK',
def test_connect(self):
"""Test whether the client establishes a connection with a SortingHat server"""
MockSortingHatServer(SORTINGHAT_SERVER_URL)
client = SortingHatClient('localhost', ssl=False)
client.connect()
self.assertIsInstance(client.gqlc, sgqlc.endpoint.http.HTTPEndpoint)
latest_requests = httpretty.latest_requests()
self.assertEqual(len(latest_requests), 1)
request = latest_requests[0]
self.assertEqual(request.method, 'GET')
headers = dict(request.headers)
self.assertEqual(headers['Host'], 'localhost:9314')
self.assertEqual(headers['Accept'], 'text/html')
# Connection was established and tokens set
expected = {
'X-CSRFToken': 'ABCDEFGHIJK',
'Cookie': 'csrftoken=ABCDEFGHIJK'
}
def test_server_http_non_conforming_json(mock_urlopen):
'Test if HTTP error that is NOT conforming to GraphQL payload is handled'
err = urllib.error.HTTPError(
test_url,
500,
'Some Error',
{'Content-Type': 'application/json'},
io.BytesIO(b'{"message": "xpto"}'),
)
configure_mock_urlopen(mock_urlopen, err)
endpoint = HTTPEndpoint(test_url)
data = endpoint(graphql_query)
eq_(data, {
'errors': [{
'message': str(err),
'exception': err,
'status': 500,
'headers': {'Content-Type': 'application/json'},
'body': '{"message": "xpto"}',
}],
'data': None,
})
check_mock_urlopen(mock_urlopen)
def test_server_http_error_string_list(mock_urlopen):
'Test if HTTP error that a JSON error string list is handled'
err = urllib.error.HTTPError(
test_url,
500,
'Some Error',
{'Content-Type': 'application/json'},
io.BytesIO(b'{"errors": ["a", "b"]}'),
)
configure_mock_urlopen(mock_urlopen, err)
endpoint = HTTPEndpoint(test_url)
data = endpoint(graphql_query)
expected_data = {'errors': [{'message': 'a'}, {'message': 'b'}]}
expected_data.update({
'exception': err,
'status': 500,
'headers': {'Content-Type': 'application/json'},
})
eq_(data, expected_data)
check_mock_urlopen(mock_urlopen)
endpoint_loglevel = max(10, 40 - ((args.verbose - 3) * 10))
logfmt = '%(levelname)s: %(message)s'
if endpoint_loglevel < logging.ERROR:
logfmt = '%(levelname)s:%(name)s: %(message)s'
logging.basicConfig(format=logfmt, level=max(10, 40 - (args.verbose * 10)))
HTTPEndpoint.logger.setLevel(endpoint_loglevel)
graphql_endpoint = (args.graphql_endpoint or cfg['graphql-endpoint']
or DEFAULT_GRAPHQL_ENDPOINT)
token = args.token or cfg['token']
if not token:
raise SystemExit('token must be provided. You may create an '
'app or personal token at '
'https://github.com/settings/tokens')
endpoint = HTTPEndpoint(graphql_endpoint, {
'Authorization': 'bearer ' + token,
})
if not args.command:
raise SystemExit('missing subcommand. See --help.')
args.func(endpoint, args)
ap.add_argument('--verbose', '-v',
help='Increase verbosity',
action='count',
default=0)
ap.add_argument('--method', '-m',
choices=['GET', 'POST'],
help='HTTP Method to use',
default='POST',
)
args = ap.parse_args()
logfmt = '%(levelname)s: %(message)s'
logging.basicConfig(format=logfmt, level=max(10, 40 - (args.verbose * 10)))
endpoint = HTTPEndpoint(args.url, dict(args.header), args.timeout,
method=args.method)
data = endpoint(args.query, dict(args.var))
json.dump(data, sys.stdout, sort_keys=True, indent=2, default=str)
sys.stdout.write('\n')
if data.get('errors'):
sys.exit(1)
)
logger.debug(
"Requesting NLG for {} from {}."
"".format(template_name, self.nlg_endpoint.url)
)
try:
if "graphql" in self.nlg_endpoint.url:
from sgqlc.endpoint.http import HTTPEndpoint
logging.getLogger("sgqlc.endpoint.http").setLevel(logging.WARNING)
api_key = os.environ.get("API_KEY")
headers = [{"Authorization": api_key}] if api_key else []
response = HTTPEndpoint(self.nlg_endpoint.url, *headers)(
NLG_QUERY, body
)
if response.get("errors"):
raise urllib.error.URLError(
", ".join([e.get("message") for e in response.get("errors")])
)
response = response.get("data", {}).get("getResponse", {})
if "customText" in response:
response["text"] = response.pop("customText")
if "customImage" in response:
response["image"] = response.pop("customImage")
if "customQuickReplies" in response:
response["quick_replies"] = response.pop("customQuickReplies")
if "customButtons" in response:
response["buttons"] = response.pop("customButtons")
if "customElements" in response:
def __init__(self, domain, url, **kwargs):
self.project_id = os.environ.get("BF_PROJECT_ID")
self.tracker_persist_time = kwargs.get("tracker_persist_time", 3600)
self.max_events = kwargs.get("max_events", 100)
self.trackers = {}
self.trackers_info = (
{}
) # in this stucture we will keep the last index and the last timestamp of events in the db for a said tracker
self.sweeper = Thread(target=_start_sweeper, args=(self, 30))
self.sweeper.setDaemon(True)
self.sweeper.start()
api_key = os.environ.get("API_KEY")
headers = [{"Authorization": api_key}] if api_key else []
self.graphql_endpoint = HTTPEndpoint(url, *headers)
self.url = url
self.environement = os.environ.get("BOTFRONT_ENV", "development")
super(BotfrontTrackerStore, self).__init__(domain)
logger.debug("BotfrontTrackerStore tracker store created")
def connect(self):
"""Establish a connection to the server."""
try:
result = requests.get(self.url, headers={'Accept': 'text/html'})
result.raise_for_status()
except requests.exceptions.RequestException as exc:
msg = "Connection error; cause: {}".format(exc)
raise SortingHatClientError(msg)
headers = {
'X-CSRFToken': result.cookies['csrftoken'],
'Cookie': 'csrftoken=' + result.cookies['csrftoken']
}
self.gqlc = HTTPEndpoint(self.url, headers)
if self.user and self.password:
op = Operation(sh_schema.SortingHatMutation)
op.token_auth(username=self.user, password=self.password).token()
result = self.gqlc(op)
if 'errors' in result:
cause = result['errors'][0]['message']
msg = "Authentication error; cause: {}".format(cause)
raise SortingHatClientError(msg)
auth_token = result['data']['tokenAuth']['token']
headers['Authorization'] = "JWT {}".format(auth_token)