Skip to content

Commit e57675e

Browse files
committed
Add test execution timeouts by overriding Minitest::Spec#run
1 parent e5171a5 commit e57675e

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

ext/erbx/test/test_helper.rb

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,48 @@
1-
$LOAD_PATH.unshift File.expand_path('../lib', __dir__)
1+
$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
22

33
require "erbx"
44
require "maxitest/autorun"
5+
require "timeout"
56

67
class Minitest::Spec
8+
TIMEOUT_THRESHOLD = 0.5 # seconds
9+
710
class << self
811
alias_method :test, :it
912
alias_method :xtest, :xit
1013
end
14+
15+
def run
16+
reader, writer = IO.pipe
17+
18+
pid = fork do
19+
reader.close
20+
result = super
21+
writer.write(Marshal.dump(result)) # Serialize result back to parent
22+
writer.close
23+
exit! # Avoid running at_exit hooks
24+
end
25+
26+
writer.close
27+
28+
begin
29+
Timeout.timeout(TIMEOUT_THRESHOLD) do
30+
Process.wait(pid) # Wait for the test to finish
31+
end
32+
33+
result = Marshal.load(reader.read) # Retrieve test result
34+
result
35+
36+
rescue Timeout::Error, Timeout::ExitException
37+
Process.kill("TERM", pid) # Gracefully terminate
38+
39+
sleep 0.5 # Give it time to exit
40+
41+
Process.kill("KILL", pid) rescue nil # Force kill if needed
42+
43+
self.fail "Test exceeded timeout of #{TIMEOUT_THRESHOLD} seconds"
44+
ensure
45+
reader.close
46+
end
47+
end
1148
end

0 commit comments

Comments
 (0)