Skip to content

Commit

Permalink
style: Fix and enforce formatting (#316)
Browse files Browse the repository at this point in the history
This commit introduces both pycodestyle and isort tooling to the CI
check pipeline. These tools ensure a consistent code style and import
order across the codebase.

The commit also includes a number of fixes to the codebase to ensure it
passes the new checks. Most of these were automated through the use of
the CLI tool `black`. The rest were fixed manually.
  • Loading branch information
keelerm84 authored Oct 24, 2024
1 parent 99610a7 commit f442e58
Show file tree
Hide file tree
Showing 123 changed files with 2,373 additions and 2,876 deletions.
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ test: install
lint: #! Run type analysis and linting checks
lint: install
@poetry run mypy ldclient
@poetry run isort --check --atomic ldclient contract-tests
@poetry run pycodestyle ldclient contract-tests

#
# Documentation generation
Expand Down
10 changes: 3 additions & 7 deletions contract-tests/big_segment_store_fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,18 @@
import os
import sys
from typing import Optional

import urllib3

# Import ldclient from parent directory
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from ldclient.interfaces import BigSegmentStore, BigSegmentStoreMetadata


http = urllib3.PoolManager()


class BigSegmentStoreFixture(BigSegmentStore):
def __init__(self, callback_uri: str):
self._callback_uri = callback_uri

def get_metadata(self) -> BigSegmentStoreMetadata:
resp_data = self._post_callback('/getMetadata', None)
return BigSegmentStoreMetadata(resp_data.get("lastUpToDate"))
Expand All @@ -26,9 +24,7 @@ def get_membership(self, context_hash: str) -> Optional[dict]:

def _post_callback(self, path: str, params: Optional[dict]) -> dict:
url = self._callback_uri + path
resp = http.request('POST', url,
body=None if params is None else json.dumps(params),
headers=None if params is None else {'Content-Type': 'application/json'})
resp = http.request('POST', url, body=None if params is None else json.dumps(params), headers=None if params is None else {'Content-Type': 'application/json'})
if resp.status != 200:
raise Exception("HTTP error %d from callback to %s" % (resp.status, url))
return json.loads(resp.data.decode('utf-8'))
Expand Down
23 changes: 7 additions & 16 deletions contract-tests/client_entity.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
import json
import logging
import os
import sys
import requests
from hook import PostingHook

import requests
from big_segment_store_fixture import BigSegmentStoreFixture
from hook import PostingHook

from ldclient.config import BigSegmentsConfig

# Import ldclient from parent directory
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from ldclient import Context, MigratorBuilder, ExecutionOrder, MigratorFn, Operation, Stage
from ldclient import *
from ldclient import (Context, ExecutionOrder, MigratorBuilder, MigratorFn,
Operation, Stage)
from ldclient.config import BigSegmentsConfig


class ClientEntity:
Expand Down Expand Up @@ -59,9 +55,7 @@ def __init__(self, tag, config):

if config.get("bigSegments") is not None:
big_params = config["bigSegments"]
big_config = {
"store": BigSegmentStoreFixture(big_params["callbackUri"])
}
big_config = {"store": BigSegmentStoreFixture(big_params["callbackUri"])}
if big_params.get("userCacheSize") is not None:
big_config["context_cache_size"] = big_params["userCacheSize"]
_set_optional_time_prop(big_params, "userCacheTimeMs", big_config, "context_cache_time")
Expand Down Expand Up @@ -151,10 +145,7 @@ def _context_response(self, c: Context) -> dict:

def get_big_segment_store_status(self) -> dict:
status = self.client.big_segment_store_status_provider.status
return {
"available": status.available,
"stale": status.stale
}
return {"available": status.available, "stale": status.stale}

def migration_variation(self, params: dict) -> dict:
stage, _ = self.client.migration_variation(params["key"], Context.from_dict(params["context"]), Stage.from_str(params["defaultStage"]))
Expand Down
7 changes: 4 additions & 3 deletions contract-tests/hook.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from ldclient.hook import Hook, EvaluationSeriesContext
from ldclient.evaluation import EvaluationDetail

from typing import Optional

import requests

from ldclient.evaluation import EvaluationDetail
from ldclient.hook import EvaluationSeriesContext, Hook


class PostingHook(Hook):
def __init__(self, name: str, callback: str, data: dict, errors: dict):
Expand Down
72 changes: 37 additions & 35 deletions contract-tests/service.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,40 @@
from client_entity import ClientEntity

import json
import logging
import os
import sys
from logging.config import dictConfig

from client_entity import ClientEntity
from flask import Flask, request
from flask.logging import default_handler
from logging.config import dictConfig
from werkzeug.exceptions import HTTPException

# Import ldclient from parent directory
sys.path.insert(1, os.path.join(sys.path[0], '..'))


default_port = 8000


# logging configuration
dictConfig({
'version': 1,
'formatters': {
'default': {
'format': '[%(asctime)s] [%(name)s] %(levelname)s: %(message)s',
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'default'
}
},
'root': {
'level': 'INFO',
'handlers': ['console']
},
'loggers': {
'ldclient': {
'level': 'INFO', # change to 'DEBUG' to enable SDK debug logging
dictConfig(
{
'version': 1,
'formatters': {
'default': {
'format': '[%(asctime)s] [%(name)s] %(levelname)s: %(message)s',
}
},
'handlers': {'console': {'class': 'logging.StreamHandler', 'formatter': 'default'}},
'root': {'level': 'INFO', 'handlers': ['console']},
'loggers': {
'ldclient': {
'level': 'INFO', # change to 'DEBUG' to enable SDK debug logging
},
'werkzeug': {'level': 'ERROR'}, # disable irrelevant Flask app logging
},
'werkzeug': { 'level': 'ERROR' } # disable irrelevant Flask app logging
}
})
)

app = Flask(__name__)
app.logger.removeHandler(default_handler)
Expand All @@ -56,6 +53,7 @@ def handle_exception(e):
app.logger.exception(e)
return str(e), 500


@app.route('/', methods=['GET'])
def status():
body = {
Expand All @@ -78,16 +76,18 @@ def status():
'anonymous-redaction',
'evaluation-hooks',
'omit-anonymous-contexts',
'client-prereq-events'
'client-prereq-events',
]
}
return (json.dumps(body), 200, {'Content-type': 'application/json'})
return json.dumps(body), 200, {'Content-type': 'application/json'}


@app.route('/', methods=['DELETE'])
def delete_stop_service():
global_log.info("Test service has told us to exit")
os._exit(0)


@app.route('/', methods=['POST'])
def post_create_client():
global client_counter, clients
Expand All @@ -102,10 +102,10 @@ def post_create_client():

if client.is_initializing() is False and options['configuration'].get('initCanFail', False) is False:
client.close()
return ("Failed to initialize", 500)
return "Failed to initialize", 500

clients[client_id] = client
return ('', 201, {'Location': resource_url})
return '', 201, {'Location': resource_url}


@app.route('/clients/<id>', methods=['POST'])
Expand All @@ -116,7 +116,7 @@ def post_client_command(id):

client = clients[id]
if client is None:
return ('', 404)
return '', 404

command = params.get('command')
sub_params = params.get(command)
Expand Down Expand Up @@ -146,22 +146,24 @@ def post_client_command(id):
elif command == "migrationOperation":
response = client.migration_operation(sub_params)
else:
return ('', 400)
return '', 400

if response is None:
return ('', 201)
return (json.dumps(response), 200)
return '', 201
return json.dumps(response), 200


@app.route('/clients/<id>', methods=['DELETE'])
def delete_client(id):
global clients

client = clients[id]
if client is None:
return ('', 404)
return '', 404

client.close()
return ('', 202)
return '', 202


if __name__ == "__main__":
port = default_port
Expand Down
2 changes: 1 addition & 1 deletion contract-tests/setup.cfg
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[pycodestyle]
ignore = E501
ignore = E501,W503
21 changes: 4 additions & 17 deletions ldclient/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
"""

from ldclient.impl.rwlock import ReadWriteLock as _ReadWriteLock
from ldclient.impl.util import log, Result
from ldclient.impl.util import Result, log
from ldclient.version import VERSION

from .client import *
from .context import *
from .migrations import *
Expand All @@ -13,8 +14,7 @@

__LONG_SCALE__ = float(0xFFFFFFFFFFFFFFF)

__BUILTINS__ = ["key", "ip", "country", "email",
"firstName", "lastName", "avatar", "name", "anonymous"]
__BUILTINS__ = ["key", "ip", "country", "email", "firstName", "lastName", "avatar", "name", "anonymous"]

"""Settings."""
start_wait = 5
Expand Down Expand Up @@ -99,17 +99,4 @@ def _reset_client():
__BASE_TYPES__ = (str, float, int, bool)


__all__ = [
'Config',
'Context',
'ContextBuilder',
'ContextMultiBuilder',
'LDClient',
'Result',
'client',
'context',
'evaluation',
'integrations',
'interfaces',
'migrations'
]
__all__ = ['Config', 'Context', 'ContextBuilder', 'ContextMultiBuilder', 'LDClient', 'Result', 'client', 'context', 'evaluation', 'integrations', 'interfaces', 'migrations']
Loading

0 comments on commit f442e58

Please sign in to comment.