事情有点复杂,让我向您展示一个最小的例子。
在我的应用中,我从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
中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
功能仍然使用DefaultVerbTransformer
而不是覆盖设置TestVerbTransformer
。
这里的问题是什么?