From bcb68a585627a1b7cd2e501b4d8cb9de8d4d767a Mon Sep 17 00:00:00 2001 From: Michael Miller Date: Sun, 14 Oct 2018 19:06:02 -0600 Subject: [PATCH] Implement example lookup by index This will be used later for executing tests in random order. --- src/spectator/example.cr | 5 +++++ src/spectator/example_component.cr | 3 +++ src/spectator/example_group.cr | 19 +++++++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/src/spectator/example.cr b/src/spectator/example.cr index bcb58f8..f3dd39c 100644 --- a/src/spectator/example.cr +++ b/src/spectator/example.cr @@ -34,6 +34,11 @@ module Spectator 1 end + # Retrieve the current example. + def [](index : Int) + 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. diff --git a/src/spectator/example_component.cr b/src/spectator/example_component.cr index fdb24d7..7814960 100644 --- a/src/spectator/example_component.cr +++ b/src/spectator/example_component.cr @@ -10,5 +10,8 @@ module Spectator # The number of examples in this instance. abstract def example_count : Int + + # Lookup the example with the specified index. + abstract def [](index : Int) : Example end end diff --git a/src/spectator/example_group.cr b/src/spectator/example_group.cr index 9c63633..4277fd6 100644 --- a/src/spectator/example_group.cr +++ b/src/spectator/example_group.cr @@ -31,6 +31,25 @@ module Spectator children.sum(&.example_count) end + def [](index : Int) : Example + raise IndexError.new if index < 0 + offset = index + found = children.find do |child| + count = child.example_count + if offset < count + true + else + offset -= count + false + end + end + if found + found[offset] + else + raise IndexError.new + end + end + # TODO: Remove this method. def all_examples Array(Example).new(example_count).tap do |array|