repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/window/open_new_window_spec.rb | lib/capybara/spec/session/window/open_new_window_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#open_new_window', requires: [:windows] do
before do
@window = @session.current_window
@session.visit('/with_windows')
end
after do
(@session.windows - [@window]).each do |w|
@session.switch_to_window w
w.close
end
@session.switch_to_window(@window)
end
it 'should open new window with blank url and title' do
window = @session.open_new_window
@session.switch_to_window(window)
expect(@session.title).to satisfy('be a blank title') { |title| ['', 'about:blank'].include? title }
expect(@session.current_url).to eq('about:blank')
end
it 'should open window with changeable content' do
window = @session.open_new_window
@session.within_window window do
@session.visit '/with_html'
expect(@session).to have_css('#first')
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/window/window_spec.rb | lib/capybara/spec/session/window/window_spec.rb | # frozen_string_literal: true
# NOTE: This file uses `sleep` to sync up parts of the tests. This is only implemented like this
# because of the methods being tested. In tests using Capybara this type of behavior should be implemented
# using Capybara provided assertions with builtin waiting behavior.
Capybara::SpecHelper.spec Capybara::Window, requires: [:windows] do
let!(:orig_window) { @session.current_window }
before do
@session.visit('/with_windows')
end
after do
(@session.windows - [orig_window]).each do |w|
@session.switch_to_window w
w.close
end
@session.switch_to_window(orig_window)
end
describe '#exists?' do
it 'should become false after window was closed' do
other_window = @session.window_opened_by do
@session.find(:css, '#openWindow').click
end
expect do
@session.switch_to_window other_window
other_window.close
end.to change(other_window, :exists?).from(true).to(false)
end
end
describe '#closed?' do
it 'should become true after window was closed' do
other_window = @session.window_opened_by do
@session.find(:css, '#openWindow').click
end
expect do
@session.switch_to_window other_window
other_window.close
end.to change { other_window.closed? }.from(false).to(true)
end
end
describe '#current?' do
let(:other_window) do
@session.window_opened_by do
@session.find(:css, '#openWindow').click
end
end
it 'should become true after switching to window' do
expect do
@session.switch_to_window(other_window)
end.to change(other_window, :current?).from(false).to(true)
end
it 'should return false if window is closed' do
@session.switch_to_window(other_window)
other_window.close
expect(other_window.current?).to be(false)
end
end
describe '#close' do
let!(:other_window) do
@session.window_opened_by do
@session.find(:css, '#openWindow').click
end
end
it 'should switch to original window if invoked not for current window' do
expect(@session.windows.size).to eq(2)
expect(@session.current_window).to eq(orig_window)
other_window.close
expect(@session.windows.size).to eq(1)
expect(@session.current_window).to eq(orig_window)
end
it 'should make subsequent invocations of other methods raise no_such_window_error if invoked for current window' do
@session.switch_to_window(other_window)
expect(@session.current_window).to eq(other_window)
other_window.close
expect do
@session.find(:css, '#some_id')
end.to raise_error(@session.driver.no_such_window_error)
@session.switch_to_window(orig_window)
end
end
describe '#size' do
def win_size
@session.evaluate_script('[window.outerWidth || window.innerWidth, window.outerHeight || window.innerHeight]')
end
it 'should return size of whole window', requires: %i[windows js] do
expect(@session.current_window.size).to eq win_size
end
it 'should switch to original window if invoked not for current window' do
other_window = @session.window_opened_by do
@session.find(:css, '#openWindow').click
end
sleep 1
size = @session.within_window(other_window) do
win_size
end
expect(other_window.size).to eq(size)
expect(@session.current_window).to eq(orig_window)
end
end
describe '#resize_to' do
let!(:initial_size) { @session.current_window.size }
after do
@session.current_window.resize_to(*initial_size)
sleep 1
end
it 'should be able to resize window', requires: %i[windows js] do
width, height = initial_size
@session.current_window.resize_to(width - 100, height - 100)
sleep 1
expect(@session.current_window.size).to eq([width - 100, height - 100])
end
it 'should stay on current window if invoked not for current window', requires: %i[windows js] do
other_window = @session.window_opened_by do
@session.find(:css, '#openWindow').click
end
other_window.resize_to(600, 400)
expect(@session.current_window).to eq(orig_window)
@session.within_window(other_window) do
expect(@session.current_window.size).to eq([600, 400])
end
end
end
describe '#maximize' do
let! :initial_size do
@session.current_window.size
end
after do
@session.current_window.resize_to(*initial_size)
sleep 0.5
end
it 'should be able to maximize window', requires: %i[windows js] do
start_width, start_height = 400, 300
@session.current_window.resize_to(start_width, start_height)
sleep 0.5
@session.current_window.maximize
sleep 0.5 # The timing on maximize is finicky on Travis -- wait a bit for maximize to occur
max_width, max_height = @session.current_window.size
# maximize behavior is window manage dependant, so just make sure it increases in size
expect(max_width).to be > start_width
expect(max_height).to be > start_height
end
it 'should stay on current window if invoked not for current window', requires: %i[windows js] do
other_window = @session.window_opened_by do
@session.find(:css, '#openWindow').click
end
other_window.resize_to(400, 300)
sleep 0.5
other_window.maximize
sleep 0.5 # The timing on maximize is finicky on Travis -- wait a bit for maximize to occur
expect(@session.current_window).to eq(orig_window)
# Maximizing the browser affects all tabs so this may not be valid in real browsers
# expect(@session.current_window.size).to eq(initial_size)
ow_width, ow_height = other_window.size
expect(ow_width).to be > 400
expect(ow_height).to be > 300
end
end
describe '#fullscreen' do
let! :initial_size do
@session.current_window.size
end
after do
@session.current_window.resize_to(*initial_size)
sleep 1
end
it 'should be able to fullscreen the window' do
expect do
@session.current_window.fullscreen
end.not_to raise_error
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/element/assert_match_selector_spec.rb | lib/capybara/spec/session/element/assert_match_selector_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#assert_matches_selector' do
before do
@session.visit('/with_html')
@element = @session.find(:css, 'span', text: '42')
end
it 'should be true if the given selector matches the element' do
expect(@element.assert_matches_selector(:css, '.number')).to be true
end
it 'should be false if the given selector does not match the element' do
expect { @element.assert_matches_selector(:css, '.not_number') }.to raise_error(Capybara::ElementNotFound)
end
it 'should not be callable on the session' do
expect { @session.assert_matches_selector(:css, '.number') }.to raise_error(NoMethodError)
end
it 'should wait for match to occur', requires: [:js] do
@session.visit('/with_js')
input = @session.find(:css, '#disable-on-click')
expect(input.assert_matches_selector(:css, 'input:enabled')).to be true
input.click
expect(input.assert_matches_selector(:css, 'input:disabled')).to be true
end
it 'should not accept count options' do
expect { @element.assert_matches_selector(:css, '.number', count: 1) }.to raise_error(ArgumentError, /count/)
end
it 'should accept a filter block' do
@element.assert_matches_selector(:css, 'span') { |el| el[:class] == 'number' }
@element.assert_not_matches_selector(:css, 'span') { |el| el[:class] == 'not_number' }
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/element/match_css_spec.rb | lib/capybara/spec/session/element/match_css_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#match_css?' do
before do
@session.visit('/with_html')
@element = @session.find(:css, 'span', text: '42')
end
it 'should be true if the given selector matches the element' do
expect(@element).to match_css('span')
expect(@element).to match_css('span.number')
end
it 'should be false if the given selector does not match' do
expect(@element).not_to match_css('div')
expect(@element).not_to match_css('p a#doesnotexist')
expect(@element).not_to match_css('p.nosuchclass')
end
it 'should accept an optional filter block' do
# This would be better done with
expect(@element).to match_css('span') { |el| el[:class] == 'number' }
expect(@element).not_to match_css('span') { |el| el[:class] == 'not_number' }
end
it 'should work with root element found via ancestor' do
el = @session.find(:css, 'body').find(:xpath, '..')
expect(el).to match_css('html')
expect { expect(el).to not_match_css('html') }.to raise_exception(RSpec::Expectations::ExpectationNotMetError)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/element/matches_selector_spec.rb | lib/capybara/spec/session/element/matches_selector_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#match_selector?' do
let(:element) { @session.find(:xpath, '//span', text: '42') }
before do
@session.visit('/with_html')
end
it 'should be true if the element matches the given selector' do
expect(element).to match_selector(:xpath, '//span')
expect(element).to match_selector(:css, 'span.number')
expect(element.matches_selector?(:css, 'span.number')).to be true
end
it 'should be false if the element does not match the given selector' do
expect(element).not_to match_selector(:xpath, '//div')
expect(element).not_to match_selector(:css, 'span.not_a_number')
expect(element.matches_selector?(:css, 'span.not_a_number')).to be false
end
it 'should use default selector' do
Capybara.default_selector = :css
expect(element).not_to match_selector('span.not_a_number')
expect(element).to match_selector('span.number')
end
it 'should work with elements located via a sibling selector' do
sibling = element.sibling(:css, 'span', text: 'Other span')
expect(sibling).to match_selector(:xpath, '//span')
expect(sibling).to match_selector(:css, 'span')
end
it 'should work with the html element' do
html = @session.find('/html')
expect(html).to match_selector(:css, 'html')
end
context 'with text' do
it 'should discard all matches where the given string is not contained' do
expect(element).to match_selector('//span', text: '42')
expect(element).not_to match_selector('//span', text: 'Doesnotexist')
end
end
it 'should have css sugar' do
expect(element.matches_css?('span.number')).to be true
expect(element.matches_css?('span.not_a_number')).to be false
expect(element.matches_css?('span.number', text: '42')).to be true
expect(element.matches_css?('span.number', text: 'Nope')).to be false
end
it 'should have xpath sugar' do
expect(element.matches_xpath?('//span')).to be true
expect(element.matches_xpath?('//div')).to be false
expect(element.matches_xpath?('//span', text: '42')).to be true
expect(element.matches_xpath?('//span', text: 'Nope')).to be false
end
it 'should accept selector filters' do
@session.visit('/form')
cbox = @session.find(:css, '#form_pets_dog')
expect(cbox.matches_selector?(:checkbox, id: 'form_pets_dog', option: 'dog', name: 'form[pets][]', checked: true)).to be true
end
it 'should accept a custom filter block' do
@session.visit('/form')
cbox = @session.find(:css, '#form_pets_dog')
expect(cbox).to match_selector(:checkbox) { |node| node[:id] == 'form_pets_dog' }
expect(cbox).not_to match_selector(:checkbox) { |node| node[:id] != 'form_pets_dog' }
expect(cbox.matches_selector?(:checkbox) { |node| node[:id] == 'form_pets_dog' }).to be true
expect(cbox.matches_selector?(:checkbox) { |node| node[:id] != 'form_pets_dog' }).to be false
end
end
Capybara::SpecHelper.spec '#not_matches_selector?' do
let(:element) { @session.find(:css, 'span', text: 42) }
before do
@session.visit('/with_html')
end
it 'should be false if the given selector matches the element' do
expect(element).not_to not_match_selector(:xpath, '//span')
expect(element).not_to not_match_selector(:css, 'span.number')
expect(element.not_matches_selector?(:css, 'span.number')).to be false
end
it 'should be true if the given selector does not match the element' do
expect(element).to not_match_selector(:xpath, '//abbr')
expect(element).to not_match_selector(:css, 'p a#doesnotexist')
expect(element.not_matches_selector?(:css, 'p a#doesnotexist')).to be true
end
it 'should use default selector' do
Capybara.default_selector = :css
expect(element).to not_match_selector('p a#doesnotexist')
expect(element).not_to not_match_selector('span.number')
end
context 'with text' do
it 'should discard all matches where the given string is contained' do
expect(element).not_to not_match_selector(:css, 'span.number', text: '42')
expect(element).to not_match_selector(:css, 'span.number', text: 'Doesnotexist')
end
end
it 'should have CSS sugar' do
expect(element.not_matches_css?('span.number')).to be false
expect(element.not_matches_css?('p a#doesnotexist')).to be true
expect(element.not_matches_css?('span.number', text: '42')).to be false
expect(element.not_matches_css?('span.number', text: 'Doesnotexist')).to be true
end
it 'should have xpath sugar' do
expect(element.not_matches_xpath?('//span')).to be false
expect(element.not_matches_xpath?('//div')).to be true
expect(element.not_matches_xpath?('//span', text: '42')).to be false
expect(element.not_matches_xpath?('//span', text: 'Doesnotexist')).to be true
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/element/match_xpath_spec.rb | lib/capybara/spec/session/element/match_xpath_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#match_xpath?' do
before do
@session.visit('/with_html')
@element = @session.find(:css, 'span.number')
end
it 'should be true if the given selector is on the page' do
expect(@element).to match_xpath('//span')
expect(@element).to match_xpath("//span[@class='number']")
end
it 'should be false if the given selector is not on the page' do
expect(@element).not_to match_xpath('//abbr')
expect(@element).not_to match_xpath('//div')
expect(@element).not_to match_xpath("//span[@class='not_a_number']")
end
it 'should use xpath even if default selector is CSS' do
Capybara.default_selector = :css
expect(@element).not_to have_xpath("//span[@class='not_a_number']")
expect(@element).not_to have_xpath("//div[@class='number']")
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/frame/within_frame_spec.rb | lib/capybara/spec/session/frame/within_frame_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#within_frame', requires: [:frames] do
before do
@session.visit('/within_frames')
end
it 'should find the div in frameOne' do
@session.within_frame('frameOne') do
expect(@session.find("//*[@id='divInFrameOne']").text).to eql 'This is the text of divInFrameOne'
end
end
it 'should find the div in FrameTwo' do
@session.within_frame('frameTwo') do
expect(@session.find("//*[@id='divInFrameTwo']").text).to eql 'This is the text of divInFrameTwo'
end
end
it 'should find the text div in the main window after finding text in frameOne' do
@session.within_frame('frameOne') do
expect(@session.find("//*[@id='divInFrameOne']").text).to eql 'This is the text of divInFrameOne'
end
expect(@session.find("//*[@id='divInMainWindow']").text).to eql 'This is the text for divInMainWindow'
end
it 'should find the text div in the main window after finding text in frameTwo' do
@session.within_frame('frameTwo') do
expect(@session.find("//*[@id='divInFrameTwo']").text).to eql 'This is the text of divInFrameTwo'
end
expect(@session.find("//*[@id='divInMainWindow']").text).to eql 'This is the text for divInMainWindow'
end
it 'should return the result of executing the block' do
expect(@session.within_frame('frameOne') { 'return value' }).to eql 'return value'
end
it 'should find the div given Element' do
element = @session.find(:id, 'frameOne')
@session.within_frame element do
expect(@session.find("//*[@id='divInFrameOne']").text).to eql 'This is the text of divInFrameOne'
end
end
it 'should find the div given selector and locator' do
@session.within_frame(:css, '#frameOne') do
expect(@session.find("//*[@id='divInFrameOne']").text).to eql 'This is the text of divInFrameOne'
end
end
it 'should default to the :frame selector kind when only options passed' do
@session.within_frame(name: 'my frame one') do
expect(@session.find("//*[@id='divInFrameOne']").text).to eql 'This is the text of divInFrameOne'
end
end
it 'should default to the :frame selector when no options passed' do
container = @session.find(:css, '#divInMainWindow')
@session.within(container) do
# Ensure only one frame in scope
@session.within_frame do
expect(@session).to have_css('body#parentBody')
end
end
expect do
# Multiple frames in scope here
# rubocop:disable Style/Semicolon
@session.within_frame { ; }
# rubocop:enable Style/Semicolon
end.to raise_error Capybara::Ambiguous
end
it 'should find multiple nested frames' do
@session.within_frame 'parentFrame' do
@session.within_frame 'childFrame' do
@session.within_frame 'grandchildFrame1' do
# dummy
end
@session.within_frame 'grandchildFrame2' do
# dummy
end
end
end
end
it 'should reset scope when changing frames' do
@session.within(:css, '#divInMainWindow') do
@session.within_frame 'innerParentFrame' do
expect(@session.has_selector?(:css, 'iframe#childFrame')).to be true
end
end
end
it 'works if the frame is closed', requires: %i[frames js] do
@session.within_frame 'parentFrame' do
@session.within_frame 'childFrame' do
@session.click_link 'Close Window Now'
end
expect(@session).to have_selector(:css, 'body#parentBody')
expect(@session).not_to have_selector(:css, '#childFrame')
end
end
it 'works if the frame is closed with a slight delay', requires: %i[frames js] do
@session.within_frame 'parentFrame' do
@session.within_frame 'childFrame' do
@session.click_link 'Close Window Soon'
sleep 1
end
expect(@session).to have_selector(:css, 'body#parentBody')
expect(@session).not_to have_selector(:css, '#childFrame')
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/frame/frame_url_spec.rb | lib/capybara/spec/session/frame/frame_url_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#frame_url', requires: [:frames] do
before do
@session.visit('/within_frames')
end
it 'should return the url in a frame' do
@session.within_frame('frameOne') do
expect(@session.driver.frame_url).to end_with '/frame_one'
end
end
it 'should return the url in FrameTwo' do
@session.within_frame('frameTwo') do
expect(@session.driver.frame_url).to end_with '/frame_two'
end
end
it 'should return the url in the main frame' do
expect(@session.driver.frame_url).to end_with('/within_frames')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/frame/frame_title_spec.rb | lib/capybara/spec/session/frame/frame_title_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#frame_title', requires: [:frames] do
before do
@session.visit('/within_frames')
end
it 'should return the title in a frame' do
@session.within_frame('frameOne') do
expect(@session.driver.frame_title).to eq 'This is the title of frame one'
end
end
it 'should return the title in FrameTwo' do
@session.within_frame('frameTwo') do
expect(@session.driver.frame_title).to eq 'This is the title of frame two'
end
end
it 'should return the title in the main frame' do
expect(@session.driver.frame_title).to eq 'With Frames'
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/frame/switch_to_frame_spec.rb | lib/capybara/spec/session/frame/switch_to_frame_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#switch_to_frame', requires: [:frames] do
before do
@session.visit('/within_frames')
end
after do
# Ensure we clean up after the frame changes
@session.switch_to_frame(:top)
end
it 'should find the div in frameOne' do
frame = @session.find(:frame, 'frameOne')
@session.switch_to_frame(frame)
expect(@session.find("//*[@id='divInFrameOne']").text).to eql 'This is the text of divInFrameOne'
end
it 'should find the div in FrameTwo' do
frame = @session.find(:frame, 'frameTwo')
@session.switch_to_frame(frame)
expect(@session.find("//*[@id='divInFrameTwo']").text).to eql 'This is the text of divInFrameTwo'
end
it 'should return to the parent frame when told to' do
frame = @session.find(:frame, 'frameOne')
@session.switch_to_frame(frame)
@session.switch_to_frame(:parent)
expect(@session.find("//*[@id='divInMainWindow']").text).to eql 'This is the text for divInMainWindow'
end
it 'should be able to switch to nested frames' do
frame = @session.find(:frame, 'parentFrame')
@session.switch_to_frame frame
frame = @session.find(:frame, 'childFrame')
@session.switch_to_frame frame
frame = @session.find(:frame, 'grandchildFrame1')
@session.switch_to_frame frame
expect(@session).to have_selector(:css, '#divInFrameOne', text: 'This is the text of divInFrameOne')
end
it 'should reset scope when changing frames' do
frame = @session.find(:frame, 'parentFrame')
@session.within(:css, '#divInMainWindow') do
@session.switch_to_frame(frame)
expect(@session.has_selector?(:css, 'iframe#childFrame')).to be true
@session.switch_to_frame(:parent)
end
end
it 'works if the frame is closed', requires: %i[frames js] do
frame = @session.find(:frame, 'parentFrame')
@session.switch_to_frame frame
frame = @session.find(:frame, 'childFrame')
@session.switch_to_frame frame
@session.click_link 'Close Window Now'
@session.switch_to_frame :parent # Go back to parentFrame
expect(@session).to have_selector(:css, 'body#parentBody')
expect(@session).not_to have_selector(:css, '#childFrame')
@session.switch_to_frame :parent # Go back to top
end
it 'works if the frame is closed with a slight delay', requires: %i[frames js] do
frame = @session.find(:frame, 'parentFrame')
@session.switch_to_frame frame
frame = @session.find(:frame, 'childFrame')
@session.switch_to_frame frame
@session.click_link 'Close Window Soon'
sleep 1
@session.switch_to_frame :parent # Go back to parentFrame
expect(@session).to have_selector(:css, 'body#parentBody')
expect(@session).not_to have_selector(:css, '#childFrame')
@session.switch_to_frame :parent # Go back to top
end
it 'can return to the top frame', requires: [:frames] do
frame = @session.find(:frame, 'parentFrame')
@session.switch_to_frame frame
frame = @session.find(:frame, 'childFrame')
@session.switch_to_frame frame
@session.switch_to_frame :top
expect(@session.find("//*[@id='divInMainWindow']").text).to eql 'This is the text for divInMainWindow'
end
it "should raise error if switching to parent unmatched inside `within` as it's nonsense" do
expect do
frame = @session.find(:frame, 'parentFrame')
@session.switch_to_frame(frame)
@session.within(:css, '#parentBody') do
@session.switch_to_frame(:parent)
end
end.to raise_error(Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's `within` block.")
end
it "should raise error if switching to top inside a `within` in a frame as it's nonsense" do
frame = @session.find(:frame, 'parentFrame')
@session.switch_to_frame(frame)
@session.within(:css, '#parentBody') do
expect do
@session.switch_to_frame(:top)
end.to raise_error(Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's `within` block.")
end
end
it "should raise error if switching to top inside a nested `within` in a frame as it's nonsense" do
frame = @session.find(:frame, 'parentFrame')
@session.switch_to_frame(frame)
@session.within(:css, '#parentBody') do
@session.switch_to_frame(@session.find(:frame, 'childFrame'))
expect do
@session.switch_to_frame(:top)
end.to raise_error(Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's `within` block.")
@session.switch_to_frame(:parent)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/server/animation_disabler.rb | lib/capybara/server/animation_disabler.rb | # frozen_string_literal: true
module Capybara
class Server
class AnimationDisabler
def self.selector_for(css_or_bool)
case css_or_bool
when String
css_or_bool
when true
'*'
else
raise CapybaraError, 'Capybara.disable_animation supports either a String (the css selector to disable) or a boolean'
end
end
def initialize(app)
@app = app
@disable_css_markup = format(DISABLE_CSS_MARKUP_TEMPLATE,
selector: self.class.selector_for(Capybara.disable_animation))
@disable_js_markup = +DISABLE_JS_MARKUP_TEMPLATE
end
def call(env)
status, headers, body = @app.call(env)
return [status, headers, body] unless html_content?(headers)
nonces = directive_nonces(headers).transform_values { |nonce| "nonce=\"#{nonce}\"" if nonce && !nonce.empty? }
response = Rack::Response.new([], status, headers)
body.each { |html| response.write insert_disable(html, nonces) }
body.close if body.respond_to?(:close)
response.finish
end
private
attr_reader :disable_css_markup, :disable_js_markup
def html_content?(headers)
/html/.match?(headers['Content-Type']) # rubocop:todo Performance/StringInclude
end
def insert_disable(html, nonces)
html.sub(%r{(</head>)}, "<style #{nonces['style-src']}>#{disable_css_markup}</style>\\1")
.sub(%r{(</body>)}, "<script #{nonces['script-src']}>#{disable_js_markup}</script>\\1")
end
def directive_nonces(headers)
headers.fetch('Content-Security-Policy', '')
.split(';')
.map(&:split)
.to_h do |s|
[
s[0], s[1..].filter_map do |value|
/^'nonce-(?<nonce>.+)'/ =~ value
nonce
end[0]
]
end
end
DISABLE_CSS_MARKUP_TEMPLATE = <<~CSS
%<selector>s, %<selector>s::before, %<selector>s::after {
transition: none !important;
animation-duration: 0s !important;
animation-delay: 0s !important;
scroll-behavior: auto !important;
}
CSS
DISABLE_JS_MARKUP_TEMPLATE = <<~SCRIPT
//<![CDATA[
(typeof jQuery !== 'undefined') && (jQuery.fx.off = true);
//]]>
SCRIPT
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/server/middleware.rb | lib/capybara/server/middleware.rb | # frozen_string_literal: true
module Capybara
class Server
class Middleware
class Counter
def initialize
@value = []
@mutex = Mutex.new
end
def increment(uri)
@mutex.synchronize { @value.push(uri) }
end
def decrement(uri)
@mutex.synchronize { @value.delete_at(@value.index(uri) || - 1) }
end
def positive?
@mutex.synchronize { @value.length.positive? }
end
def value
@mutex.synchronize { @value.dup }
end
end
attr_reader :error
def initialize(app, server_errors, extra_middleware = [])
@app = app
@extended_app = extra_middleware.inject(@app) do |ex_app, klass|
klass.new(ex_app)
end
@counter = Counter.new
@server_errors = server_errors
end
def pending_requests
@counter.value
end
def pending_requests?
@counter.positive?
end
def clear_error
@error = nil
end
def call(env)
if env['PATH_INFO'] == '/__identify__'
[200, {}, [@app.object_id.to_s]]
else
request_uri = env['REQUEST_URI']
@counter.increment(request_uri)
begin
@extended_app.call(env)
rescue *@server_errors => e
@error ||= e
raise e
ensure
@counter.decrement(request_uri)
end
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/server/checker.rb | lib/capybara/server/checker.rb | # frozen_string_literal: true
module Capybara
class Server
class Checker
TRY_HTTPS_ERRORS = [EOFError, Net::ReadTimeout, Errno::ECONNRESET].freeze
def initialize(host, port)
@host, @port = host, port
@ssl = false
end
def request(&block)
ssl? ? https_request(&block) : http_request(&block)
rescue *TRY_HTTPS_ERRORS
res = https_request(&block)
@ssl = true
res
end
def ssl?
@ssl
end
private
def http_request(&block)
make_request(read_timeout: 2, &block)
end
def https_request(&block)
make_request(**ssl_options, &block)
end
def make_request(**options, &block)
Net::HTTP.start(@host, @port, options.merge(max_retries: 0), &block)
end
def ssl_options
{ use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_NONE }
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/driver/node.rb | lib/capybara/driver/node.rb | # frozen_string_literal: true
module Capybara
module Driver
class Node
attr_reader :driver, :native, :initial_cache
def initialize(driver, native, initial_cache = {})
@driver = driver
@native = native
@initial_cache = initial_cache
end
def all_text
raise NotImplementedError
end
def visible_text
raise NotImplementedError
end
def [](name)
raise NotImplementedError
end
def value
raise NotImplementedError
end
def style(styles)
raise NotImplementedError
end
# @param value [String, Array] Array is only allowed if node has 'multiple' attribute
# @param options [Hash] Driver specific options for how to set a value on a node
def set(value, **options)
raise NotImplementedError
end
def select_option
raise NotImplementedError
end
def unselect_option
raise NotImplementedError
end
def click(keys = [], **options)
raise NotImplementedError
end
def right_click(keys = [], **options)
raise NotImplementedError
end
def double_click(keys = [], **options)
raise NotImplementedError
end
def send_keys(*args)
raise NotImplementedError
end
def hover
raise NotImplementedError
end
def drag_to(element, **options)
raise NotImplementedError
end
def drop(*args)
raise NotImplementedError
end
def scroll_by(x, y)
raise NotImplementedError
end
def scroll_to(element, alignment, position = nil)
raise NotImplementedError
end
def tag_name
raise NotImplementedError
end
def visible?
raise NotImplementedError
end
def obscured?
raise NotImplementedError
end
def checked?
raise NotImplementedError
end
def selected?
raise NotImplementedError
end
def disabled?
raise NotImplementedError
end
def readonly?
!!self[:readonly]
end
def multiple?
!!self[:multiple]
end
def rect
raise NotSupportedByDriverError, 'Capybara::Driver::Node#rect'
end
def path
raise NotSupportedByDriverError, 'Capybara::Driver::Node#path'
end
def trigger(event)
raise NotSupportedByDriverError, 'Capybara::Driver::Node#trigger'
end
def shadow_root
raise NotSupportedByDriverError, 'Capybara::Driver::Node#shadow_root'
end
def inspect
%(#<#{self.class} tag="#{tag_name}" path="#{path}">)
rescue NotSupportedByDriverError
%(#<#{self.class} tag="#{tag_name}">)
end
def ==(other)
eql?(other) || (other.respond_to?(:native) && native == other.native)
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/driver/base.rb | lib/capybara/driver/base.rb | # frozen_string_literal: true
class Capybara::Driver::Base
attr_writer :session
def current_url
raise NotImplementedError
end
def visit(path)
raise NotImplementedError
end
def refresh
raise NotImplementedError
end
def find_xpath(query, **options)
raise NotImplementedError
end
def find_css(query, **options)
raise NotImplementedError
end
def html
raise NotImplementedError
end
def go_back
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#go_back'
end
def go_forward
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#go_forward'
end
def execute_script(script, *args)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#execute_script'
end
def evaluate_script(script, *args)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#evaluate_script'
end
def evaluate_async_script(script, *args)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#evaluate_script_asnyc'
end
def save_screenshot(path, **options)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#save_screenshot'
end
def response_headers
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#response_headers'
end
def status_code
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#status_code'
end
def send_keys(*)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#send_keys'
end
def active_element
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#active_element'
end
##
#
# @param frame [Capybara::Node::Element, :parent, :top] The iframe element to switch to
#
def switch_to_frame(frame)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#switch_to_frame'
end
def frame_title
find_xpath('/html/head/title').map(&:all_text).first.to_s
end
def frame_url
evaluate_script('document.location.href')
rescue Capybara::NotSupportedByDriverError
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#frame_title'
end
def current_window_handle
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#current_window_handle'
end
def window_size(handle)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#window_size'
end
def resize_window_to(handle, width, height)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#resize_window_to'
end
def maximize_window(handle)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#maximize_window'
end
def fullscreen_window(handle)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#fullscreen_window'
end
def close_window(handle)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#close_window'
end
def window_handles
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#window_handles'
end
def open_new_window
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#open_new_window'
end
def switch_to_window(handle)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#switch_to_window'
end
def no_such_window_error
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#no_such_window_error'
end
##
#
# Execute the block, and then accept the modal opened.
# @param type [:alert, :confirm, :prompt]
# @option options [Numeric] :wait How long to wait for the modal to appear after executing the block.
# @option options [String, Regexp] :text Text to verify is in the message shown in the modal
# @option options [String] :with Text to fill in in the case of a prompt
# @return [String] the message shown in the modal
# @raise [Capybara::ModalNotFound] if modal dialog hasn't been found
#
def accept_modal(type, **options, &blk)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#accept_modal'
end
##
#
# Execute the block, and then dismiss the modal opened.
# @param type [:alert, :confirm, :prompt]
# @option options [Numeric] :wait How long to wait for the modal to appear after executing the block.
# @option options [String, Regexp] :text Text to verify is in the message shown in the modal
# @return [String] the message shown in the modal
# @raise [Capybara::ModalNotFound] if modal dialog hasn't been found
#
def dismiss_modal(type, **options, &blk)
raise Capybara::NotSupportedByDriverError, 'Capybara::Driver::Base#dismiss_modal'
end
def invalid_element_errors
[]
end
def wait?
false
end
def reset!; end
def needs_server?
false
end
def session_options
session&.config || Capybara.session_options
end
private
def session
@session ||= nil
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rack_test/errors.rb | lib/capybara/rack_test/errors.rb | # frozen_string_literal: true
module Capybara::RackTest::Errors
class StaleElementReferenceError < StandardError
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rack_test/driver.rb | lib/capybara/rack_test/driver.rb | # frozen_string_literal: true
require 'rack/test'
require 'rack/utils'
require 'mini_mime'
require 'nokogiri'
class Capybara::RackTest::Driver < Capybara::Driver::Base
DEFAULT_OPTIONS = {
respect_data_method: false,
follow_redirects: true,
redirect_limit: 5
}.freeze
attr_reader :app, :options
def initialize(app, **options)
raise ArgumentError, 'rack-test requires a rack application, but none was given' unless app
super()
@app = app
@options = DEFAULT_OPTIONS.merge(options)
end
def browser
@browser ||= Capybara::RackTest::Browser.new(self)
end
def follow_redirects?
@options[:follow_redirects]
end
def redirect_limit
@options[:redirect_limit]
end
def response
browser.last_response
end
def request
browser.last_request
end
def visit(path, **attributes)
browser.visit(path, **attributes)
end
def refresh
browser.refresh
end
def submit(method, path, attributes)
browser.submit(method, path, attributes)
end
def follow(method, path, **attributes)
browser.follow(method, path, attributes)
end
def current_url
browser.current_url
end
def response_headers
response.headers
end
def status_code
response.status
end
def find_xpath(selector)
browser.find(:xpath, selector)
end
def find_css(selector)
browser.find(:css, selector)
rescue Nokogiri::CSS::SyntaxError
raise unless selector.include?(' i]')
raise ArgumentError, "This driver doesn't support case insensitive attribute matching when using CSS base selectors"
end
def html
browser.html
end
def dom
browser.dom
end
def title
browser.title
end
def reset!
@browser = nil
end
def get(...); browser.get(...); end
def post(...); browser.post(...); end
def put(...); browser.put(...); end
def delete(...); browser.delete(...); end
def header(key, value); browser.header(key, value); end
def invalid_element_errors
[Capybara::RackTest::Errors::StaleElementReferenceError]
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rack_test/browser.rb | lib/capybara/rack_test/browser.rb | # frozen_string_literal: true
class Capybara::RackTest::Browser
include ::Rack::Test::Methods
attr_reader :driver
attr_accessor :current_host
def initialize(driver)
@driver = driver
@current_fragment = nil
end
def app
driver.app
end
def options
driver.options
end
def visit(path, **attributes)
@new_visit_request = true
reset_cache!
reset_host!
process_and_follow_redirects(:get, path, attributes)
end
def refresh
reset_cache!
request(last_request.fullpath, last_request.env)
end
def submit(method, path, attributes, content_type: nil)
path = request_path if path.nil? || path.empty?
uri = build_uri(path)
uri.query = '' if method.to_s.casecmp('get').zero?
env = { 'HTTP_REFERER' => referer_url }
env['CONTENT_TYPE'] = content_type if content_type
process_and_follow_redirects(
method,
uri.to_s,
attributes,
env
)
end
def follow(method, path, **attributes)
return if fragment_or_script?(path)
process_and_follow_redirects(method, path, attributes, 'HTTP_REFERER' => referer_url)
end
def process_and_follow_redirects(method, path, attributes = {}, env = {})
@current_fragment = build_uri(path).fragment
process(method, path, attributes, env)
return unless driver.follow_redirects?
driver.redirect_limit.times do
if last_response.redirect?
if [307, 308].include? last_response.status
process(last_request.request_method, last_response['Location'], last_request.params, env)
else
process(:get, last_response['Location'], {}, env)
end
end
end
if last_response.redirect? # rubocop:disable Style/GuardClause
raise Capybara::InfiniteRedirectError, "redirected more than #{driver.redirect_limit} times, check for infinite redirects."
end
end
def process(method, path, attributes = {}, env = {})
method = method.downcase
new_uri = build_uri(path)
@current_scheme, @current_host, @current_port = new_uri.select(:scheme, :host, :port)
@current_fragment = new_uri.fragment || @current_fragment
reset_cache!
@new_visit_request = false
send(method, new_uri.to_s, attributes, env.merge(options[:headers] || {}))
end
def build_uri(path)
uri = URI.parse(path)
base_uri = base_relative_uri_for(uri)
uri.path = base_uri.path + uri.path unless uri.absolute? || uri.path.start_with?('/')
if base_uri.absolute?
base_uri.merge(uri)
else
uri.scheme ||= @current_scheme
uri.host ||= @current_host
uri.port ||= @current_port unless uri.default_port == @current_port
uri
end
end
def current_url
uri = build_uri(last_request.url)
uri.fragment = @current_fragment if @current_fragment
uri.to_s
rescue Rack::Test::Error
''
end
def reset_host!
uri = URI.parse(driver.session_options.app_host || driver.session_options.default_host)
@current_scheme, @current_host, @current_port = uri.select(:scheme, :host, :port)
end
def reset_cache!
@dom = nil
end
def dom
@dom ||= Capybara::HTML(html)
end
def find(format, selector)
if format == :css
dom.css(selector, Capybara::RackTest::CSSHandlers.new)
else
dom.xpath(selector)
end.map { |node| Capybara::RackTest::Node.new(self, node) }
end
def html
last_response.body
rescue Rack::Test::Error
''
end
def title
dom.title
end
def last_request
raise Rack::Test::Error if @new_visit_request
super
end
def last_response
raise Rack::Test::Error if @new_visit_request
super
end
protected
def base_href
find(:css, 'head > base').first&.[](:href).to_s
end
def base_relative_uri_for(uri)
base_uri = URI.parse(base_href)
current_uri = URI.parse(safe_last_request&.url.to_s).tap do |c|
c.path.sub!(%r{/[^/]*$}, '/') unless uri.path.empty?
c.path = '/' if c.path.empty?
end
if [current_uri, base_uri].any?(&:absolute?)
current_uri.merge(base_uri)
else
base_uri.path = current_uri.path if base_uri.path.empty?
base_uri
end
end
def build_rack_mock_session
reset_host! unless current_host
Rack::MockSession.new(app, current_host)
end
def request_path
last_request.path
rescue Rack::Test::Error
'/'
end
def safe_last_request
last_request
rescue Rack::Test::Error
nil
end
private
def fragment_or_script?(path)
path.gsub(/^#{Regexp.escape(request_path)}/, '').start_with?('#') || path.downcase.start_with?('javascript:')
end
def referer_url
build_uri(last_request.url).to_s
rescue Rack::Test::Error
''
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rack_test/form.rb | lib/capybara/rack_test/form.rb | # frozen_string_literal: true
class Capybara::RackTest::Form < Capybara::RackTest::Node
# This only needs to inherit from Rack::Test::UploadedFile because Rack::Test checks for
# the class specifically when determining whether to construct the request as multipart.
# That check should be based solely on the form element's 'enctype' attribute value,
# which should probably be provided to Rack::Test in its non-GET request methods.
class NilUploadedFile < Rack::Test::UploadedFile
def initialize # rubocop:disable Lint/MissingSuper
@empty_file = Tempfile.new('nil_uploaded_file')
@empty_file.close
end
def original_filename; ''; end
def content_type; 'application/octet-stream'; end
def path; @empty_file.path; end
def size; 0; end
def read; ''; end
def append_to(_); end
def set_encoding(_); end # rubocop:disable Naming/AccessorMethodName
end
def params(button)
form_element_types = %i[input select textarea button]
form_elements_xpath = XPath.generate do |xp|
xpath = xp.descendant(*form_element_types).where(!xp.attr(:form))
xpath += xp.anywhere(*form_element_types).where(xp.attr(:form) == native[:id]) if native[:id]
xpath.where(!xp.attr(:disabled))
end.to_s
form_elements = native.xpath(form_elements_xpath).reject { |el| submitter?(el) && (el != button.native) }
form_params = form_elements.each_with_object({}.compare_by_identity) do |field, params|
case field.name
when 'input', 'button' then add_input_param(field, params)
when 'select' then add_select_param(field, params)
when 'textarea' then add_textarea_param(field, params)
end
end
form_params.each_with_object(make_params) do |(name, value), params|
merge_param!(params, name, value)
end.to_params_hash
# form_elements.each_with_object(make_params) do |field, params|
# case field.name
# when 'input', 'button' then add_input_param(field, params)
# when 'select' then add_select_param(field, params)
# when 'textarea' then add_textarea_param(field, params)
# end
# end.to_params_hash
end
def submit(button)
action = button&.[]('formaction') || native['action']
method = button&.[]('formmethod') || request_method
driver.submit(method, action.to_s, params(button), content_type: native['enctype'])
end
def multipart?
self[:enctype] == 'multipart/form-data'
end
private
class ParamsHash < Hash
def to_params_hash
self
end
end
def request_method
/post/i.match?(self[:method] || '') ? :post : :get
end
def merge_param!(params, key, value)
key = key.to_s
if Rack::Utils.respond_to?(:default_query_parser)
Rack::Utils.default_query_parser.normalize_params(params, key, value, Rack::Utils.param_depth_limit)
else
Rack::Utils.normalize_params(params, key, value)
end
end
def make_params
if Rack::Utils.respond_to?(:default_query_parser)
Rack::Utils.default_query_parser.make_params
else
ParamsHash.new
end
end
def add_input_param(field, params)
name, value = field['name'].to_s, field['value'].to_s
return if name.empty?
value = case field['type']
when 'radio', 'checkbox'
return unless field['checked']
Capybara::RackTest::Node.new(driver, field).value.to_s
when 'file'
return if value.empty? && params.keys.include?(name) && Rack::Test::VERSION.to_f >= 2.0 # rubocop:disable Performance/InefficientHashSearch
if multipart?
file_to_upload(value)
else
File.basename(value)
end
else
value
end
# merge_param!(params, name, value)
params[name] = value
end
def file_to_upload(filename)
if filename.empty?
NilUploadedFile.new
else
mime_info = MiniMime.lookup_by_filename(filename)
Rack::Test::UploadedFile.new(filename, mime_info&.content_type&.to_s)
end
end
def add_select_param(field, params)
name = field['name']
if field.has_attribute?('multiple')
value = field.xpath('.//option[@selected]').map do |option|
# merge_param!(params, field['name'], (option['value'] || option.text).to_s)
(option['value'] || option.text).to_s
end
params[name] = value unless value.empty?
else
option = field.xpath('.//option[@selected]').first || field.xpath('.//option').first
# merge_param!(params, field['name'], (option['value'] || option.text).to_s) if option
params[name] = (option['value'] || option.text).to_s if option
end
end
def add_textarea_param(field, params)
# merge_param!(params, field['name'], field['_capybara_raw_value'].to_s.gsub(/\r?\n/, "\r\n"))
params[field['name']] = field['_capybara_raw_value'].to_s.gsub(/\r?\n/, "\r\n")
end
def submitter?(el)
(%w[submit image].include? el['type']) || (el.name == 'button')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rack_test/node.rb | lib/capybara/rack_test/node.rb | # frozen_string_literal: true
require 'capybara/rack_test/errors'
require 'capybara/node/whitespace_normalizer'
class Capybara::RackTest::Node < Capybara::Driver::Node
include Capybara::Node::WhitespaceNormalizer
BLOCK_ELEMENTS = %w[p h1 h2 h3 h4 h5 h6 ol ul pre address blockquote dl div fieldset form hr noscript table].freeze
def all_text
normalize_spacing(native.text)
end
def visible_text
normalize_visible_spacing(displayed_text)
end
def [](name)
string_node[name]
end
def style(_styles)
raise NotImplementedError, 'The rack_test driver does not process CSS'
end
def value
string_node.value
end
def set(value, **options)
return if disabled? || readonly?
warn "Options passed to Node#set but the RackTest driver doesn't support any - ignoring" unless options.empty?
if value.is_a?(Array) && !multiple?
raise TypeError, "Value cannot be an Array when 'multiple' attribute is not present. Not a #{value.class}"
end
if radio? then set_radio(value)
elsif checkbox? then set_checkbox(value)
elsif range? then set_range(value)
elsif input_field? then set_input(value)
elsif textarea? then native['_capybara_raw_value'] = value.to_s
end
end
def select_option
return if disabled?
deselect_options unless select_node.multiple?
native['selected'] = 'selected'
end
def unselect_option
raise Capybara::UnselectNotAllowed, 'Cannot unselect option from single select box.' unless select_node.multiple?
native.remove_attribute('selected')
end
def click(keys = [], **options)
options.delete(:offset)
raise ArgumentError, 'The RackTest driver does not support click options' unless keys.empty? && options.empty?
if link?
follow_link
elsif submits?
associated_form = form
Capybara::RackTest::Form.new(driver, associated_form).submit(self) if associated_form
elsif checkable?
set(!checked?)
elsif tag_name == 'label'
click_label
elsif (details = native.xpath('.//ancestor-or-self::details').last)
toggle_details(details)
end
end
def tag_name
native.node_name
end
def visible?
string_node.visible?
end
def checked?
string_node.checked?
end
def selected?
string_node.selected?
end
def disabled?
return true if string_node.disabled?
if %w[option optgroup].include? tag_name
find_xpath(OPTION_OWNER_XPATH)[0].disabled?
else
!find_xpath(DISABLED_BY_FIELDSET_XPATH).empty?
end
end
def readonly?
# readonly attribute not valid on these input types
return false if input_field? && %w[hidden range color checkbox radio file submit image reset button].include?(type)
super
end
def path
native.path
end
def find_xpath(locator, **_hints)
native.xpath(locator).map { |el| self.class.new(driver, el) }
end
def find_css(locator, **_hints)
native.css(locator, Capybara::RackTest::CSSHandlers.new).map { |el| self.class.new(driver, el) }
end
public_instance_methods(false).each do |meth_name|
alias_method "unchecked_#{meth_name}", meth_name
private "unchecked_#{meth_name}" # rubocop:disable Style/AccessModifierDeclarations
class_eval <<~METHOD, __FILE__, __LINE__ + 1
def #{meth_name}(...)
stale_check
method(:"unchecked_#{meth_name}").call(...)
end
METHOD
end
protected
# @api private
def displayed_text(check_ancestor: true)
if !string_node.visible?(check_ancestor)
''
elsif native.text?
native
.text
.delete(REMOVED_CHARACTERS)
.tr(SQUEEZED_SPACES, ' ')
.squeeze(' ')
elsif native.element?
text = native.children.map do |child|
Capybara::RackTest::Node.new(driver, child).displayed_text(check_ancestor: false)
end.join || ''
text = "\n#{text}\n" if BLOCK_ELEMENTS.include?(tag_name)
text
else # rubocop:disable Lint/DuplicateBranch
''
end
end
private
def stale_check
raise Capybara::RackTest::Errors::StaleElementReferenceError unless native.document == driver.dom
end
def deselect_options
select_node.find_xpath('.//option[@selected]').each { |node| node.native.remove_attribute('selected') }
end
def string_node
@string_node ||= Capybara::Node::Simple.new(native)
end
# a reference to the select node if this is an option node
def select_node
find_xpath('./ancestor::select[1]').first
end
def type
native[:type]
end
def form
if native[:form]
native.xpath("//form[@id='#{native[:form]}']")
else
native.ancestors('form')
end.first
end
def set_radio(_value) # rubocop:disable Naming/AccessorMethodName
other_radios_xpath = XPath.generate { |xp| xp.anywhere(:input)[xp.attr(:name) == self[:name]] }.to_s
driver.dom.xpath(other_radios_xpath).each { |node| node.remove_attribute('checked') }
native['checked'] = 'checked'
end
def set_checkbox(value) # rubocop:disable Naming/AccessorMethodName
if value && !native['checked']
native['checked'] = 'checked'
elsif !value && native['checked']
native.remove_attribute('checked')
end
end
def set_range(value) # rubocop:disable Naming/AccessorMethodName
min, max, step = (native['min'] || 0).to_f, (native['max'] || 100).to_f, (native['step'] || 1).to_f
value = value.to_f
value = value.clamp(min, max)
value = (((value - min) / step).round * step) + min
native['value'] = value.clamp(min, max)
end
def set_input(value) # rubocop:disable Naming/AccessorMethodName
if text_or_password? && attribute_is_not_blank?(:maxlength)
# Browser behavior for maxlength="0" is inconsistent, so we stick with
# Firefox, allowing no input
value = value.to_s[0...self[:maxlength].to_i]
end
if value.is_a?(Array) # Assert multiple attribute is present
value.each do |val|
new_native = native.clone
new_native.remove_attribute('value')
native.add_next_sibling(new_native)
new_native['value'] = val.to_s
end
native.remove
else
value.to_s.tap do |set_value|
if set_value.end_with?("\n") && (form&.css('input, textarea')&.count == 1) # rubocop:disable Style/CollectionQuerying
native['value'] = set_value.to_s.chop
Capybara::RackTest::Form.new(driver, form).submit(self)
else
native['value'] = set_value
end
end
end
end
def attribute_is_not_blank?(attribute)
self[attribute] && !self[attribute].empty?
end
def follow_link
method = self['data-method'] || self['data-turbo-method'] if driver.options[:respect_data_method]
method ||= :get
driver.follow(method, self[:href].to_s)
end
def click_label
labelled_control = if native[:for]
find_xpath("//input[@id='#{native[:for]}']")
else
find_xpath('.//input')
end.first
labelled_control.set(!labelled_control.checked?) if checkbox_or_radio?(labelled_control)
end
def toggle_details(details = nil)
details ||= native.xpath('.//ancestor-or-self::details').last
return unless details
if details.has_attribute?('open')
details.remove_attribute('open')
else
details.set_attribute('open', 'open')
end
end
def link?
tag_name == 'a' && !self[:href].nil?
end
def submits?
(tag_name == 'input' && %w[submit image].include?(type)) || (tag_name == 'button' && [nil, 'submit'].include?(type))
end
def checkable?
tag_name == 'input' && %w[checkbox radio].include?(type)
end
protected
def checkbox_or_radio?(field = self)
field&.checkbox? || field&.radio?
end
def checkbox?
input_field? && type == 'checkbox'
end
def radio?
input_field? && type == 'radio'
end
def text_or_password?
input_field? && %w[text password].include?(type)
end
def input_field?
tag_name == 'input'
end
def textarea?
tag_name == 'textarea'
end
def range?
input_field? && type == 'range'
end
OPTION_OWNER_XPATH = XPath.parent(:optgroup, :select, :datalist).to_s.freeze
DISABLED_BY_FIELDSET_XPATH = XPath.generate do |x|
x.parent(:fieldset)[
XPath.attr(:disabled)
] + x.ancestor[
~x.self(:legend) |
x.preceding_sibling(:legend)
][
x.parent(:fieldset)[
x.attr(:disabled)
]
]
end.to_s.freeze
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rack_test/css_handlers.rb | lib/capybara/rack_test/css_handlers.rb | # frozen_string_literal: true
class Capybara::RackTest::CSSHandlers < BasicObject
include ::Kernel
def disabled(list)
list.find_all { |node| node.has_attribute? 'disabled' }
end
def enabled(list)
list.find_all { |node| !node.has_attribute? 'disabled' }
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/test_case.rb | test/test_case.rb | module Whenever
require 'minitest/autorun'
begin
# 2.0.0
class TestCase < Minitest::Test; end
rescue NameError
# 1.9.3
class TestCase < Minitest::Unit::TestCase; end
end
class TestCase
class << self
def setup(&block)
define_method(:setup) do
super()
instance_eval(&block)
end
end
def test(name, &block)
define_method("test_#{name}".to_sym, &block)
end
alias should test
end
def assert_no_match(regexp, string)
message = "<#{regexp}> expected to not match\n<#{string}>"
assert regexp !~ string, message
end
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/test_helper.rb | test/test_helper.rb | require 'whenever'
require 'test_case'
require 'mocha/minitest'
begin
require 'active_support/all'
rescue LoadError
end
module Whenever::TestHelpers
protected
def new_job(options={})
Whenever::Job.new(options)
end
def parse_time(time = nil, task = nil, at = nil, options = {})
Whenever::Output::Cron.new(time, task, at, options).time_in_cron_syntax
end
def two_hours
"0 0,2,4,6,8,10,12,14,16,18,20,22 * * *"
end
def assert_months_and_days_and_hours_and_minutes_equals(expected, time, options = {})
cron = parse_time(Whenever.seconds(1, :year), 'some task', time, options)
minutes, hours, days, months = cron.split(' ')
assert_equal expected, [months, days, hours, minutes]
end
def assert_days_and_hours_and_minutes_equals(expected, time, options = {})
cron = parse_time(Whenever.seconds(2, :months), 'some task', time, options)
minutes, hours, days, _ = cron.split(' ')
assert_equal expected, [days, hours, minutes]
end
def assert_hours_and_minutes_equals(expected, time, options = {})
cron = parse_time(Whenever.seconds(2, :days), 'some task', time, options)
minutes, hours, _ = cron.split(' ')
assert_equal expected, [hours, minutes]
end
def assert_minutes_equals(expected, time, options = {})
cron = parse_time(Whenever.seconds(2, :hours), 'some task', time, options)
assert_equal expected, cron.split(' ')[0]
end
def lines_without_empty_line(lines)
lines.map { |line| line.chomp }.reject { |line| line.empty? }
end
end
Whenever::TestCase.send(:include, Whenever::TestHelpers)
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/unit/executable_test.rb | test/unit/executable_test.rb | require 'test_helper'
describe 'Executable' do
describe 'bin/wheneverize' do
describe 'ARGV is not empty' do
describe 'file does not exist' do
file = '/tmp/this_does_not_exist'
it 'prints STDERR' do
out, err = capture_subprocess_io do
system('wheneverize', file)
end
assert_empty(out)
assert_match(/`#{file}' does not exist./, err)
end
end
describe 'file exists, but not a directory' do
file = '/tmp/this_is_a_file.txt'
before { FileUtils.touch(file) }
it 'prints STDERR' do
begin
out, err = capture_subprocess_io do
system('wheneverize', file)
end
assert_empty(out)
assert_match(/`#{file}' is not a directory./, err)
ensure
FileUtils.rm(file)
end
end
end
describe 'file is a directory, but another param(s) are given as well' do
file = '/tmp/this_is_a_directory'
before { FileUtils.mkdir(file) }
it 'prints STDERR' do
begin
out, err = capture_subprocess_io do
system('wheneverize', file, 'another', 'parameters')
end
assert_empty(out)
assert_match(/#{"Too many arguments; please specify only the " \
"directory to wheneverize."}/, err)
ensure
FileUtils.rmdir(file)
end
end
end
end
describe 'ARGV is empty' do
dir = '.'
file = 'config/schedule.rb'
path = File.join(dir, file)
describe 'config file already exists' do
before do
FileUtils.mkdir(File.dirname(path))
FileUtils.touch(path)
end
it 'prints STDOUT and STDERR' do
begin
out, err = capture_subprocess_io do
system('wheneverize')
end
assert_match(/\[done\] wheneverized!/, out)
assert_match(/\[skip\] `#{path}' already exists/, err)
ensure
FileUtils.rm_rf(File.dirname(path))
end
end
end
describe 'config directory does not exist' do
it 'prints STDOUT and STDERR' do
begin
out, err = capture_subprocess_io do
system('wheneverize')
end
assert_match(/\[add\] creating `#{File.dirname(path)}'\n/, err)
assert_match(/\[done\] wheneverized!/, out)
ensure
FileUtils.rm_rf(File.dirname(path))
end
end
end
describe 'config directory exists, but file does not' do
before { FileUtils.mkdir(File.dirname(path)) }
it 'writes config file and prints STDOUT' do
begin
out, err = capture_subprocess_io do
system('wheneverize')
end
assert_empty(err)
assert_match(
/\[add\] writing `#{path}'\n\[done\] wheneverized!/,
out
)
assert_match((<<-FILE
# Use this file to easily define all of your cron jobs.
#
# It's helpful, but not entirely necessary to understand cron before proceeding.
# http://en.wikipedia.org/wiki/Cron
# Example:
#
# set :output, "/path/to/my/cron_log.log"
#
# every 2.hours do
# command "/usr/bin/some_great_command"
# runner "MyModel.some_method"
# rake "some:great:rake:task"
# end
#
# every 4.days do
# runner "AnotherModel.prune_old_records"
# end
# Learn more: http://github.com/javan/whenever
FILE
), IO.read(path))
ensure
FileUtils.rm_rf(File.dirname(path))
end
end
end
end
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/unit/cron_test.rb | test/unit/cron_test.rb | require 'test_helper'
class CronTest < Whenever::TestCase
should "raise if less than 1 minute" do
assert_raises ArgumentError do
parse_time(Whenever.seconds(59, :seconds))
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(0, :minutes))
end
end
# For sanity, do some tests on straight cron-syntax strings
should "parse correctly" do
assert_equal '* * * * *', parse_time(Whenever.seconds(1, :minute))
assert_equal '0,5,10,15,20,25,30,35,40,45,50,55 * * * *', parse_time(Whenever.seconds(5, :minutes))
assert_equal '7,14,21,28,35,42,49,56 * * * *', parse_time(Whenever.seconds(7, :minutes))
assert_equal '0,30 * * * *', parse_time(Whenever.seconds(30, :minutes))
assert_equal '32 * * * *', parse_time(Whenever.seconds(32, :minutes))
assert '60 * * * *' != parse_time(Whenever.seconds(60, :minutes)) # 60 minutes bumps up into the hour range
end
# Test all minutes
(2..59).each do |num|
should "parse correctly for #{num} minutes" do
start = 0
start += num unless 60.modulo(num).zero?
minutes = (start..59).step(num).to_a
assert_equal "#{minutes.join(',')} * * * *", parse_time(Whenever.seconds(num, :minutes))
end
end
end
class CronParseHoursTest < Whenever::TestCase
should "parse correctly" do
assert_equal '0 * * * *', parse_time(Whenever.seconds(1, :hour))
assert_equal '0 0,2,4,6,8,10,12,14,16,18,20,22 * * *', parse_time(Whenever.seconds(2, :hours))
assert_equal '0 0,3,6,9,12,15,18,21 * * *', parse_time(Whenever.seconds(3, :hours))
assert_equal '0 5,10,15,20 * * *', parse_time(Whenever.seconds(5, :hours))
assert_equal '0 17 * * *', parse_time(Whenever.seconds(17, :hours))
assert '0 24 * * *' != parse_time(Whenever.seconds(24, :hours)) # 24 hours bumps up into the day range
end
(2..23).each do |num|
should "parse correctly for #{num} hours" do
start = 0
start += num unless 24.modulo(num).zero?
hours = (start..23).step(num).to_a
assert_equal "0 #{hours.join(',')} * * *", parse_time(Whenever.seconds(num, :hours))
end
end
should "parse correctly when given an 'at' with minutes as an Integer" do
assert_minutes_equals "1", 1
assert_minutes_equals "14", 14
assert_minutes_equals "27", 27
assert_minutes_equals "55", 55
end
should "parse correctly when given an 'at' with minutes as a Time" do
# Basically just testing that Chronic parses some times and we get the minutes out of it
assert_minutes_equals "1", '3:01am'
assert_minutes_equals "1", 'January 21 2:01 PM'
assert_minutes_equals "0", 'midnight'
assert_minutes_equals "59", '13:59'
end
should "parse correctly when given an 'at' with minutes as a Time and custom Chronic options are set" do
assert_minutes_equals "15", '3:15'
assert_minutes_equals "15", '3:15', :chronic_options => { :hours24 => true }
assert_minutes_equals "15", '3:15', :chronic_options => { :hours24 => false }
assert_minutes_equals "30", '6:30'
assert_minutes_equals "30", '6:30', :chronic_options => { :hours24 => true }
assert_minutes_equals "30", '6:30', :chronic_options => { :hours24 => false }
end
should "parse correctly when given an 'at' with minutes as a Range" do
assert_minutes_equals "15-30", 15..30
end
should "raise an exception when given an 'at' with an invalid minute value" do
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :hour), nil, 60)
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :hour), nil, -1)
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :hour), nil, 0..60)
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :hour), nil, -1..59)
end
end
end
class CronParseDaysTest < Whenever::TestCase
should "parse correctly" do
assert_equal '0 0 * * *', parse_time(Whenever.seconds(1, :days))
assert_equal '0 0 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31 * *', parse_time(Whenever.seconds(2, :days))
assert_equal '0 0 1,5,9,13,17,21,25,29 * *', parse_time(Whenever.seconds(4, :days))
assert_equal '0 0 1,8,15,22 * *', parse_time(Whenever.seconds(7, :days))
assert_equal '0 0 1,17 * *', parse_time(Whenever.seconds(16, :days))
assert_equal '0 0 17 * *', parse_time(Whenever.seconds(17, :days))
assert_equal '0 0 29 * *', parse_time(Whenever.seconds(29, :days))
assert '0 0 30 * *' != parse_time(Whenever.seconds(30, :days)) # 30 days bumps into the month range
end
should "parse correctly when given an 'at' with hours, minutes as a Time" do
# first param is an array with [hours, minutes]
assert_hours_and_minutes_equals %w(3 45), '3:45am'
assert_hours_and_minutes_equals %w(20 1), '8:01pm'
assert_hours_and_minutes_equals %w(0 0), 'midnight'
assert_hours_and_minutes_equals %w(1 23), '1:23 AM'
assert_hours_and_minutes_equals %w(23 59), 'March 21 11:59 pM'
end
should "parse correctly when given an 'at' with hours, minutes as a Time and custom Chronic options are set" do
# first param is an array with [hours, minutes]
assert_hours_and_minutes_equals %w(15 15), '3:15'
assert_hours_and_minutes_equals %w(3 15), '3:15', :chronic_options => { :hours24 => true }
assert_hours_and_minutes_equals %w(15 15), '3:15', :chronic_options => { :hours24 => false }
assert_hours_and_minutes_equals %w(6 30), '6:30'
assert_hours_and_minutes_equals %w(6 30), '6:30', :chronic_options => { :hours24 => true }
assert_hours_and_minutes_equals %w(6 30), '6:30', :chronic_options => { :hours24 => false }
end
should "parse correctly when given an 'at' with hours as an Integer" do
# first param is an array with [hours, minutes]
assert_hours_and_minutes_equals %w(1 0), 1
assert_hours_and_minutes_equals %w(3 0), 3
assert_hours_and_minutes_equals %w(15 0), 15
assert_hours_and_minutes_equals %w(19 0), 19
assert_hours_and_minutes_equals %w(23 0), 23
end
should "parse correctly when given an 'at' with hours as a Range" do
assert_hours_and_minutes_equals %w(3-23 0), 3..23
end
should "raise an exception when given an 'at' with an invalid hour value" do
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :day), nil, 24)
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :day), nil, -1)
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :day), nil, 0..24)
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :day), nil, -1..23)
end
end
end
class CronParseMonthsTest < Whenever::TestCase
should "parse correctly" do
assert_equal '0 0 1 * *', parse_time(Whenever.seconds(1, :month))
assert_equal '0 0 1 1,3,5,7,9,11 *', parse_time(Whenever.seconds(2, :months))
assert_equal '0 0 1 1,4,7,10 *', parse_time(Whenever.seconds(3, :months))
assert_equal '0 0 1 1,5,9 *', parse_time(Whenever.seconds(4, :months))
assert_equal '0 0 1 1,6 *', parse_time(Whenever.seconds(5, :months))
assert_equal '0 0 1 7 *', parse_time(Whenever.seconds(7, :months))
assert_equal '0 0 1 8 *', parse_time(Whenever.seconds(8, :months))
assert_equal '0 0 1 9 *', parse_time(Whenever.seconds(9, :months))
assert_equal '0 0 1 10 *', parse_time(Whenever.seconds(10, :months))
assert_equal '0 0 1 11 *', parse_time(Whenever.seconds(11, :months))
assert_equal '0 0 1 12 *', parse_time(Whenever.seconds(12, :months))
end
should "parse months with a date and/or time" do
# should set the day to 1 if no date is given
assert_equal '0 17 1 * *', parse_time(Whenever.seconds(1, :month), nil, "5pm")
# should use the date if one is given
assert_equal '0 2 23 * *', parse_time(Whenever.seconds(1, :month), nil, "February 23rd at 2am")
# should use an iteger as the day
assert_equal '0 0 5 * *', parse_time(Whenever.seconds(1, :month), nil, 5)
end
should "parse correctly when given an 'at' with days, hours, minutes as a Time" do
# first param is an array with [days, hours, minutes]
assert_days_and_hours_and_minutes_equals %w(1 3 45), 'January 1st 3:45am'
assert_days_and_hours_and_minutes_equals %w(11 23 0), 'Feb 11 11PM'
assert_days_and_hours_and_minutes_equals %w(22 1 1), 'march 22nd at 1:01 am'
assert_days_and_hours_and_minutes_equals %w(23 0 0), 'march 22nd at midnight' # looks like midnight means the next day
end
should "parse correctly when given an 'at' with days, hours, minutes as a Time and custom Chronic options are set" do
# first param is an array with [days, hours, minutes]
assert_days_and_hours_and_minutes_equals %w(22 15 45), 'February 22nd 3:45'
assert_days_and_hours_and_minutes_equals %w(22 15 45), '02/22 3:45'
assert_days_and_hours_and_minutes_equals %w(22 3 45), 'February 22nd 3:45', :chronic_options => { :hours24 => true }
assert_days_and_hours_and_minutes_equals %w(22 15 45), 'February 22nd 3:45', :chronic_options => { :hours24 => false }
assert_days_and_hours_and_minutes_equals %w(3 8 15), '02/03 8:15'
assert_days_and_hours_and_minutes_equals %w(3 8 15), '02/03 8:15', :chronic_options => { :endian_precedence => :middle }
assert_days_and_hours_and_minutes_equals %w(2 8 15), '02/03 8:15', :chronic_options => { :endian_precedence => :little }
assert_days_and_hours_and_minutes_equals %w(4 4 50), '03/04 4:50', :chronic_options => { :endian_precedence => :middle, :hours24 => true }
assert_days_and_hours_and_minutes_equals %w(4 16 50), '03/04 4:50', :chronic_options => { :endian_precedence => :middle, :hours24 => false }
assert_days_and_hours_and_minutes_equals %w(3 4 50), '03/04 4:50', :chronic_options => { :endian_precedence => :little, :hours24 => true }
assert_days_and_hours_and_minutes_equals %w(3 16 50), '03/04 4:50', :chronic_options => { :endian_precedence => :little, :hours24 => false }
end
should "parse correctly when given an 'at' with days as an Integer" do
# first param is an array with [days, hours, minutes]
assert_days_and_hours_and_minutes_equals %w(1 0 0), 1
assert_days_and_hours_and_minutes_equals %w(15 0 0), 15
assert_days_and_hours_and_minutes_equals %w(29 0 0), 29
end
should "parse correctly when given an 'at' with days as a Range" do
assert_days_and_hours_and_minutes_equals %w(1-7 0 0), 1..7
end
should "raise an exception when given an 'at' with an invalid day value" do
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :month), nil, 32)
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :month), nil, -1)
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :month), nil, 0..30)
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :month), nil, 1..32)
end
end
end
class CronParseYearTest < Whenever::TestCase
should "parse correctly" do
assert_equal '0 0 1 1 *', parse_time(Whenever.seconds(1, :year))
end
should "parse year with a date and/or time" do
# should set the day and month to 1 if no date is given
assert_equal '0 17 1 1 *', parse_time(Whenever.seconds(1, :year), nil, "5pm")
# should use the date if one is given
assert_equal '0 2 23 2 *', parse_time(Whenever.seconds(1, :year), nil, "February 23rd at 2am")
# should use an iteger as the month
assert_equal '0 0 1 5 *', parse_time(Whenever.seconds(1, :year), nil, 5)
end
should "parse correctly when given an 'at' with days, hours, minutes as a Time" do
# first param is an array with [months, days, hours, minutes]
assert_months_and_days_and_hours_and_minutes_equals %w(1 1 3 45), 'January 1st 3:45am'
assert_months_and_days_and_hours_and_minutes_equals %w(2 11 23 0), 'Feb 11 11PM'
assert_months_and_days_and_hours_and_minutes_equals %w(3 22 1 1), 'march 22nd at 1:01 am'
assert_months_and_days_and_hours_and_minutes_equals %w(3 23 0 0), 'march 22nd at midnight' # looks like midnight means the next day
end
should "parse correctly when given an 'at' with days, hours, minutes as a Time and custom Chronic options are set" do
# first param is an array with [months, days, hours, minutes]
assert_months_and_days_and_hours_and_minutes_equals %w(2 22 15 45), 'February 22nd 3:45'
assert_months_and_days_and_hours_and_minutes_equals %w(2 22 15 45), '02/22 3:45'
assert_months_and_days_and_hours_and_minutes_equals %w(2 22 3 45), 'February 22nd 3:45', :chronic_options => { :hours24 => true }
assert_months_and_days_and_hours_and_minutes_equals %w(2 22 15 45), 'February 22nd 3:45', :chronic_options => { :hours24 => false }
assert_months_and_days_and_hours_and_minutes_equals %w(2 3 8 15), '02/03 8:15'
assert_months_and_days_and_hours_and_minutes_equals %w(2 3 8 15), '02/03 8:15', :chronic_options => { :endian_precedence => :middle }
assert_months_and_days_and_hours_and_minutes_equals %w(3 2 8 15), '02/03 8:15', :chronic_options => { :endian_precedence => :little }
assert_months_and_days_and_hours_and_minutes_equals %w(3 4 4 50), '03/04 4:50', :chronic_options => { :endian_precedence => :middle, :hours24 => true }
assert_months_and_days_and_hours_and_minutes_equals %w(3 4 16 50), '03/04 4:50', :chronic_options => { :endian_precedence => :middle, :hours24 => false }
assert_months_and_days_and_hours_and_minutes_equals %w(4 3 4 50), '03/04 4:50', :chronic_options => { :endian_precedence => :little, :hours24 => true }
assert_months_and_days_and_hours_and_minutes_equals %w(4 3 16 50), '03/04 4:50', :chronic_options => { :endian_precedence => :little, :hours24 => false }
end
should "parse correctly when given an 'at' with month as an Integer" do
# first param is an array with [months, days, hours, minutes]
assert_months_and_days_and_hours_and_minutes_equals %w(1 1 0 0), 1
assert_months_and_days_and_hours_and_minutes_equals %w(5 1 0 0), 5
assert_months_and_days_and_hours_and_minutes_equals %w(12 1 0 0), 12
end
should "parse correctly when given an 'at' with month as a Range" do
assert_months_and_days_and_hours_and_minutes_equals %w(1-3 1 0 0), 1..3
end
should "raise an exception when given an 'at' with an invalid month value" do
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :year), nil, 13)
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :year), nil, -1)
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :year), nil, 0..12)
end
assert_raises ArgumentError do
parse_time(Whenever.seconds(1, :year), nil, 1..13)
end
end
end
class CronParseDaysOfWeekTest < Whenever::TestCase
should "parse days of the week correctly" do
{
'0' => %w(sun Sunday SUNDAY SUN),
'1' => %w(mon Monday MONDAY MON),
'2' => %w(tue tues Tuesday TUESDAY TUE),
'3' => %w(wed Wednesday WEDNESDAY WED),
'4' => %w(thu thurs thur Thursday THURSDAY THU),
'5' => %w(fri Friday FRIDAY FRI),
'6' => %w(sat Saturday SATURDAY SAT)
}.each do |day, day_tests|
day_tests.each do |day_test|
assert_equal "0 0 * * #{day}", parse_time(day_test)
end
end
end
should "allow additional directives" do
assert_equal '30 13 * * 5', parse_time('friday', nil, "1:30 pm")
assert_equal '22 2 * * 1', parse_time('Monday', nil, "2:22am")
assert_equal '55 17 * * 4', parse_time('THU', nil, "5:55PM")
end
should "parse weekday correctly" do
assert_equal '0 0 * * 1-5', parse_time('weekday')
assert_equal '0 0 * * 1-5', parse_time('Weekdays')
assert_equal '0 1 * * 1-5', parse_time('Weekdays', nil, "1:00 am")
assert_equal '59 5 * * 1-5', parse_time('Weekdays', nil, "5:59 am")
end
should "parse weekend correctly" do
assert_equal '0 0 * * 6,0', parse_time('weekend')
assert_equal '0 0 * * 6,0', parse_time('Weekends')
assert_equal '0 7 * * 6,0', parse_time('Weekends', nil, "7am")
assert_equal '2 18 * * 6,0', parse_time('Weekends', nil, "6:02PM")
end
end
class CronParseShortcutsTest < Whenever::TestCase
should "parse a :symbol into the correct shortcut" do
assert_equal '@reboot', parse_time(:reboot)
assert_equal '@annually', parse_time(:annually)
assert_equal '@yearly', parse_time(:yearly)
assert_equal '@daily', parse_time(:daily)
assert_equal '@midnight', parse_time(:midnight)
assert_equal '@monthly', parse_time(:monthly)
assert_equal '@weekly', parse_time(:weekly)
assert_equal '@hourly', parse_time(:hourly)
end
should "convert time-based shortcuts to times" do
assert_equal '0 0 1 * *', parse_time(:month)
assert_equal '0 0 * * *', parse_time(:day)
assert_equal '0 * * * *', parse_time(:hour)
assert_equal '0 0 1 1 *', parse_time(:year)
assert_equal '0 0 1,8,15,22 * *', parse_time(:week)
end
should "raise an exception if a valid shortcut is given but also an :at" do
assert_raises ArgumentError do
parse_time(:hourly, nil, "1:00 am")
end
assert_raises ArgumentError do
parse_time(:reboot, nil, 5)
end
assert_raises ArgumentError do
parse_time(:daily, nil, '4:20pm')
end
end
end
class CronParseRubyTimeTest < Whenever::TestCase
should "process things like `1.day` correctly" do
assert_equal "0 0 * * *", parse_time(1.day)
end
end
class CronParseRawTest < Whenever::TestCase
should "raise if cron-syntax string is too long" do
assert_raises ArgumentError do
parse_time('* * * * * *')
end
end
should "raise if cron-syntax string is invalid" do
assert_raises ArgumentError do
parse_time('** * * * *')
end
end
should "return the same cron sytax" do
crons = ['0 0 27-31 * *', '* * * * *', '2/3 1,9,22 11-26 1-6 *', '*/5 6-23 * * *',
"*\t*\t*\t*\t*",
'7 17 * * FRI', '7 17 * * Mon-Fri', '30 12 * Jun *', '30 12 * Jun-Aug *',
'@reboot', '@yearly', '@annually', '@monthly', '@weekly',
'@daily', '@midnight', '@hourly']
crons.each do |cron|
assert_equal cron, parse_time(cron)
end
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/unit/job_test.rb | test/unit/job_test.rb | require 'test_helper'
class JobTest < Whenever::TestCase
should "return the :at set when #at is called" do
assert_equal 'foo', new_job(:at => 'foo').at
end
should "return the :roles set when #roles is called" do
assert_equal ['foo', 'bar'], new_job(:roles => ['foo', 'bar']).roles
end
should "return whether it has a role from #has_role?" do
assert new_job(:roles => 'foo').has_role?('foo')
assert_equal false, new_job(:roles => 'bar').has_role?('foo')
end
should "substitute the :task when #output is called" do
job = new_job(:template => ":task", :task => 'abc123')
assert_equal 'abc123', job.output
end
should "substitute the :path when #output is called" do
assert_equal 'foo', new_job(:template => ':path', :path => 'foo').output
end
should "substitute the :path with the default Whenever.path if none is provided when #output is called" do
Whenever.expects(:path).returns('/my/path')
assert_equal '/my/path', new_job(:template => ':path').output
end
should "not substitute parameters for which no value is set" do
assert_equal 'Hello :world', new_job(:template => ':matching :world', :matching => 'Hello').output
end
should "escape the :path" do
assert_equal '/my/spacey\ path', new_job(:template => ':path', :path => '/my/spacey path').output
end
should "escape percent signs" do
job = new_job(
:template => "before :foo after",
:foo => "percent -> % <- percent"
)
assert_equal %q(before percent -> \% <- percent after), job.output
end
should "assume percent signs are not already escaped" do
job = new_job(
:template => "before :foo after",
:foo => %q(percent preceded by a backslash -> \% <-)
)
assert_equal %q(before percent preceded by a backslash -> \\\% <- after), job.output
end
should "squish spaces and newlines" do
job = new_job(
:template => "before :foo after",
:foo => "newline -> \n <- newline space -> <- space"
)
assert_equal "before newline -> <- newline space -> <- space after", job.output
end
end
class JobWithQuotesTest < Whenever::TestCase
should "output the :task if it's in single quotes" do
job = new_job(:template => "':task'", :task => 'abc123')
assert_equal %q('abc123'), job.output
end
should "output the :task if it's in double quotes" do
job = new_job(:template => '":task"', :task => 'abc123')
assert_equal %q("abc123"), job.output
end
should "output escaped single quotes in when it's wrapped in them" do
job = new_job(
:template => "before ':foo' after",
:foo => "quote -> ' <- quote"
)
assert_equal %q(before 'quote -> '\'' <- quote' after), job.output
end
should "output escaped double quotes when it's wrapped in them" do
job = new_job(
:template => 'before ":foo" after',
:foo => 'quote -> " <- quote'
)
assert_equal %q(before "quote -> \" <- quote" after), job.output
end
end
class JobWithJobTemplateTest < Whenever::TestCase
should "use the job template" do
job = new_job(:template => ':task', :task => 'abc123', :job_template => 'left :job right')
assert_equal 'left abc123 right', job.output
end
should "reuse parameter in the job template" do
job = new_job(:template => ':path :task', :path => 'path', :task => "abc123", :job_template => ':path left :job right')
assert_equal 'path left path abc123 right', job.output
end
should "escape single quotes" do
job = new_job(:template => "before ':task' after", :task => "quote -> ' <- quote", :job_template => "left ':job' right")
assert_equal %q(left 'before '\''quote -> '\\''\\'\\'''\\'' <- quote'\'' after' right), job.output
end
should "escape double quotes" do
job = new_job(:template => 'before ":task" after', :task => 'quote -> " <- quote', :job_template => 'left ":job" right')
assert_equal %q(left "before \"quote -> \\\" <- quote\" after" right), job.output
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/unit/capistrano_support_test.rb | test/unit/capistrano_support_test.rb | require 'test_helper'
require 'whenever/capistrano/v2/support'
class CapistranoSupportTestSubject
include Whenever::CapistranoSupport
end
class CapistranoTestCase < Whenever::TestCase
setup do
@capistrano = CapistranoSupportTestSubject.new
configuration = mock()
configuration.stubs(:load).yields(@capistrano)
Whenever::CapistranoSupport.load_into(configuration)
end
end
class CapistranoSupportTest < CapistranoTestCase
should "return fetch(:whenever_options) from #whenever_options" do
@capistrano.expects(:fetch).with(:whenever_options)
@capistrano.whenever_options
end
should "return whenever_options[:roles] as an array from #whenever_roles with one role" do
@capistrano.stubs(:whenever_options).returns({:roles => :role1})
assert_equal [:role1], @capistrano.whenever_roles
end
should "return an empty array from #whenever_roles with no defined roles" do
@capistrano.stubs(:whenever_options).returns({})
assert_equal [], @capistrano.whenever_roles
end
should "return the list of servers returned by find_servers from #whenever_servers" do
@capistrano.stubs(:whenever_options).returns({})
@capistrano.stubs(:find_servers).returns([:server1, :server2])
assert_equal [:server1, :server2], @capistrano.whenever_servers
end
should "#whenever_prepare_for_rollback: set path to previous_release if there is a previous release" do
args = {}
@capistrano.stubs(:fetch).with(:previous_release).returns("/some/path/20121221010000")
assert_equal({:path => "/some/path/20121221010000"}, @capistrano.whenever_prepare_for_rollback(args))
end
should "#whenever_prepare_for_rollback: set path to release_path and flags to whenever_clear_flags if there is no previous release" do
args = {}
@capistrano.stubs(:fetch).with(:previous_release).returns(nil)
@capistrano.stubs(:fetch).with(:release_path).returns("/some/path/20121221010000")
@capistrano.stubs(:fetch).with(:whenever_clear_flags).returns("--clear-crontab whenever_identifier")
assert_equal({:path => "/some/path/20121221010000", :flags => "--clear-crontab whenever_identifier"}, @capistrano.whenever_prepare_for_rollback(args))
end
should "#whenever_run_commands: require :command arg" do
assert_raises ArgumentError do
@capistrano.whenever_run_commands(:options => {}, :path => {}, :flags => {})
end
end
should "#whenever_run_commands: require :path arg" do
assert_raises ArgumentError do
@capistrano.whenever_run_commands(:options => {}, :command => {}, :flags => {})
end
end
should "#whenever_run_commands: require :flags arg" do
assert_raises ArgumentError do
@capistrano.whenever_run_commands(:options => {}, :path => {}, :command => {})
end
end
end
class ServerRolesTest < CapistranoTestCase
setup do
@mock_servers = ["foo", "bar"]
@capistrano.stubs(:whenever_servers).returns(@mock_servers)
@mock_server1, @mock_server2, @mock_server3 = mock("Server1"), mock("Server2"), mock("Server3")
@mock_server1.stubs(:host).returns("server1.foo.com")
@mock_server2.stubs(:host).returns("server2.foo.com")
@mock_server3.stubs(:host => "server3.foo.com", :port => 1022, :user => 'test')
@mock_servers = [@mock_server1, @mock_server2]
end
should "return a map of servers to their role(s)" do
@capistrano.stubs(:whenever_roles).returns([:role1, :role2])
@capistrano.stubs(:role_names_for_host).with("foo").returns([:role1])
@capistrano.stubs(:role_names_for_host).with("bar").returns([:role2])
assert_equal({"foo" => [:role1], "bar" => [:role2]}, @capistrano.whenever_server_roles)
end
should "exclude non-requested roles" do
@capistrano.stubs(:whenever_roles).returns([:role1, :role2])
@capistrano.stubs(:role_names_for_host).with("foo").returns([:role1, :role3])
@capistrano.stubs(:role_names_for_host).with("bar").returns([:role2])
assert_equal({"foo" => [:role1], "bar" => [:role2]}, @capistrano.whenever_server_roles)
end
should "include all roles for servers w/ >1 when they're requested" do
@capistrano.stubs(:whenever_roles).returns([:role1, :role2, :role3])
@capistrano.stubs(:role_names_for_host).with("foo").returns([:role1, :role3])
@capistrano.stubs(:role_names_for_host).with("bar").returns([:role2])
assert_equal({"foo" => [:role1, :role3], "bar" => [:role2]}, @capistrano.whenever_server_roles)
end
should "call run for each host w/ appropriate role args" do
@capistrano.stubs(:role_names_for_host).with(@mock_server1).returns([:role1])
@capistrano.stubs(:role_names_for_host).with(@mock_server2).returns([:role2])
@capistrano.stubs(:whenever_servers).returns(@mock_servers)
roles = [:role1, :role2]
@capistrano.stubs(:whenever_options).returns({:roles => roles})
@capistrano.expects(:run).once.with('cd /foo/bar && whenever --flag1 --flag2 --roles role1', {:roles => roles, :hosts => @mock_server1})
@capistrano.expects(:run).once.with('cd /foo/bar && whenever --flag1 --flag2 --roles role2', {:roles => roles, :hosts => @mock_server2})
@capistrano.whenever_run_commands(:command => "whenever",
:path => "/foo/bar",
:flags => "--flag1 --flag2")
end
should "call run w/ all role args for servers w/ >1 role" do
@capistrano.stubs(:role_names_for_host).with(@mock_server1).returns([:role1, :role3])
@capistrano.stubs(:whenever_servers).returns([@mock_server1])
roles = [:role1, :role2, :role3]
@capistrano.stubs(:whenever_options).returns({:roles => roles})
@capistrano.expects(:run).once.with('cd /foo/bar && whenever --flag1 --flag2 --roles role1,role3', {:roles => roles, :hosts => @mock_server1})
@capistrano.whenever_run_commands(:command => "whenever",
:path => "/foo/bar",
:flags => "--flag1 --flag2")
end
should "call run w/ proper server options (port, user)" do
@capistrano.stubs(:role_names_for_host).with(@mock_server3).returns([:role3])
@capistrano.stubs(:whenever_servers).returns([@mock_server3])
@capistrano.stubs(:whenever_options).returns({:roles => [:role3]})
@capistrano.expects(:run).once.with do |command, options|
options[:hosts].user == "test" && options[:hosts].port == 1022
end
@capistrano.whenever_run_commands(:command => "whenever",
:path => "/foo/bar",
:flags => "--flag1 --flag2")
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/functional/output_default_defined_jobs_test.rb | test/functional/output_default_defined_jobs_test.rb | require 'test_helper'
class OutputDefaultDefinedJobsTest < Whenever::TestCase
# command
test "A plain command with the job template set to nil" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah"
end
file
assert_match(/^.+ .+ .+ .+ blahblah$/, output)
end
test "A plain command with no job template set" do
output = Whenever.cron \
<<-file
every 2.hours do
command "blahblah"
end
file
assert_match(/^.+ .+ .+ .+ \/bin\/bash -l -c 'blahblah'$/, output)
end
test "A plain command with a job_template using a normal parameter" do
output = Whenever.cron \
<<-file
set :job_template, "/bin/bash -l -c 'cd :path && :job'"
every 2.hours do
set :path, "/tmp"
command "blahblah"
end
file
assert_match(/^.+ .+ .+ .+ \/bin\/bash -l -c 'cd \/tmp \&\& blahblah'$/, output)
end
test "A plain command that overrides the job_template set" do
output = Whenever.cron \
<<-file
set :job_template, "/bin/bash -l -c ':job'"
every 2.hours do
command "blahblah", :job_template => "/bin/sh -l -c ':job'"
end
file
assert_match(/^.+ .+ .+ .+ \/bin\/sh -l -c 'blahblah'$/, output)
assert_no_match(/bash/, output)
end
test "A plain command that overrides the job_template set using a parameter" do
output = Whenever.cron \
<<-file
set :job_template, "/bin/bash -l -c 'cd :path && :job'"
every 2.hours do
set :path, "/tmp"
command "blahblah", :job_template => "/bin/sh -l -c 'cd :path && :job'"
end
file
assert_match(/^.+ .+ .+ .+ \/bin\/sh -l -c 'cd \/tmp && blahblah'$/, output)
assert_no_match(/bash/, output)
end
test "A plain command that is conditional on default environent and path" do
Whenever.expects(:path).at_least_once.returns('/what/you/want')
output = Whenever.cron \
<<-file
set :job_template, nil
if environment == 'production' && path == '/what/you/want'
every 2.hours do
command "blahblah"
end
end
file
assert_match(/blahblah/, output)
end
# runner
test "A runner with path set" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
runner 'blahblah'
end
file
assert_match two_hours + %( cd /my/path && bundle exec script/runner -e production 'blahblah'), output
end
test "A runner that overrides the path set" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
runner "blahblah", :path => '/some/other/path'
end
file
assert_match two_hours + %( cd /some/other/path && bundle exec script/runner -e production 'blahblah'), output
end
test "A runner for a non-bundler app" do
Whenever.expects(:bundler?).returns(false)
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
runner 'blahblah'
end
file
assert_match two_hours + %( cd /my/path && script/runner -e production 'blahblah'), output
end
test "A runner for an app with bin/rails" do
Whenever.expects(:path).at_least_once.returns('/my/path')
Whenever.expects(:bin_rails?).returns(true)
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
runner 'blahblah'
end
file
assert_match two_hours + %( cd /my/path && bin/rails runner -e production 'blahblah'), output
end
test "A runner for an app with script/rails" do
Whenever.expects(:path).at_least_once.returns('/my/path')
Whenever.expects(:script_rails?).returns(true)
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
runner 'blahblah'
end
file
assert_match two_hours + %( cd /my/path && script/rails runner -e production 'blahblah'), output
end
# rake
test "A rake command with path set" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
rake "blahblah"
end
file
assert_match two_hours + ' cd /my/path && RAILS_ENV=production bundle exec rake blahblah --silent', output
end
test "A rake command with arguments" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
rake "blahblah[foobar]"
end
file
assert_match two_hours + ' cd /my/path && RAILS_ENV=production bundle exec rake blahblah[foobar] --silent', output
end
test "A rake for a non-bundler app" do
Whenever.expects(:path).at_least_once.returns('/my/path')
Whenever.expects(:bundler?).returns(false)
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
rake 'blahblah'
end
file
assert_match two_hours + ' cd /my/path && RAILS_ENV=production rake blahblah --silent', output
end
test "A rake command that overrides the path set" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
rake "blahblah", :path => '/some/other/path'
end
file
assert_match two_hours + ' cd /some/other/path && RAILS_ENV=production bundle exec rake blahblah --silent', output
end
test "A rake command that uses the default environment variable when RAILS_ENV is set" do
ENV.expects(:fetch).with("RAILS_ENV", "production").returns("development")
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
rake "blahblah"
end
file
assert_match two_hours + ' cd /my/path && RAILS_ENV=development bundle exec rake blahblah --silent', output
end
test "A rake command that sets the environment variable" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
set :environment_variable, 'RAKE_ENV'
every 2.hours do
rake "blahblah"
end
file
assert_match two_hours + ' cd /my/path && RAKE_ENV=production bundle exec rake blahblah --silent', output
end
test "A rake command that overrides the environment variable" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
set :environment_variable, 'RAKE_ENV'
every 2.hours do
rake "blahblah", :environment_variable => 'SOME_ENV'
end
file
assert_match two_hours + ' cd /my/path && SOME_ENV=production bundle exec rake blahblah --silent', output
end
# script
test "A script command with path set" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/my/path'
every 2.hours do
script "blahblah"
end
file
assert_match two_hours + ' cd /my/path && RAILS_ENV=production bundle exec script/blahblah', output
end
test "A script command for a non-bundler app" do
Whenever.expects(:path).at_least_once.returns('/my/path')
Whenever.expects(:bundler?).returns(false)
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
script 'blahblah'
end
file
assert_match two_hours + ' cd /my/path && RAILS_ENV=production script/blahblah', output
end
test "A script command that uses output" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :output, '/log/file'
set :path, '/my/path'
every 2.hours do
script "blahblah", :path => '/some/other/path'
end
file
assert_match two_hours + ' cd /some/other/path && RAILS_ENV=production bundle exec script/blahblah >> /log/file 2>&1', output
end
test "A script command that uses an environment variable" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :environment_variable, 'RAKE_ENV'
set :path, '/my/path'
every 2.hours do
script "blahblah"
end
file
assert_match two_hours + ' cd /my/path && RAKE_ENV=production bundle exec script/blahblah', output
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/functional/command_line_test.rb | test/functional/command_line_test.rb | require 'test_helper'
class CommandLineWriteTest < Whenever::TestCase
setup do
Time.stubs(:now).returns(Time.new(2017, 2, 24, 16, 21, 30, '+01:00'))
File.expects(:exist?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:write => true, :identifier => 'My identifier')
@task = "#{two_hours} /my/command"
Whenever.expects(:cron).returns(@task)
end
should "output the cron job with identifier blocks" do
output = <<-EXPECTED
# Begin Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
#{@task}
# End Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
EXPECTED
assert_equal output, @command.send(:whenever_cron)
end
should "write the crontab when run" do
@command.expects(:write_crontab).returns(true)
assert @command.run
end
end
class CommandLineUpdateTest < Whenever::TestCase
setup do
Time.stubs(:now).returns(Time.new(2017, 2, 24, 16, 21, 30, '+01:00'))
File.expects(:exist?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier')
@task = "#{two_hours} /my/command"
Whenever.expects(:cron).returns(@task)
end
should "add the cron to the end of the file if there is no existing identifier block" do
existing = '# Existing crontab'
@command.expects(:read_crontab).at_least_once.returns(existing)
new_cron = <<-EXPECTED
#{existing}
# Begin Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
#{@task}
# End Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
EXPECTED
assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run
end
should "replace an existing block if the identifier matches and the timestamp doesn't" do
existing = <<-EXISTING_CRON
# Something
# Begin Whenever generated tasks for: My identifier at: 2017-01-03 08:02:22 +0500
My whenever job that was already here
# End Whenever generated tasks for: My identifier at: 2017-01-03 08:22:22 +0500
# Begin Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
EXISTING_CRON
new_cron = <<-NEW_CRON
# Something
# Begin Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
#{@task}
# End Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
# Begin Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
NEW_CRON
@command.expects(:read_crontab).at_least_once.returns(existing)
assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run
end
should "replace an existing block if the identifier matches and the UTC timestamp doesn't" do
existing = <<-EXISTING_CRON
# Something
# Begin Whenever generated tasks for: My identifier at: 2017-01-03 08:02:22 UTC
My whenever job that was already here
# End Whenever generated tasks for: My identifier at: 2017-01-03 08:22:22 UTC
# Begin Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
EXISTING_CRON
new_cron = <<-NEW_CRON
# Something
# Begin Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
#{@task}
# End Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
# Begin Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
NEW_CRON
@command.expects(:read_crontab).at_least_once.returns(existing)
assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run
end
should "replace an existing block if the identifier matches and it doesn't contain a timestamp" do
existing = <<-EXISTING_CRON
# Something
# Begin Whenever generated tasks for: My identifier
My whenever job that was already here
# End Whenever generated tasks for: My identifier
# Begin Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
EXISTING_CRON
new_cron = <<-NEW_CRON
# Something
# Begin Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
#{@task}
# End Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
# Begin Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
NEW_CRON
@command.expects(:read_crontab).at_least_once.returns(existing)
assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run
end
end
class CommandLineUpdateWithBackslashesTest < Whenever::TestCase
setup do
Time.stubs(:now).returns(Time.new(2017, 2, 24, 16, 21, 30, '+01:00'))
@existing = <<-EXISTING_CRON
# Begin Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
script/runner -e production 'puts '\\''hello'\\'''
# End Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
EXISTING_CRON
File.expects(:exist?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier')
@command.expects(:read_crontab).at_least_once.returns(@existing)
@command.expects(:whenever_cron).returns(@existing)
end
should "replace the existing block with the backslashes in tact" do
assert_equal @existing, @command.send(:updated_crontab)
end
end
class CommandLineUpdateToSimilarCrontabTest < Whenever::TestCase
setup do
@existing = <<-EXISTING_CRON
# Begin Whenever generated tasks for: WheneverExisting at: 2017-02-24 16:21:30 +0100
# End Whenever generated tasks for: WheneverExisting at: 2017-02-24 16:21:30 +0100
EXISTING_CRON
@new = <<-NEW_CRON
# Begin Whenever generated tasks for: Whenever at: 2017-02-24 16:21:30 +0100
# End Whenever generated tasks for: Whenever at: 2017-02-24 16:21:30 +0100
NEW_CRON
File.expects(:exist?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:update => true, :identifier => 'Whenever')
@command.expects(:read_crontab).at_least_once.returns(@existing)
@command.expects(:whenever_cron).returns(@new)
end
should "append the similarly named command" do
assert_equal @existing + "\n" + @new, @command.send(:updated_crontab)
end
end
class CommandLineClearTest < Whenever::TestCase
setup do
Time.stubs(:now).returns(Time.new(2017, 2, 24, 16, 21, 30, '+01:00'))
File.expects(:exist?).with('config/schedule.rb').returns(true)
@command = Whenever::CommandLine.new(:clear => true, :identifier => 'My identifier')
@task = "#{two_hours} /my/command"
end
should "clear an existing block if the identifier matches and the timestamp doesn't" do
existing = <<-EXISTING_CRON
# Something
# Begin Whenever generated tasks for: My identifier at: 2017-01-03 08:20:02 +0500
My whenever job that was already here
# End Whenever generated tasks for: My identifier at: 2017-01-03 08:20:02 +0500
# Begin Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
EXISTING_CRON
@command.expects(:read_crontab).at_least_once.returns(existing)
new_cron = <<-NEW_CRON
# Something
# Begin Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
NEW_CRON
assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run
end
should "clear an existing block if the identifier matches and the UTC timestamp doesn't" do
existing = <<-EXISTING_CRON
# Something
# Begin Whenever generated tasks for: My identifier at: 2017-01-03 08:20:02 UTC
My whenever job that was already here
# End Whenever generated tasks for: My identifier at: 2017-01-03 08:20:02 UTC
# Begin Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
EXISTING_CRON
@command.expects(:read_crontab).at_least_once.returns(existing)
new_cron = <<-NEW_CRON
# Something
# Begin Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
NEW_CRON
assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run
end
should "clear an existing block if the identifier matches and it doesn't have a timestamp" do
existing = <<-EXISTING_CRON
# Something
# Begin Whenever generated tasks for: My identifier
My whenever job that was already here
# End Whenever generated tasks for: My identifier
# Begin Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
EXISTING_CRON
@command.expects(:read_crontab).at_least_once.returns(existing)
new_cron = <<-NEW_CRON
# Something
# Begin Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
This shouldn't get replaced
# End Whenever generated tasks for: Other identifier at: 2017-02-24 16:21:30 +0100
NEW_CRON
assert_equal new_cron, @command.send(:updated_crontab)
@command.expects(:write_crontab).with(new_cron).returns(true)
assert @command.run
end
end
class CommandLineClearWithNoScheduleTest < Whenever::TestCase
setup do
File.expects(:exist?).with('config/schedule.rb').returns(false)
@command = Whenever::CommandLine.new(:clear => true, :identifier => 'My identifier')
end
should "run successfully" do
@command.expects(:write_crontab).returns(true)
assert @command.run
end
end
class CommandLineUpdateWithNoIdentifierTest < Whenever::TestCase
setup do
Time.stubs(:now).returns(Time.new(2017, 2, 24, 16, 21, 30, '+01:00'))
File.expects(:exist?).with('config/schedule.rb').returns(true)
Whenever::CommandLine.any_instance.expects(:default_identifier).returns('DEFAULT')
@command = Whenever::CommandLine.new(:update => true)
end
should "use the default identifier" do
assert_equal "Whenever generated tasks for: DEFAULT at: 2017-02-24 16:21:30 +0100", @command.send(:comment_base)
end
end
class CombinedParamsTest < Whenever::TestCase
setup do
Whenever::CommandLine.any_instance.expects(:exit)
Whenever::CommandLine.any_instance.expects(:warn)
File.expects(:exist?).with('config/schedule.rb').returns(true)
end
should "exit with write and clear" do
@command = Whenever::CommandLine.new(:write => true, :clear => true)
end
should "exit with write and update" do
@command = Whenever::CommandLine.new(:write => true, :update => true)
end
should "exit with update and clear" do
@command = Whenever::CommandLine.new(:update => true, :clear => true)
end
end
class RunnerOverwrittenWithSetOptionTest < Whenever::TestCase
setup do
@output = Whenever.cron :set => 'environment=serious', :string => \
<<-file
set :job_template, nil
set :environment, :silly
set :path, '/my/path'
every 2.hours do
runner "blahblah"
end
file
end
should "output the runner using the override environment" do
assert_match two_hours + %( cd /my/path && bundle exec script/runner -e serious 'blahblah'), @output
end
end
class EnvironmentAndPathOverwrittenWithSetOptionTest < Whenever::TestCase
setup do
@output = Whenever.cron :set => 'environment=serious&path=/serious/path', :string => \
<<-file
set :job_template, nil
set :environment, :silly
set :path, '/silly/path'
every 2.hours do
runner "blahblah"
end
file
end
should "output the runner using the overridden path and environment" do
assert_match two_hours + %( cd /serious/path && bundle exec script/runner -e serious 'blahblah'), @output
end
end
class EnvironmentAndPathOverwrittenWithSetOptionWithSpacesTest < Whenever::TestCase
setup do
@output = Whenever.cron :set => ' environment = serious& path =/serious/path', :string => \
<<-file
set :job_template, nil
set :environment, :silly
set :path, '/silly/path'
every 2.hours do
runner "blahblah"
end
file
end
should "output the runner using the overridden path and environment" do
assert_match two_hours + %( cd /serious/path && bundle exec script/runner -e serious 'blahblah'), @output
end
end
class EnvironmentOverwrittenWithoutValueTest < Whenever::TestCase
setup do
@output = Whenever.cron :set => ' environment=', :string => \
<<-file
set :job_template, nil
set :environment, :silly
set :path, '/silly/path'
every 2.hours do
runner "blahblah"
end
file
end
should "output the runner using the original environment" do
assert_match two_hours + %( cd /silly/path && bundle exec script/runner -e silly 'blahblah'), @output
end
end
class PreparingOutputTest < Whenever::TestCase
setup do
File.expects(:exist?).with('config/schedule.rb').returns(true)
end
should "not trim off the top lines of the file" do
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier', :cut => 0)
existing = <<-EXISTING_CRON
# Useless Comments
# at the top of the file
# Begin Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
My whenever job that was already here
# End Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
EXISTING_CRON
assert_equal existing, @command.send(:prepare, existing)
end
should "trim off the top lines of the file" do
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier', :cut => '3')
existing = <<-EXISTING_CRON
# Useless Comments
# at the top of the file
# Begin Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
My whenever job that was already here
# End Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
EXISTING_CRON
new_cron = <<-NEW_CRON
# Begin Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
My whenever job that was already here
# End Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
NEW_CRON
assert_equal new_cron, @command.send(:prepare, existing)
end
should "preserve terminating newlines in files" do
@command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier')
existing = <<-EXISTING_CRON
# Begin Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
My whenever job that was already here
# End Whenever generated tasks for: My identifier at: 2017-02-24 16:21:30 +0100
# A non-Whenever task
My non-whenever job that was already here
EXISTING_CRON
assert_equal existing, @command.send(:prepare, existing)
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/functional/output_at_test.rb | test/functional/output_at_test.rb | require 'test_helper'
class OutputAtTest < Whenever::TestCase
test "weekday at a (single) given time" do
output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => '5:02am' do
command "blahblah"
end
file
assert_match '2 5 * * 1-5 blahblah', output
end
test "weekday at a multiple diverse times, via an array" do
output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => %w(5:02am 3:52pm) do
command "blahblah"
end
file
assert_match '2 5 * * 1-5 blahblah', output
assert_match '52 15 * * 1-5 blahblah', output
end
test "weekday at a multiple diverse times, comma separated" do
output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => '5:02am, 3:52pm' do
command "blahblah"
end
file
assert_match '2 5 * * 1-5 blahblah', output
assert_match '52 15 * * 1-5 blahblah', output
end
test "weekday at a multiple aligned times" do
output = Whenever.cron \
<<-file
set :job_template, nil
every "weekday", :at => '5:02am, 3:02pm' do
command "blahblah"
end
file
assert_match '2 5,15 * * 1-5 blahblah', output
end
test "various days at a various aligned times" do
output = Whenever.cron \
<<-file
set :job_template, nil
every "mon,wed,fri", :at => '5:02am, 3:02pm' do
command "blahblah"
end
file
assert_match '2 5,15 * * 1,3,5 blahblah', output
end
test "various days at a various aligned times using a runner" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/your/path'
every "mon,wed,fri", :at => '5:02am, 3:02pm' do
runner "Worker.perform_async(1.day.ago)"
end
file
assert_match %(2 5,15 * * 1,3,5 cd /your/path && bundle exec script/runner -e production 'Worker.perform_async(1.day.ago)'), output
end
test "various days at a various aligned times using a rake task" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/your/path'
every "mon,wed,fri", :at => '5:02am, 3:02pm' do
rake "blah:blah"
end
file
assert_match '2 5,15 * * 1,3,5 cd /your/path && RAILS_ENV=production bundle exec rake blah:blah --silent', output
end
test "A command every 1.month at very diverse times" do
output = Whenever.cron \
<<-file
set :job_template, nil
every [1.month, 1.day], :at => 'january 5:02am, june 17th at 2:22pm, june 3rd at 3:33am' do
command "blahblah"
end
file
# The 1.month commands
assert_match '2 5 1 * * blahblah', output
assert_match '22 14 17 * * blahblah', output
assert_match '33 3 3 * * blahblah', output
# The 1.day commands
assert_match '2 5 * * * blahblah', output
assert_match '22 14 * * * blahblah', output
assert_match '33 3 * * * blahblah', output
end
test "Multiple commands output every :reboot" do
output = Whenever.cron \
<<-file
set :job_template, nil
every :reboot do
command "command_1"
command "command_2"
end
file
assert_match "@reboot command_1", output
assert_match "@reboot command_2", output
end
test "Many different job types output every :day" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :path, '/your/path'
every :daily do
rake "blah:blah"
runner "runner_1"
command "command_1"
runner "runner_2"
command "command_2"
end
file
assert_match '@daily cd /your/path && RAILS_ENV=production bundle exec rake blah:blah --silent', output
assert_match %(@daily cd /your/path && bundle exec script/runner -e production 'runner_1'), output
assert_match '@daily command_1', output
assert_match %(@daily cd /your/path && bundle exec script/runner -e production 'runner_2'), output
assert_match '@daily command_2', output
end
test "every 5 minutes but but starting at 1" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 5.minutes, :at => 1 do
command "blahblah"
end
file
assert_match '1,6,11,16,21,26,31,36,41,46,51,56 * * * * blahblah', output
end
test "every 4 minutes but starting at 2" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 4.minutes, :at => 2 do
command "blahblah"
end
file
assert_match '2,6,10,14,18,22,26,30,34,38,42,46,50,54,58 * * * * blahblah', output
end
test "every 3 minutes but starting at 7" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 3.minutes, :at => 7 do
command "blahblah"
end
file
assert_match '7,10,13,16,19,22,25,28,31,34,37,40,43,46,49,52,55,58 * * * * blahblah', output
end
test "every 2 minutes but starting at 27" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.minutes, :at => 27 do
command "blahblah"
end
file
assert_match '27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59 * * * * blahblah', output
end
test "using raw cron syntax" do
output = Whenever.cron \
<<-file
set :job_template, nil
every '0 0 27,31 * *' do
command "blahblah"
end
file
assert_match '0 0 27,31 * * blahblah', output
end
test "using custom Chronic configuration to specify time using 24 hour clock" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :chronic_options, :hours24 => true
every 1.day, :at => '03:00' do
command "blahblah"
end
file
assert_match '0 3 * * * blahblah', output
end
test "using custom Chronic configuration to specify date using little endian preference" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :chronic_options, :endian_precedence => :little
every 1.month, :at => '02/03 10:15' do
command "blahblah"
end
file
assert_match '15 10 2 * * blahblah', output
end
test "using custom Chronic configuration to specify time using 24 hour clock and date using little endian preference" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :chronic_options, :hours24 => true, :endian_precedence => :little
every 1.month, :at => '01/02 04:30' do
command "blahblah"
end
file
assert_match '30 4 1 * * blahblah', output
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/functional/output_defined_job_test.rb | test/functional/output_defined_job_test.rb | require 'test_helper'
class OutputDefinedJobTest < Whenever::TestCase
test "defined job with a :task" do
output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after"
every 2.hours do
some_job "during"
end
file
assert_match(/^.+ .+ .+ .+ before during after$/, output)
end
test "defined job with a :task and some options" do
output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after :option1 :option2"
every 2.hours do
some_job "during", :option1 => 'happy', :option2 => 'birthday'
end
file
assert_match(/^.+ .+ .+ .+ before during after happy birthday$/, output)
end
test "defined job with a :task and an option where the option is set globally" do
output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after :option1"
set :option1, 'happy'
every 2.hours do
some_job "during"
end
file
assert_match(/^.+ .+ .+ .+ before during after happy$/, output)
end
test "defined job with a :task and an option where the option is set globally and locally" do
output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after :option1"
set :option1, 'global'
every 2.hours do
some_job "during", :option1 => 'local'
end
file
assert_match(/^.+ .+ .+ .+ before during after local$/, output)
end
test "defined job with a :task and an option where the option is set globally and on the group" do
output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after :option1"
set :option1, 'global'
every 2.hours, :option1 => 'group' do
some_job "during"
end
file
assert_match(/^.+ .+ .+ .+ before during after group$/, output)
end
test "defined job with a :task and an option where the option is set globally, on the group, and locally" do
output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after :option1"
set :option1, 'global'
every 2.hours, :option1 => 'group' do
some_job "during", :option1 => 'local'
end
file
assert_match(/^.+ .+ .+ .+ before during after local$/, output)
end
test "defined job with a :task and an option that is not set" do
output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "before :task after :option1"
every 2.hours do
some_job "during", :option2 => 'happy'
end
file
assert_match(/^.+ .+ .+ .+ before during after :option1$/, output)
end
test "defined job that uses a :path where none is explicitly set" do
Whenever.stubs(:path).returns('/my/path')
output = Whenever.cron \
<<-file
set :job_template, nil
job_type :some_job, "cd :path && :task"
every 2.hours do
some_job 'blahblah'
end
file
assert_match two_hours + %( cd /my/path && blahblah), output
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/functional/output_jobs_for_roles_test.rb | test/functional/output_jobs_for_roles_test.rb | require 'test_helper'
class OutputJobsForRolesTest < Whenever::TestCase
test "one role requested and specified on the job" do
output = Whenever.cron :roles => [:role1], :string => \
<<-file
every 2.hours, :roles => [:role1] do
command "blahblah"
end
file
assert_equal two_hours + " /bin/bash -l -c 'blahblah'\n\n", output
end
test "one role requested but none specified on the job" do
output = Whenever.cron :roles => [:role1], :string => \
<<-file
every 2.hours do
command "blahblah"
end
file
# this should output the job because not specifying a role means "all roles"
assert_equal two_hours + " /bin/bash -l -c 'blahblah'\n\n", output
end
test "no roles requested but one specified on the job" do
output = Whenever.cron \
<<-file
every 2.hours, :roles => [:role1] do
command "blahblah"
end
file
# this should output the job because not requesting roles means "all roles"
assert_equal two_hours + " /bin/bash -l -c 'blahblah'\n\n", output
end
test "a different role requested than the one specified on the job" do
output = Whenever.cron :roles => [:role1], :string => \
<<-file
every 2.hours, :roles => [:role2] do
command "blahblah"
end
file
assert_equal "", output
end
test "with 2 roles requested and a job defined for each" do
output = Whenever.cron :roles => [:role1, :role2], :string => \
<<-file
every 2.hours, :roles => [:role1] do
command "role1_cmd"
end
every :hour, :roles => [:role2] do
command "role2_cmd"
end
file
assert_match two_hours + " /bin/bash -l -c 'role1_cmd'", output
assert_match "0 * * * * /bin/bash -l -c 'role2_cmd'", output
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/functional/output_env_test.rb | test/functional/output_env_test.rb | require 'test_helper'
class OutputEnvTest < Whenever::TestCase
setup do
@output = Whenever.cron \
<<-file
env :MYVAR, 'blah'
env 'MAILTO', "someone@example.com"
env :BLANKVAR, ''
env :NILVAR, nil
file
end
should "output MYVAR environment variable" do
assert_match "MYVAR=blah", @output
end
should "output MAILTO environment variable" do
assert_match "MAILTO=someone@example.com", @output
end
should "output BLANKVAR environment variable" do
assert_match "BLANKVAR=\"\"", @output
end
should "output NILVAR environment variable" do
assert_match "NILVAR=\"\"", @output
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/functional/output_redirection_test.rb | test/functional/output_redirection_test.rb | require 'test_helper'
class OutputRedirectionTest < Whenever::TestCase
test "command when the output is set to nil" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :output, nil
every 2.hours do
command "blahblah"
end
file
assert_match(/^.+ .+ .+ .+ blahblah >> \/dev\/null 2>&1$/, output)
end
test "command when the output is set" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah"
end
file
assert_match(/^.+ .+ .+ .+ blahblah >> logfile.log 2>&1$/, output)
end
test "command when the error and standard output is set by the command" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:standard => 'dev_null', :error => 'dev_err'}
end
file
assert_match(/^.+ .+ .+ .+ blahblah >> dev_null 2>> dev_err$/, output)
end
test "command when the output is set and the comand overrides it" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah", :output => 'otherlog.log'
end
file
assert_no_match(/.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, output)
assert_match(/^.+ .+ .+ .+ blahblah >> otherlog.log 2>&1$/, output)
end
test "command when the output is set and the comand overrides with standard and error" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah", :output => {:error => 'dev_err', :standard => 'dev_null' }
end
file
assert_no_match(/.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, output)
assert_match(/^.+ .+ .+ .+ blahblah >> dev_null 2>> dev_err$/, output)
end
test "command when the output is set and the comand rejects it" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah", :output => false
end
file
assert_no_match(/.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, output)
assert_match(/^.+ .+ .+ .+ blahblah$/, output)
end
test "command when the output is set and is overridden by the :set option" do
output = Whenever.cron :set => 'output=otherlog.log', :string => \
<<-file
set :job_template, nil
set :output, 'logfile.log'
every 2.hours do
command "blahblah"
end
file
assert_no_match(/.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, output)
assert_match(/^.+ .+ .+ .+ blahblah >> otherlog.log 2>&1/, output)
end
test "command when the error and standard output is set" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :output, {:error => 'dev_err', :standard => 'dev_null' }
every 2.hours do
command "blahblah"
end
file
assert_match(/^.+ .+ .+ .+ blahblah >> dev_null 2>> dev_err$/, output)
end
test "command when error output is set" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :output, {:error => 'dev_null'}
every 2.hours do
command "blahblah"
end
file
assert_match(/^.+ .+ .+ .+ blahblah 2>> dev_null$/, output)
end
test "command when the standard output is set" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :output, {:standard => 'dev_out'}
every 2.hours do
command "blahblah"
end
file
assert_match(/^.+ .+ .+ .+ blahblah >> dev_out$/, output)
end
test "command when error output is set by the command" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => 'dev_err'}
end
file
assert_match(/^.+ .+ .+ .+ blahblah 2>> dev_err$/, output)
end
test "command when standard output is set by the command" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:standard => 'dev_out'}
end
file
assert_match(/^.+ .+ .+ .+ blahblah >> dev_out$/, output)
end
test "command when standard output is set to nil" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:standard => nil}
end
file
assert_match(/^.+ .+ .+ .+ blahblah > \/dev\/null$/, output)
end
test "command when standard error is set to nil" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => nil}
end
file
assert_match(/^.+ .+ .+ .+ blahblah 2> \/dev\/null$/, output)
end
test "command when standard output and standard error is set to nil" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => nil, :standard => nil}
end
file
assert_match(/^.+ .+ .+ .+ blahblah > \/dev\/null 2>&1$/, output)
end
test "command when standard output is set and standard error is set to nil" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => nil, :standard => 'my.log'}
end
file
assert_match(/^.+ .+ .+ .+ blahblah >> my.log 2> \/dev\/null$/, output)
end
test "command when standard output is nil and standard error is set" do
output = Whenever.cron \
<<-file
set :job_template, nil
every 2.hours do
command "blahblah", :output => {:error => 'my_error.log', :standard => nil}
end
file
assert_match(/^.+ .+ .+ .+ blahblah >> \/dev\/null 2>> my_error.log$/, output)
end
test "command when the deprecated :cron_log is set" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :cron_log, "cron.log"
every 2.hours do
command "blahblah"
end
file
assert_match(/^.+ .+ .+ .+ blahblah >> cron.log 2>&1$/, output)
end
test "a command when the standard output is set to a lambda" do
output = Whenever.cron \
<<-file
set :job_template, nil
set :output, lambda { "2>&1 | logger -t whenever_cron" }
every 2.hours do
command "blahblah"
end
file
assert_match(/^.+ .+ .+ .+ blahblah 2>&1 | logger -t whenever_cron$/, output)
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/test/functional/output_jobs_with_mailto_test.rb | test/functional/output_jobs_with_mailto_test.rb | require 'test_helper'
class OutputJobsWithMailtoTest < Whenever::TestCase
test "defined job with a mailto argument" do
output = Whenever.cron \
<<-file
every 2.hours do
command "blahblah", mailto: 'someone@example.com'
end
file
output_without_empty_line = lines_without_empty_line(output.lines)
assert_equal 'MAILTO=someone@example.com', output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah'", output_without_empty_line.shift
end
test "defined job with every method's block and a mailto argument" do
output = Whenever.cron \
<<-file
every 2.hours, mailto: 'someone@example.com' do
command "blahblah"
end
file
output_without_empty_line = lines_without_empty_line(output.lines)
assert_equal 'MAILTO=someone@example.com', output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah'", output_without_empty_line.shift
end
test "defined job which overrided mailto argument in the block" do
output = Whenever.cron \
<<-file
every 2.hours, mailto: 'of_the_block@example.com' do
command "blahblah", mailto: 'overrided_in_the_block@example.com'
end
file
output_without_empty_line = lines_without_empty_line(output.lines)
assert_equal 'MAILTO=overrided_in_the_block@example.com', output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah'", output_without_empty_line.shift
end
test "defined some jobs with various mailto argument" do
output = Whenever.cron \
<<-file
every 2.hours do
command "blahblah"
end
every 2.hours, mailto: 'john@example.com' do
command "blahblah_of_john"
command "blahblah2_of_john"
end
every 2.hours, mailto: 'sarah@example.com' do
command "blahblah_of_sarah"
end
every 2.hours do
command "blahblah_of_martin", mailto: 'martin@example.com'
command "blahblah2_of_sarah", mailto: 'sarah@example.com'
end
every 2.hours do
command "blahblah2"
end
file
output_without_empty_line = lines_without_empty_line(output.lines)
assert_equal two_hours + " /bin/bash -l -c 'blahblah'", output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah2'", output_without_empty_line.shift
assert_equal 'MAILTO=john@example.com', output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah_of_john'", output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah2_of_john'", output_without_empty_line.shift
assert_equal 'MAILTO=sarah@example.com', output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah_of_sarah'", output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah2_of_sarah'", output_without_empty_line.shift
assert_equal 'MAILTO=martin@example.com', output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah_of_martin'", output_without_empty_line.shift
end
test "defined some jobs with no mailto argument jobs and mailto argument jobs(no mailto jobs should be first line of cron output" do
output = Whenever.cron \
<<-file
every 2.hours, mailto: 'john@example.com' do
command "blahblah_of_john"
command "blahblah2_of_john"
end
every 2.hours do
command "blahblah"
end
file
output_without_empty_line = lines_without_empty_line(output.lines)
assert_equal two_hours + " /bin/bash -l -c 'blahblah'", output_without_empty_line.shift
assert_equal 'MAILTO=john@example.com', output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah_of_john'", output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah2_of_john'", output_without_empty_line.shift
end
test "defined some jobs with environment mailto define and various mailto argument" do
output = Whenever.cron \
<<-file
env 'MAILTO', 'default@example.com'
every 2.hours do
command "blahblah"
end
every 2.hours, mailto: 'sarah@example.com' do
command "blahblah_by_sarah"
end
every 2.hours do
command "blahblah_by_john", mailto: 'john@example.com'
end
every 2.hours do
command "blahblah2"
end
file
output_without_empty_line = lines_without_empty_line(output.lines)
assert_equal 'MAILTO=default@example.com', output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah'", output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah2'", output_without_empty_line.shift
assert_equal 'MAILTO=sarah@example.com', output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah_by_sarah'", output_without_empty_line.shift
assert_equal 'MAILTO=john@example.com', output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah_by_john'", output_without_empty_line.shift
end
end
class OutputJobsWithMailtoForRolesTest < Whenever::TestCase
test "one role requested and specified on the job with mailto argument" do
output = Whenever.cron roles: [:role1], :string => \
<<-file
env 'MAILTO', 'default@example.com'
every 2.hours, :roles => [:role1] do
command "blahblah"
end
every 2.hours, mailto: 'sarah@example.com', :roles => [:role2] do
command "blahblah_by_sarah"
end
file
output_without_empty_line = lines_without_empty_line(output.lines)
assert_equal 'MAILTO=default@example.com', output_without_empty_line.shift
assert_equal two_hours + " /bin/bash -l -c 'blahblah'", output_without_empty_line.shift
assert_nil output_without_empty_line.shift
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever.rb | lib/whenever.rb | require "whenever/version"
require 'whenever/numeric'
require 'whenever/numeric_seconds'
require 'whenever/job_list'
require 'whenever/job'
require 'whenever/command_line'
require 'whenever/cron'
require 'whenever/output_redirection'
require 'whenever/os'
module Whenever
def self.cron(options)
Whenever::JobList.new(options).generate_cron_output
end
def self.seconds(number, units)
Whenever::NumericSeconds.seconds(number, units)
end
def self.path
Dir.pwd
end
def self.bin_rails?
File.exist?(File.join(path, 'bin', 'rails'))
end
def self.script_rails?
File.exist?(File.join(path, 'script', 'rails'))
end
def self.bundler?
File.exist?(File.join(path, 'Gemfile'))
end
def self.update_cron options
o = { 'update' => true, 'console' => false}
o.merge! options if options
Whenever::CommandLine.execute o
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/cron.rb | lib/whenever/cron.rb | require 'chronic'
module Whenever
module Output
class Cron
DAYS = %w(sun mon tue wed thu fri sat)
MONTHS = %w(jan feb mar apr may jun jul aug sep oct nov dec)
KEYWORDS = [:reboot, :yearly, :annually, :monthly, :weekly, :daily, :midnight, :hourly]
REGEX = /^(@(#{KEYWORDS.join '|'})|((\*?[\d\/,\-]*)\s){3}(\*?([\d\/,\-]|(#{MONTHS.join '|'}))*\s)(\*?([\d\/,\-]|(#{DAYS.join '|'}))*))$/i
attr_accessor :time, :task
def initialize(time = nil, task = nil, at = nil, options = {})
chronic_options = options[:chronic_options] || {}
@at_given = at
@time = time
@task = task
@at = at.is_a?(String) ? (Chronic.parse(at, chronic_options) || 0) : (at || 0)
end
def self.enumerate(item, detect_cron = true)
if item and item.is_a?(String)
items =
if detect_cron && item =~ REGEX
[item]
else
item.split(',')
end
else
items = item
items = [items] unless items and items.respond_to?(:each)
end
items
end
def self.output(times, job, options = {})
enumerate(times).each do |time|
enumerate(job.at, false).each do |at|
yield new(time, job.output, at, options).output
end
end
end
def output
[time_in_cron_syntax, task].compact.join(' ').strip
end
def time_in_cron_syntax
@time = @time.to_i if @time.is_a?(Numeric) # Compatibility with `1.day` format using ruby 2.3 and activesupport
case @time
when REGEX then @time # raw cron syntax given
when Symbol then parse_symbol
when String then parse_as_string
else parse_time
end
end
protected
def day_given?
@at_given.is_a?(String) && (MONTHS.any? { |m| @at_given.downcase.index(m) } || @at_given[/\d\/\d/])
end
def parse_symbol
shortcut = case @time
when *KEYWORDS then "@#{@time}" # :reboot => '@reboot'
when :year then Whenever.seconds(1, :year)
when :day then Whenever.seconds(1, :day)
when :month then Whenever.seconds(1, :month)
when :week then Whenever.seconds(1, :week)
when :hour then Whenever.seconds(1, :hour)
when :minute then Whenever.seconds(1, :minute)
end
if shortcut.is_a?(Numeric)
@time = shortcut
parse_time
elsif shortcut
if @at.is_a?(Time) || (@at.is_a?(Numeric) && @at > 0)
raise ArgumentError, "You cannot specify an ':at' when using the shortcuts for times."
else
return shortcut
end
else
parse_as_string
end
end
def parse_time
timing = Array.new(5, '*')
case @time
when Whenever.seconds(0, :seconds)...Whenever.seconds(1, :minute)
raise ArgumentError, "Time must be in minutes or higher"
when Whenever.seconds(1, :minute)...Whenever.seconds(1, :hour)
minute_frequency = @time / 60
timing[0] = comma_separated_timing(minute_frequency, 59, @at || 0)
when Whenever.seconds(1, :hour)...Whenever.seconds(1, :day)
hour_frequency = (@time / 60 / 60).round
timing[0] = @at.is_a?(Time) ? @at.min : range_or_integer(@at, 0..59, 'Minute')
timing[1] = comma_separated_timing(hour_frequency, 23)
when Whenever.seconds(1, :day)...Whenever.seconds(1, :month)
day_frequency = (@time / 24 / 60 / 60).round
timing[0] = @at.is_a?(Time) ? @at.min : 0
timing[1] = @at.is_a?(Time) ? @at.hour : range_or_integer(@at, 0..23, 'Hour')
timing[2] = comma_separated_timing(day_frequency, 31, 1)
when Whenever.seconds(1, :month)...Whenever.seconds(1, :year)
month_frequency = (@time / 30 / 24 / 60 / 60).round
timing[0] = @at.is_a?(Time) ? @at.min : 0
timing[1] = @at.is_a?(Time) ? @at.hour : 0
timing[2] = if @at.is_a?(Time)
day_given? ? @at.day : 1
else
@at == 0 ? 1 : range_or_integer(@at, 1..31, 'Day')
end
timing[3] = comma_separated_timing(month_frequency, 12, 1)
when Whenever.seconds(1, :year)
timing[0] = @at.is_a?(Time) ? @at.min : 0
timing[1] = @at.is_a?(Time) ? @at.hour : 0
timing[2] = if @at.is_a?(Time)
day_given? ? @at.day : 1
else
1
end
timing[3] = if @at.is_a?(Time)
day_given? ? @at.month : 1
else
@at == 0 ? 1 : range_or_integer(@at, 1..12, 'Month')
end
else
return parse_as_string
end
timing.join(' ')
end
def parse_as_string
return unless @time
string = @time.to_s
timing = Array.new(4, '*')
timing[0] = @at.is_a?(Time) ? @at.min : 0
timing[1] = @at.is_a?(Time) ? @at.hour : 0
return (timing << '1-5') * " " if string.downcase.index('weekday')
return (timing << '6,0') * " " if string.downcase.index('weekend')
DAYS.each_with_index do |day, i|
return (timing << i) * " " if string.downcase.index(day)
end
raise ArgumentError, "Couldn't parse: #{@time.inspect}"
end
def range_or_integer(at, valid_range, name)
must_be_between = "#{name} must be between #{valid_range.min}-#{valid_range.max}"
if at.is_a?(Range)
raise ArgumentError, "#{must_be_between}, #{at.min} given" unless valid_range.include?(at.min)
raise ArgumentError, "#{must_be_between}, #{at.max} given" unless valid_range.include?(at.max)
return "#{at.min}-#{at.max}"
end
raise ArgumentError, "#{must_be_between}, #{at} given" unless valid_range.include?(at)
at
end
def comma_separated_timing(frequency, max, start = 0)
return start if frequency.nil? || frequency == "" || frequency.zero?
return '*' if frequency == 1
return frequency if frequency > (max * 0.5).ceil
original_start = start
start += frequency unless (max + 1).modulo(frequency).zero? || start > 0
output = (start..max).step(frequency).to_a
max_occurances = (max.to_f / (frequency.to_f)).round
max_occurances += 1 if original_start.zero?
output[0, max_occurances].join(',')
end
end
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/version.rb | lib/whenever/version.rb | module Whenever
VERSION = '1.1.1'
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/setup.rb | lib/whenever/setup.rb | # Environment variable defaults to RAILS_ENV
set :environment_variable, "RAILS_ENV"
# Environment defaults to the value of RAILS_ENV in the current environment if
# it's set or production otherwise
set :environment, ENV.fetch("RAILS_ENV", "production")
# Path defaults to the directory `whenever` was run from
set :path, Whenever.path
# Custom Chronic configuration for time parsing, empty by default
# Full list of options at: https://github.com/mojombo/chronic/blob/master/lib/chronic/parser.rb
set :chronic_options, {}
# All jobs are wrapped in this template.
# http://blog.scoutapp.com/articles/2010/09/07/rvm-and-cron-in-production
set :job_template, "/bin/bash -l -c ':job'"
set :runner_command, case
when Whenever.bin_rails?
"bin/rails runner"
when Whenever.script_rails?
"script/rails runner"
else
"script/runner"
end
set :bundle_command, Whenever.bundler? ? "bundle exec" : ""
job_type :command, ":task :output"
job_type :rake, "cd :path && :environment_variable=:environment :bundle_command rake :task --silent :output"
job_type :script, "cd :path && :environment_variable=:environment :bundle_command script/:task :output"
job_type :runner, "cd :path && :bundle_command :runner_command -e :environment ':task' :output"
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/capistrano.rb | lib/whenever/capistrano.rb | require 'capistrano/version'
if defined?(Capistrano::VERSION) && Gem::Version.new(Capistrano::VERSION).release >= Gem::Version.new('3.0.0')
load File.expand_path("../capistrano/v3/tasks/whenever.rake", __FILE__)
else
require 'whenever/capistrano/v2/hooks'
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/numeric_seconds.rb | lib/whenever/numeric_seconds.rb | module Whenever
class NumericSeconds
attr_reader :number
def self.seconds(number, units)
new(number).send(units)
end
def initialize(number)
@number = number.to_i
end
def seconds
number
end
alias :second :seconds
def minutes
number * 60
end
alias :minute :minutes
def hours
number * 3_600
end
alias :hour :hours
def days
number * 86_400
end
alias :day :days
def weeks
number * 604_800
end
alias :week :weeks
def months
number * 2_592_000
end
alias :month :months
def years
number * 31_557_600
end
alias :year :years
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/os.rb | lib/whenever/os.rb | module Whenever
module OS
def self.solaris?
(/solaris/ =~ RUBY_PLATFORM)
end
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/output_redirection.rb | lib/whenever/output_redirection.rb | module Whenever
module Output
class Redirection
def initialize(output)
@output = output
end
def to_s
return '' unless defined?(@output)
case @output
when String then redirect_from_string
when Hash then redirect_from_hash
when NilClass then ">> /dev/null 2>&1"
when Proc then @output.call
else ''
end
end
protected
def stdout
return unless @output.has_key?(:standard)
@output[:standard].nil? ? '/dev/null' : @output[:standard]
end
def stderr
return unless @output.has_key?(:error)
@output[:error].nil? ? '/dev/null' : @output[:error]
end
def redirect_from_hash
case
when stdout == '/dev/null' && stderr == '/dev/null'
"> /dev/null 2>&1"
when stdout && stderr == '/dev/null'
">> #{stdout} 2> /dev/null"
when stdout && stderr
">> #{stdout} 2>> #{stderr}"
when stderr == '/dev/null'
"2> /dev/null"
when stderr
"2>> #{stderr}"
when stdout == '/dev/null'
"> /dev/null"
when stdout
">> #{stdout}"
else
''
end
end
def redirect_from_string
">> #{@output} 2>&1"
end
end
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/command_line.rb | lib/whenever/command_line.rb | require 'fileutils'
module Whenever
class CommandLine
def self.execute(options={})
new(options).run
end
def initialize(options={})
@options = options
@options[:crontab_command] ||= 'crontab'
@options[:file] ||= 'config/schedule.rb'
@options[:cut] ||= 0
@options[:identifier] ||= default_identifier
@options[:console] = true if @options[:console].nil?
if !File.exist?(@options[:file]) && @options[:clear].nil?
warn("[fail] Can't find file: #{@options[:file]}")
return_or_exit(false)
end
if [@options[:update], @options[:write], @options[:clear]].compact.length > 1
warn("[fail] Can only update, write or clear. Choose one.")
return_or_exit(false)
end
unless @options[:cut].to_s =~ /[0-9]*/
warn("[fail] Can't cut negative lines from the crontab #{options[:cut]}")
return_or_exit(false)
end
@options[:cut] = @options[:cut].to_i
@timestamp = Time.now.to_s
end
def run
if @options[:update] || @options[:clear]
write_crontab(updated_crontab)
elsif @options[:write]
write_crontab(whenever_cron)
else
puts Whenever.cron(@options)
puts "## [message] Above is your schedule file converted to cron syntax; your crontab file was not updated."
puts "## [message] Run `whenever --help' for more options."
return_or_exit(true)
end
end
protected
def default_identifier
File.expand_path(@options[:file])
end
def whenever_cron
return '' if @options[:clear]
@whenever_cron ||= [comment_open, Whenever.cron(@options), comment_close].compact.join("\n") + "\n"
end
def read_crontab
return @current_crontab if instance_variable_defined?(:@current_crontab)
command = [@options[:crontab_command]]
command << '-l'
command << "-u #{@options[:user]}" if @options[:user]
command_results = %x[#{command.join(' ')} 2> /dev/null]
@current_crontab = $?.exitstatus.zero? ? prepare(command_results) : ''
end
def write_crontab(contents)
command = [@options[:crontab_command]]
command << "-u #{@options[:user]}" if @options[:user]
# Solaris/SmartOS cron does not support the - option to read from stdin.
command << "-" unless OS.solaris?
IO.popen(command.join(' '), 'r+') do |crontab|
crontab.write(contents)
crontab.close_write
stdout = crontab.read
puts stdout unless stdout == ''
end
success = $?.exitstatus.zero?
if success
action = 'written' if @options[:write]
action = 'updated' if @options[:update]
puts "[write] crontab file #{action}"
return_or_exit(true)
else
warn "[fail] Couldn't write crontab; try running `whenever' with no options to ensure your schedule file is valid."
return_or_exit(false)
end
end
def updated_crontab
# Check for unopened or unclosed identifier blocks
if read_crontab =~ Regexp.new("^#{comment_open_regex}\s*$") && (read_crontab =~ Regexp.new("^#{comment_close_regex}\s*$")).nil?
warn "[fail] Unclosed indentifier; Your crontab file contains '#{comment_open(false)}', but no '#{comment_close(false)}'"
return_or_exit(false)
elsif (read_crontab =~ Regexp.new("^#{comment_open_regex}\s*$")).nil? && read_crontab =~ Regexp.new("^#{comment_close_regex}\s*$")
warn "[fail] Unopened indentifier; Your crontab file contains '#{comment_close(false)}', but no '#{comment_open(false)}'"
return_or_exit(false)
end
# If an existing identifier block is found, replace it with the new cron entries
if read_crontab =~ Regexp.new("^#{comment_open_regex}\s*$") && read_crontab =~ Regexp.new("^#{comment_close_regex}\s*$")
# If the existing crontab file contains backslashes they get lost going through gsub.
# .gsub('\\', '\\\\\\') preserves them. Go figure.
read_crontab.gsub(Regexp.new("^#{comment_open_regex}\s*$.+^#{comment_close_regex}\s*$", Regexp::MULTILINE), whenever_cron.chomp.gsub('\\', '\\\\\\'))
else # Otherwise, append the new cron entries after any existing ones
[read_crontab, whenever_cron].join("\n\n")
end.gsub(/\n{3,}/, "\n\n") # More than two newlines becomes just two.
end
def prepare(contents)
# Strip n lines from the top of the file as specified by the :cut option.
# Use split with a -1 limit option to ensure the join is able to rebuild
# the file with all of the original seperators in-tact.
stripped_contents = contents.split($/,-1)[@options[:cut]..-1].join($/)
# Some cron implementations require all non-comment lines to be newline-
# terminated. (issue #95) Strip all newlines and replace with the default
# platform record seperator ($/)
stripped_contents.gsub!(/\s+$/, $/)
end
def comment_base(include_timestamp = true)
if include_timestamp
"Whenever generated tasks for: #{@options[:identifier]} at: #{@timestamp}"
else
"Whenever generated tasks for: #{@options[:identifier]}"
end
end
def comment_open(include_timestamp = true)
"# Begin #{comment_base(include_timestamp)}"
end
def comment_close(include_timestamp = true)
"# End #{comment_base(include_timestamp)}"
end
def comment_open_regex
"#{comment_open(false)}(#{timestamp_regex}|)"
end
def comment_close_regex
"#{comment_close(false)}(#{timestamp_regex}|)"
end
def timestamp_regex
" at: \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2} ([+-]\\d{4}|UTC)"
end
private
def return_or_exit success
result = 1
result = 0 if success
if @options[:console]
exit(result)
else
result
end
end
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/job_list.rb | lib/whenever/job_list.rb | module Whenever
class JobList
attr_reader :roles
def initialize(options)
@jobs, @env, @set_variables, @pre_set_variables = {}, {}, {}, {}
if options.is_a? String
options = { :string => options }
end
pre_set(options[:set])
@roles = options[:roles] || []
setup_file = File.expand_path('../setup.rb', __FILE__)
setup = File.read(setup_file)
schedule = if options[:string]
options[:string]
elsif options[:file]
File.read(options[:file])
end
instance_eval(setup, setup_file)
instance_eval(schedule, options[:file] || '<eval>')
end
def set(variable, value)
variable = variable.to_sym
return if @pre_set_variables[variable]
instance_variable_set("@#{variable}".to_sym, value)
@set_variables[variable] = value
end
def method_missing(name, *args, &block)
@set_variables.has_key?(name) ? @set_variables[name] : super
end
def respond_to?(name, include_private = false)
@set_variables.has_key?(name) || super
end
def env(variable, value)
@env[variable.to_s] = value
end
def every(frequency, options = {})
@current_time_scope = frequency
@options = options
yield
end
def job_type(name, template)
singleton_class.class_eval do
define_method(name) do |task, *args|
options = { :task => task, :template => template }
options.merge!(args[0]) if args[0].is_a? Hash
options[:mailto] ||= @options.fetch(:mailto, :default_mailto)
# :cron_log was an old option for output redirection, it remains for backwards compatibility
options[:output] = (options[:cron_log] || @cron_log) if defined?(@cron_log) || options.has_key?(:cron_log)
# :output is the newer, more flexible option.
options[:output] = @output if defined?(@output) && !options.has_key?(:output)
@jobs[options.fetch(:mailto)] ||= {}
@jobs[options.fetch(:mailto)][@current_time_scope] ||= []
@jobs[options.fetch(:mailto)][@current_time_scope] << Whenever::Job.new(@set_variables.merge(@options).merge(options))
end
end
end
def generate_cron_output
[environment_variables, cron_jobs].compact.join
end
private
#
# Takes a string like: "variable1=something&variable2=somethingelse"
# and breaks it into variable/value pairs. Used for setting variables at runtime from the command line.
# Only works for setting values as strings.
#
def pre_set(variable_string = nil)
return if variable_string.nil? || variable_string == ""
pairs = variable_string.split('&')
pairs.each do |pair|
next unless pair.index('=')
variable, value = *pair.split('=')
unless variable.nil? || variable == "" || value.nil? || value == ""
variable = variable.strip.to_sym
set(variable, value.strip)
@pre_set_variables[variable] = value
end
end
end
def environment_variables
return if @env.empty?
output = []
@env.each do |key, val|
output << "#{key}=#{val.nil? || val == "" ? '""' : val}\n"
end
output << "\n"
output.join
end
#
# Takes the standard cron output that Whenever generates and finds
# similar entries that can be combined. For example: If a job should run
# at 3:02am and 4:02am, instead of creating two jobs this method combines
# them into one that runs on the 2nd minute at the 3rd and 4th hour.
#
def combine(entries)
entries.map! { |entry| entry.split(/ +/, 6) }
0.upto(4) do |f|
(entries.length-1).downto(1) do |i|
next if entries[i][f] == '*'
comparison = entries[i][0...f] + entries[i][f+1..-1]
(i-1).downto(0) do |j|
next if entries[j][f] == '*'
if comparison == entries[j][0...f] + entries[j][f+1..-1]
entries[j][f] += ',' + entries[i][f]
entries.delete_at(i)
break
end
end
end
end
entries.map { |entry| entry.join(' ') }
end
def cron_jobs_of_time(time, jobs)
shortcut_jobs, regular_jobs = [], []
jobs.each do |job|
next unless roles.empty? || roles.any? do |r|
job.has_role?(r)
end
Whenever::Output::Cron.output(time, job, :chronic_options => @chronic_options) do |cron|
cron << "\n\n"
if cron[0,1] == "@"
shortcut_jobs << cron
else
regular_jobs << cron
end
end
end
shortcut_jobs.join + combine(regular_jobs).join
end
def cron_jobs
return if @jobs.empty?
output = []
# jobs with default mailto's must be output before the ones with non-default mailto's.
@jobs.delete(:default_mailto) { Hash.new }.each do |time, jobs|
output << cron_jobs_of_time(time, jobs)
end
@jobs.each do |mailto, time_and_jobs|
output_jobs = []
time_and_jobs.each do |time, jobs|
output_jobs << cron_jobs_of_time(time, jobs)
end
output_jobs.reject! { |output_job| output_job.empty? }
output << "MAILTO=#{mailto}\n\n" unless output_jobs.empty?
output << output_jobs
end
output.join
end
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/job.rb | lib/whenever/job.rb | require 'shellwords'
module Whenever
class Job
attr_reader :at, :roles, :mailto
def initialize(options = {})
@options = options
@at = options.delete(:at)
@template = options.delete(:template)
@mailto = options.fetch(:mailto, :default_mailto)
@job_template = options.delete(:job_template) || ":job"
@roles = Array(options.delete(:roles))
@options[:output] = options.has_key?(:output) ? Whenever::Output::Redirection.new(options[:output]).to_s : ''
@options[:environment_variable] ||= "RAILS_ENV"
@options[:environment] ||= :production
@options[:path] = Shellwords.shellescape(@options[:path] || Whenever.path)
end
def output
job = process_template(@template, @options)
out = process_template(@job_template, @options.merge(:job => job))
out.gsub(/%/, '\%')
end
def has_role?(role)
roles.empty? || roles.include?(role)
end
protected
def process_template(template, options)
template.gsub(/:\w+/) do |key|
before_and_after = [$`[-1..-1], $'[0..0]]
option = options[key.sub(':', '').to_sym] || key
if before_and_after.all? { |c| c == "'" }
escape_single_quotes(option)
elsif before_and_after.all? { |c| c == '"' }
escape_double_quotes(option)
else
option
end
end.gsub(/\s+/m, " ").strip
end
def escape_single_quotes(str)
str.gsub(/'/) { "'\\''" }
end
def escape_double_quotes(str)
str.gsub(/"/) { '\"' }
end
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/numeric.rb | lib/whenever/numeric.rb | Numeric.class_eval do
def respond_to?(method, include_private = false)
super || Whenever::NumericSeconds.public_method_defined?(method)
end
def method_missing(method, *args, &block)
if Whenever::NumericSeconds.public_method_defined?(method)
Whenever::NumericSeconds.new(self).send(method)
else
super
end
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/capistrano/v2/hooks.rb | lib/whenever/capistrano/v2/hooks.rb | require "whenever/capistrano/v2/recipes"
Capistrano::Configuration.instance(:must_exist).load do
# Write the new cron jobs near the end.
before "deploy:finalize_update", "whenever:update_crontab"
# If anything goes wrong, undo.
after "deploy:rollback", "whenever:update_crontab"
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/capistrano/v2/recipes.rb | lib/whenever/capistrano/v2/recipes.rb | require 'whenever/capistrano/v2/support'
Capistrano::Configuration.instance(:must_exist).load do
Whenever::CapistranoSupport.load_into(self)
_cset(:whenever_roles) { :db }
_cset(:whenever_options) { {:roles => fetch(:whenever_roles)} }
_cset(:whenever_command) { "whenever" }
_cset(:whenever_identifier) { fetch :application }
_cset(:whenever_environment) { fetch :rails_env, fetch(:stage, "production") }
_cset(:whenever_variables) { "environment=#{fetch :whenever_environment}" }
_cset(:whenever_update_flags) { "--update-crontab #{fetch :whenever_identifier} --set #{fetch :whenever_variables}" }
_cset(:whenever_clear_flags) { "--clear-crontab #{fetch :whenever_identifier}" }
_cset(:whenever_path) { fetch :latest_release }
namespace :whenever do
desc "Update application's crontab entries using Whenever"
task :update_crontab do
args = {
:command => fetch(:whenever_command),
:flags => fetch(:whenever_update_flags),
:path => fetch(:whenever_path)
}
if whenever_servers.any?
args = whenever_prepare_for_rollback(args) if task_call_frames[0].task.fully_qualified_name == 'deploy:rollback'
whenever_run_commands(args)
on_rollback do
args = whenever_prepare_for_rollback(args)
whenever_run_commands(args)
end
end
end
desc "Clear application's crontab entries using Whenever"
task :clear_crontab do
if whenever_servers.any?
args = {
:command => fetch(:whenever_command),
:flags => fetch(:whenever_clear_flags),
:path => fetch(:whenever_path)
}
whenever_run_commands(args)
end
end
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
javan/whenever | https://github.com/javan/whenever/blob/19daf02f970272ef8ce165cac8a58a7656d77b8a/lib/whenever/capistrano/v2/support.rb | lib/whenever/capistrano/v2/support.rb | module Whenever
module CapistranoSupport
def self.load_into(capistrano_configuration)
capistrano_configuration.load do
def whenever_options
fetch(:whenever_options)
end
def whenever_roles
Array(whenever_options[:roles])
end
def whenever_servers
find_servers(whenever_options)
end
def whenever_server_roles
whenever_servers.inject({}) do |map, server|
map[server] = role_names_for_host(server) & whenever_roles
map
end
end
def whenever_prepare_for_rollback args
if fetch(:previous_release)
# rollback to the previous release's crontab
args[:path] = fetch(:previous_release)
else
# clear the crontab if no previous release
args[:path] = fetch(:release_path)
args[:flags] = fetch(:whenever_clear_flags)
end
args
end
def whenever_run_commands(args)
unless [:command, :path, :flags].all? { |a| args.include?(a) }
raise ArgumentError, ":command, :path, & :flags are required"
end
whenever_server_roles.each do |server, roles|
roles_arg = roles.empty? ? "" : " --roles #{roles.join(',')}"
command = "cd #{args[:path]} && #{args[:command]} #{args[:flags]}#{roles_arg}"
run command, whenever_options.merge(:hosts => server)
end
end
end
end
end
end
| ruby | MIT | 19daf02f970272ef8ce165cac8a58a7656d77b8a | 2026-01-04T15:38:49.356492Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/app/helpers/pg_hero/home_helper.rb | app/helpers/pg_hero/home_helper.rb | module PgHero
module HomeHelper
def pghero_pretty_ident(table, schema: nil)
ident = table
if schema && schema != "public"
ident = "#{schema}.#{table}"
end
if /\A[a-z0-9_]+\z/.match?(ident)
ident
else
@database.quote_ident(ident)
end
end
def pghero_js_value(value)
json_escape(value.to_json(root: false)).html_safe
end
def pghero_remove_index(query)
if query[:columns]
columns = query[:columns].map(&:to_sym)
columns = columns.first if columns.size == 1
end
ret = String.new("remove_index #{query[:table].to_sym.inspect}")
ret << ", name: #{(query[:name] || query[:index]).to_s.inspect}"
ret << ", column: #{columns.inspect}" if columns
ret
end
def pghero_formatted_vacuum_times(time)
content_tag(:span, title: pghero_formatted_date_time(time)) do
"#{time_ago_in_words(time, include_seconds: true).sub(/(over|about|almost) /, "").sub("less than", "<")} ago"
end
end
def pghero_formatted_date_time(time)
l time.in_time_zone(@time_zone), format: :long
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/app/controllers/pg_hero/home_controller.rb | app/controllers/pg_hero/home_controller.rb | module PgHero
class HomeController < ActionController::Base
http_basic_authenticate_with name: PgHero.username, password: PgHero.password if PgHero.password
protect_from_forgery with: :exception
before_action :check_api
before_action :set_database
before_action :set_query_stats_enabled
before_action :set_show_details, only: [:index, :queries, :show_query]
before_action :ensure_query_stats, only: [:queries]
if PgHero.config["override_csp"]
# note: this does not take into account asset hosts
# which can be a string with %d or a proc
# https://api.rubyonrails.org/classes/ActionView/Helpers/AssetUrlHelper.html
# users should set CSP manually if needed
# see https://github.com/ankane/pghero/issues/297
after_action do
response.headers["Content-Security-Policy"] = "default-src 'self' 'unsafe-inline'"
end
end
layout "pg_hero/application"
def index
@title = "Overview"
@extended = params[:extended]
if @replica
@replication_lag = @database.replication_lag
@good_replication_lag = @replication_lag ? @replication_lag < 5 : true
else
@inactive_replication_slots = @database.replication_slots.select { |r| !r[:active] }
end
@walsender_queries, long_running_queries = @database.long_running_queries.partition { |q| q[:backend_type] == "walsender" }
@autovacuum_queries, @long_running_queries = long_running_queries.partition { |q| q[:query].starts_with?("autovacuum:") }
connection_states = @database.connection_states
@total_connections = connection_states.values.sum
@idle_connections = connection_states["idle in transaction"].to_i
@good_total_connections = @total_connections < @database.total_connections_threshold
@good_idle_connections = @idle_connections < 100
@transaction_id_danger = @database.transaction_id_danger(threshold: 1500000000)
sequences, @sequences_timeout = rescue_timeout([]) { @database.sequences }
@readable_sequences, @unreadable_sequences = sequences.partition { |s| s[:readable] }
@sequence_danger = @database.sequence_danger(threshold: (params[:sequence_threshold] || 0.9).to_f, sequences: @readable_sequences)
@indexes, @indexes_timeout =
if @sequences_timeout
# skip indexes for faster loading
[[], true]
else
rescue_timeout([]) { @database.indexes }
end
@invalid_indexes = @database.invalid_indexes(indexes: @indexes)
@invalid_constraints = @database.invalid_constraints
@duplicate_indexes = @database.duplicate_indexes(indexes: @indexes)
if @query_stats_enabled
@query_stats = @database.query_stats(historical: true, start_at: 3.hours.ago)
@slow_queries = @database.slow_queries(query_stats: @query_stats)
set_suggested_indexes((params[:min_average_time] || 20).to_f, (params[:min_calls] || 50).to_i)
else
@query_stats_available = @database.query_stats_available?
@query_stats_extension_enabled = @database.query_stats_extension_enabled? if @query_stats_available
@suggested_indexes = []
end
if @extended
@index_hit_rate = @database.index_hit_rate || 0
@table_hit_rate = @database.table_hit_rate || 0
@good_cache_rate = @table_hit_rate >= @database.cache_hit_rate_threshold / 100.0 && @index_hit_rate >= @database.cache_hit_rate_threshold / 100.0
@unused_indexes = @database.unused_indexes(max_scans: 0)
end
@show_migrations = PgHero.show_migrations
end
def space
@title = "Space"
@days = (params[:days] || 7).to_i
@database_size = @database.database_size
@only_tables = params[:tables].present?
@relation_sizes, @sizes_timeout = rescue_timeout([]) { @only_tables ? @database.table_sizes : @database.relation_sizes }
@space_stats_enabled = @database.space_stats_enabled? && !@only_tables
if @space_stats_enabled
space_growth = @database.space_growth(days: @days, relation_sizes: @relation_sizes)
@growth_bytes_by_relation = space_growth.to_h { |r| [[r[:schema], r[:relation]], r[:growth_bytes]] }
if params[:sort] == "growth"
@relation_sizes.sort_by! { |r| s = @growth_bytes_by_relation[[r[:schema], r[:relation]]]; [s ? 0 : 1, -s.to_i, r[:schema], r[:relation]] }
end
end
if params[:sort] == "name"
@relation_sizes.sort_by! { |r| r[:relation] || r[:table] }
end
@header_options = @only_tables ? {tables: "t"} : {}
across = params[:across].to_s.split(",")
@unused_indexes = @database.unused_indexes(max_scans: 0, across: across)
@unused_index_names = Set.new(@unused_indexes.map { |r| r[:index] })
@show_migrations = PgHero.show_migrations
@system_stats_enabled = @database.system_stats_enabled?
@index_bloat = [] # @database.index_bloat
end
def relation_space
@schema = params[:schema] || "public"
@relation = params[:relation]
@title = @relation
relation_space_stats = @database.relation_space_stats(@relation, schema: @schema)
@chart_data = [{name: "Value", data: relation_space_stats.map { |r| [r[:captured_at].change(sec: 0), r[:size_bytes].to_i] }, library: chart_library_options}]
end
def index_bloat
@title = "Index Bloat"
@index_bloat = @database.index_bloat
@show_sql = params[:sql]
end
def live_queries
@title = "Live Queries"
@running_queries = @database.running_queries(all: true)
@vacuum_progress = @database.vacuum_progress.index_by { |q| q[:pid] }
if params[:state]
@running_queries.select! { |q| q[:state] == params[:state] }
end
end
def queries
@title = "Queries"
@sort = %w(average_time calls).include?(params[:sort]) ? params[:sort] : nil
@min_average_time = params[:min_average_time] ? params[:min_average_time].to_i : nil
@min_calls = params[:min_calls] ? params[:min_calls].to_i : nil
if @historical_query_stats_enabled
begin
@start_at = params[:start_at] ? Time.zone.parse(params[:start_at]) : 24.hours.ago
@end_at = Time.zone.parse(params[:end_at]) if params[:end_at]
rescue
@error = true
end
end
@query_stats =
if @historical_query_stats_enabled && !request.xhr?
[]
else
@database.query_stats(
historical: true,
start_at: @start_at,
end_at: @end_at,
sort: @sort,
min_average_time: @min_average_time,
min_calls: @min_calls
)
end
if !@historical_query_stats_enabled || request.xhr?
set_suggested_indexes
else
@debug = params[:debug].present?
end
# fix back button issue with caching
response.headers["Cache-Control"] = "must-revalidate, no-store, no-cache, private"
if request.xhr?
render layout: false, partial: "queries_table", locals: {queries: @query_stats, xhr: true}
end
end
def show_query
@query_hash = params[:query_hash].to_i
@user = params[:user].to_s
@title = @query_hash
stats = @database.query_stats(historical: true, query_hash: @query_hash, start_at: 24.hours.ago).find { |qs| qs[:user] == @user }
if stats
@query = stats[:query]
@explainable_query = stats[:explainable_query]
if @show_details
query_hash_stats = @database.query_hash_stats(@query_hash, user: @user, current: true)
@chart_data = [{name: "Value", data: query_hash_stats.map { |r| [r[:captured_at].change(sec: 0), (r[:total_minutes] * 60 * 1000).round] }, library: chart_library_options}]
@chart2_data = [{name: "Value", data: query_hash_stats.map { |r| [r[:captured_at].change(sec: 0), r[:average_time].round(1)] }, library: chart_library_options}]
@chart3_data = [{name: "Value", data: query_hash_stats.map { |r| [r[:captured_at].change(sec: 0), r[:calls]] }, library: chart_library_options}]
@origins = query_hash_stats.group_by { |r| r[:origin].to_s }.to_h { |k, v| [k, v.size] }
@total_count = query_hash_stats.size
end
@tables = PgQuery.parse(@query).tables rescue []
@tables.sort!
if @tables.any?
@row_counts = @database.table_stats(table: @tables).to_h { |i| [i[:table], i[:estimated_rows]] }
indexes, @indexes_timeout = rescue_timeout([]) { @database.indexes }
@indexes_by_table = indexes.group_by { |i| i[:table] }
end
else
render_text "Unknown query", status: :not_found
end
end
def system
@title = "System"
@periods = {
"1 hour" => {duration: 1.hour, period: 60.seconds},
"1 day" => {duration: 1.day, period: 10.minutes},
"1 week" => {duration: 1.week, period: 30.minutes},
"2 weeks" => {duration: 2.weeks, period: 1.hours}
}
if @database.system_stats_provider == :azure
# doesn't support 10, just 5 and 15
@periods["1 day"][:period] = 15.minutes
end
@duration = (params[:duration] || 1.hour).to_i
@period = (params[:period] || 60.seconds).to_i
if @duration / @period > 1440
render_text "Too many data points", status: :bad_request
elsif @period % 60 != 0
render_text "Period must be a multiple of 60", status: :bad_request
end
end
def cpu_usage
render json: [{name: "CPU", data: @database.cpu_usage(**system_params).map { |k, v| [k, v ? v.round : v] }, library: chart_library_options}]
end
def connection_stats
render json: [{name: "Connections", data: @database.connection_stats(**system_params), library: chart_library_options}]
end
def replication_lag_stats
render json: [{name: "Lag", data: @database.replication_lag_stats(**system_params), library: chart_library_options}]
end
def load_stats
stats =
case @database.system_stats_provider
when :azure
if @database.send(:azure_flexible_server?)
[
{name: "Read IOPS", data: @database.read_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: chart_library_options},
{name: "Write IOPS", data: @database.write_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: chart_library_options}
]
else
[
{name: "IO Consumption", data: @database.azure_stats("io_consumption_percent", **system_params), library: chart_library_options}
]
end
when :gcp
[
{name: "Read Ops", data: @database.read_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: chart_library_options},
{name: "Write Ops", data: @database.write_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: chart_library_options}
]
else
[
{name: "Read IOPS", data: @database.read_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: chart_library_options},
{name: "Write IOPS", data: @database.write_iops_stats(**system_params).map { |k, v| [k, v ? v.round : v] }, library: chart_library_options}
]
end
render json: stats
end
def free_space_stats
render json: [
{name: "Free Space", data: @database.free_space_stats(duration: 14.days, period: 1.hour), library: chart_library_options}
]
end
def explain
unless @explain_enabled
render_text "Explain not enabled", status: :bad_request
return
end
@title = "Explain"
@query = params[:query]
@explain_analyze_enabled = PgHero.explain_mode == "analyze"
# TODO use get + token instead of post so users can share links
# need to prevent CSRF and DoS
if request.post? && @query.present?
begin
generic_plan = @database.server_version_num >= 160000 && @query.include?("$1")
explain_options =
case params[:commit]
when "Analyze"
{analyze: true}
when "Visualize"
if @explain_analyze_enabled && !generic_plan
{analyze: true, costs: true, verbose: true, buffers: true, format: "json"}
else
{costs: true, verbose: true, format: "json"}
end
else
{}
end
explain_options[:generic_plan] = true if generic_plan
if explain_options[:analyze] && !@explain_analyze_enabled
render_text "Explain analyze not enabled", status: :bad_request
return
end
@explanation = @database.explain_v2(@query, **explain_options)
@suggested_index = @database.suggested_indexes(queries: [@query]).first if @database.suggested_indexes_enabled?
@visualize = params[:commit] == "Visualize"
rescue ActiveRecord::StatementInvalid => e
message = e.message
@error =
if message == "Unsafe statement"
"Unsafe statement"
elsif message.start_with?("PG::UndefinedParameter")
"Can't explain queries with bind parameters"
elsif message.include?("EXPLAIN options ANALYZE and GENERIC_PLAN cannot be used together")
"Can't analyze queries with bind parameters"
elsif message.start_with?("PG::SyntaxError")
"Syntax error with query"
elsif message.start_with?("PG::QueryCanceled")
"Query timed out"
else
# default to a generic message
# since data can be extracted through the Postgres error message
"Error explaining query"
end
end
end
end
def tune
@title = "Tune"
@settings = @database.settings
@autovacuum_settings = @database.autovacuum_settings if params[:autovacuum]
end
def connections
@title = "Connections"
connections = @database.connections
@total_connections = connections.count
@connection_sources = group_connections(connections, [:database, :user, :source, :ip])
@connections_by_database = group_connections_by_key(connections, :database)
@connections_by_user = group_connections_by_key(connections, :user)
if params[:security] && @database.server_version_num >= 90500
connections.each do |connection|
connection[:ssl_status] =
if connection[:ssl]
# no way to tell if client used verify-full
# so connection may not be actually secure
"SSL"
else
# variety of reasons for no SSL
if !connection[:database].present?
"Internal Process"
elsif !connection[:ip]
if connection[:state]
"Socket"
else
# tcp or socket, don't have permission to tell
"No SSL"
end
else
# tcp
# could separate out localhost since this should be safe
"No SSL"
end
end
end
@connections_by_ssl_status = group_connections_by_key(connections, :ssl_status)
end
end
def maintenance
@title = "Maintenance"
@maintenance_info = @database.maintenance_info
@time_zone = PgHero.time_zone
@show_dead_rows = params[:dead_rows]
end
def kill
if @database.kill(params[:pid])
redirect_backward notice: "Query killed"
else
redirect_backward notice: "Query no longer running"
end
end
def kill_long_running_queries
@database.kill_long_running_queries
redirect_backward notice: "Queries killed"
end
def kill_all
@database.kill_all
redirect_backward notice: "Connections killed"
end
def enable_query_stats
@database.enable_query_stats
redirect_backward notice: "Query stats enabled"
rescue ActiveRecord::StatementInvalid
redirect_backward alert: "The database user does not have permission to enable query stats"
end
# TODO disable if historical query stats enabled?
def reset_query_stats
success =
if @database.server_version_num >= 120000
@database.reset_query_stats
else
@database.reset_instance_query_stats
end
if success
redirect_backward notice: "Query stats reset"
else
redirect_backward alert: "The database user does not have permission to reset query stats"
end
end
protected
def redirect_backward(**options)
redirect_back fallback_location: root_path, **options
end
def set_database
@databases = PgHero.databases.values
if params[:database]
# don't do direct lookup, since you don't want to call to_sym on user input
@database = @databases.find { |d| d.id == params[:database] }
elsif @databases.size > 1
redirect_to url_for(controller: controller_name, action: action_name, database: @databases.first.id)
else
@database = @databases.first
end
end
def default_url_options
{database: params[:database]}
end
def set_query_stats_enabled
@query_stats_enabled = @database.query_stats_enabled?
@system_stats_enabled = @database.system_stats_enabled?
@replica = @database.replica?
@explain_enabled = PgHero.explain_enabled?
end
def set_suggested_indexes(min_average_time = 0, min_calls = 0)
if @database.suggested_indexes_enabled? && !@indexes
@indexes, @indexes_timeout = rescue_timeout([]) { @database.indexes }
end
@suggested_indexes_by_query =
if !@indexes_timeout && @database.suggested_indexes_enabled?
@database.suggested_indexes_by_query(query_stats: @query_stats.select { |qs| qs[:average_time] >= min_average_time && qs[:calls] >= min_calls }, indexes: @indexes)
else
{}
end
@suggested_indexes = @database.suggested_indexes(suggested_indexes_by_query: @suggested_indexes_by_query)
@query_stats_by_query = @query_stats.index_by { |q| q[:query] }
@debug = params[:debug].present?
end
def system_params
{
duration: params[:duration],
period: params[:period],
series: true
}.delete_if { |_, v| v.nil? }
end
def chart_library_options
{pointRadius: 0, pointHoverRadius: 0, pointHitRadius: 5, borderWidth: 4}
end
def set_show_details
@historical_query_stats_enabled = @query_stats_enabled && @database.historical_query_stats_enabled?
@show_details = @historical_query_stats_enabled && @database.supports_query_hash?
end
def group_connections(connections, keys)
connections
.group_by { |conn| conn.slice(*keys) }
.map { |k, v| k.merge(total_connections: v.count) }
.sort_by { |v| [-v[:total_connections]] + keys.map { |k| v[k].to_s } }
end
def group_connections_by_key(connections, key)
group_connections(connections, [key]).map { |v| [v[key], v[:total_connections]] }.to_h
end
def check_api
if Rails.application.config.try(:api_only)
render_text "No support for Rails API. See https://github.com/pghero/pghero for a standalone app.", status: :internal_server_error
end
end
def render_text(message, status:)
render plain: message, status: status
end
def ensure_query_stats
unless @query_stats_enabled
redirect_to root_path, alert: "Query stats not enabled"
end
end
# rescue QueryCanceled for case when
# statement timeout is less than lock timeout
def rescue_timeout(default)
[yield, false]
rescue ActiveRecord::LockWaitTimeout, ActiveRecord::QueryCanceled
[default, true]
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/query_stats_test.rb | test/query_stats_test.rb | require_relative "test_helper"
class QueryStatsTest < Minitest::Test
def test_query_stats
assert database.query_stats
end
def test_query_stats_available
assert database.query_stats_available?
end
def test_query_stats_enabled
assert database.query_stats_enabled?
end
def test_query_stats_extension_enabled
assert database.query_stats_extension_enabled?
end
def test_query_stats_readable?
assert database.query_stats_readable?
end
def test_enable_query_stats
assert database.disable_query_stats
assert database.enable_query_stats
end
def test_reset_query_stats
skip unless gte12?
assert database.reset_query_stats
end
def test_reset_instance_query_stats
assert database.reset_instance_query_stats
end
def test_reset_instance_query_stats_database
skip unless gte12?
assert database.reset_query_stats
ActiveRecord::Base.connection.select_all("SELECT 1")
assert database.query_stats.any? { |qs| qs[:query] == "SELECT $1" }
assert database.reset_instance_query_stats(database: database.database_name)
assert_equal 1, database.query_stats.size
refute database.query_stats.any? { |qs| qs[:query] == "SELECT $1" }
end
def test_reset_instance_query_stats_database_invalid
skip unless gte12?
error = assert_raises(PgHero::Error) do
database.reset_instance_query_stats(database: "pghero_test2")
end
assert_equal "Database not found: pghero_test2", error.message
end
def test_reset_query_stats_user
skip unless gte12?
assert database.reset_query_stats
ActiveRecord::Base.connection.select_all("SELECT 1")
assert database.query_stats.any? { |qs| qs[:query] == "SELECT $1" }
assert database.reset_query_stats(user: database.current_user)
assert_equal 1, database.query_stats.size
refute database.query_stats.any? { |qs| qs[:query] == "SELECT $1" }
end
def test_reset_query_stats_user_invalid
skip unless gte12?
error = assert_raises(PgHero::Error) do
database.reset_query_stats(user: "postgres2")
end
assert_equal "User not found: postgres2", error.message
end
def test_reset_query_stats_query_hash
skip unless gte12?
assert database.reset_query_stats
ActiveRecord::Base.connection.select_all("SELECT 1")
ActiveRecord::Base.connection.select_all("SELECT 1 + 1")
assert database.query_stats.any? { |qs| qs[:query] == "SELECT $1" }
assert database.query_stats.any? { |qs| qs[:query] == "SELECT $1 + $2" }
query_hash = database.query_stats.find { |qs| qs[:query] == "SELECT $1" }[:query_hash]
assert database.reset_query_stats(query_hash: query_hash)
refute database.query_stats.any? { |qs| qs[:query] == "SELECT $1" }
assert database.query_stats.any? { |qs| qs[:query] == "SELECT $1 + $2" }
end
def test_reset_query_stats_query_hash_invalid
skip unless gte12?
error = assert_raises(PgHero::Error) do
database.reset_query_stats(query_hash: 0)
end
assert_equal "Invalid query hash: 0", error.message
end
def test_historical_query_stats_enabled
assert database.historical_query_stats_enabled?
end
def test_capture_query_stats
PgHero::QueryStats.delete_all
refute PgHero::QueryStats.any?
assert database.capture_query_stats
assert PgHero::QueryStats.any?
assert database.query_stats(historical: true)
end
def test_clean_query_stats
assert database.clean_query_stats
end
def test_slow_queries
assert database.slow_queries
end
def gte12?
database.server_version_num >= 120000
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/maintenance_test.rb | test/maintenance_test.rb | require_relative "test_helper"
class MaintenanceTest < Minitest::Test
def test_transaction_id_danger
assert database.transaction_id_danger(threshold: 10000000000).any?
assert_equal [], database.transaction_id_danger
end
def test_autovacuum_danger
assert_equal [], database.autovacuum_danger
end
def test_vacuum_progress
assert database.vacuum_progress
end
def test_maintenance_info
assert database.maintenance_info.find { |v| v[:table] == "cities" }
end
def test_analyze
assert database.analyze("cities")
end
def test_analyze_tables
assert database.analyze_tables
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/tables_test.rb | test/tables_test.rb | require_relative "test_helper"
class TablesTest < Minitest::Test
def test_table_hit_rate
database.table_hit_rate
assert true
end
def test_table_caching
assert database.table_caching
end
def test_unused_tables
assert database.unused_tables
end
def test_table_stats
assert database.table_stats
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/best_index_test.rb | test/best_index_test.rb | require_relative "test_helper"
class BestIndexTest < Minitest::Test
def test_where
assert_best_index ({table: "users", columns: ["city_id"]}), "SELECT * FROM users WHERE city_id = 1"
end
def test_all_values
index = database.best_index("SELECT * FROM users WHERE login_attempts = 1 ORDER BY created_at")
expected = {
found: true,
structure: {table: "users", where: [{column: "login_attempts", op: "="}], sort: [{column: "created_at", direction: "asc"}]},
index: {table: "users", columns: ["login_attempts", "created_at"]},
rows: 5000,
row_estimates: {"login_attempts (=)" => 167, "created_at (sort)" => 1},
row_progression: [5000, 167, 0]
}
assert_equal expected, index
end
def test_where_multiple_columns
assert_best_index ({table: "users", columns: ["city_id", "login_attempts"]}), "SELECT * FROM users WHERE city_id = 1 and login_attempts = 2"
end
def test_where_unique
assert_best_index ({table: "users", columns: ["email"]}), "SELECT * FROM users WHERE city_id = 1 AND email = 'person2@example.org'"
end
def test_order
assert_best_index ({table: "users", columns: ["created_at"]}), "SELECT * FROM users ORDER BY created_at"
end
def test_order_multiple
assert_best_index ({table: "users", columns: ["login_attempts", "created_at"]}), "SELECT * FROM users ORDER BY login_attempts, created_at"
end
def test_order_multiple_direction
assert_best_index ({table: "users", columns: ["login_attempts"]}), "SELECT * FROM users ORDER BY login_attempts DESC, created_at"
end
def test_order_multiple_unique
assert_best_index ({table: "users", columns: ["id"]}), "SELECT * FROM users ORDER BY id, created_at"
end
def test_where_unique_order
assert_best_index ({table: "users", columns: ["email"]}), "SELECT * FROM users WHERE email = 'person2@example.org' ORDER BY created_at"
end
def test_where_order
assert_best_index ({table: "users", columns: ["login_attempts", "created_at"]}), "SELECT * FROM users WHERE login_attempts = 1 ORDER BY created_at"
end
def test_where_order_unknown
assert_best_index ({table: "users", columns: ["login_attempts"]}), "SELECT * FROM users WHERE login_attempts = 1 ORDER BY NOW()"
end
def test_where_in
assert_best_index ({table: "users", columns: ["city_id"]}), "SELECT * FROM users WHERE city_id IN (1, 2)"
end
def test_like
assert_best_index ({table: "users", columns: ["email gist_trgm_ops"], using: "gist"}), "SELECT * FROM users WHERE email LIKE $1"
end
def test_like_where
assert_best_index ({table: "users", columns: ["city_id"]}), "SELECT * FROM users WHERE city_id = $1 AND email LIKE $2"
end
def test_like_where2
assert_best_index ({table: "users", columns: ["email gist_trgm_ops"], using: "gist"}), "SELECT * FROM users WHERE email LIKE $1 AND active = $2"
end
def test_ilike
assert_best_index ({table: "users", columns: ["email gist_trgm_ops"], using: "gist"}), "SELECT * FROM users WHERE email ILIKE $1"
end
def test_not_equals
assert_best_index ({table: "users", columns: ["login_attempts"]}), "SELECT * FROM users WHERE city_id != $1 and login_attempts = 2"
end
def test_not_in
assert_best_index ({table: "users", columns: ["login_attempts"]}), "SELECT * FROM users WHERE city_id NOT IN ($1) and login_attempts = 2"
end
def test_between
assert_best_index ({table: "users", columns: ["city_id"]}), "SELECT * FROM users WHERE city_id BETWEEN 1 AND 2"
end
def test_multiple_range
assert_best_index ({table: "users", columns: ["city_id"]}), "SELECT * FROM users WHERE city_id > $1 and login_attempts > $2"
end
def test_where_prepared
assert_best_index ({table: "users", columns: ["city_id"]}), "SELECT * FROM users WHERE city_id = $1"
end
def test_where_normalized
assert_best_index ({table: "users", columns: ["city_id"]}), "SELECT * FROM users WHERE city_id = $1"
end
def test_is_null
assert_best_index ({table: "users", columns: ["zip_code"]}), "SELECT * FROM users WHERE zip_code IS NULL"
end
def test_is_null_equal
assert_best_index ({table: "users", columns: ["zip_code", "login_attempts"]}), "SELECT * FROM users WHERE zip_code IS NULL AND login_attempts = $1"
end
def test_is_not_null
assert_best_index ({table: "users", columns: ["login_attempts"]}), "SELECT * FROM users WHERE zip_code IS NOT NULL AND login_attempts = $1"
end
def test_update
assert_best_index ({table: "users", columns: ["city_id"]}), "UPDATE users SET email = 'test' WHERE city_id = 1"
end
def test_delete
assert_best_index ({table: "users", columns: ["city_id"]}), "DELETE FROM users WHERE city_id = 1"
end
def test_parse_error
assert_no_index "Parse error", "SELECT *123'"
end
def test_stats_not_found
assert_no_index "Stats not found", "SELECT * FROM non_existent_table WHERE id = 1"
end
def test_unknown_structure
assert_no_index "Unknown structure", "SELECT NOW()"
end
def test_where_or
assert_no_index "Unknown structure", "SELECT FROM users WHERE login_attempts = 0 OR login_attempts = 1"
end
def test_where_nested_or
assert_no_index "Unknown structure", "SELECT FROM users WHERE city_id = 1 AND (login_attempts = 0 OR login_attempts = 1)"
end
def test_multiple_tables
assert_no_index "JOIN not supported yet", "SELECT * FROM users INNER JOIN cities ON cities.id = users.city_id"
end
def test_no_columns
assert_no_index "No columns to index", "SELECT * FROM users"
end
def test_small_table
assert_no_index "No index needed if less than 500 rows", "SELECT * FROM states WHERE name = 'State 1'"
end
def test_system_table
assert_no_index "System table", "SELECT COUNT(*) AS count FROM pg_extension WHERE extname = $1"
end
def test_insert
assert_no_index "INSERT statement", "INSERT INTO users (login_attempts) VALUES (1)"
end
def test_set
assert_no_index "SET statement", "set client_encoding to 'UTF8'"
end
def test_empty_statement
assert_no_index "Empty statement", nil
end
protected
def assert_best_index(expected, statement)
index = database.best_index(statement)
assert_nil index[:explanation]
assert index[:found]
assert_equal expected, index[:index]
end
def assert_no_index(explanation, statement)
index = database.best_index(statement)
assert !index[:found]
assert_equal explanation, index[:explanation]
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/queries_test.rb | test/queries_test.rb | require_relative "test_helper"
class QueriesTest < Minitest::Test
def test_running_queries
assert database.running_queries
end
def test_filter_data
query = "SELECT pg_sleep(1)"
# TODO manually checkout connection if needed
t = Thread.new { ActiveRecord::Base.connection.execute(query) }
sleep(0.5)
assert_equal query, database.running_queries.first[:query]
with_filter_data do
assert_equal "SELECT pg_sleep($1)", database.running_queries.first[:query]
end
t.join
end
def test_long_running_queries
assert database.long_running_queries
end
def test_blocked_queries
assert database.blocked_queries
end
def with_filter_data
previous_value = PgHero.filter_data
begin
PgHero.filter_data = true
database.remove_instance_variable(:@filter_data)
yield
ensure
PgHero.filter_data = previous_value
database.remove_instance_variable(:@filter_data)
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/query_stats_generator_test.rb | test/query_stats_generator_test.rb | require_relative "test_helper"
require "generators/pghero/query_stats_generator"
class QueryStatsGeneratorTest < Rails::Generators::TestCase
tests Pghero::Generators::QueryStatsGenerator
destination File.expand_path("../tmp", __dir__)
setup :prepare_destination
def test_works
run_generator
assert_migration "db/migrate/create_pghero_query_stats.rb", /create_table :pghero_query_stats/
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/space_test.rb | test/space_test.rb | require_relative "test_helper"
class SpaceTest < Minitest::Test
def test_database_size
assert database.database_size
end
def test_relation_sizes
relation_sizes = database.relation_sizes
assert relation_sizes.find { |r| r[:relation] == "users" && r[:type] == "table" }
assert relation_sizes.find { |r| r[:relation] == "users_pkey" && r[:type] == "index" }
assert relation_sizes.find { |r| r[:relation] == "all_users" && r[:type] == "matview" }
end
def test_table_sizes
assert database.table_sizes
end
def test_space_growth
assert database.space_growth
end
def test_relation_space_stats
assert database.relation_space_stats("cities")
end
def test_capture_space_stats
PgHero::SpaceStats.delete_all
refute PgHero::SpaceStats.any?
assert database.capture_space_stats
assert PgHero::SpaceStats.any?
end
def test_clean_space_stats
assert database.clean_space_stats
end
def test_space_stats_enabled
assert database.space_stats_enabled?
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/replication_test.rb | test/replication_test.rb | require_relative "test_helper"
class ReplicationTest < Minitest::Test
def test_replica
refute database.replica?
end
def test_replication_lag
assert_equal 0, database.replication_lag
end
def test_replication_slots
assert_equal [], database.replication_slots
end
def test_replicating
refute database.replicating?
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/database_test.rb | test/database_test.rb | require_relative "test_helper"
class DatabaseTest < Minitest::Test
def test_id
assert_equal "primary", database.id
end
def test_name
assert_equal "Primary", database.name
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/basic_test.rb | test/basic_test.rb | require_relative "test_helper"
class BasicTest < Minitest::Test
def test_ssl_used?
refute database.ssl_used?
end
def test_database_name
assert_equal "pghero_test", database.database_name
end
def test_server_version
assert_kind_of String, database.server_version
end
def test_server_version_num
assert_kind_of Integer, database.server_version_num
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/indexes_test.rb | test/indexes_test.rb | require_relative "test_helper"
class IndexesTest < Minitest::Test
def test_index_hit_rate
database.index_hit_rate
assert true
end
def test_index_caching
assert database.index_caching
end
def test_index_usage
assert database.index_usage
end
def test_missing_indexes
assert database.missing_indexes
end
def test_unused_indexes
assert database.unused_indexes
end
def test_reset_stats
assert database.reset_stats
end
def test_last_stats_reset_time
database.last_stats_reset_time
assert true
end
def test_invalid_indexes
assert_equal [], database.invalid_indexes
end
def test_indexes
assert database.indexes.find { |i| i[:name] == "cities_pkey" }
end
def test_duplicate_indexes
assert database.duplicate_indexes.find { |i| i[:unneeded_index][:name] == "index_users_on_id" }
end
def test_index_bloat
assert_equal [], database.index_bloat
assert database.index_bloat(min_size: 0).find { |i| i[:index] == "index_users_on_updated_at" }
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/explain_test.rb | test/explain_test.rb | require_relative "test_helper"
class ExplainTest < Minitest::Test
def setup
City.delete_all
end
def test_explain
assert_match "Result", database.explain("SELECT 1")
end
def test_explain_analyze
City.create!
assert_equal 1, City.count
database.explain("ANALYZE DELETE FROM cities")
assert_equal 1, City.count
end
def test_explain_statement_timeout
with_explain_timeout(0.1) do
# raises ActiveRecord::QueryCanceled in Active Record 5.2+
error = assert_raises(ActiveRecord::StatementInvalid) do
database.explain("ANALYZE SELECT pg_sleep(1)")
end
assert_match "canceling statement due to statement timeout", error.message
end
end
def test_explain_multiple_statements
City.create!
assert_raises(ActiveRecord::StatementInvalid) { database.explain("ANALYZE DELETE FROM cities; DELETE FROM cities; COMMIT") }
end
def test_explain_v2
database.explain_v2("SELECT 1")
# not affected by explain option
with_explain(false) do
database.explain_v2("SELECT 1")
end
end
def test_explain_v2_analyze
database.explain_v2("SELECT 1", analyze: true)
error = assert_raises(ActiveRecord::StatementInvalid) do
database.explain_v2("ANALYZE SELECT 1")
end
assert_match 'syntax error at or near "ANALYZE"', error.message
# not affected by explain option
with_explain(true) do
database.explain_v2("SELECT 1", analyze: true)
end
end
def test_explain_v2_generic_plan
assert_raises(ActiveRecord::StatementInvalid) do
database.explain_v2("SELECT $1")
end
if explain_normalized?
assert_match "Result", database.explain_v2("SELECT $1", generic_plan: true)
end
end
def test_explain_v2_format_text
assert_match "Result (cost=", database.explain_v2("SELECT 1", format: "text")
end
def test_explain_v2_format_json
assert_match '"Node Type": "Result"', database.explain_v2("SELECT 1", format: "json")
end
def test_explain_v2_format_xml
assert_match "<Node-Type>Result</Node-Type>", database.explain_v2("SELECT 1", format: "xml")
end
def test_explain_v2_format_yaml
assert_match 'Node Type: "Result"', database.explain_v2("SELECT 1", format: "yaml")
end
def test_explain_v2_format_bad
error = assert_raises(ArgumentError) do
database.explain_v2("SELECT 1", format: "bad")
end
assert_equal "Unknown format", error.message
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/controller_test.rb | test/controller_test.rb | require_relative "test_helper"
class ControllerTest < ActionDispatch::IntegrationTest
def test_index
get pg_hero.root_path
assert_response :success
end
def test_space
get pg_hero.space_path
assert_response :success
end
def test_relation_space
get pg_hero.relation_space_path(relation: "users")
assert_response :success
end
def test_index_bloat
get pg_hero.index_bloat_path
assert_response :success
end
def test_live_queries
get pg_hero.live_queries_path
assert_response :success
end
def test_queries
get pg_hero.queries_path
assert_response :success
end
def test_show_query
get pg_hero.show_query_path(query_hash: 123)
assert_response :not_found
end
def test_system
get pg_hero.system_path
assert_response :success
end
def test_explain
get pg_hero.explain_path
assert_response :success
end
def test_explain_not_enabled
with_explain(false) do
get pg_hero.explain_path
end
assert_response :bad_request
assert_match "Explain not enabled", response.body
end
def test_explain_only
post pg_hero.explain_path, params: {query: "SELECT 1"}
assert_response :success
assert_match "Result (cost=0.00..0.01 rows=1 width=4)", response.body
refute_match(/Planning Time/i, response.body)
refute_match(/Execution Time/i, response.body)
end
def test_explain_only_normalized
post pg_hero.explain_path, params: {query: "SELECT $1"}
assert_response :success
if explain_normalized?
assert_match "Result (cost=0.00..0.01 rows=1 width=32)", response.body
refute_match(/Planning Time/i, response.body)
refute_match(/Execution Time/i, response.body)
else
assert_match "Can't explain queries with bind parameters", response.body
end
end
def test_explain_only_not_enabled
with_explain(false) do
post pg_hero.explain_path, params: {query: "SELECT 1"}
end
assert_response :bad_request
assert_match "Explain not enabled", response.body
end
def test_explain_only_analyze
post pg_hero.explain_path, params: {query: "ANALYZE SELECT 1"}
assert_response :success
assert_match "Syntax error with query", response.body
refute_match(/Planning Time/i, response.body)
refute_match(/Execution Time/i, response.body)
end
def test_explain_analyze
with_explain("analyze") do
post pg_hero.explain_path, params: {query: "SELECT 1", commit: "Analyze"}
end
assert_response :success
assert_match "(actual time=", response.body
assert_match(/Planning Time/i, response.body)
assert_match(/Execution Time/i, response.body)
end
def test_explain_analyze_normalized
with_explain("analyze") do
post pg_hero.explain_path, params: {query: "SELECT $1", commit: "Analyze"}
end
assert_response :success
if explain_normalized?
assert_match "Can't analyze queries with bind parameters", response.body
else
assert_match "Can't explain queries with bind parameters", response.body
end
end
def test_explain_analyze_timeout
with_explain("analyze") do
with_explain_timeout(0.01) do
post pg_hero.explain_path, params: {query: "SELECT pg_sleep(1)", commit: "Analyze"}
end
end
assert_response :success
assert_match "Query timed out", response.body
end
def test_explain_analyze_not_enabled
post pg_hero.explain_path, params: {query: "SELECT 1", commit: "Analyze"}
assert_response :bad_request
assert_match "Explain analyze not enabled", response.body
end
def test_explain_visualize
post pg_hero.explain_path, params: {query: "SELECT 1", commit: "Visualize"}
assert_response :success
assert_match "https://tatiyants.com/pev/#/plans/new", response.body
assert_match ""Node Type": "Result"", response.body
refute_match "Actual Total Time", response.body
end
def test_explain_visualize_analyze
with_explain("analyze") do
post pg_hero.explain_path, params: {query: "SELECT 1", commit: "Visualize"}
end
assert_response :success
assert_match "https://tatiyants.com/pev/#/plans/new", response.body
assert_match ""Node Type": "Result"", response.body
assert_match "Actual Total Time", response.body
end
def test_explain_visualize_normalized
with_explain("analyze") do
post pg_hero.explain_path, params: {query: "SELECT $1", commit: "Visualize"}
end
assert_response :success
if explain_normalized?
assert_match "https://tatiyants.com/pev/#/plans/new", response.body
assert_match ""Node Type": "Result"", response.body
refute_match "Actual Total Time", response.body
else
assert_match "Can't explain queries with bind parameters", response.body
end
end
def test_tune
get pg_hero.tune_path
assert_response :success
end
def test_connections
get pg_hero.connections_path
assert_response :success
end
def test_maintenance
get pg_hero.maintenance_path
assert_response :success
end
# prevent warning for now
# def test_kill
# post pg_hero.kill_path(pid: 1_000_000_000)
# assert_redirected_to "/"
# end
def test_reset_query_stats
post pg_hero.reset_query_stats_path
assert_redirected_to "/"
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/sequences_test.rb | test/sequences_test.rb | require_relative "test_helper"
class SequencesTest < Minitest::Test
def test_sequences
seq = database.sequences.find { |s| s[:sequence] == "cities_id_seq" }
assert_equal "public", seq[:table_schema]
assert_equal "cities", seq[:table]
assert_equal "id", seq[:column]
assert_equal "bigint", seq[:column_type]
assert_equal 9223372036854775807, seq[:max_value]
assert_equal "public", seq[:schema]
assert_equal "cities_id_seq", seq[:sequence]
assert_equal true, seq[:readable]
end
def test_sequences_last_value
last_value = database.sequences.to_h { |s| [s[:sequence], s[:last_value]] }
assert_equal 50, last_value["states_id_seq"]
assert_equal 5000, last_value["users_id_seq"]
end
def test_sequence_danger
assert_equal [], database.sequence_danger
assert database.sequence_danger(threshold: 0).find { |s| s[:sequence] == "cities_id_seq" }
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/test_helper.rb | test/test_helper.rb | require "bundler/setup"
require "combustion"
Bundler.require(:default)
require "minitest/autorun"
class Minitest::Test
def database
@database ||= PgHero.databases[:primary]
end
def with_explain(value)
PgHero.config.merge!({"explain" => value})
yield
ensure
PgHero.remove_instance_variable(:@config)
end
def with_explain_timeout(value)
previous_value = PgHero.explain_timeout_sec
begin
PgHero.explain_timeout_sec = value
yield
ensure
PgHero.explain_timeout_sec = previous_value
end
end
def explain_normalized?
database.server_version_num >= 160000
end
end
logger = ActiveSupport::Logger.new(ENV["VERBOSE"] ? STDERR : nil)
Combustion.path = "test/internal"
Combustion.initialize! :active_record, :action_controller do
config.load_defaults Rails::VERSION::STRING.to_f
config.action_controller.logger = logger
config.active_record.logger = logger
end
class City < ActiveRecord::Base
end
class State < ActiveRecord::Base
end
class User < ActiveRecord::Base
end
states =
50.times.map do |i|
{
name: "State #{i}"
}
end
State.insert_all!(states)
ActiveRecord::Base.connection.execute("ANALYZE states")
users =
5000.times.map do |i|
city_id = i % 100
{
city_id: city_id,
email: "person#{i}@example.org",
login_attempts: rand(30),
zip_code: i % 40 == 0 ? nil : "12345",
active: true,
country: "Test #{rand(30)}",
tree_path: "path#{rand(30)}",
range: (0..rand(5)),
metadata: {favorite_color: "red"},
created_at: Time.now - i.seconds,
updated_at: Time.now - i.seconds
}
end
User.insert_all!(users)
ActiveRecord::Base.connection.execute("ANALYZE users")
ActiveRecord::Base.connection.execute("CREATE MATERIALIZED VIEW all_users AS SELECT * FROM users")
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/space_stats_generator_test.rb | test/space_stats_generator_test.rb | require_relative "test_helper"
require "generators/pghero/space_stats_generator"
class SpaceStatsGeneratorTest < Rails::Generators::TestCase
tests Pghero::Generators::SpaceStatsGenerator
destination File.expand_path("../tmp", __dir__)
setup :prepare_destination
def test_works
run_generator
assert_migration "db/migrate/create_pghero_space_stats.rb", /create_table :pghero_space_stats/
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/system_test.rb | test/system_test.rb | require_relative "test_helper"
class SystemTest < Minitest::Test
def test_system_stats_enabled
refute database.system_stats_enabled?
end
def test_system_stats_provider
assert_nil database.system_stats_provider
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/connections_test.rb | test/connections_test.rb | require_relative "test_helper"
class ConnectionsTest < Minitest::Test
def test_connections
assert_kind_of Array, database.connections
end
def test_total_connections
assert_kind_of Integer, database.total_connections
end
def test_connection_states
assert_kind_of Hash, database.connection_states
end
def test_connection_sources
assert_kind_of Array, database.connection_sources
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/config_generator_test.rb | test/config_generator_test.rb | require_relative "test_helper"
require "generators/pghero/config_generator"
class ConfigGeneratorTest < Rails::Generators::TestCase
tests Pghero::Generators::ConfigGenerator
destination File.expand_path("../tmp", __dir__)
setup :prepare_destination
def test_works
run_generator
assert_file "config/pghero.yml", /databases/
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/users_test.rb | test/users_test.rb | require_relative "test_helper"
class UsersTest < Minitest::Test
def teardown
database.drop_user(user)
end
def test_create_user
database.create_user(user)
end
def test_create_user_tables
database.create_user(user, tables: ["cities"])
end
def user
"pghero_test_user"
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/constraints_test.rb | test/constraints_test.rb | require_relative "test_helper"
class ConstraintsTest < Minitest::Test
def test_invalid_constraints
assert_equal [], database.invalid_constraints
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/settings_test.rb | test/settings_test.rb | require_relative "test_helper"
class SettingsTest < Minitest::Test
def test_settings
assert database.settings[:max_connections]
end
def test_autovacuum_settings
assert_equal "on", database.autovacuum_settings[:autovacuum]
end
def test_vacuum_settings
assert database.vacuum_settings[:vacuum_cost_limit]
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/module_test.rb | test/module_test.rb | require_relative "test_helper"
class ModuleTest < Minitest::Test
def test_databases
assert PgHero.databases.any?
end
def test_connection_pool
1000.times do
[:@config, :@databases].each do |var|
PgHero.remove_instance_variable(var) if PgHero.instance_variable_defined?(var)
end
threads =
2.times.map do
Thread.new do
PgHero.databases[:primary].instance_variable_get(:@connection_model)
end
end
values = threads.map(&:value)
assert_same values.first, values.last
refute_nil values.first
end
end
def test_analyze_all
assert PgHero.analyze_all
end
def test_clean_query_stats
assert PgHero.clean_query_stats
end
def test_clean_space_stats
assert PgHero.clean_space_stats
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/kill_test.rb | test/kill_test.rb | require_relative "test_helper"
class KillTest < Minitest::Test
def test_kill
# prevent warning for now
# refute database.kill(1_000_000_000)
end
def test_kill_long_running_queries
assert database.kill_long_running_queries
end
def test_kill_all
# skip for now
# assert database.kill_all
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/suggested_indexes_test.rb | test/suggested_indexes_test.rb | require_relative "test_helper"
class SuggestedIndexesTest < Minitest::Test
def setup
if database.server_version_num >= 120000
database.reset_query_stats
else
database.reset_instance_query_stats
end
end
def test_suggested_indexes_enabled
assert database.suggested_indexes_enabled?
end
def test_basic
User.where(email: "person1@example.org").first
assert_equal [{table: "users", columns: ["email"]}], database.suggested_indexes.map { |q| q.except(:queries, :details) }
end
def test_existing_index
User.where("updated_at > ?", Time.now).to_a
assert_equal [], database.suggested_indexes.map { |q| q.except(:queries, :details) }
end
def test_primary_key
query = "SELECT * FROM users WHERE id = 1"
result = database.suggested_indexes_by_query(queries: [query])[query]
assert_equal ["id"], result[:covering_index]
end
def test_hash
query = "SELECT * FROM users WHERE login_attempts = 1"
result = database.suggested_indexes_by_query(queries: [query])[query]
assert_equal ["login_attempts"], result[:covering_index]
end
def test_hash_multiple_values
query = "SELECT * FROM users WHERE login_attempts IN (1, 2)"
result = database.suggested_indexes_by_query(queries: [query])[query]
assert_equal ["login_attempts"], result[:covering_index]
end
def test_hash_greater_than
query = "SELECT * FROM users WHERE login_attempts > 1"
result = database.suggested_indexes_by_query(queries: [query])[query]
assert_nil result[:covering_index]
end
def test_gist_trgm
query = "SELECT * FROM users WHERE country = 'Test 1'"
result = database.suggested_indexes_by_query(queries: [query])[query]
assert_nil result[:covering_index]
end
def test_ltree
query = "SELECT * FROM users WHERE tree_path = 'path1'"
result = database.suggested_indexes_by_query(queries: [query])[query]
assert_equal ["tree_path"], result[:covering_index]
end
def test_range
query = "SELECT * FROM users WHERE range = '[0, 0]'"
result = database.suggested_indexes_by_query(queries: [query])[query]
assert_equal ["range"], result[:covering_index]
end
def test_inet
query = "SELECT * FROM users WHERE last_known_ip = '127.0.0.1'"
result = database.suggested_indexes_by_query(queries: [query])[query]
assert_equal ["last_known_ip inet_ops"], result[:covering_index]
end
def test_inet_greater_than
query = "SELECT * FROM users WHERE last_known_ip > '127.0.0.1'"
result = database.suggested_indexes_by_query(queries: [query])[query]
assert_equal ["last_known_ip inet_ops"], result[:covering_index]
end
def test_brin
query = "SELECT * FROM users WHERE created_at = NOW()"
result = database.suggested_indexes_by_query(queries: [query])[query]
assert_equal ["created_at"], result[:covering_index]
end
def test_brin_order
query = "SELECT * FROM users ORDER BY created_at LIMIT 1"
result = database.suggested_indexes_by_query(queries: [query])[query]
assert_nil result[:covering_index]
end
def test_gin
query = "SELECT * FROM users WHERE metadata = '{}'::jsonb"
result = database.suggested_indexes_by_query(queries: [query])[query]
assert_nil result[:covering_index]
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/internal/db/schema.rb | test/internal/db/schema.rb | ActiveRecord::Schema.define do
enable_extension "pg_stat_statements"
enable_extension "pg_trgm"
enable_extension "ltree"
create_table :pghero_query_stats, force: true do |t|
t.text :database
t.text :user
t.text :query
t.integer :query_hash, limit: 8
t.float :total_time
t.integer :calls, limit: 8
t.timestamp :captured_at
t.index [:database, :captured_at]
end
create_table :pghero_space_stats, force: true do |t|
t.text :database
t.text :schema
t.text :relation
t.integer :size, limit: 8
t.timestamp :captured_at
t.index [:database, :captured_at]
end
create_table :cities, force: true do |t|
t.string :name
end
create_table :states, force: true do |t|
t.string :name
end
create_table :users, force: :cascade do |t|
t.integer :city_id
t.integer :login_attempts
t.string :email
t.string :zip_code
t.boolean :active
t.string :country
t.column :tree_path, :ltree
t.column :range, :int4range
t.column :last_known_ip, :inet
t.column :metadata, :jsonb
t.timestamp :created_at
t.timestamp :updated_at
t.index :id # duplicate index
t.index :updated_at
t.index :login_attempts, using: :hash
t.index "country gist_trgm_ops", using: :gist
t.index :tree_path, using: :gist
t.index :range, using: :gist
t.index :created_at, using: :brin
t.index "last_known_ip inet_ops", using: :gist
t.index :metadata, using: :gin
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/test/internal/config/routes.rb | test/internal/config/routes.rb | Rails.application.routes.draw do
mount PgHero::Engine, at: "/"
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero.rb | lib/pghero.rb | # dependencies
require "active_support"
# stdlib
require "forwardable"
# methods
require_relative "pghero/methods/basic"
require_relative "pghero/methods/connections"
require_relative "pghero/methods/constraints"
require_relative "pghero/methods/explain"
require_relative "pghero/methods/indexes"
require_relative "pghero/methods/kill"
require_relative "pghero/methods/maintenance"
require_relative "pghero/methods/queries"
require_relative "pghero/methods/query_stats"
require_relative "pghero/methods/replication"
require_relative "pghero/methods/sequences"
require_relative "pghero/methods/settings"
require_relative "pghero/methods/space"
require_relative "pghero/methods/suggested_indexes"
require_relative "pghero/methods/system"
require_relative "pghero/methods/tables"
require_relative "pghero/methods/users"
require_relative "pghero/database"
require_relative "pghero/engine" if defined?(Rails)
require_relative "pghero/version"
module PgHero
autoload :Connection, "pghero/connection"
autoload :Stats, "pghero/stats"
autoload :QueryStats, "pghero/query_stats"
autoload :SpaceStats, "pghero/space_stats"
class Error < StandardError; end
class NotEnabled < Error; end
MUTEX = Mutex.new
# settings
class << self
attr_accessor :long_running_query_sec, :slow_query_ms, :slow_query_calls, :explain_timeout_sec, :total_connections_threshold, :cache_hit_rate_threshold, :env, :show_migrations, :config_path, :filter_data
end
self.long_running_query_sec = (ENV["PGHERO_LONG_RUNNING_QUERY_SEC"] || 60).to_i
self.slow_query_ms = (ENV["PGHERO_SLOW_QUERY_MS"] || 20).to_i
self.slow_query_calls = (ENV["PGHERO_SLOW_QUERY_CALLS"] || 100).to_i
self.explain_timeout_sec = (ENV["PGHERO_EXPLAIN_TIMEOUT_SEC"] || 10).to_f
self.total_connections_threshold = (ENV["PGHERO_TOTAL_CONNECTIONS_THRESHOLD"] || 500).to_i
self.cache_hit_rate_threshold = 99
self.env = ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"
self.show_migrations = true
self.config_path = ENV["PGHERO_CONFIG_PATH"] || "config/pghero.yml"
self.filter_data = ENV["PGHERO_FILTER_DATA"].to_s.size > 0
class << self
extend Forwardable
def_delegators :primary_database, :aws_access_key_id, :analyze, :analyze_tables, :autoindex, :autovacuum_danger,
:best_index, :blocked_queries, :connections, :connection_sources, :connection_states, :connection_stats,
:cpu_usage, :create_user, :database_size, :aws_db_instance_identifier, :disable_query_stats, :drop_user,
:duplicate_indexes, :enable_query_stats, :explain, :historical_query_stats_enabled?, :index_caching,
:index_hit_rate, :index_usage, :indexes, :invalid_constraints, :invalid_indexes, :kill, :kill_all, :kill_long_running_queries,
:last_stats_reset_time, :long_running_queries, :maintenance_info, :missing_indexes, :query_stats,
:query_stats_available?, :query_stats_enabled?, :query_stats_extension_enabled?, :query_stats_readable?,
:rds_stats, :read_iops_stats, :aws_region, :relation_sizes, :replica?, :replication_lag, :replication_lag_stats,
:reset_query_stats, :reset_stats, :running_queries, :aws_secret_access_key, :sequence_danger, :sequences, :settings,
:slow_queries, :space_growth, :ssl_used?, :suggested_indexes, :suggested_indexes_by_query,
:suggested_indexes_enabled?, :system_stats_enabled?, :table_caching, :table_hit_rate, :table_stats,
:total_connections, :transaction_id_danger, :unused_indexes, :unused_tables, :write_iops_stats
def time_zone=(time_zone)
@time_zone = time_zone.is_a?(ActiveSupport::TimeZone) ? time_zone : ActiveSupport::TimeZone[time_zone.to_s]
end
def time_zone
@time_zone || Time.zone
end
# use method instead of attr_accessor to ensure
# this works if variable set after PgHero is loaded
def username
@username ||= (file_config || {})["username"] || ENV["PGHERO_USERNAME"]
end
# use method instead of attr_accessor to ensure
# this works if variable set after PgHero is loaded
def password
@password ||= (file_config || {})["password"] || ENV["PGHERO_PASSWORD"]
end
# config pattern for https://github.com/ankane/pghero/issues/424
def stats_database_url
@stats_database_url ||= (file_config || {})["stats_database_url"] || ENV["PGHERO_STATS_DATABASE_URL"]
end
# private
def explain_enabled?
explain_mode.nil? || explain_mode == true || explain_mode == "analyze"
end
# private
def explain_mode
@config["explain"]
end
def visualize_url
@visualize_url ||= config["visualize_url"] || ENV["PGHERO_VISUALIZE_URL"] || "https://tatiyants.com/pev/#/plans/new"
end
def config
@config ||= file_config || default_config
end
# private
def file_config
unless defined?(@file_config)
require "erb"
require "yaml"
path = config_path
config_file_exists = File.exist?(path)
config = YAML.safe_load(ERB.new(File.read(path)).result, aliases: true) if config_file_exists
config ||= {}
@file_config =
if config[env]
config[env]
elsif config["databases"] # preferred format
config
elsif config_file_exists
raise "Invalid config file"
else
nil
end
end
@file_config
end
# private
def default_config
databases = {}
unless ENV["PGHERO_DATABASE_URL"]
ActiveRecord::Base.configurations.configs_for(env_name: env, include_replicas_key => true).each do |db|
databases[db.send(spec_name_key)] = {"spec" => db.send(spec_name_key)}
end
end
if databases.empty?
databases["primary"] = {
"url" => ENV["PGHERO_DATABASE_URL"]
}
end
if databases.size == 1
databases.values.first.merge!(
"aws_db_instance_identifier" => ENV["PGHERO_DB_INSTANCE_IDENTIFIER"],
"gcp_database_id" => ENV["PGHERO_GCP_DATABASE_ID"],
"azure_resource_id" => ENV["PGHERO_AZURE_RESOURCE_ID"]
)
end
{
"databases" => databases
}
end
# ensure we only have one copy of databases
# so there's only one connection pool per database
def databases
unless defined?(@databases)
# only use mutex on initialization
MUTEX.synchronize do
# return if another process initialized while we were waiting
return @databases if defined?(@databases)
@databases = config["databases"].map { |id, c| [id.to_sym, Database.new(id, c)] }.to_h
end
end
@databases
end
def primary_database
databases.values.first
end
def capture_query_stats(verbose: false)
each_database do |database|
next unless database.capture_query_stats?
puts "Capturing query stats for #{database.id}..." if verbose
database.capture_query_stats(raise_errors: true)
end
end
def capture_space_stats(verbose: false)
each_database do |database|
puts "Capturing space stats for #{database.id}..." if verbose
database.capture_space_stats
end
end
def analyze_all(**options)
each_database do |database|
next if database.replica?
database.analyze_tables(**options)
end
end
def autoindex_all(create: false, verbose: true)
each_database do |database|
puts "Autoindexing #{database.id}..." if verbose
database.autoindex(create: create)
end
end
def pretty_size(value)
ActiveSupport::NumberHelper.number_to_human_size(value, precision: 3)
end
# delete previous stats
# go database by database to use an index
# stats for old databases are not cleaned up since we can't use an index
def clean_query_stats(before: nil)
each_database do |database|
database.clean_query_stats(before: before)
end
end
def clean_space_stats(before: nil)
each_database do |database|
database.clean_space_stats(before: before)
end
end
# private
def connection_config(model)
model.connection_db_config.configuration_hash
end
# private
def spec_name_key
:name
end
# private
def include_replicas_key
:include_hidden
end
private
def each_database
first_error = nil
databases.each do |_, database|
begin
yield database
rescue => e
puts "#{e.class.name}: #{e.message}"
puts
first_error ||= e
end
end
raise first_error if first_error
true
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/generators/pghero/space_stats_generator.rb | lib/generators/pghero/space_stats_generator.rb | require "rails/generators"
require "rails/generators/active_record"
module Pghero
module Generators
class SpaceStatsGenerator < Rails::Generators::Base
include ActiveRecord::Generators::Migration
source_root File.join(__dir__, "templates")
def copy_migration
migration_template "space_stats.rb", "db/migrate/create_pghero_space_stats.rb", migration_version: migration_version
end
def migration_version
"[#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}]"
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/generators/pghero/query_stats_generator.rb | lib/generators/pghero/query_stats_generator.rb | require "rails/generators"
require "rails/generators/active_record"
module Pghero
module Generators
class QueryStatsGenerator < Rails::Generators::Base
include ActiveRecord::Generators::Migration
source_root File.join(__dir__, "templates")
def copy_migration
migration_template "query_stats.rb", "db/migrate/create_pghero_query_stats.rb", migration_version: migration_version
end
def migration_version
"[#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}]"
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/generators/pghero/config_generator.rb | lib/generators/pghero/config_generator.rb | require "rails/generators"
module Pghero
module Generators
class ConfigGenerator < Rails::Generators::Base
source_root File.join(__dir__, "templates")
def create_initializer
template "config.yml", "config/pghero.yml"
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/version.rb | lib/pghero/version.rb | module PgHero
VERSION = "3.7.0"
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/space_stats.rb | lib/pghero/space_stats.rb | module PgHero
class SpaceStats < Stats
self.table_name = "pghero_space_stats"
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/stats.rb | lib/pghero/stats.rb | module PgHero
class Stats < ActiveRecord::Base
self.abstract_class = true
establish_connection PgHero.stats_database_url if PgHero.stats_database_url
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/connection.rb | lib/pghero/connection.rb | module PgHero
class Connection < ActiveRecord::Base
self.abstract_class = true
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/engine.rb | lib/pghero/engine.rb | module PgHero
class Engine < ::Rails::Engine
isolate_namespace PgHero
initializer "pghero", group: :all do |app|
# check if Rails api mode
if app.config.respond_to?(:assets) && defined?(Sprockets)
if Sprockets::VERSION.to_i >= 4
app.config.assets.precompile << "pghero/application.js"
app.config.assets.precompile << "pghero/application.css"
app.config.assets.precompile << "pghero/favicon.png"
else
# use a proc instead of a string
app.config.assets.precompile << proc { |path| path == "pghero/application.js" }
app.config.assets.precompile << proc { |path| path == "pghero/application.css" }
app.config.assets.precompile << proc { |path| path == "pghero/favicon.png" }
end
end
file_config = PgHero.file_config || {}
PgHero.time_zone = file_config["time_zone"] if file_config["time_zone"]
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/query_stats.rb | lib/pghero/query_stats.rb | module PgHero
class QueryStats < Stats
self.table_name = "pghero_query_stats"
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/database.rb | lib/pghero/database.rb | module PgHero
class Database
include Methods::Basic
include Methods::Connections
include Methods::Constraints
include Methods::Explain
include Methods::Indexes
include Methods::Kill
include Methods::Maintenance
include Methods::Queries
include Methods::QueryStats
include Methods::Replication
include Methods::Sequences
include Methods::Settings
include Methods::Space
include Methods::SuggestedIndexes
include Methods::System
include Methods::Tables
include Methods::Users
attr_reader :id, :config
def initialize(id, config)
@id = id
@config = config || {}
# preload model to ensure only one connection pool
# this doesn't actually start any connections
@adapter_checked = false
@connection_model = build_connection_model
end
def name
@name ||= @config["name"] || id.titleize
end
def capture_query_stats?
config["capture_query_stats"] != false
end
def cache_hit_rate_threshold
(config["cache_hit_rate_threshold"] || PgHero.config["cache_hit_rate_threshold"] || PgHero.cache_hit_rate_threshold).to_i
end
def total_connections_threshold
(config["total_connections_threshold"] || PgHero.config["total_connections_threshold"] || PgHero.total_connections_threshold).to_i
end
def slow_query_ms
(config["slow_query_ms"] || PgHero.config["slow_query_ms"] || PgHero.slow_query_ms).to_i
end
def slow_query_calls
(config["slow_query_calls"] || PgHero.config["slow_query_calls"] || PgHero.slow_query_calls).to_i
end
def explain_timeout_sec
(config["explain_timeout_sec"] || PgHero.config["explain_timeout_sec"] || PgHero.explain_timeout_sec).to_f
end
def long_running_query_sec
(config["long_running_query_sec"] || PgHero.config["long_running_query_sec"] || PgHero.long_running_query_sec).to_i
end
# defaults to 100 megabytes
def index_bloat_bytes
(config["index_bloat_bytes"] || PgHero.config["index_bloat_bytes"] || 104857600).to_i
end
def aws_access_key_id
config["aws_access_key_id"] || PgHero.config["aws_access_key_id"] || ENV["PGHERO_ACCESS_KEY_ID"] || ENV["AWS_ACCESS_KEY_ID"]
end
def aws_secret_access_key
config["aws_secret_access_key"] || PgHero.config["aws_secret_access_key"] || ENV["PGHERO_SECRET_ACCESS_KEY"] || ENV["AWS_SECRET_ACCESS_KEY"]
end
def aws_region
config["aws_region"] || PgHero.config["aws_region"] || ENV["PGHERO_REGION"] || ENV["AWS_REGION"] || (defined?(Aws) && Aws.config[:region]) || "us-east-1"
end
# environment variable is only used if no config file
def aws_db_instance_identifier
@aws_db_instance_identifier ||= config["aws_db_instance_identifier"] || config["db_instance_identifier"]
end
# environment variable is only used if no config file
def gcp_database_id
@gcp_database_id ||= config["gcp_database_id"]
end
# environment variable is only used if no config file
def azure_resource_id
@azure_resource_id ||= config["azure_resource_id"]
end
# must check keys for booleans
def filter_data
unless defined?(@filter_data)
@filter_data =
if config.key?("filter_data")
config["filter_data"]
elsif PgHero.config.key?("filter_data")
PgHero.config.key?("filter_data")
else
PgHero.filter_data
end
if @filter_data
begin
require "pg_query"
rescue LoadError
raise Error, "pg_query required for filter_data"
end
end
end
@filter_data
end
private
# check adapter lazily
def connection_model
unless @adapter_checked
# rough check for Postgres adapter
# keep this message generic so it's useful
# when empty url set in Docker image pghero.yml
unless @connection_model.connection_db_config.adapter.to_s.match?(/postg/i)
raise Error, "Invalid connection URL"
end
@adapter_checked = true
end
@connection_model
end
# just return the model
# do not start a connection
def build_connection_model
url = config["url"]
# resolve spec
if !url && config["spec"]
config_options = {env_name: PgHero.env, PgHero.spec_name_key => config["spec"], PgHero.include_replicas_key => true}
resolved = ActiveRecord::Base.configurations.configs_for(**config_options)
raise Error, "Spec not found: #{config["spec"]}" unless resolved
url = resolved.configuration_hash
end
url = url.dup
Class.new(PgHero::Connection) do
def self.name
"PgHero::Connection::Database#{object_id}"
end
case url
when String
url = "#{url}#{url.include?("?") ? "&" : "?"}connect_timeout=5" unless url.include?("connect_timeout=")
when Hash
url[:connect_timeout] ||= 5
end
establish_connection url if url
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/methods/users.rb | lib/pghero/methods/users.rb | module PgHero
module Methods
module Users
# documented as unsafe to pass user input
# identifiers are now quoted, but still not officially supported
def create_user(user, password: nil, schema: "public", database: nil, readonly: false, tables: nil)
password ||= random_password
database ||= PgHero.connection_config(connection_model)[:database]
user = quote_ident(user)
schema = quote_ident(schema)
database = quote_ident(database)
commands =
[
"CREATE ROLE #{user} LOGIN PASSWORD #{quote(password)}",
"GRANT CONNECT ON DATABASE #{database} TO #{user}",
"GRANT USAGE ON SCHEMA #{schema} TO #{user}"
]
if readonly
if tables
commands.concat table_grant_commands("SELECT", tables, user)
else
commands << "GRANT SELECT ON ALL TABLES IN SCHEMA #{schema} TO #{user}"
commands << "ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} GRANT SELECT ON TABLES TO #{user}"
end
else
if tables
commands.concat table_grant_commands("ALL PRIVILEGES", tables, user)
else
commands << "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA #{schema} TO #{user}"
commands << "GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA #{schema} TO #{user}"
commands << "ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} GRANT ALL PRIVILEGES ON TABLES TO #{user}"
commands << "ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} GRANT ALL PRIVILEGES ON SEQUENCES TO #{user}"
end
end
# run commands
connection_model.transaction do
commands.each do |command|
execute command
end
end
{password: password}
end
# documented as unsafe to pass user input
# identifiers are now quoted, but still not officially supported
def drop_user(user, schema: "public", database: nil)
database ||= PgHero.connection_config(connection_model)[:database]
user = quote_ident(user)
schema = quote_ident(schema)
database = quote_ident(database)
# thanks shiftb
commands =
[
"REVOKE CONNECT ON DATABASE #{database} FROM #{user}",
"REVOKE USAGE ON SCHEMA #{schema} FROM #{user}",
"REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA #{schema} FROM #{user}",
"REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA #{schema} FROM #{user}",
"ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} REVOKE SELECT ON TABLES FROM #{user}",
"ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} REVOKE SELECT ON SEQUENCES FROM #{user}",
"ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} REVOKE ALL ON SEQUENCES FROM #{user}",
"ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} REVOKE ALL ON TABLES FROM #{user}",
"DROP ROLE #{user}"
]
# run commands
connection_model.transaction do
commands.each do |command|
execute command
end
end
true
end
private
def random_password
require "securerandom"
SecureRandom.base64(40).delete("+/=")[0...24]
end
def table_grant_commands(privilege, tables, quoted_user)
tables.map do |table|
"GRANT #{privilege} ON TABLE #{quote_ident(table)} TO #{quoted_user}"
end
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/methods/maintenance.rb | lib/pghero/methods/maintenance.rb | module PgHero
module Methods
module Maintenance
# https://www.postgresql.org/docs/current/routine-vacuuming.html#VACUUM-FOR-WRAPAROUND
# "the system will shut down and refuse to start any new transactions
# once there are fewer than 1 million transactions left until wraparound"
# warn when 10,000,000 transactions left
def transaction_id_danger(threshold: 10000000, max_value: 2146483648)
max_value = max_value.to_i
threshold = threshold.to_i
select_all <<~SQL
SELECT
n.nspname AS schema,
c.relname AS table,
#{quote(max_value)} - GREATEST(AGE(c.relfrozenxid), AGE(t.relfrozenxid)) AS transactions_left
FROM
pg_class c
INNER JOIN
pg_catalog.pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN
pg_class t ON c.reltoastrelid = t.oid
WHERE
c.relkind = 'r'
AND (#{quote(max_value)} - GREATEST(AGE(c.relfrozenxid), AGE(t.relfrozenxid))) < #{quote(threshold)}
ORDER BY
3, 1, 2
SQL
end
def autovacuum_danger
max_value = select_one("SHOW autovacuum_freeze_max_age").to_i
transaction_id_danger(threshold: 2000000, max_value: max_value)
end
def vacuum_progress
if server_version_num >= 90600
select_all <<~SQL
SELECT
pid,
phase
FROM
pg_stat_progress_vacuum
WHERE
datname = current_database()
SQL
else
[]
end
end
def maintenance_info
select_all <<~SQL
SELECT
schemaname AS schema,
relname AS table,
last_vacuum,
last_autovacuum,
last_analyze,
last_autoanalyze,
n_dead_tup AS dead_rows,
n_live_tup AS live_rows
FROM
pg_stat_user_tables
ORDER BY
1, 2
SQL
end
def analyze(table, verbose: false)
execute "ANALYZE #{verbose ? "VERBOSE " : ""}#{quote_table_name(table)}"
true
end
def analyze_tables(verbose: false, min_size: nil, tables: nil)
tables = table_stats(table: tables).reject { |s| %w(information_schema pg_catalog).include?(s[:schema]) }
tables = tables.select { |s| s[:size_bytes] > min_size } if min_size
tables.map { |s| s.slice(:schema, :table) }.each do |stats|
begin
with_transaction(lock_timeout: 5000, statement_timeout: 120000) do
analyze "#{stats[:schema]}.#{stats[:table]}", verbose: verbose
end
success = true
rescue ActiveRecord::StatementInvalid => e
$stderr.puts e.message
success = false
end
stats[:success] = success
end
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/methods/explain.rb | lib/pghero/methods/explain.rb | module PgHero
module Methods
module Explain
# TODO remove in 4.0
# note: this method is not affected by the explain option
def explain(sql)
sql = squish(sql)
explanation = nil
# use transaction for safety
with_transaction(statement_timeout: (explain_timeout_sec * 1000).round, rollback: true) do
if (sql.delete_suffix(";").include?(";") || sql.upcase.include?("COMMIT")) && !explain_safe?
raise ActiveRecord::StatementInvalid, "Unsafe statement"
end
explanation = execute("EXPLAIN #{sql}").map { |v| v["QUERY PLAN"] }.join("\n")
end
explanation
end
# TODO rename to explain in 4.0
# note: this method is not affected by the explain option
def explain_v2(sql, analyze: nil, verbose: nil, costs: nil, settings: nil, generic_plan: nil, buffers: nil, wal: nil, timing: nil, summary: nil, format: "text")
options = []
add_explain_option(options, "ANALYZE", analyze)
add_explain_option(options, "VERBOSE", verbose)
add_explain_option(options, "SETTINGS", settings)
add_explain_option(options, "GENERIC_PLAN", generic_plan)
add_explain_option(options, "COSTS", costs)
add_explain_option(options, "BUFFERS", buffers)
add_explain_option(options, "WAL", wal)
add_explain_option(options, "TIMING", timing)
add_explain_option(options, "SUMMARY", summary)
options << "FORMAT #{explain_format(format)}"
explain("(#{options.join(", ")}) #{sql}")
end
private
def explain_safe?
select_all("SELECT 1; SELECT 1")
false
rescue ActiveRecord::StatementInvalid
true
end
def add_explain_option(options, name, value)
unless value.nil?
options << "#{name}#{value ? "" : " FALSE"}"
end
end
# important! validate format to prevent injection
def explain_format(format)
if ["text", "xml", "json", "yaml"].include?(format)
format.upcase
else
raise ArgumentError, "Unknown format"
end
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/methods/constraints.rb | lib/pghero/methods/constraints.rb | module PgHero
module Methods
module Constraints
# referenced fields can be nil
# as not all constraints are foreign keys
def invalid_constraints
select_all <<~SQL
SELECT
nsp.nspname AS schema,
rel.relname AS table,
con.conname AS name,
fnsp.nspname AS referenced_schema,
frel.relname AS referenced_table
FROM
pg_catalog.pg_constraint con
INNER JOIN
pg_catalog.pg_class rel ON rel.oid = con.conrelid
LEFT JOIN
pg_catalog.pg_class frel ON frel.oid = con.confrelid
LEFT JOIN
pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
LEFT JOIN
pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
WHERE
con.convalidated = 'f'
SQL
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/methods/suggested_indexes.rb | lib/pghero/methods/suggested_indexes.rb | module PgHero
module Methods
module SuggestedIndexes
def suggested_indexes_enabled?
defined?(PgQuery) && Gem::Version.new(PgQuery::VERSION) >= Gem::Version.new("2") && query_stats_enabled?
end
# TODO clean this mess
def suggested_indexes_by_query(queries: nil, query_stats: nil, indexes: nil)
best_indexes = {}
if suggested_indexes_enabled?
# get most time-consuming queries
queries ||= (query_stats || self.query_stats(historical: true, start_at: 24.hours.ago)).map { |qs| qs[:query] }
# get best indexes for queries
best_indexes = best_index_helper(queries)
if best_indexes.any?
existing_columns = Hash.new { |hash, key| hash[key] = Hash.new { |hash2, key2| hash2[key2] = [] } }
indexes ||= self.indexes
indexes.group_by { |g| g[:using] }.each do |group, inds|
inds.each do |i|
existing_columns[group][i[:table]] << i[:columns]
end
end
indexes_by_table = indexes.group_by { |i| i[:table] }
best_indexes.each do |_query, best_index|
if best_index[:found]
index = best_index[:index]
best_index[:table_indexes] = indexes_by_table[index[:table]].to_a
# indexes of same type
indexes = existing_columns[index[:using] || "btree"][index[:table]]
if best_index[:structure][:sort].empty?
# gist indexes without an opclass
# (opclass is part of column name, so columns won't match if opclass present)
indexes += existing_columns["gist"][index[:table]]
# hash indexes work for equality
indexes += existing_columns["hash"][index[:table]] if best_index[:structure][:where].all? { |v| v[:op] == "=" }
# brin indexes work for all
indexes += existing_columns["brin"][index[:table]]
end
covering_index = indexes.find { |e| index_covers?(e.map { |v| v.delete_suffix(" inet_ops") }, index[:columns]) }
if covering_index
best_index[:covering_index] = covering_index
best_index[:explanation] = "Covered by index on (#{covering_index.join(", ")})"
end
end
end
end
else
raise NotEnabled, "Suggested indexes not enabled"
end
best_indexes
end
def suggested_indexes(suggested_indexes_by_query: nil, **options)
indexes = []
(suggested_indexes_by_query || self.suggested_indexes_by_query(**options)).select { |_s, i| i[:found] && !i[:covering_index] }.group_by { |_s, i| i[:index] }.each do |index, group|
details = {}
group.map(&:second).each do |g|
details = details.except(:index).deep_merge(g)
end
indexes << index.merge(queries: group.map(&:first), details: details)
end
indexes.sort_by { |i| [i[:table], i[:columns]] }
end
def autoindex(create: false)
suggested_indexes.each do |index|
p index
if create
with_connection do |connection|
connection.execute("CREATE INDEX CONCURRENTLY ON #{quote_table_name(index[:table])} (#{index[:columns].map { |c| quote_column_name(c) }.join(",")})")
end
end
end
end
def best_index(statement)
best_index_helper([statement])[statement]
end
private
def best_index_helper(statements)
indexes = {}
# see if this is a query we understand and can use
parts = {}
statements.each do |statement|
parts[statement] = best_index_structure(statement)
end
# get stats about columns for relevant tables
tables = parts.values.map { |t| t[:table] }.uniq
# TODO get schema from query structure, then try search path
schema = PgHero.connection_config(connection_model)[:schema] || "public"
if tables.any?
row_stats = table_stats(table: tables, schema: schema).to_h { |i| [i[:table], i[:estimated_rows]] }
col_stats = column_stats(table: tables, schema: schema).group_by { |i| i[:table] }
end
# find best index based on query structure and column stats
parts.each do |statement, structure|
index = {found: false}
if structure[:error]
index[:explanation] = structure[:error]
elsif structure[:table].start_with?("pg_")
index[:explanation] = "System table"
else
index[:structure] = structure
table = structure[:table]
where = structure[:where].uniq
sort = structure[:sort]
total_rows = row_stats[table].to_i
index[:rows] = total_rows
ranks = col_stats[table].to_a.to_h { |r| [r[:column], r] }
columns = (where + sort).map { |c| c[:column] }.uniq
if columns.any?
if columns.all? { |c| ranks[c] }
first_desc = sort.index { |c| c[:direction] == "desc" }
sort = sort.first(first_desc + 1) if first_desc
where = where.sort_by { |c| [row_estimates(ranks[c[:column]], total_rows, total_rows, c[:op]), c[:column]] } + sort
index[:row_estimates] = where.to_h { |c| ["#{c[:column]} (#{c[:op] || "sort"})", row_estimates(ranks[c[:column]], total_rows, total_rows, c[:op]).round] }
# no index needed if less than 500 rows
if total_rows >= 500
if ["~~", "~~*"].include?(where.first[:op])
index[:found] = true
index[:row_progression] = [total_rows, index[:row_estimates].values.first]
index[:index] = {table: table, columns: ["#{where.first[:column]} gist_trgm_ops"], using: "gist"}
else
# if most values are unique, no need to index others
rows_left = total_rows
final_where = []
prev_rows_left = [rows_left]
where.reject { |c| ["~~", "~~*"].include?(c[:op]) }.each do |c|
next if final_where.include?(c[:column])
final_where << c[:column]
rows_left = row_estimates(ranks[c[:column]], total_rows, rows_left, c[:op])
prev_rows_left << rows_left
if rows_left < 50 || final_where.size >= 2 || [">", ">=", "<", "<=", "~~", "~~*", "BETWEEN"].include?(c[:op])
break
end
end
index[:row_progression] = prev_rows_left.map(&:round)
# if the last indexes don't give us much, don't include
prev_rows_left.reverse!
(prev_rows_left.size - 1).times do |i|
if prev_rows_left[i] > prev_rows_left[i + 1] * 0.3
final_where.pop
else
break
end
end
if final_where.any?
index[:found] = true
index[:index] = {table: table, columns: final_where}
end
end
else
index[:explanation] = "No index needed if less than 500 rows"
end
else
index[:explanation] = "Stats not found"
end
else
index[:explanation] = "No columns to index"
end
end
indexes[statement] = index
end
indexes
end
def best_index_structure(statement)
return {error: "Empty statement"} if statement.to_s.empty?
return {error: "Too large"} if statement.to_s.length > 10000
begin
tree = PgQuery.parse(statement).tree
rescue PgQuery::ParseError
return {error: "Parse error"}
end
return {error: "Unknown structure"} unless tree.stmts.size == 1
tree = tree.stmts.first.stmt
table = parse_table(tree) rescue nil
unless table
error =
case tree.node
when :insert_stmt
"INSERT statement"
when :variable_set_stmt
"SET statement"
when :select_stmt
if (tree.select_stmt.from_clause.first.join_expr rescue false)
"JOIN not supported yet"
end
end
return {error: error || "Unknown structure"}
end
select = tree[tree.node.to_s]
where = (select.where_clause ? parse_where(select.where_clause) : []) rescue nil
return {error: "Unknown structure"} unless where
sort = (select.sort_clause ? parse_sort(select.sort_clause) : []) rescue []
{table: table, where: where, sort: sort}
end
# TODO better row estimation
# https://www.postgresql.org/docs/current/static/row-estimation-examples.html
def row_estimates(stats, total_rows, rows_left, op)
case op
when "null"
rows_left * stats[:null_frac].to_f
when "not_null"
rows_left * (1 - stats[:null_frac].to_f)
else
rows_left *= (1 - stats[:null_frac].to_f)
ret =
if stats[:n_distinct].to_f == 0
0
elsif stats[:n_distinct].to_f < 0
if total_rows > 0
(-1 / stats[:n_distinct].to_f) * (rows_left / total_rows.to_f)
else
0
end
else
rows_left / stats[:n_distinct].to_f
end
case op
when ">", ">=", "<", "<=", "~~", "~~*", "BETWEEN"
(rows_left + ret) / 10.0 # TODO better approximation
when "<>"
rows_left - ret
else
ret
end
end
end
def parse_table(tree)
case tree.node
when :select_stmt
tree.select_stmt.from_clause.first.range_var.relname
when :delete_stmt
tree.delete_stmt.relation.relname
when :update_stmt
tree.update_stmt.relation.relname
end
end
# TODO capture values
def parse_where(tree)
aexpr = tree.a_expr
if tree.bool_expr
if tree.bool_expr.boolop == :AND_EXPR
tree.bool_expr.args.flat_map { |v| parse_where(v) }
else
raise "Not Implemented"
end
elsif aexpr && ["=", "<>", ">", ">=", "<", "<=", "~~", "~~*", "BETWEEN"].include?(aexpr.name.first.string.send(str_method))
[{column: aexpr.lexpr.column_ref.fields.last.string.send(str_method), op: aexpr.name.first.string.send(str_method)}]
elsif tree.null_test
op = tree.null_test.nulltesttype == :IS_NOT_NULL ? "not_null" : "null"
[{column: tree.null_test.arg.column_ref.fields.last.string.send(str_method), op: op}]
else
raise "Not Implemented"
end
end
def str_method
@str_method ||= Gem::Version.new(PgQuery::VERSION) >= Gem::Version.new("4") ? :sval : :str
end
def parse_sort(sort_clause)
sort_clause.map do |v|
{
column: v.sort_by.node.column_ref.fields.last.string.send(str_method),
direction: v.sort_by.sortby_dir == :SORTBY_DESC ? "desc" : "asc"
}
end
end
def column_stats(schema: nil, table: nil)
select_all <<~SQL
SELECT
schemaname AS schema,
tablename AS table,
attname AS column,
null_frac,
n_distinct
FROM
pg_stats
WHERE
schemaname = #{quote(schema)}
#{table ? "AND tablename IN (#{Array(table).map { |t| quote(t) }.join(", ")})" : ""}
ORDER BY
1, 2, 3
SQL
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/methods/sequences.rb | lib/pghero/methods/sequences.rb | module PgHero
module Methods
module Sequences
def sequences
# get columns with default values
# use pg_get_expr to get correct default value
# it's what information_schema.columns uses
# also, exclude temporary tables to prevent error
# when accessing across sessions
sequences = select_all <<~SQL
SELECT
n.nspname AS table_schema,
c.relname AS table,
attname AS column,
format_type(a.atttypid, a.atttypmod) AS column_type,
pg_get_expr(d.adbin, d.adrelid) AS default_value
FROM
pg_catalog.pg_attribute a
INNER JOIN
pg_catalog.pg_class c ON c.oid = a.attrelid
INNER JOIN
pg_catalog.pg_namespace n ON n.oid = c.relnamespace
INNER JOIN
pg_catalog.pg_attrdef d ON (a.attrelid, a.attnum) = (d.adrelid, d.adnum)
WHERE
NOT a.attisdropped
AND a.attnum > 0
AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%'
AND n.nspname NOT LIKE 'pg\\_temp\\_%'
SQL
# parse out sequence
sequences.each do |column|
column[:max_value] = column[:column_type] == 'integer' ? 2147483647 : 9223372036854775807
column[:schema], column[:sequence] = parse_default_value(column[:default_value])
column.delete(:default_value) if column[:sequence]
end
add_sequence_attributes(sequences)
last_value = {}
sequences.select { |s| s[:readable] }.map { |s| [s[:schema], s[:sequence]] }.uniq.each_slice(1024) do |slice|
sql = slice.map { |s| "SELECT last_value FROM #{quote_ident(s[0])}.#{quote_ident(s[1])}" }.join(" UNION ALL ")
select_all(sql).zip(slice) do |row, seq|
last_value[seq] = row[:last_value]
end
end
sequences.select { |s| s[:readable] }.each do |seq|
seq[:last_value] = last_value[[seq[:schema], seq[:sequence]]]
end
# use to_s for unparsable sequences
sequences.sort_by { |s| s[:sequence].to_s }
end
def sequence_danger(threshold: 0.9, sequences: nil)
sequences ||= self.sequences
sequences.select { |s| s[:last_value] && s[:last_value] / s[:max_value].to_f > threshold }.sort_by { |s| s[:max_value] - s[:last_value] }
end
private
# can parse
# nextval('id_seq'::regclass)
# nextval(('id_seq'::text)::regclass)
def parse_default_value(default_value)
m = /^nextval\('(.+)'\:\:regclass\)$/.match(default_value)
m = /^nextval\(\('(.+)'\:\:text\)\:\:regclass\)$/.match(default_value) unless m
if m
unquote_ident(m[1])
else
[]
end
end
def unquote_ident(value)
schema, seq = value.split(".")
unless seq
seq = schema
schema = nil
end
[unquote(schema), unquote(seq)]
end
# adds readable attribute to all sequences
# also adds schema if missing
def add_sequence_attributes(sequences)
# fetch data
sequence_attributes = select_all <<~SQL
SELECT
n.nspname AS schema,
c.relname AS sequence,
has_sequence_privilege(c.oid, 'SELECT') AS readable
FROM
pg_class c
INNER JOIN
pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE
c.relkind = 'S'
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
SQL
# first populate missing schemas
missing_schema = sequences.select { |s| s[:schema].nil? && s[:sequence] }
if missing_schema.any?
sequence_schemas = sequence_attributes.group_by { |s| s[:sequence] }
missing_schema.each do |sequence|
schemas = sequence_schemas[sequence[:sequence]] || []
if schemas.size == 1
sequence[:schema] = schemas[0][:schema]
end
# otherwise, do nothing, will be marked as unreadable
# TODO better message for multiple schemas
end
end
# then populate attributes
readable = sequence_attributes.to_h { |s| [[s[:schema], s[:sequence]], s[:readable]] }
sequences.each do |sequence|
sequence[:readable] = readable[[sequence[:schema], sequence[:sequence]]] || false
end
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/methods/settings.rb | lib/pghero/methods/settings.rb | module PgHero
module Methods
module Settings
def settings
names =
if server_version_num >= 100000
%i(
max_connections shared_buffers effective_cache_size maintenance_work_mem
checkpoint_completion_target wal_buffers default_statistics_target
random_page_cost effective_io_concurrency work_mem huge_pages
min_wal_size max_wal_size
)
elsif server_version_num >= 90500
%i(
max_connections shared_buffers effective_cache_size work_mem
maintenance_work_mem min_wal_size max_wal_size checkpoint_completion_target
wal_buffers default_statistics_target
)
else
%i(
max_connections shared_buffers effective_cache_size work_mem
maintenance_work_mem checkpoint_segments checkpoint_completion_target
wal_buffers default_statistics_target
)
end
fetch_settings(names)
end
def autovacuum_settings
fetch_settings %i(autovacuum autovacuum_max_workers autovacuum_vacuum_cost_limit autovacuum_vacuum_scale_factor autovacuum_analyze_scale_factor)
end
def vacuum_settings
fetch_settings %i(vacuum_cost_limit)
end
private
def fetch_settings(names)
names.to_h { |name| [name, select_one("SHOW #{name}")] }
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/methods/basic.rb | lib/pghero/methods/basic.rb | module PgHero
module Methods
module Basic
def ssl_used?
ssl_used = nil
with_transaction(rollback: true) do
begin
execute("CREATE EXTENSION IF NOT EXISTS sslinfo")
rescue ActiveRecord::StatementInvalid
# not superuser
end
ssl_used = select_one("SELECT ssl_is_used()")
end
ssl_used
end
def database_name
select_one("SELECT current_database()")
end
def current_user
select_one("SELECT current_user")
end
def server_version
@server_version ||= select_one("SHOW server_version")
end
def server_version_num
@server_version_num ||= select_one("SHOW server_version_num").to_i
end
def quote_ident(value)
with_connection { |c| c.quote_column_name(value) }
end
private
def select_all(sql, stats: false, query_columns: [])
with_connection(stats: stats) do |conn|
select_all_leased(sql, conn: conn, query_columns: query_columns)
end
end
def select_all_leased(sql, conn:, query_columns:)
# squish for logs
retries = 0
begin
result = conn.select_all(add_source(squish(sql)))
if ActiveRecord::VERSION::MAJOR >= 8
result = result.to_a.map(&:symbolize_keys)
else
result = result.map(&:symbolize_keys)
end
if filter_data
query_columns.each do |column|
result.each do |row|
begin
row[column] = PgQuery.normalize(row[column])
rescue PgQuery::ParseError
# try replacing "interval $1" with "$1::interval"
# see https://github.com/lfittl/pg_query/issues/169 for more info
# this is not ideal since it changes the query slightly
# we could skip normalization
# but this has a very small chance of data leakage
begin
row[column] = PgQuery.normalize(row[column].gsub(/\binterval\s+(\$\d+)\b/i, "\\1::interval"))
rescue PgQuery::ParseError
row[column] = "<unable to filter data>"
end
end
end
end
end
result
rescue ActiveRecord::StatementInvalid => e
# fix for random internal errors
if e.message.include?("PG::InternalError") && retries < 2
retries += 1
sleep(0.1)
retry
else
raise e
end
end
end
def select_all_stats(sql, **options)
select_all(sql, **options, stats: true)
end
def select_all_size(sql)
result = select_all(sql)
result.each do |row|
row[:size] = PgHero.pretty_size(row[:size_bytes])
end
result
end
def select_one(sql)
select_all(sql).first.values.first
end
def execute(sql)
with_connection { |c| c.execute(add_source(sql)) }
end
def with_connection(stats: false, &block)
model = stats ? ::PgHero::Stats : connection_model
model.connection_pool.with_connection(&block)
end
def squish(str)
str.to_s.squish
end
def add_source(sql)
"#{sql} /*pghero*/"
end
def quote(value)
with_connection { |c| c.quote(value) }
end
def quote_table_name(value)
with_connection { |c| c.quote_table_name(value) }
end
def quote_column_name(value)
with_connection { |c| c.quote_column_name(value) }
end
def unquote(part)
if part && part.start_with?('"')
part[1..-2]
else
part
end
end
def with_transaction(lock_timeout: nil, statement_timeout: nil, rollback: false)
connection_model.transaction do
select_all "SET LOCAL statement_timeout = #{statement_timeout.to_i}" if statement_timeout
select_all "SET LOCAL lock_timeout = #{lock_timeout.to_i}" if lock_timeout
yield
raise ActiveRecord::Rollback if rollback
end
end
def table_exists?(table)
with_connection(stats: true) { |c| c.table_exists?(table) }
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/methods/queries.rb | lib/pghero/methods/queries.rb | module PgHero
module Methods
module Queries
def running_queries(min_duration: nil, all: false)
query = <<~SQL
SELECT
pid,
state,
application_name AS source,
age(NOW(), COALESCE(query_start, xact_start)) AS duration,
#{server_version_num >= 90600 ? "(wait_event IS NOT NULL) AS waiting" : "waiting"},
query,
COALESCE(query_start, xact_start) AS started_at,
EXTRACT(EPOCH FROM NOW() - COALESCE(query_start, xact_start)) * 1000.0 AS duration_ms,
usename AS user,
#{server_version_num >= 100000 ? "backend_type" : "NULL AS backend_type"}
FROM
pg_stat_activity
WHERE
state <> 'idle'
AND pid <> pg_backend_pid()
AND datname = current_database()
#{min_duration ? "AND NOW() - COALESCE(query_start, xact_start) > interval '#{min_duration.to_i} seconds'" : nil}
#{all ? nil : "AND query <> '<insufficient privilege>'"}
ORDER BY
COALESCE(query_start, xact_start) DESC
SQL
select_all(query, query_columns: [:query])
end
def long_running_queries
running_queries(min_duration: long_running_query_sec)
end
# from https://wiki.postgresql.org/wiki/Lock_Monitoring
# and https://big-elephants.com/2013-09/exploring-query-locks-in-postgres/
def blocked_queries
query = <<~SQL
SELECT
COALESCE(blockingl.relation::regclass::text,blockingl.locktype) as locked_item,
blockeda.pid AS blocked_pid,
blockeda.usename AS blocked_user,
blockeda.query as blocked_query,
age(now(), blockeda.query_start) AS blocked_duration,
blockedl.mode as blocked_mode,
blockinga.pid AS blocking_pid,
blockinga.usename AS blocking_user,
blockinga.state AS state_of_blocking_process,
blockinga.query AS current_or_recent_query_in_blocking_process,
age(now(), blockinga.query_start) AS blocking_duration,
blockingl.mode as blocking_mode
FROM
pg_catalog.pg_locks blockedl
LEFT JOIN
pg_stat_activity blockeda ON blockedl.pid = blockeda.pid
LEFT JOIN
pg_catalog.pg_locks blockingl ON blockedl.pid != blockingl.pid AND (
blockingl.transactionid = blockedl.transactionid
OR (blockingl.relation = blockedl.relation AND blockingl.locktype = blockedl.locktype)
)
LEFT JOIN
pg_stat_activity blockinga ON blockingl.pid = blockinga.pid AND blockinga.datid = blockeda.datid
WHERE
NOT blockedl.granted
AND blockeda.query <> '<insufficient privilege>'
AND blockeda.datname = current_database()
ORDER BY
blocked_duration DESC
SQL
select_all(query, query_columns: [:blocked_query, :current_or_recent_query_in_blocking_process])
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
ankane/pghero | https://github.com/ankane/pghero/blob/c11401560bdae3477a531f799168355d45e789aa/lib/pghero/methods/connections.rb | lib/pghero/methods/connections.rb | module PgHero
module Methods
module Connections
def connections
if server_version_num >= 90500
select_all <<~SQL
SELECT
pg_stat_activity.pid,
datname AS database,
usename AS user,
application_name AS source,
client_addr AS ip,
state,
ssl
FROM
pg_stat_activity
LEFT JOIN
pg_stat_ssl ON pg_stat_activity.pid = pg_stat_ssl.pid
ORDER BY
pg_stat_activity.pid
SQL
else
select_all <<~SQL
SELECT
pid,
datname AS database,
usename AS user,
application_name AS source,
client_addr AS ip,
state
FROM
pg_stat_activity
ORDER BY
pid
SQL
end
end
def total_connections
select_one("SELECT COUNT(*) FROM pg_stat_activity")
end
def connection_states
states = select_all <<~SQL
SELECT
state,
COUNT(*) AS connections
FROM
pg_stat_activity
GROUP BY
1
ORDER BY
2 DESC, 1
SQL
states.to_h { |s| [s[:state], s[:connections]] }
end
def connection_sources
select_all <<~SQL
SELECT
datname AS database,
usename AS user,
application_name AS source,
client_addr AS ip,
COUNT(*) AS total_connections
FROM
pg_stat_activity
GROUP BY
1, 2, 3, 4
ORDER BY
5 DESC, 1, 2, 3, 4
SQL
end
end
end
end
| ruby | MIT | c11401560bdae3477a531f799168355d45e789aa | 2026-01-04T15:38:52.602437Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.