Skip to content

Commit 641862e

Browse files
authored
Merge pull request segmentio#162 from pberganza-applaudostudios/fix/linting-errors
Fix/linting errors
2 parents 2a314e6 + b89bda9 commit 641862e

File tree

14 files changed

+134
-70
lines changed

14 files changed

+134
-70
lines changed

.circleci/config.yml

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ jobs:
1010
steps:
1111
- checkout
1212
- run: pip install --user .
13-
- run: sudo pip install coverage pylint==1.9.3 pycodestyle
13+
- run: sudo pip install coverage pylint==1.9.3 flake8
1414
- run: make test
1515
- persist_to_workspace:
1616
root: .
@@ -19,7 +19,7 @@ jobs:
1919
- store_artifacts:
2020
path: pylint.out
2121
- store_artifacts:
22-
path: pycodestyle.out
22+
path: flake8.out
2323

2424
coverage:
2525
docker:
@@ -51,7 +51,11 @@ jobs:
5151
steps:
5252
- checkout
5353
- run: pip install --user .
54-
- run: sudo pip install setuptools coverage pylint==1.9.3 pycodestyle
54+
- run: sudo pip install setuptools coverage pylint==1.9.3 flake8
55+
- run:
56+
name: Linting with Flake8
57+
command: |
58+
git diff origin/master..HEAD analytics | flake8 --diff --max-complexity=10 analytics
5559
- run: make test
5660
- run: make e2e_test
5761

@@ -61,7 +65,11 @@ jobs:
6165
steps:
6266
- checkout
6367
- run: pip install --user .
64-
- run: sudo pip install coverage pylint==1.9.3 pycodestyle
68+
- run: sudo pip install coverage pylint==1.9.3 flake8
69+
- run:
70+
name: Linting with Flake8
71+
command: |
72+
git diff origin/master..HEAD analytics | flake8 --diff --max-complexity=10 analytics
6573
- run: make test
6674
- run: make e2e_test
6775

Makefile

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
test:
22
pylint --rcfile=.pylintrc --reports=y --exit-zero analytics | tee pylint.out
3-
# fail on pycodestyle errors on the code change
4-
git diff origin/master..HEAD analytics | pycodestyle --ignore=E501 --diff --statistics --count
5-
pycodestyle --ignore=E501 --statistics analytics > pycodestyle.out || true
3+
flake8 --max-complexity=10 --statistics analytics > flake8.out || true
64
coverage run --branch --include=analytics/\* --omit=*/test* setup.py test
75

86
release:

analytics/__init__.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,30 +19,37 @@ def track(*args, **kwargs):
1919
"""Send a track call."""
2020
_proxy('track', *args, **kwargs)
2121

22+
2223
def identify(*args, **kwargs):
2324
"""Send a identify call."""
2425
_proxy('identify', *args, **kwargs)
2526

27+
2628
def group(*args, **kwargs):
2729
"""Send a group call."""
2830
_proxy('group', *args, **kwargs)
2931

32+
3033
def alias(*args, **kwargs):
3134
"""Send a alias call."""
3235
_proxy('alias', *args, **kwargs)
3336

37+
3438
def page(*args, **kwargs):
3539
"""Send a page call."""
3640
_proxy('page', *args, **kwargs)
3741

42+
3843
def screen(*args, **kwargs):
3944
"""Send a screen call."""
4045
_proxy('screen', *args, **kwargs)
4146

47+
4248
def flush():
4349
"""Tell the client to flush."""
4450
_proxy('flush')
4551

52+
4653
def join():
4754
"""Block program until the client clears the queue"""
4855
_proxy('join')
@@ -58,8 +65,9 @@ def _proxy(method, *args, **kwargs):
5865
"""Create an analytics client if one doesn't exist and send to it."""
5966
global default_client
6067
if not default_client:
61-
default_client = Client(write_key, host=host, debug=debug, on_error=on_error,
62-
send=send, sync_mode=sync_mode)
68+
default_client = Client(write_key, host=host, debug=debug,
69+
on_error=on_error, send=send,
70+
sync_mode=sync_mode)
6371

6472
fn = getattr(default_client, method)
6573
fn(*args, **kwargs)

analytics/client.py

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
try:
1616
import queue
17-
except:
17+
except ImportError:
1818
import Queue as queue
1919

2020

@@ -48,17 +48,20 @@ def __init__(self, write_key=None, host=None, debug=False,
4848
self.consumers = None
4949
else:
5050
# On program exit, allow the consumer thread to exit cleanly.
51-
# This prevents exceptions and a messy shutdown when the interpreter is
52-
# destroyed before the daemon thread finishes execution. However, it
53-
# is *not* the same as flushing the queue! To guarantee all messages
54-
# have been delivered, you'll still need to call flush().
51+
# This prevents exceptions and a messy shutdown when the
52+
# interpreter is destroyed before the daemon thread finishes
53+
# execution. However, it is *not* the same as flushing the queue!
54+
# To guarantee all messages have been delivered, you'll still need
55+
# to call flush().
5556
if send:
5657
atexit.register(self.join)
5758
for n in range(thread):
5859
self.consumers = []
59-
consumer = Consumer(self.queue, write_key, host=host, on_error=on_error,
60-
flush_at=flush_at, flush_interval=flush_interval,
61-
gzip=gzip, retries=max_retries, timeout=timeout)
60+
consumer = Consumer(
61+
self.queue, write_key, host=host, on_error=on_error,
62+
flush_at=flush_at, flush_interval=flush_interval,
63+
gzip=gzip, retries=max_retries, timeout=timeout,
64+
)
6265
self.consumers.append(consumer)
6366

6467
# if we've disabled sending, just don't start the consumer
@@ -87,7 +90,8 @@ def identify(self, user_id=None, traits=None, context=None, timestamp=None,
8790
return self._enqueue(msg)
8891

8992
def track(self, user_id=None, event=None, properties=None, context=None,
90-
timestamp=None, anonymous_id=None, integrations=None, message_id=None):
93+
timestamp=None, anonymous_id=None, integrations=None,
94+
message_id=None):
9195
properties = properties or {}
9296
context = context or {}
9397
integrations = integrations or {}
@@ -129,7 +133,8 @@ def alias(self, previous_id=None, user_id=None, context=None,
129133
return self._enqueue(msg)
130134

131135
def group(self, user_id=None, group_id=None, traits=None, context=None,
132-
timestamp=None, anonymous_id=None, integrations=None, message_id=None):
136+
timestamp=None, anonymous_id=None, integrations=None,
137+
message_id=None):
133138
traits = traits or {}
134139
context = context or {}
135140
integrations = integrations or {}
@@ -266,7 +271,9 @@ def flush(self):
266271
self.log.debug('successfully flushed about %s items.', size)
267272

268273
def join(self):
269-
"""Ends the consumer thread once the queue is empty. Blocks execution until finished"""
274+
"""Ends the consumer thread once the queue is empty.
275+
Blocks execution until finished
276+
"""
270277
for consumer in self.consumers:
271278
consumer.pause()
272279
try:

analytics/consumer.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import backoff
55
import json
66

7-
from analytics.version import VERSION
87
from analytics.request import post, APIError, DatetimeSerializer
98

109
try:
@@ -23,8 +22,9 @@ class Consumer(Thread):
2322
"""Consumes the messages from the client's queue."""
2423
log = logging.getLogger('segment')
2524

26-
def __init__(self, queue, write_key, flush_at=100, host=None, on_error=None,
27-
flush_interval=0.5, gzip=False, retries=10, timeout=15):
25+
def __init__(self, queue, write_key, flush_at=100, host=None,
26+
on_error=None, flush_interval=0.5, gzip=False, retries=10,
27+
timeout=15):
2828
"""Create a consumer thread."""
2929
Thread.__init__(self)
3030
# Make consumer a daemon thread so that it doesn't block program exit
@@ -38,7 +38,8 @@ def __init__(self, queue, write_key, flush_at=100, host=None, on_error=None,
3838
self.gzip = gzip
3939
# It's important to set running in the constructor: if we are asked to
4040
# pause immediately after construction, we might set running to True in
41-
# run() *after* we set it to False in pause... and keep running forever.
41+
# run() *after* we set it to False in pause... and keep running
42+
# forever.
4243
self.running = True
4344
self.retries = retries
4445
self.timeout = timeout
@@ -113,14 +114,19 @@ def request(self, batch):
113114

114115
def fatal_exception(exc):
115116
if isinstance(exc, APIError):
116-
# retry on server errors and client errors with 429 status code (rate limited),
117+
# retry on server errors and client errors
118+
# with 429 status code (rate limited),
117119
# don't retry on other client errors
118120
return (400 <= exc.status < 500) and exc.status != 429
119121
else:
120122
# retry on all other errors (eg. network)
121123
return False
122124

123-
@backoff.on_exception(backoff.expo, Exception, max_tries=self.retries + 1, giveup=fatal_exception)
125+
@backoff.on_exception(
126+
backoff.expo,
127+
Exception,
128+
max_tries=self.retries + 1,
129+
giveup=fatal_exception)
124130
def send_request():
125131
post(self.write_key, self.host, gzip=self.gzip,
126132
timeout=self.timeout, batch=batch)

analytics/request.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,13 @@ def post(write_key, host=None, gzip=False, timeout=15, **kwargs):
3030
headers['Content-Encoding'] = 'gzip'
3131
buf = BytesIO()
3232
with GzipFile(fileobj=buf, mode='w') as gz:
33-
# 'data' was produced by json.dumps(), whose default encoding is utf-8.
33+
# 'data' was produced by json.dumps(),
34+
# whose default encoding is utf-8.
3435
gz.write(data.encode('utf-8'))
3536
data = buf.getvalue()
3637

37-
res = _session.post(url, data=data, auth=auth, headers=headers, timeout=timeout)
38+
res = _session.post(url, data=data, auth=auth,
39+
headers=headers, timeout=timeout)
3840

3941
if res.status_code == 200:
4042
log.debug('data uploaded successfully')

analytics/test/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
import logging
44
import sys
55

6+
67
def all_names():
78
for _, modname, _ in pkgutil.iter_modules(__path__):
89
yield 'analytics.test.' + modname
910

11+
1012
def all():
1113
logging.basicConfig(stream=sys.stderr)
1214
return unittest.defaultTestLoader.loadTestsFromNames(all_names())

analytics/test/client.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,8 @@ def mock_post_fn(*args, **kwargs):
326326

327327
# the post function should be called 2 times, with a batch size of 10
328328
# each time.
329-
with mock.patch('analytics.consumer.post', side_effect=mock_post_fn) as mock_post:
329+
with mock.patch('analytics.consumer.post', side_effect=mock_post_fn) \
330+
as mock_post:
330331
for _ in range(20):
331332
client.identify('userId', {'trait': 'value'})
332333
time.sleep(1)

analytics/test/consumer.py

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,9 @@ def test_upload(self):
5252
self.assertTrue(success)
5353

5454
def test_flush_interval(self):
55-
# Put _n_ items in the queue, pausing a little bit more than _flush_interval_
56-
# after each one. The consumer should upload _n_ times.
55+
# Put _n_ items in the queue, pausing a little bit more than
56+
# _flush_interval_ after each one.
57+
# The consumer should upload _n_ times.
5758
q = Queue()
5859
flush_interval = 0.3
5960
consumer = Consumer(q, 'testsecret', flush_at=10,
@@ -71,8 +72,8 @@ def test_flush_interval(self):
7172
self.assertEqual(mock_post.call_count, 3)
7273

7374
def test_multiple_uploads_per_interval(self):
74-
# Put _flush_at*2_ items in the queue at once, then pause for _flush_interval_.
75-
# The consumer should upload 2 times.
75+
# Put _flush_at*2_ items in the queue at once, then pause for
76+
# _flush_interval_. The consumer should upload 2 times.
7677
q = Queue()
7778
flush_interval = 0.5
7879
flush_at = 10
@@ -99,34 +100,38 @@ def test_request(self):
99100
}
100101
consumer.request([track])
101102

102-
def _test_request_retry(self, consumer, expected_exception, exception_count):
103+
def _test_request_retry(self, consumer,
104+
expected_exception, exception_count):
103105

104106
def mock_post(*args, **kwargs):
105107
mock_post.call_count += 1
106108
if mock_post.call_count <= exception_count:
107109
raise expected_exception
108110
mock_post.call_count = 0
109111

110-
with mock.patch('analytics.consumer.post', mock.Mock(side_effect=mock_post)):
112+
with mock.patch('analytics.consumer.post',
113+
mock.Mock(side_effect=mock_post)):
111114
track = {
112115
'type': 'track',
113116
'event': 'python event',
114117
'userId': 'userId'
115118
}
116-
# request() should succeed if the number of exceptions raised is less
117-
# than the retries paramater.
119+
# request() should succeed if the number of exceptions raised is
120+
# less than the retries paramater.
118121
if exception_count <= consumer.retries:
119122
consumer.request([track])
120123
else:
121-
# if exceptions are raised more times than the retries parameter,
122-
# we expect the exception to be returned to the caller.
124+
# if exceptions are raised more times than the retries
125+
# parameter, we expect the exception to be returned to
126+
# the caller.
123127
try:
124128
consumer.request([track])
125129
except type(expected_exception) as exc:
126130
self.assertEqual(exc, expected_exception)
127131
else:
128132
self.fail(
129-
"request() should raise an exception if still failing after %d retries" % consumer.retries)
133+
"request() should raise an exception if still failing "
134+
"after %d retries" % consumer.retries)
130135

131136
def test_request_retry(self):
132137
# we should retry on general errors
@@ -180,10 +185,12 @@ def mock_post_fn(_, data, **kwargs):
180185
res = mock.Mock()
181186
res.status_code = 200
182187
self.assertTrue(len(data.encode()) < 500000,
183-
'batch size (%d) exceeds 500KB limit' % len(data.encode()))
188+
'batch size (%d) exceeds 500KB limit'
189+
% len(data.encode()))
184190
return res
185191

186-
with mock.patch('analytics.request._session.post', side_effect=mock_post_fn) as mock_post:
192+
with mock.patch('analytics.request._session.post',
193+
side_effect=mock_post_fn) as mock_post:
187194
consumer.start()
188195
for _ in range(0, n_msgs + 2):
189196
q.put(track)

analytics/test/module.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def test_track(self):
2626
analytics.flush()
2727

2828
def test_identify(self):
29-
analytics.identify('userId', { 'email': '[email protected]' })
29+
analytics.identify('userId', {'email': '[email protected]'})
3030
analytics.flush()
3131

3232
def test_group(self):

0 commit comments

Comments
 (0)