Class: Cybertrain::Test::Client

Inherits:
Object
  • Object
show all
Defined in:
cybertrain/test/client.rb

Overview

Drives an App (or a bare Router) in-process, the way Rails integration tests do: no socket, one Context per request, and a cookie jar that carries Set-Cookie values into the next request’s Cookie header.

Sessions, flash and CSRF behave as behind a browser: a form POST needs the authenticity_token from a page the client rendered. Redirects are not followed unless you call #follow_redirect!. Requires require "cybertrain/test/client" (which also loads Cybertrain::Test).

Examples:

# Cybertrain::Test.app is the application `cybertrain test` booted;
# BlogTestHelper is examples/blog/test/support/blog_test_helper.rb
client = Cybertrain::Test::Client.new(Cybertrain::Test.app)
client.get("/articles/new")
res = client.post("/articles", { "authenticity_token" => BlogTestHelper.form_token(client.response.body),
                                 "article[title]" => "Hello Rails",
                                 "article[body]" => "I am on Rails! This is my first article." })
assert_response res, :see_other
client.follow_redirect!
assert_includes client.response.body, "Hello Rails"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Client

Returns a new instance of Client.

Parameters:

  • app (Application) —

    a booted application (anything with call(ctx))



302
303
304
305
306
307
308
# File 'cybertrain/test/client.rb', line 302

def initialize(app)
  @app = app
  @response = Response.new
  @cookies = ClientCookies.new
  @boundary_counter = 0
  @peer_address = REMOTE_ADDR
end

Instance Attribute Details

#cookies ⇒ ClientCookies (readonly)

The cookie jar: name (a String or a Symbol) to raw (still percent-encoded) value; expired cookies are gone (Cybertrain::Test::ClientCookies).

Returns:



287
288
289
# File 'cybertrain/test/client.rb', line 287

def cookies
  @cookies
end

#peer_address ⇒ String

The address the requests come from, request.remote_addr in the app: “127.0.0.1” (REMOTE_ADDR) unless a test sets another, to see what a page does for a client on another machine (request.loopback?).

Examples:

client.peer_address = "203.0.113.7"
assert_response client.get("/setup"), :not_found

Returns:

  • (String)


297
298
299
# File 'cybertrain/test/client.rb', line 297

def peer_address
  @peer_address
end

#response ⇒ Response (readonly)

The last response.

Returns:



281
282
283
# File 'cybertrain/test/client.rb', line 281

def response
  @response
end

Instance Method Details

#delete(path, params = {}, headers = {}) ⇒ Response

Parameters:

  • path (String)
  • params (Hash{String => String}) (defaults to: {})
  • headers (Hash{String => String}) (defaults to: {})

Returns:



361
362
363
# File 'cybertrain/test/client.rb', line 361

def delete(path, params = {}, headers = {})
  form_request("DELETE", path, params, headers)
end

#follow_redirect! ⇒ Response

