Class: Docker::API::Transport::Fake

Inherits:
Base
  • Object
show all
Defined in:
lib/docker/api/transport/fake.rb

Overview

A scripted daemon for tests, served over a real socket pair.

The socket is genuine on purpose. Net::BufferedIO calls read_nonblock, write and to_io on whatever it is handed, and a StringIO does not honour that contract. Faking it produces tests that pass against a double the production code could never actually drive. Socket.pair gives real socket semantics with no network, so the connection layer is exercised exactly as it runs against a daemon -- including chunked bodies, keep-alive and connection upgrades.

Examples:

Scripting one response

fake = Docker::API::Transport::Fake.new([
  "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
])
client = Docker::API::Client.new(transport: fake, api_version: "1.55")
client.system.info
fake.requests.first #=> "GET /v1.55/info HTTP/1.1\r\n..."

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#host_header

Constructor Details

#initialize(responses = []) ⇒ Fake

Returns a new instance of Fake.

Parameters:

  • responses (Array<String>) (defaults to: [])

    raw HTTP responses to serve, in order



31
32
33
34
35
36
37
# File 'lib/docker/api/transport/fake.rb', line 31

def initialize(responses = [])
  super()
  @responses = Array(responses).dup
  @requests = []
  @mutex = Mutex.new
  @threads = []
end

Instance Attribute Details

#requestsArray<String> (readonly)

Returns raw request bytes, in the order received.

Returns:

  • (Array<String>)

    raw request bytes, in the order received



28
29
30
# File 'lib/docker/api/transport/fake.rb', line 28

def requests
  @requests
end

Instance Method Details

#<<(response) ⇒ self

Add another scripted response.

Parameters:

  • response (String)

    raw HTTP response bytes

Returns:

  • (self)


43
44
45
46
# File 'lib/docker/api/transport/fake.rb', line 43

def <<(response)
  @mutex.synchronize { @responses << response }
  self
end

#connectIO

Returns the client end of a socket pair with a server behind it.

Returns:

  • (IO)

    the client end of a socket pair with a server behind it



49
50
51
52
53
54
55
# File 'lib/docker/api/transport/fake.rb', line 49

def connect
  ours, theirs = Socket.pair(:UNIX, :STREAM)
  thread = Thread.new { serve(theirs) }
  thread.report_on_exception = false
  @threads << thread
  ours
end

#finishvoid

This method returns an undefined value.

Wait for the scripted server to finish, so assertions about recorded requests do not race the thread that records them.



61
62
63
64
# File 'lib/docker/api/transport/fake.rb', line 61

def finish
  @threads.each { |thread| thread.join(2) }
  self
end

#to_sString Also known as: inspect

Returns:

  • (String)


67
68
69
# File 'lib/docker/api/transport/fake.rb', line 67

def to_s
  "#<Docker::API::Transport::Fake scripted=#{@responses.size}>"
end