2016-10-20 48 views
1

我想爲一些自定義的Django電子郵件後端編寫unittests,並測試它對「真正的」smtp服務器,我試圖使用Python的內置smtpd調試服務器運行:如何從Python的smtp調試服務器捕獲輸出

python -m smtpd -n -c DebuggingServer localhost:1025 

我的單元測試基本上是這樣的:

class Tests(TestCase): 

    @override_settings(EMAIL_BACKEND='mycustombackend') 
    @override_settings(EMAIL_HOST='localhost') 
    @override_settings(EMAIL_PORT='1025') 
    def test_backend(self): 
     from django.core import mail 
     mail.send_mail(
       subject='Subject here', 
       message='Here is the message.', 
       from_email='[email protected]', 
       recipient_list=['[email protected]'], 
       fail_silently=False, 
      ) 

,當我運行此,該smtpd的過程中,電子郵件的內容正確輸出。

但是,當我嘗試捕獲它,以便我可以在我的單元測試中確認它時,我什麼也得不到。我試過使用subprocess包來啓動進程並通過管道讀取輸出,但它從來沒有收到任何輸出。

我想我是用錯誤的子進程,所以作爲最後的手段,我試着啓動過程有:

python -m smtpd -n -c DebuggingServer localhost:1025 > /tmp/smtpd.log 

和讀取日誌文件。但是,即使如此,也沒有輸出寫入文件。

這是怎麼回事嗎?

回答

3

我有同樣的問題,花了2天試圖找出發生了什麼。我試圖同時運行

python -m smtpd -n -c DebuggingServer localhost:1025 

python -m smtpd -n -c DebuggingServer localhost:1025 > mail.log 

subprocess我的集成測試之一,但沒有奏效。在通過REPL進行試驗時,我注意到首先從subprocess打開的管道中讀取數據。我殺了它後,下一次閱讀實際上會返回數據。所以我開始調查流中的內容。但是因爲我在兩個小時內沒有運氣,所以我最終圍繞着自己的包裝文件SMTPServer寫入文件,並讓自己啓動並運行。

這裏是包裝類(process_message是受smtpd模塊所需smtpd.SMTPServer的子類的是可運行一個抽象方法):我與

python -m smtpd -n -c test_smtpd.SMTPTestServer localhost:1025 

運行它

# test_smtpd.py 

import smtpd 

SMTP_DUMPFILE = '/tmp/mail.log' 

class SMTPTestServer(smtpd.SMTPServer): 
    def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): 
     with open(SMTP_DUMPFILE, 'w') as f: 
      f.write(data) 

儘管這不能直接回答你的問題,但這是一個簡單的解決方法,所以我希望這有助於解決問題。

0

根據this answer,輸出緩衝時接通:

過程STDOUT被重定向到比終端

其它東西所建議的解決方案將在這種情況下是:

stdbuf -oL python -m smtpd -n -c DebuggingServer localhost:1025 > mail.log 
相關問題