GETs the Location of the last response; an absolute URL is reduced to its path and query so it stays inside the app, and the fragment (#comments) is never sent, as a browser never sends one.

Returns:

Raises:

  • (AssertionFailed) —

    when the last response was not a redirect (a 3xx with a Location)



460
461
462
# File 'cybertrain/test/client.rb', line 460

def follow_redirect!
  get(Client.local_path(Client.redirect_location(@response)))
end

#get(path, headers = {}) ⇒ Response

Parameters:

  • path (String) —

    with its query string, if any ("/articles?page=2")

  • headers (Hash{String => String}) (defaults to: {})

Returns:



322
323
324
# File 'cybertrain/test/client.rb', line 322

def get(path, headers = {})
  request("GET", path, "", headers)
end

#get_stream(path, events:, timeout: 2, headers: {}) ⇒ Response

GETs a streaming path (the stream endpoint, an action that calls Controller#stream) and runs its writer against an in-memory sink until events events (SSE comments such as : ping do not count) have been written or timeout seconds have passed. The Response’s body is then what was written. A response that does not stream is returned as #get returns it.

Examples:

Cybertrain::Stream.broadcast("alerts", "hi")
res = client.get_stream("/cybertrain/stream?s=#{token}", events: 1, headers: { "last-event-id" => "0" })
assert_includes res.body, "data: hi"

Parameters:

  • path (String)
  • events (Integer)
  • timeout (Numeric) (defaults to: 2) —

    seconds

  • headers (Hash{String => String}) (defaults to: {})

Returns:



414
415
416
417
418
419
420
421
422
423
424
# File 'cybertrain/test/client.rb', line 414

def get_stream(path, events:, timeout: 2, headers: {})
  response = request("GET", path, "", headers)
  writer = response.body_writer
  return response if writer.nil?

  sink = MemorySink.new(events, timeout)
  # Under the request's log Scope, as the Server writes it.
  BodyWriter.write_scoped(writer, sink, response.body_scope)
  response.body = sink.memory_text
  response
end

#patch(path, params = {}, headers = {}) ⇒ Response

Parameters:

  • path (String)
  • params (Hash{String => String}) (defaults to: {})
  • headers (Hash{String => String}) (defaults to: {})

Returns:



343
344
345
# File 'cybertrain/test/client.rb', line 343

def patch(path, params = {}, headers = {})
  form_request("PATCH", path, params, headers)
end

#patch_multipart(path, fields = {}, uploads = [], headers = {}) ⇒ Response

Like #post_multipart for an edit form: a POST that carries the text part _method=patch, which MethodOverride turns into a PATCH (as a browser form does).

Parameters:

  • path (String)
  • fields (Hash{String => String}) (defaults to: {}) —

    text parts

  • uploads (Array<Upload>) (defaults to: []) —

    file parts

  • headers (Hash{String => String}) (defaults to: {})

Returns:



391
392
393
394
395
396
# File 'cybertrain/test/client.rb', line 391

def patch_multipart(path, fields = {}, uploads = [], headers = {})
  with_method = {}
  fields.each { |k, v| with_method[k] = v }
  with_method["_method"] = "patch"
  multipart_request(path, with_method, uploads, headers)
end

#post(path, params = {}, headers = {}) ⇒ Response

Sends params as a urlencoded form. Keys are written as a browser would ("article[title]"); for PATCH/DELETE from a form, add "_method" => "patch" or call #patch / #delete.

Parameters:

  • path (String)
  • params (Hash{String => String}) (defaults to: {})
  • headers (Hash{String => String}) (defaults to: {})

Returns:



334
335
336
# File 'cybertrain/test/client.rb', line 334

def post(path, params = {}, headers = {})
  form_request("POST", path, params, headers)
end

#post_multipart(path, fields = {}, uploads = [], headers = {}) ⇒ Response

Sends a multipart/form-data POST, the way a browser sends a form with file fields: fields as text parts (put the authenticity_token there like any form), then each Upload as a file part. The boundary is chosen so that no part contains it.

Examples:

client.post_multipart("/posts", { "authenticity_token" => token, "post[title]" => "Hi" },
                      [Cybertrain::Test::Upload.new("post[cover]", "cover.png", "image/png", png)])

Parameters:

  • path (String)
  • fields (Hash{String => String}) (defaults to: {}) —

    text parts

  • uploads (Array<Upload>) (defaults to: []) —

    file parts

  • headers (Hash{String => String}) (defaults to: {})

Returns:



378
379
380
# File 'cybertrain/test/client.rb', line 378

def post_multipart(path, fields = {}, uploads = [], headers = {})
  multipart_request(path, fields, uploads, headers)
end

#put(path, params = {}, headers = {}) ⇒ Response

Parameters:

  • path (String)
  • params (Hash{String => String}) (defaults to: {})
  • headers (Hash{String => String}) (defaults to: {})

Returns:



352
353
354
# File 'cybertrain/test/client.rb', line 352

def put(path, params = {}, headers = {})
  form_request("PUT", path, params, headers)
end

#request(method, path, body = "", headers = {}) ⇒ Response

Runs one request through the app and returns (and remembers) its Response. Header names are lowercased as HttpParser would. Any method and body, e.g. a JSON request.

Examples:

client.request("POST", "/api/notes", '{"title":"x"}', { "content-type" => "application/json" })

Parameters:

  • method (String)
  • path (String)
  • body (String) (defaults to: "")
  • headers (Hash{String => String}) (defaults to: {})

Returns:



437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'cybertrain/test/client.rb', line 437

def request(method, path, body = "", headers = {})
  head = {}
  headers.each { |k, v| head[k.downcase] = v }
  head["host"] = TEST_HOST unless head.key?("host")
  head["content-length"] = body.bytesize.to_s unless body.empty?
  unless head.key?("cookie")
    sent = @cookies.jar_header
    head["cookie"] = sent unless sent.empty?
  end
  ctx = Context.new(Request.new(method, path, head, body, @peer_address))
  @app.call(ctx)
  @response = ctx.response
  store_cookies(@response)
  @response
end