Skip to content

Commit

Permalink
Make utils.local_import check INSTALLED_APPS for compound paths
Browse files Browse the repository at this point in the history
 - 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 evenicoulddoit#13
  • Loading branch information
voxy-pairstation committed Aug 14, 2017
1 parent 572ff38 commit 655335b
Show file tree
Hide file tree
Showing 6 changed files with 18 additions and 3 deletions.
11 changes: 8 additions & 3 deletions rest_framework_serializer_extensions/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,14 @@ def import_local(path_to_object):
"""
path, name = path_to_object.rsplit('.', 1)

app = path.split('.')[0]

if app not in settings.INSTALLED_APPS:
path_pieces = path.split('.')
while path_pieces:
if '.'.join(path_pieces) not in settings.INSTALLED_APPS:
path_pieces.pop()
else:
break

if not path_pieces:
raise AssertionError(
"Cannot import from outside installed apps"
)
Expand Down
Empty file added test_package/__init__.py
Empty file.
Empty file.
2 changes: 2 additions & 0 deletions test_package/test_module/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
class TestSerializer(object):
pass
1 change: 1 addition & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def pytest_configure():
'rest_framework.authtoken',
'rest_framework_serializer_extensions',
'tests',
'test_package.test_module',
),
PASSWORD_HASHERS=(
'django.contrib.auth.hashers.SHA1PasswordHasher',
Expand Down
7 changes: 7 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from django.test import override_settings, TestCase

from rest_framework_serializer_extensions import fields, utils
from test_package.test_module.serializers import TestSerializer
from tests import models
from tests.base import TEST_HASH_IDS

Expand All @@ -30,6 +31,12 @@ def test_import_within_installed_apps(self):
)
self.assertIs(imported, fields.HashIdField)

def test_import_complex_path_within_installed_apps(self):
imported = utils.import_local(
'test_package.test_module.serializers.TestSerializer'
)
self.assertIs(imported, TestSerializer)


class GetSettingTests(TestCase):
"""
Expand Down

0 comments on commit 655335b

Please sign in to comment.