事情有点复杂,让我给你看一个最小的例子。
在我的应用程序中,我从 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_TRANSFORMER
from的值导入类即可。因此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中,follow
function仍然使用DefaultVerbTransformer
而不是override设置TestVerbTransformer
。</p>
这里有什么问题?