summaryrefslogtreecommitdiff
path: root/jni/ruby/test/net/smtp/test_ssl_socket.rb
blob: dc8b03e07a6295c30b9d37b89ebd909a9daf340e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
require 'net/smtp'
require 'minitest/autorun'

module Net
  class TestSSLSocket < MiniTest::Unit::TestCase
    class MySMTP < SMTP
      attr_accessor :fake_tcp, :fake_ssl

      def tcp_socket address, port
        fake_tcp
      end

      def ssl_socket socket, context
        fake_ssl
      end
    end

    require 'stringio'
    class SSLSocket < StringIO
      attr_accessor :sync_close, :connected, :closed

      def initialize(*args)
        @connected = false
        @closed    = true
        super
      end

      def connect
        self.connected = true
        self.closed = false
      end

      def close
        self.closed = true
      end

      def post_connection_check omg
      end
    end

    def test_ssl_socket_close_on_post_connection_check_fail
      tcp_socket = StringIO.new success_response

      ssl_socket = SSLSocket.new.extend Module.new {
        def post_connection_check omg
          raise OpenSSL::SSL::SSLError, 'hostname was not match with the server certificate'
        end
      }

      connection = MySMTP.new('localhost', 25)
      connection.enable_starttls_auto
      connection.fake_tcp = tcp_socket
      connection.fake_ssl = ssl_socket

      assert_raises(OpenSSL::SSL::SSLError) do
        connection.start
      end
      assert_equal true, ssl_socket.closed
    end

    def test_ssl_socket_open_on_post_connection_check_success
      tcp_socket = StringIO.new success_response

      ssl_socket = SSLSocket.new success_response

      connection = MySMTP.new('localhost', 25)
      connection.enable_starttls_auto
      connection.fake_tcp = tcp_socket
      connection.fake_ssl = ssl_socket

      connection.start
      assert_equal false, ssl_socket.closed
    end

    def success_response
      [
        '220 smtp.example.com ESMTP Postfix',
        "250-ubuntu-desktop",
        "250-PIPELINING",
        "250-SIZE 10240000",
        "250-VRFY",
        "250-ETRN",
        "250-STARTTLS",
        "250-ENHANCEDSTATUSCODES",
        "250-8BITMIME",
        "250 DSN",
        "220 2.0.0 Ready to start TLS",
      ].join("\r\n") + "\r\n"
    end
  end
end if defined?(OpenSSL)