shard-spectator/src/spectator/example.cr

73 lines
2.3 KiB
Crystal
Raw Normal View History

2020-09-06 16:31:23 +00:00
require "./example_context_delegate"
require "./example_group"
require "./example_node"
2020-11-08 03:56:30 +00:00
require "./harness"
2020-10-17 20:56:31 +00:00
require "./pending_result"
require "./result"
require "./source"
2018-08-19 07:15:32 +00:00
module Spectator
# Standard example that runs a test case.
class Example < ExampleNode
2020-11-08 03:56:30 +00:00
# Currently running example.
class_getter! current : Example
# Indicates whether the example already ran.
getter? finished : Bool = false
# Retrieves the result of the last time the example ran.
2020-10-17 20:56:31 +00:00
getter result : Result = PendingResult.new
# Creates the example.
# The *delegate* contains the test context and method that runs the test case.
# The *name* describes the purpose of the example.
# It can be a `Symbol` to describe a type.
# The *source* tracks where the example exists in source code.
# The example will be assigned to *group* if it is provided.
2020-09-06 16:31:23 +00:00
def initialize(@delegate : ExampleContextDelegate,
2020-09-27 00:14:59 +00:00
name : String? = nil, source : Source? = nil, group : ExampleGroup? = nil)
super(name, source, group)
end
2020-11-07 21:43:59 +00:00
# Creates a dynamic example.
# A block provided to this method will be called as-if it were the test code for the example.
# The block will be given this example instance as an argument.
# The *name* describes the purpose of the example.
# It can be a `Symbol` to describe a type.
# The *source* tracks where the example exists in source code.
# The example will be assigned to *group* if it is provided.
def initialize(name : String? = nil, source : Source? = nil, group : ExampleGroup? = nil, &block : Example -> _)
@delegate = ExampleContextDelegate.null(&block)
end
# Executes the test case.
# Returns the result of the execution.
# The result will also be stored in `#result`.
def run : Result
2020-11-08 03:56:30 +00:00
@@current = self
Log.debug { "Running example #{self}" }
Log.warn { "Example #{self} running more than once" } if @finished
@result = Harness.run { @delegate.call(self) }
ensure
@@current = nil
2020-10-17 20:56:31 +00:00
@finished = true
end
# Exposes information about the example useful for debugging.
def inspect(io)
2020-10-17 17:51:16 +00:00
# Full example name.
io << '"'
to_s(io)
io << '"'
# Add source if it's available.
2020-11-07 22:24:22 +00:00
if (source = self.source)
2020-10-17 17:51:16 +00:00
io << " @ "
2020-11-07 20:47:39 +00:00
io << source
2020-10-17 17:51:16 +00:00
end
2020-10-17 20:56:31 +00:00
io << result
end
2018-08-19 07:15:32 +00:00
end
end