2

事情有点复杂,让我给你看一个最小的例子。

在我的应用程序中,我从 django 设置中动态导入一个类:

 my_settings.py     

 from django.conf import settings

 SETTINGS = getattr(settings, 'ACTSTREAM_SETTINGS', {})

 def get_verb_transformer():
     mod = SETTINGS.get('VERB_TRANSFORMER', 'actstream.transformers.DefaultVerbTransformer')
     mod_path = mod.split('.')
     try:
         return getattr(__import__('.'.join(mod_path[:-1]), {}, {},
                                  [mod_path[-1]]), mod_path[-1])()
     except ImportError:
         raise ImportError(
            'Cannot import %s try fixing ACTSTREAM_SETTINGS[VERB_TRANSFORMER]'
            'setting.' % mod
         )

get_verb_transformer只需根据VERB_TRANSFORMERfrom的值导入类即可。因此django.conf.settings,我们允许开发人员指定自己的自定义VerbTransformer类。或者,如果他们不提供,内置DefaultVerbTransformer作为后备。

然后我在其他地方使用了导入的类:

from . import my_settings

def follow(user, obj, send_action=True, actor_only=True, flag='', **kwargs):
     instance, created = apps.get_model('actstream', 'follow').objects.get_or_create(
         user=user, object_id=obj.pk, flag=flag,
         content_type=ContentType.objects.get_for_model(obj),
         actor_only=actor_only
     )
     if send_action and created:
         if not flag:
             action.send(user, verb=_('started following'), target=obj, **kwargs)
         else:
             action.send(user, verb=_('started %s' % flag), target=obj, **kwargs)        

             ########### used here ###########
             transformer = settings.get_verb_transformer()
             action.send(user, verb=_('started %s' % transformer.trans(flag)), target=obj, **kwargs)
     return instance

然后我想测试开发人员自定义设置是否有效:

    @override_settings(ACTSTREAM_SETTINGS={'VERB_TRANSFORMER': 
 'actstream.tests.base.TestVerbTransformer'})
     def test_follow_verb_transformation(self):
         # User4 blocks user3
         follow(self.user4, self.another_user, timestamp=self.testdate, flag='block')
         # User4 quits group
         follow(self.user4, self.another_comment, timestamp=self.testdate, flag='quit')

但是,在unittest中,followfunction仍然使用DefaultVerbTransformer而不是override设置TestVerbTransformer。</p>

这里有什么问题?

4

0 回答 0