Skip to content

Commit f442e58

Browse files
authored
style: Fix and enforce formatting (#316)
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.
1 parent 99610a7 commit f442e58

File tree

123 files changed

+2373
-2876
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

123 files changed

+2373
-2876
lines changed

Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ test: install
3434
lint: #! Run type analysis and linting checks
3535
lint: install
3636
@poetry run mypy ldclient
37+
@poetry run isort --check --atomic ldclient contract-tests
38+
@poetry run pycodestyle ldclient contract-tests
3739

3840
#
3941
# Documentation generation

contract-tests/big_segment_store_fixture.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,18 @@
22
import os
33
import sys
44
from typing import Optional
5+
56
import urllib3
67

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

11-
1210
http = urllib3.PoolManager()
1311

1412

1513
class BigSegmentStoreFixture(BigSegmentStore):
1614
def __init__(self, callback_uri: str):
1715
self._callback_uri = callback_uri
18-
16+
1917
def get_metadata(self) -> BigSegmentStoreMetadata:
2018
resp_data = self._post_callback('/getMetadata', None)
2119
return BigSegmentStoreMetadata(resp_data.get("lastUpToDate"))
@@ -26,9 +24,7 @@ def get_membership(self, context_hash: str) -> Optional[dict]:
2624

2725
def _post_callback(self, path: str, params: Optional[dict]) -> dict:
2826
url = self._callback_uri + path
29-
resp = http.request('POST', url,
30-
body=None if params is None else json.dumps(params),
31-
headers=None if params is None else {'Content-Type': 'application/json'})
27+
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'})
3228
if resp.status != 200:
3329
raise Exception("HTTP error %d from callback to %s" % (resp.status, url))
3430
return json.loads(resp.data.decode('utf-8'))

contract-tests/client_entity.py

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,14 @@
11
import json
22
import logging
3-
import os
4-
import sys
5-
import requests
6-
from hook import PostingHook
73

4+
import requests
85
from big_segment_store_fixture import BigSegmentStoreFixture
6+
from hook import PostingHook
97

10-
from ldclient.config import BigSegmentsConfig
11-
12-
# Import ldclient from parent directory
13-
sys.path.insert(1, os.path.join(sys.path[0], '..'))
14-
from ldclient import Context, MigratorBuilder, ExecutionOrder, MigratorFn, Operation, Stage
158
from ldclient import *
9+
from ldclient import (Context, ExecutionOrder, MigratorBuilder, MigratorFn,
10+
Operation, Stage)
11+
from ldclient.config import BigSegmentsConfig
1612

1713

1814
class ClientEntity:
@@ -59,9 +55,7 @@ def __init__(self, tag, config):
5955

6056
if config.get("bigSegments") is not None:
6157
big_params = config["bigSegments"]
62-
big_config = {
63-
"store": BigSegmentStoreFixture(big_params["callbackUri"])
64-
}
58+
big_config = {"store": BigSegmentStoreFixture(big_params["callbackUri"])}
6559
if big_params.get("userCacheSize") is not None:
6660
big_config["context_cache_size"] = big_params["userCacheSize"]
6761
_set_optional_time_prop(big_params, "userCacheTimeMs", big_config, "context_cache_time")
@@ -151,10 +145,7 @@ def _context_response(self, c: Context) -> dict:
151145

152146
def get_big_segment_store_status(self) -> dict:
153147
status = self.client.big_segment_store_status_provider.status
154-
return {
155-
"available": status.available,
156-
"stale": status.stale
157-
}
148+
return {"available": status.available, "stale": status.stale}
158149

159150
def migration_variation(self, params: dict) -> dict:
160151
stage, _ = self.client.migration_variation(params["key"], Context.from_dict(params["context"]), Stage.from_str(params["defaultStage"]))

contract-tests/hook.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
from ldclient.hook import Hook, EvaluationSeriesContext
2-
from ldclient.evaluation import EvaluationDetail
3-
41
from typing import Optional
2+
53
import requests
64

5+
from ldclient.evaluation import EvaluationDetail
6+
from ldclient.hook import EvaluationSeriesContext, Hook
7+
78

89
class PostingHook(Hook):
910
def __init__(self, name: str, callback: str, data: dict, errors: dict):

contract-tests/service.py

Lines changed: 37 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,40 @@
1-
from client_entity import ClientEntity
2-
31
import json
42
import logging
53
import os
64
import sys
5+
from logging.config import dictConfig
6+
7+
from client_entity import ClientEntity
78
from flask import Flask, request
89
from flask.logging import default_handler
9-
from logging.config import dictConfig
1010
from werkzeug.exceptions import HTTPException
1111

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

1316
default_port = 8000
1417

1518

1619
# logging configuration
17-
dictConfig({
18-
'version': 1,
19-
'formatters': {
20-
'default': {
21-
'format': '[%(asctime)s] [%(name)s] %(levelname)s: %(message)s',
22-
}
23-
},
24-
'handlers': {
25-
'console': {
26-
'class': 'logging.StreamHandler',
27-
'formatter': 'default'
28-
}
29-
},
30-
'root': {
31-
'level': 'INFO',
32-
'handlers': ['console']
33-
},
34-
'loggers': {
35-
'ldclient': {
36-
'level': 'INFO', # change to 'DEBUG' to enable SDK debug logging
20+
dictConfig(
21+
{
22+
'version': 1,
23+
'formatters': {
24+
'default': {
25+
'format': '[%(asctime)s] [%(name)s] %(levelname)s: %(message)s',
26+
}
27+
},
28+
'handlers': {'console': {'class': 'logging.StreamHandler', 'formatter': 'default'}},
29+
'root': {'level': 'INFO', 'handlers': ['console']},
30+
'loggers': {
31+
'ldclient': {
32+
'level': 'INFO', # change to 'DEBUG' to enable SDK debug logging
33+
},
34+
'werkzeug': {'level': 'ERROR'}, # disable irrelevant Flask app logging
3735
},
38-
'werkzeug': { 'level': 'ERROR' } # disable irrelevant Flask app logging
3936
}
40-
})
37+
)
4138

4239
app = Flask(__name__)
4340
app.logger.removeHandler(default_handler)
@@ -56,6 +53,7 @@ def handle_exception(e):
5653
app.logger.exception(e)
5754
return str(e), 500
5855

56+
5957
@app.route('/', methods=['GET'])
6058
def status():
6159
body = {
@@ -78,16 +76,18 @@ def status():
7876
'anonymous-redaction',
7977
'evaluation-hooks',
8078
'omit-anonymous-contexts',
81-
'client-prereq-events'
79+
'client-prereq-events',
8280
]
8381
}
84-
return (json.dumps(body), 200, {'Content-type': 'application/json'})
82+
return json.dumps(body), 200, {'Content-type': 'application/json'}
83+
8584

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

90+
9191
@app.route('/', methods=['POST'])
9292
def post_create_client():
9393
global client_counter, clients
@@ -102,10 +102,10 @@ def post_create_client():
102102

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

107107
clients[client_id] = client
108-
return ('', 201, {'Location': resource_url})
108+
return '', 201, {'Location': resource_url}
109109

110110

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

117117
client = clients[id]
118118
if client is None:
119-
return ('', 404)
119+
return '', 404
120120

121121
command = params.get('command')
122122
sub_params = params.get(command)
@@ -146,22 +146,24 @@ def post_client_command(id):
146146
elif command == "migrationOperation":
147147
response = client.migration_operation(sub_params)
148148
else:
149-
return ('', 400)
149+
return '', 400
150150

151151
if response is None:
152-
return ('', 201)
153-
return (json.dumps(response), 200)
152+
return '', 201
153+
return json.dumps(response), 200
154+
154155

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

159160
client = clients[id]
160161
if client is None:
161-
return ('', 404)
162+
return '', 404
162163

163164
client.close()
164-
return ('', 202)
165+
return '', 202
166+
165167

166168
if __name__ == "__main__":
167169
port = default_port

contract-tests/setup.cfg

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
[pycodestyle]
2-
ignore = E501
2+
ignore = E501,W503

ldclient/__init__.py

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
"""
44

55
from ldclient.impl.rwlock import ReadWriteLock as _ReadWriteLock
6-
from ldclient.impl.util import log, Result
6+
from ldclient.impl.util import Result, log
77
from ldclient.version import VERSION
8+
89
from .client import *
910
from .context import *
1011
from .migrations import *
@@ -13,8 +14,7 @@
1314

1415
__LONG_SCALE__ = float(0xFFFFFFFFFFFFFFF)
1516

16-
__BUILTINS__ = ["key", "ip", "country", "email",
17-
"firstName", "lastName", "avatar", "name", "anonymous"]
17+
__BUILTINS__ = ["key", "ip", "country", "email", "firstName", "lastName", "avatar", "name", "anonymous"]
1818

1919
"""Settings."""
2020
start_wait = 5
@@ -99,17 +99,4 @@ def _reset_client():
9999
__BASE_TYPES__ = (str, float, int, bool)
100100

101101

102-
__all__ = [
103-
'Config',
104-
'Context',
105-
'ContextBuilder',
106-
'ContextMultiBuilder',
107-
'LDClient',
108-
'Result',
109-
'client',
110-
'context',
111-
'evaluation',
112-
'integrations',
113-
'interfaces',
114-
'migrations'
115-
]
102+
__all__ = ['Config', 'Context', 'ContextBuilder', 'ContextMultiBuilder', 'LDClient', 'Result', 'client', 'context', 'evaluation', 'integrations', 'interfaces', 'migrations']

0 commit comments

Comments
 (0)