覆盖自定义文件系统的测试设置 - 如何?

时间:2012-04-19 09:15:51

标签: django django-testing django-settings

在我的模型中,我已经定义了一个文件系统,它指定了一个自定义位置来保存用户配置文件的数据。它非常简单,看起来像这样:

social_user_fs = FileSystemStorage(location=settings.SOCIAL_USER_FILES,
                                   base_url=settings.SOCIAL_USER_URL)

然后我在这样的模型中使用:

class SocialUserProfile(models.Model):

    def get_user_profileimg_path(self, filename):
        return '%s/profile_images/%s' % (self.user_id, filename)
    image = models.ImageField(upload_to=get_user_profileimg_path,
                              storage=social_user_fs,
                              blank=True)

这非常有效并且表现得像我期望的那样。但现在我遇到了测试问题:

import os

from django.test import TestCase
from django.test.utils import override_settings

from social_user.forms import ProfileImageUploadForm #@UnresolvedImport
from social_user.models import SocialUserProfile #@UnresolvedImport

# point the filesystem to the subfolder data of app/test/
@override_settings(SOCIAL_USER_FILES = os.path.dirname(__file__)+'/testdata',
                   SOCIAL_USER_URL = 'profiles/')

class TestProfileImageUploadForm(TestCase):

    fixtures = ['social_user_profile_fixtures.json']

    def test_save(self):
        profile = SocialUserProfile.objects.get(pk=1)
        import ipdb; ipdb.set_trace()

交互式调试会话给了我:

ipdb> from django.conf import settings
ipdb> settings.SOCIAL_USER_FILES
'/Volumes/Data/Website/Backend/project/social_user/tests/testdata'
ipdb> settings.SOCIAL_USER_URL
'profiles/'
# ok, the settings have been changed, the filesystem should use the new values

ipdb> profile.image.url
'/user_files/profiles/1/profile_images/picture1-1.png' 
# 'profiles/1/profile_images/picture1-1.png'
# would be correct with the new settings
# the actual value still uses the original settings

ipdb> f = file(profile.image.file)
*** IOError: [Errno 2] No such file or directory:
u'/Volumes/Data/Website/Backend/user_files/profiles/1/profile_images/picture1-1.png'
# same here, overridden settings should result in
# '/Volumes/Data/Website/Backend/social_user/tests/testdata/1/profile_images/picture1-1.png'

因此设置已被覆盖。看起来我的自定义文件系统只是没有对设置的覆盖作出反应。为什么?是否可以覆盖,或者文件系统是否在某个时间点启动,之后无法更改?

1 个答案:

答案 0 :(得分:0)

我猜social_user_fs在其模块中是全局的,并且您在测试之外从该模块导入内容。因此在调用test方法(和装饰器)之前会对其进行处理。

SocialUserProfile内导入test_save,我认为这将是最好的灵魂。