o
    b                     @   s  U d Z ddlZddlZddlZddlmZ ddlmZmZm	Z	m
Z
mZ ddlmZmZ ddlZddlZddlZddlZddlmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZmZmZmZm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z(m)Z) ddl*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 e	e1 e2d< z
ddl3m4Z4m5Z5 W n e6y   dZ7Y nw dZ7ej89e!sdZ7dd Z:ee$j;G dd dZ<G dd dZ=G dd dZ>dZ?G dd  d Z@G d!d" d"e@e$jAZBG d#d$ d$e@e$jCZDG d%d& d&ZEG d'd( d(e(jFZGG d)d* d*e0eEZHG d+d, d,ZIG d-d. d.ZJG d/d0 d0eJe$jKZLG d1d2 d2eJe$jMZNG d3d4 d4ZOG d5d6 d6eOe0ZPG d7d8 d8eOe0ZQeejRjG d9d: d:ZSee$jTG d;d< d<ZUG d=d> d>ZVG d?d@ d@e0eEZWG dAdB dBe0ZXG dCdD dDeDZYG dEdF dFe0eEZZG dGdH dHe0Z[G dIdJ dJe0eEZ\G dKdL dLe j]Z^G dMdN dNe0Z_G dOdP dPe0Z`eeG dQdR dRZaG dSdT dTZbG dUdV dVe0ZcG dWdX dXe0ZdG dYdZ dZe0ZeG d[d\ d\e0ZfG d]d^ d^e0ZgG d_d` d`e0ZhG dadb dbe.ZiG dcdd dde0ZjdS )ez*
Test cases for twisted.mail.smtp module.
    N)BytesIO)AnyListOptionalTupleType)directlyProvidesimplementer)cred)AllowAnonymousAccessICredentialsChecker)
IAnonymous)UnauthorizedLogin)IRealmPortal)addressdefererror
interfacesprotocolreactortask)smtp)LOGINCredentials)basicloopback)LineLog)MemoryReactorStringTransport)TestCasesslSkip)ClientTLSContextServerTLSContextzOpenSSL not presentzReactor doesn't support SSLc                  O      d S N )spameggsr%   r%   =/usr/lib/python3/dist-packages/twisted/mail/test/test_smtp.py	spameater/      r)   c                   @   0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )BrokenMessagez
    L{BrokenMessage} is an L{IMessage} which raises an unexpected exception
    from its C{eomReceived} method.  This is useful for creating a server which
    can be used to test client retry behavior.
    c                 C   r#   r$   r%   selfuserr%   r%   r(   __init__;   r*   zBrokenMessage.__init__c                 C   r#   r$   r%   r.   liner%   r%   r(   lineReceived>   r*   zBrokenMessage.lineReceivedc                 C      t d)Nz"Some problem, delivery is failing.)RuntimeErrorr.   r%   r%   r(   eomReceivedA      zBrokenMessage.eomReceivedc                 C   r#   r$   r%   r6   r%   r%   r(   connectionLostD   r*   zBrokenMessage.connectionLostN)__name__
__module____qualname____doc__r0   r3   r7   r9   r%   r%   r%   r(   r,   3   s    r,   c                   @   (   e Zd ZdZdd Zdd Zdd ZdS )	DummyMessagez
    L{BrokenMessage} is an L{IMessage} which saves the message delivered to it
    to its domain object.

    @ivar domain: A L{DummyDomain} which will be used to store the message once
        it is received.
    c                 C      || _ || _g | _d S r$   )domainr/   buffer)r.   rA   r/   r%   r%   r(   r0   Q      
zDummyMessage.__init__c                 C   s    t d|s| j| d S d S )Ns/   Received: From yyy.com \(\[.*\]\) by localhost;)rematchrB   appendr1   r%   r%   r(   r3   V   s   zDummyMessage.lineReceivedc                 C   s>   d | jd }| jj| jjj | t	 }|
d |S )N   
   saved)joinrB   rA   messagesr/   destlocalrF   r   Deferredcallback)r.   messagedeferredr%   r%   r(   r7   [   s
   
zDummyMessage.eomReceivedN)r:   r;   r<   r=   r0   r3   r7   r%   r%   r%   r(   r?   H   s
    r?   c                   @       e Zd ZdZdd Zdd ZdS )DummyDomainzf
    L{DummyDomain} is an L{IDomain} which keeps track of messages delivered to
    it in memory.
    c                 C   s   i | _ |D ]}g | j |< qd S r$   )rJ   )r.   namesnamer%   r%   r(   r0   i   s   zDummyDomain.__init__c                    s2   j j jv rt fddS ttS )Nc                      s
   t  S r$   r?   r%   r-   r%   r(   <lambda>p      
 z$DummyDomain.exists.<locals>.<lambda>)rK   rL   rJ   r   succeedfailr   SMTPBadRcptr-   r%   r-   r(   existsn   s   zDummyDomain.existsN)r:   r;   r<   r=   r0   r[   r%   r%   r%   r(   rR   c   s    rR   s   Subject: hello

Goodbye
c                   @   s>   e Zd ZdddZdd Zdd Zdd	 Zd
d Zdd ZdS )MyClientNc                 C   s:   |d u rddgt tf}|d | _|d | _|d | _d S )Nzmoshez@foo.barr         )r   mail_sender
_recipient_datar.   messageInfor%   r%   r(   r0   |   s
   

zMyClient.__init__c                 C      | j S r$   )r`   r6   r%   r%   r(   getMailFrom      zMyClient.getMailFromc                 C   re   r$   )ra   r6   r%   r%   r(   	getMailTo   rg   zMyClient.getMailToc                 C   re   r$   )rb   r6   r%   r%   r(   getMailData   rg   zMyClient.getMailDatac                 C   
   || _ d S r$   )_error)r.   excr%   r%   r(   	sendError      
zMyClient.sendErrorc                 C   s   d | _ d | _d | _d S r$   )r`   ra   rb   )r.   coderespnumOk	addresseslogr%   r%   r(   sentMail   s   
zMyClient.sentMailr$   )	r:   r;   r<   r0   rf   rh   ri   rm   rt   r%   r%   r%   r(   r\   {   s    
r\   c                   @   s   e Zd ZdddZdS )MySMTPClientNc                 C   s   t j| d t| | d S Ns   foo.baz)r   
SMTPClientr0   r\   rc   r%   r%   r(   r0      s   zMySMTPClient.__init__r$   r:   r;   r<   r0   r%   r%   r%   r(   ru          ru   c                   @   s   e Zd ZdddZdS )MyESMTPClient    Nc                 C   s    t j| ||d t|  d S rv   )r   ESMTPClientr0   r\   )r.   secretcontextFactoryr%   r%   r(   r0      s   zMyESMTPClient.__init__)r{   Nrx   r%   r%   r%   r(   rz      ry   rz   c                   @      e Zd Zdd ZdS )LoopbackMixinc                 C   s   t ||S r$   )r   loopbackTCP)r.   serverclientr%   r%   r(   r         zLoopbackMixin.loopbackN)r:   r;   r<   r   r%   r%   r%   r(   r          r   c                   @   s$   e Zd Zg dZdd Zdd ZdS )FakeSMTPServer)	   220 hellos   250 nice to meet you	   250 greatr   s   354 go on, ladc                 C   s4   g | _ | jd d  | _| j  | | j  d S r$   )rB   
clientDatareversesendLinepopr6   r%   r%   r(   connectionMade   s   
zFakeSMTPServer.connectionMadec                 C   sr   | j | |dkr| jd | j  n|dkr!| jd n	|dkr*| j  | jr7| | j  d S d S )Ns   QUITs   221 see ya around
   .s   250 gotcha
   RSET)rB   rF   	transportwriteloseConnectionr   r   r   r1   r%   r%   r(   r3      s   
zFakeSMTPServer.lineReceivedN)r:   r;   r<   r   r   r3   r%   r%   r%   r(   r      s    r   c                   @   sH   e Zd ZdZdd Zg dZdd Zdd Zd	d
 Zdd Z	dd Z
dS )SMTPClientTestsz'
    Tests for L{smtp.SMTPClient}.
    c                 C   sj   g }t  }|j|_|t  |d |  | |d tj	 | 
