I started using unitest in my django projects, and am interested in testing process_email(). Since I am testing email functionality, I am interested in testing the parse_email() function. This code below is command line management function (i.e. I do python manage.py process_email).
How do I call parse_email() in my unittest?
Since this code is in a file called somemodel/management/commands/process_email.py, only process_email() is visible. Subsequently, call_command('parse_email', mail.outbox[1].body, interactive=False) will not work since only process_email() is visible.
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()
Here is what I mean when I say it is not visible (perhaps the wrong use of the word): When I call call_command('parse_email') in my test file, I get the following error:
======================================================================
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'
You can import
parse_emaildirectly from your tests: