Skip to content

Commit cd922c3

Browse files
committed
black reformat
1 parent 3b2fd36 commit cd922c3

File tree

10 files changed

+73
-106
lines changed

10 files changed

+73
-106
lines changed

lib/pbench/server/api/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,9 @@ def create_app():
127127
# JWT specific configuration
128128
app.config["JWT_SECRET_KEY"] = os.getenv("SECRET_KEY", "my_precious")
129129
app.config["BCRYPT_LOG_ROUNDS"] = int(app.config_server.get("bycrypt_log_rounds"))
130-
app.config["TOKEN_EXPIRATION_DURATION"] = app.config_server.get("token_expiration_duration")
130+
app.config["TOKEN_EXPIRATION_DURATION"] = app.config_server.get(
131+
"token_expiration_duration"
132+
)
131133

132134
app.bcrypt = Bcrypt(app)
133135

lib/pbench/server/api/resources/alembic/env.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,7 @@ def run_migrations_online():
6464
)
6565

6666
with connectable.connect() as connection:
67-
context.configure(
68-
connection=connection, target_metadata=target_metadata
69-
)
67+
context.configure(connection=connection, target_metadata=target_metadata)
7068

7169
with context.begin_transaction():
7270
context.run_migrations()

lib/pbench/server/api/resources/elasticsearch_api.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
import requests
32
from flask_restful import Resource, abort
43
from flask import request, make_response

lib/pbench/server/api/resources/graphql_api.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
import requests
32
from flask_restful import Resource, abort
43
from flask import request, make_response
@@ -7,15 +6,14 @@
76

87
class GraphQL(Resource):
98
"""GraphQL API for post request via server."""
9+
1010
def __init__(self, app, api):
1111
self.app = app
1212
self.api = api
1313

1414
@cross_origin()
1515
def post(self):
16-
graphQL = (
17-
f"http://{self.app.config_graphql.get('host')}:{self.app.config_graphql.get('port')}"
18-
)
16+
graphQL = f"http://{self.app.config_graphql.get('host')}:{self.app.config_graphql.get('port')}"
1917
json_data = request.get_json(silent=True)
2018

2119
if not json_data:
@@ -26,22 +24,30 @@ def post(self):
2624
# query GraphQL
2725
gql_response = requests.post(graphQL, json=json_data)
2826
except requests.exceptions.ConnectionError:
29-
self.app.logger.exception("Connection refused during the GraphQL post request")
27+
self.app.logger.exception(
28+
"Connection refused during the GraphQL post request"
29+
)
3030
abort(502, message="Network problem, could not post to GraphQL Endpoint")
3131
except requests.exceptions.Timeout:
32-
self.app.logger.exception("Connection timed out during the GraphQL post request")
32+
self.app.logger.exception(
33+
"Connection timed out during the GraphQL post request"
34+
)
3335
abort(
3436
504, message="Connection timed out, could not post to GraphQL Endpoint"
3537
)
3638
except Exception:
37-
self.app.logger.exception("Exception occurred during the GraphQL post request")
39+
self.app.logger.exception(
40+
"Exception occurred during the GraphQL post request"
41+
)
3842
abort(500, message="INTERNAL ERROR")
3943

4044
try:
4145
# construct response object
4246
response = make_response(gql_response.text)
4347
except Exception:
44-
self.app.logger.exception("Exception occurred GraphQL response construction")
48+
self.app.logger.exception(
49+
"Exception occurred GraphQL response construction"
50+
)
4551
abort(
4652
500, message="INTERNAL ERROR",
4753
)

lib/pbench/server/api/resources/models.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,15 @@ def encode_auth_token(self, app, user_id):
4242
# Expiration is not defined, token is set to expire in a second
4343
payload = {
4444
"iat": datetime.datetime.utcnow(),
45-
"exp": datetime.datetime.utcnow() + datetime.timedelta(
46-
milliseconds=100),
45+
"exp": datetime.datetime.utcnow()
46+
+ datetime.timedelta(milliseconds=100),
4747
"sub": user_id,
4848
}
4949
else:
5050
payload = {
5151
"iat": datetime.datetime.utcnow(),
52-
"exp": datetime.datetime.utcnow() + datetime.timedelta(
53-
minutes=int(expire)),
52+
"exp": datetime.datetime.utcnow()
53+
+ datetime.timedelta(minutes=int(expire)),
5454
"sub": user_id,
5555
}
5656
try:

lib/pbench/server/api/resources/pbench_users.py

