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 |
|---|---|---|---|---|---|---|---|---|
esminc/tapp | https://github.com/esminc/tapp/blob/ddc458011a82db33617bed44c6a64838f8581e13/lib/tapp/configuration.rb | lib/tapp/configuration.rb | module Tapp
class Configuration
attr_accessor :default_printer, :report_caller
def initialize
reset
end
def reset
self.default_printer = :pretty_print
self.report_caller = false
end
end
end
| ruby | MIT | ddc458011a82db33617bed44c6a64838f8581e13 | 2026-01-04T17:50:46.572797Z | false |
esminc/tapp | https://github.com/esminc/tapp/blob/ddc458011a82db33617bed44c6a64838f8581e13/lib/tapp/printer.rb | lib/tapp/printer.rb | require 'singleton'
module Tapp
module Printer
@printers = {}
class << self
def register(name, printer)
@printers[name] = printer
end
def instance(name)
@printers.fetch(name).instance
end
end
class Base
include Singleton
def print(*args)
raise NotImplementedError
end
end
end
end
| ruby | MIT | ddc458011a82db33617bed44c6a64838f8581e13 | 2026-01-04T17:50:46.572797Z | false |
esminc/tapp | https://github.com/esminc/tapp/blob/ddc458011a82db33617bed44c6a64838f8581e13/lib/tapp/util.rb | lib/tapp/util.rb | module Tapp
module Util
module_function
def report_called
inner, outer = caller.partition {|line|
line =~ %r(/lib/tapp/(?!turnip))
}
method_quoted = inner.last.split(':in').last.strip
puts "#{method_quoted} in #{outer.first}"
end
end
end
| ruby | MIT | ddc458011a82db33617bed44c6a64838f8581e13 | 2026-01-04T17:50:46.572797Z | false |
esminc/tapp | https://github.com/esminc/tapp/blob/ddc458011a82db33617bed44c6a64838f8581e13/lib/tapp/printer/puts.rb | lib/tapp/printer/puts.rb | require 'tapp/printer'
module Tapp::Printer
class Puts < Base
def print(*args)
puts(*args)
end
end
register :puts, Puts
end
| ruby | MIT | ddc458011a82db33617bed44c6a64838f8581e13 | 2026-01-04T17:50:46.572797Z | false |
esminc/tapp | https://github.com/esminc/tapp/blob/ddc458011a82db33617bed44c6a64838f8581e13/lib/tapp/printer/pretty_print.rb | lib/tapp/printer/pretty_print.rb | require 'tapp/printer'
module Tapp::Printer
class PrettyPrint < Base
def print(*args)
require 'pp'
self.class.class_eval do
remove_method :print
def print(*args)
pp(*args)
end
end
print(*args)
end
end
register :pretty_print, PrettyPrint
end
| ruby | MIT | ddc458011a82db33617bed44c6a64838f8581e13 | 2026-01-04T17:50:46.572797Z | false |
thoughtbot/capybara_discoball | https://github.com/thoughtbot/capybara_discoball/blob/d06cebf7dde482e80163fe438d6005219f0456cf/spec/spec_helper.rb | spec/spec_helper.rb | require "jet_black/rspec"
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.shared_context_metadata_behavior = :apply_to_host_groups
config.disable_monkey_patching!
config.warnings = true
config.order = :random
Kernel.srand config.seed
end
| ruby | MIT | d06cebf7dde482e80163fe438d6005219f0456cf | 2026-01-04T17:50:47.867547Z | false |
thoughtbot/capybara_discoball | https://github.com/thoughtbot/capybara_discoball/blob/d06cebf7dde482e80163fe438d6005219f0456cf/spec/black_box/rails_app_spec.rb | spec/black_box/rails_app_spec.rb | require "jet_black"
RSpec.describe "Using Discoball in a Rails app" do
let(:session) do
JetBlack::Session.new(options: { clean_bundler_env: true })
end
it "works with a block" do
create_rails_application
setup_discoball
setup_rspec_rails
install_success_api
setup_controller_action(<<~RUBY)
render plain: SuccessAPI.get
RUBY
setup_integration_spec(<<~RUBY)
visit "/successes"
expect(page).to have_content("success")
RUBY
setup_spec_supporter(<<-RUBY)
require "sinatra/base"
require "capybara_discoball"
require "success_api"
class FakeSuccess < Sinatra::Base
get("/") { "success" }
end
Capybara::Discoball.spin(FakeSuccess) do |server|
SuccessAPI.endpoint_url = server.url
end
RUBY
expect(run_integration_test).
to be_a_success.and have_stdout(/1 example, 0 failures/)
end
it "works without a block" do
create_rails_application
setup_discoball
setup_rspec_rails
install_success_api
setup_controller_action(<<~RUBY)
render :plain => SuccessAPI.get
RUBY
setup_integration_spec(<<~RUBY)
visit "/successes"
expect(page).to have_content("success")
RUBY
setup_spec_supporter(<<-RUBY)
require "sinatra/base"
require "capybara_discoball"
require "success_api"
class FakeSuccess < Sinatra::Base
get("/") { "success" }
end
SuccessAPI.endpoint_url = Capybara::Discoball.spin(FakeSuccess)
RUBY
expect(run_integration_test).
to be_a_success.and have_stdout("1 example, 0 failures")
end
private
def create_rails_application
session.create_file("Gemfile", <<~RUBY)
source "http://rubygems.org"
gem "rails"
RUBY
session.run("bundle install")
rails_new_cmd = [
"bundle exec rails new .",
"--skip-bundle",
"--skip-test",
"--skip-coffee",
"--skip-turbolinks",
"--skip-spring",
"--skip-bootsnap",
"--force",
].join(" ")
expect(session.run(rails_new_cmd)).
to be_a_success.and have_stdout("force Gemfile")
end
def setup_discoball
discoball_path = File.expand_path("../../", __dir__)
session.append_to_file "Gemfile", <<~RUBY
gem "capybara_discoball", path: "#{discoball_path}"
gem "sinatra"
RUBY
expect(session.run("bundle install")).
to be_a_success.and have_stdout(/capybara_discoball .* from source at/)
end
def setup_rspec_rails
session.append_to_file("Gemfile", <<~RUBY)
gem "rspec-rails"
RUBY
session.run("bundle install")
expect(session.run("bundle exec rails g rspec:install")).
to be_a_success.and have_stdout("create spec/rails_helper.rb")
end
def install_success_api
session.create_file("app/models/success_api.rb", <<~RUBY)
require "net/http"
require "uri"
class SuccessAPI
@@endpoint_url = "http://yahoo.com/"
def self.endpoint_url=(endpoint_url)
@@endpoint_url = endpoint_url
end
def self.get
Net::HTTP.get(uri)
end
private
def self.uri
URI.parse(@@endpoint_url)
end
end
RUBY
end
def setup_controller_action(content)
session.create_file("app/controllers/whatever_controller.rb", <<~RUBY)
class WhateverController < ApplicationController
def the_action
#{content}
end
end
RUBY
session.create_file("config/routes.rb", <<~RUBY)
Rails.application.routes.draw do
get "/successes", to: "whatever#the_action"
end
RUBY
end
def setup_integration_spec(spec_content)
session.create_file("spec/integration/whatever_spec.rb", <<~RUBY)
require "rails_helper"
require "capybara/rspec"
require "support/whatever"
RSpec.describe "whatever", type: :feature do
it "does the thing" do
#{spec_content}
end
end
RUBY
end
def setup_spec_supporter(support_content)
session.create_file("spec/support/whatever.rb", support_content)
end
def run_integration_test
session.run("bundle exec rspec spec/integration")
end
end
| ruby | MIT | d06cebf7dde482e80163fe438d6005219f0456cf | 2026-01-04T17:50:47.867547Z | false |
thoughtbot/capybara_discoball | https://github.com/thoughtbot/capybara_discoball/blob/d06cebf7dde482e80163fe438d6005219f0456cf/spec/lib/capybara_discoball_spec.rb | spec/lib/capybara_discoball_spec.rb | require "capybara_discoball"
require "net/http"
require "sinatra/base"
RSpec.describe Capybara::Discoball do
it "spins up a server" do
example_discoball_app = Class.new(Sinatra::Base) do
get("/") { "success" }
end
server_url = described_class.spin(example_discoball_app)
response = Net::HTTP.get(URI(server_url))
expect(response).to eq "success"
end
end
| ruby | MIT | d06cebf7dde482e80163fe438d6005219f0456cf | 2026-01-04T17:50:47.867547Z | false |
thoughtbot/capybara_discoball | https://github.com/thoughtbot/capybara_discoball/blob/d06cebf7dde482e80163fe438d6005219f0456cf/spec/lib/capybara_discoball/runner_spec.rb | spec/lib/capybara_discoball/runner_spec.rb | require "capybara_discoball"
require "sinatra/base"
RSpec.describe Capybara::Discoball::Runner do
describe "when Capybara fails to find an unused port" do
it "retries up to 3 times" do
expected_url = "http://localhost:9999"
allow(Capybara::Discoball::Server).to receive(:new).and_return(
unbootable_server,
unbootable_server,
unbootable_server,
bootable_server(url: expected_url),
)
runner = described_class.new(Sinatra::Base)
expect(runner.boot).to eq expected_url
end
end
private
def bootable_server(url:)
instance_double(Capybara::Discoball::Server, boot: nil, url: url)
end
def unbootable_server
server = instance_double(Capybara::Discoball::Server)
allow(server).to receive(:boot).and_raise(Errno::EADDRINUSE)
server
end
end
| ruby | MIT | d06cebf7dde482e80163fe438d6005219f0456cf | 2026-01-04T17:50:47.867547Z | false |
thoughtbot/capybara_discoball | https://github.com/thoughtbot/capybara_discoball/blob/d06cebf7dde482e80163fe438d6005219f0456cf/lib/capybara_discoball.rb | lib/capybara_discoball.rb | require "capybara_discoball/version"
require "capybara_discoball/server"
require "capybara_discoball/runner"
module Capybara
module Discoball
def self.spin(app, &block)
Runner.new(app, &block).boot
end
end
end
| ruby | MIT | d06cebf7dde482e80163fe438d6005219f0456cf | 2026-01-04T17:50:47.867547Z | false |
thoughtbot/capybara_discoball | https://github.com/thoughtbot/capybara_discoball/blob/d06cebf7dde482e80163fe438d6005219f0456cf/lib/capybara_discoball/version.rb | lib/capybara_discoball/version.rb | module Capybara
module Discoball
VERSION = "0.1.0"
end
end
| ruby | MIT | d06cebf7dde482e80163fe438d6005219f0456cf | 2026-01-04T17:50:47.867547Z | false |
thoughtbot/capybara_discoball | https://github.com/thoughtbot/capybara_discoball/blob/d06cebf7dde482e80163fe438d6005219f0456cf/lib/capybara_discoball/retryable.rb | lib/capybara_discoball/retryable.rb | module Capybara
module Discoball
module Retryable
def with_retries(retry_count, *rescuable_exceptions)
yield
rescue *rescuable_exceptions => e
if retry_count > 0
retry_count -= 1
puts e.inspect if ENV.key?("DEBUG")
retry
else
raise
end
end
end
end
end
| ruby | MIT | d06cebf7dde482e80163fe438d6005219f0456cf | 2026-01-04T17:50:47.867547Z | false |
thoughtbot/capybara_discoball | https://github.com/thoughtbot/capybara_discoball/blob/d06cebf7dde482e80163fe438d6005219f0456cf/lib/capybara_discoball/runner.rb | lib/capybara_discoball/runner.rb | require "capybara"
require_relative "retryable"
module Capybara
module Discoball
class Runner
include Capybara::Discoball::Retryable
RETRY_COUNT = 3
def initialize(server_factory, &block)
@server_factory = server_factory
@after_server = block || Proc.new {}
end
def boot
with_webrick_runner do
@server = Server.new(@server_factory.new)
@server.boot
end
@after_server.call(@server)
@server.url
end
private
def with_webrick_runner
default_server_process = Capybara.server
Capybara.server = :webrick
with_retries(RETRY_COUNT, Errno::EADDRINUSE) { yield }
ensure
Capybara.server = default_server_process
end
end
end
end
| ruby | MIT | d06cebf7dde482e80163fe438d6005219f0456cf | 2026-01-04T17:50:47.867547Z | false |
thoughtbot/capybara_discoball | https://github.com/thoughtbot/capybara_discoball/blob/d06cebf7dde482e80163fe438d6005219f0456cf/lib/capybara_discoball/server.rb | lib/capybara_discoball/server.rb | require "capybara/server"
module Capybara
module Discoball
class Server < ::Capybara::Server
def url
"http://#{host}:#{port}"
end
end
end
end
| ruby | MIT | d06cebf7dde482e80163fe438d6005219f0456cf | 2026-01-04T17:50:47.867547Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/integration_test.rb | test/integration_test.rb | require 'rubygems'
require 'test/unit'
require 'fileutils'
require 'shoulda'
class IntegrationTest < Test::Unit::TestCase
# This is slow, and Test:Unit does not have "before/after :all" method, so I'm using a single testcase for multiple tests
should "be able to send a build request, have it run and show the results" do
Thread.new {
sleep 30
puts "Still running after 30 secs, stopping..."
stop
}
cleanup
system "mkdir -p tmp/fixtures; cp -rf test/fixtures/local tmp/local"
system "export INTEGRATION_TEST=true; bin/testbot --runner --connect 127.0.0.1 --working_dir tmp/runner > /dev/null"
system "export INTEGRATION_TEST=true; bin/testbot --server > /dev/null"
# For debug
# Thread.new do
# system "export INTEGRATION_TEST=true; bin/testbot --runner run --connect 127.0.0.1 --working_dir tmp/runner"
# end
# Thread.new do
# system "export INTEGRATION_TEST=true; bin/testbot --server run"
# end
sleep 2.0
result = `cd tmp/local; INTEGRATION_TEST=true ../../bin/testbot --spec --connect 127.0.0.1 --rsync_path ../server --rsync_ignores "log/* tmp/*"`
# Should include the result from script/spec
#puts result.inspect
assert result.include?('script/spec got called with ["-O", "spec/spec.opts", "spec/models/house_spec.rb", "spec/models/car_spec.rb"]') ||
result.include?('script/spec got called with ["-O", "spec/spec.opts", "spec/models/car_spec.rb", "spec/models/house_spec.rb"]')
# Should not include ignored files
assert !File.exists?("tmp/server/log/test.log")
assert !File.exists?("tmp/server/tmp/restart.txt")
assert !File.exists?("tmp/runner/local/log/test.log")
assert !File.exists?("tmp/runner/local/tmp/restart.txt")
end
def teardown
stop
cleanup
end
def stop
system "export INTEGRATION_TEST=true; bin/testbot --server stop > /dev/null"
system "export INTEGRATION_TEST=true; bin/testbot --runner stop > /dev/null"
end
def cleanup
system "rm -rf tmp/local tmp/fixtures"
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/requester/requester_test.rb | test/requester/requester_test.rb | require File.expand_path(File.join(File.dirname(__FILE__), '../../lib/requester/requester.rb'))
require 'test/unit'
require 'shoulda'
require 'flexmock/test_unit'
# Probably a bug in flexmock, for 1.9.2
unless defined?(Test::Unit::AssertionFailedError)
class Test::Unit::AssertionFailedError
end
end
module Testbot::Requester
class RequesterTest < Test::Unit::TestCase
def requester_with_result(results)
requester = Requester.new(:server_host => "192.168.1.100", :rsync_path => 'user@server:/tmp/somewhere')
flexmock(requester).should_receive(:find_tests).and_return([])
flexmock(HTTParty).should_receive(:post).and_return(response_with_build_id)
flexmock(requester).should_receive(:sleep).once
flexmock(requester).should_receive(:print).once
flexmock(requester).should_receive(:puts).once
flexmock(requester).should_receive(:system)
flexmock(HTTParty).should_receive(:get).once.with("http://192.168.1.100:#{Testbot::SERVER_PORT}/builds/5",
:format => :json).and_return({ "done" => true, "results" => results })
requester
end
def response_with_build_id
OpenStruct.new(:response => OpenStruct.new(:code => "200", :body => "5"))
end
def error_response(opts = {})
OpenStruct.new(:response => OpenStruct.new(opts))
end
def build_with_result(results)
requester_with_result(results).run_tests(RspecAdapter, 'spec')
end
def setup
ENV['USE_JRUBY'] = nil
ENV['IN_TEST'] = 'true'
end
def mock_file_sizes
flexmock(File).should_receive(:stat).and_return(mock = Object.new)
flexmock(mock).should_receive(:size).and_return(0)
end
def fixture_path(local_path)
File.join(File.dirname(__FILE__), local_path)
end
context "self.create_by_config" do
should 'create a requester from config' do
requester = Requester.create_by_config(fixture_path("testbot.yml"))
assert_equal 'hostname', requester.config.server_host
assert_equal '/path', requester.config.rsync_path
assert_equal '.git tmp', requester.config.rsync_ignores
assert_equal 'appname', requester.config.project
assert_equal false, requester.config.ssh_tunnel
assert_equal 'user', requester.config.server_user
assert_equal '50%', requester.config.available_runner_usage
end
should 'accept ERB-snippets in testbot.yml' do
requester = Requester.create_by_config(fixture_path("testbot_with_erb.yml"))
assert_equal 'dynamic_host', requester.config.server_host
assert_equal '50%', requester.config.available_runner_usage
end
end
context "initialize" do
should "use defaults when values are missing" do
expected = { :server_host => 'hostname',
:rsync_path => Testbot::DEFAULT_SERVER_PATH,
:project => Testbot::DEFAULT_PROJECT,
:server_user => Testbot::DEFAULT_USER,
:available_runner_usage => Testbot::DEFAULT_RUNNER_USAGE }
actual = Requester.new({ "server_host" => 'hostname' }).config
assert_equal OpenStruct.new(expected), actual
end
end
context "run_tests" do
should "should be able to create a build" do
requester = Requester.new(:server_host => "192.168.1.100", :rsync_path => '/path', :available_runner_usage => '60%', :project => 'things', :server_user => "cruise")
flexmock(RspecAdapter).should_receive(:test_files).with('spec').once.and_return([ 'spec/models/house_spec.rb', 'spec/models/car_spec.rb' ])
flexmock(File).should_receive(:stat).once.with("spec/models/house_spec.rb").and_return(mock = Object.new); flexmock(mock).should_receive(:size).and_return(10)
flexmock(File).should_receive(:stat).once.with("spec/models/car_spec.rb").and_return(mock = Object.new); flexmock(mock).should_receive(:size).and_return(20)
flexmock(HTTParty).should_receive(:post).once.with("http://192.168.1.100:#{Testbot::SERVER_PORT}/builds",
:body => { :type => "spec",
:root => "cruise@192.168.1.100:/path",
:project => "things",
:available_runner_usage => "60%",
:files => "spec/models/house_spec.rb" +
" spec/models/car_spec.rb",
:sizes => "10 20",
:jruby => false }).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).and_return({ "done" => true, 'results' => '', "success" => true })
flexmock(requester).should_receive(:sleep)
flexmock(requester).should_receive(:print)
flexmock(requester).should_receive(:puts)
flexmock(requester).should_receive(:system)
assert_equal true, requester.run_tests(RspecAdapter, 'spec')
end
should "print a message and exit if the status is 503" do
requester = Requester.new(:server_host => "192.168.1.100")
flexmock(requester).should_receive(:find_tests).and_return([ 'spec/models/house_spec.rb', 'spec_models/car_spec.rb' ])
flexmock(requester).should_receive(:system)
flexmock(HTTParty).should_receive(:post).and_return(error_response(:code => "503"))
flexmock(requester).should_receive(:puts)
assert_equal false, requester.run_tests(RspecAdapter, 'spec')
end
should "print what the server returns in case there is anything but a 200 response" do
requester = Requester.new(:server_host => "192.168.1.100")
flexmock(requester).should_receive(:find_tests).and_return([ 'spec/models/house_spec.rb', 'spec_models/car_spec.rb' ])
flexmock(requester).should_receive(:system)
flexmock(HTTParty).should_receive(:post).and_return(error_response(:code => "123", :body => "Some error"))
flexmock(requester).should_receive(:puts).with("Could not create build, 123: Some error")
assert_equal false, requester.run_tests(RspecAdapter, 'spec')
end
should "print the sum of results formatted by the adapter" do
requester = Requester.new(:server_host => "192.168.1.100")
flexmock(requester).should_receive(:find_tests).and_return([ 'spec/models/house_spec.rb', 'spec_models/car_spec.rb' ])
flexmock(requester).should_receive(:system)
flexmock(HTTParty).should_receive(:post).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).times(2).with("http://192.168.1.100:#{Testbot::SERVER_PORT}/builds/5",
:format => :json).and_return({ "done" => false, "results" => "job 2 done: ...." },
{ "done" => true, "results" => "job 2 done: ....job 1 done: ...." })
mock_file_sizes
flexmock(requester).should_receive(:sleep).times(2).with(0.5)
flexmock(requester).should_receive(:print).once.with("job 2 done: ....")
flexmock(requester).should_receive(:print).once.with("job 1 done: ....")
flexmock(requester).should_receive(:puts).once.with("\nformatted result")
flexmock(RspecAdapter).should_receive(:sum_results).with("job 2 done: ....job 1 done: ....").and_return("formatted result")
requester.run_tests(RspecAdapter, 'spec')
end
should "keep calling the server for results until done" do
requester = Requester.new(:server_host => "192.168.1.100")
flexmock(requester).should_receive(:find_tests).and_return([ 'spec/models/house_spec.rb', 'spec_models/car_spec.rb' ])
flexmock(requester).should_receive(:system)
flexmock(HTTParty).should_receive(:post).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).times(2).with("http://192.168.1.100:#{Testbot::SERVER_PORT}/builds/5",
:format => :json).and_return({ "done" => false, "results" => "job 2 done: ...." },
{ "done" => true, "results" => "job 2 done: ....job 1 done: ...." })
mock_file_sizes
flexmock(requester).should_receive(:sleep).times(2).with(0.5)
flexmock(requester).should_receive(:print).once.with("job 2 done: ....")
flexmock(requester).should_receive(:print).once.with("job 1 done: ....")
flexmock(requester).should_receive(:puts).once.with("\n\033[32m0 examples, 0 failures\033[0m")
requester.run_tests(RspecAdapter, 'spec')
end
should "return false if not successful" do
requester = Requester.new(:server_host => "192.168.1.100")
flexmock(requester).should_receive(:find_tests).and_return([ 'spec/models/house_spec.rb', 'spec_models/car_spec.rb' ])
flexmock(requester).should_receive(:system)
flexmock(HTTParty).should_receive(:post).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).once.with("http://192.168.1.100:#{Testbot::SERVER_PORT}/builds/5",
:format => :json).and_return({ "success" => false, "done" => true, "results" => "job 2 done: ....job 1 done: ...." })
flexmock(requester).should_receive(:sleep).once.with(0.5)
flexmock(requester).should_receive(:print).once.with("job 2 done: ....job 1 done: ....")
flexmock(requester).should_receive(:puts).once.with("\n\033[32m0 examples, 0 failures\033[0m")
mock_file_sizes
assert_equal false, requester.run_tests(RspecAdapter, 'spec')
end
should "not print empty lines when there is no result" do
requester = Requester.new(:server_host => "192.168.1.100")
flexmock(requester).should_receive(:find_tests).and_return([ 'spec/models/house_spec.rb', 'spec_models/car_spec.rb' ])
flexmock(requester).should_receive(:system)
flexmock(HTTParty).should_receive(:post).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).times(2).with("http://192.168.1.100:#{Testbot::SERVER_PORT}/builds/5",
:format => :json).and_return({ "done" => false, "results" => "" },
{ "done" => true, "results" => "job 2 done: ....job 1 done: ...." })
flexmock(requester).should_receive(:sleep).times(2).with(0.5)
flexmock(requester).should_receive(:print).once.with("job 2 done: ....job 1 done: ....")
flexmock(requester).should_receive(:puts).once.with("\n\033[32m0 examples, 0 failures\033[0m")
mock_file_sizes
requester.run_tests(RspecAdapter, 'spec')
end
should "sync the files to the server" do
requester = Requester.new(:server_host => "192.168.1.100", :rsync_path => '/path', :rsync_ignores => '.git tmp')
flexmock(requester).should_receive(:find_tests).and_return([ 'spec/models/house_spec.rb', 'spec_models/car_spec.rb' ])
flexmock(requester).should_receive(:system)
flexmock(HTTParty).should_receive(:post).and_return(response_with_build_id)
flexmock(requester).should_receive(:sleep).once
flexmock(requester).should_receive(:print)
flexmock(requester).should_receive(:puts)
flexmock(HTTParty).should_receive(:get).once.with("http://192.168.1.100:#{Testbot::SERVER_PORT}/builds/5",
:format => :json).and_return({ "done" => true, "results" => "" })
flexmock(requester).should_receive('system').with("rsync -az --delete --delete-excluded -e ssh --exclude='.git' --exclude='tmp' . testbot@192.168.1.100:/path")
mock_file_sizes
requester.run_tests(RspecAdapter, 'spec')
end
should "just try again if the request encounters an error while running and print on the fith time" do
requester = Requester.new(:server_host => "192.168.1.100")
flexmock(requester).should_receive(:find_tests).and_return([ 'spec/models/house_spec.rb', 'spec_models/car_spec.rb' ])
flexmock(requester).should_receive(:system)
flexmock(HTTParty).should_receive(:post).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).times(5).with("http://192.168.1.100:#{Testbot::SERVER_PORT}/builds/5",
:format => :json).and_raise('some connection error')
flexmock(HTTParty).should_receive(:get).times(1).with("http://192.168.1.100:#{Testbot::SERVER_PORT}/builds/5",
:format => :json).and_return({ "done" => true, "results" => "job 2 done: ....job 1 done: ...." })
flexmock(requester).should_receive(:sleep).times(6).with(0.5)
flexmock(requester).should_receive(:puts).once.with("Failed to get status: some connection error")
flexmock(requester).should_receive(:print).once.with("job 2 done: ....job 1 done: ....")
flexmock(requester).should_receive(:puts).once.with("\n\033[32m0 examples, 0 failures\033[0m")
mock_file_sizes
requester.run_tests(RspecAdapter, 'spec')
end
should "just try again if the status returns as nil" do
requester = Requester.new(:server_host => "192.168.1.100")
flexmock(requester).should_receive(:find_tests).and_return([ 'spec/models/house_spec.rb', 'spec_models/car_spec.rb' ])
flexmock(requester).should_receive(:system)
flexmock(HTTParty).should_receive(:post).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).times(2).with("http://192.168.1.100:#{Testbot::SERVER_PORT}/builds/5",
:format => :json).and_return(nil,
{ "done" => true, "results" => "job 2 done: ....job 1 done: ...." })
flexmock(requester).should_receive(:sleep).times(2).with(0.5)
flexmock(requester).should_receive(:print).once.with("job 2 done: ....job 1 done: ....")
flexmock(requester).should_receive(:puts).once.with("\n\033[32m0 examples, 0 failures\033[0m")
mock_file_sizes
requester.run_tests(RspecAdapter, 'spec')
end
should "remove unnessesary output from rspec when told to do so" do
requester = Requester.new(:server_host => "192.168.1.100", :simple_output => true)
flexmock(requester).should_receive(:find_tests).and_return([ 'spec/models/house_spec.rb', 'spec_models/car_spec.rb' ])
flexmock(requester).should_receive(:system)
flexmock(HTTParty).should_receive(:post).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).times(2).with("http://192.168.1.100:#{Testbot::SERVER_PORT}/builds/5",
:format => :json).and_return(nil,
{ "done" => true, "results" => "testbot4:\n....\n\nFinished in 84.333 seconds\n\n206 examples, 0 failures, 2 pending; testbot4:\n.F..\n\nFinished in 84.333 seconds\n\n206 examples, 0 failures, 2 pending" })
flexmock(requester).should_receive(:sleep).times(2).with(0.5)
# Imperfect match, includes "." in 84.333, but good enough.
flexmock(requester).should_receive(:print).once.with("......F...")
flexmock(requester).should_receive(:print)
flexmock(requester).should_receive(:puts)
mock_file_sizes
requester.run_tests(RspecAdapter, 'spec')
end
should "use SSHTunnel when specified (with a port that does not collide with the runner)" do
requester = Requester.new(:ssh_tunnel => true, :server_host => "somewhere")
flexmock(requester).should_receive(:system)
flexmock(SSHTunnel).should_receive(:new).once.with("somewhere", "testbot", 2299).and_return(ssh_tunnel = Object.new)
flexmock(ssh_tunnel).should_receive(:open).once
flexmock(requester).should_receive(:find_tests).and_return([ 'spec/models/house_spec.rb' ])
flexmock(HTTParty).should_receive(:post).with("http://127.0.0.1:2299/builds", any).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).and_return({ "done" => true, "results" => "job 1 done: ...." })
flexmock(requester).should_receive(:sleep)
flexmock(requester).should_receive(:print)
flexmock(requester).should_receive(:puts)
mock_file_sizes
requester.run_tests(RspecAdapter, 'spec')
end
should "use another user for rsync and ssh_tunnel when specified" do
requester = Requester.new(:ssh_tunnel => true, :server_host => "somewhere",
:server_user => "cruise", :rsync_path => "/tmp/testbot/foo")
flexmock(SSHTunnel).should_receive(:new).once.with("somewhere", "cruise", 2299).and_return(ssh_tunnel = Object.new)
flexmock(ssh_tunnel).should_receive(:open).once
flexmock(requester).should_receive(:find_tests).and_return([ 'spec/models/house_spec.rb' ])
flexmock(HTTParty).should_receive(:post).with("http://127.0.0.1:2299/builds", any).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).and_return({ "done" => true, "results" => "job 1 done: ...." })
flexmock(requester).should_receive(:sleep)
flexmock(requester).should_receive(:print)
flexmock(requester).should_receive(:puts)
flexmock(requester).should_receive('system').with("rsync -az --delete --delete-excluded -e ssh . cruise@somewhere:/tmp/testbot/foo")
mock_file_sizes
requester.run_tests(RspecAdapter, 'spec')
end
should "use another port for cucumber to be able to run at the same time as rspec" do
requester = Requester.new(:ssh_tunnel => true, :server_host => "somewhere")
flexmock(requester).should_receive(:system)
flexmock(SSHTunnel).should_receive(:new).once.with("somewhere", "testbot", 2230).and_return(ssh_tunnel = Object.new)
flexmock(ssh_tunnel).should_receive(:open).once
flexmock(requester).should_receive(:find_tests).and_return([ 'features/some.feature' ])
flexmock(HTTParty).should_receive(:post).with("http://127.0.0.1:2230/builds", any).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).and_return({ "done" => true, "results" => "job 1 done: ...." })
flexmock(requester).should_receive(:sleep)
flexmock(requester).should_receive(:print)
flexmock(requester).should_receive(:puts)
mock_file_sizes
requester.run_tests(CucumberAdapter, 'features')
end
should "use another port for Test::Unit" do
requester = Requester.new(:ssh_tunnel => true, :server_host => "somewhere")
flexmock(requester).should_receive(:system)
flexmock(SSHTunnel).should_receive(:new).once.with("somewhere", "testbot", 2231).and_return(ssh_tunnel = Object.new)
flexmock(ssh_tunnel).should_receive(:open).once
flexmock(requester).should_receive(:find_tests).and_return([ 'test/some_test.rb' ])
flexmock(HTTParty).should_receive(:post).with("http://127.0.0.1:2231/builds", any).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).and_return({ "done" => true, "results" => "job 1 done: ...." })
flexmock(requester).should_receive(:sleep)
flexmock(requester).should_receive(:print)
flexmock(requester).should_receive(:puts)
mock_file_sizes
requester.run_tests(TestUnitAdapter, 'test')
end
should "request a run with jruby if USE_JRUBY is set" do
ENV['USE_JRUBY'] = "true"
requester = Requester.new
flexmock(requester).should_receive(:system)
# This is quite ugly. I want something like hash_including instead...
other_args = { :type=>"test", :available_runner_usage=>"100%",
:root=>"testbot@:/tmp/testbot/#{ENV['USER']}", :files=>"test/some_test.rb",
:sizes=>"0", :project=>"project" }
flexmock(TestUnitAdapter).should_receive(:test_files).and_return([ 'test/some_test.rb' ])
flexmock(HTTParty).should_receive(:post).with(any, :body => other_args.merge({ :jruby => true })).and_return(response_with_build_id)
flexmock(HTTParty).should_receive(:get).and_return({ "done" => true, "results" => "job 1 done: ...." })
flexmock(requester).should_receive(:sleep)
flexmock(requester).should_receive(:print)
flexmock(requester).should_receive(:puts)
mock_file_sizes
requester.run_tests(TestUnitAdapter, 'test')
end
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/fixtures/local/spec/models/car_spec.rb | test/fixtures/local/spec/models/car_spec.rb | ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false | |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/fixtures/local/spec/models/house_spec.rb | test/fixtures/local/spec/models/house_spec.rb | ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false | |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/runner/safe_result_text_test.rb | test/runner/safe_result_text_test.rb | require File.expand_path(File.join(File.dirname(__FILE__), '../../lib/shared/testbot.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), '../../lib/runner/safe_result_text.rb'))
require 'test/unit'
require 'shoulda'
module Testbot::Runner
class SafeResultTextTest < Test::Unit::TestCase
should "not break escape sequences" do
assert_equal "^[[32m.^[[0m^[[32m.^[[0m", SafeResultText.clean("^[[32m.^[[0m^[[32m.^[[0m^[[32m.")
assert_equal "^[[32m.^[[0m^[[32m.^[[0m", SafeResultText.clean("^[[32m.^[[0m^[[32m.^[[0m^[[3")
assert_equal "^[[32m.^[[0m", SafeResultText.clean("^[[32m.^[[0m^[")
assert_equal "[32m.[0m[32m.[0m[3", SafeResultText.clean("[32m.[0m[32m.[0m[3")
assert_equal "...", SafeResultText.clean("...")
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/runner/job_test.rb | test/runner/job_test.rb | require File.expand_path(File.join(File.dirname(__FILE__), '../../lib/shared/testbot.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), '../../lib/runner/job.rb'))
require 'test/unit'
require 'shoulda'
require 'flexmock/test_unit'
module Testbot::Runner
class JobTest < Test::Unit::TestCase
def expect_put_with(id, result_text, status, time = 0)
expected_result = "\n#{`hostname`.chomp}:#{Dir.pwd}\n"
expected_result += result_text
flexmock(Server).should_receive(:put).once.with("/jobs/#{id}", :body =>
{ :result => expected_result, :status => status, :time => time })
end
def expect_put
flexmock(Server).should_receive(:put).once
end
def expect_put_to_timeout
flexmock(Server).should_receive(:put).and_raise(Timeout::Error)
end
def stub_duration(seconds)
time ||= Time.now
flexmock(Time).should_receive(:now).and_return(time, time + seconds)
end
should "be able to run a successful job" do
job = Job.new(Runner.new({}), 10, "00:00", "project", "/tmp/testbot/user", "spec", "ruby", "spec/foo_spec.rb spec/bar_spec.rb")
flexmock(job).should_receive(:puts)
stub_duration(0)
expect_put_with(10, "result text", "successful")
flexmock(job).should_receive(:run_and_return_result).once.
with("export RAILS_ENV=test; export TEST_ENV_NUMBER=; cd project; export RSPEC_COLOR=true; ruby -S bundle exec rspec spec/foo_spec.rb spec/bar_spec.rb").
and_return('result text')
flexmock(RubyEnv).should_receive(:bundler?).returns(true)
flexmock(RubyEnv).should_receive(:rvm?).returns(false)
job.run(0)
end
should "not raise an error when posting results time out" do
job = Job.new(Runner.new({}), 10, "00:00", "project", "/tmp/testbot/user", "spec", "ruby", "spec/foo_spec.rb spec/bar_spec.rb")
flexmock(job).should_receive(:puts)
# We're using send here because triggering post_results though the rest of the
# code requires very complex setup. The code need to be refactored to be more testable.
expect_put
job.send(:post_results, "result text")
expect_put_to_timeout
job.send(:post_results, "result text")
end
should "not be successful when the job fails" do
job = Job.new(Runner.new({}), 10, "00:00", "project", "/tmp/testbot/user", "spec", "ruby", "spec/foo_spec.rb spec/bar_spec.rb")
flexmock(job).should_receive(:puts)
stub_duration(0)
expect_put_with(10, "result text", "failed")
flexmock(job).should_receive(:run_and_return_result).and_return('result text')
flexmock(job).should_receive(:success?).and_return(false)
job.run(0)
end
should "set an instance number when the instance is not 0" do
job = Job.new(Runner.new({}), 10, "00:00", "project", "/tmp/testbot/user", "spec", "ruby", "spec/foo_spec.rb spec/bar_spec.rb")
flexmock(job).should_receive(:puts)
stub_duration(0)
expect_put_with(10, "result text", "successful")
flexmock(job).should_receive(:run_and_return_result).
with(/TEST_ENV_NUMBER=2/).
and_return('result text')
flexmock(RubyEnv).should_receive(:rvm?).returns(false)
job.run(1)
end
should "return test runtime in milliseconds" do
job = Job.new(Runner.new({}), 10, "00:00", "project", "/tmp/testbot/user", "spec", "ruby", "spec/foo_spec.rb spec/bar_spec.rb")
flexmock(job).should_receive(:puts)
stub_duration(10.55)
expect_put_with(10, "result text", "successful", 1055)
flexmock(job).should_receive(:run_and_return_result).and_return('result text')
flexmock(RubyEnv).should_receive(:rvm?).returns(false)
job.run(0)
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/server/server_test.rb | test/server/server_test.rb | require File.expand_path(File.join(File.dirname(__FILE__), '../../lib/server/server'))
require 'test/unit'
require 'rack/test'
require 'shoulda'
require 'flexmock/test_unit'
set :environment, :test
module Testbot::Server
class ServerTest < Test::Unit::TestCase
include Rack::Test::Methods
def setup
Job.delete_all
Runner.delete_all
Build.delete_all
end
def app
Sinatra::Application
end
context "POST /builds" do
should "create a build and return its id" do
flexmock(Runner).should_receive(:total_instances).and_return(2)
post '/builds', :files => 'spec/models/car_spec.rb spec/models/house_spec.rb', :root => 'server:/path/to/project', :type => 'spec', :available_runner_usage => "100%", :project => 'things', :sizes => "10 20", :jruby => false
first_build = Build.all.first
assert last_response.ok?
assert_equal first_build.id.to_s, last_response.body
assert_equal 'spec/models/car_spec.rb spec/models/house_spec.rb', first_build.files
assert_equal '10 20', first_build.sizes
assert_equal 'server:/path/to/project', first_build.root
assert_equal 'spec', first_build.type
assert_equal 'things', first_build.project
assert_equal 0, first_build.jruby
assert_equal '', first_build.results
assert_equal true, first_build.success
end
should "create jobs from the build based on the number of total instances" do
flexmock(Runner).should_receive(:total_instances).and_return(2)
flexmock(Group).should_receive(:build).with(["spec/models/car_spec.rb", "spec/models/car2_spec.rb", "spec/models/house_spec.rb", "spec/models/house2_spec.rb"], [ 1, 1, 1, 1 ], 2, 'spec').once.and_return([
["spec/models/car_spec.rb", "spec/models/car2_spec.rb"],
["spec/models/house_spec.rb", "spec/models/house2_spec.rb"]
])
post '/builds', :files => 'spec/models/car_spec.rb spec/models/car2_spec.rb spec/models/house_spec.rb spec/models/house2_spec.rb', :root => 'server:/path/to/project', :type => 'spec', :available_runner_usage => "100%", :project => 'things', :sizes => "1 1 1 1", :jruby => true
assert_equal 2, Job.count
first_job, last_job = Job.all
assert_equal 'spec/models/car_spec.rb spec/models/car2_spec.rb', first_job.files
assert_equal 'spec/models/house_spec.rb spec/models/house2_spec.rb', last_job.files
assert_equal 'server:/path/to/project', first_job.root
assert_equal 'spec', first_job.type
assert_equal 'things', first_job.project
assert_equal 1, first_job.jruby
assert_equal Build.all.first, first_job.build
end
should "return a 503 error if there are no known runners" do
flexmock(Runner).should_receive(:total_instances).and_return(0)
post '/builds', :files => 'spec/models/car_spec.rb spec/models/car2_spec.rb spec/models/house_spec.rb spec/models/house2_spec.rb', :root => 'server:/path/to/project', :type => 'spec', :available_runner_usage => "100%", :project => 'things', :sizes => "1 1 1 1", :jruby => true
assert_equal 0, Job.count
assert_equal 503, last_response.status
assert_equal "No runners available", last_response.body
end
should "only use resources according to available_runner_usage" do
flexmock(Runner).should_receive(:total_instances).and_return(4)
flexmock(Group).should_receive(:build).with(["spec/models/car_spec.rb", "spec/models/car2_spec.rb", "spec/models/house_spec.rb", "spec/models/house2_spec.rb"], [ 1, 1, 1, 1 ], 2, 'spec').and_return([])
post '/builds', :files => 'spec/models/car_spec.rb spec/models/car2_spec.rb spec/models/house_spec.rb spec/models/house2_spec.rb', :root => 'server:/path/to/project', :type => 'spec', :sizes => "1 1 1 1", :available_runner_usage => "50%"
end
end
context "GET /builds/:id" do
should 'return the build status' do
build = Build.create(:done => false, :results => "testbot5\n..........\ncompleted", :success => false)
get "/builds/#{build.id}"
assert_equal true, last_response.ok?
assert_equal ({ "done" => false, "results" => "testbot5\n..........\ncompleted", "success" => false }),
JSON.parse(last_response.body)
end
should 'remove a build that is done' do
build = Build.create(:done => true)
get "/builds/#{build.id}"
assert_equal true, JSON.parse(last_response.body)['done']
assert_equal 0, Build.count
end
should 'remove all related jobs of a build that is done' do
build = Build.create(:done => true)
related_job = Job.create(:build => build)
other_job = Job.create(:build => nil)
get "/builds/#{build.id}"
assert !Job.find(related_job.id)
assert Job.find(other_job.id)
end
end
context "GET /jobs/next" do
should "be able to return a job and mark it as taken" do
build = Build.create
job1 = Job.create :files => 'spec/models/car_spec.rb', :root => 'server:/project', :type => 'spec', :build => build, :project => 'things', :jruby => 1
get '/jobs/next', :version => Testbot.version
assert last_response.ok?
assert_equal [ job1.id, build.id, "things", "server:/project", "spec", "jruby", "spec/models/car_spec.rb" ].join(','), last_response.body
assert job1.taken_at != nil
end
should "not return a job that has already been taken" do
build = Build.create
job1 = Job.create :files => 'spec/models/car_spec.rb', :taken_at => Time.now, :type => 'spec', :build => build
job2 = Job.create :files => 'spec/models/house_spec.rb', :root => 'server:/project', :type => 'spec', :build => build, :project => 'things', :jruby => 0
get '/jobs/next', :version => Testbot.version
assert last_response.ok?
assert_equal [ job2.id, build.id, "things", "server:/project", "spec", "ruby", "spec/models/house_spec.rb" ].join(','), last_response.body
assert job2.taken_at != nil
end
should "not return a job if there isnt any" do
get '/jobs/next', :version => Testbot.version
assert last_response.ok?
assert_equal '', last_response.body
end
should "save which runner takes a job" do
job = Job.create :files => 'spec/models/house_spec.rb', :root => 'server:/project', :type => 'spec', :build => Build.create
get '/jobs/next', :version => Testbot.version
assert_equal Runner.first, job.taken_by
end
should "save information about the runners" do
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini.local', :uid => "00:01:...", :idle_instances => 2, :max_instances => 4
runner = Runner.first
assert_equal Testbot.version, runner.version
assert_equal '127.0.0.1', runner.ip
assert_equal 'macmini.local', runner.hostname
assert_equal '00:01:...', runner.uid
assert_equal 2, runner.idle_instances
assert_equal 4, runner.max_instances
assert (Time.now - 5) < runner.last_seen_at
assert (Time.now + 5) > runner.last_seen_at
end
should "only create one record for the same mac" do
get '/jobs/next', :version => Testbot.version, :uid => "00:01:..."
get '/jobs/next', :version => Testbot.version, :uid => "00:01:..."
assert_equal 1, Runner.count
end
should "not return anything to outdated clients" do
Job.create :files => 'spec/models/house_spec.rb', :root => 'server:/project'
get '/jobs/next', :version => "1", :uid => "00:..."
assert last_response.ok?
assert_equal '', last_response.body
end
should "only give jobs from the same source to a runner" do
build = Build.create
job1 = Job.create :files => 'spec/models/car_spec.rb', :type => 'spec', :build => build
get '/jobs/next', :version => Testbot.version, :uid => "00:...", :build_id => build.id
# Creating the second job here because of the random lookup.
job2 = Job.create :files => 'spec/models/house_spec.rb', :root => 'server:/project', :type => 'spec', :build => build
get '/jobs/next', :version => Testbot.version, :uid => "00:...", :build_id => build.id + 1
assert last_response.ok?
assert_equal '', last_response.body
end
should "not give more jruby jobs to an instance that can't take more" do
build = Build.create
job1 = Job.create :files => 'spec/models/car_spec.rb', :type => 'spec', :jruby => 1, :build => build
get '/jobs/next', :version => Testbot.version, :uid => "00:..."
# Creating the second job here because of the random lookup.
job2 = Job.create :files => 'spec/models/house_spec.rb', :root => 'server:/project', :type => 'spec', :jruby => 1, :build => build
get '/jobs/next', :version => Testbot.version, :uid => "00:...", :no_jruby => "true"
assert last_response.ok?
assert_equal '', last_response.body
end
should "still return other jobs when the runner cant take more jruby jobs" do
job1 = Job.create :files => 'spec/models/car_spec.rb', :type => 'spec', :jruby => 1, :build => Build.create
get '/jobs/next', :version => Testbot.version, :uid => "00:..."
# Creating the second job here because of the random lookup.
job2 = Job.create :files => 'spec/models/house_spec.rb', :root => 'server:/project', :type => 'spec', :jruby => 0, :build => Build.create
get '/jobs/next', :version => Testbot.version, :uid => "00:...", :no_jruby => "true"
assert last_response.ok?
assert_equal job2.id.to_s, last_response.body.split(',')[0]
end
should "return the jobs in random order in order to start working for a new build right away" do
build1, build2 = Build.create, Build.create
20.times { Job.create :files => 'spec/models/house_spec.rb', :root => 'server:/project', :type => 'spec', :build => build1 }
20.times { Job.create :files => 'spec/models/house_spec.rb', :root => 'server:/project', :type => 'spec', :build => build2 }
build_ids = (0...10).map {
get '/jobs/next', :version => Testbot.version, :uid => "00:..."
last_response.body.split(',')[1]
}
assert build_ids.find { |build_id| build_id == build1.id.to_s }
assert build_ids.find { |build_id| build_id == build2.id.to_s }
end
should "return the jobs randomly when passing build_id" do
build = Build.create
20.times { Job.create :files => 'spec/models/house_spec.rb', :root => 'server:/project', :type => 'spec', :build => build }
20.times { Job.create :files => 'spec/models/car_spec.rb', :root => 'server:/project', :type => 'spec', :build => build }
files = (0...10).map {
get '/jobs/next', :version => Testbot.version, :uid => "00:...", :build_id => build.id
last_response.body.split(',').last
}
assert files.find { |file| file.include?('car') }
assert files.find { |file| file.include?('house') }
end
should "return taken jobs to other runners if the runner hasn't been seen for 10 seconds or more" do
missing_runner = Runner.create(:last_seen_at => Time.now - 15)
build = Build.create
old_taken_job = Job.create :files => 'spec/models/house_spec.rb', :root => 'server:/project', :type => 'spec', :build => build, :taken_by => missing_runner, :taken_at => Time.now - 30, :project => 'things'
new_runner = Runner.create(:uid => "00:01")
get '/jobs/next', :version => Testbot.version, :uid => "00:01"
assert_equal new_runner, old_taken_job.taken_by
assert last_response.ok?
assert_equal [ old_taken_job.id, build.id.to_s, "things", "server:/project", "spec", "ruby", "spec/models/house_spec.rb" ].join(','), last_response.body
end
end
context "/runners/outdated" do
should "return a list of outdated runners" do
get '/jobs/next', :version => "1", :hostname => 'macmini1.local', :uid => "00:01"
get '/jobs/next', :version => "1", :hostname => 'macmini2.local', :uid => "00:02"
get '/jobs/next'
get '/jobs/next', :version => Testbot.version.to_s, :hostname => 'macmini3.local', :uid => "00:03"
assert_equal 4, Runner.count
get '/runners/outdated'
assert last_response.ok?
assert_equal "127.0.0.1 macmini1.local 00:01\n127.0.0.1 macmini2.local 00:02\n127.0.0.1", last_response.body
end
end
context "GET /runners/available_runners" do
should "return a list of available runners" do
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini1.local', :uid => "00:01", :idle_instances => 2, :username => 'user1'
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini2.local', :uid => "00:02", :idle_instances => 4, :username => 'user2'
get '/runners/available'
assert last_response.ok?
assert_equal "127.0.0.1 macmini1.local 00:01 user1 2\n127.0.0.1 macmini2.local 00:02 user2 4", last_response.body
end
should "not return a runner as available when it hasnt pinged the server yet" do
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini1.local', :uid => "00:01", :username => 'user1'
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini2.local', :uid => "00:02", :idle_instances => 4, :username => 'user2'
get '/runners/available'
assert last_response.ok?
assert_equal "127.0.0.1 macmini2.local 00:02 user2 4", last_response.body
end
should "not return runners as available when not seen the last 10 seconds" do
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini1.local', :uid => "00:01", :idle_instances => 2, :username => "user1"
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini2.local', :uid => "00:02", :idle_instances => 4
Runner.find_by_uid("00:02").update(:last_seen_at => Time.now - 10)
get '/runners/available'
assert_equal "127.0.0.1 macmini1.local 00:01 user1 2", last_response.body
end
end
context "GET /runners/available_instances" do
should "return the number of available runner instances" do
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini1.local', :uid => "00:01", :idle_instances => 2
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini2.local', :uid => "00:02", :idle_instances => 4
get '/runners/available_instances'
assert last_response.ok?
assert_equal "6", last_response.body
end
should "not return instances as available when not seen the last 10 seconds" do
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini1.local', :uid => "00:01", :idle_instances => 2
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini2.local', :uid => "00:02", :idle_instances => 4
Runner.find_by_uid("00:02").update(:last_seen_at => Time.now - 10)
get '/runners/available_instances'
assert last_response.ok?
assert_equal "2", last_response.body
end
end
context "GET /runners/total_instances" do
should "return the number of available runner instances" do
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini1.local', :uid => "00:01", :max_instances => 2, :idle_instances => 1
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini2.local', :uid => "00:02", :max_instances => 4, :idle_instances => 2
get '/runners/total_instances'
assert last_response.ok?
assert_equal "6", last_response.body
end
should "not return instances as available when not seen the last 10 seconds" do
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini1.local', :uid => "00:01", :max_instances => 2, :idle_instances => 1
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini2.local', :uid => "00:02", :max_instances => 4, :idle_instances => 2
Runner.find_by_uid("00:02").update(:last_seen_at => Time.now - 10)
get '/runners/total_instances'
assert last_response.ok?
assert_equal "2", last_response.body
end
end
context "GET /runners/ping" do
should "update last_seen_at for the runner" do
runner = Runner.create(:uid => 'aa:aa:aa:aa:aa:aa')
get "/runners/ping", :uid => 'aa:aa:aa:aa:aa:aa', :version => Testbot.version
assert last_response.ok?
assert (Time.now - 5) < runner.last_seen_at
assert (Time.now + 5) > runner.last_seen_at
end
should "update data on the runner" do
build = Build.create
runner = Runner.create(:uid => 'aa:aa:..')
get "/runners/ping", :uid => 'aa:aa:..', :max_instances => 4, :idle_instances => 2, :hostname => "hostname1", :version => Testbot.version, :username => 'jocke', :build_id => build.id
assert last_response.ok?
assert_equal 'aa:aa:..', runner.uid
assert_equal 4, runner.max_instances
assert_equal 2, runner.idle_instances
assert_equal 'hostname1', runner.hostname
assert_equal Testbot.version, runner.version
assert_equal 'jocke', runner.username
assert_equal build, runner.build
end
should "do nothing if the version does not match" do
runner = Runner.create(:uid => 'aa:aa:..', :version => Testbot.version)
get "/runners/ping", :uid => 'aa:aa:..', :version => "OLD"
assert last_response.ok?
assert_equal Testbot.version, runner.version
end
should "do nothing if the runners isnt known yet found" do
get "/runners/ping", :uid => 'aa:aa:aa:aa:aa:aa', :version => Testbot.version
assert last_response.ok?
end
should "return an order to stop the build if the build id does not exist anymore" do
runner = Runner.create(:uid => 'aa:aa:..')
get "/runners/ping", :uid => 'aa:aa:..', :max_instances => 4, :idle_instances => 2, :hostname => "hostname1", :version => Testbot.version, :username => 'jocke', :build_id => 1
assert_equal last_response.body, "stop_build,1"
end
should "not return an order to stop a build without an id" do
runner = Runner.create(:uid => 'aa:aa:..')
get "/runners/ping", :uid => 'aa:aa:..', :max_instances => 4, :idle_instances => 2, :hostname => "hostname1", :version => Testbot.version, :username => 'jocke', :build_id => ''
assert_equal last_response.body, ''
get "/runners/ping", :uid => 'aa:aa:..', :max_instances => 4, :idle_instances => 2, :hostname => "hostname1", :version => Testbot.version, :username => 'jocke', :build_id => nil
assert_equal last_response.body, ''
end
end
context "PUT /jobs/:id" do
should "receive the results of a job" do
job = Job.create :files => 'spec/models/car_spec.rb', :taken_at => Time.now - 30
put "/jobs/#{job.id}", :result => 'test run result', :status => "successful"
assert last_response.ok?
assert_equal 'test run result', job.result
assert_equal 'successful', job.status
end
should "update the related build" do
build = Build.create
job1 = Job.create :files => 'spec/models/car_spec.rb', :taken_at => Time.now - 30, :build => build
job2 = Job.create :files => 'spec/models/car_spec.rb', :taken_at => Time.now - 30, :build => build
put "/jobs/#{job1.id}", :result => 'test run result 1\n', :status => "successful"
put "/jobs/#{job2.id}", :result => 'test run result 2\n', :status => "successful"
assert_equal 'test run result 1\ntest run result 2\n', build.results
assert_equal true, build.success
end
should "make the related build done if there are no more jobs for the build" do
build = Build.create
job1 = Job.create :files => 'spec/models/car_spec.rb', :taken_at => Time.now - 30, :build => build
job2 = Job.create :files => 'spec/models/car_spec.rb', :taken_at => Time.now - 30, :build => build
put "/jobs/#{job1.id}", :result => 'test run result 1\n', :status => "successful"
put "/jobs/#{job2.id}", :result => 'test run result 2\n', :status => "successful"
assert_equal true, build.done
end
should "make the build fail if one of the jobs fail" do
build = Build.create
job1 = Job.create :files => 'spec/models/car_spec.rb', :taken_at => Time.now - 30, :build => build
job2 = Job.create :files => 'spec/models/car_spec.rb', :taken_at => Time.now - 30, :build => build
put "/jobs/#{job1.id}", :result => 'test run result 1\n', :status => "failed"
put "/jobs/#{job2.id}", :result => 'test run result 2\n', :status => "successful"
assert_equal false, build.success
end
should "be able to update from multiple result postings" do
build = Build.create
job1 = Job.create :files => 'spec/models/car_spec.rb', :taken_at => Time.now - 30, :build => build
job2 = Job.create :files => 'spec/models/car_spec.rb', :taken_at => Time.now - 30, :build => build
# maybe later:
# put "/jobs/#{job.id}", :result => 'Preparing, db setup, etc.', :status => "preparing"
put "/jobs/#{job1.id}", :result => 'Running tests..', :status => "running"
put "/jobs/#{job2.id}", :result => 'Running other tests. done.', :status => "successful"
put "/jobs/#{job1.id}", :result => 'Running tests....', :status => "running"
assert_equal false, build.done
assert_equal false, job1.done
assert_equal "Running tests....", job1.result
assert_equal "Running tests..Running other tests. done...", build.results
end
should "not break when updating without new results" do
build = Build.create
job1 = Job.create :files => 'spec/models/car_spec.rb', :taken_at => Time.now - 30, :build => build
put "/jobs/#{job1.id}", :result => 'Running tests..', :status => "running"
put "/jobs/#{job1.id}", :result => '', :status => "successful"
assert_equal "Running tests..", build.results
end
end
context "GET /version" do
should "return its version" do
get '/version'
assert last_response.ok?
assert_equal Testbot.version.to_s, last_response.body
end
end
context "GET /runners" do
should "return runner information in json format" do
get '/jobs/next', :version => Testbot.version, :uid => "00:01"
get "/runners/ping", :uid => '00:01', :max_instances => 4, :idle_instances => 2, :hostname => "hostname1", :version => Testbot.version, :username => 'testbot', :build_id => nil
get '/runners'
assert last_response.ok?
assert_equal ([ { "version" => Testbot.version.to_s, "build" => nil, "hostname" => 'hostname1', "uid" => "00:01",
"idle_instances" => 2, "max_instances" => 4, "username" => 'testbot',
"ip" => "127.0.0.1", "last_seen_at" => Runner.first.last_seen_at.to_s } ]),
JSON.parse(last_response.body)
end
should "not return instances when not seen the last 10 seconds" do
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini1.local', :uid => "00:01", :idle_instances => 2
get '/jobs/next', :version => Testbot.version, :hostname => 'macmini2.local', :uid => "00:02", :idle_instances => 4
Runner.find_by_uid("00:02").update(:last_seen_at => Time.now - 10)
get '/runners'
assert last_response.ok?
parsed_body = JSON.parse(last_response.body)
assert_equal 1, parsed_body.size
assert_equal '00:01', parsed_body.first["uid"]
end
end
context "GET /status" do
should "return the contents of the status page" do
get '/status'
assert_equal true, last_response.body.include?('Testbot status')
end
end
context "GET /status/:dir/:file" do
should "return the file" do
get "/status/javascripts/jquery-1.4.4.min.js"
assert_equal true, last_response.body.include?('jQuery JavaScript Library v1.4.4')
end
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/server/group_test.rb | test/server/group_test.rb | require File.expand_path(File.join(File.dirname(__FILE__), '../../lib/server/group'))
require 'test/unit'
require 'shoulda'
require 'flexmock/test_unit'
module Testbot::Server
class GroupTest < Test::Unit::TestCase
context "self.build" do
should "create file groups based on the number of instances" do
groups = Group.build([ 'spec/models/car_spec.rb', 'spec/models/car2_spec.rb',
'spec/models/house_spec.rb', 'spec/models/house2_spec.rb' ], [ 1, 1, 1, 1 ], 2, 'spec')
assert_equal 2, groups.size
assert_equal [ 'spec/models/house2_spec.rb', 'spec/models/house_spec.rb' ], groups[0]
assert_equal [ 'spec/models/car2_spec.rb', 'spec/models/car_spec.rb' ], groups[1]
end
should "create a small grop when there isn't enough specs to fill a normal one" do
groups = Group.build(["spec/models/car_spec.rb", "spec/models/car2_spec.rb",
"spec/models/house_spec.rb", "spec/models/house2_spec.rb",
"spec/models/house3_spec.rb"], [ 1, 1, 1, 1, 1 ], 3, 'spec')
assert_equal 3, groups.size
assert_equal [ "spec/models/car_spec.rb" ], groups[2]
end
should "use sizes when building groups" do
groups = Group.build([ 'spec/models/car_spec.rb', 'spec/models/car2_spec.rb',
'spec/models/house_spec.rb', 'spec/models/house2_spec.rb' ], [ 40, 10, 10, 20 ], 2, 'spec')
assert_equal [ 'spec/models/car_spec.rb' ], groups[0]
assert ![ 'spec/models/house2_spec.rb', 'spec/models/car2_spec.rb', 'spec/models/house_spec.rb' ].
find { |file| !groups[1].include?(file) }
end
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/shared/testbot_test.rb | test/shared/testbot_test.rb | require File.expand_path(File.join(File.dirname(__FILE__), '../../lib/shared/testbot')) unless defined?(Testbot)
require 'test/unit'
require 'shoulda'
require 'flexmock/test_unit'
require 'sinatra'
require File.expand_path(File.join(File.dirname(__FILE__), '../../lib/requester/requester'))
require File.expand_path(File.join(File.dirname(__FILE__), '../../lib/server/server'))
module Testbot
module TestHelpers
def requester_attributes
{ :server_host => "192.168.0.100",
:rsync_path => nil,
:rsync_ignores => '', :server_user => nil, :available_runner_usage => nil,
:project => nil, :ssh_tunnel => nil }
end
end
class CLITest < Test::Unit::TestCase
include TestHelpers
context "self.run" do
context "with no args" do
should "return false" do
assert_equal false, CLI.run([])
end
end
context "with --help" do
should "return false" do
assert_equal false, CLI.run([ '--help' ])
end
end
context "with --version" do
should "print version and return true" do
flexmock(CLI).should_receive(:puts).once.with("Testbot #{Testbot.version}")
assert_equal true, CLI.run([ '--version' ])
end
end
context "with --server" do
should "start a server" do
flexmock(SimpleDaemonize).should_receive(:stop).once.with(Testbot::SERVER_PID)
flexmock(SimpleDaemonize).should_receive(:start).once.with(any, Testbot::SERVER_PID, "testbot (server)")
flexmock(CLI).should_receive(:puts).once.with("Testbot server started (pid: #{Process.pid})")
assert_equal true, CLI.run([ "--server" ])
end
should "start a server when start is passed" do
flexmock(SimpleDaemonize).should_receive(:stop).once.with(Testbot::SERVER_PID)
flexmock(SimpleDaemonize).should_receive(:start).once
flexmock(CLI).should_receive(:puts)
assert_equal true, CLI.run([ "--server", "start" ])
end
should "stop a server when stop is passed" do
flexmock(SimpleDaemonize).should_receive(:stop).once.with(Testbot::SERVER_PID).and_return(true)
flexmock(CLI).should_receive(:puts).once.with("Testbot server stopped")
assert_equal true, CLI.run([ "--server", "stop" ])
end
should "not print when SimpleDaemonize.stop returns false" do
flexmock(SimpleDaemonize).should_receive(:stop).and_return(false)
flexmock(CLI).should_receive(:puts).never
CLI.run([ "--stop", "server" ])
end
should "start it in the foreground with run" do
flexmock(SimpleDaemonize).should_receive(:stop).once.with(Testbot::SERVER_PID)
flexmock(SimpleDaemonize).should_receive(:start).never
flexmock(Sinatra::Application).should_receive(:run!).once.with(:environment => "production")
assert_equal true, CLI.run([ "--server", 'run' ])
end
end
context "with --runner" do
should "start a runner" do
flexmock(SimpleDaemonize).should_receive(:stop).once.with(Testbot::RUNNER_PID)
flexmock(SimpleDaemonize).should_receive(:start).once.with(any, Testbot::RUNNER_PID, "testbot (runner)")
flexmock(CLI).should_receive(:puts).once.with("Testbot runner started (pid: #{Process.pid})")
assert_equal true, CLI.run([ "--runner", "--connect", "192.168.0.100", "--working_dir", "/tmp/testbot" ])
end
should "start a runner when start is passed" do
flexmock(SimpleDaemonize).should_receive(:stop).once.with(Testbot::RUNNER_PID)
flexmock(SimpleDaemonize).should_receive(:start).once
flexmock(CLI).should_receive(:puts)
assert_equal true, CLI.run([ "--runner", "start", "--connect", "192.168.0.100" ])
end
should "stop a runner when stop is passed" do
flexmock(SimpleDaemonize).should_receive(:stop).once.with(Testbot::RUNNER_PID).and_return(true)
flexmock(CLI).should_receive(:puts).once.with("Testbot runner stopped")
assert_equal true, CLI.run([ "--runner", "stop" ])
end
should "return false without connect" do
assert_equal false, CLI.run([ "--runner", "--connect" ])
assert_equal false, CLI.run([ "--runner" ])
end
should "start it in the foreground with run" do
flexmock(SimpleDaemonize).should_receive(:stop).once.with(Testbot::RUNNER_PID)
flexmock(SimpleDaemonize).should_receive(:start).never
flexmock(Runner::Runner).should_receive(:new).once.and_return(mock = Object.new)
flexmock(mock).should_receive(:run!).once
assert_equal true, CLI.run([ "--runner", 'run', '--connect', '192.168.0.100' ])
end
end
Adapter.all.each do |adapter|
context "with --#{adapter.type}" do
should "start a #{adapter.name} requester and return true" do
flexmock(Requester::Requester).should_receive(:new).once.
with(requester_attributes).and_return(mock = Object.new)
flexmock(mock).should_receive(:run_tests).once.with(adapter, adapter.base_path)
assert_equal true, CLI.run([ "--#{adapter.type}", "--connect", "192.168.0.100" ])
end
should "accept a custom rsync_path" do
flexmock(Requester::Requester).should_receive(:new).once.
with(requester_attributes.merge({ :rsync_path => "/somewhere/else" })).
and_return(mock = Object.new)
flexmock(mock).should_receive(:run_tests)
CLI.run([ "--#{adapter.type}", "--connect", "192.168.0.100", '--rsync_path', '/somewhere/else' ])
end
should "accept rsync_ignores" do
flexmock(Requester::Requester).should_receive(:new).once.
with(requester_attributes.merge({ :rsync_ignores => "tmp log" })).
and_return(mock = Object.new)
flexmock(mock).should_receive(:run_tests)
CLI.run([ "--#{adapter.type}", "--connect", "192.168.0.100", '--rsync_ignores', 'tmp', 'log' ])
end
should "accept ssh tunnel" do
flexmock(Requester::Requester).should_receive(:new).once.
with(requester_attributes.merge({ :ssh_tunnel => true })).
and_return(mock = Object.new)
flexmock(mock).should_receive(:run_tests)
CLI.run([ "--#{adapter.type}", "--connect", "192.168.0.100", '--ssh_tunnel' ])
end
should "accept a custom user" do
flexmock(Requester::Requester).should_receive(:new).once.
with(requester_attributes.merge({ :server_user => "cruise" })).
and_return(mock = Object.new)
flexmock(mock).should_receive(:run_tests)
CLI.run([ "--#{adapter.type}", "--connect", "192.168.0.100", '--user', 'cruise' ])
end
should "accept a custom project name" do
flexmock(Requester::Requester).should_receive(:new).once.
with(requester_attributes.merge({ :project => "rspec" })).
and_return(mock = Object.new)
flexmock(mock).should_receive(:run_tests)
CLI.run([ "--#{adapter.type}", "--connect", "192.168.0.100", '--project', 'rspec' ])
end
end
end
end
context "self.parse_args" do
should 'convert ARGV arguments to a hash' do
hash = CLI.parse_args("--runner --connect http://127.0.0.1:#{Testbot::SERVER_PORT} --working_dir ~/testbot --ssh_tunnel user@testbot_server".split)
assert_equal ({ :runner => true, :connect => "http://127.0.0.1:#{Testbot::SERVER_PORT}", :working_dir => "~/testbot", :ssh_tunnel => "user@testbot_server" }), hash
end
should "handle just a key without a value" do
hash = CLI.parse_args([ "--server" ])
assert_equal ({ :server => true }), hash
end
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/shared/adapters/adapter_test.rb | test/shared/adapters/adapter_test.rb | require File.expand_path(File.join(File.dirname(__FILE__), '../../../lib/shared/adapters/adapter.rb'))
require 'test/unit'
require 'shoulda'
class AdapterTest < Test::Unit::TestCase
should "be able to find adapters" do
assert_equal RspecAdapter, Adapter.find(:spec)
assert_equal TestUnitAdapter, Adapter.find(:test)
end
should "find be able to find an adapter by string" do
assert_equal RspecAdapter, Adapter.find("spec")
assert_equal TestUnitAdapter, Adapter.find("test")
end
should "be able to return a list of adapters" do
assert Adapter.all.include?(RspecAdapter)
assert Adapter.all.include?(TestUnitAdapter)
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/shared/adapters/rspec_adapter_test.rb | test/shared/adapters/rspec_adapter_test.rb | require File.expand_path(File.join(File.dirname(__FILE__), '../../../lib/shared/adapters/rspec_adapter.rb'))
require 'test/unit'
require 'shoulda'
class RspecAdapterTest < Test::Unit::TestCase
context "sum_results" do
should "be able to parse and sum results" do
results =<<STR
srv-y5ei5:/tmp/testbot
..................FF..................................................
Finished in 4.962975 seconds
69 examples, 2 failures
testbot1:/tmp/testbot
.............F...........*........................
Finished in 9.987141 seconds
50 examples, 1 failure, 1 pending
testbot1:/tmp/testbot
.............FF.......****........................
Finished in 9.987141 seconds
50 examples, 2 failures, 3 pending
testbot1:/tmp/testbot
.
Finished in 9.987141 seconds
1 example, 0 failures, 0 pending
STR
assert_equal "170 examples, 5 failures, 4 pending", Color.strip(RspecAdapter.sum_results(results))
end
should "return 0 examples and failures for an empty resultset" do
assert_equal "0 examples, 0 failures", Color.strip(RspecAdapter.sum_results(""))
end
should "print in singular for examples" do
str =<<STR
testbot1:/tmp/testbot
.
Finished in 9.987141 seconds
1 example, 0 failures
STR
assert_equal "1 example, 0 failures", Color.strip(RspecAdapter.sum_results(str))
end
should "print in singular for failures" do
str =<<STR
testbot1:/tmp/testbot
F
Finished in 9.987141 seconds
0 example, 1 failures
STR
assert_equal "0 examples, 1 failure", Color.strip(RspecAdapter.sum_results(str))
end
should "make the result green if there is no failed or pending examples" do
str =<<STR
testbot1:/tmp/testbot
.
Finished in 9.987141 seconds
1 example, 0 failures
STR
assert_equal "\033[32m1 example, 0 failures\033[0m", RspecAdapter.sum_results(str)
end
should "make the result orange if there is pending examples" do
str =<<STR
testbot1:/tmp/testbot
*
Finished in 9.987141 seconds
1 example, 0 failures, 1 pending
STR
assert_equal "\033[33m1 example, 0 failures, 1 pending\033[0m", RspecAdapter.sum_results(str)
end
should "make the results red if there is failed examples" do
str = <<STR
testbot1:/tmp/testbot
F
Finished in 9.987141 seconds
1 example, 1 failures
STR
assert_equal "\033[31m1 example, 1 failure\033[0m", RspecAdapter.sum_results(str)
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/shared/adapters/cucumber_adapter_test.rb | test/shared/adapters/cucumber_adapter_test.rb | require File.expand_path(File.join(File.dirname(__FILE__), '../../../lib/shared/adapters/cucumber_adapter.rb'))
require 'test/unit'
require 'shoulda'
class CucumberAdapterTest < Test::Unit::TestCase
context "sum_results" do
should "be able to parse and sum results" do
results =<<STR
testbot4:/tmp/testbot
............................................................................................................................................................
13 scenarios (\033[32m13 passed\033[0m)
153 steps (\033[32m153 passed\033[0m)
0m25.537s
testbot3:/tmp/testbot
................................................................................................................
12 scenarios (\033[32m12 passed\033[0m)
109 steps (\033[32m109 passed\033[0m)
1m28.472s
STR
assert_equal "25 scenarios (25 passed)\n262 steps (262 passed)", Color.strip(CucumberAdapter.sum_results(results))
end
should "should handle undefined steps" do
results =<<STR
5 scenarios (1 failed, 1 undefined, 3 passed)
42 steps (1 failed, 3 skipped, 1 undefined, 37 passed)
5 scenarios (1 failed, 1 undefined, 3 passed)
42 steps (1 failed, 3 skipped, 1 undefined, 37 passed)
6 scenarios (6 passed)
80 steps (80 passed)
STR
assert_equal "16 scenarios (2 failed, 2 undefined, 12 passed)\n164 steps (2 failed, 6 skipped, 2 undefined, 154 passed)", Color.strip(CucumberAdapter.sum_results(results))
end
should "handle other combinations" do
results =<<STR
5 scenarios (1 failed, 1 undefined, 3 passed)
42 steps (1 failed, 1 undefined, 37 passed)
5 scenarios (1 failed, 1 undefined, 3 passed)
42 steps (3 skipped, 1 undefined, 37 passed)
6 scenarios (6 passed)
80 steps (80 passed)
STR
assert_equal "16 scenarios (2 failed, 2 undefined, 12 passed)\n164 steps (1 failed, 3 skipped, 2 undefined, 154 passed)", Color.strip(CucumberAdapter.sum_results(results))
end
should "colorize" do
results =<<STR
5 scenarios (1 failed, 1 undefined, 3 passed)
42 steps (1 failed, 3 skipped, 1 undefined, 37 passed)
STR
assert_equal "5 scenarios (\e[31m1 failed\e[0m, \e[33m1 undefined\e[0m, \e[32m3 passed\e[0m)\n42 steps (\e[31m1 failed\e[0m, \e[36m3 skipped\e[0m, \e[33m1 undefined\e[0m, \e[32m37 passed\e[0m)", CucumberAdapter.sum_results(results)
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/test/shared/adapters/helpers/ruby_env_test.rb | test/shared/adapters/helpers/ruby_env_test.rb | require File.expand_path(File.join(File.dirname(__FILE__), '../../../../lib/shared/adapters/helpers/ruby_env.rb'))
require 'test/unit'
require 'shoulda'
require 'flexmock/test_unit'
class RubyEnvTest < Test::Unit::TestCase
def setup
# Can't override a stub in flexmock?
def RubyEnv.rvm?; false; end
end
context "self.bundler?" do
should "return true if bundler is installed and there is a Gemfile" do
flexmock(Gem::Specification).should_receive(:find_by_name).with("bundler").once.and_return(true)
flexmock(File).should_receive(:exists?).with("path/to/project/Gemfile").once.and_return(true)
assert_equal true, RubyEnv.bundler?("path/to/project")
end
should "return false if bundler is installed but there is no Gemfile" do
flexmock(Gem::Specification).should_receive(:find_by_name).with("bundler").once.and_return(true)
flexmock(File).should_receive(:exists?).and_return(false)
assert_equal false, RubyEnv.bundler?("path/to/project")
end
should "return false if bundler is not installed" do
flexmock(Gem::Specification).should_receive(:find_by_name).with("bundler").once.and_return(false)
assert_equal false, RubyEnv.bundler?("path/to/project")
end
end
context "self.rvm_prefix" do
should "return rvm prefix if rvm is installed" do
def RubyEnv.rvm?; true; end
flexmock(File).should_receive(:exists?).with("path/to/project/.rvmrc").once.and_return(true)
flexmock(File).should_receive(:read).with("path/to/project/.rvmrc").once.and_return("rvm 1.8.7\n")
assert_equal "rvm 1.8.7 exec", RubyEnv.rvm_prefix("path/to/project")
end
should "return nil if rvm is not installed" do
assert_equal nil, RubyEnv.rvm_prefix("path/to/project")
end
end
context "self.ruby_command" do
should "use ruby by default" do
flexmock(RubyEnv).should_receive(:bundler?).and_return(false)
flexmock(File).should_receive(:exists?).and_return(false)
assert_equal 'ruby -S rspec', RubyEnv.ruby_command("path/to/project", :script => "script/spec", :bin => "rspec")
end
should "use bundler when available and use the binary when there is no script" do
flexmock(RubyEnv).should_receive(:bundler?).once.with("path/to/project").and_return(true)
flexmock(File).should_receive(:exists?).with("path/to/project/script/spec").and_return(false)
assert_equal 'ruby -S bundle exec rspec', RubyEnv.ruby_command("path/to/project", :script => "script/spec", :bin => "rspec")
end
should "use the script when it exists when using bundler" do
flexmock(RubyEnv).should_receive(:bundler?).and_return(true)
flexmock(File).should_receive(:exists?).and_return(true)
assert_equal 'ruby -S bundle exec script/spec', RubyEnv.ruby_command("path/to/project", :script => "script/spec", :bin => "rspec")
end
should "use the script when it exists when not using bundler" do
flexmock(RubyEnv).should_receive(:bundler?).and_return(false)
flexmock(File).should_receive(:exists?).and_return(true)
assert_equal 'ruby -S script/spec', RubyEnv.ruby_command("path/to/project", :script => "script/spec", :bin => "rspec")
end
should "not look for a script when none is provided" do
assert_equal 'ruby -S rspec', RubyEnv.ruby_command("path/to/project", :bin => "rspec")
end
should "be able to use jruby" do
flexmock(RubyEnv).should_receive(:bundler?).and_return(false)
flexmock(File).should_receive(:exists?).and_return(true)
assert_equal 'jruby -S script/spec', RubyEnv.ruby_command("path/to/project", :script => "script/spec",
:bin => "rspec", :ruby_interpreter => "jruby")
end
should "be able to use jruby with bundler" do
flexmock(RubyEnv).should_receive(:bundler?).and_return(true)
flexmock(File).should_receive(:exists?).and_return(true)
assert_equal 'jruby -S bundle exec script/spec', RubyEnv.ruby_command("path/to/project", :script => "script/spec",
:bin => "rspec", :ruby_interpreter => "jruby")
end
should "work when there is no binary specified and bundler is present" do
flexmock(RubyEnv).should_receive(:bundler?).and_return(true)
flexmock(File).should_receive(:exists?).and_return(false)
assert_equal 'ruby -S bundle exec', RubyEnv.ruby_command("path/to/project")
end
should "work when there is no binary specified and bundler is not present" do
flexmock(RubyEnv).should_receive(:bundler?).and_return(false)
flexmock(File).should_receive(:exists?).and_return(false)
assert_equal 'ruby -S', RubyEnv.ruby_command("path/to/project")
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/railtie.rb | lib/railtie.rb | begin
require 'rails'
@rails_loaded = true
rescue LoadError => ex
@rails_loaded = false
end
if @rails_loaded
module Testbot
class Railtie < Rails::Railtie
rake_tasks do
load File.expand_path(File.join(File.dirname(__FILE__), "tasks/testbot.rake"))
end
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/testbot.rb | lib/testbot.rb | # Rails plugin hook
require File.expand_path(File.join(File.dirname(__FILE__), '/shared/testbot'))
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/requester/requester.rb | lib/requester/requester.rb | require 'rubygems'
require 'httparty'
require 'ostruct'
require 'erb'
require File.dirname(__FILE__) + '/../shared/ssh_tunnel'
require File.expand_path(File.dirname(__FILE__) + '/../shared/testbot')
class Hash
def symbolize_keys_without_active_support
inject({}) do |options, (key, value)|
options[(key.to_sym rescue key) || key] = value
options
end
end
end
module Testbot::Requester
class Requester
attr_reader :config
def initialize(config = {})
config = config.symbolize_keys_without_active_support
config[:rsync_path] ||= Testbot::DEFAULT_SERVER_PATH
config[:project] ||= Testbot::DEFAULT_PROJECT
config[:server_user] ||= Testbot::DEFAULT_USER
config[:available_runner_usage] ||= Testbot::DEFAULT_RUNNER_USAGE
@config = OpenStruct.new(config)
end
def run_tests(adapter, dir)
puts if config.simple_output || config.logging
if config.ssh_tunnel
log "Setting up ssh tunnel" do
SSHTunnel.new(config.server_host, config.server_user, adapter.requester_port).open
end
server_uri = "http://127.0.0.1:#{adapter.requester_port}"
else
server_uri = "http://#{config.server_host}:#{Testbot::SERVER_PORT}"
end
log "Syncing files" do
rsync_ignores = config.rsync_ignores.to_s.split.map { |pattern| "--exclude='#{pattern}'" }.join(' ')
system("rsync -az --delete --delete-excluded -e ssh #{rsync_ignores} . #{rsync_uri}")
exitstatus = $?.exitstatus
unless exitstatus == 0
puts "rsync failed with exit code #{exitstatus}"
exit 1
end
end
files = adapter.test_files(dir)
sizes = adapter.get_sizes(files)
build_id = nil
log "Requesting run" do
response = HTTParty.post("#{server_uri}/builds", :body => { :root => root,
:type => adapter.type.to_s,
:project => config.project,
:available_runner_usage => config.available_runner_usage,
:files => files.join(' '),
:sizes => sizes.join(' '),
:jruby => jruby? }).response
if response.code == "503"
puts "No runners available. If you just started a runner, try again. It usually takes a few seconds before they're available."
return false
elsif response.code != "200"
puts "Could not create build, #{response.code}: #{response.body}"
return false
else
build_id = response.body
end
end
at_exit do
unless ENV['IN_TEST'] || @done
log "Notifying server we want to stop the run" do
HTTParty.delete("#{server_uri}/builds/#{build_id}")
end
end
end
puts if config.logging
last_results_size = 0
success = true
error_count = 0
while true
sleep 0.5
begin
@build = HTTParty.get("#{server_uri}/builds/#{build_id}", :format => :json)
next unless @build
rescue Exception => ex
error_count += 1
if error_count > 4
puts "Failed to get status: #{ex.message}"
error_count = 0
end
next
end
results = @build['results'][last_results_size..-1]
unless results == ''
if config.simple_output
print results.gsub(/[^\.F]|Finished/, '')
STDOUT.flush
else
print results
STDOUT.flush
end
end
last_results_size = @build['results'].size
break if @build['done']
end
puts if config.simple_output
if adapter.respond_to?(:sum_results)
puts "\n" + adapter.sum_results(@build['results'])
end
@done = true
@build["success"]
end
def self.create_by_config(path)
Requester.new(YAML.load(ERB.new(File.open(path).read).result))
end
private
def log(text)
if config.logging
print "#{text}... "; STDOUT.flush
yield
puts "done"
else
yield
end
end
def root
if localhost?
config.rsync_path
else
"#{config.server_user}@#{config.server_host}:#{config.rsync_path}"
end
end
def rsync_uri
localhost? ? config.rsync_path : "#{config.server_user}@#{config.server_host}:#{config.rsync_path}"
end
def localhost?
[ '0.0.0.0', 'localhost', '127.0.0.1' ].include?(config.server_host)
end
def jruby?
RUBY_PLATFORM =~ /java/ || !!ENV['USE_JRUBY']
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/generators/testbot/testbot_generator.rb | lib/generators/testbot/testbot_generator.rb | require File.expand_path(File.dirname(__FILE__) + "/../../shared/testbot")
require "acts_as_rails3_generator"
class TestbotGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
class_option :connect, :type => :string, :required => true, :desc => "Which server to use (required)"
class_option :project, :type => :string, :default => nil, :desc => "The name of your project (default: #{Testbot::DEFAULT_PROJECT})"
class_option :rsync_path, :type => :string, :default => nil, :desc => "Sync path on the server (default: #{Testbot::DEFAULT_SERVER_PATH})"
class_option :rsync_ignores, :type => :string, :default => nil, :desc => "Files to rsync_ignores when syncing (default: include all)"
class_option :ssh_tunnel, :type => :boolean, :default => nil, :desc => "Use a ssh tunnel"
class_option :user, :type => :string, :default => nil, :desc => "Use a custom rsync / ssh tunnel user (default: #{Testbot::DEFAULT_USER})"
def generate_config
template "testbot.yml.erb", "config/testbot.yml"
template "testbot.rake.erb", "lib/tasks/testbot.rake"
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/runner/safe_result_text.rb | lib/runner/safe_result_text.rb | require 'iconv'
module Testbot::Runner
class SafeResultText
def self.clean(text)
clean_escape_sequences(strip_invalid_utf8(text))
end
def self.strip_invalid_utf8(text)
# http://po-ru.com/diary/fixing-invalid-utf-8-in-ruby-revisited/
ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')
ic.iconv(text + ' ')[0..-2]
end
def self.clean_escape_sequences(text)
tail_marker = "^[[0m"
tail = text.rindex(tail_marker) && text[text.rindex(tail_marker)+tail_marker.length..-1]
if !tail
text
elsif tail.include?("^[[") && !tail.include?("m")
text[0..text.rindex(tail_marker) + tail_marker.length - 1]
elsif text.scan(/\[.*?m/).last != tail_marker
text[0..text.rindex(tail_marker) + tail_marker.length - 1]
else
text
end
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/runner/runner.rb | lib/runner/runner.rb | require 'rubygems'
require 'httparty'
require 'ostruct'
require File.expand_path(File.dirname(__FILE__) + '/../shared/ssh_tunnel')
require File.expand_path(File.dirname(__FILE__) + '/../shared/adapters/adapter')
require File.expand_path(File.dirname(__FILE__) + '/job')
module Testbot::Runner
TIME_BETWEEN_NORMAL_POLLS = 1
TIME_BETWEEN_QUICK_POLLS = 0.1
TIME_BETWEEN_PINGS = 5
TIME_BETWEEN_VERSION_CHECKS = Testbot.version.include?('.DEV.') ? 10 : 60
class CPU
def self.count
case RUBY_PLATFORM
when /darwin/
`sysctl machdep.cpu.core_count | awk '{ print $2 }'`.to_i
when /linux/
`cat /proc/cpuinfo | grep processor | wc -l`.to_i
end
end
end
class Server
include HTTParty
default_timeout 10
end
class Runner
def initialize(config)
@instances = []
@last_build_id = nil
@last_version_check = Time.now - TIME_BETWEEN_VERSION_CHECKS - 1
@config = OpenStruct.new(config)
@config.max_instances = @config.max_instances ? @config.max_instances.to_i : CPU.count
if @config.ssh_tunnel
server_uri = "http://127.0.0.1:#{Testbot::SERVER_PORT}"
else
server_uri = "http://#{@config.server_host}:#{Testbot::SERVER_PORT}"
end
Server.base_uri(server_uri)
end
attr_reader :config
def run!
# Remove legacy instance* and *_rsync|git style folders
Dir.entries(".").find_all { |name| name.include?('instance') || name.include?('_rsync') ||
name.include?('_git') }.each { |folder|
system "rm -rf #{folder}"
}
SSHTunnel.new(@config.server_host, @config.server_user || Testbot::DEFAULT_USER).open if @config.ssh_tunnel
while true
begin
update_uid!
start_ping
wait_for_jobs
rescue Exception => ex
break if [ 'SignalException', 'Interrupt' ].include?(ex.class.to_s)
puts "The runner crashed, restarting. Error: #{ex.inspect} #{ex.class}"
end
end
end
private
def update_uid!
# When a runner crashes or is restarted it might loose current job info. Because
# of this we provide a new unique ID to the server so that it does not wait for
# lost jobs to complete.
@uid = "#{Time.now.to_i * rand}"
end
def wait_for_jobs
last_check_found_a_job = false
loop do
sleep (last_check_found_a_job ? TIME_BETWEEN_QUICK_POLLS : TIME_BETWEEN_NORMAL_POLLS)
check_for_update if !last_check_found_a_job && time_for_update?
# Only get jobs from one build at a time
next_params = base_params
if @instances.size > 0
next_params.merge!({ :build_id => @last_build_id })
next_params.merge!({ :no_jruby => true }) if max_jruby_instances?
else
@last_build_id = nil
end
# Makes sure all instances are listed as available after a run
clear_completed_instances
next_job = Server.get("/jobs/next", :query => next_params) rescue nil
last_check_found_a_job = (next_job != nil && next_job.body != "")
next unless last_check_found_a_job
job = Job.new(*([ self, next_job.split(',') ].flatten))
if first_job_from_build?
fetch_code(job)
before_run(job)
end
@last_build_id = job.build_id
# Must be outside the thread or it will sometimes run
# multiple jobs using the same instance number.
instance_number = free_instance_number
@instances << [ Thread.new { job.run(instance_number) }, instance_number, job ]
loop do
clear_completed_instances
break unless max_instances_running?
end
end
end
def max_jruby_instances?
return unless @config.max_jruby_instances
@instances.find_all { |thread, n, job| job.jruby? }.size >= @config.max_jruby_instances
end
def fetch_code(job)
system "rsync -az --delete --delete-excluded -e ssh #{job.root}/ #{job.project}"
end
def before_run(job)
rvm_prefix = RubyEnv.rvm_prefix(job.project)
bundler_cmd = (RubyEnv.bundler?(job.project) ? [rvm_prefix, "bundle &&", rvm_prefix, "bundle exec"] : [rvm_prefix]).compact.join(" ")
command_prefix = "cd #{job.project} && export RAILS_ENV=test && export TEST_INSTANCES=#{@config.max_instances} && #{bundler_cmd}"
if File.exists?("#{job.project}/lib/tasks/testbot.rake")
system "#{command_prefix} rake testbot:before_run"
elsif File.exists?("#{job.project}/config/testbot/before_run.rb")
system "#{command_prefix} ruby config/testbot/before_run.rb"
else
# workaround to bundle within the correct env
system "#{command_prefix} ruby -e ''"
end
end
def first_job_from_build?
@last_build_id == nil
end
def time_for_update?
time_for_update = ((Time.now - @last_version_check) >= TIME_BETWEEN_VERSION_CHECKS)
@last_version_check = Time.now if time_for_update
time_for_update
end
def check_for_update
return unless @config.auto_update
version = Server.get('/version') rescue Testbot.version
return unless version != Testbot.version
# In a PXE cluster with a shared gem folder we only want one of them to do the update
if @config.wait_for_updated_gem
# Gem.available? is cached so it won't detect new gems.
gem = Gem::Dependency.new("testbot", version)
successful_install = !Gem::SourceIndex.from_installed_gems.search(gem).empty?
else
if version.include?(".DEV.")
successful_install = system("wget #{@config.dev_gem_root}/testbot-#{version}.gem && gem install testbot-#{version}.gem --no-ri --no-rdoc && rm testbot-#{version}.gem")
else
successful_install = system "gem install testbot -v #{version} --no-ri --no-rdoc"
end
end
system "testbot #{ARGV.join(' ')}" if successful_install
end
def ping_params
{ :hostname => (@hostname ||= `hostname`.chomp), :max_instances => @config.max_instances,
:idle_instances => (@config.max_instances - @instances.size), :username => ENV['USER'], :build_id => @last_build_id }.merge(base_params)
end
def base_params
{ :version => Testbot.version, :uid => @uid }
end
def max_instances_running?
@instances.size == @config.max_instances
end
def clear_completed_instances
@instances.each_with_index do |data, index|
@instances.delete_at(index) if data.first.join(0.25)
end
end
def free_instance_number
0.upto(@config.max_instances - 1) do |number|
return number unless @instances.find { |instance, n, job| n == number }
end
end
def start_ping
Thread.new do
while true
begin
response = Server.get("/runners/ping", :body => ping_params).body
if response.include?('stop_build')
build_id = response.split(',').last
@instances.each { |instance, n, job| job.kill!(build_id) }
end
rescue
end
sleep TIME_BETWEEN_PINGS
end
end
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/runner/job.rb | lib/runner/job.rb | require File.expand_path(File.join(File.dirname(__FILE__), 'runner.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), 'safe_result_text.rb'))
require 'posix/spawn'
module Testbot::Runner
class Job
attr_reader :root, :project, :build_id
TIME_TO_WAIT_BETWEEN_POSTING_RESULTS = 5
def initialize(runner, id, build_id, project, root, type, ruby_interpreter, files)
@runner, @id, @build_id, @project, @root, @type, @ruby_interpreter, @files =
runner, id, build_id, project, root, type, ruby_interpreter, files
@success = true
end
def jruby?
@ruby_interpreter == 'jruby'
end
def run(instance)
return if @killed
puts "Running job #{@id} (build #{@build_id})... "
test_env_number = (instance == 0) ? '' : instance + 1
result = "\n#{`hostname`.chomp}:#{Dir.pwd}\n"
base_environment = "export RAILS_ENV=test; export TEST_ENV_NUMBER=#{test_env_number}; cd #{@project};"
adapter = Adapter.find(@type)
run_time = measure_run_time do
result += run_and_return_result("#{base_environment} #{adapter.command(@project, ruby_cmd, @files)}")
end
Server.put("/jobs/#{@id}", :body => { :result => SafeResultText.clean(result), :status => status, :time => run_time })
puts "Job #{@id} finished."
end
def kill!(build_id)
if @build_id == build_id && @pid
kill_processes
@killed = true
end
end
private
def kill_processes
# Kill process and its children (processes in the same group)
Process.kill('KILL', -@pid) rescue :failed_to_kill_process
end
def status
success? ? "successful" : "failed"
end
def measure_run_time
start_time = Time.now
yield
(Time.now - start_time) * 100
end
def post_results(output)
Server.put("/jobs/#{@id}", :body => { :result => SafeResultText.clean(output), :status => "building" })
rescue Timeout::Error
puts "Got a timeout when posting an job result update. This can happen when the server is busy and is not a critical error."
end
def run_and_return_result(command)
read_pipe = spawn_process(command)
output = ""
last_post_time = Time.now
while char = read_pipe.getc
char = (char.is_a?(Fixnum) ? char.chr : char) # 1.8 <-> 1.9
output << char
if Time.now - last_post_time > TIME_TO_WAIT_BETWEEN_POSTING_RESULTS
post_results(output)
last_post_time = Time.now
end
end
# Kill child processes, if any
kill_processes
output
end
def spawn_process(command)
read_pipe, write_pipe = IO.pipe
@pid = POSIX::Spawn::spawn(command, :err => write_pipe, :out => write_pipe, :pgroup => true)
Thread.new do
Process.waitpid(@pid)
@success = ($?.exitstatus == 0)
write_pipe.close
end
read_pipe
end
def success?
@success
end
def ruby_cmd
if @ruby_interpreter == 'jruby' && @runner.config.jruby_opts
'jruby ' + @runner.config.jruby_opts
else
@ruby_interpreter
end
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/server/memory_model.rb | lib/server/memory_model.rb | class MemoryModel < OpenStruct
@@db = {}
@@types = {}
def initialize(hash)
@@types[self.class] ||= {}
hash = resolve_types(symbolize_keys(hash))
super(hash)
end
def id
object_id
end
def type
@table[:type]
end
def attributes
@table
end
def update(hash)
@table.merge!(resolve_types(symbolize_keys(hash)))
self
end
def destroy
self.class.all.delete_if { |b| b.id == id }
end
def self.find(id)
all.find { |r| r.id == id.to_i }
end
def self.create(hash = {})
all << new(hash)
all[-1]
end
def self.all
@@db[self] ||= []
@@db[self]
end
def self.first
all.first
end
def self.delete_all
all.clear
end
def self.count
all.size
end
def self.attribute(attribute, type)
@@types[self] ||= {}
@@types[self][attribute] = type
end
private
def resolve_types(hash)
hash.each { |attribute, value|
case @@types[self.class][attribute]
when :integer
hash[attribute] = value.to_i
when :boolean
if value == "true"
hash[attribute] = true
elsif value == "false"
hash[attribute] = false
elsif value != true && value != false
hash[attribute] = nil
end
end
}
hash
end
def symbolize_keys(hash)
h = {}
hash.each { |k, v| h[k.to_sym] = v }
h
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/server/group.rb | lib/server/group.rb | require 'rubygems'
module Testbot::Server
class Group
DEFAULT = nil
def self.build(files, sizes, instance_count, type)
tests_with_sizes = slow_tests_first(map_files_and_sizes(files, sizes))
groups = []
current_group, current_size = 0, 0
tests_with_sizes.each do |test, size|
# inserts into next group if current is full and we are not in the last group
if (0.5*size + current_size) > group_size(tests_with_sizes, instance_count) and instance_count > current_group + 1
current_size = size
current_group += 1
else
current_size += size
end
groups[current_group] ||= []
groups[current_group] << test
end
groups.compact
end
private
def self.group_size(tests_with_sizes, group_count)
total = tests_with_sizes.inject(0) { |sum, test| sum += test[1] }
total / group_count.to_f
end
def self.map_files_and_sizes(files, sizes)
list = []
files.each_with_index { |file, i| list << [ file, sizes[i] ] }
list
end
def self.slow_tests_first(tests)
tests.sort_by { |test, time| time.to_i }.reverse
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/server/build.rb | lib/server/build.rb | module Testbot::Server
class Build < MemoryModel
def initialize(hash)
super({ :success => true, :done => false, :results => '' }.merge(hash))
end
def self.create_and_build_jobs(hash)
hash["jruby"] = (hash["jruby"] == "true") ? 1 : 0
build = create(hash.reject { |k, v| k == 'available_runner_usage' })
build.create_jobs!(hash['available_runner_usage'])
build
end
def create_jobs!(available_runner_usage)
groups = Group.build(self.files.split, self.sizes.split.map { |size| size.to_i },
Runner.total_instances.to_f * (available_runner_usage.to_i / 100.0), self.type)
groups.each do |group|
Job.create(:files => group.join(' '),
:root => self.root,
:project => self.project,
:type => self.type,
:build => self,
:jruby => self.jruby)
end
end
def destroy
Job.all.find_all { |j| j.build == self }.each { |job| job.destroy }
super
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/server/runner.rb | lib/server/runner.rb | module Testbot::Server
class Runner < MemoryModel
attribute :idle_instances, :integer
attribute :max_instances, :integer
def self.record!(hash)
create_or_update_by_mac!(hash)
end
def self.create_or_update_by_mac!(hash)
if runner = find_by_uid(hash[:uid])
runner.update hash
else
Runner.create hash
end
end
def self.timeout
10
end
def self.find_by_uid(uid)
all.find { |r| r.uid == uid }
end
def self.find_all_outdated
all.find_all { |r| r.version != Testbot.version }
end
def self.find_all_available
all.find_all { |r| r.idle_instances && r.version == Testbot.version && r.last_seen_at > (Time.now - Runner.timeout) }
end
def self.available_instances
find_all_available.inject(0) { |sum, r| r.idle_instances + sum }
end
def self.total_instances
return 1 if ENV['INTEGRATION_TEST']
find_all_available.inject(0) { |sum, r| r.max_instances + sum }
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/server/server.rb | lib/server/server.rb | require 'rubygems'
require 'sinatra'
require 'yaml'
require 'json'
require File.expand_path(File.join(File.dirname(__FILE__), '/../shared/testbot'))
require File.expand_path(File.join(File.dirname(__FILE__), 'memory_model.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), 'job.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), 'group.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), 'runner.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), 'build.rb'))
module Testbot::Server
if ENV['INTEGRATION_TEST']
set :port, 22880
else
set :port, Testbot::SERVER_PORT
end
class Server
def self.valid_version?(runner_version)
Testbot.version == runner_version
end
end
post '/builds' do
if Runner.total_instances == 0
[ 503, "No runners available" ]
else
Build.create_and_build_jobs(params).id.to_s
end
end
get '/builds/:id' do
build = Build.find(params[:id])
build.destroy if build.done
{ "done" => build.done, "results" => build.results, "success" => build.success }.to_json
end
delete '/builds/:id' do
build = Build.find(params[:id])
build.destroy if build
nil
end
get '/jobs/next' do
next_job, runner = Job.next(params, @env['REMOTE_ADDR'])
if next_job
next_job.update(:taken_at => Time.now, :taken_by => runner)
[ next_job.id, next_job.build.id, next_job.project, next_job.root, next_job.type, (next_job.jruby == 1 ? 'jruby' : 'ruby'), next_job.files ].join(',')
end
end
put '/jobs/:id' do
Job.find(params[:id]).update(:result => params[:result], :status => params[:status]); nil
end
get '/runners/ping' do
return unless Server.valid_version?(params[:version])
runner = Runner.find_by_uid(params[:uid])
if runner
runner.update(params.reject { |k, v| k == "build_id" }.merge({ :last_seen_at => Time.now, :build => Build.find(params[:build_id]) }))
unless params[:build_id] == '' || params[:build_id] == nil || runner.build
return "stop_build,#{params[:build_id]}"
end
end
nil
end
get '/runners' do
Runner.find_all_available.map { |r| r.attributes }.to_json
end
get '/runners/outdated' do
Runner.find_all_outdated.map { |runner| [ runner.ip, runner.hostname, runner.uid ].join(' ') }.join("\n").strip
end
get '/runners/available_instances' do
Runner.available_instances.to_s
end
get '/runners/total_instances' do
Runner.total_instances.to_s
end
get '/runners/available' do
Runner.find_all_available.map { |runner| [ runner.ip, runner.hostname, runner.uid, runner.username, runner.idle_instances ].join(' ') }.join("\n").strip
end
get '/version' do
Testbot.version
end
get '/status' do
File.read(File.join(File.dirname(__FILE__), '/status/status.html'))
end
get '/status/:dir/:file' do
File.read(File.join(File.dirname(__FILE__), "/status/#{params[:dir]}/#{params[:file]}"))
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/server/job.rb | lib/server/job.rb | module Testbot::Server
class Job < MemoryModel
def update(hash)
super(hash)
if self.build
self.done = done?
done = !Job.all.find { |j| !j.done && j.build == self.build }
self.build.update(:results => build_results(build), :done => done)
build_broken_by_job = (self.status == "failed" && build.success)
self.build.update(:success => false) if build_broken_by_job
end
end
def self.next(params, remove_addr)
clean_params = params.reject { |k, v| k == "no_jruby" }
runner = Runner.record! clean_params.merge({ :ip => remove_addr, :last_seen_at => Time.now })
return unless Server.valid_version?(params[:version])
[ next_job(params["build_id"], params["no_jruby"]), runner ]
end
private
def build_results(build)
self.last_result_position ||= 0
new_results = self.result.to_s[self.last_result_position..-1] || ""
self.last_result_position = self.result.to_s.size
# Don't know why this is needed as the job should cleanup
# escape sequences.
if new_results[0,4] == '[32m'
new_results = new_results[4..-1]
end
build.results.to_s + new_results
end
def done?
self.status == "successful" || self.status == "failed"
end
def self.next_job(build_id, no_jruby)
release_jobs_taken_by_missing_runners!
jobs = Job.all.find_all { |j|
!j.taken_at &&
(build_id ? j.build.id.to_s == build_id : true) &&
(no_jruby ? j.jruby != 1 : true)
}
jobs[rand(jobs.size)]
end
def self.release_jobs_taken_by_missing_runners!
missing_runners = Runner.all.find_all { |r| r.last_seen_at < (Time.now - Runner.timeout) }
missing_runners.each { |runner|
Job.all.find_all { |job| job.taken_by == runner }.each { |job| job.update(:taken_at => nil) }
}
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/shared/simple_daemonize.rb | lib/shared/simple_daemonize.rb | require 'rubygems'
require 'daemons'
class SimpleDaemonize
def self.start(proc, pid_path, app_name)
working_dir = Dir.pwd
group = Daemons::ApplicationGroup.new(app_name)
group.new_application(:mode => :none).start
File.open(pid_path, 'w') { |file| file.write(Process.pid) }
Dir.chdir(working_dir)
proc.call
end
def self.stop(pid_path)
return unless File.exists?(pid_path)
pid = File.read(pid_path)
system "kill -9 #{pid} &> /dev/null"
system "rm #{pid_path} &> /dev/null"
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/shared/version.rb | lib/shared/version.rb | module Testbot
# Don't forget to update readme and changelog
def self.version
version = "0.7.9"
dev_version_file = File.join(File.dirname(__FILE__), '..', '..', 'DEV_VERSION')
if File.exists?(dev_version_file)
version += File.read(dev_version_file)
end
version
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/shared/color.rb | lib/shared/color.rb | class Color
def self.colorize(text, color)
colors = { :green => 32, :orange => 33, :red => 31, :cyan => 36 }
if colors[color]
"\033[#{colors[color]}m#{text}\033[0m"
else
raise "Color not implemented: #{color}"
end
end
def self.strip(text)
text.gsub(/\e.+?m/, '')
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/shared/testbot.rb | lib/shared/testbot.rb | require File.expand_path(File.join(File.dirname(__FILE__), '/version'))
require File.expand_path(File.join(File.dirname(__FILE__), '/simple_daemonize'))
require File.expand_path(File.join(File.dirname(__FILE__), '/adapters/adapter'))
require 'fileutils'
module Testbot
require 'railtie' if defined?(Rails)
if ENV['INTEGRATION_TEST']
SERVER_PID = "/tmp/integration_test_testbot_server.pid"
RUNNER_PID = "/tmp/integration_test_testbot_runner.pid"
else
SERVER_PID = "/tmp/testbot_server.pid"
RUNNER_PID = "/tmp/testbot_runner.pid"
end
DEFAULT_WORKING_DIR = "/tmp/testbot"
DEFAULT_SERVER_PATH = "/tmp/testbot/#{ENV['USER']}"
DEFAULT_USER = "testbot"
DEFAULT_PROJECT = "project"
DEFAULT_RUNNER_USAGE = "100%"
SERVER_PORT = ENV['INTEGRATION_TEST'] ? 22880 : 2288
class CLI
def self.run(argv)
return false if argv == []
opts = parse_args(argv)
if opts[:help]
return false
elsif opts[:version]
puts "Testbot #{Testbot.version}"
elsif [ true, 'run', 'start' ].include?(opts[:server])
start_server(opts[:server])
elsif opts[:server] == 'stop'
stop('server', Testbot::SERVER_PID)
elsif [ true, 'run', 'start' ].include?(opts[:runner])
require File.expand_path(File.join(File.dirname(__FILE__), '/../runner/runner'))
return false unless valid_runner_opts?(opts)
start_runner(opts)
elsif opts[:runner] == 'stop'
stop('runner', Testbot::RUNNER_PID)
elsif adapter = Adapter.all.find { |adapter| opts[adapter.type.to_sym] }
require File.expand_path(File.join(File.dirname(__FILE__), '/../requester/requester'))
start_requester(opts, adapter)
end
true
end
def self.parse_args(argv)
last_setter = nil
hash = {}
str = ''
argv.each_with_index do |arg, i|
if arg.include?('--')
str = ''
last_setter = arg.split('--').last.to_sym
hash[last_setter] = true if (i == argv.size - 1) || argv[i+1].include?('--')
else
str += ' ' + arg
hash[last_setter] = str.strip
end
end
hash
end
def self.start_runner(opts)
stop('runner', Testbot::RUNNER_PID)
proc = lambda {
working_dir = opts[:working_dir] || Testbot::DEFAULT_WORKING_DIR
FileUtils.mkdir_p(working_dir)
Dir.chdir(working_dir)
runner = Runner::Runner.new(:server_host => opts[:connect],
:auto_update => opts[:auto_update], :max_instances => opts[:cpus],
:ssh_tunnel => opts[:ssh_tunnel], :server_user => opts[:user],
:max_jruby_instances => opts[:max_jruby_instances],
:dev_gem_root => opts[:dev_gem_root],
:wait_for_updated_gem => opts[:wait_for_updated_gem],
:jruby_opts => opts[:jruby_opts])
runner.run!
}
if opts[:runner] == 'run'
proc.call
else
puts "Testbot runner started (pid: #{Process.pid})"
SimpleDaemonize.start(proc, Testbot::RUNNER_PID, "testbot (runner)")
end
end
def self.start_server(type)
stop('server', Testbot::SERVER_PID)
require File.expand_path(File.join(File.dirname(__FILE__), '/../server/server'))
if type == 'run'
Sinatra::Application.run! :environment => "production"
else
puts "Testbot server started (pid: #{Process.pid})"
SimpleDaemonize.start(lambda {
Sinatra::Application.run! :environment => "production"
}, Testbot::SERVER_PID, "testbot (server)")
end
end
def self.stop(name, pid)
puts "Testbot #{name} stopped" if SimpleDaemonize.stop(pid)
end
def self.start_requester(opts, adapter)
requester = Requester::Requester.new(:server_host => opts[:connect],
:rsync_path => opts[:rsync_path],
:rsync_ignores => opts[:rsync_ignores].to_s,
:available_runner_usage => nil,
:project => opts[:project],
:ssh_tunnel => opts[:ssh_tunnel], :server_user => opts[:user])
requester.run_tests(adapter, adapter.base_path)
end
def self.valid_runner_opts?(opts)
opts[:connect].is_a?(String)
end
def self.lib_path
File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/shared/ssh_tunnel.rb | lib/shared/ssh_tunnel.rb | require 'rubygems'
require 'net/ssh'
class SSHTunnel
def initialize(host, user, local_port = 2288)
@host, @user, @local_port = host, user, local_port
end
def open
connect
start_time = Time.now
while true
break if @up
sleep 0.5
if Time.now - start_time > 5
puts "SSH connection failed, trying again..."
start_time = Time.now
connect
end
end
end
def connect
@thread.kill if @thread
@thread = Thread.new do
Net::SSH.start(@host, @user, { :timeout => 1 }) do |ssh|
ssh.forward.local(@local_port, 'localhost', Testbot::SERVER_PORT)
ssh.loop { @up = true }
end
end
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/shared/adapters/rspec_adapter.rb | lib/shared/adapters/rspec_adapter.rb | require File.expand_path(File.join(File.dirname(__FILE__), "/helpers/ruby_env"))
require File.expand_path(File.join(File.dirname(__FILE__), "../color"))
class RspecAdapter
def self.command(project_path, ruby_interpreter, files)
spec_command = RubyEnv.ruby_command(project_path, :script => "script/spec", :bin => "rspec",
:ruby_interpreter => ruby_interpreter)
if File.exists?("#{project_path}/spec/spec.opts")
spec_command += " -O spec/spec.opts"
end
"export RSPEC_COLOR=true; #{spec_command} #{files}"
end
def self.test_files(dir)
Dir["#{dir}/#{file_pattern}"]
end
def self.get_sizes(files)
files.map { |file| File.stat(file).size }
end
def self.requester_port
2299
end
def self.pluralized
'specs'
end
def self.base_path
type
end
def self.name
'RSpec'
end
def self.type
'spec'
end
# This is an optional method. It gets passed the entire test result and summarizes it. See the tests.
def self.sum_results(results)
examples, failures, pending = 0, 0, 0
results.split("\n").each do |line|
line =~ /(\d+) examples?, (\d+) failures?(, (\d+) pending)?/
next unless $1
examples += $1.to_i
failures += $2.to_i
pending += $4.to_i
end
result = [ pluralize(examples, 'example'), pluralize(failures, 'failure'), (pending > 0 ? "#{pending} pending" : nil) ].compact.join(', ')
if failures == 0 && pending == 0
Color.colorize(result, :green)
elsif failures == 0 && pending > 0
Color.colorize(result, :orange)
else
Color.colorize(result, :red)
end
end
private
def self.pluralize(count, singular)
if count == 1
"#{count} #{singular}"
else
"#{count} #{singular}s"
end
end
def self.file_pattern
'**/**/*_spec.rb'
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/shared/adapters/adapter.rb | lib/shared/adapters/adapter.rb | class Adapter
FILES = Dir[File.dirname(__FILE__) + "/*_adapter.rb"]
FILES.each { |file| require(file) }
def self.all
FILES.map { |file| load_adapter(file) }
end
def self.find(type)
if adapter = all.find { |adapter| adapter.type == type.to_s }
adapter
else
raise "Unknown adapter: #{type}"
end
end
private
def self.load_adapter(file)
eval("::" + File.basename(file).
gsub(/\.rb/, '').
gsub(/(?:^|_)(.)/) { $1.upcase })
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/shared/adapters/rspec2_adapter.rb | lib/shared/adapters/rspec2_adapter.rb | require File.expand_path(File.join(File.dirname(__FILE__), "/helpers/ruby_env"))
class Rspec2Adapter
def self.command(project_path, ruby_interpreter, files)
spec_command = RubyEnv.ruby_command(project_path,
:bin => "rspec",
:ruby_interpreter => ruby_interpreter)
if File.exists?("#{project_path}/spec/spec.opts")
spec_command += " -O spec/spec.opts"
end
"export RSPEC_COLOR=true; #{spec_command} #{files}"
end
def self.test_files(dir)
Dir["#{dir}/#{file_pattern}"]
end
def self.get_sizes(files)
files.map { |file| File.stat(file).size }
end
def self.requester_port
2299
end
def self.pluralized
'specs'
end
def self.base_path
"spec"
end
def self.name
'RSpec2'
end
def self.type
'rspec'
end
private
def self.file_pattern
'**/**/*_spec.rb'
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/shared/adapters/cucumber_adapter.rb | lib/shared/adapters/cucumber_adapter.rb | require File.expand_path(File.join(File.dirname(__FILE__), "/helpers/ruby_env"))
require File.expand_path(File.join(File.dirname(__FILE__), "../color"))
class CucumberAdapter
def self.command(project_path, ruby_interpreter, files)
cucumber_command = RubyEnv.ruby_command(project_path, :script => "script/cucumber", :bin => "cucumber",
:ruby_interpreter => ruby_interpreter)
"export AUTOTEST=1; #{cucumber_command} -f progress --backtrace -r features/support -r features/step_definitions #{files} -t ~@disabled"
end
def self.test_files(dir)
Dir["#{dir}/#{file_pattern}"]
end
def self.get_sizes(files)
files.map { |file| File.stat(file).size }
end
def self.requester_port
2230
end
def self.pluralized
'features'
end
def self.base_path
pluralized
end
def self.name
'Cucumber'
end
def self.type
pluralized
end
# This is an optional method. It gets passed the entire test result and summarizes it. See the tests.
def self.sum_results(text)
scenarios, steps = parse_scenarios_and_steps(text)
scenarios_line = "#{scenarios[:total]} scenarios (" + [
(Color.colorize("#{scenarios[:failed]} failed", :red) if scenarios[:failed] > 0),
(Color.colorize("#{scenarios[:undefined]} undefined", :orange) if scenarios[:undefined] > 0),
(Color.colorize("#{scenarios[:passed]} passed", :green) if scenarios[:passed] > 0)
].compact.join(', ') + ")"
steps_line = "#{steps[:total]} steps (" + [
(Color.colorize("#{steps[:failed]} failed", :red) if steps[:failed] > 0),
(Color.colorize("#{steps[:skipped]} skipped", :cyan) if steps[:skipped] > 0),
(Color.colorize("#{steps[:undefined]} undefined", :orange) if steps[:undefined] > 0),
(Color.colorize("#{steps[:passed]} passed", :green) if steps[:passed] > 0)
].compact.join(', ') + ")"
scenarios_line + "\n" + steps_line
end
private
def self.parse_scenarios_and_steps(text)
results = {
:scenarios => { :total => 0, :passed => 0, :failed => 0, :undefined => 0 },
:steps => { :total => 0, :passed => 0, :failed => 0, :skipped => 0, :undefined => 0 }
}
Color.strip(text).split("\n").each do |line|
type = line.include?("scenarios") ? :scenarios : :steps
if match = line.match(/\((.+)\)/)
results[type][:total] += line.split.first.to_i
parse_status_counts(results[type], match[1])
end
end
[ results[:scenarios], results[:steps] ]
end
def self.parse_status_counts(results, status_counts)
status_counts.split(', ').each do |part|
results.keys.each do |key|
results[key] += part.split.first.to_i if part.include?(key.to_s)
end
end
end
def self.file_pattern
'**/**/*.feature'
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/shared/adapters/test_unit_adapter.rb | lib/shared/adapters/test_unit_adapter.rb | require File.expand_path(File.join(File.dirname(__FILE__), "/helpers/ruby_env"))
class TestUnitAdapter
def self.command(project_path, ruby_interpreter, files)
ruby_command = RubyEnv.ruby_command(project_path, :ruby_interpreter => ruby_interpreter)
%{#{ruby_command} -Itest -e '%w(#{files}).each { |file| require(Dir.pwd + "/" + file) }'}
end
def self.test_files(dir)
Dir["#{dir}/#{file_pattern}"]
end
def self.get_sizes(files)
files.map { |file| File.stat(file).size }
end
def self.requester_port
2231
end
def self.pluralized
'tests'
end
def self.base_path
type
end
def self.name
'Test::Unit'
end
def self.type
'test'
end
private
def self.file_pattern
'**/**/*_test.rb'
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
joakimk/testbot | https://github.com/joakimk/testbot/blob/d200b0ff53b7c1b886ff515fc0d160d41067b13a/lib/shared/adapters/helpers/ruby_env.rb | lib/shared/adapters/helpers/ruby_env.rb | class RubyEnv
def self.bundler?(project_path)
gem_exists?("bundler") && File.exists?("#{project_path}/Gemfile")
end
def self.gem_exists?(gem)
if Gem::Specification.respond_to?(:find_by_name)
Gem::Specification.find_by_name(gem)
else
# older depricated method
Gem.available?(gem)
end
rescue Gem::LoadError
false
end
def self.ruby_command(project_path, opts = {})
ruby_interpreter = opts[:ruby_interpreter] || "ruby"
if opts[:script] && File.exists?("#{project_path}/#{opts[:script]}")
command = opts[:script]
elsif opts[:bin]
command = opts[:bin]
else
command = nil
end
if bundler?(project_path)
"#{rvm_prefix(project_path)} #{ruby_interpreter} -S bundle exec #{command}".strip
else
"#{rvm_prefix(project_path)} #{ruby_interpreter} -S #{command}".strip
end
end
def self.rvm_prefix(project_path)
if rvm?
rvmrc_path = File.join project_path, ".rvmrc"
if File.exists?(rvmrc_path)
File.read(rvmrc_path).to_s.strip + " exec"
end
end
end
def self.rvm?
system("rvm info") != nil
end
end
| ruby | MIT | d200b0ff53b7c1b886ff515fc0d160d41067b13a | 2026-01-04T17:50:51.240118Z | false |
oelmekki/activerecord_any_of | https://github.com/oelmekki/activerecord_any_of/blob/f95f8b7c16364b67c221f8fcdf82e152c5542a03/spec/activerecord_any_of_spec.rb | spec/activerecord_any_of_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe 'ActiverecordAnyOf' do
fixtures :authors, :posts, :users
let(:davids) { Author.where(name: 'David') }
it 'matches hash combinations' do
expect(Author.where.any_of({ name: 'David' }, { name: 'Mary' })).to match_array(authors(:david, :mary))
end
it 'matches combination of hash and array' do
expect(Author.where.any_of({ name: 'David' }, ['name = ?', 'Mary'])).to match_array(authors(:david, :mary))
end
it 'matches a combination of hashes, arrays, and AR relations' do
expect(Author.where.any_of(davids, ['name = ?', 'Mary'],
{ name: 'Bob' })).to match_array(authors(:david, :mary, :bob))
end
it 'matches a combination of strings, hashes, and AR relations' do
expect(Author.where.any_of(davids, "name = 'Mary'",
{ name: 'Bob', id: 3 })).to match_array(authors(:david, :mary, :bob))
end
it 'matches a combination of only strings' do
expect(Author.where.any_of("name = 'David'", "name = 'Mary'")).to match_array(authors(:david, :mary))
end
it "doesn't match combinations previously filtered out" do
expect(Author.where.not(name: 'Mary').where.any_of(davids,
['name = ?', 'Mary'])).to contain_exactly(authors(:david))
end
it 'matches with alternate conditions on has_many association' do
david = authors(:david)
welcome = david.posts.where(body: 'Such a lovely day')
expected = ['Welcome to the weblog', 'So I was thinking']
expect(david.posts.where.any_of(welcome, { type: 'SpecialPost' }).map(&:title)).to match_array(expected)
end
describe 'with polymorphic associations' do
let(:company) { Company.create! }
let(:university) { University.create! }
let(:company2) { Company.create! }
it 'matches with combined polymorphic associations' do
company.users << users(:ezra)
university.users << users(:aria)
expect(User.where.any_of(company.users, university.users)).to match_array(users(:ezra, :aria))
end
it 'matches with more than 2 combined polymorphic associations' do
company.users << users(:ezra)
university.users << users(:aria)
company2.users << users(:james)
expect(User.where.any_of(company.users, university.users,
company2.users)).to match_array(users(:ezra, :aria, :james))
end
end
it 'matches alternatives with combined has_many associations' do
david, mary = authors(:david, :mary)
expect(Post.where.any_of(david.posts, mary.posts)).to match_array(david.posts + mary.posts)
end
it 'matches alternatives with more than 2 combined has_many associations' do
david, mary, bob = authors(:david, :mary, :bob)
expect(Post.where.any_of(david.posts, mary.posts, bob.posts)).to match_array(david.posts + mary.posts + bob.posts)
end
describe 'finding alternate dynamically with joined queries' do
it 'matches combined AR relations with joins' do
david = Author.where(posts: { title: 'Welcome to the weblog' }).joins(:posts)
mary = Author.where(posts: { title: "eager loading with OR'd conditions" }).joins(:posts)
expect(Author.where.any_of(david, mary)).to match_array(authors(:david, :mary))
end
it 'matches combined AR relations with joins and includes' do
david = Author.where(posts: { title: 'Welcome to the weblog' }).includes(:posts).references(:posts)
mary = Author.where(posts: { title: "eager loading with OR'd conditions" }).includes(:posts).references(:posts)
expect(Author.where.any_of(david, mary)).to match_array(authors(:david, :mary))
end
end
describe 'with alternate negative conditions' do
it 'filters out matching records' do
expect(Author.where.none_of({ name: 'David' }, { name: 'Mary' })).to contain_exactly(authors(:bob))
end
it 'filters out matching records with only strings' do
expect(Author.where.none_of("name = 'David'", "name = 'Mary'")).to contain_exactly(authors(:bob))
end
it 'filters out matching records with associations' do
david = Author.where(name: 'David').first
welcome = david.posts.where(body: 'Such a lovely day')
expected = ['sti comments', 'sti me', 'habtm sti test']
expect(david.posts.where.none_of(welcome, { type: 'SpecialPost' }).map(&:title)).to match_array(expected)
end
end
describe 'calling #any_of with no argument' do
it 'raises exception' do
expect { Author.where.any_of }.to raise_exception(ArgumentError)
end
end
describe 'calling #none_of with no argument' do
it 'raises exception' do
expect { Author.where.none_of }.to raise_exception(ArgumentError)
end
end
describe 'calling #any_of after including via a hash' do
it 'does not raise an exception' do
expect { User.includes(memberships: :companies).where.any_of(user_id: 1, company_id: 1) }
.not_to raise_exception
end
end
describe 'calling #any_of after a wildcard query' do
it 'matches the records matching the wildcard' do
expect(Author.where("name like '%av%'").where.any_of({ name: 'David' },
{ name: 'Mary' })).to contain_exactly(authors(:david))
end
end
describe 'calling #any_of with a single Hash as parameter' do
it 'expands the hash as multiple parameters' do
expect(Author.where.any_of(name: 'David', id: 2)).to match_array(authors(:david, :mary))
end
end
describe 'using an IN() clause' do
it 'recognize the bind values' do
expect(Author.where.any_of(name: %w[David Mary])).to match_array(authors(:david, :mary))
end
end
describe 'using a huge number of bind values' do
it 'does not crash' do
conditions = [{ name: 'Mary' }, { name: 'David' }]
(1..14).each { |i| conditions << { name: "David#{i}" } }
expect(Author.where.any_of(*conditions)).to match_array(authors(:david, :mary))
end
end
it 'makes rubocop and simplecov be happy together' do
alternative = ActiverecordAnyOf::AlternativeBuilder.new(:positive, [], 'foo = 1')
expect(alternative.instance_variable_get(:@builder)).to respond_to :each
end
end
| ruby | MIT | f95f8b7c16364b67c221f8fcdf82e152c5542a03 | 2026-01-04T17:50:52.089997Z | false |
oelmekki/activerecord_any_of | https://github.com/oelmekki/activerecord_any_of/blob/f95f8b7c16364b67c221f8fcdf82e152c5542a03/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
plugin_test_dir = File.dirname(__FILE__)
require 'bundler'
require 'simplecov'
SimpleCov.start
SimpleCov.minimum_coverage 95 # we can't cover rails-6 code when running on rails-7, and reversibly
require 'logger'
require 'rails/all'
require 'active_record'
Bundler.require :default, :development
require 'rspec/rails'
require 'pry'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new("#{plugin_test_dir}/debug.log")
ActiveRecord::Migration.verbose = false
load(File.join(plugin_test_dir, 'support', 'schema.rb'))
require 'activerecord_any_of'
require 'support/models'
require 'action_controller'
require 'database_cleaner'
RSpec.configure do |config|
config.fixture_path = "#{plugin_test_dir}/fixtures"
config.use_transactional_fixtures = true
config.filter_run focus: true
config.run_all_when_everything_filtered = true
end
| ruby | MIT | f95f8b7c16364b67c221f8fcdf82e152c5542a03 | 2026-01-04T17:50:52.089997Z | false |
oelmekki/activerecord_any_of | https://github.com/oelmekki/activerecord_any_of/blob/f95f8b7c16364b67c221f8fcdf82e152c5542a03/spec/support/models.rb | spec/support/models.rb | # frozen_string_literal: true
class Author < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :author
end
class SpecialPost < Post
end
class StiPost < Post
end
class User < ActiveRecord::Base
has_many :memberships
has_many :companies, through: :memberships, source: :organization, source_type: 'Company'
has_many :universities, through: :memberships, source: :organization, source_type: 'University'
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :organization, polymorphic: true
end
class Company < ActiveRecord::Base
has_many :memberships, as: :organization
has_many :users, through: :memberships
end
class University < ActiveRecord::Base
has_many :memberships, as: :organization
has_many :users, through: :memberships
end
| ruby | MIT | f95f8b7c16364b67c221f8fcdf82e152c5542a03 | 2026-01-04T17:50:52.089997Z | false |
oelmekki/activerecord_any_of | https://github.com/oelmekki/activerecord_any_of/blob/f95f8b7c16364b67c221f8fcdf82e152c5542a03/spec/support/schema.rb | spec/support/schema.rb | # frozen_string_literal: true
ActiveRecord::Schema.define do
create_table :authors do |t|
t.string :name
t.datetime :created_at
t.datetime :updated_at
end
create_table :posts do |t|
t.string :title
t.text :body
t.integer :author_id
t.string :type
t.datetime :created_at
t.datetime :updated_at
end
create_table :companies do |t|
t.string :name
end
create_table :universities do |t|
t.string :name
end
create_table :memberships do |t|
t.references :organization, polymorphic: true
t.references :user
end
create_table :users do |t|
t.string :name
end
end
| ruby | MIT | f95f8b7c16364b67c221f8fcdf82e152c5542a03 | 2026-01-04T17:50:52.089997Z | false |
oelmekki/activerecord_any_of | https://github.com/oelmekki/activerecord_any_of/blob/f95f8b7c16364b67c221f8fcdf82e152c5542a03/lib/activerecord_any_of.rb | lib/activerecord_any_of.rb | # frozen_string_literal: true
require 'activerecord_any_of/alternative_builder'
module ActiverecordAnyOf
# Injected into WhereChain.
module Chained
# Returns a new relation, which includes results matching any of the conditions
# passed as parameters. You can think of it as a sql <tt>OR</tt> implementation :
#
# User.where.any_of(first_name: 'Joe', last_name: 'Joe')
# # => SELECT * FROM users WHERE first_name = 'Joe' OR last_name = 'Joe'
#
#
# You can separate sets of hash condition by explicitly group them as hashes :
#
# User.where.any_of({first_name: 'John', last_name: 'Joe'}, {first_name: 'Simon', last_name: 'Joe'})
# # => SELECT * FROM users WHERE ( first_name = 'John' AND last_name = 'Joe' ) OR
# ( first_name = 'Simon' AND last_name = 'Joe' )
#
#
# Each #any_of set is the same kind you would have passed to #where :
#
# Client.where.any_of("orders_count = '2'", ["name = ?", 'Joe'], {email: 'joe@example.com'})
#
#
# You can as well pass #any_of to other relations :
#
# Client.where("orders_count = '2'").where.any_of({ email: 'joe@example.com' }, { email: 'john@example.com' })
#
#
# And with associations :
#
# User.find(1).posts.where.any_of({published: false}, "user_id IS NULL")
#
#
# The best part is that #any_of accepts other relations as parameter, to help compute
# dynamic <tt>OR</tt> queries :
#
# banned_users = User.where(banned: true)
# unconfirmed_users = User.where("confirmed_at IS NULL")
# inactive_users = User.where.any_of(banned_users, unconfirmed_users)
def any_of(*queries)
raise ArgumentError, 'Called any_of() with no arguments.' if queries.none?
AlternativeBuilder.new(:positive, @scope, *queries).build
end
# Returns a new relation, which includes results not matching any of the conditions
# passed as parameters. It's the negative version of <tt>#any_of</tt>.
#
# This will return all active users :
#
# banned_users = User.where(banned: true)
# unconfirmed_users = User.where("confirmed_at IS NULL")
# active_users = User.where.none_of(banned_users, unconfirmed_users)
def none_of(*queries)
raise ArgumentError, 'Called none_of() with no arguments.' if queries.none?
AlternativeBuilder.new(:negative, @scope, *queries).build
end
end
end
ActiveRecord::Relation::WhereChain.include ActiverecordAnyOf::Chained
| ruby | MIT | f95f8b7c16364b67c221f8fcdf82e152c5542a03 | 2026-01-04T17:50:52.089997Z | false |
oelmekki/activerecord_any_of | https://github.com/oelmekki/activerecord_any_of/blob/f95f8b7c16364b67c221f8fcdf82e152c5542a03/lib/activerecord_any_of/version.rb | lib/activerecord_any_of/version.rb | # frozen_string_literal: true
module ActiverecordAnyOf
VERSION = '2.0.2'
end
| ruby | MIT | f95f8b7c16364b67c221f8fcdf82e152c5542a03 | 2026-01-04T17:50:52.089997Z | false |
oelmekki/activerecord_any_of | https://github.com/oelmekki/activerecord_any_of/blob/f95f8b7c16364b67c221f8fcdf82e152c5542a03/lib/activerecord_any_of/alternative_builder.rb | lib/activerecord_any_of/alternative_builder.rb | # frozen_string_literal: true
module ActiverecordAnyOf
IS_RAILS_6 = ActiveRecord.version.to_s.between?('6', '7')
# Main class allowing to build alternative conditions for the query.
class AlternativeBuilder
def initialize(match_type, context, *queries)
if queries.first.is_a?(Hash) && (queries.count == 1)
queries = queries.first.each_pair.map { |attr, predicate| { attr => predicate } }
end
@builder = if match_type == :negative
NegativeBuilder.new(context,
*queries)
else
PositiveBuilder.new(context, *queries)
end
end
def build
@builder.build
end
# Common methods for both the positive builder and the negative one.
class Builder
attr_accessor :queries_joins_values
def initialize(context, *source_queries)
@context = context
@source_queries = source_queries
@queries_joins_values = { includes: [], joins: [], references: [] }
end
private
def query_to_relation(query)
if query.is_a?(String) || query.is_a?(Hash)
query = where(query)
elsif query.is_a?(Array)
query = where(*query)
end
query
end
def append_join_values(query)
{ includes_values: :includes, joins_values: :joins, references_values: :references }.each do |q, joins|
values = query.send(q)
queries_joins_values[joins].concat(values) if values.any?
end
end
def queries
@queries ||= @source_queries.map do |query|
query = query_to_relation(query)
append_join_values(query)
query.arel.constraints.reduce(:and)
end
end
def uniq_queries_joins_values
@uniq_queries_joins_values ||= { includes: [], joins: [], references: [] }.tap do |values|
queries_joins_values.each do |join_type, statements|
values[join_type] = if statements.first.respond_to?(:to_sql)
statements.uniq(&:to_sql)
else
statements.uniq
end
end
end
end
def map_multiple_bind_values(query)
query.children.map do |child|
next unless child.respond_to?(:right)
next unless child.right.respond_to?(:value)
child.right.value
end
end
def values_for(query)
return unless query.respond_to?(:right)
if query.right.is_a?(Array)
values = query.right
values.map!(&:value) unless IS_RAILS_6
values
else
return unless query.right.respond_to?(:value)
query.right.value
end
end
def queries_bind_values
queries.map do |query|
if query.respond_to?(:children)
query.children.map { |c| values_for(c) }
else
values_for(query)
end
end.flatten.compact
end
def method_missing(method_name, *args, &block)
@context.send(method_name, *args, &block)
end
def respond_to_missing?(method, *)
@context.respond_to? method
end
def add_joins_to(relation)
relation = relation.references(uniq_queries_joins_values[:references])
relation = relation.includes(uniq_queries_joins_values[:includes])
relation.joins(uniq_queries_joins_values[:joins])
end
def unprepare_query(query)
query.gsub(/((?<!\\)'.*?(?<!\\)'|(?<!\\)".*?(?<!\\)")|(=\ \$\d+)/) do |match|
::Regexp.last_match(2)&.gsub(/=\ \$\d+/, '= ?') or match
end
end
def bind_values
queries_bind_values.tap do |values|
values.map!(&:value) if IS_RAILS_6
end
end
end
# Returns records that match any of the conditions, ie `#any_of`.
class PositiveBuilder < Builder
def build
relation = if queries && queries_bind_values.size > 0
where([unprepare_query(queries.reduce(:or).to_sql), *bind_values])
else
where(queries.reduce(:or).to_sql)
end
add_joins_to relation
end
end
# Returns records that match none of the conditions, ie `#none_of`.
class NegativeBuilder < Builder
def build
relation = if queries && queries_bind_values.size > 0
where.not([unprepare_query(queries.reduce(:or).to_sql), *bind_values])
else
where.not(queries.reduce(:or).to_sql)
end
add_joins_to relation
end
end
end
end
| ruby | MIT | f95f8b7c16364b67c221f8fcdf82e152c5542a03 | 2026-01-04T17:50:52.089997Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/rails/init.rb | rails/init.rb | # This will help setup for easier setup in Rails apps.
puts 'SimpleRecord rails/init.rb...'
SimpleRecord.options[:connection_mode] = :per_thread
::ApplicationController.class_eval do
def close_sdb_connection
puts "Closing sdb connection."
SimpleRecord.close_connection
end
end
::ApplicationController.send :after_filter, :close_sdb_connection
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_conversions.rb | test/test_conversions.rb | require "yaml"
require 'aws'
require_relative "test_base"
require_relative "../lib/simple_record"
require_relative 'models/my_model'
require_relative 'models/my_child_model'
class ConversionsTest < TestBase
def test_ints
x = 0
assert_equal "09223372036854775808", SimpleRecord::Translations.pad_and_offset(x)
x = 1
assert_equal "09223372036854775809", SimpleRecord::Translations.pad_and_offset(x)
x = "09223372036854775838"
assert_equal 30, SimpleRecord::Translations.un_offset_int(x)
end
def test_float
assert_equal 0.0, SimpleRecord::Translations.pad_and_offset("0.0".to_f)
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_usage.rb | test/test_usage.rb | # These ones take longer to run
require 'test/unit'
require File.join(File.dirname(__FILE__), "/../lib/simple_record")
require File.join(File.dirname(__FILE__), "./test_helpers")
require File.join(File.dirname(__FILE__), "./test_base")
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
require 'active_support'
# Tests for SimpleRecord
#
class TestUsage < TestBase
def test_aaa_first_at_bat
MyModel.delete_domain
MyModel.create_domain
end
# ensures that it uses next token and what not
def test_select_usage_logging
SimpleRecord.log_usage(:select=>{:filename=>"/tmp/selects.csv", :format=>:csv, :lines_between_flushes=>2})
num_made = 10
num_made.times do |i|
mm = MyModel.create(:name=>"Gravis", :age=>i, :cool=>true)
end
mms = MyModel.find(:all, :conditions=>["name=?", "Gravis"],:consistent_read=>true)
mms = MyModel.find(:all, :conditions=>["name=?", "Gravis"], :order=>"name desc",:consistent_read=>true)
mms = MyModel.find(:all, :conditions=>["name=? and age>?", "Gravis", 3], :order=>"name desc",:consistent_read=>true)
SimpleRecord.close_usage_log(:select)
end
def test_zzz_last_at_bat
MyModel.delete_domain
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_simple_record.rb | test/test_simple_record.rb | gem 'test-unit'
require 'test/unit'
require File.join(File.dirname(__FILE__), "/../lib/simple_record")
require File.join(File.dirname(__FILE__), "./test_helpers")
require_relative "test_base"
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
require_relative 'models/model_with_enc'
require_relative 'models/my_simple_model'
# Tests for SimpleRecord
#
class TestSimpleRecord < TestBase
def test_aaa_first_at_bat
MyModel.delete_domain
MyChildModel.delete_domain
ModelWithEnc.delete_domain
MyModel.create_domain
MyChildModel.create_domain
ModelWithEnc.create_domain
end
def test_save_get
mm = MyModel.new
mm.name = "Travis"
mm.age = 32
mm.cool = true
mm.save
assert !mm.created.nil?
assert !mm.updated.nil?
assert !mm.id.nil?
assert_equal mm.age, 32
assert_equal mm.cool, true
assert_equal mm.name, "Travis"
id = mm.id
# Get the object back
mm2 = MyModel.find(id,:consistent_read=>true)
assert_equal mm2.id, mm.id
assert_equal mm2.age, mm.age
assert_equal mm2.cool, mm.cool
assert_equal mm2.age, 32
assert_equal mm2.cool, true
assert_equal mm2.name, "Travis"
assert mm2.created.is_a? DateTime
# test nilification
mm2.age = nil
mm2.save
sleep(2) # not sure why this might work... not respecting consistent_read?
mm3 = MyModel.find(id,:consistent_read=>true)
assert mm2.age.nil?, "doh, age should be nil, but it's " + mm2.age.inspect
end
def test_custom_id
custom_id = "id-travis"
mm = MyModel.new
mm.id = custom_id
mm.name = "Marvin"
mm.age = 32
mm.cool = true
mm.save
mm2 = MyModel.find(custom_id,:consistent_read=>true)
assert_equal mm2.id, mm.id
end
def test_updates
mm = MyModel.new
mm.name = "Angela"
mm.age = 32
mm.cool = true
mm.s1 = "Initial value"
mm.save
id = mm.id
mm = MyModel.find(id, :consistent_read=>true)
mm.name = "Angela2"
mm.age = 10
mm.cool = false
mm.s1 = "" # test blank string
mm.save
assert_equal mm.s1, ""
mm = MyModel.find(id, :consistent_read=>true)
assert_equal mm.name, "Angela2"
assert_equal mm.age, 10
assert_equal mm.cool, false
assert_equal mm.s1, ""
end
def test_funky_values
mm = MyModel.new(:name=>"Funky")
mm.s1 = "other/2009-11-10/04/84.eml" # reported here: http://groups.google.com/group/simple-record/browse_thread/thread/3659e82491d03a2c?hl=en
assert mm.save
assert_equal mm.errors.size, 0
mm2 = MyModel.find(mm.id,:consistent_read=>true)
end
def test_create
mm = MyModel.create(:name=>"Craven", :age=>32, :cool=>true)
assert !mm.id.nil?
end
def test_bad_query
assert_raise Aws::AwsError do
mm2 = MyModel.find(:all, :conditions=>["name =4?", "1"],:consistent_read=>true)
end
end
def test_batch_save
items = []
mm = MyModel.new
mm.name = "Beavis"
mm.age = 32
mm.cool = true
items << mm
mm = MyModel.new
mm.name = "Butthead"
mm.age = 44
mm.cool = false
items << mm
MyModel.batch_save(items)
items.each do |item|
new_item = MyModel.find(item.id,:consistent_read=>true)
assert_equal item.id, new_item.id
assert_equal item.name, new_item.name
assert_equal item.cool, new_item.cool
end
end
# Testing getting the association ID without materializing the obejct
def test_get_belongs_to_id
mm = MyModel.new
mm.name = "Parent"
mm.age = 55
mm.cool = true
mm.save
sleep(1) #needed because child.my_model below does not have :consistent_read set
child = MyChildModel.new
child.name = "Child"
child.my_model = mm
assert_equal child.my_model_id, mm.id
child.save
child = MyChildModel.find(child.id,:consistent_read=>true)
assert !child.my_model_id.nil?
assert !child.my_model.nil?
assert_equal child.my_model_id, mm.id
end
def test_callbacks
mm = MyModel.new
assert !mm.save
assert_equal mm.errors.count, 1 # name is required
# test queued callback before_create
mm.name = "Oresund"
assert mm.save
# now nickname should be set on before_create
assert_equal mm.nickname, mm.name
mm2 = MyModel.find(mm.id,:consistent_read=>true)
assert_equal mm2.nickname, mm.nickname
assert_equal mm2.name, mm.name
end
def test_dirty
mm = MyModel.new
mm.name = "Persephone"
mm.age = 32
mm.cool = true
mm.save
id = mm.id
# Get the object back
mm2 = MyModel.find(id,:consistent_read=>true)
assert_equal mm2.id, mm.id
assert_equal mm2.age, mm.age
assert_equal mm2.cool, mm.cool
mm2.name = "Persephone 2"
mm2.save(:dirty=>true)
# todo: how do we assert this? perhaps change a value directly in sdb and see that it doesn't get overwritten.
# or check stats and ensure only 1 attribute was put
# Test to ensure that if an item is not dirty, sdb doesn't get hit
SimpleRecord.stats.clear
mm2.save(:dirty=>true)
assert_equal 0, SimpleRecord.stats.saves
sleep(1) #needed because mmc.my_model below does not have :consistent_read set
mmc = MyChildModel.new
mmc.my_model = mm
mmc.x = mm
mmc.save
mmc2 = MyChildModel.find(mmc.id,:consistent_read=>true)
assert_equal mmc2.my_model_id, mmc.my_model_id
mmc2.my_model = nil
mmc2.x = nil
SimpleRecord.stats.clear
assert mmc2.save(:dirty=>true)
assert_equal SimpleRecord.stats.saves, 1
assert_equal SimpleRecord.stats.deletes, 1
assert_equal mmc2.id, mmc.id
assert_equal mmc2.my_model_id, nil
assert_equal mmc2.my_model, nil
mmc3 = MyChildModel.find(mmc.id,:consistent_read=>true)
assert_equal mmc3.my_model_id, nil
assert_equal mmc3.my_model, nil
mm3 = MyModel.new(:name=>"test")
assert mm3.save
sleep(1) #needed because mmc3.my_model below does not have :consistent_read set
mmc3.my_model = mm3
assert mmc3.my_model_changed?
assert mmc3.save(:dirty=>true)
assert_equal mmc3.my_model_id, mm3.id
assert_equal mmc3.my_model.id, mm3.id
mmc3 = MyChildModel.find(mmc3.id,:consistent_read=>true)
assert_equal mmc3.my_model_id, mm3.id
assert_equal mmc3.my_model.id, mm3.id
mmc3 = MyChildModel.find(mmc3.id,:consistent_read=>true)
mmc3.my_model_id = mm2.id
assert_equal mmc3.my_model_id, mm2.id
assert mmc3.changed?
assert mmc3.my_model_changed?
assert_equal mmc3.my_model.id, mm2.id
end
# http://api.rubyonrails.org/classes/ActiveRecord/Dirty.html#M002136
def test_changed
mm = MySimpleModel.new
mm.name = "Horace"
mm.age = 32
mm.cool = true
mm.save
assert !mm.changed?
assert_equal mm.changed.size, 0
assert_equal mm.changes.size, 0
assert !mm.name_changed?
mm.name = "Jim"
assert mm.changed?
assert_equal mm.changed.size, 1
assert_equal mm.changed[0], "name"
assert_equal mm.changes.size, 1
assert_equal mm.changes["name"][0], "Horace"
assert_equal mm.changes["name"][1], "Jim"
assert mm.name_changed?
assert_equal mm.name_was, "Horace"
assert_equal mm.name_change[0], "Horace"
assert_equal mm.name_change[1], "Jim"
end
def test_count
SimpleRecord.stats.clear
count = MyModel.find(:count,:consistent_read=>true) # select 1
assert count > 0
mms = MyModel.find(:all,:consistent_read=>true) # select 2
assert mms.size > 0 # still select 2
assert_equal mms.size, count
assert_equal 2, SimpleRecord.stats.selects
sleep 2
count = MyModel.find(:count, :conditions=>["name=?", "Beavis"],:consistent_read=>true)
assert count > 0
mms = MyModel.find(:all, :conditions=>["name=?", "Beavis"],:consistent_read=>true)
assert mms.size > 0
assert_equal mms.size, count
end
def test_attributes_correct
# child should contain child class attributes + parent class attributes
#MyModel.defined_attributes.each do |a|
#
#end
#MyChildModel.defined_attributes.inspect
end
def test_results_array
mms = MyModel.find(:all,:consistent_read=>true) # select 2
assert !mms.first.nil?
assert !mms.last.nil?
assert !mms.empty?
assert mms.include?(mms[0])
assert_equal mms[2, 2].size, 2
assert_equal mms[2..5].size, 4
assert_equal mms[2...5].size, 3
end
def test_random_index
create_my_models(120)
mms = MyModel.find(:all,:consistent_read=>true)
o = mms[85]
assert !o.nil?
o = mms[111]
assert !o.nil?
end
def test_objects_in_constructor
mm = MyModel.new(:name=>"model1")
mm.save
# my_model should be treated differently since it's a belong_to
mcm = MyChildModel.new(:name=>"johnny", :my_model=>mm)
mcm.save
sleep(1) #needed because mcm.my_model below does not have :consistent_read set
assert mcm.my_model != nil
mcm = MyChildModel.find(mcm.id,:consistent_read=>true)
assert mcm.my_model != nil
end
def test_nil_attr_deletion
mm = MyModel.new
mm.name = "Chad"
mm.age = 30
mm.cool = false
mm.save
# Should have 1 age attribute
sdb_atts = @@sdb.get_attributes('simplerecord_tests_my_models', mm.id, 'age',true) # consistent_read
assert_equal sdb_atts[:attributes].size, 1
mm.age = nil
mm.save
# Should be NIL
assert_equal mm.age, nil
sleep 1 #doesn't seem to be respecting consistent_read below
# Should have NO age attributes
assert_equal @@sdb.get_attributes('simplerecord_tests_my_models', mm.id, 'age',true)[:attributes].size, 0
end
def test_null
MyModel.delete_domain
MyModel.create_domain
mm = MyModel.new(:name=>"birthay is null")
mm.save
mm2 = MyModel.new(:name=>"birthday is not null")
mm2.birthday = Time.now
mm2.save
mms = MyModel.find(:all, :conditions=>["birthday is null"],:consistent_read=>true)
mms.each do |m|
m.inspect
end
assert_equal 1, mms.size
assert_equal mms[0].id, mm.id
mms = MyModel.find(:all, :conditions=>["birthday is not null"],:consistent_read=>true)
mms.each do |m|
m.inspect
end
assert_equal 1, mms.size
assert_equal mms[0].id, mm2.id
end
# Test to add support for IN
def test_in_clause
# mms = MyModel.find(:all,:consistent_read=>true)
# mms2 = MyModel.find(:all, :conditions=>["id in ?"],:consistent_read=>true)
end
def test_base_attributes
mm = MyModel.new()
mm.name = "test name tba"
mm.base_string = "in base class"
mm.save_with_validation!
mm2 = MyModel.find(mm.id,:consistent_read=>true)
assert_equal mm2.base_string, mm.base_string
assert_equal mm2.name, mm.name
assert_equal mm2.id, mm.id
mm2.name += " 2"
mm2.base_string = "changed base string"
mm2.save_with_validation!
mm3 = MyModel.find(mm2.id,:consistent_read=>true)
assert_equal mm3.base_string, mm2.base_string
end
def test_dates
mm = MyModel.new()
mm.name = "test name td"
mm.date1 = Date.today
mm.date2 = Time.now
mm.date3 = DateTime.now
mm.save
mm = MyModel.find(:first, :conditions=>["date1 >= ?", 1.days.ago.to_date],:consistent_read=>true)
assert mm.is_a? MyModel
mm = MyModel.find(:first, :conditions=>["date2 >= ?", 1.minutes.ago],:consistent_read=>true)
assert mm.is_a? MyModel
mm = MyModel.find(:first, :conditions=>["date3 >= ?", 1.minutes.ago],:consistent_read=>true)
assert mm.is_a? MyModel
end
def test_attr_encrypted
require_relative 'models/model_with_enc'
ssn = "123456789"
password = "my_password"
ob = ModelWithEnc.new
ob.name = "my name"
ob.ssn = ssn
ob.password = password
assert_equal ssn, ob.ssn
assert password != ob.password # we know this doesn't work right
assert_equal ob.password, password
ob.save
# try also with constructor, just to be safe
ob = ModelWithEnc.create(:ssn=>ssn, :name=>"my name", :password=>password)
assert_equal ssn, ob.ssn
assert password != ob.password # we know this doesn't work right
assert_equal ob.password, password
assert_equal ssn, ob.ssn
assert_equal ob.password, password
ob2 = ModelWithEnc.find(ob.id,:consistent_read=>true)
assert_equal ob2.name, ob.name
assert_equal ob2.ssn, ob.ssn
assert_equal ob2.ssn, ssn
assert_equal ob2.password, password
assert ob2.attributes["password"] != password
assert_equal ob2.password, ob.password
end
def test_non_persistent_attributes
mm = MyModel.new({:some_np_att=>"word"})
mm = MyModel.new({"some_other_np_att"=>"up"})
end
def test_atts_using_strings_and_symbols
mm = MyModel.new({:name=>"mynamex1",:age=>32})
mm2 = MyModel.new({"name"=>"mynamex2","age"=>32})
assert_equal(mm.age, mm2.age)
mm.save
mm2.save
mm = MyModel.find(mm.id,:consistent_read=>true)
mm2 = MyModel.find(mm2.id,:consistent_read=>true)
assert_equal(mm.age, mm2.age)
end
def test_constructor_using_belongs_to_ids
mm = MyModel.new({:name=>"myname tcubti"})
mm.save
sleep(1) #needed because mm2.my_model below does not have :consistent_read set
mm2 = MyChildModel.new({"name"=>"myname tcubti 2", :my_model_id=>mm.id})
assert_equal mm.id, mm2.my_model_id, "#{mm.id} != #{mm2.my_model_id}"
mm3 = mm2.my_model
assert_equal mm.name, mm3.name
mm3 = MyChildModel.create(:my_model_id=>mm.id, :name=>"myname tcubti 3")
mm4 = MyChildModel.find(mm3.id,:consistent_read=>true)
assert_equal mm4.my_model_id, mm.id
assert !mm4.my_model.nil?
end
def test_update_attributes
mm = MyModel.new({:name=>"myname tua"})
mm.save
now = Time.now
mm.update_attributes(:name=>"name2", :age=>21, "date2"=>now)
assert_equal mm.name, "name2"
assert_equal mm.age, 21
mm = MyModel.find(mm.id,:consistent_read=>true)
assert_equal mm.name, "name2"
assert_equal mm.age, 21
end
def test_explicit_class_name
mm = MyModel.new({:name=>"myname tecn"})
mm.save
mm2 = MyChildModel.new({"name"=>"myname tecn 2"})
mm2.x = mm
assert_equal mm2.x.id, mm.id
mm2.save
sleep 1 #sometimes consistent_read isn't good enough. Why? Dunno.
mm3 = MyChildModel.find(mm2.id,:consistent_read=>true)
assert_equal mm3.x.id, mm.id
end
def test_storage_format
mm = MyModel.new({:name=>"myname tsf"})
mm.date1 = Time.now
mm.date2 = DateTime.now
mm.save
raw = @@sdb.get_attributes(MyModel.domain, mm.id, nil, true)
puts raw.inspect #observation interferes with this in some way
assert_equal raw[:attributes]["updated"][0].size, "2010-01-06T16:04:23".size
assert_equal raw[:attributes]["date1"][0].size, "2010-01-06T16:04:23".size
assert_equal raw[:attributes]["date2"][0].size, "2010-01-06T16:04:23".size
end
def test_empty_initialize
mm = MyModel.new
mme = ModelWithEnc.new
mme = ModelWithEnc.new(:ssn=>"", :password=>"") # this caused encryptor errors
mme = ModelWithEnc.new(:ssn=>nil, :password=>nil)
end
def test_string_ints
mm = MyModel.new
mm.name = "whenever"
mm.age = "1"
mm2 = MyModel.new
mm2.name = "whenever2"
mm2.age = 1
params = {:name=>"scooby", :age=>"123"}
mm3 = MyModel.new(params)
assert_equal mm.age, 1
assert_equal mm2.age, 1
assert_equal mm3.age, 123
mm.save!
mm2.save!
mm3.save!
assert_equal mm.age, 1
assert_equal mm2.age, 1
assert_equal mm3.age, 123
mmf1 = MyModel.find(mm.id,:consistent_read=>true)
mmf2 = MyModel.find(mm2.id,:consistent_read=>true)
mmf3 = MyModel.find(mm3.id,:consistent_read=>true)
assert_equal mmf1.age, 1
assert_equal mmf2.age, 1
assert_equal mmf3.age, 123
mmf1.update_attributes({:age=>"456"})
assert_equal mmf1.age, 456
end
def test_box_usage
mm = MyModel.new
mm.name = "however"
mm.age = "1"
mm.save
mms = MyModel.all
assert mms.box_usage && mms.box_usage > 0
assert mms.request_id
end
def test_multi_value_attributes
val = ['a', 'b', 'c']
val2 = [1, 2, 3]
mm = MyModel.new
mm.name = val
mm.age = val2
assert_equal val, mm.name
assert_equal val2, mm.age
mm.save
mm = MyModel.find(mm.id,:consistent_read=>true)
# Values are not returned in order
assert_equal val, mm.name.sort
assert_equal val2, mm.age.sort
end
def test_zzz_last_batter_up
MyModel.delete_domain
MyChildModel.delete_domain
ModelWithEnc.delete_domain
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_pagination.rb | test/test_pagination.rb | require 'test/unit'
require File.join(File.dirname(__FILE__), "/../lib/simple_record")
require File.join(File.dirname(__FILE__), "./test_helpers")
require File.join(File.dirname(__FILE__), "./test_base")
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
require_relative 'models/model_with_enc'
require 'active_support'
# Pagination is intended to be just like will_paginate.
class TestPagination < TestBase
def setup
super
MyModel.delete_domain
MyModel.create_domain
end
def teardown
MyModel.delete_domain
super
end
def test_paginate
create_my_models(20)
i = 20
(1..3).each do |page|
models = MyModel.paginate :page=>page, :per_page=>5, :order=>"age desc", :consistent_read => true
assert models.count == 5, "models.count=#{models.count}"
assert models.size == 20, "models.size=#{models.size}"
models.each do |m|
i -= 1
assert m.age == i
end
end
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_encodings.rb | test/test_encodings.rb | require 'test/unit'
require File.expand_path(File.dirname(__FILE__) + "/../lib/simple_record")
require "yaml"
require 'aws'
require_relative 'models/my_simple_model'
require 'active_support'
require 'test_base'
class TestEncodings < TestBase
def test_aaa_setup_delete_domain
MySimpleModel.delete_domain
MySimpleModel.create_domain
end
def test_ascii_http_post
name = "joe" + ("X" * 1000) # pad the field to help get the URL over the 2000 length limit so AWS uses a POST
nickname = "blow" + ("X" * 1000) # pad the field to help get the URL over the 2000 length limit so AWS uses a POST
mm = MySimpleModel.create :name=>name, :nickname=>nickname
assert mm.save
assert_equal mm.name, name
assert_equal mm.nickname, nickname
mm2 = MySimpleModel.find(mm.id,:consistent_read=>true)
assert_equal mm2.name, name
assert_equal mm2.nickname, nickname
assert mm2.delete
end
def test_utf8_http_post
name = "jos\u00E9" + ("X" * 1000) # pad the field to help get the URL over the 2000 length limit so AWS uses a POST
nickname = "??" + ("X" * 1000) # pad the field to help get the URL over the 2000 length limit so AWS uses a POST
mm = MySimpleModel.create :name=>name, :nickname=>nickname
assert mm.save
assert_equal mm.name, name
assert_equal mm.nickname, nickname
mm2 = MySimpleModel.find(mm.id,:consistent_read=>true)
assert_equal mm2.name, name
assert_equal mm2.nickname, nickname
assert mm2.delete
end
def test_zzz_cleanup_delete_domain
MySimpleModel.delete_domain
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_translations.rb | test/test_translations.rb | gem 'test-unit'
require 'test/unit'
require File.join(File.dirname(__FILE__), "/../lib/simple_record")
require File.join(File.dirname(__FILE__), "./test_helpers")
require_relative "test_base"
require "yaml"
require 'aws'
require_relative 'models/my_translation'
# Tests for simple_record/translations.rb
#
class TestTranslations < TestBase
def test_aaa1 # run first
MyTranslation.delete_domain
MyTranslation.create_domain
end
def test_first_validations
mt = MyTranslation.new()
mt.name = "Marvin"
mt.stage_name = "Kelly"
mt.age = 29
mt.singer = true
mt.birthday = Date.new(1990,03,15)
mt.weight = 70
mt.height = 150
mt.save
mt2 = MyTranslation.find(mt.id, :consistent_read => true)
assert_kind_of String, mt2.name
assert_kind_of String, mt2.stage_name
assert_kind_of Integer, mt2.age
assert_kind_of Date, mt2.birthday
assert_kind_of Float, mt2.weight
assert_kind_of Float, mt2.height
# sadly, there is no bool type in Ruby
assert (mt.singer.is_a?(TrueClass) || mt.singer.is_a?(FalseClass))
assert_equal mt.name, mt2.name
assert_equal mt.stage_name, mt2.stage_name
assert_equal mt.age, mt2.age
assert_equal mt.singer, mt2.singer
assert_equal mt.birthday, mt2.birthday
assert_equal mt.weight, mt2.weight
assert_equal mt.height, mt2.height
end
def test_zzz9 # run last
MyTranslation.delete_domain
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_temp.rb | test/test_temp.rb | gem 'test-unit'
require 'test/unit'
require File.join(File.dirname(__FILE__), "/../lib/simple_record")
require File.join(File.dirname(__FILE__), "./test_helpers")
require_relative "test_base"
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
require_relative 'models/model_with_enc'
require_relative 'models/my_simple_model'
# Tests for SimpleRecord
#
class TestSimpleRecord < TestBase
def test_virtuals
model = MyBaseModel.new(:v1=>'abc', :base_string=>'what')
assert model.v1 == 'abc', "model.v1=" + model.v1.inspect
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_base.rb | test/test_base.rb | gem 'test-unit'
require 'test/unit'
require File.join(File.dirname(__FILE__), "/../lib/simple_record")
require File.join(File.dirname(__FILE__), "./test_helpers")
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
#require 'active_support'
class TestBase < Test::Unit::TestCase
def setup
reset_connection()
end
def teardown
SimpleRecord.close_connection
end
def delete_all(clz)
obs = clz.find(:all,:consistent_read=>true)
obs.each do |o|
o.delete
end
end
def reset_connection(options={})
@config = YAML::load(File.open(File.expand_path("~/.test_configs/simple_record.yml")))
SimpleRecord.enable_logging
SimpleRecord::Base.set_domain_prefix("simplerecord_tests_")
SimpleRecord.establish_connection(@config['amazon']['access_key'], @config['amazon']['secret_key'],
{:connection_mode=>:per_thread}.merge(options))
# Establish AWS connection directly
@@sdb = Aws::SdbInterface.new(@config['amazon']['access_key'], @config['amazon']['secret_key'],
{:connection_mode => :per_thread}.merge(options))
end
# Use to populate db
def create_my_models(count)
batch = []
count.times do |i|
mm = MyModel.new(:name=>"model_#{i}")
mm.age = i
batch << mm
end
MyModel.batch_save batch
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_lobs.rb | test/test_lobs.rb | require 'test/unit'
require_relative "../lib/simple_record"
require_relative "test_helpers"
require_relative "test_base"
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
require_relative 'models/model_with_enc'
# Tests for SimpleRecord
#
class TestLobs < TestBase
['puts','gets','deletes'].each do |stat|
eval "def assert_#{stat}(x)
assert_stat('#{stat}',x)
end"
end
def assert_stat(stat, x)
assert eval("SimpleRecord.stats.s3_#{stat} == x"), "#{stat} is #{eval("SimpleRecord.stats.s3_#{stat}")}, should be #{x}."
end
def test_prep
MyModel.delete_domain
end
def test_clobs
mm = MyModel.new
assert mm.clob1.nil?
mm.name = "whatever"
mm.age = "1"
mm.clob1 = "0" * 2000
assert_puts(0)
mm.save
assert_puts(1)
mm.clob1 = "1" * 2000
mm.clob2 = "2" * 2000
mm.save
assert_puts(3)
mm2 = MyModel.find(mm.id,:consistent_read=>true)
assert mm.id == mm2.id
assert mm.clob1 == mm2.clob1
assert_puts(3)
assert_gets(1)
mm2.clob1 # make sure it doesn't do another get
assert_gets(1)
assert mm.clob2 == mm2.clob2
assert_gets(2)
mm2.save
# shouldn't save twice if not dirty
assert_puts(3)
mm2.delete
assert_deletes(2)
e = assert_raise(Aws::AwsError) do
sclob = SimpleRecord.s3.bucket(mm2.s3_bucket_name2).get(mm2.s3_lob_id("clob1"))
end
assert_match(/NoSuchKey/, e.message)
e = assert_raise(Aws::AwsError) do
sclob = SimpleRecord.s3.bucket(mm2.s3_bucket_name2).get(mm2.s3_lob_id("clob2"))
end
assert_match(/NoSuchKey/, e.message)
end
def test_single_clob
mm = SingleClobClass.new
assert mm.clob1.nil?
mm.name = "whatever"
mm.clob1 = "0" * 2000
mm.clob2 = "2" * 2000
assert_puts(0)
mm.save
assert_puts(1)
mm2 = SingleClobClass.find(mm.id,:consistent_read=>true)
assert mm.id == mm2.id
assert_equal mm.clob1, mm2.clob1
assert_puts(1)
assert_gets(1)
mm2.clob1 # make sure it doesn't do another get
assert_gets(1)
assert mm.clob2 == mm2.clob2
assert_gets(1)
mm2.save
# shouldn't save twice if not dirty
assert_puts(1)
mm2.delete
assert_deletes(1)
e = assert_raise(Aws::AwsError) do
sclob = SimpleRecord.s3.bucket(mm2.s3_bucket_name2).get(mm2.single_clob_id)
end
assert_match(/NoSuchKey/, e.message)
end
def test_cleanup
MyModel.delete_domain
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_results_array.rb | test/test_results_array.rb | # These ones take longer to run
require 'test/unit'
require File.join(File.dirname(__FILE__), "/../lib/simple_record")
require File.join(File.dirname(__FILE__), "./test_helpers")
require File.join(File.dirname(__FILE__), "./test_base")
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
require 'active_support'
# Tests for SimpleRecord
#
class TestResultsArray < TestBase
# ensures that it uses next token and what not
def test_big_result
MyModel.delete_domain
MyModel.create_domain
SimpleRecord.stats.clear
num_made = 110
num_made.times do |i|
mm = MyModel.create(:name=>"Travis big_result #{i}", :age=>i, :cool=>true)
end
assert SimpleRecord.stats.saves == num_made, "SimpleRecord.stats.saves should be #{num_made}, is #{SimpleRecord.stats.saves}"
SimpleRecord.stats.clear # have to clear them again, as each save above created a select (in pre/post actions)
rs = MyModel.find(:all,:consistent_read=>true) # should get 100 at a time
assert rs.size == num_made, "rs.size should be #{num_made}, is #{rs.size}"
i = 0
rs.each do |x|
i+=1
end
assert SimpleRecord.stats.selects == 3, "SimpleRecord.stats.selects should be 3, is #{SimpleRecord.stats.selects}" # one for count.
assert i == num_made, "num_made should be #{i}, is #{num_made}"
# running through all the results twice to ensure it works properly after lazy loading complete.
SimpleRecord.stats.clear
i = 0
rs.each do |x|
#puts 'x=' + x.id
i+=1
end
assert SimpleRecord.stats.selects == 0, "SimpleRecord.stats.selects should be 0, is #{SimpleRecord.stats.selects}" # one for count.
assert i == num_made, "num_made should be #{i}, is #{num_made}"
end
def test_limit
SimpleRecord.stats.clear
rs = MyModel.find(:all, :per_token=>2500,:consistent_read=>true)
assert rs.size == 110, "rs.size should be 110, is #{rs.size}"
assert SimpleRecord.stats.selects == 1, "SimpleRecord.stats.selects is #{SimpleRecord.stats.selects}"
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_marshalled.rb | test/test_marshalled.rb | require 'test/unit'
require File.expand_path(File.dirname(__FILE__) + "/../lib/simple_record")
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
require 'active_support'
require 'test_base'
class Person < SimpleRecord::Base
has_strings :name, :i_as_s
has_ints :age, :i2
end
class MarshalTest < TestBase
def setup
super
Person.create_domain
@person = Person.new(:name => 'old', :age => 70)
@person.save
assert !@person.changed?
assert !@person.name_changed?
end
def teardown
Person.delete_domain
SimpleRecord.close_connection
end
def test_string_on_initialize
p = Person.new(:name=>"Travis", :age=>5, :i2=>"6")
assert p.name == "Travis"
assert p.age == 5
assert p.i2 == 6, "i2 == #{p.i2}"
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_helpers.rb | test/test_helpers.rb | class TestHelpers
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_validations.rb | test/test_validations.rb | gem 'test-unit'
require 'test/unit'
require File.join(File.dirname(__FILE__), "/../lib/simple_record")
require File.join(File.dirname(__FILE__), "./test_helpers")
require_relative "test_base"
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
require_relative 'models/model_with_enc'
require_relative 'models/validated_model'
# Tests for SimpleRecord
#
class TestValidations < TestBase
def test_aaa1 # run first
MyModel.delete_domain
ValidatedModel.delete_domain
MyModel.create_domain
ValidatedModel.create_domain
end
def test_first_validations
mm = MyModel.new()
assert mm.invalid?, "mm is valid. invalid? returned #{mm.invalid?}"
assert_equal 1, mm.errors.size
assert !mm.attr_before_create
assert !mm.valid?
assert mm.save == false, mm.errors.inspect
assert !mm.attr_before_create # should not get called if not valid
assert !mm.attr_after_save
assert !mm.attr_after_create
mm.name = "abcd"
assert mm.valid?, mm.errors.inspect
assert_equal 0, mm.errors.size
mm.save_count = 2
assert mm.invalid?
mm.save_count = nil
assert mm.valid?
assert mm.save, mm.errors.inspect
assert mm.attr_before_create
assert mm.attr_after_save
assert mm.attr_after_create
assert !mm.attr_after_update
assert mm.valid?, mm.errors.inspect
assert_equal 1, mm.save_count
mm.name = "abc123"
assert mm.save
assert mm.attr_after_update
end
def test_more_validations
name = 'abcd'
model = ValidatedModel.new
assert !model.valid?
assert !model.save
model.name = name
assert model.valid?
assert model.save
sleep 1
model2 = ValidatedModel.new
model2.name = name
assert !model.valid?
assert !model.save
assert model.errors.size > 0
end
def test_zzz9 # run last
MyModel.delete_domain
ValidatedModel.delete_domain
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_rails3.rb | test/test_rails3.rb | require 'test/unit'
require 'active_model'
require File.join(File.dirname(__FILE__), "/../lib/simple_record")
require File.join(File.dirname(__FILE__), "./test_helpers")
require File.join(File.dirname(__FILE__), "./test_base")
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
require_relative 'models/model_with_enc'
# To test things related to rails 3 like ActiveModel usage.
class TestRails3 < TestBase
def test_active_model_defined
my_model = MyModel.new
assert (defined?(MyModel.model_name))
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_shards.rb | test/test_shards.rb | require 'test/unit'
require File.join(File.dirname(__FILE__), "/../lib/simple_record")
require File.join(File.dirname(__FILE__), "./test_helpers")
require File.join(File.dirname(__FILE__), "./test_base")
require "yaml"
require 'aws'
require_relative 'models/my_sharded_model'
# Tests for SimpleRecord
#
class TestShards < TestBase
def setup
super
# delete_all MyShardedModel
# delete_all MyShardedByFieldModel
end
def teardown
super
end
# We'll want to shard based on ID's, user decides how many shards and some mapping function will
# be used to select the shard.
def test_id_sharding
# test_id_sharding start
ob_count = 1000
mm = MyShardedModel.new(:name=>"single")
mm.save
# finding by id
mm2 = MyShardedModel.find(mm.id,:consistent_read=>true)
assert_equal mm.id, mm2.id
# deleting
mm2.delete
mm3 = MyShardedModel.find(mm.id,:consistent_read=>true)
assert_nil mm3
saved = []
ob_count.times do |i|
mm = MyShardedModel.new(:name=>"name #{i}")
mm.save
saved << mm
end
# todo: assert that we're actually sharding
# finding them all sequentially
start_time = Time.now
found = []
rs = MyShardedModel.find(:all, :per_token=>2500,:consistent_read=>true)
rs.each do |m|
found << m
end
duration = Time.now.to_f - start_time.to_f
# Find sequential duration
saved.each do |so|
assert(found.find { |m1| m1.id == so.id })
end
# Now let's try concurrently
start_time = Time.now
found = []
rs = MyShardedModel.find(:all, :concurrent=>true, :per_token=>2500,:consistent_read=>true)
rs.each do |m|
found << m
end
concurrent_duration = Time.now.to_f - start_time.to_f
saved.each do |so|
assert(found.find { |m1| m1.id == so.id })
end
assert concurrent_duration < duration
# deleting all of them
found.each do |fo|
fo.delete
end
# Now ensure that all are deleted
rs = MyShardedModel.find(:all,:consistent_read=>true)
assert rs.size == 0
# Testing belongs_to sharding
end
def test_field_sharding
states = MyShardedByFieldModel.shards
mm = MyShardedByFieldModel.new(:name=>"single", :state=>"CA")
mm.save
mm2 = MyShardedByFieldModel.find(mm.id,:consistent_read=>true)
assert_equal mm.id, mm2.id
mm2.delete
mm3 = MyShardedByFieldModel.find(mm.id,:consistent_read=>true)
assert_nil mm3
# saving 20 now
saved = []
20.times do |i|
mm = MyShardedByFieldModel.new(:name=>"name #{i}", :state=>states[i % states.size])
mm.save
saved << mm
end
# todo: assert that we're actually sharding
# finding them all
found = []
rs = MyShardedByFieldModel.find(:all,:consistent_read=>true)
rs.each do |m|
found << m
end
saved.each do |so|
assert(found.find { |m1| m1.id == so.id })
end
rs = MyShardedByFieldModel.find(:all,:consistent_read=>true)
rs.each do |m|
found << m
end
saved.each do |so|
assert(found.find { |m1| m1.id == so.id })
end
# Try to find on a specific known shard
selects = SimpleRecord.stats.selects
cali_models = MyShardedByFieldModel.find(:all, :shard => "CA",:consistent_read=>true)
assert_equal(5, cali_models.size)
assert_equal(selects + 1, SimpleRecord.stats.selects)
# deleting all of them
found.each do |fo|
fo.delete
end
# Now ensure that all are deleted
rs = MyShardedByFieldModel.find(:all,:consistent_read=>true)
assert_equal rs.size, 0
end
def test_time_sharding
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_dirty.rb | test/test_dirty.rb | require 'test/unit'
require File.expand_path(File.dirname(__FILE__) + "/../lib/simple_record")
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
require 'active_support'
require 'test_base'
class Person < SimpleRecord::Base
has_strings :name, :i_as_s
has_ints :age
end
class DirtyTest < TestBase
def setup
super
Person.create_domain
@person = Person.new(:name => 'old', :age => 70)
@person.save
assert !@person.changed?
assert !@person.name_changed?
end
def teardown
Person.delete_domain
SimpleRecord.close_connection
end
def test_same_value_are_not_dirty
@person.name = "old"
assert !@person.changed?
assert !@person.name_changed?
@person.age = 70
assert !@person.changed?
assert !@person.age_changed?
end
def test_reverted_changes_are_not_dirty
@person.name = "new"
assert @person.changed?
assert @person.name_changed?
@person.name = "old"
assert !@person.changed?
assert !@person.name_changed?
@person.age = 15
assert @person.changed?
assert @person.age_changed?
@person.age = 70
assert !@person.changed?
assert !@person.age_changed?
end
def test_storing_int_as_string
@person.i_as_s = 5
assert @person.changed?
assert @person.i_as_s_changed?
@person.save
sleep 2
@person.i_as_s = 5
# Maybe this should fail? What do we expect this behavior to be?
# assert !@person.changed?
# assert !@person.i_as_s_changed?
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_json.rb | test/test_json.rb | require 'test/unit'
require File.join(File.dirname(__FILE__), "/../lib/simple_record")
require File.join(File.dirname(__FILE__), "./test_helpers")
require File.join(File.dirname(__FILE__), "./test_base")
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
require_relative 'models/model_with_enc'
require 'active_support/core_ext'
# Tests for SimpleRecord
#
class TestJson < TestBase
def test_prep
MyModel.delete_domain
end
def test_json
mm = MyModel.new
mm.name = "whatever"
mm.age = "1"
jsoned = mm.to_json
puts 'jsoned=' + jsoned
unjsoned = JSON.parse jsoned
puts 'unjsoned=' + unjsoned.inspect
assert_equal unjsoned.name, "whatever"
mm.save
puts 'no trying an array'
data = {}
models = []
data[:models] = models
models << mm
jsoned = models.to_json
puts 'jsoned=' + jsoned
unjsoned = JSON.parse jsoned
puts 'unjsoned=' + unjsoned.inspect
assert_equal unjsoned.size, models.size
assert_equal unjsoned[0].name, mm.name
assert_equal unjsoned[0].age, mm.age
assert unjsoned[0].created.present?
assert unjsoned[0].id.present?
assert_equal unjsoned[0].id, mm.id
puts 'array good'
t = Tester.new
t2 = Tester.new
t2.x1 = "i'm number 2"
t.x1 = 1
t.x2 = t2
jsoned = t.to_json
puts 'jsoned=' + jsoned
puts 'non simplerecord object good'
mcm = MyChildModel.new
mcm.name = "child"
mcm.my_model = mm
jsoned = mcm.to_json
puts 'jsoned=' + jsoned
unjsoned = JSON.parse jsoned
puts 'unjsoned=' + unjsoned.inspect
assert_equal mcm.my_model.id, unjsoned.my_model.id
end
def test_cleanup
MyModel.delete_domain
end
end
class Tester
attr_accessor :x1, :x2
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/test_global_options.rb | test/test_global_options.rb | require 'test/unit'
require_relative "../lib/simple_record"
require "yaml"
require 'aws'
require_relative 'models/my_model'
require_relative 'models/my_child_model'
require 'active_support/core_ext'
require_relative 'test_base'
class Person < SimpleRecord::Base
has_strings :name, :i_as_s
has_ints :age
end
class TestGlobalOptions < TestBase
def setup
super
end
def test_domain_prefix
SimpleRecord::Base.set_domain_prefix("someprefix_")
p = Person.create(:name=>"my prefix name")
sleep 1
sdb_atts = @@sdb.select("select * from someprefix_people")
@@sdb.delete_domain("someprefix_people") # doing it here so it's done before assertions might fail
assert_equal sdb_atts[:items].size, 1
end
def test_created_col_and_updated_col
reset_connection(:created_col=>"created_at", :updated_col=>"updated_at")
p = Person.create(:name=>"my prefix name")
sleep 1
sdb_atts = @@sdb.select("select * from simplerecord_tests_people")
@@sdb.delete_domain("simplerecord_tests_people")
items = sdb_atts[:items][0]
first = nil
items.each_pair do |k, v|
first = v
break
end
assert_nil first["created"]
assert_not_nil first["created_at"]
# put this back to normal so it doesn't interfere with other tests
reset_connection(:created_col=>"created", :updated_col=>"updated")
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/models/my_translation.rb | test/models/my_translation.rb | require File.expand_path(File.dirname(__FILE__) + "/../../lib/simple_record")
class MyTranslation < SimpleRecord::Base
has_strings :name, :stage_name
has_ints :age
has_booleans :singer
has_dates :birthday
has_floats :weight, :height
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/models/my_sharded_model.rb | test/models/my_sharded_model.rb | require File.expand_path(File.dirname(__FILE__) + "/../../lib/simple_record")
class MyShardedModel < SimpleRecord::Base
shard :shards=>:my_shards, :map=>:my_mapping_function
has_strings :name
def self.num_shards
10
end
def self.my_shards
Array(0...self.num_shards)
end
def my_mapping_function
shard_num = SimpleRecord::Sharding::Hashing.sdbm_hash(self.id) % self.class.num_shards
shard_num
end
def self.shard_for_find(id)
shard_num = SimpleRecord::Sharding::Hashing.sdbm_hash(id) % self.num_shards
end
end
class MyShardedByFieldModel < SimpleRecord::Base
shard :shards=>:my_shards, :map=>:my_mapping_function
has_strings :name, :state
def self.my_shards
['AL', 'CA', 'FL', 'NY']
end
def my_mapping_function
state
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/models/my_child_model.rb | test/models/my_child_model.rb | require File.expand_path(File.dirname(__FILE__) + "/../../lib/simple_record")
require_relative 'my_model'
class MyChildModel < SimpleRecord::Base
belongs_to :my_model
belongs_to :x, :class_name=>"MyModel"
has_attributes :name, :child_attr
end
=begin
puts 'word'
mm = MyModel.new
puts 'word2'
mcm = MyChildModel.new
puts 'mcm instance methods=' + MyChildModel.instance_methods(true).inspect
#puts 'mcm=' + mcm.instance_methods(false)
puts 'mcm class vars = ' + mcm.class.class_variables.inspect
puts mcm.class == MyChildModel
puts 'saved? ' + mm.save.to_s
puts mm.errors.inspect
puts "mm attributes=" + MyModel.defined_attributes.inspect
puts "mcm attributes=" + MyChildModel.defined_attributes.inspect
mcm2 = MyChildModel.new
puts "mcm2 attributes=" + MyChildModel.defined_attributes.inspect
=end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/models/validated_model.rb | test/models/validated_model.rb | require_relative "../../lib/simple_record"
require 'active_model'
class ValidatedModel < MyBaseModel
has_strings :name
validates_presence_of :name
validates_uniqueness_of :name
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/models/my_base_model.rb | test/models/my_base_model.rb | require File.expand_path(File.dirname(__FILE__) + "/../../lib/simple_record")
class MyBaseModel < SimpleRecord::Base
has_strings :base_string
has_virtuals :v1
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/models/my_simple_model.rb | test/models/my_simple_model.rb | require File.expand_path(File.dirname(__FILE__) + "/../../lib/simple_record")
require_relative 'my_base_model'
require_relative 'my_sharded_model'
class MySimpleModel < SimpleRecord::Base
has_strings :name, :nickname, :s1, :s2
has_ints :age, :save_count
has_booleans :cool
has_dates :birthday, :date1, :date2, :date3
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/models/my_model.rb | test/models/my_model.rb | require File.expand_path(File.dirname(__FILE__) + "/../../lib/simple_record")
require_relative 'my_base_model'
require_relative 'my_sharded_model'
require 'active_model'
class MyModel < MyBaseModel
has_strings :name, :nickname, :s1, :s2
has_ints :age, :save_count
has_booleans :cool
has_dates :birthday, :date1, :date2, :date3
# validates_presence_of :name
# validate :validate
# before_create :validate_on_create
# before_update :validate_on_update
validates_uniqueness_of :name
belongs_to :my_sharded_model
has_clobs :clob1, :clob2
attr_accessor :attr_before_save, :attr_after_save, :attr_before_create, :attr_after_create, :attr_after_update
#callbacks
before_create :set_nickname
after_create :after_create
before_save :before_save
after_save :after_save
after_update :after_update
def set_nickname
@attr_before_create = true
self.nickname = name if self.nickname.blank?
end
def before_save
@attr_before_save = true
end
def after_create
@attr_after_create = true
end
def after_save
@attr_after_save = true
bump_save_count
end
def after_update
@attr_after_update = true
end
def bump_save_count
if save_count.nil?
self.save_count = 1
else
self.save_count += 1
end
end
def validate
errors.add("name", "can't be empty.") if name.blank?
end
def validate_on_create
errors.add("save_count", "should be zero.") if !save_count.blank? && save_count > 0
end
def validate_on_update
end
def atts
@@attributes
end
end
class SingleClobClass < SimpleRecord::Base
sr_config :single_clob=>true
has_strings :name
has_clobs :clob1, :clob2
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/test/models/model_with_enc.rb | test/models/model_with_enc.rb |
class ModelWithEnc < SimpleRecord::Base
has_strings :name,
{:name=>:ssn, :encrypted=>"simple_record_test_key"},
{:name=>:password, :hashed=>true}
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record.rb | lib/simple_record.rb | # Usage:
# require 'simple_record'
#
# class MyModel < SimpleRecord::Base
#
# has_attributes :name, :age
# are_ints :age
#
# end
#
# AWS_ACCESS_KEY_ID='XXXXX'
# AWS_SECRET_ACCESS_KEY='YYYYY'
# SimpleRecord.establish_connection(AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY)
#
## Save an object
# mm = MyModel.new
# mm.name = "Travis"
# mm.age = 32
# mm.save
# id = mm.id
# # Get the object back
# mm2 = MyModel.select(id)
# puts 'got=' + mm2.name + ' and he/she is ' + mm.age.to_s + ' years old'
#
# Forked off old ActiveRecord2sdb library.
require 'aws'
require 'base64'
require 'active_support'
if ActiveSupport::VERSION::MAJOR >= 3
# had to do this due to some bug: https://github.com/rails/rails/issues/12876
# fix: https://github.com/railsmachine/shadow_puppet/pull/19/files
require 'active_support/deprecation'
require 'active_support/core_ext'
end
begin
# comment out line below to test rails2 validations
require 'active_model'
rescue LoadError => ex
puts "ActiveModel not available, falling back."
end
require File.expand_path(File.dirname(__FILE__) + "/simple_record/validations")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/attributes")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/active_sdb")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/callbacks")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/encryptor")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/errors")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/json")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/logging")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/password")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/results_array")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/stats")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/translations")
require_relative 'simple_record/sharding'
module SimpleRecord
@@options = {}
@@stats = SimpleRecord::Stats.new
@@logging = false
@@s3 = nil
@@auto_close_s3 = false
@@logger = Logger.new(STDOUT)
@@logger.level = Logger::INFO
class << self;
attr_accessor :aws_access_key, :aws_secret_key
# Deprecated
def enable_logging
@@logging = true
@@logger.level = Logger::DEBUG
end
# Deprecated
def disable_logging
@@logging = false
end
# Deprecated
def logging?
@@logging
end
def logger
@@logger
end
# This can be used to log queries and what not to a file.
# Params:
# :select=>{:filename=>"file_to_write_to", :format=>"csv"}
def log_usage(types={})
@usage_logging_options = {} unless @usage_logging_options
return if types.nil?
types.each_pair do |type, options|
options[:lines_between_flushes] = 100 unless options[:lines_between_flushes]
@usage_logging_options[type] = options
end
#puts 'SimpleRecord.usage_logging_options=' + SimpleRecord.usage_logging_options.inspect
end
def close_usage_log(type)
return unless @usage_logging_options[type]
@usage_logging_options[type][:file].close if @usage_logging_options[type][:file]
# unless we remove it, it will keep trying to log these events
# and will fail because the file is closed.
@usage_logging_options.delete(type)
end
def usage_logging_options
@usage_logging_options
end
def stats
@@stats
end
# Create a new handle to an Sdb account. All handles share the same per process or per thread
# HTTP connection to Amazon Sdb. Each handle is for a specific account.
# The +params+ are passed through as-is to Aws::SdbInterface.new
# Params:
# { :server => 'sdb.amazonaws.com' # Amazon service host: 'sdb.amazonaws.com'(default)
# :port => 443 # Amazon service port: 80(default) or 443
# :protocol => 'https' # Amazon service protocol: 'http'(default) or 'https'
# :signature_version => '0' # The signature version : '0' or '1'(default)
# :connection_mode => :default # options are
# :default (will use best known safe (as in won't need explicit close) option, may change in the future)
# :per_request (opens and closes a connection on every request to SDB)
# :single (one thread across entire app)
# :per_thread (one connection per thread)
# :pool (uses a connection pool with a maximum number of connections - NOT IMPLEMENTED YET)
# :logger => Logger Object # Logger instance: logs to STDOUT if omitted
def establish_connection(aws_access_key=nil, aws_secret_key=nil, options={})
@aws_access_key = aws_access_key
@aws_secret_key = aws_secret_key
@@options.merge!(options)
#puts 'SimpleRecord.establish_connection with options: ' + @@options.inspect
SimpleRecord::ActiveSdb.establish_connection(aws_access_key, aws_secret_key, @@options)
if options[:connection_mode] == :per_thread
@@auto_close_s3 = true
# todo: should we init this only when needed?
end
s3_ops = {:connection_mode=>options[:connection_mode] || :default}
@@s3 = Aws::S3.new(SimpleRecord.aws_access_key, SimpleRecord.aws_secret_key, s3_ops)
if options[:created_col]
SimpleRecord::Base.has_dates options[:created_col]
end
if options[:updated_col]
SimpleRecord::Base.has_dates options[:updated_col]
end
end
# Call this to close the connection to SimpleDB.
# If you're using this in Rails with per_thread connection mode, you should do this in
# an after_filter for each request.
def close_connection()
SimpleRecord::ActiveSdb.close_connection
@@s3.close_connection if @@auto_close_s3
end
# If you'd like to specify the s3 connection to use for LOBs, you can pass it in here.
# We recommend that this connection matches the type of connection you're using for SimpleDB,
# at least if you're using per_thread connection mode.
def s3=(s3)
@@s3 = s3
end
def s3
@@s3
end
def options
@@options
end
end
class Base < SimpleRecord::ActiveSdb::Base
# puts 'Is ActiveModel defined? ' + defined?(ActiveModel).inspect
if defined?(ActiveModel)
@@active_model = true
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
extend ActiveModel::Callbacks # for ActiveRecord like callbacks
include ActiveModel::Validations::Callbacks
define_model_callbacks :save, :create, :update, :destroy
include SimpleRecord::Callbacks3
alias_method :am_valid?, :valid?
else
@@active_model = false
attr_accessor :errors
include SimpleRecord::Callbacks
end
include SimpleRecord::Validations
extend SimpleRecord::Validations::ClassMethods
include SimpleRecord::Translations
# include SimpleRecord::Attributes
extend SimpleRecord::Attributes::ClassMethods
include SimpleRecord::Attributes
extend SimpleRecord::Sharding::ClassMethods
include SimpleRecord::Sharding
include SimpleRecord::Json
include SimpleRecord::Logging
extend SimpleRecord::Logging::ClassMethods
def self.extended(base)
end
def initialize(attrs={})
# todo: Need to deal with objects passed in. iterate through belongs_to perhaps and if in attrs, set the objects id rather than the object itself
initialize_base(attrs)
# Convert attributes to sdb values
attrs.each_pair do |name, value|
set(name, value, true)
end
end
def initialize_base(attrs={})
#we have to handle the virtuals.
handle_virtuals(attrs)
clear_errors
@dirty = {}
@attributes = {} # sdb values
@attributes_rb = {} # ruby values
@lobs = {}
@new_record = true
end
def initialize_from_db(attrs={})
initialize_base(attrs)
attrs.each_pair do |k, v|
@attributes[k.to_s] = v
end
end
def self.inherited(base)
# puts 'SimpleRecord::Base is inherited by ' + base.inspect
Callbacks.setup_callbacks(base)
# base.has_strings :id
base.has_dates :created, :updated
base.before_create :set_created, :set_updated
base.before_update :set_updated
end
def persisted?
!@new_record && !destroyed?
end
def destroyed?
@deleted
end
def defined_attributes_local
# todo: store this somewhere so it doesn't keep going through this
ret = self.class.defined_attributes
ret.merge!(self.class.superclass.defined_attributes) if self.class.superclass.respond_to?(:defined_attributes)
end
class << self;
attr_accessor :domain_prefix
end
#@domain_name_for_class = nil
@@cache_store = nil
# Set the cache to use
def self.cache_store=(cache)
@@cache_store = cache
end
def self.cache_store
return @@cache_store
end
# If you want a domain prefix for all your models, set it here.
def self.set_domain_prefix(prefix)
#puts 'set_domain_prefix=' + prefix
self.domain_prefix = prefix
end
# Same as set_table_name
def self.set_table_name(table_name)
set_domain_name table_name
end
# Sets the domain name for this class
def self.set_domain_name(table_name)
super
end
def domain
self.class.domain
end
def self.domain
unless @domain
# This strips off the module if there is one.
n2 = name.split('::').last || name
# puts 'n2=' + n2
if n2.respond_to?(:tableize)
@domain = n2.tableize
else
@domain = n2.downcase
end
set_domain_name @domain
end
domain_name_for_class = (SimpleRecord::Base.domain_prefix || "") + @domain.to_s
domain_name_for_class
end
def has_id_on_end(name_s)
name_s = name_s.to_s
name_s.length > 3 && name_s[-3..-1] == "_id"
end
def get_att_meta(name)
name_s = name.to_s
att_meta = defined_attributes_local[name.to_sym]
if att_meta.nil? && has_id_on_end(name_s)
att_meta = defined_attributes_local[name_s[0..-4].to_sym]
end
return att_meta
end
def sdb_att_name(name)
att_meta = get_att_meta(name)
if att_meta.type == :belongs_to && !has_id_on_end(name.to_s)
return "#{name}_id"
end
name.to_s
end
def strip_array(arg)
if arg.is_a? Array
if arg.length==1
ret = arg[0]
else
ret = arg
end
else
ret = arg
end
return ret
end
def make_dirty(arg, value)
sdb_att_name = sdb_att_name(arg)
arg = arg.to_s
# puts "Marking #{arg} dirty with #{value}" if SimpleRecord.logging?
if @dirty.include?(sdb_att_name)
old = @dirty[sdb_att_name]
# puts "#{sdb_att_name} was already dirty #{old}"
@dirty.delete(sdb_att_name) if value == old
else
old = get_attribute(arg)
# puts "dirtifying #{sdb_att_name} old=#{old.inspect} to new=#{value.inspect}" if SimpleRecord.logging?
@dirty[sdb_att_name] = old if value != old
end
end
def clear_errors
if defined?(ActiveModel)
@errors = ActiveModel::Errors.new(self)
else
@errors=SimpleRecord_errors.new
end
end
def []=(attribute, values)
make_dirty(attribute, values)
super
end
def [](attribute)
super
end
def set_created
set(SimpleRecord.options[:created_col] || :created, Time.now)
end
def set_updated
set(SimpleRecord.options[:updated_col] || :updated, Time.now)
end
# an aliased method since many people use created_at/updated_at naming convention
def created_at
self.created
end
# an aliased method since many people use created_at/updated_at naming convention
def updated_at
self.updated
end
def cache_store
@@cache_store
end
def domain_ok(ex, options={})
if (ex.message().index("NoSuchDomain") != nil)
dom = options[:domain] || domain
self.class.create_domain(dom)
return true
end
return false
end
def new_record?
# todo: new_record in activesdb should align with how we're defining a new record here, ie: if id is nil
super
end
@create_domain_called = false
# Options:
# - :except => Array of attributes to NOT save
# - :dirty => true - Will only store attributes that were modified. To make it save regardless and have it update the :updated value, include this and set it to false.
# - :domain => Explicitly define domain to use.
#
def save(options={})
puts 'SAVING: ' + self.inspect if SimpleRecord.logging?
# todo: Clean out undefined values in @attributes (in case someone set the attributes hash with values that they hadn't defined)
clear_errors
# todo: decide whether this should go before pre_save or after pre_save? pre_save dirties "updated" and perhaps other items due to callbacks
if options[:dirty]
# puts '@dirtyA=' + @dirty.inspect
return true if @dirty.size == 0 # Nothing to save so skip it
end
ok = pre_save(options) # Validates and sets ID
if ok
if @@active_model
ok = create_or_update(options)
else
ok = do_actual_save(options)
end
end
return ok
end
def do_actual_save(options)
begin
is_create = new_record? # self[:id].nil?
dirty = @dirty
# puts 'dirty before=' + @dirty.inspect
if options[:dirty]
# puts '@dirty=' + @dirty.inspect
return true if @dirty.size == 0 # This should probably never happen because after pre_save, created/updated dates are changed
options[:dirty_atts] = @dirty
end
to_delete = get_atts_to_delete
if self.class.is_sharded?
options[:domain] = sharded_domain
end
return save_super(dirty, is_create, options, to_delete)
rescue Aws::AwsError => ex
raise ex
end
end
# if @@active_model
# alias_method :old_save, :save
#
# def save(options={})
## puts 'extended save'
# x = create_or_update
## puts 'save x=' + x.to_s
# x
# end
# end
def create_or_update(options) #:nodoc:
# puts 'create_or_update'
ret = true
run_callbacks :save do
result = new_record? ? create(options) : update(options)
# puts 'save_callbacks result=' + result.inspect
ret = result
end
ret
end
def create(options) #:nodoc:
puts '3 create'
ret = true
run_callbacks :create do
x = do_actual_save(options)
# puts 'create old_save result=' + x.to_s
ret = x
end
ret
end
#
def update(options) #:nodoc:
puts '3 update'
ret = true
run_callbacks :update do
x = do_actual_save(options)
# puts 'update old_save result=' + x.to_s
ret = x
end
ret
end
def save!(options={})
save(options) || raise(RecordNotSaved.new(self))
end
# this is a bit wonky, save! should call this, not sure why it's here.
def save_with_validation!(options={})
save!
end
def self.create(attributes={})
# puts "About to create in domain #{domain}"
super
end
def self.create!(attributes={})
item = self.new(attributes)
item.save!
item
end
def save_super(dirty, is_create, options, to_delete)
SimpleRecord.stats.saves += 1
if save2(options)
self.class.cache_results(self)
delete_niled(to_delete)
save_lobs(dirty)
after_save_cleanup
unless @@active_model
if (is_create ? run_after_create : run_after_update) && run_after_save
# puts 'all good?'
return true
else
return false
end
end
return true
else
return false
end
end
def save_lobs(dirty=nil)
# puts 'dirty.inspect=' + dirty.inspect
dirty = @dirty if dirty.nil?
all_clobs = {}
dirty_clobs = {}
defined_attributes_local.each_pair do |k, v|
# collect up the clobs in case it's a single put
if v.type == :clob
val = @lobs[k]
all_clobs[k] = val
if dirty.include?(k.to_s)
dirty_clobs[k] = val
else
# puts 'NOT DIRTY'
end
end
end
if dirty_clobs.size > 0
if self.class.get_sr_config[:single_clob]
# all clobs in one chunk
# using json for now, could change later
val = all_clobs.to_json
puts 'val=' + val.inspect
put_lob(single_clob_id, val, :s3_bucket=>:new)
else
dirty_clobs.each_pair do |k, val|
put_lob(s3_lob_id(k), val)
end
end
end
end
def delete_lobs
defined_attributes_local.each_pair do |k, v|
if v.type == :clob
if self.class.get_sr_config[:single_clob]
s3_bucket(false, :s3_bucket=>:new).delete_key(single_clob_id)
SimpleRecord.stats.s3_deletes += 1
return
else
s3_bucket.delete_key(s3_lob_id(k))
SimpleRecord.stats.s3_deletes += 1
end
end
end
end
def put_lob(k, val, options={})
begin
s3_bucket(false, options).put(k, val)
rescue Aws::AwsError => ex
if ex.include? /NoSuchBucket/
s3_bucket(true, options).put(k, val)
else
raise ex
end
end
SimpleRecord.stats.s3_puts += 1
end
def is_dirty?(name)
# todo: should change all the dirty stuff to symbols?
# puts '@dirty=' + @dirty.inspect
# puts 'name=' +name.to_s
@dirty.include? name.to_s
end
def s3
return SimpleRecord.s3 if SimpleRecord.s3
# todo: should optimize this somehow, like use the same connection_mode as used in SR
# or keep open while looping in ResultsArray.
Aws::S3.new(SimpleRecord.aws_access_key, SimpleRecord.aws_secret_key)
end
# options:
# :s3_bucket => :old/:new/"#{any_bucket_name}". :new if want to use new bucket. Defaults to :old for backwards compatability.
def s3_bucket(create=false, options={})
s3.bucket(s3_bucket_name(options[:s3_bucket]), create)
end
def s3_bucket_name(s3_bucket_option=:old)
if s3_bucket_option == :new || SimpleRecord.options[:s3_bucket] == :new
# this is the bucket that will be used going forward for anything related to s3
ret = "simple_record_#{SimpleRecord.aws_access_key}"
elsif !SimpleRecord.options[:s3_bucket].nil? && SimpleRecord.options[:s3_bucket] != :old
ret = SimpleRecord.options[:s3_bucket]
else
ret = SimpleRecord.aws_access_key + "_lobs"
end
ret
end
def s3_lob_id(name)
# if s3_bucket is not nil and not :old, then we use the new key.
if !SimpleRecord.options[:s3_bucket].nil? && SimpleRecord.options[:s3_bucket] != :old
"lobs/#{self.id}_#{name}"
else
self.id + "_" + name.to_s
end
end
def single_clob_id
"lobs/#{self.id}_single_clob"
end
def self.get_encryption_key()
key = SimpleRecord.options[:encryption_key]
# if key.nil?
# puts 'WARNING: Encrypting attributes with your AWS Access Key. You should use your own :encryption_key so it doesn\'t change'
# key = connection.aws_access_key_id # default to aws access key. NOT recommended in case you start using a new key
# end
return key
end
def pre_save(options)
# puts '@@active_model ? ' + @@active_model.inspect
ok = true
is_create = self[:id].nil?
unless @@active_model
ok = run_before_validation && (is_create ? run_before_validation_on_create : run_before_validation_on_update)
return false unless ok
end
# validate()
# is_create ? validate_on_create : validate_on_update
if !valid?
puts 'not valid'
return false
end
#
## puts 'AFTER VALIDATIONS, ERRORS=' + errors.inspect
# if (!errors.nil? && errors.size > 0)
## puts 'THERE ARE ERRORS, returning false'
# return false
# end
unless @@active_model
ok = run_after_validation && (is_create ? run_after_validation_on_create : run_after_validation_on_update)
return false unless ok
end
# Now for callbacks
unless @@active_model
ok = respond_to?(:before_save) ? before_save : true
if ok
# puts 'ok'
if is_create && respond_to?(:before_create)
# puts 'responsds to before_create'
ok = before_create
elsif !is_create && respond_to?(:before_update)
ok = before_update
end
end
if ok
ok = run_before_save && (is_create ? run_before_create : run_before_update)
end
else
end
prepare_for_update
ok
end
def get_atts_to_delete
to_delete = []
changes.each_pair do |key, v|
if v[1].nil?
to_delete << key
@attributes.delete(key)
end
end
# @attributes.each do |key, value|
## puts 'key=' + key.inspect + ' value=' + value.inspect
# if value.nil? || (value.is_a?(Array) && value.size == 0) || (value.is_a?(Array) && value.size == 1 && value[0] == nil)
# to_delete << key
# @attributes.delete(key)
# end
# end
return to_delete
end
# Run pre_save on each object, then runs batch_put_attributes
# Returns
def self.batch_save(objects, options={})
options[:create_domain] = true if options[:create_domain].nil?
results = []
to_save = []
if objects && objects.size > 0
objects.each_slice(25) do |objs|
objs.each do |o|
ok = o.pre_save(options)
raise "Pre save failed on object [" + o.inspect + "]" if !ok
results << ok
next if !ok # todo: this shouldn't be here should it? raises above
o.pre_save2
to_save << Aws::SdbInterface::Item.new(o.id, o.attributes, true)
end
connection.batch_put_attributes(domain, to_save, options)
to_save.clear
end
end
objects.each do |o|
o.save_lobs(nil)
end
results
end
# Pass in an array of objects
def self.batch_delete(objects, options={})
if objects
objects.each_slice(25) do |objs|
connection.batch_delete_attributes @domain, objs.collect { |x| x.id }
end
end
end
#
# Usage: ClassName.delete id
#
def self.delete(id)
connection.delete_attributes(domain, id)
@deleted = true
end
# Pass in the same OPTIONS you'd pass into a find(:all, OPTIONS)
def self.delete_all(options={})
# could make this quicker by just getting item_names and deleting attributes rather than creating objects
obs = self.find(:all, options)
i = 0
obs.each do |a|
a.delete
i+=1
end
return i
end
# Pass in the same OPTIONS you'd pass into a find(:all, OPTIONS)
def self.destroy_all(options={})
obs = self.find(:all, options)
i = 0
obs.each do |a|
a.destroy
i+=1
end
return i
end
def delete(options={})
if self.class.is_sharded?
options[:domain] = sharded_domain
end
super(options)
# delete lobs now too
delete_lobs
end
def destroy
if @@active_model
run_callbacks :destroy do
delete
end
else
return run_before_destroy && delete && run_after_destroy
end
end
def delete_niled(to_delete)
# puts 'to_delete=' + to_delete.inspect
if to_delete.size > 0
# puts 'Deleting attributes=' + to_delete.inspect
SimpleRecord.stats.deletes += 1
delete_attributes to_delete
to_delete.each do |att|
att_meta = get_att_meta(att)
if att_meta.type == :clob
s3_bucket.key(s3_lob_id(att)).delete
end
end
end
end
def reload
super()
end
def update_attributes(atts)
set_attributes(atts)
save
end
def update_attributes!(atts)
set_attributes(atts)
save!
end
def self.quote_regexp(a, re)
a =~ re
#was there a match?
if $&
before=$`
middle=$&
after =$'
before =~ /'$/ #is there already a quote immediately before the match?
unless $&
return "#{before}'#{middle}'#{quote_regexp(after, re)}" #if not, put quotes around the match
else
return "#{before}#{middle}#{quote_regexp(after, re)}" #if so, assume it is quoted already and move on
end
else
#no match, just return the string
return a
end
end
@@regex_no_id = /.*Couldn't find.*with ID.*/
#
# Usage:
# Find by ID:
# MyModel.find(ID)
#
# Query example:
# MyModel.find(:all, :conditions=>["name = ?", name], :order=>"created desc", :limit=>10)
#
# Extra options:
# :per_token => the number of results to return per next_token, max is 2500.
# :consistent_read => true/false -- as per http://developer.amazonwebservices.com/connect/entry.jspa?externalID=3572
# :retries => maximum number of times to retry this query on an error response.
# :shard => shard name or array of shard names to use on this query.
def self.find(*params)
#puts 'params=' + params.inspect
q_type = :all
select_attributes=[]
if params.size > 0
q_type = params[0]
end
options = {}
if params.size > 1
options = params[1]
end
conditions = options[:conditions]
if conditions && conditions.is_a?(String)
conditions = [conditions]
options[:conditions] = conditions
end
if !options[:shard_find] && is_sharded?
# then break off and get results across all shards
return find_sharded(*params)
end
# Pad and Offset number attributes
params_dup = params.dup
if params.size > 1
options = params[1]
#puts 'options=' + options.inspect
#puts 'after collect=' + options.inspect
convert_condition_params(options)
per_token = options[:per_token]
consistent_read = options[:consistent_read]
if per_token || consistent_read then
op_dup = options.dup
op_dup[:limit] = per_token # simpledb uses Limit as a paging thing, not what is normal
op_dup[:consistent_read] = consistent_read
params_dup[1] = op_dup
end
end
# puts 'params2=' + params.inspect
ret = q_type == :all ? [] : nil
begin
results=find_with_metadata(*params_dup)
#puts "RESULT=" + results.inspect
write_usage(:select, domain, q_type, options, results)
#puts 'params3=' + params.inspect
SimpleRecord.stats.selects += 1
if q_type == :count
ret = results[:count]
elsif q_type == :first
ret = results[:items].first
# todo: we should store request_id and box_usage with the object maybe?
cache_results(ret)
elsif results[:single_only]
ret = results[:single]
#puts 'results[:single] ' + ret.inspect
cache_results(ret)
else
#puts 'last step items = ' + results.inspect
if results[:items] #.is_a?(Array)
cache_results(results[:items])
ret = SimpleRecord::ResultsArray.new(self, params, results, next_token)
end
end
rescue Aws::AwsError, SimpleRecord::ActiveSdb::ActiveSdbError => ex
#puts "RESCUED: " + ex.message
if (ex.message().index("NoSuchDomain") != nil)
# this is ok
# elsif (ex.message() =~ @@regex_no_id) This is RecordNotFound now
# ret = nil
else
#puts 're-raising'
raise ex
end
end
# puts 'single2=' + ret.inspect
return ret
end
def self.select(*params)
return find(*params)
end
def self.all(*args)
find(:all, *args)
end
def self.first(*args)
find(:first, *args)
end
def self.count(*args)
find(:count, *args)
end
# This gets less and less efficient the higher the page since SimpleDB has no way
# to start at a specific row. So it will iterate from the first record and pull out the specific pages.
def self.paginate(options={})
# options = args.pop
# puts 'paginate options=' + options.inspect if SimpleRecord.logging?
page = options[:page] || 1
per_page = options[:per_page] || 50
# total = options[:total_entries].to_i
options[:page] = page.to_i # makes sure it's to_i
options[:per_page] = per_page.to_i
options[:limit] = options[:page] * options[:per_page]
# puts 'paging options=' + options.inspect
fr = find(:all, options)
return fr
end
def self.convert_condition_params(options)
return if options.nil?
conditions = options[:conditions]
return if conditions.nil?
if conditions.size > 1
# all after first are values
conditions.collect! { |x|
Translations.pad_and_offset(x)
}
end
end
def self.cache_results(results)
if !cache_store.nil? && !results.nil?
if results.is_a?(Array)
# todo: cache each result
results.each do |item|
class_name = item.class.name
id = item.id
cache_key = self.cache_key(class_name, id)
#puts 'caching result at ' + cache_key + ': ' + results.inspect
cache_store.write(cache_key, item, :expires_in =>30)
end
else
class_name = results.class.name
id = results.id
cache_key = self.cache_key(class_name, id)
#puts 'caching result at ' + cache_key + ': ' + results.inspect
cache_store.write(cache_key, results, :expires_in =>30)
end
end
end
def self.cache_key(class_name, id)
return class_name + "/" + id.to_s
end
@@debug=""
def self.debug
@@debug
end
def self.sanitize_sql(*params)
return ActiveRecord::Base.sanitize_sql(*params)
end
def self.table_name
return domain
end
def changed
return @dirty.keys
end
def changed?
return @dirty.size > 0
end
def changes
ret = {}
#puts 'in CHANGES=' + @dirty.inspect
@dirty.each_pair { |key, value| ret[key] = [value, get_attribute(key)] }
return ret
end
def after_save_cleanup
@dirty = {}
end
def hash
# same as ActiveRecord
id.hash
end
end
class Activerecordtosdb_subrecord_array
def initialize(subname, referencename, referencevalue)
@subname =subname.classify
@referencename =referencename.tableize.singularize + "_id"
@referencevalue=referencevalue
end
# Performance optimization if you know the array should be empty
def init_empty
@records = []
end
def load
if @records.nil?
@records = find_all
end
return @records
end
def [](key)
return load[key]
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | true |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/attributes.rb | lib/simple_record/attributes.rb | module SimpleRecord
module Attributes
# For all things related to defining attributes.
def self.included(base)
#puts 'Callbacks included in ' + base.inspect
=begin
instance_eval <<-endofeval
def self.defined_attributes
#puts 'class defined_attributes'
@attributes ||= {}
@attributes
endendofeval
endofeval
=end
end
module ClassMethods
# Add configuration to this particular class.
# :single_clob=> true/false. If true will store all clobs as a single object in s3. Default is false.
def sr_config(options={})
get_sr_config
@sr_config.merge!(options)
end
def get_sr_config
@sr_config ||= {}
end
def defined_attributes
@attributes ||= {}
@attributes
end
def has_attributes(*args)
has_attributes2(args)
end
def has_attributes2(args, options_for_all={})
# puts 'args=' + args.inspect
# puts 'options_for_all = ' + options_for_all.inspect
args.each do |arg|
arg_options = {}
if arg.is_a?(Hash)
# then attribute may have extra options
arg_options = arg
arg = arg_options[:name].to_sym
else
arg = arg.to_sym
end
type = options_for_all[:type] || :string
attr = Attribute.new(type, arg_options)
defined_attributes[arg] = attr if defined_attributes[arg].nil?
# define reader method
arg_s = arg.to_s # to get rid of all the to_s calls
send(:define_method, arg) do
ret = get_attribute(arg)
return ret
end
# define writer method
send(:define_method, arg_s+"=") do |value|
set(arg, value)
end
define_dirty_methods(arg_s)
end
end
def define_dirty_methods(arg_s)
# Now for dirty methods: http://api.rubyonrails.org/classes/ActiveRecord/Dirty.html
# define changed? method
send(:define_method, arg_s + "_changed?") do
@dirty.has_key?(sdb_att_name(arg_s))
end
# define change method
send(:define_method, arg_s + "_change") do
old_val = @dirty[sdb_att_name(arg_s)]
[old_val, get_attribute(arg_s)]
end
# define was method
send(:define_method, arg_s + "_was") do
old_val = @dirty[sdb_att_name(arg_s)]
old_val
end
end
def has_strings(*args)
has_attributes(*args)
end
def has_ints(*args)
has_attributes(*args)
are_ints(*args)
end
def has_floats(*args)
has_attributes(*args)
are_floats(*args)
end
def has_dates(*args)
has_attributes(*args)
are_dates(*args)
end
def has_booleans(*args)
has_attributes(*args)
are_booleans(*args)
end
def are_ints(*args)
# puts 'calling are_ints: ' + args.inspect
args.each do |arg|
defined_attributes[arg.to_sym].type = :int
end
end
def are_floats(*args)
# puts 'calling are_ints: ' + args.inspect
args.each do |arg|
defined_attributes[arg.to_sym].type = :float
end
end
def are_dates(*args)
args.each do |arg|
defined_attributes[arg.to_sym].type = :date
end
end
def are_booleans(*args)
args.each do |arg|
defined_attributes[arg.to_sym].type = :boolean
end
end
def has_clobs(*args)
has_attributes2(args, :type=>:clob)
end
def virtuals
@virtuals ||= []
@virtuals
end
def has_virtuals(*args)
virtuals.concat(args)
args.each do |arg|
#we just create the accessor functions here, the actual instance variable is created during initialize
attr_accessor(arg)
end
end
# One belongs_to association per call. Call multiple times if there are more than one.
#
# This method will also create an {association)_id method that will return the ID of the foreign object
# without actually materializing it.
#
# options:
# :class_name=>"User" - to change the default class to use
def belongs_to(association_id, options = {})
arg = association_id
arg_s = arg.to_s
arg_id = arg.to_s + '_id'
attribute = Attribute.new(:belongs_to, options)
defined_attributes[arg] = attribute
# todo: should also handle foreign_key http://74.125.95.132/search?q=cache:KqLkxuXiBBQJ:wiki.rubyonrails.org/rails/show/belongs_to+rails+belongs_to&hl=en&ct=clnk&cd=1&gl=us
# puts "arg_id=#{arg}_id"
# puts "is defined? " + eval("(defined? #{arg}_id)").to_s
# puts 'atts=' + @attributes.inspect
# Define reader method
send(:define_method, arg) do
return get_attribute(arg)
end
# Define writer method
send(:define_method, arg.to_s + "=") do |value|
set(arg, value)
end
# Define ID reader method for reading the associated objects id without getting the entire object
send(:define_method, arg_id) do
get_attribute_sdb(arg_s)
end
# Define writer method for setting the _id directly without the associated object
send(:define_method, arg_id + "=") do |value|
# rb_att_name = arg_s # n2 = name.to_s[0, name.length-3]
set(arg_id, value)
# if value.nil?
# self[arg_id] = nil unless self[arg_id].nil? # if it went from something to nil, then we have to remember and remove attribute on save
# else
# self[arg_id] = value
# end
end
send(:define_method, "create_"+arg.to_s) do |*params|
newsubrecord=eval(arg.to_s.classify).new(*params)
newsubrecord.save
arg_id = arg.to_s + '_id'
self[arg_id]=newsubrecord.id
end
define_dirty_methods(arg_s)
end
# allows foreign key through class_name
# i.e. options[:class_name] = 'User'
def has_many(association_id, options = {})
send(:define_method, association_id) do
return eval(%{Activerecordtosdb_subrecord_array.new('#{options[:class_name] ? options[:class_name] : association_id}', '#{options[:class_name] ? association_id.to_s : self.class.name}', id)})
end
end
def has_many(association_id, options = {})
send(:define_method, association_id) do
return eval(%{Activerecordtosdb_subrecord_array.new('#{options[:class_name] ? options[:class_name] : association_id}', '#{options[:class_name] ? association_id.to_s : self.class.name}', id)}).first
end
end
end
def handle_virtuals(attrs)
#puts 'handle_virtuals'
self.class.virtuals.each do |virtual|
# puts 'virtual=' + virtual.inspect
#we first copy the information for the virtual to an instance variable of the same name
send("#{virtual}=", attrs[virtual])
#eval("@#{virtual}=attrs['#{virtual}']")
#and then remove the parameter before it is passed to initialize, so that it is NOT sent to SimpleDB
attrs.delete(virtual)
#eval("attrs.delete('#{virtual}')")
end
end
def set(name, value, dirtify=true)
# puts "SET #{name}=#{value.inspect}" if SimpleRecord.logging?
# puts "self=" + self.inspect
attname = name.to_s # default attname
name = name.to_sym
att_meta = get_att_meta(name)
store_rb_val = false
if att_meta.nil?
# check if it ends with id and see if att_meta is there
ends_with = name.to_s[-3, 3]
if ends_with == "_id"
# puts 'ends with id'
n2 = name.to_s[0, name.length-3]
# puts 'n2=' + n2
att_meta = defined_attributes_local[n2.to_sym]
# puts 'defined_attributes_local=' + defined_attributes_local.inspect
attname = name.to_s
attvalue = value
name = n2.to_sym
end
return if att_meta.nil?
else
if att_meta.type == :belongs_to
ends_with = name.to_s[-3, 3]
if ends_with == "_id"
att_name = name.to_s
attvalue = value
else
attname = name.to_s + '_id'
attvalue = value.nil? ? nil : value.id
store_rb_val = true
end
elsif att_meta.type == :clob
make_dirty(name, value) if dirtify
@lobs[name] = value
return
else
attname = name.to_s
attvalue = att_meta.init_value(value)
# attvalue = value
#puts 'converted ' + value.inspect + ' to ' + attvalue.inspect
end
end
attvalue = strip_array(attvalue)
make_dirty(name, attvalue) if dirtify
# puts "ARG=#{attname.to_s} setting to #{attvalue}"
sdb_val = ruby_to_sdb(name, attvalue)
# puts "sdb_val=" + sdb_val.to_s
@attributes[attname] = sdb_val
# attvalue = wrap_if_required(name, attvalue, sdb_val)
# puts 'attvalue2=' + attvalue.to_s
if store_rb_val
@attributes_rb[name.to_s] = value
else
@attributes_rb.delete(name.to_s)
end
end
def set_attribute_sdb(name, val)
@attributes[sdb_att_name(name)] = val
end
def get_attribute_sdb(name)
name = name.to_sym
ret = strip_array(@attributes[sdb_att_name(name)])
return ret
end
# Since SimpleDB supports multiple attributes per value, the values are an array.
# This method will return the value unwrapped if it's the only, otherwise it will return the array.
def get_attribute(name)
# puts "get_attribute #{name}"
# Check if this arg is already converted
name_s = name.to_s
name = name.to_sym
att_meta = get_att_meta(name)
# puts "att_meta for #{name}: " + att_meta.inspect
if att_meta && att_meta.type == :clob
ret = @lobs[name]
# puts 'get_attribute clob ' + ret.inspect
if ret
if ret.is_a? RemoteNil
return nil
else
return ret
end
end
# get it from s3
unless new_record?
if self.class.get_sr_config[:single_clob]
begin
single_clob = s3_bucket(false, :s3_bucket=>:new).get(single_clob_id)
single_clob = JSON.parse(single_clob)
# puts "single_clob=" + single_clob.inspect
single_clob.each_pair do |name2, val|
@lobs[name2.to_sym] = val
end
ret = @lobs[name]
SimpleRecord.stats.s3_gets += 1
rescue Aws::AwsError => ex
if ex.include?(/NoSuchKey/) || ex.include?(/NoSuchBucket/)
ret = nil
else
raise ex
end
end
else
begin
ret = s3_bucket.get(s3_lob_id(name))
# puts 'got from s3 ' + ret.inspect
SimpleRecord.stats.s3_gets += 1
rescue Aws::AwsError => ex
if ex.include?(/NoSuchKey/) || ex.include?(/NoSuchBucket/)
ret = nil
else
raise ex
end
end
end
if ret.nil?
ret = RemoteNil.new
end
end
@lobs[name] = ret
return nil if ret.is_a? RemoteNil
return ret
else
@attributes_rb = {} unless @attributes_rb # was getting errors after upgrade.
ret = @attributes_rb[name_s] # instance_variable_get(instance_var)
return ret unless ret.nil?
return nil if ret.is_a? RemoteNil
ret = get_attribute_sdb(name)
# p ret
ret = sdb_to_ruby(name, ret)
# p ret
@attributes_rb[name_s] = ret
return ret
end
end
private
def set_attributes(atts)
atts.each_pair do |k, v|
set(k, v)
end
end
# Holds information about an attribute
class Attribute
attr_accessor :type, :options
def initialize(type, options=nil)
@type = type
@options = options
end
def init_value(value)
return value if value.nil?
ret = value
case self.type
when :int
if value.is_a? Array
ret = value.collect { |x| x.to_i }
else
ret = value.to_i
end
end
ret
end
end
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/password.rb | lib/simple_record/password.rb | require 'digest/sha2'
# Thanks to: http://www.zacharyfox.com/blog/ruby-on-rails/password-hashing
module SimpleRecord
# This module contains functions for hashing and storing passwords
module Password
# Generates a new salt and rehashes the password
def Password.create_hash(password)
salt = self.salt
hash = self.hash(password, salt)
self.store(hash, salt)
end
# Checks the password against the stored password
def Password.check(password, store)
hash = self.get_hash(store)
salt = self.get_salt(store)
if self.hash(password, salt) == hash
true
else
false
end
end
protected
# Generates a psuedo-random 64 character string
def Password.salt
salt = ''
64.times { salt << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
salt
end
# Generates a 128 character hash
def Password.hash(password, salt)
Digest::SHA512.hexdigest("#{password}:#{salt}")
end
# Mixes the hash and salt together for storage
def Password.store(hash, salt)
hash + salt
end
# Gets the hash from a stored password
def Password.get_hash(store)
store[0..127]
end
# Gets the salt from a stored password
def Password.get_salt(store)
store[128..192]
end
end
end | ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/errors.rb | lib/simple_record/errors.rb | module SimpleRecord
class SimpleRecordError < StandardError
end
class RecordNotSaved < SimpleRecordError
attr_accessor :record
def initialize(record=nil)
@record = record
super("Validation failed: #{@record.errors.full_messages.join(", ")}")
end
end
class RecordNotFound < SimpleRecordError
end
class Error
attr_accessor :base, :attribute, :type, :message, :options
def initialize(base, attribute, message, options = {})
self.base = base
self.attribute = attribute
self.message = message
end
def message
# When type is a string, it means that we do not have to do a lookup, because
# the user already sent the "final" message.
generate_message
end
def full_message
attribute.to_s == 'base' ? message : generate_full_message()
end
alias :to_s :message
def generate_message(options = {})
@message
end
def generate_full_message(options = {})
"#{attribute.to_s} #{message}"
end
end
class SimpleRecord_errors
attr_reader :errors
def initialize(*params)
super(*params)
@errors={}
end
def add_to_base(msg)
add(:base, msg)
end
def add(attribute, message, options = {})
# options param note used; just for drop in compatibility with ActiveRecord
error, message = message, nil if message.is_a?(Error)
@errors[attribute.to_s] ||= []
@errors[attribute.to_s] << (error || Error.new(@base, attribute, message, options))
end
def length
return @errors.length
end
alias count length
alias size length
def full_messages
@errors.values.inject([]) do |full_messages, errors|
full_messages + errors.map { |error| error.full_message }
end
end
def clear
@errors.clear
end
def empty?
@errors.empty?
end
def on(attribute)
attribute = attribute.to_s
return nil unless @errors.has_key?(attribute)
errors = @errors[attribute].map(&:to_s)
errors.size == 1 ? errors.first : errors
end
alias :[] :on
def on_base
on(:base)
end
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/translations.rb | lib/simple_record/translations.rb | # This module defines all the methods that perform data translations for storage and retrieval.
module SimpleRecord
module Translations
@@offset = 9223372036854775808
@@padding = 20
@@date_format = "%Y-%m-%dT%H:%M:%S";
def ruby_to_string_val(att_meta, value)
if att_meta.type == :int
ret = Translations.pad_and_offset(value, att_meta)
elsif att_meta.type == :date
ret = Translations.pad_and_offset(value, att_meta)
else
ret = value.to_s
end
ret
end
# Time to second precision
def ruby_to_sdb(name, value)
return nil if value.nil?
name = name.to_s
# puts "Converting #{name} to sdb value=#{value}"
# puts "atts_local=" + defined_attributes_local.inspect
att_meta = get_att_meta(name)
if value.is_a? Array
ret = value.collect { |x| ruby_to_string_val(att_meta, x) }
else
ret = ruby_to_string_val(att_meta, value)
end
unless value.blank?
if att_meta.options
if att_meta.options[:encrypted]
# puts "ENCRYPTING #{name} value #{value}"
ret = Translations.encrypt(ret, att_meta.options[:encrypted])
# puts 'encrypted value=' + ret.to_s
end
if att_meta.options[:hashed]
# puts "hashing #{name}"
ret = Translations.pass_hash(ret)
# puts "hashed value=" + ret.inspect
end
end
end
return ret
end
# Convert value from SimpleDB String version to real ruby value.
def sdb_to_ruby(name, value)
# puts 'sdb_to_ruby arg=' + name.inspect + ' - ' + name.class.name + ' - value=' + value.to_s
return nil if value.nil?
att_meta = get_att_meta(name)
if att_meta.options
if att_meta.options[:encrypted]
value = Translations.decrypt(value, att_meta.options[:encrypted])
end
if att_meta.options[:hashed]
return PasswordHashed.new(value)
end
end
if !has_id_on_end(name) && att_meta.type == :belongs_to
class_name = att_meta.options[:class_name] || name.to_s[0...1].capitalize + name.to_s[1...name.to_s.length]
# Camelize classnames with underscores (ie my_model.rb --> MyModel)
class_name = class_name.camelize
# puts "attr=" + @attributes[arg_id].inspect
# puts 'val=' + @attributes[arg_id][0].inspect unless @attributes[arg_id].nil?
ret = nil
arg_id = name.to_s + '_id'
arg_id_val = send("#{arg_id}")
if arg_id_val
if !cache_store.nil?
# arg_id_val = @attributes[arg_id][0]
cache_key = self.class.cache_key(class_name, arg_id_val)
# puts 'cache_key=' + cache_key
ret = cache_store.read(cache_key)
# puts 'belongs_to incache=' + ret.inspect
end
if ret.nil?
to_eval = "#{class_name}.find('#{arg_id_val}')"
# puts 'to eval=' + to_eval
begin
ret = eval(to_eval) # (defined? #{arg}_id)
rescue SimpleRecord::ActiveSdb::ActiveSdbError => ex
if ex.message.include? "Couldn't find"
ret = RemoteNil.new
else
raise ex
end
end
end
end
value = ret
else
if value.is_a? Array
value = value.collect { |x| string_val_to_ruby(att_meta, x) }
else
value = string_val_to_ruby(att_meta, value)
end
end
value
end
def string_val_to_ruby(att_meta, value)
if att_meta.type == :int
value = Translations.un_offset_int(value)
elsif att_meta.type == :date
value = to_date(value)
elsif att_meta.type == :boolean
value = to_bool(value)
elsif att_meta.type == :float
value = Float(value)
end
value
end
def self.pad_and_offset(x, att_meta=nil) # Change name to something more appropriate like ruby_to_sdb
# todo: add Float, etc
# puts 'padding=' + x.class.name + " -- " + x.inspect
if x.kind_of? Integer
x += @@offset
x_str = x.to_s
# pad
x_str = '0' + x_str while x_str.size < 20
return x_str
elsif x.respond_to?(:iso8601)
# puts x.class.name + ' responds to iso8601'
#
# There is an issue here where Time.iso8601 on an incomparable value to DateTime.iso8601.
# Amazon suggests: 2008-02-10T16:52:01.000-05:00
# "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
#
if x.is_a? DateTime
x_str = x.getutc.strftime(@@date_format)
elsif x.is_a? Time
x_str = x.getutc.strftime(@@date_format)
elsif x.is_a? Date
x_str = x.strftime(@@date_format)
end
return x_str
elsif x.is_a? Float
from_float(x)
else
return x
end
end
# This conversion to a string is based on: http://tools.ietf.org/html/draft-wood-ldapext-float-00
# Java code sample is here: http://code.google.com/p/typica/source/browse/trunk/java/com/xerox/amazonws/simpledb/DataUtils.java
def self.from_float(x)
return x
# if x == 0.0
# return "3 000 0.0000000000000000"
# end
end
def wrap_if_required(arg, value, sdb_val)
return nil if value.nil?
att_meta = defined_attributes_local[arg.to_sym]
if att_meta && att_meta.options
if att_meta.options[:hashed]
# puts 'wrapping ' + arg_s
return PasswordHashed.new(sdb_val)
end
end
value
end
def to_date(x)
if x.is_a?(String)
DateTime.parse(x)
else
x
end
end
def to_bool(x)
if x.is_a?(String)
x == "true" || x == "1"
else
x
end
end
def self.un_offset_int(x)
if x.is_a?(String)
x2 = x.to_i
# puts 'to_i=' + x2.to_s
x2 -= @@offset
# puts 'after subtracting offset='+ x2.to_s
x2
else
x
end
end
def unpad(i, attributes)
if !attributes[i].nil?
# puts 'before=' + self[i].inspect
attributes[i].collect! { |x|
un_offset_int(x)
}
end
end
def unpad_self
defined_attributes_local.each_pair do |name, att_meta|
if att_meta.type == :int
unpad(name, @attributes)
end
end
end
def self.encrypt(value, key=nil)
key = key || get_encryption_key()
raise SimpleRecordError, "Encryption key must be defined on the attribute." if key.nil?
encrypted_value = SimpleRecord::Encryptor.encrypt(:value => value, :key => key)
encoded_value = Base64.encode64(encrypted_value)
encoded_value
end
def self.decrypt(value, key=nil)
# puts "decrypt orig value #{value} "
unencoded_value = Base64.decode64(value)
raise SimpleRecordError, "Encryption key must be defined on the attribute." if key.nil?
key = key || get_encryption_key()
# puts "decrypting #{unencoded_value} "
decrypted_value = SimpleRecord::Encryptor.decrypt(:value => unencoded_value, :key => key)
# "decrypted #{unencoded_value} to #{decrypted_value}"
decrypted_value
end
def pad_and_offset_ints_to_sdb()
# defined_attributes_local.each_pair do |name, att_meta|
# if att_meta.type == :int && !self[name.to_s].nil?
# arr = @attributes[name.to_s]
# arr.collect!{ |x| self.class.pad_and_offset(x) }
# @attributes[name.to_s] = arr
# end
# end
end
def convert_dates_to_sdb()
# defined_attributes_local.each_pair do |name, att_meta|
# puts 'int encoding: ' + i.to_s
# end
end
def self.pass_hash(value)
hashed = Password::create_hash(value)
encoded_value = Base64.encode64(hashed)
encoded_value
end
def self.pass_hash_check(value, value_to_compare)
unencoded_value = Base64.decode64(value)
return Password::check(value_to_compare, unencoded_value)
end
end
class PasswordHashed
def initialize(value)
@value = value
end
def hashed_value
@value
end
# This allows you to compare an unhashed string to the hashed one.
def ==(val)
if val.is_a?(PasswordHashed)
return val.hashed_value == self.hashed_value
end
return Translations.pass_hash_check(@value, val)
end
def to_s
@value
end
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/logging.rb | lib/simple_record/logging.rb | module SimpleRecord
require 'csv'
module Logging
module ClassMethods
def write_usage(type, domain, q_type, params, results)
#puts 'params=' + params.inspect
#puts 'logging_options=' + SimpleRecord.usage_logging_options.inspect
if SimpleRecord.usage_logging_options
type_options = SimpleRecord.usage_logging_options[type]
if type_options
file = type_options[:file]
if file.nil?
file = File.open(type_options[:filename], File.exists?(type_options[:filename]) ? "a" : "w")
puts file.path
type_options[:file] = file
end
conditions = params[:conditions][0] if params[:conditions]
line = usage_line(type_options[:format], [type, domain, q_type, conditions, params[:order]], results[:request_id], results[:box_usage])
file.puts line
type_options[:lines] = type_options[:lines] ? type_options[:lines] + 1 : 1
#puts 'lines=' + type_options[:lines].to_s
if type_options[:lines] % type_options[:lines_between_flushes] == 0
#puts "flushing to file..."
file.flush
# sleep 20
end
# puts 'line=' + line
end
end
end
def usage_line(format, query_data, request_id, box_usage)
if format == :csv
line_data = []
line_data << Time.now.iso8601
query_data.each do |r|
line_data << r.to_s
end
line_data << request_id
line_data << box_usage
return CSV.generate_line(line_data)
end
end
end
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/sharding.rb | lib/simple_record/sharding.rb | require 'concur'
module SimpleRecord
module Sharding
def self.included(base)
# base.extend ClassMethods
end
module ClassMethods
def shard(options=nil)
@sharding_options = options
end
def sharding_options
@sharding_options
end
def is_sharded?
@sharding_options
end
def find_sharded(*params)
puts 'find_sharded ' + params.inspect
options = params.size > 1 ? params[1] : {}
if options[:shard] # User specified shard.
shard = options[:shard]
domains = shard.is_a?(Array) ? (shard.collect { |x| prefix_shard_name(x) }) : [prefix_shard_name(shard)]
else
domains = sharded_domains
end
# puts "sharded_domains=" + domains.inspect
single = false
by_ids = false
case params.first
when nil then
raise "Invalid parameters passed to find: nil."
when :all, :first, :count
# nada
else # single id
by_ids = true
unless params.first.is_a?(Array)
single = true
end
end
puts 'single? ' + single.inspect
puts 'by_ids? ' + by_ids.inspect
# todo: should have a global executor
executor = options[:concurrent] ? Concur::Executor.new_multi_threaded_executor : Concur::Executor.new_single_threaded_executor
results = nil
if by_ids
results = []
else
results = ShardedResults.new(params)
end
futures = []
domains.each do |d|
p2 = params.dup
op2 = options.dup
op2[:from] = d
op2[:shard_find] = true
p2[1] = op2
futures << executor.execute do
puts 'executing=' + p2.inspect
# todo: catch RecordNotFound errors and throw later if there really isn't any record found.
rs = find(*p2)
puts 'rs=' + rs.inspect
rs
end
end
futures.each do |f|
puts 'getting future ' + f.inspect
if params.first == :first || single
puts 'f.get=' + f.get.inspect
return f.get if f.get
elsif by_ids
results << f.get if f.get
else
results.add_results f.get
end
end
executor.shutdown
# puts 'results=' + results.inspect
if params.first == :first || single
# Then we found nothing by this point so return nil
return nil
elsif params.first == :count
return results.sum_count
end
results
end
def shards
send(sharding_options[:shards])
end
def prefix_shard_name(s)
"#{domain}_#{s}"
end
def sharded_domains
sharded_domains = []
shard_names = shards
shard_names.each do |s|
sharded_domains << prefix_shard_name(s)
end
sharded_domains
end
end
def sharded_domain
# puts 'getting sharded_domain'
options = self.class.sharding_options
# val = self.send(options[:on])
# puts "val=" + val.inspect
# shards = options[:shards] # is user passed in static array of shards
# if options[:shards].is_a?(Symbol)
# shards = self.send(shards)
# end
sharded_domain = "#{domain}_#{self.send(options[:map])}"
# puts "sharded_domain=" + sharded_domain.inspect
sharded_domain
end
class ShardedResults
include Enumerable
def initialize(params)
@params = params
@options = params.size > 1 ? params[1] : {}
@results_arrays = []
end
def add_results(rs)
# puts 'adding results=' + rs.inspect
@results_arrays << rs
end
# only used for count queries
def sum_count
x = 0
@results_arrays.each do |rs|
x += rs if rs
end
x
end
def <<(val)
raise "Not supported."
end
def element_at(index)
@results_arrays.each do |rs|
if rs.size > index
return rs[index]
end
index -= rs.size
end
end
def [](*i)
if i.size == 1
# puts '[] i=' + i.to_s
index = i[0]
return element_at(index)
else
offset = i[0]
rows = i[1]
ret = []
x = offset
while x < (offset+rows)
ret << element_at(x)
x+=1
end
ret
end
end
def first
@results_arrays.first.first
end
def last
@results_arrays.last.last
end
def empty?
@results_arrays.each do |rs|
return false if !rs.empty?
end
true
end
def include?(obj)
@results_arrays.each do |rs|
x = rs.include?(obj)
return true if x
end
false
end
def size
return @size if @size
s = 0
@results_arrays.each do |rs|
# puts 'rs=' + rs.inspect
# puts 'rs.size=' + rs.size.inspect
s += rs.size
end
@size = s
s
end
def length
return size
end
def each(&blk)
i = 0
@results_arrays.each do |rs|
rs.each(&blk)
i+=1
end
end
# for will_paginate support
def total_pages
# puts 'total_pages'
# puts @params[1][:per_page].to_s
return 1 if @params[1][:per_page].nil?
ret = (size / @params[1][:per_page].to_f).ceil
#puts 'ret=' + ret.to_s
ret
end
def current_page
return query_options[:page] || 1
end
def query_options
return @options
end
def total_entries
return size
end
# Helper method that is true when someone tries to fetch a page with a
# larger number than the last page. Can be used in combination with flashes
# and redirecting.
def out_of_bounds?
current_page > total_pages
end
# Current offset of the paginated collection. If we're on the first page,
# it is always 0. If we're on the 2nd page and there are 30 entries per page,
# the offset is 30. This property is useful if you want to render ordinals
# side by side with records in the view: simply start with offset + 1.
def offset
(current_page - 1) * per_page
end
# current_page - 1 or nil if there is no previous page
def previous_page
current_page > 1 ? (current_page - 1) : nil
end
# current_page + 1 or nil if there is no next page
def next_page
current_page < total_pages ? (current_page + 1) : nil
end
def delete(item)
raise "Not supported"
end
def delete_at(index)
raise "Not supported"
end
end
# Some hashing algorithms
module Hashing
def self.sdbm_hash(str, len=str.length)
# puts 'sdbm_hash ' + str.inspect
hash = 0
len.times { |i|
c = str[i]
# puts "c=" + c.class.name + "--" + c.inspect + " -- " + c.ord.inspect
c = c.ord
hash = c + (hash << 6) + (hash << 16) - hash
}
# puts "hash=" + hash.inspect
return hash
end
end
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/stats.rb | lib/simple_record/stats.rb | module SimpleRecord
class Stats
attr_accessor :selects, :saves, :deletes, :s3_puts, :s3_gets, :s3_deletes
def initialize
@selects = 0
@saves = 0
@deletes = 0
@s3_puts = 0
@s3_gets = 0
@s3_deletes = 0
end
def clear
self.selects = 0
self.saves = 0
self.deletes = 0
self.s3_puts = 0
self.s3_gets = 0
self.s3_deletes = 0
end
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/callbacks.rb | lib/simple_record/callbacks.rb | module SimpleRecord
# For Rails3 support
module Callbacks3
# def destroy #:nodoc:
# _run_destroy_callbacks { super }
# end
#
# private
#
# def create_or_update #:nodoc:
# puts '3 create_or_update'
# _run_save_callbacks { super }
# end
#
# def create #:nodoc:
# puts '3 create'
# _run_create_callbacks { super }
# end
#
# def update(*) #:nodoc:
# puts '3 update'
# _run_update_callbacks { super }
# end
end
module Callbacks
#this bit of code creates a "run_blank" function for everything value in the @@callbacks array.
#this function can then be inserted in the appropriate place in the save, new, destroy, etc overrides
#basically, this is how we recreate the callback functions
@@callbacks=["before_validation", "before_validation_on_create", "before_validation_on_update",
"after_validation", "after_validation_on_create", "after_validation_on_update",
"before_save", "before_create", "before_update", "before_destroy",
"after_create", "after_update", "after_save",
"after_destroy"]
def self.included(base)
#puts 'Callbacks included in ' + base.inspect
# puts "setup callbacks #{base.inspect}"
base.instance_eval <<-endofeval
def callbacks
@callbacks ||= {}
@callbacks
end
endofeval
@@callbacks.each do |callback|
base.class_eval <<-endofeval
def run_#{callback}
# puts 'CLASS CALLBACKS for ' + self.inspect + ' = ' + self.class.callbacks.inspect
return true if self.class.callbacks.nil?
cnames = self.class.callbacks['#{callback}']
cnames = [] if cnames.nil?
# cnames += super.class.callbacks['#{callback}'] unless super.class.callbacks.nil?
# puts 'cnames for #{callback} = ' + cnames.inspect
return true if cnames.nil?
cnames.each { |name|
#puts 'run_ #{name}'
if eval(name) == false # nil should be an ok return, only looking for false
return false
end
}
# super.run_#{callback}
return true
end
endofeval
#this bit of code creates a "run_blank" function for everything value in the @@callbacks array.
#this function can then be inserted in the appropriate place in the save, new, destroy, etc overrides
#basically, this is how we recreate the callback functions
base.instance_eval <<-endofeval
# puts 'defining callback=' + callback + ' for ' + self.inspect
#we first have to make an initialized array for each of the callbacks, to prevent problems if they are not called
def #{callback}(*args)
# puts 'callback called in ' + self.inspect + ' with ' + args.inspect
#make_dirty(arg_s, value)
#self[arg.to_s]=value
#puts 'value in callback #{callback}=' + value.to_s
args.each do |arg|
cnames = callbacks['#{callback}']
#puts '\tcnames1=' + cnames.inspect + ' for class ' + self.inspect
cnames = [] if cnames.nil?
cnames << arg.to_s if cnames.index(arg.to_s).nil?
#puts '\tcnames2=' + cnames.inspect
callbacks['#{callback}'] = cnames
end
end
endofeval
end
end
def before_destroy()
end
def after_destroy()
end
def self.setup_callbacks(base)
end
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/validations.rb | lib/simple_record/validations.rb | # This is actually still used to continue support for this.
# ActiveModel does not work the same way so need to continue using this, will change name.
module SimpleRecord
module Validations
# if defined?(:valid?) # from ActiveModel
# alias_method :am_valid?, :valid?
# end
def self.included(base)
# puts 'Validations included ' + base.inspect
# if defined?(ActiveModel)
# base.class_eval do
# alias_method :am_valid?, :valid?
# end
# end
end
module ClassMethods
def uniques
@uniques ||= {}
@uniques
end
# only supporting single attr name right now
def validates_uniqueness_of(attr)
uniques[attr] = true
end
end
def valid?
# puts 'in rails2 valid?'
errors.clear
if respond_to?(:am_valid?)
# And now ActiveModel validations too
am_valid?
end
# run_callbacks(:validate)
validate
validate_uniques
if new_record?
# run_callbacks(:validate_on_create)
validate_on_create
else
# run_callbacks(:validate_on_update)
validate_on_update
end
errors.empty?
end
def invalid?
!valid?
end
def read_attribute_for_validation(key)
@attributes[key.to_s]
end
def validate_uniques
puts 'uniques=' + self.class.uniques.inspect
self.class.uniques.each_pair do |k, v|
val = self.send(k)
puts 'val=' + val.inspect
if val
conditions = new_record? ? ["#{k}=?", val] : ["#{k}=? AND id != ?", val, self.id]
ret = self.class.find(:first, :conditions=>conditions)
puts 'ret=' + ret.inspect
if ret
errors.add(k, "must be unique.")
end
end
end
end
def validate
true
end
def validate_on_create
true
end
def validate_on_update
true
end
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/json.rb | lib/simple_record/json.rb | module SimpleRecord
module Json
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def json_create(object)
obj = new
for key, value in object
next if key == 'json_class'
if key == 'id'
obj.id = value
next
end
obj.set key, value
end
obj
end
def from_json(json_string)
return JSON.parse(json_string)
end
end
def as_json(options={})
puts 'SimpleRecord as_json called with options: ' + options.inspect
result = {
'id' => self.id
}
result['json_class'] = self.class.name unless options && options[:exclude_json_class]
defined_attributes_local.each_pair do |name, val|
# puts name.to_s + "=" + val.inspect
if val.type == :belongs_to
result[name.to_s + "_id"] = get_attribute_sdb(name)
else
result[name] = get_attribute(name)
end
# puts 'result[name]=' + result[name].inspect
end
# ret = result.as_json(options)
# puts 'ret=' + ret.inspect
# return ret
result
end
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/encryptor.rb | lib/simple_record/encryptor.rb | require 'openssl'
# Thanks to http://github.com/shuber/encryptor
module SimpleRecord
module Encryptor
# The default options to use when calling the <tt>encrypt</tt> and <tt>decrypt</tt> methods
#
# Defaults to { :algorithm => 'aes-256-cbc' }
#
# Run 'openssl list-cipher-commands' in your terminal to view a list all cipher algorithms that are supported on your platform
class << self; attr_accessor :default_options; end
self.default_options = { :algorithm => 'aes-256-cbc' }
# Encrypts a <tt>:value</tt> with a specified <tt>:key</tt>
#
# Optionally accepts <tt>:iv</tt> and <tt>:algorithm</tt> options
#
# Example
#
# encrypted_value = Huberry::Encryptor.encrypt(:value => 'some string to encrypt', :key => 'some secret key')
def self.encrypt(options)
crypt :encrypt, options
end
# Decrypts a <tt>:value</tt> with a specified <tt>:key</tt>
#
# Optionally accepts <tt>:iv</tt> and <tt>:algorithm</tt> options
#
# Example
#
# decrypted_value = Huberry::Encryptor.decrypt(:value => 'some encrypted string', :key => 'some secret key')
def self.decrypt(options)
crypt :decrypt, options
end
protected
def self.crypt(cipher_method, options = {})
options = default_options.merge(options)
cipher = OpenSSL::Cipher::Cipher.new(options[:algorithm])
cipher.send(cipher_method)
secret_key = Digest::SHA512.hexdigest(options[:key])
if options[:iv]
cipher.key = secret_key
cipher.iv = options[:iv]
else
cipher.pkcs5_keyivgen(secret_key)
end
result = cipher.update(options[:value])
result << cipher.final
end
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/active_sdb.rb | lib/simple_record/active_sdb.rb | #
# Copyright (c) 2008 RightScale Inc
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
require 'uuidtools'
module SimpleRecord
# = Aws::ActiveSdb -- RightScale SDB interface (alpha release)
# The Aws::ActiveSdb class provides a complete interface to Amazon's Simple
# Database Service.
#
# ActiveSdb is in alpha and does not load by default with the rest of Aws. You must use an additional require statement to load the ActiveSdb class. For example:
#
# require 'right_aws'
# require 'sdb/active_sdb'
#
# Additionally, the ActiveSdb class requires the 'uuidtools' gem; this gem is not normally required by Aws and is not installed as a
# dependency of Aws.
#
# Simple ActiveSdb usage example:
#
# class Client < Aws::ActiveSdb::Base
# end
#
# # connect to SDB
# Aws::ActiveSdb.establish_connection
#
# # create domain
# Client.create_domain
#
# # create initial DB
# Client.create 'name' => 'Bush', 'country' => 'USA', 'gender' => 'male', 'expiration' => '2009', 'post' => 'president'
# Client.create 'name' => 'Putin', 'country' => 'Russia', 'gender' => 'male', 'expiration' => '2008', 'post' => 'president'
# Client.create 'name' => 'Medvedev', 'country' => 'Russia', 'gender' => 'male', 'expiration' => '2012', 'post' => 'president'
# Client.create 'name' => 'Mary', 'country' => 'USA', 'gender' => 'female', 'hobby' => ['patchwork', 'bundle jumping']
# Client.create 'name' => 'Mary', 'country' => 'Russia', 'gender' => 'female', 'hobby' => ['flowers', 'cats', 'cooking']
# sandy_id = Client.create('name' => 'Sandy', 'country' => 'Russia', 'gender' => 'female', 'hobby' => ['flowers', 'cats', 'cooking']).id
#
# # find all Bushes in USA
# Client.find(:all, :conditions => ["['name'=?] intersection ['country'=?]",'Bush','USA']).each do |client|
# client.reload
# puts client.attributes.inspect
# end
#
# # find all Maries through the world
# Client.find_all_by_name_and_gender('Mary','female').each do |mary|
# mary.reload
# puts "#{mary[:name]}, gender: #{mary[:gender]}, hobbies: #{mary[:hobby].join(',')}"
# end
#
# # find new russian president
# medvedev = Client.find_by_post_and_country_and_expiration('president','Russia','2012')
# if medvedev
# medvedev.reload
# medvedev.save_attributes('age' => '42', 'hobby' => 'Gazprom')
# end
#
# # retire old president
# Client.find_by_name('Putin').delete
#
# # Sandy disappointed in 'cooking' and decided to hide her 'gender' and 'country' ()
# sandy = Client.find(sandy_id)
# sandy.reload
# sandy.delete_values('hobby' => ['cooking'] )
# sandy.delete_attributes('country', 'gender')
#
# # remove domain
# Client.delete_domain
#
class ActiveSdb
module ActiveSdbConnect
def connection
@connection || raise(ActiveSdbError.new('Connection to SDB is not established'))
end
# Create a new handle to an Sdb account. All handles share the same per process or per thread
# HTTP connection to Amazon Sdb. Each handle is for a specific account.
# The +params+ are passed through as-is to Aws::SdbInterface.new
# Params:
# { :server => 'sdb.amazonaws.com' # Amazon service host: 'sdb.amazonaws.com'(default)
# :port => 443 # Amazon service port: 80 or 443(default)
# :protocol => 'https' # Amazon service protocol: 'http' or 'https'(default)
# :signature_version => '2' # The signature version : '0', '1' or '2' (default)
# DEPRECATED :multi_thread => true|false # Multi-threaded (connection per each thread): true or false(default)
# :connection_mode => :default # options are :default (will use best known option, may change in the future)
# :per_request (opens and closes a connection on every request to SDB)
# :single (same as old multi_thread=>false)
# :per_thread (same as old multi_thread=>true)
# :pool (uses a connection pool with a maximum number of connections - NOT IMPLEMENTED YET)
# :logger => Logger Object # Logger instance: logs to STDOUT if omitted
# :nil_representation => 'mynil'} # interpret Ruby nil as this string value; i.e. use this string in SDB to represent Ruby nils (default is the string 'nil')
# :service_endpoint => '/' # Set this to /mdb/request.mgwsi for usage with M/DB
def establish_connection(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
@connection = Aws::SdbInterface.new(aws_access_key_id, aws_secret_access_key, params)
end
def close_connection
@connection.close_connection unless @connection.nil?
end
end
class ActiveSdbError < RuntimeError
end
class << self
include ActiveSdbConnect
# Retreive a list of domains.
#
# put Aws::ActiveSdb.domains #=> ['co-workers','family','friends','clients']
#
def domains
connection.list_domains[:domains]
end
# Create new domain.
# Raises no errors if the domain already exists.
#
# Aws::ActiveSdb.create_domain('alpha') #=> {:request_id=>"6fc652a0-0000-41d5-91f4-3ed390a3d3b2", :box_usage=>"0.0055590278"}
#
def create_domain(domain_name)
connection.create_domain(domain_name)
end
# Remove domain from SDB.
# Raises no errors if the domain does not exist.
#
# Aws::ActiveSdb.create_domain('alpha') #=> {:request_id=>"6fc652a0-0000-41c6-91f4-3ed390a3d3b2", :box_usage=>"0.0055590001"}
#
def delete_domain(domain_name)
connection.delete_domain(domain_name)
end
end
class Base
class << self
include ActiveSdbConnect
# next_token value returned by last find: is useful to continue finding
attr_accessor :next_token
# Returns a Aws::SdbInterface object
#
# class A < Aws::ActiveSdb::Base
# end
#
# class B < Aws::ActiveSdb::Base
# end
#
# class C < Aws::ActiveSdb::Base
# end
#
# Aws::ActiveSdb.establish_connection 'key_id_1', 'secret_key_1'
#
# C.establish_connection 'key_id_2', 'secret_key_2'
#
# # A and B uses the default connection, C - uses its own
# puts A.connection #=> #<Aws::SdbInterface:0xb76d6d7c>
# puts B.connection #=> #<Aws::SdbInterface:0xb76d6d7c>
# puts C.connection #=> #<Aws::SdbInterface:0xb76d6ca0>
#
def connection
@connection || ActiveSdb::connection
end
@domain = nil
# Current domain name.
#
# # if 'ActiveSupport' is not loaded then class name converted to downcase
# class Client < Aws::ActiveSdb::Base
# end
# puts Client.domain #=> 'client'
#
# # if 'ActiveSupport' is loaded then class name being tableized
# require 'activesupport'
# class Client < Aws::ActiveSdb::Base
# end
# puts Client.domain #=> 'clients'
#
# # Explicit domain name definition
# class Client < Aws::ActiveSdb::Base
# set_domain_name :foreign_clients
# end
# puts Client.domain #=> 'foreign_clients'
#
def domain
unless @domain
if defined? ActiveSupport::CoreExtensions::String::Inflections
@domain = name.tableize
else
@domain = name.downcase
end
end
@domain
end
# Change the default domain name to user defined.
#
# class Client < Aws::ActiveSdb::Base
# set_domain_name :foreign_clients
# end
#
def set_domain_name(domain)
@domain = domain.to_s
end
# Create domain at SDB.
# Raises no errors if the domain already exists.
#
# class Client < Aws::ActiveSdb::Base
# end
# Client.create_domain #=> {:request_id=>"6fc652a0-0000-41d5-91f4-3ed390a3d3b2", :box_usage=>"0.0055590278"}
#
def create_domain(dom=nil)
dom = domain if dom.nil?
puts "Creating new SimpleDB Domain: " + dom
connection.create_domain(dom)
end
# Remove domain from SDB.
# Raises no errors if the domain does not exist.
#
# class Client < Aws::ActiveSdb::Base
# end
# Client.delete_domain #=> {:request_id=>"e14d90d3-0000-4898-9995-0de28cdda270", :box_usage=>"0.0055590278"}
#
def delete_domain(dom=nil)
dom = domain if dom.nil?
puts "!!! DELETING SimpleDB Domain: " + dom
connection.delete_domain(dom)
end
#
# See select(), original find with QUERY syntax is deprecated so now find and select are synonyms.
#
def find(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
case args.first
when nil then
raise "Invalid parameters passed to find: nil."
when :all then
sql_select(options)[:items]
when :first then
sql_select(options.merge(:limit => 1))[:items].first
when :count then
res = sql_select(options.merge(:count => true))[:count]
res
else
res = select_from_ids(args, options)
return res[:single] if res[:single]
return res[:items]
end
end
#
# Same as find, but will return SimpleDB metadata like :request_id and :box_usage
#
def find_with_metadata(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
case args.first
when nil then
raise "Invalid parameters passed to find: nil."
when :all then
sql_select(options)
when :first then
sql_select(options.merge(:limit => 1))
when :count then
res = sql_select(options.merge(:count => true))
res
else
select_from_ids args, options
end
end
# Perform a SQL-like select request.
#
# Single record:
#
# Client.select(:first)
# Client.select(:first, :conditions=> [ "name=? AND wife=?", "Jon", "Sandy"])
# Client.select(:first, :conditions=> { :name=>"Jon", :wife=>"Sandy" }, :select => :girfriends)
#
# Bunch of records:
#
# Client.select(:all)
# Client.select(:all, :limit => 10)
# Client.select(:all, :conditions=> [ "name=? AND 'girlfriend'=?", "Jon", "Judy"])
# Client.select(:all, :conditions=> { :name=>"Sandy" }, :limit => 3)
#
# Records by ids:
#
# Client.select('1')
# Client.select('1234987b4583475347523948')
# Client.select('1','2','3','4', :conditions=> ["toys=?", "beer"])
#
# Find helpers: Aws::ActiveSdb::Base.select_by_... and Aws::ActiveSdb::Base.select_all_by_...
#
# Client.select_by_name('Matias Rust')
# Client.select_by_name_and_city('Putin','Moscow')
# Client.select_by_name_and_city_and_post('Medvedev','Moscow','president')
#
# Client.select_all_by_author('G.Bush jr')
# Client.select_all_by_age_and_gender_and_ethnicity('34','male','russian')
# Client.select_all_by_gender_and_country('male', 'Russia', :order => 'name')
#
# Continue listing:
#
# # initial listing
# Client.select(:all, :limit => 10)
# # continue listing
# begin
# Client.select(:all, :limit => 10, :next_token => Client.next_token)
# end while Client.next_token
#
# Sort oder:
# If :order=>'attribute' option is specified then result response (ordered by 'attribute') will contain only items where attribute is defined (is not null).
#
# Client.select(:all) # returns all records
# Client.select(:all, :order => 'gender') # returns all records ordered by gender where gender attribute exists
# Client.select(:all, :order => 'name desc') # returns all records ordered by name in desc order where name attribute exists
#
# see http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/index.html?UsingSelect.html
#
def select(*args)
find(*args)
end
def generate_id # :nodoc:
# mac address creation sometimes throws errors if mac address isn't available
UUIDTools::UUID.random_create().to_s
end
protected
def logger
SimpleRecord.logger
end
# Select
def select_from_ids(args, options) # :nodoc:
cond = []
# detect amount of records requested
bunch_of_records_requested = args.size > 1 || args.first.is_a?(Array)
# flatten ids
args = args.to_a.flatten
args.each { |id| cond << "itemName() = #{self.connection.escape(id)}" }
ids_cond = "(#{cond.join(' OR ')})"
# user defined :conditions to string (if it was defined)
options[:conditions] = build_conditions(options[:conditions])
# join ids condition and user defined conditions
options[:conditions] = options[:conditions].blank? ? ids_cond : "(#{options[:conditions]}) AND #{ids_cond}"
#puts 'options=' + options.inspect
result = sql_select(options)
#puts 'select_from_ids result=' + result.inspect
# if one record was requested then return it
unless bunch_of_records_requested
result[:single_only] = true
record = result[:items].first
# railse if nothing was found
raise SimpleRecord::RecordNotFound.new("Couldn't find #{name} with ID #{args}") unless record || is_sharded?
result[:single] = record
else
# if a bunch of records was requested then return check that we found all of them
# and return as an array
puts 'is_sharded? ' + is_sharded?.to_s
unless is_sharded? || args.size == result[:items].size
# todo: might make sense to return the array but with nil values in the slots where an item wasn't found?
id_list = args.map { |i| "'#{i}'" }.join(',')
raise SimpleRecord::RecordNotFound.new("Couldn't find all #{name} with IDs (#{id_list}) (found #{result[:items].size} results, but was looking for #{args.size})")
else
result
end
end
result
end
def sql_select(options) # :nodoc:
count = options[:count] || false
#puts 'count? ' + count.to_s
@next_token = options[:next_token]
@consistent_read = options[:consistent_read]
select_expression = build_select(options)
logger.debug 'SELECT=' + select_expression
# request items
ret = {}
if count
# we'll keep going to get full count
total_count = 0
total_box_usage = 0
query_result = self.connection.select(select_expression, options) do |result|
#puts 'result=' + result.inspect
total_count += result[:items][0]["Domain"]["Count"][0].to_i # result.delete(:items)[0]["Domain"]["Count"][0].to_i
total_box_usage += result[:box_usage].to_i
true #continue loop
end
ret[:count] = total_count
ret[:box_usage] = total_box_usage
return ret
else
query_result = self.connection.select(select_expression, options)
@next_token = query_result[:next_token]
end
# puts 'QR=' + query_result.inspect
#if count
#ret[:count] = query_result.delete(:items)[0]["Domain"]["Count"][0].to_i
#ret.merge!(query_result)
#return ret
#end
items = query_result.delete(:items).map do |hash|
id, attributes = hash.shift
new_item = self.new()
new_item.initialize_from_db(attributes.merge({'id' => id}))
new_item.mark_as_old
new_item
end
ret[:items] = items
ret.merge!(query_result)
ret
end
# select_by helpers
def select_all_by_(format_str, args, options) # :nodoc:
fields = format_str.to_s.sub(/^select_(all_)?by_/, '').split('_and_')
conditions = fields.map { |field| "#{field}=?" }.join(' AND ')
options[:conditions] = [conditions, *args]
find(:all, options)
end
def select_by_(format_str, args, options) # :nodoc:
options[:limit] = 1
select_all_by_(format_str, args, options).first
end
# Query
# Returns an array of query attributes.
# Query_expression must be a well formated SDB query string:
# query_attributes("['title' starts-with 'O\\'Reily'] intersection ['year' = '2007']") #=> ["title", "year"]
def query_attributes(query_expression) # :nodoc:
attrs = []
array = query_expression.scan(/['"](.*?[^\\])['"]/).flatten
until array.empty? do
attrs << array.shift # skip it's value
array.shift #
end
attrs
end
# Returns an array of [attribute_name, 'asc'|'desc']
def sort_options(sort_string)
sort_string[/['"]?(\w+)['"]? *(asc|desc)?/i]
[$1, ($2 || 'asc')]
end
# Perform a query request.
#
# Options
# :query_expression nil | string | array
# :max_number_of_items nil | integer
# :next_token nil | string
# :sort_option nil | string "name desc|asc"
#
def query(options) # :nodoc:
@next_token = options[:next_token]
@consistent_read = options[:consistent_read]
query_expression = build_conditions(options[:query_expression])
# add sort_options to the query_expression
if options[:sort_option]
sort_by, sort_order = sort_options(options[:sort_option])
sort_query_expression = "['#{sort_by}' starts-with '']"
sort_by_expression = " sort '#{sort_by}' #{sort_order}"
# make query_expression to be a string (it may be null)
query_expression = query_expression.to_s
# quote from Amazon:
# The sort attribute must be present in at least one of the predicates of the query expression.
if query_expression.blank?
query_expression = sort_query_expression
elsif !query_attributes(query_expression).include?(sort_by)
query_expression += " intersection #{sort_query_expression}"
end
query_expression += sort_by_expression
end
# request items
query_result = self.connection.query(domain, query_expression, options[:max_number_of_items], @next_token, @consistent_read)
@next_token = query_result[:next_token]
items = query_result[:items].map do |name|
new_item = self.new('id' => name)
new_item.mark_as_old
reload_if_exists(record) if options[:auto_load]
new_item
end
items
end
# reload a record unless it is nil
def reload_if_exists(record) # :nodoc:
record && record.reload
end
def reload_all_records(*list) # :nodoc:
list.flatten.each { |record| reload_if_exists(record) }
end
def find_every(options) # :nodoc:
records = query(:query_expression => options[:conditions],
:max_number_of_items => options[:limit],
:next_token => options[:next_token],
:sort_option => options[:sort] || options[:order],
:consistent_read => options[:consistent_read])
options[:auto_load] ? reload_all_records(records) : records
end
def find_initial(options) # :nodoc:
options[:limit] = 1
record = find_every(options).first
options[:auto_load] ? reload_all_records(record).first : record
end
def find_from_ids(args, options) # :nodoc:
cond = []
# detect amount of records requested
bunch_of_records_requested = args.size > 1 || args.first.is_a?(Array)
# flatten ids
args = args.to_a.flatten
args.each { |id| cond << "'id'=#{self.connection.escape(id)}" }
ids_cond = "[#{cond.join(' OR ')}]"
# user defined :conditions to string (if it was defined)
options[:conditions] = build_conditions(options[:conditions])
# join ids condition and user defined conditions
options[:conditions] = options[:conditions].blank? ? ids_cond : "#{options[:conditions]} intersection #{ids_cond}"
result = find_every(options)
# if one record was requested then return it
unless bunch_of_records_requested
record = result.first
# railse if nothing was found
raise ActiveSdbError.new("Couldn't find #{name} with ID #{args}") unless record
options[:auto_load] ? reload_all_records(record).first : record
else
# if a bunch of records was requested then return check that we found all of them
# and return as an array
unless args.size == result.size
id_list = args.map { |i| "'#{i}'" }.join(',')
raise ActiveSdbError.new("Couldn't find all #{name} with IDs (#{id_list}) (found #{result.size} results, but was looking for #{args.size})")
else
options[:auto_load] ? reload_all_records(result) : result
end
end
end
# find_by helpers
def find_all_by_(format_str, args, options) # :nodoc:
fields = format_str.to_s.sub(/^find_(all_)?by_/, '').split('_and_')
conditions = fields.map { |field| "['#{field}'=?]" }.join(' intersection ')
options[:conditions] = [conditions, *args]
find(:all, options)
end
def find_by_(format_str, args, options) # :nodoc:
options[:limit] = 1
find_all_by_(format_str, args, options).first
end
# Misc
def method_missing(method, *args) # :nodoc:
if method.to_s[/^(find_all_by_|find_by_|select_all_by_|select_by_)/]
# get rid of the find ones, only select now
to_send_to = $1
attributes = method.to_s[$1.length..method.to_s.length]
# puts 'attributes=' + attributes
if to_send_to[0...4] == "find"
to_send_to = "select" + to_send_to[4..to_send_to.length]
# puts 'CONVERTED ' + $1 + " to " + to_send_to
end
options = args.last.is_a?(Hash) ? args.pop : {}
__send__(to_send_to, attributes, args, options)
else
super(method, *args)
end
end
def build_select(options) # :nodoc:
select = options[:select] || '*'
select = options[:count] ? "count(*)" : select
#puts 'select=' + select.to_s
from = options[:from] || domain
condition_fields = parse_condition_fields(options[:conditions])
conditions = options[:conditions] ? "#{build_conditions(options[:conditions])}" : ''
order = options[:order] ? " ORDER BY #{options[:order]}" : ''
limit = options[:limit] ? " LIMIT #{options[:limit]}" : ''
# mix sort by argument (it must present in response)
unless order.blank?
sort_by, sort_order = sort_options(options[:order])
if condition_fields.nil? || !condition_fields.include?(sort_by)
# conditions << (conditions.blank? ? " WHERE " : " AND ") << "(#{sort_by} IS NOT NULL)"
conditions = (conditions.blank? ? "" : "(#{conditions}) AND ") << "(#{sort_by} IS NOT NULL)"
else
# puts 'skipping is not null on sort because already there.'
end
end
conditions = conditions.blank? ? "" : " WHERE #{conditions}"
# puts 'CONDITIONS=' + conditions
"SELECT #{select} FROM `#{from}`#{conditions}#{order}#{limit}"
end
def build_conditions(conditions) # :nodoc:
case
when conditions.is_a?(Array) then
connection.query_expression_from_array(conditions)
when conditions.is_a?(Hash) then
connection.query_expression_from_hash(conditions)
else
conditions
end
end
# This will currently return and's, or's and betweens. Doesn't hurt anything, but could remove.
def parse_condition_fields(conditions)
return nil unless conditions && conditions.present? && conditions.is_a?(Array)
rx = /\b(\w*)[\s|>=|<=|!=|=|>|<|like|between]/
fields = conditions[0].scan(rx)
# puts 'condition_fields = ' + fields.inspect
fields.flatten
end
end
public
# instance attributes
attr_accessor :attributes
# item name
attr_accessor :id
# Create new Item instance.
# +attrs+ is a hash: { attribute1 => values1, ..., attributeN => valuesN }.
#
# item = Client.new('name' => 'Jon', 'toys' => ['girls', 'beer', 'pub'])
# puts item.inspect #=> #<Client:0xb77a2698 @new_record=true, @attributes={"name"=>["Jon"], "toys"=>["girls", "beer", "pub"]}>
# item.save #=> {"name"=>["Jon"], "id"=>"c03edb7e-e45c-11dc-bede-001bfc466dd7", "toys"=>["girls", "beer", "pub"]}
# puts item.inspect #=> #<Client:0xb77a2698 @new_record=false, @attributes={"name"=>["Jon"], "id"=>"c03edb7e-e45c-11dc-bede-001bfc466dd7", "toys"=>["girls", "beer", "pub"]}>
#
def initialize(attrs={})
@attributes = uniq_values(attrs)
@new_record = true
end
# This is to separate initialization from user vs coming from db (ie: find())
def initialize_from_db(attrs={})
initialize(attrs)
end
# Create and save new Item instance.
# +Attributes+ is a hash: { attribute1 => values1, ..., attributeN => valuesN }.
#
# item = Client.create('name' => 'Cat', 'toys' => ['Jons socks', 'mice', 'clew'])
# puts item.inspect #=> #<Client:0xb77a0a78 @new_record=false, @attributes={"name"=>["Cat"], "id"=>"2937601a-e45d-11dc-a75f-001bfc466dd7", "toys"=>["Jons socks", "mice", "clew"]}>
#
def self.create(attributes={})
item = self.new(attributes)
item.save
item
end
# Returns an item id. Same as: item['id'] or item.attributes['id']
def id
@attributes['id']
end
# Sets an item id.
def id=(id)
@attributes['id'] = id.to_s
end
# Returns a hash of all the attributes.
#
# puts item.attributes.inspect #=> {"name"=>["Cat"], "id"=>"2937601a-e45d-11dc-a75f-001bfc466dd7", "toys"=>["Jons socks", "clew", "mice"]}
#
def attributes
@attributes.dup
end
# Allows one to set all the attributes at once by passing in a hash with keys matching the attribute names.
# if '+id+' attribute is not set in new attributes has then it being derived from old attributes.
#
# puts item.attributes.inspect #=> {"name"=>["Cat"], "id"=>"2937601a-e45d-11dc-a75f-001bfc466dd7", "toys"=>["Jons socks", "clew", "mice"]}
# # set new attributes ('id' is missed)
# item.attributes = { 'name'=>'Dog', 'toys'=>['bones','cats'] }
# puts item.attributes.inspect #=> {"name"=>["Dog"], "id"=>"2937601a-e45d-11dc-a75f-001bfc466dd7", "toys"=>["bones", "cats"]}
# # set new attributes ('id' is set)
# item.attributes = { 'id' => 'blah-blah', 'name'=>'Birds', 'toys'=>['seeds','dogs tail'] }
# puts item.attributes.inspect #=> {"name"=>["Birds"], "id"=>"blah-blah", "toys"=>["seeds", "dogs tail"]}
#
def attributes=(attrs)
old_id = @attributes['id']
@attributes = uniq_values(attrs)
@attributes['id'] = old_id if @attributes['id'].blank? && !old_id.blank?
self.attributes
end
def connection
self.class.connection
end
# Item domain name.
def domain
self.class.domain
end
# Returns the values of the attribute identified by +attribute+.
#
# puts item['Cat'].inspect #=> ["Jons socks", "clew", "mice"]
#
def [](attribute)
@attributes[attribute.to_s]
end
# Updates the attribute identified by +attribute+ with the specified +values+.
#
# puts item['Cat'].inspect #=> ["Jons socks", "clew", "mice"]
# item['Cat'] = ["Whiskas", "chicken"]
# puts item['Cat'].inspect #=> ["Whiskas", "chicken"]
#
def []=(attribute, values)
attribute = attribute.to_s
@attributes[attribute] = attribute == 'id' ? values.to_s : values.is_a?(Array) ? values.uniq : [values]
end
# Reload attributes from SDB. Replaces in-memory attributes.
#
# item = Client.find_by_name('Cat') #=> #<Client:0xb77d0d40 @attributes={"id"=>"2937601a-e45d-11dc-a75f-001bfc466dd7"}, @new_record=false>
# item.reload #=> #<Client:0xb77d0d40 @attributes={"id"=>"2937601a-e45d-11dc-a75f-001bfc466dd7", "name"=>["Cat"], "toys"=>["Jons socks", "clew", "mice"]}, @new_record=false>
#
def reload
raise_on_id_absence
old_id = id
attrs = connection.get_attributes(domain, id)[:attributes]
@attributes = {}
unless attrs.blank?
attrs.each { |attribute, values| @attributes[attribute] = values }
@attributes['id'] = old_id
end
mark_as_old
@attributes
end
# Reload a set of attributes from SDB. Adds the loaded list to in-memory data.
# +attrs_list+ is an array or comma separated list of attributes names.
# Returns a hash of loaded attributes.
#
# This is not the best method to get a bunch of attributes because
# a web service call is being performed for every attribute.
#
# item = Client.find_by_name('Cat')
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | true |
appoxy/simple_record | https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/results_array.rb | lib/simple_record/results_array.rb | module SimpleRecord
#
# We need to make this behave as if the full set were loaded into the array.
class ResultsArray
include Enumerable
attr_reader :next_token, :clz, :params, :items, :index, :box_usage, :request_id
def initialize(clz=nil, params=[], results=nil, next_token=nil)
@clz = clz
#puts 'class=' + clz.inspect
@params = params
if @params.size <= 1
options = {}
@params[1] = options
end
@items = results[:items]
@currentset_items = results[:items]
@next_token = next_token
# puts 'bu=' + results[:box_usage]
@box_usage = results[:box_usage].to_f
@request_id = results[:request_id]
@options = @params[1]
if @options[:page]
load_to(@options[:per_page] * @options[:page])
@start_at = @options[:per_page] * (@options[:page] - 1)
end
@index = 0
# puts 'RESULTS_ARRAY=' + self.inspect
end
def << (val)
@items << val
end
def [](*i)
# puts 'i.inspect=' + i.inspect
# puts i.size.to_s
# i.each do |x|
# puts 'x=' + x.inspect + " -- " + x.class.name
# end
if i.size == 1
# either fixnum or range
x = i[0]
if x.is_a?(Fixnum)
load_to(x)
else
# range
end_val = x.exclude_end? ? x.end-1 : x.end
load_to(end_val)
end
elsif i.size == 2
# two fixnums
end_val = i[0] + i[1]
load_to(end_val)
end
@items[*i]
end
# Will load items from SimpleDB up to i.
def load_to(i)
return if @items.size >= i
while @items.size < i && !@next_token.nil?
load_next_token_set
end
end
def first
@items[0]
end
def last
@items[@items.length-1]
end
def empty?
@items.empty?
end
def include?(obj)
@items.include?(obj)
end
def size
# if @options[:per_page]
# return @items.size - @start_at
# end
if @next_token.nil?
return @items.size
end
return @count if @count
# puts '@params=' + @params.inspect
params_for_count = @params.dup
params_for_count[0] = :count
params_for_count[1] = params_for_count[1].dup # for deep clone
params_for_count[1].delete(:limit)
params_for_count[1].delete(:per_token)
params_for_count[1][:called_by] = :results_array
# puts '@params2=' + @params.inspect
# puts 'params_for_count=' + params_for_count.inspect
@count = clz.find(*params_for_count)
# puts '@count=' + @count.to_s
@count
end
def length
return size
end
def each(&blk)
each2((@start_at || 0), &blk)
end
def each2(i, &blk)
options = @params[1]
# puts 'options=' + options.inspect
limit = options[:limit]
# puts 'limit=' + limit.inspect
if i > @items.size
i = @items.size
end
range = i..@items.size
# puts 'range=' + range.inspect
@items[range].each do |v|
# puts "i=" + i.to_s
yield v
i += 1
@index += 1
if !limit.nil? && i >= limit
return
end
end
return if @clz.nil?
# no more items, but is there a next token?
unless @next_token.nil?
#puts 'finding more items...'
#puts 'params in block=' + params.inspect
#puts "i from results_array = " + @i.to_s
load_next_token_set
each2(i, &blk)
end
end
# for will_paginate support
def total_pages
#puts 'total_pages'
# puts @params[1][:per_page].to_s
return 1 if @params[1][:per_page].nil?
ret = (size / @params[1][:per_page].to_f).ceil
#puts 'ret=' + ret.to_s
ret
end
def current_page
return query_options[:page] || 1
end
def query_options
return @options
end
def total_entries
return size
end
# Helper method that is true when someone tries to fetch a page with a
# larger number than the last page. Can be used in combination with flashes
# and redirecting.
def out_of_bounds?
current_page > total_pages
end
# Current offset of the paginated collection. If we're on the first page,
# it is always 0. If we're on the 2nd page and there are 30 entries per page,
# the offset is 30. This property is useful if you want to render ordinals
# side by side with records in the view: simply start with offset + 1.
def offset
(current_page - 1) * per_page
end
# current_page - 1 or nil if there is no previous page
def previous_page
current_page > 1 ? (current_page - 1) : nil
end
# current_page + 1 or nil if there is no next page
def next_page
current_page < total_pages ? (current_page + 1) : nil
end
def load_next_token_set
options = @params[1]
options[:next_token] = @next_token
options[:called_by] = :results_array
res = @clz.find(*@params)
@currentset_items = res.items # get the real items array from the ResultsArray
@currentset_items.each do |item|
@items << item
end
@next_token = res.next_token
end
def delete(item)
@items.delete(item)
end
def delete_at(index)
@items.delete_at(index)
end
# A couple json serialization methods copied from active_support
def as_json(options = nil) #:nodoc:
# use encoder as a proxy to call as_json on all elements, to protect from circular references
encoder = options && options[:encoder] || ActiveSupport::JSON::Encoding::Encoder.new(options)
map { |v| encoder.as_json(v) }
end
def encode_json(encoder) #:nodoc:
# we assume here that the encoder has already run as_json on self and the elements, so we run encode_json directly
"[#{map { |v| v.encode_json(encoder) } * ','}]"
end
end
end
| ruby | MIT | 0252a022a938f368d6853ab1ae31f77f80b9f044 | 2026-01-04T17:50:57.195630Z | false |
openjournals/theoj | https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/app/serializers/basic_user_serializer.rb | app/serializers/basic_user_serializer.rb | class BasicUserSerializer < BaseSerializer
attributes :name
end
| ruby | MIT | 73c6acccc0aefe64b0030c818f405b25b7e7b589 | 2026-01-04T17:49:58.613320Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.