shard-spectator/src/spectator/example.cr

79 lines
2 KiB
Crystal
Raw Normal View History

require "./example_component"
2019-09-12 04:21:06 +00:00
require "./test_wrapper"
2018-08-19 07:15:32 +00:00
module Spectator
# Base class for all types of examples.
2019-09-08 16:38:26 +00:00
# Concrete types must implement the `#run_impl` method.
abstract class Example < ExampleComponent
@finished = false
# Indicates whether the example has already been run.
def finished? : Bool
@finished
end
# Group that the example belongs to.
2018-09-23 18:16:38 +00:00
getter group : ExampleGroup
2018-09-11 03:51:14 +00:00
2019-01-01 23:40:04 +00:00
# Retrieves the internal wrapped instance.
protected getter test_wrapper : TestWrapper
2019-01-01 23:40:04 +00:00
# Source where the example originated from.
2019-09-25 15:12:03 +00:00
def source : Source
2019-09-08 16:38:26 +00:00
@test_wrapper.source
end
def description : String | Symbol?
2019-09-08 16:38:26 +00:00
@test_wrapper.description
end
2019-09-25 15:12:03 +00:00
def symbolic? : Bool
2019-09-12 04:21:06 +00:00
description = @test_wrapper.description
description.starts_with?('#') || description.starts_with?('.')
2019-09-12 04:21:06 +00:00
end
abstract def run_impl
# Runs the example code.
# A result is returned, which represents the outcome of the test.
# An example can be run only once.
# An exception is raised if an attempt is made to run it more than once.
def run : Result
raise "Attempted to run example more than once (#{self})" if finished?
2018-10-20 00:50:21 +00:00
run_impl
ensure
@finished = true
end
# Creates the base of the example.
# The group should be the example group the example belongs to.
2019-09-08 16:38:26 +00:00
def initialize(@group, @test_wrapper)
end
# Indicates there is only one example to run.
def example_count : Int
1
end
# Retrieve the current example.
def [](index : Int) : Example
self
end
# String representation of the example.
# This consists of the groups the example is in and the description.
# The string can be given to end-users to identify the example.
2018-09-24 02:24:28 +00:00
def to_s(io)
@group.to_s(io)
io << ' ' unless symbolic? && @group.symbolic?
2019-09-26 22:49:44 +00:00
io << description
2018-09-24 02:24:28 +00:00
end
# Creates the JSON representation of the example,
# which is just its name.
def to_json(json : ::JSON::Builder)
json.string(to_s)
end
2018-08-19 07:15:32 +00:00
end
end