Skip to content

Commit

Permalink
Merge pull request #65 from heroku/schneems/in-directory-safe
Browse files Browse the repository at this point in the history
Safer tests by not mutating current process
  • Loading branch information
schneems authored Sep 11, 2019
2 parents 6b13014 + 8185c21 commit 70e7177
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
26 changes: 26 additions & 0 deletions lib/hatchet/app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,32 @@ def in_directory(directory = self.directory)
end
end

# A safer alternative to in_directory
# this method is used to run code that may mutate the
# current process anything run in this block is executed
# in a different fork
def in_directory_fork(&block)
Tempfile.create("stdout") do |tmp_file|
pid = fork do
$stdout.reopen(tmp_file, "w")
$stderr.reopen(tmp_file, "w")
$stdout.sync = true
$stderr.sync = true
in_directory do |dir|
yield dir
end
Kernel.exit!(0) # needed for https://github.com/seattlerb/minitest/pull/683
end
Process.waitpid(pid)

if $?.success?
puts File.read(tmp_file)
else
raise File.read(tmp_file)
end
end
end

# creates a new app on heroku, "pushes" via anvil or git
# then yields to self so you can call self.run or
# self.deployed?
Expand Down
14 changes: 13 additions & 1 deletion test/hatchet/local_repo_test.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
require 'test_helper'

class AppTest < Minitest::Test
class LocalRepoTest < Minitest::Test
def test_in_directory_fork
env_name = SecureRandom.hex
ENV[env_name] = env_name

Hatchet::App.new("default_ruby").in_directory_fork do
ENV.delete(env_name)
assert_nil ENV[env_name]
end

assert_equal env_name, ENV[env_name]
end

def test_repos_checked_into_git
app = Hatchet::App.new("test/different-folder-for-checked-in-repos/default_ruby")
app.in_directory do
Expand Down

0 comments on commit 70e7177

Please sign in to comment.