CombinedText stringlengths 4 3.42M |
|---|
require 'spec_helper'
describe Travis::Build::Script::R, :sexp do
let (:data) { payload_for(:push, :r) }
let (:script) { described_class.new(data) }
subject { script.sexp }
it_behaves_like 'a build script sexp'
it 'normalizes bioc-devel correctly' do
data[:config][:r] = 'bioc-devel'
should include_sexp [:export, ['TRAVIS_R_VERSION', '3.3.1']]
should include_sexp [:cmd, %r{source\(\"https://bioconductor.org/biocLite.R\"\)},
assert: true, echo: true, timing: true, retry: true]
should include_sexp [:cmd, %r{useDevel\(TRUE\)},
assert: true, echo: true, timing: true, retry: true]
end
it 'normalizes bioc-release correctly' do
data[:config][:r] = 'bioc-release'
should include_sexp [:cmd, %r{source\(\"https://bioconductor.org/biocLite.R\"\)},
assert: true, echo: true, timing: true, retry: true]
should include_sexp [:export, ['TRAVIS_R_VERSION', '3.3.1']]
end
it 'r_packages works with a single package set' do
data[:config][:r_packages] = 'test'
should include_sexp [:cmd, %r{install\.packages\(c\(\"test\"\)\)},
assert: true, echo: true, timing: true]
end
it 'r_packages works with multiple packages set' do
data[:config][:r_packages] = ['test', 'test2']
should include_sexp [:cmd, %r{install\.packages\(c\(\"test\", \"test2\"\)\)},
assert: true, echo: true, timing: true]
end
it 'exports TRAVIS_R_VERSION' do
data[:config][:r] = '3.3.0'
should include_sexp [:export, ['TRAVIS_R_VERSION', '3.3.0']]
end
it 'downloads and installs latest R' do
should include_sexp [:cmd, %r{^curl.*https://s3.amazonaws.com/rstudio-travis/R-3.3.1.xz},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads and installs latest R on OS X' do
data[:config][:os] = 'osx'
should include_sexp [:cmd, %r{^curl.*bin/macosx/R-latest.pkg},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads and installs aliased R 3.2.5 on OS X' do
data[:config][:os] = 'osx'
data[:config][:r] = '3.2.5'
should include_sexp [:cmd, %r{^curl.*bin/macosx/old/R-3.2.4-revised.pkg},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads and installs other R versions on OS X' do
data[:config][:os] = 'osx'
data[:config][:r] = '3.1.3'
should include_sexp [:cmd, %r{^curl.*bin/macosx/old/R-3.1.3.pkg},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads and installs R 3.1' do
data[:config][:r] = '3.1'
should include_sexp [:cmd, %r{^curl.*https://s3.amazonaws.com/rstudio-travis/R-3.1.3.xz},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads and installs R 3.2' do
data[:config][:r] = '3.2'
should include_sexp [:cmd, %r{^curl.*https://s3.amazonaws.com/rstudio-travis/R-3.2.5.xz},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads and installs R devel' do
data[:config][:r] = 'devel'
should include_sexp [:cmd, %r{^curl.*https://s3.amazonaws.com/rstudio-travis/R-devel.xz},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads pandoc and installs into /usr/bin/pandoc' do
data[:config][:pandoc_version] = '1.15.2'
should include_sexp [:cmd, %r{curl -Lo /tmp/pandoc-1\.15\.2-1-amd64.deb https://github\.com/jgm/pandoc/releases/download/1.15.2/pandoc-1\.15\.2-1-amd64.deb},
assert: true, echo: true, timing: true]
should include_sexp [:cmd, %r{sudo dpkg -i /tmp/pandoc-},
assert: true, echo: true, timing: true]
end
it 'sets repos in ~/.Rprofile.site with defaults' do
data[:config][:cran] = 'https://cloud.r-project.org'
should include_sexp [:cmd, "echo 'options(repos = c(CRAN = \"https://cloud.r-project.org\"))' > ~/.Rprofile.site",
assert: true, echo: true, timing: true]
end
it 'sets repos in ~/.Rprofile.site with user specified repos' do
data[:config][:cran] = 'https://cran.rstudio.org'
should include_sexp [:cmd, "echo 'options(repos = c(CRAN = \"https://cran.rstudio.org\"))' > ~/.Rprofile.site",
assert: true, echo: true, timing: true]
end
it 'sets repos in ~/.Rprofile.site with additional user specified repos' do
data[:config][:repos] = {CRAN: 'https://cran.rstudio.org', ropensci: 'http://packages.ropensci.org'}
should include_sexp [:cmd, "echo 'options(repos = c(CRAN = \"https://cran.rstudio.org\", ropensci = \"http://packages.ropensci.org\"))' > ~/.Rprofile.site",
assert: true, echo: true, timing: true]
end
it 'installs binary devtools if sudo: required' do
data[:config][:sudo] = 'required'
should include_sexp [:cmd, /sudo apt-get install.*r-cran-devtools/,
assert: true, echo: true, timing: true, retry: true]
end
it 'installs source devtools if sudo: is missing' do
should include_sexp [:cmd, /Rscript -e 'install\.packages\(c\(\"devtools\"\)/,
assert: true, echo: true, timing: true]
should_not include_sexp [:cmd, /sudo apt-get install.*r-cran-devtools/,
assert: true, echo: true, timing: true, retry: true]
end
it 'installs source devtools if sudo: false' do
data[:config][:sudo] = false
should include_sexp [:cmd, /Rscript -e 'install\.packages\(c\(\"devtools\"\)/,
assert: true, echo: true, timing: true]
should_not include_sexp [:cmd, /sudo apt-get install.*r-cran-devtools/,
assert: true, echo: true, timing: true, retry: true]
end
it 'fails on package build and test failures' do
should include_sexp [:cmd, /.*R CMD build.*/,
assert: true, echo: true, timing: true]
should include_sexp [:cmd, /.*R CMD check.*/,
echo: true, timing: true]
end
describe 'bioc configuration is optional' do
it 'does not install bioc if not required' do
should_not include_sexp [:cmd, /.*biocLite.*/,
assert: true, echo: true, retry: true, timing: true]
end
it 'does install bioc if requested' do
data[:config][:bioc_required] = true
should include_sexp [:cmd, /.*biocLite.*/,
assert: true, echo: true, retry: true, timing: true]
end
it 'does install bioc with bioc_packages' do
data[:config][:bioc_packages] = ['GenomicFeatures']
should include_sexp [:cmd, /.*biocLite.*/,
assert: true, echo: true, retry: true, timing: true]
end
end
describe '#cache_slug' do
subject { described_class.new(data).cache_slug }
it {
data[:config][:r] = '3.3.0'
should eq("cache-#{CACHE_SLUG_EXTRAS}--R-3.3.0")
}
it {
data[:config][:r] = '3.2'
should eq("cache-#{CACHE_SLUG_EXTRAS}--R-3.2.5")
}
it {
data[:config][:r] = 'release'
should eq("cache-#{CACHE_SLUG_EXTRAS}--R-3.3.1")
}
it {
data[:config][:r] = 'oldrel'
should eq("cache-#{CACHE_SLUG_EXTRAS}--R-3.2.5")
}
it {
data[:config][:r] = '3.1'
should eq("cache-#{CACHE_SLUG_EXTRAS}--R-3.1.3")
}
it {
data[:config][:r] = 'devel'
should eq("cache-#{CACHE_SLUG_EXTRAS}--R-devel")
}
end
end
add unit test for --no-manual
require 'spec_helper'
describe Travis::Build::Script::R, :sexp do
let (:data) { payload_for(:push, :r) }
let (:script) { described_class.new(data) }
subject { script.sexp }
it_behaves_like 'a build script sexp'
it 'normalizes bioc-devel correctly' do
data[:config][:r] = 'bioc-devel'
should include_sexp [:export, ['TRAVIS_R_VERSION', '3.3.1']]
should include_sexp [:cmd, %r{source\(\"https://bioconductor.org/biocLite.R\"\)},
assert: true, echo: true, timing: true, retry: true]
should include_sexp [:cmd, %r{useDevel\(TRUE\)},
assert: true, echo: true, timing: true, retry: true]
end
it 'normalizes bioc-release correctly' do
data[:config][:r] = 'bioc-release'
should include_sexp [:cmd, %r{source\(\"https://bioconductor.org/biocLite.R\"\)},
assert: true, echo: true, timing: true, retry: true]
should include_sexp [:export, ['TRAVIS_R_VERSION', '3.3.1']]
end
it 'r_packages works with a single package set' do
data[:config][:r_packages] = 'test'
should include_sexp [:cmd, %r{install\.packages\(c\(\"test\"\)\)},
assert: true, echo: true, timing: true]
end
it 'r_packages works with multiple packages set' do
data[:config][:r_packages] = ['test', 'test2']
should include_sexp [:cmd, %r{install\.packages\(c\(\"test\", \"test2\"\)\)},
assert: true, echo: true, timing: true]
end
it 'exports TRAVIS_R_VERSION' do
data[:config][:r] = '3.3.0'
should include_sexp [:export, ['TRAVIS_R_VERSION', '3.3.0']]
end
it 'downloads and installs latest R' do
should include_sexp [:cmd, %r{^curl.*https://s3.amazonaws.com/rstudio-travis/R-3.3.1.xz},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads and installs latest R on OS X' do
data[:config][:os] = 'osx'
should include_sexp [:cmd, %r{^curl.*bin/macosx/R-latest.pkg},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads and installs aliased R 3.2.5 on OS X' do
data[:config][:os] = 'osx'
data[:config][:r] = '3.2.5'
should include_sexp [:cmd, %r{^curl.*bin/macosx/old/R-3.2.4-revised.pkg},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads and installs other R versions on OS X' do
data[:config][:os] = 'osx'
data[:config][:r] = '3.1.3'
should include_sexp [:cmd, %r{^curl.*bin/macosx/old/R-3.1.3.pkg},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads and installs R 3.1' do
data[:config][:r] = '3.1'
should include_sexp [:cmd, %r{^curl.*https://s3.amazonaws.com/rstudio-travis/R-3.1.3.xz},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads and installs R 3.2' do
data[:config][:r] = '3.2'
should include_sexp [:cmd, %r{^curl.*https://s3.amazonaws.com/rstudio-travis/R-3.2.5.xz},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads and installs R devel' do
data[:config][:r] = 'devel'
should include_sexp [:cmd, %r{^curl.*https://s3.amazonaws.com/rstudio-travis/R-devel.xz},
assert: true, echo: true, retry: true, timing: true]
end
it 'downloads pandoc and installs into /usr/bin/pandoc' do
data[:config][:pandoc_version] = '1.15.2'
should include_sexp [:cmd, %r{curl -Lo /tmp/pandoc-1\.15\.2-1-amd64.deb https://github\.com/jgm/pandoc/releases/download/1.15.2/pandoc-1\.15\.2-1-amd64.deb},
assert: true, echo: true, timing: true]
should include_sexp [:cmd, %r{sudo dpkg -i /tmp/pandoc-},
assert: true, echo: true, timing: true]
end
it 'sets repos in ~/.Rprofile.site with defaults' do
data[:config][:cran] = 'https://cloud.r-project.org'
should include_sexp [:cmd, "echo 'options(repos = c(CRAN = \"https://cloud.r-project.org\"))' > ~/.Rprofile.site",
assert: true, echo: true, timing: true]
end
it 'sets repos in ~/.Rprofile.site with user specified repos' do
data[:config][:cran] = 'https://cran.rstudio.org'
should include_sexp [:cmd, "echo 'options(repos = c(CRAN = \"https://cran.rstudio.org\"))' > ~/.Rprofile.site",
assert: true, echo: true, timing: true]
end
it 'sets repos in ~/.Rprofile.site with additional user specified repos' do
data[:config][:repos] = {CRAN: 'https://cran.rstudio.org', ropensci: 'http://packages.ropensci.org'}
should include_sexp [:cmd, "echo 'options(repos = c(CRAN = \"https://cran.rstudio.org\", ropensci = \"http://packages.ropensci.org\"))' > ~/.Rprofile.site",
assert: true, echo: true, timing: true]
end
it 'installs binary devtools if sudo: required' do
data[:config][:sudo] = 'required'
should include_sexp [:cmd, /sudo apt-get install.*r-cran-devtools/,
assert: true, echo: true, timing: true, retry: true]
end
it 'installs source devtools if sudo: is missing' do
should include_sexp [:cmd, /Rscript -e 'install\.packages\(c\(\"devtools\"\)/,
assert: true, echo: true, timing: true]
should_not include_sexp [:cmd, /sudo apt-get install.*r-cran-devtools/,
assert: true, echo: true, timing: true, retry: true]
end
it 'installs source devtools if sudo: false' do
data[:config][:sudo] = false
should include_sexp [:cmd, /Rscript -e 'install\.packages\(c\(\"devtools\"\)/,
assert: true, echo: true, timing: true]
should_not include_sexp [:cmd, /sudo apt-get install.*r-cran-devtools/,
assert: true, echo: true, timing: true, retry: true]
end
it 'fails on package build and test failures' do
should include_sexp [:cmd, /.*R CMD build.*/,
assert: true, echo: true, timing: true]
should include_sexp [:cmd, /.*R CMD check.*/,
echo: true, timing: true]
end
it 'skips PDF manual when LaTeX is disabled' do
data[:config][:latex] = false
should include_sexp [:cmd, /.*R CMD check.* --no-manual.*/,
echo: true, timing: true]
end
describe 'bioc configuration is optional' do
it 'does not install bioc if not required' do
should_not include_sexp [:cmd, /.*biocLite.*/,
assert: true, echo: true, retry: true, timing: true]
end
it 'does install bioc if requested' do
data[:config][:bioc_required] = true
should include_sexp [:cmd, /.*biocLite.*/,
assert: true, echo: true, retry: true, timing: true]
end
it 'does install bioc with bioc_packages' do
data[:config][:bioc_packages] = ['GenomicFeatures']
should include_sexp [:cmd, /.*biocLite.*/,
assert: true, echo: true, retry: true, timing: true]
end
end
describe '#cache_slug' do
subject { described_class.new(data).cache_slug }
it {
data[:config][:r] = '3.3.0'
should eq("cache-#{CACHE_SLUG_EXTRAS}--R-3.3.0")
}
it {
data[:config][:r] = '3.2'
should eq("cache-#{CACHE_SLUG_EXTRAS}--R-3.2.5")
}
it {
data[:config][:r] = 'release'
should eq("cache-#{CACHE_SLUG_EXTRAS}--R-3.3.1")
}
it {
data[:config][:r] = 'oldrel'
should eq("cache-#{CACHE_SLUG_EXTRAS}--R-3.2.5")
}
it {
data[:config][:r] = '3.1'
should eq("cache-#{CACHE_SLUG_EXTRAS}--R-3.1.3")
}
it {
data[:config][:r] = 'devel'
should eq("cache-#{CACHE_SLUG_EXTRAS}--R-devel")
}
end
end
|
require 'spec_helper'
describe Clockwork::Test do
it 'has a version number' do
expect(Clockwork::Test::VERSION).not_to be nil
end
it 'does something useful' do
expect(false).to eq(true)
end
end
Clean up initial spec
This modification deletes the superfluous example test, but keeps the
version check assertion.
require "spec_helper"
describe Clockwork::Test do
it "has a version number" do
expect(Clockwork::Test::VERSION).not_to be nil
end
end
|
# encoding: UTF-8
require 'spec_helper'
describe Cloze::Deletion do
before(:all) do
String.send :include, Cloze::Deletion
end
describe '.cloze_delete' do
it 'cloze deletes each character' do
arr = "foo".cloze_delete(:each)
arr.should == ['#oo','f#o','fo#']
end
it 'cloze deletes the whole string' do
arr = "foo".cloze_delete(:all)
arr.should == ['###']
end
it 'cloze deletes each character and the whole string' do
arr = "foo".cloze_delete(:each, :all)
arr.should == ['#oo','f#o','fo#','###']
end
it 'cloze deletes kanji only' do
arr = "巻き込む".cloze_delete(:kanji)
arr.should == ['#き込む','巻き#む']
end
it 'cloze deletes kanji and the whole string' do
arr = "巻き込む".cloze_delete(:kanji, :all)
arr.should == ['####','#き込む','巻き#む']
end
it 'cloze deletes with a different separator' do
arr = "foo".cloze_delete(:each, with: '?')
arr.should == ['?oo','f?o','fo?']
end
it 'defaults to :each if no args are supplied' do
arr = "foo".cloze_delete
arr.should == ['#oo','f#o','fo#']
end
end
describe '.cloze' do
it 'is an alias for .cloze_delete' do
# arr = "foo".cloze
# arr.should == ['#oo','f#o','fo#']
end
end
describe '#default_deletion_character=' do
it 'changes the default deletion character' do
Cloze::Deletion.default_deletion_character = '?'
arr = "foo".cloze_delete(:each)
arr.should == ['?oo','f?o','fo?']
arr = "foo".cloze_delete(:each, with: '#')
arr.should == ['#oo','f#o','fo#']
end
end
describe '#included' do
it 'raises a TypeError when included in a non-String class' do
expect{
class Array
include Cloze::Deletion
end
}.to raise_error(TypeError)
end
end
end
reset deletion char to avoid failing specs by random order
# encoding: UTF-8
require 'spec_helper'
describe Cloze::Deletion do
before(:all) do
String.send :include, Cloze::Deletion
end
describe '.cloze_delete' do
it 'cloze deletes each character' do
arr = "foo".cloze_delete(:each)
arr.should == ['#oo','f#o','fo#']
end
it 'cloze deletes the whole string' do
arr = "foo".cloze_delete(:all)
arr.should == ['###']
end
it 'cloze deletes each character and the whole string' do
arr = "foo".cloze_delete(:each, :all)
arr.should == ['#oo','f#o','fo#','###']
end
it 'cloze deletes kanji only' do
arr = "巻き込む".cloze_delete(:kanji)
arr.should == ['#き込む','巻き#む']
end
it 'cloze deletes kanji and the whole string' do
arr = "巻き込む".cloze_delete(:kanji, :all)
arr.should == ['####','#き込む','巻き#む']
end
it 'cloze deletes with a different separator' do
arr = "foo".cloze_delete(:each, with: '?')
arr.should == ['?oo','f?o','fo?']
end
it 'defaults to :each if no args are supplied' do
arr = "foo".cloze_delete
arr.should == ['#oo','f#o','fo#']
end
end
describe '.cloze' do
it 'is an alias for .cloze_delete' do
# arr = "foo".cloze
# arr.should == ['#oo','f#o','fo#']
end
end
describe '#default_deletion_character=' do
before do
@orig_char = Cloze::Deletion.default_deletion_character
Cloze::Deletion.default_deletion_character = '?'
end
it 'changes the default deletion character' do
arr = "foo".cloze_delete(:each)
arr.should == ['?oo','f?o','fo?']
end
after do
Cloze::Deletion.default_deletion_character = @orig_char
end
end
describe '#included' do
it 'raises a TypeError when included in a non-String class' do
expect{
class Array
include Cloze::Deletion
end
}.to raise_error(TypeError)
end
end
end
|
require 'spec_helper'
describe Launchy::DetectHostOs do
it "uses the defult host os from ruby's config" do
Launchy::DetectHostOs.new.raw_host_os.must_equal RbConfig::CONFIG['host_os']
end
it "uses the passed in value as the host os" do
Launchy::DetectHostOs.new( "fake-os-1").raw_host_os.must_equal "fake-os-1"
end
it "uses the environment variable LAUNCHY_HOST_OS to override ruby's config" do
ENV['LAUNCHY_HOST_OS'] = "fake-os-2"
Launchy::DetectHostOs.new.raw_host_os.must_equal "fake-os-2"
ENV.delete('LAUNCHY_HOST_OS')
end
end
some whitespace would be nice here
require 'spec_helper'
describe Launchy::DetectHostOs do
it "uses the defult host os from ruby's config" do
Launchy::DetectHostOs.new.raw_host_os.must_equal RbConfig::CONFIG['host_os']
end
it "uses the passed in value as the host os" do
Launchy::DetectHostOs.new( "fake-os-1").raw_host_os.must_equal "fake-os-1"
end
it "uses the environment variable LAUNCHY_HOST_OS to override ruby's config" do
ENV['LAUNCHY_HOST_OS'] = "fake-os-2"
Launchy::DetectHostOs.new.raw_host_os.must_equal "fake-os-2"
ENV.delete('LAUNCHY_HOST_OS')
end
end
|
require 'spec_helper'
describe Docker::Network do
let(:name) do |example|
example.description.downcase.gsub('\s', '-')
end
describe '#to_s' do
subject { described_class.new(Docker.connection, info) }
let(:connection) { Docker.connection }
let(:id) do
'a6c5ffd25e07a6c906accf804174b5eb6a9d2f9e07bccb8f5aa4f4de5be6d01d'
end
let(:info) do
{
'Name' => 'bridge',
'Scope' => 'local',
'Driver' => 'bridge',
'IPAM' => {
'Driver' => 'default',
'Config' => [{ 'Subnet' => '172.17.0.0/16' }]
},
'Containers' => {},
'Options' => {
'com.docker.network.bridge.default_bridge' => 'true',
'com.docker.network.bridge.enable_icc' => 'true',
'com.docker.network.bridge.enable_ip_masquerade' => 'true',
'com.docker.network.bridge.host_binding_ipv4' => '0.0.0.0',
'com.docker.network.bridge.name' => 'docker0',
'com.docker.network.driver.mtu' => '1500'
},
'id' => id
}
end
let(:expected_string) do
"Docker::Network { :id => #{id}, :info => #{info.inspect}, "\
":connection => #{connection} }"
end
its(:to_s) { should == expected_string }
end
describe '.create' do
let!(:id) { subject.id }
subject { described_class.create(name) }
after { described_class.remove(id) }
it 'creates a Network' do
expect(Docker::Network.all.map(&:id)).to include(id)
end
end
describe '.remove' do
let(:id) { subject.id }
subject { described_class.create(name) }
it 'removes the Network' do
described_class.remove(id)
expect(Docker::Network.all.map(&:id)).to_not include(id)
end
end
describe '.get' do
after do
described_class.remove(name)
end
let!(:network) { described_class.create(name) }
it 'returns a network' do
expect(Docker::Network.get(name).id).to eq(network.id)
end
end
describe '.all' do
let!(:networks) do
5.times.map { |i| described_class.create("#{name}-#{i}") }
end
after do
networks.each(&:remove)
end
it 'should return all networks' do
expect(Docker::Network.all.map(&:id)).to include(*networks.map(&:id))
end
end
describe '#connect' do
let!(:container) do
Docker::Container.create(
'Cmd' => %w(sleep 10),
'Image' => 'debian:wheezy'
)
end
subject { described_class.create(name) }
before(:each) { container.start }
after(:each) do
container.kill!.remove
subject.remove
end
it 'connects a container to a network' do
subject.connect(container.id)
expect(subject.info['Containers']).to include(container.id)
end
end
describe '#disconnect' do
let!(:container) do
Docker::Container.create(
'Cmd' => %w(sleep 10),
'Image' => 'debian:wheezy'
)
end
subject { described_class.create(name) }
before(:each) do
container.start
sleep 1
subject.connect(container.id)
end
after(:each) do
container.kill!.remove
subject.remove
end
it 'connects a container to a network' do
subject.disconnect(container.id)
expect(subject.info['Containers']).not_to include(container.id)
end
end
describe '#remove' do
let(:id) { subject.id }
let(:name) { 'test-network-remove' }
subject { described_class.create(name) }
it 'removes the Network' do
subject.remove
expect(Docker::Network.all.map(&:id)).to_not include(id)
end
end
end
Filter network tests to 1.9
require 'spec_helper'
describe Docker::Network, docker_1_9: true do
let(:name) do |example|
example.description.downcase.gsub('\s', '-')
end
describe '#to_s' do
subject { described_class.new(Docker.connection, info) }
let(:connection) { Docker.connection }
let(:id) do
'a6c5ffd25e07a6c906accf804174b5eb6a9d2f9e07bccb8f5aa4f4de5be6d01d'
end
let(:info) do
{
'Name' => 'bridge',
'Scope' => 'local',
'Driver' => 'bridge',
'IPAM' => {
'Driver' => 'default',
'Config' => [{ 'Subnet' => '172.17.0.0/16' }]
},
'Containers' => {},
'Options' => {
'com.docker.network.bridge.default_bridge' => 'true',
'com.docker.network.bridge.enable_icc' => 'true',
'com.docker.network.bridge.enable_ip_masquerade' => 'true',
'com.docker.network.bridge.host_binding_ipv4' => '0.0.0.0',
'com.docker.network.bridge.name' => 'docker0',
'com.docker.network.driver.mtu' => '1500'
},
'id' => id
}
end
let(:expected_string) do
"Docker::Network { :id => #{id}, :info => #{info.inspect}, "\
":connection => #{connection} }"
end
its(:to_s) { should == expected_string }
end
describe '.create' do
let!(:id) { subject.id }
subject { described_class.create(name) }
after { described_class.remove(id) }
it 'creates a Network' do
expect(Docker::Network.all.map(&:id)).to include(id)
end
end
describe '.remove' do
let(:id) { subject.id }
subject { described_class.create(name) }
it 'removes the Network' do
described_class.remove(id)
expect(Docker::Network.all.map(&:id)).to_not include(id)
end
end
describe '.get' do
after do
described_class.remove(name)
end
let!(:network) { described_class.create(name) }
it 'returns a network' do
expect(Docker::Network.get(name).id).to eq(network.id)
end
end
describe '.all' do
let!(:networks) do
5.times.map { |i| described_class.create("#{name}-#{i}") }
end
after do
networks.each(&:remove)
end
it 'should return all networks' do
expect(Docker::Network.all.map(&:id)).to include(*networks.map(&:id))
end
end
describe '#connect' do
let!(:container) do
Docker::Container.create(
'Cmd' => %w(sleep 10),
'Image' => 'debian:wheezy'
)
end
subject { described_class.create(name) }
before(:each) { container.start }
after(:each) do
container.kill!.remove
subject.remove
end
it 'connects a container to a network' do
subject.connect(container.id)
expect(subject.info['Containers']).to include(container.id)
end
end
describe '#disconnect' do
let!(:container) do
Docker::Container.create(
'Cmd' => %w(sleep 10),
'Image' => 'debian:wheezy'
)
end
subject { described_class.create(name) }
before(:each) do
container.start
sleep 1
subject.connect(container.id)
end
after(:each) do
container.kill!.remove
subject.remove
end
it 'connects a container to a network' do
subject.disconnect(container.id)
expect(subject.info['Containers']).not_to include(container.id)
end
end
describe '#remove' do
let(:id) { subject.id }
let(:name) { 'test-network-remove' }
subject { described_class.create(name) }
it 'removes the Network' do
subject.remove
expect(Docker::Network.all.map(&:id)).to_not include(id)
end
end
end
|
Dummy::Application.routes.draw do
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id))(.:format)'
end
mod route.rb simple
Dummy::Application.routes.draw do
root :to => 'welcome#index'
end
|
require 'ludicrous/yarv_vm'
require 'ludicrous/iter_loop'
require 'internal/vm/constants'
class RubyVM
class Instruction
def set_source(function)
# TODO
end
class TRACE
def ludicrous_compile(function, env)
end
end
class PUTOBJECT
def ludicrous_compile(function, env)
value = function.const(JIT::Type::OBJECT, self.operands[0])
env.stack.push(value)
end
end
class PUTSTRING
def ludicrous_compile(function, env)
str = function.const(JIT::Type::OBJECT, self.operands[0])
env.stack.push(function.rb_str_dup(str))
end
end
class PUTNIL
def ludicrous_compile(function, env)
env.stack.push(function.const(JIT::Type::OBJECT, nil))
end
end
class PUTSELF
def ludicrous_compile(function, env)
env.stack.push(env.scope.self)
end
end
class LEAVE
def ludicrous_compile(function, env)
retval = env.stack.pop
function.insn_return(retval)
end
end
def ludicrous_compile_binary_op(args)
function = args[:function]
env = args[:env]
operator = args[:operator]
fixnum_proc = args[:fixnum]
rhs = env.stack.pop
lhs = env.stack.pop
result = function.value(JIT::Type::OBJECT)
end_label = JIT::Label.new
function.if(lhs.is_fixnum & rhs.is_fixnum) {
# TODO: This optimization is only valid if Fixnum#+ has not
# been redefined. Fortunately, YARV gives us
# ruby_vm_redefined_flag, which we can check.
result.store(fixnum_proc.call(lhs, rhs))
function.insn_branch(end_label)
} .end
set_source(function)
env.stack.sync_sp()
result.store(function.rb_funcall(lhs, operator, rhs))
function.insn_label(end_label)
env.stack.push(result)
end
class OPT_PLUS
def ludicrous_compile(function, env)
ludicrous_compile_binary_op(
:function => function,
:env => env,
:operator => :+,
:fixnum => proc { |lhs, rhs|
lhs + (rhs & function.const(JIT::Type::INT, ~1)) }
)
end
end
class OPT_MINUS
def ludicrous_compile(function, env)
ludicrous_compile_binary_op(
:function => function,
:env => env,
:operator => :-,
:fixnum => proc { |lhs, rhs|
lhs - (rhs & function.const(JIT::Type::INT, ~1)) }
)
end
end
class OPT_NEQ
def ludicrous_compile(function, env)
ludicrous_compile_binary_op(
:function => function,
:env => env,
:operator => :!=,
:fixnum => proc { |lhs, rhs|
lhs.neq(rhs).to_rbool }
)
end
end
def ludicrous_compile_unary_op(args)
function = args[:function]
env = args[:env]
operator = args[:operator]
fixnum_proc = args[:fixnum]
operand = env.stack.pop
result = function.value(JIT::Type::OBJECT)
end_label = JIT::Label.new
function.if(operand.is_fixnum) {
# TODO: This optimization is only valid if Fixnum#<operator> has
# not been redefined. Fortunately, YARV gives us
# ruby_vm_redefined_flag, which we can check.
result.store(fixnum_proc.call(operand))
function.insn_branch(end_label)
} .end
set_source(function)
env.stack.sync_sp()
result.store(function.rb_funcall(operand, operator))
function.insn_label(end_label)
env.stack.push(result)
end
class OPT_NOT
def ludicrous_compile(function, env)
operand = env.stack.pop
env.stack.push(operand.rnot)
end
end
class OPT_AREF
def ludicrous_compile(function, env)
obj = env.stack.pop
recv = env.stack.pop
result = function.rb_funcall(recv, :[], obj)
env.stack.push(result)
end
end
class DUP
def ludicrous_compile(function, env)
env.stack.push(env.stack.top)
end
end
class DUPARRAY
def ludicrous_compile(function, env)
ary = @operands[0]
env.stack.sync_sp()
ary = function.rb_ary_dup(ary)
env.stack.push(ary)
end
end
class SPLATARRAY
def ludicrous_compile(function, env)
ary = env.stack.pop
env.stack.sync_sp()
env.stack.push(ary.splat)
end
end
class EXPANDARRAY
class Flags
attr_reader :is_splat
attr_reader :is_post
attr_reader :is_normal
def initialize(flags)
@is_splat = (flags & 0x1) != 0
@is_post = (flags & 0x2) != 0
@is_normal = !@is_post
end
end
def ludicrous_compile(function, env)
num = @operands[0]
flags = Flags.new(@operands[1])
# TODO: insn_dup does not dup constants, so we do this -- is
# there a better way?
ary = env.stack.pop
# ary = function.insn_dup(ary)
ary = ary + function.const(JIT::Type::INT, 0)
function.unless(ary.is_type(Ludicrous::T_ARRAY)) {
ary.store(function.rb_ary_to_ary(ary))
}.end
if flags.is_post then
ludicrous_compile_post(function, env, ary, num, flags)
else
ludicrous_compile_normal(function, env, ary, num, flags)
end
end
def ludicrous_compile_post(function, env, ary, num, flags)
raise "Not implemented"
end
def ludicrous_compile_normal(function, env, ary, num, flags)
if flags.is_splat then
remainder = function.rb_funcall(ary, :[], 0..num)
env.stack.push(remainder)
end
(num-1).downto(0) do |i|
env.stack.push(function.rb_ary_at(ary, i))
end
end
end
class NEWARRAY
def ludicrous_compile(function, env)
# TODO: possible to optimize this
num = @operands[0]
env.stack.sync_sp()
ary = function.rb_ary_new2(num)
num.times do
env.stack.sync_sp
function.rb_ary_push(ary, env.stack.pop)
end
env.stack.push(ary)
end
end
class CONCATARRAY
def ludicrous_compile(function, env)
ary1 = env.stack.pop
ary2 = env.stack.pop
tmp1 = ary1.splat
tmp2 = ary2.splat
env.stack.sync_sp()
env.stack.push(function.rb_ary_concat(tmp1, tmp2))
end
end
class POP
def ludicrous_compile(function, env)
env.stack.pop
end
end
class SETN
def ludicrous_compile(function, env)
n = @operands[0]
env.stack.setn(n, env.stack.pop)
end
end
class SETLOCAL
def ludicrous_compile(function, env)
name = env.local_variable_name(@operands[0])
value = env.stack.pop
env.scope.local_set(name, value)
end
end
class GETLOCAL
def ludicrous_compile(function, env)
name = env.local_variable_name(@operands[0])
env.stack.push(env.scope.local_get(name))
end
end
class GETDYNAMIC
def ludicrous_compile(function, env)
name = env.local_variable_name(@operands[0])
env.stack.push(env.scope.dyn_get(name))
end
end
class GETCONSTANT
def ludicrous_compile(function, env)
klass = env.stack.pop
vid = @operands[0]
# TODO: can determine this at compile-time
result = function.value(JIT::Type::OBJECT)
function.if(klass == function.const(JIT::Type::OBJECT, nil)) {
result.store(env.get_constant(vid))
}.else {
result.store(function.rb_const_get(klass, vid))
}.end
env.stack.push(result)
end
end
class JUMP
def ludicrous_compile(function, env)
relative_offset = @operands[0]
env.branch(relative_offset)
end
end
class BRANCHIF
def ludicrous_compile(function, env)
relative_offset = @operands[0]
val = env.stack.pop
env.branch_if(val.rtest, relative_offset)
end
end
class BRANCHUNLESS
def ludicrous_compile(function, env)
relative_offset = @operands[0]
val = env.stack.pop
env.branch_unless(val.rtest, relative_offset)
end
end
def ludicrous_iterate(function, env, body, recv=nil)
# body - the iseq for body of the loop
# recv -
# 1. compile a nested function from the body of the loop
# 2. pass this nested function as a parameter to
iter_signature = JIT::Type.create_signature(
JIT::ABI::CDECL,
JIT::Type::OBJECT,
[ JIT::Type::VOID_PTR ])
iter_f = JIT::Function.compile(function.context, iter_signature) do |f|
f.optimization_level = env.options.optimization_level
iter_arg = Ludicrous::IterArg.wrap(f, f.get_param(0))
inner_scope = Ludicrous::AddressableScope.load(
f, iter_arg.scope, env.scope.local_names,
env.scope.args, env.scope.rest_arg)
inner_env = Ludicrous::YarvEnvironment.new(
f, env.options, env.cbase, iter_arg.scope, nil)
result = yield(f, inner_env, iter_arg.recv)
f.insn_return result
end
body_signature = JIT::Type::create_signature(
JIT::ABI::CDECL,
JIT::Type::OBJECT,
[ JIT::Type::OBJECT, JIT::Type::VOID_PTR ])
body_f = JIT::Function.compile(function.context, body_signature) do |f|
f.optimization_level = env.options.optimization_level
value = f.get_param(0)
outer_scope_obj = f.get_param(1)
inner_scope = Ludicrous::AddressableScope.load(
f, outer_scope_obj, env.scope.local_names, env.scope.args,
env.scope.rest_arg)
inner_env = Ludicrous::YarvEnvironment.new(
f, env.options, env.cbase, inner_scope, body)
loop = Ludicrous::IterLoop.new(f)
inner_env.iter(loop) {
ludicrous_iter_arg_assign(f, inner_env, body, value)
body.ludicrous_compile(f, inner_env)
}
end
iter_arg = Ludicrous::IterArg.new(function, env, recv)
# TODO: will this leak memory if the function is redefined later?
iter_c = function.const(JIT::Type::FUNCTION_PTR, iter_f.to_closure)
body_c = function.const(JIT::Type::FUNCTION_PTR, body_f.to_closure)
set_source(function)
result = function.rb_iterate(iter_c, iter_arg.ptr, body_c, iter_arg.scope)
return result
end
def ludicrous_iter_arg_assign(function, env, body, value)
len = function.ruby_struct_member(:RArray, :len, value)
ptr = function.ruby_struct_member(:RArray, :ptr, value)
if not body.arg_simple then
raise "Cannot handle non-simple block arguments"
end
# TODO: size check?
for i in 0...(body.argc) do
# TODO: make sure the block argument is local to this scope
idx = function.const(JIT::Type::INT, i)
value = function.insn_load_elem(ptr, idx, JIT::Type::OBJECT)
env.scope.dyn_set(body.local_table[i], value)
end
end
class SEND
def ludicrous_compile(function, env)
mid = @operands[0]
argc = @operands[1]
blockiseq = @operands[2]
flags = @operands[3]
ic = @operands[4]
if flags & RubyVM::CALL_ARGS_BLOCKARG_BIT != 0 then
# TODO: set blockiseq
raise "Block arg not supported"
end
if flags & RubyVM::CALL_ARGS_SPLAT_BIT != 0 then
raise "Splat not supported"
end
if flags & RubyVM::CALL_VCALL_BIT != 0 then
raise "Vcall not supported"
end
args = (1..argc).collect { env.stack.pop }
if flags & RubyVM::CALL_FCALL_BIT != 0 then
recv = env.scope.self
env.stack.pop # nil
else
recv = env.stack.pop
end
# TODO: pull in optimizations from eval_nodes.rb
env.stack.sync_sp()
if blockiseq then
result = ludicrous_iterate(function, env, blockiseq, recv) do |f, e, r|
# TODO: args is still referencing the outer function
f.rb_funcall(r, mid, *args)
end
else
result = function.rb_funcall(recv, mid, *args)
# TODO: not sure why this was here, maybe I was trying to
# prevent a crash
# result = function.const(JIT::Type::OBJECT, nil)
end
env.stack.push(result)
end
end
class GETINLINECACHE
def ludicrous_compile(function, env)
# ignore, for now
env.stack.push(function.const(JIT::Type::OBJECT, nil))
end
end
class SETINLINECACHE
def ludicrous_compile(function, env)
# ignore, for now
end
end
class NOP
def ludicrous_compile(function, env)
end
end
class DEFINEMETHOD
def ludicrous_compile(function, env)
mid = @operands[0]
iseq = @operands[1]
is_singleton = @operands[2] != 0
obj = env.stack.pop
klass = is_singleton \
? function.rb_class_of(obj)
: function.rb_class_of(env.scope.self) # TODO: cref->nd_clss
# COPY_CREF(miseq->cref_stack, cref);
# miseq->klass = klass;
# miseq->defined_method_id = id;
# newbody = NEW_NODE(RUBY_VM_METHOD_NODE, 0, miseq->self, 0);
# rb_add_method(klass, id, newbody, noex);
# TODO: set_source(function)
# TODO: set cref on iseq
# TODO: set klass on iseq
# TODO: set defined_method_id on iseq
newbody = function.rb_node_newnode(
Node::METHOD,
0,
function.const(JIT::Type::OBJECT, iseq),
0)
function.rb_add_method(
klass,
function.const(JIT::Type::ID, mid),
newbody,
function.const(JIT::Type::INT, 0)) # TODO: noex
end
end
end
end
Implemented THROW.
require 'ludicrous/yarv_vm'
require 'ludicrous/iter_loop'
require 'internal/vm/constants'
class RubyVM
class Instruction
def set_source(function)
# TODO
end
class TRACE
def ludicrous_compile(function, env)
end
end
class PUTOBJECT
def ludicrous_compile(function, env)
value = function.const(JIT::Type::OBJECT, self.operands[0])
env.stack.push(value)
end
end
class PUTSTRING
def ludicrous_compile(function, env)
str = function.const(JIT::Type::OBJECT, self.operands[0])
env.stack.push(function.rb_str_dup(str))
end
end
class PUTNIL
def ludicrous_compile(function, env)
env.stack.push(function.const(JIT::Type::OBJECT, nil))
end
end
class PUTSELF
def ludicrous_compile(function, env)
env.stack.push(env.scope.self)
end
end
class LEAVE
def ludicrous_compile(function, env)
retval = env.stack.pop
function.insn_return(retval)
end
end
def ludicrous_compile_binary_op(args)
function = args[:function]
env = args[:env]
operator = args[:operator]
fixnum_proc = args[:fixnum]
rhs = env.stack.pop
lhs = env.stack.pop
result = function.value(JIT::Type::OBJECT)
end_label = JIT::Label.new
function.if(lhs.is_fixnum & rhs.is_fixnum) {
# TODO: This optimization is only valid if Fixnum#+ has not
# been redefined. Fortunately, YARV gives us
# ruby_vm_redefined_flag, which we can check.
result.store(fixnum_proc.call(lhs, rhs))
function.insn_branch(end_label)
} .end
set_source(function)
env.stack.sync_sp()
result.store(function.rb_funcall(lhs, operator, rhs))
function.insn_label(end_label)
env.stack.push(result)
end
class OPT_PLUS
def ludicrous_compile(function, env)
ludicrous_compile_binary_op(
:function => function,
:env => env,
:operator => :+,
:fixnum => proc { |lhs, rhs|
lhs + (rhs & function.const(JIT::Type::INT, ~1)) }
)
end
end
class OPT_MINUS
def ludicrous_compile(function, env)
ludicrous_compile_binary_op(
:function => function,
:env => env,
:operator => :-,
:fixnum => proc { |lhs, rhs|
lhs - (rhs & function.const(JIT::Type::INT, ~1)) }
)
end
end
class OPT_NEQ
def ludicrous_compile(function, env)
ludicrous_compile_binary_op(
:function => function,
:env => env,
:operator => :!=,
:fixnum => proc { |lhs, rhs|
lhs.neq(rhs).to_rbool }
)
end
end
def ludicrous_compile_unary_op(args)
function = args[:function]
env = args[:env]
operator = args[:operator]
fixnum_proc = args[:fixnum]
operand = env.stack.pop
result = function.value(JIT::Type::OBJECT)
end_label = JIT::Label.new
function.if(operand.is_fixnum) {
# TODO: This optimization is only valid if Fixnum#<operator> has
# not been redefined. Fortunately, YARV gives us
# ruby_vm_redefined_flag, which we can check.
result.store(fixnum_proc.call(operand))
function.insn_branch(end_label)
} .end
set_source(function)
env.stack.sync_sp()
result.store(function.rb_funcall(operand, operator))
function.insn_label(end_label)
env.stack.push(result)
end
class OPT_NOT
def ludicrous_compile(function, env)
operand = env.stack.pop
env.stack.push(operand.rnot)
end
end
class OPT_AREF
def ludicrous_compile(function, env)
obj = env.stack.pop
recv = env.stack.pop
result = function.rb_funcall(recv, :[], obj)
env.stack.push(result)
end
end
class DUP
def ludicrous_compile(function, env)
env.stack.push(env.stack.top)
end
end
class DUPARRAY
def ludicrous_compile(function, env)
ary = @operands[0]
env.stack.sync_sp()
ary = function.rb_ary_dup(ary)
env.stack.push(ary)
end
end
class SPLATARRAY
def ludicrous_compile(function, env)
ary = env.stack.pop
env.stack.sync_sp()
env.stack.push(ary.splat)
end
end
class EXPANDARRAY
class Flags
attr_reader :is_splat
attr_reader :is_post
attr_reader :is_normal
def initialize(flags)
@is_splat = (flags & 0x1) != 0
@is_post = (flags & 0x2) != 0
@is_normal = !@is_post
end
end
def ludicrous_compile(function, env)
num = @operands[0]
flags = Flags.new(@operands[1])
# TODO: insn_dup does not dup constants, so we do this -- is
# there a better way?
ary = env.stack.pop
# ary = function.insn_dup(ary)
ary = ary + function.const(JIT::Type::INT, 0)
function.unless(ary.is_type(Ludicrous::T_ARRAY)) {
ary.store(function.rb_ary_to_ary(ary))
}.end
if flags.is_post then
ludicrous_compile_post(function, env, ary, num, flags)
else
ludicrous_compile_normal(function, env, ary, num, flags)
end
end
def ludicrous_compile_post(function, env, ary, num, flags)
raise "Not implemented"
end
def ludicrous_compile_normal(function, env, ary, num, flags)
if flags.is_splat then
remainder = function.rb_funcall(ary, :[], 0..num)
env.stack.push(remainder)
end
(num-1).downto(0) do |i|
env.stack.push(function.rb_ary_at(ary, i))
end
end
end
class NEWARRAY
def ludicrous_compile(function, env)
# TODO: possible to optimize this
num = @operands[0]
env.stack.sync_sp()
ary = function.rb_ary_new2(num)
num.times do
env.stack.sync_sp
function.rb_ary_push(ary, env.stack.pop)
end
env.stack.push(ary)
end
end
class CONCATARRAY
def ludicrous_compile(function, env)
ary1 = env.stack.pop
ary2 = env.stack.pop
tmp1 = ary1.splat
tmp2 = ary2.splat
env.stack.sync_sp()
env.stack.push(function.rb_ary_concat(tmp1, tmp2))
end
end
class POP
def ludicrous_compile(function, env)
env.stack.pop
end
end
class SETN
def ludicrous_compile(function, env)
n = @operands[0]
env.stack.setn(n, env.stack.pop)
end
end
class SETLOCAL
def ludicrous_compile(function, env)
name = env.local_variable_name(@operands[0])
value = env.stack.pop
env.scope.local_set(name, value)
end
end
class GETLOCAL
def ludicrous_compile(function, env)
name = env.local_variable_name(@operands[0])
env.stack.push(env.scope.local_get(name))
end
end
class GETDYNAMIC
def ludicrous_compile(function, env)
name = env.local_variable_name(@operands[0])
env.stack.push(env.scope.dyn_get(name))
end
end
class GETCONSTANT
def ludicrous_compile(function, env)
klass = env.stack.pop
vid = @operands[0]
# TODO: can determine this at compile-time
result = function.value(JIT::Type::OBJECT)
function.if(klass == function.const(JIT::Type::OBJECT, nil)) {
result.store(env.get_constant(vid))
}.else {
result.store(function.rb_const_get(klass, vid))
}.end
env.stack.push(result)
end
end
class JUMP
def ludicrous_compile(function, env)
relative_offset = @operands[0]
env.branch(relative_offset)
end
end
class BRANCHIF
def ludicrous_compile(function, env)
relative_offset = @operands[0]
val = env.stack.pop
env.branch_if(val.rtest, relative_offset)
end
end
class BRANCHUNLESS
def ludicrous_compile(function, env)
relative_offset = @operands[0]
val = env.stack.pop
env.branch_unless(val.rtest, relative_offset)
end
end
def ludicrous_iterate(function, env, body, recv=nil)
# body - the iseq for body of the loop
# recv -
# 1. compile a nested function from the body of the loop
# 2. pass this nested function as a parameter to
iter_signature = JIT::Type.create_signature(
JIT::ABI::CDECL,
JIT::Type::OBJECT,
[ JIT::Type::VOID_PTR ])
iter_f = JIT::Function.compile(function.context, iter_signature) do |f|
f.optimization_level = env.options.optimization_level
iter_arg = Ludicrous::IterArg.wrap(f, f.get_param(0))
inner_scope = Ludicrous::AddressableScope.load(
f, iter_arg.scope, env.scope.local_names,
env.scope.args, env.scope.rest_arg)
inner_env = Ludicrous::YarvEnvironment.new(
f, env.options, env.cbase, iter_arg.scope, nil)
result = yield(f, inner_env, iter_arg.recv)
f.insn_return result
end
body_signature = JIT::Type::create_signature(
JIT::ABI::CDECL,
JIT::Type::OBJECT,
[ JIT::Type::OBJECT, JIT::Type::VOID_PTR ])
body_f = JIT::Function.compile(function.context, body_signature) do |f|
f.optimization_level = env.options.optimization_level
value = f.get_param(0)
outer_scope_obj = f.get_param(1)
inner_scope = Ludicrous::AddressableScope.load(
f, outer_scope_obj, env.scope.local_names, env.scope.args,
env.scope.rest_arg)
inner_env = Ludicrous::YarvEnvironment.new(
f, env.options, env.cbase, inner_scope, body)
loop = Ludicrous::IterLoop.new(f)
inner_env.iter(loop) {
ludicrous_iter_arg_assign(f, inner_env, body, value)
body.ludicrous_compile(f, inner_env)
}
end
iter_arg = Ludicrous::IterArg.new(function, env, recv)
# TODO: will this leak memory if the function is redefined later?
iter_c = function.const(JIT::Type::FUNCTION_PTR, iter_f.to_closure)
body_c = function.const(JIT::Type::FUNCTION_PTR, body_f.to_closure)
set_source(function)
result = function.rb_iterate(iter_c, iter_arg.ptr, body_c, iter_arg.scope)
return result
end
def ludicrous_iter_arg_assign(function, env, body, value)
len = function.ruby_struct_member(:RArray, :len, value)
ptr = function.ruby_struct_member(:RArray, :ptr, value)
if not body.arg_simple then
raise "Cannot handle non-simple block arguments"
end
# TODO: size check?
for i in 0...(body.argc) do
# TODO: make sure the block argument is local to this scope
idx = function.const(JIT::Type::INT, i)
value = function.insn_load_elem(ptr, idx, JIT::Type::OBJECT)
env.scope.dyn_set(body.local_table[i], value)
end
end
class SEND
def ludicrous_compile(function, env)
mid = @operands[0]
argc = @operands[1]
blockiseq = @operands[2]
flags = @operands[3]
ic = @operands[4]
if flags & RubyVM::CALL_ARGS_BLOCKARG_BIT != 0 then
# TODO: set blockiseq
raise "Block arg not supported"
end
if flags & RubyVM::CALL_ARGS_SPLAT_BIT != 0 then
raise "Splat not supported"
end
if flags & RubyVM::CALL_VCALL_BIT != 0 then
raise "Vcall not supported"
end
args = (1..argc).collect { env.stack.pop }
if flags & RubyVM::CALL_FCALL_BIT != 0 then
recv = env.scope.self
env.stack.pop # nil
else
recv = env.stack.pop
end
# TODO: pull in optimizations from eval_nodes.rb
env.stack.sync_sp()
if blockiseq then
result = ludicrous_iterate(function, env, blockiseq, recv) do |f, e, r|
# TODO: args is still referencing the outer function
f.rb_funcall(r, mid, *args)
end
else
result = function.rb_funcall(recv, mid, *args)
# TODO: not sure why this was here, maybe I was trying to
# prevent a crash
# result = function.const(JIT::Type::OBJECT, nil)
end
env.stack.push(result)
end
end
class THROW
def ludicrous_compile(function, env)
throw_state = @operands[0]
state = throw_state & 0xff
flag = throw_state & 0x8000
level = throw_state >> 16
throwobj = env.stack.pop
case state
when Tag::RETURN
env.return(throwobj)
else
raise "Cannot handle tag #{state}"
end
end
end
class GETINLINECACHE
def ludicrous_compile(function, env)
# ignore, for now
env.stack.push(function.const(JIT::Type::OBJECT, nil))
end
end
class SETINLINECACHE
def ludicrous_compile(function, env)
# ignore, for now
end
end
class NOP
def ludicrous_compile(function, env)
end
end
class DEFINEMETHOD
def ludicrous_compile(function, env)
mid = @operands[0]
iseq = @operands[1]
is_singleton = @operands[2] != 0
obj = env.stack.pop
klass = is_singleton \
? function.rb_class_of(obj)
: function.rb_class_of(env.scope.self) # TODO: cref->nd_clss
# COPY_CREF(miseq->cref_stack, cref);
# miseq->klass = klass;
# miseq->defined_method_id = id;
# newbody = NEW_NODE(RUBY_VM_METHOD_NODE, 0, miseq->self, 0);
# rb_add_method(klass, id, newbody, noex);
# TODO: set_source(function)
# TODO: set cref on iseq
# TODO: set klass on iseq
# TODO: set defined_method_id on iseq
newbody = function.rb_node_newnode(
Node::METHOD,
0,
function.const(JIT::Type::OBJECT, iseq),
0)
function.rb_add_method(
klass,
function.const(JIT::Type::ID, mid),
newbody,
function.const(JIT::Type::INT, 0)) # TODO: noex
end
end
end
end
|
Rails.application.routes.draw do
devise_for :users
mount FassetsCore::Engine => "/fassets-core"
root :to => "catalogs#index"
end
change mount-point in dummy project
Rails.application.routes.draw do
devise_for :users
mount FassetsCore::Engine => "/core"
root :to => "FassetsCore::Catalogs#index"
end
|
Dummy::Application.routes.draw do
api vendor_string: "myvendor" do
version 1 do
cache as: 'v1' do
resources :bar
end
end
version 2 do
cache as: 'v2' do
resources :foo
inherit from: 'v1'
end
end
version 3 do
inherit from: 'v2'
end
end
get '*a' => 'errors#not_found'
get 'index' => 'simplified_format#index'
end
Remove meaningless line that was leftover.
Dummy::Application.routes.draw do
api vendor_string: "myvendor" do
version 1 do
cache as: 'v1' do
resources :bar
end
end
version 2 do
cache as: 'v2' do
resources :foo
inherit from: 'v1'
end
end
version 3 do
inherit from: 'v2'
end
end
get '*a' => 'errors#not_found'
end
|
# encoding: UTF-8
#
# Copyright (c) 2010-2017 GoodData Corporation. All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
module GoodData
module Environment
module ConnectionHelper
set_const :GD_PROJECT_TOKEN, GoodData::Helpers.decrypt("DIRchLbHH1fovLSVEfo3f5aQwHHQ432+PxF3uR5IuNn+iYWz+HZrLtaZ3LVE\n0ZNc\n", ENV['GD_SPEC_PASSWORD'] || ENV['BIA_ENCRYPTION_KEY'])
set_const :DEFAULT_DOMAIN, 'staging2-lcm-prod'
set_const :DEFAULT_SERVER, 'https://staging2-lcm-prod.intgdc.com'
set_const :DEFAULT_USER_URL, '/gdc/account/profile/f099860dd647395377fbf65ae7a78ed4'
set_const :STAGING_URI, 'https://na1-staging2-di.intgdc.com/uploads/'
end
module ProcessHelper
set_const :PROCESS_ID, '3dddcd0d-1b56-4508-a94b-abea70c7154d'
end
module ProjectHelper
set_const :PROJECT_ID, 'fbhs09oddsgezqtn3um5rp08midmbpg5'
end
module ScheduleHelper
set_const :SCHEDULE_ID, '58ad4fbbe4b02e90f6422677'
end
end
end
Fix DEFAULT_USER_URL in testing environment
# encoding: UTF-8
#
# Copyright (c) 2010-2017 GoodData Corporation. All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
module GoodData
module Environment
module ConnectionHelper
set_const :GD_PROJECT_TOKEN, GoodData::Helpers.decrypt("DIRchLbHH1fovLSVEfo3f5aQwHHQ432+PxF3uR5IuNn+iYWz+HZrLtaZ3LVE\n0ZNc\n", ENV['GD_SPEC_PASSWORD'] || ENV['BIA_ENCRYPTION_KEY'])
set_const :DEFAULT_DOMAIN, 'staging2-lcm-prod'
set_const :DEFAULT_SERVER, 'https://staging2-lcm-prod.intgdc.com'
set_const :DEFAULT_USER_URL, '/gdc/account/profile/5ad80b895edcc438e5a4418e222733fa'
set_const :STAGING_URI, 'https://na1-staging2-di.intgdc.com/uploads/'
end
module ProcessHelper
set_const :PROCESS_ID, '3dddcd0d-1b56-4508-a94b-abea70c7154d'
end
module ProjectHelper
set_const :PROJECT_ID, 'fbhs09oddsgezqtn3um5rp08midmbpg5'
end
module ScheduleHelper
set_const :SCHEDULE_ID, '58ad4fbbe4b02e90f6422677'
end
end
end
|
require 'sprockets'
module Marv
module Project
class Assets
# Initialize assets builder
def initialize(builder)
@builder = builder
@task = builder.task
@project = builder.project
@config = builder.project.config
init_sprockets
end
# Clean images
def clean_images
@task.shell.mute do
# Remove screenshot image
::Dir.glob(::File.join(@project.build_path, 'screenshot.*')).each do |file|
@task.remove_file file
end
# Remove images folder
@task.remove_dir ::File.join(@project.build_path, 'images')
end
end
# Copy images
def copy_images
@task.shell.mute do
::Dir.glob(::File.join(@project.assets_path, 'images', '*')).each do |filename|
# Check for screenshot and move it into main build directory
if filename.index(/screenshot/)
@task.copy_file filename, ::File.join(@project.build_path, ::File.basename(filename)), :force => true
else
# Copy the other files in images directory
@task.copy_file filename, ::File.join(@project.build_path, 'images'), :force => true
end
end
end
end
# Build assets
def build_assets
@task.shell.mute do
@project.assets.each do |asset|
destination = ::File.join(@project.build_path, asset)
# Catch any sprockets errors and continue the process
begin
sprocket = @sprockets.find_asset(asset.last)
# Create assets destination
unless ::File.directory?(::File.dirname(destination))
@task.empty_directory ::File.dirname(destination)
end
# Write file to destination
sprocket.write_to(destination) unless sprocket.nil?
rescue Exception => e
@task.say "Error while building #{asset.last}:"
@task.say e.message, :red
# Print error to file
@task.create_file destination unless ::File.exists?(destination)
@task.append_to_file destination, e.message
end
end
end
end
# Init sprockets
def init_sprockets
@sprockets = ::Sprockets::Environment.new
['javascripts', 'stylesheets'].each do |dir|
@sprockets.append_path ::File.join(@project.assets_path, dir)
end
# Check for js compression
if @config[:compress_js]
@sprockets.js_compressor = :uglify
end
# Check for css compression
if @config[:compress_css]
@sprockets.css_compressor = :scss
end
# Passing the @project instance variable to the Sprockets::Context instance
# used for processing the asset ERB files
@sprockets.context_class.instance_exec(@project) do |project|
define_method :config do
project.config
end
end
end
end
end
end
optimize project assets class
require 'sprockets'
module Marv
module Project
class Assets
# Initialize assets builder
def initialize(builder)
@builder = builder
@task = builder.task
@project = builder.project
@config = builder.project.config
init_sprockets
end
# Clean images
def clean_images
@task.shell.mute do
# Remove screenshot image
::Dir.glob(::File.join(@project.build_path, 'screenshot.*')).each do |file|
@task.remove_file file
end
# Remove images folder
@task.remove_dir ::File.join(@project.build_path, 'images')
end
end
# Copy images
def copy_images
@task.shell.mute do
::Dir.glob(::File.join(@project.assets_path, 'images', '*')).each do |filename|
# Check for screenshot and move it into main build directory
if filename.index(/screenshot/)
@task.copy_file filename, ::File.join(@project.build_path, ::File.basename(filename)), :force => true
else
# Copy the other files in images directory
@task.copy_file filename, ::File.join(@project.build_path, 'images'), :force => true
end
end
end
end
# Build assets
def build_assets
@project.assets.each do |asset|
# Catch any sprockets errors and continue the process
begin
build_asset_file asset
rescue Exception => e
print_asset_error asset, e.message
end
end
end
# Build asset file
def build_asset_file(asset)
destination = ::File.join(@project.build_path, asset)
@task.shell.mute do
sprocket = @sprockets.find_asset(asset.last)
# Create asset destination
@task.empty_directory ::File.dirname(destination) unless ::File.directory?(::File.dirname(destination))
# Write file to destination
sprocket.write_to(destination) unless sprocket.nil?
end
end
# Print error to screen and file
def print_asset_error(asset, message)
destination = ::File.join(@project.build_path, asset)
@task.say "Error while building #{asset.last}:"
@task.say message, :red
@task.create_file destination unless ::File.exists?(destination)
@task.append_to_file destination, message
end
# Init sprockets
def init_sprockets
@sprockets = ::Sprockets::Environment.new
['javascripts', 'stylesheets'].each do |dir|
@sprockets.append_path ::File.join(@project.assets_path, dir)
end
# Check for js compression
if @config[:compress_js]
@sprockets.js_compressor = :uglify
end
# Check for css compression
if @config[:compress_css]
@sprockets.css_compressor = :scss
end
# Passing the @project instance variable to the Sprockets::Context instance
# used for processing the asset ERB files
@sprockets.context_class.instance_exec(@project) do |project|
define_method :config do
project.config
end
end
end
end
end
end |
# ~*~ encoding: utf-8 ~*~
require 'spec_helper'
require 'lamp/lesson'
describe Lamp::Lesson do
describe '::clone_from' do
context 'given an unsafe name' do
it 'raises an error' do
expect { Lamp::Lesson.clone_from 'x', '../jimjh/x' }.to raise_error Lamp::Lesson::NameError
end
end
context 'given a non-existent repository' do
it 'raises a GitCloneError' do
expect do
Lamp::Lesson.clone_from "/does/not/exist/#{SecureRandom.uuid}/dot.git", 'test'
end.to raise_error Lamp::Git::GitCloneError
end
end
context 'given a fake repository' do
include_context 'lesson repo'
let(:master) { Grit::Repo.new(@fake_repo).get_head('master').commit.id }
let(:commit) { Grit::Repo.new(@fake_repo).head.commit.id }
def clone(opts={})
@lesson = Lamp::Lesson.clone_from url, 'test', opts
end
after(:each) { @lesson.nil? || @lesson.rm }
shared_examples 'clone directory permissions' do
it 'creates a private directory' do
dir = Pathname.new clone.repo.working_dir
dir.should have_mode(Lamp::PERMISSIONS[:private_dir])
end
end
it 'defaults to the master branch' do
clone.repo.head.commit.id.should eq master
end
include_examples 'clone directory permissions'
context 'with a specified branch' do
before :each do
silence @fake_repo, <<-eos
git co -b x
git ci --allow-empty -am 'branch'
eos
end
it 'uses the specified branch' do
clone(branch: 'x').repo.head.commit.id.should eq commit
end
include_examples 'clone directory permissions'
end
context 'with a missing index.md' do
before(:each) { (@fake_repo + Spirit::INDEX).unlink; commit_all }
it 'raises an InvalidLessonError' do
expect { clone }
.to raise_error Lamp::Lesson::InvalidLessonError do |e|
e.errors.should_not be_empty
end
end
end
context 'with a missing manifest' do
before(:each) { (@fake_repo + Spirit::MANIFEST).unlink; commit_all }
it 'raises an InvalidLessonError if the manifest is missing.' do
expect { clone }
.to raise_error Lamp::Lesson::InvalidLessonError do |e|
e.errors.should_not be_empty
end
end
end
context 'and an existing lesson at the target path' do
let(:dir) { empty_directory Lamp::Lesson.source_path + 'test' }
before(:each) { random_file dir + 'x' }
it 'overwrites any existing lessons' do
clone.repo.head.commit.id.should eq master
(dir + Spirit::MANIFEST).should be_file
(dir + 'x').should_not be_file
end
end
end
end
end
added more specs
# ~*~ encoding: utf-8 ~*~
require 'spec_helper'
require 'lamp/lesson'
describe Lamp::Lesson do
describe '::clone_from' do
context 'given an unsafe name' do
it 'raises an error' do
expect { Lamp::Lesson.clone_from 'x', '../jimjh/x' }.to raise_error Lamp::Lesson::NameError
end
end
context 'given a non-existent repository' do
it 'raises a GitCloneError' do
expect do
Lamp::Lesson.clone_from "/does/not/exist/#{SecureRandom.uuid}/dot.git", 'test'
end.to raise_error Lamp::Git::GitCloneError
end
end
context 'given a fake repository' do
include_context 'lesson repo'
let(:master) { Grit::Repo.new(@fake_repo).get_head('master').commit.id }
let(:commit) { Grit::Repo.new(@fake_repo).head.commit.id }
def clone(opts={})
@lesson = Lamp::Lesson.clone_from url, 'test', opts
end
after(:each) { @lesson.nil? || @lesson.rm }
shared_examples 'clone directory permissions' do
it 'creates a private directory' do
dir = Pathname.new clone.repo.working_dir
dir.should have_mode(Lamp::PERMISSIONS[:private_dir])
end
end
it 'defaults to the master branch' do
clone.repo.head.commit.id.should eq master
end
include_examples 'clone directory permissions'
context 'with a specified branch' do
before :each do
silence @fake_repo, <<-eos
git co -b x
git ci --allow-empty -am 'branch'
eos
end
it 'uses the specified branch' do
clone(branch: 'x').repo.head.commit.id.should eq commit
end
include_examples 'clone directory permissions'
end
context 'with a missing index.md' do
before(:each) { (@fake_repo + Spirit::INDEX).unlink; commit_all }
it 'raises an InvalidLessonError' do
expect { clone }.to raise_error { |e|
e.should be_a Lamp::Lesson::InvalidLessonError
e.errors.should eq [[:index, 'lesson.lamp.missing']]
}
end
end
context 'with a missing manifest' do
before(:each) { (@fake_repo + Spirit::MANIFEST).unlink; commit_all }
it 'raises an InvalidLessonError' do
expect { clone }.to raise_error { |e|
e.should be_a Lamp::Lesson::InvalidLessonError
e.errors.should eq [[:manifest, 'lesson.lamp.missing']]
}
end
end
context 'and an existing lesson at the target path' do
let(:dir) { empty_directory Lamp::Lesson.source_path + 'test' }
before(:each) { random_file dir + 'x' }
it 'overwrites any existing lessons' do
clone.repo.head.commit.id.should eq master
(dir + Spirit::MANIFEST).should be_file
(dir + 'x').should_not be_file
end
end
end
end
end
|
require "./lib/math_expansion/matriz.rb"
module MathExpansion
# Esta clase permite representar matrices densas. Las matrices densas son aquellas que no tienen más de un 60% de elementos nulos.
# Su representación será muy similar a como se suelen representar tradicionalmente.
class Matriz_Densa < Matriz
# Constructor de la matriz. Crea una matriz de tamaño N*M inicializada a valores nulos.
# * *Argumentos* :
# - +n+: Número de filas. Debe ser mayor que 0.
# - +m+: Número de columnas. Debe ser mayor que 0.
def initialize(n, m)
super
@contenido = Array.new(@N,0)
i = 0
while i < @N
@contenido[i] = Array.new(@M,0)
i += 1
end
end
# Permite obtener el elemento en la posición (i,j), donde:
# * *Argumentos* :
# - +i+: Número de fila.
# - +j+: Número de columna.
# - +value+: Valor a insertar en la matriz.
# * *Devuelve* :
# - Valor almacenado en la fila +i+ y en la columna +j+. Devuelve nil si +i+ o +j+ están fuera de rango.
def get(i, j)
if( i < 0 or i >=@N or j < 0 or j >= @M)
return nil
end
@contenido[i][j]
end
# Devuelve el porcentaje de valores nulos que hay en la matriz.
# * *Devuelve* :
# - Número flotante entre 0 y 1 que represente cuantos valores nulos existen en la matriz densa.
def null_percent
total = @N*@M
no_nulos = 0
i = 0
while(i < @N)
j = 0
while(j < @M)
if(@contenido[i][j] != @contenido[i][j].class.null)
no_nulos += 1
end
j += 1
end
i += 1
end
nulos = total - no_nulos
nulos.to_f/total.to_f
end #-- #endmethod null_percent #++
# Establece el valor _value_ en la posición (i,j) de la matriz, donde:
# * *Argumentos* :
# - +i+: Número de fila.
# - +j+: Número de columna.
# - +value+: Valor a insertar en la matriz.
def set(i, j, value)
if( i < 0 or i >=@N or j < 0 or j >= @M)
return nil
end
if(!(value.class.respond_to? :null))
puts "Se debe definir el metodo \"null\" que devuelva un elemento nulo para la clase #{value.class}"
return nil
end
#--
# Contar elementos nulos y comprobar si se hace una matriz dispersa
# De momento, no dejamos añadir elementos nulos
# ¿o si?
#if(value != nil and value != value.class.null) # Y se puede comprobar para todos los tipos si es necesario. (con un método zero, por ejemplo)
@contenido[i][j] = value
#end
#++
end
# Permite representar de manera gráfica la matriz por consola.
# * *Devuelve* :
# - Objeto del tipo string con todos los elementos de la matriz.
def to_s
s = ""
i = 0
while(i < @N)
j = 0
while(j < @M)
s += "#{@contenido[i][j].to_s}\t"
j += 1
end
s += "\n"
i += 1
end
s
end
# Devuelve el máximo valor almacenado en la matriz.
# * *Devuelve* :
# - Valor máximo almacenado en la matriz.
def max
m = get(0,0)
i = 0
while(i < @N)
j = 0
while(j < @M)
if (get(i,j) > m)
m = get(i,j)
end
j += 1
end
i += 1
end
m
end
# Devuelve el mínimo valor almacenado en la matriz.
# * *Devuelve* :
# - Valor mínimo almacenado en la matriz.
def min
m = get(0,0)
i = 0
while(i < @N)
j = 0
while(j < @M)
if (get(i,j) < m)
m = get(i,j)
end
j += 1
end
i += 1
end
m
end #-- # Method min
end # Class
end # Module #++
Se ha definido el método de clase leerArray para la clase Matriz_Densa que permite leer un Array y convertirlo en una Matriz_Densa.
require "./lib/math_expansion/matriz.rb"
module MathExpansion
# Esta clase permite representar matrices densas. Las matrices densas son aquellas que no tienen más de un 60% de elementos nulos.
# Su representación será muy similar a como se suelen representar tradicionalmente.
class Matriz_Densa < Matriz
# Constructor de la matriz. Crea una matriz de tamaño N*M inicializada a valores nulos.
# * *Argumentos* :
# - +n+: Número de filas. Debe ser mayor que 0.
# - +m+: Número de columnas. Debe ser mayor que 0.
def initialize(n, m)
super
@contenido = Array.new(@N,0)
i = 0
while i < @N
@contenido[i] = Array.new(@M,0)
i += 1
end
end
# Permite obtener el elemento en la posición (i,j), donde:
# * *Argumentos* :
# - +i+: Número de fila.
# - +j+: Número de columna.
# - +value+: Valor a insertar en la matriz.
# * *Devuelve* :
# - Valor almacenado en la fila +i+ y en la columna +j+. Devuelve nil si +i+ o +j+ están fuera de rango.
def get(i, j)
if( i < 0 or i >=@N or j < 0 or j >= @M)
return nil
end
@contenido[i][j]
end
# Devuelve el porcentaje de valores nulos que hay en la matriz.
# * *Devuelve* :
# - Número flotante entre 0 y 1 que represente cuantos valores nulos existen en la matriz densa.
def null_percent
total = @N*@M
no_nulos = 0
i = 0
while(i < @N)
j = 0
while(j < @M)
if(@contenido[i][j] != @contenido[i][j].class.null)
no_nulos += 1
end
j += 1
end
i += 1
end
nulos = total - no_nulos
nulos.to_f/total.to_f
end #-- #endmethod null_percent #++
# Establece el valor _value_ en la posición (i,j) de la matriz, donde:
# * *Argumentos* :
# - +i+: Número de fila.
# - +j+: Número de columna.
# - +value+: Valor a insertar en la matriz.
def set(i, j, value)
if( i < 0 or i >=@N or j < 0 or j >= @M)
return nil
end
if(!(value.class.respond_to? :null))
puts "Se debe definir el metodo \"null\" que devuelva un elemento nulo para la clase #{value.class}"
return nil
end
#--
# Contar elementos nulos y comprobar si se hace una matriz dispersa
# De momento, no dejamos añadir elementos nulos
# ¿o si?
#if(value != nil and value != value.class.null) # Y se puede comprobar para todos los tipos si es necesario. (con un método zero, por ejemplo)
@contenido[i][j] = value
#end
#++
end
# Permite representar de manera gráfica la matriz por consola.
# * *Devuelve* :
# - Objeto del tipo string con todos los elementos de la matriz.
def to_s
s = ""
i = 0
while(i < @N)
j = 0
while(j < @M)
s += "#{@contenido[i][j].to_s}\t"
j += 1
end
s += "\n"
i += 1
end
s
end
# Devuelve el máximo valor almacenado en la matriz.
# * *Devuelve* :
# - Valor máximo almacenado en la matriz.
def max
m = get(0,0)
i = 0
while(i < @N)
j = 0
while(j < @M)
if (get(i,j) > m)
m = get(i,j)
end
j += 1
end
i += 1
end
m
end
# Devuelve el mínimo valor almacenado en la matriz.
# * *Devuelve* :
# - Valor mínimo almacenado en la matriz.
def min
m = get(0,0)
i = 0
while(i < @N)
j = 0
while(j < @M)
if (get(i,j) < m)
m = get(i,j)
end
j += 1
end
i += 1
end
m
end #-- # Method min
# Devuelve el mínimo valor almacenado en la matriz.
# * *Argumentos* :
# - Array bidimensional (clase Array).
# * *Devuelve* :
# - Matriz densa copiada de ese array.
def self.leerArray(array)
raise ArgumentError , 'Tipo invalido' unless array.is_a? Array
c = Matriz_Densa.new(array.size(), array[0].size())
array.each_index do |i|
array[i].each_index do |j|
c.set(i, j, array[i][j])
end
end
c
end #-- # Method leerArray
end # Class
end # Module #++
|
class FeedInfo
CACHE_EXPIRATION = Float(Figaro.env.feed_info_cache_expiration.presence || 14400)
def initialize(url: nil, path: nil)
fail ArgumentError.new('must provide url') unless url.present?
@url = url
@path = path
@gtfs = nil
end
def open(&block)
if @gtfs
yield self
elsif @path
@gtfs = GTFS::Source.build(@path, {strict: false})
@gtfs.load_graph
yield self
elsif @url
FeedFetch.download_to_tempfile(@url) do |path|
@path = path
@gtfs = GTFS::Source.build(@path, {strict: false})
@gtfs.load_graph
yield self
end
end
end
def parse_feed_and_operators
# feed
feed = Feed.from_gtfs(@gtfs, url: @url)
# operators
operators = []
@gtfs.agencies.each do |agency|
next if agency.stops.size == 0
operator = Operator.from_gtfs(agency)
operators << operator
feed.operators_in_feed.new(gtfs_agency_id: agency.id, operator: operator, id: nil)
end
# done
return [feed, operators]
end
end
Feed includes_operators
class FeedInfo
CACHE_EXPIRATION = Float(Figaro.env.feed_info_cache_expiration.presence || 14400)
def initialize(url: nil, path: nil)
fail ArgumentError.new('must provide url') unless url.present?
@url = url
@path = path
@gtfs = nil
end
def open(&block)
if @gtfs
yield self
elsif @path
@gtfs = GTFS::Source.build(@path, {strict: false})
@gtfs.load_graph
yield self
elsif @url
FeedFetch.download_to_tempfile(@url) do |path|
@path = path
@gtfs = GTFS::Source.build(@path, {strict: false})
@gtfs.load_graph
yield self
end
end
end
def parse_feed_and_operators
# feed
feed = Feed.from_gtfs(@gtfs, url: @url)
# operators
operators = []
@gtfs.agencies.each do |agency|
next if agency.stops.size == 0
operator = Operator.from_gtfs(agency)
operators << operator
feed.includes_operators ||= []
feed.includes_operators << {gtfsAgencyId: agency.id, operatorOnestopId: operator.onestop_id}
feed.operators_in_feed.new(gtfs_agency_id: agency.id, operator: operator, id: nil)
end
# done
return [feed, operators]
end
end
|
require 'rails_helper'
feature 'Users' do
feature 'Show (public page)' do
background do
@user = create(:user)
1.times {create(:debate, author: @user)}
2.times {create(:proposal, author: @user)}
3.times {create(:comment, user: @user)}
visit user_path(@user)
end
scenario 'shows user public activity' do
expect(page).to have_content('1 Debate')
expect(page).to have_content('2 Proposals')
expect(page).to have_content('3 Comments')
end
scenario 'default filter is proposals' do
@user.proposals.each do |proposal|
expect(page).to have_content(proposal.title)
end
@user.debates.each do |debate|
expect(page).to_not have_content(debate.title)
end
@user.comments.each do |comment|
expect(page).to_not have_content(comment.body)
end
end
scenario 'filters' do
click_link '1 Debate'
@user.debates.each do |debate|
expect(page).to have_content(debate.title)
end
@user.proposals.each do |proposal|
expect(page).to_not have_content(proposal.title)
end
@user.comments.each do |comment|
expect(page).to_not have_content(comment.body)
end
click_link '3 Comments'
@user.comments.each do |comment|
expect(page).to have_content(comment.body)
end
@user.proposals.each do |proposal|
expect(page).to_not have_content(proposal.title)
end
@user.debates.each do |debate|
expect(page).to_not have_content(debate.title)
end
end
end
feature 'Public activity' do
background do
@user = create(:user)
end
scenario 'visible by default' do
visit user_path(@user)
expect(page).to have_content(@user.username)
expect(page).to_not have_content('activity list private')
end
scenario 'user can hide public page' do
login_as(@user)
visit account_path
uncheck 'account_public_activity'
click_button 'Save changes'
logout
visit user_path(@user)
expect(page).to have_content('activity list private')
end
scenario 'is always visible for the owner' do
login_as(@user)
visit account_path
uncheck 'account_public_activity'
click_button 'Save changes'
visit user_path(@user)
expect(page).to_not have_content('activity list private')
end
scenario 'is always visible for admins' do
login_as(@user)
visit account_path
uncheck 'account_public_activity'
click_button 'Save changes'
logout
login_as(create(:administrator).user)
visit user_path(@user)
expect(page).to_not have_content('activity list private')
end
scenario 'is always visible for moderators' do
login_as(@user)
visit account_path
uncheck 'account_public_activity'
click_button 'Save changes'
logout
login_as(create(:moderator).user)
visit user_path(@user)
expect(page).to_not have_content('activity list private')
end
end
end
increases coverage of user page
require 'rails_helper'
feature 'Users' do
feature 'Show (public page)' do
background do
@user = create(:user)
1.times {create(:debate, author: @user)}
2.times {create(:proposal, author: @user)}
3.times {create(:comment, user: @user)}
visit user_path(@user)
end
scenario 'shows user public activity' do
expect(page).to have_content('1 Debate')
expect(page).to have_content('2 Proposals')
expect(page).to have_content('3 Comments')
end
scenario 'shows only items where user has activity' do
@user.proposals.destroy_all
expect(page).to_not have_content('0 Proposals')
expect(page).to have_content('1 Debate')
expect(page).to have_content('3 Comments')
end
scenario 'default filter is proposals' do
@user.proposals.each do |proposal|
expect(page).to have_content(proposal.title)
end
@user.debates.each do |debate|
expect(page).to_not have_content(debate.title)
end
@user.comments.each do |comment|
expect(page).to_not have_content(comment.body)
end
end
scenario 'shows debates by default if user has no proposals' do
@user.proposals.destroy_all
visit user_path(@user)
expect(page).to have_content(@user.debates.first.title)
end
scenario 'shows comments by default if user has no proposals nor debates' do
@user.proposals.destroy_all
@user.debates.destroy_all
visit user_path(@user)
@user.comments.each do |comment|
expect(page).to have_content(comment.body)
end
end
scenario 'filters' do
click_link '1 Debate'
@user.debates.each do |debate|
expect(page).to have_content(debate.title)
end
@user.proposals.each do |proposal|
expect(page).to_not have_content(proposal.title)
end
@user.comments.each do |comment|
expect(page).to_not have_content(comment.body)
end
click_link '3 Comments'
@user.comments.each do |comment|
expect(page).to have_content(comment.body)
end
@user.proposals.each do |proposal|
expect(page).to_not have_content(proposal.title)
end
@user.debates.each do |debate|
expect(page).to_not have_content(debate.title)
end
click_link '2 Proposals'
@user.proposals.each do |proposal|
expect(page).to have_content(proposal.title)
end
@user.comments.each do |comment|
expect(page).to_not have_content(comment.body)
end
@user.debates.each do |debate|
expect(page).to_not have_content(debate.title)
end
end
end
feature 'Public activity' do
background do
@user = create(:user)
end
scenario 'visible by default' do
visit user_path(@user)
expect(page).to have_content(@user.username)
expect(page).to_not have_content('activity list private')
end
scenario 'user can hide public page' do
login_as(@user)
visit account_path
uncheck 'account_public_activity'
click_button 'Save changes'
logout
visit user_path(@user)
expect(page).to have_content('activity list private')
end
scenario 'is always visible for the owner' do
login_as(@user)
visit account_path
uncheck 'account_public_activity'
click_button 'Save changes'
visit user_path(@user)
expect(page).to_not have_content('activity list private')
end
scenario 'is always visible for admins' do
login_as(@user)
visit account_path
uncheck 'account_public_activity'
click_button 'Save changes'
logout
login_as(create(:administrator).user)
visit user_path(@user)
expect(page).to_not have_content('activity list private')
end
scenario 'is always visible for moderators' do
login_as(@user)
visit account_path
uncheck 'account_public_activity'
click_button 'Save changes'
logout
login_as(create(:moderator).user)
visit user_path(@user)
expect(page).to_not have_content('activity list private')
end
end
end |
require 'active_support/time_with_zone'
require 'active_support/core_ext/time/calculations'
module Middleman
module Blog
# A module that adds blog-article methods to Resources.
module BlogArticle
# Render this resource
# @return [String]
def render(opts={}, locs={}, &block)
if opts[:layout].nil?
if metadata[:options] && !metadata[:options][:layout].nil?
opts[:layout] = metadata[:options][:layout]
end
opts[:layout] = app.blog.options.layout if opts[:layout].nil?
opts[:layout] = opts[:layout].to_s if opts[:layout].is_a? Symbol
end
content = super(opts, locs, &block)
unless opts[:keep_separator]
if content =~ app.blog.options.summary_separator
content.sub!($1, "")
end
end
content
end
# The title of the article, set from frontmatter
# @return [String]
def title
data["title"]
end
# Whether or not this article has been published
# @return [Boolean]
def published?
data["published"] != false and date <= Time.current
end
# The body of this article, in HTML. This is for
# things like RSS feeds or lists of articles - individual
# articles will automatically be rendered from their
# template.
# @return [String]
def body
render(:layout => false)
end
# The summary for this article, in HTML. The summary is either
# everything before the summary separator (set via :summary_separator
# and defaulting to "READMORE") or the first :summary_length
# characters of the post.
# @return [String]
def summary
@_summary ||= begin
source = app.template_data_for_file(source_file).dup
summary_source = if app.blog.options.summary_generator
app.blog.options.summary_generator.call(self, source)
else
default_summary_generator(source)
end
md = metadata.dup
locs = md[:locals]
opts = md[:options].merge({:template_body => summary_source})
app.render_individual_file(source_file, locs, opts)
end
end
def default_summary_generator(source)
if source =~ app.blog.options.summary_separator
source.split(app.blog.options.summary_separator).first
else
source.match(/(.{1,#{app.blog.options.summary_length}}.*?)(\n|\Z)/m).to_s
end
end
# A list of tags for this article, set from frontmatter.
# @return [Array<String>] (never nil)
def tags
article_tags = data["tags"]
if article_tags.is_a? String
article_tags.split(',').map(&:strip)
else
article_tags || []
end
end
# Retrieve a section of the source path
# @param [String] The part of the path, e.g. "year", "month", "day", "title"
# @return [String]
def path_part(part)
@_path_parts ||= app.blog.path_matcher.match(path).captures
@_path_parts[app.blog.matcher_indexes[part]]
end
# Attempt to figure out the date of the post. The date should be
# present in the source path, but users may also provide a date
# in the frontmatter in order to provide a time of day for sorting
# reasons.
#
# @return [TimeWithZone]
def date
return @_date if @_date
frontmatter_date = data["date"]
# First get the date from frontmatter
if frontmatter_date.is_a? Time
@_date = frontmatter_date.in_time_zone
else
@_date = Time.zone.parse(frontmatter_date.to_s)
end
# Next figure out the date from the filename
if app.blog.options.sources.include?(":year") &&
app.blog.options.sources.include?(":month") &&
app.blog.options.sources.include?(":day")
filename_date = Time.zone.local(path_part("year").to_i, path_part("month").to_i, path_part("day").to_i)
if @_date
raise "The date in #{path}'s filename doesn't match the date in its frontmatter" unless @_date.to_date == filename_date.to_date
else
@_date = filename_date.to_time.in_time_zone
end
end
raise "Blog post #{path} needs a date in its filename or frontmatter" unless @_date
@_date
end
# The "slug" of the article that shows up in its URL.
# @return [String]
def slug
@_slug ||= path_part("title")
end
# The previous (chronologically earlier) article before this one
# or nil if this is the first article.
# @return [Middleman::Sitemap::Resource]
def previous_article
app.blog.articles.find {|a| a.date < self.date }
end
# The next (chronologically later) article after this one
# or nil if this is the most recent article.
# @return [Middleman::Sitemap::Resource]
def next_article
app.blog.articles.reverse.find {|a| a.date > self.date }
end
end
end
end
Don't require blog separator regex to have a capturing group
require 'active_support/time_with_zone'
require 'active_support/core_ext/time/calculations'
module Middleman
module Blog
# A module that adds blog-article methods to Resources.
module BlogArticle
# Render this resource
# @return [String]
def render(opts={}, locs={}, &block)
if opts[:layout].nil?
if metadata[:options] && !metadata[:options][:layout].nil?
opts[:layout] = metadata[:options][:layout]
end
opts[:layout] = app.blog.options.layout if opts[:layout].nil?
opts[:layout] = opts[:layout].to_s if opts[:layout].is_a? Symbol
end
content = super(opts, locs, &block)
unless opts[:keep_separator]
if content =~ app.blog.options.summary_separator
content.sub!(app.blog.options.summary_separator, "")
end
end
content
end
# The title of the article, set from frontmatter
# @return [String]
def title
data["title"]
end
# Whether or not this article has been published
# @return [Boolean]
def published?
data["published"] != false and date <= Time.current
end
# The body of this article, in HTML. This is for
# things like RSS feeds or lists of articles - individual
# articles will automatically be rendered from their
# template.
# @return [String]
def body
render(:layout => false)
end
# The summary for this article, in HTML. The summary is either
# everything before the summary separator (set via :summary_separator
# and defaulting to "READMORE") or the first :summary_length
# characters of the post.
# @return [String]
def summary
@_summary ||= begin
source = app.template_data_for_file(source_file).dup
summary_source = if app.blog.options.summary_generator
app.blog.options.summary_generator.call(self, source)
else
default_summary_generator(source)
end
md = metadata.dup
locs = md[:locals]
opts = md[:options].merge({:template_body => summary_source})
app.render_individual_file(source_file, locs, opts)
end
end
def default_summary_generator(source)
if source =~ app.blog.options.summary_separator
source.split(app.blog.options.summary_separator).first
else
source.match(/(.{1,#{app.blog.options.summary_length}}.*?)(\n|\Z)/m).to_s
end
end
# A list of tags for this article, set from frontmatter.
# @return [Array<String>] (never nil)
def tags
article_tags = data["tags"]
if article_tags.is_a? String
article_tags.split(',').map(&:strip)
else
article_tags || []
end
end
# Retrieve a section of the source path
# @param [String] The part of the path, e.g. "year", "month", "day", "title"
# @return [String]
def path_part(part)
@_path_parts ||= app.blog.path_matcher.match(path).captures
@_path_parts[app.blog.matcher_indexes[part]]
end
# Attempt to figure out the date of the post. The date should be
# present in the source path, but users may also provide a date
# in the frontmatter in order to provide a time of day for sorting
# reasons.
#
# @return [TimeWithZone]
def date
return @_date if @_date
frontmatter_date = data["date"]
# First get the date from frontmatter
if frontmatter_date.is_a? Time
@_date = frontmatter_date.in_time_zone
else
@_date = Time.zone.parse(frontmatter_date.to_s)
end
# Next figure out the date from the filename
if app.blog.options.sources.include?(":year") &&
app.blog.options.sources.include?(":month") &&
app.blog.options.sources.include?(":day")
filename_date = Time.zone.local(path_part("year").to_i, path_part("month").to_i, path_part("day").to_i)
if @_date
raise "The date in #{path}'s filename doesn't match the date in its frontmatter" unless @_date.to_date == filename_date.to_date
else
@_date = filename_date.to_time.in_time_zone
end
end
raise "Blog post #{path} needs a date in its filename or frontmatter" unless @_date
@_date
end
# The "slug" of the article that shows up in its URL.
# @return [String]
def slug
@_slug ||= path_part("title")
end
# The previous (chronologically earlier) article before this one
# or nil if this is the first article.
# @return [Middleman::Sitemap::Resource]
def previous_article
app.blog.articles.find {|a| a.date < self.date }
end
# The next (chronologically later) article after this one
# or nil if this is the most recent article.
# @return [Middleman::Sitemap::Resource]
def next_article
app.blog.articles.reverse.find {|a| a.date > self.date }
end
end
end
end
|
class FeedInfo
CACHE_EXPIRATION = Float(Figaro.env.feed_info_cache_expiration.presence || 14400)
def initialize(url: nil, path: nil)
fail ArgumentError.new('must provide url') unless url.present?
@url = url
@path = path
@gtfs = nil
end
def open(&block)
if @gtfs
yield self
elsif @path
@gtfs = GTFS::Source.build(@path, {strict: false})
@gtfs.load_graph
yield self
elsif @url
FeedFetch.download_to_tempfile(@url) do |path|
@path = path
@gtfs = GTFS::Source.build(@path, {strict: false})
@gtfs.load_graph
yield self
end
end
end
def parse_feed_and_operators
# feed
feed = Feed.from_gtfs(@gtfs, url: @url)
# operators
operators = []
@gtfs.agencies.each do |agency|
next if agency.stops.size == 0
operator = Operator.from_gtfs(agency)
operators << operator
feed.operators_in_feed.new(gtfs_agency_id: agency.id, operator: operator, id: nil)
end
# done
return [feed, operators]
end
end
FeedInfo download and process methods with progress
class FeedInfo
CACHE_EXPIRATION = Float(Figaro.env.feed_info_cache_expiration.presence || 14400)
def initialize(url: nil, path: nil)
fail ArgumentError.new('must provide url') unless url.present?
@url = url
@path = path
@gtfs = nil
end
def download(progress: nil, &block)
FeedFetch.download_to_tempfile(@url) do |path|
@path = path
block.call self
end
end
def process(progress: nil, &block)
@gtfs = GTFS::Source.build(@path, {strict: false})
@gtfs.load_graph(&progress)
block.call self
end
def open(&block)
if @gtfs
block.call self
elsif @path
process { |i| open(&block) }
elsif @url
download { |i| open(&block) }
end
end
def parse_feed_and_operators
# feed
feed = Feed.from_gtfs(@gtfs, url: @url)
# operators
operators = []
@gtfs.agencies.each do |agency|
next if agency.stops.size == 0
operator = Operator.from_gtfs(agency)
operators << operator
feed.operators_in_feed.new(gtfs_agency_id: agency.id, operator: operator, id: nil)
end
# done
return [feed, operators]
end
end
|
describe Geometry::Point do
describe '.initialize' do
it 'should create a point when given co-ordinates' do
expect{
Geometry::Point.new(2,3)
}.not_to raise_exception
end
it 'should be readable' do
point = Geometry::Point.new(5,8)
expect(point.abscissa).to eq(5)
expect(point.ordinate).to eq(8)
end
it 'should not be writable' do
point = Geometry::Point.new(0,0)
expect{
point.ordinate = 4
point.abscissa = 5
}.to raise_error(NoMethodError)
end
end
describe '#equality (==)' do
it 'should be unequal when their attributes are unequal' do
point1 = Geometry::Point.new(5,2)
point2 = Geometry::Point.new(5,1)
expect(point1 == point2).to be_falsey
end
it 'should be equal when their attributes are equal' do
point1 = Geometry::Point.new(5,2)
expect(point1 == point1).to be_truthy
end
it 'should return true for two points when checked for Symmetric property of equality' do
point1 = Geometry::Point.new(2,2)
point2 = Geometry::Point.new(2,2)
expect(point1 == point2 && point2 == point1).to be_truthy
end
it 'should return true for three points when checked for transitive property of equality' do
point1 = Geometry::Point.new(2,2)
point2 = Geometry::Point.new(2,2)
point3 = Geometry::Point.new(2,2)
expect((point1 == point2 && point2 == point3) && point1 == point3).to be_truthy
end
it 'should not be equal to any object of different type' do
point1 = Geometry::Point.new(2,2)
point2 = Object.new
expect(point1 == point2).to be_falsey
end
it 'should not be equal to nil' do
point1 = Geometry::Point.new(2,2)
point2 = nil
expect(point1 == point2).to be_falsey
end
end
describe '#distance' do
it 'should return square root of 2 when given (0,0) and (1,1)' do
point1 = Geometry::Point.new(0,0)
point2 = Geometry::Point.new(1,1)
expect(point1.distance(point2)).to eq(Math.sqrt(2))
end
it 'should return 10 when given (4,6) and (10,14)' do
point1 = Geometry::Point.new(4,6)
point2 = Geometry::Point.new(10,14)
expect(point1.distance(point2)).to eq(10)
end
it 'should return same value when the order of points reversed' do
point1 = Geometry::Point.new(4,6)
point2 = Geometry::Point.new(10,14)
expect(point1.distance(point2)).to eq(point2.distance(point1))
end
end
end
Add extra spec to Point#distance method to test when one or more of the co-ordinates are float numbers.
describe Geometry::Point do
describe '.initialize' do
it 'should create a point when given co-ordinates' do
expect{
Geometry::Point.new(2,3)
}.not_to raise_exception
end
it 'should be readable' do
point = Geometry::Point.new(5,8)
expect(point.abscissa).to eq(5)
expect(point.ordinate).to eq(8)
end
it 'should not be writable' do
point = Geometry::Point.new(0,0)
expect{
point.ordinate = 4
point.abscissa = 5
}.to raise_error(NoMethodError)
end
end
describe '#equality (==)' do
it 'should be unequal when their attributes are unequal' do
point1 = Geometry::Point.new(5,2)
point2 = Geometry::Point.new(5,1)
expect(point1 == point2).to be_falsey
end
it 'should be equal when their attributes are equal' do
point1 = Geometry::Point.new(5,2)
expect(point1 == point1).to be_truthy
end
it 'should return true for two points when checked for Symmetric property of equality' do
point1 = Geometry::Point.new(2,2)
point2 = Geometry::Point.new(2,2)
expect(point1 == point2 && point2 == point1).to be_truthy
end
it 'should return true for three points when checked for transitive property of equality' do
point1 = Geometry::Point.new(2,2)
point2 = Geometry::Point.new(2,2)
point3 = Geometry::Point.new(2,2)
expect((point1 == point2 && point2 == point3) && point1 == point3).to be_truthy
end
it 'should not be equal to any object of different type' do
point1 = Geometry::Point.new(2,2)
point2 = Object.new
expect(point1 == point2).to be_falsey
end
it 'should not be equal to nil' do
point1 = Geometry::Point.new(2,2)
point2 = nil
expect(point1 == point2).to be_falsey
end
end
describe '#distance' do
it 'should return square root of 2 when given (0,0) and (1,1)' do
point1 = Geometry::Point.new(0,0)
point2 = Geometry::Point.new(1,1)
expect(point1.distance(point2)).to eq(Math.sqrt(2))
end
it 'should return 10 when given (4,6) and (10,14)' do
point1 = Geometry::Point.new(4,6)
point2 = Geometry::Point.new(10,14)
expect(point1.distance(point2)).to eq(10)
end
it 'should return same value when the order of points reversed' do
point1 = Geometry::Point.new(4,6)
point2 = Geometry::Point.new(10,14)
expect(point1.distance(point2)).to eq(point2.distance(point1))
end
it 'should return square root of 10.09 when given (1.5, 2) and (3, 4.8)' do
point1 = Geometry::Point.new(1.5, 2)
point2 = Geometry::Point.new(3, 4.8)
expect(point1.distance(point2)).to eq(Math.sqrt(10.09))
end
end
end |
require 'middleman-core'
module Middleman
module S3Sync
class Options < Struct.new(
:prefix,
:bucket,
:region,
:aws_access_key_id,
:aws_secret_access_key,
:after_build,
:delete,
:existing_remote_file,
:build_dir,
:force
)
def add_caching_policy(content_type, options)
caching_policies[content_type.to_s] = BrowserCachePolicy.new(options)
end
def caching_policy_for(content_type)
caching_policies.fetch(content_type.to_s, caching_policies[:default])
end
def default_caching_policy
caching_policies[:default]
end
def caching_policies
@caching_policies ||= Map.new
end
protected
class BrowserCachePolicy
attr_accessor :policies
def initialize(options)
@policies = Map.from_hash(options)
end
def cache_control
policy = []
policy << "max-age=#{policies.max_age}" if policies.has_key?(:max_age)
policy << "s-maxage=#{s_maxage}" if policies.has_key?(:s_maxage)
policy << "public" if policies.fetch(:public, false)
policy << "private" if policies.fetch(:private, false)
policy << "no-cache" if policies.fetch(:no_cache, false)
policy << "no-store" if policies.fetch(:no_store, false)
policy << "must-revalidate" if policies.fetch(:must_revalidate, false)
policy << "proxy-revalidate" if policies.fetch(:proxy_revalidate, false)
if policy.empty?
nil
else
policy.join(", ")
end
end
def expires
if expiration = policies.fetch(:expires, nil)
CGI.rfc1123_date(expiration)
end
end
end
end
class << self
def options
@@options
end
def registered(app, options_hash = {}, &block)
options = Options.new(options_hash)
yield options if block_given?
@@options = options
app.send :include, Helpers
app.after_configuration do |config|
options.build_dir ||= build_dir
end
app.after_build do |builder|
::Middleman::S3Sync.sync if options.after_build
end
end
alias :included :registered
module Helpers
def options
::Middleman::S3Sync.options
end
def default_caching_policy(policy = {})
options.add_caching_policy(:default, policy)
end
def caching_policy(content_type, policy = {})
options.add_caching_policy(content_type, policy)
end
end
end
end
end
Requiring Map.
require 'middleman-core'
require 'map'
module Middleman
module S3Sync
class Options < Struct.new(
:prefix,
:bucket,
:region,
:aws_access_key_id,
:aws_secret_access_key,
:after_build,
:delete,
:existing_remote_file,
:build_dir,
:force
)
def add_caching_policy(content_type, options)
caching_policies[content_type.to_s] = BrowserCachePolicy.new(options)
end
def caching_policy_for(content_type)
caching_policies.fetch(content_type.to_s, caching_policies[:default])
end
def default_caching_policy
caching_policies[:default]
end
def caching_policies
@caching_policies ||= Map.new
end
protected
class BrowserCachePolicy
attr_accessor :policies
def initialize(options)
@policies = Map.from_hash(options)
end
def cache_control
policy = []
policy << "max-age=#{policies.max_age}" if policies.has_key?(:max_age)
policy << "s-maxage=#{s_maxage}" if policies.has_key?(:s_maxage)
policy << "public" if policies.fetch(:public, false)
policy << "private" if policies.fetch(:private, false)
policy << "no-cache" if policies.fetch(:no_cache, false)
policy << "no-store" if policies.fetch(:no_store, false)
policy << "must-revalidate" if policies.fetch(:must_revalidate, false)
policy << "proxy-revalidate" if policies.fetch(:proxy_revalidate, false)
if policy.empty?
nil
else
policy.join(", ")
end
end
def expires
if expiration = policies.fetch(:expires, nil)
CGI.rfc1123_date(expiration)
end
end
end
end
class << self
def options
@@options
end
def registered(app, options_hash = {}, &block)
options = Options.new(options_hash)
yield options if block_given?
@@options = options
app.send :include, Helpers
app.after_configuration do |config|
options.build_dir ||= build_dir
end
app.after_build do |builder|
::Middleman::S3Sync.sync if options.after_build
end
end
alias :included :registered
module Helpers
def options
::Middleman::S3Sync.options
end
def default_caching_policy(policy = {})
options.add_caching_policy(:default, policy)
end
def caching_policy(content_type, policy = {})
options.add_caching_policy(content_type, policy)
end
end
end
end
end
|
module ModernResumeTheme
VERSION = "1.4.0"
end
Bumped to version 1.5
module ModernResumeTheme
VERSION = "1.5.0"
end
|
#
# Copyright 2015, Noah Kantrowitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
describe PoiseBoiler::Helpers::Rake::Travis do
rakefile "require 'poise_boiler/rakefile'"
rake_task 'travis'
file 'example.gemspec', <<-EOH
Gem::Specification.new do |s|
s.name = 'example'
s.version = '1.0.0'
end
EOH
file '.kitchen.yml', <<-EOH
driver:
name: dummy
provisioner:
name: dummy
platforms:
- name: default
suites:
- name: default
EOH
file 'README.md'
context 'no secure vars' do
environment TRAVIS_SECURE_ENV_VARS: ''
its(:stdout) { is_expected.to include 'Running task spec' }
its(:stdout) { is_expected.to include 'Running task chef:foodcritic' }
its(:stdout) { is_expected.to_not include 'Running task travis:integration' }
its(:exitstatus) { is_expected.to eq 0 }
end # /context no secure vars
context 'secure vars' do
environment TRAVIS_SECURE_ENV_VARS: '1', KITCHEN_DOCKER_PASS: 'secret'
file 'test/docker/docker.pem', <<-EOH
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,AE2AED599B3951C641A08DBEA9584DDC
jxqeiXKaX5vJvU9j5sN7ejykQ37dCd5xzuDMCNmEvS330shqQUA1k5NfexviQzHU
3xaDiFwXloNJBY6bmOoYF/Jy23J6eDr0D5L6lvDFjMRObu2Qe1bRSY1cxL+ttoBz
GPUL8Zp8xKisne13XBS2BWLwj+tatE8e1UJNd17nc1kdDIlOaCpvHQ44DVhTRvsO
wg7oiCHdj7xNaZBzLzXTxuGywFtegPwKYZRIFpMIftk4BY0M0X2IZkpCAIZkhukz
tIDPqsJMGeVSAAdcQUH278IAnjlyrSfLWjRnTwJyla8M62uCl2bW12UrqmBYbfy1
twQGF9ZTAk/9SBGvoedhJ0+lwyG8KoBPToZn0q6M1WtGlvOzcZUhHnuJPQte8Ka8
sHLkIjKj6IQVu+WaMTFML7sKHgvum9mCgMFP3BVn01wUcuAby+tQuO6xlTuXiz07
yvsVBr5TpoVzhCsxOrt/pj/2P3FwqSs0Ww9CMpZOF2sMTAiKYqMCIqTGP+BuIBAO
9Nn7RQcShxKvj/0SadUDO33XZlBJU3XY0lJkbHBS8znCOSGoabCeaxHlatdgTw2i
6Fxutc4PnMY72GWuhUYrWP0SwyUUnK+TFzGn6QddoHpu812ADRAFMIp4+B9AYcHA
Jku+btM0firmK2F9ZEKWAzd6iinVLAZ8gunr4sjNS4Mp+iP9GNC7iOdItzE3Trxm
GYc8g9og6OTx2qWEfS1Gfn1GyoVwZcTZ7jujVGicXYWuvuiAzD/YoNQjCxdlfGhM
cq4Weg3fUufmZ3XCGT4eCHl7Cu6pXP6NsrGjHAKbpL5S8kv8WSso3AEfdX9wu5wd
dGlqFg442Muz3cClAzDDgpC+eZBbDgLrpYnSzSYDiB3Nk8JKgtrWYa8Ytkn178D6
VYlyqat71YsqCpVfzESuoSnQcDOn8hoX1cqTQKrwBCc+iaVjJ+uPdaOYGUSndSXo
CViJI4IgUXfGvmrzqqeSMkxog13MrnZxqZ3alTSHTXIIJSNR/tl19t45Pm2+Fczt
VtU5Xu2+CddAARaW7qhm8R/0XfW72ZHWEf1D+ruRWXUGLp/EHMtj/p1jpYtdjWyH
azF97O+Pdww2/rvNa5ccbAtcNHXLRGM3PyXijGoF7oEXFRI5Q6+9UaBg0XteWKB4
wGia0wft8yNRbUQuzh8XBop6TGe/WWN1RfpZ4C0deWE7DE664RtATip3hMwub307
7v9g0dfoxCZuD9f9cvW1u7kQb+JHb6et9skyeZL8wDEVWqEHCCceOWYvs/C2+jRw
SjdyjtrJBDlqaXYaW4TXDn0dAtgQ3R6RGyQ/EQ5bbbbmA/npLKr6gFnQwABVVsK/
UqN9VDCI41RSFqrx48aFLYCmxVojS91cGx/QRAH38qGnwgqN13Y3Td0jZ9Mekl0Y
98JAi+1LSRWjhFZeH4Z5I0b4jHzL7/rlZxPdJY0KloC7a3p0yn3otpBk691Clvy6
K3wpVjHkvqXmmHaCDi9PYXd6Sxma9C8tO0uZIkDnyt6UxHhVbhJSkBD7eBugIPqz
Z45ph63rTFAl99gz8F7Ngr+RtE0r0Sabo7oToEbWG47enDkbHvRDBmrMfMbpM8La
JhxZYzc8XcZScBZFMp6mCkfntejjCjmfUODieogst2yB1ONYtfaXPZ/zuVShXlmK
AA/eYzDVPct5blRblyAE0FhE+9u5jAllDb+VSiPrcasXo6MSj7XfRomqIzPqMHcq
8ZtZz56zsG3fmuCJXbOJXjO3eRYD+rrmMdBg4DRu7vGOyC5HcloZFxW10JzN/wr7
AYe/lOeacbZAqCnaL3V4Bf72NWih+4xHA57pooqhrodW52egGgVxD3udGM9nFYPR
Rtof1n0ed3rl9vJC7Dx/ZPX6e1krCdOAAr5cYVKUNAKkMv+BjA2jYqY5jM+MRxHm
H5mut0H9RqMR91BcYIqG3/1fuDeRF5r7TKYFiSAd/MxijONi38z8gvtEMNt9CrSD
jz142Mb13faEKdc4bjbBeBaCCkPm0e9Ka4cVPWEaema5xjO8lg07MdUnr6mKyf2J
UVjrITLPqg2zN5K40AKK748C5sC7ra4F2Izn0noCcwinYyBg53W+x/G/tLywkKfv
5h4dpLfZ+Z20/IQDV4fqDh8Gv7BkTK8lLRhazzqO7tGkKQ89WgWEeYgzLMuT8AEU
q12OZTKJhJ2IqHNdSLOmXR3aroT6NVWQASB5A48u2eOedjVtFVkIKFx1BHWJnSmS
qlBGfKaA71f9G/7mG7wYjPvxLH8wtL64oiHaY/w4mC2IhOWzG/mePF7d1ALqCFss
zNpZc3hx7DsH9wcN3QFcbQCrxRCjhI8qwTgStU4IIFvxHzY7dFX7YirvLShWQt9u
YfVqx5h/TdkGtLtWz2FM0lp079lNCYXc7+ZIBy7Ma1u+qRVlxwe/dhv6YpXfT+Tv
jOG1HDSMvethWJRN0aayVWC9Xv4+8hDj0h6l92UpDwWz3nlQDvk8VFDmnPCpJgtq
Qv15nb8Eh+CDx9tItPtiv1DThQC+seqaz+UmGx7DPNoG+4Cq3PYXUfPOlibeGwYJ
/rTxJJz5pfEthBUTP+r53Yk5fabiDx25vDn041dhzFXJEHECG/KWafiQJ20oKPNe
6EEhgZkfpN5v1xZl6I/NP7MqryMn5OdiZ2Sz6h4TR0hqgCNWz7TBLMqFIdcWUit+
rsd0bCmQuwWDv2rW9HqQd+D3xqHR18BBLNVvNy7QFgOyvAZel+uh+Gvopri3Czqe
sGVszNE1VjIRPSSqi92/tuwsfsnC/B0/X2OeXqDzlbP+UENrblW7OmSvRWYHdzwC
gwXKPnqk1Cqy8nreQaiNCHrmblDZ4/PsTjbGt/cjOgT5xfFYBqk5O7S1aUMwR2zh
wCpMX4SHzwX+Kxq1fkjlKN6DWbzJU/XTqp9MdHtsVPDLqhWU7v+rZ1+W1t1taQtC
44y4GucYAoBqfqBfE5rd4k2oHHb+zkODoN8B96zoLpigbBd3eRpd7oAY5v0Ae94o
kZ24dsHjCt68RmJqriz8GHZY+0SjFRFand6FZaBTLndSnqfoncHgj1Cbq2E+pNQm
UbWRwbhlKYyN9bgK47cxD7r39KRh3jAkiTcMlscquirkZTuyWj5INTn/g2ICIg5w
-----END RSA PRIVATE KEY-----
EOH
its(:stdout) { is_expected.to include 'Running task spec' }
its(:stdout) { is_expected.to include 'Running task chef:foodcritic' }
if (ENV['BUNDLE_GEMFILE'] || '').include?('master')
its(:stdout) { is_expected.to_not include 'Running task travis:integration' }
else
its(:stdout) { is_expected.to include 'Running task travis:integration' }
end
its(:exitstatus) { is_expected.to eq 0 }
end # /context secure vars
context 'secure vars and Rackspace' do
file '.kitchen.travis.yml', 'name: rackspace'
file '.ssh/stub'
environment TRAVIS_SECURE_ENV_VARS: '1'
before do
_environment['HOME'] = temp_path
end
its(:stdout) { is_expected.to include 'Running task spec' }
its(:stdout) { is_expected.to include 'Running task chef:foodcritic' }
if (ENV['BUNDLE_GEMFILE'] || '').include?('master')
its(:stdout) { is_expected.to_not include 'Running task travis:integration' }
else
its(:stdout) { is_expected.to include 'Running task travis:integration' }
end
its(:exitstatus) { is_expected.to eq 0 }
end
end
Travis uses false not ''.
#
# Copyright 2015, Noah Kantrowitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
describe PoiseBoiler::Helpers::Rake::Travis do
rakefile "require 'poise_boiler/rakefile'"
rake_task 'travis'
file 'example.gemspec', <<-EOH
Gem::Specification.new do |s|
s.name = 'example'
s.version = '1.0.0'
end
EOH
file '.kitchen.yml', <<-EOH
driver:
name: dummy
provisioner:
name: dummy
platforms:
- name: default
suites:
- name: default
EOH
file 'README.md'
context 'no secure vars' do
environment TRAVIS_SECURE_ENV_VARS: 'false'
its(:stdout) { is_expected.to include 'Running task spec' }
its(:stdout) { is_expected.to include 'Running task chef:foodcritic' }
its(:stdout) { is_expected.to_not include 'Running task travis:integration' }
its(:exitstatus) { is_expected.to eq 0 }
end # /context no secure vars
context 'secure vars' do
environment TRAVIS_SECURE_ENV_VARS: '1', KITCHEN_DOCKER_PASS: 'secret'
file 'test/docker/docker.pem', <<-EOH
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,AE2AED599B3951C641A08DBEA9584DDC
jxqeiXKaX5vJvU9j5sN7ejykQ37dCd5xzuDMCNmEvS330shqQUA1k5NfexviQzHU
3xaDiFwXloNJBY6bmOoYF/Jy23J6eDr0D5L6lvDFjMRObu2Qe1bRSY1cxL+ttoBz
GPUL8Zp8xKisne13XBS2BWLwj+tatE8e1UJNd17nc1kdDIlOaCpvHQ44DVhTRvsO
wg7oiCHdj7xNaZBzLzXTxuGywFtegPwKYZRIFpMIftk4BY0M0X2IZkpCAIZkhukz
tIDPqsJMGeVSAAdcQUH278IAnjlyrSfLWjRnTwJyla8M62uCl2bW12UrqmBYbfy1
twQGF9ZTAk/9SBGvoedhJ0+lwyG8KoBPToZn0q6M1WtGlvOzcZUhHnuJPQte8Ka8
sHLkIjKj6IQVu+WaMTFML7sKHgvum9mCgMFP3BVn01wUcuAby+tQuO6xlTuXiz07
yvsVBr5TpoVzhCsxOrt/pj/2P3FwqSs0Ww9CMpZOF2sMTAiKYqMCIqTGP+BuIBAO
9Nn7RQcShxKvj/0SadUDO33XZlBJU3XY0lJkbHBS8znCOSGoabCeaxHlatdgTw2i
6Fxutc4PnMY72GWuhUYrWP0SwyUUnK+TFzGn6QddoHpu812ADRAFMIp4+B9AYcHA
Jku+btM0firmK2F9ZEKWAzd6iinVLAZ8gunr4sjNS4Mp+iP9GNC7iOdItzE3Trxm
GYc8g9og6OTx2qWEfS1Gfn1GyoVwZcTZ7jujVGicXYWuvuiAzD/YoNQjCxdlfGhM
cq4Weg3fUufmZ3XCGT4eCHl7Cu6pXP6NsrGjHAKbpL5S8kv8WSso3AEfdX9wu5wd
dGlqFg442Muz3cClAzDDgpC+eZBbDgLrpYnSzSYDiB3Nk8JKgtrWYa8Ytkn178D6
VYlyqat71YsqCpVfzESuoSnQcDOn8hoX1cqTQKrwBCc+iaVjJ+uPdaOYGUSndSXo
CViJI4IgUXfGvmrzqqeSMkxog13MrnZxqZ3alTSHTXIIJSNR/tl19t45Pm2+Fczt
VtU5Xu2+CddAARaW7qhm8R/0XfW72ZHWEf1D+ruRWXUGLp/EHMtj/p1jpYtdjWyH
azF97O+Pdww2/rvNa5ccbAtcNHXLRGM3PyXijGoF7oEXFRI5Q6+9UaBg0XteWKB4
wGia0wft8yNRbUQuzh8XBop6TGe/WWN1RfpZ4C0deWE7DE664RtATip3hMwub307
7v9g0dfoxCZuD9f9cvW1u7kQb+JHb6et9skyeZL8wDEVWqEHCCceOWYvs/C2+jRw
SjdyjtrJBDlqaXYaW4TXDn0dAtgQ3R6RGyQ/EQ5bbbbmA/npLKr6gFnQwABVVsK/
UqN9VDCI41RSFqrx48aFLYCmxVojS91cGx/QRAH38qGnwgqN13Y3Td0jZ9Mekl0Y
98JAi+1LSRWjhFZeH4Z5I0b4jHzL7/rlZxPdJY0KloC7a3p0yn3otpBk691Clvy6
K3wpVjHkvqXmmHaCDi9PYXd6Sxma9C8tO0uZIkDnyt6UxHhVbhJSkBD7eBugIPqz
Z45ph63rTFAl99gz8F7Ngr+RtE0r0Sabo7oToEbWG47enDkbHvRDBmrMfMbpM8La
JhxZYzc8XcZScBZFMp6mCkfntejjCjmfUODieogst2yB1ONYtfaXPZ/zuVShXlmK
AA/eYzDVPct5blRblyAE0FhE+9u5jAllDb+VSiPrcasXo6MSj7XfRomqIzPqMHcq
8ZtZz56zsG3fmuCJXbOJXjO3eRYD+rrmMdBg4DRu7vGOyC5HcloZFxW10JzN/wr7
AYe/lOeacbZAqCnaL3V4Bf72NWih+4xHA57pooqhrodW52egGgVxD3udGM9nFYPR
Rtof1n0ed3rl9vJC7Dx/ZPX6e1krCdOAAr5cYVKUNAKkMv+BjA2jYqY5jM+MRxHm
H5mut0H9RqMR91BcYIqG3/1fuDeRF5r7TKYFiSAd/MxijONi38z8gvtEMNt9CrSD
jz142Mb13faEKdc4bjbBeBaCCkPm0e9Ka4cVPWEaema5xjO8lg07MdUnr6mKyf2J
UVjrITLPqg2zN5K40AKK748C5sC7ra4F2Izn0noCcwinYyBg53W+x/G/tLywkKfv
5h4dpLfZ+Z20/IQDV4fqDh8Gv7BkTK8lLRhazzqO7tGkKQ89WgWEeYgzLMuT8AEU
q12OZTKJhJ2IqHNdSLOmXR3aroT6NVWQASB5A48u2eOedjVtFVkIKFx1BHWJnSmS
qlBGfKaA71f9G/7mG7wYjPvxLH8wtL64oiHaY/w4mC2IhOWzG/mePF7d1ALqCFss
zNpZc3hx7DsH9wcN3QFcbQCrxRCjhI8qwTgStU4IIFvxHzY7dFX7YirvLShWQt9u
YfVqx5h/TdkGtLtWz2FM0lp079lNCYXc7+ZIBy7Ma1u+qRVlxwe/dhv6YpXfT+Tv
jOG1HDSMvethWJRN0aayVWC9Xv4+8hDj0h6l92UpDwWz3nlQDvk8VFDmnPCpJgtq
Qv15nb8Eh+CDx9tItPtiv1DThQC+seqaz+UmGx7DPNoG+4Cq3PYXUfPOlibeGwYJ
/rTxJJz5pfEthBUTP+r53Yk5fabiDx25vDn041dhzFXJEHECG/KWafiQJ20oKPNe
6EEhgZkfpN5v1xZl6I/NP7MqryMn5OdiZ2Sz6h4TR0hqgCNWz7TBLMqFIdcWUit+
rsd0bCmQuwWDv2rW9HqQd+D3xqHR18BBLNVvNy7QFgOyvAZel+uh+Gvopri3Czqe
sGVszNE1VjIRPSSqi92/tuwsfsnC/B0/X2OeXqDzlbP+UENrblW7OmSvRWYHdzwC
gwXKPnqk1Cqy8nreQaiNCHrmblDZ4/PsTjbGt/cjOgT5xfFYBqk5O7S1aUMwR2zh
wCpMX4SHzwX+Kxq1fkjlKN6DWbzJU/XTqp9MdHtsVPDLqhWU7v+rZ1+W1t1taQtC
44y4GucYAoBqfqBfE5rd4k2oHHb+zkODoN8B96zoLpigbBd3eRpd7oAY5v0Ae94o
kZ24dsHjCt68RmJqriz8GHZY+0SjFRFand6FZaBTLndSnqfoncHgj1Cbq2E+pNQm
UbWRwbhlKYyN9bgK47cxD7r39KRh3jAkiTcMlscquirkZTuyWj5INTn/g2ICIg5w
-----END RSA PRIVATE KEY-----
EOH
its(:stdout) { is_expected.to include 'Running task spec' }
its(:stdout) { is_expected.to include 'Running task chef:foodcritic' }
if (ENV['BUNDLE_GEMFILE'] || '').include?('master')
its(:stdout) { is_expected.to_not include 'Running task travis:integration' }
else
its(:stdout) { is_expected.to include 'Running task travis:integration' }
end
its(:exitstatus) { is_expected.to eq 0 }
end # /context secure vars
context 'secure vars and Rackspace' do
file '.kitchen.travis.yml', 'name: rackspace'
file '.ssh/stub'
environment TRAVIS_SECURE_ENV_VARS: '1'
before do
_environment['HOME'] = temp_path
end
its(:stdout) { is_expected.to include 'Running task spec' }
its(:stdout) { is_expected.to include 'Running task chef:foodcritic' }
if (ENV['BUNDLE_GEMFILE'] || '').include?('master')
its(:stdout) { is_expected.to_not include 'Running task travis:integration' }
else
its(:stdout) { is_expected.to include 'Running task travis:integration' }
end
its(:exitstatus) { is_expected.to eq 0 }
end
end
|
require "zlib"
require 'pp'
# Methods used in the ApiLoc publication
class BScript
def apiloc_stats
puts "For each species, how many genes, publications"
total_proteins = 0
total_publications = 0
Species.apicomplexan.all.sort{|a,b| a.name <=> b.name}.each do |s|
protein_count = s.number_of_proteins_localised_in_apiloc
publication_count = s.number_of_publications_in_apiloc
puts [
s.name,
protein_count,
publication_count,
].join("\t")
total_proteins += protein_count
total_publications += publication_count
end
puts [
'Total',
total_proteins,
total_publications
].join("\t")
end
# Like HTML stats, but used for the version information part
# of the ApiLoc website
def apiloc_html_stats
total_proteins = 0
total_publications = 0
puts '<table>'
puts '<tr><th>Species</th><th>Localised genes</th><th>Publications curated</th></tr>'
Species.apicomplexan.all.push.sort{|a,b| a.name <=> b.name}.each do |s|
protein_count = s.number_of_proteins_localised_in_apiloc
publication_count = s.number_of_publications_in_apiloc
puts "<tr><td><i>#{s.name}</i></td><td>#{protein_count}</td><td>#{publication_count}</td></tr>"
total_proteins += protein_count
total_publications += publication_count
end
print [
'<tr><td><b>Total</b>',
total_proteins,
total_publications
].join("</b></td><td><b>")
puts '</b></td></tr>'
puts '</table>'
end
def species_localisation_breakdown
# names = Localisation.all(:joins => :apiloc_top_level_localisation).reach.name.uniq.push(nil)
# print "species\t"
# puts names.join("\t")
top_names = [
'apical',
'inner membrane complex',
'merozoite surface',
'parasite plasma membrane',
'parasitophorous vacuole',
'exported',
'cytoplasm',
'food vacuole',
'mitochondrion',
'apicoplast',
'golgi',
'endoplasmic reticulum',
'other',
'nucleus'
]
interests = [
'Plasmodium falciparum',
'Toxoplasma gondii',
'Plasmodium berghei',
'Cryptosporidium parvum'
]
puts [nil].push(interests).flatten.join("\t")
top_names.each do |top_name|
top = TopLevelLocalisation.find_by_name(top_name)
print top_name
interests.each do |name|
s = Species.find_by_name(name)
if top.name == 'other'
count = 0
CodingRegion.all(
:select => 'distinct(coding_regions.id)',
:joins => {:expression_contexts => {:localisation => :apiloc_top_level_localisation}},
:conditions => ['top_level_localisation_id = ? and species_id = ?', top.id, s.id]
).each do |code|
tops = code.expressed_localisations.reach.apiloc_top_level_localisation.flatten
if tops.length == 1
raise unless tops[0].name == 'other'
count += 1
end
end
print "\t#{count}"
else
count = CodingRegion.count(
:select => 'distinct(coding_regions.id)',
:joins => {:expression_contexts => {:localisation => :apiloc_top_level_localisation}},
:conditions => ['top_level_localisation_id = ? and species_id = ?', top.id, s.id]
)
print "\t#{count}"
end
end
puts
end
end
def how_many_falciparum_genes_have_toxo_orthologs
puts ".. all according to orthomcl #{OrthomclRun::ORTHOMCL_OFFICIAL_NEWEST_NAME}"
all_orthomcl_groups_with_falciparum = OrthomclRun.find_by_name(OrthomclRun::ORTHOMCL_OFFICIAL_NEWEST_NAME).orthomcl_groups.select {|group|
group.orthomcl_genes.code('pfa').count > 0
}
puts "How many P. falciparum orthomcl groups?"
puts all_orthomcl_groups_with_falciparum.length
numbers_of_orthologs = all_orthomcl_groups_with_falciparum.each do |group|
group.orthomcl_genes.code('tgo').count
end
puts
puts "How many P. falciparum genes have any toxo orthomcl orthologs?"
puts numbers_of_orthologs.reject {|num|
num == 0
}.length
puts
puts "How many P. falciparum genes have 1 to 1 mapping with toxo?"
puts all_orthomcl_groups_with_falciparum.select {|group|
group.orthomcl_genes.code('pfa') == 1 and group.orthomcl_genes.code('tgo') == 1
}
end
def distribution_of_falciparum_hits_given_toxo
toxo_only = []
falc_only = []
no_hits = []
hits_not_localised = []
falc_and_toxo = []
# why the hell doesn't bioruby do this for me?
falciparum_blasts = {}
toxo_blasts = {}
# convert the blast file as it currently exists into a hash of plasmodb => blast_hits
Bio::Blast::Report.new(
File.open("#{PHD_DIR}/apiloc/experiments/falciparum_vs_toxo_blast/falciparum_v_toxo.1e-5.tab.out",'r').read,
:tab
).iterations[0].hits.each do |hit|
q = hit.query_id.gsub(/.*\|/,'')
s = hit.definition.gsub(/.*\|/,'')
falciparum_blasts[q] ||= []
falciparum_blasts[q].push s
end
Bio::Blast::Report.new(
File.open("#{PHD_DIR}/apiloc/experiments/falciparum_vs_toxo_blast/toxo_v_falciparum.1e-5.tab.out",'r').read,
:tab
).iterations[0].hits.each do |hit|
q = hit.query_id.gsub(/.*\|/,'')
s = hit.definition.gsub(/.*\|/,'')
toxo_blasts[q] ||= []
toxo_blasts[q].push s
end
# On average, how many hits does the toxo gene have to falciparum given
# arbitrary 1e-5 cutoff?
# File.open("#{PHD_DIR}/apiloc/experiments/falciparum_to_toxo_how_many_hits.csv",'w') do |how_many_hits|
# File.open("#{PHD_DIR}/apiloc/experiments/falciparum_to_toxo_best_evalue.csv",'w') do |best_evalue|
File.open("#{PHD_DIR}/apiloc/experiments/falciparum_to_toxo_best_evalue.csv", 'w') do |loc_comparison|
blast_hits = CodingRegion.s(Species::FALCIPARUM_NAME).all(
:joins => :amino_acid_sequence,
:include => {:expression_contexts => :localisation}
# :limit => 10,
# :conditions => ['string_id = ?', 'PF13_0280']
).collect do |falciparum|
# does this falciparum have a hit?
# compare localisation of the falciparum and toxo protein
falciparum_locs = falciparum.expression_contexts.reach.localisation.reject{|l| l.nil?}
toxo_ids = falciparum_blasts[falciparum.string_id]
toxo_ids ||= []
toxos = toxo_ids.collect do |toxo_id|
t = CodingRegion.find_by_name_or_alternate_and_species(toxo_id, Species::TOXOPLASMA_GONDII)
raise unless t
t
end
toxo_locs = toxos.collect {|toxo|
toxo.expression_contexts.reach.localisation.retract
}.flatten.reject{|l| l.nil?}
if toxos.length > 0
# protein localised in falciparum but not in toxo
if !falciparum_locs.empty? and !toxo_locs.empty?
loc_comparison.puts [
falciparum.string_id,
falciparum.annotation.annotation,
falciparum.localisation_english
].join("\t")
toxos.each do |toxo|
loc_comparison.puts [
toxo.string_id,
toxo.annotation.annotation,
toxo.localisation_english
].join("\t")
end
loc_comparison.puts
falc_and_toxo.push [falciparum, toxos]
end
# stats about how well the protein is localised
if toxo_locs.empty? and !falciparum_locs.empty?
falc_only.push [falciparum, toxos]
end
if !toxo_locs.empty? and falciparum_locs.empty?
toxo_only.push [falciparum, toxos]
end
if toxo_locs.empty? and falciparum_locs.empty?
hits_not_localised.push falciparum.string_id
end
else
no_hits.push falciparum.string_id
end
end
end
puts "How many genes are localised in toxo and falciparum?"
puts falc_and_toxo.length
puts
puts "How many genes are localised in toxo but not in falciparum?"
puts toxo_only.length
puts
puts "How many genes are localised in falciparum but not in toxo?"
puts falc_only.length
puts
puts "How many falciparum genes have no toxo hit?"
puts no_hits.length
puts
puts "How many have hits but are not localised?"
puts hits_not_localised.length
puts
end
def tgo_v_pfa_crossover_count
both = OrthomclGroup.all_overlapping_groups(%w(tgo pfa))
pfa = OrthomclGroup.all_overlapping_groups(%w(pfa))
tgo = OrthomclGroup.all_overlapping_groups(%w(tgo))
both_genes_pfa = both.collect{|b| b.orthomcl_genes.codes(%w(pfa)).count(:select => 'distinct(orthomcl_genes.id)')}.sum
both_genes_tgo = both.collect{|b| b.orthomcl_genes.codes(%w(tgo)).count(:select => 'distinct(orthomcl_genes.id)')}.sum
pfa_genes = CodingRegion.s(Species::FALCIPARUM).count(:joins => :amino_acid_sequence)
tgo_genes = CodingRegion.s(Species::TOXOPLASMA_GONDII).count(:joins => :amino_acid_sequence)
puts "How many OrthoMCL groups have at least one protein in pfa and tgo?"
puts "#{both.length} groups, #{both_genes_pfa} falciparum genes, #{both_genes_tgo} toxo genes"
puts
puts "How many OrthoMCL groups are specific to falciparum?"
puts "#{pfa.length - both.length} groups, #{pfa_genes - both_genes_pfa} genes"
puts
puts "How many OrthoMCL groups are specific to toxo?"
puts "#{tgo.length - both.length} groups, #{tgo_genes - both_genes_tgo} genes"
puts
end
# Print out a fasta file of all the sequences that are in apiloc.
# If a block is given it takes each coding region so that it can be transformed
# into a fasta sequence header as in AminiAcidSequence#fasta, otherwise
# a default is used.
def apiloc_fasta(io = $stdout)
CodingRegion.all(
:joins => :expression_contexts
).uniq.each do |code|
if code.amino_acid_sequence and code.amino_acid_sequence.sequence.length > 0
io.print ">"
if block_given?
io.puts yield(code)
else
io.puts [
code.species.name,
code.string_id,
code.annotation ? code.annotation.annotation : nil
].join(' | ')
end
io.puts code.amino_acid_sequence.sequence
else
$stderr.puts "Couldn't find amino acid sequence for #{code.string_id}/#{code.id}"
end
end
end
def apiloc_mapping_orthomcl_v3
# Starting with falciparum, how many genes have localised orthologues?
CodingRegion.falciparum.all(
:joins => {:expression_contexts => :localisation},
:select => 'distinct(coding_regions.*)'
).each do |code|
next if ["PF14_0078",'PF13_0011'].include?(code.string_id) #fair enough there is no orthomcl for this - just the way v3 is.
# Is this in orthomcl
ogene = nil
begin
ogene = code.single_orthomcl
rescue CodingRegion::UnexpectedOrthomclGeneCount
next
end
if ogene
groups = ogene.orthomcl_groups
raise unless groups.length == 1
group = groups[0]
others = group.orthomcl_genes.apicomplexan.all.reject{|r| r.id==ogene.id}
next if others.empty?
orthologues = CodingRegion.all(
:joins => [
{:expression_contexts => :localisation},
:orthomcl_genes,
],
:conditions => "orthomcl_genes.id in (#{others.collect{|o|o.id}.join(',')})",
:select => 'distinct(coding_regions.*)'
)
if orthologues.empty?
$stderr.puts "Nothing useful found for #{code.names.join(', ')}"
else
# output the whole group, including localisations where known
puts [
code.string_id,
code.case_sensitive_literature_defined_coding_region_alternate_string_ids.reach.name.join(', '),
code.annotation.annotation,
code.localisation_english
].join("\t")
group.orthomcl_genes.apicomplexan.all.each do |oge|
next if %w(cmur chom).include?(oge.official_split[0])
c = nil
if oge.official_split[1] == 'TGGT1_036620' #stupid v3
c = CodingRegion.find_by_name_or_alternate("TGME49_084810")
else
c = oge.single_code!
end
if c.nil?
# if no coding region is returned, then don't complain too much,
# but I will check these manually later
puts oge.orthomcl_name
else
next if c.id == code.id #don't duplicate the query
print c.string_id
puts [
nil,
c.case_sensitive_literature_defined_coding_region_alternate_string_ids.reach.name.join(', '),
c.annotation.annotation,
c.localisation_english
].join("\t")
end
end
puts
end
end
end
end
# Get all of the sequences that are recorded in ApiLoc and put them into
# a blast file where the hits can be identified using a -m 8 blast output
def create_apiloc_m8_ready_blast_database
File.open('/tmp/apiloc_m8_ready.protein.fa','w') do |file|
BScript.new.apiloc_fasta(file) do |code|
"#{code.species.name.gsub(' ','_')}|#{code.string_id}"
end
end
Dir.chdir('/tmp') do
`formatdb -i apiloc_m8_ready.protein.fa`
%w(
apiloc_m8_ready.protein.fa
apiloc_m8_ready.protein.fa.phr
apiloc_m8_ready.protein.fa.pin
apiloc_m8_ready.protein.fa.psq
).each do |filename|
`mv #{filename} /blastdb`
end
end
end
# Taking all the falciparum proteins, where are the orthologues localised?
def orthomcl_localisation_annotations
CodingRegion.falciparum.all(
:joins => :expressed_localisations,
:limit => 20,
:select => 'distinct(coding_regions.*)'
).each do |code|
begin
falciparum_orthomcl_gene = code.single_orthomcl
puts [
code.string_id,
code.annotation.annotation,
falciparum_orthomcl_gene.official_group.orthomcl_genes.code('scer').all.collect { |sceg|
sceg.single_code.coding_region_go_terms.useful.all.reach.go_term.term.join(', ')
}.join(' | ')
].join("\t")
rescue CodingRegion::UnexpectedOrthomclGeneCount => e
$stderr.puts "Couldn't map #{code.string_id}/#{code.annotation.annotation} to orthomcl"
end
end
end
def upload_apiloc_relevant_go_terms
require 'ensembl'
# create the species and dummy scaffolds, genes, etc.
# yeast should already be uploaded
# yeast = Species.find_or_create_by_name_and_orthomcl_three_letter(Species::YEAST_NAME, 'scer')
# human = Species.find_or_create_by_name_and_orthomcl_three_letter(Species::HUMAN_NAME, 'hsap')
# mouse = Species.find_or_create_by_name_and_orthomcl_three_letter(Species::MOUSE_NAME, 'mmus')
# mouse = Species.find_or_create_by_name_and_orthomcl_three_letter(Species::ELEGANS_NAME, 'cele')
gene = Gene.new.create_dummy('apiloc conservation dummy gene for multiple species')
ensembl_uniprot_db = ExternalDb.find_by_db_name("Uniprot/SWISSPROT")
# for each human, mouse, yeast gene in a group with a localised apicomplexan
# gene, get the go terms from Ensembl so we can start to compare them later
# OrthomclGroup.all(
ogroup = OrthomclGroup.first(
:joins => {
:orthomcl_gene_orthomcl_group_orthomcl_runs => [
:orthomcl_run,
{:orthomcl_gene => {:coding_regions => :expressed_localisations}}
]
},
:conditions => {
:orthomcl_runs => {:name => OrthomclRun::ORTHOMCL_OFFICIAL_VERSION_3_NAME}
}
)
# ).each do |ogroup|
ogroup.orthomcl_genes.codes(%w(hsap mmus scer cele)).all.each do |orthomcl_gene|
ensembl = OrthomclGene.new.official_split[1]
# fetch the uniprot ID from Ensembl
ensp = Ensembl::Core::Translation.find_by_stable_id(ensembl)
unless ensp
$stderr.puts "Couldn't find ensembl gene to match #{ensembl}, skipping"
next
end
# extract the uniprot id
uniprots = ensp.xrefs.select{|x| ensembl_uniprot_db.id == x.id}.collect{|x| x.db_primaryacc}.uniq
uniprot = uniprots[0]
unless uniprots.length == 1
$stderr.puts "Unexpected number of uniprot IDs found: #{uniprots.inspect}"
next if uniprots.empty?
end
# wget the uniprot txt file entry
filename = "/tmp/uniprot#{uniprot}.txt"
`wget http://www.uniprot.org/#{uniprot}.txt -O #{filename}`
# parse the uniprot entry
bio = Bio::Uniprot.new(File.open(filename).read)
p bio
# create the gene
# find the GO term that I've annnotated, otherwise add a new one, which
# will need to be filled in with the term
# add the relevant GO term and evidence code
# end
end
end
# not realyl working - too slow for me.
def map_using_uniprot_mapper
# require 'uni_prot_i_d_mapping_selected'
# mapper = Bio::UniProtIDMappingSelected.new
# ogroup =
OrthomclGroup.all(
# :limit => 5,
:joins => {
:orthomcl_gene_orthomcl_group_orthomcl_runs => [
:orthomcl_run,
{:orthomcl_gene => {:coding_regions => :expressed_localisations}}
]
},
:conditions => {
:orthomcl_runs => {:name => OrthomclRun::ORTHOMCL_OFFICIAL_VERSION_3_NAME}
}
# )
).each do |ogroup|
ogroup.orthomcl_genes.codes(%w(mmus)).all.each do |orthomcl_gene|
ensembl = orthomcl_gene.official_split[1]
puts ensembl
# mapped = mapper.find_by_ensembl_protein_id(ensembl)
# p mapped
end
end
end
def generate_biomart_to_go_input
{
'hsap' => 'human',
'mmus' => 'mouse',
'atha' => 'arabidopsis',
'dmel' => 'fly',
'cele' => 'worm',
'scer' => 'yeast',
'crei' => 'chlamydomonas',
'tthe' => 'tetrahymena',
'rnor' => 'rat',
'spom' => 'pombe',
}.each do |code, name|
$stderr.puts name
out = File.open("#{species_orthologue_folder}/#{name}.txt",'w')
OrthomclGroup.all(
:joins => {
:orthomcl_gene_orthomcl_group_orthomcl_runs => [
:orthomcl_run,
{:orthomcl_gene => {:coding_regions => :expressed_localisations}}
]
},
:conditions => {
:orthomcl_runs => {:name => OrthomclRun::ORTHOMCL_OFFICIAL_VERSION_3_NAME}
}
).uniq.each do |ogroup|
ogroup.orthomcl_genes.code(code).all.each do |orthomcl_gene|
ensembl = orthomcl_gene.official_split[1]
out.puts ensembl
end
end
end
end
# \
def species_orthologue_folder; "#{PHD_DIR}/apiloc/species_orthologues3"; end
# all the methods required to get from the biomart and uniprot
# id to GO term mappings to a spreadsheet that can be inspected for the
# localisations required.
def apiloc_gathered_output_to_generated_spreadsheet_for_inspection
upload_apiloc_ensembl_go_terms
upload_apiloc_uniprot_go_terms
upload_apiloc_uniprot_mappings
upload_apiloc_flybase_mappings
# for some reason a single refseq sequence can be linked to multiple uniprot sequences,
# which is stupid but something I'll have to live with
OrthomclGene.new.link_orthomcl_and_coding_regions(%w(atha), :accept_multiple_coding_regions=>true)
OrthomclGene.new.link_orthomcl_and_coding_regions(%w(hsap mmus dmel cele))
generate_apiloc_orthomcl_groups_for_inspection
end
def upload_apiloc_ensembl_go_terms
{
'human' => Species::HUMAN_NAME,
'mouse' => Species::MOUSE_NAME,
'rat' => Species::RAT_NAME,
}.each do |this_name, proper_name|
$stderr.puts this_name
FasterCSV.foreach("#{species_orthologue_folder}/biomart_results/#{this_name}.csv",
:col_sep => "\t",
:headers => true
) do |row|
protein_name = row['Ensembl Protein ID']
go_id = row['GO Term Accession (cc)']
evidence = row['GO Term Evidence Code (cc)']
next if go_id.nil? #ignore empty columns
code = CodingRegion.find_or_create_dummy(protein_name, proper_name)
go = GoTerm.find_by_go_identifier_or_alternate go_id
unless go
$stderr.puts "Couldn't find GO id #{go_id}"
next
end
CodingRegionGoTerm.find_or_create_by_coding_region_id_and_go_term_id_and_evidence_code(
code.id, go.id, evidence
) or raise
end
end
end
def upload_apiloc_uniprot_go_terms
{
'arabidopsis' => Species::ARABIDOPSIS_NAME,
'worm' => Species::ELEGANS_NAME,
'fly' => Species::DROSOPHILA_NAME
}.each do |this_name, proper_name|
File.open("#{species_orthologue_folder}/uniprot_results/#{this_name}.uniprot.txt").read.split("//\n").each do |uniprot|
u = Bio::UniProt.new(uniprot)
axes = u.ac
protein_name = axes[0]
raise unless protein_name
code = CodingRegion.find_or_create_dummy(protein_name, proper_name)
protein_alternate_names = axes[1..(axes.length-1)].no_nils
protein_alternate_names.each do |name|
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name(
code.id, name
) or raise
end
goes = u.dr["GO"]
next if goes.nil? #no go terms associated
goes.each do |go_array|
go_id = go_array[0]
evidence_almost = go_array[2]
evidence = nil
if (matches = evidence_almost.match(/^([A-Z]{2,3})\:.*$/))
evidence = matches[1]
end
# error checking
if evidence.nil?
raise Exception, "No evidence code found in #{go_array.inspect} from #{evidence_almost}!"
end
go = GoTerm.find_by_go_identifier_or_alternate go_id
unless go
$stderr.puts "Couldn't find GO id #{go_id}"
next
end
CodingRegionGoTerm.find_or_create_by_coding_region_id_and_go_term_id_and_evidence_code(
code.id, go.id, evidence
).save!
end
end
end
end
def upload_apiloc_uniprot_mappings
{
'arabidopsis' => Species::ARABIDOPSIS_NAME,
'worm' => Species::ELEGANS_NAME,
'fly' => Species::DROSOPHILA_NAME
}.each do |this_name, proper_name|
FasterCSV.foreach("#{species_orthologue_folder}/uniprot_results/#{this_name}.mapping.tab",
:col_sep => "\t", :headers => true
) do |row|
code = CodingRegion.fs(row[1], proper_name) or raise Exception, "Don't know #{row[1]}"
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name(
code.id, row[0]
)
end
end
end
# Drosophila won't match well to orthomcl because orthomcl uses protein IDs whereas
# uniprot uses gene ids.
# This file was created by using the (useful and working) ID converter in flybase
def upload_apiloc_flybase_mappings
FasterCSV.foreach("#{species_orthologue_folder}/uniprot_results/flybase.mapping.tab",
:col_sep => "\t"
) do |row|
next if row[1] == 'unknown ID' #ignore rubbish
gene_id = row[3]
next if gene_id == '-' # not sure what this is, but I'll ignore for the moment
protein_id = row[1]
code = CodingRegion.fs(gene_id, Species::DROSOPHILA_NAME)
if code.nil?
$stderr.puts "Couldn't find gene #{gene_id}, skipping"
next
end
CodingRegionAlternateStringId.find_or_create_by_name_and_coding_region_id(
protein_id, code.id
)
end
end
# Return a list of orthomcl groups that fulfil these conditions:
# 1. It has a localised apicomplexan gene in it, as recorded by ApiLoc
# 2. It has a localised non-apicomplexan gene in it, as recorded by GO CC IDA annotation
def apiloc_orthomcl_groups_of_interest
OrthomclGroup.all(
:select => 'distinct(orthomcl_groups.*)',
:joins => {
:orthomcl_gene_orthomcl_group_orthomcl_runs => [
:orthomcl_run,
{:orthomcl_gene => {:coding_regions => [
:expressed_localisations
]}}
]
},
:conditions => {
:orthomcl_runs => {:name => OrthomclRun::ORTHOMCL_OFFICIAL_VERSION_3_NAME},
}
).select do |ogroup|
# only select those groups that have go terms annotated in non-apicomplexan species
OrthomclGroup.count(
:joins => {:coding_regions =>[
:go_terms
]},
:conditions => ['orthomcl_groups.id = ? and coding_region_go_terms.evidence_code = ? and go_terms.partition = ?',
ogroup.id, 'IDA', GoTerm::CELLULAR_COMPONENT
]
) > 0
end
end
def generate_apiloc_orthomcl_groups_for_inspection
interestings = %w(hsap mmus scer drer osat crei atha dmel cele)
apiloc_orthomcl_groups_of_interest.each do |ogroup|
paragraph = []
ogroup.orthomcl_genes.all.each do |orthomcl_gene|
four = orthomcl_gene.official_split[0]
# Possible to have many coding regions now - using all of them just together, though there is
# probably one good one and other useless and IEA if anything annotated. Actually
# not necesssarilly, due to strain problems.
#
# Only print out one entry for each OrthoMCL gene, to condense things
# but that line should have all the (uniq) go terms associated
orthomcl_gene.coding_regions.uniq.each do |code|
if OrthomclGene::OFFICIAL_ORTHOMCL_APICOMPLEXAN_CODES.include?(four)
paragraph.push [
orthomcl_gene.orthomcl_name,
code.nil? ? nil : code.annotation.annotation,
code.nil? ? nil : code.localisation_english,
].join("\t")
elsif interestings.include?(four)
unless code.nil?
goes = code.coding_region_go_terms.cc.useful.all
unless goes.empty?
worthwhile = true
orig = orthomcl_gene.orthomcl_name
goes.each do |code_go|
paragraph.push [
orig,
code_go.go_term.go_identifier,
code_go.go_term.term,
code_go.evidence_code
].join("\t")
orig = ''
end
end
end
end
end
end
puts paragraph.uniq.join("\n")
puts
end
end
def apiloc_go_localisation_conservation_groups_to_database
# FasterCSV.foreach("#{PHD_DIR}/apiloc/species_orthologues2/breakdown.manual.xls",
# FasterCSV.foreach("#{PHD_DIR}/apiloc/species_orthologues4/breakdown2.manual.csv",
FasterCSV.foreach("#{PHD_DIR}/apiloc/species_orthologues4/breakdown3.manual.csv",
:col_sep => "\t"
) do |row|
# ignore lines that have nothing first or are the header line
next unless row[0] and row[0].length > 0 and row[3]
single = row[0]
eg = row[1]
full = OrthomclLocalisationConservations.single_letter_to_full_name(single)
raise Exception, "Couldn't understand single letter '#{single}'" unless full
# find the orthomcl group by using the gene in the first line (the example)
ogene = OrthomclGene.official.find_by_orthomcl_name(eg)
raise Exception, "Coun't find orthomcl gene '#{eg}' as expected" if ogene.nil?
# create the record
OrthomclLocalisationConservations.find_or_create_by_orthomcl_group_id_and_conservation(
ogene.official_group.id, full
).id
end
end
def yes_vs_no_human_examples
OrthomclLocalisationConservations.all.collect do |l|
max_human = OrthomclGene.code('hsap').all(
:joins =>[
[:coding_regions => :go_terms],
:orthomcl_gene_orthomcl_group_orthomcl_runs
],
:conditions => {:orthomcl_gene_orthomcl_group_orthomcl_runs => {:orthomcl_group_id => l.orthomcl_group_id}}
).max do |h1, h2|
counter = lambda {|h|
CodingRegionGoTerm.cc.useful.count(
:joins => {:coding_region => :orthomcl_genes},
:conditions => {:orthomcl_genes => {:id => h.id}}
)
}
counter.call(h1) <=> counter.call(h2)
end
next unless max_human
puts [
l.conservation,
max_human.coding_regions.first.names.sort
].flatten.join("\t")
end
end
def upload_uniprot_identifiers_for_ensembl_ids
FasterCSV.foreach("#{species_orthologue_folder}/gostat/human_ensembl_uniprot_ids.txt",
:col_sep => "\t", :headers => true
) do |row|
ens = row['Ensembl Protein ID']
uni = row['UniProt/SwissProt Accession']
raise unless ens
next unless uni
code = CodingRegion.f(ens)
raise unless code
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, uni, CodingRegionAlternateStringId::UNIPROT_SOURCE_NAME
) or raise
end
end
def download_uniprot_data
UNIPROT_SPECIES_ID_NAME_HASH.each do |taxon_id, species_name|
# Download the data into the expected name
Dir.chdir("#{DATA_DIR}/UniProt/knowledgebase") do
unless File.exists?("#{species_name}.gz")
cmd = "wget -O '#{species_name}.gz' 'http://www.uniprot.org/uniprot/?query=taxonomy%3a#{taxon_id}&compress=yes&format=txt'"
p cmd
`#{cmd}`
end
end
end
end
# Delete all the data associated with the uniprot species so
# I can start again.
def destroy_all_uniprot_species
APILOC_UNIPROT_SPECIES_NAMES.each do |species_name|
s = Species.find_by_name(species_name)
puts "#{species_name}..."
s.delete unless s.nil?
end
end
UNIPROT_SPECIES_ID_NAME_HASH = {
3702 => Species::ARABIDOPSIS_NAME,
9606 => Species::HUMAN_NAME,
10090 => Species::MOUSE_NAME,
4932 => Species::YEAST_NAME,
4896 => Species::POMBE_NAME,
10116 => Species::RAT_NAME,
7227 => Species::DROSOPHILA_NAME,
6239 => Species::ELEGANS_NAME,
44689 => Species::DICTYOSTELIUM_DISCOIDEUM_NAME,
7955 => Species::DANIO_RERIO_NAME,
5691 => Species::TRYPANOSOMA_BRUCEI_NAME,
}
APILOC_UNIPROT_SPECIES_NAMES = UNIPROT_SPECIES_ID_NAME_HASH.values
# Given that the species of interest are already downloaded from uniprot
# (using download_uniprot_data for instance), upload this data
# to the database, including GO terms. Other things need to be run afterwards
# to be able to link to OrthoMCL.
#
# This method could be more DRY - UniProtIterator could replace
# much of the code here. But eh for the moment.
def uniprot_to_database(species_names=nil)
species_names ||= APILOC_UNIPROT_SPECIES_NAMES
species_names = [species_names] unless species_names.kind_of?(Array)
species_names.each do |species_name|
count = 0
current_uniprot_string = ''
complete_filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz"
# Convert the whole gzip in to a smaller one, so parsing is faster:
# Don't use a static name because if two instance are running clashes occur.
Tempfile.open("#{species_name}_reduced") do |tempfile|
filename = tempfile.path
cmd = "zcat '#{complete_filename}' |egrep '^(AC|DR GO|//)' >'#{filename}'"
`#{cmd}`
dummy_gene = Gene.find_or_create_dummy(species_name)
progress = ProgressBar.new(species_name, `grep '^//' '#{filename}' |wc -l`.to_i)
File.foreach(filename) do |line|
if line == "//\n"
count += 1
progress.inc
#current uniprot is finished - upload it
#puts current_uniprot_string
u = Bio::UniProt.new(current_uniprot_string)
# Upload the UniProt name as the
axes = u.ac
protein_name = axes[0]
raise unless protein_name
code = CodingRegion.find_or_create_by_gene_id_and_string_id(
dummy_gene.id,
protein_name
)
raise unless code.save!
protein_alternate_names = axes.no_nils
protein_alternate_names.each do |name|
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, name, 'UniProt'
) or raise
end
goes = u.dr["GO"]
goes ||= [] #no go terms associated - best to still make it to the end of the method, because it is too complex here for such hackery
goes.each do |go_array|
go_id = go_array[0]
evidence_almost = go_array[2]
evidence = nil
if (matches = evidence_almost.match(/^([A-Z]{2,3})\:.*$/))
evidence = matches[1]
end
# error checking
if evidence.nil?
raise Exception, "No evidence code found in #{go_array.inspect} from #{evidence_almost}!"
end
go = GoTerm.find_by_go_identifier_or_alternate go_id
if go
CodingRegionGoTerm.find_or_create_by_coding_region_id_and_go_term_id_and_evidence_code(
code.id, go.id, evidence
).save!
else
$stderr.puts "Couldn't find GO id #{go_id}"
end
end
current_uniprot_string = ''
else
current_uniprot_string += line
end
end
progress.finish
end #tempfile
$stderr.puts "Uploaded #{count} from #{species_name}, now there is #{CodingRegion.s(species_name).count} coding regions in #{species_name}."
end
#uploadin the last one not required because the last line is always
# '//' already - making it easy.
end
def tetrahymena_orf_names_to_database
species_name = Species::TETRAHYMENA_NAME
current_uniprot_string = ''
filename = "#{DATA_DIR}/UniProt/knowledgebase/#{Species::TETRAHYMENA_NAME}.gz"
progress = ProgressBar.new(Species::TETRAHYMENA_NAME, `gunzip -c '#{filename}' |grep '^//' |wc -l`.to_i)
Zlib::GzipReader.open(filename).each do |line|
if line == "//\n"
progress.inc
#current uniprot is finished - upload it
u = Bio::UniProt.new(current_uniprot_string)
axes = u.ac
protein_name = axes[0]
raise unless protein_name
code = CodingRegion.fs(protein_name, species_name)
raise unless code
u.gn[0][:orfs].each do |orfname|
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name(
code.id, orfname
)
end
current_uniprot_string = ''
else
current_uniprot_string += line
end
end
end
# upload aliases so that orthomcl entries can be linked to uniprot ones.
# have to run tetrahymena_orf_names_to_database first though.
def tetrahymena_gene_aliases_to_database
bads = 0
goods = 0
filename = "#{DATA_DIR}/Tetrahymena thermophila/genome/TGD/Tt_ID_Mapping_File.txt"
progress = ProgressBar.new(Species::TETRAHYMENA_NAME, `wc -l '#{filename}'`.to_i)
FasterCSV.foreach(filename,
:col_sep => "\t"
) do |row|
progress.inc
uniprot = row[0]
orthomcl = row[1]
code = CodingRegion.fs(uniprot, Species::TETRAHYMENA_NAME)
if code.nil?
bads +=1
else
goods += 1
a = CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_source_and_name(
code.id, 'TGD', orthomcl
)
raise unless a
end
end
progress.finish
$stderr.puts "Found #{goods}, failed #{bads}"
end
def yeastgenome_ids_to_database
species_name = Species::YEAST_NAME
current_uniprot_string = ''
filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz"
progress = ProgressBar.new(species_name, `gunzip -c '#{filename}' |grep '^//' |wc -l`.to_i)
Zlib::GzipReader.open(filename).each do |line|
if line == "//\n"
progress.inc
#current uniprot is finished - upload it
u = Bio::UniProt.new(current_uniprot_string)
axes = u.ac
protein_name = axes[0]
raise unless protein_name
code = CodingRegion.fs(protein_name, species_name)
if code
unless u.gn.empty?
u.gn[0][:loci].each do |orfname|
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name(
code.id, orfname
)
end
end
else
$stderr.puts "Unable to find protein `#{protein_name}'"
end
current_uniprot_string = ''
else
current_uniprot_string += line
end
end
progress.finish
end
def elegans_wormbase_identifiers
species_name = Species::ELEGANS_NAME
current_uniprot_string = ''
complete_filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz"
# Convert the whole gzip in to a smaller one, so parsing is faster:
filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}_reduced"
`zcat '#{complete_filename}' |egrep '^(AC|DR WormBase|//)' >'#{filename}'`
progress = ProgressBar.new(species_name, `grep '^//' '#{filename}' |wc -l`.to_i)
File.foreach(filename) do |line|
if line == "//\n"
progress.inc
u = Bio::UniProt.new(current_uniprot_string)
code = CodingRegion.fs(u.ac[0], Species::ELEGANS_NAME)
raise unless code
# DR WormBase; WBGene00000467; cep-1.
ides = u.dr['WormBase']
ides ||= []
ides.flatten.each do |ident|
a = CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, ident, 'WormBase'
)
raise unless a.save!
end
current_uniprot_string = ''
else
current_uniprot_string += line
end
end
`rm #{filename}`
end
def dicystelium_names_to_database
species_name = Species::DICTYOSTELIUM_DISCOIDEUM_NAME
current_uniprot_string = ''
complete_filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz"
# Convert the whole gzip in to a smaller one, so parsing is faster:
filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}_reduced"
`zcat '#{complete_filename}' |egrep '^(AC|GN|//)' >'#{filename}'`
progress = ProgressBar.new(species_name, `grep '^//' '#{filename}' |wc -l`.to_i)
skipped_count = 0
skipped_count2 = 0
added_count = 0
File.foreach(filename) do |line|
if line == "//\n"
progress.inc
u = Bio::UniProt.new(current_uniprot_string)
code = CodingRegion.fs(u.ac[0], species_name)
raise unless code
# GN Name=myoJ; Synonyms=myo5B; ORFNames=DDB_G0272112;
unless u.gn.empty? # for some reason using u.gn when there is nothing there returns an array, not a hash. Annoying.
ides = []
u.gn.each do |g|
ides.push g[:name] unless g[:name].nil?
ides.push g[:orfs] unless g[:orfs].nil?
end
ides = ides.flatten.no_nils
ides ||= []
ides.flatten.each do |ident|
a = CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, ident, 'UniProtName'
)
raise unless a.save!
end
if ides.empty?
skipped_count2 += 1
else
added_count += 1
end
else
skipped_count += 1
end
current_uniprot_string = ''
else
current_uniprot_string += line
end
end
`rm '#{filename}'`
progress.finish
$stderr.puts "Added names for #{added_count}, skipped #{skipped_count} and #{skipped_count2}"
end
def tbrucei_names_to_database
species_name = Species::TRYPANOSOMA_BRUCEI_NAME
current_uniprot_string = ''
complete_filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz"
# Convert the whole gzip in to a smaller one, so parsing is faster:
filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}_reduced"
`zcat '#{complete_filename}' |egrep '^(AC|GN|//)' >'#{filename}'`
progress = ProgressBar.new(species_name, `grep '^//' '#{filename}' |wc -l`.to_i)
skipped_count = 0
skipped_count2 = 0
added_count = 0
File.foreach(filename) do |line|
if line == "//\n"
progress.inc
u = Bio::UniProt.new(current_uniprot_string)
code = CodingRegion.fs(u.ac[0], species_name)
raise unless code
# GN Name=myoJ; Synonyms=myo5B; ORFNames=DDB_G0272112;
unless u.gn.empty? # for some reason using u.gn when there is nothing there returns an array, not a hash. Annoying.
ides = []
u.gn.each do |g|
#ides.push g[:name] unless g[:name].nil?
ides.push g[:orfs] unless g[:orfs].nil?
end
ides = ides.flatten.no_nils
ides ||= []
ides.flatten.each do |ident|
a = CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, ident, 'UniProtName'
)
raise unless a.save!
end
if ides.empty?
skipped_count2 += 1
else
added_count += 1
end
else
skipped_count += 1
end
current_uniprot_string = ''
else
current_uniprot_string += line
end
end
`rm '#{filename}'`
progress.finish
$stderr.puts "Added names for #{added_count}, skipped #{skipped_count} and #{skipped_count2}"
end
def uniprot_ensembl_databases
[
Species::MOUSE_NAME,
Species::HUMAN_NAME,
Species::DANIO_RERIO_NAME,
Species::DROSOPHILA_NAME,
Species::RAT_NAME,
].each do |species_name|
Bio::UniProtIterator.foreach("#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz", 'DR Ensembl') do |u|
code = CodingRegion.fs(u.ac[0], species_name) or raise
ens = u.dr['Ensembl']
ens ||= []
ens.flatten.each do |e|
if e.match(/^ENS/) or (species_name == Species::DROSOPHILA_NAME and e.match(/^FBpp/))
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, e, 'Ensembl'
)
end
end
end
end
end
def uniprot_refseq_databases
[
Species::ARABIDOPSIS_NAME,
Species::RICE_NAME,
Species::POMBE_NAME,
].each do |species_name|
Bio::UniProtIterator.foreach("#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz", 'DR RefSeq') do |u|
code = CodingRegion.fs(u.ac[0], species_name) or raise
refseqs = u.dr['RefSeq']
refseqs ||= []
refseqs = refseqs.collect{|r| r[0]}
refseqs.each do |r|
r = r.gsub(/\..*/,'')
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, r, 'Refseq'
)
end
end
end
end
def chlamydomonas_link_to_orthomcl_ids
species_name = Species::CHLAMYDOMONAS_NAME
Bio::UniProtIterator.foreach("#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz", 'GN') do |u|
code = CodingRegion.fs(u.ac[0], species_name) or raise
gn = u.gn
unless gn.empty?
orfs = gn.collect{|g| g[:orfs]}
unless orfs.empty?
orfs.flatten.each do |orf|
o = 'CHLREDRAFT_168484' if orf == 'CHLRE_168484' #manual fix
raise Exception, "Unexpected orf: #{orf}" unless orf.match(/^CHLREDRAFT_/) or orf.match(/^CHLRE_/)
o = orf.gsub(/^CHLREDRAFT_/, '')
o = o.gsub(/^CHLRE_/,'')
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, o, 'JGI'
)
end
end
end
end
end
# OrthoMCL gene IDs for Drosophila are encoded in the 'DR EnsemblMetazoa;' lines,
# such as
# DR EnsemblMetazoa; FBtr0075201; FBpp0074964; FBgn0036740.
# (and in particular the FBpp ones). Upload these pp ones as synonyms
def drosophila_ensembl_metazoa
addeds = 0
non_addeds = 0
terms = 0
Bio::UniProtIterator.foreach("#{DATA_DIR}/UniProt/knowledgebase/#{Species::DROSOPHILA_NAME}.gz", 'DR EnsemblMetazoa;') do |u|
ensembl_metazoas = u.dr['EnsemblMetazoa']
if ensembl_metazoas.nil?
non_addeds += 1
else
added = false
code = CodingRegion.fs(u.ac[0], Species::DROSOPHILA_NAME) or raise
ensembl_metazoas.flatten.select{|s| s.match /^FBpp/}.each do |e|
added = true
terms+= 1
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, e, 'EnsemblMetazoa'
)
end
addeds += 1 if added
end
end
$stderr.puts "Uploaded #{terms} IDs for #{addeds} different genes, missed #{non_addeds}"
end
def uniprot_go_annotation_species_stats
APILOC_UNIPROT_SPECIES_NAMES.each do |species_name|
filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz"
if File.exists?(filename)
puts [
species_name,
`zcat '#{filename}'|grep ' GO' |grep -v IEA |grep -v ISS |grep 'C\:' |wc -l`
].join("\t")
else
puts "Couldn't find #{species_name} uniprot file"
end
end
end
# Create a spreadsheet that encapsulates all of the localisation
# information from apiloc, so that large scale analysis is simpler
def create_apiloc_spreadsheet
nil_char = nil #because I'm not sure how the joins will work
microscopy_method_names = LocalisationAnnotation::POPULAR_MICROSCOPY_TYPE_NAME_SCOPE.keys.sort.reverse
small_split_string = '#' #use when only 1 delimiter within a cell is needed
big_split_string = ';' #use when 2 delimiters in one cell are needed
orthomcl_split_char = '_'
# Headings
puts [
'Species',
'Gene ID',
'Abbreviations',
'Official Gene Annotation',
'Localisation Summary',
'Cellular Localisation',
'Total Number of Cellular Localisations',
'OrthoMCL Group Identifier',
'Apicomplexan Orthologues with Recorded Localisation',
'Apicomplexan Orthologues without Recorded Localisation',
'Non-Apicomplexan Orthologues with IDA GO Cellular Component Annotation',
'Consensus Localisation of Orthology Group',
'PubMed IDs of Publications with Localisation',
microscopy_method_names,
'All Localisation Methods Used',
'Strains',
'Gene Model Mapping Comments',
'Quotes'
].flatten.join("\t")
codes = CodingRegion.all(:joins => :expressed_localisations).uniq
progress = ProgressBar.new('apiloc_spreadsheet', codes.length)
codes.each do |code|
$stderr.puts code.string_id
progress.inc
to_print = []
organellar_locs = []
# species
to_print.push code.species.name
#EuPath or GenBank ID
to_print.push code.string_id
#common names
to_print.push code.literature_defined_names.join(small_split_string)
#annotation
a1 = code.annotation
to_print.push(a1.nil? ? nil_char : a1.annotation)
#full localisation description
to_print.push code.localisation_english
#'organellar' localisation (one per record,
#if there is more repeat the whole record)
#this might more sensibly be GO-oriented, but eh for the moment
organellar_locs = code.topsa.uniq
to_print.push nil_char
# number of organellar localisations (ie number of records for this gene)
to_print.push organellar_locs.length
# OrthoMCL-related stuffs
ogene = code.single_orthomcl!
ogroup = (ogene.nil? ? nil : ogene.official_group)
if ogroup.nil?
5.times do
to_print.push nil_char
end
else
#orthomcl group
to_print.push ogroup.orthomcl_name
#localised apicomplexans in orthomcl group
locked = CodingRegion.all(
:joins => [
{:orthomcl_genes => :orthomcl_groups},
:expression_contexts
],
:conditions => [
'orthomcl_groups.id = ? and coding_regions.id != ?',
ogroup.id, code.id
],
:select => 'distinct(coding_regions.*)'
)
to_print.push "\"#{locked.collect{|a|
[
a.string_id,
a.annotation.annotation,
a.localisation_english
].join(small_split_string)
}.join(big_split_string)}\""
#unlocalised apicomplexans in orthomcl group
to_print.push ogroup.orthomcl_genes.apicomplexan.all.reject {|a|
a.coding_regions.select { |c|
c.expressed_localisations.count > 0
}.length > 0
}.reach.orthomcl_name.join(', ').gsub('|',orthomcl_split_char)
#non-apicomplexans with useful GO annotations in orthomcl group
#species, orthomcl id, uniprot id(s), go annotations
go_codes = CodingRegion.go_cc_usefully_termed.not_apicomplexan.all(
:joins => {:orthomcl_genes => :orthomcl_groups},
:conditions =>
["orthomcl_groups.id = ?", ogroup.id],
:select => 'distinct(coding_regions.*)',
:order => 'coding_regions.id'
)
to_print.push "\"#{go_codes.collect { |g|
[
g.species.name,
g.orthomcl_genes.reach.orthomcl_name.join(', ').gsub('|',orthomcl_split_char),
g.names.join(', '),
g.coding_region_go_terms.useful.cc.all.reach.go_term.term.join(', ')
].join(small_split_string)
}.join(big_split_string)}\""
# consensus of orthology group.
to_print.push 'consensus - TODO'
end
contexts = code.expression_contexts
annotations = code.localisation_annotations
# pubmed ids that localise the gene
to_print.push contexts.reach.publication.definition.no_nils.uniq.join(small_split_string)
# Categorise the microscopy methods
microscopy_method_names.each do |name|
scopes =
LocalisationAnnotation::POPULAR_MICROSCOPY_TYPE_NAME_SCOPE[name]
done = LocalisationAnnotation
scopes.each do |scope|
done = done.send(scope)
end
if done.find_by_coding_region_id(code.id)
to_print.push 'yes'
else
to_print.push 'no'
end
end
# localisation methods used (assume different methods never give different results for the same gene)
to_print.push annotations.reach.microscopy_method.no_nils.uniq.join(small_split_string)
# strains
to_print.push annotations.reach.strain.no_nils.uniq.join(small_split_string)
# mapping comments
to_print.push annotations.reach.gene_mapping_comments.no_nils.uniq.join(small_split_string).gsub(/\"/,'')
# quotes
# have to escape quote characters otherwise I get rows joined together
to_print.push "\"#{annotations.reach.quote.uniq.join(small_split_string).gsub(/\"/,'\"')}\""
if organellar_locs.empty?
puts to_print.join("\t")
else
organellar_locs.each do |o|
to_print[5] = o.name
puts to_print.join("\t")
end
end
end
progress.finish
end
# The big GOA file has not been 'redundancy reduced', a process which is buggy,
# like the species level ones. Here I upload the species that I'm interested
# in using that big file, not the small one
def goa_all_species_to_database
require 'gene_association'
UNIPROT_SPECIES_ID_NAME_HASH.each do |species_id, species_name|
bad_codes_count = 0
bad_go_count = 0
good_count = 0
Bio::GzipAndFilterGeneAssociation.foreach(
"#{DATA_DIR}/GOA/gene_association.goa_uniprot.gz",
"\ttaxon:#{species_id}\t"
) do |go|
name = go.primary_id
code = CodingRegion.fs(name, species_name)
unless code
$stderr.puts "Couldn't find coding region #{name}"
bad_codes_count += 1
next
end
go_term = GoTerm.find_by_go_identifier(go.go_identifier)
unless go_term
$stderr.puts "Couldn't find coding region #{go.go_identifier}"
bad_go_count += 1
next
end
CodingRegionGoTerm.find_or_create_by_coding_region_id_and_go_term_id(
code.id, go_term.id
)
good_count += 1
end
$stderr.puts "#{good_count} all good, failed to find #{bad_codes_count} coding regions and #{bad_go_count} go terms"
end
end
def how_many_genes_have_dual_localisation?
dual_loc_folder = "#{PHD_DIR}/apiloc/experiments/dual_localisations"
raise unless File.exists?(dual_loc_folder)
file = File.open(File.join(dual_loc_folder, 'duals.csv'),'w')
Species.apicomplexan.each do |species|
species_name = species.name
codes = CodingRegion.s(species_name).all(
:joins => :expressed_localisations,
:select => 'distinct(coding_regions.*)'
)
counts = []
nuc_aware_counts = []
codes_per_count = []
# write the results to the species-specific file
codes.each do |code|
next if code.string_id == CodingRegion::UNANNOTATED_CODING_REGIONS_DUMMY_GENE_NAME
tops = TopLevelLocalisation.positive.all(
:joins => {:apiloc_localisations => :expressed_coding_regions},
:conditions => ['coding_regions.id = ?',code.id],
:select => 'distinct(top_level_localisations.*)'
)
count = tops.length
counts[count] ||= 0
counts[count] += 1
codes_per_count[count] ||= []
codes_per_count[count].push code.string_id
# nucleus and cytoplasm as a single localisation if both are included
names = tops.reach.name.retract
if names.include?('nucleus') and names.include?('cytoplasm')
count -= 1
end
# Write out the coding regions to a file
# gather the falciparum data
og = code.single_orthomcl!
fals = []
if og and og.official_group
fals = og.official_group.orthomcl_genes.code('pfal').all.collect do |ogene|
ogene.single_code
end
end
file.puts [
code.species.name,
code.string_id,
code.names,
count,
code.compartments.join('|'),
fals.reach.compartments.join('|'),
fals.reach.localisation_english.join('|')
].join("\t")
nuc_aware_counts[count] ||= 0
nuc_aware_counts[count] += 1
end
puts species_name
# p codes_per_count
p counts
p nuc_aware_counts
end
file.close
end
def falciparum_test_prediction_by_orthology_to_non_apicomplexans
bins = {}
puts [
'PlasmoDB ID',
'Names',
'Compartments',
'Prediction',
'Comparison',
'Full P. falciparum Localisation Information'
].join("\t")
CodingRegion.localised.falciparum.all(
:select => 'distinct(coding_regions.*)'
).each do |code|
# Unassigned genes just cause problems for orthomcl
next if code.string_id == CodingRegion::NO_MATCHING_GENE_MODEL
# When there is more than 1 P. falciparum protein in the group, then ignore this
group = code.single_orthomcl.official_group
if group.nil?
$stderr.puts "#{code.names.join(', ')} has no OrthoMCL group, ignoring."
next
end
num = group.orthomcl_genes.code(code.species.orthomcl_three_letter).count
if num != 1
$stderr.puts "#{code.names.join(', ')} has #{num} genes in its localisation group, ignoring"
next
end
pred = code.apicomplexan_localisation_prediction_by_most_common_localisation
next if pred.nil?
goodness = code.compare_localisation_to_list(pred)
puts [
code.string_id,
code.names.join('|'),
code.compartments.join('|'),
pred,
goodness,
code.localisation_english,
].join("\t")
bins[goodness] ||= 0
bins[goodness] += 1
end
# Print the results of the analysis
p bins
end
# Looking through all the genes in the database, cache of the compartments so that things are easier to compare
def cache_all_compartments
# Cache all apicomplexan compartments
codes = CodingRegion.apicomplexan.all
progress = ProgressBar.new('apicomplexans', codes.length)
codes.each do |code|
progress.inc
comps = code.compartments
comps.each do |comp|
CodingRegionCompartmentCache.find_or_create_by_coding_region_id_and_compartment(
code.id, comp
)
end
end
progress.finish
# Cache all non-apicomplexan compartments
codes = CodingRegion.go_cc_usefully_termed.all
progress = ProgressBar.new('eukaryotes', codes.length)
codes.each do |code|
progress.inc
comps = code.compartments
comps.each do |comp|
CodingRegionCompartmentCache.find_or_create_by_coding_region_id_and_compartment(
code.id, comp
)
end
end
progress.finish
end
# How conserved is localisation between the three branches of life with significant
# data known about them?
# This method FAILS due to memory and compute time issues - I ended up
# essentially abandoning rails for this effort.
def conservation_of_eukaryotic_sub_cellular_localisation(debug = false)
groups_to_counts = {}
# For each orthomcl group that has a connection to coding region, and
# that coding region has a cached compartment
groups = OrthomclGroup.all(
# :select => 'distinct(orthomcl_groups.*)',
:joins => {:orthomcl_genes => {:coding_regions => :coding_region_compartment_caches}}
# :limit => 10,
# :include => {:orthomcl_genes => {:coding_regions => :coding_region_compartment_caches}}
)
# ProgressBar on stdout, because debug is on stderr
progress = ProgressBar.new('conservation', groups.length, STDOUT)
groups.each do |ortho_group|
progress.inc
$stderr.puts "---------------------------------------------" if debug
# For each non-Apicomplexan gene with localisation information in this group,
# assign it compartments.
# For each apicomplexan, get the compartments from apiloc
# This is nicely abstracted already!
# However, a single orthomcl gene can have multiple CodingRegion's associated.
# Therefore each has to be analysed as an array, frustratingly.
# reject the orthomcl gene if it has no coding regions associated with it.
orthomcl_genes = OrthomclGene.all(
:joins => [:coding_regions, :orthomcl_groups],
:conditions => {:orthomcl_groups => {:id => ortho_group.id}}
)
# ortho_group.orthomcl_genes.uniq.reject do |s|
# # reject the orthomcl gene if it has no coding regions associated with it.
# s.coding_regions.empty?
# end
# Setup data structures
kingdom_orthomcls = {} #array of kingdoms to orthomcl genes
orthomcl_locs = {} #array of orthomcl_genes to localisations, cached for convenience and speed
orthomcl_genes.each do |orthomcl_gene|
# Localisations from all coding regions associated with an orthomcl gene are used.
locs = CodingRegionCompartmentCache.all(
:joins => {:coding_region => :orthomcl_genes},
:conditions => {:orthomcl_genes => {:id => orthomcl_gene.id}}
).reach.compartment.uniq
# locs = orthomcl_gene.coding_regions.reach.cached_compartments.flatten.uniq
next if locs.empty? #ignore unlocalised genes completely from hereafter
name = orthomcl_gene.orthomcl_name
orthomcl_locs[name] = locs
# no one orthomcl gene will have coding regions from 2 different species,
# so using the first element of the array is fine
species = orthomcl_gene.coding_regions[0].species
kingdom_orthomcls[species.kingdom] ||= []
kingdom_orthomcls[species.kingdom].push name
end
$stderr.puts kingdom_orthomcls.inspect if debug
$stderr.puts orthomcl_locs.inspect if debug
$stderr.puts "Kingdoms: #{kingdom_orthomcls.to_a.collect{|k| k[0]}.sort.join(', ')}" if debug
# within the one kingdom, do they agree?
kingdom_orthomcls.each do |kingdom, orthomcls|
# If there is only a single coding region, then don't record
number_in_kingdom_localised = orthomcls.length
if number_in_kingdom_localised < 2
$stderr.puts "#{ortho_group.orthomcl_name}, #{kingdom}, skipping (#{orthomcls.join(', ')})" if debug
next
end
# convert orthomcl genes to localisation arrays
locs = orthomcls.collect {|orthomcl|
orthomcl_locs[orthomcl]
}
# OK, so now we are on. Let's do this
agreement = OntologyComparison.new.agreement_of_group(locs)
index = [kingdom]
$stderr.puts "#{ortho_group.orthomcl_name}, #{index.inspect}, #{agreement}, #{orthomcls.join(' ')}" if debug
groups_to_counts[index] ||= {}
groups_to_counts[index][agreement] ||= 0
groups_to_counts[index][agreement] += 1
end
# within two kingdoms, do they agree?
kingdom_orthomcls.to_a.each_lower_triangular_matrix do |array1, array2|
kingdom1 = array1[0]
kingdom2 = array2[0]
orthomcl_array1 = array1[1]
orthomcl_array2 = array2[1]
orthomcl_arrays = [orthomcl_array1, orthomcl_array2]
# don't include unless there is an orthomcl in each kingdom
zero_entriers = orthomcl_arrays.select{|o| o.length==0}
if zero_entriers.length > 0
$stderr.puts "#{ortho_group.orthomcl_name}, #{kingdoms.join(' ')}, skipping"
next
end
locs_for_all = orthomcl_arrays.flatten.collect {|orthomcl| orthomcl_locs[orthomcl]}
agreement = OntologyComparison.new.agreement_of_group(locs_for_all)
index = [kingdom1, kingdom2].sort
$stderr.puts "#{ortho_group.orthomcl_name}, #{index.inspect}, #{agreement}" if debug
groups_to_counts[index] ||= {}
groups_to_counts[index][agreement] ||= 0
groups_to_counts[index][agreement] += 1
end
# within three kingdoms, do they agree?
kingdom_orthomcls.to_a.each_lower_triangular_3d_matrix do |a1, a2, a3|
kingdom1 = a1[0]
kingdom2 = a2[0]
kingdom3 = a3[0]
orthomcl_array1 = a1[1]
orthomcl_array2 = a2[1]
orthomcl_array3 = a3[1]
kingdoms = [kingdom1, kingdom2, kingdom3]
orthomcl_arrays = [orthomcl_array1, orthomcl_array2, orthomcl_array3]
# don't include unless there is an orthomcl in each kingdom
zero_entriers = orthomcl_arrays.select{|o| o.length==0}
if zero_entriers.length > 0
$stderr.puts "#{ortho_group.orthomcl_name}, #{kingdoms.join(' ')}, skipping" if debug
next
end
locs_for_all = orthomcl_arrays.flatten.collect {|orthomcl| orthomcl_locs[orthomcl]}
agreement = OntologyComparison.new.agreement_of_group locs_for_all
index = kingdoms.sort
$stderr.puts "#{ortho_group.orthomcl_name}, #{index.inspect}, #{agreement}" if debug
groups_to_counts[index] ||= {}
groups_to_counts[index][agreement] ||= 0
groups_to_counts[index][agreement] += 1
end
end
progress.finish
# print out the counts for each group of localisations
p groups_to_counts
end
# An attempt to make conservation_of_eukaryotic_sub_cellular_localisation faster
# as well as using less memory. In the end the easiest way was to stay away from Rails
# almost completely, and just use find_by_sql for the big database dump to a csv file,
# and then parse that csv file one line at a time.
def conservation_of_eukaryotic_sub_cellular_localisation_slimmer
# Cache all of the kingdom information as orthomcl_split to kingdom
orthomcl_abbreviation_to_kingdom = {}
Species.all(:conditions => 'orthomcl_three_letter is not null').each do |sp|
orthomcl_abbreviation_to_kingdom[sp.orthomcl_three_letter] = Species::NAME_TO_KINGDOM[sp.name]
end
# Copy the data out of the database to a csv file. Beware that there is duplicates in this file
tempfile = File.open('/tmp/eukaryotic_conservation','w')
# Tempfile.open('eukaryotic_conservation') do |tempfile|
`chmod go+w #{tempfile.path}` #so postgres can write to this file as well
OrthomclGene.find_by_sql "copy (select groupa.orthomcl_name, gene.orthomcl_name, cache.compartment from orthomcl_groups groupa inner join orthomcl_gene_orthomcl_group_orthomcl_runs ogogor on groupa.id=ogogor.orthomcl_group_id inner join orthomcl_genes gene on ogogor.orthomcl_gene_id=gene.id inner join orthomcl_gene_coding_regions ogc on ogc.orthomcl_gene_id=gene.id inner join coding_regions code on ogc.coding_region_id=code.id inner join coding_region_compartment_caches cache on code.id=cache.coding_region_id order by groupa.orthomcl_name) to '#{tempfile.path}'"
tempfile.close
# Parse the csv file to get the answers I'm looking for
data = {}
kingdom_orthomcls = {} #array of kingdoms to orthomcl genes
orthomcl_locs = {} #array of orthomcl_genes to localisations, cached for convenience and speed
FasterCSV.foreach(tempfile.path, :col_sep => "\t") do |row|
# name columns
raise unless row.length == 3
group = row[0]
gene = row[1]
compartment = row[2]
data[group] ||= {}
kingdom = orthomcl_abbreviation_to_kingdom[OrthomclGene.new.official_split(gene)[0]]
data[group]['kingdom_orthomcls'] ||= {}
data[group]['kingdom_orthomcls'][kingdom] ||= []
data[group]['kingdom_orthomcls'][kingdom].push gene
data[group]['kingdom_orthomcls'][kingdom].uniq!
data[group]['orthomcl_locs'] ||= {}
data[group]['orthomcl_locs'][gene] ||= []
data[group]['orthomcl_locs'][gene].push compartment
data[group]['orthomcl_locs'][gene].uniq!
end
# end
# Classify each of the groups into the different categories where possible
groups_to_counts = {}
data.each do |group, data2|
classify_eukaryotic_conservation_of_single_orthomcl_group(
data2['kingdom_orthomcls'],
data2['orthomcl_locs'],
groups_to_counts
)
end
pp groups_to_counts
end
# This is a modularisation of conservation_of_eukaryotic_sub_cellular_localisation,
# and does the calculations on the already transformed data (kingdom_orthomcls, orthomcl_locs).
# More details in conservation_of_eukaryotic_sub_cellular_localisation
def classify_eukaryotic_conservation_of_single_orthomcl_group(kingdom_orthomcls, orthomcl_locs, groups_to_counts, debug = false)
$stderr.puts kingdom_orthomcls.inspect if debug
$stderr.puts orthomcl_locs.inspect if debug
$stderr.puts "Kingdoms: #{kingdom_orthomcls.to_a.collect{|k| k[0]}.sort.join(', ')}" if debug
# within the one kingdom, do they agree?
kingdom_orthomcls.each do |kingdom, orthomcls|
# If there is only a single coding region, then don't record
number_in_kingdom_localised = orthomcls.length
if number_in_kingdom_localised < 2
$stderr.puts "#{ortho_group.orthomcl_name}, #{kingdom}, skipping (#{orthomcls.join(', ')})" if debug
next
end
# convert orthomcl genes to localisation arrays
locs = orthomcls.collect {|orthomcl|
orthomcl_locs[orthomcl]
}
# OK, so now we are on. Let's do this
agreement = OntologyComparison.new.agreement_of_group(locs)
index = [kingdom]
$stderr.puts "#{ortho_group.orthomcl_name}, #{index.inspect}, #{agreement}, #{orthomcls.join(' ')}" if debug
groups_to_counts[index] ||= {}
groups_to_counts[index][agreement] ||= 0
groups_to_counts[index][agreement] += 1
end
# within two kingdoms, do they agree?
kingdom_orthomcls.to_a.each_lower_triangular_matrix do |array1, array2|
kingdom1 = array1[0]
kingdom2 = array2[0]
orthomcl_array1 = array1[1]
orthomcl_array2 = array2[1]
orthomcl_arrays = [orthomcl_array1, orthomcl_array2]
# don't include unless there is an orthomcl in each kingdom
zero_entriers = orthomcl_arrays.select{|o| o.length==0}
if zero_entriers.length > 0
$stderr.puts "#{ortho_group.orthomcl_name}, #{kingdoms.join(' ')}, skipping"
next
end
locs_for_all = orthomcl_arrays.flatten.collect {|orthomcl| orthomcl_locs[orthomcl]}
agreement = OntologyComparison.new.agreement_of_group(locs_for_all)
index = [kingdom1, kingdom2].sort
$stderr.puts "#{ortho_group.orthomcl_name}, #{index.inspect}, #{agreement}" if debug
groups_to_counts[index] ||= {}
groups_to_counts[index][agreement] ||= 0
groups_to_counts[index][agreement] += 1
end
# within three kingdoms, do they agree?
kingdom_orthomcls.to_a.each_lower_triangular_3d_matrix do |a1, a2, a3|
kingdom1 = a1[0]
kingdom2 = a2[0]
kingdom3 = a3[0]
orthomcl_array1 = a1[1]
orthomcl_array2 = a2[1]
orthomcl_array3 = a3[1]
kingdoms = [kingdom1, kingdom2, kingdom3]
orthomcl_arrays = [orthomcl_array1, orthomcl_array2, orthomcl_array3]
# don't include unless there is an orthomcl in each kingdom
zero_entriers = orthomcl_arrays.select{|o| o.length==0}
if zero_entriers.length > 0
$stderr.puts "#{ortho_group.orthomcl_name}, #{kingdoms.join(' ')}, skipping" if debug
next
end
locs_for_all = orthomcl_arrays.flatten.collect {|orthomcl| orthomcl_locs[orthomcl]}
agreement = OntologyComparison.new.agreement_of_group locs_for_all
index = kingdoms.sort
$stderr.puts "#{ortho_group.orthomcl_name}, #{index.inspect}, #{agreement}" if debug
groups_to_counts[index] ||= {}
groups_to_counts[index][agreement] ||= 0
groups_to_counts[index][agreement] += 1
end
end
# Using the assumption that the yeast-mouse, yeast-human and falciparum-toxo divergences are approximately
# equivalent, whatever that means, work out the conservation of localisation between each of those groups.
# Does yeast/mouse exhibit the same problems as falciparum/toxo when comparing localisations?
def localisation_conservation_between_pairs_of_species(species1 = Species::FALCIPARUM_NAME, species2 = Species::TOXOPLASMA_GONDII_NAME)
groups_to_counts = {} #this array ends up holding all the answers after we have finished going through everything
toxo_fal_groups = OrthomclGroup.with_species(Species::ORTHOMCL_CURRENT_LETTERS[species1]).with_species(Species::ORTHOMCL_CURRENT_LETTERS[species2]).all(
:joins => {:orthomcl_genes => {:coding_regions => :coding_region_compartment_caches}},
# :limit => 10,
:select => 'distinct(orthomcl_groups.*)'
# :conditions => ['orthomcl_groups.orthomcl_name = ? or orthomcl_groups.orthomcl_name = ?','OG3_10042','OG3_10032']
)
$stderr.puts "Found #{toxo_fal_groups.length} groups containing proteins from #{species1} and #{species2}"
progress = ProgressBar.new('tfal', toxo_fal_groups.length, STDOUT)
toxo_fal_groups.each do |tfgroup|
progress.inc
orthomcl_locs = {}
species_orthomcls = {} #used like kingdom_locs in previous methods
# collect the orthomcl_locs array for each species
arrays = [species1, species2].collect do |species_name|
# collect compartments for each of the toxos
genes = tfgroup.orthomcl_genes.code(Species::ORTHOMCL_CURRENT_LETTERS[species_name]).all
gene_locs = {}
# add all the locs for a given gene
genes.each do |gene|
locs = gene.coding_regions.collect{|c| c.coding_region_compartment_caches.reach.compartment.retract}.flatten.uniq #all compartments associated with the gene
unless locs.empty?
gene_locs[gene.orthomcl_name] = locs
end
end
# $stderr.puts "Found #{genes.length} orthomcl genes in #{species_name} from #{tfgroup.orthomcl_name}, of those, #{gene_locs.length} had localisations"
gene_locs.each do |gene, locs|
species_orthomcls[species_name] ||= []
species_orthomcls[species_name].push gene
orthomcl_locs[gene] = locs
end
end
# pp species_orthomcls
# pp orthomcl_locs
classify_eukaryotic_conservation_of_single_orthomcl_group(species_orthomcls, orthomcl_locs, groups_to_counts)
end
progress.finish
pp groups_to_counts
end
# Run localisation_conservation_between_pairs_of_species for each pair of species
# that I care about
def exhaustive_localisation_conservation_between_pairs_of_species
[
Species::YEAST_NAME,
Species::MOUSE_NAME,
Species::HUMAN_NAME,
Species::ARABIDOPSIS_NAME,
Species::FALCIPARUM_NAME,
Species::TOXOPLASMA_GONDII_NAME,
].each_lower_triangular_matrix do |s1, s2|
puts '=============================================================='
localisation_conservation_between_pairs_of_species(s1, s2)
end
end
def localisation_pairs_as_matrix
master = {}
File.foreach("#{PHD_DIR}/apiloc/pairs/results.ruby").each do |line|
hash = eval "{#{line}}"
master = master.merge hash
end
organisms = [
Species::YEAST_NAME,
Species::MOUSE_NAME,
Species::HUMAN_NAME,
Species::ARABIDOPSIS_NAME,
Species::FALCIPARUM_NAME,
Species::TOXOPLASMA_GONDII_NAME,
]
print "\t"
puts organisms.join("\t")
organisms.each do |o1|
print o1
organisms.each do |o2|
print "\t"
next if o1 == o2
result = master[[o1,o2].sort]
raise Exception, "Couldn't find #{[o1,o2].sort}" if result.nil?
print result['complete agreement'].to_f/result.values.sum
end
puts
end
end
# If you take only localised falciparum proteins with localised yeast and mouse orthologues,
# what are the chances that they are conserved
def falciparum_predicted_by_yeast_mouse(predicting_species=[Species::YEAST_NAME, Species::MOUSE_NAME],
test_species=Species::FALCIPARUM_NAME)
answer = {}
# Build up the query using the with_species named_scope,
# retrieving all groups that have members in each species
fal_groups = OrthomclGroup.with_species(Species::ORTHOMCL_CURRENT_LETTERS[test_species])
predicting_species.each do |sp|
fal_groups = fal_groups.send(:with_species, Species::ORTHOMCL_CURRENT_LETTERS[sp])
end
fal_groups = fal_groups.all(:select => 'distinct(orthomcl_groups.*)')#, :limit => 20)
$stderr.puts "Found #{fal_groups.length} groups with #{predicting_species.join(', ')} and #{test_species} proteins"
progress = ProgressBar.new('predictionByTwo', fal_groups.length, STDOUT)
fal_groups.each do |fal_group|
progress.inc
$stderr.puts
# get the localisations from each of the predicting species
predicting_array = predicting_species.collect do |species_name|
genes = fal_group.orthomcl_genes.code(Species::ORTHOMCL_CURRENT_LETTERS[species_name]).all
gene_locs = {}
# add all the locs for a given gene
genes.each do |gene|
locs = gene.coding_regions.collect{|c| c.coding_region_compartment_caches.reach.compartment.retract}.flatten.uniq #all compartments associated with the gene
unless locs.empty?
gene_locs[gene.orthomcl_name] = locs
end
end
gene_locs
end
$stderr.puts "OGroup #{fal_group.orthomcl_name} gave #{predicting_array.inspect}"
# only consider cases where there is localisations in each of the predicting species
next if predicting_array.select{|a| a.empty?}.length > 0
# only consider genes where the localisations from the predicting species agree
flattened = predicting_array.inject{|a,b| a.merge(b)}.values
$stderr.puts "flattened: #{flattened.inspect}"
agreement = OntologyComparison.new.agreement_of_group(flattened)
next unless agreement == OntologyComparison::COMPLETE_AGREEMENT
$stderr.puts "They agree..."
# Now compare the agreement between a random falciparum hit and the locs from the predicting
prediction = flattened.to_a[0]
$stderr.puts "Prediction: #{prediction}"
all_fals = CodingRegion.falciparum.all(
:joins => [:coding_region_compartment_caches, {:orthomcl_genes => :orthomcl_groups}],
:conditions => ['orthomcl_groups.id = ?', fal_group.id]
)
next if all_fals.empty?
fal = all_fals[rand(all_fals.length)]
fal_compartments = fal.cached_compartments
$stderr.puts "fal: #{fal.string_id} #{fal_compartments}"
agreement = OntologyComparison.new.agreement_of_group([prediction, fal_compartments])
$stderr.puts "Final agreement #{agreement}"
answer[agreement] ||= 0
answer[agreement] += 1
end
progress.finish
pp answer
end
def how_many_genes_are_localised_in_each_species
interests = Species.all.reach.name.retract
# How many genes?
interests.each do |interest|
count = OrthomclGene.count(
:joins => {:coding_regions => [:coding_region_compartment_caches, {:gene => {:scaffold => :species}}]},
:select => 'distinct(orthomcl_genes.id)',
:conditions => {:species => {:name => interest}}
)
puts "Found #{count} genes with localisation from #{interest}"
end
# how many orthomcl groups?
interests.each do |interest|
count = OrthomclGroup.official.count(
:joins => {:orthomcl_genes => {:coding_regions => [:coding_region_compartment_caches, {:gene => {:scaffold => :species}}]}},
:conditions => ['orthomcl_genes.orthomcl_name like ? and species.name = ?', "#{Species::ORTHOMCL_CURRENT_LETTERS[interest]}|%", interest],
:select => 'distinct(orthomcl_groups.id)'
)
puts "Found #{count} OrthoMCL groups with localisation from #{interest}"
end
end
# Predict the localisation of a protein by determining the amount
def prediction_by_most_common_localisation(predicting_species=[Species::YEAST_NAME, Species::MOUSE_NAME],
test_species=Species::FALCIPARUM_NAME)
answer = {}
# Build up the query using the with_species named_scope,
# retrieving all groups that have members in each species
fal_groups = OrthomclGroup.with_species(Species::ORTHOMCL_CURRENT_LETTERS[test_species])
predicting_species.each do |sp|
fal_groups = fal_groups.send(:with_species, Species::ORTHOMCL_CURRENT_LETTERS[sp])
end
fal_groups = fal_groups.all(:select => 'distinct(orthomcl_groups.*)')#, :limit => 20)
$stderr.puts "Found #{fal_groups.length} groups with #{predicting_species.join(', ')} and #{test_species} proteins"
progress = ProgressBar.new('predictionByCommon', fal_groups.length, STDOUT)
fal_groups.each do |fal_group|
progress.inc
# Only include gene that have exactly 1 gene from that species, otherwise it is harder to
# work out what is going on.
all_tests = fal_group.orthomcl_genes.code(Species::ORTHOMCL_CURRENT_LETTERS[test_species]).all
if all_tests.length > 1
answer['Too many orthomcl genes found'] ||= 0
answer['Too many orthomcl genes found'] += 1
next
end
# gather the actual coding region - discard if there is not exactly 1
codes = all_tests[0].coding_regions
unless codes.length == 1
answer["#{codes.length} coding regions for the 1 orthomcl gene"] ||= 0
answer["#{codes.length} coding regions for the 1 orthomcl gene"] += 1
next
end
code = codes[0]
# Find the most common localisation in each species predicting
preds = [] # the prediction of the most common localisations
commons = predicting_species.collect do |s|
common = code.localisation_prediction_by_most_common_localisation(s)
# Ignore when no loc is found or it is confusing
if common.nil?
answer["No localisation found when trying to find common"] ||= 0
answer["No localisation found when trying to find common"] += 1
next
end
# add the commonest localisation to the prediction array
preds.push [common]
end
# Don't predict unless all species are present
if preds.length == predicting_species.length
# Only predict if the top 2 species are in agreement
if OntologyComparison.new.agreement_of_group(preds) == OntologyComparison::COMPLETE_AGREEMENT
final_locs = code.cached_compartments
if final_locs.empty?
answer["No test species localisation"] ||= 0
answer["No test species localisation"] += 1
else
# Add the final localisation compartments
preds.push final_locs
acc = OntologyComparison.new.agreement_of_group(preds)
answer[acc] ||= 0
answer[acc] += 1
end
else
answer["Predicting species don't agree"] ||= 0
answer["Predicting species don't agree"] += 1
end
else
answer["Not enough localisation info in predicting groups"] ||= 0
answer["Not enough localisation info in predicting groups"] += 1
end
end
progress.finish
pp answer
end
def stuarts_basel_spreadsheet_yeast_setup
# uniprot_to_database(Species::YEAST_NAME)
# yeastgenome_ids_to_database
# OrthomclGene.new.link_orthomcl_and_coding_regions(
# "scer",
# :accept_multiple_coding_regions => true
# )
# cache compartments
codes = CodingRegion.s(Species::YEAST_NAME).go_cc_usefully_termed.all
progress = ProgressBar.new('eukaryotes', codes.length)
codes.each do |code|
progress.inc
comps = code.compartments
comps.each do |comp|
CodingRegionCompartmentCache.find_or_create_by_coding_region_id_and_compartment(
code.id, comp
)
end
end
progress.finish
end
def stuarts_basel_spreadsheet(accept_multiples = false)
species_of_interest = [
Species::ARABIDOPSIS_NAME,
Species::FALCIPARUM,
Species::TOXOPLASMA_GONDII,
Species::YEAST_NAME,
Species::MOUSE_NAME,
Species::HUMAN_NAME
]
$stderr.puts "Copying data to tempfile.."
# Copy the data out of the database to a csv file. Beware that there is duplicates in this file
tempfile = File.open('/tmp/eukaryotic_conservation','w')
# Tempfile.open('eukaryotic_conservation') do |tempfile|
`chmod go+w #{tempfile.path}` #so postgres can write to this file as well
OrthomclGene.find_by_sql "copy (select groupa.orthomcl_name, gene.orthomcl_name, cache.compartment from orthomcl_groups groupa inner join orthomcl_gene_orthomcl_group_orthomcl_runs ogogor on groupa.id=ogogor.orthomcl_group_id inner join orthomcl_genes gene on ogogor.orthomcl_gene_id=gene.id inner join orthomcl_gene_coding_regions ogc on ogc.orthomcl_gene_id=gene.id inner join coding_regions code on ogc.coding_region_id=code.id inner join coding_region_compartment_caches cache on code.id=cache.coding_region_id order by groupa.orthomcl_name) to '#{tempfile.path}'"
tempfile.close
groups_genes = {}
genes_localisations = {}
# Read groups, genes, and locs into memory
$stderr.puts "Reading into memory sql results.."
FasterCSV.foreach(tempfile.path, :col_sep => "\t") do |row|
#FasterCSV.foreach('/tmp/eukaryotic_conservation_test', :col_sep => "\t") do |row|
# name columns
raise unless row.length == 3
group = row[0]
gene = row[1]
compartment = row[2]
groups_genes[group] ||= []
groups_genes[group].push gene
groups_genes[group].uniq!
genes_localisations[gene] ||= []
genes_localisations[gene].push compartment
genes_localisations[gene].uniq!
end
# Print headers
header = ['']
species_of_interest.each do |s|
header.push "#{s} ID 1"
header.push "#{s} loc 1"
header.push "#{s} ID 2"
header.push "#{s} loc 2"
end
puts header.join("\t")
# Iterate through each OrthoMCL group, printing them out if they fit the criteria
$stderr.puts "Iterating through groups.."
groups_genes.each do |group, ogenes|
$stderr.puts "looking at group #{group}"
# associate genes with species
species_gene = {}
ogenes.each do |ogene|
sp = Species.four_letter_to_species_name(OrthomclGene.new.official_split(ogene)[0])
unless species_of_interest.include?(sp)
$stderr.puts "Ignoring info for #{sp}"
next
end
species_gene[sp] ||= []
species_gene[sp].push ogene
species_gene[sp].uniq!
end
# skip groups that are only localised in a single species
if species_gene.length == 1
$stderr.puts "Rejecting #{group} because it only has localised genes in 1 species of interest"
next
end
# skip groups that have more than 2 localised genes in each group.
failed = false
species_gene.each do |species, genes|
if genes.length > 2
$stderr.puts "Rejecting #{group}, because there are >2 genes with localisation info in #{species}.."
failed = true
end
end
next if failed
# procedure for making printing easier
generate_cell = lambda do |gene|
locs = genes_localisations[gene]
if locs.include?('cytoplasm') and locs.include?('nucleus')
locs.reject!{|l| l=='cytoplasm'}
end
if locs.length == 1
[OrthomclGene.new.official_split(gene)[1], locs[0]]
elsif locs.length == 0
raise Exception, "Unexpected lack of loc information"
else
if accept_multiples
[OrthomclGene.new.official_split(gene)[1], locs.sort.join(', ')]
else
$stderr.puts "Returning nil for #{gene} because there is #{locs.length} localisations"
nil
end
end
end
row = [group]
failed = false #fail if genes have >1 localisation
species_of_interest.each do |s|
$stderr.puts "What's in #{s}? #{species_gene[s].inspect}"
if species_gene[s].nil? or species_gene[s].length == 0
row.push ['','']
row.push ['','']
elsif species_gene[s].length == 1
r = generate_cell.call species_gene[s][0]
failed = true if r.nil?
row.push r
row.push ['','']
else
species_gene[s].each do |g|
r = generate_cell.call g
failed = true if r.nil?
row.push r
end
end
end
puts row.join("\t") unless failed
end
end
# Generate the data for
def publication_per_year_graphing
years = {}
fails = 0
Publication.all(:joins => {:expression_contexts => :localisation}).uniq.each do |p|
y = p.year
if y.nil?
fails += 1
$stderr.puts "Failed: #{p.inspect}"
else
years[y] ||= 0
years[y] += 1
end
end
puts ['Year','Number of Publications'].join("\t")
years.sort.each do |a,b|
puts [a,b].join("\t")
end
$stderr.puts "Failed to year-ify #{fails} publications."
end
def localisation_per_year_graphing
already_localised = []
years = {}
fails = 0
# Get all the publications that have localisations in order
Publication.all(:joins => {:expression_contexts => :localisation}).uniq.sort {|p1,p2|
if p1.year.nil?
-1
elsif p2.year.nil?
1
else
p1.year <=> p2.year
end
}.each do |pub|
y = pub.year
if y.nil? #ignore publications with improperly parsed years
fails += 1
next
end
ids = CodingRegion.all(:select => 'coding_regions.id',
:joins => {
:expression_contexts => [:localisation, :publication]
},
:conditions => {:publications => {:id => pub.id}}
)
ids.each do |i|
unless already_localised.include?(i)
already_localised.push i
years[y] ||= 0
years[y] += 1
end
end
end
puts ['Year','Number of New Protein Localisations'].join("\t")
years.sort.each do |a,b|
puts [a,b].join("\t")
end
$stderr.puts "Failed to year-ify #{fails} publications."
end
# How many and which genes are recorded in the malaria metabolic pathways database,
# but aren't recorded in ApiLoc?
def comparison_with_hagai
File.open("#{PHD_DIR}/screenscraping_hagai/localised_genes_and_links.txt").each_line do |line|
line.strip!
splits = line.split(' ')
#next unless splits[0].match(/#{splits[1]}/) #ignore possibly incorrect links
code = CodingRegion.ff(splits[1])
unless code
puts "Couldn't find plasmodb id #{splits[1]}"
next
end
if code.expressed_localisations.count == 0
puts "Not found in ApiLoc: #{splits[1]}"
else
puts "Found in ApiLoc: #{splits[1]}"
end
end
end
# Create a spreadsheet with all the synonyms, so it can be attached as supplementary
def synonyms_spreadsheet
sep = "\t"
# Print titles
puts [
"Localistion or Developmental Stage?",
"Species",
"Full name(s)",
"Synonym"
].join(sep)
# Procedure for printing out each of the hits
printer = lambda do |species_name, actual, synonym, cv_name|
if actual.kind_of?(Array)
puts [cv_name, species_name, actual.join(","), synonym].join(sep)
else
puts [cv_name, species_name, actual, synonym].join(sep)
end
end
# Print all the synonyms
[
LocalisationConstants::KNOWN_LOCALISATION_SYNONYMS,
DevelopmentalStageConstants::KNOWN_DEVELOPMENTAL_STAGE_SYNONYMS,
].each do |cv|
cv_name = {
DevelopmentalStageConstants::KNOWN_DEVELOPMENTAL_STAGE_SYNONYMS => 'Developmental Stage',
LocalisationConstants::KNOWN_LOCALISATION_SYNONYMS => 'Localisation'
}[cv]
cv.each do |sp, hash|
if sp == Species::OTHER_SPECIES #for species not with a genome project
# Species::OTHER_SPECIES => {
# 'Sarcocystis muris' => {
# 'surface' => 'cell surface'
# },
# 'Babesia gibsoni' => {
# 'surface' => 'cell surface',
# 'erythrocyte cytoplasm' => 'host cell cytoplasm',
# 'pm' => 'plasma membrane',
# 'membrane' => 'plasma membrane'
# },
hash.each do |species_name, hash2|
hash2.each do |synonym, actual|
printer.call(species_name, actual, synonym, cv_name)
end
end
else #normal species
hash.each do |synonym, actual|
printer.call(sp, actual, synonym, cv_name)
end
end
end
end
end
def umbrella_localisations_controlled_vocabulary
sep = "\t"
# Print titles
puts [
"Localistion or Developmental Stage?",
"Umbrella",
"Specific Localisation Name"
].join(sep)
ApilocLocalisationTopLevelLocalisation::APILOC_TOP_LEVEL_LOCALISATION_HASH.each do |umbrella, unders|
unders.each do |under|
puts ["Localisation", umbrella, under].join(sep)
end
end
DevelopmentalStageTopLevelDevelopmentalStage::APILOC_DEVELOPMENTAL_STAGE_TOP_LEVEL_DEVELOPMENTAL_STAGES.each do |under, umbrella|
puts ["Developmental Stage", umbrella, under].join(sep)
end
end
def how_many_apicomplexan_genes_have_localised_orthologues
$stderr.puts "starting group search"
groups = OrthomclGroup.official.all(
:joins => {:orthomcl_genes => {:coding_regions => :coding_region_compartment_caches}},
:select => 'distinct(orthomcl_groups.id)'
)
$stderr.puts "finished group search, found #{groups.length} groups"
group_ids = groups.collect{|g| g.id}
$stderr.puts "finished group id transform"
puts '# Genes that have localised ortholgues, if you consider GO CC IDA terms from all Eukaryotes'
Species.sequenced_apicomplexan.all.each do |sp|
num_orthomcl_genes = OrthomclGene.code(sp.orthomcl_three_letter).count(
:select => 'distinct(orthomcl_genes.id)'
)
# go through the groups and work out how many coding regions there are in those groups from this species
num_with_a_localised_orthologue = OrthomclGene.code(sp.orthomcl_three_letter).count(
:select => 'distinct(orthomcl_genes.id)',
:joins => :orthomcl_groups,
:conditions => "orthomcl_gene_orthomcl_group_orthomcl_runs.orthomcl_group_id in #{group_ids.to_sql_in_string}"
)
puts [
sp.name,
num_orthomcl_genes,
num_with_a_localised_orthologue
].join("\t")
end
puts
puts '# Genes that have localised ortholgues, if you don\'t consider GO CC IDA terms from all Eukaryotes'
$stderr.puts "starting group search"
groups = OrthomclGroup.official.all(
:joins => {:orthomcl_genes => {:coding_regions => :expressed_localisations}},
:select => 'distinct(orthomcl_groups.id)'
)
$stderr.puts "finished group search, found #{groups.length} groups"
group_ids = groups.collect{|g| g.id}
$stderr.puts "finished group id transform"
puts '# Genes that have localised ortholgues, if you consider GO CC IDA terms from all Eukaryotes'
Species.sequenced_apicomplexan.all.each do |sp|
num_orthomcl_genes = OrthomclGene.code(sp.orthomcl_three_letter).count(
:select => 'distinct(orthomcl_genes.id)'
)
# go through the groups and work out how many coding regions there are in those groups from this species
num_with_a_localised_orthologue = OrthomclGene.code(sp.orthomcl_three_letter).count(
:select => 'distinct(orthomcl_genes.id)',
:joins => :orthomcl_groups,
:conditions => "orthomcl_gene_orthomcl_group_orthomcl_runs.orthomcl_group_id in #{group_ids.to_sql_in_string}"
)
puts [
sp.name,
num_orthomcl_genes,
num_with_a_localised_orthologue
].join("\t")
end
end
end
added untested method for finding conservation of localisation in apicomplexa
require "zlib"
require 'pp'
# Methods used in the ApiLoc publication
class BScript
def apiloc_stats
puts "For each species, how many genes, publications"
total_proteins = 0
total_publications = 0
Species.apicomplexan.all.sort{|a,b| a.name <=> b.name}.each do |s|
protein_count = s.number_of_proteins_localised_in_apiloc
publication_count = s.number_of_publications_in_apiloc
puts [
s.name,
protein_count,
publication_count,
].join("\t")
total_proteins += protein_count
total_publications += publication_count
end
puts [
'Total',
total_proteins,
total_publications
].join("\t")
end
# Like HTML stats, but used for the version information part
# of the ApiLoc website
def apiloc_html_stats
total_proteins = 0
total_publications = 0
puts '<table>'
puts '<tr><th>Species</th><th>Localised genes</th><th>Publications curated</th></tr>'
Species.apicomplexan.all.push.sort{|a,b| a.name <=> b.name}.each do |s|
protein_count = s.number_of_proteins_localised_in_apiloc
publication_count = s.number_of_publications_in_apiloc
puts "<tr><td><i>#{s.name}</i></td><td>#{protein_count}</td><td>#{publication_count}</td></tr>"
total_proteins += protein_count
total_publications += publication_count
end
print [
'<tr><td><b>Total</b>',
total_proteins,
total_publications
].join("</b></td><td><b>")
puts '</b></td></tr>'
puts '</table>'
end
def species_localisation_breakdown
# names = Localisation.all(:joins => :apiloc_top_level_localisation).reach.name.uniq.push(nil)
# print "species\t"
# puts names.join("\t")
top_names = [
'apical',
'inner membrane complex',
'merozoite surface',
'parasite plasma membrane',
'parasitophorous vacuole',
'exported',
'cytoplasm',
'food vacuole',
'mitochondrion',
'apicoplast',
'golgi',
'endoplasmic reticulum',
'other',
'nucleus'
]
interests = [
'Plasmodium falciparum',
'Toxoplasma gondii',
'Plasmodium berghei',
'Cryptosporidium parvum'
]
puts [nil].push(interests).flatten.join("\t")
top_names.each do |top_name|
top = TopLevelLocalisation.find_by_name(top_name)
print top_name
interests.each do |name|
s = Species.find_by_name(name)
if top.name == 'other'
count = 0
CodingRegion.all(
:select => 'distinct(coding_regions.id)',
:joins => {:expression_contexts => {:localisation => :apiloc_top_level_localisation}},
:conditions => ['top_level_localisation_id = ? and species_id = ?', top.id, s.id]
).each do |code|
tops = code.expressed_localisations.reach.apiloc_top_level_localisation.flatten
if tops.length == 1
raise unless tops[0].name == 'other'
count += 1
end
end
print "\t#{count}"
else
count = CodingRegion.count(
:select => 'distinct(coding_regions.id)',
:joins => {:expression_contexts => {:localisation => :apiloc_top_level_localisation}},
:conditions => ['top_level_localisation_id = ? and species_id = ?', top.id, s.id]
)
print "\t#{count}"
end
end
puts
end
end
def how_many_falciparum_genes_have_toxo_orthologs
puts ".. all according to orthomcl #{OrthomclRun::ORTHOMCL_OFFICIAL_NEWEST_NAME}"
all_orthomcl_groups_with_falciparum = OrthomclRun.find_by_name(OrthomclRun::ORTHOMCL_OFFICIAL_NEWEST_NAME).orthomcl_groups.select {|group|
group.orthomcl_genes.code('pfa').count > 0
}
puts "How many P. falciparum orthomcl groups?"
puts all_orthomcl_groups_with_falciparum.length
numbers_of_orthologs = all_orthomcl_groups_with_falciparum.each do |group|
group.orthomcl_genes.code('tgo').count
end
puts
puts "How many P. falciparum genes have any toxo orthomcl orthologs?"
puts numbers_of_orthologs.reject {|num|
num == 0
}.length
puts
puts "How many P. falciparum genes have 1 to 1 mapping with toxo?"
puts all_orthomcl_groups_with_falciparum.select {|group|
group.orthomcl_genes.code('pfa') == 1 and group.orthomcl_genes.code('tgo') == 1
}
end
def distribution_of_falciparum_hits_given_toxo
toxo_only = []
falc_only = []
no_hits = []
hits_not_localised = []
falc_and_toxo = []
# why the hell doesn't bioruby do this for me?
falciparum_blasts = {}
toxo_blasts = {}
# convert the blast file as it currently exists into a hash of plasmodb => blast_hits
Bio::Blast::Report.new(
File.open("#{PHD_DIR}/apiloc/experiments/falciparum_vs_toxo_blast/falciparum_v_toxo.1e-5.tab.out",'r').read,
:tab
).iterations[0].hits.each do |hit|
q = hit.query_id.gsub(/.*\|/,'')
s = hit.definition.gsub(/.*\|/,'')
falciparum_blasts[q] ||= []
falciparum_blasts[q].push s
end
Bio::Blast::Report.new(
File.open("#{PHD_DIR}/apiloc/experiments/falciparum_vs_toxo_blast/toxo_v_falciparum.1e-5.tab.out",'r').read,
:tab
).iterations[0].hits.each do |hit|
q = hit.query_id.gsub(/.*\|/,'')
s = hit.definition.gsub(/.*\|/,'')
toxo_blasts[q] ||= []
toxo_blasts[q].push s
end
# On average, how many hits does the toxo gene have to falciparum given
# arbitrary 1e-5 cutoff?
# File.open("#{PHD_DIR}/apiloc/experiments/falciparum_to_toxo_how_many_hits.csv",'w') do |how_many_hits|
# File.open("#{PHD_DIR}/apiloc/experiments/falciparum_to_toxo_best_evalue.csv",'w') do |best_evalue|
File.open("#{PHD_DIR}/apiloc/experiments/falciparum_to_toxo_best_evalue.csv", 'w') do |loc_comparison|
blast_hits = CodingRegion.s(Species::FALCIPARUM_NAME).all(
:joins => :amino_acid_sequence,
:include => {:expression_contexts => :localisation}
# :limit => 10,
# :conditions => ['string_id = ?', 'PF13_0280']
).collect do |falciparum|
# does this falciparum have a hit?
# compare localisation of the falciparum and toxo protein
falciparum_locs = falciparum.expression_contexts.reach.localisation.reject{|l| l.nil?}
toxo_ids = falciparum_blasts[falciparum.string_id]
toxo_ids ||= []
toxos = toxo_ids.collect do |toxo_id|
t = CodingRegion.find_by_name_or_alternate_and_species(toxo_id, Species::TOXOPLASMA_GONDII)
raise unless t
t
end
toxo_locs = toxos.collect {|toxo|
toxo.expression_contexts.reach.localisation.retract
}.flatten.reject{|l| l.nil?}
if toxos.length > 0
# protein localised in falciparum but not in toxo
if !falciparum_locs.empty? and !toxo_locs.empty?
loc_comparison.puts [
falciparum.string_id,
falciparum.annotation.annotation,
falciparum.localisation_english
].join("\t")
toxos.each do |toxo|
loc_comparison.puts [
toxo.string_id,
toxo.annotation.annotation,
toxo.localisation_english
].join("\t")
end
loc_comparison.puts
falc_and_toxo.push [falciparum, toxos]
end
# stats about how well the protein is localised
if toxo_locs.empty? and !falciparum_locs.empty?
falc_only.push [falciparum, toxos]
end
if !toxo_locs.empty? and falciparum_locs.empty?
toxo_only.push [falciparum, toxos]
end
if toxo_locs.empty? and falciparum_locs.empty?
hits_not_localised.push falciparum.string_id
end
else
no_hits.push falciparum.string_id
end
end
end
puts "How many genes are localised in toxo and falciparum?"
puts falc_and_toxo.length
puts
puts "How many genes are localised in toxo but not in falciparum?"
puts toxo_only.length
puts
puts "How many genes are localised in falciparum but not in toxo?"
puts falc_only.length
puts
puts "How many falciparum genes have no toxo hit?"
puts no_hits.length
puts
puts "How many have hits but are not localised?"
puts hits_not_localised.length
puts
end
def tgo_v_pfa_crossover_count
both = OrthomclGroup.all_overlapping_groups(%w(tgo pfa))
pfa = OrthomclGroup.all_overlapping_groups(%w(pfa))
tgo = OrthomclGroup.all_overlapping_groups(%w(tgo))
both_genes_pfa = both.collect{|b| b.orthomcl_genes.codes(%w(pfa)).count(:select => 'distinct(orthomcl_genes.id)')}.sum
both_genes_tgo = both.collect{|b| b.orthomcl_genes.codes(%w(tgo)).count(:select => 'distinct(orthomcl_genes.id)')}.sum
pfa_genes = CodingRegion.s(Species::FALCIPARUM).count(:joins => :amino_acid_sequence)
tgo_genes = CodingRegion.s(Species::TOXOPLASMA_GONDII).count(:joins => :amino_acid_sequence)
puts "How many OrthoMCL groups have at least one protein in pfa and tgo?"
puts "#{both.length} groups, #{both_genes_pfa} falciparum genes, #{both_genes_tgo} toxo genes"
puts
puts "How many OrthoMCL groups are specific to falciparum?"
puts "#{pfa.length - both.length} groups, #{pfa_genes - both_genes_pfa} genes"
puts
puts "How many OrthoMCL groups are specific to toxo?"
puts "#{tgo.length - both.length} groups, #{tgo_genes - both_genes_tgo} genes"
puts
end
# Print out a fasta file of all the sequences that are in apiloc.
# If a block is given it takes each coding region so that it can be transformed
# into a fasta sequence header as in AminiAcidSequence#fasta, otherwise
# a default is used.
def apiloc_fasta(io = $stdout)
CodingRegion.all(
:joins => :expression_contexts
).uniq.each do |code|
if code.amino_acid_sequence and code.amino_acid_sequence.sequence.length > 0
io.print ">"
if block_given?
io.puts yield(code)
else
io.puts [
code.species.name,
code.string_id,
code.annotation ? code.annotation.annotation : nil
].join(' | ')
end
io.puts code.amino_acid_sequence.sequence
else
$stderr.puts "Couldn't find amino acid sequence for #{code.string_id}/#{code.id}"
end
end
end
def apiloc_mapping_orthomcl_v3
# Starting with falciparum, how many genes have localised orthologues?
CodingRegion.falciparum.all(
:joins => {:expression_contexts => :localisation},
:select => 'distinct(coding_regions.*)'
).each do |code|
next if ["PF14_0078",'PF13_0011'].include?(code.string_id) #fair enough there is no orthomcl for this - just the way v3 is.
# Is this in orthomcl
ogene = nil
begin
ogene = code.single_orthomcl
rescue CodingRegion::UnexpectedOrthomclGeneCount
next
end
if ogene
groups = ogene.orthomcl_groups
raise unless groups.length == 1
group = groups[0]
others = group.orthomcl_genes.apicomplexan.all.reject{|r| r.id==ogene.id}
next if others.empty?
orthologues = CodingRegion.all(
:joins => [
{:expression_contexts => :localisation},
:orthomcl_genes,
],
:conditions => "orthomcl_genes.id in (#{others.collect{|o|o.id}.join(',')})",
:select => 'distinct(coding_regions.*)'
)
if orthologues.empty?
$stderr.puts "Nothing useful found for #{code.names.join(', ')}"
else
# output the whole group, including localisations where known
puts [
code.string_id,
code.case_sensitive_literature_defined_coding_region_alternate_string_ids.reach.name.join(', '),
code.annotation.annotation,
code.localisation_english
].join("\t")
group.orthomcl_genes.apicomplexan.all.each do |oge|
next if %w(cmur chom).include?(oge.official_split[0])
c = nil
if oge.official_split[1] == 'TGGT1_036620' #stupid v3
c = CodingRegion.find_by_name_or_alternate("TGME49_084810")
else
c = oge.single_code!
end
if c.nil?
# if no coding region is returned, then don't complain too much,
# but I will check these manually later
puts oge.orthomcl_name
else
next if c.id == code.id #don't duplicate the query
print c.string_id
puts [
nil,
c.case_sensitive_literature_defined_coding_region_alternate_string_ids.reach.name.join(', '),
c.annotation.annotation,
c.localisation_english
].join("\t")
end
end
puts
end
end
end
end
# Get all of the sequences that are recorded in ApiLoc and put them into
# a blast file where the hits can be identified using a -m 8 blast output
def create_apiloc_m8_ready_blast_database
File.open('/tmp/apiloc_m8_ready.protein.fa','w') do |file|
BScript.new.apiloc_fasta(file) do |code|
"#{code.species.name.gsub(' ','_')}|#{code.string_id}"
end
end
Dir.chdir('/tmp') do
`formatdb -i apiloc_m8_ready.protein.fa`
%w(
apiloc_m8_ready.protein.fa
apiloc_m8_ready.protein.fa.phr
apiloc_m8_ready.protein.fa.pin
apiloc_m8_ready.protein.fa.psq
).each do |filename|
`mv #{filename} /blastdb`
end
end
end
# Taking all the falciparum proteins, where are the orthologues localised?
def orthomcl_localisation_annotations
CodingRegion.falciparum.all(
:joins => :expressed_localisations,
:limit => 20,
:select => 'distinct(coding_regions.*)'
).each do |code|
begin
falciparum_orthomcl_gene = code.single_orthomcl
puts [
code.string_id,
code.annotation.annotation,
falciparum_orthomcl_gene.official_group.orthomcl_genes.code('scer').all.collect { |sceg|
sceg.single_code.coding_region_go_terms.useful.all.reach.go_term.term.join(', ')
}.join(' | ')
].join("\t")
rescue CodingRegion::UnexpectedOrthomclGeneCount => e
$stderr.puts "Couldn't map #{code.string_id}/#{code.annotation.annotation} to orthomcl"
end
end
end
def upload_apiloc_relevant_go_terms
require 'ensembl'
# create the species and dummy scaffolds, genes, etc.
# yeast should already be uploaded
# yeast = Species.find_or_create_by_name_and_orthomcl_three_letter(Species::YEAST_NAME, 'scer')
# human = Species.find_or_create_by_name_and_orthomcl_three_letter(Species::HUMAN_NAME, 'hsap')
# mouse = Species.find_or_create_by_name_and_orthomcl_three_letter(Species::MOUSE_NAME, 'mmus')
# mouse = Species.find_or_create_by_name_and_orthomcl_three_letter(Species::ELEGANS_NAME, 'cele')
gene = Gene.new.create_dummy('apiloc conservation dummy gene for multiple species')
ensembl_uniprot_db = ExternalDb.find_by_db_name("Uniprot/SWISSPROT")
# for each human, mouse, yeast gene in a group with a localised apicomplexan
# gene, get the go terms from Ensembl so we can start to compare them later
# OrthomclGroup.all(
ogroup = OrthomclGroup.first(
:joins => {
:orthomcl_gene_orthomcl_group_orthomcl_runs => [
:orthomcl_run,
{:orthomcl_gene => {:coding_regions => :expressed_localisations}}
]
},
:conditions => {
:orthomcl_runs => {:name => OrthomclRun::ORTHOMCL_OFFICIAL_VERSION_3_NAME}
}
)
# ).each do |ogroup|
ogroup.orthomcl_genes.codes(%w(hsap mmus scer cele)).all.each do |orthomcl_gene|
ensembl = OrthomclGene.new.official_split[1]
# fetch the uniprot ID from Ensembl
ensp = Ensembl::Core::Translation.find_by_stable_id(ensembl)
unless ensp
$stderr.puts "Couldn't find ensembl gene to match #{ensembl}, skipping"
next
end
# extract the uniprot id
uniprots = ensp.xrefs.select{|x| ensembl_uniprot_db.id == x.id}.collect{|x| x.db_primaryacc}.uniq
uniprot = uniprots[0]
unless uniprots.length == 1
$stderr.puts "Unexpected number of uniprot IDs found: #{uniprots.inspect}"
next if uniprots.empty?
end
# wget the uniprot txt file entry
filename = "/tmp/uniprot#{uniprot}.txt"
`wget http://www.uniprot.org/#{uniprot}.txt -O #{filename}`
# parse the uniprot entry
bio = Bio::Uniprot.new(File.open(filename).read)
p bio
# create the gene
# find the GO term that I've annnotated, otherwise add a new one, which
# will need to be filled in with the term
# add the relevant GO term and evidence code
# end
end
end
# not realyl working - too slow for me.
def map_using_uniprot_mapper
# require 'uni_prot_i_d_mapping_selected'
# mapper = Bio::UniProtIDMappingSelected.new
# ogroup =
OrthomclGroup.all(
# :limit => 5,
:joins => {
:orthomcl_gene_orthomcl_group_orthomcl_runs => [
:orthomcl_run,
{:orthomcl_gene => {:coding_regions => :expressed_localisations}}
]
},
:conditions => {
:orthomcl_runs => {:name => OrthomclRun::ORTHOMCL_OFFICIAL_VERSION_3_NAME}
}
# )
).each do |ogroup|
ogroup.orthomcl_genes.codes(%w(mmus)).all.each do |orthomcl_gene|
ensembl = orthomcl_gene.official_split[1]
puts ensembl
# mapped = mapper.find_by_ensembl_protein_id(ensembl)
# p mapped
end
end
end
def generate_biomart_to_go_input
{
'hsap' => 'human',
'mmus' => 'mouse',
'atha' => 'arabidopsis',
'dmel' => 'fly',
'cele' => 'worm',
'scer' => 'yeast',
'crei' => 'chlamydomonas',
'tthe' => 'tetrahymena',
'rnor' => 'rat',
'spom' => 'pombe',
}.each do |code, name|
$stderr.puts name
out = File.open("#{species_orthologue_folder}/#{name}.txt",'w')
OrthomclGroup.all(
:joins => {
:orthomcl_gene_orthomcl_group_orthomcl_runs => [
:orthomcl_run,
{:orthomcl_gene => {:coding_regions => :expressed_localisations}}
]
},
:conditions => {
:orthomcl_runs => {:name => OrthomclRun::ORTHOMCL_OFFICIAL_VERSION_3_NAME}
}
).uniq.each do |ogroup|
ogroup.orthomcl_genes.code(code).all.each do |orthomcl_gene|
ensembl = orthomcl_gene.official_split[1]
out.puts ensembl
end
end
end
end
# \
def species_orthologue_folder; "#{PHD_DIR}/apiloc/species_orthologues3"; end
# all the methods required to get from the biomart and uniprot
# id to GO term mappings to a spreadsheet that can be inspected for the
# localisations required.
def apiloc_gathered_output_to_generated_spreadsheet_for_inspection
upload_apiloc_ensembl_go_terms
upload_apiloc_uniprot_go_terms
upload_apiloc_uniprot_mappings
upload_apiloc_flybase_mappings
# for some reason a single refseq sequence can be linked to multiple uniprot sequences,
# which is stupid but something I'll have to live with
OrthomclGene.new.link_orthomcl_and_coding_regions(%w(atha), :accept_multiple_coding_regions=>true)
OrthomclGene.new.link_orthomcl_and_coding_regions(%w(hsap mmus dmel cele))
generate_apiloc_orthomcl_groups_for_inspection
end
def upload_apiloc_ensembl_go_terms
{
'human' => Species::HUMAN_NAME,
'mouse' => Species::MOUSE_NAME,
'rat' => Species::RAT_NAME,
}.each do |this_name, proper_name|
$stderr.puts this_name
FasterCSV.foreach("#{species_orthologue_folder}/biomart_results/#{this_name}.csv",
:col_sep => "\t",
:headers => true
) do |row|
protein_name = row['Ensembl Protein ID']
go_id = row['GO Term Accession (cc)']
evidence = row['GO Term Evidence Code (cc)']
next if go_id.nil? #ignore empty columns
code = CodingRegion.find_or_create_dummy(protein_name, proper_name)
go = GoTerm.find_by_go_identifier_or_alternate go_id
unless go
$stderr.puts "Couldn't find GO id #{go_id}"
next
end
CodingRegionGoTerm.find_or_create_by_coding_region_id_and_go_term_id_and_evidence_code(
code.id, go.id, evidence
) or raise
end
end
end
def upload_apiloc_uniprot_go_terms
{
'arabidopsis' => Species::ARABIDOPSIS_NAME,
'worm' => Species::ELEGANS_NAME,
'fly' => Species::DROSOPHILA_NAME
}.each do |this_name, proper_name|
File.open("#{species_orthologue_folder}/uniprot_results/#{this_name}.uniprot.txt").read.split("//\n").each do |uniprot|
u = Bio::UniProt.new(uniprot)
axes = u.ac
protein_name = axes[0]
raise unless protein_name
code = CodingRegion.find_or_create_dummy(protein_name, proper_name)
protein_alternate_names = axes[1..(axes.length-1)].no_nils
protein_alternate_names.each do |name|
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name(
code.id, name
) or raise
end
goes = u.dr["GO"]
next if goes.nil? #no go terms associated
goes.each do |go_array|
go_id = go_array[0]
evidence_almost = go_array[2]
evidence = nil
if (matches = evidence_almost.match(/^([A-Z]{2,3})\:.*$/))
evidence = matches[1]
end
# error checking
if evidence.nil?
raise Exception, "No evidence code found in #{go_array.inspect} from #{evidence_almost}!"
end
go = GoTerm.find_by_go_identifier_or_alternate go_id
unless go
$stderr.puts "Couldn't find GO id #{go_id}"
next
end
CodingRegionGoTerm.find_or_create_by_coding_region_id_and_go_term_id_and_evidence_code(
code.id, go.id, evidence
).save!
end
end
end
end
def upload_apiloc_uniprot_mappings
{
'arabidopsis' => Species::ARABIDOPSIS_NAME,
'worm' => Species::ELEGANS_NAME,
'fly' => Species::DROSOPHILA_NAME
}.each do |this_name, proper_name|
FasterCSV.foreach("#{species_orthologue_folder}/uniprot_results/#{this_name}.mapping.tab",
:col_sep => "\t", :headers => true
) do |row|
code = CodingRegion.fs(row[1], proper_name) or raise Exception, "Don't know #{row[1]}"
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name(
code.id, row[0]
)
end
end
end
# Drosophila won't match well to orthomcl because orthomcl uses protein IDs whereas
# uniprot uses gene ids.
# This file was created by using the (useful and working) ID converter in flybase
def upload_apiloc_flybase_mappings
FasterCSV.foreach("#{species_orthologue_folder}/uniprot_results/flybase.mapping.tab",
:col_sep => "\t"
) do |row|
next if row[1] == 'unknown ID' #ignore rubbish
gene_id = row[3]
next if gene_id == '-' # not sure what this is, but I'll ignore for the moment
protein_id = row[1]
code = CodingRegion.fs(gene_id, Species::DROSOPHILA_NAME)
if code.nil?
$stderr.puts "Couldn't find gene #{gene_id}, skipping"
next
end
CodingRegionAlternateStringId.find_or_create_by_name_and_coding_region_id(
protein_id, code.id
)
end
end
# Return a list of orthomcl groups that fulfil these conditions:
# 1. It has a localised apicomplexan gene in it, as recorded by ApiLoc
# 2. It has a localised non-apicomplexan gene in it, as recorded by GO CC IDA annotation
def apiloc_orthomcl_groups_of_interest
OrthomclGroup.all(
:select => 'distinct(orthomcl_groups.*)',
:joins => {
:orthomcl_gene_orthomcl_group_orthomcl_runs => [
:orthomcl_run,
{:orthomcl_gene => {:coding_regions => [
:expressed_localisations
]}}
]
},
:conditions => {
:orthomcl_runs => {:name => OrthomclRun::ORTHOMCL_OFFICIAL_VERSION_3_NAME},
}
).select do |ogroup|
# only select those groups that have go terms annotated in non-apicomplexan species
OrthomclGroup.count(
:joins => {:coding_regions =>[
:go_terms
]},
:conditions => ['orthomcl_groups.id = ? and coding_region_go_terms.evidence_code = ? and go_terms.partition = ?',
ogroup.id, 'IDA', GoTerm::CELLULAR_COMPONENT
]
) > 0
end
end
def generate_apiloc_orthomcl_groups_for_inspection
interestings = %w(hsap mmus scer drer osat crei atha dmel cele)
apiloc_orthomcl_groups_of_interest.each do |ogroup|
paragraph = []
ogroup.orthomcl_genes.all.each do |orthomcl_gene|
four = orthomcl_gene.official_split[0]
# Possible to have many coding regions now - using all of them just together, though there is
# probably one good one and other useless and IEA if anything annotated. Actually
# not necesssarilly, due to strain problems.
#
# Only print out one entry for each OrthoMCL gene, to condense things
# but that line should have all the (uniq) go terms associated
orthomcl_gene.coding_regions.uniq.each do |code|
if OrthomclGene::OFFICIAL_ORTHOMCL_APICOMPLEXAN_CODES.include?(four)
paragraph.push [
orthomcl_gene.orthomcl_name,
code.nil? ? nil : code.annotation.annotation,
code.nil? ? nil : code.localisation_english,
].join("\t")
elsif interestings.include?(four)
unless code.nil?
goes = code.coding_region_go_terms.cc.useful.all
unless goes.empty?
worthwhile = true
orig = orthomcl_gene.orthomcl_name
goes.each do |code_go|
paragraph.push [
orig,
code_go.go_term.go_identifier,
code_go.go_term.term,
code_go.evidence_code
].join("\t")
orig = ''
end
end
end
end
end
end
puts paragraph.uniq.join("\n")
puts
end
end
def apiloc_go_localisation_conservation_groups_to_database
# FasterCSV.foreach("#{PHD_DIR}/apiloc/species_orthologues2/breakdown.manual.xls",
# FasterCSV.foreach("#{PHD_DIR}/apiloc/species_orthologues4/breakdown2.manual.csv",
FasterCSV.foreach("#{PHD_DIR}/apiloc/species_orthologues4/breakdown3.manual.csv",
:col_sep => "\t"
) do |row|
# ignore lines that have nothing first or are the header line
next unless row[0] and row[0].length > 0 and row[3]
single = row[0]
eg = row[1]
full = OrthomclLocalisationConservations.single_letter_to_full_name(single)
raise Exception, "Couldn't understand single letter '#{single}'" unless full
# find the orthomcl group by using the gene in the first line (the example)
ogene = OrthomclGene.official.find_by_orthomcl_name(eg)
raise Exception, "Coun't find orthomcl gene '#{eg}' as expected" if ogene.nil?
# create the record
OrthomclLocalisationConservations.find_or_create_by_orthomcl_group_id_and_conservation(
ogene.official_group.id, full
).id
end
end
def yes_vs_no_human_examples
OrthomclLocalisationConservations.all.collect do |l|
max_human = OrthomclGene.code('hsap').all(
:joins =>[
[:coding_regions => :go_terms],
:orthomcl_gene_orthomcl_group_orthomcl_runs
],
:conditions => {:orthomcl_gene_orthomcl_group_orthomcl_runs => {:orthomcl_group_id => l.orthomcl_group_id}}
).max do |h1, h2|
counter = lambda {|h|
CodingRegionGoTerm.cc.useful.count(
:joins => {:coding_region => :orthomcl_genes},
:conditions => {:orthomcl_genes => {:id => h.id}}
)
}
counter.call(h1) <=> counter.call(h2)
end
next unless max_human
puts [
l.conservation,
max_human.coding_regions.first.names.sort
].flatten.join("\t")
end
end
def upload_uniprot_identifiers_for_ensembl_ids
FasterCSV.foreach("#{species_orthologue_folder}/gostat/human_ensembl_uniprot_ids.txt",
:col_sep => "\t", :headers => true
) do |row|
ens = row['Ensembl Protein ID']
uni = row['UniProt/SwissProt Accession']
raise unless ens
next unless uni
code = CodingRegion.f(ens)
raise unless code
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, uni, CodingRegionAlternateStringId::UNIPROT_SOURCE_NAME
) or raise
end
end
def download_uniprot_data
UNIPROT_SPECIES_ID_NAME_HASH.each do |taxon_id, species_name|
# Download the data into the expected name
Dir.chdir("#{DATA_DIR}/UniProt/knowledgebase") do
unless File.exists?("#{species_name}.gz")
cmd = "wget -O '#{species_name}.gz' 'http://www.uniprot.org/uniprot/?query=taxonomy%3a#{taxon_id}&compress=yes&format=txt'"
p cmd
`#{cmd}`
end
end
end
end
# Delete all the data associated with the uniprot species so
# I can start again.
def destroy_all_uniprot_species
APILOC_UNIPROT_SPECIES_NAMES.each do |species_name|
s = Species.find_by_name(species_name)
puts "#{species_name}..."
s.delete unless s.nil?
end
end
UNIPROT_SPECIES_ID_NAME_HASH = {
3702 => Species::ARABIDOPSIS_NAME,
9606 => Species::HUMAN_NAME,
10090 => Species::MOUSE_NAME,
4932 => Species::YEAST_NAME,
4896 => Species::POMBE_NAME,
10116 => Species::RAT_NAME,
7227 => Species::DROSOPHILA_NAME,
6239 => Species::ELEGANS_NAME,
44689 => Species::DICTYOSTELIUM_DISCOIDEUM_NAME,
7955 => Species::DANIO_RERIO_NAME,
5691 => Species::TRYPANOSOMA_BRUCEI_NAME,
}
APILOC_UNIPROT_SPECIES_NAMES = UNIPROT_SPECIES_ID_NAME_HASH.values
# Given that the species of interest are already downloaded from uniprot
# (using download_uniprot_data for instance), upload this data
# to the database, including GO terms. Other things need to be run afterwards
# to be able to link to OrthoMCL.
#
# This method could be more DRY - UniProtIterator could replace
# much of the code here. But eh for the moment.
def uniprot_to_database(species_names=nil)
species_names ||= APILOC_UNIPROT_SPECIES_NAMES
species_names = [species_names] unless species_names.kind_of?(Array)
species_names.each do |species_name|
count = 0
current_uniprot_string = ''
complete_filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz"
# Convert the whole gzip in to a smaller one, so parsing is faster:
# Don't use a static name because if two instance are running clashes occur.
Tempfile.open("#{species_name}_reduced") do |tempfile|
filename = tempfile.path
cmd = "zcat '#{complete_filename}' |egrep '^(AC|DR GO|//)' >'#{filename}'"
`#{cmd}`
dummy_gene = Gene.find_or_create_dummy(species_name)
progress = ProgressBar.new(species_name, `grep '^//' '#{filename}' |wc -l`.to_i)
File.foreach(filename) do |line|
if line == "//\n"
count += 1
progress.inc
#current uniprot is finished - upload it
#puts current_uniprot_string
u = Bio::UniProt.new(current_uniprot_string)
# Upload the UniProt name as the
axes = u.ac
protein_name = axes[0]
raise unless protein_name
code = CodingRegion.find_or_create_by_gene_id_and_string_id(
dummy_gene.id,
protein_name
)
raise unless code.save!
protein_alternate_names = axes.no_nils
protein_alternate_names.each do |name|
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, name, 'UniProt'
) or raise
end
goes = u.dr["GO"]
goes ||= [] #no go terms associated - best to still make it to the end of the method, because it is too complex here for such hackery
goes.each do |go_array|
go_id = go_array[0]
evidence_almost = go_array[2]
evidence = nil
if (matches = evidence_almost.match(/^([A-Z]{2,3})\:.*$/))
evidence = matches[1]
end
# error checking
if evidence.nil?
raise Exception, "No evidence code found in #{go_array.inspect} from #{evidence_almost}!"
end
go = GoTerm.find_by_go_identifier_or_alternate go_id
if go
CodingRegionGoTerm.find_or_create_by_coding_region_id_and_go_term_id_and_evidence_code(
code.id, go.id, evidence
).save!
else
$stderr.puts "Couldn't find GO id #{go_id}"
end
end
current_uniprot_string = ''
else
current_uniprot_string += line
end
end
progress.finish
end #tempfile
$stderr.puts "Uploaded #{count} from #{species_name}, now there is #{CodingRegion.s(species_name).count} coding regions in #{species_name}."
end
#uploadin the last one not required because the last line is always
# '//' already - making it easy.
end
def tetrahymena_orf_names_to_database
species_name = Species::TETRAHYMENA_NAME
current_uniprot_string = ''
filename = "#{DATA_DIR}/UniProt/knowledgebase/#{Species::TETRAHYMENA_NAME}.gz"
progress = ProgressBar.new(Species::TETRAHYMENA_NAME, `gunzip -c '#{filename}' |grep '^//' |wc -l`.to_i)
Zlib::GzipReader.open(filename).each do |line|
if line == "//\n"
progress.inc
#current uniprot is finished - upload it
u = Bio::UniProt.new(current_uniprot_string)
axes = u.ac
protein_name = axes[0]
raise unless protein_name
code = CodingRegion.fs(protein_name, species_name)
raise unless code
u.gn[0][:orfs].each do |orfname|
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name(
code.id, orfname
)
end
current_uniprot_string = ''
else
current_uniprot_string += line
end
end
end
# upload aliases so that orthomcl entries can be linked to uniprot ones.
# have to run tetrahymena_orf_names_to_database first though.
def tetrahymena_gene_aliases_to_database
bads = 0
goods = 0
filename = "#{DATA_DIR}/Tetrahymena thermophila/genome/TGD/Tt_ID_Mapping_File.txt"
progress = ProgressBar.new(Species::TETRAHYMENA_NAME, `wc -l '#{filename}'`.to_i)
FasterCSV.foreach(filename,
:col_sep => "\t"
) do |row|
progress.inc
uniprot = row[0]
orthomcl = row[1]
code = CodingRegion.fs(uniprot, Species::TETRAHYMENA_NAME)
if code.nil?
bads +=1
else
goods += 1
a = CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_source_and_name(
code.id, 'TGD', orthomcl
)
raise unless a
end
end
progress.finish
$stderr.puts "Found #{goods}, failed #{bads}"
end
def yeastgenome_ids_to_database
species_name = Species::YEAST_NAME
current_uniprot_string = ''
filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz"
progress = ProgressBar.new(species_name, `gunzip -c '#{filename}' |grep '^//' |wc -l`.to_i)
Zlib::GzipReader.open(filename).each do |line|
if line == "//\n"
progress.inc
#current uniprot is finished - upload it
u = Bio::UniProt.new(current_uniprot_string)
axes = u.ac
protein_name = axes[0]
raise unless protein_name
code = CodingRegion.fs(protein_name, species_name)
if code
unless u.gn.empty?
u.gn[0][:loci].each do |orfname|
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name(
code.id, orfname
)
end
end
else
$stderr.puts "Unable to find protein `#{protein_name}'"
end
current_uniprot_string = ''
else
current_uniprot_string += line
end
end
progress.finish
end
def elegans_wormbase_identifiers
species_name = Species::ELEGANS_NAME
current_uniprot_string = ''
complete_filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz"
# Convert the whole gzip in to a smaller one, so parsing is faster:
filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}_reduced"
`zcat '#{complete_filename}' |egrep '^(AC|DR WormBase|//)' >'#{filename}'`
progress = ProgressBar.new(species_name, `grep '^//' '#{filename}' |wc -l`.to_i)
File.foreach(filename) do |line|
if line == "//\n"
progress.inc
u = Bio::UniProt.new(current_uniprot_string)
code = CodingRegion.fs(u.ac[0], Species::ELEGANS_NAME)
raise unless code
# DR WormBase; WBGene00000467; cep-1.
ides = u.dr['WormBase']
ides ||= []
ides.flatten.each do |ident|
a = CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, ident, 'WormBase'
)
raise unless a.save!
end
current_uniprot_string = ''
else
current_uniprot_string += line
end
end
`rm #{filename}`
end
def dicystelium_names_to_database
species_name = Species::DICTYOSTELIUM_DISCOIDEUM_NAME
current_uniprot_string = ''
complete_filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz"
# Convert the whole gzip in to a smaller one, so parsing is faster:
filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}_reduced"
`zcat '#{complete_filename}' |egrep '^(AC|GN|//)' >'#{filename}'`
progress = ProgressBar.new(species_name, `grep '^//' '#{filename}' |wc -l`.to_i)
skipped_count = 0
skipped_count2 = 0
added_count = 0
File.foreach(filename) do |line|
if line == "//\n"
progress.inc
u = Bio::UniProt.new(current_uniprot_string)
code = CodingRegion.fs(u.ac[0], species_name)
raise unless code
# GN Name=myoJ; Synonyms=myo5B; ORFNames=DDB_G0272112;
unless u.gn.empty? # for some reason using u.gn when there is nothing there returns an array, not a hash. Annoying.
ides = []
u.gn.each do |g|
ides.push g[:name] unless g[:name].nil?
ides.push g[:orfs] unless g[:orfs].nil?
end
ides = ides.flatten.no_nils
ides ||= []
ides.flatten.each do |ident|
a = CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, ident, 'UniProtName'
)
raise unless a.save!
end
if ides.empty?
skipped_count2 += 1
else
added_count += 1
end
else
skipped_count += 1
end
current_uniprot_string = ''
else
current_uniprot_string += line
end
end
`rm '#{filename}'`
progress.finish
$stderr.puts "Added names for #{added_count}, skipped #{skipped_count} and #{skipped_count2}"
end
def tbrucei_names_to_database
species_name = Species::TRYPANOSOMA_BRUCEI_NAME
current_uniprot_string = ''
complete_filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz"
# Convert the whole gzip in to a smaller one, so parsing is faster:
filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}_reduced"
`zcat '#{complete_filename}' |egrep '^(AC|GN|//)' >'#{filename}'`
progress = ProgressBar.new(species_name, `grep '^//' '#{filename}' |wc -l`.to_i)
skipped_count = 0
skipped_count2 = 0
added_count = 0
File.foreach(filename) do |line|
if line == "//\n"
progress.inc
u = Bio::UniProt.new(current_uniprot_string)
code = CodingRegion.fs(u.ac[0], species_name)
raise unless code
# GN Name=myoJ; Synonyms=myo5B; ORFNames=DDB_G0272112;
unless u.gn.empty? # for some reason using u.gn when there is nothing there returns an array, not a hash. Annoying.
ides = []
u.gn.each do |g|
#ides.push g[:name] unless g[:name].nil?
ides.push g[:orfs] unless g[:orfs].nil?
end
ides = ides.flatten.no_nils
ides ||= []
ides.flatten.each do |ident|
a = CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, ident, 'UniProtName'
)
raise unless a.save!
end
if ides.empty?
skipped_count2 += 1
else
added_count += 1
end
else
skipped_count += 1
end
current_uniprot_string = ''
else
current_uniprot_string += line
end
end
`rm '#{filename}'`
progress.finish
$stderr.puts "Added names for #{added_count}, skipped #{skipped_count} and #{skipped_count2}"
end
def uniprot_ensembl_databases
[
Species::MOUSE_NAME,
Species::HUMAN_NAME,
Species::DANIO_RERIO_NAME,
Species::DROSOPHILA_NAME,
Species::RAT_NAME,
].each do |species_name|
Bio::UniProtIterator.foreach("#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz", 'DR Ensembl') do |u|
code = CodingRegion.fs(u.ac[0], species_name) or raise
ens = u.dr['Ensembl']
ens ||= []
ens.flatten.each do |e|
if e.match(/^ENS/) or (species_name == Species::DROSOPHILA_NAME and e.match(/^FBpp/))
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, e, 'Ensembl'
)
end
end
end
end
end
def uniprot_refseq_databases
[
Species::ARABIDOPSIS_NAME,
Species::RICE_NAME,
Species::POMBE_NAME,
].each do |species_name|
Bio::UniProtIterator.foreach("#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz", 'DR RefSeq') do |u|
code = CodingRegion.fs(u.ac[0], species_name) or raise
refseqs = u.dr['RefSeq']
refseqs ||= []
refseqs = refseqs.collect{|r| r[0]}
refseqs.each do |r|
r = r.gsub(/\..*/,'')
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, r, 'Refseq'
)
end
end
end
end
def chlamydomonas_link_to_orthomcl_ids
species_name = Species::CHLAMYDOMONAS_NAME
Bio::UniProtIterator.foreach("#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz", 'GN') do |u|
code = CodingRegion.fs(u.ac[0], species_name) or raise
gn = u.gn
unless gn.empty?
orfs = gn.collect{|g| g[:orfs]}
unless orfs.empty?
orfs.flatten.each do |orf|
o = 'CHLREDRAFT_168484' if orf == 'CHLRE_168484' #manual fix
raise Exception, "Unexpected orf: #{orf}" unless orf.match(/^CHLREDRAFT_/) or orf.match(/^CHLRE_/)
o = orf.gsub(/^CHLREDRAFT_/, '')
o = o.gsub(/^CHLRE_/,'')
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, o, 'JGI'
)
end
end
end
end
end
# OrthoMCL gene IDs for Drosophila are encoded in the 'DR EnsemblMetazoa;' lines,
# such as
# DR EnsemblMetazoa; FBtr0075201; FBpp0074964; FBgn0036740.
# (and in particular the FBpp ones). Upload these pp ones as synonyms
def drosophila_ensembl_metazoa
addeds = 0
non_addeds = 0
terms = 0
Bio::UniProtIterator.foreach("#{DATA_DIR}/UniProt/knowledgebase/#{Species::DROSOPHILA_NAME}.gz", 'DR EnsemblMetazoa;') do |u|
ensembl_metazoas = u.dr['EnsemblMetazoa']
if ensembl_metazoas.nil?
non_addeds += 1
else
added = false
code = CodingRegion.fs(u.ac[0], Species::DROSOPHILA_NAME) or raise
ensembl_metazoas.flatten.select{|s| s.match /^FBpp/}.each do |e|
added = true
terms+= 1
CodingRegionAlternateStringId.find_or_create_by_coding_region_id_and_name_and_source(
code.id, e, 'EnsemblMetazoa'
)
end
addeds += 1 if added
end
end
$stderr.puts "Uploaded #{terms} IDs for #{addeds} different genes, missed #{non_addeds}"
end
def uniprot_go_annotation_species_stats
APILOC_UNIPROT_SPECIES_NAMES.each do |species_name|
filename = "#{DATA_DIR}/UniProt/knowledgebase/#{species_name}.gz"
if File.exists?(filename)
puts [
species_name,
`zcat '#{filename}'|grep ' GO' |grep -v IEA |grep -v ISS |grep 'C\:' |wc -l`
].join("\t")
else
puts "Couldn't find #{species_name} uniprot file"
end
end
end
# Create a spreadsheet that encapsulates all of the localisation
# information from apiloc, so that large scale analysis is simpler
def create_apiloc_spreadsheet
nil_char = nil #because I'm not sure how the joins will work
microscopy_method_names = LocalisationAnnotation::POPULAR_MICROSCOPY_TYPE_NAME_SCOPE.keys.sort.reverse
small_split_string = '#' #use when only 1 delimiter within a cell is needed
big_split_string = ';' #use when 2 delimiters in one cell are needed
orthomcl_split_char = '_'
# Headings
puts [
'Species',
'Gene ID',
'Abbreviations',
'Official Gene Annotation',
'Localisation Summary',
'Cellular Localisation',
'Total Number of Cellular Localisations',
'OrthoMCL Group Identifier',
'Apicomplexan Orthologues with Recorded Localisation',
'Apicomplexan Orthologues without Recorded Localisation',
'Non-Apicomplexan Orthologues with IDA GO Cellular Component Annotation',
'Consensus Localisation of Orthology Group',
'PubMed IDs of Publications with Localisation',
microscopy_method_names,
'All Localisation Methods Used',
'Strains',
'Gene Model Mapping Comments',
'Quotes'
].flatten.join("\t")
codes = CodingRegion.all(:joins => :expressed_localisations).uniq
progress = ProgressBar.new('apiloc_spreadsheet', codes.length)
codes.each do |code|
$stderr.puts code.string_id
progress.inc
to_print = []
organellar_locs = []
# species
to_print.push code.species.name
#EuPath or GenBank ID
to_print.push code.string_id
#common names
to_print.push code.literature_defined_names.join(small_split_string)
#annotation
a1 = code.annotation
to_print.push(a1.nil? ? nil_char : a1.annotation)
#full localisation description
to_print.push code.localisation_english
#'organellar' localisation (one per record,
#if there is more repeat the whole record)
#this might more sensibly be GO-oriented, but eh for the moment
organellar_locs = code.topsa.uniq
to_print.push nil_char
# number of organellar localisations (ie number of records for this gene)
to_print.push organellar_locs.length
# OrthoMCL-related stuffs
ogene = code.single_orthomcl!
ogroup = (ogene.nil? ? nil : ogene.official_group)
if ogroup.nil?
5.times do
to_print.push nil_char
end
else
#orthomcl group
to_print.push ogroup.orthomcl_name
#localised apicomplexans in orthomcl group
locked = CodingRegion.all(
:joins => [
{:orthomcl_genes => :orthomcl_groups},
:expression_contexts
],
:conditions => [
'orthomcl_groups.id = ? and coding_regions.id != ?',
ogroup.id, code.id
],
:select => 'distinct(coding_regions.*)'
)
to_print.push "\"#{locked.collect{|a|
[
a.string_id,
a.annotation.annotation,
a.localisation_english
].join(small_split_string)
}.join(big_split_string)}\""
#unlocalised apicomplexans in orthomcl group
to_print.push ogroup.orthomcl_genes.apicomplexan.all.reject {|a|
a.coding_regions.select { |c|
c.expressed_localisations.count > 0
}.length > 0
}.reach.orthomcl_name.join(', ').gsub('|',orthomcl_split_char)
#non-apicomplexans with useful GO annotations in orthomcl group
#species, orthomcl id, uniprot id(s), go annotations
go_codes = CodingRegion.go_cc_usefully_termed.not_apicomplexan.all(
:joins => {:orthomcl_genes => :orthomcl_groups},
:conditions =>
["orthomcl_groups.id = ?", ogroup.id],
:select => 'distinct(coding_regions.*)',
:order => 'coding_regions.id'
)
to_print.push "\"#{go_codes.collect { |g|
[
g.species.name,
g.orthomcl_genes.reach.orthomcl_name.join(', ').gsub('|',orthomcl_split_char),
g.names.join(', '),
g.coding_region_go_terms.useful.cc.all.reach.go_term.term.join(', ')
].join(small_split_string)
}.join(big_split_string)}\""
# consensus of orthology group.
to_print.push 'consensus - TODO'
end
contexts = code.expression_contexts
annotations = code.localisation_annotations
# pubmed ids that localise the gene
to_print.push contexts.reach.publication.definition.no_nils.uniq.join(small_split_string)
# Categorise the microscopy methods
microscopy_method_names.each do |name|
scopes =
LocalisationAnnotation::POPULAR_MICROSCOPY_TYPE_NAME_SCOPE[name]
done = LocalisationAnnotation
scopes.each do |scope|
done = done.send(scope)
end
if done.find_by_coding_region_id(code.id)
to_print.push 'yes'
else
to_print.push 'no'
end
end
# localisation methods used (assume different methods never give different results for the same gene)
to_print.push annotations.reach.microscopy_method.no_nils.uniq.join(small_split_string)
# strains
to_print.push annotations.reach.strain.no_nils.uniq.join(small_split_string)
# mapping comments
to_print.push annotations.reach.gene_mapping_comments.no_nils.uniq.join(small_split_string).gsub(/\"/,'')
# quotes
# have to escape quote characters otherwise I get rows joined together
to_print.push "\"#{annotations.reach.quote.uniq.join(small_split_string).gsub(/\"/,'\"')}\""
if organellar_locs.empty?
puts to_print.join("\t")
else
organellar_locs.each do |o|
to_print[5] = o.name
puts to_print.join("\t")
end
end
end
progress.finish
end
# The big GOA file has not been 'redundancy reduced', a process which is buggy,
# like the species level ones. Here I upload the species that I'm interested
# in using that big file, not the small one
def goa_all_species_to_database
require 'gene_association'
UNIPROT_SPECIES_ID_NAME_HASH.each do |species_id, species_name|
bad_codes_count = 0
bad_go_count = 0
good_count = 0
Bio::GzipAndFilterGeneAssociation.foreach(
"#{DATA_DIR}/GOA/gene_association.goa_uniprot.gz",
"\ttaxon:#{species_id}\t"
) do |go|
name = go.primary_id
code = CodingRegion.fs(name, species_name)
unless code
$stderr.puts "Couldn't find coding region #{name}"
bad_codes_count += 1
next
end
go_term = GoTerm.find_by_go_identifier(go.go_identifier)
unless go_term
$stderr.puts "Couldn't find coding region #{go.go_identifier}"
bad_go_count += 1
next
end
CodingRegionGoTerm.find_or_create_by_coding_region_id_and_go_term_id(
code.id, go_term.id
)
good_count += 1
end
$stderr.puts "#{good_count} all good, failed to find #{bad_codes_count} coding regions and #{bad_go_count} go terms"
end
end
def how_many_genes_have_dual_localisation?
dual_loc_folder = "#{PHD_DIR}/apiloc/experiments/dual_localisations"
raise unless File.exists?(dual_loc_folder)
file = File.open(File.join(dual_loc_folder, 'duals.csv'),'w')
Species.apicomplexan.each do |species|
species_name = species.name
codes = CodingRegion.s(species_name).all(
:joins => :expressed_localisations,
:select => 'distinct(coding_regions.*)'
)
counts = []
nuc_aware_counts = []
codes_per_count = []
# write the results to the species-specific file
codes.each do |code|
next if code.string_id == CodingRegion::UNANNOTATED_CODING_REGIONS_DUMMY_GENE_NAME
tops = TopLevelLocalisation.positive.all(
:joins => {:apiloc_localisations => :expressed_coding_regions},
:conditions => ['coding_regions.id = ?',code.id],
:select => 'distinct(top_level_localisations.*)'
)
count = tops.length
counts[count] ||= 0
counts[count] += 1
codes_per_count[count] ||= []
codes_per_count[count].push code.string_id
# nucleus and cytoplasm as a single localisation if both are included
names = tops.reach.name.retract
if names.include?('nucleus') and names.include?('cytoplasm')
count -= 1
end
# Write out the coding regions to a file
# gather the falciparum data
og = code.single_orthomcl!
fals = []
if og and og.official_group
fals = og.official_group.orthomcl_genes.code('pfal').all.collect do |ogene|
ogene.single_code
end
end
file.puts [
code.species.name,
code.string_id,
code.names,
count,
code.compartments.join('|'),
fals.reach.compartments.join('|'),
fals.reach.localisation_english.join('|')
].join("\t")
nuc_aware_counts[count] ||= 0
nuc_aware_counts[count] += 1
end
puts species_name
# p codes_per_count
p counts
p nuc_aware_counts
end
file.close
end
def falciparum_test_prediction_by_orthology_to_non_apicomplexans
bins = {}
puts [
'PlasmoDB ID',
'Names',
'Compartments',
'Prediction',
'Comparison',
'Full P. falciparum Localisation Information'
].join("\t")
CodingRegion.localised.falciparum.all(
:select => 'distinct(coding_regions.*)'
).each do |code|
# Unassigned genes just cause problems for orthomcl
next if code.string_id == CodingRegion::NO_MATCHING_GENE_MODEL
# When there is more than 1 P. falciparum protein in the group, then ignore this
group = code.single_orthomcl.official_group
if group.nil?
$stderr.puts "#{code.names.join(', ')} has no OrthoMCL group, ignoring."
next
end
num = group.orthomcl_genes.code(code.species.orthomcl_three_letter).count
if num != 1
$stderr.puts "#{code.names.join(', ')} has #{num} genes in its localisation group, ignoring"
next
end
pred = code.apicomplexan_localisation_prediction_by_most_common_localisation
next if pred.nil?
goodness = code.compare_localisation_to_list(pred)
puts [
code.string_id,
code.names.join('|'),
code.compartments.join('|'),
pred,
goodness,
code.localisation_english,
].join("\t")
bins[goodness] ||= 0
bins[goodness] += 1
end
# Print the results of the analysis
p bins
end
# Looking through all the genes in the database, cache of the compartments so that things are easier to compare
def cache_all_compartments
# Cache all apicomplexan compartments
codes = CodingRegion.apicomplexan.all
progress = ProgressBar.new('apicomplexans', codes.length)
codes.each do |code|
progress.inc
comps = code.compartments
comps.each do |comp|
CodingRegionCompartmentCache.find_or_create_by_coding_region_id_and_compartment(
code.id, comp
)
end
end
progress.finish
# Cache all non-apicomplexan compartments
codes = CodingRegion.go_cc_usefully_termed.all
progress = ProgressBar.new('eukaryotes', codes.length)
codes.each do |code|
progress.inc
comps = code.compartments
comps.each do |comp|
CodingRegionCompartmentCache.find_or_create_by_coding_region_id_and_compartment(
code.id, comp
)
end
end
progress.finish
end
# How conserved is localisation between the three branches of life with significant
# data known about them?
# This method FAILS due to memory and compute time issues - I ended up
# essentially abandoning rails for this effort.
def conservation_of_eukaryotic_sub_cellular_localisation(debug = false)
groups_to_counts = {}
# For each orthomcl group that has a connection to coding region, and
# that coding region has a cached compartment
groups = OrthomclGroup.all(
# :select => 'distinct(orthomcl_groups.*)',
:joins => {:orthomcl_genes => {:coding_regions => :coding_region_compartment_caches}}
# :limit => 10,
# :include => {:orthomcl_genes => {:coding_regions => :coding_region_compartment_caches}}
)
# ProgressBar on stdout, because debug is on stderr
progress = ProgressBar.new('conservation', groups.length, STDOUT)
groups.each do |ortho_group|
progress.inc
$stderr.puts "---------------------------------------------" if debug
# For each non-Apicomplexan gene with localisation information in this group,
# assign it compartments.
# For each apicomplexan, get the compartments from apiloc
# This is nicely abstracted already!
# However, a single orthomcl gene can have multiple CodingRegion's associated.
# Therefore each has to be analysed as an array, frustratingly.
# reject the orthomcl gene if it has no coding regions associated with it.
orthomcl_genes = OrthomclGene.all(
:joins => [:coding_regions, :orthomcl_groups],
:conditions => {:orthomcl_groups => {:id => ortho_group.id}}
)
# ortho_group.orthomcl_genes.uniq.reject do |s|
# # reject the orthomcl gene if it has no coding regions associated with it.
# s.coding_regions.empty?
# end
# Setup data structures
kingdom_orthomcls = {} #array of kingdoms to orthomcl genes
orthomcl_locs = {} #array of orthomcl_genes to localisations, cached for convenience and speed
orthomcl_genes.each do |orthomcl_gene|
# Localisations from all coding regions associated with an orthomcl gene are used.
locs = CodingRegionCompartmentCache.all(
:joins => {:coding_region => :orthomcl_genes},
:conditions => {:orthomcl_genes => {:id => orthomcl_gene.id}}
).reach.compartment.uniq
# locs = orthomcl_gene.coding_regions.reach.cached_compartments.flatten.uniq
next if locs.empty? #ignore unlocalised genes completely from hereafter
name = orthomcl_gene.orthomcl_name
orthomcl_locs[name] = locs
# no one orthomcl gene will have coding regions from 2 different species,
# so using the first element of the array is fine
species = orthomcl_gene.coding_regions[0].species
kingdom_orthomcls[species.kingdom] ||= []
kingdom_orthomcls[species.kingdom].push name
end
$stderr.puts kingdom_orthomcls.inspect if debug
$stderr.puts orthomcl_locs.inspect if debug
$stderr.puts "Kingdoms: #{kingdom_orthomcls.to_a.collect{|k| k[0]}.sort.join(', ')}" if debug
# within the one kingdom, do they agree?
kingdom_orthomcls.each do |kingdom, orthomcls|
# If there is only a single coding region, then don't record
number_in_kingdom_localised = orthomcls.length
if number_in_kingdom_localised < 2
$stderr.puts "#{ortho_group.orthomcl_name}, #{kingdom}, skipping (#{orthomcls.join(', ')})" if debug
next
end
# convert orthomcl genes to localisation arrays
locs = orthomcls.collect {|orthomcl|
orthomcl_locs[orthomcl]
}
# OK, so now we are on. Let's do this
agreement = OntologyComparison.new.agreement_of_group(locs)
index = [kingdom]
$stderr.puts "#{ortho_group.orthomcl_name}, #{index.inspect}, #{agreement}, #{orthomcls.join(' ')}" if debug
groups_to_counts[index] ||= {}
groups_to_counts[index][agreement] ||= 0
groups_to_counts[index][agreement] += 1
end
# within two kingdoms, do they agree?
kingdom_orthomcls.to_a.each_lower_triangular_matrix do |array1, array2|
kingdom1 = array1[0]
kingdom2 = array2[0]
orthomcl_array1 = array1[1]
orthomcl_array2 = array2[1]
orthomcl_arrays = [orthomcl_array1, orthomcl_array2]
# don't include unless there is an orthomcl in each kingdom
zero_entriers = orthomcl_arrays.select{|o| o.length==0}
if zero_entriers.length > 0
$stderr.puts "#{ortho_group.orthomcl_name}, #{kingdoms.join(' ')}, skipping"
next
end
locs_for_all = orthomcl_arrays.flatten.collect {|orthomcl| orthomcl_locs[orthomcl]}
agreement = OntologyComparison.new.agreement_of_group(locs_for_all)
index = [kingdom1, kingdom2].sort
$stderr.puts "#{ortho_group.orthomcl_name}, #{index.inspect}, #{agreement}" if debug
groups_to_counts[index] ||= {}
groups_to_counts[index][agreement] ||= 0
groups_to_counts[index][agreement] += 1
end
# within three kingdoms, do they agree?
kingdom_orthomcls.to_a.each_lower_triangular_3d_matrix do |a1, a2, a3|
kingdom1 = a1[0]
kingdom2 = a2[0]
kingdom3 = a3[0]
orthomcl_array1 = a1[1]
orthomcl_array2 = a2[1]
orthomcl_array3 = a3[1]
kingdoms = [kingdom1, kingdom2, kingdom3]
orthomcl_arrays = [orthomcl_array1, orthomcl_array2, orthomcl_array3]
# don't include unless there is an orthomcl in each kingdom
zero_entriers = orthomcl_arrays.select{|o| o.length==0}
if zero_entriers.length > 0
$stderr.puts "#{ortho_group.orthomcl_name}, #{kingdoms.join(' ')}, skipping" if debug
next
end
locs_for_all = orthomcl_arrays.flatten.collect {|orthomcl| orthomcl_locs[orthomcl]}
agreement = OntologyComparison.new.agreement_of_group locs_for_all
index = kingdoms.sort
$stderr.puts "#{ortho_group.orthomcl_name}, #{index.inspect}, #{agreement}" if debug
groups_to_counts[index] ||= {}
groups_to_counts[index][agreement] ||= 0
groups_to_counts[index][agreement] += 1
end
end
progress.finish
# print out the counts for each group of localisations
p groups_to_counts
end
# An attempt to make conservation_of_eukaryotic_sub_cellular_localisation faster
# as well as using less memory. In the end the easiest way was to stay away from Rails
# almost completely, and just use find_by_sql for the big database dump to a csv file,
# and then parse that csv file one line at a time.
def conservation_of_eukaryotic_sub_cellular_localisation_slimmer
# Cache all of the kingdom information as orthomcl_split to kingdom
orthomcl_abbreviation_to_kingdom = {}
Species.all(:conditions => 'orthomcl_three_letter is not null').each do |sp|
orthomcl_abbreviation_to_kingdom[sp.orthomcl_three_letter] = Species::NAME_TO_KINGDOM[sp.name]
end
# Copy the data out of the database to a csv file. Beware that there is duplicates in this file
tempfile = File.open('/tmp/eukaryotic_conservation','w')
# Tempfile.open('eukaryotic_conservation') do |tempfile|
`chmod go+w #{tempfile.path}` #so postgres can write to this file as well
OrthomclGene.find_by_sql "copy (select groupa.orthomcl_name, gene.orthomcl_name, cache.compartment from orthomcl_groups groupa inner join orthomcl_gene_orthomcl_group_orthomcl_runs ogogor on groupa.id=ogogor.orthomcl_group_id inner join orthomcl_genes gene on ogogor.orthomcl_gene_id=gene.id inner join orthomcl_gene_coding_regions ogc on ogc.orthomcl_gene_id=gene.id inner join coding_regions code on ogc.coding_region_id=code.id inner join coding_region_compartment_caches cache on code.id=cache.coding_region_id order by groupa.orthomcl_name) to '#{tempfile.path}'"
tempfile.close
# Parse the csv file to get the answers I'm looking for
data = {}
kingdom_orthomcls = {} #array of kingdoms to orthomcl genes
orthomcl_locs = {} #array of orthomcl_genes to localisations, cached for convenience and speed
FasterCSV.foreach(tempfile.path, :col_sep => "\t") do |row|
# name columns
raise unless row.length == 3
group = row[0]
gene = row[1]
compartment = row[2]
data[group] ||= {}
kingdom = orthomcl_abbreviation_to_kingdom[OrthomclGene.new.official_split(gene)[0]]
data[group]['kingdom_orthomcls'] ||= {}
data[group]['kingdom_orthomcls'][kingdom] ||= []
data[group]['kingdom_orthomcls'][kingdom].push gene
data[group]['kingdom_orthomcls'][kingdom].uniq!
data[group]['orthomcl_locs'] ||= {}
data[group]['orthomcl_locs'][gene] ||= []
data[group]['orthomcl_locs'][gene].push compartment
data[group]['orthomcl_locs'][gene].uniq!
end
# end
# Classify each of the groups into the different categories where possible
groups_to_counts = {}
data.each do |group, data2|
classify_eukaryotic_conservation_of_single_orthomcl_group(
data2['kingdom_orthomcls'],
data2['orthomcl_locs'],
groups_to_counts
)
end
pp groups_to_counts
end
# This is a modularisation of conservation_of_eukaryotic_sub_cellular_localisation,
# and does the calculations on the already transformed data (kingdom_orthomcls, orthomcl_locs).
# More details in conservation_of_eukaryotic_sub_cellular_localisation
def classify_eukaryotic_conservation_of_single_orthomcl_group(kingdom_orthomcls, orthomcl_locs, groups_to_counts, debug = false)
$stderr.puts kingdom_orthomcls.inspect if debug
$stderr.puts orthomcl_locs.inspect if debug
$stderr.puts "Kingdoms: #{kingdom_orthomcls.to_a.collect{|k| k[0]}.sort.join(', ')}" if debug
# within the one kingdom, do they agree?
kingdom_orthomcls.each do |kingdom, orthomcls|
# If there is only a single coding region, then don't record
number_in_kingdom_localised = orthomcls.length
if number_in_kingdom_localised < 2
$stderr.puts "#{ortho_group.orthomcl_name}, #{kingdom}, skipping (#{orthomcls.join(', ')})" if debug
next
end
# convert orthomcl genes to localisation arrays
locs = orthomcls.collect {|orthomcl|
orthomcl_locs[orthomcl]
}
# OK, so now we are on. Let's do this
agreement = OntologyComparison.new.agreement_of_group(locs)
index = [kingdom]
$stderr.puts "#{ortho_group.orthomcl_name}, #{index.inspect}, #{agreement}, #{orthomcls.join(' ')}" if debug
groups_to_counts[index] ||= {}
groups_to_counts[index][agreement] ||= 0
groups_to_counts[index][agreement] += 1
end
# within two kingdoms, do they agree?
kingdom_orthomcls.to_a.each_lower_triangular_matrix do |array1, array2|
kingdom1 = array1[0]
kingdom2 = array2[0]
orthomcl_array1 = array1[1]
orthomcl_array2 = array2[1]
orthomcl_arrays = [orthomcl_array1, orthomcl_array2]
# don't include unless there is an orthomcl in each kingdom
zero_entriers = orthomcl_arrays.select{|o| o.length==0}
if zero_entriers.length > 0
$stderr.puts "#{ortho_group.orthomcl_name}, #{kingdoms.join(' ')}, skipping"
next
end
locs_for_all = orthomcl_arrays.flatten.collect {|orthomcl| orthomcl_locs[orthomcl]}
agreement = OntologyComparison.new.agreement_of_group(locs_for_all)
index = [kingdom1, kingdom2].sort
$stderr.puts "#{ortho_group.orthomcl_name}, #{index.inspect}, #{agreement}" if debug
groups_to_counts[index] ||= {}
groups_to_counts[index][agreement] ||= 0
groups_to_counts[index][agreement] += 1
end
# within three kingdoms, do they agree?
kingdom_orthomcls.to_a.each_lower_triangular_3d_matrix do |a1, a2, a3|
kingdom1 = a1[0]
kingdom2 = a2[0]
kingdom3 = a3[0]
orthomcl_array1 = a1[1]
orthomcl_array2 = a2[1]
orthomcl_array3 = a3[1]
kingdoms = [kingdom1, kingdom2, kingdom3]
orthomcl_arrays = [orthomcl_array1, orthomcl_array2, orthomcl_array3]
# don't include unless there is an orthomcl in each kingdom
zero_entriers = orthomcl_arrays.select{|o| o.length==0}
if zero_entriers.length > 0
$stderr.puts "#{ortho_group.orthomcl_name}, #{kingdoms.join(' ')}, skipping" if debug
next
end
locs_for_all = orthomcl_arrays.flatten.collect {|orthomcl| orthomcl_locs[orthomcl]}
agreement = OntologyComparison.new.agreement_of_group locs_for_all
index = kingdoms.sort
$stderr.puts "#{ortho_group.orthomcl_name}, #{index.inspect}, #{agreement}" if debug
groups_to_counts[index] ||= {}
groups_to_counts[index][agreement] ||= 0
groups_to_counts[index][agreement] += 1
end
end
# Using the assumption that the yeast-mouse, yeast-human and falciparum-toxo divergences are approximately
# equivalent, whatever that means, work out the conservation of localisation between each of those groups.
# Does yeast/mouse exhibit the same problems as falciparum/toxo when comparing localisations?
def localisation_conservation_between_pairs_of_species(species1 = Species::FALCIPARUM_NAME, species2 = Species::TOXOPLASMA_GONDII_NAME)
groups_to_counts = {} #this array ends up holding all the answers after we have finished going through everything
toxo_fal_groups = OrthomclGroup.with_species(Species::ORTHOMCL_CURRENT_LETTERS[species1]).with_species(Species::ORTHOMCL_CURRENT_LETTERS[species2]).all(
:joins => {:orthomcl_genes => {:coding_regions => :coding_region_compartment_caches}},
# :limit => 10,
:select => 'distinct(orthomcl_groups.*)'
# :conditions => ['orthomcl_groups.orthomcl_name = ? or orthomcl_groups.orthomcl_name = ?','OG3_10042','OG3_10032']
)
$stderr.puts "Found #{toxo_fal_groups.length} groups containing proteins from #{species1} and #{species2}"
progress = ProgressBar.new('tfal', toxo_fal_groups.length, STDOUT)
toxo_fal_groups.each do |tfgroup|
progress.inc
orthomcl_locs = {}
species_orthomcls = {} #used like kingdom_locs in previous methods
# collect the orthomcl_locs array for each species
arrays = [species1, species2].collect do |species_name|
# collect compartments for each of the toxos
genes = tfgroup.orthomcl_genes.code(Species::ORTHOMCL_CURRENT_LETTERS[species_name]).all
gene_locs = {}
# add all the locs for a given gene
genes.each do |gene|
locs = gene.coding_regions.collect{|c| c.coding_region_compartment_caches.reach.compartment.retract}.flatten.uniq #all compartments associated with the gene
unless locs.empty?
gene_locs[gene.orthomcl_name] = locs
end
end
# $stderr.puts "Found #{genes.length} orthomcl genes in #{species_name} from #{tfgroup.orthomcl_name}, of those, #{gene_locs.length} had localisations"
gene_locs.each do |gene, locs|
species_orthomcls[species_name] ||= []
species_orthomcls[species_name].push gene
orthomcl_locs[gene] = locs
end
end
# pp species_orthomcls
# pp orthomcl_locs
classify_eukaryotic_conservation_of_single_orthomcl_group(species_orthomcls, orthomcl_locs, groups_to_counts)
end
progress.finish
pp groups_to_counts
end
# Run localisation_conservation_between_pairs_of_species for each pair of species
# that I care about
def exhaustive_localisation_conservation_between_pairs_of_species
[
Species::YEAST_NAME,
Species::MOUSE_NAME,
Species::HUMAN_NAME,
Species::ARABIDOPSIS_NAME,
Species::FALCIPARUM_NAME,
Species::TOXOPLASMA_GONDII_NAME,
].each_lower_triangular_matrix do |s1, s2|
puts '=============================================================='
localisation_conservation_between_pairs_of_species(s1, s2)
end
end
def localisation_pairs_as_matrix
master = {}
File.foreach("#{PHD_DIR}/apiloc/pairs/results.ruby").each do |line|
hash = eval "{#{line}}"
master = master.merge hash
end
organisms = [
Species::YEAST_NAME,
Species::MOUSE_NAME,
Species::HUMAN_NAME,
Species::ARABIDOPSIS_NAME,
Species::FALCIPARUM_NAME,
Species::TOXOPLASMA_GONDII_NAME,
]
print "\t"
puts organisms.join("\t")
organisms.each do |o1|
print o1
organisms.each do |o2|
print "\t"
next if o1 == o2
result = master[[o1,o2].sort]
raise Exception, "Couldn't find #{[o1,o2].sort}" if result.nil?
print result['complete agreement'].to_f/result.values.sum
end
puts
end
end
# If you take only localised falciparum proteins with localised yeast and mouse orthologues,
# what are the chances that they are conserved
def falciparum_predicted_by_yeast_mouse(predicting_species=[Species::YEAST_NAME, Species::MOUSE_NAME],
test_species=Species::FALCIPARUM_NAME)
answer = {}
# Build up the query using the with_species named_scope,
# retrieving all groups that have members in each species
fal_groups = OrthomclGroup.with_species(Species::ORTHOMCL_CURRENT_LETTERS[test_species])
predicting_species.each do |sp|
fal_groups = fal_groups.send(:with_species, Species::ORTHOMCL_CURRENT_LETTERS[sp])
end
fal_groups = fal_groups.all(:select => 'distinct(orthomcl_groups.*)')#, :limit => 20)
$stderr.puts "Found #{fal_groups.length} groups with #{predicting_species.join(', ')} and #{test_species} proteins"
progress = ProgressBar.new('predictionByTwo', fal_groups.length, STDOUT)
fal_groups.each do |fal_group|
progress.inc
$stderr.puts
# get the localisations from each of the predicting species
predicting_array = predicting_species.collect do |species_name|
genes = fal_group.orthomcl_genes.code(Species::ORTHOMCL_CURRENT_LETTERS[species_name]).all
gene_locs = {}
# add all the locs for a given gene
genes.each do |gene|
locs = gene.coding_regions.collect{|c| c.coding_region_compartment_caches.reach.compartment.retract}.flatten.uniq #all compartments associated with the gene
unless locs.empty?
gene_locs[gene.orthomcl_name] = locs
end
end
gene_locs
end
$stderr.puts "OGroup #{fal_group.orthomcl_name} gave #{predicting_array.inspect}"
# only consider cases where there is localisations in each of the predicting species
next if predicting_array.select{|a| a.empty?}.length > 0
# only consider genes where the localisations from the predicting species agree
flattened = predicting_array.inject{|a,b| a.merge(b)}.values
$stderr.puts "flattened: #{flattened.inspect}"
agreement = OntologyComparison.new.agreement_of_group(flattened)
next unless agreement == OntologyComparison::COMPLETE_AGREEMENT
$stderr.puts "They agree..."
# Now compare the agreement between a random falciparum hit and the locs from the predicting
prediction = flattened.to_a[0]
$stderr.puts "Prediction: #{prediction}"
all_fals = CodingRegion.falciparum.all(
:joins => [:coding_region_compartment_caches, {:orthomcl_genes => :orthomcl_groups}],
:conditions => ['orthomcl_groups.id = ?', fal_group.id]
)
next if all_fals.empty?
fal = all_fals[rand(all_fals.length)]
fal_compartments = fal.cached_compartments
$stderr.puts "fal: #{fal.string_id} #{fal_compartments}"
agreement = OntologyComparison.new.agreement_of_group([prediction, fal_compartments])
$stderr.puts "Final agreement #{agreement}"
answer[agreement] ||= 0
answer[agreement] += 1
end
progress.finish
pp answer
end
def how_many_genes_are_localised_in_each_species
interests = Species.all.reach.name.retract
# How many genes?
interests.each do |interest|
count = OrthomclGene.count(
:joins => {:coding_regions => [:coding_region_compartment_caches, {:gene => {:scaffold => :species}}]},
:select => 'distinct(orthomcl_genes.id)',
:conditions => {:species => {:name => interest}}
)
puts "Found #{count} genes with localisation from #{interest}"
end
# how many orthomcl groups?
interests.each do |interest|
count = OrthomclGroup.official.count(
:joins => {:orthomcl_genes => {:coding_regions => [:coding_region_compartment_caches, {:gene => {:scaffold => :species}}]}},
:conditions => ['orthomcl_genes.orthomcl_name like ? and species.name = ?', "#{Species::ORTHOMCL_CURRENT_LETTERS[interest]}|%", interest],
:select => 'distinct(orthomcl_groups.id)'
)
puts "Found #{count} OrthoMCL groups with localisation from #{interest}"
end
end
# Predict the localisation of a protein by determining the amount
def prediction_by_most_common_localisation(predicting_species=[Species::YEAST_NAME, Species::MOUSE_NAME],
test_species=Species::FALCIPARUM_NAME)
answer = {}
# Build up the query using the with_species named_scope,
# retrieving all groups that have members in each species
fal_groups = OrthomclGroup.with_species(Species::ORTHOMCL_CURRENT_LETTERS[test_species])
predicting_species.each do |sp|
fal_groups = fal_groups.send(:with_species, Species::ORTHOMCL_CURRENT_LETTERS[sp])
end
fal_groups = fal_groups.all(:select => 'distinct(orthomcl_groups.*)')#, :limit => 20)
$stderr.puts "Found #{fal_groups.length} groups with #{predicting_species.join(', ')} and #{test_species} proteins"
progress = ProgressBar.new('predictionByCommon', fal_groups.length, STDOUT)
fal_groups.each do |fal_group|
progress.inc
# Only include gene that have exactly 1 gene from that species, otherwise it is harder to
# work out what is going on.
all_tests = fal_group.orthomcl_genes.code(Species::ORTHOMCL_CURRENT_LETTERS[test_species]).all
if all_tests.length > 1
answer['Too many orthomcl genes found'] ||= 0
answer['Too many orthomcl genes found'] += 1
next
end
# gather the actual coding region - discard if there is not exactly 1
codes = all_tests[0].coding_regions
unless codes.length == 1
answer["#{codes.length} coding regions for the 1 orthomcl gene"] ||= 0
answer["#{codes.length} coding regions for the 1 orthomcl gene"] += 1
next
end
code = codes[0]
# Find the most common localisation in each species predicting
preds = [] # the prediction of the most common localisations
commons = predicting_species.collect do |s|
common = code.localisation_prediction_by_most_common_localisation(s)
# Ignore when no loc is found or it is confusing
if common.nil?
answer["No localisation found when trying to find common"] ||= 0
answer["No localisation found when trying to find common"] += 1
next
end
# add the commonest localisation to the prediction array
preds.push [common]
end
# Don't predict unless all species are present
if preds.length == predicting_species.length
# Only predict if the top 2 species are in agreement
if OntologyComparison.new.agreement_of_group(preds) == OntologyComparison::COMPLETE_AGREEMENT
final_locs = code.cached_compartments
if final_locs.empty?
answer["No test species localisation"] ||= 0
answer["No test species localisation"] += 1
else
# Add the final localisation compartments
preds.push final_locs
acc = OntologyComparison.new.agreement_of_group(preds)
answer[acc] ||= 0
answer[acc] += 1
end
else
answer["Predicting species don't agree"] ||= 0
answer["Predicting species don't agree"] += 1
end
else
answer["Not enough localisation info in predicting groups"] ||= 0
answer["Not enough localisation info in predicting groups"] += 1
end
end
progress.finish
pp answer
end
def stuarts_basel_spreadsheet_yeast_setup
# uniprot_to_database(Species::YEAST_NAME)
# yeastgenome_ids_to_database
# OrthomclGene.new.link_orthomcl_and_coding_regions(
# "scer",
# :accept_multiple_coding_regions => true
# )
# cache compartments
codes = CodingRegion.s(Species::YEAST_NAME).go_cc_usefully_termed.all
progress = ProgressBar.new('eukaryotes', codes.length)
codes.each do |code|
progress.inc
comps = code.compartments
comps.each do |comp|
CodingRegionCompartmentCache.find_or_create_by_coding_region_id_and_compartment(
code.id, comp
)
end
end
progress.finish
end
def stuarts_basel_spreadsheet(accept_multiples = false)
species_of_interest = [
Species::ARABIDOPSIS_NAME,
Species::FALCIPARUM,
Species::TOXOPLASMA_GONDII,
Species::YEAST_NAME,
Species::MOUSE_NAME,
Species::HUMAN_NAME
]
$stderr.puts "Copying data to tempfile.."
# Copy the data out of the database to a csv file. Beware that there is duplicates in this file
tempfile = File.open('/tmp/eukaryotic_conservation','w')
# Tempfile.open('eukaryotic_conservation') do |tempfile|
`chmod go+w #{tempfile.path}` #so postgres can write to this file as well
OrthomclGene.find_by_sql "copy (select groupa.orthomcl_name, gene.orthomcl_name, cache.compartment from orthomcl_groups groupa inner join orthomcl_gene_orthomcl_group_orthomcl_runs ogogor on groupa.id=ogogor.orthomcl_group_id inner join orthomcl_genes gene on ogogor.orthomcl_gene_id=gene.id inner join orthomcl_gene_coding_regions ogc on ogc.orthomcl_gene_id=gene.id inner join coding_regions code on ogc.coding_region_id=code.id inner join coding_region_compartment_caches cache on code.id=cache.coding_region_id order by groupa.orthomcl_name) to '#{tempfile.path}'"
tempfile.close
groups_genes = {}
genes_localisations = {}
# Read groups, genes, and locs into memory
$stderr.puts "Reading into memory sql results.."
FasterCSV.foreach(tempfile.path, :col_sep => "\t") do |row|
#FasterCSV.foreach('/tmp/eukaryotic_conservation_test', :col_sep => "\t") do |row|
# name columns
raise unless row.length == 3
group = row[0]
gene = row[1]
compartment = row[2]
groups_genes[group] ||= []
groups_genes[group].push gene
groups_genes[group].uniq!
genes_localisations[gene] ||= []
genes_localisations[gene].push compartment
genes_localisations[gene].uniq!
end
# Print headers
header = ['']
species_of_interest.each do |s|
header.push "#{s} ID 1"
header.push "#{s} loc 1"
header.push "#{s} ID 2"
header.push "#{s} loc 2"
end
puts header.join("\t")
# Iterate through each OrthoMCL group, printing them out if they fit the criteria
$stderr.puts "Iterating through groups.."
groups_genes.each do |group, ogenes|
$stderr.puts "looking at group #{group}"
# associate genes with species
species_gene = {}
ogenes.each do |ogene|
sp = Species.four_letter_to_species_name(OrthomclGene.new.official_split(ogene)[0])
unless species_of_interest.include?(sp)
$stderr.puts "Ignoring info for #{sp}"
next
end
species_gene[sp] ||= []
species_gene[sp].push ogene
species_gene[sp].uniq!
end
# skip groups that are only localised in a single species
if species_gene.length == 1
$stderr.puts "Rejecting #{group} because it only has localised genes in 1 species of interest"
next
end
# skip groups that have more than 2 localised genes in each group.
failed = false
species_gene.each do |species, genes|
if genes.length > 2
$stderr.puts "Rejecting #{group}, because there are >2 genes with localisation info in #{species}.."
failed = true
end
end
next if failed
# procedure for making printing easier
generate_cell = lambda do |gene|
locs = genes_localisations[gene]
if locs.include?('cytoplasm') and locs.include?('nucleus')
locs.reject!{|l| l=='cytoplasm'}
end
if locs.length == 1
[OrthomclGene.new.official_split(gene)[1], locs[0]]
elsif locs.length == 0
raise Exception, "Unexpected lack of loc information"
else
if accept_multiples
[OrthomclGene.new.official_split(gene)[1], locs.sort.join(', ')]
else
$stderr.puts "Returning nil for #{gene} because there is #{locs.length} localisations"
nil
end
end
end
row = [group]
failed = false #fail if genes have >1 localisation
species_of_interest.each do |s|
$stderr.puts "What's in #{s}? #{species_gene[s].inspect}"
if species_gene[s].nil? or species_gene[s].length == 0
row.push ['','']
row.push ['','']
elsif species_gene[s].length == 1
r = generate_cell.call species_gene[s][0]
failed = true if r.nil?
row.push r
row.push ['','']
else
species_gene[s].each do |g|
r = generate_cell.call g
failed = true if r.nil?
row.push r
end
end
end
puts row.join("\t") unless failed
end
end
# Generate the data for
def publication_per_year_graphing
years = {}
fails = 0
Publication.all(:joins => {:expression_contexts => :localisation}).uniq.each do |p|
y = p.year
if y.nil?
fails += 1
$stderr.puts "Failed: #{p.inspect}"
else
years[y] ||= 0
years[y] += 1
end
end
puts ['Year','Number of Publications'].join("\t")
years.sort.each do |a,b|
puts [a,b].join("\t")
end
$stderr.puts "Failed to year-ify #{fails} publications."
end
def localisation_per_year_graphing
already_localised = []
years = {}
fails = 0
# Get all the publications that have localisations in order
Publication.all(:joins => {:expression_contexts => :localisation}).uniq.sort {|p1,p2|
if p1.year.nil?
-1
elsif p2.year.nil?
1
else
p1.year <=> p2.year
end
}.each do |pub|
y = pub.year
if y.nil? #ignore publications with improperly parsed years
fails += 1
next
end
ids = CodingRegion.all(:select => 'coding_regions.id',
:joins => {
:expression_contexts => [:localisation, :publication]
},
:conditions => {:publications => {:id => pub.id}}
)
ids.each do |i|
unless already_localised.include?(i)
already_localised.push i
years[y] ||= 0
years[y] += 1
end
end
end
puts ['Year','Number of New Protein Localisations'].join("\t")
years.sort.each do |a,b|
puts [a,b].join("\t")
end
$stderr.puts "Failed to year-ify #{fails} publications."
end
# How many and which genes are recorded in the malaria metabolic pathways database,
# but aren't recorded in ApiLoc?
def comparison_with_hagai
File.open("#{PHD_DIR}/screenscraping_hagai/localised_genes_and_links.txt").each_line do |line|
line.strip!
splits = line.split(' ')
#next unless splits[0].match(/#{splits[1]}/) #ignore possibly incorrect links
code = CodingRegion.ff(splits[1])
unless code
puts "Couldn't find plasmodb id #{splits[1]}"
next
end
if code.expressed_localisations.count == 0
puts "Not found in ApiLoc: #{splits[1]}"
else
puts "Found in ApiLoc: #{splits[1]}"
end
end
end
# Create a spreadsheet with all the synonyms, so it can be attached as supplementary
def synonyms_spreadsheet
sep = "\t"
# Print titles
puts [
"Localistion or Developmental Stage?",
"Species",
"Full name(s)",
"Synonym"
].join(sep)
# Procedure for printing out each of the hits
printer = lambda do |species_name, actual, synonym, cv_name|
if actual.kind_of?(Array)
puts [cv_name, species_name, actual.join(","), synonym].join(sep)
else
puts [cv_name, species_name, actual, synonym].join(sep)
end
end
# Print all the synonyms
[
LocalisationConstants::KNOWN_LOCALISATION_SYNONYMS,
DevelopmentalStageConstants::KNOWN_DEVELOPMENTAL_STAGE_SYNONYMS,
].each do |cv|
cv_name = {
DevelopmentalStageConstants::KNOWN_DEVELOPMENTAL_STAGE_SYNONYMS => 'Developmental Stage',
LocalisationConstants::KNOWN_LOCALISATION_SYNONYMS => 'Localisation'
}[cv]
cv.each do |sp, hash|
if sp == Species::OTHER_SPECIES #for species not with a genome project
# Species::OTHER_SPECIES => {
# 'Sarcocystis muris' => {
# 'surface' => 'cell surface'
# },
# 'Babesia gibsoni' => {
# 'surface' => 'cell surface',
# 'erythrocyte cytoplasm' => 'host cell cytoplasm',
# 'pm' => 'plasma membrane',
# 'membrane' => 'plasma membrane'
# },
hash.each do |species_name, hash2|
hash2.each do |synonym, actual|
printer.call(species_name, actual, synonym, cv_name)
end
end
else #normal species
hash.each do |synonym, actual|
printer.call(sp, actual, synonym, cv_name)
end
end
end
end
end
def umbrella_localisations_controlled_vocabulary
sep = "\t"
# Print titles
puts [
"Localistion or Developmental Stage?",
"Umbrella",
"Specific Localisation Name"
].join(sep)
ApilocLocalisationTopLevelLocalisation::APILOC_TOP_LEVEL_LOCALISATION_HASH.each do |umbrella, unders|
unders.each do |under|
puts ["Localisation", umbrella, under].join(sep)
end
end
DevelopmentalStageTopLevelDevelopmentalStage::APILOC_DEVELOPMENTAL_STAGE_TOP_LEVEL_DEVELOPMENTAL_STAGES.each do |under, umbrella|
puts ["Developmental Stage", umbrella, under].join(sep)
end
end
def how_many_apicomplexan_genes_have_localised_orthologues
$stderr.puts "starting group search"
groups = OrthomclGroup.official.all(
:joins => {:orthomcl_genes => {:coding_regions => :coding_region_compartment_caches}},
:select => 'distinct(orthomcl_groups.id)'
)
$stderr.puts "finished group search, found #{groups.length} groups"
group_ids = groups.collect{|g| g.id}
$stderr.puts "finished group id transform"
puts '# Genes that have localised ortholgues, if you consider GO CC IDA terms from all Eukaryotes'
Species.sequenced_apicomplexan.all.each do |sp|
num_orthomcl_genes = OrthomclGene.code(sp.orthomcl_three_letter).count(
:select => 'distinct(orthomcl_genes.id)'
)
# go through the groups and work out how many coding regions there are in those groups from this species
num_with_a_localised_orthologue = OrthomclGene.code(sp.orthomcl_three_letter).count(
:select => 'distinct(orthomcl_genes.id)',
:joins => :orthomcl_groups,
:conditions => "orthomcl_gene_orthomcl_group_orthomcl_runs.orthomcl_group_id in #{group_ids.to_sql_in_string}"
)
puts [
sp.name,
num_orthomcl_genes,
num_with_a_localised_orthologue
].join("\t")
end
puts
puts '# Genes that have localised ortholgues, if you don\'t consider GO CC IDA terms from all Eukaryotes'
$stderr.puts "starting group search"
groups = OrthomclGroup.official.all(
:joins => {:orthomcl_genes => {:coding_regions => :expressed_localisations}},
:select => 'distinct(orthomcl_groups.id)'
)
$stderr.puts "finished group search, found #{groups.length} groups"
group_ids = groups.collect{|g| g.id}
$stderr.puts "finished group id transform"
puts '# Genes that have localised ortholgues, if you consider GO CC IDA terms from all Eukaryotes'
Species.sequenced_apicomplexan.all.each do |sp|
num_orthomcl_genes = OrthomclGene.code(sp.orthomcl_three_letter).count(
:select => 'distinct(orthomcl_genes.id)'
)
# go through the groups and work out how many coding regions there are in those groups from this species
num_with_a_localised_orthologue = OrthomclGene.code(sp.orthomcl_three_letter).count(
:select => 'distinct(orthomcl_genes.id)',
:joins => :orthomcl_groups,
:conditions => "orthomcl_gene_orthomcl_group_orthomcl_runs.orthomcl_group_id in #{group_ids.to_sql_in_string}"
)
puts [
sp.name,
num_orthomcl_genes,
num_with_a_localised_orthologue
].join("\t")
end
end
def conservation_of_localisation_in_apicomplexa
# For each OrthoMCL group that contains 2 or more proteins localised,
# When there is at least 2 different species involved
groups = OrthomclGroup.all(
:joins => {:orthomcl_genes => {:coding_regions => :expressed_localisations}}
).uniq
groups.each do |g|
genes = g.orthomcl_genes.uniq
# If there is more than 1 species involved
if genes.collect{|g| g.official_split[0]}.uniq.length > 1
puts
puts '#####################################'
genes.each do |g|
codes = g.coding_regions
if codes.length != 1
$stderr.puts "Too many coding regions for #{g.orthomcl_name}: #{code}"
next
end
code = coding_regions[0]
puts [
code.species.name,
code.annotation.annotation,
code.coding_region_compartment_caches.reach.join(', ')
code.localisation_english,
].joint("\t")
end
end
end
end
end
|
$:.push File.expand_path("../lib", __FILE__)
require "simple_datatables/version"
Gem::Specification.new do |s|
s.name = "simple_datatables"
s.version = SimpleDatatables::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Grigory"]
s.email = ["grigory@snsk.ru"]
s.homepage = "http://github.com/gryphon/simple_datatables"
s.summary = %q{Simple datatables to rails mapping using meta_search, will_paginage and jsonify}
s.description = %q{Simple data preparation from AR/Mongoid to the jQuery DataTables plugin}
s.rubyforge_project = "data_table"
s.files = `git ls-files`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_dependency "rails", ">=3.0.0"
s.add_dependency "will_paginate", "~>3.0.pre2"
s.add_dependency "meta_search"
s.add_dependency "jsonify-rails"
end
Version
$:.push File.expand_path("../lib", __FILE__)
require "simple_datatables/version"
Gem::Specification.new do |s|
s.name = "simple_datatables"
s.version = SimpleDatatables::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Grigory"]
s.email = ["grigory@snsk.ru"]
s.homepage = "http://github.com/gryphon/simple_datatables"
s.summary = %q{Simple datatables to rails mapping using meta_search, will_paginage and jsonify}
s.description = %q{Simple datatables to rails mapping using meta_search, will_paginage and jsonify}
s.rubyforge_project = "data_table"
s.files = `git ls-files`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_dependency "rails", ">=3.0.0"
s.add_dependency "will_paginate", "~>3.0.pre2"
s.add_dependency "meta_search"
s.add_dependency "jsonify-rails"
end
|
require 'spec_helper'
describe Archive::Ar do
describe "create" do
end
describe "extract" do
end
describe "traverse" do
let(:options) { {} }
subject { Archive::Ar.traverse(source_file, options) }
context "archive.ar" do
let(:source_file) { "spec/fixtures/archive.ar" }
it "yields the file" do
expect {|b|
Archive::Ar.traverse(source_file, options, &b)
}.to yield_successive_args(anything)
end
end
end
end
More testing work
require 'spec_helper'
describe Archive::Ar do
let(:options) { {} }
describe "create" do
let(:dest_file) { "tmp/create.ar" }
let(:filenames) { ["spec/fixtures/file"] }
subject { Archive::Ar.create(dest_file, filenames, options) }
it { should == 65 }
end
describe "extract" do
let(:dest_dir) { "tmp/" }
subject { Archive::Ar.extract(source_file, dest_dir, options) }
context "archive.ar" do
let(:source_file) { "spec/fixtures/archive.ar" }
it { should == ["file"] }
end
end
describe "traverse" do
subject { Archive::Ar.traverse(source_file, options) }
context "archive.ar" do
let(:source_file) { "spec/fixtures/archive.ar" }
it "yields the file" do
expect {|b|
Archive::Ar.traverse(source_file, options, &b)
}.to yield_successive_args(anything)
end
end
end
end
|
# encoding: utf-8
require 'spec_helper'
require 'fileutils'
require_relative '../../lib/git-client'
describe GitClient do
let(:source_dir) { nil }
let(:dir) { nil }
let(:dir_to_update) { nil }
after do
FileUtils.rm_rf(source_dir) unless source_dir.nil?
FileUtils.rm_rf(dir) unless dir.nil?
FileUtils.rm_rf(dir_to_update) unless dir_to_update.nil?
end
describe '#update_submodule_to_latest' do
let(:source_dir) { Dir.mktmpdir }
let(:dir_to_update) { Dir.mktmpdir }
let(:latest_sha) { "latest_sha" }
subject { described_class.update_submodule_to_latest(source_dir, dir_to_update) }
it "should update target repo's submodule to latest submodule sha" do
expect(GitClient).to receive(:get_commit_sha).with(source_dir, 0).and_return(latest_sha)
expect(GitClient).to receive(:fetch).with(dir_to_update)
expect(GitClient).to receive(:checkout_branch).with(latest_sha)
subject
end
end
describe '#get_commit_sha' do
let(:dir) { Dir.mktmpdir }
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:commit_sha) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
let(:number_commits_before_head) { 3 }
subject { described_class.get_commit_sha(dir, number_commits_before_head) }
before { allow(Open3).to receive(:capture3) }
context 'git works properly' do
let(:commit_sha) { 'ffffaaaaaec7c534f0e1c6a295a2450d17f711a1' }
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should return the last git commit message' do
expect(Open3).to receive(:capture3).with('git rev-parse HEAD~3').and_return([commit_sha, stderr_output, process_status])
expect(subject).to eq('ffffaaaaaec7c534f0e1c6a295a2450d17f711a1')
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to read the commit message' do
expect(Open3).to receive(:capture3).with('git rev-parse HEAD~3').and_return([commit_sha, stderr_output, process_status])
expect{ subject }.to raise_error(GitClient::GitError, 'Could not get commit SHA for HEAD~3. STDERR was: stderr output')
end
end
end
describe '#last_commit_message' do
let(:dir) { Dir.mktmpdir }
let(:last_commit_message) { 'this should not matter but is here to avoid undefined symbols' }
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
subject { described_class.last_commit_message(dir) }
before { allow(Open3).to receive(:capture3).and_return([last_commit_message, stderr_output, process_status]) }
context 'git works properly' do
let(:last_commit_message) { 'I was last committed' }
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should return the last git commit message' do
expect(subject).to eq('I was last committed')
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to read the commit message' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not get commit message for HEAD~0. STDERR was: stderr output')
end
end
end
describe '#last_commit_author' do
let(:dir) { Dir.mktmpdir }
let(:last_commit_message) { 'this should not matter but is here to avoid undefined symbols' }
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
subject { described_class.last_commit_author(dir) }
before { allow(Open3).to receive(:capture3).and_return([last_commit_message, stderr_output, process_status]) }
context 'git works properly' do
let(:last_commit_message) { "I was last committed\n Author: Firstname Lastname <flastname@example.com>" }
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should return the name of the author of the last git commit' do
expect(subject).to eq('Firstname Lastname')
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to get the author of the commit' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not get author of commit HEAD~0. STDERR was: stderr output')
end
end
end
describe '#get_current_branch' do
let(:dir) { Dir.mktmpdir }
let(:current_branch) { 'this should not matter but is here to avoid undefined symbols' }
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
subject { described_class.get_current_branch(dir) }
before { allow(Open3).to receive(:capture3).and_return([current_branch, stderr_output, process_status]) }
context 'git works properly' do
let(:current_branch) { 'the-current-git-branch' }
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should return the current git branch' do
expect(subject).to eq('the-current-git-branch')
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to get the current branch' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not get current branch. STDERR was: stderr output')
end
end
end
describe '#get_list_of_one_line_commits' do
let(:dir) { Dir.mktmpdir }
let(:number) { 3 }
let(:last_few_commits) { 'this should not matter but is here to avoid undefined symbols' }
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
subject { described_class.get_list_of_one_line_commits(dir,number) }
before { allow(Open3).to receive(:capture3).and_return([last_few_commits, stderr_output, process_status]) }
context 'git works properly' do
let(:last_few_commits) { "7652882 recent commit 1\n34e6f44 recent commit 2\n0b5a735 recent commit 3\n" }
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should be an array of size 3' do
expect(subject.class).to eq(Array)
expect(subject.count).to eq(3)
end
it 'should contain the commits' do
expect(subject).to include('7652882 recent commit 1')
expect(subject).to include('34e6f44 recent commit 2')
expect(subject).to include('0b5a735 recent commit 3')
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to get the most recent commits' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not get last 3 commits. STDERR was: stderr output')
end
end
end
describe '#checkout_branch' do
let(:git_branch) {'a-different-git-branch'}
subject { described_class.checkout_branch(git_branch) }
before { allow(described_class).to receive(:system).and_return(git_successful) }
context 'git works properly' do
let(:git_successful) { true }
it 'checks out the specified branch' do
expect(described_class).to receive(:system).with('git checkout a-different-git-branch')
subject
end
end
context 'git fails' do
let(:git_successful) { false }
it 'throws an exception about not checking out the branch' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not checkout branch: a-different-git-branch')
end
end
end
describe '#pull_current_branch' do
subject { described_class.pull_current_branch }
before { allow(described_class).to receive(:system).and_return(git_successful) }
context 'git works properly' do
let(:git_successful) { true }
it 'pulls the current branch' do
expect(described_class).to receive(:system).with('git pull -r')
subject
end
end
context 'git fails' do
let(:git_successful) { false }
it 'throws an exception about not checking out the branch' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not pull branch')
end
end
end
describe '#set_global_config' do
let(:test_option) { 'test.option' }
let(:test_value) { 'value_to_set' }
subject { described_class.set_global_config(test_option,test_value) }
before { allow(described_class).to receive(:system).and_return(git_successful) }
context 'git works properly' do
let(:git_successful) { true }
it 'should set the global git config' do
expect(described_class).to receive(:system).with('git config --global test.option "value_to_set"')
subject
end
end
context 'git fails' do
let(:git_successful) { false }
it 'throws an exception about not setting global config' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not set global config test.option to value_to_set')
end
end
end
describe '#add_everything' do
subject { described_class.add_everything }
before { allow(described_class).to receive(:system).and_return(git_successful) }
context 'git works properly' do
let(:git_successful) { true }
it 'should git add all' do
expect(described_class).to receive(:system).with('git add -A')
subject
end
end
context 'git fails' do
let(:git_successful) { false }
it 'throws an exception about not adding files' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not add files')
end
end
end
describe '#add_file' do
let(:file_to_add) {'test_file.yml'}
subject { described_class.add_file(file_to_add) }
before { allow(described_class).to receive(:system).and_return(git_successful) }
context 'git works properly' do
let(:git_successful) { true }
it 'should git add the file' do
expect(described_class).to receive(:system).with("git add #{file_to_add}")
subject
end
end
context 'git fails' do
let(:git_successful) { false }
it 'throws an exception about not adding the file ' do
expect{ subject }.to raise_error(GitClient::GitError, "Could not add file: #{file_to_add}")
end
end
end
describe '#safe_commit' do
let(:git_commit_message) { 'Beautiful commits for all' }
subject { described_class.safe_commit(git_commit_message) }
before { allow(described_class).to receive(:system).with('git diff --cached --exit-code').and_return(no_changes_staged) }
context 'changes are staged' do
let(:no_changes_staged) { false }
context 'commit succeeds' do
it 'makes a commit with the specified message' do
expect(described_class).to receive(:system).with("git commit -m 'Beautiful commits for all'").and_return(true)
subject
end
end
context 'commit fails' do
it 'throws an exception about committing' do
expect(described_class).to receive(:system).with("git commit -m 'Beautiful commits for all'").and_return(false)
expect{ subject }.to raise_error(GitClient::GitError, 'Commit failed')
end
end
end
context 'no changes are staged' do
let(:no_changes_staged) { true }
it 'advises that no changes were committed' do
expect{ subject }.to output("No staged changes were available to commit, doing nothing.\n").to_stdout
end
end
end
describe '#git_tag_shas' do
let(:dir) { Dir.mktmpdir }
let(:git_tag_output) { <<~OUTPUT
sha1 refs/tags/v1.0.0
sha2 refs/tags/v1.0.1
sha3 refs/tags/v1.1.0
OUTPUT
}
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
subject { described_class.git_tag_shas(dir) }
before { allow(Open3).to receive(:capture3).and_return([git_tag_output, stderr_output, process_status]) }
context 'git works properly' do
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should return the last git commit message' do
expect(subject).to eq(['sha1', 'sha2', 'sha3'])
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to get the shas of the git tags' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not get git tag shas. STDERR was: stderr output')
end
end
end
describe '#get_file_contents_at_sha' do
let(:dir) { Dir.mktmpdir }
let(:git_show_output) { <<~OUTPUT
CONTENT OF FILE
OUTPUT
}
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
let(:sha) { 'sha1' }
let(:file) { 'important_file.txt' }
subject { described_class.get_file_contents_at_sha(dir, sha, file) }
before { allow(Open3).to receive(:capture3).with('git show sha1:important_file.txt').and_return([git_show_output, stderr_output, process_status]) }
context 'git works properly' do
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should return the last git commit message' do
expect(subject).to eq("CONTENT OF FILE\n")
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to show the file at specified sha' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not show important_file.txt at sha1. STDERR was: stderr output')
end
end
end
describe '#fetch' do
let(:dir) {Dir.mktmpdir }
subject { described_class.fetch(dir) }
before { allow(described_class).to receive(:system).and_return(git_successful) }
context 'git works properly' do
let(:git_successful) { true }
it 'should git fetch' do
expect(described_class).to receive(:system).with('git fetch')
subject
end
end
context 'git fails' do
let(:git_successful) { false }
it 'throws an exception about not fetching' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not fetch')
end
end
end
end
Backfill GitClient spec
[#126710539]
# encoding: utf-8
require 'spec_helper'
require 'fileutils'
require_relative '../../lib/git-client'
describe GitClient do
let(:source_dir) { nil }
let(:dir) { nil }
let(:dir_to_update) { nil }
after do
FileUtils.rm_rf(source_dir) unless source_dir.nil?
FileUtils.rm_rf(dir) unless dir.nil?
FileUtils.rm_rf(dir_to_update) unless dir_to_update.nil?
end
describe '#update_submodule_to_latest' do
let(:source_dir) { Dir.mktmpdir }
let(:dir_to_update) { Dir.mktmpdir }
let(:latest_sha) { "latest_sha" }
subject { described_class.update_submodule_to_latest(source_dir, dir_to_update) }
it "should update target repo's submodule to latest submodule sha" do
expect(GitClient).to receive(:get_commit_sha).with(source_dir, 0).and_return(latest_sha)
expect(GitClient).to receive(:fetch).with(dir_to_update)
expect(GitClient).to receive(:checkout_branch).with(latest_sha)
subject
end
end
describe '#get_commit_sha' do
let(:dir) { Dir.mktmpdir }
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:commit_sha) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
let(:number_commits_before_head) { 3 }
subject { described_class.get_commit_sha(dir, number_commits_before_head) }
before { allow(Open3).to receive(:capture3) }
context 'git works properly' do
let(:commit_sha) { 'ffffaaaaaec7c534f0e1c6a295a2450d17f711a1' }
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should return the last git commit message' do
expect(Open3).to receive(:capture3).with('git rev-parse HEAD~3').and_return([commit_sha, stderr_output, process_status])
expect(subject).to eq('ffffaaaaaec7c534f0e1c6a295a2450d17f711a1')
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to read the commit message' do
expect(Open3).to receive(:capture3).with('git rev-parse HEAD~3').and_return([commit_sha, stderr_output, process_status])
expect{ subject }.to raise_error(GitClient::GitError, 'Could not get commit SHA for HEAD~3. STDERR was: stderr output')
end
end
end
describe '#last_commit_message' do
let(:dir) { Dir.mktmpdir }
let(:last_commit_message) { 'this should not matter but is here to avoid undefined symbols' }
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
subject { described_class.last_commit_message(dir) }
before { allow(Open3).to receive(:capture3).with('git log --format=%B -n 1 HEAD~0').and_return([last_commit_message, stderr_output, process_status]) }
context 'git works properly' do
let(:last_commit_message) { 'I was last committed' }
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should return the last git commit message' do
expect(subject).to eq('I was last committed')
end
end
context 'for a specific file' do
let(:last_commit_message) { 'I was last committed' }
let(:filename) { 'directory/info.yml' }
subject { described_class.last_commit_message(dir, 0, filename) }
before do
allow(Open3).to receive(:capture3).with('git log --format=%B -n 1 HEAD~0 directory/info.yml').and_return([last_commit_message, stderr_output, process_status])
allow(process_status).to receive(:success?).and_return(true)
end
it 'should return the last git commit message' do
expect(subject).to eq('I was last committed')
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to read the commit message' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not get commit message for HEAD~0. STDERR was: stderr output')
end
end
end
describe '#last_commit_author' do
let(:dir) { Dir.mktmpdir }
let(:last_commit_message) { 'this should not matter but is here to avoid undefined symbols' }
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
subject { described_class.last_commit_author(dir) }
before { allow(Open3).to receive(:capture3).and_return([last_commit_message, stderr_output, process_status]) }
context 'git works properly' do
let(:last_commit_message) { "I was last committed\n Author: Firstname Lastname <flastname@example.com>" }
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should return the name of the author of the last git commit' do
expect(subject).to eq('Firstname Lastname')
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to get the author of the commit' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not get author of commit HEAD~0. STDERR was: stderr output')
end
end
end
describe '#get_current_branch' do
let(:dir) { Dir.mktmpdir }
let(:current_branch) { 'this should not matter but is here to avoid undefined symbols' }
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
subject { described_class.get_current_branch(dir) }
before { allow(Open3).to receive(:capture3).and_return([current_branch, stderr_output, process_status]) }
context 'git works properly' do
let(:current_branch) { 'the-current-git-branch' }
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should return the current git branch' do
expect(subject).to eq('the-current-git-branch')
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to get the current branch' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not get current branch. STDERR was: stderr output')
end
end
end
describe '#get_list_of_one_line_commits' do
let(:dir) { Dir.mktmpdir }
let(:number) { 3 }
let(:last_few_commits) { 'this should not matter but is here to avoid undefined symbols' }
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
subject { described_class.get_list_of_one_line_commits(dir,number) }
before { allow(Open3).to receive(:capture3).and_return([last_few_commits, stderr_output, process_status]) }
context 'git works properly' do
let(:last_few_commits) { "7652882 recent commit 1\n34e6f44 recent commit 2\n0b5a735 recent commit 3\n" }
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should be an array of size 3' do
expect(subject.class).to eq(Array)
expect(subject.count).to eq(3)
end
it 'should contain the commits' do
expect(subject).to include('7652882 recent commit 1')
expect(subject).to include('34e6f44 recent commit 2')
expect(subject).to include('0b5a735 recent commit 3')
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to get the most recent commits' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not get last 3 commits. STDERR was: stderr output')
end
end
end
describe '#checkout_branch' do
let(:git_branch) {'a-different-git-branch'}
subject { described_class.checkout_branch(git_branch) }
before { allow(described_class).to receive(:system).and_return(git_successful) }
context 'git works properly' do
let(:git_successful) { true }
it 'checks out the specified branch' do
expect(described_class).to receive(:system).with('git checkout a-different-git-branch')
subject
end
end
context 'git fails' do
let(:git_successful) { false }
it 'throws an exception about not checking out the branch' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not checkout branch: a-different-git-branch')
end
end
end
describe '#pull_current_branch' do
subject { described_class.pull_current_branch }
before { allow(described_class).to receive(:system).and_return(git_successful) }
context 'git works properly' do
let(:git_successful) { true }
it 'pulls the current branch' do
expect(described_class).to receive(:system).with('git pull -r')
subject
end
end
context 'git fails' do
let(:git_successful) { false }
it 'throws an exception about not checking out the branch' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not pull branch')
end
end
end
describe '#set_global_config' do
let(:test_option) { 'test.option' }
let(:test_value) { 'value_to_set' }
subject { described_class.set_global_config(test_option,test_value) }
before { allow(described_class).to receive(:system).and_return(git_successful) }
context 'git works properly' do
let(:git_successful) { true }
it 'should set the global git config' do
expect(described_class).to receive(:system).with('git config --global test.option "value_to_set"')
subject
end
end
context 'git fails' do
let(:git_successful) { false }
it 'throws an exception about not setting global config' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not set global config test.option to value_to_set')
end
end
end
describe '#add_everything' do
subject { described_class.add_everything }
before { allow(described_class).to receive(:system).and_return(git_successful) }
context 'git works properly' do
let(:git_successful) { true }
it 'should git add all' do
expect(described_class).to receive(:system).with('git add -A')
subject
end
end
context 'git fails' do
let(:git_successful) { false }
it 'throws an exception about not adding files' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not add files')
end
end
end
describe '#add_file' do
let(:file_to_add) {'test_file.yml'}
subject { described_class.add_file(file_to_add) }
before { allow(described_class).to receive(:system).and_return(git_successful) }
context 'git works properly' do
let(:git_successful) { true }
it 'should git add the file' do
expect(described_class).to receive(:system).with("git add #{file_to_add}")
subject
end
end
context 'git fails' do
let(:git_successful) { false }
it 'throws an exception about not adding the file ' do
expect{ subject }.to raise_error(GitClient::GitError, "Could not add file: #{file_to_add}")
end
end
end
describe '#safe_commit' do
let(:git_commit_message) { 'Beautiful commits for all' }
subject { described_class.safe_commit(git_commit_message) }
before { allow(described_class).to receive(:system).with('git diff --cached --exit-code').and_return(no_changes_staged) }
context 'changes are staged' do
let(:no_changes_staged) { false }
context 'commit succeeds' do
it 'makes a commit with the specified message' do
expect(described_class).to receive(:system).with("git commit -m 'Beautiful commits for all'").and_return(true)
subject
end
end
context 'commit fails' do
it 'throws an exception about committing' do
expect(described_class).to receive(:system).with("git commit -m 'Beautiful commits for all'").and_return(false)
expect{ subject }.to raise_error(GitClient::GitError, 'Commit failed')
end
end
end
context 'no changes are staged' do
let(:no_changes_staged) { true }
it 'advises that no changes were committed' do
expect{ subject }.to output("No staged changes were available to commit, doing nothing.\n").to_stdout
end
end
end
describe '#git_tag_shas' do
let(:dir) { Dir.mktmpdir }
let(:git_tag_output) { <<~OUTPUT
sha1 refs/tags/v1.0.0
sha2 refs/tags/v1.0.1
sha3 refs/tags/v1.1.0
OUTPUT
}
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
subject { described_class.git_tag_shas(dir) }
before { allow(Open3).to receive(:capture3).and_return([git_tag_output, stderr_output, process_status]) }
context 'git works properly' do
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should return the last git commit message' do
expect(subject).to eq(['sha1', 'sha2', 'sha3'])
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to get the shas of the git tags' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not get git tag shas. STDERR was: stderr output')
end
end
end
describe '#get_file_contents_at_sha' do
let(:dir) { Dir.mktmpdir }
let(:git_show_output) { <<~OUTPUT
CONTENT OF FILE
OUTPUT
}
let(:stderr_output) { 'this should not matter but is here to avoid undefined symbols' }
let(:process_status) { double(:process_status) }
let(:sha) { 'sha1' }
let(:file) { 'important_file.txt' }
subject { described_class.get_file_contents_at_sha(dir, sha, file) }
before { allow(Open3).to receive(:capture3).with('git show sha1:important_file.txt').and_return([git_show_output, stderr_output, process_status]) }
context 'git works properly' do
before { allow(process_status).to receive(:success?).and_return(true) }
it 'should return the last git commit message' do
expect(subject).to eq("CONTENT OF FILE\n")
end
end
context 'git fails' do
let(:stderr_output) { 'stderr output' }
before { allow(process_status).to receive(:success?).and_return(false) }
it 'throws an exception about being unable to show the file at specified sha' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not show important_file.txt at sha1. STDERR was: stderr output')
end
end
end
describe '#fetch' do
let(:dir) {Dir.mktmpdir }
subject { described_class.fetch(dir) }
before { allow(described_class).to receive(:system).and_return(git_successful) }
context 'git works properly' do
let(:git_successful) { true }
it 'should git fetch' do
expect(described_class).to receive(:system).with('git fetch')
subject
end
end
context 'git fails' do
let(:git_successful) { false }
it 'throws an exception about not fetching' do
expect{ subject }.to raise_error(GitClient::GitError, 'Could not fetch')
end
end
end
end
|
# frozen_string_literal: true
require 'spec_helper'
describe 'license fillable fields' do
licenses.each do |license|
context "The #{license['title']} license" do
it 'should only contain supported fillable fields' do
matches = license['content'].scan(/\[([a-z]+)\]/)
extra_fields = matches.flatten - (fields.map { |f| f['name'] })
expect(extra_fields).to be_empty
end
end
end
end
only look for unknown [] fields in first 1000 charcters
that's where they're likely to be, outside of examples at the end
of long licenses
still want to check as if there are unknown [] fields in first
1000 characters, might be a field that should be filled in, but
wouldn't for lack of correct name
# frozen_string_literal: true
require 'spec_helper'
describe 'license fillable fields' do
licenses.each do |license|
context "The #{license['title']} license" do
it 'should only contain supported fillable fields' do
matches = license['content'][0,1000].scan(/\[([a-z]+)\]/)
extra_fields = matches.flatten - (fields.map { |f| f['name'] })
expect(extra_fields).to be_empty
end
end
end
end
|
module MongoSessionStore
VERSION = "3.0.0.beta.1".freeze
end
Bump to v3.0.0 [ci skip]
module MongoSessionStore
VERSION = "3.0.0".freeze
end
|
require 'spec_helper'
describe Mailer do
context "Err Notification" do
include EmailSpec::Helpers
include EmailSpec::Matchers
before do
@notice = Factory(:notice, :message => "class < ActionController::Base")
@email = Mailer.err_notification(@notice).deliver
end
it "should send the email" do
ActionMailer::Base.deliveries.size.should == 1
end
it "should html-escape the notice's message for the html part" do
@email.should have_body_text("class < ActionController::Base")
end
it "should have inline css" do
@email.should have_body_text('<p class="backtrace" style="')
end
end
end
fix spec about spec/mailers/mailer with fabrication_gem
require 'spec_helper'
describe Mailer do
context "Err Notification" do
include EmailSpec::Helpers
include EmailSpec::Matchers
before do
@notice = Fabricate(:notice, :message => "class < ActionController::Base")
@email = Mailer.err_notification(@notice).deliver
end
it "should send the email" do
ActionMailer::Base.deliveries.size.should == 1
end
it "should html-escape the notice's message for the html part" do
@email.should have_body_text("class < ActionController::Base")
end
it "should have inline css" do
@email.should have_body_text('<p class="backtrace" style="')
end
end
end
|
module MortgageCalculator
module Version
MAJOR = 3
MINOR = 4
PATCH = 0
STRING = [MAJOR, MINOR, PATCH].join('.')
end
end
bump engine version number
module MortgageCalculator
module Version
MAJOR = 3
MINOR = 5
PATCH = 0
STRING = [MAJOR, MINOR, PATCH].join('.')
end
end
|
module MortgageCalculator
module Version
MAJOR = 1
MINOR = 0
PATCH = 0
STRING = [MAJOR, MINOR, PATCH].join('.')
end
end
Bump version to 1.0.1.
module MortgageCalculator
module Version
MAJOR = 1
MINOR = 0
PATCH = 1
STRING = [MAJOR, MINOR, PATCH].join('.')
end
end
|
# Copyright (c) 2012, HipByte SPRL and contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
module Motion; module Project;
class XcodeConfig < Config
variable :xcode_dir, :sdk_version, :deployment_target, :frameworks,
:weak_frameworks, :framework_search_paths, :libs, :identifier,
:codesign_certificate, :short_version, :entitlements, :delegate_class
def initialize(project_dir, build_mode)
super
@info_plist = {}
@dependencies = {}
@frameworks = []
@weak_frameworks = []
@framework_search_paths = []
@libs = []
@bundle_signature = '????'
@short_version = nil
@entitlements = {}
@delegate_class = 'AppDelegate'
@spec_mode = false
end
def xcode_dir
@xcode_dir ||= begin
xcode_dot_app_path = '/Applications/Xcode.app/Contents/Developer'
# First, honor /usr/bin/xcode-select
xcodeselect = '/usr/bin/xcode-select'
if File.exist?(xcodeselect)
path = `#{xcodeselect} -print-path`.strip
if path.match(/^\/Developer\//) and File.exist?(xcode_dot_app_path)
@xcode_error_printed ||= false
$stderr.puts(<<EOS) unless @xcode_error_printed
===============================================================================
It appears that you have a version of Xcode installed in /Applications that has
not been set as the default version. It is possible that RubyMotion may be
using old versions of certain tools which could eventually cause issues.
To fix this problem, you can type the following command in the terminal:
$ sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer
===============================================================================
EOS
@xcode_error_printed = true
end
return path if File.exist?(path)
end
# Since xcode-select is borked, we assume the user installed Xcode
# as an app (new in Xcode 4.3).
return xcode_dot_app_path if File.exist?(xcode_dot_app_path)
App.fail "Can't locate any version of Xcode on the system."
end
unescape_path(@xcode_dir)
end
def xcode_version
@xcode_version ||= begin
txt = `#{locate_binary('xcodebuild')} -version`
vers = txt.scan(/Xcode\s(.+)/)[0][0]
build = txt.scan(/(BuildVersion:|Build version)\s(.+)/)[0][1]
[vers, build]
end
end
def platforms; raise; end
def local_platform; raise; end
def deploy_platform; raise; end
def validate
# Xcode version
App.fail "Xcode 4.x or greater is required" if xcode_version[0] < '4.0'
# sdk_version
platforms.each do |platform|
sdk_path = File.join(platforms_dir, platform + '.platform',
"Developer/SDKs/#{platform}#{sdk_version}.sdk")
unless File.exist?(sdk_path)
App.fail "Can't locate #{platform} SDK #{sdk_version} at `#{sdk_path}'"
end
end
# deployment_target
if deployment_target.to_f > sdk_version.to_f
App.fail "Deployment target `#{deployment_target}' must be equal or lesser than SDK version `#{sdk_version}'"
end
unless File.exist?(datadir)
App.fail "iOS deployment target #{deployment_target} is not supported by this version of RubyMotion"
end
super
end
def platforms_dir
File.join(xcode_dir, 'Platforms')
end
def platform_dir(platform)
File.join(platforms_dir, platform + '.platform')
end
def sdk_version
@sdk_version ||= begin
versions = Dir.glob(File.join(platforms_dir, "#{deploy_platform}.platform/Developer/SDKs/#{deploy_platform}*.sdk")).map do |path|
File.basename(path).scan(/#{deploy_platform}(.*)\.sdk/)[0][0]
end
if versions.size == 0
App.fail "Can't find an iOS SDK in `#{platforms_dir}'"
end
supported_vers = supported_sdk_versions(versions)
unless supported_vers
App.fail "RubyMotion doesn't support any of these SDK versions: #{versions.join(', ')}"
end
supported_vers
end
end
def deployment_target
@deployment_target ||= sdk_version
end
def sdk(platform)
path = File.join(platform_dir(platform), 'Developer/SDKs',
platform + sdk_version + '.sdk')
escape_path(path)
end
def frameworks_dependencies
@frameworks_dependencies ||= begin
# Compute the list of frameworks, including dependencies, that the project uses.
deps = frameworks.dup.uniq
slf = File.join(sdk(local_platform), 'System', 'Library', 'Frameworks')
deps.each do |framework|
framework_path = File.join(slf, framework + '.framework', framework)
if File.exist?(framework_path)
`#{locate_binary('otool')} -L \"#{framework_path}\"`.scan(/\t([^\s]+)\s\(/).each do |dep|
# Only care about public, non-umbrella frameworks (for now).
if md = dep[0].match(/^\/System\/Library\/Frameworks\/(.+)\.framework\/(Versions\/.\/)?(.+)$/) and md[1] == md[3]
if File.exist?(File.join(datadir, 'BridgeSupport', md[1] + '.bridgesupport'))
deps << md[1]
deps.uniq!
end
end
end
end
end
if @framework_search_paths.empty?
deps = deps.select { |dep| File.exist?(File.join(datadir, 'BridgeSupport', dep + '.bridgesupport')) }
end
deps
end
end
def frameworks_stubs_objects(platform)
stubs = []
(frameworks_dependencies + weak_frameworks).uniq.each do |framework|
stubs_obj = File.join(datadir, platform, "#{framework}_stubs.o")
stubs << stubs_obj if File.exist?(stubs_obj)
end
stubs
end
def bridgesupport_files
@bridgesupport_files ||= begin
bs_files = []
deps = ['RubyMotion'] + (frameworks_dependencies + weak_frameworks).uniq
deps << 'UIAutomation' if spec_mode
deps.each do |framework|
supported_versions.each do |ver|
next if ver < deployment_target || sdk_version < ver
bs_path = File.join(datadir(ver), 'BridgeSupport', framework + '.bridgesupport')
if File.exist?(bs_path)
bs_files << bs_path
end
end
end
bs_files
end
end
def default_archs
h = {}
platforms.each do |platform|
h[platform] = Dir.glob(File.join(datadir, platform, '*.bc')).map do |path|
path.scan(/kernel-(.+).bc$/)[0][0]
end
end
h
end
def archs
@archs ||= default_archs
end
def arch_flags(platform)
archs[platform].map { |x| "-arch #{x}" }.join(' ')
end
def common_flags(platform)
"#{arch_flags(platform)} -isysroot \"#{unescape_path(sdk(platform))}\" -F#{sdk(platform)}/System/Library/Frameworks"
end
def cflags(platform, cplusplus)
"#{common_flags(platform)} -fexceptions -fblocks" + (cplusplus ? '' : ' -std=c99') + (xcode_version[0] < '5.0' ? '' : ' -fmodules')
end
def ldflags(platform)
common_flags(platform)
end
def bundle_name
@name + (spec_mode ? '_spec' : '')
end
def app_bundle_dsym(platform)
File.join(versionized_build_dir(platform), bundle_name + '.dSYM')
end
def archive_extension
raise "not implemented"
end
def archive
File.join(versionized_build_dir(deploy_platform), bundle_name + archive_extension)
end
def identifier
@identifier ||= "com.yourcompany.#{@name.gsub(/\s/, '')}"
spec_mode ? @identifier + '_spec' : @identifier
end
def info_plist
@info_plist
end
def dt_info_plist
{}
end
def generic_info_plist
{
'BuildMachineOSBuild' => `sw_vers -buildVersion`.strip,
'CFBundleDevelopmentRegion' => 'en',
'CFBundleName' => @name,
'CFBundleDisplayName' => @name,
'CFBundleIdentifier' => identifier,
'CFBundleExecutable' => @name,
'CFBundleInfoDictionaryVersion' => '6.0',
'CFBundlePackageType' => 'APPL',
'CFBundleShortVersionString' => (@short_version || @version),
'CFBundleSignature' => @bundle_signature,
'CFBundleVersion' => @version
}
end
def pkginfo_data
"AAPL#{@bundle_signature}"
end
def codesign_certificate(platform)
@codesign_certificate ||= begin
cert_type = (distribution_mode ? 'Distribution' : 'Developer')
certs = `/usr/bin/security -q find-certificate -a`.scan(/"#{platform} #{cert_type}: [^"]+"/).uniq
if certs.size == 0
App.fail "Cannot find any #{platform} #{cert_type} certificate in the keychain"
elsif certs.size > 1
App.warn "Found #{certs.size} #{platform} #{cert_type} certificates in the keychain. Set the `codesign_certificate' project setting. Will use the first certificate: `#{certs[0]}'"
end
certs[0][1..-2] # trim trailing `"` characters
end
end
def gen_bridge_metadata(platform, headers, bs_file, c_flags, exceptions=[])
sdk_path = self.sdk(local_platform)
includes = headers.map { |header| "-I'#{File.dirname(header)}'" }.uniq
exceptions = exceptions.map { |x| "\"#{x}\"" }.join(' ')
a = sdk_version.scan(/(\d+)\.(\d+)/)[0]
sdk_version_headers = ((a[0].to_i * 10000) + (a[1].to_i * 100)).to_s
extra_flags = begin
case platform
when "MacOSX"
'--64-bit'
else
(OSX_VERSION >= 10.7 && sdk_version < '7.0') ? '--no-64-bit' : ''
end
end
sh "RUBYOPT='' '#{File.join(bindir, 'gen_bridge_metadata')}' --format complete #{extra_flags} --cflags \" #{c_flags} -isysroot \"#{sdk_path}\" -miphoneos-version-min=#{sdk_version} -D__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__=#{sdk_version_headers} -D__STRICT_ANSI__ -I. #{includes.join(' ')}\" #{headers.map { |x| "\"#{x}\"" }.join(' ')} -o \"#{bs_file}\" #{ "-e #{exceptions}" if exceptions.length != 0}"
end
def define_global_env_txt
rubymotion_env =
if spec_mode
'test'
else
development? ? 'development' : 'release'
end
"rb_define_global_const(\"RUBYMOTION_ENV\", @\"#{rubymotion_env}\");\nrb_define_global_const(\"RUBYMOTION_VERSION\", @\"#{Motion::Version}\");\n"
end
def spritekit_texture_atlas_compiler
path = File.join(xcode_dir, 'usr/bin/TextureAtlas')
File.exist?(path) ? path : nil
end
def assets_bundles
xcassets_bundles = []
resources_dirs.each do |dir|
if File.exist?(dir)
xcassets_bundles.concat(Dir.glob(File.join(dir, '*.xcassets')))
end
end
xcassets_bundles
end
def app_icons_asset_bundle
app_icons_asset_bundles = assets_bundles.map { |b| Dir.glob(File.join(b, '*.appiconset')) }.flatten
if app_icons_asset_bundles.size > 1
App.warn "Found #{app_icons_asset_bundles.size} app icon sets across all " \
"xcasset bundles. Only the first one (alphabetically) " \
"will be used."
end
app_icons_asset_bundles.sort.first
end
def app_icon_name_from_asset_bundle
File.basename(app_icons_asset_bundle, '.appiconset')
end
end
end; end
specify the optimization level when compile the RubyMotion boot codes or vendor codes
# Copyright (c) 2012, HipByte SPRL and contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
module Motion; module Project;
class XcodeConfig < Config
variable :xcode_dir, :sdk_version, :deployment_target, :frameworks,
:weak_frameworks, :framework_search_paths, :libs, :identifier,
:codesign_certificate, :short_version, :entitlements, :delegate_class
def initialize(project_dir, build_mode)
super
@info_plist = {}
@dependencies = {}
@frameworks = []
@weak_frameworks = []
@framework_search_paths = []
@libs = []
@bundle_signature = '????'
@short_version = nil
@entitlements = {}
@delegate_class = 'AppDelegate'
@spec_mode = false
end
def xcode_dir
@xcode_dir ||= begin
xcode_dot_app_path = '/Applications/Xcode.app/Contents/Developer'
# First, honor /usr/bin/xcode-select
xcodeselect = '/usr/bin/xcode-select'
if File.exist?(xcodeselect)
path = `#{xcodeselect} -print-path`.strip
if path.match(/^\/Developer\//) and File.exist?(xcode_dot_app_path)
@xcode_error_printed ||= false
$stderr.puts(<<EOS) unless @xcode_error_printed
===============================================================================
It appears that you have a version of Xcode installed in /Applications that has
not been set as the default version. It is possible that RubyMotion may be
using old versions of certain tools which could eventually cause issues.
To fix this problem, you can type the following command in the terminal:
$ sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer
===============================================================================
EOS
@xcode_error_printed = true
end
return path if File.exist?(path)
end
# Since xcode-select is borked, we assume the user installed Xcode
# as an app (new in Xcode 4.3).
return xcode_dot_app_path if File.exist?(xcode_dot_app_path)
App.fail "Can't locate any version of Xcode on the system."
end
unescape_path(@xcode_dir)
end
def xcode_version
@xcode_version ||= begin
txt = `#{locate_binary('xcodebuild')} -version`
vers = txt.scan(/Xcode\s(.+)/)[0][0]
build = txt.scan(/(BuildVersion:|Build version)\s(.+)/)[0][1]
[vers, build]
end
end
def platforms; raise; end
def local_platform; raise; end
def deploy_platform; raise; end
def validate
# Xcode version
App.fail "Xcode 4.x or greater is required" if xcode_version[0] < '4.0'
# sdk_version
platforms.each do |platform|
sdk_path = File.join(platforms_dir, platform + '.platform',
"Developer/SDKs/#{platform}#{sdk_version}.sdk")
unless File.exist?(sdk_path)
App.fail "Can't locate #{platform} SDK #{sdk_version} at `#{sdk_path}'"
end
end
# deployment_target
if deployment_target.to_f > sdk_version.to_f
App.fail "Deployment target `#{deployment_target}' must be equal or lesser than SDK version `#{sdk_version}'"
end
unless File.exist?(datadir)
App.fail "iOS deployment target #{deployment_target} is not supported by this version of RubyMotion"
end
super
end
def platforms_dir
File.join(xcode_dir, 'Platforms')
end
def platform_dir(platform)
File.join(platforms_dir, platform + '.platform')
end
def sdk_version
@sdk_version ||= begin
versions = Dir.glob(File.join(platforms_dir, "#{deploy_platform}.platform/Developer/SDKs/#{deploy_platform}*.sdk")).map do |path|
File.basename(path).scan(/#{deploy_platform}(.*)\.sdk/)[0][0]
end
if versions.size == 0
App.fail "Can't find an iOS SDK in `#{platforms_dir}'"
end
supported_vers = supported_sdk_versions(versions)
unless supported_vers
App.fail "RubyMotion doesn't support any of these SDK versions: #{versions.join(', ')}"
end
supported_vers
end
end
def deployment_target
@deployment_target ||= sdk_version
end
def sdk(platform)
path = File.join(platform_dir(platform), 'Developer/SDKs',
platform + sdk_version + '.sdk')
escape_path(path)
end
def frameworks_dependencies
@frameworks_dependencies ||= begin
# Compute the list of frameworks, including dependencies, that the project uses.
deps = frameworks.dup.uniq
slf = File.join(sdk(local_platform), 'System', 'Library', 'Frameworks')
deps.each do |framework|
framework_path = File.join(slf, framework + '.framework', framework)
if File.exist?(framework_path)
`#{locate_binary('otool')} -L \"#{framework_path}\"`.scan(/\t([^\s]+)\s\(/).each do |dep|
# Only care about public, non-umbrella frameworks (for now).
if md = dep[0].match(/^\/System\/Library\/Frameworks\/(.+)\.framework\/(Versions\/.\/)?(.+)$/) and md[1] == md[3]
if File.exist?(File.join(datadir, 'BridgeSupport', md[1] + '.bridgesupport'))
deps << md[1]
deps.uniq!
end
end
end
end
end
if @framework_search_paths.empty?
deps = deps.select { |dep| File.exist?(File.join(datadir, 'BridgeSupport', dep + '.bridgesupport')) }
end
deps
end
end
def frameworks_stubs_objects(platform)
stubs = []
(frameworks_dependencies + weak_frameworks).uniq.each do |framework|
stubs_obj = File.join(datadir, platform, "#{framework}_stubs.o")
stubs << stubs_obj if File.exist?(stubs_obj)
end
stubs
end
def bridgesupport_files
@bridgesupport_files ||= begin
bs_files = []
deps = ['RubyMotion'] + (frameworks_dependencies + weak_frameworks).uniq
deps << 'UIAutomation' if spec_mode
deps.each do |framework|
supported_versions.each do |ver|
next if ver < deployment_target || sdk_version < ver
bs_path = File.join(datadir(ver), 'BridgeSupport', framework + '.bridgesupport')
if File.exist?(bs_path)
bs_files << bs_path
end
end
end
bs_files
end
end
def default_archs
h = {}
platforms.each do |platform|
h[platform] = Dir.glob(File.join(datadir, platform, '*.bc')).map do |path|
path.scan(/kernel-(.+).bc$/)[0][0]
end
end
h
end
def archs
@archs ||= default_archs
end
def arch_flags(platform)
archs[platform].map { |x| "-arch #{x}" }.join(' ')
end
def common_flags(platform)
"#{arch_flags(platform)} -isysroot \"#{unescape_path(sdk(platform))}\" -F#{sdk(platform)}/System/Library/Frameworks"
end
def cflags(platform, cplusplus)
optz_level = development? ? '-O0' : '-O3'
"#{common_flags(platform)} #{optz_level} -fexceptions -fblocks" + (cplusplus ? '' : ' -std=c99') + (xcode_version[0] < '5.0' ? '' : ' -fmodules')
end
def ldflags(platform)
common_flags(platform)
end
def bundle_name
@name + (spec_mode ? '_spec' : '')
end
def app_bundle_dsym(platform)
File.join(versionized_build_dir(platform), bundle_name + '.dSYM')
end
def archive_extension
raise "not implemented"
end
def archive
File.join(versionized_build_dir(deploy_platform), bundle_name + archive_extension)
end
def identifier
@identifier ||= "com.yourcompany.#{@name.gsub(/\s/, '')}"
spec_mode ? @identifier + '_spec' : @identifier
end
def info_plist
@info_plist
end
def dt_info_plist
{}
end
def generic_info_plist
{
'BuildMachineOSBuild' => `sw_vers -buildVersion`.strip,
'CFBundleDevelopmentRegion' => 'en',
'CFBundleName' => @name,
'CFBundleDisplayName' => @name,
'CFBundleIdentifier' => identifier,
'CFBundleExecutable' => @name,
'CFBundleInfoDictionaryVersion' => '6.0',
'CFBundlePackageType' => 'APPL',
'CFBundleShortVersionString' => (@short_version || @version),
'CFBundleSignature' => @bundle_signature,
'CFBundleVersion' => @version
}
end
def pkginfo_data
"AAPL#{@bundle_signature}"
end
def codesign_certificate(platform)
@codesign_certificate ||= begin
cert_type = (distribution_mode ? 'Distribution' : 'Developer')
certs = `/usr/bin/security -q find-certificate -a`.scan(/"#{platform} #{cert_type}: [^"]+"/).uniq
if certs.size == 0
App.fail "Cannot find any #{platform} #{cert_type} certificate in the keychain"
elsif certs.size > 1
App.warn "Found #{certs.size} #{platform} #{cert_type} certificates in the keychain. Set the `codesign_certificate' project setting. Will use the first certificate: `#{certs[0]}'"
end
certs[0][1..-2] # trim trailing `"` characters
end
end
def gen_bridge_metadata(platform, headers, bs_file, c_flags, exceptions=[])
sdk_path = self.sdk(local_platform)
includes = headers.map { |header| "-I'#{File.dirname(header)}'" }.uniq
exceptions = exceptions.map { |x| "\"#{x}\"" }.join(' ')
a = sdk_version.scan(/(\d+)\.(\d+)/)[0]
sdk_version_headers = ((a[0].to_i * 10000) + (a[1].to_i * 100)).to_s
extra_flags = begin
case platform
when "MacOSX"
'--64-bit'
else
(OSX_VERSION >= 10.7 && sdk_version < '7.0') ? '--no-64-bit' : ''
end
end
sh "RUBYOPT='' '#{File.join(bindir, 'gen_bridge_metadata')}' --format complete #{extra_flags} --cflags \" #{c_flags} -isysroot \"#{sdk_path}\" -miphoneos-version-min=#{sdk_version} -D__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__=#{sdk_version_headers} -D__STRICT_ANSI__ -I. #{includes.join(' ')}\" #{headers.map { |x| "\"#{x}\"" }.join(' ')} -o \"#{bs_file}\" #{ "-e #{exceptions}" if exceptions.length != 0}"
end
def define_global_env_txt
rubymotion_env =
if spec_mode
'test'
else
development? ? 'development' : 'release'
end
"rb_define_global_const(\"RUBYMOTION_ENV\", @\"#{rubymotion_env}\");\nrb_define_global_const(\"RUBYMOTION_VERSION\", @\"#{Motion::Version}\");\n"
end
def spritekit_texture_atlas_compiler
path = File.join(xcode_dir, 'usr/bin/TextureAtlas')
File.exist?(path) ? path : nil
end
def assets_bundles
xcassets_bundles = []
resources_dirs.each do |dir|
if File.exist?(dir)
xcassets_bundles.concat(Dir.glob(File.join(dir, '*.xcassets')))
end
end
xcassets_bundles
end
def app_icons_asset_bundle
app_icons_asset_bundles = assets_bundles.map { |b| Dir.glob(File.join(b, '*.appiconset')) }.flatten
if app_icons_asset_bundles.size > 1
App.warn "Found #{app_icons_asset_bundles.size} app icon sets across all " \
"xcasset bundles. Only the first one (alphabetically) " \
"will be used."
end
app_icons_asset_bundles.sort.first
end
def app_icon_name_from_asset_bundle
File.basename(app_icons_asset_bundle, '.appiconset')
end
end
end; end
|
# encoding: utf-8
module Nanoc3::CLI::Commands
class Compile < Cri::Command
def name
'compile'
end
def aliases
[]
end
def short_desc
'compile items of this site'
end
def long_desc
'Compile all items of the current site.' +
"\n\n" +
'By default, only item that are outdated will be compiled. This can ' +
'speed up the compilation process quite a bit, but items that include ' +
'content from other items may have to be recompiled manually.'
end
def usage
"nanoc3 compile [options]"
end
def option_definitions
[
# --all
{
:long => 'all', :short => 'a', :argument => :forbidden,
:desc => '(ignored)'
},
# --force
{
:long => 'force', :short => 'f', :argument => :forbidden,
:desc => '(ignored)'
}
]
end
def run(options, arguments)
# Make sure we are in a nanoc site directory
puts "Loading site data..."
@base.require_site
# Check presence of --all option
if options.has_key?(:all) || options.has_key?(:force)
$stderr.puts "Warning: the --force option (and its deprecated --all alias) are, as of nanoc 3.2, no longer supported and have no effect."
end
# Warn if trying to compile a single item
if arguments.size == 1
$stderr.puts '-' * 80
$stderr.puts 'Note: As of nanoc 3.2, it is no longer possible to compile a single item. When invoking the “compile” command, all items in the site will be compiled.'.make_compatible_with_env
$stderr.puts '-' * 80
end
# Give feedback
puts "Compiling site..."
# Initialize profiling stuff
time_before = Time.now
@rep_times = {}
@filter_times = {}
setup_notifications
# Compile
@base.site.compiler.run
# Find reps
reps = @base.site.items.map { |i| i.reps }.flatten
# Show skipped reps
reps.select { |r| !r.compiled? }.each do |rep|
rep.raw_paths.each do |snapshot_name, filename|
next if filename.nil?
duration = @rep_times[filename]
Nanoc3::CLI::Logger.instance.file(:high, :skip, filename, duration)
end
end
# Show diff
write_diff_for(reps)
# Give general feedback
puts
puts "Site compiled in #{format('%.2f', Time.now - time_before)}s."
# Give detailed feedback
if options.has_key?(:verbose)
print_profiling_feedback(reps)
end
end
private
def setup_notifications
# File notifications
Nanoc3::NotificationCenter.on(:rep_written) do |rep, path, is_created, is_modified|
action = (is_created ? :create : (is_modified ? :update : :identical))
duration = Time.now - @rep_times[rep.raw_path] if @rep_times[rep.raw_path]
Nanoc3::CLI::Logger.instance.file(:high, action, path, duration)
end
# Debug notifications
Nanoc3::NotificationCenter.on(:compilation_started) do |rep|
puts "*** Started compilation of #{rep.inspect}" if @base.debug?
end
Nanoc3::NotificationCenter.on(:compilation_ended) do |rep|
puts "*** Ended compilation of #{rep.inspect}" if @base.debug?
end
Nanoc3::NotificationCenter.on(:compilation_failed) do |rep|
puts "*** Suspended compilation of #{rep.inspect} due to unmet dependencies" if @base.debug?
end
Nanoc3::NotificationCenter.on(:cached_content_used) do |rep|
puts "*** Used cached compiled content for #{rep.inspect} instead of recompiling" if @base.debug?
end
# Timing notifications
Nanoc3::NotificationCenter.on(:compilation_started) do |rep|
@rep_times[rep.raw_path] = Time.now
end
Nanoc3::NotificationCenter.on(:compilation_ended) do |rep|
@rep_times[rep.raw_path] = Time.now - @rep_times[rep.raw_path]
end
Nanoc3::NotificationCenter.on(:filtering_started) do |rep, filter_name|
@filter_times[filter_name] = Time.now
start_filter_progress(rep, filter_name)
end
Nanoc3::NotificationCenter.on(:filtering_ended) do |rep, filter_name|
@filter_times[filter_name] = Time.now - @filter_times[filter_name]
stop_filter_progress(rep, filter_name)
end
end
def write_diff_for(reps)
# Delete diff
FileUtils.rm('output.diff') if File.file?('output.diff')
# Don’t generate diffs when diffs are disabled
return if !@base.site.config[:enable_output_diff]
# Generate diff
full_diff = ''
reps.each do |rep|
diff = rep.diff
next if diff.nil?
# Fix header
# FIXME this may break for other lines starting with --- or +++
diff.sub!(/^--- .*/, '--- ' + rep.raw_path)
diff.sub!(/^\+\+\+ .*/, '+++ ' + rep.raw_path)
# Add
full_diff << diff
end
# Write
File.open('output.diff', 'w') { |io| io.write(full_diff) }
end
def start_filter_progress(rep, filter_name)
# Only show progress on terminals
return if $stdout.tty?
@progress_thread = Thread.new do
delay = 1.0
step = 0
text = "Running #{filter_name} filter… ".make_compatible_with_env
while !Thread.current[:stopped]
sleep 0.1
delay -= 0.1
next if !$stdout.tty? || delay > 0.05
$stdout.print text + %w( | / - \\ )[step] + "\r"
step = (step + 1) % 4
end
if $stdout.tty? && delay < 0.05
$stdout.print ' ' * (text.length + 1 + 1) + "\r"
end
end
end
def stop_filter_progress(rep, filter_name)
# Only show progress on terminals
return if $stdout.tty?
@progress_thread[:stopped] = true
end
def print_profiling_feedback(reps)
# Get max filter length
max_filter_name_length = @filter_times.keys.map { |k| k.to_s.size }.max
return if max_filter_name_length.nil?
# Print warning if necessary
if reps.any? { |r| !r.compiled? }
$stderr.puts
$stderr.puts "Warning: profiling information may not be accurate because " +
"some items were not compiled."
end
# Print header
puts
puts ' ' * max_filter_name_length + ' | count min avg max tot'
puts '-' * max_filter_name_length + '-+-----------------------------------'
@filter_times.to_a.sort_by { |r| r[1] }.each do |row|
# Extract data
filter_name, samples = *row
# Calculate stats
count = samples.size
min = samples.min
tot = samples.inject { |memo, i| memo + i}
avg = tot/count
max = samples.max
# Format stats
count = format('%4d', count)
min = format('%4.2f', min)
avg = format('%4.2f', avg)
max = format('%4.2f', max)
tot = format('%5.2f', tot)
# Output stats
filter_name = format("%#{max_filter_name_length}s", filter_name)
puts "#{filter_name} | #{count} #{min}s #{avg}s #{max}s #{tot}s"
end
end
end
end
made progress be printed when stdout *IS* a terminal (oops)
# encoding: utf-8
module Nanoc3::CLI::Commands
class Compile < Cri::Command
def name
'compile'
end
def aliases
[]
end
def short_desc
'compile items of this site'
end
def long_desc
'Compile all items of the current site.' +
"\n\n" +
'By default, only item that are outdated will be compiled. This can ' +
'speed up the compilation process quite a bit, but items that include ' +
'content from other items may have to be recompiled manually.'
end
def usage
"nanoc3 compile [options]"
end
def option_definitions
[
# --all
{
:long => 'all', :short => 'a', :argument => :forbidden,
:desc => '(ignored)'
},
# --force
{
:long => 'force', :short => 'f', :argument => :forbidden,
:desc => '(ignored)'
}
]
end
def run(options, arguments)
# Make sure we are in a nanoc site directory
puts "Loading site data..."
@base.require_site
# Check presence of --all option
if options.has_key?(:all) || options.has_key?(:force)
$stderr.puts "Warning: the --force option (and its deprecated --all alias) are, as of nanoc 3.2, no longer supported and have no effect."
end
# Warn if trying to compile a single item
if arguments.size == 1
$stderr.puts '-' * 80
$stderr.puts 'Note: As of nanoc 3.2, it is no longer possible to compile a single item. When invoking the “compile” command, all items in the site will be compiled.'.make_compatible_with_env
$stderr.puts '-' * 80
end
# Give feedback
puts "Compiling site..."
# Initialize profiling stuff
time_before = Time.now
@rep_times = {}
@filter_times = {}
setup_notifications
# Compile
@base.site.compiler.run
# Find reps
reps = @base.site.items.map { |i| i.reps }.flatten
# Show skipped reps
reps.select { |r| !r.compiled? }.each do |rep|
rep.raw_paths.each do |snapshot_name, filename|
next if filename.nil?
duration = @rep_times[filename]
Nanoc3::CLI::Logger.instance.file(:high, :skip, filename, duration)
end
end
# Show diff
write_diff_for(reps)
# Give general feedback
puts
puts "Site compiled in #{format('%.2f', Time.now - time_before)}s."
# Give detailed feedback
if options.has_key?(:verbose)
print_profiling_feedback(reps)
end
end
private
def setup_notifications
# File notifications
Nanoc3::NotificationCenter.on(:rep_written) do |rep, path, is_created, is_modified|
action = (is_created ? :create : (is_modified ? :update : :identical))
duration = Time.now - @rep_times[rep.raw_path] if @rep_times[rep.raw_path]
Nanoc3::CLI::Logger.instance.file(:high, action, path, duration)
end
# Debug notifications
Nanoc3::NotificationCenter.on(:compilation_started) do |rep|
puts "*** Started compilation of #{rep.inspect}" if @base.debug?
end
Nanoc3::NotificationCenter.on(:compilation_ended) do |rep|
puts "*** Ended compilation of #{rep.inspect}" if @base.debug?
end
Nanoc3::NotificationCenter.on(:compilation_failed) do |rep|
puts "*** Suspended compilation of #{rep.inspect} due to unmet dependencies" if @base.debug?
end
Nanoc3::NotificationCenter.on(:cached_content_used) do |rep|
puts "*** Used cached compiled content for #{rep.inspect} instead of recompiling" if @base.debug?
end
# Timing notifications
Nanoc3::NotificationCenter.on(:compilation_started) do |rep|
@rep_times[rep.raw_path] = Time.now
end
Nanoc3::NotificationCenter.on(:compilation_ended) do |rep|
@rep_times[rep.raw_path] = Time.now - @rep_times[rep.raw_path]
end
Nanoc3::NotificationCenter.on(:filtering_started) do |rep, filter_name|
@filter_times[filter_name] = Time.now
start_filter_progress(rep, filter_name)
end
Nanoc3::NotificationCenter.on(:filtering_ended) do |rep, filter_name|
@filter_times[filter_name] = Time.now - @filter_times[filter_name]
stop_filter_progress(rep, filter_name)
end
end
def write_diff_for(reps)
# Delete diff
FileUtils.rm('output.diff') if File.file?('output.diff')
# Don’t generate diffs when diffs are disabled
return if !@base.site.config[:enable_output_diff]
# Generate diff
full_diff = ''
reps.each do |rep|
diff = rep.diff
next if diff.nil?
# Fix header
# FIXME this may break for other lines starting with --- or +++
diff.sub!(/^--- .*/, '--- ' + rep.raw_path)
diff.sub!(/^\+\+\+ .*/, '+++ ' + rep.raw_path)
# Add
full_diff << diff
end
# Write
File.open('output.diff', 'w') { |io| io.write(full_diff) }
end
def start_filter_progress(rep, filter_name)
# Only show progress on terminals
return if !$stdout.tty?
@progress_thread = Thread.new do
delay = 1.0
step = 0
text = "Running #{filter_name} filter… ".make_compatible_with_env
while !Thread.current[:stopped]
sleep 0.1
delay -= 0.1
next if !$stdout.tty? || delay > 0.05
$stdout.print text + %w( | / - \\ )[step] + "\r"
step = (step + 1) % 4
end
if $stdout.tty? && delay < 0.05
$stdout.print ' ' * (text.length + 1 + 1) + "\r"
end
end
end
def stop_filter_progress(rep, filter_name)
# Only show progress on terminals
return if !$stdout.tty?
@progress_thread[:stopped] = true
end
def print_profiling_feedback(reps)
# Get max filter length
max_filter_name_length = @filter_times.keys.map { |k| k.to_s.size }.max
return if max_filter_name_length.nil?
# Print warning if necessary
if reps.any? { |r| !r.compiled? }
$stderr.puts
$stderr.puts "Warning: profiling information may not be accurate because " +
"some items were not compiled."
end
# Print header
puts
puts ' ' * max_filter_name_length + ' | count min avg max tot'
puts '-' * max_filter_name_length + '-+-----------------------------------'
@filter_times.to_a.sort_by { |r| r[1] }.each do |row|
# Extract data
filter_name, samples = *row
# Calculate stats
count = samples.size
min = samples.min
tot = samples.inject { |memo, i| memo + i}
avg = tot/count
max = samples.max
# Format stats
count = format('%4d', count)
min = format('%4.2f', min)
avg = format('%4.2f', avg)
max = format('%4.2f', max)
tot = format('%5.2f', tot)
# Output stats
filter_name = format("%#{max_filter_name_length}s", filter_name)
puts "#{filter_name} | #{count} #{min}s #{avg}s #{max}s #{tot}s"
end
end
end
end
|
# encoding: utf-8
require 'haml'
module NanocFuel::Helpers
module Facebook
def fb_init(app_id)
fb_init_haml(app_id)
end
def fb_init_haml(app_id)
template = File.read(File.expand_path("../templates/fb_init.haml", __FILE__))
Haml::Engine.new(template).render(Object.new, :app_id => app_id)
end
def fb_comments(url, num_posts, width)
haml_fb_comments(url, num_posts, width)
end
def fb_comments_haml(url, num_posts, width)
template = File.read(File.expand_path("../templates/fb_comments.haml", __FILE__))
Haml::Engine.new(template).render(Object.new, :url => url, :num_posts => num_posts, :width => width)
end
end
end
fixes fb_comments helper
# encoding: utf-8
require 'haml'
module NanocFuel::Helpers
module Facebook
def fb_init(app_id)
fb_init_haml(app_id)
end
def fb_init_haml(app_id)
template = File.read(File.expand_path("../templates/fb_init.haml", __FILE__))
Haml::Engine.new(template).render(Object.new, :app_id => app_id)
end
def fb_comments(url, num_posts, width)
fb_comments_haml(url, num_posts, width)
end
def fb_comments_haml(url, num_posts, width)
template = File.read(File.expand_path("../templates/fb_comments.haml", __FILE__))
Haml::Engine.new(template).render(Object.new, :url => url, :num_posts => num_posts, :width => width)
end
end
end |
module NewRelicAWS
module Collectors
class ELB < Base
def load_balancers
elb = AWS::ELB.new(
:access_key_id => @aws_access_key,
:secret_access_key => @aws_secret_key,
:region => @aws_region
)
elb.load_balancers.map { |load_balancer| load_balancer.name }
end
def metric_list
{
"Latency" => "Seconds",
"RequestCount" => "Count",
"HealthyHostCount" => "Count",
"UnHealthyHostCount" => "Count",
"HTTPCode_ELB_4XX" => "Count",
"HTTPCode_ELB_5XX" => "Count",
"HTTPCode_Backend_2XX" => "Count",
"HTTPCode_Backend_3XX" => "Count",
"HTTPCode_Backend_4XX" => "Count",
"HTTPCode_Backend_5XX" => "Count"
}
end
def collect
data_points = []
load_balancers.each do |load_balancer_name|
metric_list.each do |metric_name, unit|
data_point = get_data_point(
:namespace => "AWS/ELB",
:metric_name => metric_name,
:unit => unit,
:dimension => {
:name => "LoadBalancerName",
:value => load_balancer_name
}
)
unless data_point.nil?
data_points << data_point
end
end
end
data_points
end
end
end
end
[statistic] fixed statistics for elb
module NewRelicAWS
module Collectors
class ELB < Base
def load_balancers
elb = AWS::ELB.new(
:access_key_id => @aws_access_key,
:secret_access_key => @aws_secret_key,
:region => @aws_region
)
elb.load_balancers.map { |load_balancer| load_balancer.name }
end
def metric_list
[
["Latency", "Average", "Seconds"],
["RequestCount", "Sum", "Count"],
["HealthyHostCount", "Maximum", "Count"],
["UnHealthyHostCount", "Maximum", "Count"],
["HTTPCode_ELB_4XX", "Sum", "Count"],
["HTTPCode_ELB_5XX", "Sum", "Count"],
["HTTPCode_Backend_2XX", "Sum", "Count"],
["HTTPCode_Backend_3XX", "Sum", "Count"],
["HTTPCode_Backend_4XX", "Sum", "Count"],
["HTTPCode_Backend_5XX", "Sum", "Count"]
]
end
def collect
data_points = []
load_balancers.each do |load_balancer_name|
metric_list.each do |(metric_name, statistic, unit)|
data_point = get_data_point(
:namespace => "AWS/ELB",
:metric_name => metric_name,
:statistic => statistic,
:unit => unit,
:dimension => {
:name => "LoadBalancerName",
:value => load_balancer_name
}
)
unless data_point.nil?
data_points << data_point
end
end
end
data_points
end
end
end
end
|
#
# Author:: Benjamin Black (<nostromo@gmail.com>)
# Copyright:: Copyright (c) 2008 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'resolv'
require 'scanf'
# wow, this is ugly!
def parse_medium(medium)
m_array = medium.split(' ')
medium = { m_array[0] => { "options" => [] }}
if m_array.length > 1
if m_array[1] =~ /^\<([a-zA-Z\-\,]+)\>/
medium[m_array[0]]["options"] = $1.split(',')
end
end
medium
end
def parse_media(media_string)
media = Array.new
line_array = media_string.split(' ')
0.upto(line_array.length - 1) do |i|
unless line_array[i].eql?("none")
if line_array[i + 1] =~ /^\<([a-zA-Z\-\,]+)\>/
media << parse_medium(line_array[i,i + 1].join(' '))
else
media << { "autoselect" => { "options" => [] } } if line_array[i].eql?("autoselect")
next
end
else
media << { "none" => { "options" => [] } }
end
end
media
end
def encaps_lookup(ifname)
return "Loopback" if ifname.eql?("lo")
return "Ethernet" if ifname.eql?("en")
return "1394" if ifname.eql?("fw")
return "IPIP" if ifname.eql?("gif")
return "6to4" if ifname.eql?("stf")
return "dot1q" if ifname.eql?("vlan")
end
network_interfaces(Array.new)
iface = Mash.new
popen4("/sbin/ifconfig -a") do |pid, stdin, stdout, stderr|
stdin.close
cint = nil
stdout.each do |line|
if line =~ /^([[:alnum:]|\:|\-]+) \S+ mtu (\d+)$/
cint = $1.chop
network_interfaces.push(cint)
iface[cint] = Mash.new
iface[cint]["mtu"] = $2
STDERR.puts "LINE IS " + line
if line =~ /flags\=\d+\<((UP|BROADCAST|DEBUG|SMART|SIMPLEX|LOOPBACK|POINTOPOINT|NOTRAILERS|RUNNING|NOARP|PROMISC|ALLMULTI|SLAVE|MASTER|MULTICAST|DYNAMIC|,)+)\>\s/
flags = $1.split(',')
else
flags = Array.new
end
iface[cint]["flags"] = flags.flatten
if cint =~ /^(\w+)(\d+.*)/
iface[cint]["type"] = $1
iface[cint]["number"] = $2
iface[cint]["encapsulation"] = encaps_lookup($1)
end
end
if line =~ /^\s+ether (.+?)\s/
iface[cint]["addresses"] = Array.new unless iface[cint]["addresses"]
iface[cint]["addresses"] << { "family" => "lladdr", "address" => $1 }
end
if line =~ /^\s+lladdr (.+?)\s/
iface[cint]["addresses"] = Array.new unless iface[cint]["addresses"]
iface[cint]["addresses"] << { "family" => "lladdr", "address" => $1 }
end
if line =~ /\s+inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) netmask 0x(([0-9]|[a-f]){1,8})(\s|(broadcast (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})))/
iface[cint]["addresses"] = Array.new unless iface[cint]["addresses"]
iface[cint]["addresses"] << { "family" => "inet", "address" => $1, "netmask" => $2.scanf('%2x'*4)*"."}
iface[cint]["addresses"].last["broadcast"] = $4 if $4.length > 1
end
if line =~ /\s+inet6 ([a-f0-9\:]+)(\s*|(\%[a-z0-9]+)\s*) prefixlen (\d+)(\s|(scopeid 0x(([0-9]|[a-f]))))/
iface[cint]["addresses"] = Array.new unless iface[cint]["addresses"]
begin
Resolv::IPv6.create($1) # this step validates the IPv6 address since the regex above is very loose
iface[cint]["addresses"] << { "family" => "inet6", "address" => $1, "prefixlen" => $4 }
iface[cint]["addresses"].last["scopeid"] = $5 if $5.length > 1
rescue
# guess it wasn't an IPv6 address! this shouldn't happen, but we'll soldier on.
end
end
if line =~ /^\s+media: ((\w+)|(\w+ [a-zA-Z0-9\-\<\>]+)) status: (\w+)/
iface[cint]["media"] = Hash.new unless iface[cint]["media"]
iface[cint]["media"]["selected"] = parse_medium($1)
iface[cint]["status"] = $4
end
if line =~ /^\s+supported media: (.*)/
iface[cint]["media"] = Hash.new unless iface[cint]["media"]
iface[cint]["media"]["supported"] = parse_media($1)
end
end
end
network_interface iface
removed v6 addr validation because ifconfig is the only source
#
# Author:: Benjamin Black (<nostromo@gmail.com>)
# Copyright:: Copyright (c) 2008 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'scanf'
# wow, this is ugly!
def parse_medium(medium)
m_array = medium.split(' ')
medium = { m_array[0] => { "options" => [] }}
if m_array.length > 1
if m_array[1] =~ /^\<([a-zA-Z\-\,]+)\>/
medium[m_array[0]]["options"] = $1.split(',')
end
end
medium
end
def parse_media(media_string)
media = Array.new
line_array = media_string.split(' ')
0.upto(line_array.length - 1) do |i|
unless line_array[i].eql?("none")
if line_array[i + 1] =~ /^\<([a-zA-Z\-\,]+)\>/
media << parse_medium(line_array[i,i + 1].join(' '))
else
media << { "autoselect" => { "options" => [] } } if line_array[i].eql?("autoselect")
next
end
else
media << { "none" => { "options" => [] } }
end
end
media
end
def encaps_lookup(ifname)
return "Loopback" if ifname.eql?("lo")
return "Ethernet" if ifname.eql?("en")
return "1394" if ifname.eql?("fw")
return "IPIP" if ifname.eql?("gif")
return "6to4" if ifname.eql?("stf")
return "dot1q" if ifname.eql?("vlan")
end
network_interfaces(Array.new)
iface = Mash.new
popen4("/sbin/ifconfig -a") do |pid, stdin, stdout, stderr|
stdin.close
cint = nil
stdout.each do |line|
if line =~ /^([[:alnum:]|\:|\-]+) \S+ mtu (\d+)$/
cint = $1.chop
network_interfaces.push(cint)
iface[cint] = Mash.new
iface[cint]["mtu"] = $2
STDERR.puts "LINE IS " + line
if line =~ /flags\=\d+\<((UP|BROADCAST|DEBUG|SMART|SIMPLEX|LOOPBACK|POINTOPOINT|NOTRAILERS|RUNNING|NOARP|PROMISC|ALLMULTI|SLAVE|MASTER|MULTICAST|DYNAMIC|,)+)\>\s/
flags = $1.split(',')
else
flags = Array.new
end
iface[cint]["flags"] = flags.flatten
if cint =~ /^(\w+)(\d+.*)/
iface[cint]["type"] = $1
iface[cint]["number"] = $2
iface[cint]["encapsulation"] = encaps_lookup($1)
end
end
if line =~ /^\s+ether (.+?)\s/
iface[cint]["addresses"] = Array.new unless iface[cint]["addresses"]
iface[cint]["addresses"] << { "family" => "lladdr", "address" => $1 }
end
if line =~ /^\s+lladdr (.+?)\s/
iface[cint]["addresses"] = Array.new unless iface[cint]["addresses"]
iface[cint]["addresses"] << { "family" => "lladdr", "address" => $1 }
end
if line =~ /\s+inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) netmask 0x(([0-9]|[a-f]){1,8})(\s|(broadcast (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})))/
iface[cint]["addresses"] = Array.new unless iface[cint]["addresses"]
iface[cint]["addresses"] << { "family" => "inet", "address" => $1, "netmask" => $2.scanf('%2x'*4)*"."}
iface[cint]["addresses"].last["broadcast"] = $4 if $4.length > 1
end
if line =~ /\s+inet6 ([a-f0-9\:]+)(\s*|(\%[a-z0-9]+)\s*) prefixlen (\d+)(\s|(scopeid 0x(([0-9]|[a-f]))))/
iface[cint]["addresses"] = Array.new unless iface[cint]["addresses"]
iface[cint]["addresses"] << { "family" => "inet6", "address" => $1, "prefixlen" => $4 }
iface[cint]["addresses"].last["scopeid"] = $5 if $5.length > 1
end
if line =~ /^\s+media: ((\w+)|(\w+ [a-zA-Z0-9\-\<\>]+)) status: (\w+)/
iface[cint]["media"] = Hash.new unless iface[cint]["media"]
iface[cint]["media"]["selected"] = parse_medium($1)
iface[cint]["status"] = $4
end
if line =~ /^\s+supported media: (.*)/
iface[cint]["media"] = Hash.new unless iface[cint]["media"]
iface[cint]["media"]["supported"] = parse_media($1)
end
end
end
network_interface iface
|
module Onebox
module Engine
class FlickrOnebox
include OpenGraph
matches
/^https?\:\/\/.*\.flickr\.com\/.*$/
end
private
def extracted_data
{
url: @url,
title: @body.title,
image: @body.images[0],
description: @body.description
}
end
end
end
end
add verbal expression block for flickr
module Onebox
module Engine
class FlickrOnebox
include Engine
include OpenGraph
matches do
# /^https?\:\/\/.*\.flickr\.com\/.*$/
find "flickr.com"
end
private
def extracted_data
{
url: @url,
title: @body.title,
image: @body.images[0],
description: @body.description
}
end
end
end
end
|
module Operationcode
module Slack
VERSION = "0.1.0"
end
end
bump version
module Operationcode
module Slack
VERSION = "0.2.0"
end
end
|
# Copyright (c) 2016-2017 Pierre Goudet <p-goudet@ruby-dev.jp>
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# and Eclipse Distribution License v1.0 which accompany this distribution.
#
# The Eclipse Public License is available at
# https://eclipse.org/org/documents/epl-v10.php.
# and the Eclipse Distribution License is available at
# https://eclipse.org/org/documents/edl-v10.php.
#
# Contributors:
# Pierre Goudet - initial committer
require 'socket'
module PahoMqtt
class ConnectionHelper
attr_accessor :sender
def initialize(host, port, ssl, ssl_context, ack_timeout)
@cs = MQTT_CS_DISCONNECT
@socket = nil
@host = host
@port = port
@ssl = ssl
@ssl_context = ssl_context
@ack_timeout = ack_timeout
@sender = Sender.new(ack_timeout)
end
def handler=(handler)
@handler = handler
end
def do_connect(reconnection=false)
@cs = MQTT_CS_NEW
@handler.socket = @socket
# Waiting a Connack packet for "ack_timeout" second from the remote
connect_timeout = Time.now + @ack_timeout
while (Time.now <= connect_timeout) && !is_connected? do
@cs = @handler.receive_packet
end
unless is_connected?
PahoMqtt.logger.warn("Connection failed. Couldn't recieve a Connack packet from: #{@host}.") if PahoMqtt.logger?
raise Exception.new("Connection failed. Check log for more details.") unless reconnection
end
@cs
end
def is_connected?
@cs == MQTT_CS_CONNECTED
end
def do_disconnect(publisher, explicit, mqtt_thread)
PahoMqtt.logger.debug("Disconnecting from #{@host}.") if PahoMqtt.logger?
if explicit
explicit_disconnect(publisher, mqtt_thread)
end
@socket.close unless @socket.nil? || @socket.closed?
@socket = nil
end
def explicit_disconnect(publisher, mqtt_thread)
@sender.flush_waiting_packet(false)
send_disconnect
mqtt_thread.kill if mqtt_thread && mqtt_thread.alive?
publisher.flush_publisher unless publisher.nil?
end
def setup_connection
clean_start(@host, @port)
config_socket
unless @socket.nil?
@sender.socket = @socket
end
end
def config_socket
PahoMqtt.logger.debug("Attempt to connect to host: #{@host}...") if PahoMqtt.logger?
begin
tcp_socket = TCPSocket.new(@host, @port)
raise if tcp_socket.nil?
if @ssl
encrypted_socket(tcp_socket, @ssl_context)
else
@socket = tcp_socket
end
rescue StandardError
PahoMqtt.logger.warn("Could not open a socket with #{@host} on port #{@port}.") if PahoMqtt.logger?
end
end
def encrypted_socket(tcp_socket, ssl_context)
unless ssl_context.nil?
@socket = OpenSSL::SSL::SSLSocket.new(tcp_socket, ssl_context)
@socket.sync_close = true
@socket.connect
else
PahoMqtt.logger.error("The SSL context was found as nil while the socket's opening.") if PahoMqtt.logger?
raise Exception
end
end
def clean_start(host, port)
self.host = host
self.port = port
unless @socket.nil?
@socket.close unless @socket.closed?
@socket = nil
end
end
def host=(host)
if host.nil? || host == ""
PahoMqtt.logger.error("The host was found as nil while the connection setup.") if PahoMqtt.logger?
raise ArgumentError
else
@host = host
end
end
def port=(port)
if port.to_i <= 0
PahoMqtt.logger.error("The port value is invalid (<= 0). Could not setup the connection.") if PahoMqtt.logger?
raise ArgumentError
else
@port = port
end
end
def send_connect(session_params)
setup_connection
packet = PahoMqtt::Packet::Connect.new(session_params)
@handler.clean_session = session_params[:clean_session]
@sender.send_packet(packet)
MQTT_ERR_SUCCESS
end
def send_disconnect
packet = PahoMqtt::Packet::Disconnect.new
@sender.send_packet(packet)
MQTT_ERR_SUCCESS
end
def check_keep_alive(persistent, last_ping_resp, keep_alive)
now = Time.now
timeout_req = (@sender.last_ping_req + (keep_alive * 0.7).ceil)
if timeout_req <= now && persistent
PahoMqtt.logger.debug("Checking if server is still alive...") if PahoMqtt.logger?
@sender.send_pingreq
end
timeout_resp = last_ping_resp + (keep_alive * 1.1).ceil
if timeout_resp <= now
PahoMqtt.logger.debug("No activity is over timeout, disconnecting from #{@host}.") if PahoMqtt.logger?
@cs = MQTT_CS_DISCONNECT
end
@cs
end
end
end
Add support for EC key
# Copyright (c) 2016-2017 Pierre Goudet <p-goudet@ruby-dev.jp>
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# and Eclipse Distribution License v1.0 which accompany this distribution.
#
# The Eclipse Public License is available at
# https://eclipse.org/org/documents/epl-v10.php.
# and the Eclipse Distribution License is available at
# https://eclipse.org/org/documents/edl-v10.php.
#
# Contributors:
# Pierre Goudet - initial committer
require 'socket'
module PahoMqtt
class ConnectionHelper
attr_accessor :sender
def initialize(host, port, ssl, ssl_context, ack_timeout)
@cs = MQTT_CS_DISCONNECT
@socket = nil
@host = host
@port = port
@ssl = ssl
@ssl_context = ssl_context
@ack_timeout = ack_timeout
@sender = Sender.new(ack_timeout)
end
def handler=(handler)
@handler = handler
end
def do_connect(reconnection=false)
@cs = MQTT_CS_NEW
@handler.socket = @socket
# Waiting a Connack packet for "ack_timeout" second from the remote
connect_timeout = Time.now + @ack_timeout
while (Time.now <= connect_timeout) && !is_connected? do
@cs = @handler.receive_packet
end
unless is_connected?
PahoMqtt.logger.warn("Connection failed. Couldn't recieve a Connack packet from: #{@host}.") if PahoMqtt.logger?
raise Exception.new("Connection failed. Check log for more details.") unless reconnection
end
@cs
end
def is_connected?
@cs == MQTT_CS_CONNECTED
end
def do_disconnect(publisher, explicit, mqtt_thread)
PahoMqtt.logger.debug("Disconnecting from #{@host}.") if PahoMqtt.logger?
if explicit
explicit_disconnect(publisher, mqtt_thread)
end
@socket.close unless @socket.nil? || @socket.closed?
@socket = nil
end
def explicit_disconnect(publisher, mqtt_thread)
@sender.flush_waiting_packet(false)
send_disconnect
mqtt_thread.kill if mqtt_thread && mqtt_thread.alive?
publisher.flush_publisher unless publisher.nil?
end
def setup_connection
clean_start(@host, @port)
config_socket
unless @socket.nil?
@sender.socket = @socket
end
end
def config_socket
PahoMqtt.logger.debug("Attempt to connect to host: #{@host}...") if PahoMqtt.logger?
begin
tcp_socket = TCPSocket.new(@host, @port)
if @ssl
encrypted_socket(tcp_socket, @ssl_context)
else
@socket = tcp_socket
end
rescue StandardError
PahoMqtt.logger.warn("Could not open a socket with #{@host} on port #{@port}.") if PahoMqtt.logger?
end
end
def encrypted_socket(tcp_socket, ssl_context)
unless ssl_context.nil?
@socket = OpenSSL::SSL::SSLSocket.new(tcp_socket, ssl_context)
@socket.sync_close = true
@socket.connect
else
PahoMqtt.logger.error("The SSL context was found as nil while the socket's opening.") if PahoMqtt.logger?
raise Exception
end
end
def clean_start(host, port)
self.host = host
self.port = port
unless @socket.nil?
@socket.close unless @socket.closed?
@socket = nil
end
end
def host=(host)
if host.nil? || host == ""
PahoMqtt.logger.error("The host was found as nil while the connection setup.") if PahoMqtt.logger?
raise ArgumentError
else
@host = host
end
end
def port=(port)
if port.to_i <= 0
PahoMqtt.logger.error("The port value is invalid (<= 0). Could not setup the connection.") if PahoMqtt.logger?
raise ArgumentError
else
@port = port
end
end
def send_connect(session_params)
setup_connection
packet = PahoMqtt::Packet::Connect.new(session_params)
@handler.clean_session = session_params[:clean_session]
@sender.send_packet(packet)
MQTT_ERR_SUCCESS
end
def send_disconnect
packet = PahoMqtt::Packet::Disconnect.new
@sender.send_packet(packet)
MQTT_ERR_SUCCESS
end
def check_keep_alive(persistent, last_ping_resp, keep_alive)
now = Time.now
timeout_req = (@sender.last_ping_req + (keep_alive * 0.7).ceil)
if timeout_req <= now && persistent
PahoMqtt.logger.debug("Checking if server is still alive...") if PahoMqtt.logger?
@sender.send_pingreq
end
timeout_resp = last_ping_resp + (keep_alive * 1.1).ceil
if timeout_resp <= now
PahoMqtt.logger.debug("No activity is over timeout, disconnecting from #{@host}.") if PahoMqtt.logger?
@cs = MQTT_CS_DISCONNECT
end
@cs
end
end
end
|
# encoding: UTF-8
# frozen_string_literal: true
require 'active_model'
require 'active_support'
require 'active_support/inflector'
require 'active_support/core_ext'
require 'active_support/core_ext/object'
require 'active_support/inflector'
require 'active_model_serializers'
require 'active_support/inflector'
require 'active_model_serializers'
require 'active_support/hash_with_indifferent_access'
require 'time'
=begin
This module provides support for handling all the different types of column data types
supported in Parse and mapping them between their remote names with their local ruby named attributes.
By default, the convention used for naming parameters is that the remote column should be in lower-first-camelcase, (ex. myField, eventAddress), except for
a few special columns like "id" and "acl".
Properties are defined when creating subclasses of Parse::Object and using the `property` class method.
By defining properties, dynamic methods are created in order to allow getters and setters to be used. We will go into detail below.
Each class will have a different copy of attribute mapping and field mappings.
=end
module Parse
module Properties
# This is an exception that is thrown if there is an issue when creating a specific property for a class.
class DefinitionError < StandardError; end;
class ValueError < StandardError; end;
# These are the base types supported by Parse.
TYPES = [:id, :string, :relation, :integer, :float, :boolean, :date, :array, :file, :geopoint, :bytes, :object, :acl].freeze
# These are the base mappings of the remote field name types.
BASE = {objectId: :string, createdAt: :date, updatedAt: :date, ACL: :acl}.freeze
# The list of properties that are part of all objects
BASE_KEYS = [:id, :created_at, :updated_at].freeze
# Default hash map of local attribute name to remote column name
BASE_FIELD_MAP = {id: :objectId, created_at: :createdAt, updated_at: :updatedAt, acl: :ACL}.freeze
DELETE_OP = {"__op"=>"Delete"}.freeze
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
# The fields method returns a mapping of all local attribute names and their data type.
# if type is passed, we return only the fields that matched that data type
def fields(type = nil)
@fields ||= {id: :string, created_at: :date, updated_at: :date, acl: :acl}
if type.present?
type = type.to_sym
return @fields.select { |k,v| v == type }
end
@fields
end
# This returns the mapping of local to remote attribute names.
def field_map
@field_map ||= BASE_FIELD_MAP.dup
end
def enums
@enums ||= {}
end
# Keeps track of all the attributes supported by this class.
def attributes=(hash)
@attributes = BASE.merge(hash)
end
def attributes
@attributes ||= BASE.dup
end
def defaults_list
@defaults_list ||= []
end
# property :songs, :array
# property :my_date, :date, field: "myRemoteCOLUMNName"
# property :my_int, :integer, required: true, default: ->{ rand(10) }
# field: (literal column name in Parse)
# required: (data_type)
# default: (value or Proc)
# alias: Whether to create the remote field alias getter/setters for this attribute
# This is the class level property method to be used when declaring properties. This helps builds specific methods, formatters
# and conversion handlers for property storing and saving data for a particular parse class.
# The first parameter is the name of the local attribute you want to declare with its corresponding data type.
# Declaring a `property :my_date, :date`, would declare the attribute my_date with a corresponding remote column called
# "myDate" (lower-first-camelcase) with a Parse data type of Date.
# You can override the implicit naming behavior by passing the option :field to override.
# symbolize: Makes sure the saved and return value locally is in symbol format. useful
# for enum type fields that are string columns in Parse. Ex. a booking_status for a field
# could be either "submitted" or "completed" in Parse, however with symbolize, these would
# be available as :submitted or :completed.
def property(key, data_type = :string, **opts)
key = key.to_sym
ivar = :"@#{key}"
will_change_method = :"#{key}_will_change!"
set_attribute_method = :"#{key}_set_attribute!"
if data_type.is_a?(Hash)
opts.merge!(data_type)
data_type = :string
end
# allow :bool for :boolean
data_type = :boolean if data_type == :bool
data_type = :integer if data_type == :int
# set defaults
opts = { required: false,
alias: true,
symbolize: false,
enum: nil,
scopes: true,
_prefix: nil,
_suffix: false,
field: key.to_s.camelize(:lower)
}.merge( opts )
#By default, the remote field name is a lower-first-camelcase version of the key
# it can be overriden by the :field parameter
parse_field = opts[:field].to_sym
if self.fields[key].present? && BASE_FIELD_MAP[key].nil?
raise DefinitionError, "Property #{self}##{key} already defined with data type #{data_type}"
end
# We keep the list of fields that are on the remote Parse store
if self.fields[parse_field].present?
raise DefinitionError, "Alias property #{self}##{parse_field} conflicts with previously defined property."
end
#dirty tracking. It is declared to use with ActiveModel DirtyTracking
define_attribute_methods key
# this hash keeps list of attributes (based on remote fields) and their data types
self.attributes.merge!( parse_field => data_type )
# this maps all the possible attribute fields and their data types. We use both local
# keys and remote keys because when we receive a remote object that has the remote field name
# we need to know what the data type conversion should be.
self.fields.merge!( key => data_type, parse_field => data_type )
# This creates a mapping between the local field and the remote field name.
self.field_map.merge!( key => parse_field )
#puts "Current Self: #{self} - #{key} = #{self.attributes}"
# if the field is marked as required, then add validations
if opts[:required]
# if integer or float, validate that it's a number
if data_type == :integer || data_type == :float
validates_numericality_of key
end
# validate that it is not empty
validates_presence_of key
end
is_enum_type = opts[:enum].nil? == false
if is_enum_type
unless data_type == :string
raise DefinitionError, "Property #{self}##{parse_field} :enum option is only supported on :string data types."
end
enum_values = opts[:enum]
unless enum_values.is_a?(Array) && enum_values.empty? == false
raise DefinitionError, "Property #{self}##{parse_field} :enum option must be an Array type of symbols."
end
opts[:symbolize] = true
enum_values = enum_values.dup.map(&:to_sym).freeze
self.enums.merge!( key => enum_values )
validates key, inclusion: { in: enum_values }, allow_nil: opts[:required]
unless opts[:scopes] == false
# You can use the :_prefix or :_suffix options when you need to define multiple enums with same values.
# If the passed value is true, the methods are prefixed/suffixed with the name of the enum. It is also possible to supply a custom value:
prefix = opts[:_prefix]
add_suffix = opts[:_suffix] == true
prefix_or_key = (prefix.blank? ? key : prefix).to_sym
class_method_name = prefix_or_key.to_s.pluralize.to_sym
if singleton_class.method_defined?(class_method_name)
raise DefinitionError, "You tried to define an enum named `#{key}` for #{self} " + \
"but this will generate a method `#{self}.#{class_method_name}` " + \
" which is already defined. Try using :_suffix or :_prefix options."
end
define_singleton_method(class_method_name) { enum_values }
method_name = add_suffix ? :"valid_#{prefix_or_key}?" : :"#{prefix_or_key}_valid?"
define_method(method_name) { enum_values.include?(instance_variable_get(ivar).to_s.to_sym) }
enum_values.each do |enum|
method_name = enum # default
scope_name = enum
if add_suffix
method_name = :"#{enum}_#{prefix_or_key}"
elsif prefix.present?
method_name = :"#{prefix}_#{enum}"
end
self.scope method_name, ->(ex = {}){ ex.merge!(key => enum); query( ex ) }
define_method("#{method_name}!") { instance_variable_set(ivar, enum) }
define_method("#{method_name}?") { enum == instance_variable_get(ivar).to_s.to_sym }
end
end # unless scopes
end
symbolize_value = opts[:symbolize]
#only support symbolization of string data types
if symbolize_value && (data_type == :string || data_type == :array) == false
raise DefinitionError, 'Symbolization is only supported on :string or :array data types.'
end
# Here is the where the 'magic' begins. For each property defined, we will
# generate special setters and getters that will take advantage of ActiveModel
# helpers.
# get the default value if provided (or Proc)
default_value = opts[:default]
unless default_value.nil?
defaults_list.push(key) unless default_value.nil?
define_method("#{key}_default") do
# If the default object provided is a Proc, then run the proc, otherwise
# we'll assume it's just a plain literal value
default_value.is_a?(Proc) ? default_value.call(self) : default_value
end
end
# We define a getter with the key
define_method(key) do
# we will get the value using the internal value of the instance variable
# using the instance_variable_get
value = instance_variable_get ivar
# If the value is nil and this current Parse::Object instance is a pointer?
# then someone is calling the getter for this, which means they probably want
# its value - so let's go turn this pointer into a full object record
if value.nil? && pointer?
# call autofetch to fetch the entire record
# and then get the ivar again cause it might have been updated.
autofetch!(key)
value = instance_variable_get ivar
end
# if value is nil (even after fetching), then lets see if the developer
# set a default value for this attribute.
if value.nil? && respond_to?("#{key}_default")
value = send("#{key}_default")
value = format_value(key, value, data_type)
# lets set the variable with the updated value
instance_variable_set ivar, value
send will_change_method
end
# if the value is a String (like an iso8601 date) and the data type of
# this object is :date, then let's be nice and create a parse date for it.
if value.is_a?(String) && data_type == :date
value = format_value(key, value, data_type)
instance_variable_set ivar, value
send will_change_method
end
# finally return the value
if symbolize_value
if data_type == :string
return value.respond_to?(:to_sym) ? value.to_sym : value
elsif data_type == :array && value.is_a?(Array)
# value.map(&:to_sym)
return value.compact.map { |m| m.respond_to?(:to_sym) ? m.to_sym : m }
end
end
value
end
# support question mark methods for boolean
if data_type == :boolean
if self.method_defined?("#{key}?")
puts "Creating boolean helper :#{key}?. Will overwrite existing method #{self}##{key}?."
end
# returns true if set to true, false otherwise
define_method("#{key}?") { (send(key) == true) }
unless opts[:scopes] == false
scope key, ->(opts = {}){ query( opts.merge(key => true) ) }
end
end
# The second method to be defined is a setter method. This is done by
# defining :key with a '=' sign. However, to support setting the attribute
# with and without dirty tracking, we really will just proxy it to another method
define_method("#{key}=") do |val|
#we proxy the method passing the value and true. Passing true to the
# method tells it to make sure dirty tracking is enabled.
self.send set_attribute_method, val, true
end
# This is the real setter method. Takes two arguments, the value to set
# and whether to mark it as dirty tracked.
define_method(set_attribute_method) do |val, track = true|
# Each value has a data type, based on that we can treat the incoming
# value as input, and format it to the correct storage format. This method is
# defined in this file (instance method)
val = format_value(key, val, data_type)
# if dirty trackin is enabled, call the ActiveModel required method of _will_change!
# this will grab the current value and keep a copy of it - but we only do this if
# the new value being set is different from the current value stored.
if track == true
send will_change_method unless val == instance_variable_get( ivar )
end
if symbolize_value
if data_type == :string
val = nil if val.blank?
val = val.to_sym if val.respond_to?(:to_sym)
elsif val.is_a?(Parse::CollectionProxy)
items = val.collection.map { |m| m.respond_to?(:to_sym) ? m.to_sym : m }
val.set_collection! items
end
end
# if is_enum_type
#
# end
# now set the instance value
instance_variable_set ivar, val
end
# The core methods above support all attributes with the base local :key parameter
# however, for ease of use and to handle that the incoming fields from parse have different
# names, we will alias all those methods defined above with the defined parse_field.
# if both the local name matches the calculated/provided remote column name, don't create
# an alias method since it is the same thing. Ex. attribute 'username' would probably have the
# remote column name also called 'username'.
return if parse_field == key
# we will now create the aliases, however if the method is already defined
# we warn the user unless the field is :objectId since we are in charge of that one.
# this is because it is possible they want to override. You can turn off this
# behavior by passing false to :alias
if self.method_defined?(parse_field) == false && opts[:alias]
alias_method parse_field, key
alias_method "#{parse_field}=", "#{key}="
alias_method "#{parse_field}_set_attribute!", set_attribute_method
elsif parse_field.to_sym != :objectId
warn "Alias property method #{self}##{parse_field} already defined."
end
end # property
end #ClassMethods
# returns the class level stored field map
def field_map
self.class.field_map
end
# returns the list of fields
def fields(type = nil)
self.class.fields(type)
end
# TODO: We can optimize
def attributes
{__type: :string, :className => :string}.merge!(self.class.attributes)
end
# support for setting a hash of attributes on the object with a given dirty tracking value
# if dirty_track: is set to false (default), attributes are set without dirty tracking.
def apply_attributes!(hash, dirty_track: false)
return unless hash.is_a?(Hash)
@id ||= hash["id"] || hash["objectId"] || hash[:objectId]
hash.each do |key, value|
method = "#{key}_set_attribute!".freeze
send(method, value, dirty_track) if respond_to?( method )
end
end
# applies a hash of attributes overriding any current value the object has for those
# attributes
def attributes=(hash)
return unless hash.is_a?(Hash)
# - [:id, :objectId]
# only overwrite @id if it hasn't been set.
apply_attributes!(hash, dirty_track: true)
end
# returns a hash of attributes (and their new values) that had been changed.
# This will not include any of the base attributes (ex. id, created_at, etc)
# If true is passed as an argument, then all attributes will be included.
# This method is useful for generating an update hash for the Parse PUT API
# TODO: Replace this algorithm with reduce()
def attribute_updates(include_all = false)
h = {}
changed.each do |key|
key = key.to_sym
next if include_all == false && Parse::Properties::BASE_KEYS.include?(key)
next unless fields[key].present?
remote_field = self.field_map[key] || key
h[remote_field] = send key
h[remote_field] = {__op: :Delete} if h[remote_field].nil?
# in the case that the field is a Parse object, generate a pointer
h[remote_field] = h[remote_field].pointer if h[remote_field].respond_to?(:pointer)
end
h
end
# determines if any of the attributes have changed.
def attribute_changes?
changed.any? do |key|
fields[key.to_sym].present?
end
end
def format_operation(key, val, data_type)
return val unless val.is_a?(Hash) && val["__op"].present?
op = val["__op"]
ivar = :"@#{key}"
#handles delete case otherwise 'null' shows up in column
if "Delete" == op
val = nil
elsif "Add" == op && data_type == :array
val = (instance_variable_get(ivar) || []).to_a + (val["objects"] || [])
elsif "Remove" == op && data_type == :array
val = (instance_variable_get(ivar) || []).to_a - (val["objects"] || [])
elsif "AddUnique" == op && data_type == :array
objects = (val["objects"] || []).uniq
original_items = (instance_variable_get(ivar) || []).to_a
objects.reject! { |r| original_items.include?(r) }
val = original_items + objects
elsif "Increment" == op && data_type == :integer || data_type == :integer
# for operations that increment by a certain amount, they come as a hash
val = (instance_variable_get(ivar) || 0) + (val["amount"] || 0).to_i
end
val
end
# this method takes an input value and transforms it to the proper local format
# depending on the data type that was set for a particular property key.
def format_value(key, val, data_type = nil)
# if data_type wasn't passed, then get the data_type from the fields hash
data_type ||= self.fields[key]
val = format_operation(key, val, data_type)
case data_type
when :object
val = val.with_indifferent_access if val.is_a?(Hash)
when :array
# All "array" types use a collection proxy
val = val.to_a if val.is_a?(Parse::CollectionProxy) #all objects must be in array form
val = [val] unless val.is_a?(Array) #all objects must be in array form
val.compact! #remove any nil
val = Parse::CollectionProxy.new val, delegate: self, key: key
when :geopoint
val = Parse::GeoPoint.new(val) unless val.blank?
when :file
val = Parse::File.new(val) unless val.blank?
when :bytes
val = Parse::Bytes.new(val) unless val.blank?
when :integer
if val.nil? || val.respond_to?(:to_i) == false
val = nil
else
val = val.to_i
end
when :boolean
if val.nil?
val = nil
else
val = val ? true : false
end
when :string
val = val.to_s unless val.blank?
when :float
val = val.to_f unless val.blank?
when :acl
# ACL types go through a special conversion
val = ACL.typecast(val, self)
when :date
# if it respond to parse_date, then use that as the conversion.
if val.respond_to?(:parse_date) && val.is_a?(Parse::Date) == false
val = val.parse_date
# if the value is a hash, then it may be the Parse hash format for an iso date.
elsif val.is_a?(Hash) # val.respond_to?(:iso8601)
val = Parse::Date.parse(val["iso"] || val[:iso])
elsif val.is_a?(String)
# if it's a string, try parsing the date
val = Parse::Date.parse val
#elsif val.present?
# pus "[Parse::Stack] Invalid date value '#{val}' assigned to #{self.class}##{key}, it should be a Parse::Date or DateTime."
# raise ValueError, "Invalid date value '#{val}' assigned to #{self.class}##{key}, it should be a Parse::Date or DateTime."
end
else
# You can provide a specific class instead of a symbol format
if data_type.respond_to?(:typecast)
val = data_type.typecast(val)
else
warn "Property :#{key}: :#{data_type} has no valid data type"
val = val #default
end
end
val
end
end # Properties
end # Parse
Warning when :_prefix is not a symbol or string.
# encoding: UTF-8
# frozen_string_literal: true
require 'active_model'
require 'active_support'
require 'active_support/inflector'
require 'active_support/core_ext'
require 'active_support/core_ext/object'
require 'active_support/inflector'
require 'active_model_serializers'
require 'active_support/inflector'
require 'active_model_serializers'
require 'active_support/hash_with_indifferent_access'
require 'time'
=begin
This module provides support for handling all the different types of column data types
supported in Parse and mapping them between their remote names with their local ruby named attributes.
By default, the convention used for naming parameters is that the remote column should be in lower-first-camelcase, (ex. myField, eventAddress), except for
a few special columns like "id" and "acl".
Properties are defined when creating subclasses of Parse::Object and using the `property` class method.
By defining properties, dynamic methods are created in order to allow getters and setters to be used. We will go into detail below.
Each class will have a different copy of attribute mapping and field mappings.
=end
module Parse
module Properties
# This is an exception that is thrown if there is an issue when creating a specific property for a class.
class DefinitionError < StandardError; end;
class ValueError < StandardError; end;
# These are the base types supported by Parse.
TYPES = [:id, :string, :relation, :integer, :float, :boolean, :date, :array, :file, :geopoint, :bytes, :object, :acl].freeze
# These are the base mappings of the remote field name types.
BASE = {objectId: :string, createdAt: :date, updatedAt: :date, ACL: :acl}.freeze
# The list of properties that are part of all objects
BASE_KEYS = [:id, :created_at, :updated_at].freeze
# Default hash map of local attribute name to remote column name
BASE_FIELD_MAP = {id: :objectId, created_at: :createdAt, updated_at: :updatedAt, acl: :ACL}.freeze
DELETE_OP = {"__op"=>"Delete"}.freeze
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
# The fields method returns a mapping of all local attribute names and their data type.
# if type is passed, we return only the fields that matched that data type
def fields(type = nil)
@fields ||= {id: :string, created_at: :date, updated_at: :date, acl: :acl}
if type.present?
type = type.to_sym
return @fields.select { |k,v| v == type }
end
@fields
end
# This returns the mapping of local to remote attribute names.
def field_map
@field_map ||= BASE_FIELD_MAP.dup
end
def enums
@enums ||= {}
end
# Keeps track of all the attributes supported by this class.
def attributes=(hash)
@attributes = BASE.merge(hash)
end
def attributes
@attributes ||= BASE.dup
end
def defaults_list
@defaults_list ||= []
end
# property :songs, :array
# property :my_date, :date, field: "myRemoteCOLUMNName"
# property :my_int, :integer, required: true, default: ->{ rand(10) }
# field: (literal column name in Parse)
# required: (data_type)
# default: (value or Proc)
# alias: Whether to create the remote field alias getter/setters for this attribute
# This is the class level property method to be used when declaring properties. This helps builds specific methods, formatters
# and conversion handlers for property storing and saving data for a particular parse class.
# The first parameter is the name of the local attribute you want to declare with its corresponding data type.
# Declaring a `property :my_date, :date`, would declare the attribute my_date with a corresponding remote column called
# "myDate" (lower-first-camelcase) with a Parse data type of Date.
# You can override the implicit naming behavior by passing the option :field to override.
# symbolize: Makes sure the saved and return value locally is in symbol format. useful
# for enum type fields that are string columns in Parse. Ex. a booking_status for a field
# could be either "submitted" or "completed" in Parse, however with symbolize, these would
# be available as :submitted or :completed.
def property(key, data_type = :string, **opts)
key = key.to_sym
ivar = :"@#{key}"
will_change_method = :"#{key}_will_change!"
set_attribute_method = :"#{key}_set_attribute!"
if data_type.is_a?(Hash)
opts.merge!(data_type)
data_type = :string
end
# allow :bool for :boolean
data_type = :boolean if data_type == :bool
data_type = :integer if data_type == :int
# set defaults
opts = { required: false,
alias: true,
symbolize: false,
enum: nil,
scopes: true,
_prefix: nil,
_suffix: false,
field: key.to_s.camelize(:lower)
}.merge( opts )
#By default, the remote field name is a lower-first-camelcase version of the key
# it can be overriden by the :field parameter
parse_field = opts[:field].to_sym
if self.fields[key].present? && BASE_FIELD_MAP[key].nil?
raise DefinitionError, "Property #{self}##{key} already defined with data type #{data_type}"
end
# We keep the list of fields that are on the remote Parse store
if self.fields[parse_field].present?
raise DefinitionError, "Alias property #{self}##{parse_field} conflicts with previously defined property."
end
#dirty tracking. It is declared to use with ActiveModel DirtyTracking
define_attribute_methods key
# this hash keeps list of attributes (based on remote fields) and their data types
self.attributes.merge!( parse_field => data_type )
# this maps all the possible attribute fields and their data types. We use both local
# keys and remote keys because when we receive a remote object that has the remote field name
# we need to know what the data type conversion should be.
self.fields.merge!( key => data_type, parse_field => data_type )
# This creates a mapping between the local field and the remote field name.
self.field_map.merge!( key => parse_field )
#puts "Current Self: #{self} - #{key} = #{self.attributes}"
# if the field is marked as required, then add validations
if opts[:required]
# if integer or float, validate that it's a number
if data_type == :integer || data_type == :float
validates_numericality_of key
end
# validate that it is not empty
validates_presence_of key
end
is_enum_type = opts[:enum].nil? == false
if is_enum_type
unless data_type == :string
raise DefinitionError, "Property #{self}##{parse_field} :enum option is only supported on :string data types."
end
enum_values = opts[:enum]
unless enum_values.is_a?(Array) && enum_values.empty? == false
raise DefinitionError, "Property #{self}##{parse_field} :enum option must be an Array type of symbols."
end
opts[:symbolize] = true
enum_values = enum_values.dup.map(&:to_sym).freeze
self.enums.merge!( key => enum_values )
validates key, inclusion: { in: enum_values }, allow_nil: opts[:required]
unless opts[:scopes] == false
# You can use the :_prefix or :_suffix options when you need to define multiple enums with same values.
# If the passed value is true, the methods are prefixed/suffixed with the name of the enum. It is also possible to supply a custom value:
prefix = opts[:_prefix]
unless prefix.is_a?(Symbol) || prefix.is_a?(String)
raise DefinitionError, "Enumeration option :_prefix must either be a symbol or string."
end
add_suffix = opts[:_suffix] == true
prefix_or_key = (prefix.blank? ? key : prefix).to_sym
class_method_name = prefix_or_key.to_s.pluralize.to_sym
if singleton_class.method_defined?(class_method_name)
raise DefinitionError, "You tried to define an enum named `#{key}` for #{self} " + \
"but this will generate a method `#{self}.#{class_method_name}` " + \
" which is already defined. Try using :_suffix or :_prefix options."
end
define_singleton_method(class_method_name) { enum_values }
method_name = add_suffix ? :"valid_#{prefix_or_key}?" : :"#{prefix_or_key}_valid?"
define_method(method_name) { enum_values.include?(instance_variable_get(ivar).to_s.to_sym) }
enum_values.each do |enum|
method_name = enum # default
scope_name = enum
if add_suffix
method_name = :"#{enum}_#{prefix_or_key}"
elsif prefix.present?
method_name = :"#{prefix}_#{enum}"
end
self.scope method_name, ->(ex = {}){ ex.merge!(key => enum); query( ex ) }
define_method("#{method_name}!") { instance_variable_set(ivar, enum) }
define_method("#{method_name}?") { enum == instance_variable_get(ivar).to_s.to_sym }
end
end # unless scopes
end
symbolize_value = opts[:symbolize]
#only support symbolization of string data types
if symbolize_value && (data_type == :string || data_type == :array) == false
raise DefinitionError, 'Symbolization is only supported on :string or :array data types.'
end
# Here is the where the 'magic' begins. For each property defined, we will
# generate special setters and getters that will take advantage of ActiveModel
# helpers.
# get the default value if provided (or Proc)
default_value = opts[:default]
unless default_value.nil?
defaults_list.push(key) unless default_value.nil?
define_method("#{key}_default") do
# If the default object provided is a Proc, then run the proc, otherwise
# we'll assume it's just a plain literal value
default_value.is_a?(Proc) ? default_value.call(self) : default_value
end
end
# We define a getter with the key
define_method(key) do
# we will get the value using the internal value of the instance variable
# using the instance_variable_get
value = instance_variable_get ivar
# If the value is nil and this current Parse::Object instance is a pointer?
# then someone is calling the getter for this, which means they probably want
# its value - so let's go turn this pointer into a full object record
if value.nil? && pointer?
# call autofetch to fetch the entire record
# and then get the ivar again cause it might have been updated.
autofetch!(key)
value = instance_variable_get ivar
end
# if value is nil (even after fetching), then lets see if the developer
# set a default value for this attribute.
if value.nil? && respond_to?("#{key}_default")
value = send("#{key}_default")
value = format_value(key, value, data_type)
# lets set the variable with the updated value
instance_variable_set ivar, value
send will_change_method
end
# if the value is a String (like an iso8601 date) and the data type of
# this object is :date, then let's be nice and create a parse date for it.
if value.is_a?(String) && data_type == :date
value = format_value(key, value, data_type)
instance_variable_set ivar, value
send will_change_method
end
# finally return the value
if symbolize_value
if data_type == :string
return value.respond_to?(:to_sym) ? value.to_sym : value
elsif data_type == :array && value.is_a?(Array)
# value.map(&:to_sym)
return value.compact.map { |m| m.respond_to?(:to_sym) ? m.to_sym : m }
end
end
value
end
# support question mark methods for boolean
if data_type == :boolean
if self.method_defined?("#{key}?")
puts "Creating boolean helper :#{key}?. Will overwrite existing method #{self}##{key}?."
end
# returns true if set to true, false otherwise
define_method("#{key}?") { (send(key) == true) }
unless opts[:scopes] == false
scope key, ->(opts = {}){ query( opts.merge(key => true) ) }
end
end
# The second method to be defined is a setter method. This is done by
# defining :key with a '=' sign. However, to support setting the attribute
# with and without dirty tracking, we really will just proxy it to another method
define_method("#{key}=") do |val|
#we proxy the method passing the value and true. Passing true to the
# method tells it to make sure dirty tracking is enabled.
self.send set_attribute_method, val, true
end
# This is the real setter method. Takes two arguments, the value to set
# and whether to mark it as dirty tracked.
define_method(set_attribute_method) do |val, track = true|
# Each value has a data type, based on that we can treat the incoming
# value as input, and format it to the correct storage format. This method is
# defined in this file (instance method)
val = format_value(key, val, data_type)
# if dirty trackin is enabled, call the ActiveModel required method of _will_change!
# this will grab the current value and keep a copy of it - but we only do this if
# the new value being set is different from the current value stored.
if track == true
send will_change_method unless val == instance_variable_get( ivar )
end
if symbolize_value
if data_type == :string
val = nil if val.blank?
val = val.to_sym if val.respond_to?(:to_sym)
elsif val.is_a?(Parse::CollectionProxy)
items = val.collection.map { |m| m.respond_to?(:to_sym) ? m.to_sym : m }
val.set_collection! items
end
end
# if is_enum_type
#
# end
# now set the instance value
instance_variable_set ivar, val
end
# The core methods above support all attributes with the base local :key parameter
# however, for ease of use and to handle that the incoming fields from parse have different
# names, we will alias all those methods defined above with the defined parse_field.
# if both the local name matches the calculated/provided remote column name, don't create
# an alias method since it is the same thing. Ex. attribute 'username' would probably have the
# remote column name also called 'username'.
return if parse_field == key
# we will now create the aliases, however if the method is already defined
# we warn the user unless the field is :objectId since we are in charge of that one.
# this is because it is possible they want to override. You can turn off this
# behavior by passing false to :alias
if self.method_defined?(parse_field) == false && opts[:alias]
alias_method parse_field, key
alias_method "#{parse_field}=", "#{key}="
alias_method "#{parse_field}_set_attribute!", set_attribute_method
elsif parse_field.to_sym != :objectId
warn "Alias property method #{self}##{parse_field} already defined."
end
end # property
end #ClassMethods
# returns the class level stored field map
def field_map
self.class.field_map
end
# returns the list of fields
def fields(type = nil)
self.class.fields(type)
end
# TODO: We can optimize
def attributes
{__type: :string, :className => :string}.merge!(self.class.attributes)
end
# support for setting a hash of attributes on the object with a given dirty tracking value
# if dirty_track: is set to false (default), attributes are set without dirty tracking.
def apply_attributes!(hash, dirty_track: false)
return unless hash.is_a?(Hash)
@id ||= hash["id"] || hash["objectId"] || hash[:objectId]
hash.each do |key, value|
method = "#{key}_set_attribute!".freeze
send(method, value, dirty_track) if respond_to?( method )
end
end
# applies a hash of attributes overriding any current value the object has for those
# attributes
def attributes=(hash)
return unless hash.is_a?(Hash)
# - [:id, :objectId]
# only overwrite @id if it hasn't been set.
apply_attributes!(hash, dirty_track: true)
end
# returns a hash of attributes (and their new values) that had been changed.
# This will not include any of the base attributes (ex. id, created_at, etc)
# If true is passed as an argument, then all attributes will be included.
# This method is useful for generating an update hash for the Parse PUT API
# TODO: Replace this algorithm with reduce()
def attribute_updates(include_all = false)
h = {}
changed.each do |key|
key = key.to_sym
next if include_all == false && Parse::Properties::BASE_KEYS.include?(key)
next unless fields[key].present?
remote_field = self.field_map[key] || key
h[remote_field] = send key
h[remote_field] = {__op: :Delete} if h[remote_field].nil?
# in the case that the field is a Parse object, generate a pointer
h[remote_field] = h[remote_field].pointer if h[remote_field].respond_to?(:pointer)
end
h
end
# determines if any of the attributes have changed.
def attribute_changes?
changed.any? do |key|
fields[key.to_sym].present?
end
end
def format_operation(key, val, data_type)
return val unless val.is_a?(Hash) && val["__op"].present?
op = val["__op"]
ivar = :"@#{key}"
#handles delete case otherwise 'null' shows up in column
if "Delete" == op
val = nil
elsif "Add" == op && data_type == :array
val = (instance_variable_get(ivar) || []).to_a + (val["objects"] || [])
elsif "Remove" == op && data_type == :array
val = (instance_variable_get(ivar) || []).to_a - (val["objects"] || [])
elsif "AddUnique" == op && data_type == :array
objects = (val["objects"] || []).uniq
original_items = (instance_variable_get(ivar) || []).to_a
objects.reject! { |r| original_items.include?(r) }
val = original_items + objects
elsif "Increment" == op && data_type == :integer || data_type == :integer
# for operations that increment by a certain amount, they come as a hash
val = (instance_variable_get(ivar) || 0) + (val["amount"] || 0).to_i
end
val
end
# this method takes an input value and transforms it to the proper local format
# depending on the data type that was set for a particular property key.
def format_value(key, val, data_type = nil)
# if data_type wasn't passed, then get the data_type from the fields hash
data_type ||= self.fields[key]
val = format_operation(key, val, data_type)
case data_type
when :object
val = val.with_indifferent_access if val.is_a?(Hash)
when :array
# All "array" types use a collection proxy
val = val.to_a if val.is_a?(Parse::CollectionProxy) #all objects must be in array form
val = [val] unless val.is_a?(Array) #all objects must be in array form
val.compact! #remove any nil
val = Parse::CollectionProxy.new val, delegate: self, key: key
when :geopoint
val = Parse::GeoPoint.new(val) unless val.blank?
when :file
val = Parse::File.new(val) unless val.blank?
when :bytes
val = Parse::Bytes.new(val) unless val.blank?
when :integer
if val.nil? || val.respond_to?(:to_i) == false
val = nil
else
val = val.to_i
end
when :boolean
if val.nil?
val = nil
else
val = val ? true : false
end
when :string
val = val.to_s unless val.blank?
when :float
val = val.to_f unless val.blank?
when :acl
# ACL types go through a special conversion
val = ACL.typecast(val, self)
when :date
# if it respond to parse_date, then use that as the conversion.
if val.respond_to?(:parse_date) && val.is_a?(Parse::Date) == false
val = val.parse_date
# if the value is a hash, then it may be the Parse hash format for an iso date.
elsif val.is_a?(Hash) # val.respond_to?(:iso8601)
val = Parse::Date.parse(val["iso"] || val[:iso])
elsif val.is_a?(String)
# if it's a string, try parsing the date
val = Parse::Date.parse val
#elsif val.present?
# pus "[Parse::Stack] Invalid date value '#{val}' assigned to #{self.class}##{key}, it should be a Parse::Date or DateTime."
# raise ValueError, "Invalid date value '#{val}' assigned to #{self.class}##{key}, it should be a Parse::Date or DateTime."
end
else
# You can provide a specific class instead of a symbol format
if data_type.respond_to?(:typecast)
val = data_type.typecast(val)
else
warn "Property :#{key}: :#{data_type} has no valid data type"
val = val #default
end
end
val
end
end # Properties
end # Parse
|
require 'timeout'
class PassengerStatusAggregator
attr_accessor :stats
def initialize(options)
@stats = {
:max => 0,
:booted => 0,
:active => 0,
:inactive => 0,
:queued => 0,
}
@ssh_command = options[:ssh_command]
@app_hostnames = options[:app_hostnames]
@passenger_status_command = options[:passenger_status_command]
run
end
def percent_capacity
if @stats[:max] > 0
@stats[:active] / @stats[:max] * 100
else
0
end
end
private
def app_hostnames
YAML.load_file("config/newrelic_plugin.yml")["agents"]["passenger_stats"]["app_hostnames"]
end
def run
app_hostnames.each do |hostname|
collect_stats(hostname)
end
end
def collect_stats(hostname)
begin
Timeout::timeout(10) do
output = `#{@ssh_command} #{hostname} '#{@passenger_status_command}'`
parse_output(output)
end
rescue StandardError
# continue on if we get an error
end
end
# Example output from passenger-status:
# ----------- General information -----------
# max = 8
# count = 6
# active = 4
# inactive = 2
# Waiting on global queue: 5
def parse_output(output)
@stats[:max] += output.match(/max\s+=\s+(\d+)/)[1].to_i
@stats[:booted] += output.match(/count\s+=\s+(\d+)/)[1].to_i
@stats[:active] += output.match(/active\s+=\s+(\d+)/)[1].to_i
@stats[:inactive] += output.match(/inactive\s+=\s+(\d+)/)[1].to_i
@stats[:queued] += output.match(/Waiting on global queue:\s+(\d+)/)[1].to_i
end
end
convert to float
require 'timeout'
class PassengerStatusAggregator
attr_accessor :stats
def initialize(options)
@stats = {
:max => 0,
:booted => 0,
:active => 0,
:inactive => 0,
:queued => 0,
}
@ssh_command = options[:ssh_command]
@app_hostnames = options[:app_hostnames]
@passenger_status_command = options[:passenger_status_command]
run
end
def percent_capacity
if @stats[:max] > 0
@stats[:active].to_f / @stats[:max].to_f * 100
else
0
end
end
private
def app_hostnames
YAML.load_file("config/newrelic_plugin.yml")["agents"]["passenger_stats"]["app_hostnames"]
end
def run
app_hostnames.each do |hostname|
collect_stats(hostname)
end
end
def collect_stats(hostname)
begin
Timeout::timeout(10) do
output = `#{@ssh_command} #{hostname} '#{@passenger_status_command}'`
parse_output(output)
end
rescue StandardError
# continue on if we get an error
end
end
# Example output from passenger-status:
# ----------- General information -----------
# max = 8
# count = 6
# active = 4
# inactive = 2
# Waiting on global queue: 5
def parse_output(output)
@stats[:max] += output.match(/max\s+=\s+(\d+)/)[1].to_i
@stats[:booted] += output.match(/count\s+=\s+(\d+)/)[1].to_i
@stats[:active] += output.match(/active\s+=\s+(\d+)/)[1].to_i
@stats[:inactive] += output.match(/inactive\s+=\s+(\d+)/)[1].to_i
@stats[:queued] += output.match(/Waiting on global queue:\s+(\d+)/)[1].to_i
end
end |
require 'cgi'
module ScalaJenkinsInfra
module JobBlurbs
# works both for
def stdRefSpec
# can't use "+refs/pull/${_scabot_pr}/head:refs/remotes/${repo_user}/pr/${_scabot_pr}/head " because _scabot_pr isn't always set, and don't know how to default it to *
"+refs/heads/*:refs/remotes/${repo_user}/* +refs/pull/*/head:refs/remotes/${repo_user}/pr/*/head"
end
def properties(repoUser, repoName, repoRef, params)
stringPar =
"""
<hudson.model.StringParameterDefinition>
<name>%{name}</name>
<description>%{desc}</description>
<defaultValue>%{default}</defaultValue>
</hudson.model.StringParameterDefinition>""".gsub(/ /, '')
paramDefaults = {:default => nil}
"""<properties>
<com.tikal.hudson.plugins.notification.HudsonNotificationProperty plugin=\"notification@1.7\">
<endpoints>
<com.tikal.hudson.plugins.notification.Endpoint>
<protocol>HTTP</protocol>
<format>JSON</format>
<url>#{node['master']['jenkins']['notifyUrl']}</url>
<event>all</event>
<timeout>30000</timeout>
</com.tikal.hudson.plugins.notification.Endpoint>
</endpoints>
</com.tikal.hudson.plugins.notification.HudsonNotificationProperty>
<hudson.model.ParametersDefinitionProperty>
<parameterDefinitions>
#{scmParams(repoUser, repoName, repoRef)}
#{params.map { |param| stringPar % paramDefaults.merge(param) }.join("\n")}
</parameterDefinitions>
</hudson.model.ParametersDefinitionProperty>
</properties>"""
end
def flowProject(options = {})
# chef's still stuck on ruby 1.9 (on our amazon linux)
repoUser = options[:repoUser]
repoName = options.fetch(:repoName, nil)
repoRef = options[:repoRef]
dsl = options[:dsl]
description = options.fetch(:description, '')
params = options.fetch(:params, [])
concurrent = options.fetch(:concurrent, true)
buildNameScript = options.fetch(:buildNameScript, setBuildNameScript)
<<-EOX
<description>#{CGI.escapeHTML(description)}</description>
#{properties(repoUser, repoName, repoRef, params)}
<scm class="hudson.scm.NullSCM"/>
<canRoam>true</canRoam>
<concurrentBuild>#{concurrent}</concurrentBuild>
<dsl>#{CGI.escapeHTML(buildNameScript+"\n\n"+dsl)}</dsl>
EOX
end
def githubProject(options = {})
# chef's still stuck on ruby 1.9 (on our amazon linux)
repoUser = options[:repoUser]
repoName = options.fetch(:repoName, nil)
repoRef = options[:repoRef]
description = options.fetch(:description, '')
nodeRestriction = options.fetch(:nodeRestriction, nil)
params = options.fetch(:params, [])
refspec = options.fetch(:refspec, stdRefSpec)
concurrent = options.fetch(:concurrent, true)
timeoutMinutesElasticDefault = options.fetch(:timeoutMinutesElasticDefault, 150)
buildNameScript = options.fetch(:buildNameScript, setBuildNameScript)
jvmFlavor = options[:jvmFlavor]
jvmVersion = options[:jvmVersion]
jvmSelectScript = ""
if jvmFlavor && jvmVersion
params.concat([
{:name => "jvmFlavor", :default => jvmFlavor, :desc => "Java flavor to use (oracle/openjdk)."},
{:name => "jvmVersion", :default => jvmVersion, :desc => "Java version to use (6/7/8)."}
])
jvmSelectScript=jvmSelect
end
restriction =
"""<assignedNode>%{nodes}</assignedNode>
<canRoam>false</canRoam>""".gsub(/ /, '')
def env(name)
"${ENV,var="#{name}"}"
end
<<-EOX
<description>#{CGI.escapeHTML(description)}</description>
#{properties(repoUser, repoName, repoRef, params)}
#{scmBlurb(refspec)}
#{restriction % {nodes: CGI.escapeHTML(nodeRestriction)} if nodeRestriction}
<concurrentBuild>#{concurrent}</concurrentBuild>
<builders>
#{groovySysScript(buildNameScript)}
#{jvmSelectScript}
#{scriptBuild}
</builders>
<buildWrappers>
<hudson.plugins.build__timeout.BuildTimeoutWrapper plugin="build-timeout@1.14.1">
<strategy class="hudson.plugins.build_timeout.impl.ElasticTimeOutStrategy">
<timeoutPercentage>300</timeoutPercentage>
<numberOfBuilds>100</numberOfBuilds>
<timeoutMinutesElasticDefault>#{timeoutMinutesElasticDefault}</timeoutMinutesElasticDefault>
</strategy>
<operationList/>
</hudson.plugins.build__timeout.BuildTimeoutWrapper>
</buildWrappers>
EOX
end
def scmBlurb(refspec)
<<-EOH.gsub(/^ {8}/, '')
<scm class="hudson.plugins.git.GitSCM" plugin="git@2.2.1">
<configVersion>2</configVersion>
<userRemoteConfigs>
<hudson.plugins.git.UserRemoteConfig>
<name>${repo_user}</name>
<refspec>#{refspec}</refspec>
<url>https://github.com/${repo_user}/${repo_name}.git</url>
</hudson.plugins.git.UserRemoteConfig>
</userRemoteConfigs>
<branches>
<hudson.plugins.git.BranchSpec>
<name>${repo_ref}</name>
</hudson.plugins.git.BranchSpec>
</branches>
<doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
<submoduleCfg class="list"/>
<extensions>
<hudson.plugins.git.extensions.impl.CleanCheckout/>
</extensions>
</scm>
EOH
end
def versionedJob(version, name)
"scala-#{version}-#{name.gsub(/\//, '-')}"
end
def job(name)
versionedJob(@version, name)
end
def jvmSelect
<<-EOH.gsub(/^ /, '')
<hudson.tasks.Shell>
<command>#!/bin/bash -e
source /usr/local/share/jvm/jvm-select
jvmSelect $jvmFlavor $jvmVersion
</command>
</hudson.tasks.Shell>
EOH
end
def scriptBuild
<<-EOH.gsub(/^ /, '')
<hudson.tasks.Shell>
<command>#!/bin/bash -ex
source scripts/#{@scriptName}
</command>
</hudson.tasks.Shell>
EOH
end
def setBuildNameScript
<<-EOH.gsub(/^ /, '')
repo_user = build.buildVariableResolver.resolve("repo_user")
repo_name = build.buildVariableResolver.resolve("repo_name")
repo_ref = build.buildVariableResolver.resolve("repo_ref").take(12)
build.setDisplayName("[${build.number}] $repo_user/$repo_name\#$repo_ref")
EOH
end
def setValidateBuildNameScript
<<-EOH.gsub(/^ /, '')
repo_user = build.buildVariableResolver.resolve("repo_user")
repo_name = build.buildVariableResolver.resolve("repo_name")
repo_ref = build.buildVariableResolver.resolve("repo_ref").take(6)
_scabot_pr = build.buildVariableResolver.resolve("_scabot_pr")
build.setDisplayName("[${build.number}] $repo_user/$repo_name\#$_scabot_pr at $repo_ref")
EOH
end
def setReleaseBuildNameScript
<<-EOH.gsub(/^ /, '')
repo_user = build.buildVariableResolver.resolve("repo_user")
repo_name = build.buildVariableResolver.resolve("repo_name")
repo_ref = build.buildVariableResolver.resolve("repo_ref").take(12)
ver = params["SCALA_VER_BASE"] + params["SCALA_VER_SUFFIX"]
build.setDisplayName("[${build.number}] Scala dist ${ver} $repo_user/$repo_name\#$repo_ref")
EOH
end
def groovySysScript(script)
<<-EOH.gsub(/^ /, '')
<hudson.plugins.groovy.SystemGroovy plugin="groovy">
<scriptSource class="hudson.plugins.groovy.StringScriptSource">
<command>#{CGI.escapeHTML(script)}</command>
</scriptSource>
</hudson.plugins.groovy.SystemGroovy>
EOH
end
def scmUserParam(user)
<<-EOH.gsub(/^ {8}/, '')
<hudson.model.StringParameterDefinition>
<name>repo_user</name>
<description>The github username for the repo to clone.</description>
<defaultValue>#{user}</defaultValue>
</hudson.model.StringParameterDefinition>
EOH
end
def scmNameParam(name)
name == nil ? '' : <<-EOH.gsub(/^ {8}/, '')
<hudson.model.StringParameterDefinition>
<name>repo_name</name>
<description>The name of the repo to clone.</description>
<defaultValue>#{name}</defaultValue>
</hudson.model.StringParameterDefinition>
EOH
end
def scmRefParam(ref)
<<-EOH.gsub(/^ {8}/, '')
<hudson.model.StringParameterDefinition>
<name>repo_ref</name>
<description>The git ref at ${repo_user}/${repo_name} to build.</description>
<defaultValue>#{ref}</defaultValue>
</hudson.model.StringParameterDefinition>
EOH
end
def scmParams(user, name, ref)
scmUserParam(user) + scmNameParam(name) + scmRefParam(ref)
end
end
end
Rework #19, fix #4: set JAVA_HOME during scriptBuild
require 'cgi'
module ScalaJenkinsInfra
module JobBlurbs
# works both for
def stdRefSpec
# can't use "+refs/pull/${_scabot_pr}/head:refs/remotes/${repo_user}/pr/${_scabot_pr}/head " because _scabot_pr isn't always set, and don't know how to default it to *
"+refs/heads/*:refs/remotes/${repo_user}/* +refs/pull/*/head:refs/remotes/${repo_user}/pr/*/head"
end
def properties(repoUser, repoName, repoRef, params)
stringPar =
"""
<hudson.model.StringParameterDefinition>
<name>%{name}</name>
<description>%{desc}</description>
<defaultValue>%{default}</defaultValue>
</hudson.model.StringParameterDefinition>""".gsub(/ /, '')
paramDefaults = {:default => nil}
"""<properties>
<com.tikal.hudson.plugins.notification.HudsonNotificationProperty plugin=\"notification@1.7\">
<endpoints>
<com.tikal.hudson.plugins.notification.Endpoint>
<protocol>HTTP</protocol>
<format>JSON</format>
<url>#{node['master']['jenkins']['notifyUrl']}</url>
<event>all</event>
<timeout>30000</timeout>
</com.tikal.hudson.plugins.notification.Endpoint>
</endpoints>
</com.tikal.hudson.plugins.notification.HudsonNotificationProperty>
<hudson.model.ParametersDefinitionProperty>
<parameterDefinitions>
#{scmParams(repoUser, repoName, repoRef)}
#{params.map { |param| stringPar % paramDefaults.merge(param) }.join("\n")}
</parameterDefinitions>
</hudson.model.ParametersDefinitionProperty>
</properties>"""
end
def flowProject(options = {})
# chef's still stuck on ruby 1.9 (on our amazon linux)
repoUser = options[:repoUser]
repoName = options.fetch(:repoName, nil)
repoRef = options[:repoRef]
dsl = options[:dsl]
description = options.fetch(:description, '')
params = options.fetch(:params, [])
concurrent = options.fetch(:concurrent, true)
buildNameScript = options.fetch(:buildNameScript, setBuildNameScript)
<<-EOX
<description>#{CGI.escapeHTML(description)}</description>
#{properties(repoUser, repoName, repoRef, params)}
<scm class="hudson.scm.NullSCM"/>
<canRoam>true</canRoam>
<concurrentBuild>#{concurrent}</concurrentBuild>
<dsl>#{CGI.escapeHTML(buildNameScript+"\n\n"+dsl)}</dsl>
EOX
end
def githubProject(options = {})
# chef's still stuck on ruby 1.9 (on our amazon linux)
repoUser = options[:repoUser]
repoName = options.fetch(:repoName, nil)
repoRef = options[:repoRef]
description = options.fetch(:description, '')
nodeRestriction = options.fetch(:nodeRestriction, nil)
params = options.fetch(:params, [])
refspec = options.fetch(:refspec, stdRefSpec)
concurrent = options.fetch(:concurrent, true)
timeoutMinutesElasticDefault = options.fetch(:timeoutMinutesElasticDefault, 150)
buildNameScript = options.fetch(:buildNameScript, setBuildNameScript)
jvmFlavor = options[:jvmFlavor]
jvmVersion = options[:jvmVersion]
jvmSelectScript = ""
if jvmFlavor && jvmVersion
params.concat([
{:name => "jvmFlavor", :default => jvmFlavor, :desc => "Java flavor to use (oracle/openjdk)."},
{:name => "jvmVersion", :default => jvmVersion, :desc => "Java version to use (6/7/8)."}
])
jvmSelectScript=jvmSelect
end
restriction =
"""<assignedNode>%{nodes}</assignedNode>
<canRoam>false</canRoam>""".gsub(/ /, '')
def env(name)
"${ENV,var="#{name}"}"
end
<<-EOX
<description>#{CGI.escapeHTML(description)}</description>
#{properties(repoUser, repoName, repoRef, params)}
#{scmBlurb(refspec)}
#{restriction % {nodes: CGI.escapeHTML(nodeRestriction)} if nodeRestriction}
<concurrentBuild>#{concurrent}</concurrentBuild>
<builders>
#{groovySysScript(buildNameScript)}
#{scriptBuild(jvmSelectScript)}
</builders>
<buildWrappers>
<hudson.plugins.build__timeout.BuildTimeoutWrapper plugin="build-timeout@1.14.1">
<strategy class="hudson.plugins.build_timeout.impl.ElasticTimeOutStrategy">
<timeoutPercentage>300</timeoutPercentage>
<numberOfBuilds>100</numberOfBuilds>
<timeoutMinutesElasticDefault>#{timeoutMinutesElasticDefault}</timeoutMinutesElasticDefault>
</strategy>
<operationList/>
</hudson.plugins.build__timeout.BuildTimeoutWrapper>
</buildWrappers>
EOX
end
def scmBlurb(refspec)
<<-EOH.gsub(/^ {8}/, '')
<scm class="hudson.plugins.git.GitSCM" plugin="git@2.2.1">
<configVersion>2</configVersion>
<userRemoteConfigs>
<hudson.plugins.git.UserRemoteConfig>
<name>${repo_user}</name>
<refspec>#{refspec}</refspec>
<url>https://github.com/${repo_user}/${repo_name}.git</url>
</hudson.plugins.git.UserRemoteConfig>
</userRemoteConfigs>
<branches>
<hudson.plugins.git.BranchSpec>
<name>${repo_ref}</name>
</hudson.plugins.git.BranchSpec>
</branches>
<doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
<submoduleCfg class="list"/>
<extensions>
<hudson.plugins.git.extensions.impl.CleanCheckout/>
</extensions>
</scm>
EOH
end
def versionedJob(version, name)
"scala-#{version}-#{name.gsub(/\//, '-')}"
end
def job(name)
versionedJob(@version, name)
end
def jvmSelect
<<-EOH.gsub(/^ /, '')
source /usr/local/share/jvm/jvm-select
jvmSelect $jvmFlavor $jvmVersion
EOH
end
def scriptBuild(setup)
<<-EOH.gsub(/^ /, '')
<hudson.tasks.Shell>
<command>#!/bin/bash -ex
#{setup}
source scripts/#{@scriptName}
</command>
</hudson.tasks.Shell>
EOH
end
def setBuildNameScript
<<-EOH.gsub(/^ /, '')
repo_user = build.buildVariableResolver.resolve("repo_user")
repo_name = build.buildVariableResolver.resolve("repo_name")
repo_ref = build.buildVariableResolver.resolve("repo_ref").take(12)
build.setDisplayName("[${build.number}] $repo_user/$repo_name\#$repo_ref")
EOH
end
def setValidateBuildNameScript
<<-EOH.gsub(/^ /, '')
repo_user = build.buildVariableResolver.resolve("repo_user")
repo_name = build.buildVariableResolver.resolve("repo_name")
repo_ref = build.buildVariableResolver.resolve("repo_ref").take(6)
_scabot_pr = build.buildVariableResolver.resolve("_scabot_pr")
build.setDisplayName("[${build.number}] $repo_user/$repo_name\#$_scabot_pr at $repo_ref")
EOH
end
def setReleaseBuildNameScript
<<-EOH.gsub(/^ /, '')
repo_user = build.buildVariableResolver.resolve("repo_user")
repo_name = build.buildVariableResolver.resolve("repo_name")
repo_ref = build.buildVariableResolver.resolve("repo_ref").take(12)
ver = params["SCALA_VER_BASE"] + params["SCALA_VER_SUFFIX"]
build.setDisplayName("[${build.number}] Scala dist ${ver} $repo_user/$repo_name\#$repo_ref")
EOH
end
def groovySysScript(script)
<<-EOH.gsub(/^ /, '')
<hudson.plugins.groovy.SystemGroovy plugin="groovy">
<scriptSource class="hudson.plugins.groovy.StringScriptSource">
<command>#{CGI.escapeHTML(script)}</command>
</scriptSource>
</hudson.plugins.groovy.SystemGroovy>
EOH
end
def scmUserParam(user)
<<-EOH.gsub(/^ {8}/, '')
<hudson.model.StringParameterDefinition>
<name>repo_user</name>
<description>The github username for the repo to clone.</description>
<defaultValue>#{user}</defaultValue>
</hudson.model.StringParameterDefinition>
EOH
end
def scmNameParam(name)
name == nil ? '' : <<-EOH.gsub(/^ {8}/, '')
<hudson.model.StringParameterDefinition>
<name>repo_name</name>
<description>The name of the repo to clone.</description>
<defaultValue>#{name}</defaultValue>
</hudson.model.StringParameterDefinition>
EOH
end
def scmRefParam(ref)
<<-EOH.gsub(/^ {8}/, '')
<hudson.model.StringParameterDefinition>
<name>repo_ref</name>
<description>The git ref at ${repo_user}/${repo_name} to build.</description>
<defaultValue>#{ref}</defaultValue>
</hudson.model.StringParameterDefinition>
EOH
end
def scmParams(user, name, ref)
scmUserParam(user) + scmNameParam(name) + scmRefParam(ref)
end
end
end
|
#
# Author:: Sander Botman <sbotman@schubergphilis.com>
# Cookbook Name:: nagios
# Library:: timeperiod
#
# Copyright 2014, Sander Botman
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require_relative 'base'
class Nagios
#
# This class holds all methods with regard to timeperiodentries,
# that are used within the timeperiod nagios configurations.
#
class Timeperiodentry
attr_reader :moment,
:period
def initialize(moment, period)
@moment = moment
@period = check_period(period)
end
def id
moment
end
def to_s
moment
end
private
def check_period(period)
# should be HH:MM-HH:MM ([01]?[0-9]|2[0-3])\:[0-5][0-9]
return period if period =~ /^([01]?[0-9]|2[0-3])\:[0-5][0-9]-([01]?[0-9]|2[0-4])\:[0-5][0-9]$/
nil
end
end
#
# This class holds all methods with regard to timeperiod options,
# that are used within nagios configurations.
#
class Timeperiod < Nagios::Base
attr_reader :timeperiod_name
attr_accessor :alias,
:periods,
:exclude
def initialize(timeperiod_name)
@timeperiod_name = timeperiod_name
@periods = {}
@exclude = {}
end
def self.create(name)
Nagios.instance.find(Nagios::Timeperiod.new(name))
end
def definition
configured = configured_options
periods.values.each { |v| configured[v.moment] = v.period }
get_definition(configured, 'timeperiod')
end
# exclude
# This directive is used to specify the short names of other timeperiod definitions
# whose time ranges should be excluded from this timeperiod.
# Multiple timeperiod names should be separated with a comma.
def exclude
@exclude.values.map(&:id).sort.join(',')
end
def id
timeperiod_name
end
def import(hash)
update_options(hash)
if hash['times'].class == Hash
hash['times'].each { |k, v| push(Nagios::Timeperiodentry.new(k, v)) }
end
update_members(hash, 'exclude', Nagios::Timeperiod)
end
def push(obj)
case obj
when Nagios::Timeperiod
push_object(obj, @exclude)
when Nagios::Timeperiodentry
push_object(obj, @periods)
end
end
def to_s
timeperiod_name
end
# [weekday]
# The weekday directives ("sunday" through "saturday")are comma-delimited
# lists of time ranges that are "valid" times for a particular day of the week.
# Notice that there are seven different days for which you can define time
# ranges (Sunday through Saturday). Each time range is in the form of
# HH:MM-HH:MM, where hours are specified on a 24 hour clock.
# For example, 00:15-24:00 means 12:15am in the morning for this day until
# 12:00am midnight (a 23 hour, 45 minute total time range).
# If you wish to exclude an entire day from the timeperiod, simply do not include
# it in the timeperiod definition.
# [exception]
# You can specify several different types of exceptions to the standard rotating
# weekday schedule. Exceptions can take a number of different forms including single
# days of a specific or generic month, single weekdays in a month, or single calendar
# dates. You can also specify a range of days/dates and even specify skip intervals
# to obtain functionality described by "every 3 days between these dates".
# Rather than list all the possible formats for exception strings, I'll let you look
# at the example timeperiod definitions above to see what's possible.
# Weekdays and different types of exceptions all have different levels of precedence,
# so its important to understand how they can affect each other.
private
def config_options
{
'timeperiod_name' => 'timeperiod_name',
'alias' => 'alias',
'exclude' => 'exclude'
}
end
def merge_members(obj)
obj.periods.each { |m| push(m) }
obj.exclude.each { |m| push(m) }
end
end
end
ignore timeperiods that are nil and don't comply to the regex structure
#
# Author:: Sander Botman <sbotman@schubergphilis.com>
# Cookbook Name:: nagios
# Library:: timeperiod
#
# Copyright 2014, Sander Botman
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require_relative 'base'
class Nagios
#
# This class holds all methods with regard to timeperiodentries,
# that are used within the timeperiod nagios configurations.
#
class Timeperiodentry
attr_reader :moment,
:period
def initialize(moment, period)
@moment = moment
@period = check_period(period)
end
def id
moment
end
def to_s
moment
end
private
def check_period(period)
# should be HH:MM-HH:MM ([01]?[0-9]|2[0-3])\:[0-5][0-9]
return period if period =~ /^([01]?[0-9]|2[0-3])\:[0-5][0-9]-([01]?[0-9]|2[0-4])\:[0-5][0-9]$/
nil
end
end
#
# This class holds all methods with regard to timeperiod options,
# that are used within nagios configurations.
#
class Timeperiod < Nagios::Base
attr_reader :timeperiod_name
attr_accessor :alias,
:periods,
:exclude
def initialize(timeperiod_name)
@timeperiod_name = timeperiod_name
@periods = {}
@exclude = {}
end
def self.create(name)
Nagios.instance.find(Nagios::Timeperiod.new(name))
end
def definition
configured = configured_options
periods.values.each { |v| configured[v.moment] = v.period }
get_definition(configured, 'timeperiod')
end
# exclude
# This directive is used to specify the short names of other timeperiod definitions
# whose time ranges should be excluded from this timeperiod.
# Multiple timeperiod names should be separated with a comma.
def exclude
@exclude.values.map(&:id).sort.join(',')
end
def id
timeperiod_name
end
def import(hash)
update_options(hash)
if hash['times'].class == Hash
hash['times'].each { |k, v| push(Nagios::Timeperiodentry.new(k, v)) }
end
update_members(hash, 'exclude', Nagios::Timeperiod)
end
def push(obj)
case obj
when Nagios::Timeperiod
push_object(obj, @exclude)
when Nagios::Timeperiodentry
push_object(obj, @periods) unless obj.period.nil?
end
end
def to_s
timeperiod_name
end
# [weekday]
# The weekday directives ("sunday" through "saturday")are comma-delimited
# lists of time ranges that are "valid" times for a particular day of the week.
# Notice that there are seven different days for which you can define time
# ranges (Sunday through Saturday). Each time range is in the form of
# HH:MM-HH:MM, where hours are specified on a 24 hour clock.
# For example, 00:15-24:00 means 12:15am in the morning for this day until
# 12:00am midnight (a 23 hour, 45 minute total time range).
# If you wish to exclude an entire day from the timeperiod, simply do not include
# it in the timeperiod definition.
# [exception]
# You can specify several different types of exceptions to the standard rotating
# weekday schedule. Exceptions can take a number of different forms including single
# days of a specific or generic month, single weekdays in a month, or single calendar
# dates. You can also specify a range of days/dates and even specify skip intervals
# to obtain functionality described by "every 3 days between these dates".
# Rather than list all the possible formats for exception strings, I'll let you look
# at the example timeperiod definitions above to see what's possible.
# Weekdays and different types of exceptions all have different levels of precedence,
# so its important to understand how they can affect each other.
private
def config_options
{
'timeperiod_name' => 'timeperiod_name',
'alias' => 'alias',
'exclude' => 'exclude'
}
end
def merge_members(obj)
obj.periods.each { |m| push(m) }
obj.exclude.each { |m| push(m) }
end
end
end
|
# @see https://developers.podio.com/doc/calendar
class Podio::CalendarEvent < ActivePodio::Base
property :uid, :string
property :ref_type, :string
property :ref_id, :integer
property :title, :string
property :description, :string
property :location, :string
property :status, :string
property :start, :datetime, :convert_timezone => false
property :start_utc, :datetime, :convert_timezone => false
property :start_date, :date
property :start_time, :string
property :end, :datetime, :convert_timezone => false
property :end_utc, :datetime, :convert_timezone => false
property :end_date, :date
property :end_time, :string
property :link, :string
property :app, :hash
property :source, :string
alias_method :id, :uid
class << self
# @see https://developers.podio.com/doc/calendar/get-global-calendar-22458
def find_all(options = {})
list Podio.connection.get { |req|
req.url('/calendar/', options)
}.body
end
def find_all_for_linked_account(linked_account_id, options = {})
list Podio.connection.get { |req|
req.url("/calendar/linked_account/#{linked_account_id}/", options)
}.body
end
# @see https://developers.podio.com/doc/calendar/get-space-calendar-22459
def find_all_for_space(space_id, options={})
list Podio.connection.get { |req|
req.url("/calendar/space/#{space_id}/", options)
}.body
end
# @see https://developers.podio.com/doc/calendar/get-app-calendar-22460
def find_all_for_app(app_id, options={})
list Podio.connection.get { |req|
req.url("/calendar/app/#{app_id}/", options)
}.body
end
# @see
def move_event(uid, attributes={})
response = Podio.connection.post do |req|
req.url "/calendar/event/#{uid}/move"
req.body = attributes
end
response.status
end
# @see
def move_event_external(linked_account_id, uid, attributes={})
response = Podio.connection.post do |req|
req.url "/calendar/linked_account/#{linked_account_id}/event/#{uid}/move"
req.body = attributes
end
response.status
end
# @see
def update_event_duration(uid, attributes={})
response = Podio.connection.put do |req|
req.url "/calendar/event/#{uid}/duration"
req.body = attributes
end
response.status
end
# @see
def update_event_duration_external(linked_account_id, uid, attributes={})
response = Podio.connection.put do |req|
req.url "/calendar/linked_account/#{linked_account_id}/event/#{uid}/duration"
req.body = attributes
end
response.status
end
def get_calendars_for_linked_acc(acc_id, options={})
list Podio.connection.get { |req|
req.url("/calendar/export/linked_account/#{acc_id}/available", options)
}.body
end
# @see https://developers.podio.com/doc/calendar/get-calendar-summary-1609256
def find_summary(options = {})
response = Podio.connection.get do |req|
req.url("/calendar/summary", options)
end.body
response['today']['events'] = list(response['today']['events'])
response['upcoming']['events'] = list(response['upcoming']['events'])
response
end
# @see https://developers.podio.com/doc/calendar/get-calendar-summary-for-space-1609328
def find_summary_for_space(space_id)
response = Podio.connection.get("/calendar/space/#{space_id}/summary").body
response['today']['events'] = list(response['today']['events'])
response['upcoming']['events'] = list(response['upcoming']['events'])
response
end
def find_summary_for_org(org_id)
response = Podio.connection.get("/calendar/org/#{org_id}/summary").body
response['today']['events'] = list(response['today']['events'])
response['upcoming']['events'] = list(response['upcoming']['events'])
response
end
# @see https://developers.podio.com/doc/calendar/get-calendar-summary-for-personal-1657903
def find_personal_summary
response = Podio.connection.get("/calendar/personal/summary").body
response['today']['events'] = list(response['today']['events'])
response['upcoming']['events'] = list(response['upcoming']['events'])
response
end
# @see https://developers.podio.com/doc/calendar/set-reference-export-9183515
def set_reference_export(linked_account_id, ref_type, ref_id, attributes={})
response = Podio.connection.put do |req|
req.url "/calendar/export/linked_account/#{linked_account_id}/#{ref_type}/#{ref_id}"
req.body = attributes
end
response.status
end
# @see https://developers.podio.com/doc/calendar/get-exports-by-reference-7554180
def get_reference_exports(ref_type, ref_id)
list Podio.connection.get { |req|
req.url("/calendar/export/#{ref_type}/#{ref_id}/")
}.body
end
# @see https://developers.podio.com/doc/calendar/stop-reference-export-9183590
def stop_reference_export(linked_account_id, ref_type, ref_id)
Podio.connection.delete("/calendar/export/linked_account/#{linked_account_id}/#{ref_type}/#{ref_id}").status
end
# @see https://developers.podio.com/doc/calendar/get-global-export-9381099
def set_global_export(linked_account_id, attributes={})
response = Podio.connection.put do |req|
req.url "/calendar/export/linked_account/#{linked_account_id}"
req.body = attributes
end
response.status
end
# @see https://developers.podio.com/doc/calendar/get-global-exports-7554169
def get_global_exports()
list Podio.connection.get { |req|
req.url("/calendar/export/")
}.body
end
def stop_global_export(linked_account_id)
Podio.connection.delete("/calendar/export/linked_account/#{linked_account_id}").status
end
end
end
Need to escape the uid
# @see https://developers.podio.com/doc/calendar
class Podio::CalendarEvent < ActivePodio::Base
property :uid, :string
property :ref_type, :string
property :ref_id, :integer
property :title, :string
property :description, :string
property :location, :string
property :status, :string
property :start, :datetime, :convert_timezone => false
property :start_utc, :datetime, :convert_timezone => false
property :start_date, :date
property :start_time, :string
property :end, :datetime, :convert_timezone => false
property :end_utc, :datetime, :convert_timezone => false
property :end_date, :date
property :end_time, :string
property :link, :string
property :app, :hash
property :source, :string
alias_method :id, :uid
class << self
# @see https://developers.podio.com/doc/calendar/get-global-calendar-22458
def find_all(options = {})
list Podio.connection.get { |req|
req.url('/calendar/', options)
}.body
end
def find_all_for_linked_account(linked_account_id, options = {})
list Podio.connection.get { |req|
req.url("/calendar/linked_account/#{linked_account_id}/", options)
}.body
end
# @see https://developers.podio.com/doc/calendar/get-space-calendar-22459
def find_all_for_space(space_id, options={})
list Podio.connection.get { |req|
req.url("/calendar/space/#{space_id}/", options)
}.body
end
# @see https://developers.podio.com/doc/calendar/get-app-calendar-22460
def find_all_for_app(app_id, options={})
list Podio.connection.get { |req|
req.url("/calendar/app/#{app_id}/", options)
}.body
end
# @see
def move_event(uid, attributes={})
response = Podio.connection.post do |req|
req.url "/calendar/event/#{uid}/move"
req.body = attributes
end
response.status
end
# @see
def move_event_external(linked_account_id, uid, attributes={})
response = Podio.connection.post do |req|
req.url "/calendar/linked_account/#{linked_account_id}/event/#{CGI.escape(uid)}/move"
req.body = attributes
end
response.status
end
# @see
def update_event_duration(uid, attributes={})
response = Podio.connection.put do |req|
req.url "/calendar/event/#{uid}/duration"
req.body = attributes
end
response.status
end
# @see
def update_event_duration_external(linked_account_id, uid, attributes={})
response = Podio.connection.put do |req|
req.url "/calendar/linked_account/#{linked_account_id}/event/#{CGI.escape(uid)}/duration"
req.body = attributes
end
response.status
end
def get_calendars_for_linked_acc(acc_id, options={})
list Podio.connection.get { |req|
req.url("/calendar/export/linked_account/#{acc_id}/available", options)
}.body
end
# @see https://developers.podio.com/doc/calendar/get-calendar-summary-1609256
def find_summary(options = {})
response = Podio.connection.get do |req|
req.url("/calendar/summary", options)
end.body
response['today']['events'] = list(response['today']['events'])
response['upcoming']['events'] = list(response['upcoming']['events'])
response
end
# @see https://developers.podio.com/doc/calendar/get-calendar-summary-for-space-1609328
def find_summary_for_space(space_id)
response = Podio.connection.get("/calendar/space/#{space_id}/summary").body
response['today']['events'] = list(response['today']['events'])
response['upcoming']['events'] = list(response['upcoming']['events'])
response
end
def find_summary_for_org(org_id)
response = Podio.connection.get("/calendar/org/#{org_id}/summary").body
response['today']['events'] = list(response['today']['events'])
response['upcoming']['events'] = list(response['upcoming']['events'])
response
end
# @see https://developers.podio.com/doc/calendar/get-calendar-summary-for-personal-1657903
def find_personal_summary
response = Podio.connection.get("/calendar/personal/summary").body
response['today']['events'] = list(response['today']['events'])
response['upcoming']['events'] = list(response['upcoming']['events'])
response
end
# @see https://developers.podio.com/doc/calendar/set-reference-export-9183515
def set_reference_export(linked_account_id, ref_type, ref_id, attributes={})
response = Podio.connection.put do |req|
req.url "/calendar/export/linked_account/#{linked_account_id}/#{ref_type}/#{ref_id}"
req.body = attributes
end
response.status
end
# @see https://developers.podio.com/doc/calendar/get-exports-by-reference-7554180
def get_reference_exports(ref_type, ref_id)
list Podio.connection.get { |req|
req.url("/calendar/export/#{ref_type}/#{ref_id}/")
}.body
end
# @see https://developers.podio.com/doc/calendar/stop-reference-export-9183590
def stop_reference_export(linked_account_id, ref_type, ref_id)
Podio.connection.delete("/calendar/export/linked_account/#{linked_account_id}/#{ref_type}/#{ref_id}").status
end
# @see https://developers.podio.com/doc/calendar/get-global-export-9381099
def set_global_export(linked_account_id, attributes={})
response = Podio.connection.put do |req|
req.url "/calendar/export/linked_account/#{linked_account_id}"
req.body = attributes
end
response.status
end
# @see https://developers.podio.com/doc/calendar/get-global-exports-7554169
def get_global_exports()
list Podio.connection.get { |req|
req.url("/calendar/export/")
}.body
end
def stop_global_export(linked_account_id)
Podio.connection.delete("/calendar/export/linked_account/#{linked_account_id}").status
end
end
end
|
#
# Copyright 2015, Noah Kantrowitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'securerandom'
require 'chef/provider'
require 'chef/resource'
require 'poise'
require 'poise_service/service_mixin'
module PoiseMonit
module Resources
# (see Monit::Resource)
# @since 1.0.0
module Monit
UNIXSOCKET_VERSION = Gem::Requirement.create('>= 5.12')
# A `monit` resource to install and configure Monit.
#
# @provides monit
# @action enable
# @action disable
# @action start
# @action stop
# @action restart
# @action reload
# @example
# monit 'monit'
class Resource < Chef::Resource
include Poise(container: true, inversion: true)
provides(:monit)
include PoiseService::ServiceMixin
attribute(:config, template: true, default_source: 'monit.conf.erb')
attribute(:daemon_interval, kind_of: Integer, default: 120)
attribute(:event_slots, kind_of: Integer, default: 100)
attribute(:httpd_port, kind_of: [String, Integer, NilClass, FalseClass], default: lazy { default_httpd_port })
attribute(:httpd_password, kind_of: [String, NilClass, FalseClass], default: lazy { default_httpd_password })
attribute(:httpd_username, kind_of: [String, NilClass, FalseClass], default: 'cli')
attribute(:group, kind_of: [String, NilClass, FalseClass], default: nil)
attribute(:logfile, kind_of: [String, NilClass, FalseClass], default: '/var/log/monit.')
attribute(:owner, kind_of: [String, NilClass, FalseClass], default: nil)
attribute(:path, kind_of: String, default: lazy { default_path })
attribute(:pidfile, kind_of: String, default: lazy { default_pidfile })
attribute(:var_path, kind_of: String, default: lazy { default_var_path })
attribute(:version, kind_of: [String, NilClass, FalseClass], default: nil)
# @!attribute [r] Path to the conf.d/ directory.
def confd_path
::File.join(path, 'conf.d')
end
def config_path
::File.join(path, 'monitrc')
end
def password_path
::File.join(path, '.cli-password')
end
def httpd_is_unix?
httpd_port.to_s[0] == '/'
end
# The path to the `monit` binary for this Monit installation. This is
# an output property.
#
# @return [String]
# @example
# execute "#{resources('monit[monit]').monit_binary} start myapp"
def monit_binary
provider_for_action(:monit_binary).monit_binary
end
private
# Default HTTP port. Use a Unix socket if possible for security reasons.
def default_httpd_port
if monit_version && UNIXSOCKET_VERSION.satisfied_by?(monit_version)
monit_name_path('/var/run/%{name}.sock')
else
2812
end
end
# Default HTTP password for CLI authentication.
#
# @return [String]
def default_httpd_password
if httpd_is_unix?
# Unix sockets have ACLs already, don't need a password.
nil
elsif ::File.exist?(password_path)
# Strip is just to be safe in case a user edits the file.
IO.read(password_path).strip
else
# Monit offers no protections against brute force so use a long one.
SecureRandom.hex(64)
end
end
# Default logfile path.
#
# @return [String]
def default_logfile
monit_name_path('/var/log/%{name}.log')
end
# Default config path.
#
# @return [String]
def default_path
monit_name_path('/etc/%{name}')
end
# Default pidfile path. This MUST NOT be the same as the pidfile used
# by the sysvinit or dummy providers or monit will refuse to start. It
# also can't be /dev/null or something tricky because the client uses it
# to check if the daemon is running. I hate monit.
#
# @return [String]
def default_pidfile
monit_name_path('/var/run/%{name}_real.pid')
end
# Default var files path.
#
# @return [String]
def default_var_path
monit_name_path('/var/lib/%{name}')
end
# Find the version of Monit installed. Returns nil if monit is not
# installed.
#
# @api private
# @return [String, nil]
def monit_version
@monit_version ||= begin
cmd = shell_out([monit_binary, '-V'])
if !cmd.error? && /version ([0-9.]+)$/ =~ cmd.stdout
Gem::Version.create($1)
else
nil
end
end
end
# Interpolate the name of this monit instance in to a path.
#
# @api private
# @param path [String] A string with a %{name} template in it.
# @return [String]
def monit_name_path(path)
name = if service_name == 'monit'
'monit'
else
# If we are using a non-default service name, put that in the path.
"monit-#{service_name}"
end
path % {name: name}
end
end
end
end
end
Docstrings. Also move the CLI password to /var.
#
# Copyright 2015, Noah Kantrowitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'securerandom'
require 'chef/provider'
require 'chef/resource'
require 'poise'
require 'poise_service/service_mixin'
module PoiseMonit
module Resources
# (see Monit::Resource)
# @since 1.0.0
module Monit
UNIXSOCKET_VERSION = Gem::Requirement.create('>= 5.12')
# A `monit` resource to install and configure Monit.
#
# @provides monit
# @action enable
# @action disable
# @action start
# @action stop
# @action restart
# @action reload
# @example
# monit 'monit'
class Resource < Chef::Resource
include Poise(container: true, inversion: true)
provides(:monit)
include PoiseService::ServiceMixin
# @!attribute config
# Template content resource for the Monit configuration file.
attribute(:config, template: true, default_source: 'monit.conf.erb')
# @!attribute daemon_interval
# Number of seconds between service checks. Defaults to 120 seconds.
# @return [Integer]
attribute(:daemon_interval, kind_of: Integer, default: 120)
# @!attribute event_slots
# Number of slots in the Monit event buffer. Set to 0 to disable
# event buffering, or -1 for an unlimited queue. Defaults to 100.
# @return [Integer]
attribute(:event_slots, kind_of: Integer, default: 100)
# @!attribute httpd_port
# Port to listen on for Monit's HTTPD. If a path is specified, it is
# used as a Unix socket path. If set to nil or false, no HTTPD
# configuration is generated. This may break some other poise-monit
# resources. Default is a Unix socket if the version of Monit supports
# it, otherwise 2812.
# @return [String, Integer, nil, false]
attribute(:httpd_port, kind_of: [String, Integer, NilClass, FalseClass], default: lazy { default_httpd_port })
# @!attribute httpd_password
# Cleartext password for authentication between the Monit daemon and
# CLI. Set to nil or false to disable authentication. Default is nil
# for Unix socket connections and auto-generated otherwise.
# @return [String, nil, false]
attribute(:httpd_password, kind_of: [String, NilClass, FalseClass], default: lazy { default_httpd_password })
# @!attribute httpd_username
# Username for authentication between the Monit daemon and CLI.
# Default is cli.
# @return [String]
attribute(:httpd_username, kind_of: String, default: 'cli')
# @!attribute group
# System group to deploy Monit as.
# @return [String, nil, false]
attribute(:group, kind_of: [String, NilClass, FalseClass], default: nil)
# @!attribute logfile
# Path to the Monit log file. Default is /var/log/monit.log.
# @return [String, nil, false]
attribute(:logfile, kind_of: [String, NilClass, FalseClass], default: lazy { default_logfile })
# @!attribute group
# System user to deploy Monit as.
# @return [String, nil, false]
attribute(:owner, kind_of: [String, NilClass, FalseClass], default: nil)
# @!attribute path
# Path to the Monit configuration directory. Default is /etc/monit.
# @return [String]
attribute(:path, kind_of: String, default: lazy { default_path })
# @!attribute pidfile
# Path to the Monit PID file. Default is /var/run/monit.pid.
# @return [String]
attribute(:pidfile, kind_of: String, default: lazy { default_pidfile })
# @!attribute var_path
# Path the Monit state directory. Default is /var/lib/monit.
# @return [String]
attribute(:var_path, kind_of: String, default: lazy { default_var_path })
# @!attribute version
# Version of Monit to install.
# @return [String, nil, false]
attribute(:version, kind_of: [String, NilClass, FalseClass], default: nil)
# @!attribute [r] confd_path
# Path to the conf.d/ directory.
# @return [String]
def confd_path
::File.join(path, 'conf.d')
end
# @!attribute [r] config_path
# Path to the Monit configuration file.
# @return [String]
def config_path
::File.join(path, 'monitrc')
end
# @!attribute [r] password_path
# Path to the CLI password state tracking file.
# @return [String]
def password_path
::File.join(var_path, '.cli-password')
end
# @!attribute [r] httpd_is_unix?
# Are we using a Unix socket or TCP socket for Monit's HTTPD?
# @return [Boolean]
def httpd_is_unix?
httpd_port.to_s[0] == '/'
end
# The path to the `monit` binary for this Monit installation. This is
# an output property.
#
# @return [String]
# @example
# execute "#{resources('monit[monit]').monit_binary} start myapp"
def monit_binary
provider_for_action(:monit_binary).monit_binary
end
private
# Default HTTP port. Use a Unix socket if possible for security reasons.
def default_httpd_port
if monit_version && UNIXSOCKET_VERSION.satisfied_by?(monit_version)
monit_name_path('/var/run/%{name}.sock')
else
2812
end
end
# Default HTTP password for CLI authentication.
#
# @return [String]
def default_httpd_password
if httpd_is_unix?
# Unix sockets have ACLs already, don't need a password.
nil
elsif ::File.exist?(password_path)
# Strip is just to be safe in case a user edits the file.
IO.read(password_path).strip
else
# Monit offers no protections against brute force so use a long one.
SecureRandom.hex(64)
end
end
# Default logfile path.
#
# @return [String]
def default_logfile
monit_name_path('/var/log/%{name}.log')
end
# Default config path.
#
# @return [String]
def default_path
monit_name_path('/etc/%{name}')
end
# Default pidfile path. This MUST NOT be the same as the pidfile used
# by the sysvinit or dummy providers or monit will refuse to start. It
# also can't be /dev/null or something tricky because the client uses it
# to check if the daemon is running. I hate monit.
#
# @return [String]
def default_pidfile
monit_name_path('/var/run/%{name}_real.pid')
end
# Default var files path.
#
# @return [String]
def default_var_path
monit_name_path('/var/lib/%{name}')
end
# Find the version of Monit installed. Returns nil if monit is not
# installed.
#
# @api private
# @return [String, nil]
def monit_version
@monit_version ||= begin
cmd = shell_out([monit_binary, '-V'])
if !cmd.error? && /version ([0-9.]+)$/ =~ cmd.stdout
Gem::Version.create($1)
else
nil
end
end
end
# Interpolate the name of this monit instance in to a path.
#
# @api private
# @param path [String] A string with a %{name} template in it.
# @return [String]
def monit_name_path(path)
name = if service_name == 'monit'
'monit'
else
# If we are using a non-default service name, put that in the path.
"monit-#{service_name}"
end
path % {name: name}
end
end
end
end
end
|
module PostfixStatusLine
VERSION = '0.2.4'
end
Bump up version [ci skip]
module PostfixStatusLine
VERSION = '0.2.5'
end
|
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'cucumber'
s.version = File.read(File.expand_path('../lib/cucumber/version', __FILE__))
s.authors = ["Aslak Hellesøy", 'Matt Wynne', 'Steve Tooke']
s.description = 'Behaviour Driven Development with elegance and joy'
s.summary = "cucumber-#{s.version}"
s.email = 'cukes@googlegroups.com'
s.license = 'MIT'
s.homepage = 'https://cucumber.io/'
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 1.9.3'
s.add_dependency 'cucumber-core', '3.0.0.pre.2'
s.add_dependency 'builder', '>= 2.1.2'
s.add_dependency 'diff-lcs', '~> 1.3'
s.add_dependency 'gherkin', '~> 4.0'
s.add_dependency 'multi_json', '>= 1.7.5', '< 2.0'
s.add_dependency 'multi_test', '>= 0.1.2'
s.add_dependency 'cucumber-wire', '~> 0.0.1'
s.add_dependency 'cucumber-expressions', '~> 4.0.3'
s.add_development_dependency 'aruba', '~> 0.6.1'
s.add_development_dependency 'json', '~> 1.8.6'
s.add_development_dependency 'nokogiri', '~> 1.5'
s.add_development_dependency 'rake', '>= 0.9.2'
s.add_development_dependency 'rspec', '>= 3.0'
s.add_development_dependency 'simplecov', '>= 0.6.2'
s.add_development_dependency 'coveralls', '~> 0.7'
s.add_development_dependency 'syntax', '>= 1.0.0'
s.add_development_dependency 'pry'
s.add_development_dependency 'rubocop', '~> 0.40.0'
# For maintainer scripts
s.add_development_dependency 'octokit'
# For Documentation:
s.add_development_dependency 'bcat', '~> 0.6.2'
s.add_development_dependency 'kramdown', '~> 0.14'
s.add_development_dependency 'yard', '~> 0.8.0'
# Needed for examples (rake examples)
s.add_development_dependency 'capybara', '>= 2.1'
s.add_development_dependency 'rack-test', '>= 0.6.1'
s.add_development_dependency 'sinatra', '>= 1.3.2'
s.rubygems_version = '>= 1.6.1'
s.files = `git ls-files`.split("\n").reject {|path| path =~ /\.gitignore$/ }
s.test_files = `git ls-files -- {spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.rdoc_options = ['--charset=UTF-8']
s.require_path = 'lib'
end
Start depending on 3.0.0 of core
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'cucumber'
s.version = File.read(File.expand_path('../lib/cucumber/version', __FILE__))
s.authors = ["Aslak Hellesøy", 'Matt Wynne', 'Steve Tooke']
s.description = 'Behaviour Driven Development with elegance and joy'
s.summary = "cucumber-#{s.version}"
s.email = 'cukes@googlegroups.com'
s.license = 'MIT'
s.homepage = 'https://cucumber.io/'
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 1.9.3'
s.add_dependency 'cucumber-core', '~> 3.0.0'
s.add_dependency 'builder', '>= 2.1.2'
s.add_dependency 'diff-lcs', '~> 1.3'
s.add_dependency 'gherkin', '~> 4.0'
s.add_dependency 'multi_json', '>= 1.7.5', '< 2.0'
s.add_dependency 'multi_test', '>= 0.1.2'
s.add_dependency 'cucumber-wire', '~> 0.0.1'
s.add_dependency 'cucumber-expressions', '~> 4.0.3'
s.add_development_dependency 'aruba', '~> 0.6.1'
s.add_development_dependency 'json', '~> 1.8.6'
s.add_development_dependency 'nokogiri', '~> 1.5'
s.add_development_dependency 'rake', '>= 0.9.2'
s.add_development_dependency 'rspec', '>= 3.0'
s.add_development_dependency 'simplecov', '>= 0.6.2'
s.add_development_dependency 'coveralls', '~> 0.7'
s.add_development_dependency 'syntax', '>= 1.0.0'
s.add_development_dependency 'pry'
s.add_development_dependency 'rubocop', '~> 0.40.0'
# For maintainer scripts
s.add_development_dependency 'octokit'
# For Documentation:
s.add_development_dependency 'bcat', '~> 0.6.2'
s.add_development_dependency 'kramdown', '~> 0.14'
s.add_development_dependency 'yard', '~> 0.8.0'
# Needed for examples (rake examples)
s.add_development_dependency 'capybara', '>= 2.1'
s.add_development_dependency 'rack-test', '>= 0.6.1'
s.add_development_dependency 'sinatra', '>= 1.3.2'
s.rubygems_version = '>= 1.6.1'
s.files = `git ls-files`.split("\n").reject {|path| path =~ /\.gitignore$/ }
s.test_files = `git ls-files -- {spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.rdoc_options = ['--charset=UTF-8']
s.require_path = 'lib'
end
|
require 'uri'
require 'zlib'
class Premailer
module Rails
module CSSLoaders
# Loads the CSS from cache when not in development env.
module CacheLoader
extend self
def load(path)
unless ::Rails.env.development?
CSSHelper.cache[path]
end
end
end
# Loads the CSS from the asset pipeline.
module AssetPipelineLoader
extend self
def load(path)
if assets_enabled?
file = file_name(path)
if asset = ::Rails.application.assets.find_asset(file)
asset.to_s
else
Net::HTTP.get(uri_for_path(path))
end
end
end
def assets_enabled?
::Rails.configuration.assets.enabled rescue false
end
def file_name(path)
path
.sub("#{::Rails.configuration.assets.prefix}/", '')
.sub(/-\h{32}\.css$/, '.css')
end
def uri_for_path(path)
URI(path).tap do |uri|
scheme, host =
::Rails.configuration.action_controller.asset_host.split(%r{:?//})
scheme = 'http' if scheme.blank?
uri.scheme ||= scheme
uri.host ||= host
end
end
end
# Loads the CSS from the file system.
module FileSystemLoader
extend self
def load(path)
file_path = "#{::Rails.root}/public#{path}"
File.read(file_path) if File.exist?(file_path)
end
end
end
end
end
No longer require zlib
[ci skip]
require 'uri'
class Premailer
module Rails
module CSSLoaders
# Loads the CSS from cache when not in development env.
module CacheLoader
extend self
def load(path)
unless ::Rails.env.development?
CSSHelper.cache[path]
end
end
end
# Loads the CSS from the asset pipeline.
module AssetPipelineLoader
extend self
def load(path)
if assets_enabled?
file = file_name(path)
if asset = ::Rails.application.assets.find_asset(file)
asset.to_s
else
Net::HTTP.get(uri_for_path(path))
end
end
end
def assets_enabled?
::Rails.configuration.assets.enabled rescue false
end
def file_name(path)
path
.sub("#{::Rails.configuration.assets.prefix}/", '')
.sub(/-\h{32}\.css$/, '.css')
end
def uri_for_path(path)
URI(path).tap do |uri|
scheme, host =
::Rails.configuration.action_controller.asset_host.split(%r{:?//})
scheme = 'http' if scheme.blank?
uri.scheme ||= scheme
uri.host ||= host
end
end
end
# Loads the CSS from the file system.
module FileSystemLoader
extend self
def load(path)
file_path = "#{::Rails.root}/public#{path}"
File.read(file_path) if File.exist?(file_path)
end
end
end
end
end
|
require "thread_safe"
require "protobuf/rpc/connectors/base"
require "protobuf/rpc/connectors/ping"
require "protobuf/rpc/service_directory"
module Protobuf
module Rpc
module Connectors
class Zmq < Base
RequestTimeout = Class.new(RuntimeError)
ZmqRecoverableError = Class.new(RuntimeError)
ZmqEagainError = Class.new(RuntimeError)
##
# Included Modules
#
include Protobuf::Logging
##
# Class Constants
#
CLIENT_RETRIES = (ENV['PB_CLIENT_RETRIES'] || 3)
##
# Class Methods
#
def self.ping_port_responses
@ping_port_responses ||= ::ThreadSafe::Cache.new
end
def self.zmq_context
@zmq_contexts ||= Hash.new do |hash, key|
hash[key] = ZMQ::Context.new
end
@zmq_contexts[Process.pid]
end
##
# Instance methods
#
def log_signature
@_log_signature ||= "[client-#{self.class}]"
end
# Start the request/response cycle. We implement the Lazy Pirate
# req/reply reliability pattern as laid out in the ZMQ Guide, Chapter 4.
#
# @see http://zguide.zeromq.org/php:chapter4#Client-side-Reliability-Lazy-Pirate-Pattern
#
def send_request
setup_connection
send_request_with_lazy_pirate unless error?
end
private
##
# Private Instance methods
#
def check_available_rcv_timeout
@check_available_rcv_timeout ||= begin
case
when ENV.key?("PB_ZMQ_CLIENT_CHECK_AVAILABLE_RCV_TIMEOUT") then
ENV["PB_ZMQ_CLIENT_CHECK_AVAILABLE_RCV_TIMEOUT"].to_i
else
200 # ms
end
end
end
def check_available_snd_timeout
@check_available_snd_timeout ||= begin
case
when ENV.key?("PB_ZMQ_CLIENT_CHECK_AVAILABLE_SND_TIMEOUT") then
ENV["PB_ZMQ_CLIENT_CHECK_AVAILABLE_SND_TIMEOUT"].to_i
else
200 # ms
end
end
end
def close_connection
# The socket is automatically closed after every request.
end
# Create a socket connected to a server that can handle the current
# service. The LINGER is set to 0 so we can close immediately in
# the event of a timeout
def create_socket
begin
socket = zmq_context.socket(::ZMQ::REQ)
if socket # Make sure the context builds the socket
server_uri = lookup_server_uri
socket.setsockopt(::ZMQ::LINGER, 0)
zmq_error_check(socket.connect(server_uri), :socket_connect)
socket = socket_to_available_server(socket) if first_alive_load_balance?
end
end while socket.try(:socket).nil?
socket
end
# Method to determine error state, must be used with Connector API.
#
def error?
!! @error
end
def host_alive?(host)
return true unless ping_port_enabled?
if (last_response = self.class.ping_port_responses[host])
if (Time.now.to_i - last_response[:at]) <= host_alive_check_interval
return last_response[:ping_port_open]
end
end
ping_port_open = ping_port_open?(host)
self.class.ping_port_responses[host] = {
:at => Time.now.to_i,
:ping_port_open => ping_port_open,
}
ping_port_open
end
def host_alive_check_interval
@host_alive_check_interval ||= [ENV["PB_ZMQ_CLIENT_HOST_ALIVE_CHECK_INTERVAL"].to_i, 1].max
end
# Lookup a server uri for the requested service in the service
# directory. If the service directory is not running, default
# to the host and port in the options
#
def lookup_server_uri
server_lookup_attempts.times do
first_alive_listing = service_directory.all_listings_for(service).find do |listing|
host_alive?(listing.try(:address))
end
if first_alive_listing
host = first_alive_listing.try(:address)
port = first_alive_listing.try(:port)
@stats.server = [port, host]
return "tcp://#{host}:#{port}"
end
host = options[:host]
port = options[:port]
if host_alive?(host)
@stats.server = [port, host]
return "tcp://#{host}:#{port}"
end
sleep(1.0 / 100.0)
end
fail "Host not found for service #{service}"
end
def ping_port_open?(host)
Ping.new(host, ping_port.to_i).online?
end
def rcv_timeout
@rcv_timeout ||= begin
case
when options[:timeout] then
options[:timeout]
when ENV.key?("PB_ZMQ_CLIENT_RCV_TIMEOUT") then
ENV["PB_ZMQ_CLIENT_RCV_TIMEOUT"].to_i
else
300_000 # 300 seconds
end
end
end
# Trying a number of times, attempt to get a response from the server.
# If we haven't received a legitimate response in the CLIENT_RETRIES number
# of retries, fail the request.
#
def send_request_with_lazy_pirate
attempt = 0
begin
attempt += 1
send_request_with_timeout(attempt)
parse_response
rescue RequestTimeout
retry if attempt < CLIENT_RETRIES
failure(:RPC_FAILED, "The server repeatedly failed to respond within #{timeout} seconds")
end
end
def send_request_with_timeout(attempt = 0)
socket = create_socket
socket.setsockopt(::ZMQ::RCVTIMEO, rcv_timeout)
socket.setsockopt(::ZMQ::SNDTIMEO, snd_timeout)
logger.debug { sign_message("Sending Request (attempt #{attempt}, #{socket})") }
zmq_eagain_error_check(socket.send_string(@request_data), :socket_send_string)
logger.debug { sign_message("Waiting #{rcv_timeout}ms for response (attempt #{attempt}, #{socket})") }
zmq_eagain_error_check(socket.recv_string(@response_data = ""), :socket_recv_string)
logger.debug { sign_message("Response received (attempt #{attempt}, #{socket})") }
rescue ZmqEagainError
logger.debug { sign_message("Timed out waiting for response (attempt #{attempt}, #{socket})") }
raise RequestTimeout
ensure
logger.debug { sign_message("Closing Socket") }
zmq_error_check(socket.close, :socket_close) if socket
logger.debug { sign_message("Socket closed") }
end
def server_lookup_attempts
@server_lookup_attempts ||= [ENV["PB_ZMQ_CLIENT_SERVER_LOOKUP_ATTEMPTS"].to_i, 5].max
end
# The service we're attempting to connect to
#
def service
options[:service]
end
# Alias for ::Protobuf::Rpc::ServiceDirectory.instance
def service_directory
::Protobuf::Rpc.service_directory
end
def snd_timeout
@snd_timeout ||= begin
case
when options[:timeout] then
options[:timeout]
when ENV.key?("PB_ZMQ_CLIENT_SND_TIMEOUT") then
ENV["PB_ZMQ_CLIENT_SND_TIMEOUT"].to_i
else
300_000 # 300 seconds
end
end
end
def socket_to_available_server(socket)
check_available_response = ""
socket.setsockopt(::ZMQ::RCVTIMEO, check_available_rcv_timeout)
socket.setsockopt(::ZMQ::SNDTIMEO, check_available_snd_timeout)
zmq_recoverable_error_check(socket.send_string(::Protobuf::Rpc::Zmq::CHECK_AVAILABLE_MESSAGE), :socket_send_string)
zmq_recoverable_error_check(socket.recv_string(check_available_response), :socket_recv_string)
if check_available_response == ::Protobuf::Rpc::Zmq::NO_WORKERS_AVAILABLE
zmq_recoverable_error_check(socket.close, :socket_close)
end
socket.setsockopt(::ZMQ::RCVTIMEO, -1)
socket.setsockopt(::ZMQ::SNDTIMEO, -1)
socket
rescue ZmqRecoverableError
return nil # couldn't make a connection and need to try again
end
# Return the ZMQ Context to use for this process.
# If the context does not exist, create it, then register
# an exit block to ensure the context is terminated correctly.
#
def zmq_context
self.class.zmq_context
end
def zmq_eagain_error_check(return_code, source)
return if ::ZMQ::Util.resultcode_ok?(return_code || -1)
if ::ZMQ::Util.errno == ::ZMQ::EAGAIN # rubocop:disable Style/GuardClause
fail ZmqEagainError, <<-ERROR
Last ZMQ API call to #{source} failed with "#{::ZMQ::Util.error_string}".
#{caller(1).join($INPUT_RECORD_SEPARATOR)}
ERROR
else
fail <<-ERROR
Last ZMQ API call to #{source} failed with "#{::ZMQ::Util.error_string}".
#{caller(1).join($INPUT_RECORD_SEPARATOR)}
ERROR
end
end
def zmq_error_check(return_code, source)
return if ::ZMQ::Util.resultcode_ok?(return_code || -1)
fail <<-ERROR
Last ZMQ API call to #{source} failed with "#{::ZMQ::Util.error_string}".
#{caller(1).join($INPUT_RECORD_SEPARATOR)}
ERROR
end
def zmq_recoverable_error_check(return_code, source)
return if ::ZMQ::Util.resultcode_ok?(return_code || -1)
fail ZmqRecoverableError, <<-ERROR
Last ZMQ API call to #{source} failed with "#{::ZMQ::Util.error_string}".
#{caller(1).join($INPUT_RECORD_SEPARATOR)}
ERROR
end
end
end
end
end
prevent infinite loop on socket create when a problem
require "thread_safe"
require "protobuf/rpc/connectors/base"
require "protobuf/rpc/connectors/ping"
require "protobuf/rpc/service_directory"
module Protobuf
module Rpc
module Connectors
class Zmq < Base
RequestTimeout = Class.new(RuntimeError)
ZmqRecoverableError = Class.new(RuntimeError)
ZmqEagainError = Class.new(RuntimeError)
##
# Included Modules
#
include Protobuf::Logging
##
# Class Constants
#
CLIENT_RETRIES = (ENV['PB_CLIENT_RETRIES'] || 3)
##
# Class Methods
#
def self.ping_port_responses
@ping_port_responses ||= ::ThreadSafe::Cache.new
end
def self.zmq_context
@zmq_contexts ||= Hash.new do |hash, key|
hash[key] = ZMQ::Context.new
end
@zmq_contexts[Process.pid]
end
##
# Instance methods
#
def log_signature
@_log_signature ||= "[client-#{self.class}]"
end
# Start the request/response cycle. We implement the Lazy Pirate
# req/reply reliability pattern as laid out in the ZMQ Guide, Chapter 4.
#
# @see http://zguide.zeromq.org/php:chapter4#Client-side-Reliability-Lazy-Pirate-Pattern
#
def send_request
setup_connection
send_request_with_lazy_pirate unless error?
end
private
##
# Private Instance methods
#
def check_available_rcv_timeout
@check_available_rcv_timeout ||= begin
case
when ENV.key?("PB_ZMQ_CLIENT_CHECK_AVAILABLE_RCV_TIMEOUT") then
ENV["PB_ZMQ_CLIENT_CHECK_AVAILABLE_RCV_TIMEOUT"].to_i
else
200 # ms
end
end
end
def check_available_snd_timeout
@check_available_snd_timeout ||= begin
case
when ENV.key?("PB_ZMQ_CLIENT_CHECK_AVAILABLE_SND_TIMEOUT") then
ENV["PB_ZMQ_CLIENT_CHECK_AVAILABLE_SND_TIMEOUT"].to_i
else
200 # ms
end
end
end
def close_connection
# The socket is automatically closed after every request.
end
# Create a socket connected to a server that can handle the current
# service. The LINGER is set to 0 so we can close immediately in
# the event of a timeout
def create_socket
attempt_number = 0
begin
attempt_number += 1
socket = zmq_context.socket(::ZMQ::REQ)
if socket # Make sure the context builds the socket
server_uri = lookup_server_uri
socket.setsockopt(::ZMQ::LINGER, 0)
zmq_error_check(socket.connect(server_uri), :socket_connect)
socket = socket_to_available_server(socket) if first_alive_load_balance?
end
end while socket.nil? && attempt_number < socket_creation_attempts
raise RequestTimeout, "Cannot create new ZMQ client socket" if socket.nil?
socket
end
# Method to determine error state, must be used with Connector API.
#
def error?
!! @error
end
def host_alive?(host)
return true unless ping_port_enabled?
if (last_response = self.class.ping_port_responses[host])
if (Time.now.to_i - last_response[:at]) <= host_alive_check_interval
return last_response[:ping_port_open]
end
end
ping_port_open = ping_port_open?(host)
self.class.ping_port_responses[host] = {
:at => Time.now.to_i,
:ping_port_open => ping_port_open,
}
ping_port_open
end
def host_alive_check_interval
@host_alive_check_interval ||= [ENV["PB_ZMQ_CLIENT_HOST_ALIVE_CHECK_INTERVAL"].to_i, 1].max
end
# Lookup a server uri for the requested service in the service
# directory. If the service directory is not running, default
# to the host and port in the options
#
def lookup_server_uri
server_lookup_attempts.times do
first_alive_listing = service_directory.all_listings_for(service).find do |listing|
host_alive?(listing.try(:address))
end
if first_alive_listing
host = first_alive_listing.try(:address)
port = first_alive_listing.try(:port)
@stats.server = [port, host]
return "tcp://#{host}:#{port}"
end
host = options[:host]
port = options[:port]
if host_alive?(host)
@stats.server = [port, host]
return "tcp://#{host}:#{port}"
end
sleep(1.0 / 100.0)
end
fail "Host not found for service #{service}"
end
def ping_port_open?(host)
Ping.new(host, ping_port.to_i).online?
end
def rcv_timeout
@rcv_timeout ||= begin
case
when options[:timeout] then
options[:timeout]
when ENV.key?("PB_ZMQ_CLIENT_RCV_TIMEOUT") then
ENV["PB_ZMQ_CLIENT_RCV_TIMEOUT"].to_i
else
300_000 # 300 seconds
end
end
end
# Trying a number of times, attempt to get a response from the server.
# If we haven't received a legitimate response in the CLIENT_RETRIES number
# of retries, fail the request.
#
def send_request_with_lazy_pirate
attempt = 0
begin
attempt += 1
send_request_with_timeout(attempt)
parse_response
rescue RequestTimeout
retry if attempt < CLIENT_RETRIES
failure(:RPC_FAILED, "The server repeatedly failed to respond within #{timeout} seconds")
end
end
def send_request_with_timeout(attempt = 0)
socket = create_socket
socket.setsockopt(::ZMQ::RCVTIMEO, rcv_timeout)
socket.setsockopt(::ZMQ::SNDTIMEO, snd_timeout)
logger.debug { sign_message("Sending Request (attempt #{attempt}, #{socket})") }
zmq_eagain_error_check(socket.send_string(@request_data), :socket_send_string)
logger.debug { sign_message("Waiting #{rcv_timeout}ms for response (attempt #{attempt}, #{socket})") }
zmq_eagain_error_check(socket.recv_string(@response_data = ""), :socket_recv_string)
logger.debug { sign_message("Response received (attempt #{attempt}, #{socket})") }
rescue ZmqEagainError
logger.debug { sign_message("Timed out waiting for response (attempt #{attempt}, #{socket})") }
raise RequestTimeout
ensure
logger.debug { sign_message("Closing Socket") }
zmq_error_check(socket.close, :socket_close) if socket
logger.debug { sign_message("Socket closed") }
end
def server_lookup_attempts
@server_lookup_attempts ||= [ENV["PB_ZMQ_CLIENT_SERVER_LOOKUP_ATTEMPTS"].to_i, 5].max
end
# The service we're attempting to connect to
#
def service
options[:service]
end
# Alias for ::Protobuf::Rpc::ServiceDirectory.instance
def service_directory
::Protobuf::Rpc.service_directory
end
def snd_timeout
@snd_timeout ||= begin
case
when options[:timeout] then
options[:timeout]
when ENV.key?("PB_ZMQ_CLIENT_SND_TIMEOUT") then
ENV["PB_ZMQ_CLIENT_SND_TIMEOUT"].to_i
else
300_000 # 300 seconds
end
end
end
def socket_creation_attempts
@socket_creation_attempts ||= (ENV["PB_ZMQ_CLIENT_SOCKET_CREATION_ATTEMPTS"] || 5).to_i
end
def socket_to_available_server(socket)
check_available_response = ""
socket.setsockopt(::ZMQ::RCVTIMEO, check_available_rcv_timeout)
socket.setsockopt(::ZMQ::SNDTIMEO, check_available_snd_timeout)
zmq_recoverable_error_check(socket.send_string(::Protobuf::Rpc::Zmq::CHECK_AVAILABLE_MESSAGE), :socket_send_string)
zmq_recoverable_error_check(socket.recv_string(check_available_response), :socket_recv_string)
if check_available_response == ::Protobuf::Rpc::Zmq::NO_WORKERS_AVAILABLE
zmq_recoverable_error_check(socket.close, :socket_close)
end
socket.setsockopt(::ZMQ::RCVTIMEO, -1)
socket.setsockopt(::ZMQ::SNDTIMEO, -1)
socket
rescue ZmqRecoverableError
return nil # couldn't make a connection and need to try again
end
# Return the ZMQ Context to use for this process.
# If the context does not exist, create it, then register
# an exit block to ensure the context is terminated correctly.
#
def zmq_context
self.class.zmq_context
end
def zmq_eagain_error_check(return_code, source)
return if ::ZMQ::Util.resultcode_ok?(return_code || -1)
if ::ZMQ::Util.errno == ::ZMQ::EAGAIN # rubocop:disable Style/GuardClause
fail ZmqEagainError, <<-ERROR
Last ZMQ API call to #{source} failed with "#{::ZMQ::Util.error_string}".
#{caller(1).join($INPUT_RECORD_SEPARATOR)}
ERROR
else
fail <<-ERROR
Last ZMQ API call to #{source} failed with "#{::ZMQ::Util.error_string}".
#{caller(1).join($INPUT_RECORD_SEPARATOR)}
ERROR
end
end
def zmq_error_check(return_code, source)
return if ::ZMQ::Util.resultcode_ok?(return_code || -1)
fail <<-ERROR
Last ZMQ API call to #{source} failed with "#{::ZMQ::Util.error_string}".
#{caller(1).join($INPUT_RECORD_SEPARATOR)}
ERROR
end
def zmq_recoverable_error_check(return_code, source)
return if ::ZMQ::Util.resultcode_ok?(return_code || -1)
fail ZmqRecoverableError, <<-ERROR
Last ZMQ API call to #{source} failed with "#{::ZMQ::Util.error_string}".
#{caller(1).join($INPUT_RECORD_SEPARATOR)}
ERROR
end
end
end
end
end
|
Puppet::Type.type(:a2mod).provide(:a2mod) do
desc "Manage Apache 2 modules on Debian and Ubuntu"
optional_commands :encmd => "a2enmod"
optional_commands :discmd => "a2dismod"
defaultfor :operatingsystem => [:debian, :ubuntu]
def create
encmd resource[:name]
end
def destroy
discmd resource[:name]
end
def exists?
mod= "/etc/apache2/mods-enabled/" + resource[:name] + ".load"
File.exists?(mod)
end
end
Add self.instances to a2mod a2mod provider to allow puppet resource to work
Puppet::Type.type(:a2mod).provide(:a2mod) do
desc "Manage Apache 2 modules on Debian and Ubuntu"
optional_commands :encmd => "a2enmod"
optional_commands :discmd => "a2dismod"
defaultfor :operatingsystem => [:debian, :ubuntu]
def create
encmd resource[:name]
end
def destroy
discmd resource[:name]
end
def exists?
mod= "/etc/apache2/mods-enabled/" + resource[:name] + ".load"
File.exists?(mod)
end
def self.instances
# Empty hash to allow `puppet resource` to work
{}
end
end
|
module QueueDispatcher
class RcAndMsg
attr_accessor :rc, :output, :error_msg
def self.good_rc(output, args = {})
rc_and_msg = new
rc_and_msg.good_rc(output, args)
end
def self.bad_rc(error_msg, args = {})
rc_and_msg = new
rc_and_msg.bad_rc(error_msg, args)
end
# Initializer
def initialize(args = {})
@rc = args[:rc].to_i if args[:rc]
@output = args[:output]
@error_msg = args[:error_msg]
self
end
# Fake a good RC
def good_rc(output, args = {})
@rc = 0
@output = output
@error_msg = args[:error_msg]
self
end
# Fake a bad RC
def bad_rc(error_msg, args = {})
@rc = 999
@output = args[:output]
@error_msg = error_msg
self
end
# Addition
def +(other)
rc_and_msg = self.clone
rc_and_msg.rc += other.rc
rc_and_msg.output += "\n#{other.output}" if other.output.present?
rc_and_msg.error_msg += "\n#{other.error_msg}" if other.error_msg.present?
rc_and_msg
end
# Return hash
def to_hash
{ :rc => @rc, :output => @output, :error_msg => @error_msg }
end
end
end
Better calculation of two RcAndMsg-classes
module QueueDispatcher
class RcAndMsg
attr_accessor :rc, :output, :error_msg
def self.good_rc(output = '', args = {})
rc_and_msg = new
rc_and_msg.good_rc(output, args)
end
def self.bad_rc(error_msg, args = {})
rc_and_msg = new
rc_and_msg.bad_rc(error_msg, args)
end
# Initializer
def initialize(args = {})
@rc = args[:rc].to_i if args[:rc]
@output = args[:output]
@error_msg = args[:error_msg]
self
end
# Fake a good RC
def good_rc(output, args = {})
@rc = 0
@output = output
@error_msg = args[:error_msg]
self
end
# Fake a bad RC
def bad_rc(error_msg, args = {})
@rc = 999
@output = args[:output]
@error_msg = error_msg
self
end
# Addition
def +(other)
rc_and_msg = self.clone
rc_and_msg.rc += other.rc
rc_and_msg.output = rc_and_msg.output ? "#{output}\n#{other.output}" : other.output if other.output.present?
rc_and_msg.error_msg = rc_and_msg.error_msg ? "#{error_msg}\n#{other.error_msg}" : other.error_msg if other.error_msg.present?
rc_and_msg
end
# Return hash
def to_hash
{ :rc => @rc, :output => @output, :error_msg => @error_msg }
end
end
end
|
module Rack
module Secure
module Referer
VERSION = "0.0.1"
end
end
end
First version
module Rack
module Secure
module Referer
VERSION = "1.0.0"
end
end
end
|
module Rack
module TrafficSignal
VERSION = "0.1.2"
end
end
:+1: Bump version
module Rack
module TrafficSignal
VERSION = "0.1.3"
end
end
|
module RadioactiveBunnies
VERSION = "0.2.0"
end
Bump to 0.2.1
module RadioactiveBunnies
VERSION = "0.2.1"
end
|
module RailsClientLogger
VERSION = "1.0.1"
end
bumped up the version to 1.0.2
module RailsClientLogger
VERSION = "1.0.2"
end
|
# encoding: utf-8
require 'spec_helper'
require File.expand_path('../../fixtures/classes', __FILE__)
shared_examples_for 'memoizes method' do
it 'memoizes the instance method' do
subject
instance = object.new
instance.send(method).should equal(instance.send(method))
end
it 'creates a method that returns a frozen value' do
subject
object.new.send(method).should be_frozen
end
specification = proc do
subject
file, line = object.new.send(method).first.split(':')[0, 2]
File.expand_path(file).should eql(File.expand_path('../../../../../lib/adamantium/module_methods.rb', __FILE__))
line.to_i.should eql(80)
end
it 'sets the file and line number properly' do
if RUBY_PLATFORM.include?('java')
pending('Kernel#caller returns the incorrect line number in JRuby', &specification)
else
instance_eval(&specification)
end
end
context 'when the initializer calls the memoized method' do
before do
method = self.method
object.send(:define_method, :initialize) { send(method) }
end
it 'allows the memoized method to be called within the initializer' do
subject
expect { object.new }.to_not raise_error(NoMethodError)
end
it 'memoizes the methdod inside the initializer' do
subject
object.new.memoized(method).should_not be_nil
end
end
end
describe Adamantium::ModuleMethods, '#memoize' do
subject { object.memoize(method) }
let(:object) { Class.new(AdamantiumSpecs::Object) }
context 'public method' do
let(:method) { :public_method }
it_should_behave_like 'a command method'
it_should_behave_like 'memoizes method'
it 'is still a public method' do
should be_public_method_defined(method)
end
end
context 'protected method' do
let(:method) { :protected_method }
it_should_behave_like 'a command method'
it_should_behave_like 'memoizes method'
it 'is still a protected method' do
should be_protected_method_defined(method)
end
end
context 'private method' do
let(:method) { :private_method }
it_should_behave_like 'a command method'
it_should_behave_like 'memoizes method'
it 'is still a private method' do
should be_private_method_defined(method)
end
end
end
Add spec that covers mutation of Adamantium::ModuleMethods#memoize
# encoding: utf-8
require 'spec_helper'
require File.expand_path('../../fixtures/classes', __FILE__)
shared_examples_for 'memoizes method' do
it 'memoizes the instance method' do
subject
instance = object.new
instance.send(method).should equal(instance.send(method))
end
it 'creates a method that returns a same value' do
subject
instance = object.new
first = instance.send(method)
second = instance.send(method)
first.should be(second)
end
specification = proc do
subject
if method != :some_state
file, line = object.new.send(method).first.split(':')[0, 2]
File.expand_path(file).should eql(File.expand_path('../../../../../lib/adamantium/module_methods.rb', __FILE__))
line.to_i.should eql(80)
end
end
it 'sets the file and line number properly' do
# Exclude example for methot that does not return caller
if method == :some_method
return
end
if RUBY_PLATFORM.include?('java')
pending('Kernel#caller returns the incorrect line number in JRuby', &specification)
else
instance_eval(&specification)
end
end
context 'when the initializer calls the memoized method' do
before do
method = self.method
object.send(:define_method, :initialize) { send(method) }
end
it 'allows the memoized method to be called within the initializer' do
subject
expect { object.new }.to_not raise_error(NoMethodError)
end
it 'memoizes the methdod inside the initializer' do
subject
object.new.memoized(method).should_not be_nil
end
end
end
describe Adamantium::ModuleMethods, '#memoize' do
subject { object.memoize(method, options) }
let(:options) { {} }
let(:object) do
Class.new(AdamantiumSpecs::Object) do
def some_state
Object.new
end
end
end
context 'with :noop freezer option' do
let(:method) { :some_state }
let(:options) { { :freezer => :noop } }
it_should_behave_like 'a command method'
it_should_behave_like 'memoizes method'
it 'is still a public method' do
should be_public_method_defined(method)
end
it 'creates a method that returns a non frozen value' do
subject
object.new.send(method).should_not be_frozen
end
end
context 'memoized method that returns generated values' do
let(:method) { :some_state }
it_should_behave_like 'a command method'
it_should_behave_like 'memoizes method'
it 'creates a method that returns a frozen value' do
subject
object.new.send(method).should be_frozen
end
end
context 'public method' do
let(:method) { :public_method }
it_should_behave_like 'a command method'
it_should_behave_like 'memoizes method'
it 'is still a public method' do
should be_public_method_defined(method)
end
it 'creates a method that returns a frozen value' do
subject
object.new.send(method).should be_frozen
end
end
context 'protected method' do
let(:method) { :protected_method }
it_should_behave_like 'a command method'
it_should_behave_like 'memoizes method'
it 'is still a protected method' do
should be_protected_method_defined(method)
end
it 'creates a method that returns a frozen value' do
subject
object.new.send(method).should be_frozen
end
end
context 'private method' do
let(:method) { :private_method }
it_should_behave_like 'a command method'
it_should_behave_like 'memoizes method'
it 'is still a private method' do
should be_private_method_defined(method)
end
it 'creates a method that returns a frozen value' do
subject
object.new.send(method).should be_frozen
end
end
end
|
require 'test_helper'
class Api::V1::ServicesControllerTest < ActionDispatch::IntegrationTest
def setup
@user = create(:user, password: 'pass123')
@user_params = {
user: {
email: @user.email,
password: 'pass123'
}
}
end
test 'returns JWT token for succesfull login' do
post api_v1_sessions_url, params: @user_params, as: :json
json = response.parsed_body
refute_nil json['token']
end
test 'returns user info' do
post api_v1_sessions_url, params: @user_params, as: :json
json = response.parsed_body
assert_equal @user.id, json['user']['id']
assert_equal @user.first_name, json['user']['first_name']
assert_equal @user.last_name, json['user']['last_name']
refute json['user']['mentor']
end
test 'it returns a redirect_to path to the users profile for a regular login' do
post api_v1_sessions_url, params: @user_params, as: :json
json = response.parsed_body
assert_equal '/profile', json['redirect_to']
end
test 'it returns a redirect_to path to discourse for an sso login' do
post api_v1_sessions_url, params: @user_params.merge(sso_params), as: :json
json = response.parsed_body
assert_match /^https:\/\/community\.operationcode\.org\?sso=.*sig=.*$/, json['redirect_to']
end
def discourse_sso_url
'https://community.operationcode.org?sso=bm9uY2U9Y2I2ODI1MWVlZmI1MjExZTU4YzAwZmYxMzk1ZjBjMGImbmFtZT1M%0AaWxpYW4rUm9tYWd1ZXJhJnVzZXJuYW1lPWFpZGElNDBiZWVyLmluZm8mZW1h%0AaWw9YWlkYSU0MGJlZXIuaW5mbyZyZXF1aXJlX2FjdGl2YXRpb249dHJ1ZSZl%0AeHRlcm5hbF9pZD0yOA%3D%3D%0A&sig=e57b3554b951149981433a63738891892e2da9499125b57ba8084f57cc035de4'
end
def sso_params
{
sso: 'bm9uY2U9Y2I2ODI1MWVlZmI1MjExZTU4YzAwZmYxMzk1ZjBjMGImbmFtZT1zYW0mdXNlcm5hbWU9c2Ftc2FtJmVtYWlsPXRlc3QlNDB0ZXN0LmNvbSZleHRlcm5hbF9pZD1oZWxsbzEyMyZyZXF1aXJlX2FjdGl2YXRpb249dHJ1ZQ==',
sig: 'd6bc820029617d00b54f1bb0cf117a91a037b284cbd7d2832c95ef8371062eb1'
}
end
end
Fix test
require 'test_helper'
class Api::V1::ServicesControllerTest < ActionDispatch::IntegrationTest
def setup
@user = create(:user, password: 'pass123')
@user_params = {
user: {
email: @user.email,
password: 'pass123'
}
}
end
test 'returns JWT token for succesfull login' do
post api_v1_sessions_url, params: @user_params, as: :json
json = response.parsed_body
refute_nil json['token']
end
test 'returns user info' do
post api_v1_sessions_url, params: @user_params, as: :json
json = response.parsed_body
assert_equal @user.id, json['user']['id']
assert_equal @user.first_name, json['user']['first_name']
assert_equal @user.last_name, json['user']['last_name']
refute json['user']['mentor']
end
test 'it returns a redirect_to path to the users profile for a regular login' do
post api_v1_sessions_url, params: @user_params, as: :json
json = response.parsed_body
assert_equal '/profile', json['redirect_to']
end
test 'it returns a redirect_to path to discourse for an sso login' do
post api_v1_sessions_url, params: @user_params.merge(sso_params), as: :json
json = response.parsed_body
assert_match /^https:\/\/community\.operationcode\.org\/session\/sso_login\?sso=.*sig=.*$/, json['redirect_to']
end
def discourse_sso_url
'https://community.operationcode.org?sso=bm9uY2U9Y2I2ODI1MWVlZmI1MjExZTU4YzAwZmYxMzk1ZjBjMGImbmFtZT1M%0AaWxpYW4rUm9tYWd1ZXJhJnVzZXJuYW1lPWFpZGElNDBiZWVyLmluZm8mZW1h%0AaWw9YWlkYSU0MGJlZXIuaW5mbyZyZXF1aXJlX2FjdGl2YXRpb249dHJ1ZSZl%0AeHRlcm5hbF9pZD0yOA%3D%3D%0A&sig=e57b3554b951149981433a63738891892e2da9499125b57ba8084f57cc035de4'
end
def sso_params
{
sso: 'bm9uY2U9Y2I2ODI1MWVlZmI1MjExZTU4YzAwZmYxMzk1ZjBjMGImbmFtZT1zYW0mdXNlcm5hbWU9c2Ftc2FtJmVtYWlsPXRlc3QlNDB0ZXN0LmNvbSZleHRlcm5hbF9pZD1oZWxsbzEyMyZyZXF1aXJlX2FjdGl2YXRpb249dHJ1ZQ==',
sig: 'd6bc820029617d00b54f1bb0cf117a91a037b284cbd7d2832c95ef8371062eb1'
}
end
end
|
require 'test_helper'
class BatchPublishingTest < ActionController::TestCase
tests PeopleController
fixtures :all
include AuthenticatedTestHelper
def setup
login_as(:aaron)
end
test "should have the -Publish your all assets- only one your own profile" do
get :show, :id => User.current_user.person
assert_response :success
assert_select "a[href=?]", batch_publishing_preview_person_path, :text => /Publish your all assets/
get :show, :id => Factory(:person)
assert_response :success
assert_select "a", :text => /Publish your all assets/, :count => 0
end
test "get batch_publishing_preview" do
#bundle of assets that can publish immediately
publish_immediately_assets = can_publish_immediately_assets
publish_immediately_assets.each do |a|
assert a.can_publish?,"The asset must be publishable immediately for this test to succeed"
end
#bundle of assets that can not publish immediately but can send the publish request
send_request_assets = can_send_request_assets
send_request_assets.each do |a|
assert !a.can_publish?,"The asset must not be publishable immediately for this test to succeed"
assert a.publish_authorized?,"The publish request for this asset must be able to be sent for this test to succeed"
end
total_asset_count = (publish_immediately_assets + send_request_assets).count
get :batch_publishing_preview
assert_response :success
assert_select "li.type_and_title", :count=>total_asset_count do
publish_immediately_assets.each do |a|
assert_select "a[href=?]",eval("#{a.class.name.underscore}_path(#{a.id})"),:text=>/#{a.title}/
end
send_request_assets.each do |a|
assert_select "a[href=?]",eval("#{a.class.name.underscore}_path(#{a.id})"),:text=>/#{a.title}/
end
assert_select "li.type_and_title img[src*=?][title=?]",/lock.png/, /Private/, :count => total_asset_count
end
assert_select "li.secondary", :text => /Publish/, :count => publish_immediately_assets.count
publish_immediately_assets.each do |a|
assert_select "input[checked='checked'][type='checkbox'][id=?]", "publish_#{a.class.name}_#{a.id}"
end
assert_select "li.secondary", :text => /Submit publishing request/, :count => send_request_assets.count
send_request_assets.each do |a|
assert_select "input[checked='checked'][type='checkbox'][id=?]", "publish_#{a.class.name}_#{a.id}"
end
end
test "do not have published items in batch_publishing_preview" do
published_item = Factory(:data_file,
:contributor=> User.current_user,
:policy => Factory(:public_policy))
assert published_item.is_published?, "This data file must be published for the test to succeed"
assert published_item.publish_authorized?, "This data file must be publish_authorized for the test to be meaningful"
get :batch_publishing_preview
assert_response :success
assert_select "input[checked='checked'][type='checkbox'][id=?]", "publish_#{published_item.class.name}_#{published_item.id}",
:count => 0
end
test "do not have not_publish_authorized items in batch_publishing_preview" do
item = Factory(:data_file, :policy => Factory(:all_sysmo_viewable_policy))
assert !item.publish_authorized?, "This data file must not be publish_authorized for the test to succeed"
assert !item.is_published?, "This data file must not be published for the test to be meaningful"
get :batch_publishing_preview
assert_response :success
assert_select "input[checked='checked'][type='checkbox'][id=?]", "publish_#{item.class.name}_#{item.id}",
:count => 0
end
test "do not have not_publishable_type item in batch_publishing_preview" do
item = Factory(:sample, :contributor => User.current_user)
assert item.publish_authorized?, "This data file must be publish_authorized for the test to be meaningful"
assert !item.is_published?, "This data file must not be published for the test to be meaningful"
get :batch_publishing_preview
assert_response :success
assert_select "input[checked='checked'][type='checkbox'][id=?]", "publish_#{item.class.name}_#{item.id}",
:count => 0
end
test "do batch_publish" do
#bundle of assets that can publish immediately
publish_immediately_assets = can_publish_immediately_assets
publish_immediately_assets.each do |a|
assert !a.is_published?,"The asset must not be published for this test to succeed"
assert a.can_publish?,"The asset must be publishable immediately for this test to succeed"
end
#bundle of assets that can not publish immediately but can send the publish request
send_request_assets = can_send_request_assets
send_request_assets.each do |a|
assert !a.can_publish?,"The asset must not be publishable immediately for this test to succeed"
assert a.publish_authorized?,"The publish request for this asset must be able to be sent for this test to succeed"
end
total_assets = publish_immediately_assets + send_request_assets
params={:publish=>{}}
total_assets.each do |asset|
params[:publish][asset.class.name]||={}
params[:publish][asset.class.name][asset.id.to_s]="1"
end
assert_difference("ResourcePublishLog.count", total_assets.count) do
assert_emails send_request_assets.count do
post :batch_publish, params
end
end
assert_response :success
assert_nil flash[:error]
assert_not_nil flash[:notice]
publish_immediately_assets.each do |a|
a.reload
assert a.is_published?
end
send_request_assets.each do |a|
a.reload
assert !a.is_published?
end
end
test "do not batch_publish for already published items" do
published_item = Factory(:data_file,
:contributor=> User.current_user,
:policy => Factory(:public_policy))
assert published_item.is_published?, "This data file must be published for the test to succeed"
assert published_item.publish_authorized?, "This data file must be publish_authorized for the test to be meaningful"
params={:publish=>{}}
params[:publish][published_item.class.name]||={}
params[:publish][published_item.class.name][published_item.id.to_s]="1"
assert_no_difference("ResourcePublishLog.count") do
assert_emails 0 do
post :batch_publish, params
end
end
assert_response :success
assert_nil flash[:error]
assert_not_nil flash[:notice]
end
test "do not batch_publish for not_publish_authorized items" do
item = Factory(:data_file, :policy => Factory(:all_sysmo_viewable_policy))
assert !item.publish_authorized?, "This data file must not be publish_authorized for the test to succeed"
assert !item.is_published?, "This data file must not be published for the test to be meaningful"
params={:publish=>{}}
params[:publish][item.class.name]||={}
params[:publish][item.class.name][item.id.to_s]="1"
assert_no_difference("ResourcePublishLog.count") do
assert_emails 0 do
post :batch_publish, params
end
end
assert_response :success
assert_nil flash[:error]
assert_not_nil flash[:notice]
item.reload
assert !item.is_published?
end
test "get batch_publish redirects to show" do
#This is useful because if you logout it redirects to root.
#If you just published something, that will do a get request to *Controller#batch_publish
get :batch_publish
assert_redirected_to :root
end
private
def can_publish_immediately_assets
publishable_types = Seek::Util.authorized_types.select {|c| c.first.try(:is_in_isa_publishable?)}
publishable_types.collect do |klass|
Factory(klass.name.underscore.to_sym, :contributor => User.current_user)
end
end
def can_send_request_assets
publishable_types = Seek::Util.authorized_types.select {|c| c.first.try(:is_in_isa_publishable?)}
publishable_types.collect do |klass|
Factory(klass.name.underscore.to_sym, :contributor => User.current_user, :projects => Factory(:gatekeeper).projects)
end
end
end
update test for batch publishing
require 'test_helper'
class BatchPublishingTest < ActionController::TestCase
tests PeopleController
fixtures :all
include AuthenticatedTestHelper
def setup
login_as(:aaron)
end
test "should have the -Publish all your assets- only one your own profile" do
get :show, :id => User.current_user.person
assert_response :success
assert_select "a[href=?]", batch_publishing_preview_person_path, :text => /Publish all your assets/
get :batch_publishing_preview, :id => User.current_user.person.id
assert_response :success
assert_nil flash[:error]
#not yourself
a_person = Factory(:person)
get :show, :id => a_person
assert_response :success
assert_select "a", :text => /Publish all your assets/, :count => 0
get :batch_publishing_preview, :id => a_person.id
assert_redirected_to :root
assert_not_nil flash[:error]
end
test "get batch_publishing_preview" do
#bundle of assets that can publish immediately
publish_immediately_assets = can_publish_immediately_assets
publish_immediately_assets.each do |a|
assert a.can_publish?,"The asset must be publishable immediately for this test to succeed"
end
#bundle of assets that can not publish immediately but can send the publish request
send_request_assets = can_send_request_assets
send_request_assets.each do |a|
assert !a.can_publish?,"The asset must not be publishable immediately for this test to succeed"
assert a.publish_authorized?,"The publish request for this asset must be able to be sent for this test to succeed"
end
total_asset_count = (publish_immediately_assets + send_request_assets).count
get :batch_publishing_preview, :id => User.current_user.person.id
assert_response :success
assert_select "li.type_and_title", :count=>total_asset_count do
publish_immediately_assets.each do |a|
assert_select "a[href=?]",eval("#{a.class.name.underscore}_path(#{a.id})"),:text=>/#{a.title}/
end
send_request_assets.each do |a|
assert_select "a[href=?]",eval("#{a.class.name.underscore}_path(#{a.id})"),:text=>/#{a.title}/
end
assert_select "li.type_and_title img[src*=?][title=?]",/lock.png/, /Private/, :count => total_asset_count
end
assert_select "li.secondary", :text => /Publish/, :count => publish_immediately_assets.count
publish_immediately_assets.each do |a|
assert_select "input[checked='checked'][type='checkbox'][id=?]", "publish_#{a.class.name}_#{a.id}"
end
assert_select "li.secondary", :text => /Submit publishing request/, :count => send_request_assets.count
send_request_assets.each do |a|
assert_select "input[checked='checked'][type='checkbox'][id=?]", "publish_#{a.class.name}_#{a.id}"
end
end
test "do not have published items in batch_publishing_preview" do
published_item = Factory(:data_file,
:contributor=> User.current_user,
:policy => Factory(:public_policy))
assert published_item.is_published?, "This data file must be published for the test to succeed"
assert published_item.publish_authorized?, "This data file must be publish_authorized for the test to be meaningful"
get :batch_publishing_preview, :id => User.current_user.person.id
assert_response :success
assert_select "input[checked='checked'][type='checkbox'][id=?]", "publish_#{published_item.class.name}_#{published_item.id}",
:count => 0
end
test "do not have not_publish_authorized items in batch_publishing_preview" do
item = Factory(:data_file, :policy => Factory(:all_sysmo_viewable_policy))
assert !item.publish_authorized?, "This data file must not be publish_authorized for the test to succeed"
assert !item.is_published?, "This data file must not be published for the test to be meaningful"
get :batch_publishing_preview, :id => User.current_user.person.id
assert_response :success
assert_select "input[checked='checked'][type='checkbox'][id=?]", "publish_#{item.class.name}_#{item.id}",
:count => 0
end
test "do not have not_publishable_type item in batch_publishing_preview" do
item = Factory(:sample, :contributor => User.current_user)
assert item.publish_authorized?, "This data file must be publish_authorized for the test to be meaningful"
assert !item.is_published?, "This data file must not be published for the test to be meaningful"
get :batch_publishing_preview, :id => User.current_user.person.id
assert_response :success
assert_select "input[checked='checked'][type='checkbox'][id=?]", "publish_#{item.class.name}_#{item.id}",
:count => 0
end
test "do publish" do
#bundle of assets that can publish immediately
publish_immediately_assets = can_publish_immediately_assets
publish_immediately_assets.each do |a|
assert !a.is_published?,"The asset must not be published for this test to succeed"
assert a.can_publish?,"The asset must be publishable immediately for this test to succeed"
end
#bundle of assets that can not publish immediately but can send the publish request
send_request_assets = can_send_request_assets
send_request_assets.each do |a|
assert !a.can_publish?,"The asset must not be publishable immediately for this test to succeed"
assert a.publish_authorized?,"The publish request for this asset must be able to be sent for this test to succeed"
end
total_assets = publish_immediately_assets + send_request_assets
params={:publish=>{}}
total_assets.each do |asset|
params[:publish][asset.class.name]||={}
params[:publish][asset.class.name][asset.id.to_s]="1"
end
assert_difference("ResourcePublishLog.count", total_assets.count) do
assert_emails send_request_assets.count do
post :publish, params.merge(:id=> User.current_user.person.id)
end
end
assert_response :success
assert_nil flash[:error]
assert_not_nil flash[:notice]
publish_immediately_assets.each do |a|
a.reload
assert a.is_published?
end
send_request_assets.each do |a|
a.reload
assert !a.is_published?
end
end
test "do not publish for already published items" do
published_item = Factory(:data_file,
:contributor=> User.current_user,
:policy => Factory(:public_policy))
assert published_item.is_published?, "This data file must be published for the test to succeed"
assert published_item.publish_authorized?, "This data file must be publish_authorized for the test to be meaningful"
params={:publish=>{}}
params[:publish][published_item.class.name]||={}
params[:publish][published_item.class.name][published_item.id.to_s]="1"
assert_no_difference("ResourcePublishLog.count") do
assert_emails 0 do
post :publish, params.merge(:id=> User.current_user.person.id)
end
end
assert_response :success
assert_nil flash[:error]
assert_not_nil flash[:notice]
end
test "get batch_publish redirects to show" do
#This is useful because if you logout it redirects to root.
#If you just published something, that will do a get request to *Controller#batch_publish
get :publish, :id=> User.current_user.person.id
assert_response :redirect
end
private
def can_publish_immediately_assets
publishable_types = Seek::Util.authorized_types.select {|c| c.first.try(:is_in_isa_publishable?)}
publishable_types.collect do |klass|
Factory(klass.name.underscore.to_sym, :contributor => User.current_user)
end
end
def can_send_request_assets
publishable_types = Seek::Util.authorized_types.select {|c| c.first.try(:is_in_isa_publishable?)}
publishable_types.collect do |klass|
Factory(klass.name.underscore.to_sym, :contributor => User.current_user, :projects => Factory(:gatekeeper).projects)
end
end
end
|
require 'test_helper'
class SampleTransfersControllerTest < ActionController::TestCase
site_administrators.each do |cu|
test "should destroy with #{cu} login" do
sample_transfer = Factory(:sample_transfer)
login_as send(cu)
assert_difference('SampleTransfer.count',-1){
delete :destroy, :id => sample_transfer.id
}
assert_nil flash[:error]
assert_redirected_to sample_transfers_path
end
test "should NOT destroy with invalid id #{cu} login" do
sample_transfer = Factory(:sample_transfer)
login_as send(cu)
assert_difference('SampleTransfer.count',0){
delete :destroy, :id => 0
}
assert_not_nil flash[:error]
assert_redirected_to sample_transfers_path
end
end
non_site_administrators.each do |cu|
test "should NOT destroy with #{cu} login" do
sample_transfer = Factory(:sample_transfer)
login_as send(cu)
assert_difference('SampleTransfer.count',0){
delete :destroy, :id => sample_transfer.id
}
assert_not_nil flash[:error]
assert_redirected_to root_path
end
end
site_editors.each do |cu|
test "should not confirm without organization_id with #{cu} login" do
login_as send(cu)
put :confirm
assert_redirected_to sample_transfers_path
assert_not_nil flash[:error]
assert_match /Valid organization id required/, flash[:error]
end
test "should not confirm without valid organization_id with #{cu} login" do
login_as send(cu)
put :confirm, :organization_id => 0
assert_redirected_to sample_transfers_path
assert_not_nil flash[:error]
assert_match /Valid organization id required/, flash[:error]
end
test "confirm should do what with sample transfer update_all fail and #{cu} login" do
prep_confirm_test
login_as send(cu)
SampleTransfer.any_instance.stubs(:create_or_update).returns(false)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
# how to fake a fail update_all and does it raise an error?
#flunk 'manually flunked'
pending
end
test "confirm should fail with operational event invalid and #{cu} login" do
prep_confirm_test
login_as send(cu)
OperationalEvent.any_instance.stubs(:valid?).returns(false)
assert_difference('OperationalEvent.count',0){
put :confirm, :organization_id => Organization['GEGL'].id
}
assert_redirected_to sample_transfers_path
assert_not_nil flash[:error]
#TODO not particularly descriptive "Something really bad happened"
assert_match /Something really bad happened/, flash[:error]
end
test "confirm should fail with operational event create fail and #{cu} login" do
prep_confirm_test
login_as send(cu)
OperationalEvent.any_instance.stubs(:create_or_update).returns(false)
assert_difference('OperationalEvent.count',0){
put :confirm, :organization_id => Organization['GEGL'].id
}
assert_redirected_to sample_transfers_path
assert_not_nil flash[:error]
#TODO not particularly descriptive "Something really bad happened"
assert_match /Something really bad happened/, flash[:error]
end
# can't create a typeless sample so invalid test
# test "confirm should do what with typeless sample and #{cu} login" do
# prep_confirm_test
# login_as send(cu)
# put :confirm, :organization_id => Organization['GEGL'].id
# assert_redirected_to sample_transfers_path
# end
# can't create a projectless sample so invalid test
# test "confirm should do what with projectless sample and #{cu} login" do
# prep_confirm_test
# login_as send(cu)
# put :confirm, :organization_id => Organization['GEGL'].id
# assert_redirected_to sample_transfers_path
# end
test "confirm should work with locationless sample and #{cu} login" do
prep_confirm_test(:active_sample => { :location_id => nil })
SampleTransfer.active.each { |st| assert_nil st.sample.location_id }
login_as send(cu)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
end
test "confirm should do what with subjectless sample and #{cu} login" do
prep_confirm_test(:active_sample => { :study_subject => nil })
login_as send(cu)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
end
test "confirm should require active transfers with #{cu} login" do
# prep_confirm_test # <- don't do this
login_as send(cu)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
assert_not_nil flash[:error]
assert_match /Active sample transfers required to confirm/, flash[:error]
end
test "confirm should set each sample location_id with #{cu} login" do
prep_confirm_test
active_transfers = SampleTransfer.active.all # must do before as status changes
assert_equal 3.times.collect{Organization['CCLS'].id},
active_transfers.collect(&:reload).collect(&:sample).collect(&:location_id)
login_as send(cu)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
assert_equal 3.times.collect{Organization['GEGL'].id},
active_transfers.collect(&:reload).collect(&:sample).collect(&:location_id)
end
test "confirm should set each sample sent_to_lab_at with #{cu} login" do
prep_confirm_test
active_transfers = SampleTransfer.active.all # must do before as status changes
login_as send(cu)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
# as this is a datetime, can't test EXACT, so just test date portion
assert_equal 3.times.collect{Date.today},
active_transfers.collect(&:reload).collect(&:sample)
.collect(&:sent_to_lab_at).collect(&:to_date)
end
test "confirm should set each sample transfer destination_org_id with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
assert_equal 3.times.collect{nil},
active_transfers.collect(&:destination_org_id)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
assert_equal 3.times.collect{Organization['GEGL'].id},
active_transfers.collect(&:reload).collect(&:destination_org_id)
end
test "confirm should set each sample transfer sent_on with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
assert_equal 3.times.collect{nil},
active_transfers.collect(&:sent_on)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
assert_equal 3.times.collect{Date.today},
active_transfers.collect(&:reload).collect(&:sent_on)
end
test "confirm should set each sample transfer status with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
assert_equal 3.times.collect{'active'},
active_transfers.collect(&:status)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
assert_equal 3.times.collect{'complete'},
active_transfers.collect(&:reload).collect(&:status)
end
test "confirm should create operational event for each sample with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
assert_difference('OperationalEvent.count',3){
put :confirm, :organization_id => Organization['GEGL'].id
}
assert_redirected_to sample_transfers_path
end
test "confirm should set each operational event type with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
# assert_difference("OperationalEvent.where(:operational_event_type_id => OperationalEventType['sample_to_lab'].id ).count",3){
assert_difference("OperationalEventType['sample_to_lab'].operational_events.count",3){
put :confirm, :organization_id => Organization['GEGL'].id
}
assert_redirected_to sample_transfers_path
end
test "confirm should set each operational event project with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
active_transfers.collect(&:reload).collect(&:sample).each do |s|
assert s.study_subject.operational_events.collect(&:project).include?(s.project)
end
end
test "confirm should set each operational event description with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
OperationalEventType['sample_to_lab'].operational_events.each {|oe|
assert_match /Sample ID \d{7}, \w+, transferred to GEGL from \w+/,
oe.description }
end
test "should get sample transfers index with #{cu} login and no transfers" do
login_as send(cu)
get :index
assert_response :success
assert_template 'index'
assert assigns(:active_sample_transfers)
assert assigns(:active_sample_transfers).empty?
assert assigns(:waitlist_sample_transfers)
assert assigns(:waitlist_sample_transfers).empty?
end
test "should get sample transfers index with #{cu} login and waitlist transfers" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'waitlist')
get :index
assert_response :success
assert_template 'index'
assert assigns(:active_sample_transfers)
assert assigns(:active_sample_transfers).empty?
assert assigns(:waitlist_sample_transfers)
assert !assigns(:waitlist_sample_transfers).empty?
assert_equal 1, assigns(:waitlist_sample_transfers).length
end
test "should get sample transfers index with #{cu} login and active transfers" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
get :index
assert_response :success
assert_template 'index'
assert assigns(:active_sample_transfers)
assert !assigns(:active_sample_transfers).empty?
assert_equal 1, assigns(:active_sample_transfers).length
assert assigns(:waitlist_sample_transfers)
assert assigns(:waitlist_sample_transfers).empty?
end
test "should export sample transfers to csv with #{cu} login and active transfers" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active' )
get :index, :format => 'csv'
assert_response :success
assert_not_nil @response.headers['Content-Disposition'].match(/attachment;.*csv/)
assert_template 'index'
assert assigns(:active_sample_transfers)
assert !assigns(:active_sample_transfers).empty?
assert_equal 1, assigns(:active_sample_transfers).length
assert assigns(:waitlist_sample_transfers)
assert assigns(:waitlist_sample_transfers).empty?
require 'csv'
f = CSV.parse(@response.body)
assert_equal 2, f.length # 2 rows, 1 header and 1 data
# assert_equal f[0], ["masterid", "biomom", "biodad", "date", "mother_full_name", "mother_maiden_name", "father_full_name", "child_full_name", "child_dobm", "child_dobd", "child_doby", "child_gender", "birthplace_country", "birthplace_state", "birthplace_city", "mother_hispanicity", "mother_hispanicity_mex", "mother_race", "other_mother_race", "father_hispanicity", "father_hispanicity_mex", "father_race", "other_father_race"]
# assert_equal 23, f[0].length
##["46", nil, nil, nil, "[name not available]", nil, "[name not available]", "[name not available]", "3", "23", "2006", "F", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
# assert_equal f[1][0], case_study_subject.icf_master_id
# assert_equal f[1][8], case_study_subject.dob.try(:month).to_s
# assert_equal f[1][9], case_study_subject.dob.try(:day).to_s
# assert_equal f[1][10], case_study_subject.dob.try(:year).to_s
# assert_equal f[1][11], case_study_subject.sex
end
test "should NOT update sample_transfer status with invalid sample_transfer #{cu} login" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
SampleTransfer.any_instance.stubs(:valid?).returns(false)
deny_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => st.id, :status => 'waitlist'
}
assert_not_nil flash[:error]
assert_redirected_to sample_transfers_path
end
test "should NOT update sample_transfer status with failed save and #{cu} login" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
SampleTransfer.any_instance.stubs(:create_or_update).returns(false)
deny_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => st.id, :status => 'waitlist'
}
assert_not_nil flash[:error]
assert_redirected_to sample_transfers_path
end
test "should NOT update sample_transfer status with invalid status and #{cu} login" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
deny_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => st.id, :status => 'bogus'
}
assert_not_nil flash[:error]
assert_redirected_to sample_transfers_path
end
test "should NOT update sample_transfer status with invalid id and #{cu} login" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
deny_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => 0, :status => 'waitlist'
}
assert_not_nil flash[:error]
assert_redirected_to sample_transfers_path
end
test "should update sample_transfer status with #{cu} login" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
assert_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => st.id, :status => 'waitlist'
}
assert_not_nil assigns(:sample_transfer)
assert_nil flash[:error]
assert_redirected_to sample_transfers_path
end
end
non_site_editors.each do |cu|
test "should NOT get sample transfers index with #{cu} login" do
login_as send(cu)
get :index
assert_not_nil flash[:error]
assert_redirected_to root_path
end
test "should NOT update sample_transfer status with #{cu} login" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
deny_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => st.id, :status => 'waitlist'
}
assert_nil assigns(:sample_transfer)
assert_not_nil flash[:error]
assert_redirected_to root_path
end
end
test "should NOT get sample transfers index without login" do
get :index
assert_redirected_to_login
end
test "should NOT update sample_transfer status without login" do
st = Factory(:sample_transfer, :status => 'active')
deny_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => st.id, :status => 'waitlist'
}
assert_redirected_to_login
end
protected
def prep_confirm_test(options={})
assert_difference('SampleTransfer.waitlist.count',3) {
assert_difference('SampleTransfer.active.count',3) {
assert_difference('SampleTransfer.count',6) {
assert_difference('Sample.count',6) {
3.times {
study_subject = Factory(:study_subject)
active_sample = Factory(:sample, { :study_subject => study_subject
}.merge(options[:active_sample]||{}))
waitlist_sample = Factory(:sample, { :study_subject => study_subject
}.merge(options[:waitlist_sample]||{}))
Factory(:active_sample_transfer, { :sample => active_sample
}.merge(options[:active_sample_transfer]||{}))
Factory(:waitlist_sample_transfer, { :sample => waitlist_sample
}.merge(options[:waitlist_sample_transfer]||{}))
} } } } }
end
end
Maniputed user permissions.
require 'test_helper'
class SampleTransfersControllerTest < ActionController::TestCase
site_administrators.each do |cu|
test "should destroy with #{cu} login" do
sample_transfer = Factory(:sample_transfer)
login_as send(cu)
assert_difference('SampleTransfer.count',-1){
delete :destroy, :id => sample_transfer.id
}
assert_nil flash[:error]
assert_redirected_to sample_transfers_path
end
test "should NOT destroy with invalid id #{cu} login" do
sample_transfer = Factory(:sample_transfer)
login_as send(cu)
assert_difference('SampleTransfer.count',0){
delete :destroy, :id => 0
}
assert_not_nil flash[:error]
assert_redirected_to sample_transfers_path
end
end
non_site_administrators.each do |cu|
test "should NOT destroy with #{cu} login" do
sample_transfer = Factory(:sample_transfer)
login_as send(cu)
assert_difference('SampleTransfer.count',0){
delete :destroy, :id => sample_transfer.id
}
assert_not_nil flash[:error]
assert_redirected_to root_path
end
end
site_editors.each do |cu|
test "should not confirm without organization_id with #{cu} login" do
login_as send(cu)
put :confirm
assert_redirected_to sample_transfers_path
assert_not_nil flash[:error]
assert_match /Valid organization id required/, flash[:error]
end
test "should not confirm without valid organization_id with #{cu} login" do
login_as send(cu)
put :confirm, :organization_id => 0
assert_redirected_to sample_transfers_path
assert_not_nil flash[:error]
assert_match /Valid organization id required/, flash[:error]
end
test "confirm should do what with sample transfer update_all fail and #{cu} login" do
prep_confirm_test
login_as send(cu)
SampleTransfer.any_instance.stubs(:create_or_update).returns(false)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
# how to fake a fail update_all and does it raise an error?
#flunk 'manually flunked'
pending
end
test "confirm should fail with operational event invalid and #{cu} login" do
prep_confirm_test
login_as send(cu)
OperationalEvent.any_instance.stubs(:valid?).returns(false)
assert_difference('OperationalEvent.count',0){
put :confirm, :organization_id => Organization['GEGL'].id
}
assert_redirected_to sample_transfers_path
assert_not_nil flash[:error]
#TODO not particularly descriptive "Something really bad happened"
assert_match /Something really bad happened/, flash[:error]
end
test "confirm should fail with operational event create fail and #{cu} login" do
prep_confirm_test
login_as send(cu)
OperationalEvent.any_instance.stubs(:create_or_update).returns(false)
assert_difference('OperationalEvent.count',0){
put :confirm, :organization_id => Organization['GEGL'].id
}
assert_redirected_to sample_transfers_path
assert_not_nil flash[:error]
#TODO not particularly descriptive "Something really bad happened"
assert_match /Something really bad happened/, flash[:error]
end
# can't create a typeless sample so invalid test
# test "confirm should do what with typeless sample and #{cu} login" do
# prep_confirm_test
# login_as send(cu)
# put :confirm, :organization_id => Organization['GEGL'].id
# assert_redirected_to sample_transfers_path
# end
# can't create a projectless sample so invalid test
# test "confirm should do what with projectless sample and #{cu} login" do
# prep_confirm_test
# login_as send(cu)
# put :confirm, :organization_id => Organization['GEGL'].id
# assert_redirected_to sample_transfers_path
# end
test "confirm should work with locationless sample and #{cu} login" do
prep_confirm_test(:active_sample => { :location_id => nil })
SampleTransfer.active.each { |st| assert_nil st.sample.location_id }
login_as send(cu)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
end
test "confirm should do what with subjectless sample and #{cu} login" do
prep_confirm_test(:active_sample => { :study_subject => nil })
login_as send(cu)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
end
test "confirm should require active transfers with #{cu} login" do
# prep_confirm_test # <- don't do this
login_as send(cu)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
assert_not_nil flash[:error]
assert_match /Active sample transfers required to confirm/, flash[:error]
end
test "confirm should set each sample location_id with #{cu} login" do
prep_confirm_test
active_transfers = SampleTransfer.active.all # must do before as status changes
assert_equal 3.times.collect{Organization['CCLS'].id},
active_transfers.collect(&:reload).collect(&:sample).collect(&:location_id)
login_as send(cu)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
assert_equal 3.times.collect{Organization['GEGL'].id},
active_transfers.collect(&:reload).collect(&:sample).collect(&:location_id)
end
test "confirm should set each sample sent_to_lab_at with #{cu} login" do
prep_confirm_test
active_transfers = SampleTransfer.active.all # must do before as status changes
login_as send(cu)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
# as this is a datetime, can't test EXACT, so just test date portion
assert_equal 3.times.collect{Date.today},
active_transfers.collect(&:reload).collect(&:sample)
.collect(&:sent_to_lab_at).collect(&:to_date)
end
test "confirm should set each sample transfer destination_org_id with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
assert_equal 3.times.collect{nil},
active_transfers.collect(&:destination_org_id)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
assert_equal 3.times.collect{Organization['GEGL'].id},
active_transfers.collect(&:reload).collect(&:destination_org_id)
end
test "confirm should set each sample transfer sent_on with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
assert_equal 3.times.collect{nil},
active_transfers.collect(&:sent_on)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
assert_equal 3.times.collect{Date.today},
active_transfers.collect(&:reload).collect(&:sent_on)
end
test "confirm should set each sample transfer status with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
assert_equal 3.times.collect{'active'},
active_transfers.collect(&:status)
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
assert_equal 3.times.collect{'complete'},
active_transfers.collect(&:reload).collect(&:status)
end
test "confirm should create operational event for each sample with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
assert_difference('OperationalEvent.count',3){
put :confirm, :organization_id => Organization['GEGL'].id
}
assert_redirected_to sample_transfers_path
end
test "confirm should set each operational event type with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
# assert_difference("OperationalEvent.where(:operational_event_type_id => OperationalEventType['sample_to_lab'].id ).count",3){
assert_difference("OperationalEventType['sample_to_lab'].operational_events.count",3){
put :confirm, :organization_id => Organization['GEGL'].id
}
assert_redirected_to sample_transfers_path
end
test "confirm should set each operational event project with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
active_transfers.collect(&:reload).collect(&:sample).each do |s|
assert s.study_subject.operational_events.collect(&:project).include?(s.project)
end
end
test "confirm should set each operational event description with #{cu} login" do
prep_confirm_test
login_as send(cu)
active_transfers = SampleTransfer.active.all # must do before as status changes
put :confirm, :organization_id => Organization['GEGL'].id
assert_redirected_to sample_transfers_path
OperationalEventType['sample_to_lab'].operational_events.each {|oe|
assert_match /Sample ID \d{7}, \w+, transferred to GEGL from \w+/,
oe.description }
end
test "should NOT update sample_transfer status with invalid sample_transfer #{cu} login" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
SampleTransfer.any_instance.stubs(:valid?).returns(false)
deny_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => st.id, :status => 'waitlist'
}
assert_not_nil flash[:error]
assert_redirected_to sample_transfers_path
end
test "should NOT update sample_transfer status with failed save and #{cu} login" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
SampleTransfer.any_instance.stubs(:create_or_update).returns(false)
deny_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => st.id, :status => 'waitlist'
}
assert_not_nil flash[:error]
assert_redirected_to sample_transfers_path
end
test "should NOT update sample_transfer status with invalid status and #{cu} login" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
deny_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => st.id, :status => 'bogus'
}
assert_not_nil flash[:error]
assert_redirected_to sample_transfers_path
end
test "should NOT update sample_transfer status with invalid id and #{cu} login" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
deny_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => 0, :status => 'waitlist'
}
assert_not_nil flash[:error]
assert_redirected_to sample_transfers_path
end
test "should update sample_transfer status with #{cu} login" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
assert_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => st.id, :status => 'waitlist'
}
assert_not_nil assigns(:sample_transfer)
assert_nil flash[:error]
assert_redirected_to sample_transfers_path
end
end
non_site_editors.each do |cu|
test "should NOT update sample_transfer status with #{cu} login" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
deny_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => st.id, :status => 'waitlist'
}
assert_nil assigns(:sample_transfer)
assert_not_nil flash[:error]
assert_redirected_to root_path
end
end
site_readers.each do |cu|
test "should get sample transfers index with #{cu} login and no transfers" do
login_as send(cu)
get :index
assert_response :success
assert_template 'index'
assert assigns(:active_sample_transfers)
assert assigns(:active_sample_transfers).empty?
assert assigns(:waitlist_sample_transfers)
assert assigns(:waitlist_sample_transfers).empty?
end
test "should get sample transfers index with #{cu} login and waitlist transfers" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'waitlist')
get :index
assert_response :success
assert_template 'index'
assert assigns(:active_sample_transfers)
assert assigns(:active_sample_transfers).empty?
assert assigns(:waitlist_sample_transfers)
assert !assigns(:waitlist_sample_transfers).empty?
assert_equal 1, assigns(:waitlist_sample_transfers).length
end
test "should get sample transfers index with #{cu} login and active transfers" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active')
get :index
assert_response :success
assert_template 'index'
assert assigns(:active_sample_transfers)
assert !assigns(:active_sample_transfers).empty?
assert_equal 1, assigns(:active_sample_transfers).length
assert assigns(:waitlist_sample_transfers)
assert assigns(:waitlist_sample_transfers).empty?
end
test "should export sample transfers to csv with #{cu} login and active transfers" do
login_as send(cu)
st = Factory(:sample_transfer, :status => 'active' )
get :index, :format => 'csv'
assert_response :success
assert_not_nil @response.headers['Content-Disposition'].match(/attachment;.*csv/)
assert_template 'index'
assert assigns(:active_sample_transfers)
assert !assigns(:active_sample_transfers).empty?
assert_equal 1, assigns(:active_sample_transfers).length
assert assigns(:waitlist_sample_transfers)
assert assigns(:waitlist_sample_transfers).empty?
require 'csv'
f = CSV.parse(@response.body)
assert_equal 2, f.length # 2 rows, 1 header and 1 data
# assert_equal f[0], ["masterid", "biomom", "biodad", "date", "mother_full_name", "mother_maiden_name", "father_full_name", "child_full_name", "child_dobm", "child_dobd", "child_doby", "child_gender", "birthplace_country", "birthplace_state", "birthplace_city", "mother_hispanicity", "mother_hispanicity_mex", "mother_race", "other_mother_race", "father_hispanicity", "father_hispanicity_mex", "father_race", "other_father_race"]
# assert_equal 23, f[0].length
##["46", nil, nil, nil, "[name not available]", nil, "[name not available]", "[name not available]", "3", "23", "2006", "F", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
# assert_equal f[1][0], case_study_subject.icf_master_id
# assert_equal f[1][8], case_study_subject.dob.try(:month).to_s
# assert_equal f[1][9], case_study_subject.dob.try(:day).to_s
# assert_equal f[1][10], case_study_subject.dob.try(:year).to_s
# assert_equal f[1][11], case_study_subject.sex
end
end
non_site_readers.each do |cu|
test "should NOT get sample transfers index with #{cu} login" do
login_as send(cu)
get :index
assert_not_nil flash[:error]
assert_redirected_to root_path
end
end
test "should NOT get sample transfers index without login" do
get :index
assert_redirected_to_login
end
test "should NOT update sample_transfer status without login" do
st = Factory(:sample_transfer, :status => 'active')
deny_changes("SampleTransfer.find(#{st.id}).status") {
put :update_status, :id => st.id, :status => 'waitlist'
}
assert_redirected_to_login
end
protected
def prep_confirm_test(options={})
assert_difference('SampleTransfer.waitlist.count',3) {
assert_difference('SampleTransfer.active.count',3) {
assert_difference('SampleTransfer.count',6) {
assert_difference('Sample.count',6) {
3.times {
study_subject = Factory(:study_subject)
active_sample = Factory(:sample, { :study_subject => study_subject
}.merge(options[:active_sample]||{}))
waitlist_sample = Factory(:sample, { :study_subject => study_subject
}.merge(options[:waitlist_sample]||{}))
Factory(:active_sample_transfer, { :sample => active_sample
}.merge(options[:active_sample_transfer]||{}))
Factory(:waitlist_sample_transfer, { :sample => waitlist_sample
}.merge(options[:waitlist_sample_transfer]||{}))
} } } } }
end
end
|
#
# Copyright 2015, Noah Kantrowitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'net/http'
require 'serverspec'
set :backend, :exec
describe 'rackup' do
context '/opt/rack1' do
describe port(8000) do
it { is_expected.to be_listening }
end
describe process('rackup') do
it { is_expected.to be_running }
end
describe 'HTTP response' do
subject { Net::HTTP.new('localhost', 8000).get('/').body }
it { is_expected.to eq 'Hello world' }
end
end # /context /opt/rack1
context '/opt/rack2' do
describe port(8001) do
it { is_expected.to be_listening }
end
describe 'HTTP response' do
subject { Net::HTTP.new('localhost', 8001).get('/').body }
it { is_expected.to start_with '/opt/rack2' }
end
end # /context /opt/rack2
end
Remove the process check because rackup isn't run directly anymore.
The important thing is that the app works anyway :)
#
# Copyright 2015, Noah Kantrowitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'net/http'
require 'serverspec'
set :backend, :exec
describe 'rackup' do
context '/opt/rack1' do
describe port(8000) do
it { is_expected.to be_listening }
end
describe 'HTTP response' do
subject { Net::HTTP.new('localhost', 8000).get('/').body }
it { is_expected.to eq 'Hello world' }
end
end # /context /opt/rack1
context '/opt/rack2' do
describe port(8001) do
it { is_expected.to be_listening }
end
describe 'HTTP response' do
subject { Net::HTTP.new('localhost', 8001).get('/').body }
it { is_expected.to start_with '/opt/rack2' }
end
end # /context /opt/rack2
end
|
require 'test_helper'
class EvercookieControllerTest < ActionController::TestCase
test "should have route to set evercookie" do
assert_routing '/evercookie/set',
{ controller: "evercookie/evercookie", action: "set" }
end
test "should have route to get evercookie" do
assert_routing '/evercookie/get',
{ controller: "evercookie/evercookie", action: "get" }
end
test "should have route to save evercookie" do
assert_routing '/evercookie/save',
{ controller: "evercookie/evercookie", action: "save" }
end
test "should have route to ec_png evercookie" do
assert_routing '/evercookie/ec_png',
{ controller: "evercookie/evercookie", action: "ec_png" }
end
test "should have route to ec_cache evercookie" do
assert_routing '/evercookie/ec_cache',
{ controller: "evercookie/evercookie", action: "ec_cache" }
end
test "should have route to ec_etag evercookie" do
assert_routing '/evercookie/ec_etag',
{ controller: "evercookie/evercookie", action: "ec_etag" }
end
test "should set view variables on evercookie set and have right js" do
@controller = Evercookie::EvercookieController.new
session_data = {'key': 'testkey', value: 'testvalue'}
get :set, { format: :js }, { Evercookie.hash_name_for_set => session_data }
assert_response :success
assert_equal session_data, assigns[:data]
assert @response.body.include? "var ec = new evercookie()"
assert @response.body.include? "ec.set('testkey', 'testvalue')"
end
test "should set view variables on evercookie get and have right js" do
@controller = Evercookie::EvercookieController.new
session_data = {key: 'testkey'}
get :get, { format: :js }, { Evercookie.hash_name_for_get => session_data }
assert_response :success
assert_equal session_data, assigns[:data]
assert @response.body.include? "var ec = new evercookie()"
assert @response.body.include? "ec.get('testkey')"
end
test "should set session variables on evercookie save if cookie present" do
@controller = Evercookie::EvercookieController.new
cookies[:testkey] = 'testvalue'
get :save, nil, { Evercookie.hash_name_for_get => {key: 'testkey'} }
assert_response :success
assert_equal session[Evercookie.hash_name_for_saved],
{'testkey' => 'testvalue'}
end
test "should not set session variables on save if cookie not present" do
@controller = Evercookie::EvercookieController.new
session[Evercookie.hash_name_for_get] = {key: 'testkey'}
get :save
assert_response :success
assert session[Evercookie.hash_name_for_saved].nil?
end
end
fixed tests
require 'test_helper'
class EvercookieControllerTest < ActionController::TestCase
test "should have route to set evercookie" do
assert_routing '/evercookie/set',
{ controller: "evercookie/evercookie", action: "set" }
end
test "should have route to get evercookie" do
assert_routing '/evercookie/get',
{ controller: "evercookie/evercookie", action: "get" }
end
test "should have route to save evercookie" do
assert_routing '/evercookie/save',
{ controller: "evercookie/evercookie", action: "save" }
end
test "should have route to ec_png evercookie" do
assert_routing '/evercookie/ec_png',
{ controller: "evercookie/evercookie", action: "ec_png" }
end
test "should have route to ec_cache evercookie" do
assert_routing '/evercookie/ec_cache',
{ controller: "evercookie/evercookie", action: "ec_cache" }
end
test "should have route to ec_etag evercookie" do
assert_routing '/evercookie/ec_etag',
{ controller: "evercookie/evercookie", action: "ec_etag" }
end
test "should set view variables on evercookie set and have right js" do
@controller = Evercookie::EvercookieController.new
session_data = {key: 'testkey', value: 'testvalue'}
@request.session[Evercookie.hash_name_for_set] = session_data
get :set, format: :js
assert_response :success
assert_equal session_data, assigns(:data).symbolize_keys
assert @response.body.include? "var ec = new evercookie()"
assert @response.body.include? "ec.set('testkey', 'testvalue')"
end
test "should set view variables on evercookie get and have right js" do
@controller = Evercookie::EvercookieController.new
session_data = {key: 'testkey'}
@request.session[Evercookie.hash_name_for_get] = session_data
get :get, format: :js
assert_response :success
assert_equal session_data, assigns(:data).symbolize_keys
assert @response.body.include? "var ec = new evercookie()"
assert @response.body.include? "ec.get('testkey')"
end
test "should set session variables on evercookie save if cookie present" do
@controller = Evercookie::EvercookieController.new
cookies[:testkey] = 'testvalue'
@request.session[Evercookie.hash_name_for_get] = {key: 'testkey'}
get :save
assert_response :success
assert_equal 'testvalue', session[Evercookie.hash_name_for_saved]['testkey']
end
test "should not set session variables on save if cookie not present" do
@controller = Evercookie::EvercookieController.new
@request.session[Evercookie.hash_name_for_get] = {key: 'testkey'}
get :save
assert_response :success
assert session[Evercookie.hash_name_for_saved].nil?
end
end
|
Pod::Spec.new do |s|
s.name = "WFExtension"
s.version = "1.0.1"
s.summary = "字典/模型转化库"
s.homepage = "https://github.com/CWFJ/WFExtension"
s.license = "MIT"
s.authors = { 'WF Chia' => '345609097@qq.com'}
s.platform = :ios, "6.0"
s.source = { :git => "https://github.com/CWFJ/WFExtension.git", :tag => s.version }
s.source_files = "WFExtension/Classes/WFExtension/*.{h,m}"
s.requires_arc = true
end
增加license文件
Pod::Spec.new do |s|
s.name = "WFExtension"
s.version = "1.0.2"
s.summary = "字典/模型转化库"
s.homepage = "https://github.com/CWFJ/WFExtension"
s.license = "MIT"
s.authors = { 'WF Chia' => '345609097@qq.com'}
s.platform = :ios, "6.0"
s.source = { :git => "https://github.com/CWFJ/WFExtension.git", :tag => s.version }
s.source_files = "WFExtension/Classes/WFExtension/*.{h,m}"
s.requires_arc = true
end
|
require 'spec_helper_acceptance'
describe 'cassandra class' do
describe 'running puppet code' do
# Using puppet_apply as a helper
it 'should work with no errors' do
pp = <<-EOS
if $::osfamily == 'Debian' {
class { 'cassandra':
config_path => '/etc/cassandra',
datastax_agent_ensure => 'present',
datastax_agent_manage_service => false,
manage_dsc_repo => true,
java_package_name => 'openjdk-7-jre-headless',
}
} else {
class { 'cassandra':
datastax_agent_ensure => 'present',
datastax_agent_manage_service => false,
manage_dsc_repo => true,
java_package_name => 'java-1.7.0-openjdk',
}
}
EOS
# Run it twice and test for idempotency
apply_manifest(pp, :catch_failures => true)
expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero
end
end
end
Refactor of beaker test (#17).
require 'spec_helper_acceptance'
describe 'cassandra class' do
describe 'running puppet code' do
# Using puppet_apply as a helper
it 'should work with no errors' do
pp = <<-EOS
if $::osfamily == 'Debian' {
$config_path = '/etc/cassandra'
$java_package_name = 'openjdk-7-jre-headless'
} else {
$java_package_name = 'java-1.7.0-openjdk'
}
class { 'cassandra':
datastax_agent_ensure => 'present',
datastax_agent_manage_service => false,
manage_dsc_repo => true,
}
EOS
# Run it twice and test for idempotency
apply_manifest(pp, :catch_failures => true)
expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero
end
end
end
|
Tests that the module installs with indempotency (#8).
require 'spec_helper_acceptance'
describe 'cassandra class' do
describe 'running puppet code' do
# Using puppet_apply as a helper
it 'should work with no errors' do
pp = <<-EOS
class { 'cassandra': manage_dsc_repo => true }
EOS
# Run it twice and test for idempotency
apply_manifest(pp, :catch_failures => true)
expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero
end
end
end
|
require 'spec_helper_acceptance'
describe 'firewall type', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do
describe 'reset' do
it 'deletes all iptables rules' do
shell('iptables --flush; iptables -t nat --flush; iptables -t mangle --flush')
end
it 'deletes all ip6tables rules' do
shell('ip6tables --flush; ip6tables -t nat --flush; ip6tables -t mangle --flush')
end
end
if default['platform'] !~ /sles-10/
describe 'connlimit_above' do
context '10' do
it 'applies' do
pp = <<-EOS
class { '::firewall': }
firewall { '500 - test':
proto => tcp,
dport => '2222',
connlimit_above => '10',
action => reject,
}
EOS
apply_manifest(pp, :catch_failures => true)
end
it 'should contain the rule' do
shell('iptables-save') do |r|
#connlimit-saddr is added in Ubuntu 14.04.
expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --dports 2222 -m comment --comment "500 - test" -m connlimit --connlimit-above 10 --connlimit-mask 32 (--connlimit-saddr )?-j REJECT --reject-with icmp-port-unreachable/)
end
end
end
end
describe 'connlimit_mask' do
context '24' do
it 'applies' do
pp = <<-EOS
class { '::firewall': }
firewall { '501 - test':
proto => tcp,
dport => '2222',
connlimit_above => '10',
connlimit_mask => '24',
action => reject,
}
EOS
apply_manifest(pp, :catch_failures => true)
end
it 'should contain the rule' do
shell('iptables-save') do |r|
#connlimit-saddr is added in Ubuntu 14.04.
expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --dports 2222 -m comment --comment "501 - test" -m connlimit --connlimit-above 10 --connlimit-mask 24 (--connlimit-saddr )?-j REJECT --reject-with icmp-port-unreachable/)
end
end
end
end
end
end
Updated acceptance test for modules-2159
require 'spec_helper_acceptance'
describe 'firewall type', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do
describe 'reset' do
it 'deletes all iptables rules' do
shell('iptables --flush; iptables -t nat --flush; iptables -t mangle --flush')
end
it 'deletes all ip6tables rules' do
shell('ip6tables --flush; ip6tables -t nat --flush; ip6tables -t mangle --flush')
end
end
if default['platform'] !~ /sles-10/
describe 'connlimit_above' do
context '10' do
it 'applies' do
pp = <<-EOS
class { '::firewall': }
firewall { '500 - test':
proto => tcp,
dport => '2222',
connlimit_above => '10',
action => reject,
}
EOS
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :catch_changes => do_catch_changes)
end
it 'should contain the rule' do
shell('iptables-save') do |r|
#connlimit-saddr is added in Ubuntu 14.04.
expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --dports 2222 -m comment --comment "500 - test" -m connlimit --connlimit-above 10 --connlimit-mask 32 (--connlimit-saddr )?-j REJECT --reject-with icmp-port-unreachable/)
end
end
end
end
describe 'connlimit_mask' do
context '24' do
it 'applies' do
pp = <<-EOS
class { '::firewall': }
firewall { '501 - test':
proto => tcp,
dport => '2222',
connlimit_above => '10',
connlimit_mask => '24',
action => reject,
}
EOS
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :catch_changes => do_catch_changes)
end
it 'should contain the rule' do
shell('iptables-save') do |r|
#connlimit-saddr is added in Ubuntu 14.04.
expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --dports 2222 -m comment --comment "501 - test" -m connlimit --connlimit-above 10 --connlimit-mask 24 (--connlimit-saddr )?-j REJECT --reject-with icmp-port-unreachable/)
end
end
end
end
end
end
|
describe Bandwidth::V2::Message do
client = nil
before :each do
client = Helper.get_client()
end
after :each do
client.stubs.verify_stubbed_calls()
end
describe '#create' do
it 'should create new item' do
client.stubs.post('/api/v2/users/userId/messages', '{"text":"hello"}') {|env| [202, {}, '{"id": "messageId"}']}
expect(V2::Message.create(client, {:text=>'hello'})).to eql({id: 'messageId'})
end
end
describe '#create_iris_request' do
it 'should create Faraday instance for Bandwidth dashboard' do
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
connection = V2::Message.send(:create_iris_request, {user_name: 'user', password: 'password'})
expect(connection.headers["Authorization"]).to eql("Basic dXNlcjpwYXNzd29yZA==")
expect(connection.headers["Accept"]).to eql("application/xml")
end
end
describe '#make_iris_request' do
it 'should make http request to dashboard' do
client.stubs.get('/api/accounts/accountId/test') {|env| [200, {}, '<Response>test</Response>']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
r = V2::Message.send(:make_iris_request, {user_name: 'user', password: 'password', account_id: 'accountId'}, :get, '/test')
expect(r[0]).to eql("test")
end
end
describe '#check_response' do
it 'should check errors 1' do
client.stubs.get('/api/accounts/accountId/test') {|env| [200, {}, '<Response><ErrorCode>Code</ErrorCode><Description>Description</Description></Response>']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
expect{V2::Message.send(:make_iris_request, {user_name: 'user', password: 'password', account_id: 'accountId'}, :get, '/test')}.to raise_error(Errors::GenericIrisError)
end
it 'should check errors 2' do
client.stubs.get('/api/accounts/accountId/test') {|env| [200, {}, '<Response><Error><Code>Code</Code><Description>Description</Description></Error></Response>']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
expect{V2::Message.send(:make_iris_request, {user_name: 'user', password: 'password', account_id: 'accountId'}, :get, '/test')}.to raise_error(Errors::GenericIrisError)
end
it 'should check errors 3' do
client.stubs.get('/api/accounts/accountId/test') {|env| [200, {}, '<Response><Errors><Code>Code</Code><Description>Description</Description></Errors></Response>']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
expect{V2::Message.send(:make_iris_request, {user_name: 'user', password: 'password', account_id: 'accountId'}, :get, '/test')}.to raise_error(Errors::AgregateError)
end
it 'should check errors 4' do
client.stubs.get('/api/accounts/accountId/test') {|env| [200, {}, '<Response><resultCode>Code</resultCode><resultMessage>Description</resultMessage></Response>']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
expect{V2::Message.send(:make_iris_request, {user_name: 'user', password: 'password', account_id: 'accountId'}, :get, '/test')}.to raise_error(Errors::GenericIrisError)
end
it 'should check errors 5' do
client.stubs.get('/api/accounts/accountId/test') {|env| [404, {}, '']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
expect{V2::Message.send(:make_iris_request, {user_name: 'user', password: 'password', account_id: 'accountId'}, :get, '/test')}.to raise_error(Errors::GenericIrisError)
end
end
describe '#create_application' do
it 'should make create a messaging application' do
client.stubs.post('/api/accounts/accountId/applications', '<Application><AppName>Test</AppName><CallbackUrl>url</CallbackUrl><CallBackCreds></CallBackCreds></Application>') {|env| [200, {}, '<ApplicationProvisioningResponse><Application><ApplicationId>id</ApplicationId></Application></ApplicationProvisioningResponse>']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
id = V2::Message.send(:create_application, {user_name: 'user', password: 'password', account_id: 'accountId'}, {name: 'Test', callback_url: 'url'})
expect(id).to eql("id")
end
end
describe '#create_location' do
it 'should make create a location' do
client.stubs.post('/api/accounts/accountId/sites/subaccountId/sippeers', '<SipPeer><PeerName>current</PeerName><IsDefaultPeer>false</IsDefaultPeer></SipPeer>') {|env| [201, {'Location' => 'httpl//localhoost/id'}, '']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
id = V2::Message.send(:create_location, {user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {location_name: 'current', is_default_location: false})
expect(id).to eql("id")
end
end
describe '#enable_sms' do
it 'should change sms settings' do
client.stubs.post('/api/accounts/accountId/sites/subaccountId/sippeers/locationId/products/messaging/features/sms', '<SipPeerSmsFeature><SipPeerSmsFeatureSettings><TollFree>true</TollFree><ShortCode>false</ShortCode><Protocol>HTTP</Protocol><Zone1>true</Zone1><Zone2>false</Zone2><Zone3>false</Zone3><Zone4>false</Zone4><Zone5>false</Zone5></SipPeerSmsFeatureSettings><HttpSettings><ProxyPeerId>539692</ProxyPeerId></HttpSettings></SipPeerSmsFeature>') {|env| [201, {}, '']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
V2::Message.send(:enable_sms, {user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {toll_free_enabled: true}, {application_id: 'appId', location_id: 'locationId'})
end
it 'should do nothing when enabled=false' do
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
V2::Message.send(:enable_sms, {user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {enabled: false}, {application_id: 'appId', location_id: 'locationId'})
end
end
describe '#enable_mms' do
it 'should change mms settings' do
client.stubs.post('/api/accounts/accountId/sites/subaccountId/sippeers/locationId/products/messaging/features/mms', '<MmsFeature><MmsSettings><protocol>HTTP</protocol></MmsSettings><Protocols><HTTP><HttpSettings><ProxyPeerId>539692</ProxyPeerId></HttpSettings></HTTP></Protocols></MmsFeature>') {|env| [201, {}, '']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
V2::Message.send(:enable_mms, {user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {enabled: true}, {application_id: 'appId', location_id: 'locationId'})
end
it 'should do nothing when enabled=false' do
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
V2::Message.send(:enable_mms, {user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {enabled: false}, {application_id: 'appId', location_id: 'locationId'})
end
end
describe '#assign_application_to_location' do
it 'should assign application to location' do
client.stubs.put('/api/accounts/accountId/sites/subaccountId/sippeers/locationId/products/messaging/applicationSettings', '<ApplicationsSettings><HttpMessagingV2AppId>appId</HttpMessagingV2AppId></ApplicationsSettings>') {|env| [200, {}, '']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
V2::Message.send(:assign_application_to_location, {user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {application_id: 'appId', location_id: 'locationId'})
end
end
describe '#create_messaging_application' do
it 'should make create a messaging application and location' do
client.stubs.post('/api/accounts/accountId/applications', '<Application><AppName>Test</AppName><CallbackUrl>url</CallbackUrl><CallBackCreds></CallBackCreds></Application>') {|env| [200, {}, '<ApplicationProvisioningResponse><Application><ApplicationId>id</ApplicationId></Application></ApplicationProvisioningResponse>']}
client.stubs.post('/api/accounts/accountId/sites/subaccountId/sippeers', '<SipPeer><PeerName>current</PeerName><IsDefaultPeer>false</IsDefaultPeer></SipPeer>') {|env| [201, {'Location' => 'httpl//localhoost/locationId'}, '']}
client.stubs.post('/api/accounts/accountId/sites/subaccountId/sippeers/locationId/products/messaging/features/sms', '<SipPeerSmsFeature><SipPeerSmsFeatureSettings><TollFree>true</TollFree><ShortCode>false</ShortCode><Protocol>HTTP</Protocol><Zone1>true</Zone1><Zone2>false</Zone2><Zone3>false</Zone3><Zone4>false</Zone4><Zone5>false</Zone5></SipPeerSmsFeatureSettings><HttpSettings><ProxyPeerId>539692</ProxyPeerId></HttpSettings></SipPeerSmsFeature>') {|env| [201, {}, '']}
client.stubs.post('/api/accounts/accountId/sites/subaccountId/sippeers/locationId/products/messaging/features/mms', '<MmsFeature><MmsSettings><protocol>HTTP</protocol></MmsSettings><Protocols><HTTP><HttpSettings><ProxyPeerId>539692</ProxyPeerId></HttpSettings></HTTP></Protocols></MmsFeature>') {|env| [201, {}, '']}
client.stubs.put('/api/accounts/accountId/sites/subaccountId/sippeers/locationId/products/messaging/applicationSettings', '<ApplicationsSettings><HttpMessagingV2AppId>id</HttpMessagingV2AppId></ApplicationsSettings>') {|env| [200, {}, '']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
app = V2::Message.create_messaging_application({user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {name: 'Test', callback_url: 'url', location_name: 'current', is_default_location: false, sms_options: {toll_free_enabled: true}, mms_options: {enabled: true}})
expect(app[:application_id]).to eql("id")
expect(app[:location_id]).to eql("locationId")
end
end
describe '#search_and_order_numbers' do
it 'should search and order numbers' do
order_response = '<OrderResponse><CompletedQuantity>1</CompletedQuantity><CreatedByUser>lorem</CreatedByUser><LastModifiedDate>2017-09-18T17:36:57.411Z</LastModifiedDate><OrderCompleteDate>2017-09-18T17:36:57.410Z</OrderCompleteDate><Order><OrderCreateDate>2017-09-18T17:36:57.274Z</OrderCreateDate><PeerId>{{location}}</PeerId><BackOrderRequested>false</BackOrderRequested><AreaCodeSearchAndOrderType><AreaCode>910</AreaCode><Quantity>2</Quantity></AreaCodeSearchAndOrderType><PartialAllowed>true</PartialAllowed><SiteId>{{subaccount}}</SiteId></Order><OrderStatus>COMPLETE</OrderStatus><CompletedNumbers><TelephoneNumber><FullNumber>9102398766</FullNumber></TelephoneNumber><TelephoneNumber><FullNumber>9102398767</FullNumber></TelephoneNumber></CompletedNumbers><Summary>1 number ordered in (910)</Summary><FailedQuantity>0</FailedQuantity></OrderResponse>'
client.stubs.post('/api/accounts/accountId/orders', '<Order><AreaCodeSearchAndOrderType><AreaCode>910</AreaCode><Quantity>2</Quantity></AreaCodeSearchAndOrderType><SiteId>subaccountId</SiteId><PeerId>locationId</PeerId></Order>') {|env| [200, {}, '<OrderResponse><Order><OrderCreateDate>2017-09-18T17:36:57.274Z</OrderCreateDate><PeerId>{{location}}</PeerId><BackOrderRequested>false</BackOrderRequested><id>orderId</id><AreaCodeSearchAndOrderType><AreaCode>910</AreaCode><Quantity>1</Quantity></AreaCodeSearchAndOrderType><PartialAllowed>true</PartialAllowed><SiteId>{{subaccount}}</SiteId></Order><OrderStatus>RECEIVED</OrderStatus></OrderResponse>']}
client.stubs.get('/api/accounts/accountId/orders/orderId'){|env| [200, {}, order_response]}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
numbers = V2::Message.search_and_order_numbers({user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {application_id: 'id', location_id: 'locationId'}) do |query|
query.AreaCodeSearchAndOrderType do |b|
b.AreaCode("910")
b.Quantity(2)
end
end
expect(numbers.size).to eql(2)
end
end
end
Fixed unit tests
describe Bandwidth::V2::Message do
client = nil
before :each do
client = Helper.get_client()
end
after :each do
client.stubs.verify_stubbed_calls()
end
describe '#create' do
it 'should create new item' do
client.stubs.post('/api/v2/users/userId/messages', '{"text":"hello"}') {|env| [202, {}, '{"id": "messageId"}']}
expect(V2::Message.create(client, {:text=>'hello'})).to eql({id: 'messageId'})
end
end
describe '#create_iris_request' do
it 'should create Faraday instance for Bandwidth dashboard' do
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
connection = V2::Message.send(:create_iris_request, {user_name: 'user', password: 'password'})
expect(connection.headers["Authorization"]).to eql("Basic dXNlcjpwYXNzd29yZA==")
expect(connection.headers["Accept"]).to eql("application/xml")
end
end
describe '#make_iris_request' do
it 'should make http request to dashboard' do
client.stubs.get('/api/accounts/accountId/test') {|env| [200, {}, '<Response>test</Response>']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
r = V2::Message.send(:make_iris_request, {user_name: 'user', password: 'password', account_id: 'accountId'}, :get, '/test')
expect(r[0]).to eql("test")
end
end
describe '#check_response' do
it 'should check errors 1' do
client.stubs.get('/api/accounts/accountId/test') {|env| [200, {}, '<Response><ErrorCode>Code</ErrorCode><Description>Description</Description></Response>']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
expect{V2::Message.send(:make_iris_request, {user_name: 'user', password: 'password', account_id: 'accountId'}, :get, '/test')}.to raise_error(Errors::GenericIrisError)
end
it 'should check errors 2' do
client.stubs.get('/api/accounts/accountId/test') {|env| [200, {}, '<Response><Error><Code>Code</Code><Description>Description</Description></Error></Response>']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
expect{V2::Message.send(:make_iris_request, {user_name: 'user', password: 'password', account_id: 'accountId'}, :get, '/test')}.to raise_error(Errors::GenericIrisError)
end
it 'should check errors 3' do
client.stubs.get('/api/accounts/accountId/test') {|env| [200, {}, '<Response><Errors><Code>Code</Code><Description>Description</Description></Errors></Response>']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
expect{V2::Message.send(:make_iris_request, {user_name: 'user', password: 'password', account_id: 'accountId'}, :get, '/test')}.to raise_error(Errors::AgregateError)
end
it 'should check errors 4' do
client.stubs.get('/api/accounts/accountId/test') {|env| [200, {}, '<Response><resultCode>Code</resultCode><resultMessage>Description</resultMessage></Response>']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
expect{V2::Message.send(:make_iris_request, {user_name: 'user', password: 'password', account_id: 'accountId'}, :get, '/test')}.to raise_error(Errors::GenericIrisError)
end
it 'should check errors 5' do
client.stubs.get('/api/accounts/accountId/test') {|env| [404, {}, '']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
expect{V2::Message.send(:make_iris_request, {user_name: 'user', password: 'password', account_id: 'accountId'}, :get, '/test')}.to raise_error(Errors::GenericIrisError)
end
end
describe '#create_application' do
it 'should make create a messaging application' do
client.stubs.post('/api/accounts/accountId/applications', '<Application><AppName>Test</AppName><CallbackUrl>url</CallbackUrl><CallBackCreds></CallBackCreds></Application>') {|env| [200, {}, '<ApplicationProvisioningResponse><Application><ApplicationId>id</ApplicationId></Application></ApplicationProvisioningResponse>']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
id = V2::Message.send(:create_application, {user_name: 'user', password: 'password', account_id: 'accountId'}, {name: 'Test', callback_url: 'url'})
expect(id).to eql("id")
end
end
describe '#create_location' do
it 'should make create a location' do
client.stubs.post('/api/accounts/accountId/sites/subaccountId/sippeers', '<SipPeer><PeerName>current</PeerName><IsDefaultPeer>false</IsDefaultPeer></SipPeer>') {|env| [201, {'Location' => 'httpl//localhoost/id'}, '']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
id = V2::Message.send(:create_location, {user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {location_name: 'current', is_default_location: false})
expect(id).to eql("id")
end
end
describe '#enable_sms' do
it 'should change sms settings' do
client.stubs.post('/api/accounts/accountId/sites/subaccountId/sippeers/locationId/products/messaging/features/sms', '<SipPeerSmsFeature><SipPeerSmsFeatureSettings><TollFree>true</TollFree><ShortCode>false</ShortCode><Protocol>HTTP</Protocol><Zone1>true</Zone1><Zone2>false</Zone2><Zone3>false</Zone3><Zone4>false</Zone4><Zone5>false</Zone5></SipPeerSmsFeatureSettings><HttpSettings><ProxyPeerId></ProxyPeerId></HttpSettings></SipPeerSmsFeature>') {|env| [201, {}, '']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
V2::Message.send(:enable_sms, {user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {toll_free_enabled: true}, {application_id: 'appId', location_id: 'locationId'})
end
it 'should do nothing when enabled=false' do
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
V2::Message.send(:enable_sms, {user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {enabled: false}, {application_id: 'appId', location_id: 'locationId'})
end
end
describe '#enable_mms' do
it 'should change mms settings' do
client.stubs.post('/api/accounts/accountId/sites/subaccountId/sippeers/locationId/products/messaging/features/mms', '<MmsFeature><MmsSettings><Protocol>HTTP</Protocol></MmsSettings><Protocols><HTTP><HttpSettings><ProxyPeerId></ProxyPeerId></HttpSettings></HTTP></Protocols></MmsFeature>') {|env| [201, {}, '']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
V2::Message.send(:enable_mms, {user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {enabled: true}, {application_id: 'appId', location_id: 'locationId'})
end
it 'should do nothing when enabled=false' do
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
V2::Message.send(:enable_mms, {user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {enabled: false}, {application_id: 'appId', location_id: 'locationId'})
end
end
describe '#assign_application_to_location' do
it 'should assign application to location' do
client.stubs.put('/api/accounts/accountId/sites/subaccountId/sippeers/locationId/products/messaging/applicationSettings', '<ApplicationsSettings><HttpMessagingV2AppId>appId</HttpMessagingV2AppId></ApplicationsSettings>') {|env| [200, {}, '']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
V2::Message.send(:assign_application_to_location, {user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {application_id: 'appId', location_id: 'locationId'})
end
end
describe '#create_messaging_application' do
it 'should make create a messaging application and location' do
client.stubs.post('/api/accounts/accountId/applications', '<Application><AppName>Test</AppName><CallbackUrl>url</CallbackUrl><CallBackCreds></CallBackCreds></Application>') {|env| [200, {}, '<ApplicationProvisioningResponse><Application><ApplicationId>id</ApplicationId></Application></ApplicationProvisioningResponse>']}
client.stubs.post('/api/accounts/accountId/sites/subaccountId/sippeers', '<SipPeer><PeerName>current</PeerName><IsDefaultPeer>false</IsDefaultPeer></SipPeer>') {|env| [201, {'Location' => 'httpl//localhoost/locationId'}, '']}
client.stubs.post('/api/accounts/accountId/sites/subaccountId/sippeers/locationId/products/messaging/features/sms', '<SipPeerSmsFeature><SipPeerSmsFeatureSettings><TollFree>true</TollFree><ShortCode>false</ShortCode><Protocol>HTTP</Protocol><Zone1>true</Zone1><Zone2>false</Zone2><Zone3>false</Zone3><Zone4>false</Zone4><Zone5>false</Zone5></SipPeerSmsFeatureSettings><HttpSettings><ProxyPeerId></ProxyPeerId></HttpSettings></SipPeerSmsFeature>') {|env| [201, {}, '']}
client.stubs.post('/api/accounts/accountId/sites/subaccountId/sippeers/locationId/products/messaging/features/mms', '<MmsFeature><MmsSettings><Protocol>HTTP</Protocol></MmsSettings><Protocols><HTTP><HttpSettings><ProxyPeerId></ProxyPeerId></HttpSettings></HTTP></Protocols></MmsFeature>') {|env| [201, {}, '']}
client.stubs.put('/api/accounts/accountId/sites/subaccountId/sippeers/locationId/products/messaging/applicationSettings', '<ApplicationsSettings><HttpMessagingV2AppId>id</HttpMessagingV2AppId></ApplicationsSettings>') {|env| [200, {}, '']}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
app = V2::Message.create_messaging_application({user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {name: 'Test', callback_url: 'url', location_name: 'current', is_default_location: false, sms_options: {toll_free_enabled: true}, mms_options: {enabled: true}})
expect(app[:application_id]).to eql("id")
expect(app[:location_id]).to eql("locationId")
end
end
describe '#search_and_order_numbers' do
it 'should search and order numbers' do
order_response = '<OrderResponse><CompletedQuantity>1</CompletedQuantity><CreatedByUser>lorem</CreatedByUser><LastModifiedDate>2017-09-18T17:36:57.411Z</LastModifiedDate><OrderCompleteDate>2017-09-18T17:36:57.410Z</OrderCompleteDate><Order><OrderCreateDate>2017-09-18T17:36:57.274Z</OrderCreateDate><PeerId>{{location}}</PeerId><BackOrderRequested>false</BackOrderRequested><AreaCodeSearchAndOrderType><AreaCode>910</AreaCode><Quantity>2</Quantity></AreaCodeSearchAndOrderType><PartialAllowed>true</PartialAllowed><SiteId>{{subaccount}}</SiteId></Order><OrderStatus>COMPLETE</OrderStatus><CompletedNumbers><TelephoneNumber><FullNumber>9102398766</FullNumber></TelephoneNumber><TelephoneNumber><FullNumber>9102398767</FullNumber></TelephoneNumber></CompletedNumbers><Summary>1 number ordered in (910)</Summary><FailedQuantity>0</FailedQuantity></OrderResponse>'
client.stubs.post('/api/accounts/accountId/orders', '<Order><AreaCodeSearchAndOrderType><AreaCode>910</AreaCode><Quantity>2</Quantity></AreaCodeSearchAndOrderType><SiteId>subaccountId</SiteId><PeerId>locationId</PeerId></Order>') {|env| [200, {}, '<OrderResponse><Order><OrderCreateDate>2017-09-18T17:36:57.274Z</OrderCreateDate><PeerId>{{location}}</PeerId><BackOrderRequested>false</BackOrderRequested><id>orderId</id><AreaCodeSearchAndOrderType><AreaCode>910</AreaCode><Quantity>1</Quantity></AreaCodeSearchAndOrderType><PartialAllowed>true</PartialAllowed><SiteId>{{subaccount}}</SiteId></Order><OrderStatus>RECEIVED</OrderStatus></OrderResponse>']}
client.stubs.get('/api/accounts/accountId/orders/orderId'){|env| [200, {}, order_response]}
V2::Message.send(:configure_connection, lambda {|faraday| faraday.adapter(:test, client.stubs)})
numbers = V2::Message.search_and_order_numbers({user_name: 'user', password: 'password', account_id: 'accountId', subaccount_id: 'subaccountId'}, {application_id: 'id', location_id: 'locationId'}) do |query|
query.AreaCodeSearchAndOrderType do |b|
b.AreaCode("910")
b.Quantity(2)
end
end
expect(numbers.size).to eql(2)
end
end
end
|
require 'spec_helper'
shared_examples_for "triggering events registered for an instance" do |target|
scope = target == :class ? :instance : :itself
shared_examples "triggering event" do |event|
context "when triggering event #{event.inspect}" do
subject { instance.trigger(event, :arg) }
before { expect(callback).to receive(:call).with(__send__(scope), [:arg]) }
it { expect{ subject }.not_to raise_error }
end
end
let(:callback) { proc{} }
context "when a callback is attached for a single event" do
before do
callback = self.callback
instance.__send__(target).on(:event){ |*args| callback.call(self, args) }
end
include_examples "triggering event", :event
end
context "when a callback is attached for multiple events" do
before do
callback = self.callback
instance.__send__(target).on(:event1, :event2){ |*args| callback.call(self, args) }
end
include_examples "triggering event", :event1
include_examples "triggering event", :event2
end
end
describe "CallbacksAttachable included into a regular class" do
subject(:instance) { klass.new }
let!(:klass) { Class.new{ include CallbacksAttachable } }
include_examples "triggering events registered for an instance", :class
include_examples "triggering events registered for an instance", :singleton_class
include_examples "triggering events registered for an instance", :itself
end
describe "CallbacksAttachable included into a singleton class" do
subject(:instance) { Object.new.extend CallbacksAttachable }
before { instance.singleton_class.class_eval{ include CallbacksAttachable } }
include_examples "triggering events registered for an instance", :singleton_class
include_examples "triggering events registered for an instance", :itself
end
describe "CallbacksAttachable extending an object" do
subject(:instance) { Object.new.extend CallbacksAttachable }
include_examples "triggering events registered for an instance", :singleton_class
include_examples "triggering events registered for an instance", :itself
end
fixed redefinition of shared examples
require 'spec_helper'
shared_examples "triggering event" do |event, scope|
context "when triggering event #{event.inspect}" do
subject { instance.trigger(event, :arg) }
before { expect(callback).to receive(:call).with(__send__(scope), [:arg]) }
it { expect{ subject }.not_to raise_error }
end
end
shared_examples_for "triggering events registered for an instance" do |target|
scope = target == :class ? :instance : :itself
let(:callback) { proc{} }
context "when a callback is attached for a single event" do
before do
callback = self.callback
instance.__send__(target).on(:event){ |*args| callback.call(self, args) }
end
include_examples "triggering event", :event, scope
end
context "when a callback is attached for multiple events" do
before do
callback = self.callback
instance.__send__(target).on(:event1, :event2){ |*args| callback.call(self, args) }
end
include_examples "triggering event", :event1, scope
include_examples "triggering event", :event2, scope
end
end
describe "CallbacksAttachable included into a regular class" do
subject(:instance) { klass.new }
let!(:klass) { Class.new{ include CallbacksAttachable } }
include_examples "triggering events registered for an instance", :class
include_examples "triggering events registered for an instance", :singleton_class
include_examples "triggering events registered for an instance", :itself
end
describe "CallbacksAttachable included into a singleton class" do
subject(:instance) { Object.new.extend CallbacksAttachable }
before { instance.singleton_class.class_eval{ include CallbacksAttachable } }
include_examples "triggering events registered for an instance", :singleton_class
include_examples "triggering events registered for an instance", :itself
end
describe "CallbacksAttachable extending an object" do
subject(:instance) { Object.new.extend CallbacksAttachable }
include_examples "triggering events registered for an instance", :singleton_class
include_examples "triggering events registered for an instance", :itself
end
|
require_relative '../spec_helper'
describe Careerbuilder::Client do
context '#get' do
it 'passes in query params'
end
end
add specs titles to client
require_relative '../spec_helper'
describe Careerbuilder::Client do
let(:url) { 'example' }
let(:params) { {test: 123} }
let(:api_token) do
"#{Careerbuilder.configuration.api_token}"
end
context '#get' do
it 'merges api_token with query params'
it 'passes in query params'
end
end
|
require 'spec_helper'
describe Hbc::Artifact::Binary do
let(:cask) {
Hbc.load('with-binary').tap do |cask|
shutup do
InstallHelper::install_without_artifacts(cask)
end
end
}
let(:expected_path) {
Hbc.binarydir.join('binary')
}
after(:each) {
if expected_path.exist?
FileUtils.rm expected_path
end
}
it "links the binary to the proper directory" do
shutup do
Hbc::Artifact::Binary.new(cask).install_phase
end
expect(FileHelper.valid_alias?(expected_path)).to be true
end
it "avoids clobbering an existing binary by linking over it" do
FileUtils.touch expected_path
shutup do
Hbc::Artifact::Binary.new(cask).install_phase
end
expect(expected_path).to_not be :symlink?
end
it "clobbers an existing symlink" do
expected_path.make_symlink('/tmp')
shutup do
Hbc::Artifact::Binary.new(cask).install_phase
end
expect(File.readlink(expected_path)).not_to eq('/tmp')
end
it "respects --no-binaries flag" do
Hbc.no_binaries = true
shutup do
Hbc::Artifact::Binary.new(cask).install_phase
end
expect(expected_path.exist?).to be false
Hbc.no_binaries = false
end
end
Add test for creating binarydir if it doesn't exist
require 'spec_helper'
describe Hbc::Artifact::Binary do
let(:cask) {
Hbc.load('with-binary').tap do |cask|
shutup do
InstallHelper::install_without_artifacts(cask)
end
end
}
let(:expected_path) {
Hbc.binarydir.join('binary')
}
after(:each) {
if expected_path.exist?
FileUtils.rm expected_path
end
}
it "links the binary to the proper directory" do
shutup do
Hbc::Artifact::Binary.new(cask).install_phase
end
expect(FileHelper.valid_alias?(expected_path)).to be true
end
it "avoids clobbering an existing binary by linking over it" do
FileUtils.touch expected_path
shutup do
Hbc::Artifact::Binary.new(cask).install_phase
end
expect(expected_path).to_not be :symlink?
end
it "clobbers an existing symlink" do
expected_path.make_symlink('/tmp')
shutup do
Hbc::Artifact::Binary.new(cask).install_phase
end
expect(File.readlink(expected_path)).not_to eq('/tmp')
end
it "respects --no-binaries flag" do
Hbc.no_binaries = true
shutup do
Hbc::Artifact::Binary.new(cask).install_phase
end
expect(expected_path.exist?).to be false
Hbc.no_binaries = false
end
it "creates parent directory if it doesn't exist" do
FileUtils.rmdir Hbc.binarydir
shutup do
Hbc::Artifact::Binary.new(cask).install_phase
end
expect(expected_path.exist?).to be true
end
end
|
Add in a place to stick specs for the Cucumber integration.
# (c) Copyright 2006-2008 Nick Sieger <nicksieger@gmail.com>
# See the file LICENSE.txt included with the distribution for
# software license details.
require File.dirname(__FILE__) + "/../../spec_helper.rb"
require 'stringio'
describe "The Cucumber reporter" do
it "should work"
end
|
RSpec.shared_examples 'exchanger method with indefinite timeout' do
before(:each) do
subject # ensure proper initialization
end
it 'blocks indefinitely' do
latch_1 = Concurrent::CountDownLatch.new
latch_2 = Concurrent::CountDownLatch.new
in_thread do
latch_1.count_down
subject.send(method, 1)
latch_2.count_down
end
latch_1.wait(1)
latch_2.wait(0.1)
expect(latch_1.count).to eq 0
expect(latch_2.count).to eq 1
end
it 'receives the other value' do
first_value = nil
second_value = nil
latch = Concurrent::CountDownLatch.new(2)
in_thread { first_value = subject.send(method, 2); latch.count_down }
in_thread { second_value = subject.send(method, 4); latch.count_down }
latch.wait(1)
expect(get_value(first_value)).to eq 4
expect(get_value(second_value)).to eq 2
end
it 'can be reused' do
first_value = nil
second_value = nil
latch_1 = Concurrent::CountDownLatch.new(2)
latch_2 = Concurrent::CountDownLatch.new(2)
in_thread { first_value = subject.send(method, 1); latch_1.count_down }
in_thread { second_value = subject.send(method, 0); latch_1.count_down }
latch_1.wait(1)
in_thread { first_value = subject.send(method, 10); latch_2.count_down }
in_thread { second_value = subject.send(method, 12); latch_2.count_down }
latch_2.wait(1)
expect(get_value(first_value)).to eq 12
expect(get_value(second_value)).to eq 10
end
end
RSpec.shared_examples 'exchanger method with finite timeout' do
it 'blocks until timeout' do
duration = Concurrent::TestHelpers.monotonic_interval do
begin
subject.send(method, 2, 0.1)
rescue Concurrent::TimeoutError
# do nothing
end
end
expect(duration).to be_within(0.05).of(0.1)
end
it 'receives the other value' do
first_value = nil
second_value = nil
latch = Concurrent::CountDownLatch.new(2)
in_thread { first_value = subject.send(method, 2, 1); latch.count_down }
in_thread { second_value = subject.send(method, 4, 1); latch.count_down }
latch.wait(1)
expect(get_value(first_value)).to eq 4
expect(get_value(second_value)).to eq 2
end
it 'can be reused' do
first_value = nil
second_value = nil
latch_1 = Concurrent::CountDownLatch.new(2)
latch_2 = Concurrent::CountDownLatch.new(2)
in_thread { first_value = subject.send(method, 1, 1); latch_1.count_down }
in_thread { second_value = subject.send(method, 0, 1); latch_1.count_down }
latch_1.wait(1)
in_thread { first_value = subject.send(method, 10, 1); latch_2.count_down }
in_thread { second_value = subject.send(method, 12, 1); latch_2.count_down }
latch_2.wait(1)
expect(get_value(first_value)).to eq 12
expect(get_value(second_value)).to eq 10
end
end
RSpec.shared_examples 'exchanger method cross-thread interactions' do
it 'when first, waits for a second' do
first_value = nil
second_value = nil
latch = Concurrent::CountDownLatch.new(1)
t1 = in_thread do
first_value = subject.send(method, :foo, 1)
latch.count_down
end
t1.join(0.1)
second_value = subject.send(method, :bar, 0)
latch.wait(1)
expect(get_value(first_value)).to eq :bar
expect(get_value(second_value)).to eq :foo
end
it 'allows multiple firsts to cancel if necessary', buggy: true do
first_value = nil
second_value = nil
cancels = 3
cancel_latch = Concurrent::CountDownLatch.new(cancels)
success_latch = Concurrent::CountDownLatch.new(1)
threads = cancels.times.collect do
in_thread do
begin
first_value = subject.send(method, :foo, 0.1)
rescue Concurrent::TimeoutError
# suppress
ensure
cancel_latch.count_down
end
end
end
threads.each { |t| t.join(1) }
cancel_latch.wait(1)
t1 = in_thread do
first_value = subject.send(method, :bar, 1)
success_latch.count_down
end
t1.join(0.1)
second_value = subject.send(method, :baz, 0)
success_latch.wait(1)
expect(get_value(first_value)).to eq :baz
expect(get_value(second_value)).to eq :bar
end
end
RSpec.shared_examples :exchanger do
context '#exchange' do
let!(:method) { :exchange }
def get_value(result)
result
end
it_behaves_like 'exchanger method with indefinite timeout'
it_behaves_like 'exchanger method with finite timeout'
it_behaves_like 'exchanger method cross-thread interactions'
end
context '#exchange!' do
let!(:method) { :exchange! }
def get_value(result)
result
end
it_behaves_like 'exchanger method with indefinite timeout'
it_behaves_like 'exchanger method with finite timeout'
it_behaves_like 'exchanger method cross-thread interactions'
end
context '#try_exchange' do
let!(:method) { :try_exchange }
def get_value(result)
result.value
end
it_behaves_like 'exchanger method with indefinite timeout'
it_behaves_like 'exchanger method with finite timeout'
it_behaves_like 'exchanger method cross-thread interactions'
end
end
module Concurrent
RSpec.describe RubyExchanger do
it_behaves_like :exchanger
if Concurrent.on_cruby?
specify 'stress test', notravis: true do
thread_count = 100
exchange_count = 100
latch = Concurrent::CountDownLatch.new(thread_count)
good = Concurrent::AtomicFixnum.new(0)
bad = Concurrent::AtomicFixnum.new(0)
ugly = Concurrent::AtomicFixnum.new(0)
thread_count.times.collect do |i|
in_thread do
exchange_count.times do |j|
begin
result = subject.exchange!(i, 1)
result == i ? ugly.up : good.up
rescue Concurrent::TimeoutError
bad.up
end
end
latch.count_down
end
end
latch.wait
puts "Good: #{good.value}, Bad (timeout): #{bad.value}, Ugly: #{ugly.value}"
expect(good.value + bad.value + ugly.value).to eq thread_count * exchange_count
expect(ugly.value).to eq 0
end
end
end
if defined? JavaExchanger
RSpec.describe JavaExchanger do
it_behaves_like :exchanger
end
end
RSpec.describe Exchanger do
context 'class hierarchy' do
if Concurrent.on_jruby?
it 'inherits from JavaExchanger' do
expect(Exchanger.ancestors).to include(JavaExchanger)
end
else
it 'inherits from RubyExchanger' do
expect(Exchanger.ancestors).to include(RubyExchanger)
end
end
end
end
end
rename to avoid IDE confusion
RSpec.shared_examples 'exchanger method with indefinite timeout' do
before(:each) do
subject # ensure proper initialization
end
it 'blocks indefinitely' do
latch_1 = Concurrent::CountDownLatch.new
latch_2 = Concurrent::CountDownLatch.new
in_thread do
latch_1.count_down
subject.send(method_name, 1)
latch_2.count_down
end
latch_1.wait(1)
latch_2.wait(0.1)
expect(latch_1.count).to eq 0
expect(latch_2.count).to eq 1
end
it 'receives the other value' do
first_value = nil
second_value = nil
latch = Concurrent::CountDownLatch.new(2)
in_thread { first_value = subject.send(method_name, 2); latch.count_down }
in_thread { second_value = subject.send(method_name, 4); latch.count_down }
latch.wait(1)
expect(get_value(first_value)).to eq 4
expect(get_value(second_value)).to eq 2
end
it 'can be reused' do
first_value = nil
second_value = nil
latch_1 = Concurrent::CountDownLatch.new(2)
latch_2 = Concurrent::CountDownLatch.new(2)
in_thread { first_value = subject.send(method_name, 1); latch_1.count_down }
in_thread { second_value = subject.send(method_name, 0); latch_1.count_down }
latch_1.wait(1)
in_thread { first_value = subject.send(method_name, 10); latch_2.count_down }
in_thread { second_value = subject.send(method_name, 12); latch_2.count_down }
latch_2.wait(1)
expect(get_value(first_value)).to eq 12
expect(get_value(second_value)).to eq 10
end
end
RSpec.shared_examples 'exchanger method with finite timeout' do
it 'blocks until timeout' do
duration = Concurrent::TestHelpers.monotonic_interval do
begin
subject.send(method_name, 2, 0.1)
rescue Concurrent::TimeoutError
# do nothing
end
end
expect(duration).to be_within(0.05).of(0.1)
end
it 'receives the other value' do
first_value = nil
second_value = nil
latch = Concurrent::CountDownLatch.new(2)
in_thread { first_value = subject.send(method_name, 2, 1); latch.count_down }
in_thread { second_value = subject.send(method_name, 4, 1); latch.count_down }
latch.wait(1)
expect(get_value(first_value)).to eq 4
expect(get_value(second_value)).to eq 2
end
it 'can be reused' do
first_value = nil
second_value = nil
latch_1 = Concurrent::CountDownLatch.new(2)
latch_2 = Concurrent::CountDownLatch.new(2)
in_thread { first_value = subject.send(method_name, 1, 1); latch_1.count_down }
in_thread { second_value = subject.send(method_name, 0, 1); latch_1.count_down }
latch_1.wait(1)
in_thread { first_value = subject.send(method_name, 10, 1); latch_2.count_down }
in_thread { second_value = subject.send(method_name, 12, 1); latch_2.count_down }
latch_2.wait(1)
expect(get_value(first_value)).to eq 12
expect(get_value(second_value)).to eq 10
end
end
RSpec.shared_examples 'exchanger method cross-thread interactions' do
it 'when first, waits for a second' do
first_value = nil
second_value = nil
latch = Concurrent::CountDownLatch.new(1)
t1 = in_thread do
first_value = subject.send(method_name, :foo, 1)
latch.count_down
end
t1.join(0.1)
second_value = subject.send(method_name, :bar, 0)
latch.wait(1)
expect(get_value(first_value)).to eq :bar
expect(get_value(second_value)).to eq :foo
end
it 'allows multiple firsts to cancel if necessary', buggy: true do
first_value = nil
second_value = nil
cancels = 3
cancel_latch = Concurrent::CountDownLatch.new(cancels)
success_latch = Concurrent::CountDownLatch.new(1)
threads = cancels.times.collect do
in_thread do
begin
first_value = subject.send(method_name, :foo, 0.1)
rescue Concurrent::TimeoutError
# suppress
ensure
cancel_latch.count_down
end
end
end
threads.each { |t| t.join(1) }
cancel_latch.wait(1)
t1 = in_thread do
first_value = subject.send(method_name, :bar, 1)
success_latch.count_down
end
t1.join(0.1)
second_value = subject.send(method_name, :baz, 0)
success_latch.wait(1)
expect(get_value(first_value)).to eq :baz
expect(get_value(second_value)).to eq :bar
end
end
RSpec.shared_examples :exchanger do
context '#exchange' do
let!(:method_name) { :exchange }
def get_value(result)
result
end
it_behaves_like 'exchanger method with indefinite timeout'
it_behaves_like 'exchanger method with finite timeout'
it_behaves_like 'exchanger method cross-thread interactions'
end
context '#exchange!' do
let!(:method_name) { :exchange! }
def get_value(result)
result
end
it_behaves_like 'exchanger method with indefinite timeout'
it_behaves_like 'exchanger method with finite timeout'
it_behaves_like 'exchanger method cross-thread interactions'
end
context '#try_exchange' do
let!(:method_name) { :try_exchange }
def get_value(result)
result.value
end
it_behaves_like 'exchanger method with indefinite timeout'
it_behaves_like 'exchanger method with finite timeout'
it_behaves_like 'exchanger method cross-thread interactions'
end
end
module Concurrent
RSpec.describe RubyExchanger do
it_behaves_like :exchanger
if Concurrent.on_cruby?
specify 'stress test', notravis: true do
thread_count = 100
exchange_count = 100
latch = Concurrent::CountDownLatch.new(thread_count)
good = Concurrent::AtomicFixnum.new(0)
bad = Concurrent::AtomicFixnum.new(0)
ugly = Concurrent::AtomicFixnum.new(0)
thread_count.times.collect do |i|
in_thread do
exchange_count.times do |j|
begin
result = subject.exchange!(i, 1)
result == i ? ugly.up : good.up
rescue Concurrent::TimeoutError
bad.up
end
end
latch.count_down
end
end
latch.wait
puts "Good: #{good.value}, Bad (timeout): #{bad.value}, Ugly: #{ugly.value}"
expect(good.value + bad.value + ugly.value).to eq thread_count * exchange_count
expect(ugly.value).to eq 0
end
end
end
if defined? JavaExchanger
RSpec.describe JavaExchanger do
it_behaves_like :exchanger
end
end
RSpec.describe Exchanger do
context 'class hierarchy' do
if Concurrent.on_jruby?
it 'inherits from JavaExchanger' do
expect(Exchanger.ancestors).to include(JavaExchanger)
end
else
it 'inherits from RubyExchanger' do
expect(Exchanger.ancestors).to include(RubyExchanger)
end
end
end
end
end
|
test: add test for tagging pacticipant version
describe "tagging a pacticipant version" do
let(:path) { "/pacticipants/Foo/versions/1.2.3/tags/feat%2Fbar" }
subject { put path,nil, {'CONTENT_TYPE' => 'application/json'}; last_response }
context "when the pacticipant/version/tag do not exist" do
it "creates a tag" do
expect{ subject }.to change {
PactBroker::Domain::Tag.where(name: 'feat/bar').count
}.by(1)
end
end
end
|
require 'spec_helper'
describe Feedson::FeedToJson do
def initialize_converter(file_name, doc_config)
feed_path = File.join("spec/examples", file_name)
feed = File.read(feed_path)
Feedson::FeedToJson.new(feed, doc_config: doc_config)
end
let(:rss_doc_config) do
Feedson::RssConfig.new
end
let(:atom_doc_config) do
Feedson::AtomConfig.new
end
context "with very simple RSS feed" do
subject(:converter) do
initialize_converter("rss2sample.xml", rss_doc_config)
end
let(:doc) { converter.as_json }
it "returns `rss` as its root element" do
root = doc.keys.first
expect(root).to eq("rss")
end
it "returns the tags for the element with `#`" do
version = doc["rss"]["#version"]
expect(version).to eq("2.0")
end
it "returns the text content for a tag `$t`" do
description = doc["rss"]["channel"]["description"]
expect(description["$t"]).to match(/to Space/)
end
it "has a list of items" do
items = doc["rss"]["channel"]["item"]
expect(items.length).to eq(4)
end
it "parses each item" do
items = doc["rss"]["channel"]["item"]
expect(items.last["title"]["$t"]).to match(/Astronauts/)
end
it "doesn't add whitespace only text elements" do
text_node = doc["rss"]["$t"]
expect(text_node).to be_nil
end
end
context "with an itunes podcast feed" do
subject(:converter) do
initialize_converter("itunes.xml", rss_doc_config)
end
let(:doc) { converter.as_json }
it "doesn't have problems with namespaces" do
itunes_subtitle = doc["rss"]["channel"]["itunes:subtitle"]["$t"]
expect(itunes_subtitle).to match(/A show/)
end
end
context "with mixed atom & html content" do
subject(:converter) do
initialize_converter("nondefaultnamespace-xhtml.atom", atom_doc_config)
end
let(:doc) { converter.as_json }
it "collapses mixed content elements into a single text one" do
entry_content = doc["feed"]["entry"].first["content"]
expect(entry_content.keys).to eq(["#type", "$t"])
end
it "returns text with tags for the mixed content elements" do
entry_content = doc["feed"]["entry"].first["content"]["$t"]
expect(entry_content).to match(/an <h:abb/)
end
it "keeps the attributes for the children tags" do
entry_content = doc["feed"]["entry"].first["content"]["$t"]
expect(entry_content).to match(/<h:abbr title="/)
end
end
context "with CDATA fields" do
subject(:converter) do
initialize_converter("tender_love.xml", rss_doc_config)
end
let(:doc) { converter.as_json }
it "gets inserts content CDATA content as a text node" do
item_description = doc["rss"]["channel"]["item"].first["description"]["$t"]
expect(item_description).to match(/^<!\[CDATA\[Oops.*?\]\]>$/m)
end
end
end
fix spec wording
require 'spec_helper'
describe Feedson::FeedToJson do
def initialize_converter(file_name, doc_config)
feed_path = File.join("spec/examples", file_name)
feed = File.read(feed_path)
Feedson::FeedToJson.new(feed, doc_config: doc_config)
end
let(:rss_doc_config) do
Feedson::RssConfig.new
end
let(:atom_doc_config) do
Feedson::AtomConfig.new
end
context "with very simple RSS feed" do
subject(:converter) do
initialize_converter("rss2sample.xml", rss_doc_config)
end
let(:doc) { converter.as_json }
it "returns `rss` as its root element" do
root = doc.keys.first
expect(root).to eq("rss")
end
it "returns the tags for the element with `#`" do
version = doc["rss"]["#version"]
expect(version).to eq("2.0")
end
it "returns the text content for a tag `$t`" do
description = doc["rss"]["channel"]["description"]
expect(description["$t"]).to match(/to Space/)
end
it "has a list of items" do
items = doc["rss"]["channel"]["item"]
expect(items.length).to eq(4)
end
it "parses each item" do
items = doc["rss"]["channel"]["item"]
expect(items.last["title"]["$t"]).to match(/Astronauts/)
end
it "doesn't add whitespace only text elements" do
text_node = doc["rss"]["$t"]
expect(text_node).to be_nil
end
end
context "with an itunes podcast feed" do
subject(:converter) do
initialize_converter("itunes.xml", rss_doc_config)
end
let(:doc) { converter.as_json }
it "doesn't have problems with namespaces" do
itunes_subtitle = doc["rss"]["channel"]["itunes:subtitle"]["$t"]
expect(itunes_subtitle).to match(/A show/)
end
end
context "with mixed atom & html content" do
subject(:converter) do
initialize_converter("nondefaultnamespace-xhtml.atom", atom_doc_config)
end
let(:doc) { converter.as_json }
it "collapses mixed content elements into a single text one" do
entry_content = doc["feed"]["entry"].first["content"]
expect(entry_content.keys).to eq(["#type", "$t"])
end
it "returns text with tags for the mixed content elements" do
entry_content = doc["feed"]["entry"].first["content"]["$t"]
expect(entry_content).to match(/an <h:abb/)
end
it "keeps the attributes for the children tags" do
entry_content = doc["feed"]["entry"].first["content"]["$t"]
expect(entry_content).to match(/<h:abbr title="/)
end
end
context "with CDATA fields" do
subject(:converter) do
initialize_converter("tender_love.xml", rss_doc_config)
end
let(:doc) { converter.as_json }
it "inserts CDATA content as a text node" do
item_description = doc["rss"]["channel"]["item"].first["description"]["$t"]
expect(item_description).to match(/^<!\[CDATA\[Oops.*?\]\]>$/m)
end
end
end
|
require 'spec_helper'
describe 'Phony.normalize' do
describe 'cases' do
it 'handles the US (with cc) correctly' do
Phony.normalize('+1 724 999 9999').should == '17249999999'
end
it 'handles the US (with cc and cc option) correctly' do
Phony.normalize('+1 724 999 9999', cc: '1').should == '17249999999'
end
it 'handles the US (without cc) correctly' do
Phony.normalize('(310) 555-2121', cc: '1').should == '13105552121'
end
end
end
+ Dutch normalisation case
require 'spec_helper'
describe 'Phony.normalize' do
describe 'cases' do
it 'handles the US (with cc) correctly' do
Phony.normalize('+1 724 999 9999').should == '17249999999'
end
it 'handles the Dutch number (without US cc) correctly' do
Phony.normalize('310 5552121').should == '315552121'
end
it 'handles the US (with cc and cc option) correctly' do
Phony.normalize('+1 724 999 9999', cc: '1').should == '17249999999'
end
it 'handles the US (without cc) correctly' do
Phony.normalize('(310) 555-2121', cc: '1').should == '13105552121'
end
end
end |
require 'spec_helper'
describe Yeb::HTTPRequestHandler do
let(:handler) { Yeb::HTTPRequestHandler.new }
describe '#get_response' do
let(:request_body) do
<<EOS
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate, compress
Host: lulu.dev
User-Agent: HTTPie/0.3.0
EOS
end
subject { handler.get_response(request_body) }
it 'looks up app by hostname' do
end
end
end
Spec for HTTPRequestHandler
require 'spec_helper'
describe Yeb::HTTPRequestHandler do
let(:apps_dir) { Dir.mktmpdir }
let(:sockets_dir) { Dir.mktmpdir }
let(:handler) { Yeb::HTTPRequestHandler.new(apps_dir, sockets_dir) }
describe '#get_response' do
let(:request) { double('request') }
let(:response) { double('response') }
let(:hostname) { double('hostname') }
let(:vhost) { double('vhost') }
let(:socket) { double('socket') }
subject { handler.get_response(request) }
before do
Yeb::Hostname.stub!(:from_http_request => hostname)
end
it 'returns response from VirtualHost socket' do
# FIX: Violating law of Demeter like a boss
Yeb::VirtualHost.should_receive(:new).
with(hostname, apps_dir, sockets_dir).and_return(vhost)
vhost.should_receive(:socket).and_return(socket)
socket.should_receive(:send).with(request, 0)
socket.should_receive(:recv).and_return(response)
socket.should_receive(:close)
handler.get_response(request).should == response
end
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'app_store_reviews/version'
Gem::Specification.new do |spec|
spec.name = 'app_store_reviews'
spec.version = AppStoreReviews::VERSION
spec.author = 'Alexander Greim'
spec.email = 'alexxx@iltempo.de'
spec.summary = 'Fetching and syncing app store reviews'
spec.description = <<-EOF
Ruby library for fetching and syncing app store reviews via iTunes json
protocol.
EOF
spec.homepage = 'https://github.com/iltempo/app_store_reviews'
spec.license = 'MIT'
# Prevent pushing this gem to RubyGems.org. To allow pushes either set
# the 'allowed_push_host' to allow pushing to a single host or delete this
# section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise('RubyGems 2.0 or newer is required to protect
against public gem pushes.')
end
spec.files = `git ls-files -z`.split("\x0").reject { |f|
f.match(%r{^(test|spec|features)/})
}
spec.bindir = 'bin'
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.test_files = spec.files.grep(%r{^spec/})
spec.add_runtime_dependency 'httparty', '~> 0.13'
spec.add_runtime_dependency 'nokogiri', '~> 1.6'
spec.add_development_dependency 'bundler', '~> 1.12'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.0'
spec.add_development_dependency 'fakeweb', '~> 1.3'
end
Take down bundler version for Travis
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'app_store_reviews/version'
Gem::Specification.new do |spec|
spec.name = 'app_store_reviews'
spec.version = AppStoreReviews::VERSION
spec.author = 'Alexander Greim'
spec.email = 'alexxx@iltempo.de'
spec.summary = 'Fetching and syncing app store reviews'
spec.description = <<-EOF
Ruby library for fetching and syncing app store reviews via iTunes json
protocol.
EOF
spec.homepage = 'https://github.com/iltempo/app_store_reviews'
spec.license = 'MIT'
# Prevent pushing this gem to RubyGems.org. To allow pushes either set
# the 'allowed_push_host' to allow pushing to a single host or delete this
# section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise('RubyGems 2.0 or newer is required to protect
against public gem pushes.')
end
spec.files = `git ls-files -z`.split("\x0").reject { |f|
f.match(%r{^(test|spec|features)/})
}
spec.bindir = 'bin'
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.test_files = spec.files.grep(%r{^spec/})
spec.add_runtime_dependency 'httparty', '~> 0.13'
spec.add_runtime_dependency 'nokogiri', '~> 1.6'
spec.add_development_dependency 'bundler', '~> 1.7'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.0'
spec.add_development_dependency 'fakeweb', '~> 1.3'
end
|
Add trunk code specs.
require 'spec_helper'
describe Phony::TrunkCode do
describe '#format' do
it 'is correct' do
code = described_class.new('0')
expect(code.format('%s %s')).to eq '0'
end
it 'is correct' do
code = described_class.new('0', format: true)
expect(code.format('%s %s')).to eq '0'
end
it 'is correct' do
code = described_class.new('0', format: false)
expect(code.format('%s %s')).to eq nil
end
it 'is correct' do
code = described_class.new('06')
expect(code.format('%s %s')).to eq '06'
end
it 'is correct' do
code = described_class.new('06', format: true)
expect(code.format('%s %s')).to eq '06'
end
it 'is correct' do
code = described_class.new('06', format: false)
expect(code.format('%s %s')).to eq nil
end
end
describe '#normalize' do
it 'is correct' do
code = described_class.new('0')
expect(code.normalize('0123')).to eq '0123'
end
it 'is correct' do
code = described_class.new('0', normalize: true)
expect(code.normalize('0123')).to eq '0123'
end
it 'is correct' do
code = described_class.new('0', normalize: false)
expect(code.normalize('0123')).to eq '0123'
end
it 'is correct' do
code = described_class.new('06')
expect(code.normalize('06123')).to eq '06123'
end
it 'is correct' do
code = described_class.new('06', normalize: true)
expect(code.normalize('06123')).to eq '06123'
end
it 'is correct' do
code = described_class.new('06', normalize: false)
expect(code.normalize('0123')).to eq '0123'
end
end
describe '#split' do
it 'is correct' do
code = described_class.new('0')
expect(code.split('0123')).to eq [code, '0123']
end
it 'is correct' do
code = described_class.new('0', split: true)
expect(code.split('0123')).to eq [code, '123']
end
it 'is correct' do
code = described_class.new('0', split: false)
expect(code.split('0123')).to eq [code, '0123']
end
it 'is correct' do
code = described_class.new('06')
expect(code.split('06123')).to eq [code, '06123']
end
it 'is correct' do
code = described_class.new('06', split: true)
expect(code.split('06123')).to eq [code, '123']
end
it 'is correct' do
code = described_class.new('06', split: false)
expect(code.split('06123')).to eq [code, '06123']
end
end
end |
# encoding: utf-8
require 'spec_helper'
describe Protobuf::Message do
describe '.decode' do
let(:message) { ::Test::Resource.new(:name => "Jim") }
it 'creates a new message object decoded from the given bytes' do
expect(::Test::Resource.decode(message.encode)).to eq message
end
context 'with a new enum value' do
let(:older_message) do
Class.new(Protobuf::Message) do
enum_class = Class.new(::Protobuf::Enum) do
define :YAY, 1
end
optional enum_class, :enum_field, 1
repeated enum_class, :enum_list, 2
end
end
let(:newer_message) do
Class.new(Protobuf::Message) do
enum_class = Class.new(::Protobuf::Enum) do
define :YAY, 1
define :HOORAY, 2
end
optional enum_class, :enum_field, 1
repeated enum_class, :enum_list, 2
end
end
context 'with a singular field' do
it 'treats the field as if it was unset when decoding' do
newer = newer_message.new(:enum_field => :HOORAY).serialize
expect(older_message.decode(newer).enum_field!).to be_nil
end
it 'rejects an unknown value when using the constructor' do
expect { older_message.new(:enum_field => :HOORAY) }.to raise_error
end
it 'rejects an unknown value when the setter' do
older = older_message.new
expect { older.enum_field = :HOORAY }.to raise_error
end
end
context 'with a repeated field' do
it 'treats the field as if it was unset when decoding' do
newer = newer_message.new(:enum_list => [:HOORAY]).serialize
expect(older_message.decode(newer).enum_list).to eq([])
end
it 'rejects an unknown value when using the constructor' do
expect { older_message.new(:enum_list => [:HOORAY]) }.to raise_error
end
it 'rejects an unknown value when the setter' do
older = older_message.new
expect { older.enum_field = [:HOORAY] }.to raise_error
end
end
end
end
describe 'defining a new field' do
context 'when defining a field with a tag that has already been used' do
it 'raises a TagCollisionError' do
expect do
Class.new(Protobuf::Message) do
optional ::Protobuf::Field::Int32Field, :foo, 1
optional ::Protobuf::Field::Int32Field, :bar, 1
end
end.to raise_error(Protobuf::TagCollisionError, /Field number 1 has already been used/)
end
end
context 'when defining an extension field with a tag that has already been used' do
it 'raises a TagCollisionError' do
expect do
Class.new(Protobuf::Message) do
extensions 100...110
optional ::Protobuf::Field::Int32Field, :foo, 100
optional ::Protobuf::Field::Int32Field, :bar, 100, :extension => true
end
end.to raise_error(Protobuf::TagCollisionError, /Field number 100 has already been used/)
end
end
context 'when defining a field with a name that has already been used' do
it 'raises a DuplicateFieldNameError' do
expect do
Class.new(Protobuf::Message) do
optional ::Protobuf::Field::Int32Field, :foo, 1
optional ::Protobuf::Field::Int32Field, :foo, 2
end
end.to raise_error(Protobuf::DuplicateFieldNameError, /Field name foo has already been used/)
end
end
context 'when defining an extension field with a name that has already been used' do
it 'raises a DuplicateFieldNameError' do
expect do
Class.new(Protobuf::Message) do
extensions 100...110
optional ::Protobuf::Field::Int32Field, :foo, 1
optional ::Protobuf::Field::Int32Field, :foo, 100, :extension => true
end
end.to raise_error(Protobuf::DuplicateFieldNameError, /Field name foo has already been used/)
end
end
end
describe '.encode' do
let(:values) { { :name => "Jim" } }
it 'creates a new message object with the given values and returns the encoded bytes' do
expect(::Test::Resource.encode(values)).to eq ::Test::Resource.new(values).encode
end
end
describe '#initialize' do
it "defaults to the first value listed in the enum's type definition" do
test_enum = Test::EnumTestMessage.new
expect(test_enum.non_default_enum).to eq(1)
end
it "defaults to a a value with a name" do
test_enum = Test::EnumTestMessage.new
expect(test_enum.non_default_enum.name).to eq(:ONE)
end
it "exposes the enum getter raw value through ! method" do
test_enum = Test::EnumTestMessage.new
expect(test_enum.non_default_enum!).to be_nil
end
it "exposes the enum getter raw value through ! method (when set)" do
test_enum = Test::EnumTestMessage.new
test_enum.non_default_enum = 1
expect(test_enum.non_default_enum!).to eq(1)
end
it "does not try to set attributes which have nil values" do
expect_any_instance_of(Test::EnumTestMessage).not_to receive("non_default_enum=")
Test::EnumTestMessage.new(:non_default_enum => nil)
end
it "takes a hash as an initialization argument" do
test_enum = Test::EnumTestMessage.new(:non_default_enum => 2)
expect(test_enum.non_default_enum).to eq(2)
end
it "initializes with an object that responds to #to_hash" do
hashie_object = OpenStruct.new(:to_hash => { :non_default_enum => 2 })
test_enum = Test::EnumTestMessage.new(hashie_object)
expect(test_enum.non_default_enum).to eq(2)
end
context 'ignoring unknown fields' do
before { ::Protobuf.ignore_unknown_fields = true }
context 'with valid fields' do
let(:values) { { :name => "Jim" } }
it "does not raise an error" do
expect { ::Test::Resource.new(values) }.to_not raise_error
end
end
context 'with non-existent field' do
let(:values) { { :name => "Jim", :othername => "invalid" } }
it "does not raise an error" do
expect { ::Test::Resource.new(values) }.to_not raise_error
end
end
end
context 'not ignoring unknown fields' do
before { ::Protobuf.ignore_unknown_fields = false }
after { ::Protobuf.ignore_unknown_fields = true }
context 'with valid fields' do
let(:values) { { :name => "Jim" } }
it "does not raise an error" do
expect { ::Test::Resource.new(values) }.to_not raise_error
end
end
context 'with non-existent field' do
let(:values) { { :name => "Jim", :othername => "invalid" } }
it "raises an error and mentions the erroneous field" do
expect { ::Test::Resource.new(values) }.to raise_error(::Protobuf::FieldNotDefinedError, /othername/)
end
context 'with a nil value' do
let(:values) { { :name => "Jim", :othername => nil } }
it "raises an error and mentions the erroneous field" do
expect { ::Test::Resource.new(values) }.to raise_error(::Protobuf::FieldNotDefinedError, /othername/)
end
end
end
end
end
describe '#encode' do
context "encoding" do
it "accepts UTF-8 strings into string fields" do
message = ::Test::Resource.new(:name => "Kyle Redfearn\u0060s iPad")
expect { message.encode }.to_not raise_error
end
it "keeps utf-8 when utf-8 is input for string fields" do
name = 'my name💩'
name.force_encoding(Encoding::UTF_8)
message = ::Test::Resource.new(:name => name)
new_message = ::Test::Resource.decode(message.encode)
expect(new_message.name == name).to be true
end
it "trims binary when binary is input for string fields" do
name = "my name\xC3"
name.force_encoding(Encoding::BINARY)
message = ::Test::Resource.new(:name => name)
new_message = ::Test::Resource.decode(message.encode)
expect(new_message.name == "my name").to be true
end
end
context "when there's no value for a required field" do
let(:message) { ::Test::ResourceWithRequiredField.new }
it "raises a 'message not initialized' error" do
expect do
message.encode
end.to raise_error(Protobuf::SerializationError, /required/i)
end
end
context "repeated fields" do
let(:message) { ::Test::Resource.new(:name => "something") }
it "does not raise an error when repeated fields are []" do
expect do
message.repeated_enum = []
message.encode
end.to_not raise_error
end
it "sets the value to nil when empty array is passed" do
message.repeated_enum = []
expect(message.instance_variable_get("@values")[:repeated_enum]).to be_nil
end
it "does not compact the edit original array" do
a = [nil].freeze
message.repeated_enum = a
expect(message.repeated_enum).to eq([])
expect(a).to eq([nil].freeze)
end
it "compacts the set array" do
message.repeated_enum = [nil]
expect(message.repeated_enum).to eq([])
end
it "raises TypeError when a non-array replaces it" do
expect do
message.repeated_enum = 2
end.to raise_error(/value of type/)
end
end
end
describe "boolean predicate methods" do
subject { Test::ResourceFindRequest.new(:name => "resource") }
it { is_expected.to respond_to(:active?) }
it "sets the predicate to true when the boolean value is true" do
subject.active = true
expect(subject.active?).to be true
end
it "sets the predicate to false when the boolean value is false" do
subject.active = false
expect(subject.active?).to be false
end
it "does not put predicate methods on non-boolean fields" do
expect(Test::ResourceFindRequest.new(:name => "resource")).to_not respond_to(:name?)
end
end
describe "#respond_to_and_has?" do
subject { Test::EnumTestMessage.new(:non_default_enum => 2) }
it "is false when the message does not have the field" do
expect(subject.respond_to_and_has?(:other_field)).to be false
end
it "is true when the message has the field" do
expect(subject.respond_to_and_has?(:non_default_enum)).to be true
end
end
describe "#respond_to_has_and_present?" do
subject { Test::EnumTestMessage.new(:non_default_enum => 2) }
it "is false when the message does not have the field" do
expect(subject.respond_to_and_has_and_present?(:other_field)).to be false
end
it "is false when the field is repeated and a value is not present" do
expect(subject.respond_to_and_has_and_present?(:repeated_enums)).to be false
end
it "is false when the field is repeated and the value is empty array" do
subject.repeated_enums = []
expect(subject.respond_to_and_has_and_present?(:repeated_enums)).to be false
end
it "is true when the field is repeated and a value is present" do
subject.repeated_enums = [2]
expect(subject.respond_to_and_has_and_present?(:repeated_enums)).to be true
end
it "is true when the message has the field" do
expect(subject.respond_to_and_has_and_present?(:non_default_enum)).to be true
end
context "#API" do
subject { Test::EnumTestMessage.new(:non_default_enum => 2) }
specify { expect(subject).to respond_to(:respond_to_and_has_and_present?) }
specify { expect(subject).to respond_to(:responds_to_and_has_and_present?) }
specify { expect(subject).to respond_to(:responds_to_has?) }
specify { expect(subject).to respond_to(:respond_to_has?) }
specify { expect(subject).to respond_to(:respond_to_has_present?) }
specify { expect(subject).to respond_to(:responds_to_has_present?) }
specify { expect(subject).to respond_to(:respond_to_and_has_present?) }
specify { expect(subject).to respond_to(:responds_to_and_has_present?) }
end
end
describe '#inspect' do
let(:klass) do
Class.new(Protobuf::Message) do
optional :string, :name, 1
repeated :int32, :counts, 2
optional :int32, :timestamp, 3
end
end
before { stub_const('MyMessage', klass) }
it 'lists the fields' do
proto = klass.new(:name => 'wooo', :counts => [1, 2, 3])
expect(proto.inspect).to eq \
'#<MyMessage name="wooo" counts=[1, 2, 3] timestamp=0>'
end
end
describe '#to_hash' do
context 'generating values for an ENUM field' do
it 'converts the enum to its tag representation' do
hash = Test::EnumTestMessage.new(:non_default_enum => :TWO).to_hash
expect(hash).to eq(:non_default_enum => 2)
end
it 'does not populate default values' do
hash = Test::EnumTestMessage.new.to_hash
expect(hash).to eq(Hash.new)
end
it 'converts repeated enum fields to an array of the tags' do
hash = Test::EnumTestMessage.new(:repeated_enums => [:ONE, :TWO, :TWO, :ONE]).to_hash
expect(hash).to eq(:repeated_enums => [1, 2, 2, 1])
end
end
context 'generating values for a Message field' do
it 'recursively hashes field messages' do
hash = Test::Nested.new(:resource => { :name => 'Nested' }).to_hash
expect(hash).to eq(:resource => { :name => 'Nested' })
end
it 'recursively hashes a repeated set of messages' do
proto = Test::Nested.new(:multiple_resources => [
Test::Resource.new(:name => 'Resource 1'),
Test::Resource.new(:name => 'Resource 2'),
])
expect(proto.to_hash).to eq(
:multiple_resources => [
{ :name => 'Resource 1' },
{ :name => 'Resource 2' },
],
)
end
end
end
describe '#to_json' do
subject do
::Test::ResourceFindRequest.new(:name => 'Test Name', :active => false)
end
specify { expect(subject.to_json).to eq '{"name":"Test Name","active":false}' }
end
describe '.to_json' do
it 'returns the class name of the message for use in json encoding' do
expect do
::Timeout.timeout(0.1) do
expect(::Test::Resource.to_json).to eq("Test::Resource")
end
end.not_to raise_error
end
end
describe "#define_setter" do
subject { ::Test::Resource.new }
it "allows string fields to be set to nil" do
expect { subject.name = nil }.to_not raise_error
end
it "does not allow string fields to be set to Numeric" do
expect { subject.name = 1 }.to raise_error(/name/)
end
end
describe '.get_extension_field' do
it 'fetches an extension field by its tag' do
field = ::Test::Resource.get_extension_field(100)
expect(field).to be_a(::Protobuf::Field::BoolField)
expect(field.tag).to eq(100)
expect(field.name).to eq(:ext_is_searchable)
expect(field).to be_extension
end
it 'fetches an extension field by its symbolized name' do
expect(::Test::Resource.get_extension_field(:ext_is_searchable)).to be_a(::Protobuf::Field::BoolField)
expect(::Test::Resource.get_extension_field('ext_is_searchable')).to be_a(::Protobuf::Field::BoolField)
end
it 'returns nil when attempting to get a non-extension field' do
expect(::Test::Resource.get_extension_field(1)).to be_nil
end
it 'returns nil when field is not found' do
expect(::Test::Resource.get_extension_field(-1)).to be_nil
expect(::Test::Resource.get_extension_field(nil)).to be_nil
end
end
describe '.get_field' do
it 'fetches a non-extension field by its tag' do
field = ::Test::Resource.get_field(1)
expect(field).to be_a(::Protobuf::Field::StringField)
expect(field.tag).to eq(1)
expect(field.name).to eq(:name)
expect(field).not_to be_extension
end
it 'fetches a non-extension field by its symbolized name' do
expect(::Test::Resource.get_field(:name)).to be_a(::Protobuf::Field::StringField)
expect(::Test::Resource.get_field('name')).to be_a(::Protobuf::Field::StringField)
end
it 'fetches an extension field when forced' do
expect(::Test::Resource.get_field(100, true)).to be_a(::Protobuf::Field::BoolField)
expect(::Test::Resource.get_field(:ext_is_searchable, true)).to be_a(::Protobuf::Field::BoolField)
expect(::Test::Resource.get_field('ext_is_searchable', true)).to be_a(::Protobuf::Field::BoolField)
end
it 'returns nil when attempting to get an extension field' do
expect(::Test::Resource.get_field(100)).to be_nil
end
it 'returns nil when field is not defined' do
expect(::Test::Resource.get_field(-1)).to be_nil
expect(::Test::Resource.get_field(nil)).to be_nil
end
end
end
Test enum inspect display, and fix the failing test
# encoding: utf-8
require 'spec_helper'
describe Protobuf::Message do
describe '.decode' do
let(:message) { ::Test::Resource.new(:name => "Jim") }
it 'creates a new message object decoded from the given bytes' do
expect(::Test::Resource.decode(message.encode)).to eq message
end
context 'with a new enum value' do
let(:older_message) do
Class.new(Protobuf::Message) do
enum_class = Class.new(::Protobuf::Enum) do
define :YAY, 1
end
optional enum_class, :enum_field, 1
repeated enum_class, :enum_list, 2
end
end
let(:newer_message) do
Class.new(Protobuf::Message) do
enum_class = Class.new(::Protobuf::Enum) do
define :YAY, 1
define :HOORAY, 2
end
optional enum_class, :enum_field, 1
repeated enum_class, :enum_list, 2
end
end
context 'with a singular field' do
it 'treats the field as if it was unset when decoding' do
newer = newer_message.new(:enum_field => :HOORAY).serialize
expect(older_message.decode(newer).enum_field!).to be_nil
end
it 'rejects an unknown value when using the constructor' do
expect { older_message.new(:enum_field => :HOORAY) }.to raise_error
end
it 'rejects an unknown value when the setter' do
older = older_message.new
expect { older.enum_field = :HOORAY }.to raise_error
end
end
context 'with a repeated field' do
it 'treats the field as if it was unset when decoding' do
newer = newer_message.new(:enum_list => [:HOORAY]).serialize
expect(older_message.decode(newer).enum_list).to eq([])
end
it 'rejects an unknown value when using the constructor' do
expect { older_message.new(:enum_list => [:HOORAY]) }.to raise_error
end
it 'rejects an unknown value when the setter' do
older = older_message.new
expect { older.enum_field = [:HOORAY] }.to raise_error
end
end
end
end
describe 'defining a new field' do
context 'when defining a field with a tag that has already been used' do
it 'raises a TagCollisionError' do
expect do
Class.new(Protobuf::Message) do
optional ::Protobuf::Field::Int32Field, :foo, 1
optional ::Protobuf::Field::Int32Field, :bar, 1
end
end.to raise_error(Protobuf::TagCollisionError, /Field number 1 has already been used/)
end
end
context 'when defining an extension field with a tag that has already been used' do
it 'raises a TagCollisionError' do
expect do
Class.new(Protobuf::Message) do
extensions 100...110
optional ::Protobuf::Field::Int32Field, :foo, 100
optional ::Protobuf::Field::Int32Field, :bar, 100, :extension => true
end
end.to raise_error(Protobuf::TagCollisionError, /Field number 100 has already been used/)
end
end
context 'when defining a field with a name that has already been used' do
it 'raises a DuplicateFieldNameError' do
expect do
Class.new(Protobuf::Message) do
optional ::Protobuf::Field::Int32Field, :foo, 1
optional ::Protobuf::Field::Int32Field, :foo, 2
end
end.to raise_error(Protobuf::DuplicateFieldNameError, /Field name foo has already been used/)
end
end
context 'when defining an extension field with a name that has already been used' do
it 'raises a DuplicateFieldNameError' do
expect do
Class.new(Protobuf::Message) do
extensions 100...110
optional ::Protobuf::Field::Int32Field, :foo, 1
optional ::Protobuf::Field::Int32Field, :foo, 100, :extension => true
end
end.to raise_error(Protobuf::DuplicateFieldNameError, /Field name foo has already been used/)
end
end
end
describe '.encode' do
let(:values) { { :name => "Jim" } }
it 'creates a new message object with the given values and returns the encoded bytes' do
expect(::Test::Resource.encode(values)).to eq ::Test::Resource.new(values).encode
end
end
describe '#initialize' do
it "defaults to the first value listed in the enum's type definition" do
test_enum = Test::EnumTestMessage.new
expect(test_enum.non_default_enum).to eq(1)
end
it "defaults to a a value with a name" do
test_enum = Test::EnumTestMessage.new
expect(test_enum.non_default_enum.name).to eq(:ONE)
end
it "exposes the enum getter raw value through ! method" do
test_enum = Test::EnumTestMessage.new
expect(test_enum.non_default_enum!).to be_nil
end
it "exposes the enum getter raw value through ! method (when set)" do
test_enum = Test::EnumTestMessage.new
test_enum.non_default_enum = 1
expect(test_enum.non_default_enum!).to eq(1)
end
it "does not try to set attributes which have nil values" do
expect_any_instance_of(Test::EnumTestMessage).not_to receive("non_default_enum=")
Test::EnumTestMessage.new(:non_default_enum => nil)
end
it "takes a hash as an initialization argument" do
test_enum = Test::EnumTestMessage.new(:non_default_enum => 2)
expect(test_enum.non_default_enum).to eq(2)
end
it "initializes with an object that responds to #to_hash" do
hashie_object = OpenStruct.new(:to_hash => { :non_default_enum => 2 })
test_enum = Test::EnumTestMessage.new(hashie_object)
expect(test_enum.non_default_enum).to eq(2)
end
context 'ignoring unknown fields' do
before { ::Protobuf.ignore_unknown_fields = true }
context 'with valid fields' do
let(:values) { { :name => "Jim" } }
it "does not raise an error" do
expect { ::Test::Resource.new(values) }.to_not raise_error
end
end
context 'with non-existent field' do
let(:values) { { :name => "Jim", :othername => "invalid" } }
it "does not raise an error" do
expect { ::Test::Resource.new(values) }.to_not raise_error
end
end
end
context 'not ignoring unknown fields' do
before { ::Protobuf.ignore_unknown_fields = false }
after { ::Protobuf.ignore_unknown_fields = true }
context 'with valid fields' do
let(:values) { { :name => "Jim" } }
it "does not raise an error" do
expect { ::Test::Resource.new(values) }.to_not raise_error
end
end
context 'with non-existent field' do
let(:values) { { :name => "Jim", :othername => "invalid" } }
it "raises an error and mentions the erroneous field" do
expect { ::Test::Resource.new(values) }.to raise_error(::Protobuf::FieldNotDefinedError, /othername/)
end
context 'with a nil value' do
let(:values) { { :name => "Jim", :othername => nil } }
it "raises an error and mentions the erroneous field" do
expect { ::Test::Resource.new(values) }.to raise_error(::Protobuf::FieldNotDefinedError, /othername/)
end
end
end
end
end
describe '#encode' do
context "encoding" do
it "accepts UTF-8 strings into string fields" do
message = ::Test::Resource.new(:name => "Kyle Redfearn\u0060s iPad")
expect { message.encode }.to_not raise_error
end
it "keeps utf-8 when utf-8 is input for string fields" do
name = 'my name💩'
name.force_encoding(Encoding::UTF_8)
message = ::Test::Resource.new(:name => name)
new_message = ::Test::Resource.decode(message.encode)
expect(new_message.name == name).to be true
end
it "trims binary when binary is input for string fields" do
name = "my name\xC3"
name.force_encoding(Encoding::BINARY)
message = ::Test::Resource.new(:name => name)
new_message = ::Test::Resource.decode(message.encode)
expect(new_message.name == "my name").to be true
end
end
context "when there's no value for a required field" do
let(:message) { ::Test::ResourceWithRequiredField.new }
it "raises a 'message not initialized' error" do
expect do
message.encode
end.to raise_error(Protobuf::SerializationError, /required/i)
end
end
context "repeated fields" do
let(:message) { ::Test::Resource.new(:name => "something") }
it "does not raise an error when repeated fields are []" do
expect do
message.repeated_enum = []
message.encode
end.to_not raise_error
end
it "sets the value to nil when empty array is passed" do
message.repeated_enum = []
expect(message.instance_variable_get("@values")[:repeated_enum]).to be_nil
end
it "does not compact the edit original array" do
a = [nil].freeze
message.repeated_enum = a
expect(message.repeated_enum).to eq([])
expect(a).to eq([nil].freeze)
end
it "compacts the set array" do
message.repeated_enum = [nil]
expect(message.repeated_enum).to eq([])
end
it "raises TypeError when a non-array replaces it" do
expect do
message.repeated_enum = 2
end.to raise_error(/value of type/)
end
end
end
describe "boolean predicate methods" do
subject { Test::ResourceFindRequest.new(:name => "resource") }
it { is_expected.to respond_to(:active?) }
it "sets the predicate to true when the boolean value is true" do
subject.active = true
expect(subject.active?).to be true
end
it "sets the predicate to false when the boolean value is false" do
subject.active = false
expect(subject.active?).to be false
end
it "does not put predicate methods on non-boolean fields" do
expect(Test::ResourceFindRequest.new(:name => "resource")).to_not respond_to(:name?)
end
end
describe "#respond_to_and_has?" do
subject { Test::EnumTestMessage.new(:non_default_enum => 2) }
it "is false when the message does not have the field" do
expect(subject.respond_to_and_has?(:other_field)).to be false
end
it "is true when the message has the field" do
expect(subject.respond_to_and_has?(:non_default_enum)).to be true
end
end
describe "#respond_to_has_and_present?" do
subject { Test::EnumTestMessage.new(:non_default_enum => 2) }
it "is false when the message does not have the field" do
expect(subject.respond_to_and_has_and_present?(:other_field)).to be false
end
it "is false when the field is repeated and a value is not present" do
expect(subject.respond_to_and_has_and_present?(:repeated_enums)).to be false
end
it "is false when the field is repeated and the value is empty array" do
subject.repeated_enums = []
expect(subject.respond_to_and_has_and_present?(:repeated_enums)).to be false
end
it "is true when the field is repeated and a value is present" do
subject.repeated_enums = [2]
expect(subject.respond_to_and_has_and_present?(:repeated_enums)).to be true
end
it "is true when the message has the field" do
expect(subject.respond_to_and_has_and_present?(:non_default_enum)).to be true
end
context "#API" do
subject { Test::EnumTestMessage.new(:non_default_enum => 2) }
specify { expect(subject).to respond_to(:respond_to_and_has_and_present?) }
specify { expect(subject).to respond_to(:responds_to_and_has_and_present?) }
specify { expect(subject).to respond_to(:responds_to_has?) }
specify { expect(subject).to respond_to(:respond_to_has?) }
specify { expect(subject).to respond_to(:respond_to_has_present?) }
specify { expect(subject).to respond_to(:responds_to_has_present?) }
specify { expect(subject).to respond_to(:respond_to_and_has_present?) }
specify { expect(subject).to respond_to(:responds_to_and_has_present?) }
end
end
describe '#inspect' do
let(:klass) do
Class.new(Protobuf::Message) do
EnumKlass = Class.new(Protobuf::Enum) do
define :YAY, 1
end
optional :string, :name, 1
repeated :int32, :counts, 2
optional EnumKlass, :enum, 3
end
end
before { stub_const('MyMessage', klass) }
it 'lists the fields' do
proto = klass.new(:name => 'wooo', :counts => [1, 2, 3], :enum => klass::EnumKlass::YAY)
expect(proto.inspect).to eq \
'#<MyMessage name="wooo" counts=[1, 2, 3] enum=#<Protobuf::Enum(EnumKlass)::YAY=1>>'
end
end
describe '#to_hash' do
context 'generating values for an ENUM field' do
it 'converts the enum to its tag representation' do
hash = Test::EnumTestMessage.new(:non_default_enum => :TWO).to_hash
expect(hash).to eq(:non_default_enum => 2)
end
it 'does not populate default values' do
hash = Test::EnumTestMessage.new.to_hash
expect(hash).to eq(Hash.new)
end
it 'converts repeated enum fields to an array of the tags' do
hash = Test::EnumTestMessage.new(:repeated_enums => [:ONE, :TWO, :TWO, :ONE]).to_hash
expect(hash).to eq(:repeated_enums => [1, 2, 2, 1])
end
end
context 'generating values for a Message field' do
it 'recursively hashes field messages' do
hash = Test::Nested.new(:resource => { :name => 'Nested' }).to_hash
expect(hash).to eq(:resource => { :name => 'Nested' })
end
it 'recursively hashes a repeated set of messages' do
proto = Test::Nested.new(:multiple_resources => [
Test::Resource.new(:name => 'Resource 1'),
Test::Resource.new(:name => 'Resource 2'),
])
expect(proto.to_hash).to eq(
:multiple_resources => [
{ :name => 'Resource 1' },
{ :name => 'Resource 2' },
],
)
end
end
end
describe '#to_json' do
subject do
::Test::ResourceFindRequest.new(:name => 'Test Name', :active => false)
end
specify { expect(subject.to_json).to eq '{"name":"Test Name","active":false}' }
end
describe '.to_json' do
it 'returns the class name of the message for use in json encoding' do
expect do
::Timeout.timeout(0.1) do
expect(::Test::Resource.to_json).to eq("Test::Resource")
end
end.not_to raise_error
end
end
describe "#define_setter" do
subject { ::Test::Resource.new }
it "allows string fields to be set to nil" do
expect { subject.name = nil }.to_not raise_error
end
it "does not allow string fields to be set to Numeric" do
expect { subject.name = 1 }.to raise_error(/name/)
end
end
describe '.get_extension_field' do
it 'fetches an extension field by its tag' do
field = ::Test::Resource.get_extension_field(100)
expect(field).to be_a(::Protobuf::Field::BoolField)
expect(field.tag).to eq(100)
expect(field.name).to eq(:ext_is_searchable)
expect(field).to be_extension
end
it 'fetches an extension field by its symbolized name' do
expect(::Test::Resource.get_extension_field(:ext_is_searchable)).to be_a(::Protobuf::Field::BoolField)
expect(::Test::Resource.get_extension_field('ext_is_searchable')).to be_a(::Protobuf::Field::BoolField)
end
it 'returns nil when attempting to get a non-extension field' do
expect(::Test::Resource.get_extension_field(1)).to be_nil
end
it 'returns nil when field is not found' do
expect(::Test::Resource.get_extension_field(-1)).to be_nil
expect(::Test::Resource.get_extension_field(nil)).to be_nil
end
end
describe '.get_field' do
it 'fetches a non-extension field by its tag' do
field = ::Test::Resource.get_field(1)
expect(field).to be_a(::Protobuf::Field::StringField)
expect(field.tag).to eq(1)
expect(field.name).to eq(:name)
expect(field).not_to be_extension
end
it 'fetches a non-extension field by its symbolized name' do
expect(::Test::Resource.get_field(:name)).to be_a(::Protobuf::Field::StringField)
expect(::Test::Resource.get_field('name')).to be_a(::Protobuf::Field::StringField)
end
it 'fetches an extension field when forced' do
expect(::Test::Resource.get_field(100, true)).to be_a(::Protobuf::Field::BoolField)
expect(::Test::Resource.get_field(:ext_is_searchable, true)).to be_a(::Protobuf::Field::BoolField)
expect(::Test::Resource.get_field('ext_is_searchable', true)).to be_a(::Protobuf::Field::BoolField)
end
it 'returns nil when attempting to get an extension field' do
expect(::Test::Resource.get_field(100)).to be_nil
end
it 'returns nil when field is not defined' do
expect(::Test::Resource.get_field(-1)).to be_nil
expect(::Test::Resource.get_field(nil)).to be_nil
end
end
end
|
require 'raml/parser/root'
require 'yaml'
describe Raml::Parser::Root do
describe '#parse' do
let(:raml) { YAML.load File.read('spec/fixtures/basic.raml') }
subject { Raml::Parser::Root.new.parse(raml) }
it { should be_kind_of Raml::Root }
its('resources.count') { should == 2 }
its('documentation.count') { should == 0 }
its(:uri) { should == 'http://example.api.com/v1' }
its(:version) { should == 'v1' }
context 'traits' do
subject { Raml::Parser::Root.new.parse(raml).resources.fetch(1).methods.first.query_parameters.first }
its(:name) { should == 'pages' }
its(:description) { should == 'The number of pages to return' }
its(:type) { should == 'number' }
end
end
end
Ensure non-trait inherited attrs are not overwritten by traits
require 'raml/parser/root'
require 'yaml'
describe Raml::Parser::Root do
describe '#parse' do
let(:raml) { YAML.load File.read('spec/fixtures/basic.raml') }
subject { Raml::Parser::Root.new.parse(raml) }
it { should be_kind_of Raml::Root }
its('resources.count') { should == 2 }
its('documentation.count') { should == 0 }
its(:uri) { should == 'http://example.api.com/v1' }
its(:version) { should == 'v1' }
context 'trait-inherited attributes' do
subject { Raml::Parser::Root.new.parse(raml).resources.fetch(1).methods.first.query_parameters.first }
its(:name) { should == 'pages' }
its(:description) { should == 'The number of pages to return' }
its(:type) { should == 'number' }
end
context 'non trait-inherited attributes' do
subject { Raml::Parser::Root.new.parse(raml).resources.fetch(1).methods.first.query_parameters.last }
its(:name) { should == 'genre' }
its(:description) { should == 'filter the songs by genre' }
its(:type) { should == nil }
end
end
end
|
require 'spec_helper'
RSpec.describe AdminMailer, type: :mailer do
describe 'nightly owner email' do
before :all do
@owner = create(:user)
@collection = create(:collection, owner_user_id: @owner.id)
@new_collaborator = create(:user)
@old_collaborator = create(:user)
@old_deed = create(:deed, {
deed_type: DeedType::WORK_ADDED,
collection_id: @collection.id,
user_id: @old_collaborator.id,
created_at: 2.days.ago
})
end
after :all do
@owner.destroy
@collection.destroy
@new_collaborator.destroy
@old_collaborator.destroy
@old_deed.destroy
end
context "email metadata" do
it "mailer has correct subject" do
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.subject).to eq('Recent Activity in Your Collections')
end
it "mailer has correct recipient" do
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.to).to eq([@owner.email])
end
end
context "email content" do
it "doesn't show old collaborators" do
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).not_to match("You have new collabor=\nators!")
end
it "doesn't show old activity" do
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).not_to match("Other Recent Activity in Your Collections")
end
it "shows new collaborators' email" do
@new_collaborator_deed = create(:deed, {
deed_type: DeedType::WORK_ADDED,
collection_id: @collection.id,
user_id: @new_collaborator.id
})
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).to match("You have new collabora=\ntors!")
expect(mail.body.encoded).to match(@new_collaborator.email)
@new_collaborator_deed.destroy
end
it "shows new comments" do
@new_comment = create(:deed, {
deed_type: DeedType::NOTE_ADDED,
collection_id: @collection.id,
user_id: @old_collaborator.id
})
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).to match("Comments from Your Col=\nlaborators")
@new_comment.destroy
end
it "doesn't show comments when there aren't any" do
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).not_to match("Comments from Your Co=\nllaborators")
end
it "shows new activity collection title" do
@new_deed = create(:deed, {
deed_type: DeedType::WORK_ADDED,
collection_id: @collection.id,
user_id: @old_collaborator.id
})
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).to match(@collection.title)
@new_deed.destroy
end
it "shows new activity" do
@new_deed = create(:deed, {
deed_type: DeedType::WORK_ADDED,
collection_id: @collection.id,
user_id: @old_collaborator.id
})
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).to match(@old_collaborator.display_name)
@new_deed.destroy
end
it "doesn't show other activity if there isn't any" do
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).not_to match("Other Recent Activity in Your Collections")
end
it "doesn't show other activity if is only comments" do
@new_comment = create(:deed, {
deed_type: DeedType::NOTE_ADDED,
collection_id: @collection.id,
user_id: @old_collaborator.id
})
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).not_to match("Other Recent Activity in Your Collections")
end
end
end
end
admin_mailer_spec: remove trailing whitespace
require 'spec_helper'
RSpec.describe AdminMailer, type: :mailer do
describe 'nightly owner email' do
before :all do
@owner = create(:user)
@collection = create(:collection, owner_user_id: @owner.id)
@new_collaborator = create(:user)
@old_collaborator = create(:user)
@old_deed = create(:deed, {
deed_type: DeedType::WORK_ADDED,
collection_id: @collection.id,
user_id: @old_collaborator.id,
created_at: 2.days.ago
})
end
after :all do
@owner.destroy
@collection.destroy
@new_collaborator.destroy
@old_collaborator.destroy
@old_deed.destroy
end
context "email metadata" do
it "mailer has correct subject" do
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.subject).to eq('Recent Activity in Your Collections')
end
it "mailer has correct recipient" do
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.to).to eq([@owner.email])
end
end
context "email content" do
it "doesn't show old collaborators" do
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).not_to match("You have new collabor=\nators!")
end
it "doesn't show old activity" do
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).not_to match("Other Recent Activity in Your Collections")
end
it "shows new collaborators' email" do
@new_collaborator_deed = create(:deed, {
deed_type: DeedType::WORK_ADDED,
collection_id: @collection.id,
user_id: @new_collaborator.id
})
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).to match("You have new collabora=\ntors!")
expect(mail.body.encoded).to match(@new_collaborator.email)
@new_collaborator_deed.destroy
end
it "shows new comments" do
@new_comment = create(:deed, {
deed_type: DeedType::NOTE_ADDED,
collection_id: @collection.id,
user_id: @old_collaborator.id
})
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).to match("Comments from Your Col=\nlaborators")
@new_comment.destroy
end
it "doesn't show comments when there aren't any" do
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).not_to match("Comments from Your Co=\nllaborators")
end
it "shows new activity collection title" do
@new_deed = create(:deed, {
deed_type: DeedType::WORK_ADDED,
collection_id: @collection.id,
user_id: @old_collaborator.id
})
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).to match(@collection.title)
@new_deed.destroy
end
it "shows new activity" do
@new_deed = create(:deed, {
deed_type: DeedType::WORK_ADDED,
collection_id: @collection.id,
user_id: @old_collaborator.id
})
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).to match(@old_collaborator.display_name)
@new_deed.destroy
end
it "doesn't show other activity if there isn't any" do
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).not_to match("Other Recent Activity in Your Collections")
end
it "doesn't show other activity if is only comments" do
@new_comment = create(:deed, {
deed_type: DeedType::NOTE_ADDED,
collection_id: @collection.id,
user_id: @old_collaborator.id
})
activity = AdminMailer::OwnerCollectionActivity.build(@owner)
mail = AdminMailer.collection_stats_by_owner(activity).deliver
expect(mail.body.encoded).not_to match("Other Recent Activity in Your Collections")
end
end
end
end
|
# Build a simple guessing game
# I worked on this challenge [by myself, with: ].
# I spent [#] hours on this challenge.
# Pseudocode
# Input: Two integers. First, the correct answer to the guessing game, which I will call ANSWER. Then, using a separate set of actions, a value that I will call GUESS
# Output: A boolean value, true or false
# Steps:
# Define ANSWER as a definite input to the game that will be reused..
# Define GUESS as a temporary input to the game, which can and will be terminated once a different GUESS input is entered by the user.
# compare GUESS against ANSWER, see which is bigger
# IF GUESS is bigger than ANSWER
# => Game should tell user that their guess was too low
# => Game will store "too low" as a value
# ELSE IF ANSWER is bigger than GUESS
# => Game should tell user that their guess was too high
# => Game will store "too high" as a (temporary) value
# ELSE IF ANSWER and GUESS are equal
# => Game should tell user that their guess was correct
# => Game will store "correct" as a (temporary) value
# The user then asks the game whether the game is solved or not
# IF the last guess resulted in a value of "too high" or "too low"
# => Game will tell user false, it is not solved
# ELSE IF the last guess resulted in a value of "correct"
# => Game will tell user true, it has been solved
# Initial Solution
# class GuessingGame
# def initialize(answer)
# @answer = answer
# end
# def guess(guess)
# if guess < @answer
# @guess = :low
# elsif guess > @answer
# @guess = :high
# #return value
# else # guess == @answer
# @guess = :correct
# #return value
# end
# end
# def solved?
# if @guess == :correct
# return true
# else
# return false
# end
# end
# end
# new_game = GuessingGame.new(14)
# puts new_game.guess(5).inspect
# puts new_game.solved?
# puts new_game.guess(79).inspect
# puts new_game.solved?
# puts new_game.guess(1).inspect
# puts new_game.solved?
# puts new_game.guess(14).inspect
# puts new_game.solved?
# puts new_game.guess(6).inspect
# puts new_game.solved?
# puts new_game.guess(98).inspect
# puts new_game.solved?
# Refactored Solution
class GuessingGame
def initialize(answer)
@answer = answer
end
def guess(guess)
if guess < @answer
@guess = :low
elsif guess > @answer
@guess = :high
else
@guess = :correct
end
end
def solved?
@guess == :correct ? true : false
end
end
# Reflection
Finishing reflection
# Build a simple guessing game
# I worked on this challenge by myself.
# I spent 3 hours on this challenge.
# Pseudocode
# Input: Two integers. First, the correct answer to the guessing game, which I will call ANSWER. Then, using a separate set of actions, a value that I will call GUESS
# Output: A boolean value, true or false
# Steps:
# Define ANSWER as a definite input to the game that will be reused..
# Define GUESS as a temporary input to the game, which can and will be terminated once a different GUESS input is entered by the user.
# compare GUESS against ANSWER, see which is bigger
# IF GUESS is bigger than ANSWER
# => Game should tell user that their guess was too low
# => Game will store "too low" as a value
# ELSE IF ANSWER is bigger than GUESS
# => Game should tell user that their guess was too high
# => Game will store "too high" as a (temporary) value
# ELSE IF ANSWER and GUESS are equal
# => Game should tell user that their guess was correct
# => Game will store "correct" as a (temporary) value
# The user then asks the game whether the game is solved or not
# IF the last guess resulted in a value of "too high" or "too low"
# => Game will tell user false, it is not solved
# ELSE IF the last guess resulted in a value of "correct"
# => Game will tell user true, it has been solved
# Initial Solution
# class GuessingGame
# def initialize(answer)
# @answer = answer
# end
# def guess(guess)
# if guess < @answer
# @guess = :low
# elsif guess > @answer
# @guess = :high
# #return value
# else # guess == @answer
# @guess = :correct
# #return value
# end
# end
# def solved?
# if @guess == :correct
# return true
# else
# return false
# end
# end
# end
# new_game = GuessingGame.new(14)
# puts new_game.guess(5).inspect
# puts new_game.solved?
# puts new_game.guess(79).inspect
# puts new_game.solved?
# puts new_game.guess(1).inspect
# puts new_game.solved?
# puts new_game.guess(14).inspect
# puts new_game.solved?
# puts new_game.guess(6).inspect
# puts new_game.solved?
# puts new_game.guess(98).inspect
# puts new_game.solved?
# Refactored Solution
class GuessingGame
def initialize(answer)
@answer = answer
end
def guess(guess)
if guess < @answer
@guess = :low
elsif guess > @answer
@guess = :high
else
@guess = :correct
end
end
def solved?
@guess == :correct ? true : false
end
end
# Reflection
# This questions revolved around the use of scope in a Ruby class. Local variables can only be accessed from within the particular method, loop, or code block. They disappear when said thing ends operation. Global variables exist in their own specific forms across all classes, modules, procs, and loops. Their accessibility is their downfall, they aren't used much. Instance variables are to classes as local variables are to methods and loops and blocks. A class method may have both instance and local variables in its workings, possibly also global variables. Class variables are accesible within all instances of that class and are used to define something specific to the class itself.
# Here's examples of how the various variables are written in Ruby. local_variable, $global_variable, @instance_Variable, @@class_variable, CONSTANT.
# We used symbols in this challenge because they are less taxing on the computer's memory. Unlike strings, symbols cannot be changed and only overwritten. Even though we aren't taking that much processing power for this week's challenge, calling the guess function several times requires a data type that lends itself well to being overwritten. So the rest of the program can compare that particular instance variable to the answer.
# In this challenge I used a ternary operator expression for the first time, and it was an interesting way to think about flow control. Instead of being broken up by line breaks and keywords, the "meat" of the statement is contained on one line, broken up by the operators, and "rearranged." Incidentally, I didn't solve the problem until I fixed the solved? method to return false for any instance of @guess that didn't have :correct stored in it. I could easily have represented the method guess as a case statement, because there are three non-overlapping options for the solution. |
require 'spec_helper'
describe DeletedBoard, :type => :model do
it "should create a record whenever a board is deleted" do
u = User.create
b = Board.create(:user => u)
expect(DeletedBoard.find_by_path(b.key)).to eq(nil)
expect(DeletedBoard.find_by_path(b.global_id)).to eq(nil)
b.destroy
expect(DeletedBoard.find_by_path(b.key)).not_to eq(nil)
expect(DeletedBoard.find_by_path(b.global_id)).not_to eq(nil)
end
describe "generate_defaults" do
it "should generate default values" do
db = DeletedBoard.create
expect(db.cleared).to eq(false)
end
end
describe "board_global_id" do
it "should return the board_id for the related board" do
u = User.create
b = Board.create(:user => u)
db = DeletedBoard.create(:board_id => b.id)
expect(db.board_global_id).to eq(b.global_id)
end
end
describe "find_by_path" do
it "should find by key" do
u = User.create
b = Board.create(:user => u)
b.destroy
db = DeletedBoard.find_by_path(b.key)
expect(db).not_to eq(nil)
expect(db.board_id).to eq(b.id)
end
it "should find by id" do
u = User.create
b = Board.create(:user => u)
b.destroy
db = DeletedBoard.find_by_path(b.global_id)
expect(db).not_to eq(nil)
expect(db.board_id).to eq(b.id)
end
it "should find the newest result when finding by key in case of duplicates" do
u = User.create
b = Board.create(:user => u)
b.destroy
b2 = Board.create(:user => u, :key => b.key)
b2.destroy
db = DeletedBoard.find_by_path(b.key)
expect(db).not_to eq(nil)
expect(db.board_id).to eq(b2.id)
end
end
describe "process" do
it "should pull basic information from the board before deleting" do
u = User.create
b = Board.create(:user => u)
db = DeletedBoard.process(b)
expect(db).not_to eq(nil)
expect(db.key).to eq(b.key)
expect(db.board_id).to eq(b.id)
expect(db.cleared).to eq(false)
expect(db.settings['stats']).to eq(b.settings['stats'])
expect(db.id).not_to eq(nil)
end
end
describe "flush_old_records" do
it "should delete old entries" do
u = User.create
b = Board.create(:user => u)
b2 = Board.create(:user => u)
db = DeletedBoard.process(b)
DeletedBoard.where(:id => db.id).update_all(:created_at => 6.months.ago)
db = DeletedBoard.process(b2)
expect(Worker).to receive(:flush_board_by_db_id).with(b.id, b.key)
expect(Worker).not_to receive(:flush_board_by_db_id).with(b2.id, b2.key)
DeletedBoard.flush_old_records
end
it "should return the number of records deleted" do
u = User.create
b = Board.create(:user => u)
b2 = Board.create(:user => u)
db = DeletedBoard.process(b)
DeletedBoard.where(:id => db.id).update_all(:created_at => 6.months.ago)
db = DeletedBoard.process(b2)
expect(Worker).to receive(:flush_board_by_db_id).with(b.id, b.key)
expect(Worker).not_to receive(:flush_board_by_db_id).with(b2.id, b2.key)
res = DeletedBoard.flush_old_records
expect(res).to eq(1)
end
end
end
missed a typo
require 'spec_helper'
describe DeletedBoard, :type => :model do
it "should create a record whenever a board is deleted" do
u = User.create
b = Board.create(:user => u)
expect(DeletedBoard.find_by_path(b.key)).to eq(nil)
expect(DeletedBoard.find_by_path(b.global_id)).to eq(nil)
b.destroy
expect(DeletedBoard.find_by_path(b.key)).not_to eq(nil)
expect(DeletedBoard.find_by_path(b.global_id)).not_to eq(nil)
end
describe "generate_defaults" do
it "should generate default values" do
db = DeletedBoard.create
expect(db.cleared).to eq(false)
end
end
describe "board_global_id" do
it "should return the board_id for the related board" do
u = User.create
b = Board.create(:user => u)
db = DeletedBoard.create(:board_id => b.id)
expect(db.board_global_id).to eq(b.global_id)
end
end
describe "find_by_path" do
it "should find by key" do
u = User.create
b = Board.create(:user => u)
b.destroy
db = DeletedBoard.find_by_path(b.key)
expect(db).not_to eq(nil)
expect(db.board_id).to eq(b.id)
end
it "should find by id" do
u = User.create
b = Board.create(:user => u)
b.destroy
db = DeletedBoard.find_by_path(b.global_id)
expect(db).not_to eq(nil)
expect(db.board_id).to eq(b.id)
end
it "should find the newest result when finding by key in case of duplicates" do
u = User.create
b = Board.create(:user => u)
b.destroy
b2 = Board.create(:user => u, :key => b.key)
b2.destroy
db = DeletedBoard.find_by_path(b.key)
expect(db).not_to eq(nil)
expect(db.board_id).to eq(b2.id)
end
end
describe "process" do
it "should pull basic information from the board before deleting" do
u = User.create
b = Board.create(:user => u)
db = DeletedBoard.process(b)
expect(db).not_to eq(nil)
expect(db.key).to eq(b.key)
expect(db.board_id).to eq(b.id)
expect(db.cleared).to eq(false)
expect(db.settings['stats']).to eq(b.settings['stats'])
expect(db.id).not_to eq(nil)
end
end
describe "flush_old_records" do
it "should delete old entries" do
u = User.create
b = Board.create(:user => u)
b2 = Board.create(:user => u)
db = DeletedBoard.process(b)
DeletedBoard.where(:id => db.id).update_all(:created_at => 6.months.ago)
db = DeletedBoard.process(b2)
expect(Flusher).to receive(:flush_board_by_db_id).with(b.id, b.key)
expect(Flusher).not_to receive(:flush_board_by_db_id).with(b2.id, b2.key)
DeletedBoard.flush_old_records
end
it "should return the number of records deleted" do
u = User.create
b = Board.create(:user => u)
b2 = Board.create(:user => u)
db = DeletedBoard.process(b)
DeletedBoard.where(:id => db.id).update_all(:created_at => 6.months.ago)
db = DeletedBoard.process(b2)
expect(Flusher).to receive(:flush_board_by_db_id).with(b.id, b.key)
expect(Flusher).not_to receive(:flush_board_by_db_id).with(b2.id, b2.key)
res = DeletedBoard.flush_old_records
expect(res).to eq(1)
end
end
end
|
=begin
Build a simple guessing game
I worked on this challenge [by myself].
I spent [#] hours on this challenge.
====== Release 1: Pseudocode ======
Input:
Output:
Steps:
====== Release 2: Initial Solution ======
=end
class GuessingGame
def initialize(number)
# prng = Random.new # If we want to make the game fun
# @answer = prng.rand(number) # we can generate a random number.
@answer = number
end
def guess(guess)
if guess > @answer
@result = :high
elsif guess < @answer
@result = :low
else
@result = :correct
end
end
def solved?
if @result == :correct
return true
else
return false
end
end
end
#====== Release 4: Refactored Solution ======
class GuessingGame
def initialize(number)
@answer = number
end
def guess(guess)
@guess = guess
@guess = @guess > @answer ? :high : (@guess < @answer ? :low : :correct)
end
def solved?
unless @guess == :correct
return false
else
return true
end
end
end
=begin ====== Release 5: Reflection ======
How do instance variables and methods represent the characteristics and behaviors (actions) of a real-world object?
When should you use instance variables? What do they do for you?
Explain how to use flow control. Did you have any trouble using it in this challenge? If so, what did you struggle with?
Why do you think this code requires you to return symbols? What are the benefits of using symbols?
=end
Complete 6.3 reflection
=begin
Build a simple guessing game
I worked on this challenge [by myself].
I spent [#] hours on this challenge.
====== Release 1: Pseudocode ======
Input: a number
Output: a sybmol and a boolean
Steps:
CREATE an instance variable for the answer
CREATE a method that receives a guess and determines
IF the guess is LESS THAN the answer
RETURN the sybmol :low
ELSIF the guess is GREATER THAN the answer
RETURN the sybmol :high
ELSIF the guess EQUALS the answer
RETURN the symbol :correct
END
END
CREATE a method that tells user if the game is solved
IF the result of the user's last guess EQUALS the sybmol :correct
RETURN true
ELSE
RETURN false
END
END
====== Release 2: Initial Solution ======
=end
class GuessingGame
def initialize(number)
# prng = Random.new # If we want to make the game fun
# @answer = prng.rand(number) # we can generate a random number.
@answer = number
end
def guess(guess)
if guess > @answer
@result = :high
elsif guess < @answer
@result = :low
else
@result = :correct
end
end
def solved?
if @result == :correct
return true
else
return false
end
end
end
#====== Release 4: Refactored Solution ======
class GuessingGame
def initialize(number)
@answer = number
end
def guess(guess)
@guess = guess
@guess = @guess > @answer ? :high : (@guess < @answer ? :low : :correct)
end
def solved?
unless @guess == :correct
return false
else
return true
end
end
end
=begin ====== Release 5: Reflection ======
How do instance variables and methods represent the characteristics and behaviors (actions) of a real-world object?
Instance variables represent the properties of a real-world object. For example, the color of a car, the name of a person, the model of a computer. Instance methods describe the behvaiors of such an object. For example, a car can *drive* or *park*, a person can *say hello*, and a computer can *calculate* a sum. Together, instance variables and methods describe the state of an object.
When should you use instance variables? What do they do for you?
Instance variables are useful when you are building a class. Every time an instance of the class is created, that object is associated with the instance variables (and methods) defined within that class. This is extremely useful if you desire to maintain mulitple instances of the class in different states. For example, you may want to represent multiple kinds and colors of cars. Intead of re-creating variables for every object, simply define instance variables within the class. Then, every instance of the class that you create will inherit those variables and they can be accessed anywhere within the that instance of the class.
Explain how to use flow control. Did you have any trouble using it in this challenge? If so, what did you struggle with?
Flow control can be implmented wth either if/eslif/else statements or case/when/else statements. In the first form, a condition is evaluated and a boolean true or false is returned. Depending on the condition, the resulting code is evaluated, or, the statement is ended. In the latter form, a value is specifed (i.e. case name) and then a series of arguments are described (i.e. when "Jared", when "Amy"). If the value is the same as one of those conditions, the code defined within that "when" clause is executed. I did not encounter trouble using flow control in this challenge. I kept it simple by using if/else statements.
Why do you think this code requires you to return symbols? What are the benefits of using symbols?
Symbols are inherently immutable:
Symbols can only be overwritten while strings can be updated. For example, we can manipulate a string by appending and deleting characters. However, a symbol cannot be manipulated like a string. I think we returned sybmols in this challenge because the values are never going to change--we are never going to return anything other than :low, :high, or :correct. There is no need to have the interpreter assign memory each time we want to return a value by instantiating a new string for "low", "high", and "correct."
Symbols require less memory:
The interpreter handles symbols differently from strings. When a string is instantiated, it's given an unique object ID. Even when we type the same string again and again, a new instance is created and therefore a new object ID has been assigned to every instance. This means that more memory has been allocated to these strings. On the other hand, a symbol, once created, maintains the same object ID, no matter how many times it is written. This means the interpreter is allocating only enough memory for the one symbol.
Sybmols require less computational power:
In the previous paragraph, I stated that multiple strings with the same value will have different object IDs, while mulitple symbols with the same values will have only one ojbect ID. Well, this is important when the interpreter needs to two objects. When the interpreter sees that two objects have the same ID, it know's it's comparison work is complete. However, if two objects have different IDs, then the interpreter must evaluate the value of the objects and make a comparison.
=end |
require 'spec_helper'
module Spree
describe Product do
describe "associations" do
it { should belong_to(:supplier) }
it { should belong_to(:primary_taxon) }
it { should have_many(:product_distributions) }
end
describe "validations and defaults" do
it "is valid when created from factory" do
create(:product).should be_valid
end
it "requires a primary taxon" do
product = create(:simple_product)
product.primary_taxon = nil
product.should_not be_valid
end
it "requires a supplier" do
product = create(:simple_product)
product.supplier = nil
product.should_not be_valid
end
it "should default available_on to now" do
Timecop.freeze
product = Product.new
product.available_on.should == Time.now
end
context "when the product has variants" do
let(:product) do
product = create(:simple_product)
create(:variant, product: product)
product.reload
end
it "requires a unit" do
product.variant_unit = nil
product.should_not be_valid
end
%w(weight volume).each do |unit|
context "when unit is #{unit}" do
it "is valid when unit scale is set and unit name is not" do
product.variant_unit = unit
product.variant_unit_scale = 1
product.variant_unit_name = nil
product.should be_valid
end
it "is invalid when unit scale is not set" do
product.variant_unit = unit
product.variant_unit_scale = nil
product.variant_unit_name = nil
product.should_not be_valid
end
end
end
context "when the unit is items" do
it "is valid when unit name is set and unit scale is not" do
product.variant_unit = 'items'
product.variant_unit_name = 'loaf'
product.variant_unit_scale = nil
product.should be_valid
end
it "is invalid when unit name is not set" do
product.variant_unit = 'items'
product.variant_unit_name = nil
product.variant_unit_scale = nil
product.should_not be_valid
end
end
end
context "when product does not have variants" do
let(:product) { create(:simple_product) }
it "does not require any variant unit fields" do
product.variant_unit = nil
product.variant_unit_name = nil
product.variant_unit_scale = nil
product.should be_valid
end
it "requires a unit scale when variant unit is weight" do
product.variant_unit = 'weight'
product.variant_unit_scale = nil
product.variant_unit_name = nil
product.should_not be_valid
end
end
end
describe "scopes" do
describe "in_supplier" do
it "shows products in supplier" do
s1 = create(:supplier_enterprise)
s2 = create(:supplier_enterprise)
p1 = create(:product, supplier: s1)
p2 = create(:product, supplier: s2)
Product.in_supplier(s1).should == [p1]
end
end
describe "in_distributor" do
it "shows products in product distribution" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product, distributors: [d1])
p2 = create(:product, distributors: [d2])
Product.in_distributor(d1).should == [p1]
end
it "shows products in order cycle distribution" do
s = create(:supplier_enterprise)
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
create(:simple_order_cycle, suppliers: [s], distributors: [d1], variants: [p1.master])
create(:simple_order_cycle, suppliers: [s], distributors: [d2], variants: [p2.master])
Product.in_distributor(d1).should == [p1]
end
it "shows products in order cycle distribution by variant" do
s = create(:supplier_enterprise)
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
v1 = create(:variant, product: p1)
p2 = create(:product)
v2 = create(:variant, product: p2)
create(:simple_order_cycle, suppliers: [s], distributors: [d1], variants: [v1])
create(:simple_order_cycle, suppliers: [s], distributors: [d2], variants: [v2])
Product.in_distributor(d1).should == [p1]
end
it "doesn't show products listed in the incoming exchange only", :future => true do
s = create(:supplier_enterprise)
c = create(:distributor_enterprise)
d = create(:distributor_enterprise)
p = create(:product)
oc = create(:simple_order_cycle, coordinator: c, suppliers: [s], distributors: [d])
ex = oc.exchanges.incoming.first
ex.variants << p.master
Product.in_distributor(d).should be_empty
end
it "shows products in both without duplicates" do
s = create(:supplier_enterprise)
d = create(:distributor_enterprise)
p = create(:product, distributors: [d])
create(:simple_order_cycle, suppliers: [s], distributors: [d], variants: [p.master])
Product.in_distributor(d).should == [p]
end
end
describe "in_product_distribution_by" do
it "shows products in product distribution" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product, distributors: [d1])
p2 = create(:product, distributors: [d2])
Product.in_product_distribution_by(d1).should == [p1]
end
it "does not show products in order cycle distribution" do
s = create(:supplier_enterprise)
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
create(:simple_order_cycle, suppliers: [s], distributors: [d1], variants: [p1.master])
create(:simple_order_cycle, suppliers: [s], distributors: [d2], variants: [p2.master])
Product.in_product_distribution_by(d1).should == []
end
end
describe "in_supplier_or_distributor" do
it "shows products in supplier" do
s1 = create(:supplier_enterprise)
s2 = create(:supplier_enterprise)
p1 = create(:product, supplier: s1)
p2 = create(:product, supplier: s2)
Product.in_supplier_or_distributor(s1).should == [p1]
end
it "shows products in product distribution" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product, distributors: [d1])
p2 = create(:product, distributors: [d2])
Product.in_supplier_or_distributor(d1).should == [p1]
end
it "shows products in order cycle distribution" do
s = create(:supplier_enterprise)
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
create(:simple_order_cycle, suppliers: [s], distributors: [d1], variants: [p1.master])
create(:simple_order_cycle, suppliers: [s], distributors: [d2], variants: [p2.master])
Product.in_supplier_or_distributor(d1).should == [p1]
end
it "shows products in all three without duplicates" do
s = create(:supplier_enterprise)
d = create(:distributor_enterprise)
p = create(:product, supplier: s, distributors: [d])
create(:simple_order_cycle, suppliers: [s], distributors: [d], variants: [p.master])
[s, d].each { |e| Product.in_supplier_or_distributor(e).should == [p] }
end
end
describe "in_order_cycle" do
it "shows products in order cycle distribution" do
s = create(:supplier_enterprise)
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
oc1 = create(:simple_order_cycle, suppliers: [s], distributors: [d1], variants: [p1.master])
oc2 = create(:simple_order_cycle, suppliers: [s], distributors: [d2], variants: [p2.master])
Product.in_order_cycle(oc1).should == [p1]
end
end
describe "in_an_active_order_cycle" do
it "shows products in order cycle distribution" do
s = create(:supplier_enterprise)
d2 = create(:distributor_enterprise)
d3 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
p3 = create(:product)
oc2 = create(:simple_order_cycle, suppliers: [s], distributors: [d2], variants: [p2.master], orders_close_at: 1.day.ago)
oc2 = create(:simple_order_cycle, suppliers: [s], distributors: [d3], variants: [p3.master], orders_close_at: Date.tomorrow)
Product.in_an_active_order_cycle.should == [p3]
end
end
describe "access roles" do
before(:each) do
@e1 = create(:enterprise)
@e2 = create(:enterprise)
@p1 = create(:product, supplier: @e1)
@p2 = create(:product, supplier: @e2)
end
it "shows only products for given user" do
user = create(:user)
user.spree_roles = []
@e1.enterprise_roles.build(user: user).save
product = Product.managed_by user
product.count.should == 1
product.should include @p1
end
it "shows all products for admin user" do
user = create(:admin_user)
product = Product.managed_by user
product.count.should == 2
product.should include @p1
product.should include @p2
end
end
end
describe "finders" do
it "finds the product distribution for a particular distributor" do
distributor = create(:distributor_enterprise)
product = create(:product)
product_distribution = create(:product_distribution, product: product, distributor: distributor)
product.product_distribution_for(distributor).should == product_distribution
end
end
describe "membership" do
it "queries its membership of a particular product distribution" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p = create(:product, distributors: [d1])
p.should be_in_distributor d1
p.should_not be_in_distributor d2
end
it "queries its membership of a particular order cycle distribution" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
oc1 = create(:order_cycle, :distributors => [d1], :variants => [p1.master])
oc2 = create(:order_cycle, :distributors => [d2], :variants => [p2.master])
p1.should be_in_distributor d1
p1.should_not be_in_distributor d2
end
it "queries its membership of a particular order cycle" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
oc1 = create(:order_cycle, :distributors => [d1], :variants => [p1.master])
oc2 = create(:order_cycle, :distributors => [d2], :variants => [p2.master])
p1.should be_in_order_cycle oc1
p1.should_not be_in_order_cycle oc2
end
end
describe "finding variants for an order cycle and hub" do
let(:oc) { create(:simple_order_cycle) }
let(:s) { create(:supplier_enterprise) }
let(:d1) { create(:distributor_enterprise) }
let(:d2) { create(:distributor_enterprise) }
let(:p1) { create(:simple_product) }
let(:p2) { create(:simple_product) }
let(:v1) { create(:variant, product: p1) }
let(:v2) { create(:variant, product: p2) }
let(:p_external) { create(:simple_product) }
let(:v_external) { create(:variant, product: p_external) }
let!(:ex_in) { create(:exchange, order_cycle: oc, sender: s, receiver: oc.coordinator,
incoming: true, variants: [v1, v2]) }
let!(:ex_out1) { create(:exchange, order_cycle: oc, sender: oc.coordinator, receiver: d1,
incoming: false, variants: [v1]) }
let!(:ex_out2) { create(:exchange, order_cycle: oc, sender: oc.coordinator, receiver: d2,
incoming: false, variants: [v2]) }
it "returns variants in the order cycle and distributor" do
p1.variants_for(oc, d1).should == [v1]
p2.variants_for(oc, d2).should == [v2]
end
it "does not return variants in the order cycle but not the distributor" do
p1.variants_for(oc, d2).should be_empty
p2.variants_for(oc, d1).should be_empty
end
it "does not return variants not in the order cycle" do
p_external.variants_for(oc, d1).should be_empty
end
end
describe "variant units" do
context "when the product initially has no variant unit" do
let!(:p) { create(:simple_product,
variant_unit: nil,
variant_unit_scale: nil,
variant_unit_name: nil) }
context "when the required option type does not exist" do
it "creates the option type and assigns it to the product" do
expect {
p.update_attributes!(variant_unit: 'weight', variant_unit_scale: 1000)
}.to change(Spree::OptionType, :count).by(1)
ot = Spree::OptionType.last
ot.name.should == 'unit_weight'
ot.presentation.should == 'Weight'
p.option_types.should == [ot]
end
it "does the same with volume" do
expect {
p.update_attributes!(variant_unit: 'volume', variant_unit_scale: 1000)
}.to change(Spree::OptionType, :count).by(1)
ot = Spree::OptionType.last
ot.name.should == 'unit_volume'
ot.presentation.should == 'Volume'
p.option_types.should == [ot]
end
it "does the same with items" do
expect {
p.update_attributes!(variant_unit: 'items', variant_unit_name: 'packet')
}.to change(Spree::OptionType, :count).by(1)
ot = Spree::OptionType.last
ot.name.should == 'unit_items'
ot.presentation.should == 'Items'
p.option_types.should == [ot]
end
end
context "when the required option type already exists" do
let!(:ot) { create(:option_type, name: 'unit_weight', presentation: 'Weight') }
it "looks up the option type and assigns it to the product" do
expect {
p.update_attributes!(variant_unit: 'weight', variant_unit_scale: 1000)
}.to change(Spree::OptionType, :count).by(0)
p.option_types.should == [ot]
end
end
end
context "when the product already has a variant unit set (and all required option types exist)" do
let!(:p) { create(:simple_product,
variant_unit: 'weight',
variant_unit_scale: 1,
variant_unit_name: nil) }
let!(:ot_volume) { create(:option_type, name: 'unit_volume', presentation: 'Volume') }
it "removes the old option type and assigns the new one" do
p.update_attributes!(variant_unit: 'volume', variant_unit_scale: 0.001)
p.option_types.should == [ot_volume]
end
it "leaves option type unassigned if none is provided" do
p.update_attributes!(variant_unit: nil, variant_unit_scale: nil)
p.option_types.should == []
end
it "does not remove and re-add the option type if it is not changed" do
p.option_types.should_receive(:delete).never
p.update_attributes!(name: 'foo')
end
it "removes the related option values from all its variants" do
ot = Spree::OptionType.find_by_name 'unit_weight'
v = create(:variant, product: p)
p.reload
expect {
p.update_attributes!(variant_unit: 'volume', variant_unit_scale: 0.001)
}.to change(v.option_values(true), :count).by(-1)
end
it "removes the related option values from its master variant" do
ot = Spree::OptionType.find_by_name 'unit_weight'
p.master.update_attributes!(unit_value: 1)
p.reload
expect {
p.update_attributes!(variant_unit: 'volume', variant_unit_scale: 0.001)
}.to change(p.master.option_values(true), :count).by(-1)
end
end
describe "returning the variant unit option type" do
it "returns nil when variant_unit is not set" do
p = create(:simple_product, variant_unit: nil)
p.variant_unit_option_type.should be_nil
end
end
it "finds all variant unit option types" do
ot1 = create(:option_type, name: 'unit_weight', presentation: 'Weight')
ot2 = create(:option_type, name: 'unit_volume', presentation: 'Volume')
ot3 = create(:option_type, name: 'unit_items', presentation: 'Items')
ot4 = create(:option_type, name: 'foo_unit_bar', presentation: 'Foo')
Spree::Product.all_variant_unit_option_types.sort.should == [ot1, ot2, ot3].sort
end
end
describe "option types" do
describe "removing an option type" do
it "removes the associated option values from all variants" do
# Given a product with a variant unit option type and values
p = create(:simple_product, variant_unit: 'weight', variant_unit_scale: 1)
v1 = create(:variant, product: p, unit_value: 100, option_values: [])
v2 = create(:variant, product: p, unit_value: 200, option_values: [])
# And a custom option type and values
ot = create(:option_type, name: 'foo', presentation: 'foo')
p.option_types << ot
ov1 = create(:option_value, option_type: ot, name: 'One', presentation: 'One')
ov2 = create(:option_value, option_type: ot, name: 'Two', presentation: 'Two')
v1.option_values << ov1
v2.option_values << ov2
# When we remove the custom option type
p.option_type_ids = p.option_type_ids.reject { |id| id == ot.id }
# Then the associated option values should have been removed from the variants
v1.option_values(true).should_not include ov1
v2.option_values(true).should_not include ov2
# And the option values themselves should still exist
Spree::OptionValue.where(id: [ov1.id, ov2.id]).count.should == 2
end
end
end
describe "stock filtering" do
it "considers products that are on_demand as being in stock" do
product = create(:simple_product, on_demand: true)
product.master.update_attribute(:count_on_hand, 0)
product.has_stock?.should == true
end
describe "finding products in stock for a particular distribution" do
it "returns in-stock products without variants" do
p = create(:simple_product)
p.master.update_attribute(:count_on_hand, 1)
d = create(:distributor_enterprise)
oc = create(:simple_order_cycle, distributors: [d])
oc.exchanges.outgoing.first.variants << p.master
p.should have_stock_for_distribution(oc, d)
end
it "returns on-demand products" do
p = create(:simple_product, on_demand: true)
p.master.update_attribute(:count_on_hand, 0)
d = create(:distributor_enterprise)
oc = create(:simple_order_cycle, distributors: [d])
oc.exchanges.outgoing.first.variants << p.master
p.should have_stock_for_distribution(oc, d)
end
it "returns products with in-stock variants" do
p = create(:simple_product)
v = create(:variant, product: p)
v.update_attribute(:count_on_hand, 1)
d = create(:distributor_enterprise)
oc = create(:simple_order_cycle, distributors: [d])
oc.exchanges.outgoing.first.variants << v
p.should have_stock_for_distribution(oc, d)
end
it "returns products with on-demand variants" do
p = create(:simple_product)
v = create(:variant, product: p, on_demand: true)
v.update_attribute(:count_on_hand, 0)
d = create(:distributor_enterprise)
oc = create(:simple_order_cycle, distributors: [d])
oc.exchanges.outgoing.first.variants << v
p.should have_stock_for_distribution(oc, d)
end
it "does not return products that have stock not in the distribution" do
p = create(:simple_product)
p.master.update_attribute(:count_on_hand, 1)
d = create(:distributor_enterprise)
oc = create(:simple_order_cycle, distributors: [d])
p.should_not have_stock_for_distribution(oc, d)
end
end
end
describe "Taxons" do
let(:taxon1) { create(:taxon) }
let(:taxon2) { create(:taxon) }
let(:product) { create(:simple_product) }
it "returns the first taxon as the primary taxon" do
product.taxons.should == [product.primary_taxon]
end
end
end
end
Fix spec to check validation of missing primary_taxon correctly
require 'spec_helper'
module Spree
describe Product do
describe "associations" do
it { should belong_to(:supplier) }
it { should belong_to(:primary_taxon) }
it { should have_many(:product_distributions) }
end
describe "validations and defaults" do
it "is valid when created from factory" do
create(:product).should be_valid
end
it "requires a primary taxon" do
product = create(:simple_product)
product.taxons = []
product.primary_taxon = nil
product.should_not be_valid
end
it "requires a supplier" do
product = create(:simple_product)
product.supplier = nil
product.should_not be_valid
end
it "should default available_on to now" do
Timecop.freeze
product = Product.new
product.available_on.should == Time.now
end
context "when the product has variants" do
let(:product) do
product = create(:simple_product)
create(:variant, product: product)
product.reload
end
it "requires a unit" do
product.variant_unit = nil
product.should_not be_valid
end
%w(weight volume).each do |unit|
context "when unit is #{unit}" do
it "is valid when unit scale is set and unit name is not" do
product.variant_unit = unit
product.variant_unit_scale = 1
product.variant_unit_name = nil
product.should be_valid
end
it "is invalid when unit scale is not set" do
product.variant_unit = unit
product.variant_unit_scale = nil
product.variant_unit_name = nil
product.should_not be_valid
end
end
end
context "when the unit is items" do
it "is valid when unit name is set and unit scale is not" do
product.variant_unit = 'items'
product.variant_unit_name = 'loaf'
product.variant_unit_scale = nil
product.should be_valid
end
it "is invalid when unit name is not set" do
product.variant_unit = 'items'
product.variant_unit_name = nil
product.variant_unit_scale = nil
product.should_not be_valid
end
end
end
context "when product does not have variants" do
let(:product) { create(:simple_product) }
it "does not require any variant unit fields" do
product.variant_unit = nil
product.variant_unit_name = nil
product.variant_unit_scale = nil
product.should be_valid
end
it "requires a unit scale when variant unit is weight" do
product.variant_unit = 'weight'
product.variant_unit_scale = nil
product.variant_unit_name = nil
product.should_not be_valid
end
end
end
describe "scopes" do
describe "in_supplier" do
it "shows products in supplier" do
s1 = create(:supplier_enterprise)
s2 = create(:supplier_enterprise)
p1 = create(:product, supplier: s1)
p2 = create(:product, supplier: s2)
Product.in_supplier(s1).should == [p1]
end
end
describe "in_distributor" do
it "shows products in product distribution" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product, distributors: [d1])
p2 = create(:product, distributors: [d2])
Product.in_distributor(d1).should == [p1]
end
it "shows products in order cycle distribution" do
s = create(:supplier_enterprise)
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
create(:simple_order_cycle, suppliers: [s], distributors: [d1], variants: [p1.master])
create(:simple_order_cycle, suppliers: [s], distributors: [d2], variants: [p2.master])
Product.in_distributor(d1).should == [p1]
end
it "shows products in order cycle distribution by variant" do
s = create(:supplier_enterprise)
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
v1 = create(:variant, product: p1)
p2 = create(:product)
v2 = create(:variant, product: p2)
create(:simple_order_cycle, suppliers: [s], distributors: [d1], variants: [v1])
create(:simple_order_cycle, suppliers: [s], distributors: [d2], variants: [v2])
Product.in_distributor(d1).should == [p1]
end
it "doesn't show products listed in the incoming exchange only", :future => true do
s = create(:supplier_enterprise)
c = create(:distributor_enterprise)
d = create(:distributor_enterprise)
p = create(:product)
oc = create(:simple_order_cycle, coordinator: c, suppliers: [s], distributors: [d])
ex = oc.exchanges.incoming.first
ex.variants << p.master
Product.in_distributor(d).should be_empty
end
it "shows products in both without duplicates" do
s = create(:supplier_enterprise)
d = create(:distributor_enterprise)
p = create(:product, distributors: [d])
create(:simple_order_cycle, suppliers: [s], distributors: [d], variants: [p.master])
Product.in_distributor(d).should == [p]
end
end
describe "in_product_distribution_by" do
it "shows products in product distribution" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product, distributors: [d1])
p2 = create(:product, distributors: [d2])
Product.in_product_distribution_by(d1).should == [p1]
end
it "does not show products in order cycle distribution" do
s = create(:supplier_enterprise)
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
create(:simple_order_cycle, suppliers: [s], distributors: [d1], variants: [p1.master])
create(:simple_order_cycle, suppliers: [s], distributors: [d2], variants: [p2.master])
Product.in_product_distribution_by(d1).should == []
end
end
describe "in_supplier_or_distributor" do
it "shows products in supplier" do
s1 = create(:supplier_enterprise)
s2 = create(:supplier_enterprise)
p1 = create(:product, supplier: s1)
p2 = create(:product, supplier: s2)
Product.in_supplier_or_distributor(s1).should == [p1]
end
it "shows products in product distribution" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product, distributors: [d1])
p2 = create(:product, distributors: [d2])
Product.in_supplier_or_distributor(d1).should == [p1]
end
it "shows products in order cycle distribution" do
s = create(:supplier_enterprise)
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
create(:simple_order_cycle, suppliers: [s], distributors: [d1], variants: [p1.master])
create(:simple_order_cycle, suppliers: [s], distributors: [d2], variants: [p2.master])
Product.in_supplier_or_distributor(d1).should == [p1]
end
it "shows products in all three without duplicates" do
s = create(:supplier_enterprise)
d = create(:distributor_enterprise)
p = create(:product, supplier: s, distributors: [d])
create(:simple_order_cycle, suppliers: [s], distributors: [d], variants: [p.master])
[s, d].each { |e| Product.in_supplier_or_distributor(e).should == [p] }
end
end
describe "in_order_cycle" do
it "shows products in order cycle distribution" do
s = create(:supplier_enterprise)
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
oc1 = create(:simple_order_cycle, suppliers: [s], distributors: [d1], variants: [p1.master])
oc2 = create(:simple_order_cycle, suppliers: [s], distributors: [d2], variants: [p2.master])
Product.in_order_cycle(oc1).should == [p1]
end
end
describe "in_an_active_order_cycle" do
it "shows products in order cycle distribution" do
s = create(:supplier_enterprise)
d2 = create(:distributor_enterprise)
d3 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
p3 = create(:product)
oc2 = create(:simple_order_cycle, suppliers: [s], distributors: [d2], variants: [p2.master], orders_close_at: 1.day.ago)
oc2 = create(:simple_order_cycle, suppliers: [s], distributors: [d3], variants: [p3.master], orders_close_at: Date.tomorrow)
Product.in_an_active_order_cycle.should == [p3]
end
end
describe "access roles" do
before(:each) do
@e1 = create(:enterprise)
@e2 = create(:enterprise)
@p1 = create(:product, supplier: @e1)
@p2 = create(:product, supplier: @e2)
end
it "shows only products for given user" do
user = create(:user)
user.spree_roles = []
@e1.enterprise_roles.build(user: user).save
product = Product.managed_by user
product.count.should == 1
product.should include @p1
end
it "shows all products for admin user" do
user = create(:admin_user)
product = Product.managed_by user
product.count.should == 2
product.should include @p1
product.should include @p2
end
end
end
describe "finders" do
it "finds the product distribution for a particular distributor" do
distributor = create(:distributor_enterprise)
product = create(:product)
product_distribution = create(:product_distribution, product: product, distributor: distributor)
product.product_distribution_for(distributor).should == product_distribution
end
end
describe "membership" do
it "queries its membership of a particular product distribution" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p = create(:product, distributors: [d1])
p.should be_in_distributor d1
p.should_not be_in_distributor d2
end
it "queries its membership of a particular order cycle distribution" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
oc1 = create(:order_cycle, :distributors => [d1], :variants => [p1.master])
oc2 = create(:order_cycle, :distributors => [d2], :variants => [p2.master])
p1.should be_in_distributor d1
p1.should_not be_in_distributor d2
end
it "queries its membership of a particular order cycle" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p1 = create(:product)
p2 = create(:product)
oc1 = create(:order_cycle, :distributors => [d1], :variants => [p1.master])
oc2 = create(:order_cycle, :distributors => [d2], :variants => [p2.master])
p1.should be_in_order_cycle oc1
p1.should_not be_in_order_cycle oc2
end
end
describe "finding variants for an order cycle and hub" do
let(:oc) { create(:simple_order_cycle) }
let(:s) { create(:supplier_enterprise) }
let(:d1) { create(:distributor_enterprise) }
let(:d2) { create(:distributor_enterprise) }
let(:p1) { create(:simple_product) }
let(:p2) { create(:simple_product) }
let(:v1) { create(:variant, product: p1) }
let(:v2) { create(:variant, product: p2) }
let(:p_external) { create(:simple_product) }
let(:v_external) { create(:variant, product: p_external) }
let!(:ex_in) { create(:exchange, order_cycle: oc, sender: s, receiver: oc.coordinator,
incoming: true, variants: [v1, v2]) }
let!(:ex_out1) { create(:exchange, order_cycle: oc, sender: oc.coordinator, receiver: d1,
incoming: false, variants: [v1]) }
let!(:ex_out2) { create(:exchange, order_cycle: oc, sender: oc.coordinator, receiver: d2,
incoming: false, variants: [v2]) }
it "returns variants in the order cycle and distributor" do
p1.variants_for(oc, d1).should == [v1]
p2.variants_for(oc, d2).should == [v2]
end
it "does not return variants in the order cycle but not the distributor" do
p1.variants_for(oc, d2).should be_empty
p2.variants_for(oc, d1).should be_empty
end
it "does not return variants not in the order cycle" do
p_external.variants_for(oc, d1).should be_empty
end
end
describe "variant units" do
context "when the product initially has no variant unit" do
let!(:p) { create(:simple_product,
variant_unit: nil,
variant_unit_scale: nil,
variant_unit_name: nil) }
context "when the required option type does not exist" do
it "creates the option type and assigns it to the product" do
expect {
p.update_attributes!(variant_unit: 'weight', variant_unit_scale: 1000)
}.to change(Spree::OptionType, :count).by(1)
ot = Spree::OptionType.last
ot.name.should == 'unit_weight'
ot.presentation.should == 'Weight'
p.option_types.should == [ot]
end
it "does the same with volume" do
expect {
p.update_attributes!(variant_unit: 'volume', variant_unit_scale: 1000)
}.to change(Spree::OptionType, :count).by(1)
ot = Spree::OptionType.last
ot.name.should == 'unit_volume'
ot.presentation.should == 'Volume'
p.option_types.should == [ot]
end
it "does the same with items" do
expect {
p.update_attributes!(variant_unit: 'items', variant_unit_name: 'packet')
}.to change(Spree::OptionType, :count).by(1)
ot = Spree::OptionType.last
ot.name.should == 'unit_items'
ot.presentation.should == 'Items'
p.option_types.should == [ot]
end
end
context "when the required option type already exists" do
let!(:ot) { create(:option_type, name: 'unit_weight', presentation: 'Weight') }
it "looks up the option type and assigns it to the product" do
expect {
p.update_attributes!(variant_unit: 'weight', variant_unit_scale: 1000)
}.to change(Spree::OptionType, :count).by(0)
p.option_types.should == [ot]
end
end
end
context "when the product already has a variant unit set (and all required option types exist)" do
let!(:p) { create(:simple_product,
variant_unit: 'weight',
variant_unit_scale: 1,
variant_unit_name: nil) }
let!(:ot_volume) { create(:option_type, name: 'unit_volume', presentation: 'Volume') }
it "removes the old option type and assigns the new one" do
p.update_attributes!(variant_unit: 'volume', variant_unit_scale: 0.001)
p.option_types.should == [ot_volume]
end
it "leaves option type unassigned if none is provided" do
p.update_attributes!(variant_unit: nil, variant_unit_scale: nil)
p.option_types.should == []
end
it "does not remove and re-add the option type if it is not changed" do
p.option_types.should_receive(:delete).never
p.update_attributes!(name: 'foo')
end
it "removes the related option values from all its variants" do
ot = Spree::OptionType.find_by_name 'unit_weight'
v = create(:variant, product: p)
p.reload
expect {
p.update_attributes!(variant_unit: 'volume', variant_unit_scale: 0.001)
}.to change(v.option_values(true), :count).by(-1)
end
it "removes the related option values from its master variant" do
ot = Spree::OptionType.find_by_name 'unit_weight'
p.master.update_attributes!(unit_value: 1)
p.reload
expect {
p.update_attributes!(variant_unit: 'volume', variant_unit_scale: 0.001)
}.to change(p.master.option_values(true), :count).by(-1)
end
end
describe "returning the variant unit option type" do
it "returns nil when variant_unit is not set" do
p = create(:simple_product, variant_unit: nil)
p.variant_unit_option_type.should be_nil
end
end
it "finds all variant unit option types" do
ot1 = create(:option_type, name: 'unit_weight', presentation: 'Weight')
ot2 = create(:option_type, name: 'unit_volume', presentation: 'Volume')
ot3 = create(:option_type, name: 'unit_items', presentation: 'Items')
ot4 = create(:option_type, name: 'foo_unit_bar', presentation: 'Foo')
Spree::Product.all_variant_unit_option_types.sort.should == [ot1, ot2, ot3].sort
end
end
describe "option types" do
describe "removing an option type" do
it "removes the associated option values from all variants" do
# Given a product with a variant unit option type and values
p = create(:simple_product, variant_unit: 'weight', variant_unit_scale: 1)
v1 = create(:variant, product: p, unit_value: 100, option_values: [])
v2 = create(:variant, product: p, unit_value: 200, option_values: [])
# And a custom option type and values
ot = create(:option_type, name: 'foo', presentation: 'foo')
p.option_types << ot
ov1 = create(:option_value, option_type: ot, name: 'One', presentation: 'One')
ov2 = create(:option_value, option_type: ot, name: 'Two', presentation: 'Two')
v1.option_values << ov1
v2.option_values << ov2
# When we remove the custom option type
p.option_type_ids = p.option_type_ids.reject { |id| id == ot.id }
# Then the associated option values should have been removed from the variants
v1.option_values(true).should_not include ov1
v2.option_values(true).should_not include ov2
# And the option values themselves should still exist
Spree::OptionValue.where(id: [ov1.id, ov2.id]).count.should == 2
end
end
end
describe "stock filtering" do
it "considers products that are on_demand as being in stock" do
product = create(:simple_product, on_demand: true)
product.master.update_attribute(:count_on_hand, 0)
product.has_stock?.should == true
end
describe "finding products in stock for a particular distribution" do
it "returns in-stock products without variants" do
p = create(:simple_product)
p.master.update_attribute(:count_on_hand, 1)
d = create(:distributor_enterprise)
oc = create(:simple_order_cycle, distributors: [d])
oc.exchanges.outgoing.first.variants << p.master
p.should have_stock_for_distribution(oc, d)
end
it "returns on-demand products" do
p = create(:simple_product, on_demand: true)
p.master.update_attribute(:count_on_hand, 0)
d = create(:distributor_enterprise)
oc = create(:simple_order_cycle, distributors: [d])
oc.exchanges.outgoing.first.variants << p.master
p.should have_stock_for_distribution(oc, d)
end
it "returns products with in-stock variants" do
p = create(:simple_product)
v = create(:variant, product: p)
v.update_attribute(:count_on_hand, 1)
d = create(:distributor_enterprise)
oc = create(:simple_order_cycle, distributors: [d])
oc.exchanges.outgoing.first.variants << v
p.should have_stock_for_distribution(oc, d)
end
it "returns products with on-demand variants" do
p = create(:simple_product)
v = create(:variant, product: p, on_demand: true)
v.update_attribute(:count_on_hand, 0)
d = create(:distributor_enterprise)
oc = create(:simple_order_cycle, distributors: [d])
oc.exchanges.outgoing.first.variants << v
p.should have_stock_for_distribution(oc, d)
end
it "does not return products that have stock not in the distribution" do
p = create(:simple_product)
p.master.update_attribute(:count_on_hand, 1)
d = create(:distributor_enterprise)
oc = create(:simple_order_cycle, distributors: [d])
p.should_not have_stock_for_distribution(oc, d)
end
end
end
describe "Taxons" do
let(:taxon1) { create(:taxon) }
let(:taxon2) { create(:taxon) }
let(:product) { create(:simple_product) }
it "returns the first taxon as the primary taxon" do
product.taxons.should == [product.primary_taxon]
end
end
end
end
|
# Drawer Debugger
# I worked on this challenge [by myself, with: ].
# I spent [#] hours on this challenge.
# Original Code
class Drawer
attr_reader :contents
# Are there any more methods needed in this class?
def initialize
@contents = []
@open = true
end
def open
@open = true
end
def close
@open = false
end
def add_item (item)
@contents << item
end
def remove_item(item = @contents.pop) #what is `#pop` doing?
@contents.delete(item)
end
def dump # what should this method return?
puts "Your drawer is empty."
@contents = []
end
def view_contents
puts "The drawer contains:"
@contents.each {|silverware| puts "- " + silverware.type}
end
end
class Silverware < Drawer
attr_reader :type
# Are there any more methods needed in this class?
def initialize(type, clean = true)
@type = type
@clean = clean
end
def eat
puts "eating with the #{type}"
@clean = false
end
def clean_silverware
@clean = true
end
end
# DO NOT MODIFY THE DRIVER CODE UNLESS DIRECTED TO DO SO
knife1 = Silverware.new("knife")
silverware_drawer = Drawer.new
silverware_drawer.add_item(knife1)
silverware_drawer.add_item(Silverware.new("spoon"))
silverware_drawer.add_item(Silverware.new("fork"))
silverware_drawer.view_contents
silverware_drawer.remove_item
silverware_drawer.view_contents
sharp_knife = Silverware.new("sharp_knife")
silverware_drawer.add_item(sharp_knife)
silverware_drawer.view_contents
removed_knife = silverware_drawer.remove_item(sharp_knife)
removed_knife.eat
removed_knife.clean_silverware
raise Exception.new("Your silverware is not actually clean!") unless removed_knife.clean_silverware == true
silverware_drawer.view_contents
silverware_drawer.dump
raise Exception.new("Your drawer is not actually empty") unless silverware_drawer.contents.empty?
silverware_drawer.view_contents
# What will you need here in order to remove a spoon? You may modify the driver code for this error.
spoon = Silverware.new("spoon")
silverware_drawer = Drawer.new
silverware_drawer.add_item(spoon)
silverware_drawer.view_contents
raise Exception.new("You don't have a spoon to remove") unless silverware_drawer.contents.include?(spoon)
silverware_drawer.remove_item(spoon) #What is happening when you run this the first time?
spoon.eat
puts spoon.clean_silverware #=> this should be false
# DRIVER TESTS GO BELOW THIS LINE
# Reflection
added reflection to ruby-review pair session
# Drawer Debugger
# I worked on this challenge [by myself, with: ].
# I spent [#] hours on this challenge.
# Original Code
class Drawer
attr_reader :contents
# Are there any more methods needed in this class?
def initialize
@contents = []
@open = true
end
def open
@open = true
end
def close
@open = false
end
def add_item (item)
@contents << item
end
def remove_item(item = @contents.pop) #what is `#pop` doing?
@contents.delete(item)
end
def dump # what should this method return?
puts "Your drawer is empty."
@contents = []
end
def view_contents
puts "The drawer contains:"
@contents.each {|silverware| puts "- " + silverware.type}
end
end
class Silverware < Drawer
attr_reader :type
# Are there any more methods needed in this class?
def initialize(type, clean = true)
@type = type
@clean = clean
end
def eat
puts "eating with the #{type}"
@clean = false
end
def clean_silverware
@clean = true
end
end
# DO NOT MODIFY THE DRIVER CODE UNLESS DIRECTED TO DO SO
knife1 = Silverware.new("knife")
silverware_drawer = Drawer.new
silverware_drawer.add_item(knife1)
silverware_drawer.add_item(Silverware.new("spoon"))
silverware_drawer.add_item(Silverware.new("fork"))
silverware_drawer.view_contents
silverware_drawer.remove_item
silverware_drawer.view_contents
sharp_knife = Silverware.new("sharp_knife")
silverware_drawer.add_item(sharp_knife)
silverware_drawer.view_contents
removed_knife = silverware_drawer.remove_item(sharp_knife)
removed_knife.eat
removed_knife.clean_silverware
raise Exception.new("Your silverware is not actually clean!") unless removed_knife.clean_silverware == true
silverware_drawer.view_contents
silverware_drawer.dump
raise Exception.new("Your drawer is not actually empty") unless silverware_drawer.contents.empty?
silverware_drawer.view_contents
# What will you need here in order to remove a spoon? You may modify the driver code for this error.
spoon = Silverware.new("spoon")
silverware_drawer = Drawer.new
silverware_drawer.add_item(spoon)
silverware_drawer.view_contents
raise Exception.new("You don't have a spoon to remove") unless silverware_drawer.contents.include?(spoon)
silverware_drawer.remove_item(spoon) #What is happening when you run this the first time?
spoon.eat
puts spoon.clean_silverware #=> this should be false
# DRIVER TESTS GO BELOW THIS LINE
# Reflection
# What concepts did you review in this challenge?
# Method syntax, class structures, class inheritance, instance variables, and code indentation.
# What is still confusing to you about Ruby?
# Nothing from this challenge.. we did have a hard time realizing one of the errors we were receiving
# because it had nothing to check lol. Once we realized that tho, we added the necessary code for it
# to work and we were well on our way.
# What are you going to study to get more prepared for Phase 1?
# Everything I can, to be honest. This exercise was editing a code so it worked, so it wasn't all that tough.
# It's different editing and creating tho, much different comfort zones. Low key afraid of phase-1 lol.
|
require 'spec_helper'
module Pageflow
describe UserPolicy do
it_behaves_like 'a membership-based permission that',
allows: :manager,
but_forbids: :publisher,
of_account: -> (topic) { topic.accounts.first },
to: :read,
topic: -> { create(:user, :member, on: create(:account)) }
it_behaves_like 'a membership-based permission that',
allows: :manager,
but_forbids: :publisher,
of_account: -> (topic) { topic.accounts.first },
to: :redirect_to_user,
topic: -> { create(:user, :member, on: create(:account)) }
it_behaves_like 'an admin permission that',
allows_admins_but_forbids_even_managers: true,
of_account: -> (topic) { topic.accounts.first },
to: :admin,
topic: -> { create(:user, :member, on: create(:account)) }
it_behaves_like 'an admin permission that',
allows_admins_but_forbids_even_managers: true,
of_account: -> (topic) {topic.accounts.first},
to: :set_admin,
topic: -> { create(:user, :member, on: create(:account)) }
describe 'delete_own_user?' do
it 'allows users when authorize_user_deletion is true' do
Pageflow.config.authorize_user_deletion = lambda { |_user| true }
user = create(:user)
expect(UserPolicy.new(user, user)).to permit_action(:delete_own_user)
end
it 'does not allow users when authorize_user_deletion is false' do
Pageflow.config.authorize_user_deletion = lambda { |_user| false }
user = create(:user)
expect(UserPolicy.new(user, user)).not_to permit_action(:delete_own_user)
end
end
describe '.resolve' do
it 'includes all users if admin' do
admin = create(:user, :admin)
expect(UserPolicy::Scope.new(admin, ::User).resolve).to include(create(:user))
end
it 'includes member on managed account' do
account_manager = create(:user)
managed_user = create(:user)
create(:account, with_member: managed_user, with_manager: account_manager)
expect(UserPolicy::Scope.new(account_manager, ::User).resolve).to include(managed_user)
end
it 'does not include member on publisher account' do
account_publisher = create(:user)
managed_user = create(:user)
create(:account, with_member: managed_user, with_publisher: account_publisher)
expect(UserPolicy::Scope
.new(account_publisher, ::User).resolve).not_to include(managed_user)
end
it 'does not include previewer on managed entry' do
account_manager = create(:user)
managed_user = create(:user)
create(:entry, with_previewer: managed_user, with_manager: account_manager)
expect(UserPolicy::Scope.new(account_manager, ::User).resolve).not_to include(managed_user)
end
it 'does not include member on other account' do
account_manager = create(:user)
managed_user = create(:user)
create(:account, with_manager: account_manager)
create(:account, with_member: managed_user)
expect(UserPolicy::Scope.new(account_manager, ::User).resolve).not_to include(managed_user)
end
it 'does not include user with nil id' do
account_manager = create(:user)
managed_user = User.new
create(:account, with_manager: account_manager)
create(:account, with_member: managed_user)
expect(UserPolicy::Scope.new(account_manager, ::User).resolve).not_to include(managed_user)
end
end
describe 'index?' do
it 'allows user with manager permissions on account to index users' do
user = create(:user, :manager, on: create(:account))
policy = UserPolicy.new(user, create(:user))
expect(policy).to permit_action(:index)
end
it 'does not allow user with publisher permissions on account to index users' do
user = create(:user, :publisher, on: create(:account))
policy = UserPolicy.new(user, create(:user))
expect(policy).not_to permit_action(:index)
end
it 'does not allow user with manager permissions on entry to index users' do
user = create(:user, :manager, on: create(:entry))
policy = UserPolicy.new(user, create(:user))
expect(policy).not_to permit_action(:index)
end
end
describe 'create?' do
it 'allows user with manager permissions on account to create users' do
user = create(:user, :manager, on: create(:account))
policy = UserPolicy.new(user, create(:user))
expect(policy).to permit_action(:create)
end
it 'does not allow user with publisher permissions on account to create users' do
user = create(:user, :publisher, on: create(:account))
policy = UserPolicy.new(user, create(:user))
expect(policy).not_to permit_action(:create)
end
it 'does not allow user with manager permissions on entry to index users' do
user = create(:user, :manager, on: create(:entry))
policy = UserPolicy.new(user, create(:user))
expect(policy).not_to permit_action(:create)
end
end
end
end
Substitute more realistic test case
require 'spec_helper'
module Pageflow
describe UserPolicy do
it_behaves_like 'a membership-based permission that',
allows: :manager,
but_forbids: :publisher,
of_account: -> (topic) { topic.accounts.first },
to: :read,
topic: -> { create(:user, :member, on: create(:account)) }
it_behaves_like 'a membership-based permission that',
allows: :manager,
but_forbids: :publisher,
of_account: -> (topic) { topic.accounts.first },
to: :redirect_to_user,
topic: -> { create(:user, :member, on: create(:account)) }
it_behaves_like 'an admin permission that',
allows_admins_but_forbids_even_managers: true,
of_account: -> (topic) { topic.accounts.first },
to: :admin,
topic: -> { create(:user, :member, on: create(:account)) }
it_behaves_like 'an admin permission that',
allows_admins_but_forbids_even_managers: true,
of_account: -> (topic) { topic.accounts.first },
to: :set_admin,
topic: -> { create(:user, :member, on: create(:account)) }
describe 'delete_own_user?' do
it 'allows users when authorize_user_deletion is true' do
Pageflow.config.authorize_user_deletion = lambda { |_user| true }
user = create(:user)
expect(UserPolicy.new(user, user)).to permit_action(:delete_own_user)
end
it 'does not allow users when authorize_user_deletion is false' do
Pageflow.config.authorize_user_deletion =
lambda { |_user| 'User cannot be deleted. Database is read-only' }
user = create(:user)
expect(UserPolicy.new(user, user)).not_to permit_action(:delete_own_user)
end
end
describe '.resolve' do
it 'includes all users if admin' do
admin = create(:user, :admin)
expect(UserPolicy::Scope.new(admin, ::User).resolve).to include(create(:user))
end
it 'includes member on managed account' do
account_manager = create(:user)
managed_user = create(:user)
create(:account, with_member: managed_user, with_manager: account_manager)
expect(UserPolicy::Scope.new(account_manager, ::User).resolve).to include(managed_user)
end
it 'does not include member on publisher account' do
account_publisher = create(:user)
managed_user = create(:user)
create(:account, with_member: managed_user, with_publisher: account_publisher)
expect(UserPolicy::Scope
.new(account_publisher, ::User).resolve).not_to include(managed_user)
end
it 'does not include previewer on managed entry' do
account_manager = create(:user)
managed_user = create(:user)
create(:entry, with_previewer: managed_user, with_manager: account_manager)
expect(UserPolicy::Scope.new(account_manager, ::User).resolve).not_to include(managed_user)
end
it 'does not include member on other account' do
account_manager = create(:user)
managed_user = create(:user)
create(:account, with_manager: account_manager)
create(:account, with_member: managed_user)
expect(UserPolicy::Scope.new(account_manager, ::User).resolve).not_to include(managed_user)
end
it 'does not include user with nil id' do
account_manager = create(:user)
managed_user = User.new
create(:account, with_manager: account_manager)
create(:account, with_member: managed_user)
expect(UserPolicy::Scope.new(account_manager, ::User).resolve).not_to include(managed_user)
end
end
describe 'index?' do
it 'allows user with manager permissions on account to index users' do
user = create(:user, :manager, on: create(:account))
policy = UserPolicy.new(user, create(:user))
expect(policy).to permit_action(:index)
end
it 'does not allow user with publisher permissions on account to index users' do
user = create(:user, :publisher, on: create(:account))
policy = UserPolicy.new(user, create(:user))
expect(policy).not_to permit_action(:index)
end
it 'does not allow user with manager permissions on entry to index users' do
user = create(:user, :manager, on: create(:entry))
policy = UserPolicy.new(user, create(:user))
expect(policy).not_to permit_action(:index)
end
end
describe 'create?' do
it 'allows user with manager permissions on account to create users' do
user = create(:user, :manager, on: create(:account))
policy = UserPolicy.new(user, create(:user))
expect(policy).to permit_action(:create)
end
it 'does not allow user with publisher permissions on account to create users' do
user = create(:user, :publisher, on: create(:account))
policy = UserPolicy.new(user, create(:user))
expect(policy).not_to permit_action(:create)
end
it 'does not allow user with manager permissions on entry to index users' do
user = create(:user, :manager, on: create(:entry))
policy = UserPolicy.new(user, create(:user))
expect(policy).not_to permit_action(:create)
end
end
end
end
|
# encoding: utf-8
require_relative "../../spec_helper"
require "rack/mock"
require "rango/controller"
require "rango/mixins/message"
require "rango/mixins/rendering"
# HACK because of rSpec, the trouble was:
# TestController.method_defined?(:context) => true
Rango::Controller.send(:undef_method, :context)
class TestController < Rango::Controller
include Rango::MessageMixin
end
describe Rango::MessageMixin do
before(:each) do
@env = Rack::MockRequest.env_for("/?msg")
@controller = TestController.new(@env)
end
describe ".included" do
it "should not do anything if method context isn't defined" do
@controller.should_not respond_to(:context)
end
class ExplicitRenderingController < Rango::Controller
include Rango::ExplicitRendering
include Rango::MessageMixin
end
it "should add message to context if method context is defined" do
controller = ExplicitRenderingController.new(@env)
controller.context.should have_key(:message)
end
end
describe "#message" do
before(:each) do
@env = Rack::MockRequest.env_for("/")
end
it "should" do
@env["QUERY_STRING"] = "msg=Hello%20There%21"
controller = TestController.new(@env)
controller.message.should eql("Hello There!")
end
it "should" do
@env["QUERY_STRING"] = "msg%5Berror%5D%3DHello%20There%21"
controller = TestController.new(@env)
controller.message[:error].should eql("Hello There!")
end
it "should" do
@env["QUERY_STRING"] = "msg%5Berror%5D=Hello%20There%21&msg%5Bnotice%5D=Welcome%21"
controller = TestController.new(@env)
controller.message[:error].should eql("Hello There!")
controller.message[:notice].should eql("Welcome!")
end
end
describe "#redirect" do
before(:each) do
@env = Rack::MockRequest.env_for("/")
Posts = Class.new(Rango::Controller) { include Rango::MessageMixin }
@controller = Posts.new(@env)
end
it "should be satisfied just with url" do
@controller.redirect("/")
@controller.status.should eql(302)
@controller.headers["Location"].should eql("http://example.org/")
end
it "should be satisfied just with url" do
@controller.redirect("/", "Try again")
@controller.headers["Location"].should eql("http://example.org/?msg=Try%20again")
end
it "should be satisfied just with url" do
@controller.redirect("/", error: "Try again")
@controller.headers["Location"].should eql("http://example.org/?msg[error]=Try%20again")
end
end
end
Controller#redirect raise a Redirection exception now
# encoding: utf-8
require_relative "../../spec_helper"
require "rack/mock"
require "rango/controller"
require "rango/mixins/message"
require "rango/mixins/rendering"
# HACK because of rSpec, the trouble was:
# TestController.method_defined?(:context) => true
Rango::Controller.send(:undef_method, :context)
class TestController < Rango::Controller
include Rango::MessageMixin
end
describe Rango::MessageMixin do
before(:each) do
@env = Rack::MockRequest.env_for("/?msg")
@controller = TestController.new(@env)
end
describe ".included" do
it "should not do anything if method context isn't defined" do
@controller.should_not respond_to(:context)
end
class ExplicitRenderingController < Rango::Controller
include Rango::ExplicitRendering
include Rango::MessageMixin
end
it "should add message to context if method context is defined" do
controller = ExplicitRenderingController.new(@env)
controller.context.should have_key(:message)
end
end
describe "#message" do
before(:each) do
@env = Rack::MockRequest.env_for("/")
end
it "should" do
@env["QUERY_STRING"] = "msg=Hello%20There%21"
controller = TestController.new(@env)
controller.message.should eql("Hello There!")
end
it "should" do
@env["QUERY_STRING"] = "msg%5Berror%5D%3DHello%20There%21"
controller = TestController.new(@env)
controller.message[:error].should eql("Hello There!")
end
it "should" do
@env["QUERY_STRING"] = "msg%5Berror%5D=Hello%20There%21&msg%5Bnotice%5D=Welcome%21"
controller = TestController.new(@env)
controller.message[:error].should eql("Hello There!")
controller.message[:notice].should eql("Welcome!")
end
end
describe "#redirect" do
before(:each) do
@env = Rack::MockRequest.env_for("/")
@controller = TestController.new(@env)
end
it "should be satisfied just with url" do
begin
@controller.redirect("/")
rescue Rango::Exceptions::Redirection => redirection
redirection.status.should eql(303)
redirection.headers["Location"].should eql("http://example.org")
end
end
it "should be satisfied just with url" do
begin
@controller.redirect("/", "Try again")
rescue Rango::Exceptions::Redirection => redirection
redirection.status.should eql(303)
redirection.headers["Location"].should eql("http://example.org/?msg=Try%20again")
end
end
it "should be satisfied just with url" do
begin
@controller.redirect("/", error: "Try again")
rescue Rango::Exceptions::Redirection => redirection
redirection.status.should eql(303)
redirection.headers["Location"].should eql("http://example.org/?msg[error]=Try%20again")
end
end
end
end
|
require 'spec_helper'
describe 'config-driven-helper::apache-sites' do
before do
stub_command("/usr/sbin/apache2 -t").and_return(true)
end
context 'apache 2.2' do
cached(:chef_run) do
ChefSpec::SoloRunner.new do |node|
node.set['apache']['version'] = '2.2'
node.set['apache']['sites']['hello.example.com']['docroot'] = '/var/www/hello.example.com'
node.set['apache']['sites']['hello.example.com']['server_name'] = 'hello.example.com'
end.converge(described_recipe)
end
it 'will write out a hello.example.com vhost' do
expect(chef_run).to create_template('/etc/apache2/sites-available/hello.example.com')
end
it 'will write out apache 2.2 configuration when 2.2 is in use' do
expect(chef_run).to render_file('/etc/apache2/sites-available/hello.example.com').with_content('Order allow,deny')
end
it 'will not write out apache 2.4 configuration when 2.2 is in use' do
expect(chef_run).to_not render_file('/etc/apache2/sites-available/hello.example.com').with_content('Require all granted')
end
end
context 'apache 2.4' do
cached(:chef_run) do
ChefSpec::SoloRunner.new do |node|
node.set['apache']['version'] = '2.4'
node.set['apache']['sites']['hello.example.com']['docroot'] = '/var/www/hello.example.com'
node.set['apache']['sites']['hello.example.com']['server_name'] = 'hello.example.com'
end.converge(described_recipe)
end
it 'will write out a hello.example.com vhost' do
expect(chef_run).to create_template('/etc/apache2/sites-available/hello.example.com')
end
it 'will write out apache 2.4 configuration when 2.4 is in use' do
expect(chef_run).to render_file('/etc/apache2/sites-available/hello.example.com').with_content('Require all granted')
end
it 'will not write out apache 2.2 configuration when 2.4 is in use' do
expect(chef_run).to_not render_file('/etc/apache2/sites-available/hello.example.com').with_content('Order allow,deny')
end
end
end
Fix specs when under apache 2.2 or 2.4
require 'spec_helper'
describe 'config-driven-helper::apache-sites' do
before do
stub_command("/usr/sbin/apache2 -t").and_return(true)
end
context 'apache 2.2' do
cached(:chef_run) do
ChefSpec::SoloRunner.new do |node|
node.set['apache']['version'] = '2.2'
node.set['apache']['sites']['hello.example.com']['docroot'] = '/var/www/hello.example.com'
node.set['apache']['sites']['hello.example.com']['server_name'] = 'hello.example.com'
end.converge(described_recipe)
end
it 'will write out a hello.example.com vhost' do
expect(chef_run).to create_template('/etc/apache2/sites-available/hello.example.com')
end
it 'will write out apache 2.2 configuration when 2.2 is in use' do
expect(chef_run).to render_file('/etc/apache2/sites-available/hello.example.com')
.with_content('Order allow,deny')
end
it 'will not write out apache 2.4 configuration when 2.2 is in use' do
expect(chef_run).to_not render_file('/etc/apache2/sites-available/hello.example.com')
.with_content('Require all granted')
end
end
context 'apache 2.4' do
cached(:chef_run) do
ChefSpec::SoloRunner.new do |node|
node.set['apache']['version'] = '2.4'
node.set['apache']['sites']['hello.example.com']['docroot'] = '/var/www/hello.example.com'
node.set['apache']['sites']['hello.example.com']['server_name'] = 'hello.example.com'
end.converge(described_recipe)
end
it 'will write out a hello.example.com vhost' do
expect(chef_run).to create_template('/etc/apache2/sites-available/hello.example.com.conf')
end
it 'will write out apache 2.4 configuration when 2.4 is in use' do
expect(chef_run).to render_file('/etc/apache2/sites-available/hello.example.com.conf')
.with_content('Require all granted')
end
it 'will not write out apache 2.2 configuration when 2.4 is in use' do
expect(chef_run).to_not render_file('/etc/apache2/sites-available/hello.example.com.conf').with_content('Order allow,deny')
end
end
end
|
#!/usr/bin/env ruby
#encoding: utf-8
require_relative "../spec_helper"
require 'rubygems'
require 'reckon'
require 'pp'
require 'rantly'
require 'rantly/rspec_extensions'
require 'shellwords'
describe Reckon::LedgerParser do
before do
@ledger = Reckon::LedgerParser.new(EXAMPLE_LEDGER, date_format: '%Y/%m/%d')
end
describe "parse" do
it "should match ledger csv output" do
# ledger only parses dates with - or / as separator, and separator is required
formats = ["%Y/%m/%d", "%Y-%m-%d"]
types = [' ! ', ' * ', ' ']
delimiters = [" ", "\t", "\t\t"]
comment_chars = ';#%*|'
currency_delimiters = delimiters + ['']
currencies = ['', '$', '£']
property_of do
Rantly do
description = Proc.new do
sized(15){string}.tr(%q{'`:*\\},'').gsub(/\s+/, ' ').gsub(/^[!;<\[( #{comment_chars}]+/, '')
end
currency = choose(*currencies) # to be consistent within the transaction
single_line_comments = ";#|%*".split('').map { |n| "#{n} #{call(description)}" }
comments = ['', '; ', "\t;#{call(description)}", " ; #{call(description)}"]
date = Time.at(range(0, 1_581_389_644)).strftime(choose(*formats))
codes = [' ', " (#{string(:alnum).tr('()', '')}) "]
account = Proc.new { choose(*delimiters) + call(description) }
account_money = Proc.new do
sprintf("%.02f", (float * range(5,10) + 1) * choose(1, -1))
end
account_line = Proc.new do
call(account) + \
choose(*delimiters) + \
currency + \
choose(*currency_delimiters) + \
call(account_money) + \
choose(*comments)
end
ledger = "#{date}#{choose(*types)}#{choose(*codes)}#{call(description)}\n"
range(1,5).times do
ledger += "#{call(account_line)}\n"
end
ledger += "#{call(account)}\n"
ledger += choose(*single_line_comments) + "\n"
ledger
end
end.check(1000) do |s|
filter_format = lambda { |n| [n['date'], n['desc'], n['name'], sprintf("%.02f", n['amount'])] }
headers = %w[date code desc name currency amount type commend]
safe_s = Shellwords.escape(s)
lp_csv = Reckon::LedgerParser.new(s, date_format: '%Y-%m-%d').to_csv.join("\n")
actual = CSV.parse(lp_csv, headers: headers).map(&filter_format)
ledger_csv = `echo #{safe_s} | ledger csv --date-format '%Y-%m-%d' -f - `
expected = CSV.parse(ledger_csv.gsub('\"', '""'), headers: headers).map(&filter_format)
expected.length.times do |i|
expect(actual[i]).to eq(expected[i])
end
end
end
it 'should filter block comments' do
ledger = <<HERE
1970/11/01 Dinner should show up
Assets:Checking -123.00
Expenses:Restaurants
comment
1970/11/01 Lunch should NOT show up
Assets:Checking -12.00
Expenses:Restaurants
end comment
HERE
l = Reckon::LedgerParser.new(ledger)
expect(l.entries.length).to eq(1)
expect(l.entries.first[:desc]).to eq('Dinner should show up')
end
it 'should transaction comments' do
ledger = <<HERE
2020-03-27 AMZN Mktp USX999H3203; Shopping; Sale
Expenses:Household $82.77
Liabilities:ChaseSapphire -$81.77
# END FINANCE SCRIPT OUTPUT Thu 02 Apr 2020 12:05:54 PM EDT
HERE
l = Reckon::LedgerParser.new(ledger)
expect(l.entries.first[:accounts].map { |n| n[:name] }).to eq(['Expenses:Household', 'Liabilities:ChaseSapphire'])
expect(l.entries.first[:accounts].size).to eq(2)
expect(l.entries.length).to eq(1)
end
it "should ignore non-standard entries" do
@ledger.entries.length.should == 7
end
it "should parse entries correctly" do
@ledger.entries.first[:desc].should == "Checking balance"
@ledger.entries.first[:date].should == Date.parse("2004-05-01")
@ledger.entries.first[:accounts].first[:name].should == "Assets:Bank:Checking"
@ledger.entries.first[:accounts].first[:amount].should == 1000
@ledger.entries.first[:accounts].last[:name].should == "Equity:Opening Balances"
@ledger.entries.first[:accounts].last[:amount].should == -1000
@ledger.entries.last[:desc].should == "Credit card company"
@ledger.entries.last[:date].should == Date.parse("2004/05/27")
@ledger.entries.last[:accounts].first[:name].should == "Liabilities:MasterCard"
@ledger.entries.last[:accounts].first[:amount].should == 20.24
@ledger.entries.last[:accounts].last[:name].should == "Assets:Bank:Checking"
@ledger.entries.last[:accounts].last[:amount].should == -20.24
end
end
describe "balance" do
it "it should balance out missing account values" do
@ledger.send(:balance, [
{ :name => "Account1", :amount => 1000 },
{ :name => "Account2", :amount => nil }
]).should == [ { :name => "Account1", :amount => 1000 }, { :name => "Account2", :amount => -1000 } ]
end
it "it should balance out missing account values" do
@ledger.send(:balance, [
{ :name => "Account1", :amount => 1000 },
{ :name => "Account2", :amount => 100 },
{ :name => "Account3", :amount => -200 },
{ :name => "Account4", :amount => nil }
]).should == [
{ :name => "Account1", :amount => 1000 },
{ :name => "Account2", :amount => 100 },
{ :name => "Account3", :amount => -200 },
{ :name => "Account4", :amount => -900 }
]
end
it "it should work on normal values too" do
@ledger.send(:balance, [
{ :name => "Account1", :amount => 1000 },
{ :name => "Account2", :amount => -1000 }
]).should == [ { :name => "Account1", :amount => 1000 }, { :name => "Account2", :amount => -1000 } ]
end
end
# Data
EXAMPLE_LEDGER = (<<-LEDGER).strip
= /^Expenses:Books/
(Liabilities:Taxes) -0.10
~ Monthly
Assets:Bank:Checking $500.00
Income:Salary
2004-05-01 * Checking balance
Assets:Bank:Checking $1,000.00
Equity:Opening Balances
2004-05-01 * Checking balance
Assets:Bank:Checking €1,000.00
Equity:Opening Balances
2004-05-01 * Checking balance
Assets:Bank:Checking 1,000.00 SEK
Equity:Opening Balances
2004/05/01 * Investment balance
Assets:Brokerage 50 AAPL @ $30.00
Equity:Opening Balances
; blah
!account blah
!end
D $1,000
2004/05/14 * Pay day
Assets:Bank:Checking $500.00
Income:Salary
2004/05/27 Book Store
Expenses:Books $20.00
Liabilities:MasterCard
2004/05/27 (100) Credit card company
Liabilities:MasterCard $20.24
Assets:Bank:Checking
LEDGER
end
ledger v3.1.3 does not support date-format for csv output, use default
Ledger v3.1.3 (installed by current ubuntu LTS) doesn't honor the date-format arg for
csv output and always uses %Y/%m/%d. Specify the formats to both the LedgerParser and
ledger call, even though the ledger format arg doesn't have an effect.
#!/usr/bin/env ruby
#encoding: utf-8
require_relative "../spec_helper"
require 'rubygems'
require 'reckon'
require 'pp'
require 'rantly'
require 'rantly/rspec_extensions'
require 'shellwords'
describe Reckon::LedgerParser do
before do
@ledger = Reckon::LedgerParser.new(EXAMPLE_LEDGER, date_format: '%Y/%m/%d')
end
describe "parse" do
it "should match ledger csv output" do
# ledger only parses dates with - or / as separator, and separator is required
formats = ["%Y/%m/%d", "%Y-%m-%d"]
types = [' ! ', ' * ', ' ']
delimiters = [" ", "\t", "\t\t"]
comment_chars = ';#%*|'
currency_delimiters = delimiters + ['']
currencies = ['', '$', '£']
property_of do
Rantly do
description = Proc.new do
sized(15){string}.tr(%q{'`:*\\},'').gsub(/\s+/, ' ').gsub(/^[!;<\[( #{comment_chars}]+/, '')
end
currency = choose(*currencies) # to be consistent within the transaction
single_line_comments = ";#|%*".split('').map { |n| "#{n} #{call(description)}" }
comments = ['', '; ', "\t;#{call(description)}", " ; #{call(description)}"]
date = Time.at(range(0, 1_581_389_644)).strftime(choose(*formats))
codes = [' ', " (#{string(:alnum).tr('()', '')}) "]
account = Proc.new { choose(*delimiters) + call(description) }
account_money = Proc.new do
sprintf("%.02f", (float * range(5,10) + 1) * choose(1, -1))
end
account_line = Proc.new do
call(account) + \
choose(*delimiters) + \
currency + \
choose(*currency_delimiters) + \
call(account_money) + \
choose(*comments)
end
ledger = "#{date}#{choose(*types)}#{choose(*codes)}#{call(description)}\n"
range(1,5).times do
ledger += "#{call(account_line)}\n"
end
ledger += "#{call(account)}\n"
ledger += choose(*single_line_comments) + "\n"
ledger
end
end.check(1000) do |s|
filter_format = lambda { |n| [n['date'], n['desc'], n['name'], sprintf("%.02f", n['amount'])] }
headers = %w[date code desc name currency amount type commend]
safe_s = Shellwords.escape(s)
lp_csv = Reckon::LedgerParser.new(s, date_format: '%Y/%m/%d').to_csv.join("\n")
actual = CSV.parse(lp_csv, headers: headers).map(&filter_format)
ledger_csv = `echo #{safe_s} | ledger csv --date-format '%Y/%m/%d' -f - `
expected = CSV.parse(ledger_csv.gsub('\"', '""'), headers: headers).map(&filter_format)
expected.length.times do |i|
expect(actual[i]).to eq(expected[i])
end
end
end
it 'should filter block comments' do
ledger = <<HERE
1970/11/01 Dinner should show up
Assets:Checking -123.00
Expenses:Restaurants
comment
1970/11/01 Lunch should NOT show up
Assets:Checking -12.00
Expenses:Restaurants
end comment
HERE
l = Reckon::LedgerParser.new(ledger)
expect(l.entries.length).to eq(1)
expect(l.entries.first[:desc]).to eq('Dinner should show up')
end
it 'should transaction comments' do
ledger = <<HERE
2020-03-27 AMZN Mktp USX999H3203; Shopping; Sale
Expenses:Household $82.77
Liabilities:ChaseSapphire -$81.77
# END FINANCE SCRIPT OUTPUT Thu 02 Apr 2020 12:05:54 PM EDT
HERE
l = Reckon::LedgerParser.new(ledger)
expect(l.entries.first[:accounts].map { |n| n[:name] }).to eq(['Expenses:Household', 'Liabilities:ChaseSapphire'])
expect(l.entries.first[:accounts].size).to eq(2)
expect(l.entries.length).to eq(1)
end
it "should ignore non-standard entries" do
@ledger.entries.length.should == 7
end
it "should parse entries correctly" do
@ledger.entries.first[:desc].should == "Checking balance"
@ledger.entries.first[:date].should == Date.parse("2004-05-01")
@ledger.entries.first[:accounts].first[:name].should == "Assets:Bank:Checking"
@ledger.entries.first[:accounts].first[:amount].should == 1000
@ledger.entries.first[:accounts].last[:name].should == "Equity:Opening Balances"
@ledger.entries.first[:accounts].last[:amount].should == -1000
@ledger.entries.last[:desc].should == "Credit card company"
@ledger.entries.last[:date].should == Date.parse("2004/05/27")
@ledger.entries.last[:accounts].first[:name].should == "Liabilities:MasterCard"
@ledger.entries.last[:accounts].first[:amount].should == 20.24
@ledger.entries.last[:accounts].last[:name].should == "Assets:Bank:Checking"
@ledger.entries.last[:accounts].last[:amount].should == -20.24
end
end
describe "balance" do
it "it should balance out missing account values" do
@ledger.send(:balance, [
{ :name => "Account1", :amount => 1000 },
{ :name => "Account2", :amount => nil }
]).should == [ { :name => "Account1", :amount => 1000 }, { :name => "Account2", :amount => -1000 } ]
end
it "it should balance out missing account values" do
@ledger.send(:balance, [
{ :name => "Account1", :amount => 1000 },
{ :name => "Account2", :amount => 100 },
{ :name => "Account3", :amount => -200 },
{ :name => "Account4", :amount => nil }
]).should == [
{ :name => "Account1", :amount => 1000 },
{ :name => "Account2", :amount => 100 },
{ :name => "Account3", :amount => -200 },
{ :name => "Account4", :amount => -900 }
]
end
it "it should work on normal values too" do
@ledger.send(:balance, [
{ :name => "Account1", :amount => 1000 },
{ :name => "Account2", :amount => -1000 }
]).should == [ { :name => "Account1", :amount => 1000 }, { :name => "Account2", :amount => -1000 } ]
end
end
# Data
EXAMPLE_LEDGER = (<<-LEDGER).strip
= /^Expenses:Books/
(Liabilities:Taxes) -0.10
~ Monthly
Assets:Bank:Checking $500.00
Income:Salary
2004-05-01 * Checking balance
Assets:Bank:Checking $1,000.00
Equity:Opening Balances
2004-05-01 * Checking balance
Assets:Bank:Checking €1,000.00
Equity:Opening Balances
2004-05-01 * Checking balance
Assets:Bank:Checking 1,000.00 SEK
Equity:Opening Balances
2004/05/01 * Investment balance
Assets:Brokerage 50 AAPL @ $30.00
Equity:Opening Balances
; blah
!account blah
!end
D $1,000
2004/05/14 * Pay day
Assets:Bank:Checking $500.00
Income:Salary
2004/05/27 Book Store
Expenses:Books $20.00
Liabilities:MasterCard
2004/05/27 (100) Credit card company
Liabilities:MasterCard $20.24
Assets:Bank:Checking
LEDGER
end
|
require 'spec_helper'
describe Subscription do
describe "add-ons" do
it "must assign via hash" do
subscription = Subscription.new :add_ons => [:trial]
subscription.add_ons.must_equal(
Subscription::AddOns.new(subscription, [:trial])
)
end
it "must serialize" do
subscription = Subscription.new
subscription.add_ons << :trial
subscription.to_xml.must_equal <<XML.chomp
<subscription>\
<currency>USD</currency>\
<subscription_add_ons>\
<subscription_add_on><add_on_code>trial</add_on_code></subscription_add_on>\
</subscription_add_ons>\
</subscription>
XML
end
it "must deserialize" do
xml = <<XML.chomp
<subscription>\
<currency>USD</currency>\
<subscription_add_ons>\
<subscription_add_on><add_on_code>trial</add_on_code><quantity>2</quantity></subscription_add_on>\
<subscription_add_on><add_on_code>trial2</add_on_code></subscription_add_on>\
</subscription_add_ons>\
</subscription>
XML
subscription = Subscription.from_xml xml
subscription.add_ons.to_a.must_equal([{:add_on_code=>"trial", :quantity=>2}, {:add_on_code=>"trial2"}])
end
end
describe "active and inactive" do
let(:active) {
stub_api_request :get, 'subscriptions/active', 'subscriptions/show-200'
Subscription.find 'active'
}
let(:inactive) {
stub_api_request(
:get, 'subscriptions/inactive', 'subscriptions/show-200-inactive'
)
Subscription.find 'inactive'
}
describe "#cancel" do
it "must cancel an active subscription" do
stub_api_request(
:put,
'subscriptions/abcdef1234567890/cancel',
'subscriptions/show-200'
)
active.cancel.must_equal true
end
it "won't cancel an inactive subscription" do
inactive.cancel.must_equal false
end
end
describe "#terminate" do
it "must fully refund a subscription" do
stub_api_request(
:put,
'subscriptions/abcdef1234567890/terminate?refund=full',
'subscriptions/show-200'
)
active.terminate(:full).must_equal true
end
it "won't fully refund an inactive subscription" do
inactive.terminate(:full).must_equal false
end
it "must partially refund a subscription" do
stub_api_request(
:put,
'subscriptions/abcdef1234567890/terminate?refund=partial',
'subscriptions/show-200'
)
active.terminate(:partial).must_equal true
end
it "won't partially refund an inactive subscription" do
inactive.terminate(:partial).must_equal false
end
it "must terminate a subscription with no refund" do
stub_api_request(
:put,
'subscriptions/abcdef1234567890/terminate?refund=none',
'subscriptions/show-200'
)
active.terminate.must_equal true
end
end
describe "#reactivate" do
it "must reactivate an inactive subscription" do
stub_api_request(
:put,
'subscriptions/abcdef1234567890/reactivate',
'subscriptions/show-200'
)
inactive.reactivate.must_equal true
end
it "won't reactivate an active subscription" do
active.reactivate.must_equal false
end
end
describe "plan assignment" do
it "must use the assigned plan code" do
active.plan_code = 'new_plan'
active.plan_code.must_equal 'new_plan'
end
end
end
end
Adding a couple tests
require 'spec_helper'
describe Subscription do
describe "add-ons" do
it "must assign via symbol array" do
subscription = Subscription.new :add_ons => [:trial]
subscription.add_ons.must_equal(
Subscription::AddOns.new(subscription, [:trial])
)
end
it "must assign via hash array" do
subscription = Subscription.new :add_ons => [{:add_on_code => "trial", :quantity => 2}, {:add_on_code => "trial2"}]
subscription.add_ons.to_a.must_equal([{:add_on_code=>"trial", :quantity=>2}, {:add_on_code=>"trial2"}])
end
it "must assign track multiple addons" do
subscription = Subscription.new :add_ons => [:trial, :trial]
subscription.add_ons.to_a.must_equal([{:add_on_code=>"trial", :quantity=>2}])
end
it "must serialize" do
subscription = Subscription.new
subscription.add_ons << :trial
subscription.to_xml.must_equal <<XML.chomp
<subscription>\
<currency>USD</currency>\
<subscription_add_ons>\
<subscription_add_on><add_on_code>trial</add_on_code></subscription_add_on>\
</subscription_add_ons>\
</subscription>
XML
end
it "must deserialize" do
xml = <<XML.chomp
<subscription>\
<currency>USD</currency>\
<subscription_add_ons>\
<subscription_add_on><add_on_code>trial</add_on_code><quantity>2</quantity></subscription_add_on>\
<subscription_add_on><add_on_code>trial2</add_on_code></subscription_add_on>\
</subscription_add_ons>\
</subscription>
XML
subscription = Subscription.from_xml xml
subscription.add_ons.to_a.must_equal([{:add_on_code=>"trial", :quantity=>2}, {:add_on_code=>"trial2"}])
end
end
describe "active and inactive" do
let(:active) {
stub_api_request :get, 'subscriptions/active', 'subscriptions/show-200'
Subscription.find 'active'
}
let(:inactive) {
stub_api_request(
:get, 'subscriptions/inactive', 'subscriptions/show-200-inactive'
)
Subscription.find 'inactive'
}
describe "#cancel" do
it "must cancel an active subscription" do
stub_api_request(
:put,
'subscriptions/abcdef1234567890/cancel',
'subscriptions/show-200'
)
active.cancel.must_equal true
end
it "won't cancel an inactive subscription" do
inactive.cancel.must_equal false
end
end
describe "#terminate" do
it "must fully refund a subscription" do
stub_api_request(
:put,
'subscriptions/abcdef1234567890/terminate?refund=full',
'subscriptions/show-200'
)
active.terminate(:full).must_equal true
end
it "won't fully refund an inactive subscription" do
inactive.terminate(:full).must_equal false
end
it "must partially refund a subscription" do
stub_api_request(
:put,
'subscriptions/abcdef1234567890/terminate?refund=partial',
'subscriptions/show-200'
)
active.terminate(:partial).must_equal true
end
it "won't partially refund an inactive subscription" do
inactive.terminate(:partial).must_equal false
end
it "must terminate a subscription with no refund" do
stub_api_request(
:put,
'subscriptions/abcdef1234567890/terminate?refund=none',
'subscriptions/show-200'
)
active.terminate.must_equal true
end
end
describe "#reactivate" do
it "must reactivate an inactive subscription" do
stub_api_request(
:put,
'subscriptions/abcdef1234567890/reactivate',
'subscriptions/show-200'
)
inactive.reactivate.must_equal true
end
it "won't reactivate an active subscription" do
active.reactivate.must_equal false
end
end
describe "plan assignment" do
it "must use the assigned plan code" do
active.plan_code = 'new_plan'
active.plan_code.must_equal 'new_plan'
end
end
end
end
|
require 'rails_helper'
RSpec.describe 'repositories', type: :request do
describe '#show' do
it 'renders .css path with proper Content-Type' do
repo = FactoryGirl.create(
:repository,
name: 'animate.css',
full_name: 'daneden/animate.css',
owner: FactoryGirl.create(:user, login: 'daneden')
)
get "/#{repo.full_name}"
expect(response.status).to eq(200)
expect(response.headers['Content-Type']).to match(%r[\Atext/html;])
end
it 'renders .jss path with proper Content-Type' do
repo = FactoryGirl.create(
:repository,
name: 'angular.js',
full_name: 'angular/angular.js',
owner: FactoryGirl.create(:user, login: 'angular')
)
get "/#{repo.full_name}"
expect(response.status).to eq(200)
expect(response.headers['Content-Type']).to match(%r[\Atext/html;])
end
end
end
Cosmetic changes in specs
require 'rails_helper'
RSpec.describe 'repositories', type: :request do
describe '#show' do
it 'renders .css path with proper Content-Type' do
repo = FactoryGirl.create(
:repository,
name: 'animate.css',
full_name: 'daneden/animate.css',
owner: FactoryGirl.create(:user, login: 'daneden'),
)
get "/#{repo.full_name}"
expect(response.status).to eq(200)
expect(response.headers['Content-Type']).to match(%r[\Atext/html;])
end
it 'renders .js path with proper Content-Type' do
repo = FactoryGirl.create(
:repository,
name: 'angular.js',
full_name: 'angular/angular.js',
owner: FactoryGirl.create(:user, login: 'angular'),
)
get "/#{repo.full_name}"
expect(response.status).to eq(200)
expect(response.headers['Content-Type']).to match(%r[\Atext/html;])
end
end
end
|
Created request spec for drugs admin CRUD.
require "rails_helper"
RSpec.describe "Configuring Drugs", type: :request do
let(:drug) { create(:drug) }
describe "GET new" do
it "responds with a form" do
get new_drugs_drug_path
expect(response).to have_http_status(:success)
end
end
describe "POST create" do
context "given valid attributes" do
it "creates a new record" do
attributes = attributes_for(:drug)
post drugs_drugs_path, drugs_drug: attributes
expect(response).to have_http_status(:redirect)
expect(Renalware::Drugs::Drug.exists?(attributes)).to be_truthy
follow_redirect!
expect(response).to have_http_status(:success)
end
end
context "given invalid attributes" do
it "responds with form" do
attributes = {name: ""}
post drugs_drugs_path, drugs_drug: attributes
expect(response).to have_http_status(:success)
end
end
end
describe "GET index" do
it "responds successfully" do
get drugs_drugs_path
expect(response).to have_http_status(:success)
end
end
describe "GET index as JSON" do
it "responds with json" do
create(:drug, name: ":drug_name:")
get drugs_drugs_path, format: :json
expect(response).to have_http_status(:success)
parsed_json = JSON.parse(response.body)
expect(parsed_json.size).to eq(1)
expect(parsed_json.first["name"]).to eq(":drug_name:")
end
end
describe "GET index with search" do
it "responds with a filtered list of records matching the query" do
create(:drug, name: ":target_drug_name:")
create(:drug, name: ":another_drug_name:")
get drugs_drugs_path, q: {name_cont: "target"}
expect(response).to have_http_status(:success)
expect(response.body).to match(":target_drug_name:")
expect(response.body).not_to match(":another_drug_name:")
end
end
describe "GET edit" do
it "responds with a form" do
get edit_drugs_drug_path(drug)
expect(response).to have_http_status(:success)
end
end
describe "PATCH update" do
context "given valid attributes" do
it "updates a record" do
attributes = {name: "My Edited Drug"}
patch drugs_drug_path(drug), drugs_drug: attributes
expect(response).to have_http_status(:redirect)
expect(Renalware::Drugs::Drug.exists?(attributes)).to be_truthy
follow_redirect!
expect(response).to have_http_status(:success)
end
end
context "given invalid attributes" do
it "responds with a form" do
attributes = {name: ""}
patch drugs_drug_path(drug), drugs_drug: attributes
expect(response).to have_http_status(:success)
end
end
end
describe "DELETE destroy" do
it "deletes the drug" do
delete drugs_drug_path(drug)
expect(response).to have_http_status(:redirect)
expect(Renalware::Drugs::Drug.exists?(id: drug.id)).to be_falsey
follow_redirect!
expect(response).to have_http_status(:success)
end
end
end |
rspec Module monkey-patching
describe "Module#short_name" do
it "returns the inner name of the module" do
Rscons::Environment.short_name.should == "Environment"
Rscons::Object.short_name.should == "Object"
end
end
|
# frozen_string_literal: true
require 'rails_helper'
describe Api::SignUp, type: :model do
let(:params) do
{
email: 'me@example.com',
password: 'password',
password_confirmation: 'password'
}
end
subject { described_class.new(params) }
it { should be_a(ActiveModel::Validations) }
it { should delegate_method(:decorate).to(:session) }
it { should validate_presence_of(:email) }
it { should validate_presence_of(:password) }
it { should validate_confirmation_of(:password) }
describe '#initialize' do
specify { expect(subject.email).to eq('me@example.com') }
specify { expect(subject.password).to eq('password') }
specify { expect(subject.password_confirmation).to eq('password') }
end
describe '#save' do
context 'user valid' do
specify { expect { subject.save }.to change { User.count }.from(0).to(1) }
specify { expect { subject.save }.to change { Session.count }.from(0).to(1) }
end
context 'user not valid' do
let(:params) do
{
email: nil,
password: nil
}
end
specify { expect(subject.save).to eq(false) }
end
context 'user valid but email has already been taken' do
let!(:existed_user) { create(:user, email: 'me@example.com') }
specify do
expect { subject.save }.to raise_error(ActiveModel::StrictValidationFailed) do
expect(subject.errors[:email]).to eq(['has already been taken'])
end
end
end
end
end
Pending
# frozen_string_literal: true
require 'rails_helper'
describe Api::SignUp, type: :model do
let(:params) do
{
email: 'me@example.com',
password: 'password',
password_confirmation: 'password'
}
end
subject { described_class.new(params) }
it { should be_a(ActiveModel::Validations) }
it { should delegate_method(:decorate).to(:session) }
it { should validate_presence_of(:email) }
it { should validate_presence_of(:password) }
it { should validate_confirmation_of(:password) }
describe '#initialize' do
specify { expect(subject.email).to eq('me@example.com') }
specify { expect(subject.password).to eq('password') }
specify { expect(subject.password_confirmation).to eq('password') }
end
describe '#save' do
context 'user valid' do
specify { expect { subject.save }.to change { User.count }.from(0).to(1) }
specify { expect { subject.save }.to change { Session.count }.from(0).to(1) }
end
context 'user not valid' do
let(:params) do
{
email: nil,
password: nil
}
end
specify { expect(subject.save).to eq(false) }
end
context 'user valid but email has already been taken' do
let!(:existed_user) { create(:user, email: 'me@example.com') }
pending do
expect { subject.save }.to raise_error(ActiveModel::StrictValidationFailed) do
expect(subject.errors[:email]).to eq(['has already been taken'])
end
end
end
end
end
|
# Creates a pull request with the new version of a formula.
#
# Usage: brew bump [options...] <formula-name>
#
# Requires either `--url` and `--sha256` or `--tag` and `--revision`.
#
# Options:
# --dry-run: Print what would be done rather than doing it.
# --devel: Bump a `devel` rather than `stable` version.
# --url: The new formula URL.
# --sha256: The new formula SHA-256.
# --tag: The new formula's `tag`
# --revision: The new formula's `revision`.
require "formula"
module Homebrew
def bump_formula_pr
formula = ARGV.formulae.first
odie "No formula found!" unless formula
requested_spec, formula_spec = if ARGV.include?("--devel")
devel_message = " (devel)"
[:devel, formula.devel]
else
[:stable, formula.stable]
end
odie "#{formula}: no #{requested_spec} specification found!" unless formula
hash_type, old_hash = if (checksum = formula_spec.checksum)
[checksum.hash_type.to_s, checksum.hexdigest]
end
new_url = ARGV.value("url")
new_hash = ARGV.value(hash_type)
new_tag = ARGV.value("tag")
new_revision = ARGV.value("revision")
new_url_hash = if new_url && new_hash
true
elsif new_tag && new_revision
false
elsif !hash_type
odie "#{formula}: no tag/revision specified!"
else
odie "#{formula}: no url/#{hash_type} specified!"
end
if ARGV.dry_run?
ohai "brew update"
else
safe_system "brew", "update"
end
Utils::Inreplace.inreplace(formula.path) do |s|
if new_url_hash
old_url = formula_spec.url
if ARGV.dry_run?
ohai "replace '#{old_url}' with '#{new_url}'"
ohai "replace '#{old_hash}' with '#{new_hash}'"
else
s.gsub!(old_url, new_url)
s.gsub!(old_hash, new_hash)
end
else
resource_specs = formula_spec.specs
old_tag = resource_specs[:tag]
old_revision = resource_specs[:revision]
if ARGV.dry_run?
ohai "replace '#{old_tag}' with '#{new_tag}'"
ohai "replace '#{old_revision}' with '#{new_revision}'"
else
s.gsub!(/['"]#{old_tag}['"]/, "\"#{new_tag}\"")
s.gsub!(old_revision, new_revision)
end
end
end
new_formula = Formulary.load_formula_from_path(formula.name, formula.path)
new_formula_version = new_formula.version
unless Formula["hub"].any_version_installed?
if ARGV.dry_run?
ohai "brew install hub"
else
safe_system "brew", "install", "hub"
end
end
formula.path.parent.cd do
branch = "#{formula.name}-#{new_formula_version}"
if ARGV.dry_run?
ohai "git checkout -b #{branch} origin/master"
ohai "git commit --no-edit --verbose --message='#{formula.name} #{new_formula_version}#{devel_message}' -- #{formula.path}"
ohai "hub fork --no-remote"
ohai "hub fork"
ohai "hub fork (to read $HUB_REMOTE)"
ohai "git push $HUB_REMOTE #{branch}:#{branch}"
ohai "hub pull-request --browse -m '#{formula.name} #{new_formula_version}#{devel_message}'"
else
safe_system "git", "checkout", "-b", branch, "origin/master"
safe_system "git", "commit", "--no-edit", "--verbose",
"--message=#{formula.name} #{new_formula_version}#{devel_message}",
"--", formula.path
safe_system "hub", "fork", "--no-remote"
quiet_system "hub", "fork"
remote = Utils.popen_read("hub fork 2>&1")[/fatal: remote (.+) already exists./, 1]
odie "cannot get remote from 'hub'!" if remote.to_s.empty?
safe_system "git", "push", remote, "#{branch}:#{branch}"
safe_system "hub", "pull-request", "--browse", "-m",
"#{formula.name} #{new_formula_version}#{devel_message}\n\nCreated with `brew bump-formula-pr`."
end
end
end
end
bump-formula-pr: fix typo in spec existence check
Closes Homebrew/homebrew#50472.
Signed-off-by: Mike McQuaid <a17fed27eaa842282862ff7c1b9c8395a26ac320@mikemcquaid.com>
# Creates a pull request with the new version of a formula.
#
# Usage: brew bump [options...] <formula-name>
#
# Requires either `--url` and `--sha256` or `--tag` and `--revision`.
#
# Options:
# --dry-run: Print what would be done rather than doing it.
# --devel: Bump a `devel` rather than `stable` version.
# --url: The new formula URL.
# --sha256: The new formula SHA-256.
# --tag: The new formula's `tag`
# --revision: The new formula's `revision`.
require "formula"
module Homebrew
def bump_formula_pr
formula = ARGV.formulae.first
odie "No formula found!" unless formula
requested_spec, formula_spec = if ARGV.include?("--devel")
devel_message = " (devel)"
[:devel, formula.devel]
else
[:stable, formula.stable]
end
odie "#{formula}: no #{requested_spec} specification found!" unless formula_spec
hash_type, old_hash = if (checksum = formula_spec.checksum)
[checksum.hash_type.to_s, checksum.hexdigest]
end
new_url = ARGV.value("url")
new_hash = ARGV.value(hash_type)
new_tag = ARGV.value("tag")
new_revision = ARGV.value("revision")
new_url_hash = if new_url && new_hash
true
elsif new_tag && new_revision
false
elsif !hash_type
odie "#{formula}: no tag/revision specified!"
else
odie "#{formula}: no url/#{hash_type} specified!"
end
if ARGV.dry_run?
ohai "brew update"
else
safe_system "brew", "update"
end
Utils::Inreplace.inreplace(formula.path) do |s|
if new_url_hash
old_url = formula_spec.url
if ARGV.dry_run?
ohai "replace '#{old_url}' with '#{new_url}'"
ohai "replace '#{old_hash}' with '#{new_hash}'"
else
s.gsub!(old_url, new_url)
s.gsub!(old_hash, new_hash)
end
else
resource_specs = formula_spec.specs
old_tag = resource_specs[:tag]
old_revision = resource_specs[:revision]
if ARGV.dry_run?
ohai "replace '#{old_tag}' with '#{new_tag}'"
ohai "replace '#{old_revision}' with '#{new_revision}'"
else
s.gsub!(/['"]#{old_tag}['"]/, "\"#{new_tag}\"")
s.gsub!(old_revision, new_revision)
end
end
end
new_formula = Formulary.load_formula_from_path(formula.name, formula.path)
new_formula_version = new_formula.version
unless Formula["hub"].any_version_installed?
if ARGV.dry_run?
ohai "brew install hub"
else
safe_system "brew", "install", "hub"
end
end
formula.path.parent.cd do
branch = "#{formula.name}-#{new_formula_version}"
if ARGV.dry_run?
ohai "git checkout -b #{branch} origin/master"
ohai "git commit --no-edit --verbose --message='#{formula.name} #{new_formula_version}#{devel_message}' -- #{formula.path}"
ohai "hub fork --no-remote"
ohai "hub fork"
ohai "hub fork (to read $HUB_REMOTE)"
ohai "git push $HUB_REMOTE #{branch}:#{branch}"
ohai "hub pull-request --browse -m '#{formula.name} #{new_formula_version}#{devel_message}'"
else
safe_system "git", "checkout", "-b", branch, "origin/master"
safe_system "git", "commit", "--no-edit", "--verbose",
"--message=#{formula.name} #{new_formula_version}#{devel_message}",
"--", formula.path
safe_system "hub", "fork", "--no-remote"
quiet_system "hub", "fork"
remote = Utils.popen_read("hub fork 2>&1")[/fatal: remote (.+) already exists./, 1]
odie "cannot get remote from 'hub'!" if remote.to_s.empty?
safe_system "git", "push", remote, "#{branch}:#{branch}"
safe_system "hub", "pull-request", "--browse", "-m",
"#{formula.name} #{new_formula_version}#{devel_message}\n\nCreated with `brew bump-formula-pr`."
end
end
end
end
|
describe "every accessible has(n, :through) association", :shared => true do
it "should allow to update an existing project via Person#projects_attributes" do
Person.all.size.should == 0
Project.all.size.should == 0
ProjectMembership.all.size.should == 0
@person.save
project = Project.create(:name => 'dm-accepts_nested_attributes')
project_membership = ProjectMembership.create(:person => @person, :project => project)
Person.all.size.should == 1
Project.all.size.should == 1
ProjectMembership.all.size.should == 1
@person.projects_attributes = { project.id.to_s => { :id => project.id, :name => 'still dm-accepts_nested_attributes' } }
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 1
Project.all.size.should == 1
Project.first.name.should == 'still dm-accepts_nested_attributes'
end
it "should return the attributes written to Person#projects_attributes from the Person#projects_attributes reader" do
@person.projects_attributes.should be_nil
@person.projects_attributes = { 'new_1' => { :name => 'write specs' } }
@person.projects_attributes.should == { 'new_1' => { :name => 'write specs' } }
end
end
describe "every accessible has(n, :through) association with a valid reject_if proc", :shared => true do
it "should not allow to create a new project via Person#projects_attributes" do
Person.all.size.should == 0
Project.all.size.should == 0
ProjectMembership.all.size.should == 0
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 0
Project.all.size.should == 0
@person.projects_attributes = { 'new_1' => { :name => 'dm-accepts_nested_attributes' } }
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 0
Project.all.size.should == 0
end
end
describe "every accessible has(n, :through) association with no reject_if proc", :shared => true do
it "should allow to create a new project via Person#projects_attributes" do
Person.all.size.should == 0
Project.all.size.should == 0
ProjectMembership.all.size.should == 0
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 0
Project.all.size.should == 0
@person.projects_attributes = { 'new_1' => { :name => 'dm-accepts_nested_attributes' } }
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 1
Project.all.size.should == 1
Project.first.name.should == 'dm-accepts_nested_attributes'
end
it "should perform atomic commits" do
@person.projects_attributes = { 'new_1' => { :name => nil } } # should fail because of validations
@person.save
Person.all.size.should == 0 # TODO think more if this should be '1'
ProjectMembership.all.size.should == 0
Project.all.size.should == 0
@person.name = nil # should fail because of validations
@person.projects_attributes = { 'new_1' => { :name => nil } }
@person.save
Person.all.size.should == 0
ProjectMembership.all.size.should == 0
Project.all.size.should == 0
end
end
describe "every accessible has(n, :through) association with :allow_destroy => false", :shared => true do
it "should not allow to delete an existing project via Person#projects_attributes" do
@person.save
project = Project.create(:name => 'dm-accepts_nested_attributes')
project_membership = ProjectMembership.create(:person => @person, :project => project)
Person.all.size.should == 1
ProjectMembership.all.size.should == 1
Project.all.size.should == 1
@person.projects_attributes = { '1' => { :id => project.id, :_delete => true } }
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 1
Project.all.size.should == 1
end
end
describe "every accessible has(n, :through) association with :allow_destroy => true", :shared => true do
it "should allow to delete an existing project via Person#projects_attributes" do
@person.save
project = Project.create(:name => 'dm-accepts_nested_attributes')
project_membership = ProjectMembership.create(:person => @person, :project => project)
Person.all.size.should == 1
ProjectMembership.all.size.should == 1
Project.all.size.should == 1
@person.projects_attributes = { '1' => { :id => project.id, :_delete => true } }
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 0
Project.all.size.should == 0
end
end
added spec that proves that m2m deletion wipes out all intermediaries
* this is bad bad behavior and needs to be fixed
describe "every accessible has(n, :through) association", :shared => true do
it "should allow to update an existing project via Person#projects_attributes" do
Person.all.size.should == 0
Project.all.size.should == 0
ProjectMembership.all.size.should == 0
@person.save
project = Project.create(:name => 'dm-accepts_nested_attributes')
project_membership = ProjectMembership.create(:person => @person, :project => project)
Person.all.size.should == 1
Project.all.size.should == 1
ProjectMembership.all.size.should == 1
@person.projects_attributes = { project.id.to_s => { :id => project.id, :name => 'still dm-accepts_nested_attributes' } }
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 1
Project.all.size.should == 1
Project.first.name.should == 'still dm-accepts_nested_attributes'
end
it "should return the attributes written to Person#projects_attributes from the Person#projects_attributes reader" do
@person.projects_attributes.should be_nil
@person.projects_attributes = { 'new_1' => { :name => 'write specs' } }
@person.projects_attributes.should == { 'new_1' => { :name => 'write specs' } }
end
end
describe "every accessible has(n, :through) association with a valid reject_if proc", :shared => true do
it "should not allow to create a new project via Person#projects_attributes" do
Person.all.size.should == 0
Project.all.size.should == 0
ProjectMembership.all.size.should == 0
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 0
Project.all.size.should == 0
@person.projects_attributes = { 'new_1' => { :name => 'dm-accepts_nested_attributes' } }
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 0
Project.all.size.should == 0
end
end
describe "every accessible has(n, :through) association with no reject_if proc", :shared => true do
it "should allow to create a new project via Person#projects_attributes" do
Person.all.size.should == 0
Project.all.size.should == 0
ProjectMembership.all.size.should == 0
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 0
Project.all.size.should == 0
@person.projects_attributes = { 'new_1' => { :name => 'dm-accepts_nested_attributes' } }
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 1
Project.all.size.should == 1
Project.first.name.should == 'dm-accepts_nested_attributes'
end
it "should perform atomic commits" do
@person.projects_attributes = { 'new_1' => { :name => nil } } # should fail because of validations
@person.save
Person.all.size.should == 0 # TODO think more if this should be '1'
ProjectMembership.all.size.should == 0
Project.all.size.should == 0
@person.name = nil # should fail because of validations
@person.projects_attributes = { 'new_1' => { :name => nil } }
@person.save
Person.all.size.should == 0
ProjectMembership.all.size.should == 0
Project.all.size.should == 0
end
end
describe "every accessible has(n, :through) association with :allow_destroy => false", :shared => true do
it "should not allow to delete an existing project via Person#projects_attributes" do
@person.save
project = Project.create(:name => 'dm-accepts_nested_attributes')
project_membership = ProjectMembership.create(:person => @person, :project => project)
Person.all.size.should == 1
ProjectMembership.all.size.should == 1
Project.all.size.should == 1
@person.projects_attributes = { '1' => { :id => project.id, :_delete => true } }
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 1
Project.all.size.should == 1
end
end
describe "every accessible has(n, :through) association with :allow_destroy => true", :shared => true do
it "should allow to delete an existing project via Person#projects_attributes" do
@person.save
project_1 = Project.create(:name => 'dm-accepts_nested_attributes')
project_2 = Project.create(:name => 'dm-is-localizable')
project_membership_1 = ProjectMembership.create(:person => @person, :project => project_1)
project_membership_2 = ProjectMembership.create(:person => @person, :project => project_2)
Person.all.size.should == 1
ProjectMembership.all.size.should == 2
Project.all.size.should == 2
@person.projects_attributes = { '1' => { :id => project_1.id, :_delete => true } }
@person.save
Person.all.size.should == 1
ProjectMembership.all.size.should == 1
Project.all.size.should == 1
end
end
|
require 'shoes/spec_helper'
describe Shoes::App do
let(:input_blk) { Proc.new {} }
let(:opts) { Hash.new }
subject(:app) { Shoes::App.new(opts, &input_blk) }
after do
Shoes.unregister_all
end
# it_behaves_like "DSL container"
it { is_expected.to respond_to :clipboard }
it { is_expected.to respond_to :clipboard= }
it { is_expected.to respond_to :owner }
# For Shoes 3 compatibility
it "exposes self as #app" do
expect(app.app).to eq(app)
end
describe "initialize" do
let(:input_blk) { Proc.new {} }
it "initializes style hash", :qt do
style = Shoes::App.new.style
expect(style.class).to eq(Hash)
end
describe "console" do
end
describe "defaults" do
let(:opts) { Hash.new }
let(:defaults) { Shoes::InternalApp::DEFAULT_OPTIONS }
it "sets width", :qt, :no_browser do
expect(subject.width).to eq defaults[:width]
end
it "sets height", :qt, :no_browser do
expect(subject.height).to eq defaults[:height]
end
it 'has an absolute_left of 0' do
expect(subject.absolute_left).to eq 0
end
it 'has an absolute_top of 0' do
expect(subject.absolute_top).to eq 0
end
describe "inspect" do
include InspectHelpers
it "shows title in #to_s" do
expect(subject.to_s).to eq("(Shoes::App \"#{defaults.fetch :title}\")")
end
it "shows title in #inspect" do
expect(subject.inspect).to match(/\(Shoes::App:#{shoes_object_id_pattern} "#{defaults.fetch :title}"\)/)
end
end
end
describe "from opts" do
let(:opts) { {:width => 150, :height => 2, :title => "Shoes::App Spec", :resizable => false} }
it "sets width", :qt, :no_browser do
expect(subject.width).to eq opts[:width]
end
it "sets height", :qt, :no_browser do
expect(subject.height).to eq opts[:height]
end
it "passes opts to InternalApp" do
expect(Shoes::InternalApp).to receive(:new).with(kind_of(Shoes::App), opts).and_call_original
subject
end
it 'initializes a flow with the right parameters' do
expect(Shoes::Flow).to receive(:new).with(anything, anything,
{width: opts[:width],
height: opts[:height]}).
and_call_original
subject
end
end
describe "when registering" do
before :each do
Shoes.unregister_all
end
it "registers" do
old_apps_length = Shoes.apps.length
subject
expect(Shoes.apps.length).to eq(old_apps_length + 1)
expect(Shoes.apps).to include(subject)
end
end
end
describe "style with defaults" do
let(:default_styles) { Shoes::Common::Style::DEFAULT_STYLES }
it "sets app defaults" do
expect(app.style).to eq(default_styles)
end
it "merges new styles with existing styles" do
subject.style strokewidth: 4
expect(subject.style).to eq(default_styles.merge(strokewidth: 4))
end
default_styles = Shoes::Common::Style::DEFAULT_STYLES
default_styles.each do |key, value|
describe "#{key}" do
it "defaults to #{value}" do
expect(subject.style[key]).to eq(value)
end
it "passes default to objects" do
expect(subject.line(0, 100, 100, 0).style[key]).to eq(value)
end
end
end
describe "default styles" do
it "are independent among Shoes::App instances" do
app1 = Shoes::App.new
app2 = Shoes::App.new
app1.strokewidth 10
expect(app1.line(0, 100, 100, 0).style[:strokewidth]).to eq(10)
# .. but does not affect app2
expect(app2.line(0, 100, 100, 0).style[:strokewidth]).not_to eq(10)
end
end
end
describe "app-level style setter" do
let(:goldenrod) { Shoes::COLORS[:goldenrod] }
pattern_styles = Shoes::DSL::PATTERN_APP_STYLES
other_styles = Shoes::DSL::OTHER_APP_STYLES
pattern_styles.each do |style|
it "sets #{style} for objects" do
subject.public_send(style, goldenrod)
expect(subject.line(0, 100, 100, 0).style[style]).to eq(goldenrod)
end
end
other_styles.each do |style|
it "sets #{style} for objects" do
subject.public_send(style, 'val')
expect(subject.line(0, 100, 100, 0).style[style]).to eq('val')
end
end
end
describe "connecting with gui" do
let(:gui) { app.instance_variable_get(:@__app__).gui }
describe "clipboard" do
it "gets clipboard" do
expect(gui).to receive(:clipboard)
subject.clipboard
end
it "sets clipboard" do
expect(gui).to receive(:clipboard=).with("test")
subject.clipboard = "test"
end
end
describe "quitting" do
it "#quit tells the GUI to quit" do
expect(gui).to receive :quit
subject.quit
end
it '#close tells the GUI to quit' do
expect(gui).to receive :quit
subject.close
end
end
end
describe "#started?" do
it "checks the window has been displayed or not" do
subject.started?
end
end
describe 'Execution context' do
it 'starts with self as the execution context' do
my_self = nil
app = Shoes.app do my_self = self end
expect(my_self).to eq app
end
end
describe '#append' do
let(:input_blk) {Proc.new do append do para 'Hi' end end}
it 'understands append' do
expect(subject).to respond_to :append
end
it 'should receive a call to what is called in the append block' do
expect_any_instance_of(Shoes::App).to receive :para
subject
end
end
describe '#resize' do
it 'understands resize' do
expect(subject).to respond_to :resize
end
end
describe 'fullscreen' do
describe 'defaults' do
it 'is not fullscreen' do
expect(app).not_to be_fullscreen
end
it 'can enter fullscreen' do
app.fullscreen = true
expect(app).to be_fullscreen
end
end
describe 'going into fullscreen and back out again' do
let(:defaults) { Shoes::InternalApp::DEFAULT_OPTIONS }
before :each do
app.fullscreen = true
app.fullscreen = false
end
# Failing on Mac fullscreen doesnt seem to work see #397
it 'is not in fullscreen', :fails_on_osx do
expect(app).not_to be_fullscreen
end
# Failing on Mac fullscreen doesnt seem to work see #397
it 'has its origina', :fails_on_osx do
expect(app.width).to eq(defaults[:width])
end
# Failing on Mac fullscreen doesnt seem to work see #397
it 'has its original height', :fails_on_osx do
expect(app.height).to eq(defaults[:height])
end
end
end
describe '#clear' do
let(:input_blk) do
Proc.new do
para 'Hello'
end
end
it 'has initial contents' do
puts subject.contents.inspect
expect(subject.contents).to_not be_empty
end
it 'removes everything (regression)' do
subject.clear
expect(subject.contents).to be_empty
end
end
describe "#gutter" do
describe "when app has a scrollbar" do
let(:input_opts) { {width: 100, height: 100} }
let(:input_block) { Proc.new { para "Round peg, square hole" * 200 } }
it "has gutter of 16" do
expect(app.gutter).to be_within(2).of(16)
end
end
describe "when app has no scrollbar" do
let(:input_block) { Proc.new { para "Round peg, square hole" } }
it "has gutter of 16" do
expect(app.gutter).to be_within(2).of(16)
end
end
end
describe "#parent" do
describe "for a top-level element (not explicitly in a slot)" do
it "returns the top_slot" do
my_parent = nil
app = Shoes.app do
flow do
my_parent = parent
end
end
expect(my_parent).to eq app.instance_variable_get(:@__app__).top_slot
end
end
describe "for an element within a slot" do
it "returns the enclosing slot" do
my_parent = nil
my_stack = nil
app = Shoes.app do
my_stack = stack do
flow do
my_parent = parent
end
end
end
expect(my_parent).to eq my_stack
end
end
end
describe "additional context" do
it "fails on unknown method" do
expect { subject.asdf }.to raise_error(NoMethodError)
end
it "calls through to context if available" do
context = double("context", asdf: nil)
expect(context).to receive(:asdf)
subject.eval_with_additional_context(context) do
asdf
end
end
it "clears context when finished" do
context = double("context")
captured_context = nil
subject.eval_with_additional_context(context) do
captured_context = @__additional_context__
end
expect(captured_context).to eq(context)
expect(subject.instance_variable_get(:@__additional_context__)).to be_nil
end
it "still clears context when failure in eval" do
context = double("context")
expect do
subject.eval_with_additional_context(context) { raise "O_o" }
end.to raise_error(RuntimeError)
expect(subject.instance_variable_get(:@__additional_context__)).to be_nil
end
end
describe 'subscribing to DSL methods', :no_opal do
class TestSubscribeClass
attr_reader :app
def initialize(app)
@app = app
end
Shoes::App.subscribe_to_dsl_methods(self)
end
let(:subscribed_instance) {TestSubscribeClass.new subject}
# Declaring classes (TestSubscribeClass) in this context blows up the opal
# rspec runner
AUTO_SUBSCRIBED_CLASSES = [Shoes::App, Shoes::URL, Shoes::Widget]
#SUBSCRIBED_CLASSES = AUTO_SUBSCRIBED_CLASSES + [TestSubscribeClass]
SUBSCRIBED_CLASSES = AUTO_SUBSCRIBED_CLASSES
describe '.subscribe_to_dsl_methods' do
it 'has its instances respond to the dsl methods of the app' do
expect(subscribed_instance).to respond_to :para, :image
end
it 'delegates does methods to the passed in app' do
expect(subject).to receive(:para)
subscribed_instance.para
end
SUBSCRIBED_CLASSES.each do |klazz|
it "#{klazz} responds to a regular DSL method" do
expect(klazz).to be_public_method_defined(:para)
end
end
end
describe '.new_dsl_method (for widget method notifications etc.)' do
before :each do
Shoes::App.new_dsl_method :widget_method do
# noop
end
end
SUBSCRIBED_CLASSES.each do |klazz|
it "#{klazz} now responds to this method" do
expect(klazz).to be_public_method_defined(:widget_method)
end
end
end
describe 'DELEGATE_METHODS' do
subject {Shoes::App::DELEGATE_METHODS}
describe 'does not include general ruby object methods' do
it {is_expected.not_to include :new, :initialize}
end
describe 'it has access to Shoes app and DSL methods' do
it {is_expected.to include :para, :rect, :stack, :flow, :image, :location}
end
describe 'it does not have access to private methods' do
it {is_expected.not_to include :pop_style, :style_normalizer, :create}
end
describe 'there are blacklisted methods that wreck havoc' do
it {is_expected.not_to include :parent, :app}
end
end
end
end
describe "App registry" do
subject { Shoes.apps }
before :each do
Shoes.unregister_all
end
it "only exposes a copy" do
subject << double("app")
expect(Shoes.apps.length).to eq(0)
end
describe "with no apps" do
it { is_expected.to be_empty }
end
describe "with one app" do
let(:app) { double('app') }
before :each do
Shoes.register(app)
end
its(:length) { should eq(1) }
it "marks first app as main app" do
expect(Shoes.main_app).to be(app)
end
end
describe "with two apps" do
let(:app_1) { double("app 1") }
let(:app_2) { double("app 2") }
before :each do
[app_1, app_2].each { |a| Shoes.register(a) }
end
its(:length) { should eq(2) }
it "marks first app as main app" do
expect(Shoes.main_app).to be(app_1)
end
end
end
Tag fullscreen specs as :no_browser
Currently, I'm thinking of browser apps as not having control over their
window size, so these specs don't apply.
require 'shoes/spec_helper'
describe Shoes::App do
let(:input_blk) { Proc.new {} }
let(:opts) { Hash.new }
subject(:app) { Shoes::App.new(opts, &input_blk) }
after do
Shoes.unregister_all
end
# it_behaves_like "DSL container"
it { is_expected.to respond_to :clipboard }
it { is_expected.to respond_to :clipboard= }
it { is_expected.to respond_to :owner }
# For Shoes 3 compatibility
it "exposes self as #app" do
expect(app.app).to eq(app)
end
describe "initialize" do
let(:input_blk) { Proc.new {} }
it "initializes style hash", :qt do
style = Shoes::App.new.style
expect(style.class).to eq(Hash)
end
describe "console" do
end
describe "defaults" do
let(:opts) { Hash.new }
let(:defaults) { Shoes::InternalApp::DEFAULT_OPTIONS }
it "sets width", :qt, :no_browser do
expect(subject.width).to eq defaults[:width]
end
it "sets height", :qt, :no_browser do
expect(subject.height).to eq defaults[:height]
end
it 'has an absolute_left of 0' do
expect(subject.absolute_left).to eq 0
end
it 'has an absolute_top of 0' do
expect(subject.absolute_top).to eq 0
end
describe "inspect" do
include InspectHelpers
it "shows title in #to_s" do
expect(subject.to_s).to eq("(Shoes::App \"#{defaults.fetch :title}\")")
end
it "shows title in #inspect" do
expect(subject.inspect).to match(/\(Shoes::App:#{shoes_object_id_pattern} "#{defaults.fetch :title}"\)/)
end
end
end
describe "from opts" do
let(:opts) { {:width => 150, :height => 2, :title => "Shoes::App Spec", :resizable => false} }
it "sets width", :qt, :no_browser do
expect(subject.width).to eq opts[:width]
end
it "sets height", :qt, :no_browser do
expect(subject.height).to eq opts[:height]
end
it "passes opts to InternalApp" do
expect(Shoes::InternalApp).to receive(:new).with(kind_of(Shoes::App), opts).and_call_original
subject
end
it 'initializes a flow with the right parameters' do
expect(Shoes::Flow).to receive(:new).with(anything, anything,
{width: opts[:width],
height: opts[:height]}).
and_call_original
subject
end
end
describe "when registering" do
before :each do
Shoes.unregister_all
end
it "registers" do
old_apps_length = Shoes.apps.length
subject
expect(Shoes.apps.length).to eq(old_apps_length + 1)
expect(Shoes.apps).to include(subject)
end
end
end
describe "style with defaults" do
let(:default_styles) { Shoes::Common::Style::DEFAULT_STYLES }
it "sets app defaults" do
expect(app.style).to eq(default_styles)
end
it "merges new styles with existing styles" do
subject.style strokewidth: 4
expect(subject.style).to eq(default_styles.merge(strokewidth: 4))
end
default_styles = Shoes::Common::Style::DEFAULT_STYLES
default_styles.each do |key, value|
describe "#{key}" do
it "defaults to #{value}" do
expect(subject.style[key]).to eq(value)
end
it "passes default to objects" do
expect(subject.line(0, 100, 100, 0).style[key]).to eq(value)
end
end
end
describe "default styles" do
it "are independent among Shoes::App instances" do
app1 = Shoes::App.new
app2 = Shoes::App.new
app1.strokewidth 10
expect(app1.line(0, 100, 100, 0).style[:strokewidth]).to eq(10)
# .. but does not affect app2
expect(app2.line(0, 100, 100, 0).style[:strokewidth]).not_to eq(10)
end
end
end
describe "app-level style setter" do
let(:goldenrod) { Shoes::COLORS[:goldenrod] }
pattern_styles = Shoes::DSL::PATTERN_APP_STYLES
other_styles = Shoes::DSL::OTHER_APP_STYLES
pattern_styles.each do |style|
it "sets #{style} for objects" do
subject.public_send(style, goldenrod)
expect(subject.line(0, 100, 100, 0).style[style]).to eq(goldenrod)
end
end
other_styles.each do |style|
it "sets #{style} for objects" do
subject.public_send(style, 'val')
expect(subject.line(0, 100, 100, 0).style[style]).to eq('val')
end
end
end
describe "connecting with gui" do
let(:gui) { app.instance_variable_get(:@__app__).gui }
describe "clipboard" do
it "gets clipboard" do
expect(gui).to receive(:clipboard)
subject.clipboard
end
it "sets clipboard" do
expect(gui).to receive(:clipboard=).with("test")
subject.clipboard = "test"
end
end
describe "quitting" do
it "#quit tells the GUI to quit" do
expect(gui).to receive :quit
subject.quit
end
it '#close tells the GUI to quit' do
expect(gui).to receive :quit
subject.close
end
end
end
describe "#started?" do
it "checks the window has been displayed or not" do
subject.started?
end
end
describe 'Execution context' do
it 'starts with self as the execution context' do
my_self = nil
app = Shoes.app do my_self = self end
expect(my_self).to eq app
end
end
describe '#append' do
let(:input_blk) {Proc.new do append do para 'Hi' end end}
it 'understands append' do
expect(subject).to respond_to :append
end
it 'should receive a call to what is called in the append block' do
expect_any_instance_of(Shoes::App).to receive :para
subject
end
end
describe '#resize' do
it 'understands resize' do
expect(subject).to respond_to :resize
end
end
describe 'fullscreen', :no_browser do
describe 'defaults' do
it 'is not fullscreen' do
expect(app).not_to be_fullscreen
end
it 'can enter fullscreen' do
app.fullscreen = true
expect(app).to be_fullscreen
end
end
describe 'going into fullscreen and back out again' do
let(:defaults) { Shoes::InternalApp::DEFAULT_OPTIONS }
before :each do
app.fullscreen = true
app.fullscreen = false
end
# Failing on Mac fullscreen doesnt seem to work see #397
it 'is not in fullscreen', :fails_on_osx do
expect(app).not_to be_fullscreen
end
# Failing on Mac fullscreen doesnt seem to work see #397
it 'has its origina', :fails_on_osx do
expect(app.width).to eq(defaults[:width])
end
# Failing on Mac fullscreen doesnt seem to work see #397
it 'has its original height', :fails_on_osx do
expect(app.height).to eq(defaults[:height])
end
end
end
describe '#clear' do
let(:input_blk) do
Proc.new do
para 'Hello'
end
end
it 'has initial contents' do
puts subject.contents.inspect
expect(subject.contents).to_not be_empty
end
it 'removes everything (regression)' do
subject.clear
expect(subject.contents).to be_empty
end
end
describe "#gutter" do
describe "when app has a scrollbar" do
let(:input_opts) { {width: 100, height: 100} }
let(:input_block) { Proc.new { para "Round peg, square hole" * 200 } }
it "has gutter of 16" do
expect(app.gutter).to be_within(2).of(16)
end
end
describe "when app has no scrollbar" do
let(:input_block) { Proc.new { para "Round peg, square hole" } }
it "has gutter of 16" do
expect(app.gutter).to be_within(2).of(16)
end
end
end
describe "#parent" do
describe "for a top-level element (not explicitly in a slot)" do
it "returns the top_slot" do
my_parent = nil
app = Shoes.app do
flow do
my_parent = parent
end
end
expect(my_parent).to eq app.instance_variable_get(:@__app__).top_slot
end
end
describe "for an element within a slot" do
it "returns the enclosing slot" do
my_parent = nil
my_stack = nil
app = Shoes.app do
my_stack = stack do
flow do
my_parent = parent
end
end
end
expect(my_parent).to eq my_stack
end
end
end
describe "additional context" do
it "fails on unknown method" do
expect { subject.asdf }.to raise_error(NoMethodError)
end
it "calls through to context if available" do
context = double("context", asdf: nil)
expect(context).to receive(:asdf)
subject.eval_with_additional_context(context) do
asdf
end
end
it "clears context when finished" do
context = double("context")
captured_context = nil
subject.eval_with_additional_context(context) do
captured_context = @__additional_context__
end
expect(captured_context).to eq(context)
expect(subject.instance_variable_get(:@__additional_context__)).to be_nil
end
it "still clears context when failure in eval" do
context = double("context")
expect do
subject.eval_with_additional_context(context) { raise "O_o" }
end.to raise_error(RuntimeError)
expect(subject.instance_variable_get(:@__additional_context__)).to be_nil
end
end
describe 'subscribing to DSL methods', :no_opal do
class TestSubscribeClass
attr_reader :app
def initialize(app)
@app = app
end
Shoes::App.subscribe_to_dsl_methods(self)
end
let(:subscribed_instance) {TestSubscribeClass.new subject}
# Declaring classes (TestSubscribeClass) in this context blows up the opal
# rspec runner
AUTO_SUBSCRIBED_CLASSES = [Shoes::App, Shoes::URL, Shoes::Widget]
#SUBSCRIBED_CLASSES = AUTO_SUBSCRIBED_CLASSES + [TestSubscribeClass]
SUBSCRIBED_CLASSES = AUTO_SUBSCRIBED_CLASSES
describe '.subscribe_to_dsl_methods' do
it 'has its instances respond to the dsl methods of the app' do
expect(subscribed_instance).to respond_to :para, :image
end
it 'delegates does methods to the passed in app' do
expect(subject).to receive(:para)
subscribed_instance.para
end
SUBSCRIBED_CLASSES.each do |klazz|
it "#{klazz} responds to a regular DSL method" do
expect(klazz).to be_public_method_defined(:para)
end
end
end
describe '.new_dsl_method (for widget method notifications etc.)' do
before :each do
Shoes::App.new_dsl_method :widget_method do
# noop
end
end
SUBSCRIBED_CLASSES.each do |klazz|
it "#{klazz} now responds to this method" do
expect(klazz).to be_public_method_defined(:widget_method)
end
end
end
describe 'DELEGATE_METHODS' do
subject {Shoes::App::DELEGATE_METHODS}
describe 'does not include general ruby object methods' do
it {is_expected.not_to include :new, :initialize}
end
describe 'it has access to Shoes app and DSL methods' do
it {is_expected.to include :para, :rect, :stack, :flow, :image, :location}
end
describe 'it does not have access to private methods' do
it {is_expected.not_to include :pop_style, :style_normalizer, :create}
end
describe 'there are blacklisted methods that wreck havoc' do
it {is_expected.not_to include :parent, :app}
end
end
end
end
describe "App registry" do
subject { Shoes.apps }
before :each do
Shoes.unregister_all
end
it "only exposes a copy" do
subject << double("app")
expect(Shoes.apps.length).to eq(0)
end
describe "with no apps" do
it { is_expected.to be_empty }
end
describe "with one app" do
let(:app) { double('app') }
before :each do
Shoes.register(app)
end
its(:length) { should eq(1) }
it "marks first app as main app" do
expect(Shoes.main_app).to be(app)
end
end
describe "with two apps" do
let(:app_1) { double("app 1") }
let(:app_2) { double("app 2") }
before :each do
[app_1, app_2].each { |a| Shoes.register(a) }
end
its(:length) { should eq(2) }
it "marks first app as main app" do
expect(Shoes.main_app).to be(app_1)
end
end
end
|
refactored cash to_s
require 'spec_helper.rb'
module SuperTues
module Board
describe Game do
let(:game) { Game.new }
context "new game" do
specify { game.should be_a Game }
describe "candidates" do
let(:candidates) { game.remaining_candidates }
end
describe "#states" do
# new game state for the state bins
specify { game.states.length.should == 51 } # 50 states + DC
specify { (game.states.map { |state| state.name } - State::NAMES.keys).should be_empty }
specify { game.states.each { |state| state.picks.empty?.should be_true } }
specify { game.states.each { |state| state.electoral_votes.should > 0 } }
specify { game.states.each { |state| state.sway.should be_within(4).of(0) } }
end
describe "#state(name)" do
specify { game.state(:in).name.should == 'Indiana' }
# we have two hash -- make sure they point to exactly the same object
specify { game.state(:in).should equal game.state('Indiana') }
end
describe "days" do
# new game initializes the game day array
specify { game.days.should_not be_empty }
let(:first_day) { game.days.first }
specify { first_day.date.should == Date.new(2016, 1, 4)}
end
describe "card deck and cards" do
specify { game.instance_variable_get(:@card_deck).should be_present }
end
describe "news deck and news" do
specify { game.instance_variable_get(:@news_deck).should be_present }
end
describe "bills deck" do
specify { game.instance_variable_get(:@bill_deck).should be_present }
end
end
describe "seats" do
describe "#seat_taken?(seat_num)" do
it "looks into players' seats" do
player = double(seat: 1)
game.stub(:players) { [player] }
game.seat_taken?(1).should be_true
game.seat_taken?(0).should be_false
end
end
describe "#seats" do
it "returns a hash mapping seats to players" do
p1 = double(seat: 0).tap { |p| p.should_receive(:game=) }
p2 = double(seat: 1).tap { |p| p.should_receive(:game=) }
game.add_players p1, p2
game.seats.should == { 0 => p1, 1 => p2 }
end
end
describe "#seat_players" do
it "seats players" do
p1 = Player.new(name: 'p1')
p2 = Player.new(name: 'p2')
game.add_players p1, p2
seats = game.seat_players
seats.keys.sort.should == (0...2).to_a
end
end
end
describe "setup" do
let(:bob) { Player.new(name: 'bob') }
let(:tom) { Player.new(name: 'tom') }
let(:jim) { Player.new(name: 'jim') }
describe "adding players" do
describe "adding players" do
it "add players and updates player's game" do
game.add_players(bob, tom)
game.players.count.should == 2
game.players.each { |player| player.game.should == game }
end
end
end
describe "once players added" do
before(:each) { game.add_players(bob, tom, jim) }
describe "picking candidates" do
describe "#deal_candidates" do
it "deals candidates to players" do
game.deal_candidates
game.players.each { |player| player.candidates_dealt.count.should == SuperTues::Board.config[:candidates_per_player] }
end
it "candidates are unique" do
game.deal_candidates
dealt = game.players.map { |player| player.candidates_dealt }.flatten
dealt.length.should == dealt.uniq.length
end
end
describe "#candidate_available?" do
let(:a) { double }
it "true when" do
game.stub(:candidates) { [] }
game.candidate_available?(a).should be
end
it "false when" do
game.stub(:candidates) { [a] }
game.candidate_available?(a).should_not be
end
end
describe "#candidates_picked?" do
before(:each) { game.deal_candidates }
specify { game.candidates_picked?.should_not be }
it "true when all players have picked a candidate" do
game.players.each { |p| p.candidate = p.candidates_dealt.sample }
game.candidates_picked?.should be
end
end
end
describe "#seed_player_funds" do
it "calls #seed_funds for each player" do
game.players.each { |player| player.should_receive :seed_funds }
game.send(:seed_player_funds)
end
end
describe "#reset_state_bins" do
it "sets each states picks to zero" do
game.states.first.picks[:red] = 10
game.send(:reset_state_bins)
game.states.each do |state|
expect(state.picks.total).to be == 0
end
end
end
describe "#add_home_state_picks" do
let(:p1) { double('player', candidate: double(state: :in), to_sym: :red, name: 'p1') }
let(:p2) { double('player', candidate: double(state: :ny), to_sym: :blue, name: 'p2') }
before(:each) { game.stub(players: [p1, p2]) }
it "should give in and ny 3 picks each" do
game.send(:add_home_state_picks)
game.state(:in).picks[:red].should == 3
game.state(:ny).picks[:blue].should == 3
end
end
describe "#start_game" do
it "following initializing methods are called" do
game.should_receive :seat_players
game.should_receive :seed_player_funds
game.should_receive :reset_state_bins
game.should_receive :add_home_state_picks
game.start_game
expect(game.front_runner).to_not be_nil
game.round.should == 0
game.turn.should == 0
end
end
end # once players added
end # setup
describe "rules" do
describe "querying rules" do
describe "#rule('rule.str.ing')" do
# check a default rule
specify { game.rule('action.radio_spot.picks.max').should == 5 }
end
# describe "rule(rule_str)" do
# specify { game.rule('action.radio_spot.max_picks').should == 5 }
# end
# describe "allowed?(rule_str)" do
# specify { game.allowed?('action.play_card.max_cards', 1).should be_true }
# specify { game.allowed?('action.play_card.max_cards', 2).should be_false }
# end
end
end
end
end
end |
#!/usr/bin/env ruby
$: << File.join(File.dirname(__FILE__), 'lib')
require 'irclogger'
require 'irclogger/cinch_plugin'
require 'redis'
pidfile = File.join(File.dirname(__FILE__), 'tmp', 'logger.pid')
begin
old_pid = File.read(pidfile).to_i
Process.kill 0, old_pid
raise "An existing logger process is running with pid #{old_pid}. Refusing to start"
rescue Errno::ESRCH, Errno::ENOENT
end
File.open(pidfile, 'w') do |f|
f.write Process.pid
end
bot = Cinch::Bot.new do
configure do |c|
# Server config
c.server = Config['server']
c.port = Config['port'] unless Config['port'].nil?
c.ssl.use = Config['ssl'] unless Config['ssl'].nil?
# Auth config
c.user = Config['username']
c.password = Config['password'] unless Config['password'].nil?
c.realname = Config['realname']
c.nick = Config['nickname']
# Logging config
c.channels = Config['channels']
# cinch, oh god why?!
c.plugins.plugins = [IrcLogger::CinchPlugin]
end
end
IrcLogger::CinchPlugin.redis = Redis.new(url: Config['redis'])
bot.start
Limit messages per second to 1 to avoid Excess Flood on Freenode.
#!/usr/bin/env ruby
$: << File.join(File.dirname(__FILE__), 'lib')
require 'irclogger'
require 'irclogger/cinch_plugin'
require 'redis'
pidfile = File.join(File.dirname(__FILE__), 'tmp', 'logger.pid')
begin
old_pid = File.read(pidfile).to_i
Process.kill 0, old_pid
raise "An existing logger process is running with pid #{old_pid}. Refusing to start"
rescue Errno::ESRCH, Errno::ENOENT
end
File.open(pidfile, 'w') do |f|
f.write Process.pid
end
bot = Cinch::Bot.new do
configure do |c|
# Server config
c.server = Config['server']
c.port = Config['port'] unless Config['port'].nil?
c.ssl.use = Config['ssl'] unless Config['ssl'].nil?
# Auth config
c.user = Config['username']
c.password = Config['password'] unless Config['password'].nil?
c.realname = Config['realname']
c.nick = Config['nickname']
# Logging config
c.channels = Config['channels']
# cinch, oh god why?!
c.plugins.plugins = [IrcLogger::CinchPlugin]
# Trying to avoid "Excess Flood"
c.messages_per_second = 1
end
end
IrcLogger::CinchPlugin.redis = Redis.new(url: Config['redis'])
bot.start
|
class Racket
def tokenize(str)
str.gsub("(", "( ") # add space after '('
.gsub(")", " )") # add space before ')'
.gsub("[", "[ ")
.gsub("]", " ]")
.split(" ") # split string into an array(tokens) base on whitespaces
end
def generate_ast(tokens)
parenthesis_map = {"("=>")", "["=>"]"} # the march parenthesis
aux = lambda do |tokens, acc, left_parenthesis=nil|
# the auxiliary(helper) function
# @param tokens: the token array which is generated by 'tokenize' function
# @param acc: the accumulator holds the result. array(maybe nested), default []
if tokens.empty?
# no tokens left, return result
return acc
end
token = tokens.shift # get first token
if '(' == token or '[' == token # start one s-expression
sub_ast = aux.call tokens, [], token
acc.push sub_ast
aux.call(tokens, acc, left_parenthesis) # recursive call to continue handling rest tokens
elsif ')' == token or ']' == token # end one s-expression
# match parenthesis
if left_parenthesis.nil?
raise "unexpected \"%s\" ." % token
elsif parenthesis_map[left_parenthesis] != token
raise "unmatched parenthesis. excepted \"%s\" to close \"%s\", found instead \"%s\"." % [
parenthesis_map[left_parenthesis], left_parenthesis, token]
else
return acc
end
else
acc.push atom(token) # convent current token to atom
aux.call tokens, acc, left_parenthesis # recursive
end
end
# initial call helper. copy tokens pass to 'aux', because tokens will be mutated in 'aux'
aux.call tokens[0..-1], [], nil
end
def atom(token)
str_part = token[/^"(.*)"$/, 1] # try match string(start and end with ")
if not str_part.nil?
str_part
elsif token[/(?=(\.|[eE]))(\.\d+)?([eE][+-]?\d+)?$/] # decimal
token.to_f
elsif token[/^\d+$/] # integer
token.to_i
else # symbol
token.to_sym
end
end
def parse(str)
generate_ast( tokenize(str) )
end
ALGEBRA_OPERATORS = [:+, :-, :*, :/]
def initialize()
@env = {
:'#t' => true,
:'#f' => false
}
ALGEBRA_OPERATORS.map do |opt|
@env[opt] = lambda{ |*operands| operands.inject(opt) }
end
end
def eval_expressions(exps, env=@env)
results = exps.map { |one_exp| eval(one_exp, env) }
results[-1]
end
def eval(exp, env=@env)
def lookup_env(env, var)
error_no_var = "undefined: %s !" % var
val = env[var]
if val.nil?
raise error_no_var
else
return val
end
end
if exp.is_a? Numeric
exp # is a number(integer and float) return itself
elsif exp.is_a? Symbol
lookup_env(env, exp) # look up var and return its value
elsif exp[0] == :define
_, var, value_exp = exp
env[var] = eval( value_exp, env )
elsif exp[0] == :set!
_, var, new_val_exp = exp
if env[var].nil?
raise "set! assignment disallowed. undefined: %s !" % var
else
env[var] = eval( new_val_exp, env )
end
elsif exp[0] == :if
_, test_exp, then_exp, else_exp = exp
if eval(test_exp, env) == false
eval( else_exp, env )
else # other than false(#f)
eval( then_exp, env)
end
else
operator = eval(exp[0], env) # first thing of s-expression sequence.
operands = exp[1..-1].map {|sub_exp| eval(sub_exp, env) } # the rest things of sequence
operator.call *operands
end
end
def repl(prompt='RacketOnRb >>', output_prompt="=>")
while true
print prompt
code = gets
begin
ast = parse(code)
result = eval_expressions(ast)
puts output_prompt + result.to_s
rescue Exception => e
puts e
end
end
end
end
finish eval not function.
class Racket
def tokenize(str)
str.gsub("(", "( ") # add space after '('
.gsub(")", " )") # add space before ')'
.gsub("[", "[ ")
.gsub("]", " ]")
.split(" ") # split string into an array(tokens) base on whitespaces
end
def generate_ast(tokens)
parenthesis_map = {"("=>")", "["=>"]"} # the march parenthesis
aux = lambda do |tokens, acc, left_parenthesis=nil|
# the auxiliary(helper) function
# @param tokens: the token array which is generated by 'tokenize' function
# @param acc: the accumulator holds the result. array(maybe nested), default []
if tokens.empty?
# no tokens left, return result
return acc
end
token = tokens.shift # get first token
if '(' == token or '[' == token # start one s-expression
sub_ast = aux.call tokens, [], token
acc.push sub_ast
aux.call(tokens, acc, left_parenthesis) # recursive call to continue handling rest tokens
elsif ')' == token or ']' == token # end one s-expression
# match parenthesis
if left_parenthesis.nil?
raise "unexpected \"%s\" ." % token
elsif parenthesis_map[left_parenthesis] != token
raise "unmatched parenthesis. excepted \"%s\" to close \"%s\", found instead \"%s\"." % [
parenthesis_map[left_parenthesis], left_parenthesis, token]
else
return acc
end
else
acc.push atom(token) # convent current token to atom
aux.call tokens, acc, left_parenthesis # recursive
end
end
# initial call helper. copy tokens pass to 'aux', because tokens will be mutated in 'aux'
aux.call tokens[0..-1], [], nil
end
def atom(token)
str_part = token[/^"(.*)"$/, 1] # try match string(start and end with ")
if not str_part.nil?
str_part
elsif token[/(?=(\.|[eE]))(\.\d+)?([eE][+-]?\d+)?$/] # decimal
token.to_f
elsif token[/^\d+$/] # integer
token.to_i
else # symbol
token.to_sym
end
end
def parse(str)
generate_ast( tokenize(str) )
end
ALGEBRA_OPERATORS = [:+, :-, :*, :/]
def initialize()
@env = {
:'#t' => true,
:'#f' => false,
# Racket 'not' operator if exp is #f, results #t. otherwise false. it differents from ruby not
:not => lambda { |exp| if false==exp then true else false end }
}
ALGEBRA_OPERATORS.map do |opt|
@env[opt] = lambda{ |*operands| operands.inject(opt) }
end
end
def eval_expressions(exps, env=@env)
results = exps.map { |one_exp| eval(one_exp, env) }
results[-1]
end
def eval(exp, env=@env)
def lookup_env(env, var)
error_no_var = "undefined: %s !" % var
val = env[var]
if val.nil?
raise error_no_var
else
return val
end
end
if exp.is_a? Numeric
exp # is a number(integer and float) return itself
elsif exp.is_a? Symbol
lookup_env(env, exp) # look up var and return its value
elsif exp[0] == :define
_, var, value_exp = exp
env[var] = eval( value_exp, env )
elsif exp[0] == :set!
_, var, new_val_exp = exp
if env[var].nil?
raise "set! assignment disallowed. undefined: %s !" % var
else
env[var] = eval( new_val_exp, env )
end
elsif exp[0] == :if
_, test_exp, then_exp, else_exp = exp
if eval(test_exp, env) == false
eval( else_exp, env )
else # other than false(#f)
eval( then_exp, env)
end
else
operator = eval(exp[0], env) # first thing of s-expression sequence.
operands = exp[1..-1].map {|sub_exp| eval(sub_exp, env) } # the rest things of sequence
operator.call *operands
end
end
def repl(prompt='RacketOnRb >>', output_prompt="=>")
while true
print prompt
code = gets
begin
ast = parse(code)
result = eval_expressions(ast)
puts output_prompt + result.to_s
rescue Exception => e
puts e
end
end
end
end
|
require 'spec_helper'
require 'bosh/cpi/compatibility_helpers/delete_vm'
require 'tempfile'
require 'logger'
require 'cloud'
describe Bosh::AwsCloud::Cloud do
before(:all) do
@access_key_id = ENV['BOSH_AWS_ACCESS_KEY_ID'] || raise("Missing BOSH_AWS_ACCESS_KEY_ID")
@secret_access_key = ENV['BOSH_AWS_SECRET_ACCESS_KEY'] || raise("Missing BOSH_AWS_SECRET_ACCESS_KEY")
@subnet_id = ENV['BOSH_AWS_SUBNET_ID'] || raise("Missing BOSH_AWS_SUBNET_ID")
@subnet_zone = ENV['BOSH_AWS_SUBNET_ZONE'] || raise("Missing BOSH_AWS_SUBNET_ZONE")
@manual_ip = ENV['BOSH_AWS_LIFECYCLE_MANUAL_IP'] || raise("Missing BOSH_AWS_LIFECYCLE_MANUAL_IP")
@elb_id = ENV['BOSH_AWS_ELB_ID'] || raise("Missing BOSH_AWS_ELB_ID")
end
let(:instance_type_with_ephemeral) { ENV.fetch('BOSH_AWS_INSTANCE_TYPE', 'm3.medium') }
let(:instance_type_without_ephemeral) { ENV.fetch('BOSH_AWS_INSTANCE_TYPE_WITHOUT_EPHEMERAL', 't2.small') }
let(:default_key_name) { ENV.fetch('BOSH_AWS_DEFAULT_KEY_NAME', 'bosh')}
let(:ami) { ENV.fetch('BOSH_AWS_IMAGE_ID', 'ami-b66ed3de') }
let(:instance_type) { instance_type_with_ephemeral }
let(:vm_metadata) { { deployment: 'deployment', job: 'cpi_spec', index: '0', delete_me: 'please' } }
let(:disks) { [] }
let(:network_spec) { {} }
let(:resource_pool) { { 'instance_type' => instance_type, 'availability_zone' => @subnet_zone } }
let(:registry) { instance_double(Bosh::Cpi::RegistryClient).as_null_object }
before {
allow(Bosh::Cpi::RegistryClient).to receive(:new).and_return(registry)
allow(registry).to receive(:read_settings).and_return({})
}
# Use subject-bang because AWS SDK needs to be reconfigured
# with a current test's logger before new AWS::EC2 object is created.
# Reconfiguration happens via `AWS.config`.
subject!(:cpi) do
described_class.new(
'aws' => {
'region' => 'us-east-1',
'default_key_name' => default_key_name,
'default_security_groups' => get_security_group_ids(@subnet_id),
'fast_path_delete' => 'yes',
'access_key_id' => @access_key_id,
'secret_access_key' => @secret_access_key
},
'registry' => {
'endpoint' => 'fake',
'user' => 'fake',
'password' => 'fake'
}
)
end
before do
begin
AWS::EC2.new(
access_key_id: @access_key_id,
secret_access_key: @secret_access_key,
).instances.tagged('delete_me').each(&:terminate)
rescue AWS::EC2::Errors::InvalidInstanceID::NotFound
# don't blow up tests if instance that we're trying to delete was not found
end
end
before { allow(Bosh::Clouds::Config).to receive_messages(logger: logger) }
let(:logger) { Logger.new(STDERR) }
extend Bosh::Cpi::CompatibilityHelpers
describe 'deleting things that no longer exist' do
it 'raises the appropriate Clouds::Error' do
# pass in *real* previously deleted ids instead of made up ones
# because AWS returns Malformed/Invalid errors for fake ids
expect {
cpi.delete_vm('i-49f9f169')
}.to raise_error Bosh::Clouds::VMNotFound
expect {
cpi.delete_disk('vol-4c68780b')
}.to raise_error Bosh::Clouds::DiskNotFound
end
end
context 'manual networking' do
let(:network_spec) do
{
'default' => {
'type' => 'manual',
'ip' => @manual_ip, # use different IP to avoid race condition
'cloud_properties' => { 'subnet' => @subnet_id }
}
}
end
context 'resource_pool specifies elb for instance' do
let(:resource_pool) do
{
'instance_type' => instance_type,
'availability_zone' => @subnet_zone,
'elbs' => [@elb_id]
}
end
let(:endpoint_configured_cpi) do
Bosh::AwsCloud::Cloud.new(
'aws' => {
'ec2_endpoint' => 'https://ec2.us-east-1.amazonaws.com',
'elb_endpoint' => 'https://elasticloadbalancing.us-east-1.amazonaws.com',
'default_key_name' => default_key_name,
'fast_path_delete' => 'yes',
'access_key_id' => @access_key_id,
'secret_access_key' => @secret_access_key
},
'registry' => {
'endpoint' => 'fake',
'user' => 'fake',
'password' => 'fake'
}
)
end
it 'registers new instance with elb' do
begin
stemcell_id = endpoint_configured_cpi.create_stemcell('/not/a/real/path', {'ami' => {'us-east-1' => ami}})
vm_id = endpoint_configured_cpi.create_vm(
nil,
stemcell_id,
resource_pool,
network_spec,
nil,
)
aws_params = {
'access_key_id' => @access_key_id,
'secret_access_key' => @secret_access_key
}
elb_client = AWS::ELB::Client.new(aws_params)
instances = elb_client.describe_load_balancers({:load_balancer_names => [@elb_id]})[:load_balancer_descriptions]
.first[:instances].first[:instance_id]
expect(instances).to include(vm_id)
endpoint_configured_cpi.delete_vm(vm_id)
vm_id=nil
retry_options = { sleep: 10, tries: 10, on: RegisteredInstances }
logger.debug("Waiting for deregistration from ELB")
expect {
Bosh::Common.retryable(retry_options) do |tries, error|
ensure_no_instances_registered_with_elb(logger, elb_client, @elb_id)
end
}.to_not raise_error
instances = elb_client.describe_load_balancers({:load_balancer_names => [@elb_id]})[:load_balancer_descriptions]
.first[:instances]
expect(instances).to be_empty
ensure
endpoint_configured_cpi.delete_stemcell(stemcell_id) if stemcell_id
endpoint_configured_cpi.delete_vm(vm_id) if vm_id
end
end
end
context 'without existing disks' do
it 'should exercise the vm lifecycle' do
vm_lifecycle do |instance_id|
begin
volume_id = cpi.create_disk(2048, {}, instance_id)
expect(volume_id).not_to be_nil
expect(cpi.has_disk?(volume_id)).to be(true)
cpi.attach_disk(instance_id, volume_id)
snapshot_metadata = vm_metadata.merge(
bosh_data: 'bosh data',
instance_id: 'instance',
agent_id: 'agent',
director_name: 'Director',
director_uuid: '6d06b0cc-2c08-43c5-95be-f1b2dd247e18',
)
snapshot_id = cpi.snapshot_disk(volume_id, snapshot_metadata)
expect(snapshot_id).not_to be_nil
snapshot = cpi.ec2_client.snapshots[snapshot_id]
expect(snapshot.tags.device).to eq '/dev/sdf'
expect(snapshot.tags.agent_id).to eq 'agent'
expect(snapshot.tags.instance_id).to eq 'instance'
expect(snapshot.tags.director_name).to eq 'Director'
expect(snapshot.tags.director_uuid).to eq '6d06b0cc-2c08-43c5-95be-f1b2dd247e18'
expect(snapshot.tags[:Name]).to eq 'deployment/cpi_spec/0/sdf'
ensure
cpi.delete_snapshot(snapshot_id)
Bosh::Common.retryable(tries: 20, on: Bosh::Clouds::DiskNotAttached, sleep: lambda { |n, _| [2**(n-1), 30].min }) do
cpi.detach_disk(instance_id, volume_id)
true
end
cpi.delete_disk(volume_id)
end
end
end
end
context 'with existing disks' do
it 'can exercise the vm lifecycle and list the disks' do
begin
volume_id = nil
vm_lifecycle do |instance_id|
begin
volume_id = cpi.create_disk(2048, {}, instance_id)
expect(volume_id).not_to be_nil
expect(cpi.has_disk?(volume_id)).to be(true)
cpi.attach_disk(instance_id, volume_id)
expect(cpi.get_disks(instance_id)).to include(volume_id)
ensure
Bosh::Common.retryable(tries: 20, on: Bosh::Clouds::DiskNotAttached, sleep: lambda { |n, _| [2**(n-1), 30].min }) do
cpi.detach_disk(instance_id, volume_id)
true
end
end
end
vm_options = {
:disks => [volume_id]
}
vm_lifecycle(vm_options) do |instance_id|
begin
cpi.attach_disk(instance_id, volume_id)
expect(cpi.get_disks(instance_id)).to include(volume_id)
ensure
Bosh::Common.retryable(tries: 20, on: Bosh::Clouds::DiskNotAttached, sleep: lambda { |n, _| [2**(n-1), 30].min }) do
cpi.detach_disk(instance_id, volume_id)
true
end
end
end
ensure
cpi.delete_disk(volume_id) if volume_id
end
end
end
it 'can create encrypted disks' do
vm_lifecycle do |instance_id|
begin
volume_id = cpi.create_disk(2048, {'encrypted' => true}, instance_id)
expect(volume_id).not_to be_nil
expect(cpi.has_disk?(volume_id)).to be(true)
encrypted_volume = cpi.ec2_client.volumes[volume_id]
expect(encrypted_volume.encrypted?).to be(true)
ensure
cpi.delete_disk(volume_id)
end
end
end
context 'when ephemeral_disk properties are specified' do
let(:resource_pool) do
{
'instance_type' => instance_type,
'availability_zone' => @subnet_zone,
'ephemeral_disk' => {
'size' => 4 * 1024,
'type' => 'io1',
'iops' => 100
}
}
end
let(:instance_type) { instance_type_without_ephemeral }
it 'requests ephemeral disk with the specified size' do
vm_lifecycle do |instance_id|
disks = cpi.get_disks(instance_id)
expect(disks.size).to eq(2)
ephemeral_volume = cpi.ec2_client.volumes[disks[1]]
expect(ephemeral_volume.size).to eq(4)
expect(ephemeral_volume.type).to eq('io1')
expect(ephemeral_volume.iops).to eq(100)
end
end
end
context 'when raw_instance_storage is true' do
let(:resource_pool) do
{
'instance_type' => instance_type,
'availability_zone' => @subnet_zone,
'raw_instance_storage' => true,
'ephemeral_disk' => {
'size' => 4 * 1024,
'type' => 'gp2'
}
}
end
let(:instance_type) { instance_type_with_ephemeral }
it 'requests all available instance disks and puts the mappings in the registry' do
vm_lifecycle do |instance_id|
expect(registry).to have_received(:update_settings).with(instance_id, hash_including({
"disks" => {
"system" => "/dev/xvda",
"persistent" => {},
"ephemeral" => "/dev/sdb",
"raw_ephemeral" => [{"path" => "/dev/xvdba"}]
}
}))
end
end
context 'when root_disk properties are specified' do
let(:resource_pool) do
{
'instance_type' => instance_type,
'availability_zone' => @subnet_zone,
'root_disk' => {
'size' => 11 * 1024,
'type' => 'gp2'
}
}
end
let(:instance_type) { instance_type_without_ephemeral }
it 'requests root disk with the specified size and type' do
vm_lifecycle do |instance_id|
disks = cpi.get_disks(instance_id)
expect(disks.size).to eq(2)
root_disk = cpi.ec2_client.volumes[disks[0]]
expect(root_disk.size).to eq(11)
expect(root_disk.type).to eq('gp2')
end
end
end
end
context 'when vm with attached disk is removed' do
it 'should wait for 10 mins to attach disk/delete disk ignoring VolumeInUse error' do
begin
stemcell_id = cpi.create_stemcell('/not/a/real/path', {'ami' => {'us-east-1' => ami}})
vm_id = cpi.create_vm(
nil,
stemcell_id,
resource_pool,
network_spec,
[],
nil,
)
disk_id = cpi.create_disk(2048, {}, vm_id)
expect(cpi.has_disk?(disk_id)).to be(true)
cpi.attach_disk(vm_id, disk_id)
expect(cpi.get_disks(vm_id)).to include(disk_id)
cpi.delete_vm(vm_id)
vm_id = nil
new_vm_id = cpi.create_vm(
nil,
stemcell_id,
resource_pool,
network_spec,
[disk_id],
nil,
)
expect {
cpi.attach_disk(new_vm_id, disk_id)
}.to_not raise_error
expect(cpi.get_disks(new_vm_id)).to include(disk_id)
ensure
cpi.delete_vm(new_vm_id) if new_vm_id
cpi.delete_disk(disk_id) if disk_id
cpi.delete_stemcell(stemcell_id) if stemcell_id
cpi.delete_vm(vm_id) if vm_id
end
end
end
it 'will not raise error when detaching a non-existing disk' do
# Detaching a non-existing disk from vm should NOT raise error
vm_lifecycle do |instance_id|
expect {
cpi.detach_disk(instance_id, 'non-existing-volume-uuid')
}.to_not raise_error
end
end
context '#set_vm_metadata' do
it 'correctly sets the tags set by #set_vm_metadata' do
vm_lifecycle do |instance_id|
tags = cpi.ec2_client.instances[instance_id].tags
expect(tags['deployment']).to eq('deployment')
expect(tags['job']).to eq('cpi_spec')
expect(tags['index']).to eq('0')
expect(tags['delete_me']).to eq('please')
end
end
end
end
context 'dynamic networking' do
let(:network_spec) do
{
'default' => {
'type' => 'dynamic',
'cloud_properties' => { 'subnet' => @subnet_id }
}
}
end
it 'can exercise the vm lifecycle' do
vm_lifecycle
end
end
def vm_lifecycle(options = {})
vm_disks = options[:disks] || disks
stemcell_id = cpi.create_stemcell('/not/a/real/path', { 'ami' => { 'us-east-1' => ami } })
instance_id = cpi.create_vm(
nil,
stemcell_id,
resource_pool,
network_spec,
vm_disks,
nil,
)
expect(instance_id).not_to be_nil
expect(cpi.has_vm?(instance_id)).to be(true)
cpi.set_vm_metadata(instance_id, vm_metadata)
yield(instance_id) if block_given?
ensure
cpi.delete_vm(instance_id) if instance_id
cpi.delete_stemcell(stemcell_id) if stemcell_id
end
def get_security_group_ids(subnet_id)
ec2 = AWS::EC2.new(
access_key_id: @access_key_id,
secret_access_key: @secret_access_key,
)
security_groups = ec2.subnets[subnet_id].vpc.security_groups
security_groups.map { |sg| sg.id }
end
end
class RegisteredInstances < StandardError; end
def ensure_no_instances_registered_with_elb(logger, elb_client, elb_id)
instances = elb_client.describe_load_balancers({:load_balancer_names => [elb_id]})[:load_balancer_descriptions]
.first[:instances]
logger.debug("we believe instances: #{instances} are attached to elb #{elb_id}")
if !instances.empty?
raise RegisteredInstances
end
true
end
Add default security groups for all AWS defaults in lifecycles
[#116934273](https://www.pivotaltracker.com/story/show/116934273)
Signed-off-by: Lyle Franklin <31e283733c7a4b3b6cb03b95ab535671c2112bbe@pivotal.io>
require 'spec_helper'
require 'bosh/cpi/compatibility_helpers/delete_vm'
require 'tempfile'
require 'logger'
require 'cloud'
describe Bosh::AwsCloud::Cloud do
before(:all) do
@access_key_id = ENV['BOSH_AWS_ACCESS_KEY_ID'] || raise("Missing BOSH_AWS_ACCESS_KEY_ID")
@secret_access_key = ENV['BOSH_AWS_SECRET_ACCESS_KEY'] || raise("Missing BOSH_AWS_SECRET_ACCESS_KEY")
@subnet_id = ENV['BOSH_AWS_SUBNET_ID'] || raise("Missing BOSH_AWS_SUBNET_ID")
@subnet_zone = ENV['BOSH_AWS_SUBNET_ZONE'] || raise("Missing BOSH_AWS_SUBNET_ZONE")
@manual_ip = ENV['BOSH_AWS_LIFECYCLE_MANUAL_IP'] || raise("Missing BOSH_AWS_LIFECYCLE_MANUAL_IP")
@elb_id = ENV['BOSH_AWS_ELB_ID'] || raise("Missing BOSH_AWS_ELB_ID")
end
let(:instance_type_with_ephemeral) { ENV.fetch('BOSH_AWS_INSTANCE_TYPE', 'm3.medium') }
let(:instance_type_without_ephemeral) { ENV.fetch('BOSH_AWS_INSTANCE_TYPE_WITHOUT_EPHEMERAL', 't2.small') }
let(:default_key_name) { ENV.fetch('BOSH_AWS_DEFAULT_KEY_NAME', 'bosh')}
let(:ami) { ENV.fetch('BOSH_AWS_IMAGE_ID', 'ami-b66ed3de') }
let(:instance_type) { instance_type_with_ephemeral }
let(:vm_metadata) { { deployment: 'deployment', job: 'cpi_spec', index: '0', delete_me: 'please' } }
let(:disks) { [] }
let(:network_spec) { {} }
let(:resource_pool) { { 'instance_type' => instance_type, 'availability_zone' => @subnet_zone } }
let(:registry) { instance_double(Bosh::Cpi::RegistryClient).as_null_object }
before {
allow(Bosh::Cpi::RegistryClient).to receive(:new).and_return(registry)
allow(registry).to receive(:read_settings).and_return({})
}
# Use subject-bang because AWS SDK needs to be reconfigured
# with a current test's logger before new AWS::EC2 object is created.
# Reconfiguration happens via `AWS.config`.
subject!(:cpi) do
described_class.new(
'aws' => {
'region' => 'us-east-1',
'default_key_name' => default_key_name,
'default_security_groups' => get_security_group_ids(@subnet_id),
'fast_path_delete' => 'yes',
'access_key_id' => @access_key_id,
'secret_access_key' => @secret_access_key
},
'registry' => {
'endpoint' => 'fake',
'user' => 'fake',
'password' => 'fake'
}
)
end
before do
begin
AWS::EC2.new(
access_key_id: @access_key_id,
secret_access_key: @secret_access_key,
).instances.tagged('delete_me').each(&:terminate)
rescue AWS::EC2::Errors::InvalidInstanceID::NotFound
# don't blow up tests if instance that we're trying to delete was not found
end
end
before { allow(Bosh::Clouds::Config).to receive_messages(logger: logger) }
let(:logger) { Logger.new(STDERR) }
extend Bosh::Cpi::CompatibilityHelpers
describe 'deleting things that no longer exist' do
it 'raises the appropriate Clouds::Error' do
# pass in *real* previously deleted ids instead of made up ones
# because AWS returns Malformed/Invalid errors for fake ids
expect {
cpi.delete_vm('i-49f9f169')
}.to raise_error Bosh::Clouds::VMNotFound
expect {
cpi.delete_disk('vol-4c68780b')
}.to raise_error Bosh::Clouds::DiskNotFound
end
end
context 'manual networking' do
let(:network_spec) do
{
'default' => {
'type' => 'manual',
'ip' => @manual_ip, # use different IP to avoid race condition
'cloud_properties' => { 'subnet' => @subnet_id }
}
}
end
context 'resource_pool specifies elb for instance' do
let(:resource_pool) do
{
'instance_type' => instance_type,
'availability_zone' => @subnet_zone,
'elbs' => [@elb_id]
}
end
let(:endpoint_configured_cpi) do
Bosh::AwsCloud::Cloud.new(
'aws' => {
'ec2_endpoint' => 'https://ec2.us-east-1.amazonaws.com',
'elb_endpoint' => 'https://elasticloadbalancing.us-east-1.amazonaws.com',
'default_key_name' => default_key_name,
'default_security_groups' => get_security_group_ids(@subnet_id),
'fast_path_delete' => 'yes',
'access_key_id' => @access_key_id,
'secret_access_key' => @secret_access_key
},
'registry' => {
'endpoint' => 'fake',
'user' => 'fake',
'password' => 'fake'
}
)
end
it 'registers new instance with elb' do
begin
stemcell_id = endpoint_configured_cpi.create_stemcell('/not/a/real/path', {'ami' => {'us-east-1' => ami}})
vm_id = endpoint_configured_cpi.create_vm(
nil,
stemcell_id,
resource_pool,
network_spec,
nil,
)
aws_params = {
'access_key_id' => @access_key_id,
'secret_access_key' => @secret_access_key
}
elb_client = AWS::ELB::Client.new(aws_params)
instances = elb_client.describe_load_balancers({:load_balancer_names => [@elb_id]})[:load_balancer_descriptions]
.first[:instances].first[:instance_id]
expect(instances).to include(vm_id)
endpoint_configured_cpi.delete_vm(vm_id)
vm_id=nil
retry_options = { sleep: 10, tries: 10, on: RegisteredInstances }
logger.debug("Waiting for deregistration from ELB")
expect {
Bosh::Common.retryable(retry_options) do |tries, error|
ensure_no_instances_registered_with_elb(logger, elb_client, @elb_id)
end
}.to_not raise_error
instances = elb_client.describe_load_balancers({:load_balancer_names => [@elb_id]})[:load_balancer_descriptions]
.first[:instances]
expect(instances).to be_empty
ensure
endpoint_configured_cpi.delete_stemcell(stemcell_id) if stemcell_id
endpoint_configured_cpi.delete_vm(vm_id) if vm_id
end
end
end
context 'without existing disks' do
it 'should exercise the vm lifecycle' do
vm_lifecycle do |instance_id|
begin
volume_id = cpi.create_disk(2048, {}, instance_id)
expect(volume_id).not_to be_nil
expect(cpi.has_disk?(volume_id)).to be(true)
cpi.attach_disk(instance_id, volume_id)
snapshot_metadata = vm_metadata.merge(
bosh_data: 'bosh data',
instance_id: 'instance',
agent_id: 'agent',
director_name: 'Director',
director_uuid: '6d06b0cc-2c08-43c5-95be-f1b2dd247e18',
)
snapshot_id = cpi.snapshot_disk(volume_id, snapshot_metadata)
expect(snapshot_id).not_to be_nil
snapshot = cpi.ec2_client.snapshots[snapshot_id]
expect(snapshot.tags.device).to eq '/dev/sdf'
expect(snapshot.tags.agent_id).to eq 'agent'
expect(snapshot.tags.instance_id).to eq 'instance'
expect(snapshot.tags.director_name).to eq 'Director'
expect(snapshot.tags.director_uuid).to eq '6d06b0cc-2c08-43c5-95be-f1b2dd247e18'
expect(snapshot.tags[:Name]).to eq 'deployment/cpi_spec/0/sdf'
ensure
cpi.delete_snapshot(snapshot_id)
Bosh::Common.retryable(tries: 20, on: Bosh::Clouds::DiskNotAttached, sleep: lambda { |n, _| [2**(n-1), 30].min }) do
cpi.detach_disk(instance_id, volume_id)
true
end
cpi.delete_disk(volume_id)
end
end
end
end
context 'with existing disks' do
it 'can exercise the vm lifecycle and list the disks' do
begin
volume_id = nil
vm_lifecycle do |instance_id|
begin
volume_id = cpi.create_disk(2048, {}, instance_id)
expect(volume_id).not_to be_nil
expect(cpi.has_disk?(volume_id)).to be(true)
cpi.attach_disk(instance_id, volume_id)
expect(cpi.get_disks(instance_id)).to include(volume_id)
ensure
Bosh::Common.retryable(tries: 20, on: Bosh::Clouds::DiskNotAttached, sleep: lambda { |n, _| [2**(n-1), 30].min }) do
cpi.detach_disk(instance_id, volume_id)
true
end
end
end
vm_options = {
:disks => [volume_id]
}
vm_lifecycle(vm_options) do |instance_id|
begin
cpi.attach_disk(instance_id, volume_id)
expect(cpi.get_disks(instance_id)).to include(volume_id)
ensure
Bosh::Common.retryable(tries: 20, on: Bosh::Clouds::DiskNotAttached, sleep: lambda { |n, _| [2**(n-1), 30].min }) do
cpi.detach_disk(instance_id, volume_id)
true
end
end
end
ensure
cpi.delete_disk(volume_id) if volume_id
end
end
end
it 'can create encrypted disks' do
vm_lifecycle do |instance_id|
begin
volume_id = cpi.create_disk(2048, {'encrypted' => true}, instance_id)
expect(volume_id).not_to be_nil
expect(cpi.has_disk?(volume_id)).to be(true)
encrypted_volume = cpi.ec2_client.volumes[volume_id]
expect(encrypted_volume.encrypted?).to be(true)
ensure
cpi.delete_disk(volume_id)
end
end
end
context 'when ephemeral_disk properties are specified' do
let(:resource_pool) do
{
'instance_type' => instance_type,
'availability_zone' => @subnet_zone,
'ephemeral_disk' => {
'size' => 4 * 1024,
'type' => 'io1',
'iops' => 100
}
}
end
let(:instance_type) { instance_type_without_ephemeral }
it 'requests ephemeral disk with the specified size' do
vm_lifecycle do |instance_id|
disks = cpi.get_disks(instance_id)
expect(disks.size).to eq(2)
ephemeral_volume = cpi.ec2_client.volumes[disks[1]]
expect(ephemeral_volume.size).to eq(4)
expect(ephemeral_volume.type).to eq('io1')
expect(ephemeral_volume.iops).to eq(100)
end
end
end
context 'when raw_instance_storage is true' do
let(:resource_pool) do
{
'instance_type' => instance_type,
'availability_zone' => @subnet_zone,
'raw_instance_storage' => true,
'ephemeral_disk' => {
'size' => 4 * 1024,
'type' => 'gp2'
}
}
end
let(:instance_type) { instance_type_with_ephemeral }
it 'requests all available instance disks and puts the mappings in the registry' do
vm_lifecycle do |instance_id|
expect(registry).to have_received(:update_settings).with(instance_id, hash_including({
"disks" => {
"system" => "/dev/xvda",
"persistent" => {},
"ephemeral" => "/dev/sdb",
"raw_ephemeral" => [{"path" => "/dev/xvdba"}]
}
}))
end
end
context 'when root_disk properties are specified' do
let(:resource_pool) do
{
'instance_type' => instance_type,
'availability_zone' => @subnet_zone,
'root_disk' => {
'size' => 11 * 1024,
'type' => 'gp2'
}
}
end
let(:instance_type) { instance_type_without_ephemeral }
it 'requests root disk with the specified size and type' do
vm_lifecycle do |instance_id|
disks = cpi.get_disks(instance_id)
expect(disks.size).to eq(2)
root_disk = cpi.ec2_client.volumes[disks[0]]
expect(root_disk.size).to eq(11)
expect(root_disk.type).to eq('gp2')
end
end
end
end
context 'when vm with attached disk is removed' do
it 'should wait for 10 mins to attach disk/delete disk ignoring VolumeInUse error' do
begin
stemcell_id = cpi.create_stemcell('/not/a/real/path', {'ami' => {'us-east-1' => ami}})
vm_id = cpi.create_vm(
nil,
stemcell_id,
resource_pool,
network_spec,
[],
nil,
)
disk_id = cpi.create_disk(2048, {}, vm_id)
expect(cpi.has_disk?(disk_id)).to be(true)
cpi.attach_disk(vm_id, disk_id)
expect(cpi.get_disks(vm_id)).to include(disk_id)
cpi.delete_vm(vm_id)
vm_id = nil
new_vm_id = cpi.create_vm(
nil,
stemcell_id,
resource_pool,
network_spec,
[disk_id],
nil,
)
expect {
cpi.attach_disk(new_vm_id, disk_id)
}.to_not raise_error
expect(cpi.get_disks(new_vm_id)).to include(disk_id)
ensure
cpi.delete_vm(new_vm_id) if new_vm_id
cpi.delete_disk(disk_id) if disk_id
cpi.delete_stemcell(stemcell_id) if stemcell_id
cpi.delete_vm(vm_id) if vm_id
end
end
end
it 'will not raise error when detaching a non-existing disk' do
# Detaching a non-existing disk from vm should NOT raise error
vm_lifecycle do |instance_id|
expect {
cpi.detach_disk(instance_id, 'non-existing-volume-uuid')
}.to_not raise_error
end
end
context '#set_vm_metadata' do
it 'correctly sets the tags set by #set_vm_metadata' do
vm_lifecycle do |instance_id|
tags = cpi.ec2_client.instances[instance_id].tags
expect(tags['deployment']).to eq('deployment')
expect(tags['job']).to eq('cpi_spec')
expect(tags['index']).to eq('0')
expect(tags['delete_me']).to eq('please')
end
end
end
end
context 'dynamic networking' do
let(:network_spec) do
{
'default' => {
'type' => 'dynamic',
'cloud_properties' => { 'subnet' => @subnet_id }
}
}
end
it 'can exercise the vm lifecycle' do
vm_lifecycle
end
end
def vm_lifecycle(options = {})
vm_disks = options[:disks] || disks
stemcell_id = cpi.create_stemcell('/not/a/real/path', { 'ami' => { 'us-east-1' => ami } })
instance_id = cpi.create_vm(
nil,
stemcell_id,
resource_pool,
network_spec,
vm_disks,
nil,
)
expect(instance_id).not_to be_nil
expect(cpi.has_vm?(instance_id)).to be(true)
cpi.set_vm_metadata(instance_id, vm_metadata)
yield(instance_id) if block_given?
ensure
cpi.delete_vm(instance_id) if instance_id
cpi.delete_stemcell(stemcell_id) if stemcell_id
end
def get_security_group_ids(subnet_id)
ec2 = AWS::EC2.new(
access_key_id: @access_key_id,
secret_access_key: @secret_access_key,
)
security_groups = ec2.subnets[subnet_id].vpc.security_groups
security_groups.map { |sg| sg.id }
end
end
class RegisteredInstances < StandardError; end
def ensure_no_instances_registered_with_elb(logger, elb_client, elb_id)
instances = elb_client.describe_load_balancers({:load_balancer_names => [elb_id]})[:load_balancer_descriptions]
.first[:instances]
logger.debug("we believe instances: #{instances} are attached to elb #{elb_id}")
if !instances.empty?
raise RegisteredInstances
end
true
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.