我开始在我的 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'