freechat/json-api/client-tests/request.py
shockrah e8348918c4 + More qol like better __str__ methods everywhere
+ More error handling in case shit goes wrong
Basically handling more cases where some initial test could result in the whole
script exiting with code(1)
Not really that big of a deal since most tests after _that_ point will fail anyway
but the fix has revealed issues in the auth code magically so I'm keeping up with the new idea
that initial tests should have every resultant case validated to avoid weird behavior

> good code results in good results
who would have guessed
2021-05-08 02:07:32 -07:00

83 lines
2.7 KiB
Python

from requests import Session
import requests
NC = '\033[0m'
RED = '\033[1;31m'
GREEN = '\033[1;32m'
YELLOW = '\033[1;33m'
class Request:
def __init__(self, url: str, method: str, qs: dict, headers: dict, hope: int, body=None, verbose=False):
self.method = method
self.url = url
# query string parameters are appended to the url which is why we do this
self.qs = qs
self.headers = headers
self.body = body
self.response = None
self.hope = hope
# This flag lets us control how much output we want to see
self.verbose = verbose
def __str__(self):
return str(self.qs)
@property
def passing(self):
if self.response is None:
return False
else:
return self.response.status_code == self.hope
def fire(self) -> requests.Response:
try:
if self.method == 'get':
self.response = requests.get(self.url, headers=self.headers, params=self.qs)
elif self.method == 'post':
self.response = requests.post(self.url, headers=self.headers, params=self.qs, data=self.body)
elif self.method == 'delete':
self.response = requests.delete(self.url, headers=self.headers, params=self.qs)
return self.response
except Exception as e:
print(e)
return None
def show_response(self):
if self.response is None:
print('Response := None')
return
real_code = self.response.status_code
if self.hope != real_code:
abstract = RED + 'Fail ' + NC + 'Expected ' + str(self.hope) + ' Got ' + str(real_code)
print(abstract)
print('\t', self.method, ' ', self.url)
if len(self.headers) != 0:
print(YELLOW + '\tRequest-Headers ' + NC, self.headers)
if len(self.qs) != 0:
print(YELLOW + '\tQuery-Dictionary' + NC, self.qs)
if self.body is not None:
print(YELLOW + '\tRequest-Body' + NC, str(self.body))
if self.verbose:
print(f'\t{YELLOW}Response-Status{NC} {self.response.status_code}')
print(f'\t{YELLOW}Response-Headers{NC} {self.response.headers}')
print(f'\t{YELLOW}Response-Text{NC} {self.response.text}')
else:
print(f'{GREEN}Pass{NC} {self.method} {self.url}')
if self.verbose:
print(f'\t{YELLOW}Response-Status{NC} {self.response.status_code}')
print(f'\t{YELLOW}Response-Headers{NC} {self.response.headers}')
print(f'\t{YELLOW}Response-Text{NC} {self.response.text}')