2012-04-19 76 views
1

Somwhere在我的模型中定义了一个文件系统,该文件系统为用户配置文件指定了保存数据的自定义位置。这是非常简单的,看起来像这样:覆盖自定义文件系统的测试设置 - 如何?

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' 

所以设置已经覆盖。它看起来像我的自定义文件系统只是没有反应的设置覆盖。为什么?可能是压倒性的,还是文件系统在某一时刻启动,并且之后无法更改?

回答

0

我猜social_user_fs在其模块中是全球性的,并且您在测试之外从该模块导入东西。所以它在调用测试方法(和装饰器)之前得到处理。

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