Skip to content

Commit c4b9578

Browse files
committed
fix not working code because webargs upgrade
1 parent b12ee81 commit c4b9578

File tree

8 files changed

+54
-33
lines changed

8 files changed

+54
-33
lines changed

Pipfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ tox = "*"
88
ipython = "*"
99
cx-Oracle = "*"
1010
zipp = {extras = ["hobbit", "hobbit_core"], path = "."}
11+
hobbit-core = {extras = ["hobbit", "hobbit_core"], version = "==2.0.0"}
1112

1213
[dev-packages]
1314
sphinx = "==2.0.1"

hobbit_core/schemas.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def create_user(username, password):
3030
"""
3131

3232
@post_load()
33-
def make_instance(self, data):
33+
def make_instance(self, data, many, **kwargs):
3434
return data
3535

3636

@@ -101,7 +101,7 @@ class EnumSetMeta(SQLAlchemyAutoSchemaMeta):
101101
def gen_func(cls, decorator, field_name, enum, verbose=True):
102102

103103
@decorator
104-
def wrapper(self, data):
104+
def wrapper(self, data, many, **kwargs):
105105
if data.get(field_name) is None:
106106
return data
107107

hobbit_core/utils.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -110,19 +110,20 @@ def _get_init_args(instance, base_class):
110110
"""Get instance's __init__ args and it's value when __call__.
111111
"""
112112
getargspec = inspect.getfullargspec
113-
114113
argspec = getargspec(base_class.__init__)
115-
no_defaults = argspec.args[:-len(argspec.defaults)]
116-
has_defaults = argspec.args[-len(argspec.defaults):]
117-
118-
kwargs = {k: getattr(instance, k) for k in no_defaults
119-
if k != 'self' and hasattr(instance, k)}
120-
kwargs.update({k: getattr(instance, k) if hasattr(instance, k) else
121-
getattr(instance, k, argspec.defaults[i])
122-
for i, k in enumerate(has_defaults)})
123-
124-
assert len(kwargs) == len(argspec.args) - 1, 'exclude `self`'
125114

115+
defaults = argspec.defaults
116+
kwargs = {}
117+
if defaults is not None:
118+
no_defaults = argspec.args[:-len(defaults)]
119+
has_defaults = argspec.args[-len(defaults):]
120+
121+
kwargs = {k: getattr(instance, k) for k in no_defaults
122+
if k != 'self' and hasattr(instance, k)}
123+
kwargs.update({k: getattr(instance, k) if hasattr(instance, k) else
124+
getattr(instance, k, defaults[i])
125+
for i, k in enumerate(has_defaults)})
126+
assert len(kwargs) == len(argspec.args) - 1, 'exclude `self`'
126127
return kwargs
127128

128129

hobbit_core/webargs.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,24 @@
1+
from collections.abc import Mapping
2+
13
from webargs.flaskparser import FlaskParser
24

35

6+
def strip_whitespace(value):
7+
if isinstance(value, str):
8+
value = value.strip()
9+
# you'll be getting a MultiDictProxy here potentially, but it should work
10+
elif isinstance(value, Mapping):
11+
return {k: strip_whitespace(value[k]) for k in value}
12+
elif isinstance(value, (list, set)):
13+
return type(value)(map(strip_whitespace, value))
14+
return value
15+
16+
417
class CustomParser(FlaskParser):
518

6-
def parse_arg(self, name, field, req, locations=None):
7-
ret = super().parse_arg(name, field, req, locations=locations)
8-
if hasattr(ret, 'strip'):
9-
return ret.strip()
10-
return ret
19+
def _load_location_data(self, **kwargs):
20+
data = super()._load_location_data(**kwargs)
21+
return strip_whitespace(data)
1122

1223

1324
parser = CustomParser()

tests/conftest.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -63,22 +63,26 @@ def session(request):
6363
class MockRequestParser(Parser):
6464
"""A minimal parser implementation that parses mock requests."""
6565

66-
def parse_querystring(self, req, schema):
67-
return self.load_json(req, schema)
66+
def load_querystring(self, req, schema):
67+
return req.query
6868

69-
def parse_json(self, req, schema):
70-
return self.load_json(req, schema)
7169

72-
def parse_cookies(self, req, schema):
73-
return self.load_json(req, schema)
70+
@pytest.fixture
71+
def request_context(app):
72+
"""create the app and return the request context as a fixture
73+
so that this process does not need to be repeated in each test
74+
"""
75+
return app.test_request_context
7476

7577

7678
@pytest.yield_fixture(scope="function")
77-
def web_request():
78-
req = mock.Mock()
79-
req.query = {}
80-
yield req
81-
req.query = {}
79+
def web_request(request_context):
80+
with request_context():
81+
from flask import request
82+
req = request # mock.Mock()
83+
req.query = {}
84+
yield req
85+
req.query = {}
8286

8387

8488
@pytest.fixture

tests/importsub/schemas.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
ma = Marshmallow()
77

88

9-
class UserSchema(ma.ModelSchema): # type: ignore
9+
class UserSchema(ma.SQLAlchemyAutoSchema): # type: ignore
1010

1111
class Meta:
1212
from .models import OtherUser

tests/test_pagination.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,17 @@ class TestPagination(BaseTest):
1313

1414
def test_page_params(self, web_request, parser):
1515
# test default
16-
@parser.use_kwargs(PageParams, web_request, locations=('query', ))
16+
@parser.use_kwargs(PageParams, web_request, location='query')
1717
def viewfunc(page, page_size, order_by):
1818
return {'page': page, 'page_size': page_size, 'order_by': order_by}
1919

2020
assert viewfunc() == {'order_by': ['-id'], 'page': 1, 'page_size': 10}
2121

2222
# test page_size_range
2323
web_request.query = {'page_size': 101}
24-
msg = r".*page_size': .*Must be between 5 and 100.*"
24+
msg = r".*page_size': .*Must be greater than or equal to 5 and less than or equal to 100.*"
2525
with pytest.raises(ValidationError, match=msg):
26-
viewfunc()
26+
print(viewfunc())
2727

2828
# test order_by
2929
web_request.query = {'order_by': 'id,-11'}

tests/test_schemas.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,12 @@ def test_model_schema(self, client):
1515

1616
class UserSchema(ModelSchema):
1717
role = EnumField(RoleEnum)
18+
pass
1819

1920
class Meta:
2021
model = User
22+
include_relationships = True
23+
load_instance = True
2124

2225
assert UserSchema.Meta.dateformat == '%Y-%m-%d %H:%M:%S'
2326

@@ -26,6 +29,7 @@ class Meta:
2629
db.session.commit()
2730

2831
data = UserSchema().dump(user)
32+
print(data)
2933
assert data['role'] == {'key': 1, 'label': 'admin', 'value': '管理员'}
3034

3135
class UserSchema(ModelSchema):

0 commit comments

Comments
 (0)