Skip to content

Add support for experiment after_run blocks #211

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 5, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions lib/scientist/experiment.rb
Original file line number Diff line number Diff line change
@@ -87,6 +87,16 @@ def before_run(&block)
@_scientist_before_run = block
end

# Define a block of code to run after an experiment completes, if the experiment
# is enabled.
#
# The block takes one argument, the Scientist::Result containing experiment results.
#
# Returns the configured block.
def after_run(&block)
@_scientist_after_run = block
end

# A Hash of behavior blocks, keyed by String name. Register behavior blocks
# with the `try` and `use` methods.
def behaviors
@@ -230,6 +240,10 @@ def run(name = nil)

result = generate_result(name)

if @_scientist_after_run
@_scientist_after_run.call(result)
end

begin
publish(result)
rescue StandardError => ex
31 changes: 31 additions & 0 deletions test/scientist/experiment_test.rb
Original file line number Diff line number Diff line change
@@ -635,6 +635,37 @@ def @ex.enabled?
end
end

describe "after run block" do
it "runs when an experiment is enabled" do
control_ok = candidate_ok = false
after_result = nil
@ex.after_run { |result| after_result = result }
@ex.use { control_ok = after_result.nil? }
@ex.try { candidate_ok = after_result.nil? }

@ex.run

assert after_result, "after_run should have run"
assert after_result.matched?, "after_run should be called with the result"
assert control_ok, "control should have run before after_run"
assert candidate_ok, "candidate should have run before after_run"
end

it "does not run when an experiment is disabled" do
after_result = nil

def @ex.enabled?
false
end
@ex.after_run { |result| after_result = result }
@ex.use { "value" }
@ex.try { "value" }
@ex.run

refute after_result, "after_run should not have run"
end
end

describe "testing hooks for extending code" do
it "allows a user to provide fabricated durations for testing purposes" do
@ex.use { true }