我开始在我的django项目中使用unitest,并且对测试process_email()
感兴趣。由于我正在测试电子邮件功能,因此我对测试parse_email()
函数感兴趣。下面的代码是命令行管理功能(即我做python manage.py process_email)。
如何在我的单元测试中调用parse_email()
?
由于此代码位于名为somemodel/management/commands/process_email.py
的文件中,因此只能看到process_email()
。随后,call_command('parse_email', mail.outbox[1].body, interactive=False)
将无效,因为只有process_email()
可见。
def process_email():
server = imaplib.IMAP4_SSL(settings.EMAIL_HOST,993)
server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
server.select('INBOX')
status, data = server.search(None, 'NOT', 'DELETED')
if data:
msgnums = data[0].split()
for num in msgnums:
status, data = server.fetch(num, '(RFC822)')
valid = parse_email(data[0][1])
print "valid is ", valid
# if not valid:
server.store(num, '+FLAGS', '\\Deleted')
server.expunge()
server.close()
server.logout()
def parse_email(message):
# 'message' must be an RFC822 formatted message.
pdb.set_trace()
try:
msg = message
message = email.message_from_string(msg)
subject = message.get('subject', _('Created from e-mail'))
subject = decode_mail_headers(decodeUnknown(message.get_charset(), subject))
subject = subject.replace("Re: ", "").replace("Fw: ", "").replace("RE: ", "").replace("FW: ", "").strip()
这就是我的意思,当我说它不可见时(可能错误地使用了这个词):当我在我的测试文件中调用call_command('parse_email')
时,我收到以下错误:
======================================================================
ERROR: test_submit_bldg (bldg.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/bldg/tests.py", line 36, in test_submit_bldg
print call_command('parse_email')
File "django/core/management/__init__.py", line 136, in call_command
raise CommandError("Unknown command: %r" % name)
CommandError: Unknown command: 'parse_email'
答案 0 :(得分:1)
您可以直接从测试中导入parse_email
:
from somemodel.management.commands.process_email import parse_email
assert_equals(parse_email("..."), ...)