Skip to content

Commit d2002c4

Browse files
style(): Follow PEP8 with consistent formatting (#6)
1 parent 97e84e8 commit d2002c4

File tree

5 files changed

+84
-83
lines changed

5 files changed

+84
-83
lines changed

src/create_mock_endpoints.py

Lines changed: 27 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,49 +4,51 @@
44

55

66
def slugify(value):
7-
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
8-
value = re.sub(r'[^\w\s-]', '', value).strip().lower()
9-
return re.sub(r'[-\s]+', '_', value)
7+
value = (
8+
unicodedata.normalize("NFKD", value).encode("ascii", "ignore").decode("ascii")
9+
)
10+
value = re.sub(r"[^\w\s-]", "", value).strip().lower()
11+
return re.sub(r"[-\s]+", "_", value)
1012

1113

1214
def generate_code_for_single_mock_api_route(endpoint_data):
13-
if not endpoint_data['endpoint'] or not endpoint_data['method']:
14-
return ''
15-
output_data = "@app.route('" + endpoint_data['endpoint'] + "'"
16-
output_data += ", methods=['" + endpoint_data['method'] + "'])\n"
17-
output_data += "def " + slugify(endpoint_data['description']) + "():\n"
18-
output_data += " return Response(json.dumps(" + str(
19-
json.dumps(endpoint_data['response_body'], sort_keys=True)) + "), "
15+
if not endpoint_data["endpoint"] or not endpoint_data["method"]:
16+
return ""
17+
output_data = "@app.route('" + endpoint_data["endpoint"] + "'"
18+
output_data += ", methods=['" + endpoint_data["method"] + "'])\n"
19+
output_data += "def " + slugify(endpoint_data["description"]) + "():\n"
20+
output_data += (
21+
" return Response(json.dumps("
22+
+ str(json.dumps(endpoint_data["response_body"], sort_keys=True))
23+
+ "), "
24+
)
2025
output_data += "mimetype='application/json; charset=utf-8')\n"
2126
output_data += "\n\n"
2227
return output_data
2328

2429

25-
def create_mock_api_endpoints(json_filename='endpoints_data.json', filename='app.py'):
30+
def create_mock_api_endpoints(json_filename="endpoints_data.json", filename="app.py"):
2631
data = None
27-
with open(json_filename, 'r') as json_file:
32+
with open(json_filename, "r") as json_file:
2833
data = json.load(json_file)
2934
generated_code_list = [
30-
'import json\n',
31-
'\n',
32-
'from flask import Flask, Response\n',
33-
'\n',
34-
'app = Flask(__name__)\n',
35-
'\n\n'
35+
"import json\n",
36+
"\n",
37+
"from flask import Flask, Response\n",
38+
"\n",
39+
"app = Flask(__name__)\n",
40+
"\n\n",
3641
]
3742
for endpoint_data in data:
3843
generated_code_list.append(
3944
generate_code_for_single_mock_api_route(endpoint_data)
4045
)
4146

42-
generated_code_list.extend([
43-
'if __name__ == "__main__":\n',
44-
' app.run()'
45-
])
46-
with open(filename, 'w') as outfile:
47-
outfile.write(''.join(generated_code_list))
47+
generated_code_list.extend(['if __name__ == "__main__":\n', " app.run()"])
48+
with open(filename, "w") as outfile:
49+
outfile.write("".join(generated_code_list))
4850
print("Run `python app.py` to host your app")
4951

5052

51-
if __name__ == '__main__':
53+
if __name__ == "__main__":
5254
create_mock_api_endpoints()

src/serialize_data.py

Lines changed: 31 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import json
22
import click
33

4-
HTTP_VERBS = ('GET', 'POST', 'HEAD', 'OPTIONS', 'PUT', 'PATCH', 'DELETE')
4+
HTTP_VERBS = ("GET", "POST", "HEAD", "OPTIONS", "PUT", "PATCH", "DELETE")
55

66

77
def get_single_endpoint_detail(lines):
@@ -10,38 +10,42 @@ def get_single_endpoint_detail(lines):
1010
"method": str(),
1111
"description": str(),
1212
"request_body": str(),
13-
"response_body": str()
13+
"response_body": str(),
1414
}
1515
lines_iterator = iter(lines)
1616
for line in lines_iterator:
17-
if not line or line == '```':
17+
if not line or line == "```":
1818
continue
19-
if line.startswith('##'):
20-
endpoint_details["description"] = line.split('## ')[1]
19+
if line.startswith("##"):
20+
endpoint_details["description"] = line.split("## ")[1]
2121
continue
2222
if line.startswith(HTTP_VERBS):
23-
method, endpoint = line.split(' ')[:2]
23+
method, endpoint = line.split(" ")[:2]
2424
endpoint_details["endpoint"] = endpoint
2525
endpoint_details["method"] = method
2626
continue
27-
if line.startswith('__Example__'):
27+
if line.startswith("__Example__"):
2828
json_data = parse_and_get_json_from_subsequent_lines(lines_iterator)
2929
try:
3030
endpoint_details["request_body"] = json.loads(json_data)
3131
except ValueError as e:
32-
print("Error in parsing request_body of {}: {}".format(
33-
endpoint_details['endpoint'], e)
32+
print(
33+
"Error in parsing request_body of {}: {}".format(
34+
endpoint_details["endpoint"], e
35+
)
3436
)
3537
print("Invalid JSON: {}".format(json_data))
3638
return None
3739
continue
38-
if line.startswith('__Response__'):
40+
if line.startswith("__Response__"):
3941
json_data = parse_and_get_json_from_subsequent_lines(lines_iterator)
4042
try:
4143
endpoint_details["response_body"] = json.loads(json_data)
4244
except ValueError as e:
43-
print("Error in parsing response_body of {}: {}".format(
44-
endpoint_details['endpoint'], e)
45+
print(
46+
"Error in parsing response_body of {}: {}".format(
47+
endpoint_details["endpoint"], e
48+
)
4549
)
4650
print("Invalid JSON: {}".format(json_data))
4751
return None
@@ -53,31 +57,31 @@ def parse_and_get_json_from_subsequent_lines(lines_iterator):
5357
try:
5458
next_line = next(lines_iterator)
5559
except StopIteration:
56-
return ''
57-
while next_line != '```json':
60+
return ""
61+
while next_line != "```json":
5862
try:
5963
next_line = next(lines_iterator)
6064
except StopIteration:
61-
return ''
65+
return ""
6266
# Skip the row having starting json tag
6367
next_line = next(lines_iterator)
6468
array_of_json_statements = list()
65-
while next_line != '```':
69+
while next_line != "```":
6670
array_of_json_statements.append(next_line)
6771
try:
6872
next_line = next(lines_iterator)
6973
except StopIteration:
7074
pass
7175

72-
json_statements = ''.join(array_of_json_statements)
76+
json_statements = "".join(array_of_json_statements)
7377
json_statements = json_statements.replace("...", "")
7478
return json_statements
7579

7680

7781
def get_json_from_endpoints(lines):
78-
all_lines = lines.split('\n')
82+
all_lines = lines.split("\n")
7983
next_endpoint_starting_location = [
80-
i for i, line in enumerate(all_lines) if line.startswith('##')
84+
i for i, line in enumerate(all_lines) if line.startswith("##")
8185
]
8286
endpoint_json_list = list()
8387
for x in range(len(next_endpoint_starting_location)):
@@ -95,16 +99,20 @@ def get_json_from_endpoints(lines):
9599

96100

97101
@click.command()
98-
@click.option('--file-path', default='proposed_endpoints.md', help='Path for the proposed endpoints docs')
102+
@click.option(
103+
"--file-path",
104+
default="proposed_endpoints.md",
105+
help="Path for the proposed endpoints docs",
106+
)
99107
def generate_json_from_docs_file(file_path):
100108
lines = None
101-
with open(file_path, 'r') as endpoint_file:
109+
with open(file_path, "r") as endpoint_file:
102110
lines = endpoint_file.read()
103111
json_data = get_json_from_endpoints(lines)
104112

105-
with open('endpoints_data.json', 'w') as json_file:
113+
with open("endpoints_data.json", "w") as json_file:
106114
json.dump(json_data, json_file, indent=4)
107115

108116

109-
if __name__ == '__main__':
117+
if __name__ == "__main__":
110118
generate_json_from_docs_file()

tests/test_data_serialization.py

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,32 +6,30 @@
66
from src.serialize_data import get_json_from_endpoints
77

88

9-
@pytest.mark.datafiles(
10-
os.path.join(FIXTURE_DIR, 'proposed_endpoints.md'),
11-
)
9+
@pytest.mark.datafiles(os.path.join(FIXTURE_DIR, "proposed_endpoints.md"))
1210
def test_data_serialization(datafiles):
1311
lines = datafiles.listdir()[0].read()
1412

1513
json_data = json.dumps(get_json_from_endpoints(lines), sort_keys=True)
1614

17-
expected_json = json.dumps([
18-
{
19-
"description": "Login to the app",
20-
"request_body": {
21-
"email": "[email protected]",
22-
"password": "123456"
23-
},
24-
"response_body": {
25-
"email": "[email protected]",
26-
"last_name": "Doe",
27-
"first_name": "John",
28-
"auth_token": "qduvpuMvqZUx4Emcpevp.RaGnPgoGZKvGBUHDuivwkvFQowYcwFq.FUGArGvzzfeGe",
29-
"phone_number": "+123423423423",
30-
"id": "e59d2c4f-ef3f-4455-aa41-c70af8c4e2df"
31-
},
32-
"endpoint": "/api/users/login",
33-
"method": "POST"
34-
}
35-
], sort_keys=True)
15+
expected_json = json.dumps(
16+
[
17+
{
18+
"description": "Login to the app",
19+
"request_body": {"email": "[email protected]", "password": "123456"},
20+
"response_body": {
21+
"email": "[email protected]",
22+
"last_name": "Doe",
23+
"first_name": "John",
24+
"auth_token": "qduvpuMvqZUx4Emcpevp.RaGnPgoGZKvGBUHDuivwkvFQowYcwFq.FUGArGvzzfeGe",
25+
"phone_number": "+123423423423",
26+
"id": "e59d2c4f-ef3f-4455-aa41-c70af8c4e2df",
27+
},
28+
"endpoint": "/api/users/login",
29+
"method": "POST",
30+
}
31+
],
32+
sort_keys=True,
33+
)
3634

3735
assert json_data == expected_json

tests/test_mock_endpoint_creation.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,21 @@
66
from src.create_mock_endpoints import generate_code_for_single_mock_api_route
77

88

9-
@pytest.mark.datafiles(
10-
os.path.join(FIXTURE_DIR, 'endpoints_data.json'),
11-
)
9+
@pytest.mark.datafiles(os.path.join(FIXTURE_DIR, "endpoints_data.json"))
1210
def test_generated_code_from_serialization(datafiles):
1311
data = datafiles.listdir()[0].read()
1412

1513
json_data = json.loads(data)
1614
for each_endpoint in json_data:
17-
generated_code = generate_code_for_single_mock_api_route(
18-
each_endpoint
19-
)
15+
generated_code = generate_code_for_single_mock_api_route(each_endpoint)
2016
expected_response = str(
21-
u'@app.route(\'/api/users/login\', methods=[\'POST\'])'
22-
'\ndef login_to_the_app():\n return Response('
17+
u"@app.route('/api/users/login', methods=['POST'])"
18+
"\ndef login_to_the_app():\n return Response("
2319
'json.dumps({"auth_token": "qduvpuMvqZUx4Emcpevp.RaGnPgoGZKvGBUHDuiv'
2420
'wkvFQowYcwFq.FUGArGvzzfeGe", "email": "[email protected]", '
2521
'"first_name": "John", "id": "e59d2c4f-ef3f-4455-aa41-c70af8c4e2df"'
2622
', "last_name": "Doe", "phone_number": "+123423423423"}), '
27-
'mimetype=\'application/json; charset=utf-8\')\n\n\n'
23+
"mimetype='application/json; charset=utf-8')\n\n\n"
2824
)
2925

3026
assert generated_code == expected_response

tests/utils.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
import os
22

33

4-
FIXTURE_DIR = os.path.join(
5-
os.path.dirname(os.path.realpath(__file__)),
6-
'test_files',
7-
)
4+
FIXTURE_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_files")

0 commit comments

Comments
 (0)