|d j | t|d d dS )z
        L{smtp.SMTPClient.timeoutConnection} calls the C{sendError} hook with a
        fatal L{SMTPTimeoutError} with the current line log.
        r   r   sH   Timeout waiting for SMTP server response
<<< 220 hello
>>> HELO foo.baz
N)ru   rF   rm   makeConnectionr   r3   timeoutConnectionassertIsInstancer   SMTPTimeoutError
assertTrueisFatalassertEqualbytes)r.   errorsr   r%   r%   r(   test_timeoutConnection   s   

z&SMTPClientTests.test_timeoutConnection)	s   HELO foo.bazs   MAIL FROM:<moshez@foo.bar>s   RCPT TO:<moshez@foo.bar>s   DATAs   Subject: hellor{   s   Goodbyer   r   c                    s0   t  }t  |}| fdd |S )z
        L{smtp.SMTPClient} sends I{HELO}, I{MAIL FROM}, I{RCPT TO}, and I{DATA}
        commands based on the return values of its C{getMailFrom},
        C{getMailTo}, and C{getMailData} methods.
        c                    s     j jS r$   )r   rB   expected_outputxr.   r   r%   r(   rV      s    z/SMTPClientTests.test_messages.<locals>.<lambda>)ru   r   r   addCallback)r.   r   dr%   r   r(   test_messages   s
   zSMTPClientTests.test_messagesc                 C   sd   t ddgtdf}t }|| |d | |jd | |j |j	  | 
|jt dS )z
        If there is an error while producing the message body to the
        connection, the C{sendError} callback is invoked.
        zalice@example.comzbob@example.com   foo(   220 Ok
250 Ok
250 Ok
250 Ok
354 Ok
N)ru   r   r   r   dataReceivedassertNotIdenticalproducerassertFalse	streamingstopProducingr   rk   	Exceptionr.   r   r   r%   r%   r(   test_transferError   s   
	
z"SMTPClientTests.test_transferErrorc                 C   P   t d}t }|| |t jdddd | | d | |j	 dS )z
        If L{smtp.SMTPClient.sendError} is called with an L{SMTPClientError}
        which is fatal, it disconnects its transport without writing anything
        more to it.
        N{   fooTr   r{   )
r   rw   r   r   rm   SMTPClientErrorr   valuer   disconnectingr   r%   r%   r(   test_sendFatalError     

z#SMTPClientTests.test_sendFatalErrorc                 C   r   )z
        If L{smtp.SMTPClient.sendError} is called with an L{SMTPClientError}
        which is not fatal, it sends C{"QUIT"} and waits for the server to
        close the connection.
        Nr   r   Fr      QUIT
)
r   rw   r   r   rm   r   r   r   r   r   r   r%   r%   r(   test_sendNonFatalError  r   z&SMTPClientTests.test_sendNonFatalErrorc                 C   sH   t d}t }|| |td | | d | |j	 dS )z
        If L{smtp.SMTPClient.sendError} is called with an exception which is
        not an L{SMTPClientError}, it disconnects its transport without
        writing anything more to it.
        Nr   r{   )
r   rw   r   r   rm   r   r   r   r   r   r   r%   r%   r(   test_sendOtherError,  s   

z#SMTPClientTests.test_sendOtherErrorN)r:   r;   r<   r=   r   r   r   r   r   r   r   r%   r%   r%   r(   r      s    r   c                   @   $   e Zd Zdd Zdd Zdd ZdS )DummySMTPMessagec                 C   r@   r$   )r   usersrB   )r.   r   r   r%   r%   r(   r0   ;  rC   zDummySMTPMessage.__init__c                 C   s   | j | d S r$   )rB   rF   r1   r%   r%   r(   r3   @  s   zDummySMTPMessage.lineReceivedc                 C   sr   d | jd }| jd jd t| jd j}}g }| jD ]	}|t| q||||f| jjt	|< t
dS )NrG   r   rH   )rI   rB   r   helor   origrF   r   rO   tupler   rX   )r.   rO   r   origin
recipientsr/   r%   r%   r(   r7   C  s   "

zDummySMTPMessage.eomReceivedN)r:   r;   r<   r0   r3   r7   r%   r%   r%   r(   r   :  s    r   c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )

DummyProtoc                 C   s   | j |  i | _d S r$   )dummyMixinBaser   rO   r6   r%   r%   r(   r   N  s   
zDummyProto.connectionMadec                  G   r#   r$   r%   )r&   r%   r%   r(   receivedHeaderR  r*   zDummyProto.receivedHeaderc                    s   t d  _ fddS )Nc                      s   t  gS r$   )r   r%   r-   r%   r(   rV   W      z'DummyProto.validateTo.<locals>.<lambda>)SimpleDeliverydeliveryr-   r%   r-   r(   
validateToU  s   
zDummyProto.validateToc                 C      |S r$   r%   r.   r   r   r%   r%   r(   validateFromY  r*   zDummyProto.validateFromN)r:   r;   r<   r   r   r   r   r%   r%   r%   r(   r   M  s
    r   c                   @      e Zd ZejZdS )	DummySMTPN)r:   r;   r<   r   SMTPr   r%   r%   r%   r(   r   ]      
r   c                   @   r   )
DummyESMTPN)r:   r;   r<   r   ESMTPr   r%   r%   r%   r(   r   a  r   r   c                   @   s  e Zd ZU dZeeej  ed< dZ	eee
j  ed< dddgddgdfddd	d
gdd	d
gdfdddgddgdfgZg dZeeeeeef  ed< eD ]6\ZZZZZZede d dddf eD ]Zede d dddf qceddedeeeefff qLdd ZdS )AnotherTestCaseNserverClassclientClass   foo.coms   moshez@foo.coms   moshez@bar.coms(   From: Moshe
To: Moshe

Hi,
how are you?
s   tttt@rrr.coms   uuu@ooos   yyy@eees   Subject: pass

..rrrr..
s   @this,@is,@ignored:foo@bar.coms   @ignore,@this,@too:bar@foo.coms   foo@bar.coms   bar@foo.coms    Subject: apa
To: foo

123
.
456
))r{   s   220.*
$NN)s   HELO foo.com
   250.*
