Skip to content

Commit

Permalink
feat(Quality): Add Quality Tools: Black (#5)
Browse files Browse the repository at this point in the history
Reformat code style.

PR: #5
  • Loading branch information
mohnoor94 authored Jan 15, 2023
1 parent a48a6d1 commit f121310
Show file tree
Hide file tree
Showing 19 changed files with 165 additions and 150 deletions.
5 changes: 4 additions & 1 deletion .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ extend-exclude = venv*,*lib,*test

max-line-length = 160
max-doc-length = 160
indent-size = 2
indent-size = 4
show_source = True
statistics = True
count = True
Expand All @@ -13,7 +13,10 @@ ignore =
D204
D401
E126
E203
W503

require-plugins =
flake8-black
flake8-bugbear
flake8-isort
8 changes: 5 additions & 3 deletions QUALITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
To run the code quality checks, run the following command:

```bash
flake8
flake8 openworld/ generator/
```

### Fixing Code Quality Issues

- If you have `isort` installed, you can run `isort .` to automatically fix import order issues.
- You can run `isort openworld/ generator/` to automatically fix import order issues.
- `flake8` will report `isort` related issues as `I` errors.
- You may fix other issues manually.
- You can run `black openworld/ generator/` to automatically fix formatting issues.
- `flake8` will report `black` related issues as `BLK` errors.
- You may fix other issues manually.
41 changes: 18 additions & 23 deletions generator/scripts/add-imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,17 @@ def prepend(filename: str, line: str) -> None:
:param line: the line to prepend
:return: none
"""
with open(filename, 'r+') as file_to_update:
with open(filename, "r+") as file_to_update:
content = file_to_update.read()
file_to_update.seek(0, 0)
file_to_update.write(line.rstrip('\r\n') + '\n' + content)
file_to_update.write(line.rstrip("\r\n") + "\n" + content)


def get_class_definition(text: str):
text = text.strip() \
.removeprefix('class') \
.removesuffix(':') \
.strip()
text = text.strip().removeprefix("class").removesuffix(":").strip()

if '(' in text:
text = text.rsplit('(')
if "(" in text:
text = text.rsplit("(")
text = text[0].strip()

return text
Expand All @@ -53,21 +50,19 @@ def get_class_definition(text: str):
print("Usage: >> python3 add-imports.py <path to directory>")
exit(1)

files = list(pathlib.Path(sys.argv[1]).glob('*.py'))
files = list(pathlib.Path(sys.argv[1]).glob("*.py"))

imports = {
'List': 'from typing import List',
'Optional': 'from typing import Optional',
'Union': 'from typing import Union',

'field': 'from dataclasses import field',
'dataclass': 'from dataclasses import dataclass',
'dataclass_json': 'from dataclasses_json import dataclass_json',
'config': 'from dataclasses_json import config',
'datetime': 'from datetime import datetime',
'platform': 'import platform',

'header': 'from openworld.sdk.core.constant import header',
"List": "from typing import List",
"Optional": "from typing import Optional",
"Union": "from typing import Union",
"field": "from dataclasses import field",
"dataclass": "from dataclasses import dataclass",
"dataclass_json": "from dataclasses_json import dataclass_json",
"config": "from dataclasses_json import config",
"datetime": "from datetime import datetime",
"platform": "import platform",
"header": "from openworld.sdk.core.constant import header",
}

for file in files:
Expand All @@ -81,9 +76,9 @@ def get_class_definition(text: str):
file_path = str(file)
with open(file) as f:
contents = pathlib.Path(file).read_text()
prepend(file_path, '\n\n\n')
prepend(file_path, "\n\n\n")
for k in imports.keys():
is_class_definition = (f'class {k}' in contents) and (k == get_class_definition(contents))
is_class_definition = (f"class {k}" in contents) and (k == get_class_definition(contents))
if k in contents and not is_class_definition:
print(f">> Adding import {k} to {file.name}")
prepend(file_path, imports[k])
10 changes: 6 additions & 4 deletions openworld/sdk/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@
from logging.config import fileConfig

try:
with open(file='logging.cfg', mode='r+') as f:
with open(file="logging.cfg", mode="r+") as f:
fileConfig(f)
except FileNotFoundError:
default_logger_handler = logging.StreamHandler()
default_formatter = logging.Formatter(fmt='[%(asctime)s] %(name)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
default_formatter = logging.Formatter(
fmt="[%(asctime)s] %(name)s %(levelname)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
default_logger_handler.setFormatter(default_formatter)

default_logger = logging.getLogger(name='openworld')
default_logger = logging.getLogger(name="openworld")
default_logger.addHandler(default_logger_handler)
default_logger.setLevel(level=logging.DEBUG)
20 changes: 13 additions & 7 deletions openworld/sdk/core/client/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def __init__(self, config: ClientConfig):
"""
self.__auth_client: _AuthClient = _AuthClient(
credentials=config.auth_config.credentials,
auth_endpoint=config.auth_config.auth_endpoint
auth_endpoint=config.auth_config.auth_endpoint,
)

self.endpoint = config.endpoint
Expand All @@ -51,16 +51,22 @@ def __build_response(response: requests.Response, response_model):
if response.status_code not in OK_STATUS_CODES_RANGE:
raise service_exception.OpenWorldServiceException.of(
error=Error.from_json(response.json()),
error_code=HTTPStatus(response.status_code)
error_code=HTTPStatus(response.status_code),
)

if response_model is None:
return None

return response_model.from_dict(response.json())

def call(self, method: str, url: str, obj: Any = None, request_headers: Optional[Dict] = None,
response_model: Optional[Any] = None) -> Any:
def call(
self,
method: str,
url: str,
obj: Any = None,
request_headers: Optional[Dict] = None,
response_model: Optional[Any] = None,
) -> Any:
r"""Sends HTTP request to API.
:param method: Http request method
Expand All @@ -84,7 +90,7 @@ def call(self, method: str, url: str, obj: Any = None, request_headers: Optional
method=method.upper(),
url=url,
headers=request_headers,
auth=auth_bearer
auth=auth_bearer,
)
else:
request_body = obj.to_json(default=ApiClient.__serialization_helper)
Expand All @@ -93,15 +99,15 @@ def call(self, method: str, url: str, obj: Any = None, request_headers: Optional
url=url,
headers=request_headers,
data=request_body,
auth=auth_bearer
auth=auth_bearer,
)

request_log_message = log_util.request_log(
headers=request_headers,
body=str(request_body),
endpoint=url,
method=method,
response=response
response=response,
)

LOG.info(log_constant.OPENWORLD_LOG_MESSAGE_TEMPLATE.format(request_log_message))
Expand Down
21 changes: 8 additions & 13 deletions openworld/sdk/core/client/auth_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,27 +45,22 @@ def __init__(self, credentials: Credentials, auth_endpoint: str = url_constant.A
def __retrieve_token(self, auth_endpoint: str = url_constant.AUTH_ENDPOINT) -> Response:
LOG.info(log_constant.OPENWORLD_LOG_MESSAGE_TEMPLATE.format(log_constant.TOKEN_RENEWAL_IN_PROCESS))

auth_method = HTTPBasicAuth(
username=self.__credentials.key,
password=self.__credentials.secret
)
auth_method = HTTPBasicAuth(username=self.__credentials.key, password=self.__credentials.secret)

response = post(
url=auth_endpoint,
auth=auth_method,
data=body_constant.TOKEN_REQUEST
)
response = post(url=auth_endpoint, auth=auth_method, data=body_constant.TOKEN_REQUEST)

if response.status_code not in OK_STATUS_CODES_RANGE:
raise service_exception.OpenWorldAuthException(message=UNABLE_TO_AUTHENTICATE,
error_code=HTTPStatus(response.status_code))
raise service_exception.OpenWorldAuthException(
message=UNABLE_TO_AUTHENTICATE,
error_code=HTTPStatus(response.status_code),
)

request_log_message = log_util.request_log(
headers=log_util.filter_credentials(auth_method.__dict__),
body=str(body_constant.TOKEN_REQUEST),
endpoint=auth_endpoint,
method='post',
response=response
method="post",
response=response,
)

LOG.info(log_constant.OPENWORLD_LOG_MESSAGE_TEMPLATE.format(request_log_message))
Expand Down
19 changes: 11 additions & 8 deletions openworld/sdk/core/configuration/auth_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@

@dataclass
class AuthConfig:
def __init__(self,
credentials: Credentials = DEFAULT_CREDENTIALS,
auth_endpoint: str = AUTH_ENDPOINT):
def __init__(
self,
credentials: Credentials = DEFAULT_CREDENTIALS,
auth_endpoint: str = AUTH_ENDPOINT,
):
r"""Holds authentication config data.
:param credentials: Client's credentials.
Expand All @@ -42,16 +44,17 @@ def __init__(self,
def __post_init__(self):
missing = list()

for attribute in [('Key', self.__credentials.key),
('Secret', self.__credentials.secret),
('Auth_Endpoint', self.__auth_endpoint)]:
for attribute in [
("Key", self.__credentials.key),
("Secret", self.__credentials.secret),
("Auth_Endpoint", self.__auth_endpoint),
]:

if not attribute[1]:
missing.append(attribute[0])

if len(missing):
raise client_exception.OpenWorldConfigurationException(
message=message.NONE_VALUE_NOT_ALLOWED_FOR_MESSAGE_TEMPLATE.format(f'{missing}'))
raise client_exception.OpenWorldConfigurationException(message=message.NONE_VALUE_NOT_ALLOWED_FOR_MESSAGE_TEMPLATE.format(f"{missing}"))

@property
def credentials(self) -> Credentials:
Expand Down
13 changes: 7 additions & 6 deletions openworld/sdk/core/configuration/client_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@
class ClientConfig:
__auth_config: AuthConfig = None

def __init__(self,
key: str,
secret: str,
endpoint: Optional[str] = url.ENDPOINT,
auth_endpoint: Optional[str] = url.AUTH_ENDPOINT
):
def __init__(
self,
key: str,
secret: str,
endpoint: Optional[str] = url.ENDPOINT,
auth_endpoint: Optional[str] = url.AUTH_ENDPOINT,
):
r"""SDK Client Configurations Holder.
:param key: The API key to use for authentication.
Expand Down
2 changes: 1 addition & 1 deletion openworld/sdk/core/constant/constant.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

EMPTY_STRING: str = ''
EMPTY_STRING: str = ""

REFRESH_TOKEN_TIME_GAP_IN_SECONDS: int = 10

Expand Down
23 changes: 10 additions & 13 deletions openworld/sdk/core/constant/header.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,24 @@

from typing import Dict

BEARER: str = 'Bearer '
BEARER: str = "Bearer "

AUTHORIZATION: str = 'Authorization'
AUTHORIZATION: str = "Authorization"

GRANT_TYPE: str = 'grant_type'
GRANT_TYPE: str = "grant_type"

CLIENT_CREDENTIALS: str = "client_credentials"

CONTENT_TYPE: str = 'Content-type'
CONTENT_TYPE: str = "Content-type"

JSON_CONTENT_TYPE: str = 'application/json'
JSON_CONTENT_TYPE: str = "application/json"

ACCEPT: str = 'Accept'
ACCEPT: str = "Accept"

TRANSACTION_ID: str = 'transaction-id'
TRANSACTION_ID: str = "transaction-id"

USER_AGENT: str = 'User-agent'
USER_AGENT: str = "User-agent"

OPENWORLD_SDK_PYTHON: str = 'open-world-sdk-python/'
OPENWORLD_SDK_PYTHON: str = "open-world-sdk-python/"

API_REQUEST: Dict = {
CONTENT_TYPE: JSON_CONTENT_TYPE,
ACCEPT: JSON_CONTENT_TYPE
}
API_REQUEST: Dict = {CONTENT_TYPE: JSON_CONTENT_TYPE, ACCEPT: JSON_CONTENT_TYPE}
31 changes: 19 additions & 12 deletions openworld/sdk/core/constant/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,33 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from textwrap import dedent

TOKEN_RENEWAL_IN_PROCESS: str = "Renewing token"

TOKEN_RENEWAL_SUCCESSFUL: str = "Token renewal successful"

TOKEN_EXPIRED: str = "Token expired or is about to expire, request will wait until token is renewed"

OPENWORLD_LOG_MESSAGE_TEMPLATE: str = 'ExpediaSDK: {0}'
OPENWORLD_LOG_MESSAGE_TEMPLATE: str = "ExpediaSDK: {0}"

UNSUCCESSFUL_RESPONSE_MESSAGE_TEMPLATE: str = 'Unsuccessful response [{0}]'
UNSUCCESSFUL_RESPONSE_MESSAGE_TEMPLATE: str = "Unsuccessful response [{0}]"

NEW_TOKEN_EXPIRATION_TEMPLATE: str = 'New token expires in {0} seconds'
NEW_TOKEN_EXPIRATION_TEMPLATE: str = "New token expires in {0} seconds"

HTTP_HEADERS_LOG_MESSAGE_TEMPLATE: str = '\tHeaders: \n' \
'\t--- BEGIN ---\n' \
'{0}' \
'\t--- END ---\n'
HTTP_HEADERS_LOG_MESSAGE_TEMPLATE: str = dedent(
"""\tHeaders:
\t--- BEGIN ---
{0}
\t--- END ---
"""
)

HTTP_BODY_LOG_MESSAGE_TEMPLATE: str = '\n\tBody: \n' \
'\t--- BEGIN ---\n' \
'{0}' \
'\t--- END ---\n'
HTTP_BODY_LOG_MESSAGE_TEMPLATE: str = dedent(
"""
\tBody:
\t--- BEGIN ---
{0}
\t--- END ---
"""
)
6 changes: 3 additions & 3 deletions openworld/sdk/core/constant/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.

UNABLE_TO_AUTHENTICATE: str = 'Unable to authenticate'
UNABLE_TO_AUTHENTICATE: str = "Unable to authenticate"

NONE_VALUE_NOT_ALLOWED = 'None value not allowed'
NONE_VALUE_NOT_ALLOWED = "None value not allowed"

NONE_VALUE_NOT_ALLOWED_FOR_MESSAGE_TEMPLATE = 'None value not allowed for {0}'
NONE_VALUE_NOT_ALLOWED_FOR_MESSAGE_TEMPLATE = "None value not allowed for {0}"
4 changes: 2 additions & 2 deletions openworld/sdk/core/constant/url.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

AUTH_ENDPOINT: str = 'https://api.expediagroup.com/identity/oauth2/v3/token/'
AUTH_ENDPOINT: str = "https://api.expediagroup.com/identity/oauth2/v3/token/"

ENDPOINT: str = 'https://api.expediagroup.com/'
ENDPOINT: str = "https://api.expediagroup.com/"
Loading

0 comments on commit f121310

Please sign in to comment.