summaryrefslogtreecommitdiff
path: root/spec/ruby/library/socket/socket/tcp_spec.rb
blob: 29f166ffc513746fea7e48e8ee9a7069e213edcd (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
require_relative '../spec_helper'

describe 'Socket.tcp' do
  before do
    @server = Socket.new(:INET, :STREAM)
    @client = nil

    @server.bind(Socket.sockaddr_in(0, '127.0.0.1'))
    @server.listen(1)

    @host = @server.connect_address.ip_address
    @port = @server.connect_address.ip_port
  end

  after do
    @client.close if @client && !@client.closed?
    @client = nil

    @server.close
  end

  it 'returns a Socket when no block is given' do
    @client = Socket.tcp(@host, @port)

    @client.should be_an_instance_of(Socket)
  end

  it 'yields the Socket when a block is given' do
    Socket.tcp(@host, @port) do |socket|
      socket.should be_an_instance_of(Socket)
    end
  end

  it 'closes the Socket automatically when a block is given' do
    Socket.tcp(@host, @port) do |socket|
      @socket = socket
    end

    @socket.closed?.should == true
  end

  it 'binds to a local address and port when specified' do
    @client = Socket.tcp(@host, @port, @host, 0)

    @client.local_address.ip_address.should == @host

    @client.local_address.ip_port.should > 0
    @client.local_address.ip_port.should_not == @port
  end

  it 'raises ArgumentError when 6 arguments are provided' do
    lambda {
      Socket.tcp(@host, @port, @host, 0, {:connect_timeout => 1}, 10)
    }.should raise_error(ArgumentError)
  end

  it 'connects to the server' do
    @client = Socket.tcp(@host, @port)

    @client.write('hello')

    connection, _ = @server.accept

    begin
      connection.recv(5).should == 'hello'
    ensure
      connection.close
    end
  end
end