$NN)s   RSET
r   NNdatas   MAIL FROM:<s   >
s   250.*
s	   RCPT TO:<s   DATA
s   354.*
c                 C   sF  t  }|  }G dd d}| |_|| | jD ]\}}}}|r'|| | }|  t	||s;t
||||dd dkr| D ]}	|	rW|	dd dkrWd|	 }	||	d	  qG|d
 | }|  |\}
}t	|
|s{t
|
||d D ]}t|dd }|g|d< | |j|f t| qq|d dS )a  
        Exercise a lot of the SMTP client code.  This is a "shotgun" style unit
        test.  It does a lot of things and hopes that something will go really
        wrong if it is going to go wrong.  This test should be replaced with a
        suite of nicer tests.
        c                   @   s   e Zd ZdZdS )z/AnotherTestCase.test_buffer.<locals>.fooFactoryr   N)r:   r;   r<   rA   r%   r%   r%   r(   
fooFactory  s    r   N   s   354r   r]   r      
s   .
r^   )r   r   factoryr   r   r   r   clearrD   rE   AssertionError
splitlineslistr   rO   r   
setTimeout)r.   r   ar   sendexpectmsg	msgexpectr   r2   rp   msgdatarecipexpectedr%   r%   r(   test_buffer  s:   




zAnotherTestCase.test_buffer)r:   r;   r<   r   r   r   r   Protocol__annotations__r   r   rw   rJ   r   r   r   r   r   helo_from_to_realfromrealtor   rF   rcptr   r%   r%   r%   r(   r   e  sL   
  ,	r   c                   @      e Zd ZeZeZdS )AnotherESMTPTestsN)r:   r;   r<   r   r   rz   r   r%   r%   r%   r(   r         r   c                   @   r   )AnotherSMTPTestsN)r:   r;   r<   r   r   ru   r   r%   r%   r%   r(   r     r   r   c                   @   s4   e Zd ZddiZejjejjfZdd Z	dd Z
dS )DummyChecker   testuser   testpasswordc                 C   s"   t |j| j|j | j|jS r$   )r   maybeDeferredcheckPasswordr   usernamer   _cbCheckr.   credentialsr%   r%   r(   requestAvatarId  s
   zDummyChecker.requestAvatarIdc                 C   s   |r|S t j r$   )r
   r   r   )r.   resultr   r%   r%   r(   r     s   
zDummyChecker._cbCheckN)r:   r;   r<   r   r
   r   IUsernamePasswordIUsernameHashedPasswordcredentialInterfacesr  r   r%   r%   r%   r(   r     s    r   c                   @   r+   )r   z[
    L{SimpleDelivery} is a message delivery factory with no interesting
    behavior.
    c                 C   rj   r$   _messageFactory)r.   messageFactoryr%   r%   r(   r0     rn   zSimpleDelivery.__init__c                 C   r#   r$   r%   r.   r   r   r   r%   r%   r(   r     r*   zSimpleDelivery.receivedHeaderc                 C   r   r$   r%   r   r%   r%   r(   r     r*   zSimpleDelivery.validateFromc                    s    fddS )Nc                      s
     S r$   r  r%   r-   r%   r(   rV     rW   z+SimpleDelivery.validateTo.<locals>.<lambda>r%   r-   r%   r-   r(   r      s   zSimpleDelivery.validateToN)r:   r;   r<   r=   r0   r   r   r   r%   r%   r%   r(   r     s    r   c                   @   r   )
DummyRealmc                 G   s   t jtd dd fS )Nc                   S   r#   r$   r%   r%   r%   r%   r(   rV         z*DummyRealm.requestAvatar.<locals>.<lambda>)r   IMessageDeliveryr   )r.   avatarIdmindr   r%   r%   r(   requestAvatar     zDummyRealm.requestAvatarN)r:   r;   r<   r  r%   r%   r%   r(   r
    r   r
  c                   @   r   )	AuthTestsc                    st   t  }tj|}|t  tdtjji|_t	d}t
d}||  |}| fdd |S )z
        L{ESMTPClient} can authenticate using the I{CRAM-MD5} SASL mechanism.

        @see: U{http://tools.ietf.org/html/rfc2195}
        s   CRAM-MD5r   r   c                    s     jdS )Nr]   )r   authenticatedr   r   r%   r(   rV     s    z,AuthTests.test_crammd5Auth.<locals>.<lambda>)r
  r
   portalr   registerCheckerr   r   r   CramMD5Credentialsrz   r   CramMD5ClientAuthenticatorregisterAuthenticatorr   r   r.   realmpr   cAuthr   r%   r   r(   test_crammd5Auth
  s   

zAuthTests.test_crammd5Authc                    sp   t  }tj|}|t  tdti|_td}t	
d}||  |}| fdd |S )z
        L{ESMTPClient} can authenticate using the I{LOGIN} SASL mechanism.

        @see: U{http://sepp.oetiker.ch/sasl-2.1.19-ds/draft-murchison-sasl-login-00.txt}
           LOGINr   r   c                         jS r$   r   r  r   r   r%   r(   rV   1  r   z*AuthTests.test_loginAuth.<locals>.<lambda>)r
  r
   r  r   r  r   r   r   rz   r   LOGINAuthenticatorr  r   r   r  r%   r   r(   test_loginAuth  s   

zAuthTests.test_loginAuthc                    sr   t  }tj|}|t  tdtji|_t	d}t
d}||  |}| fdd |S )a  
        When communicating with a server which implements the I{LOGIN} SASL
        mechanism using C{"Username:"} as the challenge (rather than C{"User
        Name\0"}), L{ESMTPClient} can still authenticate successfully using
        the I{LOGIN} mechanism.
        r  r   r   c                    r  r$   r  r   r   r%   r(   rV   G  r   z8AuthTests.test_loginAgainstWeirdServer.<locals>.<lambda>)r
  r
   r  r   r  r   r   r   r   rz   r   r  r   r   r  r%   r   r(   test_loginAgainstWeirdServer4  s   

z&AuthTests.test_loginAgainstWeirdServerN)r:   r;   r<   r  r!  r"  r%   r%   r%   r(   r  	  s    r  c                   @   s<   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd ZdS )SMTPHelperTestsc                 C   s6   i }t dD ]}td}| ||v  d ||< qd S )Ni  testcase)ranger   	messageidr   )r.   r   imr%   r%   r(   testMessageIDL  s   

zSMTPHelperTests.testMessageIDc                 C   sR   ddgddgt ddgddgt ddgg}|D ]\}}| t || qd S )Ns   user@host.names   <user@host.name>s   "User Name" <user@host.name>s   someguy@someplaces   <someguy@someplace>r{   s   <>)r   Addressr   	quoteaddr)r.   casescer%   r%   r(   testQuoteAddrS  s   zSMTPHelperTests.testQuoteAddrc                 C   s$   t ddd d }| t|d d S )Ns	   user@hosts   helo.host.namez	user@host)r   Userr   str)r.   ur%   r%   r(   testUser_  s   zSMTPHelperTests.testUserc                 C   sr   g d}|D ]0\}}|  t||t|f |  |d| |  t||t|f |  |d| qd S )N))Hello worlds   Hello+20world)zHello+worlds   Hello+2Bworld)z s   +00+01+02+03+04+05)ze=mc2@example.coms   e+3Dmc2@example.comxtext)r   r   xtext_encodelenencodextext_decodedecode)r.   r,  caser   r%   r%   r(   testXtextEncodingc  s   z!SMTPHelperTests.testXtextEncodingc                 C   D   d}|  t|d|dt|f |  |dd|d dS )z
        Specifying an error policy to C{unicode.encode} with the
        I{xtext} codec should produce the same result as not
        specifying the error policy.
        r4  strictr5  N)r   r   r6  r8  r7  )r.   textr%   r%   r(   test_encodeWithErrorsq  s
   z%SMTPHelperTests.test_encodeWithErrorsc                 C   r=  )zO
        Similar to L{test_encodeWithErrors}, but for C{bytes.decode}.
        s   Hello worldr>  r5  N)r   r   r9  r:  r7  )r.   r   r%   r%   r(   test_decodeWithErrors}  s
   z%SMTPHelperTests.test_decodeWithErrorsN)	r:   r;   r<   r)  r/  r3  r<  r@  rA  r%   r%   r%   r(   r#  K  s    r#  c                   @      e Zd ZdZdd ZdS )NoticeTLSClientFc                 C   s   t | || d| _d S NT)rz   esmtpState_starttlstls)r.   ro   rp   r%   r%   r(   rE    s   
z#NoticeTLSClient.esmtpState_starttlsN)r:   r;   r<   rF  rE  r%   r%   r%   r(   rC        rC  c                   @   s   e Zd ZeZdd ZdS )TLSTestsc                    sB   t  }t }t|d t|d fdd} |S )N)r~   c                    s      jd  jd d S rD  )r   rF  
startedTLSignoredr   r.   r   r%   r(   check  s   zTLSTests.testTLS.<locals>.check)r!   r"   rC  r   r   r   )r.   	clientCTX	serverCTXrM  r%   rL  r(   testTLS  s   

zTLSTests.testTLSN)r:   r;   r<   r    skiprP  r%   r%   r%   r(   rH    rG  rH  c                   @   r   )EmptyLineTestsc                 C   sp   t  }t }|| |d |d |  }| t	|d | 
|d d | |d d dS )z
        If L{smtp.SMTP} receives an empty line, it responds with a 500 error
        response code and a message about a syntax error.
        r{   Nr^   r   s   220r]   s   500 Error: bad syntax)r   r   r   r   r3   r   r   r   r   r7  r   
startswith)r.   protor   outr%   r%   r(   test_emptyLineSyntaxError  s   


z(EmptyLineTests.test_emptyLineSyntaxErrorN)r:   r;   r<   rV  r%   r%   r%   r(   rR    r   rR  c                   @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )TimeoutTestszE
    Check that SMTP client factories correctly use the timeout.
    c                    st   t   |tddd} j|_t }|| ||_ fdd}	|t
j|} d  d |S )zR
        Connect the clientFactory, and check the timeout on the request.
        TCPexample.net   c                    s      d d S )N      ?)r   seconds)ignclockr.   r%   r(   rM    r  z(TimeoutTests._timeoutTest.<locals>.checkg?g?)r   ClockbuildProtocolr   IPv4Address	callLaterr   r   r   assertFailurer   r   r   advance)r.   onDoneclientFactoryr   trM  r   r%   r^  r(   _timeoutTest  s   


zTimeoutTests._timeoutTestc                 C   .   t  }tjddtd|ddd}| ||S )z
        Test timeout for L{smtp.SMTPSenderFactory}: the response L{Deferred}
        should be errback with a L{smtp.SMTPTimeoutError}.
        source@addresss   recipient@address   Message bodyr   r[  retriestimeoutr   rM   r   SMTPSenderFactoryr   ri  r.   rf  rg  r%   r%   r(   test_SMTPClientRecipientBytes  s   z*TimeoutTests.test_SMTPClientRecipientBytesc                 C   rj  )z-
        Use a L{unicode} recipient.
        rk  recipient@addressrl  r   r[  rm  rp  rr  r%   r%   r(   test_SMTPClientRecipientUnicode     z,TimeoutTests.test_SMTPClientRecipientUnicodec                 C   rj  )z.
        Use a L{list} of recipients.
        rk  )zrecipient1@addresss   recipient2@addressrl  r   r[  rm  rp  rr  r%   r%   r(   test_SMTPClientRecipientList  rv  z)TimeoutTests.test_SMTPClientRecipientListc              
   C   s2   t  }tjddddtd|ddd}| ||S )	z
        Test timeout for L{smtp.ESMTPSenderFactory}: the response L{Deferred}
        should be errback with a L{smtp.SMTPTimeoutError}.
        r   passwordrk  rt  rl  r   r[  rm  )r   rM   r   ESMTPSenderFactoryr   ri  rr  r%   r%   r(   test_ESMTPClient  s   
zTimeoutTests.test_ESMTPClientc                 C   s  G dd d}g }t  }||j tjdd|d|ddd}d	|_t }|	t
d
dd}|j|_t }|| |d | |jd | |j |d | |g  |j  |d | |g  |j  |d | |g  | | d dS )z
        The timeout is not allowed to expire after the server has accepted a
        DATA command and the client is actively sending data to it.
        c                   @   s"   e Zd ZdZdd ZdddZdS )z<TimeoutTests.test_resetTimeoutWhileSending.<locals>.SlowFilez
            A file-like which returns one byte from each read call until the
            specified number of bytes have been returned.
            c                 S   rj   r$   _size)r.   sizer%   r%   r(   r0     rn   zETimeoutTests.test_resetTimeoutWhileSending.<locals>.SlowFile.__init__Nc                 S   s   | j r|  j d8  _ dS dS )Nr]      xr{   r{  )r.   maxr%   r%   r(   read  s   zATimeoutTests.test_resetTimeoutWhileSending.<locals>.SlowFile.readr$   )r:   r;   r<   r=   r0   r  r%   r%   r%   r(   SlowFile  s    r  rk  rt  r]   r   r   rm     example.orgrX  rY  rZ  r   Nr^   s   250 Ok
s]   HELO example.org
MAIL FROM:<source@address>
RCPT TO:<recipient@address>
DATA
x
.
RSET
)r   rM   
addErrbackrF   r   rq  rA   r   r`  ra  r   rb  rc  r   r   r   r   r   r   r   re  r   resumeProducingr   )r.   r  failedrf  rg  r_  r   r   r%   r%   r(   test_resetTimeoutWhileSending  sJ   





z*TimeoutTests.test_resetTimeoutWhileSendingN)
r:   r;   r<   r=   ri  rs  ru  rw  rz  r  r%   r%   r%   r(   rW    s    rW  c                   @   rQ   )(MultipleDeliveryFactorySMTPServerFactorya  
    L{MultipleDeliveryFactorySMTPServerFactory} creates SMTP server protocol
    instances with message delivery factory objects supplied to it.  Each
    factory is used for one connection and then discarded.  Factories are used
    in the order they are supplied.
    c                 C   rj   r$   )_messageFactories)r.   messageFactoriesr%   r%   r(   r0   q  rn   z1MultipleDeliveryFactorySMTPServerFactory.__init__c                 C   s$   t j| |}t| jd|_|S )Nr   )r   ServerFactoryra  r   r  r   r   )r.   addrr  r%   r%   r(   ra  t  s   z6MultipleDeliveryFactorySMTPServerFactory.buildProtocolN)r:   r;   r<   r=   r0   ra  r%   r%   r%   r(   r  i  s    r  c                   @   rQ   )SMTPSenderFactoryTestsz.
    Tests for L{smtp.SMTPSenderFactory}.
    c                 C   ^   t  }t }tddtd|}|dd|}|d ||t	
d | |jd dS )zt
        L{smtp.SMTPSenderFactory} removes the current protocol when the client
        connection is lost.
        rk  rt     message	localhostrZ  NBye.)r   r   rM   r   rq  r   
connectTCPra  clientConnectionLostr   ConnectionDoner   currentProtocolr.   r   sentDeferredrg  	connectorr%   r%   r(   2test_removeCurrentProtocolWhenClientConnectionLost     
zISMTPSenderFactoryTests.test_removeCurrentProtocolWhenClientConnectionLostc                 C   r  )zv
        L{smtp.SMTPSenderFactory} removes the current protocol when the client
        connection is failed.
        rk  rt  r  r  rZ  Nr  )r   r   rM   r   rq  r   r  ra  clientConnectionFailedr   r  r   r  r  r%   r%   r(   4test_removeCurrentProtocolWhenClientConnectionFailed  r  zKSMTPSenderFactoryTests.test_removeCurrentProtocolWhenClientConnectionFailedN)r:   r;   r<   r=   r  r  r%   r%   r%   r(   r  z  s    r  c                   @   rB  )SMTPSenderFactoryRetryTestszD
    Tests for the retry behavior of L{smtp.SMTPSenderFactory}.
    c           	         s   ddt g G fdddtj}tt fddg}||_tjd|dd	}| }	|j
 t }td
d t|}d|_t|j|j|}	|j  fdd}|| |S )z
        If the protocol created by L{SMTPSenderFactory} loses its connection
        before receiving confirmation of message delivery, it reconnects and
        tries to deliver the message again.
        s   alices   some message textc                       s   e Zd ZdZ fddZdS )zHSMTPSenderFactoryRetryTests.test_retryAfterDisconnect.<locals>.CleanSMTPz
            An SMTP subclass which ensures that its transport will be
            disconnected before the test ends.
            c                    s     |j tj| | d S r$   )
addCleanupr   r   r   r   )	innerSelfr   r6   r%   r(   r     s   zWSMTPSenderFactoryRetryTests.test_retryAfterDisconnect.<locals>.CleanSMTP.makeConnectionN)r:   r;   r<   r=   r   r%   r6   r%   r(   	CleanSMTP  s    r  c                    s
   t  | S r$   rU   )r/   )rA   r%   r(   rV     rW   zGSMTPSenderFactoryRetryTests.test_retryAfterDisconnect.<locals>.<lambda>r   	127.0.0.1)	interfaces   bob@example.orgs   @example.comr  c                    s6     jd d gi  ttd dS )z
            Verify that the message was successfully delivered and flush the
            error which caused the first attempt to fail.
            rG   r]   N)r   rJ   r7  flushLoggedErrorsr5   rJ  rA   rO   	recipientr.   r%   r(   cbSent  s   zESMTPSenderFactoryRetryTests.test_retryAfterDisconnect.<locals>.cbSent)rR   r   r   r  r,   r   r   	listenTCPgetHostr  stopListeningr   rM   rq  r   rA   r  hostport
disconnectr   )	r.   r  serverFactory
serverPort
serverHostr  rg  clientConnectorr  r%   r  r(   test_retryAfterDisconnect  s4   


	z5SMTPSenderFactoryRetryTests.test_retryAfterDisconnectN)r:   r;   r<   r=   r  r%   r%   r%   r(   r        r  c                   @   rQ   )SingletonRealmz
    Trivial realm implementation which is constructed with an interface and an
    avatar and returns that avatar when asked for that interface.
    c                 C   s   || _ || _d S r$   r  avatar)r.   r  r  r%   r%   r(   r0     s   
zSingletonRealm.__init__c                 G   s,   |D ]}|| j u r|| jdd f  S qd S )Nc                   S   r#   r$   r%   r%   r%   r%   r(   rV     r  z.SingletonRealm.requestAvatar.<locals>.<lambda>r  )r.   r  r  r   ifacer%   r%   r(   r    s
   
zSingletonRealm.requestAvatarN)r:   r;   r<   r=   r0   r  r%   r%   r%   r(   r    s    r  c                   @   r>   )	NotImplementedDeliveryz
    Non-implementation of L{smtp.IMessageDelivery} which only has methods which
    raise L{NotImplementedError}.  Subclassed by various tests to provide the
    particular behavior being tested.
    c                 C   r4   Nz3This oughtn't be called in the course of this test.NotImplementedErrorr   r%   r%   r(   r     r8   z#NotImplementedDelivery.validateFromc                 C   r4   r  r  r-   r%   r%   r(   r     r8   z!NotImplementedDelivery.validateToc                 C   r4   r  r  r	  r%   r%   r(   r     r8   z%NotImplementedDelivery.receivedHeaderN)r:   r;   r<   r=   r   r   r   r%   r%   r%   r(   r    s
    r  c                   @   sf   e Zd ZdZejfddZdd Zdd Zdd	 Z	d
d Z
dd Zdd Zeedd Zdd ZdS )SMTPServerTestsza
    Test various behaviors of L{twisted.mail.smtp.SMTP} and
    L{twisted.mail.smtp.ESMTP}.
    c                 C   s>   | }d|_ t }|| |t  | d|  dS )zb
        Test that the specified hostname shows up in the SMTP server's
        greeting.
        s   example.comN)r  r   r   r9   r   r  assertInr   )r.   r   srh  r%   r%   r(   testSMTPGreetingHost  s   
z$SMTPServerTests.testSMTPGreetingHostc                 C   :   t  }t }|| |t  | d|  dS )z
        Test that the string "ESMTP" does not appear in the SMTP server's
        greeting since that string strongly suggests the presence of support
        for various SMTP extensions which are not supported by L{smtp.SMTP}.
           ESMTPN)	r   r   r   r   r9   r   r  assertNotInr   r.   r  rh  r%   r%   r(   testSMTPGreetingNotExtended  
   
z+SMTPServerTests.testSMTPGreetingNotExtendedc                 C   s   |  tj dS )zS
        Similar to testSMTPGreetingHost, but for the L{smtp.ESMTP} class.
        N)r  r   r   r6   r%   r%   r(   testESMTPGreetingHost  s   z%SMTPServerTests.testESMTPGreetingHostc                 C   r  )z
        Test that the string "ESMTP" does appear in the ESMTP server's
        greeting since L{smtp.ESMTP} does support the SMTP extensions which
        that advertises to the client.
        r  N)	r   r   r   r   r9   r   r  r  r   r  r%   r%   r(   testESMTPGreetingExtended$  r  z)SMTPServerTests.testESMTPGreetingExtendedc                 C   sD   t  }t }|| |d |t  | d|	  dS )zN
        Sending an unimplemented command is responded to with a 500.
        s   DOAGOODTHINGs   500 Command not implementedN)
r   r   r   r   r3   r9   r   r  r  r   r  r%   r%   r(   test_SMTPUnknownCommand0  s   

z'SMTPServerTests.test_SMTPUnknownCommandc                 C      G dd dt }ttj| }t|t g}t }||_t }|	| |
d |  |
d |t  | | d dS )z
        Test that a C{MAIL FROM} command with an acceptable address is
        responded to with the correct success code.
        c                   @   rB  )zDSMTPServerTests.test_acceptSenderAddress.<locals>.AcceptanceDeliveryzM
            Delivery object which accepts all senders as valid.
            c                 S   r   r$   r%   r   r%   r%   r(   r   F  r*   zQSMTPServerTests.test_acceptSenderAddress.<locals>.AcceptanceDelivery.validateFromNr:   r;   r<   r=   r   r%   r%   r%   r(   AcceptanceDeliveryA  r  r     HELO example.com
   MAIL FROM:<alice@example.com>
s   250 Sender address accepted
Nr  r  r   r  r   r   r   r  r   r   r   r   r9   r   ConnectionLostr   r   )r.   r  r  r  rT  transr%   r%   r(   test_acceptSenderAddress;  s   


z(SMTPServerTests.test_acceptSenderAddressc                 C   r  )z
        Test that a C{MAIL FROM} command with an address rejected by a
        L{smtp.IMessageDelivery} instance is responded to with the correct
        error code.
        c                   @   rB  )zMSMTPServerTests.test_deliveryRejectedSenderAddress.<locals>.RejectionDeliveryzO
            Delivery object which rejects all senders as invalid.
            c                 S   s
   t |r$   )r   SMTPBadSenderr   r%   r%   r(   r   j  rn   zZSMTPServerTests.test_deliveryRejectedSenderAddress.<locals>.RejectionDelivery.validateFromNr  r%   r%   r%   r(   RejectionDeliverye  r  r  r  r  V   550 Cannot receive from specified address <alice@example.com>: Sender not acceptable
Nr  )r.   r  r  r  rT  r  r%   r%   r(   "test_deliveryRejectedSenderAddress^  s   


z2SMTPServerTests.test_deliveryRejectedSenderAddressc                 C   s   G dd d}t tjt }t|| g}t }||_t }|| |	d |
  |	d |t  | | d dS )z
        Test that a C{MAIL FROM} command with an address rejected by an
        L{smtp.SMTP} instance's portal is responded to with the correct error
        code.
        c                   @   s   e Zd ZdZefZdd ZdS )zQSMTPServerTests.test_portalRejectedSenderAddress.<locals>.DisallowAnonymousAccesszZ
            Checker for L{IAnonymous} which rejects authentication attempts.
            c                 S   s   t t S r$   )r   rY   r   r   r%   r%   r(   r    r   zaSMTPServerTests.test_portalRejectedSenderAddress.<locals>.DisallowAnonymousAccess.requestAvatarIdN)r:   r;   r<   r=   r   r  r  r%   r%   r%   r(   DisallowAnonymousAccess  s    r  r  r  r  Nr  r   r  r  r   r   r  r   r   r   r   r9   r   r  r   r   )r.   r  r  r  rT  r  r%   r%   r(    test_portalRejectedSenderAddress  s   



z0SMTPServerTests.test_portalRejectedSenderAddressc                 C   st   t tjt }t|g }t }||_t }|| |	d |
  |	d |t  | | d dS )z
        Test that a C{MAIL FROM} command issued without first authenticating
        when a portal has been configured to disallow anonymous logins is
        responded to with the correct error code.
        r  r  sd   550 Cannot receive from specified address <alice@example.com>: Unauthenticated senders not allowed
Nr  )r.   r  r  rT  r  r%   r%   r(   "test_portalRejectedAnonymousSender  s   



z2SMTPServerTests.test_portalRejectedAnonymousSenderN)r:   r;   r<   r=   r   r   r  r  r  r  r  r  r  r	   r   r  r  r%   r%   r%   r(   r     s    #(
*r  c                   @   sx   e Zd Zdd Z	dddZdd Zd	d
 Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd ZdS )ESMTPAuthenticationTestsc                 C   s0   | j   | j| | || j    dS )z
        Assert that when the given bytes are delivered to the ESMTP server
        instance, it responds with the indicated lines.

        @type bytes: str
        @type response: list of str
        N)r   r   r   r   r   r   r   )r.   r   responser%   r%   r(   assertServerResponse  s   
z-ESMTPAuthenticationTests.assertServerResponse   username   passwordc                 C   s   |  \}}}}| |g  | tjjj| | |j| | |	| | 
tj| | 
tj| |tjddd f | dg| j   dS )a  
        Assert that a login attempt has been made, that the credentials and
        interfaces passed to it are correct, and that when the login request
        is satisfied, a successful response is sent by the ESMTP server
        instance.

        @param loginArgs: A C{list} previously passed to L{portalFactory}.
        @param username: The login user.
        @param password: The login password.
        Nc                   S   r#   r$   r%   r%   r%   r%   r(   rV     r  zDESMTPAuthenticationTests.assertServerAuthenticated.<locals>.<lambda>s   235 Authentication successful.)r   r   r   twistedr
   r   r  
providedByr   r   r  r   IMessageDeliveryFactoryr  rN   r   r   r   )r.   	loginArgsr   rx  r   r   r  r   r%   r%   r(   assertServerAuthenticated  s   z2ESMTPAuthenticationTests.assertServerAuthenticatedc                 C   s@   t dti| _d| j_ttdddd| _| j	| j dS )zI
        Create an ESMTP instance attached to a StringTransport.
        r  s	   localhostrX  r  i90  )peerAddressN)
r   r   r   r   r  r   r   rb  r   r   r6   r%   r%   r(   setUp  s   zESMTPAuthenticationTests.setUpc                 C   s   | j t  dS )zT
        Disconnect the ESMTP instance to clean up its timeout DelayedCall.
        N)r   r9   r   r  r6   r%   r%   r(   tearDown  s   z!ESMTPAuthenticationTests.tearDownc                    s   G  fddd}| S )Nc                       s   e Zd Z fddZdS )z;ESMTPAuthenticationTests.portalFactory.<locals>.DummyPortalc                    s   t  } ||||f |S r$   )r   rM   rF   )r.   r   r  r   r   	loginListr%   r(   login  s   zAESMTPAuthenticationTests.portalFactory.<locals>.DummyPortal.loginN)r:   r;   r<   r  r%   r  r%   r(   DummyPortal  s    r  r%   )r.   r  r  r%   r  r(   portalFactory  s   z&ESMTPAuthenticationTests.portalFactoryc                 C   sX   | j   | jd | j   }| |d d | |d d | t|d dS )zV
        Test that AUTH is advertised to clients which issue an EHLO command.
           EHLO
r   s/   250-localhost Hello 127.0.0.1, nice to meet your]   s   250 AUTH LOGINr^   N)r   r   r   r   r   r   r   r7  )r.   responseLinesr%   r%   r(   'test_authenticationCapabilityAdvertised  s   
z@ESMTPAuthenticationTests.test_authenticationCapabilityAdvertisedc                 C   s   g }|  || j_| jd | j  | ddtd	  g | tdd dtd	  g | td	 d g  | 
| d	S )
zJ
        Test that the LOGIN authentication mechanism can be used
        r     AUTH LOGIN
   334 
   User Name r  r   	   Password r  Nr  r   r  r   r   r   r  base64	b64encodestripr  r.   r  r%   r%   r(   test_plainAuthentication!  s   
z1ESMTPAuthenticationTests.test_plainAuthenticationc                 C   s   g }|  || j_| jd | j  | ddtd	  g | tdd dtd	  g | dg  | j
|dd	 d
S )zM
        Test that giving an empty password for plain auth succeeds.
        r  r  r  r  r  r   r  r{   )rx  Nr  r  r%   r%   r(   %test_plainAuthenticationEmptyPassword8  s   
z>ESMTPAuthenticationTests.test_plainAuthenticationEmptyPasswordc                 C   s~   g }|  || j_| jd | j  | dtd	  d dtd	  g | td	 d g  | 
| dS )	z
        The response to the first challenge may be included on the AUTH command
        line.  Test that this is also supported.
        r     AUTH LOGIN r  r   r  r  r  Nr  r  r%   r%   r(   'test_plainAuthenticationInitialResponseN  s   
z@ESMTPAuthenticationTests.test_plainAuthenticationInitialResponsec                 C   s<   g }|  || j_| jd | jd | ddg dS )zW
        Test that a challenge/response sequence can be aborted by the client.
        r  r  s   *
s   501 Authentication abortedN)r  r   r  r   r  r  r%   r%   r(   test_abortAuthenticationb  s
   z1ESMTPAuthenticationTests.test_abortAuthenticationc                 C   sH   g }|  || j_| jd | jd | ddg | |g  dS )zz
        Test that a response which is not properly Base64 encoded results in
        the appropriate error code.
        r  r  s   x
+   501 Syntax error in parameters or argumentsNr  r   r  r   r  r   r  r%   r%   r(   !test_invalidBase64EncodedResponsen  s   z:ESMTPAuthenticationTests.test_invalidBase64EncodedResponsec                 C   s<   g }|  || j_| jd | ddg | |g  dS )z
        Like L{test_invalidBase64EncodedResponse} but for the case of an
        initial response included with the C{AUTH} command.
        r  s   AUTH LOGIN x
r  Nr  r  r%   r%   r(   (test_invalidBase64EncodedInitialResponse  s   zAESMTPAuthenticationTests.test_invalidBase64EncodedInitialResponsec                 C   s   g }|  || j_| jd | j  | dtd	  d dtd	  g | td	 d g  |
 \}}}}|td | d	| j  | t| td
 dS )z
        If the L{Deferred} returned by L{Portal.login} fires with an
        exception of any type other than L{UnauthorizedLogin}, the exception
        is logged and the client is informed that the authentication attempt
        has failed.
        r  r  r  r   r  r  r  zSomething wrong with the servers9   451 Requested action aborted: local error in processing
r]   N)r  r   r  r   r   r   r  r  r  r  r   errbackr5   r   r   r7  r  )r.   r  r   r   r  r   r%   r%   r(   test_unexpectedLoginFailure  s    
z4ESMTPAuthenticationTests.test_unexpectedLoginFailureN)r  r  )r:   r;   r<   r  r  r  r  r  r  r  r  r  r  r  r  r   r%   r%   r%   r(   r    s    
	r  c                   @   r>   )	SMTPClientErrorTestsz,
    Tests for L{smtp.SMTPClientError}.
    c                 C       t dd}| t|d dS )z
        The string representation of a L{SMTPClientError} instance includes
        the response code and response string.
        r   z	some textz123 some textNr   r   r   r1  r.   errr%   r%   r(   test_str     zSMTPClientErrorTests.test_strc                 C   r  )z
        If the response code supplied to L{SMTPClientError} is negative, it
        is excluded from the string representation.
        s   foo barzfoo barNr  r  r%   r%   r(   test_strWithNegativeCode  r  z-SMTPClientErrorTests.test_strWithNegativeCodec                 C   sD   t d}|d |d tjdd| d}| t|d dS )	z
        If a line log is supplied to L{SMTPClientError}, its contents are
        included in the string representation of the exception instance.
        
   s   testlogs
   secondlined   z
test error)rs   z"100 test error
testlog
secondline
N)r   rF   r   r   r1  r   )r.   rs   r  r%   r%   r(   test_strWithLog  s
   

z$SMTPClientErrorTests.test_strWithLogN)r:   r;   r<   r=   r  r	  r  r%   r%   r%   r(   r    s
    r  c                   @   rB  )SenderMixinSentMailTestsz
    Tests for L{smtp.SenderMixin.sentMail}, used in particular by
    L{smtp.SMTPSenderFactory} and L{smtp.ESMTPSenderFactory}.
    c                    sr     t tj}| fdd tjddtd|ddd}|t	
d	d
d}ddg}|ddd||j |S )z
        L{smtp.SenderMixin.sentMail} adds only the addresses with failing
        SMTP response codes to the log passed to the factory's errback.
        c                    s     | jdS )Ns'   bob@example.com: 199 Error in sending.
)r   rs   )r.  r6   r%   r(   rV     s    zFSenderMixinSentMailTests.test_onlyLogFailedAddresses.<locals>.<lambda>rk  rt  rl  r   r[  rm  rX  rY  rZ  )s   alice@example.com   s   No errors here!)s   bob@example.com   s   Error in sending.r  s   Test responser]   )rd  r   rM   r   SMTPDeliveryErrorr   rq  r   ra  r   rb  rt   rs   )r.   rf  rg  r   rr   r%   r6   r(   test_onlyLogFailedAddresses  s(   
	z4SenderMixinSentMailTests.test_onlyLogFailedAddressesN)r:   r;   r<   r=   r  r%   r%   r%   r(   r    s    r  c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )ESMTPDowngradeTestCasezU
    Tests for the ESMTP -> SMTP downgrade functionality in L{smtp.ESMTPClient}.
    c                 C   s   t dd d| _d S )Nr   r   )r   r|   clientProtocolr6   r%   r%   r(   r    r  zESMTPDowngradeTestCase.setUpc                 C   s^   t  }d| j_d| j_d| j_| j| | jd |  | jd | d|	  dS )z
        If both authentication and transport security are not required, and it
        is asked for, it will fall back to allowing HELO.
        FT   220 localhost
   500 not an esmtp server
   HELO testuser
N
r   r  requireAuthenticationrequireTransportSecurityheloFallbackr   r   r   r   r   r.   r   r%   r%   r(    test_requireHELOFallbackOperates     z7ESMTPDowngradeTestCase.test_requireHELOFallbackOperatesc                 C   s^   t  }d| j_d| j_d| j_| j| | jd |  | jd | d|	  dS )z
        If authentication is required, and HELO fallback is on, HELO fallback
        must not be honoured, as authentication requires EHLO to succeed.
        TFr  r  r   Nr  r  r%   r%   r(   !test_requireAuthFailsHELOFallback  r  z8ESMTPDowngradeTestCase.test_requireAuthFailsHELOFallbackc                 C   s^   t  }d| j_d| j_d| j_| j| | jd |  | jd | d|	  dS )z
        If TLS is required and the connection is insecure, HELO fallback must
        not be honoured, as STARTTLS requires EHLO to succeed.
        FTr  r  r   Nr  r  r%   r%   r(    test_requireTLSFailsHELOFallback  r  z7ESMTPDowngradeTestCase.test_requireTLSFailsHELOFallbackc                 C   sj   t  }t|tj d| j_d| j_d| j_| j| | j	d |
  | j	d | d|  dS )z
        If TLS is provided at the transport level, we can honour the HELO
        fallback if we're set to require TLS.
        FTr  r  r  N)r   r   r   ISSLTransportr  r  r  r  r   r   r   r   r   r  r%   r%   r(   /test_requireTLSAndHELOFallbackSucceedsIfOverTLS-  s   zFESMTPDowngradeTestCase.test_requireTLSAndHELOFallbackSucceedsIfOverTLSN)	r:   r;   r<   r=   r  r  r  r  r!  r%   r%   r%   r(   r    s    r  c                   @   sd   e Zd ZdZeZdZdZdd Zdd Z	dd	 Z
d
d Zdd Zdd Zdd Zdd Zdd ZdS )SSLTestCasezD
    Tests for the TLS negotiation done by L{smtp.ESMTPClient}.
    s3   220 localhost NO UCE NO UBE NO RELAY PROBES ESMTP
s1   250-localhost Hello 127.0.0.1, nice to meet you
c                 C   s*   t dt d| _d| j_dd | j_d S )Nr   r   Tc                   S   s   dS )Nztest@example.orgr%   r%   r%   r%   r(   rV   N  r  z#SSLTestCase.setUp.<locals>.<lambda>)r   r|   r!   r  r  rf   r6   r%   r%   r(   r  I  s
   zSSLTestCase.setUpc                 C   sZ   t  }t|tj | j| | j| j |  | j| j	|  | 
d|  dS )a  
        Verify that when L{smtp.ESMTPClient} connects to a server over a
        transport providing L{ISSLTransport}, C{requireTransportSecurity} is
        C{True}, and it is presented with the given capabilities, it will try
        to send its mail and not first attempt to negotiate TLS using the
        I{STARTTLS} protocol action.

        @param capabilities: Bytes to include in the test server's capability
            response.  These must be formatted exactly as required by the
            protocol, including a line which ends the capability response.
        @type param: L{bytes}

        @raise: C{self.failureException} if the behavior of
            C{self.clientProtocol} is not as described.
        s   MAIL FROM:<test@example.org>
N)r   r   r   r   r  r   r   SERVER_GREETINGr   EHLO_RESPONSEr   r   )r.   capabilitiesr   r%   r%   r(   $_requireTransportSecurityOverSSLTestP  s   z0SSLTestCase._requireTransportSecurityOverSSLTestc                 C      |  d dS )z
        When C{requireTransportSecurity} is C{True} and the client is connected
        over an SSL transport, mail may be delivered.
           250 AUTH LOGIN
Nr&  r6   r%   r%   r(   $test_requireTransportSecurityOverSSLo     z0SSLTestCase.test_requireTransportSecurityOverSSLc                 C   N   t  }| j| | j| j |  | j| jd  | d|  dS )z
        When C{requireTransportSecurity} is C{True} and the client is connected
        over a non-SSL transport, if the server offers the I{STARTTLS}
        extension, it is used before mail is delivered.
           250-AUTH LOGIN
250 STARTTLS
s
   STARTTLS
N	r   r  r   r   r#  r   r$  r   r   r  r%   r%   r(   'test_requireTransportSecurityTLSOfferedv  s   z3SSLTestCase.test_requireTransportSecurityTLSOfferedc                 C   r'  )z
        When C{requireTransportSecurity} is C{True} and the client is connected
        over an SSL transport, if the server offers the I{STARTTLS}
        extension, it is not used before mail is delivered.
        r-  Nr)  r6   r%   r%   r(   .test_requireTransportSecurityTLSOfferedOverSSL  s   z:SSLTestCase.test_requireTransportSecurityTLSOfferedOverSSLc                 C   r,  )z
        When C{requireTransportSecurity} is C{True} and the client is connected
        over a non-SSL transport, if the server does not offer the I{STARTTLS}
        extension, mail is not delivered.
        r(  r   Nr.  r  r%   r%   r(   *test_requireTransportSecurityTLSNotOffered  s   z6SSLTestCase.test_requireTransportSecurityTLSNotOfferedc                 C   sV   | j j}~| j| jgd}| t|d | |d d t | |d d d dS )<
        L{smtp.ESMTPClient.tlsMode} is deprecated.
        offendingFunctionsr]   r   categoryrO   StlsMode attribute of twisted.mail.smtp.ESMTPClient is deprecated since Twisted 13.0N)r  tlsModeflushWarnings%test_esmtpClientTlsModeDeprecationGetr   r7  assertIdenticalDeprecationWarning)r.   valwarningsShownr%   r%   r(   r9    s   
z1SSLTestCase.test_esmtpClientTlsModeDeprecationGetc                    s     t fdd dS )z
        L{smtp.ESMTPClient.__getattr__} raises an attribute error for other
        attribute names which do not exist.
        c                      s    j jS r$   )r  doesNotExistr%   r6   r%   r(   rV     s    zQSSLTestCase.test_esmtpClientTlsModeDeprecationGetAttributeError.<locals>.<lambda>N)assertRaisesAttributeErrorr6   r%   r6   r(   3test_esmtpClientTlsModeDeprecationGetAttributeError  s   z?SSLTestCase.test_esmtpClientTlsModeDeprecationGetAttributeErrorc                 C   sT   d| j _| j| jgd}| t|d | |d d t | |d d d dS )	r2  Fr3  r]   r   r5  rO   r6  N)r  r7  r8  %test_esmtpClientTlsModeDeprecationSetr   r7  r:  r;  )r.   r=  r%   r%   r(   rB    s   
z1SSLTestCase.test_esmtpClientTlsModeDeprecationSetN)r:   r;   r<   r=   r    rQ  r#  r$  r  r&  r*  r/  r0  r1  r9  rA  rB  r%   r%   r%   r(   r"  ?  s    
r"  c                   @   s   e Zd ZdZdZdd ZdS )AbortableStringTransportzK
    A version of L{StringTransport} that supports C{abortConnection}.
    Fc                 C   s   d| _ |   dS )z
        A testable version of the C{ITCPTransport.abortConnection} method.

        Since this is a special case of closing the connection,
        C{loseConnection} is also called.
        TN)abortingr   r6   r%   r%   r(   abortConnection  s   z(AbortableStringTransport.abortConnectionN)r:   r;   r<   r=   rD  rE  r%   r%   r%   r(   rC    s    rC  c                   @   sX   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd ZdS )SendmailTestsz2
    Tests for L{twisted.mail.smtp.sendmail}.
    c                 C   s(   t tj\}}}}| t|d  dS )z{
        The default C{reactor} parameter of L{twisted.mail.smtp.sendmail} is
        L{twisted.internet.reactor}.
        r^   N)inspect
getargspecr   sendmailr   r   )r.   argsvarArgskeywordsdefaultsr%   r%   r(   "test_defaultReactorIsGlobalReactor  s   z0SendmailTests.test_defaultReactorIsGlobalReactorc                 C   sl   t  }tjdddd|||ddd	 |jd d }| |jd | |jd | |jd	 | |jd
 dS )zk
        L{twisted.mail.smtp.sendmail} creates the ESMTP factory with the ESMTP
        arguments.
        r  rk  rt  r  T)r   r   rx  r  r  r   r^   r      barN)	r   r   rI  
tcpClientsr   _requireTransportSecurity_requireAuthenticationr   rx  )r.   r   rx  r   r   r%   r%   r(   _honorsESMTPArguments  s"   z#SendmailTests._honorsESMTPArgumentsc                 C      | j dddS )zw
        L{twisted.mail.smtp.sendmail} should accept C{username} and C{password}
        which are L{unicode}.
        r   barr   rx  rS  r6   r%   r%   r(   &test_honorsESMTPArgumentsUnicodeUserPW  r+  z4SendmailTests.test_honorsESMTPArgumentsUnicodeUserPWc                 C   rT  )zu
        L{twisted.mail.smtp.sendmail} should accept C{username} and C{password}
        which are L{bytes}.
        r   rO  rV  rW  r6   r%   r%   r(   $test_honorsESMTPArgumentsBytesUserPW  r+  z2SendmailTests.test_honorsESMTPArgumentsBytesUserPWc                 C   sB   t  }td}tjddd||d |jd d }| |j| dS )	z|
        L{twisted.mail.smtp.sendmail} will pass through the message untouched
        if it is a file-like object.
        s   File!r  rk  rt  r   r   r^   N)r   r   r   rI  rP  assertIsfile)r.   r   messageFiler   r%   r%   r(   test_messageFilePassthrough  s   z)SendmailTests.test_messageFilePassthroughc                 C   sL   t  }tjdddd|d |jd d }|j}|d | | d dS )	z
        L{twisted.mail.smtp.sendmail} will turn non-file-like objects
        (eg. strings) into file-like objects before sending.
        r  rk  rt  r  rZ  r   r^   N)r   r   rI  rP  r\  seekr   r  )r.   r   r   r]  r%   r%   r(   test_messageStringMadeFile(  s   
z(SendmailTests.test_messageStringMadeFilec                 C   s<   t  }tjdddd|dd |jd d }| |jd	 d
S )zk
        L{twisted.mail.smtp.sendmail} passes through the sender domain name, if
        provided.
        r  rk  rt  r  r   )r   senderDomainNamer   r^   r   N)r   r   rI  rP  r   rA   )r.   r   r   r%   r%   r(   test_senderDomainName:  s   z#SendmailTests.test_senderDomainNamec                 C   sP   t  }tjdddd|d}|  | |jd jd | |}|t	j
 dS )	z
        When a user cancels L{twisted.mail.smtp.sendmail} before the connection
        is made, the connection is closed by
        L{twisted.internet.interfaces.IConnector.disconnect}.
        r  rk  rt  r  rZ  r   TN)r   r   rI  cancelr   
connectors_disconnectedfailureResultOftrapr   CancelledError)r.   r   r   failurer%   r%   r(   test_cancelBeforeConnectionMadeK  s   
z-SendmailTests.test_cancelBeforeConnectionMadec                 C   s   t  }t }tjdddd|d}|jd d }|d}|| |  | |j	d	 | |j
d	 | |}|tj dS )
z
        When a user cancels L{twisted.mail.smtp.sendmail} after the connection
        is made, the connection is closed by
        L{twisted.internet.interfaces.ITransport.abortConnection}.
        r  rk  rt  r  rZ  r   r^   NT)r   rC  r   rI  rP  ra  r   rc  r   rD  r   rf  rg  r   rh  )r.   r   r   r   r   r  ri  r%   r%   r(   test_cancelAfterConnectionMade^  s"   


z,SendmailTests.test_cancelAfterConnectionMadeN)r:   r;   r<   r=   rN  rS  rX  rY  r^  r`  rb  rj  rk  r%   r%   r%   r(   rF    s    rF  )kr=   r  rG  rD   ior   typingr   r   r   r   r   zope.interfacer   r	   twisted.cred.checkersr  twisted.cred.credentialstwisted.cred.errortwisted.cred.portalr
   r   r   r   r   r   r   twisted.internetr   r   r   r   r   r   r   twisted.mailr   twisted.mail._credr   twisted.protocolsr   r   twisted.python.utilr   twisted.test.proto_helpersr   r   twisted.trial.unittestr   r1  r   twisted.test.ssl_helpersr!   r"   ImportErrorr    IReactorSSLr  r)   IMessager,   r?   rR   r_   r\   rw   ru   r|   rz   r   LineReceiverr   r   r   r   r   r   r   r   r   r   r   checkersr   r  r   r
  r  r#  rC  rH  rR  rW  r  r  r  r  r  r  r  r  r  r  r  r"  rC  rF  r%   r%   r%   r(   <module>   s   $um
B= 7$@ R \!(J 