Lines changed: 38 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -102,26 +102,30 @@ def post(self):
102102
db_session.add(user)
103103
db_session.commit()
104104
self.app.logger.info(
105-
f"New user registered, Name: {user_data.get('firstName')} {user_data.get('lastName')}, "
106-
f"username: {user_data.get('username')}, email: {email}"
105+
f"New user registered, Name: {user_data.get('firstName')} {user_data.get('lastName')} username: {user_data.get('username')}, email: {email}"
107106
)
108107

109108
# generate the auth token
110109
auth_token = user.encode_auth_token(self.app, user.id)
111110
if not auth_token:
112-
self.app.logger.info(f"User registered but unable to encode the auth token. username {user_data.get('username')}")
113-
return make_response("{'message':'Registered but unable to encode the auth token, please try logging in}", 500)
111+
self.app.logger.info(
112+
f"User registered but unable to encode the auth token. username {user_data.get('username')}"
113+
)
114+
return make_response(
115+
"{'message':'Registered but unable to encode the auth token, please try logging in}",
116+
500,
117+
)
114118

115119
self.app.logger.info(auth_token.decode())
116120
response_object = {
117-
'status': 'success',
118-
'message': 'Successfully registered.',
119-
'auth_token': auth_token.decode()
121+
"status": "success",
122+
"message": "Successfully registered.",
123+
"auth_token": auth_token.decode(),
120124
}
121125
response = jsonify(response_object)
122126
response.status_code = 201
123127
return make_response(response, 201)
124-
#return Response(response_object, status=201, mimetype="application/json")
128+
# return Response(response_object, status=201, mimetype="application/json")
125129

126130
except (
127131
SQLAlchemyError,
@@ -189,14 +193,18 @@ def post(self):
189193

190194
try:
191195
# fetch the user data
192-
user = db_session.query(UserModel).filter_by(username=post_data.get("username")).first()
196+
user = (
197+
db_session.query(UserModel)
198+
.filter_by(username=post_data.get("username"))
199+
.first()
200+
)
193201
except (
194-
SQLAlchemyError,
195-
DataError,
196-
DatabaseError,
197-
DBAPIError,
198-
CompileError,
199-
) as e:
202+
SQLAlchemyError,
203+
DataError,
204+
DatabaseError,
205+
DBAPIError,
206+
CompileError,
207+
) as e:
200208
self.app.logger.error(
201209
f"Some SQLAlchemy error occurred while logging in a user {e.__dict__['orig']}"
202210
)
@@ -230,9 +238,9 @@ def post(self):
230238
abort(500, message="Auth token encoding failed please try again")
231239

232240
response_object = {
233-
'status': 'success',
234-
'message': 'Successfully logged in.',
235-
'auth_token': auth_token.decode(),
241+
"status": "success",
242+
"message": "Successfully logged in.",
243+
"auth_token": auth_token.decode(),
236244
}
237245
return make_response(jsonify(response_object), 200)
238246

@@ -291,8 +299,8 @@ def delete(self):
291299
# Add the token to the blacklist
292300
self.app.blacklist.add(auth_token)
293301
response_object = {
294-
'status': 'success',
295-
'message': 'Successfully logged out.',
302+
"status": "success",
303+
"message": "Successfully logged out.",
296304
}
297305
return make_response(jsonify(response_object), 200)
298306

@@ -380,17 +388,15 @@ def get(self, username):
380388
self.app.logger.info(
381389
f"Username retrieved from the auth token {user_id} is different for the username provided"
382390
)
383-
abort(
384-
403, message="Authentication token does not belong to the user"
385-
)
391+
abort(403, message="Authentication token does not belong to the user")
386392

387393
response_object = {
388-
'status': 'success',
389-
'data': {
390-
'email': user.email,
391-
'firstName': user.firstName,
392-
'lastName': user.lastName,
393-
'registered_on': user.registered_on,
394+
"status": "success",
395+
"data": {
396+
"email": user.email,
397+
"firstName": user.firstName,
398+
"lastName": user.lastName,
399+
"registered_on": user.registered_on,
394400
},
395401
}
396402
return make_response(jsonify(response_object), 200)
@@ -449,8 +455,7 @@ def delete(self, username):
449455
f"Token expired, Could not decode the auth token: {auth_token} for user {user_id}"
450456
)
451457
abort(
452-
401,
453-
message="Token expired, please log back in",
458+
401, message="Token expired, please log back in",
454459
)
455460

456461
try:
@@ -487,7 +492,7 @@ def delete(self, username):
487492
abort(500, message="There was something wrong deleting, please try again")
488493

489494
response_object = {
490-
'status': 'success',
491-
'message': 'Successfully deleted.',
495+
"status": "success",
496+
"message": "Successfully deleted.",
492497
}
493498
return make_response(jsonify(response_object), 200)

