Last active
December 7, 2023 11:56
-
-
Save BharatKalluri/b627551bb2e04fbef0ce14ff1e4402d7 to your computer and use it in GitHub Desktop.
generate tests from har
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
import itertools | |
import json | |
import os.path | |
import sys | |
from urllib.parse import urlparse | |
from haralyzer import HarParser, HarPage, HarEntry | |
def filter_fn(entry: HarEntry): | |
return ("-api.refyne" in entry.request.url) and ( | |
entry.request.method.lower() in ["post", "get"] | |
) | |
def convert_camel_case(words: list[str]): | |
return "".join(word.capitalize() if i > 0 else word for i, word in enumerate(words)) | |
def generate_test(har_entry: HarEntry): | |
url_components = urlparse(har_entry.request.url) | |
url_path = url_components.path | |
url_bread_crumbs = list( | |
itertools.chain(*[el.split("-") for el in url_path.split("/")]) | |
) | |
possible_var_name = convert_camel_case( | |
[ | |
*([el for el in url_bread_crumbs if len(el) > 0]), | |
har_entry.request.method.lower(), | |
] | |
) | |
make_req_params = { | |
"method": har_entry.request.method.lower(), | |
"url": url_path, | |
"data": json.loads(har_entry.request.text) if har_entry.request.text else None, | |
} | |
response_json = ( | |
json.loads(har_entry.response.text) | |
if har_entry.response.mimeType == "application/json" | |
else har_entry.response.text | |
) | |
test_template = f""" | |
const {possible_var_name} = await userClient.makeHttpRequest({json.dumps(make_req_params)}); | |
const {possible_var_name}Res = await {possible_var_name}.json() | |
expect({possible_var_name}.status()).toEqual({har_entry.response.status}) | |
expect({possible_var_name}Res).toMatchObject({json.dumps(response_json)}) | |
""" | |
print(test_template) | |
def test_gen(har_file_path: str): | |
har_parser = HarParser.from_file(os.path.expanduser(har_file_path)) | |
pages: list[HarPage] = [el for el in har_parser.pages] | |
entries: list[HarEntry] = list(itertools.chain(*[el.entries for el in pages])) | |
filtered_entries = [el for el in entries if filter_fn(el)] | |
for e in filtered_entries: | |
generate_test(e) | |
if __name__ == "__main__": | |
if len(sys.argv) != 2: | |
print("Usage: python test_gen_from_har.py <file_path>") | |
sys.exit(1) | |
file_path = sys.argv[1] | |
test_gen(har_file_path=file_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment