1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
require 'English'
require 'pathname'
module TestConstruct
module Helpers
extend self
def within_construct(opts = {})
container = setup_construct(opts)
yield(container)
rescue Exception => error
raise unless container
teardown_construct(container, error, opts)
raise error
else
teardown_construct(container, nil, opts)
end
def create_construct(opts = {})
chdir_default = opts.delete(:chdir) { true }
base_path = Pathname(opts.delete(:base_dir) { TestConstruct.tmpdir })
name = opts.delete(:name) { "" }
slug = name.downcase.tr_s("^a-z0-9", "-")[0..63]
if opts.any?
raise "[TestConstruct] Unrecognized options: #{opts.keys}"
end
dir = "#{CONTAINER_PREFIX}-#{$PROCESS_ID}-#{rand(1_000_000_000)}"
dir << "-" << slug unless slug.empty?
path = base_path + dir
path.mkpath
path.extend(PathnameExtensions)
path.construct__chdir_default = chdir_default
path
end
# THIS METHOD MAY HAVE EXTERNAL SIDE-EFFECTS, including:
# - creating the container directory tree
# - changing the current working directory
#
# It is intended to be paired with #teardown_construct
def setup_construct(opts = {})
opts = opts.dup
chdir = opts.fetch(:chdir, true)
opts.delete(:keep_on_error) { false } # not used in setup
container = create_construct(opts)
container.maybe_change_dir(chdir)
container
end
# THIS METHOD MAY HAVE EXTERNAL SIDE-EFFECTS, including:
# - removing the container directory tree
# - changing the current working directory
# - modifying any exception passed as `error`
#
# It is intended to be paired with #setup_construct
def teardown_construct(container, error = nil, opts = {})
if error && opts[:keep_on_error]
container.keep
container.annotate_exception!(error)
end
container.finalize
end
end
extend Helpers
end
|