File: socket_acceptance_spec.rb

package info (click to toggle)
ruby-flores 0.0.8-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 244 kB
  • sloc: ruby: 952; makefile: 36
file content (81 lines) | stat: -rw-r--r-- 1,943 bytes parent folder | download
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
# encoding: utf-8
# This file is part of ruby-flores.
# Copyright (C) 2015 Jordan Sissel
# 
require "flores/rspec"
require "flores/random"
require "socket"

RSpec.configure do |config|
  Kernel.srand config.seed
  Flores::RSpec.configure(config)

  # Demonstrate the wonderful Analyze formatter
  config.add_formatter("Flores::RSpec::Formatters::Analyze")
end

# A factory for encapsulating behavior of a tcp server and client for the
# purposes of testing.
#
# This is probably not really a "factory" in a purist-sense, but whatever.
class TCPIntegrationTestFactory
  def initialize(port)
    @listener = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
    @client = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
    @port = port
  end

  def teardown
    @listener.close unless @listener.closed?
    @client.close unless @listener.closed?
  end

  def sockaddr
    Socket.sockaddr_in(@port, "127.0.0.1")
  end

  def setup
    @listener.bind(sockaddr)
    @listener.listen(5)
  end

  def send_and_receive(text)
    @client.connect(sockaddr)
    server, _ = @listener.accept

    @client.syswrite(text)
    @client.close
    data = server.read
    data.force_encoding(Encoding.default_external).encoding
    data
  ensure
    @client.close unless @client.closed?
    server.close unless server.nil? || server.closed?
  end
end

describe "TCPServer+TCPSocket" do
  analyze_results

  let(:port) { Flores::Random.integer(1024..65535) }
  let(:text) { Flores::Random.text(1..2000) }
  subject { TCPIntegrationTestFactory.new(port) }

  before do
    begin
      subject.setup
    rescue Errno::EADDRINUSE
      skip "Port #{port} was in use. Skipping!"
    end
  end
  
  stress_it "should send data correctly", [:port, :text] do
    begin
      received = subject.send_and_receive(text)
      expect(received.encoding).to(be == text.encoding)
      expect(received).to(be == text)
    ensure
      subject.teardown
    end
  end
end