Skip to content

Commit 655335b

Browse files
author
voxy-pairstation
committed
Make utils.local_import check INSTALLED_APPS for compound paths
- Checks all possible iterations of app name against `INSTALLED_APPS`, so `app.sub_app.module.Class` checks `INSTALLED_APPS` for `app.sub_app.module`, then `app.sub_app`, then `app`, instead of just checking for `app`. - Adds test to characterize new import behavior. - Fixes issue #13
1 parent 572ff38 commit 655335b

File tree

6 files changed

+18
-3
lines changed

6 files changed

+18
-3
lines changed

rest_framework_serializer_extensions/utils.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,14 @@ def import_local(path_to_object):
1515
"""
1616
path, name = path_to_object.rsplit('.', 1)
1717

18-
app = path.split('.')[0]
19-
20-
if app not in settings.INSTALLED_APPS:
18+
path_pieces = path.split('.')
19+
while path_pieces:
20+
if '.'.join(path_pieces) not in settings.INSTALLED_APPS:
21+
path_pieces.pop()
22+
else:
23+
break
24+
25+
if not path_pieces:
2126
raise AssertionError(
2227
"Cannot import from outside installed apps"
2328
)

test_package/__init__.py

Whitespace-only changes.

test_package/test_module/__init__.py

Whitespace-only changes.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
class TestSerializer(object):
2+
pass

tests/conftest.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ def pytest_configure():
3434
'rest_framework.authtoken',
3535
'rest_framework_serializer_extensions',
3636
'tests',
37+
'test_package.test_module',
3738
),
3839
PASSWORD_HASHERS=(
3940
'django.contrib.auth.hashers.SHA1PasswordHasher',

tests/test_utils.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from django.test import override_settings, TestCase
55

66
from rest_framework_serializer_extensions import fields, utils
7+
from test_package.test_module.serializers import TestSerializer
78
from tests import models
89
from tests.base import TEST_HASH_IDS
910

@@ -30,6 +31,12 @@ def test_import_within_installed_apps(self):
3031
)
3132
self.assertIs(imported, fields.HashIdField)
3233

34+
def test_import_complex_path_within_installed_apps(self):
35+
imported = utils.import_local(
36+
'test_package.test_module.serializers.TestSerializer'
37+
)
38+
self.assertIs(imported, TestSerializer)
39+
3340

3441
class GetSettingTests(TestCase):
3542
"""

0 commit comments

Comments
 (0)