lib/pbench/server/api/resources/upload_api.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
import os
32
import humanize
43
import tempfile
@@ -25,7 +24,9 @@ def get(self):
2524
)
2625
)
2726
except Exception:
28-
self.app.logger.exception("There was something wrong constructing the host info")
27+
self.app.logger.exception(
28+
"There was something wrong constructing the host info"
29+
)
2930
abort(500, message="There was something wrong with your request")
3031
response.status_code = 200
3132
return response

lib/pbench/test/unit/server/test_requests.py

Lines changed: 0 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -9,54 +9,12 @@
99
from werkzeug.utils import secure_filename
1010

1111

12-
def register_user(client, email, username, password, firstname, lastname):
13-
return client.post(
14-
f"{client.config['REST_URI']}/user",
15-
data=json.dumps(dict(
16-
email=email,
17-
password=password,
18-
username=username,
19-
firstName=firstname,
20-
lastName=lastname
21-
)),
22-
content_type='application/json',
23-
)
24-
25-
26-
def login_user(client, username, password):
27-
return client.post(
28-
f"{client.config['REST_URI']}/session",
29-
data=json.dumps(dict(
30-
username=username,
31-
password=password
32-
)),
33-
content_type='application/json',
34-
)
35-
3612
@pytest.fixture
3713
def mocked_responses():
3814
with responses.RequestsMock() as rsps:
3915
yield rsps
4016

4117

42-
class TestRegistration:
43-
@staticmethod
44-
def test_user_registration(client):
45-
response = register_user(client, username='user', firstname="firstname", lastname="lastName", email='[email protected]', password='12345')
46-
data = json.loads(response.data.decode())
47-
assert data["status"] == "success"
48-
49-
@staticmethod
50-
def test_user_login(client, pytestconfig, caplog):
51-
response = register_user(client, username='user', firstname="firstname", lastname="lastName",
52-
email='[email protected]', password='12345')
53-
data = json.loads(response.data.decode())
54-
assert data["status"] == "success"
55-
response = login_user(client, "user", "12345")
56-
data = json.loads(response.data.decode())
57-
assert data["status"] == "success"
58-
59-
6018
class TestHostInfo:
6119
@staticmethod
6220
def test_host_info(client, pytestconfig, caplog):

lib/pbench/test/unit/server/test_user_auth.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -297,15 +297,15 @@ def test_invalid_logout(client):
297297
password="12345",
298298
)
299299
data_register = json.loads(resp_register.data.decode())
300-
assert data_register['message'] == 'Successfully registered.'
301-
assert data_register['auth_token']
300+
assert data_register["message"] == "Successfully registered."
301+
assert data_register["auth_token"]
302302
assert resp_register.status_code == 201
303303
# user login
304304
resp_login = login_user(client, "username", "12345")
305305
data_login = json.loads(resp_login.data.decode())
306-
assert data_login['status'] == 'success'
307-
assert data_login['message'] == 'Successfully logged in.'
308-
assert data_login['auth_token']
306+
assert data_login["status"] == "success"
307+
assert data_login["message"] == "Successfully logged in."
308+
assert data_login["auth_token"]
309309
assert resp_login.status_code == 200
310310
# invalid token logout
311311
time.sleep(1)
@@ -314,7 +314,7 @@ def test_invalid_logout(client):
314314
headers=dict(Authorization="Bearer " + data_login["auth_token"]),
315315
)
316316
data = json.loads(response.data.decode())
317-
assert data['message'] == 'Token expired, please log back in'
317+
assert data["message"] == "Token expired, please log back in"
318318
assert response.status_code == 401
319319

320320
@staticmethod
@@ -330,16 +330,13 @@ def test_delete_user(client):
330330
password="12345",
331331
)
332332
data_register = json.loads(resp_register.data.decode())
333-
assert data_register['message'] == 'Successfully registered.'
334-
assert data_register['auth_token']
333+
assert data_register["message"] == "Successfully registered."
334+
assert data_register["auth_token"]
335335

336336
response = client.delete(
337337
f"{client.config['REST_URI']}/user/username",
338338
headers=dict(Authorization="Bearer " + data_register["auth_token"]),
339339
)
340340
data = json.loads(response.data.decode())
341-
assert (
342-
data["message"]
343-
== 'Successfully deleted.'
344-
)
341+
assert data["message"] == "Successfully deleted."
345342
assert response.status_code == 200

server/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ boto3
22
elasticsearch1==1.10.0
33
email-validator
44
flask
5+
flask-bcrypt
56
flask-restful
67
flask-cors
78
flask-jwt-extended

0 commit comments

Comments
 (0)