Last active
April 15, 2024 10:28
-
-
Save xbns/9a4dc95465ea75f98e7ed197056e582b to your computer and use it in GitHub Desktop.
#tech
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
__author_ = "Josphat Mutuku" | |
__date__ ="2019-07-03" | |
""" | |
import requests | |
import unittest | |
import json | |
import ijson | |
USERS_URL = 'http://jsonplaceholder.typicode.com/users' | |
def get_users(): | |
# Do a GET request to the /users endpoint | |
response = requests.get(USERS_URL) | |
if response.ok: | |
return response | |
else: | |
return None | |
def parse_json(json_filename): | |
with open(json_filename, 'rb') as input_file: | |
# load json iteratively | |
parser = ijson.parse(input_file) | |
for prefix, event, value in parser: | |
print('prefix={}, event={}, value={}'.format(prefix, event, value)) | |
def extract_company_names(json_filename): | |
with open(json_filename, 'rb') as input_file: | |
company_names = ijson.items(input_file, 'item.company.name') | |
for name in company_names: | |
if name.endswith('Group'): | |
print('Company Name: {}'.format(name)) | |
class APITests(unittest.TestCase): | |
# Validate the response to be 200 OK | |
def test_response_status(self): | |
response = get_users() | |
print(response.status_code) | |
self.assertEqual(response.status_code, 200) | |
# Validate the response to be less than 200ms | |
def test_response_time(self): | |
responseTime = get_users().elapsed.total_seconds() | |
print(responseTime) | |
# 200milliseconds = 0.2 seconds | |
self.assertLess(responseTime,0.2) | |
""" Iterate over all elements of the json response body | |
& print out company names ending in "Group" | |
""" | |
def test_print_company_names_ending_with_group(self): | |
# users = json.loads(get_users().content) | |
with open('./users.json', mode='wb') as json_filename: | |
json_filename.write(get_users().content) | |
json_filename.close() | |
extract_company_names('./users.json') | |
# self.assertIsNotNone(company_names) | |
if __name__ == "__main__": | |
unittest.main() | |
""" | |
Usage: | |
$ python users.py | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment