Skip to content

Commit 3c455cf

Browse files
authored
Improve health of this package (#1409)
* added flake8 and flake8-import-order to travis for py27 * fixed a test that fails from time to time depending on an order of a dict * flake8 tweaks for the entire codebase excluding tests
1 parent 5135185 commit 3c455cf

File tree

22 files changed

+351
-296
lines changed

22 files changed

+351
-296
lines changed

.travis.yml

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
language: python
2+
23
python:
34
- '2.6'
45
- '2.7'
@@ -7,35 +8,51 @@ python:
78
- '3.5'
89
- pypy
910
- pypy3
11+
1012
env:
1113
- PYMONGO=2.7
1214
- PYMONGO=2.8
1315
- PYMONGO=3.0
1416
- PYMONGO=dev
17+
1518
matrix:
1619
fast_finish: true
20+
1721
before_install:
1822
- travis_retry sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
1923
- echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' |
2024
sudo tee /etc/apt/sources.list.d/mongodb.list
2125
- travis_retry sudo apt-get update
2226
- travis_retry sudo apt-get install mongodb-org-server
27+
2328
install:
2429
- sudo apt-get install python-dev python3-dev libopenjpeg-dev zlib1g-dev libjpeg-turbo8-dev
2530
libtiff4-dev libjpeg8-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev
2631
python-tk
27-
# virtualenv>=14.0.0 has dropped Python 3.2 support
28-
- travis_retry pip install "virtualenv<14.0.0" "tox>=1.9" coveralls
32+
- travis_retry pip install --upgrade pip
33+
- travis_retry pip install coveralls
34+
- travis_retry pip install flake8
35+
- travis_retry pip install tox>=1.9
36+
- travis_retry pip install "virtualenv<14.0.0" # virtualenv>=14.0.0 has dropped Python 3.2 support (and pypy3 is based on py32)
2937
- travis_retry tox -e $(echo py$TRAVIS_PYTHON_VERSION-mg$PYMONGO | tr -d . | sed -e 's/pypypy/pypy/') -- -e test
38+
39+
# Run flake8 for py27
40+
before_script:
41+
- if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then tox -e flake8; fi
42+
3043
script:
3144
- tox -e $(echo py$TRAVIS_PYTHON_VERSION-mg$PYMONGO | tr -d . | sed -e 's/pypypy/pypy/') -- --with-coverage
45+
3246
after_script: coveralls --verbose
47+
3348
notifications:
3449
irc: irc.freenode.org#mongoengine
50+
3551
branches:
3652
only:
3753
- master
3854
- /^v.*$/
55+
3956
deploy:
4057
provider: pypi
4158
user: the_drow

mongoengine/__init__.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1+
import connection
2+
from connection import *
13
import document
24
from document import *
5+
import errors
6+
from errors import *
37
import fields
48
from fields import *
5-
import connection
6-
from connection import *
79
import queryset
810
from queryset import *
911
import signals
1012
from signals import *
11-
from errors import *
12-
import errors
1313

1414
__all__ = (list(document.__all__) + fields.__all__ + connection.__all__ +
1515
list(queryset.__all__) + signals.__all__ + list(errors.__all__))
@@ -22,4 +22,5 @@ def get_version():
2222
return '.'.join(map(str, VERSION[:-1])) + VERSION[-1]
2323
return '.'.join(map(str, VERSION))
2424

25+
2526
__version__ = get_version()

mongoengine/base/datastructures.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import weakref
21
import itertools
2+
import weakref
33

44
from mongoengine.common import _import_class
55
from mongoengine.errors import DoesNotExist, MultipleObjectsReturned
@@ -199,8 +199,9 @@ def sort(self, *args, **kwargs):
199199
def _mark_as_changed(self, key=None):
200200
if hasattr(self._instance, '_mark_as_changed'):
201201
if key:
202-
self._instance._mark_as_changed('%s.%s' % (self._name,
203-
key % len(self)))
202+
self._instance._mark_as_changed(
203+
'%s.%s' % (self._name, key % len(self))
204+
)
204205
else:
205206
self._instance._mark_as_changed(self._name)
206207

mongoengine/base/document.py

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,28 @@
11
import copy
2-
import operator
32
import numbers
3+
import operator
44
from collections import Hashable
55
from functools import partial
66

7-
import pymongo
8-
from bson import json_util, ObjectId
7+
from bson import ObjectId, json_util
98
from bson.dbref import DBRef
109
from bson.son import SON
10+
import pymongo
1111

1212
from mongoengine import signals
13-
from mongoengine.common import _import_class
14-
from mongoengine.errors import (ValidationError, InvalidDocumentError,
15-
LookUpError, FieldDoesNotExist)
16-
from mongoengine.python_support import PY3, txt_type
17-
from mongoengine.base.common import get_document, ALLOW_INHERITANCE
13+
from mongoengine.base.common import ALLOW_INHERITANCE, get_document
1814
from mongoengine.base.datastructures import (
1915
BaseDict,
2016
BaseList,
2117
EmbeddedDocumentList,
22-
StrictDict,
23-
SemiStrictDict
18+
SemiStrictDict,
19+
StrictDict
2420
)
2521
from mongoengine.base.fields import ComplexBaseField
22+
from mongoengine.common import _import_class
23+
from mongoengine.errors import (FieldDoesNotExist, InvalidDocumentError,
24+
LookUpError, ValidationError)
25+
from mongoengine.python_support import PY3, txt_type
2626

2727
__all__ = ('BaseDocument', 'NON_FIELD_ERRORS')
2828

@@ -73,7 +73,7 @@ def __init__(self, *args, **values):
7373
# if so raise an Exception.
7474
if not self._dynamic and (self._meta.get('strict', True) or _created):
7575
_undefined_fields = set(values.keys()) - set(
76-
self._fields.keys() + ['id', 'pk', '_cls', '_text_score'])
76+
self._fields.keys() + ['id', 'pk', '_cls', '_text_score'])
7777
if _undefined_fields:
7878
msg = (
7979
"The fields '{0}' do not exist on the document '{1}'"
@@ -310,7 +310,7 @@ def to_mongo(self, use_db_field=True, fields=None):
310310
data = SON()
311311
data["_id"] = None
312312
data['_cls'] = self._class_name
313-
313+
314314
# only root fields ['test1.a', 'test2'] => ['test1', 'test2']
315315
root_fields = set([f.split('.')[0] for f in fields])
316316

@@ -333,11 +333,11 @@ def to_mongo(self, use_db_field=True, fields=None):
333333
i.replace(key, '') for i in fields
334334
if i.startswith(key)]
335335

336-
ex_vars['fields'] = embedded_fields
336+
ex_vars['fields'] = embedded_fields
337337

338338
if 'use_db_field' in f_inputs:
339339
ex_vars['use_db_field'] = use_db_field
340-
340+
341341
value = field.to_mongo(value, **ex_vars)
342342

343343
# Handle self generating fields
@@ -566,8 +566,10 @@ def _get_changed_fields(self, inspected=None):
566566
continue
567567
if isinstance(field, ReferenceField):
568568
continue
569-
elif (isinstance(data, (EmbeddedDocument, DynamicEmbeddedDocument))
570-
and db_field_name not in changed_fields):
569+
elif (
570+
isinstance(data, (EmbeddedDocument, DynamicEmbeddedDocument)) and
571+
db_field_name not in changed_fields
572+
):
571573
# Find all embedded fields that have been changed
572574
changed = data._get_changed_fields(inspected)
573575
changed_fields += ["%s%s" % (key, k) for k in changed if k]
@@ -608,7 +610,7 @@ def _delta(self):
608610
break
609611
elif isinstance(d, list) and p.lstrip('-').isdigit():
610612
if p[0] == '-':
611-
p = str(len(d)+int(p))
613+
p = str(len(d) + int(p))
612614
try:
613615
d = d[int(p)]
614616
except IndexError:
@@ -644,7 +646,7 @@ def _delta(self):
644646
for p in parts:
645647
if isinstance(d, list) and p.lstrip('-').isdigit():
646648
if p[0] == '-':
647-
p = str(len(d)+int(p))
649+
p = str(len(d) + int(p))
648650
d = d[int(p)]
649651
elif (hasattr(d, '__getattribute__') and
650652
not isinstance(d, dict)):
@@ -775,8 +777,12 @@ def _build_index_spec(cls, spec):
775777
# Check to see if we need to include _cls
776778
allow_inheritance = cls._meta.get('allow_inheritance',
777779
ALLOW_INHERITANCE)
778-
include_cls = (allow_inheritance and not spec.get('sparse', False) and
779-
spec.get('cls', True) and '_cls' not in spec['fields'])
780+
include_cls = (
781+
allow_inheritance and
782+
not spec.get('sparse', False) and
783+
spec.get('cls', True) and
784+
'_cls' not in spec['fields']
785+
)
780786

781787
# 733: don't include cls if index_cls is False unless there is an explicit cls with the index
782788
include_cls = include_cls and (spec.get('cls', False) or cls._meta.get('index_cls', True))

mongoengine/base/fields.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@
55
from bson import DBRef, ObjectId, SON
66
import pymongo
77

8-
from mongoengine.common import _import_class
9-
from mongoengine.errors import ValidationError
108
from mongoengine.base.common import ALLOW_INHERITANCE
119
from mongoengine.base.datastructures import (
1210
BaseDict, BaseList, EmbeddedDocumentList
1311
)
12+
from mongoengine.common import _import_class
13+
from mongoengine.errors import ValidationError
1414

1515
__all__ = ("BaseField", "ComplexBaseField",
1616
"ObjectIdField", "GeoJsonBaseField")
@@ -85,13 +85,13 @@ def __init__(self, db_field=None, name=None, required=False, default=None,
8585
self.null = null
8686
self.sparse = sparse
8787
self._owner_document = None
88-
88+
8989
# Detect and report conflicts between metadata and base properties.
9090
conflicts = set(dir(self)) & set(kwargs)
9191
if conflicts:
9292
raise TypeError("%s already has attribute(s): %s" % (
93-
self.__class__.__name__, ', '.join(conflicts) ))
94-
93+
self.__class__.__name__, ', '.join(conflicts)))
94+
9595
# Assign metadata to the instance
9696
# This efficient method is available because no __slots__ are defined.
9797
self.__dict__.update(kwargs)
@@ -169,11 +169,11 @@ def _to_mongo_safe_call(self, value, use_db_field=True, fields=None):
169169
f_inputs = self.to_mongo.__code__.co_varnames
170170
ex_vars = {}
171171
if 'fields' in f_inputs:
172-
ex_vars['fields'] = fields
172+
ex_vars['fields'] = fields
173173

174174
if 'use_db_field' in f_inputs:
175175
ex_vars['use_db_field'] = use_db_field
176-
176+
177177
return self.to_mongo(value, **ex_vars)
178178

179179
def prepare_query_value(self, op, value):
@@ -206,7 +206,6 @@ def _validate_choices(self, value):
206206
elif value not in choice_list:
207207
self.error('Value must be one of %s' % unicode(choice_list))
208208

209-
210209
def _validate(self, value, **kwargs):
211210
# Check the Choices Constraint
212211
if self.choices:

mongoengine/base/metaclasses.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
11
import warnings
22

3+
from mongoengine.base.common import ALLOW_INHERITANCE, _document_registry
4+
from mongoengine.base.fields import BaseField, ComplexBaseField, ObjectIdField
35
from mongoengine.common import _import_class
46
from mongoengine.errors import InvalidDocumentError
57
from mongoengine.python_support import PY3
68
from mongoengine.queryset import (DO_NOTHING, DoesNotExist,
79
MultipleObjectsReturned,
810
QuerySetManager)
911

10-
from mongoengine.base.common import _document_registry, ALLOW_INHERITANCE
11-
from mongoengine.base.fields import BaseField, ComplexBaseField, ObjectIdField
1212

1313
__all__ = ('DocumentMetaclass', 'TopLevelDocumentMetaclass')
1414

1515

1616
class DocumentMetaclass(type):
17-
"""Metaclass for all documents.
18-
"""
17+
"""Metaclass for all documents."""
1918

19+
# TODO lower complexity of this method
2020
def __new__(cls, name, bases, attrs):
2121
flattened_bases = cls._get_bases(bases)
2222
super_new = super(DocumentMetaclass, cls).__new__
@@ -162,7 +162,7 @@ def __new__(cls, name, bases, attrs):
162162
# copies __func__ into im_func and __self__ into im_self for
163163
# classmethod objects in Document derived classes.
164164
if PY3:
165-
for key, val in new_class.__dict__.items():
165+
for val in new_class.__dict__.values():
166166
if isinstance(val, classmethod):
167167
f = val.__get__(new_class)
168168
if hasattr(f, '__func__') and not hasattr(f, 'im_func'):

mongoengine/dereference.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
from bson import DBRef, SON
22

3-
from mongoengine.python_support import txt_type
4-
5-
from base import (
3+
from .base import (
64
BaseDict, BaseList, EmbeddedDocumentList,
75
TopLevelDocumentMetaclass, get_document
86
)
9-
from fields import (ReferenceField, ListField, DictField, MapField)
10-
from connection import get_db
11-
from queryset import QuerySet
12-
from document import Document, EmbeddedDocument
7+
from .connection import get_db
8+
from .document import Document, EmbeddedDocument
9+
from .fields import DictField, ListField, MapField, ReferenceField
10+
from .python_support import txt_type
11+
from .queryset import QuerySet
1312

1413

1514
class DeReference(object):

0 commit comments

Comments
 (0)