Skip to content

Commit 8a49be4

Browse files
committedJul 30, 2020
fix typings & linting
1 parent e5c46d9 commit 8a49be4

File tree

10 files changed

+149
-85
lines changed

10 files changed

+149
-85
lines changed
 

‎magpie/api/exception.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
URL_REGEX = colander.URL_REGEX
4242

4343

44-
def verify_param( # noqa: E126
44+
def verify_param( # noqa: E126 # pylint: disable=R0913,too-many-arguments
4545
# --- verification values ---
4646
param, # type: Any
4747
param_compare=None, # type: Optional[Union[Any, List[Any]]]

‎magpie/api/login/login.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -292,4 +292,4 @@ def get_providers(request): # noqa: F811
292292
"""
293293
return ax.valid_http(http_success=HTTPOk, detail=s.Providers_GET_OkResponseSchema.description,
294294
content={"providers": {"internal": sorted(MAGPIE_INTERNAL_PROVIDERS.values()),
295-
"external": sorted(MAGPIE_EXTERNAL_PROVIDERS.values()), }})
295+
"external": sorted(MAGPIE_EXTERNAL_PROVIDERS.values()), }})

‎magpie/api/management/resource/resource_formats.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,11 @@ def format_resource_tree(children, db_session, resources_perms_dict=None, _inter
8383
perms = _internal_svc_res_perm_dict[service_id][resource.resource_type] # 'resource_type' is str here
8484

8585
fmt_res_tree[child_id] = format_resource(resource, perms)
86-
fmt_res_tree[child_id]["children"] = format_resource_tree(new_children, db_session,
87-
resources_perms_dict, _internal_svc_res_perm_dict)
86+
fmt_res_tree[child_id]["children"] = format_resource_tree(
87+
new_children, db_session,
88+
resources_perms_dict,
89+
_internal_svc_res_perm_dict
90+
)
8891

8992
return fmt_res_tree
9093

‎magpie/api/management/resource/resource_utils.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
# pylint: disable=W0611,unused-import
2626
from pyramid.httpexceptions import HTTPException
2727
from sqlalchemy.orm.session import Session
28-
from magpie.typedefs import List, Str, Optional, Tuple, Type, ServiceOrResourceType # noqa: F401
28+
from magpie.typedefs import List, Str, Optional, Tuple, Type, ServiceOrResourceType, Union # noqa: F401
2929
from magpie.services import ServiceInterface # noqa: F401
3030

3131

@@ -121,7 +121,7 @@ def get_resource_permissions(resource, db_session):
121121
msg_on_fail=s.UserResourcePermissions_GET_BadRequestResourceResponseSchema.description)
122122
# directly access the service resource
123123
if resource.root_service_id is None:
124-
service = resource
124+
service = resource # type: models.Service # noqa
125125
return SERVICE_TYPE_DICT[service.type].permissions
126126

127127
# otherwise obtain root level service to infer sub-resource permissions
@@ -137,7 +137,7 @@ def get_resource_permissions(resource, db_session):
137137

138138

139139
def get_resource_root_service(resource, db_session):
140-
# type: (models.Resource, Session) -> Optional[models.Resource]
140+
# type: (Union[models.Service, models.Resource], Session) -> Optional[models.Service]
141141
"""
142142
Recursively rewinds back through the top of the resource tree up to the top-level service-resource.
143143

‎magpie/api/management/service/service_utils.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from typing import TYPE_CHECKING
22

3-
import colander
43
from pyramid.httpexceptions import HTTPBadRequest, HTTPConflict, HTTPCreated, HTTPForbidden, HTTPInternalServerError
54
from ziggurat_foundations.models.services.group import GroupService
65
from ziggurat_foundations.models.services.resource import ResourceService

‎magpie/register.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
if TYPE_CHECKING:
4949
# pylint: disable=W0611,unused-import
5050
from magpie.typedefs import ( # noqa: F401
51-
Any, AnyCookiesType, CookiesOrSessionType, Dict, List, JSON, Optional, Str, Tuple, Union
51+
Any, AnyCookiesType, CookiesOrSessionType, Dict, Iterable, List, JSON, Optional, Str, Tuple, Union
5252
)
5353
ConfigItem = Dict[Str, Str]
5454
ConfigList = List[ConfigItem]
@@ -276,25 +276,27 @@ def _register_services(where, # type: Optional[Str]
276276
return success, statuses
277277

278278

279-
def sync_services_phoenix(services_object_dict, services_as_dicts=False):
280-
# type: (Dict[Str, Union[models.Service, JSON]], bool) -> bool
279+
def sync_services_phoenix(services, services_as_dicts=False):
280+
# type: (Union[Iterable[models.Service], JSON], bool) -> bool
281281
"""
282282
Syncs Magpie services by pushing updates to Phoenix.
283283
284284
Services must be one of types specified in :py:data:`magpie.register.SERVICES_PHOENIX_ALLOWED`.
285285
286-
:param services_object_dict:
287-
dictionary of ``{svc-name: models.Service}`` objects containing each service's information
288-
:param services_as_dicts:
289-
alternatively specify :paramref:`services_object_dict` as dict of ``{svc-name: {service-info}}``
290-
where ``{service-info}`` is defined as::
286+
:param services:
287+
An iterable of :class:`models.Service` by default, or a dictionary of ``{svc-name: {<service-info>}}`` JSON
288+
objects containing each service's information if :paramref:`services_ad_dicts` is ``True``.
289+
290+
where ``<service-info>`` is defined as::
291291
292292
{"public_url": <url>, "service_name": <name>, "service_type": <type>}
293+
294+
:param services_as_dicts: indicate if services must be parsed as JSON definitions.
293295
"""
294296
services_dict = {}
295-
for svc in services_object_dict:
297+
for svc in services:
296298
if services_as_dicts:
297-
svc_dict = services_object_dict[svc]
299+
svc_dict = services[svc]
298300
services_dict[svc] = {"url": svc_dict["public_url"], "title": svc_dict["service_name"],
299301
"type": svc_dict["service_type"], "c4i": False, "public": True}
300302
else:

‎magpie/typedefs.py

-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@
4545
AnyCookiesType = Union[CookiesType, RequestsCookieJar]
4646
AnyResponseType = Union[WebobResponse, PyramidResponse, TestResponse]
4747
CookiesOrSessionType = Union[RequestsCookieJar, Session]
48-
OptionalHeaderCookiesType = Tuple[Optional[AnyHeadersType], Optional[AnyCookiesType]]
4948

5049
AnyKey = Union[Str, int]
5150
AnyValue = Union[Str, Number, bool, None]

‎tests/interfaces.py

+47-44
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import unittest
22
import warnings
3-
from abc import ABCMeta, abstactmethod
3+
from abc import ABCMeta, abstractmethod
44
from copy import deepcopy
55
from distutils.version import LooseVersion
66
from typing import TYPE_CHECKING
@@ -29,45 +29,40 @@ class Base_Magpie_TestCase(six.with_metaclass(ABCMeta, unittest.TestCase)):
2929
"""
3030
Base definition for all other Test Suite interfaces.
3131
32-
The implementers must provide :meth:`initClass` which prepares the various test parameters, session cookies and
32+
The implementers must provide :meth:`setUpClass` which prepares the various test parameters, session cookies and
3333
the local application or remote Magpie URL configuration to evaluate test cases on.
3434
3535
The implementers Test Suites must also set :attr:`__test__` to ``True`` so that tests are picked up as executable.
3636
3737
.. note::
3838
Attribute attr:`__test__` is employed to avoid duplicate runs of this base class or other derived classes that
3939
must not be considered as the *final implementer* Test Suite.
40-
41-
.. warning::
42-
Do not use :meth:`setUpClass` with :py:exception:`NotImplementedError` in this class or any derived *incomplete*
43-
class as this method still gets called by some test runners although marked with ``__test__ = False``.
44-
The tests would be interpreted as failing in this situation (due to raised error) instead of only indicating an
45-
abstract class definition. You are free to use it if the method is non-raising, but remember that the code will
46-
be executed during initialization of the Test Suite even if seemingly disabled for testing.
4740
"""
4841
# pylint: disable=C0103,invalid-name
4942
version = None # type: Optional[Str]
43+
require = None # type: Optional[Str]
44+
# parameters for setup operations, admin-level access to the app
5045
grp = None # type: Optional[Str]
5146
usr = None # type: Optional[Str]
5247
pwd = None # type: Optional[Str]
53-
require = None # type: Optional[Str]
5448
cookies = None # type: Optional[CookiesType]
5549
headers = None # type: Optional[HeadersType]
5650
json_headers = None # type: Optional[HeadersType]
51+
# parameters for testing, extracted automatically within utils.TestSetup methods
5752
test_service_type = None # type: Optional[Str]
5853
test_service_name = None # type: Optional[Str]
59-
test_user = None # type: Optional[Str]
60-
test_group = None # type: Optional[Str]
54+
test_user_name = None # type: Optional[Str]
55+
test_group_name = None # type: Optional[Str]
6156

6257
__test__ = False # won't run this as a test suite, only its derived classes that overrides to True
6358

6459
@classmethod
65-
@abstactmethod
66-
def initClass(cls):
60+
@abstractmethod
61+
def setUpClass(cls):
6762
raise NotImplementedError
6863

6964
@classmethod
70-
def tearDownClass(cls): # noqa: N802
65+
def tearDownClass(cls):
7166
pyramid.testing.tearDown()
7267

7368

@@ -77,16 +72,12 @@ class Interface_MagpieAPI_NoAuth(six.with_metaclass(ABCMeta, Base_Magpie_TestCas
7772
"""
7873
Interface class for unittests of Magpie API. Test any operation that do not require user AuthN/AuthZ.
7974
80-
Derived classes must implement :meth:`initClass` accordingly to generate the Magpie test application.
75+
Derived classes must implement :meth:`setUpClass` accordingly to generate the Magpie test application.
8176
"""
8277

83-
@classmethod
84-
def initClass(cls):
85-
raise NotImplementedError
86-
8778
@classmethod
8879
def setUpClass(cls):
89-
cls.initClass()
80+
raise NotImplementedError
9081

9182
@runner.MAGPIE_TEST_LOGIN
9283
def test_GetSession_Anonymous(self):
@@ -130,18 +121,30 @@ def test_NotAcceptableRequest(self):
130121
utils.check_response_basic_info(resp, expected_code=406)
131122

132123
@runner.MAGPIE_TEST_USERS
124+
@runner.MAGPIE_TEST_LOGGED
133125
def test_RegisterDiscoverableGroup_Unauthorized(self):
134126
"""Not logged-in user cannot update membership to group although group is discoverable."""
135-
raise NotImplementedError # TODO
127+
utils.warn_version(self, "User registration views not yet available.", "2.0.0", skip=True)
128+
resp = utils.test_request(self, "GET", "/register/groups", headers=self.json_headers, expect_errors=True)
129+
body = utils.check_response_basic_info(resp, 401)
130+
utils.check_val_not_in("group_names", body)
136131

137132
@runner.MAGPIE_TEST_USERS
138133
def test_UnregisterDiscoverableGroup_Unauthorized(self):
139134
"""Not logged-in user cannot remove membership to group although group is discoverable."""
140-
raise NotImplementedError # TODO
135+
utils.warn_version(self, "User registration views not yet available.", "2.0.0", skip=True)
136+
path = "/register/groups/random-group"
137+
resp = utils.test_request(self, "DELETE", path, headers=self.json_headers, expect_errors=True)
138+
utils.check_response_basic_info(resp, 401)
141139

142140
def test_ViewDiscoverableGroup_Unauthorized(self):
143141
"""Not logged-in user cannot view group although group is discoverable."""
144-
raise NotImplementedError # TODO
142+
utils.warn_version(self, "User registration views not yet available.", "2.0.0", skip=True)
143+
utils.TestSetup
144+
145+
path = "/register/groups/random-group"
146+
resp = utils.test_request(self, "DELETE", path, headers=self.json_headers, expect_errors=True)
147+
utils.check_response_basic_info(resp, 401)
145148

146149
def test_ListDiscoverableGroup_Unauthorized(self):
147150
"""Not logged-in user cannot list group names although groups are discoverable."""
@@ -154,11 +157,11 @@ class Interface_MagpieAPI_UsersAuth(six.with_metaclass(ABCMeta, Base_Magpie_Test
154157
"""
155158
Interface class for unittests of Magpie API. Test any operation that require at least logged user AuthN/AuthZ.
156159
157-
Derived classes must implement :meth:`initClass` accordingly to generate the Magpie test application.
160+
Derived classes must implement :meth:`setUpClass` accordingly to generate the Magpie test application.
158161
"""
159162

160163
@classmethod
161-
def initClass(cls):
164+
def setUpClass(cls):
162165
raise NotImplementedError
163166

164167
@classmethod
@@ -352,11 +355,11 @@ class Interface_MagpieAPI_AdminAuth(six.with_metaclass(ABCMeta, Base_Magpie_Test
352355
Interface class for unittests of Magpie API. Test any operation that require at least 'administrator' group
353356
AuthN/AuthZ.
354357
355-
Derived classes must implement :meth:`initClass` accordingly to generate the Magpie test application.
358+
Derived classes must implement :meth:`setUpClass` accordingly to generate the Magpie test application.
356359
"""
357360

358361
@classmethod
359-
def initClass(cls):
362+
def setUpClass(cls):
360363
raise NotImplementedError
361364

362365
def tearDown(self):
@@ -404,7 +407,6 @@ def setup_test_values(cls):
404407

405408
cls.test_group_name = "magpie-unittest-dummy-group"
406409
cls.test_user_name = "magpie-unittest-toto"
407-
cls.test_user_group = get_constant("MAGPIE_USERS_GROUP")
408410

409411
def setUp(self):
410412
self.check_requirements()
@@ -536,15 +538,15 @@ def test_GetCurrentUserResourcesPermissions_Queries(self):
536538
body = utils.TestSetup.create_TestService(self, override_service_type=ServiceAPI.service_type)
537539
test_svc_res_id = body["service"]["resource_id"]
538540
test_res_type = Route.resource_type_name
539-
body = utils.TestSetup.create_TestServiceResource(self, data_override={"resource_type": test_res_type})
541+
body = utils.TestSetup.create_TestServiceResource(self, override_data={"resource_type": test_res_type})
540542
test_parent_res_id = body["resource"]["resource_id"]
541543
child_resource_name = self.test_resource_name + "-child"
542-
data_override = {
544+
override_data = {
543545
"resource_name": child_resource_name,
544546
"resource_type": test_res_type,
545547
"parent_id": test_parent_res_id
546548
}
547-
body = utils.TestSetup.create_TestServiceResource(self, data_override)
549+
body = utils.TestSetup.create_TestServiceResource(self, override_data)
548550
test_child_res_id = body["resource"]["resource_id"]
549551
anonym_usr = get_constant("MAGPIE_ANONYMOUS_USER")
550552
anonym_grp = get_constant("MAGPIE_ANONYMOUS_GROUP")
@@ -617,7 +619,7 @@ def test_PostUserResourcesPermissions_Created(self):
617619
utils.TestSetup.delete_TestServiceResource(self, override_resource_name=resource_name)
618620

619621
data = {"resource_name": resource_name}
620-
body = utils.TestSetup.create_TestServiceResource(self, data_override=data)
622+
body = utils.TestSetup.create_TestServiceResource(self, override_data=data)
621623
test_res_id = body["resource"]["resource_id"]
622624

623625
# test permission creation
@@ -641,7 +643,7 @@ def test_PostUserResourcesPermissions_Conflict(self):
641643
utils.TestSetup.delete_TestServiceResource(self, override_resource_name=resource_name)
642644

643645
data = {"resource_name": resource_name}
644-
body = utils.TestSetup.create_TestServiceResource(self, data_override=data)
646+
body = utils.TestSetup.create_TestServiceResource(self, override_data=data)
645647
test_res_id = body["resource"]["resource_id"]
646648

647649
path = "/users/{usr}/resources/{res}/permissions".format(res=test_res_id, usr=self.usr)
@@ -978,7 +980,7 @@ def test_PostUsers_InvalidParameters(self):
978980
"user_name": self.test_user_name,
979981
"email": "{}@mail.com".format(self.test_user_name),
980982
"password": self.test_user_name,
981-
"group_name": self.test_user_group,
983+
"group_name": self.test_group_name,
982984
}
983985
for code, variant in [
984986
(400, {"user_name": ""}),
@@ -1214,7 +1216,8 @@ def test_PostUserGroup_conflict(self):
12141216

12151217
@runner.MAGPIE_TEST_USERS
12161218
def test_GetUserGroups(self):
1217-
utils.TestSetup.create_TestUser(self) # automatically adds user to "MAGPIE_USERS_GROUP"
1219+
users_group = get_constant("MAGPIE_USERS_GROUP")
1220+
utils.TestSetup.create_TestUser(self, override_group_name=users_group)
12181221
utils.TestSetup.create_TestGroup(self)
12191222
utils.TestSetup.assign_TestUserGroup(self)
12201223

@@ -1224,7 +1227,7 @@ def test_GetUserGroups(self):
12241227
body = utils.check_response_basic_info(resp, 200, expected_method="GET")
12251228
utils.check_val_is_in("group_names", body)
12261229
utils.check_val_type(body["group_names"], list)
1227-
expected_groups = {self.test_group_name, self.test_user_group}
1230+
expected_groups = {self.test_group_name, users_group}
12281231
if LooseVersion(self.version) >= LooseVersion("1.4.0"):
12291232
expected_groups.add(get_constant("MAGPIE_ANONYMOUS_GROUP"))
12301233
utils.check_all_equal(body["group_names"], expected_groups, any_order=True)
@@ -1767,12 +1770,12 @@ def test_PostServiceResources_ChildrenResource_ParentID(self):
17671770

17681771
# create the child resource under the direct resource and validate response info
17691772
child_resource_name = self.test_resource_name + "-children"
1770-
data_override = {
1773+
override_data = {
17711774
"resource_name": child_resource_name,
17721775
"resource_type": self.test_resource_type,
17731776
"parent_id": test_resource_id
17741777
}
1775-
body = utils.TestSetup.create_TestServiceResource(self, data_override)
1778+
body = utils.TestSetup.create_TestServiceResource(self, override_data)
17761779
if LooseVersion(self.version) >= LooseVersion("0.6.3"):
17771780
utils.check_val_is_in("resource", body)
17781781
utils.check_val_type(body["resource"], dict)
@@ -1950,11 +1953,11 @@ class Interface_MagpieUI_NoAuth(six.with_metaclass(ABCMeta, Base_Magpie_TestCase
19501953
"""
19511954
Interface class for unittests of Magpie UI. Test any operation that do not require user AuthN/AuthZ.
19521955
1953-
Derived classes must implement :meth:`initClass` accordingly to generate the Magpie test application.
1956+
Derived classes must implement :meth:`setUpClass` accordingly to generate the Magpie test application.
19541957
"""
19551958

19561959
@classmethod
1957-
def initClass(cls):
1960+
def setUpClass(cls):
19581961
raise NotImplementedError
19591962

19601963
@runner.MAGPIE_TEST_STATUS
@@ -2028,7 +2031,7 @@ class Interface_MagpieUI_UsersAuth(six.with_metaclass(ABCMeta, Base_Magpie_TestC
20282031
"""
20292032
Interface class for unittests of Magpie UI. Test any operation that require at least logged user AuthN/AuthZ.
20302033
2031-
Derived classes must implement :meth:`initClass` accordingly to generate the Magpie test application.
2034+
Derived classes must implement :meth:`setUpClass` accordingly to generate the Magpie test application.
20322035
"""
20332036

20342037
def __init__(self, *args, **kwargs):
@@ -2087,11 +2090,11 @@ class Interface_MagpieUI_AdminAuth(six.with_metaclass(ABCMeta, Base_Magpie_TestC
20872090
Interface class for unittests of Magpie UI. Test any operation that require at least 'administrator' group
20882091
AuthN/AuthZ.
20892092
2090-
Derived classes must implement :meth:`initClass` accordingly to generate the Magpie test application.
2093+
Derived classes must implement :meth:`setUpClass` accordingly to generate the Magpie test application.
20912094
"""
20922095

20932096
@classmethod
2094-
def initClass(cls):
2097+
def setUpClass(cls):
20952098
raise NotImplementedError
20962099

20972100
@classmethod

0 commit comments

Comments
 (0)