Module: Cybertrain::Test

Defined in:
cybertrain/test.rb,
cybertrain/test/args.rb,
cybertrain/test/jobs.rb,
cybertrain/test/mail.rb,
cybertrain/test_help.rb,
cybertrain/test_help.rb,
cybertrain/test_help.rb,
cybertrain/test/views.rb,
cybertrain/test/bundle.rb,
cybertrain/test/client.rb,
cybertrain/test/select.rb,
cybertrain/test/database.rb,
cybertrain/test/receiver.rb,
cybertrain/test/test_case.rb,
cybertrain/test/assertions.rb,
cybertrain/test/broadcasts.rb,
cybertrain/test/html_reader.rb,
cybertrain/test/integration.rb,
cybertrain/test/http_receiver.rb,
cybertrain/test/smtp_receiver.rb,
cybertrain/test/sentry_receiver.rb,
cybertrain/test/websocket_receiver.rb

Overview

The test harness for applications (and the framework’s own tests). minitest and RSpec cannot run under Spinel, so a test file is a plain program: it registers cases with the top-level test "name" do ... end, asserts with the top-level assert* methods (see the overview), and ends with Cybertrain::Test.run!. For requests, see Client. An application’s tests are usually the class form instead (ActiveSupport::TestCase and its subclasses, run by cybertrain test; docs/guide/testing.md); this is the top-level form.

cybertrain spin test compiles each test/*.rb (not test/support/) into its own program and compares its output with test/<name>.rb.expected. Top-level setup do ... end and teardown do ... end run before and after every case of the file; after each case the clock is real again and every receiver the case started is stopped; before each case nothing rendered or requested is left for assert_select, no log tags are left on the thread (Cybertrain.logger.tagged), and the Test.on_reset hooks run (with cybertrain/test_help: the default locale, the rate-limit counters, Mailer.deliveries and the broadcasts’ starting point). The database is not reset under spin test: clear what you need in setup (e.g. Article.all.delete_all). In cybertrain test every table is emptied and the fixtures loaded before each case, and the configured time zone is restored.

Examples:

test/article_title.rb

require "test_helper"

setup do
  Article.all.delete_all
end

test "title must be present" do
  article = Article.new(body: "a body long enough to pass length")
  refute article.save
  assert_includes article.errors.full_messages, "Title can't be blank"
end

Cybertrain::Test.run!

Defined Under Namespace

Modules: HtmlReader, Selector Classes: AssertionFailed, Base, Client, ClientCookies, FixtureNotFound, HtmlNode, HttpReceiver, ReceivedMessage, ReceivedRequest, Receiver, RecordedFrame, SentryEnvelope, SentryReceiver, SmtpReceiver, Upload, WebSocketReceiver, WsStep

Class Method Summary collapse

Class Method Details

.after_case(t) ⇒ nil

Steps 6-7: t.teardown, always (a failure is reported after the body’s, on a line of its own), then, in this plain method’s ensure, travel_back and every after_this_case callable.

Parameters:

Returns:

  • (nil)


423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'cybertrain/test.rb', line 423

def self.after_case(t)
  t.teardown
  nil
rescue AssertionFailed => e
  step_failed("in teardown", e.message)
  nil
rescue StandardError => e
  step_failed("in teardown", "#{e.class.name}: #{e.message}")
  nil
rescue NotImplementedError, SystemStackError, ScriptError => e
  step_failed("in teardown", "#{e.class.name}: #{e.message}")
  nil
ensure
  case_cleanup
end

.after_this_case(callable) ⇒ nil

Registers a callable run once, after the current test’s teardown (step 7), then forgotten; such callables run newest first. A receiver’s start registers its stop here.

Parameters:

  • callable (Proc) —

    a lambda taking no argument

Returns:

  • (nil)


244
245
246
247
# File 'cybertrain/test.rb', line 244

def self.after_this_case(callable)
  @after_this_case << callable
  nil
end

.before_case(t) ⇒ Boolean

Steps 1-4 of the order for a class-form test: the bundle’s database steps, the resets, then t.setup (which calls super first). False when one of them raised: the case is then ERR with the step named and its body must not run. Records only; the runners print.

Examples:

what cybertrain test runs for each test

t = ArticleTest.new
if Cybertrain::Test.before_case(t)
  Cybertrain::Test.run_body(t) { t.test_title_must_be_present }
end
Cybertrain::Test.after_case(t)

Parameters:

Returns:

  • (Boolean)


365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'cybertrain/test.rb', line 365

def self.before_case(t)
  return false unless case_begin

  t.setup
  true
rescue AssertionFailed => e
  step_failed("in setup", e.message)
  false
rescue StandardError => e
  step_failed("in setup", "#{e.class.name}: #{e.message}")
  false
rescue NotImplementedError, SystemStackError, ScriptError => e
  step_failed("in setup", "#{e.class.name}: #{e.message}")
  false
end

.binary(ints) ⇒ String

A binary String from a list of byte values, for file contents in a test: NUL and 0x80..0xFF come out as exactly those bytes on CRuby and under Spinel.

Examples:

Cybertrain::Test.binary([0x89, 0x50, 0x4E, 0x47, 0, 255]).bytesize   # => 6

Parameters:

  • ints (Array<Integer>) —

    each 0..255

Returns:

  • (String) —

    binary

Raises:

  • (ArgumentError) —

    for a value outside 0..255



68
69
70
71
72
73
74
75
76
77
78
79
# File 'cybertrain/test/client.rb', line 68

def self.binary(ints)
  out = +""
  i = 0
  while i < ints.length
    n = ints[i]
    raise ArgumentError, "byte value out of range: #{n}" if n < 0 || n > 255

    out << BYTE_TABLE.byteslice(n, 1)
    i += 1
  end
  out.b
end

.case_message_floor ⇒ Integer

The largest message id when the current test began (read by the reset hook cybertrain/test_help registers): what assert_broadcasts without a block counts from. 0 when the database had no messages table, or none was connected.

Returns:



227
# File 'cybertrain/test/broadcasts.rb', line 227

def self.case_message_floor = Broadcasts.case_floor

.flatten_params(params) ⇒ Hash{String => String}

Nested params: as the bracketed keys a browser’s form sends: { article: { title: "x", tags: { a: "1" } } } gives "article[title]" => "x" and "article[tags][a]" => "1". Keys and values are written with to_s; a value may be a String, Symbol, number, true / false, nil (sent empty, as Rails sends it) or a nested Hash. A key already written with brackets ("article[title]" => "x") is kept as it is. Each value is written as the text the model’s cast reads back to the same value (what a record’s readers answer can be sent as it is, as Rails’ scaffold tests send them): a Date as YYYY-MM-DD, a Time (or ZonedTime) in the storage format, UTC with microseconds (2026-11-11 12:00:00.000000, Cast.sql_datetime), true / false as "true" / "false", a Float by its shortest text.

Examples:

Cybertrain::Test.flatten_params({ article: { title: "New" } })   # => { "article[title]" => "New" }

Parameters:

  • params (Hash)

Returns:

  • (Hash{String => String})

Raises:



40
41
42
43
44
45
46
47
48
# File 'cybertrain/test/integration.rb', line 40

def self.flatten_params(params)
  uploads = no_uploads
  out = flatten_form(params, uploads)
  unless uploads.empty?
    message = "params: a file (fixture_file_upload) is sent by post, patch or put as a form, not in a query string (at #{uploads[0].field})"
    raise ArgumentError, message
  end
  out
end

.in_case? ⇒ Boolean

Whether a test is running, from its first reset to its last cleanup: what a receiver asks before registering its stop.

Returns:

  • (Boolean)


253
254
255
# File 'cybertrain/test.rb', line 253

def self.in_case?
  @in_case
end

.last_message ⇒ String

The message of the case just run: “” when it passed; for a failure outside the body, the step first (in setup: RuntimeError: boom); a failing teardown adds in teardown: ... on a line of its own after the body’s message.

Returns:

  • (String)


350
# File 'cybertrain/test.rb', line 350

def self.last_message = @message

.last_status ⇒ String

The status of the case just run: "ok", "FAIL" or "ERR".

Returns:

  • (String)


342
# File 'cybertrain/test.rb', line 342

def self.last_status = @status

.on_reset(callable) ⇒ nil

Registers a hook run before every test’s setup (step 3 of the order: Mailer.deliveries, the rate-limit counters, I18n.locale), in registration order. cybertrain/test_help registers the framework’s.

Parameters:

  • callable (Proc) —

    a lambda taking no argument

Returns:

  • (nil)


233
234
235
236
# File 'cybertrain/test.rb', line 233

def self.on_reset(callable)
  @resets << callable
  nil
end

.render_component(component, content: "") ⇒ Object

Views.render_component, with the block’s HTML as content:.



26
27
28
# File 'cybertrain/test/views.rb', line 26

def self.render_component(component, content: "")
  Views.render_component(component, content)
end

.render_partial(name, locals = {}) ⇒ Object

Views.render_partial(“articles/article”, article: a).



20
21
22
# File 'cybertrain/test/views.rb', line 20

def self.render_partial(name, locals = {})
  Views.render_partial(name, locals)
end

.run!

This method returns an undefined value.

Runs every registered case in registration order, prints one line per case plus a summary, and exits non-zero when anything failed.

Each case runs as run_top_level_case does: the resets, the file’s setup blocks, the body, its teardown blocks, then travel_back and the receivers’ stop. The lines are ok <name>, FAIL <name>: <message> for a failed assertion, ERR <name>: <Class>: <message> for another exception (ERR <name>: in setup: <Class>: <message> outside the body), then <n> tests, <n> assertions, <n> failures. Call it at the end of every test file. Inside cybertrain test’s program (bundled?) it does nothing: the bundle runs every test once, at its end. The cases of a file the bundle began (begin_file) are the bundle’s, not run!’s.



590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
# File 'cybertrain/test.rb', line 590

def self.run!
  return nil if @bundled

  @cases.each do |c|
    next unless c.top_file.top_file_path.empty?

    run_top_level_case(c)
    @failures += 1 unless @status == "ok"
    puts result_line(c.name)
  end
  run = 0
  @cases.each { |c| run += 1 if c.top_file.top_file_path.empty? }
  puts "#{run} tests, #{@assertions} assertions, #{@failures} failures"
  exit(1) if @failures > 0
end

.run_body(t) { ... } ⇒ nil

Step 5: runs the body and records ok, FAIL (a failed assertion, its message) or ERR (another exception, <Class>: <message>). A StandardError, NotImplementedError, any other ScriptError and SystemStackError are recorded and the run goes on (teardown, the next test, the totals), as Minitest records every exception but NoMemoryError, SignalException (Interrupt) and SystemExit; those three are left to end the program. The second arm is Job::Executor’s (rescue NotImplementedError, SystemStackError, ScriptError): a rescue Exception would catch Interrupt and SystemExit too. Under Spinel a stack overflow is a SIGSEGV of the process, so only a SystemStackError raised by hand reaches the arm there.

Parameters:

Yields:

  • the test method

Returns:

  • (nil)


397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'cybertrain/test.rb', line 397

def self.run_body(t)
  begin
    yield
    @status = "ok"
  rescue AssertionFailed => e
    @status = "FAIL"
    text = e.message
    @message = text
  rescue StandardError => e
    @status = "ERR"
    text = "#{e.class.name}: #{e.message}"
    @message = text
  rescue NotImplementedError, SystemStackError, ScriptError => e
    @status = "ERR"
    text = "#{e.class.name}: #{e.message}"
    @message = text
  end
  nil
end

.select_nodes(selector, html) ⇒ Array<HtmlNode>

The elements of html matching selector.

Parameters:

  • selector (String)
  • html (String)

Returns:

Raises:

  • (AssertionFailed) —

    for an unsupported selector or HTML the reader refuses (with the byte offset and the excerpt)



378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'cybertrain/test/select.rb', line 378

def self.select_nodes(selector, html)
  chains = Selector.parse(selector)
  nodes = Array.new(0) { HtmlNode.new("", 0, -1, 0) }
  problem = ""
  begin
    nodes = HtmlReader.parse(html)
  rescue HtmlReader::Malformed => e
    problem = e.message
  end
  unless problem == ""
    text = "assert_select: the HTML could not be read: #{problem}\n#{html_excerpt(html)}"
    fail_with(text)
  end
  Selector.matching_nodes(nodes, chains)
end

.squished_text(text) ⇒ String

text with runs of whitespace made one space and the ends stripped: what text: is compared with (Rails’ default).

Parameters:

  • text (String)

Returns:

  • (String)


405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'cybertrain/test/select.rb', line 405

def self.squished_text(text)
  s = text.to_s
  out = +""
  n = s.bytesize
  i = 0
  while i < n
    i += 1 while i < n && HtmlReader.html_space?(s.getbyte(i))
    j = i
    j += 1 while j < n && !HtmlReader.html_space?(s.getbyte(j))
    if j > i
      out << " " unless out.empty?
      out << s.byteslice(i, j - i)
    end
    i = j
  end
  out
end